UserService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. namespace App\Services;
  3. use App\Http\Controllers\api\TelegramWebHook;
  4. use App\Services\BaseService;
  5. use App\Models\User;
  6. use App\Models\Agent\Agent;
  7. use App\Models\BalanceLog;
  8. use Illuminate\Support\Facades\App;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Cache;
  11. use Telegram\Bot\Api;
  12. use Telegram\Bot\Exceptions\TelegramSDKException;
  13. use App\Http\Controllers\api\Home;
  14. class UserService extends BaseService
  15. {
  16. public static string $MODEL = User::class;
  17. /**
  18. * @description: 模型
  19. * @return {string}
  20. */
  21. public static function model(): string
  22. {
  23. return User::class;
  24. }
  25. /**
  26. * @description: 枚举
  27. * @return {*}
  28. */
  29. public static function enum(): string
  30. {
  31. return '';
  32. }
  33. /**
  34. * @description: 获取查询条件
  35. * @param {array} $search 查询内容
  36. * @return {array}
  37. */
  38. public static function getWhere(array $search = []): array
  39. {
  40. $where = [];
  41. if (isset($search['id']) && !empty($search['id'])) {
  42. $where[] = ['users.id', '=', $search['id']];
  43. }
  44. if (isset($search['register_ip']) && !empty($search['register_ip'])) {
  45. $where[] = ['users.register_ip', '=', $search['register_ip']];
  46. }
  47. if (isset($search['member_id']) && !empty($search['member_id'])) {
  48. $where[] = ['users.member_id', '=', $search['member_id']];
  49. }
  50. if (isset($search['account']) && $search['account'] !== '') {
  51. $where[] = ['users.account', '=', $search['account']];
  52. }
  53. if (isset($search['first_name']) && !empty($search['first_name'])) {
  54. $where[] = ['users.first_name', '=', $search['first_name']];
  55. }
  56. if (isset($search['username']) && !empty($search['username'])) {
  57. $where[] = ['users.username', '=', $search['username']];
  58. }
  59. if (isset($search['like_first_name']) && !empty($search['like_first_name'])) {
  60. $where[] = ['users.first_name', 'like', "%" . $search['like_first_name'] . "%"];
  61. }
  62. if (isset($search['user_code']) && !empty($search['user_code'])) {
  63. $where[] = ['users.user_code', '=', $search['user_code']];
  64. }
  65. if (isset($search['agent_user_code']) && !empty($search['agent_user_code'])) {
  66. $where[] = ['users.agent_user_code', '=', $search['agent_user_code']];
  67. }
  68. if (isset($search['level']) && !empty($search['level'])) {
  69. $where[] = ['users.level', '=', $search['level']];
  70. }
  71. // 用户类型/注册来源:-1 tg用户,0 后台客服账号,1 真实用户,2 虚拟用户
  72. // 不能用 empty(),否则 from=0(后台客服)会被误判为空
  73. if (array_key_exists('from', $search) && $search['from'] !== null && $search['from'] !== '') {
  74. $where[] = ['users.from', '=', $search['from']];
  75. }
  76. if (!empty($search['start_time'])) {
  77. $startTime = $search['start_time'] . " 00:00:00";
  78. $where[] = ['users.created_at', '>=', $startTime];
  79. }
  80. if (!empty($search['end_time'])) {
  81. $endTime = $search['end_time'] . " 23:59:59";
  82. $where[] = ['users.created_at', '<=', $endTime];
  83. }
  84. if (!empty($search['agent_id'])) {
  85. $where[] = ['users.agent_id', '=', (int) $search['agent_id']];
  86. }
  87. if (!empty($search['recharge_channel_group_id'])) {
  88. $where[] = ['users.recharge_channel_group_id', '=', $search['recharge_channel_group_id']];
  89. }
  90. return $where;
  91. }
  92. /**
  93. * @description: 查询单条数据
  94. * @param array $search
  95. * @return \App\Models\User|null
  96. */
  97. public static function findOne(array $search): ?User
  98. {
  99. return static::$MODEL::where(self::getWhere($search))->first();
  100. }
  101. /**
  102. * @description: 查询所有数据
  103. * @param array $search
  104. * @return \Illuminate\Database\Eloquent\Collection
  105. */
  106. public static function findAll(array $search = [])
  107. {
  108. return static::$MODEL::where(self::getWhere($search))->get();
  109. }
  110. /**
  111. * @description: 分页查询
  112. * @param array $search
  113. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  114. */
  115. /** @var list<string> wallets 表排序字段(与 GET /admin/user 的 sort_field 一致) */
  116. private const PAGINATE_WALLET_SORT_FIELDS = [
  117. 'available_balance',
  118. 'frozen_balance',
  119. 'yuebao',
  120. 'wager_required',
  121. 'wager_completed',
  122. ];
  123. /** @var list<string> users 表排序字段 */
  124. private const PAGINATE_USER_SORT_FIELDS = [
  125. 'created_at',
  126. 'last_active_time',
  127. 'third_game_total_balance',
  128. ];
  129. public static function paginate(array $search = [], $sortOrder = 'desc', $sortField = 'created_at')
  130. {
  131. $limit = isset($search['limit']) ? $search['limit'] : 15;
  132. $page = isset($search['page']) ? $search['page'] : 1;
  133. $query = static::$MODEL::where(self::getWhere($search));
  134. \App\Support\MemberAudience::visibleUsers($query, 'users'); // 后台模拟会员只在模拟管理里出现
  135. [$onlineSql, $onlineBindings] = OnlineUserService::onlineStatusSql($query->getConnection()->getTablePrefix() . 'users');
  136. if (isset($search['is_online'])) {
  137. $query->whereRaw("{$onlineSql} = ?", [...$onlineBindings, (int) $search['is_online']]);
  138. }
  139. $total = $query->count();
  140. $sortOrder = strtolower($sortOrder) === 'asc' ? 'asc' : 'desc';
  141. // agent:邀请人(会员);systemAgent:所属的独立代理(合营 / 入股)
  142. $agentColumns = 'systemAgent:id,username,real_name,type' . (\App\Support\StatsScope::enabled() ? ',is_test' : '');
  143. $query->with(['wallet', 'level', 'agent', $agentColumns])
  144. ->leftJoin('wallets', 'users.member_id', '=', 'wallets.member_id')
  145. ->withCasts(['is_online' => 'boolean']);
  146. self::applyPaginateSort($query, $sortField, $sortOrder);
  147. $list = $query->select('users.*')->selectRaw("{$onlineSql} AS is_online", $onlineBindings)->forPage($page, $limit)->get();
  148. $parentIds = MemberSuperiorService::memberParentIds($list);
  149. $displayParentIds = array_unique(array_filter(array_values($parentIds), fn ($id) => $id !== null));
  150. $parents = $displayParentIds === [] ? collect() : User::query()->whereKey($displayParentIds)
  151. ->get(['id', 'user_code', 'account', 'first_name', 'member_id'])->keyBy('id');
  152. foreach ($list as &$item) {
  153. $item->real_name = $item->real_name ?? null;
  154. $item->makeVisible('real_name');
  155. $item['total_consume'] = BalanceLog::getTotalConsume($item->member_id);//用户累计消费总额
  156. $item['third_game_total_balance'] = data_get($item, 'third_game_total_balance');
  157. $parentId = $parentIds[$item->id] ?? null;
  158. $jointAgent = $item->systemAgent?->isJoint() ? $item->systemAgent : null;
  159. $item['superior'] = self::superior($jointAgent, $parents->get($parentId));
  160. $item['can_bind_superior'] = (int) $item->from !== 2 && $jointAgent === null && !array_key_exists($item->id, $parentIds);
  161. // 当前周期打码量:wager_required 所需、wager_completed 当前打码量、wager_remaining 剩余打码量(提现后重置)
  162. foreach (WageringService::summary($item->wallet) as $key => $value) {
  163. $item[$key] = $value;
  164. }
  165. }
  166. return ['total' => $total, 'data' => $list];
  167. }
  168. /**
  169. * 列表「上级」列只有两种:合营代理(绑定域名注册),或会员邀请人。都没有为 null。入股代理不发展会员。
  170. * type:agent 代理 / member 会员;label 直接展示,如「合营:agent01」「邀请人:member01(邀请码:ABC123)」。
  171. */
  172. private static function superior(?Agent $agent, ?User $inviter): ?array
  173. {
  174. if ($inviter) return self::memberSuperior($inviter);
  175. if ($agent) {
  176. return ['type' => 'agent', 'type_text' => '代理', 'id' => (int) $agent->id, 'account' => (string) $agent->username,
  177. 'label' => $agent->type_text . ':' . $agent->username . ((int) ($agent->is_test ?? 0) === 1 ? '(测试)' : ''),
  178. 'agent_type' => (int) $agent->type, 'agent_type_text' => (string) $agent->type_text, 'is_test' => (int) ($agent->is_test ?? 0)];
  179. }
  180. return null;
  181. }
  182. private static function memberSuperior(User $inviter): array
  183. {
  184. $account = (string) ($inviter->account ?: $inviter->first_name);
  185. $code = (string) $inviter->user_code;
  186. return ['type' => 'member', 'type_text' => '会员', 'id' => (int) $inviter->id, 'account' => $account,
  187. 'label' => '邀请人:' . $account . ($code !== '' ? '(邀请码:' . $code . ')' : ''),
  188. 'member_id' => (string) $inviter->member_id, 'invite_code' => $code];
  189. }
  190. private static function applyPaginateSort($query, string $sortField, string $sortOrder): void
  191. {
  192. if ($sortField === 'total_consume') {
  193. $query->leftJoinSub(self::totalConsumeSubquery(), 'user_total_consume', 'users.member_id', '=', 'user_total_consume.member_id')
  194. ->orderBy('user_total_consume.total_consume', $sortOrder);
  195. } elseif ($sortField === 'wager_remaining') {
  196. $direction = $sortOrder === 'asc' ? 'ASC' : 'DESC';
  197. $grammar = $query->getQuery()->getGrammar();
  198. $required = $grammar->wrap('wallets.wager_required');
  199. $completed = $grammar->wrap('wallets.wager_completed');
  200. $query->orderByRaw(
  201. "GREATEST(COALESCE({$required}, 0) - COALESCE({$completed}, 0), 0) {$direction}"
  202. );
  203. } elseif (in_array($sortField, self::PAGINATE_WALLET_SORT_FIELDS, true)) {
  204. $query->orderBy("wallets.{$sortField}", $sortOrder);
  205. } elseif (in_array($sortField, self::PAGINATE_USER_SORT_FIELDS, true)) {
  206. $query->orderBy('users.' . $sortField, $sortOrder);
  207. } else {
  208. $query->orderBy('users.created_at', $sortOrder);
  209. }
  210. $query->orderByDesc('users.created_at')->orderByDesc('users.id');
  211. }
  212. private static function totalConsumeSubquery()
  213. {
  214. return BalanceLog::query()
  215. ->select('member_id')
  216. ->groupBy('member_id')
  217. ->selectRaw(
  218. "GREATEST(ABS(COALESCE(SUM(CASE WHEN type = 1 AND change_type LIKE '%投注%' THEN amount ELSE 0 END), 0))"
  219. . " - COALESCE(SUM(CASE WHEN type = 1 AND change_type LIKE '%彩退款' THEN amount ELSE 0 END), 0), 0) AS total_consume"
  220. );
  221. }
  222. //设置游戏ID
  223. public function setGameID($chatId, $gameId)
  224. {
  225. $gameId = trim($gameId);
  226. if (!$gameId) return ['chat_id' => $chatId, 'text' => '❌游戏ID设置失败,请输入正确的游戏ID'];
  227. if (User::where('game_id', $gameId)->where('member_id', '<>', $chatId)->first()) {
  228. return ['chat_id' => $chatId, 'text' => '❌游戏ID设置失败,游戏ID已绑定其他用户'];
  229. }
  230. $user = User::where('member_id', $chatId)->first();
  231. $user->game_id = $gameId;
  232. $user->save();
  233. return ['chat_id' => $chatId, 'text' => "✅ 游戏ID设置成功\n游戏ID:{$gameId}"];
  234. }
  235. /**
  236. * @param Api $telegram
  237. * @param $data
  238. * @param $chatId
  239. * @param $firstName
  240. * @param $messageId
  241. * @return void
  242. * @throws TelegramSDKException
  243. */
  244. public static function init(Api $telegram, $data, $chatId, $firstName, $messageId): void
  245. {
  246. $pattern = "/^setLanguage@@.*$/";
  247. if (preg_match($pattern, $data)) {
  248. $language = preg_replace('/^setLanguage@@/', '', $data);
  249. $res = UserService::setLanguage($chatId, $language);
  250. $telegram->deleteMessage(['chat_id' => $chatId, 'message_id' => $messageId]);
  251. TelegramWebHook::setReplyKeyboard($chatId, $language);
  252. // $telegram->sendMessage($res);
  253. }
  254. }
  255. public static function getIsBanned($memberId)
  256. {
  257. $user = User::where('member_id', $memberId)->first();
  258. return $user->is_banned == 1;
  259. }
  260. public static function setLanguage($chatId, $language): array
  261. {
  262. $userInfo = self::findOne(['member_id' => $chatId]);
  263. $userInfo->setLanguage($language);
  264. $userInfo->save();
  265. App::setLocale($language);
  266. (new Home)->setMyCommands();
  267. return self::getLanguages($chatId);
  268. }
  269. public static function getLanguages($chatId): array
  270. {
  271. $keyboard = [
  272. [['text' => lang('en'), 'callback_data' => "setLanguage@@en"]],
  273. [['text' => lang('zh'), 'callback_data' => "setLanguage@@zh"]],
  274. [['text' => lang('vi'), 'callback_data' => "setLanguage@@vi"]],
  275. [['text' => lang('❌取消'), 'callback_data' => "message@@close"]],
  276. ];
  277. return [
  278. 'chat_id' => $chatId,
  279. 'text' => lang("请选择您的语言"),
  280. 'reply_markup' => json_encode(['inline_keyboard' => $keyboard]),
  281. 'protect_content' => true
  282. ];
  283. }
  284. }