Browse Source

fix:我的佣金

super-yimizi 9 hours ago
parent
commit
1bba06c593

+ 9 - 32
application/api/controller/Test.php

@@ -23,18 +23,18 @@ class Test extends Api
     public function testOrderPaidEvent()
     {
         // 检查是否为开发环境
-        if (config('app_debug') !== true) {
-            $this->error('此接口仅在开发环境下可用');
-        }
+        // if (config('app_debug') !== true) {
+        //     $this->error('此接口仅在开发环境下可用');
+        // }
 
         $orderId = $this->request->param('order_id');
         if (empty($orderId)) {
             $this->error('请提供订单ID');
         }
 
-        try {
+        // try {
             // 查询订单信息
-            $order = OrderModel::with(['items', 'user'])
+            $order = OrderModel::with('items')
                 ->where('id', $orderId)
                 ->find();
 
@@ -48,9 +48,6 @@ class Test extends Api
                 $this->error('用户不存在');
             }
 
-            // 记录触发前的状态
-            $beforeStats = $this->getCommissionStats($order, $user);
-
             // 手动触发支付后事件
             $eventData = [
                 'order' => $order,
@@ -59,33 +56,13 @@ class Test extends Api
 
             Hook::listen('order_paid_after', $eventData);
 
-            // 记录触发后的状态
-            $afterStats = $this->getCommissionStats($order, $user);
 
-            // 构建测试结果
-            $result = [
-                'test_info' => [
-                    'order_id' => $order->id,
-                    'order_sn' => $order->order_sn,
-                    'user_id' => $user->id,
-                    'user_nickname' => $user->nickname,
-                    'event_triggered_time' => date('Y-m-d H:i:s'),
-                    'order_status' => $order->status,
-                    'pay_status' => $order->pay_status,
-                    'total_amount' => $order->total_price,
-                ],
-                'order_items' => $this->formatOrderItems($order->items),
-                'commission_before' => $beforeStats,
-                'commission_after' => $afterStats,
-                'changes' => $this->compareStats($beforeStats, $afterStats),
-                'event_logs' => $this->getRecentCommissionLogs($user->id)
-            ];
 
-            $this->success('支付后事件测试完成', $result);
+            $this->success('支付后事件测试完成',);
 
-        } catch (\Exception $e) {
-            $this->error('测试失败: ' . $e->getMessage());
-        }
+        // } catch (\Exception $e) {
+        //     $this->error('测试失败: ' . $e->getMessage());
+        // }
     }
 
     /**

+ 34 - 120
application/api/controller/commission/Reward.php

@@ -19,7 +19,7 @@ class Reward extends Commission
     {
         $params = $this->request->param();
         
-        // 使用验证器验证分页参数:page, page_size, time_filter, start_date, end_date
+        // 使用验证器验证分页参数:page, page_size, year_month
         $validate = new \app\api\validate\Reward();
         if (!$validate->scene('list')->check($params)) {
             $this->error($validate->getError());
@@ -35,24 +35,19 @@ class Reward extends Commission
         
         // 获取验证后的参数
         $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'] : '';
+        $yearMonth = isset($params['year_month']) ? trim($params['year_month']) : '';
 
         // 构建查询条件
-        $query = RewardModel::where('agent_id', $agent->id)
+        $query = RewardModel::where('agent_id', $agent->user_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']);
-                }
+        // 年月筛选 (支持YYYY-MM格式)
+        if (!empty($yearMonth)) {
+            $timeWhere = $this->getYearMonthConditions($yearMonth);
+            if ($timeWhere) {
+                $query->where($timeWhere);
             }
         }
 
@@ -64,7 +59,11 @@ class Reward extends Commission
         $this->processRewardList($paginateData['data']);
         
         // 计算summary统计信息
-        $summary = $this->calculateSummary($agent, $timeFilter, $startDate, $endDate);
+        $totalAmount = '0.00';
+        $arrData = $paginateData['data'] ?? [];
+        foreach ($arrData as $record) {
+            $totalAmount = BcMath::add($totalAmount, $record['commission'], 2);
+        }
         
         // 重新构造返回数据
         $result = [
@@ -73,7 +72,9 @@ class Reward extends Commission
             'current_page' => $paginateData['current_page'],
             'last_page' => $paginateData['last_page'],
             'list' => $paginateData['data'],
-            'summary' => $summary
+            'summary' => [
+                'total_amount' => BcMath::format($totalAmount),
+            ]
         ];
 
         $this->success("", $result);
@@ -134,117 +135,30 @@ class Reward extends Commission
     }
 
     /**
-     * 计算summary统计信息
-     * @param object $agent 当前代理商对象
-     * @param string $timeFilter 时间筛选类型
-     * @param string $startDate 开始日期
-     * @param string $endDate 结束日期
-     * @return array
+     * 获取年月筛选条件 (与提现模块保持一致)
+     * @param string $yearMonth 年月字符串 (YYYY-MM格式)
+     * @return array|null 返回包含时间条件的数组
      */
-    private function calculateSummary($agent, $timeFilter, $startDate, $endDate)
+    private function getYearMonthConditions($yearMonth)
     {
-        // 根据筛选条件构建统计查询
-        $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']);
-                }
-            }
+        if (empty($yearMonth)) {
+            return null;
         }
-
-        // 计算筛选条件下的统计数据
-        $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)
+        // 解析年月字符串 (YYYY-MM)
+        if (preg_match('/^(\d{4})-(\d{2})$/', $yearMonth, $matches)) {
+            $year = (int)$matches[1];
+            $month = (int)$matches[2];
+            
+            // 按年月筛选
+            $startTime = mktime(0, 0, 0, $month, 1, $year);
+            $endTime = mktime(23, 59, 59, $month + 1, 0, $year);
+            
+            return [
+                'commission_time' => ['between', [$startTime, $endTime]]
             ];
         }
-
-        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;
-        }
+        return null;
     }
 }

+ 3 - 10
application/api/validate/Reward.php

@@ -9,9 +9,7 @@ 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',
+        'year_month' => 'regex:/^\d{4}-\d{2}$/',
     ];
 
     protected $message = [
@@ -19,15 +17,10 @@ class Reward extends Validate
         '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' => '结束日期必须大于等于开始日期',
+        'year_month.regex' => '年月格式不正确,请使用YYYY-MM格式',
     ];
 
     protected $scene = [
-        'list' => ['page', 'page_size', 'time_filter', 'start_date', 'end_date'],
+        'list' => ['page', 'page_size', 'year_month'],
     ];
 }

+ 26 - 0
application/common.php

@@ -110,6 +110,32 @@ if (!function_exists('get_sn')) {
     }
 }
 
+/**
+ * @notes 随机生成邀请码
+ * @param $length
+ * @return string
+ * @author Tab
+ * @date 2021/7/26 11:17
+ */
+function generate_code($length = 6)
+{
+    // 去除字母IO数字012
+    $letters = 'ABCDEFGHJKLMNPQRSTUVWXYZ3456789';
+    // 随机起始索引
+    $start = mt_rand(0, strlen($letters) - $length);
+    // 打乱字符串
+    $shuffleStr = str_shuffle($letters);
+    // 截取字符
+    $randomStr = substr($shuffleStr, $start, $length);
+    // 判断是否已被使用
+    $user = \app\common\model\User::where('code', $randomStr)->findOrEmpty();
+    if($user->isEmpty()) {
+        return $randomStr;
+    }
+    generate_code($length);
+}
+
+
 
 
 if (!function_exists('format_log_error')) {

+ 6 - 5
application/common/Service/Commission/Config.php

@@ -56,14 +56,15 @@ class Config
     // 是否需要完善分销商表单信息
     public function isAgentApplyForm()
     {
-        return boolval($this->config['agent_form']['status']);
+       // return boolval($this->config['agent_form']['status']);
+       return boolval("1");
     }
 
     // 获取申请资料表单信息
-    public function getAgentForm()
-    {
-        return $this->config['agent_form'];
-    }
+    // public function getAgentForm()
+    // {
+    //     return $this->config['agent_form'];
+    // }
 
 
     // 申请协议

+ 87 - 73
application/common/Service/Commission/Goods.php

@@ -2,63 +2,73 @@
 
 namespace app\common\Service\Commission;
 
-
 use app\common\model\commission\Level as LevelModel;
 use app\common\model\commission\CommissionGoods as CommissionGoodsModel;
 
-
-
 /**
- * 分销商品
+ * 分销商品服务(全新设计)
  */
 class Goods
 {
-
-    public $commissionGoods;     // 分销商品
-    protected $commissionConfig = NULL;    // 独立分销设置 默认无
+    public $commissionGoods;     // 分销商品模型
+    protected $commissionConfig = null;    // 独立分销设置
     protected $commissionRules;     // 分销规则
     protected $skuPriceId;          // 商品规格ID
 
     /**
-     * 获取商品实时分佣规则
+     * 构造函数
      * 
-     * @param int $goods   商品
-     * @param int $skuId   商品规格ID
+     * @param int|object $goods 商品ID或商品对象
+     * @param int $skuPriceId 商品规格ID
      */
     public function __construct($goods, $skuPriceId = 0)
     {
-        $commissionRules = CommissionGoodsModel::GOODS_COMMISSION_STATUS_OFF;
-
-        if(is_numeric($goods)) {
-            $this->commissionGoods = CommissionGoodsModel::where(['goods_id' => $goods, 'status' => CommissionGoodsModel::GOODS_COMMISSION_STATUS_ON])->find();
-        }else {
+        $this->skuPriceId = $skuPriceId;
+        
+        // 获取分销商品信息
+        if (is_numeric($goods)) {
+            $this->commissionGoods = CommissionGoodsModel::where([
+                'goods_id' => $goods, 
+                'status' => 1  // 参与分销
+            ])->find();
+        } else {
             $this->commissionGoods = $goods;
         }
-        $this->skuPriceId = $skuPriceId;
 
         if ($this->commissionGoods) {
-            $commission_config = $this->commissionGoods->commission_config;
-            if ($commission_config['status']) {
-                $this->commissionConfig = $commission_config;
-            }
-            switch ($this->commissionGoods->self_rules) {
-                    // 默认分销规则
-                case CommissionGoodsModel::GOODS_COMMISSION_RULES_DEFAULT:
-                    $commissionRules = $this->getDefaultCommissionRules();
-                    break;
+            // 获取独立配置
+            $this->commissionConfig = $this->commissionGoods->getCommissionConfig();
+            
+            // 获取佣金规则
+            $this->commissionRules = $this->loadCommissionRules();
+        } else {
+            $this->commissionRules = false;
+        }
+    }
 
-                    // 独立分销规则
-                case CommissionGoodsModel::GOODS_COMMISSION_RULES_SELF:
-                    $commissionRules = $this->getSelfCommissionRules();
-                    break;
+    /**
+     * 加载佣金规则
+     * @return array|false
+     */
+    private function loadCommissionRules()
+    {
+        if (!$this->commissionGoods) {
+            return false;
+        }
 
-                    // 批量分销规则
-                case CommissionGoodsModel::GOODS_COMMISSION_RULES_BATCH:
-                    $commissionRules = $this->getBatchCommissionRules();
-                    break;
-            }
+        switch ($this->commissionGoods->rule_type) {
+            case 0: // 默认规则
+                return $this->getDefaultCommissionRules();
+                
+            case 1: // 独立规则
+                return $this->commissionGoods->getCommissionRules($this->skuPriceId);
+                
+            case 2: // 批量规则
+                return $this->commissionGoods->getCommissionRules(0);
+                
+            default:
+                return false;
         }
-        $this->commissionRules = $commissionRules;
     }
 
     public function getCommissionConfig()
@@ -74,77 +84,81 @@ class Goods
     /**
      * 获取对应分销商等级、对应层级的商品佣金规则
      * 
-     * @param int $agentLevel      分销商等级(不是id)
-     * @param int $commissionLevel 分销商层级(默认一级)
+     * @param int $agentLevel 分销商等级
+     * @param int $commissionLevel 分销层级
+     * @return array|false
      */
     public function getCommissionLevelRule($agentLevel, $commissionLevel = 1)
     {
-        if (isset($this->commissionRules[$agentLevel]) && isset($this->commissionRules[$agentLevel][$commissionLevel])) {
-            $commissionRule = $this->commissionRules[$agentLevel][$commissionLevel];
-            return $commissionRule;
+        if (empty($this->commissionRules)) {
+            return false;
+        }
+
+        if (isset($this->commissionRules[$agentLevel][$commissionLevel])) {
+            return $this->commissionRules[$agentLevel][$commissionLevel];
         }
+        
         return false;
     }
 
     /**
-     * 计算对应规则分销佣金
+     * 计算分销佣金
      * 
-     * @param int $commissionRule      分销规则
-     * @param int $amount              结算价格
-     * @param int $goodsNum            购买数量
+     * @param array $commissionRule 分销规则
+     * @param string $amount 结算价格
+     * @param int $goodsNum 购买数量
+     * @return string
      */
     public function caculateGoodsCommission($commissionRule, $amount, $goodsNum = 1)
     {
-        $commission = 0;
-        if (!empty($commissionRule['rate']) && $commissionRule['rate'] > 0) {
-            $commission = round($amount * $commissionRule['rate'] * 0.01, 2);
+        if (empty($commissionRule)) {
+            return '0.00';
         }
-        if (!empty($commissionRule['money']) && $commissionRule['money'] > 0) {
-            $commission = $commissionRule['money'] * $goodsNum;
+
+        // 使用新的统一计算方法
+        if ($this->commissionGoods) {
+            return $this->commissionGoods->calculateCommission($commissionRule, $amount, $goodsNum);
         }
-        return number_format($commission, 2, '.', '');
+
+        return '0.00';
     }
 
-    // 获取分销商等级默认规则
+    /**
+     * 获取分销商等级默认规则
+     * @return array
+     */
     private function getDefaultCommissionRules()
     {
         $agentLevelRules = LevelModel::order('level asc')->column('commission_rules', 'level');
         $commissionRules = [];
+        
         foreach ($agentLevelRules as $agentLevel => $rule) {
             $rule = json_decode($rule, true);
+            if (!is_array($rule)) {
+                continue;
+            }
+            
             foreach ($rule as $commission_level => $percent) {
                 $commission_level = explode('_', $commission_level);
                 if (count($commission_level) >= 2) {
                     $levelName = $commission_level[1];
                     // 将英文级别名映射为数字级别
                     $levelMap = [
-                        'first' => 1,     // 一级 -> 一级  
-                        'second' => 2,    // 二级 -> 二级
-                        'third' => 3,     // 三级 -> 三级
+                        'first' => 1,     // 一级
+                        'second' => 2,    // 二级
+                        'third' => 3,     // 三级
                     ];
                     $level = isset($levelMap[$levelName]) ? $levelMap[$levelName] : intval($levelName);
-                    $commissionRules[$agentLevel][$level] = ['rate' => $percent];
+                    $commissionRules[$agentLevel][$level] = [
+                        'type' => 'rate',
+                        'value' => $percent,
+                        'rate' => $percent,
+                        'money' => ''
+                    ];
                 }
             }
         }
+        
         return $commissionRules;
     }
-
-    // 获取分销商品独立分佣规则
-    private function getSelfCommissionRules()
-    {
-        $commissionRules = [];
-        if (isset($this->commissionGoods->commission_rules[$this->skuPriceId])) {
-            $commissionRules = $this->commissionGoods->commission_rules[$this->skuPriceId];
-        }
-
-        return $commissionRules;
-    }
-
-
-    // 获取商品批量分佣规则
-    private function getBatchCommissionRules()
-    {
-        return $this->commissionGoods->commission_rules;
-    }
 }

+ 10 - 13
application/common/Service/Commission/Order.php

@@ -52,16 +52,17 @@ class Order
         }
 
         // 获取商品分销佣金规则
-        $this->goods = new Goods($this->item['goods_id'], $this->item['goods_sku_price_id']);
+        $this->goods = new Goods($this->item['goods_id'], $this->item['goods_sku_id']);
 
         // 商品有独立分销设置,覆盖默认系统配置
         if ($commissionConfig = $this->goods->getCommissionConfig()) {
             $this->config->setConfig($commissionConfig);
         }
+       
 
         // 获取系统设置分销层级
         $this->commissionLevel = $this->config->getCommissionLevel();
-
+     
         // 分销中心已关闭
         if (self::COMMISSION_CLOSE === $this->commissionLevel) {
             return false;
@@ -71,7 +72,6 @@ class Order
         if (!$this->goods->getCommissionRules()) {
             return false;
         }
-
         // 是否自购分销订单
         $this->selfBuy = $this->buyer->isAgentAvaliable() && $this->config->isSelfBuy();
 
@@ -84,7 +84,7 @@ class Order
         $this->amount = $this->getGoodsCommissionAmount();
 
         // 没有分佣的必要了
-        if ($this->amount <= 0) {
+        if (bccomp($this->amount, '0', 2) <= 0) {
             return false;
         }
 
@@ -95,13 +95,13 @@ class Order
     public function getGoodsCommissionAmount()
     {
         $commissionType = $this->config->getRewardType();
-        $amount = round(0, 2);
+        $amount = '0.00';
         switch ($commissionType) {
             case 'pay_price':
-                $amount = $this->item['pay_fee'];
+                $amount = bcadd($this->item['pay_amount'], '0', 2);
                 break;
             case 'goods_price':
-                $amount = round($this->item['goods_price'] * $this->item['goods_num'], 2);
+                $amount = bcmul($this->item['goods_price'], $this->item['nums'], 2);
                 break;
         }
         return $amount;
@@ -122,7 +122,6 @@ class Order
         if ($commissionOrder) {
             return $commissionOrder;
         }
-
         $commissionOrderParams = [
             'self_buy' => intval($this->selfBuy),
             'order_id' => $this->item['order_id'],
@@ -134,12 +133,11 @@ class Order
             'reward_type' => $this->config->getRewardType(),
             'commission_rules' => $this->goods->getCommissionRules(),  // 记录当前设置的分佣规则,防止以后系统或者分销商设置有变导致更改历史规则
             'reward_event' => $this->config->getRewardEvent(),
-            'commission_order_status' => $this->goods->commissionGoods->commission_order_status,  // 是否计入分销业绩
+            'commission_order_status' => $this->goods->commissionGoods->order_status,  // 是否计入分销业绩
             'commission_reward_status' => RewardModel::COMMISSION_REWARD_STATUS_PENDING,  // 佣金状态
         ];
 
         $commissionOrder = OrderModel::create($commissionOrderParams);
-
         // 添加分销商推广订单业绩
         $orderAgent = new Agent($commissionOrder->agent_id);
         if ($orderAgent->isAgentAvaliable() && $commissionOrder->commission_order_status) {
@@ -187,13 +185,12 @@ class Order
                 'agent_id' => $currentAgent->user->id,
                 'commission_level' => $currentCommissionLevel,   // 分佣层级
             ])->find();
-
             if (!$commissionReward) {
                 $currentAgentLevel = $currentAgent->getAgentLevel();
                 $currentCommissionLevelRule = $this->goods->getCommissionLevelRule($currentAgentLevel, $currentCommissionLevel);
                 if ($currentCommissionLevelRule) {
-                    $commission = $this->goods->caculateGoodsCommission($currentCommissionLevelRule, $this->amount, $this->item['goods_num']);
-                    if ($commission > 0) {
+                    $commission = $this->goods->caculateGoodsCommission($currentCommissionLevelRule, $this->amount, $this->item['nums']);
+                    if (bccomp($commission, '0', 2) > 0) {
                         $commissionRewardParams = [
                             'order_id' => $commissionOrder->order_id,
                             'order_item_id' => $commissionOrder->order_item_id,

+ 2 - 2
application/common/Service/Commission/Reward.php

@@ -41,10 +41,11 @@ class Reward
             return false;
         }
         // 已经操作过了
-
+       
         if ($commissionOrder['commission_reward_status'] !== RewardModel::COMMISSION_REWARD_STATUS_PENDING) {
             return false;
         }
+      
 
         $rewardEvent = $commissionOrder['reward_event'];
 
@@ -57,7 +58,6 @@ class Reward
         $commissionOrder->commission_reward_status = RewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED;
         $commissionOrder->commission_time = time();
         $commissionOrder->save();
-
         // 防止重复添加佣金
         $commissionRewards = RewardModel::where([
             'commission_order_id' => $commissionOrder['id'],

+ 4 - 1
application/common/model/Order.php

@@ -56,7 +56,10 @@ class Order extends Model
     {
         return $this->hasMany('OrderGoods', 'order_sn', 'order_sn');
     }
-
+    public function items()
+    {
+        return $this->hasMany('OrderGoods', 'order_id', 'id');
+    }
     public function orderElectronics()
     {
         return $this->hasMany('OrderElectronics', 'order_sn', 'order_sn');

+ 176 - 25
application/common/model/commission/CommissionGoods.php

@@ -2,46 +2,197 @@
 
 namespace app\common\model\commission;
 
-use app\common\model\Goods as GoodsModel;
 use think\Model;
 
+/**
+ * 分销商品模型(全新设计)
+ */
 class CommissionGoods extends Model
 {
-    protected $pk = 'goods_id';
-
     protected $name = 'shop_commission_goods';
-    
-    protected $autoWriteTimestamp = false;
 
-    // 分销状态
-    const GOODS_COMMISSION_STATUS_OFF = 0;     // 商品不参与分佣
-    const GOODS_COMMISSION_STATUS_ON = 1;     // 商品参与分佣
-    const GOODS_COMMISSION_RULES_DEFAULT = 0;       // 默认分销规则  只看系统分销商等级规则
-    const GOODS_COMMISSION_RULES_SELF = 1;          // 独立分销规则  等级规则对应多种规格规则
-    const GOODS_COMMISSION_RULES_BATCH = 2;         // 批量分销规则  只看保存的各分销商等级规则
+    // 规则类型常量
+    const RULE_TYPE_DEFAULT = 0;  // 默认规则(使用分销商等级规则)
+    const RULE_TYPE_CUSTOM = 1;   // 独立规则(每个SKU独立设置)
+    const RULE_TYPE_BATCH = 2;    // 批量规则(所有SKU相同)
+
+    // 状态常量
+    const STATUS_DISABLED = 0;    // 不参与分销
+    const STATUS_ENABLED = 1;     // 参与分销
 
     protected $type = [
-        'commission_rules' => 'json'
-    ];
-    protected $append = [
-        'status_text'
+        'config' => 'json',
+        'created_at' => 'timestamp',
+        'updated_at' => 'timestamp'
     ];
 
-    public function statusList()
+    protected $json = ['config'];
+
+    /**
+     * 关联佣金规则
+     */
+    public function rules()
     {
-        return [
-            0 => '不参与',
-            1 => '参与中'
-        ];
+        return $this->hasMany('CommissionRules', 'goods_id', 'goods_id')
+                   ->where('status', 1)
+                   ->order('agent_level asc, level asc');
+    }
+
+    /**
+     * 获取商品分销配置
+     * @return array|null
+     */
+    public function getCommissionConfig()
+    {
+        if ($this->rule_type === self::RULE_TYPE_CUSTOM && !empty($this->config)) {
+            return $this->config;
+        }
+        return null;
+    }
+
+    /**
+     * 获取商品佣金规则
+     * @param int $skuId SKU ID
+     * @return array
+     */
+    public function getCommissionRules($skuId = 0)
+    {
+        if ($this->rule_type === self::RULE_TYPE_DEFAULT) {
+            return false; // 使用默认规则
+        }
+
+        $query = $this->rules();
+        
+        if ($this->rule_type === self::RULE_TYPE_CUSTOM) {
+            // 独立规则:查询指定SKU的规则
+            $query->where('sku_id', $skuId);
+        } else {
+            // 批量规则:查询通用规则
+            $query->where('sku_id', 0);
+        }
+
+        $rules = $query->select();
+        
+        if ($rules->isEmpty()) {
+            return false;
+        }
+
+        // 转换为嵌套数组格式
+        $result = [];
+        foreach ($rules as $rule) {
+            $result[$rule['agent_level']][$rule['level']] = [
+                'type' => $rule['type'],
+                'value' => $rule['value'],
+                'rate' => $rule['type'] === 'rate' ? $rule['value'] : '',
+                'money' => $rule['type'] === 'money' ? $rule['value'] : ''
+            ];
+        }
+
+        return $result;
+    }
+
+    /**
+     * 获取指定层级的佣金规则
+     * @param int $agentLevel 分销商等级
+     * @param int $commissionLevel 分销层级
+     * @param int $skuId SKU ID
+     * @return array|false
+     */
+    public function getCommissionLevelRule($agentLevel, $commissionLevel, $skuId = 0)
+    {
+        $rules = $this->getCommissionRules($skuId);
+        
+        if ($rules && isset($rules[$agentLevel][$commissionLevel])) {
+            return $rules[$agentLevel][$commissionLevel];
+        }
+        
+        return false;
+    }
+
+    /**
+     * 计算佣金
+     * @param array $rule 佣金规则
+     * @param string $amount 结算金额
+     * @param int $quantity 商品数量
+     * @return string
+     */
+    public function calculateCommission($rule, $amount, $quantity = 1)
+    {
+        if (empty($rule) || !isset($rule['type'], $rule['value'])) {
+            return '0.00';
+        }
+
+        if ($rule['type'] === 'rate' && bccomp($rule['value'], '0', 4) > 0) {
+            // 比例佣金:金额 * 比例 / 100
+            return bcmul(
+                bcmul($amount, $rule['value'], 4),
+                '0.01',
+                2
+            );
+        }
+
+        if ($rule['type'] === 'money' && bccomp($rule['value'], '0', 2) > 0) {
+            // 固定金额:金额 * 数量
+            return bcmul($rule['value'], $quantity, 2);
+        }
+
+        return '0.00';
+    }
+
+    /**
+     * 设置商品佣金规则
+     * @param array $rulesData 规则数据
+     * @param int $skuId SKU ID
+     * @return bool
+     */
+    public function setCommissionRules($rulesData, $skuId = 0)
+    {
+        // 删除现有规则
+        CommissionRules::where([
+            'goods_id' => $this->goods_id,
+            'sku_id' => $skuId
+        ])->delete();
+
+        // 批量插入新规则
+        $insertData = [];
+        foreach ($rulesData as $agentLevel => $levelRules) {
+            foreach ($levelRules as $level => $rule) {
+                if (!empty($rule['value']) && bccomp($rule['value'], '0', 4) > 0) {
+                    $insertData[] = [
+                        'goods_id' => $this->goods_id,
+                        'sku_id' => $skuId,
+                        'agent_level' => $agentLevel,
+                        'level' => $level,
+                        'type' => $rule['type'],
+                        'value' => $rule['value'],
+                        'status' => 1
+                    ];
+                }
+            }
+        }
+
+        if (!empty($insertData)) {
+            return CommissionRules::insertAll($insertData);
+        }
+
+        return true;
     }
 
-    public function getCommissionConfigAttr($value, $data)
+    /**
+     * 检查商品是否参与分销
+     * @return bool
+     */
+    public function isCommissionEnabled()
     {
-        return json_decode($value, true);
+        return $this->status === self::STATUS_ENABLED;
     }
 
-    public function goods()
+    /**
+     * 检查是否计入业绩
+     * @return bool
+     */
+    public function isOrderStatusEnabled()
     {
-        return $this->belongsTo(GoodsModel::class, 'goods_id', 'id');
+        return $this->order_status === 1;
     }
-}
+}

+ 182 - 0
application/common/model/commission/CommissionRules.php

@@ -0,0 +1,182 @@
+<?php
+
+namespace app\common\model\commission;
+
+use think\Model;
+
+/**
+ * 分销佣金规则模型
+ */
+class CommissionRules extends Model
+{
+    protected $name = 'shop_commission_rules';
+
+    // 佣金类型常量
+    const TYPE_RATE = 'rate';   // 比例佣金
+    const TYPE_MONEY = 'money'; // 固定金额
+
+    // 状态常量
+    const STATUS_DISABLED = 0; // 禁用
+    const STATUS_ENABLED = 1;  // 启用
+
+    protected $type = [
+        'value' => 'float',
+        'created_at' => 'timestamp',
+        'updated_at' => 'timestamp'
+    ];
+
+    /**
+     * 关联商品
+     */
+    public function goods()
+    {
+        return $this->belongsTo('CommissionGoods', 'goods_id', 'goods_id');
+    }
+
+    /**
+     * 计算佣金
+     * @param string $amount 结算金额
+     * @param int $quantity 商品数量
+     * @return string
+     */
+    public function calculateCommission($amount, $quantity = 1)
+    {
+        if ($this->type === self::TYPE_RATE) {
+            // 比例佣金:金额 * 比例 / 100
+            return bcmul(
+                bcmul($amount, $this->value, 4),
+                '0.01',
+                2
+            );
+        } else {
+            // 固定金额:金额 * 数量
+            return bcmul($this->value, $quantity, 2);
+        }
+    }
+
+    /**
+     * 获取特定规则
+     * @param int $goodsId 商品ID
+     * @param int $skuId SKU ID
+     * @param int $agentLevel 分销商等级
+     * @param int $level 分销层级
+     * @return CommissionRules|null
+     */
+    public static function getRule($goodsId, $skuId, $agentLevel, $level)
+    {
+        return self::where([
+            'goods_id' => $goodsId,
+            'sku_id' => $skuId,
+            'agent_level' => $agentLevel,
+            'level' => $level,
+            'status' => self::STATUS_ENABLED
+        ])->find();
+    }
+
+    /**
+     * 批量获取商品规则
+     * @param int $goodsId 商品ID
+     * @param int $skuId SKU ID,0表示批量规则
+     * @return array
+     */
+    public static function getGoodsRules($goodsId, $skuId = 0)
+    {
+        $rules = self::where([
+            'goods_id' => $goodsId,
+            'sku_id' => $skuId,
+            'status' => self::STATUS_ENABLED
+        ])->order('agent_level asc, level asc')->select();
+
+        $result = [];
+        foreach ($rules as $rule) {
+            $result[$rule['agent_level']][$rule['level']] = [
+                'type' => $rule['type'],
+                'value' => $rule['value'],
+                'rate' => $rule['type'] === self::TYPE_RATE ? $rule['value'] : '',
+                'money' => $rule['type'] === self::TYPE_MONEY ? $rule['value'] : ''
+            ];
+        }
+
+        return $result;
+    }
+
+    /**
+     * 批量设置规则
+     * @param int $goodsId 商品ID
+     * @param int $skuId SKU ID
+     * @param array $rulesData 规则数据
+     * @return bool
+     */
+    public static function setGoodsRules($goodsId, $skuId, $rulesData)
+    {
+        // 删除现有规则
+        self::where([
+            'goods_id' => $goodsId,
+            'sku_id' => $skuId
+        ])->delete();
+
+        // 批量插入新规则
+        $insertData = [];
+        foreach ($rulesData as $agentLevel => $levelRules) {
+            foreach ($levelRules as $level => $rule) {
+                if (isset($rule['type'], $rule['value']) && bccomp($rule['value'], '0', 4) > 0) {
+                    $insertData[] = [
+                        'goods_id' => $goodsId,
+                        'sku_id' => $skuId,
+                        'agent_level' => $agentLevel,
+                        'level' => $level,
+                        'type' => $rule['type'],
+                        'value' => $rule['value'],
+                        'status' => self::STATUS_ENABLED
+                    ];
+                }
+            }
+        }
+
+        if (!empty($insertData)) {
+            return self::insertAll($insertData);
+        }
+
+        return true;
+    }
+
+    /**
+     * 删除商品的所有规则
+     * @param int $goodsId 商品ID
+     * @return bool
+     */
+    public static function deleteGoodsRules($goodsId)
+    {
+        return self::where('goods_id', $goodsId)->delete();
+    }
+
+    /**
+     * 复制规则到新商品
+     * @param int $fromGoodsId 源商品ID
+     * @param int $toGoodsId 目标商品ID
+     * @return bool
+     */
+    public static function copyRules($fromGoodsId, $toGoodsId)
+    {
+        $sourceRules = self::where('goods_id', $fromGoodsId)->select();
+        
+        if ($sourceRules->isEmpty()) {
+            return true;
+        }
+
+        $insertData = [];
+        foreach ($sourceRules as $rule) {
+            $insertData[] = [
+                'goods_id' => $toGoodsId,
+                'sku_id' => $rule['sku_id'],
+                'agent_level' => $rule['agent_level'],
+                'level' => $rule['level'],
+                'type' => $rule['type'],
+                'value' => $rule['value'],
+                'status' => $rule['status']
+            ];
+        }
+
+        return self::insertAll($insertData);
+    }
+}

+ 28 - 0
application/common/model/commission/Reward.php

@@ -50,6 +50,26 @@ class Reward extends Model
     }
 
     /**
+     * 获取状态文本
+     */
+    public function getStatusTextAttr($value, $data)
+    {
+        $status = isset($data['status']) ? $data['status'] : $this->getData('status');
+        $statusList = $this->statusList();
+        return isset($statusList[$status]) ? $statusList[$status] : '未知';
+    }
+
+    /**
+     * 获取类型文本
+     */
+    public function getTypeTextAttr($value, $data)
+    {
+        $type = isset($data['type']) ? $data['type'] : $this->getData('type');
+        $typeList = $this->typeList();
+        return isset($typeList[$type]) ? $typeList[$type] : '未知';
+    }
+
+    /**
      * 待入账
      */
     public function scopePending($query)
@@ -109,4 +129,12 @@ class Reward extends Model
     {
         return $this->belongsTo(OrderItemModel::class, 'order_item_id', 'id');
     }
+
+    /**
+     * 关联分销订单
+     */
+    public function commissionOrder()
+    {
+        return $this->belongsTo('app\common\model\commission\Order', 'commission_order_id', 'id');
+    }
 }

+ 1 - 5
application/listeners/Commission.php

@@ -57,19 +57,16 @@ class Commission
         // 订单支付成功
         $order = $params['order'];
 
-        // 积分商品订单不参与分销
-        if ($order['type'] === 'score') return;
+        //
 
         $user = $params['user'];
 
         $agent = new AgentService($user);
-
         // 绑定用户关系
         $agent->bindUserRelation('pay');
 
         // 先记录分佣 再处理记录业绩、升级等情况
         $items = $order ? $order['items'] : [];
-
         foreach ($items as $item) {
             if (isset($item['ext']['is_commission']) && !$item['ext']['is_commission']) continue;
 
@@ -86,7 +83,6 @@ class Commission
             // 支付后拨款
             (new RewardService('paid'))->runCommissionRewardByOrder($commissionOrder);
         }
-
         // 创建分销商
         $agent->createNewAgent();
         // 分销商数据统计&升级(异步执行)