InfoHandler.php 17 KB

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