TeamLogic.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace App\Module\Farm\Logics;
  3. use App\Module\Farm\Models\FarmTeamProfit;
  4. use App\Module\Farm\Models\FarmUserReferral;
  5. use Illuminate\Support\Collection;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Log;
  8. use App\Module\Team\Services\TalentService;
  9. use App\Module\Team\Services\ReferralService;
  10. use UCore\Db\Helper;
  11. /**
  12. * 团队管理逻辑
  13. */
  14. class TeamLogic
  15. {
  16. /**
  17. * 添加推荐关系
  18. *
  19. * @param int $userId
  20. * @param int $referrerId
  21. * @return bool
  22. */
  23. public function addReferral(int $userId, int $referrerId): bool
  24. {
  25. try {
  26. Helper::check_tr();
  27. // 检查用户ID和推荐人ID是否相同
  28. if ($userId === $referrerId) {
  29. throw new \Exception('用户不能推荐自己');
  30. }
  31. // 检查是否已存在推荐关系
  32. $existingReferral = FarmUserReferral::where('user_id', $userId)
  33. ->where('referrer_id', $referrerId)
  34. ->first();
  35. if ($existingReferral) {
  36. return true; // 已存在推荐关系,直接返回成功
  37. }
  38. TalentService::checkAndUpdateUserTalentLevel($referrerId);
  39. Log::info('添加推荐关系成功', [
  40. 'user_id' => $userId,
  41. 'referrer_id' => $referrerId,
  42. 'indirect_referrer_id' => $indirectReferrerId ?? null
  43. ]);
  44. return true;
  45. } catch (\Exception $e) {
  46. Log::error('添加推荐关系失败', [
  47. 'user_id' => $userId,
  48. 'referrer_id' => $referrerId,
  49. 'error' => $e->getMessage(),
  50. 'trace' => $e->getTraceAsString()
  51. ]);
  52. return false;
  53. }
  54. }
  55. /**
  56. * 获取用户的团队收益记录
  57. *
  58. * @param int $userId
  59. * @param int $limit
  60. * @return Collection
  61. */
  62. public function getTeamProfits(int $userId, int $limit = 100): Collection
  63. {
  64. try {
  65. return FarmTeamProfit::where('user_id', $userId)
  66. ->orderByDesc('created_at')
  67. ->limit($limit)
  68. ->get();
  69. } catch (\Exception $e) {
  70. Log::error('获取用户团队收益记录失败', [
  71. 'user_id' => $userId,
  72. 'limit' => $limit,
  73. 'error' => $e->getMessage(),
  74. 'trace' => $e->getTraceAsString()
  75. ]);
  76. return collect();
  77. }
  78. }
  79. }