UserService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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」「邀请人:member01」;入股代理不显示。
  164. */
  165. public static function superior($user): ?array
  166. {
  167. // 只显示合营代理;入股代理是平台股东(按利润分成),名下会员不显示为它的下级
  168. $agent = $user->relationLoaded('systemAgent') ? $user->systemAgent : null;
  169. if ($agent && (int) $agent->type !== \App\Models\Agent\Agent::TYPE_EQUITY) {
  170. return ['type' => 'agent', 'type_text' => '代理', 'id' => (int) $agent->id, 'account' => (string) $agent->username,
  171. 'label' => $agent->type_text . ':' . $agent->username . ((int) ($agent->is_test ?? 0) === 1 ? '(测试)' : ''),
  172. 'agent_type' => (int) $agent->type, 'agent_type_text' => (string) $agent->type_text, 'is_test' => (int) ($agent->is_test ?? 0)];
  173. }
  174. $inviter = $user->relationLoaded('agent') ? $user->agent : null;
  175. if ($inviter) {
  176. $account = (string) ($inviter->account ?: $inviter->first_name);
  177. return ['type' => 'member', 'type_text' => '会员', 'id' => (int) $inviter->id, 'account' => $account, 'label' => '邀请人:' . $account,
  178. 'member_id' => (string) $inviter->member_id];
  179. }
  180. return null;
  181. }
  182. private static function applyPaginateSort($query, string $sortField, string $sortOrder): void
  183. {
  184. if ($sortField === 'total_consume') {
  185. $query->leftJoinSub(self::totalConsumeSubquery(), 'user_total_consume', 'users.member_id', '=', 'user_total_consume.member_id')
  186. ->orderBy('user_total_consume.total_consume', $sortOrder);
  187. } elseif ($sortField === 'wager_remaining') {
  188. $direction = $sortOrder === 'asc' ? 'ASC' : 'DESC';
  189. $grammar = $query->getQuery()->getGrammar();
  190. $required = $grammar->wrap('wallets.wager_required');
  191. $completed = $grammar->wrap('wallets.wager_completed');
  192. $query->orderByRaw(
  193. "GREATEST(COALESCE({$required}, 0) - COALESCE({$completed}, 0), 0) {$direction}"
  194. );
  195. } elseif (in_array($sortField, self::PAGINATE_WALLET_SORT_FIELDS, true)) {
  196. $query->orderBy("wallets.{$sortField}", $sortOrder);
  197. } elseif (in_array($sortField, self::PAGINATE_USER_SORT_FIELDS, true)) {
  198. $query->orderBy('users.' . $sortField, $sortOrder);
  199. } else {
  200. $query->orderBy('users.created_at', $sortOrder);
  201. }
  202. $query->orderByDesc('users.created_at')->orderByDesc('users.id');
  203. }
  204. private static function totalConsumeSubquery()
  205. {
  206. return BalanceLog::query()
  207. ->select('member_id')
  208. ->groupBy('member_id')
  209. ->selectRaw(
  210. "GREATEST(ABS(COALESCE(SUM(CASE WHEN type = 1 AND change_type LIKE '%投注%' THEN amount ELSE 0 END), 0))"
  211. . " - COALESCE(SUM(CASE WHEN type = 1 AND change_type LIKE '%彩退款' THEN amount ELSE 0 END), 0), 0) AS total_consume"
  212. );
  213. }
  214. //设置游戏ID
  215. public function setGameID($chatId, $gameId)
  216. {
  217. $gameId = trim($gameId);
  218. if (!$gameId) return ['chat_id' => $chatId, 'text' => '❌游戏ID设置失败,请输入正确的游戏ID'];
  219. if (User::where('game_id', $gameId)->where('member_id', '<>', $chatId)->first()) {
  220. return ['chat_id' => $chatId, 'text' => '❌游戏ID设置失败,游戏ID已绑定其他用户'];
  221. }
  222. $user = User::where('member_id', $chatId)->first();
  223. $user->game_id = $gameId;
  224. $user->save();
  225. return ['chat_id' => $chatId, 'text' => "✅ 游戏ID设置成功\n游戏ID:{$gameId}"];
  226. }
  227. /**
  228. * @param Api $telegram
  229. * @param $data
  230. * @param $chatId
  231. * @param $firstName
  232. * @param $messageId
  233. * @return void
  234. * @throws TelegramSDKException
  235. */
  236. public static function init(Api $telegram, $data, $chatId, $firstName, $messageId): void
  237. {
  238. $pattern = "/^setLanguage@@.*$/";
  239. if (preg_match($pattern, $data)) {
  240. $language = preg_replace('/^setLanguage@@/', '', $data);
  241. $res = UserService::setLanguage($chatId, $language);
  242. $telegram->deleteMessage(['chat_id' => $chatId, 'message_id' => $messageId]);
  243. TelegramWebHook::setReplyKeyboard($chatId, $language);
  244. // $telegram->sendMessage($res);
  245. }
  246. }
  247. public static function getIsBanned($memberId)
  248. {
  249. $user = User::where('member_id', $memberId)->first();
  250. return $user->is_banned == 1;
  251. }
  252. public static function setLanguage($chatId, $language): array
  253. {
  254. $userInfo = self::findOne(['member_id' => $chatId]);
  255. $userInfo->setLanguage($language);
  256. $userInfo->save();
  257. App::setLocale($language);
  258. (new Home)->setMyCommands();
  259. return self::getLanguages($chatId);
  260. }
  261. public static function getLanguages($chatId): array
  262. {
  263. $keyboard = [
  264. [['text' => lang('en'), 'callback_data' => "setLanguage@@en"]],
  265. [['text' => lang('zh'), 'callback_data' => "setLanguage@@zh"]],
  266. [['text' => lang('vi'), 'callback_data' => "setLanguage@@vi"]],
  267. [['text' => lang('❌取消'), 'callback_data' => "message@@close"]],
  268. ];
  269. return [
  270. 'chat_id' => $chatId,
  271. 'text' => lang("请选择您的语言"),
  272. 'reply_markup' => json_encode(['inline_keyboard' => $keyboard]),
  273. 'protect_content' => true
  274. ];
  275. }
  276. }