ソースを参照

refactor(urs-promotion):重构 URS 推广模块代码

- 删除了多个不再使用的命令文件
- 更新了达人等级逻辑测试代码
- 重构了 UrsReferralService 中的推荐关系创建和统计更新逻辑
- 修复了 UrsRewardDistributionService 中的用户 talent 获取问题
notfff 6 ヶ月 前
コミット
66f9cd974d

+ 0 - 135
app/Module/UrsPromotion/Commands/InsertUrsPromotionAdminMenuCommand.php

@@ -1,135 +0,0 @@
-<?php
-
-namespace App\Module\UrsPromotion\Commands;
-
-use Illuminate\Console\Command;
-use Illuminate\Support\Facades\DB;
-
-/**
- * URS推广模块后台菜单配置命令
- * 
- * 用于配置URS推广模块的后台管理菜单
- */
-class InsertUrsPromotionAdminMenuCommand extends Command
-{
-    /**
-     * 命令签名
-     */
-    protected $signature = 'urs:insert-admin-menu {--force : 强制重新创建菜单}';
-
-    /**
-     * 命令描述
-     */
-    protected $description = '配置URS推广模块后台管理菜单';
-
-    /**
-     * 执行命令
-     */
-    public function handle()
-    {
-        $this->info('开始配置URS推广模块后台管理菜单...');
-        
-        // 检查是否强制重新创建
-        $force = $this->option('force');
-        
-        // 检查菜单是否已存在
-        $existingMenu = DB::table('admin_menu')->where('title', 'URS推广管理')->first();
-        if ($existingMenu && !$force) {
-            $this->warn('URS推广管理菜单已存在,使用 --force 参数强制重新创建');
-            return;
-        }
-        
-        if ($existingMenu && $force) {
-            $this->info('删除现有菜单...');
-            $this->deleteExistingMenus();
-        }
-        
-        // 创建菜单
-        $this->createMenus();
-        
-        $this->info('URS推广模块后台管理菜单配置完成!');
-    }
-    
-    /**
-     * 删除现有菜单
-     */
-    private function deleteExistingMenus(): void
-    {
-        // 删除URS推广相关的所有菜单
-        DB::table('admin_menu')->where('title', 'like', '%URS%')->delete();
-    }
-    
-    /**
-     * 创建菜单
-     */
-    private function createMenus(): void
-    {
-        // 获取下一个可用的order值
-        $maxOrder = DB::table('admin_menu')->max('order') ?? 0;
-        
-        // 1. 创建一级菜单:URS推广管理
-        $parentId = DB::table('admin_menu')->insertGetId([
-            'parent_id' => 0,
-            'order' => $maxOrder + 1,
-            'title' => 'URS推广管理',
-            'icon' => 'fa-users',
-            'uri' => '',
-            'extension' => '',
-            'show' => 1,
-            'created_at' => now(),
-            'updated_at' => now(),
-        ]);
-        
-        $this->info("创建一级菜单:URS推广管理 (ID: {$parentId})");
-        
-        // 2. 创建二级菜单
-        $menus = [
-            [
-                'title' => 'URS用户绑定关系',
-                'icon' => 'fa-exchange',
-                'uri' => 'urs-promotion/user-mappings',
-                'permission' => '',
-            ],
-            [
-                'title' => 'URS推荐关系',
-                'icon' => 'fa-link',
-                'uri' => 'urs-promotion/user-referrals',
-                'permission' => '',
-            ],
-            [
-                'title' => 'URS达人等级',
-                'icon' => 'fa-star',
-                'uri' => 'urs-promotion/user-talents',
-                'permission' => '',
-            ],
-            [
-                'title' => 'URS收益记录',
-                'icon' => 'fa-money',
-                'uri' => 'urs-promotion/profits',
-                'permission' => '',
-            ],
-            [
-                'title' => 'URS等级配置',
-                'icon' => 'fa-cog',
-                'uri' => 'urs-promotion/talent-configs',
-                'permission' => '',
-            ],
-        ];
-        
-        foreach ($menus as $index => $menu) {
-            $menuId = DB::table('admin_menu')->insertGetId([
-                'parent_id' => $parentId,
-                'order' => $maxOrder + 2 + $index,
-                'title' => $menu['title'],
-                'icon' => $menu['icon'],
-                'uri' => $menu['uri'],
-                'extension' => '',
-                'show' => 1,
-                'created_at' => now(),
-                'updated_at' => now(),
-            ]);
-            
-            $this->info("创建二级菜单:{$menu['title']} (ID: {$menuId})");
-        }
-    }
-}

+ 0 - 81
app/Module/UrsPromotion/Commands/InsertUrsTransferFeeAdminMenuCommand.php

@@ -1,81 +0,0 @@
-<?php
-
-namespace App\Module\UrsPromotion\Commands;
-
-use Illuminate\Console\Command;
-use Dcat\Admin\Models\Menu;
-
-/**
- * 插入URS转出手续费配置后台菜单命令
- */
-class InsertUrsTransferFeeAdminMenuCommand extends Command
-{
-    /**
-     * 命令签名
-     *
-     * @var string
-     */
-    protected $signature = 'urs:insert-transfer-fee-admin-menu';
-
-    /**
-     * 命令描述
-     *
-     * @var string
-     */
-    protected $description = '插入URS转出手续费配置后台管理菜单';
-
-    /**
-     * 执行命令
-     */
-    public function handle()
-    {
-        $this->info('开始插入URS转出手续费配置后台管理菜单...');
-
-        try {
-            // 查找URS推广管理的父菜单
-            $parentMenu = Menu::where('title', 'URS推广管理')->first();
-            
-            if (!$parentMenu) {
-                $this->error('未找到URS推广管理父菜单,请先运行 php artisan urs:insert-admin-menu');
-                return 1;
-            }
-
-            // 检查菜单是否已存在
-            $existingMenu = Menu::where('title', 'URS转出手续费配置')
-                ->where('parent_id', $parentMenu->id)
-                ->first();
-
-            if ($existingMenu) {
-                $this->warn('URS转出手续费配置菜单已存在,跳过创建');
-                return 0;
-            }
-
-            // 获取当前最大排序值
-            $maxOrder = Menu::where('parent_id', $parentMenu->id)->max('order') ?? 0;
-
-            // 创建菜单
-            $menu = new Menu();
-            $menu->parent_id = $parentMenu->id;
-            $menu->order = $maxOrder + 1;
-            $menu->title = 'URS转出手续费配置';
-            $menu->icon = 'feather icon-percent';
-            $menu->uri = 'urs-promotion/transfer-fee-config';
-            $menu->created_at = now();
-            $menu->updated_at = now();
-            $menu->save();
-
-            $this->info('URS转出手续费配置菜单创建成功!');
-            $this->info("菜单ID: {$menu->id}");
-            $this->info("菜单标题: {$menu->title}");
-            $this->info("菜单URI: {$menu->uri}");
-            $this->info("父菜单: {$parentMenu->title}");
-            $this->info("排序: {$menu->order}");
-
-            return 0;
-
-        } catch (\Exception $e) {
-            $this->error('插入菜单失败: ' . $e->getMessage());
-            return 1;
-        }
-    }
-}

+ 0 - 219
app/Module/UrsPromotion/Commands/UrsPromotionIntegrationTestCommand.php

@@ -1,219 +0,0 @@
-<?php
-
-namespace App\Module\UrsPromotion\Commands;
-
-use Illuminate\Console\Command;
-use App\Module\UrsPromotion\Services\UrsProfitService;
-use App\Module\UrsPromotion\Services\UrsTalentService;
-use App\Module\UrsPromotion\Models\UrsUserReferral;
-use App\Module\UrsPromotion\Models\UrsUserTalent;
-use App\Module\UrsPromotion\Models\UrsProfit;
-use App\Module\UrsPromotion\Models\UrsTalentConfig;
-use Illuminate\Support\Facades\DB;
-
-/**
- * URS推广模块集成测试命令
- * 
- * 用于全面测试URS推广系统的各项功能
- */
-class UrsPromotionIntegrationTestCommand extends Command
-{
-    /**
-     * 命令签名
-     */
-    protected $signature = 'urs:integration-test {--reset : 重置测试数据}';
-
-    /**
-     * 命令描述
-     */
-    protected $description = 'URS推广模块集成测试';
-
-    /**
-     * 执行命令
-     */
-    public function handle()
-    {
-        $this->info('开始URS推广模块集成测试...');
-        $this->line('');
-        
-        // 检查是否重置数据
-        if ($this->option('reset')) {
-            $this->resetTestData();
-        }
-        
-        // 1. 测试达人等级配置
-        $this->testTalentConfigs();
-        
-        // 2. 测试推荐关系
-        $this->testReferralRelations();
-        
-        // 3. 测试达人等级计算
-        $this->testTalentLevelCalculation();
-        
-        // 4. 测试收益分成
-        $this->testProfitDistribution();
-        
-        // 5. 测试统计功能
-        $this->testStatistics();
-        
-        $this->line('');
-        $this->info('URS推广模块集成测试完成!');
-    }
-    
-    /**
-     * 重置测试数据
-     */
-    private function resetTestData(): void
-    {
-        $this->warn('重置测试数据...');
-        
-        // 清空测试数据(保留配置)
-        UrsProfit::where('source_type', 'like', 'test_%')->delete();
-        UrsUserTalent::whereIn('user_id', [2001, 2002, 2003, 2004, 2005])->delete();
-        UrsUserReferral::whereIn('user_id', [2001, 2002, 2003, 2004, 2005])->delete();
-        
-        $this->info('测试数据重置完成');
-        $this->line('');
-    }
-    
-    /**
-     * 测试达人等级配置
-     */
-    private function testTalentConfigs(): void
-    {
-        $this->info('=== 测试达人等级配置 ===');
-        
-        $configs = UrsTalentService::getAllTalentConfigs();
-        $this->line('达人等级配置数量: ' . count($configs));
-        
-        foreach ($configs as $config) {
-            $this->line("等级{$config['level']}: {$config['name']} (直推{$config['direct_count_required']}人, 团队{$config['promotion_count_required']}人)");
-        }
-        
-        $this->line('');
-    }
-    
-    /**
-     * 测试推荐关系
-     */
-    private function testReferralRelations(): void
-    {
-        $this->info('=== 测试推荐关系 ===');
-        
-        // 创建测试推荐关系: 2001 -> 2002 -> 2003 -> 2004
-        $referrals = [
-            ['urs_user_id' => 2002, 'urs_referrer_id' => 2001],
-            ['urs_user_id' => 2003, 'urs_referrer_id' => 2002],
-            ['urs_user_id' => 2004, 'urs_referrer_id' => 2003],
-            ['urs_user_id' => 2005, 'urs_referrer_id' => 2001], // 2001的另一个直推
-        ];
-        
-        foreach ($referrals as $referral) {
-            UrsUserReferral::updateOrCreate(
-                ['urs_user_id' => $referral['urs_user_id']],
-                array_merge($referral, [
-                    'referral_time' => now(),
-                    'status' => UrsUserReferral::STATUS_VALID,
-                ])
-            );
-            $this->line("创建推荐关系: URS用户{$referral['urs_user_id']} <- URS用户{$referral['urs_referrer_id']}");
-        }
-        
-        $this->line('');
-    }
-    
-    /**
-     * 测试达人等级计算
-     */
-    private function testTalentLevelCalculation(): void
-    {
-        $this->info('=== 测试达人等级计算 ===');
-        
-        // 更新用户2001的达人等级
-        $talent = UrsTalentService::updateUserTalent(2001);
-        if ($talent) {
-            $this->line("用户2001达人等级: {$talent->getTalentLevelName()}");
-            $this->line("直推: {$talent->direct_count}, 间推: {$talent->indirect_count}, 三推: {$talent->third_count}, 总计: {$talent->promotion_count}");
-        }
-        
-        // 显示推荐关系树
-        $tree = UrsTalentService::getUserReferralTree(2001);
-        $this->line('推荐关系树:');
-        $this->line("  直推: " . count($tree['direct']) . "人");
-        $this->line("  间推: " . count($tree['indirect']) . "人");
-        $this->line("  三推: " . count($tree['third']) . "人");
-        
-        $this->line('');
-    }
-    
-    /**
-     * 测试收益分成
-     */
-    private function testProfitDistribution(): void
-    {
-        $this->info('=== 测试收益分成 ===');
-        
-        // 测试推广收益分成
-        $this->line('测试推广收益分成 (用户2005进入农场, 奖励500金币):');
-        $profits = UrsProfitService::distributePromotionReward(2005, 'test_farm_enter', 12345, '500');
-        $this->displayProfits($profits);
-        
-        // 测试种植收益分成
-        $this->line('测试种植收益分成 (用户2004收获作物, 奖励1000金币):');
-        $profits = UrsProfitService::distributePlantingReward(2004, 'test_farm_harvest', 67890, '1000');
-        $this->displayProfits($profits);
-        
-        $this->line('');
-    }
-    
-    /**
-     * 测试统计功能
-     */
-    private function testStatistics(): void
-    {
-        $this->info('=== 测试统计功能 ===');
-        
-        // 获取用户2001的收益统计
-        $stats = UrsProfitService::getUserProfitStats(2001);
-        $this->line("用户2001总收益: {$stats['total_amount']} (共{$stats['total_count']}笔)");
-        
-        if (!empty($stats['by_type'])) {
-            foreach ($stats['by_type'] as $type => $data) {
-                $typeName = $type === 'promotion_reward' ? '推广收益' : '种植收益';
-                $this->line("  {$typeName}: {$data['amount']} (共{$data['count']}笔)");
-            }
-        }
-        
-        if (!empty($stats['by_level'])) {
-            foreach ($stats['by_level'] as $level => $data) {
-                $levelName = match($level) {
-                    1 => '直推',
-                    2 => '间推',
-                    3 => '三推',
-                    default => "层级{$level}",
-                };
-                $this->line("  {$levelName}: {$data['amount']} (共{$data['count']}笔)");
-            }
-        }
-        
-        $this->line('');
-    }
-    
-    /**
-     * 显示收益分成结果
-     */
-    private function displayProfits(array $profits): void
-    {
-        if (empty($profits)) {
-            $this->line('  无收益分成');
-            return;
-        }
-        
-        foreach ($profits as $profit) {
-            $rate = round($profit->profit_rate * 100, 2);
-            $levelName = $profit->getRelationLevelName();
-            $typeName = $profit->getProfitTypeName();
-            $this->line("  用户{$profit->user_id}: {$profit->profit_amount} ({$rate}%, {$levelName}, {$typeName})");
-        }
-    }
-}

+ 3 - 3
app/Module/UrsPromotion/Docs/达人等级逻辑.md

@@ -567,14 +567,14 @@ class UrsTalentServiceTest extends TestCase
     public function testUpdateTalentLevel()
     {
         // 准备测试数据
-        $ursUserId = 12345;
+        $userId = 12345;
 
         // 执行测试
-        $result = UrsTalentService::updateTalentLevel($ursUserId);
+        $result = UrsTalentService::updateTalentLevel($userId);
 
         // 断言结果
         $this->assertInstanceOf(UrsUserTalentDto::class, $result);
-        $this->assertEquals($ursUserId, $result->ursUserId);
+        $this->assertEquals($userId, $result->user_id);
         $this->assertGreaterThanOrEqual(0, $result->talentLevel);
     }
 

+ 15 - 13
app/Module/UrsPromotion/Services/UrsReferralService.php

@@ -3,6 +3,7 @@
 namespace App\Module\UrsPromotion\Services;
 
 use App\Module\UrsPromotion\Dtos\UrsUserReferralDto;
+use App\Module\UrsPromotion\Models\UrsUserMapping;
 use App\Module\UrsPromotion\Models\UrsUserReferral;
 use App\Module\UrsPromotion\Models\UrsUserTalent;
 use Illuminate\Support\Facades\DB;
@@ -10,7 +11,7 @@ use Illuminate\Support\Facades\Log;
 
 /**
  * URS推荐关系服务
- * 
+ *
  * 管理URS用户之间的推荐关系
  */
 class UrsReferralService
@@ -27,23 +28,23 @@ class UrsReferralService
     {
         try {
             DB::beginTransaction();
-            
+
             // 检查是否已存在推荐关系
             $existingReferral = UrsUserReferral::where('urs_user_id', $ursUserId)->first();
             if ($existingReferral) {
                 throw new \Exception("URS用户ID {$ursUserId} 已存在推荐关系");
             }
-            
+
             // 检查推荐人是否存在
             if ($ursUserId === $ursReferrerId) {
                 throw new \Exception("不能推荐自己");
             }
-            
+
             // 检查是否会形成循环推荐
             if (self::wouldCreateCircularReferral($ursUserId, $ursReferrerId)) {
                 throw new \Exception("不能形成循环推荐关系");
             }
-            
+
             // 获取农场用户ID(如果已进入农场)
             $farmUserId = UrsUserMappingService::getFarmUserId($ursUserId);
             $referrerFarmUserId = UrsUserMappingService::getFarmUserId($ursReferrerId);
@@ -57,12 +58,12 @@ class UrsReferralService
                 'referral_time' => now(),
                 'status' => UrsUserReferral::STATUS_VALID,
             ]);
-            
+
             // 更新推荐人的团队统计
             self::updateReferrerStats($ursReferrerId);
-            
+
             DB::commit();
-            
+
             Log::info('URS推荐关系创建成功', [
                 'urs_user_id' => $ursUserId,
                 'urs_referrer_id' => $ursReferrerId,
@@ -70,7 +71,7 @@ class UrsReferralService
             ]);
 
             return UrsUserReferralDto::fromModel($referral);
-            
+
         } catch (\Exception $e) {
             DB::rollBack();
             Log::error('URS推荐关系创建失败', [
@@ -81,7 +82,7 @@ class UrsReferralService
             throw $e;
         }
     }
-    
+
     /**
      * 获取用户的推荐人
      *
@@ -135,7 +136,7 @@ class UrsReferralService
 
         return $chain;
     }
-    
+
     /**
      * 获取用户的团队成员(向下查找)
      *
@@ -188,6 +189,7 @@ class UrsReferralService
      */
     private static function updateReferrerStats(int $ursReferrerId): void
     {
+        $user_id = UrsUserMapping::getFarmUserIdByUrsUserId($ursReferrerId);
         $teamMembers = self::getTeamMembers($ursReferrerId);
 
         $directCount = count($teamMembers[1] ?? []);
@@ -196,7 +198,7 @@ class UrsReferralService
         $totalCount = $directCount + $indirectCount + $thirdCount;
 
         UrsUserTalent::updateOrCreate(
-            ['urs_user_id' => $ursReferrerId],
+            ['user_id' => $user_id],
             [
                 'direct_count' => $directCount,
                 'indirect_count' => $indirectCount,
@@ -205,7 +207,7 @@ class UrsReferralService
             ]
         );
     }
-    
+
     /**
      * 批量更新团队统计
      *

+ 3 - 1
app/Module/UrsPromotion/Services/UrsRewardDistributionService.php

@@ -165,7 +165,9 @@ class UrsRewardDistributionService
         float  $profitRate
     ): array
     {
-        $talent      = UrsUserTalent::where('user_id', $ursUserId)->first();
+        $framUserId = UrsUserMappingService::getFarmUserId($ursUserId);
+
+        $talent      = UrsUserTalent::where('user_id', $framUserId)->first();
         $talentLevel = $talent ? $talent->talent_level : 0;
 
         $profit = UrsProfit::create([