UserService.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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['recharge_channel_group_id'])) {
  84. $where[] = ['users.recharge_channel_group_id', '=', $search['recharge_channel_group_id']];
  85. }
  86. return $where;
  87. }
  88. /**
  89. * @description: 查询单条数据
  90. * @param array $search
  91. * @return \App\Models\User|null
  92. */
  93. public static function findOne(array $search): ?User
  94. {
  95. return static::$MODEL::where(self::getWhere($search))->first();
  96. }
  97. /**
  98. * @description: 查询所有数据
  99. * @param array $search
  100. * @return \Illuminate\Database\Eloquent\Collection
  101. */
  102. public static function findAll(array $search = [])
  103. {
  104. return static::$MODEL::where(self::getWhere($search))->get();
  105. }
  106. /**
  107. * @description: 分页查询
  108. * @param array $search
  109. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  110. */
  111. /** @var list<string> wallets 表排序字段(与 GET /admin/user 的 sort_field 一致) */
  112. private const PAGINATE_WALLET_SORT_FIELDS = [
  113. 'available_balance',
  114. 'frozen_balance',
  115. 'yuebao',
  116. 'wager_required',
  117. 'wager_completed',
  118. ];
  119. /** @var list<string> users 表排序字段 */
  120. private const PAGINATE_USER_SORT_FIELDS = [
  121. 'created_at',
  122. 'last_active_time',
  123. 'third_game_total_balance',
  124. ];
  125. public static function paginate(array $search = [], $sortOrder = 'desc', $sortField = 'created_at')
  126. {
  127. $limit = isset($search['limit']) ? $search['limit'] : 15;
  128. $page = isset($search['page']) ? $search['page'] : 1;
  129. $where = self::getWhere($search);
  130. $total = static::$MODEL::where($where)->count();
  131. $sortOrder = strtolower($sortOrder) === 'asc' ? 'asc' : 'desc';
  132. $query = static::$MODEL::with(['wallet', 'level', 'agent'])
  133. ->leftJoin('wallets', 'users.member_id', '=', 'wallets.member_id')
  134. ->where($where);
  135. self::applyPaginateSort($query, $sortField, $sortOrder);
  136. $list = $query->select('users.*')->forPage($page, $limit)->get();
  137. foreach ($list as &$item) {
  138. $item['total_consume'] = BalanceLog::getTotalConsume($item->member_id);//用户累计消费总额
  139. $item['third_game_total_balance'] = data_get($item, 'third_game_total_balance');
  140. // 当前周期打码量:wager_required 所需、wager_completed 当前打码量、wager_remaining 剩余打码量(提现后重置)
  141. foreach (WageringService::summary($item->wallet) as $key => $value) {
  142. $item[$key] = $value;
  143. }
  144. }
  145. return ['total' => $total, 'data' => $list];
  146. }
  147. private static function applyPaginateSort($query, string $sortField, string $sortOrder): void
  148. {
  149. if ($sortField === 'total_consume') {
  150. $query->leftJoinSub(self::totalConsumeSubquery(), 'user_total_consume', 'users.member_id', '=', 'user_total_consume.member_id')
  151. ->orderBy('user_total_consume.total_consume', $sortOrder);
  152. } elseif ($sortField === 'wager_remaining') {
  153. $direction = $sortOrder === 'asc' ? 'ASC' : 'DESC';
  154. $query->orderByRaw(
  155. "GREATEST(CAST(wallets.wager_required AS DECIMAL(20,4)) - CAST(wallets.wager_completed AS DECIMAL(20,4)), 0) {$direction}"
  156. );
  157. } elseif (in_array($sortField, self::PAGINATE_WALLET_SORT_FIELDS, true)) {
  158. $query->orderBy("wallets.{$sortField}", $sortOrder);
  159. } elseif (in_array($sortField, self::PAGINATE_USER_SORT_FIELDS, true)) {
  160. $query->orderBy('users.' . $sortField, $sortOrder);
  161. } else {
  162. $query->orderBy('users.created_at', $sortOrder);
  163. }
  164. $query->orderByDesc('users.created_at')->orderByDesc('users.id');
  165. }
  166. private static function totalConsumeSubquery()
  167. {
  168. return BalanceLog::query()
  169. ->select('member_id')
  170. ->groupBy('member_id')
  171. ->selectRaw(
  172. "GREATEST(ABS(COALESCE(SUM(CASE WHEN type = 1 AND change_type LIKE '%投注%' THEN amount ELSE 0 END), 0))"
  173. . " - COALESCE(SUM(CASE WHEN type = 1 AND change_type LIKE '%彩退款' THEN amount ELSE 0 END), 0), 0) AS total_consume"
  174. );
  175. }
  176. //设置游戏ID
  177. public function setGameID($chatId, $gameId)
  178. {
  179. $gameId = trim($gameId);
  180. if (!$gameId) return ['chat_id' => $chatId, 'text' => '❌游戏ID设置失败,请输入正确的游戏ID'];
  181. if (User::where('game_id', $gameId)->where('member_id', '<>', $chatId)->first()) {
  182. return ['chat_id' => $chatId, 'text' => '❌游戏ID设置失败,游戏ID已绑定其他用户'];
  183. }
  184. $user = User::where('member_id', $chatId)->first();
  185. $user->game_id = $gameId;
  186. $user->save();
  187. return ['chat_id' => $chatId, 'text' => "✅ 游戏ID设置成功\n游戏ID:{$gameId}"];
  188. }
  189. /**
  190. * @param Api $telegram
  191. * @param $data
  192. * @param $chatId
  193. * @param $firstName
  194. * @param $messageId
  195. * @return void
  196. * @throws TelegramSDKException
  197. */
  198. public static function init(Api $telegram, $data, $chatId, $firstName, $messageId): void
  199. {
  200. $pattern = "/^setLanguage@@.*$/";
  201. if (preg_match($pattern, $data)) {
  202. $language = preg_replace('/^setLanguage@@/', '', $data);
  203. $res = UserService::setLanguage($chatId, $language);
  204. $telegram->deleteMessage(['chat_id' => $chatId, 'message_id' => $messageId]);
  205. TelegramWebHook::setReplyKeyboard($chatId, $language);
  206. // $telegram->sendMessage($res);
  207. }
  208. }
  209. public static function getIsBanned($memberId)
  210. {
  211. $user = User::where('member_id', $memberId)->first();
  212. return $user->is_banned == 1;
  213. }
  214. public static function setLanguage($chatId, $language): array
  215. {
  216. $userInfo = self::findOne(['member_id' => $chatId]);
  217. $userInfo->setLanguage($language);
  218. $userInfo->save();
  219. App::setLocale($language);
  220. (new Home)->setMyCommands();
  221. return self::getLanguages($chatId);
  222. }
  223. public static function getLanguages($chatId): array
  224. {
  225. $keyboard = [
  226. [['text' => lang('en'), 'callback_data' => "setLanguage@@en"]],
  227. [['text' => lang('zh'), 'callback_data' => "setLanguage@@zh"]],
  228. [['text' => lang('vi'), 'callback_data' => "setLanguage@@vi"]],
  229. [['text' => lang('❌取消'), 'callback_data' => "message@@close"]],
  230. ];
  231. return [
  232. 'chat_id' => $chatId,
  233. 'text' => lang("请选择您的语言"),
  234. 'reply_markup' => json_encode(['inline_keyboard' => $keyboard]),
  235. 'protect_content' => true
  236. ];
  237. }
  238. }