InfoHandler.php 18 KB

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