InfoHandler.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. <?php
  2. namespace App\Module\AppGame\Handler\Promotion;
  3. use App\Module\AppGame\Handler\BaseHandler;
  4. use App\Module\UrsPromotion\Services\UrsUserMappingService;
  5. use App\Module\UrsPromotion\Services\UrsReferralService;
  6. use App\Module\UrsPromotion\Services\UrsTalentService;
  7. use App\Module\UrsPromotion\Models\UrsUserRelationCache;
  8. use App\Module\UrsPromotion\Models\UrsUserMapping;
  9. use App\Module\User\Services\UserActivityService;
  10. use App\Module\User\Models\UserInfo;
  11. use App\Module\Fund\Enums\FUND_TYPE;
  12. use App\Module\Game\Enums\REWARD_SOURCE_TYPE;
  13. use App\Module\Fund\Models\FundLogModel;
  14. use Google\Protobuf\Internal\Message;
  15. use Illuminate\Support\Facades\Log;
  16. use Uraus\Kku\Request\RequestPromotionInfo;
  17. use Uraus\Kku\Response\ResponsePromotionInfo;
  18. use Uraus\Kku\Common\Reward;
  19. use Uraus\Kku\Common\RewardCoin;
  20. use Uraus\Kku\Common\RewardItem;
  21. use Carbon\Carbon;
  22. /**
  23. * 处理推广团队信息请求
  24. *
  25. * 获取用户的推广团队统计信息,包括:
  26. * - 总人数、直推人数、间推人数
  27. * - 今日新增统计
  28. * - 团队活跃人数统计
  29. * - 达人等级信息
  30. */
  31. class InfoHandler extends BaseHandler
  32. {
  33. /**
  34. * 是否需要登录
  35. *
  36. * @var bool
  37. */
  38. protected bool $need_login = true;
  39. /**
  40. * 处理推广团队信息请求
  41. *
  42. * @param RequestPromotionInfo $data 推广团队信息请求数据
  43. * @return ResponsePromotionInfo 推广团队信息响应
  44. */
  45. public function handle(Message $data): Message
  46. {
  47. // 创建响应对象
  48. $response = new ResponsePromotionInfo();
  49. try {
  50. // 更新用户活动时间
  51. $this->updateUserActivityTime();
  52. // 获取当前农场用户对应的URS用户ID
  53. $ursUserId = UrsUserMappingService::getUrsUserId($this->user_id);
  54. if (!$ursUserId) {
  55. // 用户未进入URS推广系统,返回空数据
  56. Log::info('用户未进入URS推广系统', [
  57. 'user_id' => $this->user_id
  58. ]);
  59. return $this->setEmptyResponse($response);
  60. }
  61. // Log::debug('获取推广关系统计 start ', [
  62. // 'user_id' => $this->user_id
  63. // ]);
  64. // // 获取推广关系统计
  65. // $referralStats = UrsReferralService::getReferralStats($ursUserId);
  66. //// Log::debug('获取推广关系统计 end ', [
  67. //// 'user_id' => $this->user_id
  68. //// ]);
  69. $t = UrsTalentService::getTalentInfo($this->user_id);
  70. Log::debug('getTodayStats start ', [
  71. 'user_id' => $this->user_id
  72. ]);
  73. // 获取今日统计数据
  74. $todayStats = $this->getTodayStats($ursUserId);
  75. Log::debug('getActiveStats start ', [
  76. 'user_id' => $this->user_id
  77. ]);
  78. // 获取活跃用户统计
  79. $team_active_count = UrsReferralService::getTeamANumber($this->user_id);
  80. // 获取收益统计
  81. $rewardStats = $this->getRewardStats($ursUserId);
  82. // 获取达人等级信息
  83. $talentInfo = UrsTalentService::getTalentInfo($this->user_id);
  84. $starLevel = $talentInfo ? $talentInfo->talentLevel : 0;
  85. // 设置响应数据
  86. $response->setTotalCount($t->promotionCount);
  87. $response->setDirectCount($t->directCount);
  88. $response->setIndirectCount($t->indirectCount);
  89. $response->setDayRecentCount($todayStats['team_new_count'] ?? 0);
  90. $response->setDayDirectCount($todayStats['direct_new_count'] ?? 0);
  91. $response->setActiveCount($team_active_count);
  92. // $response->setDirectActiveCount($activeStats['direct_active_count'] ?? 0);
  93. $response->setStarLevel($starLevel);
  94. // 设置收益数据 - 始终设置奖励字段,没有数据时使用空奖励对象
  95. $todayReward = $rewardStats['today_reward'] ?? $this->createEmptyReward();
  96. $totalReward = $rewardStats['total_reward'] ?? $this->createEmptyReward();
  97. $response->setTodayReward($todayReward);
  98. $response->setTotalReward($totalReward);
  99. Log::info('推广团队信息获取成功', [
  100. 'user_id' => $this->user_id,
  101. 'urs_user_id' => $ursUserId,
  102. 'total_count' => $t->promotionCount,
  103. 'direct_count' => $t->directCount
  104. ]);
  105. } catch (\Exception $e) {
  106. Log::error('获取推广团队信息失败', [
  107. 'user_id' => $this->user_id,
  108. 'error' => $e->getMessage(),
  109. 'trace' => $e->getTraceAsString()
  110. ]);
  111. // 发生错误时返回空数据
  112. return $this->setEmptyResponse($response);
  113. }
  114. return $response;
  115. }
  116. /**
  117. * 设置空响应数据
  118. *
  119. * @param ResponsePromotionInfo $response
  120. * @return ResponsePromotionInfo
  121. */
  122. private function setEmptyResponse(ResponsePromotionInfo $response): ResponsePromotionInfo
  123. {
  124. $response->setTotalCount(0);
  125. $response->setDirectCount(0);
  126. $response->setIndirectCount(0);
  127. $response->setDayRecentCount(0);
  128. $response->setDayDirectCount(0);
  129. $response->setActiveCount(0);
  130. $response->setDirectActiveCount(0);
  131. $response->setStarLevel(0); // 设置达人等级为0
  132. // 设置空的奖励对象
  133. $emptyReward = $this->createEmptyReward();
  134. $response->setTodayReward($emptyReward);
  135. $response->setTotalReward($emptyReward);
  136. return $response;
  137. }
  138. /**
  139. * 创建空的奖励对象
  140. *
  141. * @return Reward
  142. */
  143. private function createEmptyReward(): Reward
  144. {
  145. $reward = new Reward();
  146. // 设置空的奖励列表
  147. $reward->setItems([]);
  148. $reward->setCoins([]);
  149. $reward->setGods([]);
  150. $reward->setLands([]);
  151. $reward->setPets([]);
  152. $reward->setPetPowers([]);
  153. $reward->setSkins([]);
  154. return $reward;
  155. }
  156. /**
  157. * 获取今日统计数据
  158. *
  159. * @param int $ursUserId URS用户ID
  160. * @return array
  161. */
  162. private function getTodayStats(int $ursUserId): array
  163. {
  164. try {
  165. // 获取当前用户的农场用户ID
  166. $farmUserId = UrsUserMappingService::getFarmUserId($ursUserId);
  167. if (!$farmUserId) {
  168. return [
  169. 'direct_new_count' => 0,
  170. 'team_new_count' => 0
  171. ];
  172. }
  173. // 使用 UrsUserRelationCache 关联 UrsUserMapping 查询今日新增的用户
  174. // 基于用户的 mapping_time(进入农场时间)而不是缓存的 created_at 时间
  175. $todayRelations = UrsUserRelationCache::where('related_user_id', $farmUserId)
  176. ->join('urs_promotion_user_mappings', 'kku_urs_promotion_user_relation_cache.urs_user_id', '=', 'urs_promotion_user_mappings.urs_user_id')
  177. ->where('urs_promotion_user_mappings.status', UrsUserMapping::STATUS_VALID)
  178. ->whereDate('urs_promotion_user_mappings.mapping_time', today())
  179. ->selectRaw('
  180. COUNT(CASE WHEN kku_urs_promotion_user_relation_cache.depth = 1 THEN 1 END) as direct_new_count,
  181. COUNT(CASE WHEN kku_urs_promotion_user_relation_cache.depth <= 3 THEN 1 END) as team_new_count
  182. ')
  183. ->first();
  184. $directNewCount = $todayRelations->direct_new_count ?? 0;
  185. $teamNewCount = $todayRelations->team_new_count ?? 0;
  186. return [
  187. 'direct_new_count' => (int)$directNewCount,
  188. 'team_new_count' => (int)$teamNewCount
  189. ];
  190. } catch (\Exception $e) {
  191. Log::error('获取今日统计数据失败', [
  192. 'urs_user_id' => $ursUserId,
  193. 'error' => $e->getMessage()
  194. ]);
  195. return [
  196. 'direct_new_count' => 0,
  197. 'team_new_count' => 0
  198. ];
  199. }
  200. }
  201. /**
  202. * 获取活跃用户统计
  203. *
  204. * @param int $ursUserId URS用户ID
  205. * @return array
  206. */
  207. private function getActiveStats(int $ursUserId): array
  208. {
  209. try {
  210. // 获取当前用户的农场用户ID
  211. $farmUserId = UrsUserMappingService::getFarmUserId($ursUserId);
  212. if (!$farmUserId) {
  213. return [
  214. 'direct_active_count' => 0,
  215. 'team_active_count' => 0
  216. ];
  217. }
  218. $activeThreshold = Carbon::now()->subHours(24); // 24小时内活跃
  219. // 使用 UrsUserRelationCache 和 UserInfo 进行 JOIN 查询
  220. // 一次性获取所有团队成员的活跃状态
  221. $activeStats = UrsUserRelationCache::where('related_user_id', $farmUserId)
  222. ->where('depth', '<=', 3) // 只统计前3级
  223. ->join('kku_user_infos', 'kku_urs_promotion_user_relation_cache.user_id', '=', 'kku_user_infos.user_id')
  224. ->where('kku_user_infos.last_activity_time', '>=', $activeThreshold)
  225. ->selectRaw('
  226. COUNT(CASE WHEN depth = 1 THEN 1 END) as direct_active_count,
  227. COUNT(*) as team_active_count
  228. ')
  229. ->first();
  230. $directActiveCount = $activeStats->direct_active_count ?? 0;
  231. $teamActiveCount = $activeStats->team_active_count ?? 0;
  232. return [
  233. 'direct_active_count' => (int)$directActiveCount,
  234. 'team_active_count' => (int)$teamActiveCount
  235. ];
  236. } catch (\Exception $e) {
  237. Log::error('获取活跃用户统计失败', [
  238. 'urs_user_id' => $ursUserId,
  239. 'error' => $e->getMessage()
  240. ]);
  241. return [
  242. 'direct_active_count' => 0,
  243. 'team_active_count' => 0
  244. ];
  245. }
  246. }
  247. /**
  248. * 获取收益统计
  249. *
  250. * @param int $ursUserId URS用户ID
  251. * @return array
  252. */
  253. private function getRewardStats(int $ursUserId): array
  254. {
  255. try {
  256. // 获取对应的农场用户ID
  257. $farmUserId = UrsUserMappingService::getFarmUserId($ursUserId);
  258. if (!$farmUserId) {
  259. Log::info('URS用户未映射到农场用户', [ 'urs_user_id' => $ursUserId ]);
  260. return [
  261. 'today_reward' => null,
  262. 'total_reward' => null
  263. ];
  264. }
  265. // 获取今日收益统计
  266. $today = Carbon::today()->format('Y-m-d');
  267. $tomorrow = Carbon::tomorrow()->format('Y-m-d');
  268. $todayStats = $this->getRewardStatsFromLogs($farmUserId, $today, $tomorrow);
  269. // 获取总收益统计
  270. $totalStats = $this->getRewardStatsFromLogs($farmUserId);
  271. // 构建今日收益Reward对象
  272. $todayReward = null;
  273. if ($todayStats['total_count'] > 0) {
  274. $todayReward = $this->buildRewardFromStats($todayStats);
  275. }
  276. // 构建总收益Reward对象
  277. $totalReward = null;
  278. if ($totalStats['total_count'] > 0) {
  279. $totalReward = $this->buildRewardFromStats($totalStats);
  280. }
  281. return [
  282. 'today_reward' => $todayReward,
  283. 'total_reward' => $totalReward
  284. ];
  285. } catch (\Exception $e) {
  286. Log::error('获取收益统计失败', [
  287. 'urs_user_id' => $ursUserId,
  288. 'error' => $e->getMessage()
  289. ]);
  290. return [
  291. 'today_reward' => null,
  292. 'total_reward' => null
  293. ];
  294. }
  295. }
  296. /**
  297. * 从物品模块和资金模块的日志中获取收益统计
  298. *
  299. * @param int $farmUserId 农场用户ID
  300. * @param string|null $startDate 开始日期
  301. * @param string|null $endDate 结束日期
  302. * @return array
  303. */
  304. private function getRewardStatsFromLogs(int $farmUserId, ?string $startDate = null, ?string $endDate = null): array
  305. {
  306. $stats = [
  307. 'total_amount' => 0,
  308. 'total_count' => 0,
  309. 'items' => [], // 物品奖励列表
  310. 'coins' => [], // 代币奖励列表
  311. 'by_source_type' => []
  312. ];
  313. try {
  314. // URS推广相关的收益来源类型
  315. $ursPromotionSourceTypes = [
  316. REWARD_SOURCE_TYPE::URSPROMOTION_HAVEST->value,
  317. REWARD_SOURCE_TYPE::URSPROMOTION_BACKFILL->value,
  318. REWARD_SOURCE_TYPE::URSPROMOTION_REWARD->value,
  319. REWARD_SOURCE_TYPE::URSPROMOTION_REGISTER->value,
  320. REWARD_SOURCE_TYPE::URSPROMOTION_LEVEL->value,
  321. ];
  322. // 1.1. 从物品交易日志表中统计URS推广奖励(补充查询)
  323. $itemQuery = \App\Module\GameItems\Models\ItemTransactionLog::where('user_id', $farmUserId)
  324. ->where('transaction_type', 1) // 收入类型
  325. ->whereIn('source_type', $ursPromotionSourceTypes);
  326. if ($startDate) {
  327. $itemQuery->where('created_at', '>=', $startDate);
  328. }
  329. if ($endDate) {
  330. $itemQuery->where('created_at', '<=', $endDate);
  331. }
  332. $itemLogs = $itemQuery->get();
  333. foreach ($itemLogs as $log) {
  334. $stats['total_count']++;
  335. $itemId = $log->item_id;
  336. $quantity = $log->quantity;
  337. if ($itemId > 0) {
  338. // 累加相同物品的数量
  339. if (isset($stats['items'][$itemId])) {
  340. $stats['items'][$itemId] += $quantity;
  341. } else {
  342. $stats['items'][$itemId] = $quantity;
  343. }
  344. }
  345. // 按来源类型统计
  346. $sourceType = $log->source_type;
  347. if (!isset($stats['by_source_type'][$sourceType])) {
  348. $stats['by_source_type'][$sourceType] = [ 'amount' => 0, 'count' => 0 ];
  349. }
  350. $stats['by_source_type'][$sourceType]['count']++;
  351. }
  352. // 2. 从资金日志表中统计钻石奖励
  353. $fundQuery = FundLogModel::where('user_id', $farmUserId)
  354. ->where('fund_id', FUND_TYPE::FUND2->value) // 钻石类型
  355. ->where('amount', '>', 0) // 只统计收入
  356. ->where('remark', 'like', '%推广%'); // 包含推广关键词的备注
  357. if ($startDate) {
  358. $fundQuery->where('create_time', '>=', strtotime($startDate));
  359. }
  360. if ($endDate) {
  361. $fundQuery->where('create_time', '<=', strtotime($endDate));
  362. }
  363. $fundLogs = $fundQuery->get();
  364. foreach ($fundLogs as $log) {
  365. $stats['total_count']++;
  366. $amount = (float)$log->amount;
  367. // 累加钻石数量
  368. $fundType = FUND_TYPE::FUND2->value;
  369. if (isset($stats['coins'][$fundType])) {
  370. $stats['coins'][$fundType] += $amount;
  371. } else {
  372. $stats['coins'][$fundType] = $amount;
  373. }
  374. $stats['total_amount'] += $amount;
  375. // 按备注内容推断来源类型
  376. $sourceType = $this->inferSourceTypeFromRemark($log->remark);
  377. if (!isset($stats['by_source_type'][$sourceType])) {
  378. $stats['by_source_type'][$sourceType] = [ 'amount' => 0, 'count' => 0 ];
  379. }
  380. $stats['by_source_type'][$sourceType]['amount'] += $amount;
  381. $stats['by_source_type'][$sourceType]['count']++;
  382. }
  383. } catch (\Exception $e) {
  384. Log::error('从日志获取收益统计失败', [
  385. 'farm_user_id' => $farmUserId,
  386. 'start_date' => $startDate,
  387. 'end_date' => $endDate,
  388. 'error' => $e->getMessage()
  389. ]);
  390. }
  391. return $stats;
  392. }
  393. /**
  394. * 从备注推断收益来源类型
  395. *
  396. * @param string $remark 备注内容
  397. * @return string
  398. */
  399. private function inferSourceTypeFromRemark(string $remark): string
  400. {
  401. if (strpos($remark, '收获') !== false) {
  402. return REWARD_SOURCE_TYPE::URSPROMOTION_HAVEST->value;
  403. }
  404. if (strpos($remark, '补发') !== false) {
  405. return REWARD_SOURCE_TYPE::URSPROMOTION_BACKFILL->value;
  406. }
  407. if (strpos($remark, '注册') !== false) {
  408. return REWARD_SOURCE_TYPE::URSPROMOTION_REGISTER->value;
  409. }
  410. if (strpos($remark, '等级') !== false) {
  411. return REWARD_SOURCE_TYPE::URSPROMOTION_LEVEL->value;
  412. }
  413. return REWARD_SOURCE_TYPE::URSPROMOTION_REWARD->value; // 默认推广奖励
  414. }
  415. /**
  416. * 从统计数据构建Reward对象
  417. *
  418. * @param array $stats 统计数据
  419. * @return Reward
  420. */
  421. private function buildRewardFromStats(array $stats): Reward
  422. {
  423. $reward = new Reward();
  424. // 创建物品奖励列表
  425. $items = [];
  426. if (!empty($stats['items'])) {
  427. foreach ($stats['items'] as $itemId => $quantity) {
  428. $rewardItem = new RewardItem();
  429. $rewardItem->setItemId($itemId);
  430. $rewardItem->setInstanceId(0); // 默认为0,表示不指定实例
  431. $rewardItem->setQuantity($quantity);
  432. $items[] = $rewardItem;
  433. }
  434. }
  435. // 创建代币奖励列表
  436. $coins = [];
  437. if (!empty($stats['coins'])) {
  438. foreach ($stats['coins'] as $fundType => $amount) {
  439. $rewardCoin = new RewardCoin();
  440. $rewardCoin->setType($fundType);
  441. $rewardCoin->setQuantity((float)$amount);
  442. $coins[] = $rewardCoin;
  443. }
  444. }
  445. $reward->setItems($items);
  446. $reward->setCoins($coins);
  447. // 其他奖励类型暂时为空
  448. $reward->setGods([]);
  449. $reward->setLands([]);
  450. $reward->setPets([]);
  451. $reward->setPetPowers([]);
  452. $reward->setSkins([]);
  453. return $reward;
  454. }
  455. }