UpdateTalentLevelsCommand.php 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. <?php
  2. namespace App\Module\Promotion\Commands;
  3. use App\Module\Promotion\Logics\TalentLogic;
  4. use App\Module\Promotion\Models\PromotionUserTalent;
  5. use Illuminate\Console\Command;
  6. /**
  7. * 更新达人等级命令
  8. *
  9. * 用于更新所有用户的达人等级,确保等级数据的准确性。
  10. */
  11. class UpdateTalentLevelsCommand extends Command
  12. {
  13. /**
  14. * 命令名称
  15. *
  16. * @var string
  17. */
  18. protected $signature = 'promotion:update-talent-levels {--user-id= : 指定用户ID} {--debug-info : 显示详细信息}';
  19. /**
  20. * 命令描述
  21. *
  22. * @var string
  23. */
  24. protected $description = '更新用户达人等级';
  25. /**
  26. * 达人等级逻辑类
  27. *
  28. * @var TalentLogic
  29. */
  30. protected $talentLogic;
  31. /**
  32. * 创建命令实例
  33. *
  34. * @param TalentLogic $talentLogic 达人等级逻辑类
  35. * @return void
  36. */
  37. public function __construct(TalentLogic $talentLogic)
  38. {
  39. parent::__construct();
  40. $this->talentLogic = $talentLogic;
  41. }
  42. /**
  43. * 执行命令
  44. *
  45. * @return int
  46. */
  47. public function handle()
  48. {
  49. $this->info('开始更新达人等级...');
  50. $userId = $this->option('user-id');
  51. $showDebugInfo = $this->option('debug-info');
  52. try {
  53. if ($userId) {
  54. // 更新指定用户的达人等级
  55. $result = $this->talentLogic->checkAndUpdateTalentLevel($userId);
  56. if ($showDebugInfo) {
  57. if ($result) {
  58. $talent = PromotionUserTalent::where('user_id', $userId)->first();
  59. $this->info("用户 {$userId} 的达人等级更新为 {$talent->talent_level}");
  60. } else {
  61. $this->info("用户 {$userId} 的达人等级未变更");
  62. }
  63. } else {
  64. $this->info("更新完成");
  65. }
  66. } else {
  67. // 更新所有用户的达人等级
  68. $users = PromotionUserTalent::all();
  69. $total = $users->count();
  70. $updated = 0;
  71. if ($showDebugInfo) {
  72. $this->info("共有 {$total} 个用户需要更新达人等级");
  73. $bar = $this->output->createProgressBar($total);
  74. $bar->start();
  75. }
  76. foreach ($users as $user) {
  77. $result = $this->talentLogic->checkAndUpdateTalentLevel($user->user_id);
  78. if ($result) {
  79. $updated++;
  80. }
  81. if ($showDebugInfo) {
  82. $bar->advance();
  83. }
  84. }
  85. if ($showDebugInfo) {
  86. $bar->finish();
  87. $this->newLine();
  88. $this->info("共更新了 {$updated} 个用户的达人等级");
  89. } else {
  90. $this->info("更新完成");
  91. }
  92. }
  93. return 0;
  94. } catch (\Exception $e) {
  95. $this->error("更新达人等级失败: " . $e->getMessage());
  96. if ($showDebugInfo) {
  97. $this->error($e->getTraceAsString());
  98. }
  99. return 1;
  100. }
  101. }
  102. }