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