Browse Source

fix:我的佣金

super-yimizi 13 hours ago
parent
commit
95fa3ff5ea
2 changed files with 273 additions and 0 deletions
  1. 240 0
      application/api/controller/commission/Reward.php
  2. 33 0
      application/api/validate/Reward.php

+ 240 - 0
application/api/controller/commission/Reward.php

@@ -3,8 +3,248 @@
 namespace app\api\controller\commission;
 
 use app\common\model\commission\Reward as RewardModel;
+use app\common\model\commission\Agent as AgentModel;
+use app\common\library\BcMath;
 
 
 class Reward extends Commission
 {
+    protected $noNeedLogin = [];
+    protected $noNeedRight = ['*'];
+
+    /**
+     * 分销商佣金列表
+     */
+    public function list()
+    {
+        $params = $this->request->param();
+        
+        // 使用验证器验证分页参数:page, page_size, time_filter, start_date, end_date
+        $validate = new \app\api\validate\Reward();
+        if (!$validate->scene('list')->check($params)) {
+            $this->error($validate->getError());
+        }
+        
+        $agentId = $this->service->user->id;
+        
+        // 验证当前用户是否为代理商
+        $agent = $this->service->agent;
+        if (!$agent) {
+            $this->error('您还不是分销商');
+        }
+        
+        // 获取验证后的参数
+        $pageSize = isset($params['page_size']) ? (int)$params['page_size'] : 8;
+        $timeFilter = isset($params['time_filter']) ? $params['time_filter'] : 'all';
+        $startDate = isset($params['start_date']) ? $params['start_date'] : '';
+        $endDate = isset($params['end_date']) ? $params['end_date'] : '';
+
+        // 构建查询条件
+        $query = RewardModel::where('agent_id', $agent->id)
+            ->where('status', RewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED) // 只查询已结算的佣金
+            ->with(['commissionOrder']) // 关联佣金订单信息
+            ->order('commission_time desc'); // 按佣金时间倒序
+
+        // 根据时间筛选参数添加时间条件
+        if ($timeFilter !== 'all') {
+            $timeConditions = $this->getTimeFilterConditions($timeFilter, $startDate, $endDate);
+            if ($timeConditions) {
+                $query->where('commission_time', '>=', $timeConditions['start_time']);
+                if (isset($timeConditions['end_time'])) {
+                    $query->where('commission_time', '<=', $timeConditions['end_time']);
+                }
+            }
+        }
+
+        // 分页查询
+        $data = $query->paginate($pageSize);
+        $paginateData = $data->toArray();
+        
+        // 处理佣金列表数据
+        $this->processRewardList($paginateData['data']);
+        
+        // 计算summary统计信息
+        $summary = $this->calculateSummary($agent, $timeFilter, $startDate, $endDate);
+        
+        // 重新构造返回数据
+        $result = [
+            'total' => $paginateData['total'],
+            'per_page' => $paginateData['per_page'],
+            'current_page' => $paginateData['current_page'],
+            'last_page' => $paginateData['last_page'],
+            'list' => $paginateData['data'],
+            'summary' => $summary
+        ];
+
+        $this->success("", $result);
+    }
+
+    /**
+     * 处理佣金列表数据
+     * @param array $rewardList 佣金列表数据的引用
+     * @return void
+     */
+    private function processRewardList(&$rewardList)
+    {
+        if (empty($rewardList)) {
+            return;
+        }
+
+        foreach ($rewardList as &$reward) {
+            // 格式化佣金金额
+            $reward['commission'] = BcMath::format($reward['commission'] ?? '0.00');
+            
+            // 格式化佣金时间
+            $reward['commission_time_text'] = !empty($reward['commission_time']) 
+                ? date('Y-m-d H:i:s', $reward['commission_time']) 
+                : '';
+                
+            // 添加佣金类型描述
+            $reward['type_text'] = $this->getRewardTypeText($reward['type'] ?? '');
+            
+            // 添加订单信息(如果有关联订单)
+            if (!empty($reward['commission_order'])) {
+                $order = $reward['commission_order'];
+                $reward['order_info'] = [
+                    'order_id' => $order['order_id'] ?? '',
+                    'amount' => BcMath::format($order['amount'] ?? '0.00'),
+                    'buyer_nickname' => $order['buyer_nickname'] ?? '',
+                ];
+            }
+            
+            // 清理不需要的关联数据,避免冗余
+            unset($reward['commission_order']);
+        }
+    }
+
+    /**
+     * 获取佣金类型描述
+     * @param string $type 佣金类型
+     * @return string
+     */
+    private function getRewardTypeText($type)
+    {
+        $typeMap = [
+            'money' => '现金佣金',
+            'score' => '积分佣金',
+            'commission' => '佣金收益',
+        ];
+
+        return $typeMap[$type] ?? '未知类型';
+    }
+
+    /**
+     * 计算summary统计信息
+     * @param object $agent 当前代理商对象
+     * @param string $timeFilter 时间筛选类型
+     * @param string $startDate 开始日期
+     * @param string $endDate 结束日期
+     * @return array
+     */
+    private function calculateSummary($agent, $timeFilter, $startDate, $endDate)
+    {
+        // 根据筛选条件构建统计查询
+        $query = RewardModel::where('agent_id', $agent->id)
+            ->where('status', RewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
+
+        // 应用时间筛选
+        if ($timeFilter !== 'all') {
+            $timeConditions = $this->getTimeFilterConditions($timeFilter, $startDate, $endDate);
+            if ($timeConditions) {
+                $query->where('commission_time', '>=', $timeConditions['start_time']);
+                if (isset($timeConditions['end_time'])) {
+                    $query->where('commission_time', '<=', $timeConditions['end_time']);
+                }
+            }
+        }
+
+        // 计算筛选条件下的统计数据
+        $totalCommission = $query->sum('commission') ?: '0.00';
+        $totalCount = $query->count();
+        
+        // 按佣金类型统计
+        $typeStats = $query->field('type, SUM(commission) as total_amount, COUNT(*) as count')
+            ->group('type')
+            ->select()
+            ->toArray();
+
+        $typeStatistics = [];
+        foreach ($typeStats as $stat) {
+            $typeStatistics[] = [
+                'type' => $stat['type'],
+                'type_text' => $this->getRewardTypeText($stat['type']),
+                'total_amount' => BcMath::format($stat['total_amount'] ?? '0.00'),
+                'count' => intval($stat['count'] ?? 0)
+            ];
+        }
+
+        return [
+            'total_commission' => BcMath::format($totalCommission),
+            'total_count' => $totalCount,
+            'agent_total_income' => BcMath::format($agent->total_income ?? '0.00'),
+            'agent_withdrawn_amount' => BcMath::format($agent->withdrawn_amount ?? '0.00'),
+            'available_balance' => BcMath::format(BcMath::sub($agent->total_income ?? '0.00', $agent->withdrawn_amount ?? '0.00')),
+            'type_statistics' => $typeStatistics
+        ];
+    }
+
+    /**
+     * 获取时间筛选条件
+     * @param string $timeFilter 时间筛选类型
+     * @param string $startDate 开始日期 (Y-m-d格式,用于自定义时间段)
+     * @param string $endDate 结束日期 (Y-m-d格式,用于自定义时间段)
+     * @return array|null 返回包含开始时间和结束时间的数组
+     */
+    private function getTimeFilterConditions($timeFilter, $startDate = '', $endDate = '')
+    {
+        $currentTime = time();
+        
+        switch ($timeFilter) {
+            case 'recent_7_days':
+                return [
+                    'start_time' => $currentTime - 7 * 24 * 3600,
+                ];
+                
+            case 'recent_30_days':
+                return [
+                    'start_time' => $currentTime - 30 * 24 * 3600,
+                ];
+                
+            case 'recent_90_days':
+                return [
+                    'start_time' => $currentTime - 90 * 24 * 3600,
+                ];
+                
+            case 'current_year':
+                // 当前年份的开始时间
+                $yearStart = strtotime(date('Y-01-01 00:00:00'));
+                // 当前年份的结束时间
+                $yearEnd = strtotime(date('Y-12-31 23:59:59'));
+                return [
+                    'start_time' => $yearStart,
+                    'end_time' => $yearEnd,
+                ];
+                
+            case 'custom':
+                // 自定义时间段
+                if (empty($startDate) || empty($endDate)) {
+                    return null;
+                }
+                
+                $startTime = strtotime($startDate . ' 00:00:00');
+                $endTime = strtotime($endDate . ' 23:59:59');
+                
+                if ($startTime === false || $endTime === false || $startTime > $endTime) {
+                    return null;
+                }
+                
+                return [
+                    'start_time' => $startTime,
+                    'end_time' => $endTime,
+                ];
+                
+            default:
+                return null;
+        }
+    }
 }

+ 33 - 0
application/api/validate/Reward.php

@@ -0,0 +1,33 @@
+<?php
+
+namespace app\api\validate;
+
+use think\Validate;
+
+class Reward extends Validate
+{
+    protected $rule = [
+        'page' => 'integer|egt:1',
+        'page_size' => 'integer|between:1,100',
+        'time_filter' => 'in:all,recent_7_days,recent_30_days,recent_90_days,current_year,custom',
+        'start_date' => 'date|requireIf:time_filter,custom',
+        'end_date' => 'date|requireIf:time_filter,custom|afterWith:start_date',
+    ];
+
+    protected $message = [
+        'page.integer' => '页码必须为整数',
+        'page.egt' => '页码必须大于等于1',
+        'page_size.integer' => '分页大小必须为整数',
+        'page_size.between' => '分页大小必须在1-100之间',
+        'time_filter.in' => '时间筛选参数无效,必须为:all、recent_7_days、recent_30_days、recent_90_days、current_year、custom中的一个',
+        'start_date.date' => '开始日期格式不正确',
+        'start_date.requireIf' => '选择自定义时间段时,开始日期不能为空',
+        'end_date.date' => '结束日期格式不正确',
+        'end_date.requireIf' => '选择自定义时间段时,结束日期不能为空',
+        'end_date.afterWith' => '结束日期必须大于等于开始日期',
+    ];
+
+    protected $scene = [
+        'list' => ['page', 'page_size', 'time_filter', 'start_date', 'end_date'],
+    ];
+}