UserService.php 12 KB

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