BetService.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  1. <?php
  2. namespace App\Services;
  3. use App\Support\MemberAudience;
  4. use App\Constants\StepStatus;
  5. use App\Constants\Util;
  6. use App\Models\Message;
  7. use App\Models\PcIssue;
  8. use App\Models\User;
  9. use App\Models\LhcOrder;
  10. use App\Models\Config;
  11. use App\Models\LhcOrderItem;
  12. use Illuminate\Support\Facades\App;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Cache;
  15. use App\Jobs\SendTelegramMessageJob;
  16. use App\Jobs\SendTelegramGroupMessageJob;
  17. use Exception;
  18. use Illuminate\Support\Facades\Log;
  19. use Telegram\Bot\Api;
  20. use Telegram\Bot\Exceptions\TelegramSDKException;
  21. use App\Services\ActivityRewardService;
  22. use App\Services\AdminRealtime\AdminRealtime;
  23. /**
  24. * 投注
  25. */
  26. class BetService extends BaseService
  27. {
  28. /**
  29. * @param Api $telegram
  30. * @param $data
  31. * @param $chatId
  32. * @param $firstName
  33. * @param $messageId
  34. * @param $callbackId
  35. * @return void
  36. * @throws TelegramSDKException
  37. */
  38. public static function init(Api $telegram, $data, $chatId, $firstName, $messageId, $callbackId): void
  39. {
  40. switch ($data) {
  41. case "todayExchangeRate@@rate": // 今日汇率
  42. BetService::todayExchangeRate($chatId);
  43. break;
  44. case "betsAlert":// 近期注单弹窗
  45. Cache::put('message_id_bet_record_' . $chatId, 0, 600);
  46. $alertText = BetService::recentlyRecord($chatId);
  47. BetService::alertNotice($callbackId, $alertText);
  48. break;
  49. case "promotionalActivityAlert":
  50. // 删除个人缓存
  51. Util::delCache($chatId);
  52. $returnMsg = ActivityRewardService::promotionalActivity($chatId);
  53. $telegram->sendMessage($returnMsg);
  54. break;
  55. default:
  56. //选择投注记录
  57. $pattern = "/^betRecordType@@\d+$/";
  58. if (preg_match($pattern, $data)) {
  59. $type = preg_replace('/^betRecordType@@/', '', $data);
  60. Cache::put('message_id_bet_record_' . $chatId, intval($type), 600);
  61. $telegram->deleteMessage([
  62. 'chat_id' => $chatId,
  63. 'message_id' => $messageId,
  64. ]);
  65. $returnMsg = BetService::record($chatId);
  66. $telegram->sendMessage($returnMsg);
  67. }
  68. //近期注单,下一页
  69. $pattern = "/^betRecordNextPage@@\d+$/";
  70. if (preg_match($pattern, $data)) {
  71. $page = preg_replace('/^betRecordNextPage@@/', '', $data);
  72. $page = intval($page);
  73. $res = BetService::record($chatId, $messageId, $page);
  74. $telegram->editMessageText($res);
  75. }
  76. break;
  77. }
  78. }
  79. public static function onMessage($chatId, $text, $messageId, $stepStatus): ?array
  80. {
  81. switch ($stepStatus) {
  82. default:
  83. $res = null;
  84. break;
  85. }
  86. return $res;
  87. }
  88. public static $OTHER_BET_1 = [
  89. '大',
  90. '小',
  91. '单',
  92. '双',
  93. ];
  94. public static $OTHER_BET_2 = [
  95. '大单',
  96. '大双',
  97. '小单',
  98. '小双',
  99. ];
  100. /**
  101. * @description: 模型
  102. * @return {string}
  103. */
  104. public static function model(): string
  105. {
  106. return LhcOrder::class;
  107. }
  108. /**
  109. * @description: 枚举
  110. * @return {*}
  111. */
  112. public static function enum(): string
  113. {
  114. return '';
  115. }
  116. public static function getWhere(array $search = []): array
  117. {
  118. $where = [];
  119. if (isset($search['issue_no']) && !empty($search['issue_no'])) {
  120. $where[] = ['issue', '=', $search['issue_no']];
  121. }
  122. if (isset($search['issue']) && !empty($search['issue'])) {
  123. $where[] = ['issue', '=', $search['issue']];
  124. }
  125. if (isset($search['member_id']) && !empty($search['member_id'])) {
  126. $where[] = ['member_id', '=', $search['member_id']];
  127. }
  128. if (isset($search['keywords']) && !empty($search['keywords'])) {
  129. $where[] = ['number', '=', $search['keywords']];
  130. }
  131. if (isset($search['number']) && !empty($search['number'])) {
  132. $where[] = ['number', '=', $search['number']];
  133. }
  134. if (isset($search['issue_id']) && !empty($search['issue_id'])) {
  135. $where[] = ['lhc_number_id', '=', $search['issue_id']];
  136. }
  137. if (isset($search['id']) && !empty($search['id'])) {
  138. $where[] = ['id', '=', $search['id']];
  139. }
  140. if (isset($search['user_id']) && !empty($search['user_id'])) {
  141. $where[] = ['user_id', '=', $search['user_id']];
  142. }
  143. if (isset($search['start_time']) && !empty($search['start_time'])) {
  144. $where[] = ['created_at', '>=', "{$search['start_time']} 00:00:00"];
  145. $where[] = ['created_at', '<=', "{$search['end_time']} 23:59:59"];
  146. }
  147. if (isset($search['is_winner']) && $search['is_winner'] != '') {
  148. $where[] = ['lottery_status', '=', 2];
  149. if ($search['is_winner'] == 1) {
  150. $where[] = ['profit_and_loss', '>', 0];
  151. } else {
  152. $where[] = ['profit_and_loss', '<=', 0];
  153. }
  154. } else {
  155. if (isset($search['status']) && $search['status'] != '') {
  156. $where[] = ['lottery_status', '=', $search['status']];
  157. }
  158. }
  159. if (isset($search['lottery_status']) && $search['lottery_status'] !== '') {
  160. $where[] = ['lottery_status', '=', $search['lottery_status']];
  161. }
  162. $where[] = ['type', '>=', 5];
  163. $where[] = ['type', '<=', 6];
  164. return $where;
  165. }
  166. /**
  167. * @description: 查询单条数据
  168. * @param array $search
  169. * @return \App\Models\Coin|null
  170. */
  171. public static function findOne(array $search): ?LhcOrder
  172. {
  173. return self::model()::where(self::getWhere($search))->first();
  174. }
  175. /**
  176. * @description: 查询所有数据
  177. * @param array $search
  178. * @return \Illuminate\Database\Eloquent\Collection
  179. */
  180. public static function findAll(array $search = [])
  181. {
  182. return self::model()::where(self::getWhere($search))->get();
  183. }
  184. /**
  185. * @description: 分页查询
  186. * @param array $search
  187. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  188. */
  189. public static function paginate(array $search = [])
  190. {
  191. $limit = isset($search['limit']) ? $search['limit'] : 15;
  192. $query = self::model()::where(self::getWhere($search))
  193. ->with(['user']);
  194. if (isset($search['username']) && !empty($search['username'])) {
  195. $username = $search['username'];
  196. $query = $query->whereHas('user', function ($query) use ($username) {
  197. $query->where('username', $username);
  198. });
  199. }
  200. $query->orderBy('id', 'desc');
  201. $paginator = $query->paginate($limit);
  202. return ['total' => $paginator->total(), 'data' => $paginator->items()];
  203. }
  204. /**
  205. * @description: 投注操作
  206. * @param string $memberId
  207. * @param string $input
  208. * @param int $messageId
  209. * @return array
  210. */
  211. public static function bet(string $memberId, string $input, int $messageId = 0): array
  212. {
  213. $msg = [];
  214. $msg['chat_id'] = $memberId;
  215. // 分解投注的内容
  216. $betResult = GameplayRuleService::bettingRuleVerify($input);
  217. $serviceAccount = Config::where('field', 'service_customer')->first()->val;
  218. $maintenanceSwitch = Config::where('field', 'maintenance_switch')->first()->val;
  219. if ($maintenanceSwitch != 0) {
  220. $text = lang("系统维护中") . "\n";
  221. $text .= lang("任何疑问都可以联系唯一客服") . ":@{$serviceAccount}";
  222. $msg['text'] = $text;
  223. if ($messageId) {
  224. $msg['reply_to_message_id'] = $messageId;
  225. }
  226. return $msg;
  227. }
  228. // 后台「整站与游戏维护」:整站、F1彩票大类或当前28彩种(加拿大28/极速28)维护时不接单
  229. $maintenance = (new MaintenanceService())->telegramPc28Failure(User::where('member_id', $memberId)->value('language'));
  230. if ($maintenance !== null) {
  231. $msg['text'] = $maintenance['msg'] . "\n" . lang("任何疑问都可以联系唯一客服") . ":@{$serviceAccount}";
  232. if ($messageId) {
  233. $msg['reply_to_message_id'] = $messageId;
  234. }
  235. return $msg;
  236. }
  237. //是否封号
  238. $isBanned = UserService::getIsBanned($memberId);
  239. if ($isBanned) {
  240. $text = lang("账号异常") . "\n";
  241. $text .= lang("任何疑问都可以联系唯一客服") . ":@{$serviceAccount}";
  242. $msg['text'] = $text;
  243. if ($messageId) {
  244. $msg['reply_to_message_id'] = $messageId;
  245. }
  246. return $msg;
  247. }
  248. if ($betResult == null) {
  249. $text = lang("消息格式错误!") . "\n";
  250. $text .= lang("任何疑问都可以联系唯一客服") . ":@{$serviceAccount}";
  251. $msg['text'] = $text;
  252. if ($messageId) {
  253. $msg['reply_to_message_id'] = $messageId;
  254. }
  255. return $msg;
  256. }
  257. DB::beginTransaction();
  258. try {
  259. $pc28Switch = (int) Config::where('field', 'pc28_switch')->value('val');
  260. $template = LotteryOdds::template($pc28Switch === 1 ? 'jisu28' : 'canada28');
  261. $text = lang('下注期数') . ":{issue_no}\n";
  262. $text .= lang("下注内容") . "\n";
  263. $text .= "--------\n";
  264. $success = false;
  265. $sumAmount = 0;
  266. $errText = $groupText = "";
  267. foreach ($betResult as $index => $item) {
  268. $keywords = $item['rule'];
  269. $amount = $item['amount'];
  270. $error = $issueNo = "";
  271. $b = static::singleNote($memberId, $keywords, $amount, $issueNo, $text, $error, $groupText, $index, $pc28Switch, $template);
  272. if ($b) {
  273. $sumAmount += $amount;
  274. $text = str_replace("{issue_no}", $issueNo, $text);
  275. $success = true;
  276. $text .= "\n";
  277. } else {
  278. $errText .= $error;
  279. $errText .= "\n";
  280. }
  281. }
  282. if (!$success) {
  283. $msg['text'] = $errText;
  284. if ($messageId) {
  285. $msg['reply_to_message_id'] = $messageId;
  286. }
  287. } else {
  288. $sumAmount = number_format($sumAmount, 2);
  289. $text .= "--------\n";
  290. $text .= lang("合计金额") . ":{$sumAmount}\n";
  291. $text .= lang("下注成功");
  292. $msg['text'] = $text;
  293. $msg['text'] .= "\n";
  294. if (!empty($errText)) {
  295. $msg['text'] .= "------------------------\n";
  296. $msg['text'] .= $errText;
  297. }
  298. $groupText .= "\n--------\n";
  299. self::asyncBettingGroupNotice($groupText, self::getOperateButton()); // 异步群通知
  300. }
  301. DB::commit();
  302. } catch (Exception $e) {
  303. DB::rollBack();
  304. Log::error('错误信息', [
  305. 'message' => $e->getMessage(),
  306. 'file' => $e->getFile(),
  307. 'line' => $e->getLine(),
  308. 'trace' => $e->getTraceAsString()
  309. ]);
  310. $msg['text'] = "投注失败,请联系管理员";
  311. if ($messageId) {
  312. $msg['reply_to_message_id'] = $messageId;
  313. }
  314. }
  315. return $msg;
  316. }
  317. private static function singleNote($memberId, $keywords, $amount, &$issueNo, &$text, &$errText, &$groupText, $index, int $pc28Switch, object $template): bool
  318. {
  319. $errText .= "【{$keywords}{$amount}】\n";
  320. //客服号
  321. $serviceAccount = Config::where('field', 'service_customer')->first()->val;
  322. $price = LotteryOdds::pc28Price($template, $keywords);
  323. if ($price === null) {
  324. $errText .= lang("玩法未配置!") . "\n";
  325. $errText .= lang("任何疑问都可以联系唯一财务") . ":@{$serviceAccount}";
  326. return false;
  327. }
  328. $gameplayRuleInfo = (array) $price;
  329. if ($gameplayRuleInfo['odds'] <= 0) {
  330. $errText .= lang("赔率为0 庄家通吃 禁止投注!") . "\n";
  331. $errText .= lang("任何疑问都可以联系唯一财务") . ":@{$serviceAccount}";
  332. return false;
  333. }
  334. // 期数验证
  335. if ($pc28Switch == 1) {
  336. $issueInfo = PcIssue::where('status', PcIssue::STATUS_BETTING)->orderBy('id', 'desc')->first();
  337. } else {
  338. $issueInfo = IssueService::model()::where('status', IssueService::model()::STATUS_BETTING)->orderBy('id', 'desc')->first();
  339. }
  340. if (empty($issueInfo)) {
  341. if ($pc28Switch == 1) {
  342. $issueCloseInfo = PcIssue::where('status', PcIssue::STATUS_CLOSE)->orderBy('id', 'desc')->first();
  343. } else {
  344. $issueCloseInfo = IssueService::model()::where('status', IssueService::model()::STATUS_CLOSE)->orderBy('id', 'desc')->first();
  345. }
  346. if (empty($issueCloseInfo)) {
  347. $errText .= lang("暂无可下注期数,本次下注无效!");
  348. return false;
  349. } else {
  350. $errText .= lang("封盘中,本次下注无效!");
  351. return false;
  352. }
  353. }
  354. if (!is_numeric($amount) || $amount <= 0) {
  355. $errText .= lang("投注金额格式不正确!");
  356. $errText .= lang("任何疑问都可以联系唯一财务") . ":@{$serviceAccount}";
  357. return false;
  358. }
  359. $now_date = date('Y-m-d H:i:s', time() + 30); // 提前30秒
  360. if ($issueInfo['end_time'] < $now_date) {
  361. $errText .= lang("封盘中,本次下注无效!");
  362. return false;
  363. }
  364. // 投注限制校验
  365. if ($amount < $gameplayRuleInfo['mininum']) {
  366. $errText .= lang("下注失败,最小金额限制") . "{$gameplayRuleInfo['mininum']}\n";
  367. return false;
  368. }
  369. // 投注限制校验
  370. if ($amount > $gameplayRuleInfo['maxinum']) {
  371. $errText .= lang("下注失败,最大金额限制") . "{$gameplayRuleInfo['maxinum']}\n";
  372. return false;
  373. }
  374. // 获取用户余额
  375. $walletInfo = WalletService::findOne(['member_id' => $memberId]);
  376. $balance = $walletInfo['available_balance'];
  377. // 余额计算
  378. if ($balance < $amount) {
  379. $errText .= lang("余额不足,本次下注无效!\n");
  380. return false;
  381. }
  382. $userInfo = UserService::findOne(['member_id' => $memberId]);
  383. $type = $pc28Switch == 1 ? 6 : 5;
  384. // 下注项存于 lhc_order_item;相同下注只合并到本机器人建的单项、无优惠券、未开奖的订单
  385. $betInfo = LhcOrder::where('type', $type)
  386. ->where('bet_source', LhcOrder::SOURCE_TELEGRAM)
  387. ->where('member_id', $memberId)
  388. ->where('issue', $issueInfo->issue_no)
  389. ->where('lottery_status', LhcOrder::STATUS_STAY)
  390. ->where(LotteryOdds::orderFields($template))
  391. ->where('odds', $gameplayRuleInfo['odds'])
  392. ->whereNull('coupon_id')
  393. ->whereColumn('total_amount', 'amount')
  394. ->whereIn('ordernum', LhcOrderItem::where('member_id', $memberId)->where('number', $keywords)->select('ordernum'))
  395. ->lockForUpdate()
  396. ->first(); // 相同下注
  397. if ($betInfo) {
  398. $betInfo->amount = bcadd($betInfo->amount, $amount, 2);
  399. $betInfo->total_amount = $betInfo->amount;
  400. $betInfo->save();
  401. $bet_id = $betInfo->id;
  402. } else {
  403. $ordernum = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
  404. LhcOrderItem::create([
  405. 'ordernum' => $ordernum,
  406. 'member_id' => $memberId,
  407. 'number' => $keywords, // 玩法
  408. ]);
  409. $newBet = LhcOrder::create([
  410. 'type' => $type,
  411. 'bet_source' => LhcOrder::SOURCE_TELEGRAM,
  412. 'issue' => $issueInfo->issue_no,
  413. 'ordernum' => $ordernum,
  414. 'member_id' => $memberId,
  415. 'odds' => $gameplayRuleInfo['odds'],
  416. 'amount' => $amount, // 分数
  417. 'total_amount' => $amount,
  418. ] + LotteryOdds::orderFields($template));
  419. $bet_id = $newBet->id;
  420. }
  421. WalletService::updateBalance($memberId, -$amount);
  422. BalanceLogService::addLog($memberId, -$amount, $balance, ($balance - $amount), '投注', $bet_id, '');
  423. $odds = floatval($gameplayRuleInfo['odds']);
  424. $issueNo = $issueInfo->issue_no;
  425. $text .= "{$keywords} {$amount} ({$odds}" . lang('倍率') . ")";
  426. $lastStr = self::hideMiddleDigits($userInfo->member_id, 4);
  427. $lang = App::getLocale();
  428. $group_language = Config::where('field', 'group_language')->first()->val;
  429. App::setLocale($group_language);
  430. if ($index === 0) {
  431. $groupText .= lang("第") . "{$issueNo}" . lang("期") . "\n";
  432. $groupText .= lang("开奖时间") . ":" . date("H:i:s", strtotime($issueInfo['end_time'])) . "\n";
  433. $groupText .= lang('投注截止') . ":" . date("H:i:s", (strtotime($issueInfo['end_time'])) - 30) . "\n";;
  434. $groupText .= lang("成功") . "\n";
  435. $groupText .= lang('玩家') . ": 【{$lastStr}】 \n";
  436. }
  437. $groupText .= "{$keywords} {$amount} ({$odds}" . lang("倍率") . ") \n";
  438. App::setLocale($lang);
  439. return true;
  440. }
  441. //随机虚拟下注
  442. public static function randomVirtualBetting($maxPeople = 1): void
  443. {
  444. $maxPeople = intval($maxPeople);
  445. $maxPeople = max($maxPeople, 1);
  446. $maxPeople = min($maxPeople, 20);
  447. $num = rand(1, $maxPeople);
  448. for ($i = 0; $i < $num; $i++) {
  449. static::fakeBet(4);
  450. }
  451. }
  452. // 模拟下注
  453. private static function fakeBet($betNumber = 1): void
  454. {
  455. $noRule = ['0操', '27操'];
  456. // 防止一开就虚拟投注
  457. $cache = Cache::get('new_issue_no');
  458. if ($cache) {
  459. echo "防止一开就虚拟投注\n";
  460. return;
  461. }
  462. //系统维护
  463. $maintenanceSwitch = Config::where('field', 'maintenance_switch')->first()->val;
  464. if ($maintenanceSwitch != 0) {
  465. echo "系统维护中\n";
  466. return;
  467. }
  468. if ((new MaintenanceService())->telegramPc28Failure('zh') !== null) {
  469. echo "28彩种维护中\n";
  470. return;
  471. }
  472. //后台是否开启虚拟投注
  473. $betFake = Config::where('field', 'bet_fake')->first()->val;
  474. if ($betFake != 1) {
  475. echo "未开启虚拟投注\n";
  476. return;
  477. }
  478. // 期数验证
  479. $pc28Switch = Config::where('field', 'pc28_switch')->first()->val;
  480. if ($pc28Switch == 1) {
  481. $issueInfo = PcIssue::where('status', PcIssue::STATUS_BETTING)->orderBy('id', 'desc')->first();
  482. } else {
  483. $issueInfo = IssueService::model()::where('status', IssueService::model()::STATUS_BETTING)->orderBy('id', 'desc')->first();
  484. }
  485. if ($issueInfo) {
  486. $betFakeRandAmount = Config::where('field', 'bet_fake_rand_amount')->first()->val;
  487. $betFakeRandAmount = explode(',', $betFakeRandAmount);
  488. $betMini = $betFakeRandAmount[0] ?? 10;
  489. $betMax = $betFakeRandAmount[1] ?? 10000;
  490. $now_date = date('Y-m-d H:i:s', time() + 38); // 提前45秒
  491. if ($issueInfo['end_time'] > $now_date) {
  492. $fake_bet_list = Cache::get('fake_bet_' . $issueInfo->issue_no, []);
  493. $key = $pc28Switch == 1 ? 'jisu28' : 'canada28';
  494. $gameplayRuleList = DB::transaction(fn () => LotteryOdds::pricedCatalog($key, LotteryOdds::template($key)->id)
  495. ->filter(fn ($rule) => $rule->odds > 0)->values()->map(fn ($rule) => (array) $rule)->all());
  496. if ($gameplayRuleList === []) {
  497. return;
  498. }
  499. $member_id = self::generateRandomNumber(10);
  500. $betTimes = rand(1, $betNumber); // 每次下注次数
  501. Cache::add("封盘后下注单数_{$issueInfo->issue_no}", rand(3, 5), 4);
  502. $lastStr = self::hideMiddleDigits($member_id, 4);
  503. $lang = App::getLocale();
  504. $group_language = Config::where('field', 'group_language')->first()->val;
  505. $first_name = self::generateRandomString(6);
  506. App::setLocale($group_language);
  507. $groupText = lang("第") . "{$issueInfo->issue_no}" . lang("期") . "\n";
  508. $groupText .= lang("开奖时间") . ":" . date("H:i:s", strtotime($issueInfo['end_time'])) . "\n";
  509. $groupText .= lang('投注截止') . ":" . date("H:i:s", (strtotime($issueInfo['end_time'])) - 30) . "\n";;
  510. $groupText .= lang("成功") . "\n";
  511. $groupText .= lang('玩家') . ": 【{$lastStr}】 \n";
  512. App::setLocale($lang);
  513. $haveBet = false;
  514. for ($i = 0; $i < $betTimes; $i++) {
  515. if (strtotime($issueInfo['end_time']) - time() < IssueService::COUNTDOWN_TO_CLOSING_THE_MARKET) {
  516. $fake_bet_count = Cache::get("fake_bet_count_{$issueInfo->issue_no}", 0);
  517. $cc = Cache::get("封盘后下注单数_{$issueInfo->issue_no}");
  518. if ($fake_bet_count >= $cc) return;
  519. }
  520. $randKey = array_rand($gameplayRuleList, 1);
  521. $gameplayRuleInfo = $gameplayRuleList[$randKey] ?? [];
  522. if ($gameplayRuleInfo) {
  523. if (in_array($gameplayRuleInfo['keywords'], $noRule)) {
  524. return;
  525. }
  526. if ($gameplayRuleInfo['maxinum'] < $betMax) {
  527. $betMax = $gameplayRuleInfo['maxinum'];
  528. }
  529. if ($gameplayRuleInfo['mininum'] > $betMini) {
  530. $betMini = $gameplayRuleInfo['mininum'];
  531. }
  532. $amount = rand($betMini, $betMax);
  533. $amount = floor($amount / 10) * 10;
  534. $input = $gameplayRuleInfo['keywords'] . ' ' . $amount;
  535. // $amount = number_format($amount,2);
  536. $item = [];
  537. $item['keywords'] = $gameplayRuleInfo['keywords'];
  538. $item['odds'] = floatval($gameplayRuleInfo['odds']);
  539. $item['amount'] = $amount;
  540. $item['first_name'] = $first_name;
  541. $item['member_id'] = $member_id;
  542. $item['profit'] = 0;
  543. // $input = $item['keywords'] . $item['amount'];
  544. $fake_bet_list[] = $item;
  545. $lang = App::getLocale();
  546. $group_language = Config::where('field', 'group_language')->first()->val;
  547. $first_name = self::generateRandomString(6);
  548. App::setLocale($group_language);
  549. $groupText .= "{$input} (" . $item['odds'] . lang("倍率") . ") \n";
  550. $haveBet = true;
  551. App::setLocale($lang);
  552. if (strtotime($issueInfo['end_time']) - strtotime($now_date) < 22) {
  553. $fake_bet_count = Cache::get("fake_bet_count_{$issueInfo->issue_no}", 0);
  554. Cache::put("fake_bet_count_{$issueInfo->issue_no}", $fake_bet_count + 1, 500);
  555. }
  556. }
  557. }
  558. if ($haveBet) {
  559. $groupText .= "\n-------- \n";
  560. $inlineButton = self::getOperateButton();
  561. // 群通知 暂停2秒再发送,避免同时发送多个消息而超过 Telegram 的频率限制
  562. self::asyncBettingGroupNotice($groupText, $inlineButton); // 异步群通知
  563. sleep(2);
  564. }
  565. Cache::put('fake_bet_' . $issueInfo->issue_no, $fake_bet_list, 500);
  566. }
  567. }
  568. }
  569. /**
  570. * @description: 当期下注
  571. * @param {*} $memberId
  572. * @return {*}
  573. */
  574. public static function currentBet($memberId)
  575. {
  576. $msg['chat_id'] = $memberId;
  577. // 期数验证
  578. $issueInfo = IssueService::model()::where('status', IssueService::model()::STATUS_BETTING)->orderBy('id', 'desc')->first();
  579. $issue_no = '';
  580. if (!empty($issueInfo)) {
  581. $issue_no = $issueInfo->issue_no;
  582. } else {
  583. $issueCloseInfo = IssueService::model()::where('status', IssueService::model()::STATUS_CLOSE)->orderBy('id', 'desc')->first();
  584. if (empty($issueCloseInfo)) {
  585. $issue_no = $issueCloseInfo->issue_no;
  586. }
  587. }
  588. if ($issue_no) {
  589. $text = lang("期数") . " {$issue_no} \n";
  590. // $text .= "\n";
  591. // $text .= "----------\n";
  592. $list = self::model()::with('items')->whereIn('type', [5, 6])->where('member_id', $memberId)->where('issue', $issue_no)->get();
  593. $list = $list->map(fn ($v) => ['number' => $v->items->pluck('number')->implode(','), 'amount' => $v->amount])->toArray();
  594. if (empty($list)) {
  595. $text .= lang("本期暂未下注") . "! \n";
  596. } else {
  597. $keywords = implode(',', array_column($list, 'number'));
  598. $amounts = implode(',', array_column($list, 'amount'));
  599. $text .= lang("下注类型") . ":[" . $keywords . "] \n";
  600. $text .= lang("下注金额") . ":" . $amounts . " \n";
  601. $text .= lang("下注总额") . ":" . array_sum(array_column($list, 'amount')) . " \n";
  602. $text .= lang("开奖状态") . ":" . lang("等待开奖") . " \n";
  603. }
  604. // foreach ($list->toArray() as $k => $v) {
  605. // $text .= "{$v['keywords']}{$v['amount']} \n";
  606. // }
  607. // $text .= "\n";
  608. // $text .= "----------\n";
  609. $msg['text'] = $text;
  610. } else {
  611. $msg['text'] = lang("当前没有开放的投注期数") . "! \n";
  612. }
  613. return $msg;
  614. }
  615. /**
  616. * @description: 近期投注
  617. * @param {*} $memberId
  618. * @return {*}
  619. */
  620. public static function recentlyRecord($memberId, $page = 1, $limit = 5)
  621. {
  622. $list = self::model()::with('items')->whereIn('type', [5, 6])->where('member_id', $memberId)->orderBy('id', 'desc')->forPage($page, $limit)->get();
  623. // $text = "```\n";
  624. $text = "";
  625. $text .= "期数--内容--盈亏 \n";
  626. foreach ($list as $k => $v) {
  627. $v = $v->toArray() + ['number' => $v->items->pluck('number')->implode(',')];
  628. $profit = $v['win_amount'] - $v['amount'];
  629. // $text .= $v['issue_no']." ".$v['keywords']." ".$v['amount']." ".$v['profit']."\n";
  630. $item = $v['issue'] . "==" . $v['number'] . rtrim(rtrim(number_format($v['amount'], 2, '.', ''), '0'), '.') . "==" . rtrim(rtrim(number_format($profit, 2, '.', ''), '0'), '.') . "\n";
  631. $text .= $item;
  632. }
  633. // $text .= "```\n";
  634. return $text;
  635. }
  636. /**
  637. * @description: 投注记录
  638. * @param {*} $memberId
  639. * @param {*} $page
  640. * @param {*} $limit
  641. * @return {*}
  642. */
  643. public static function record($memberId, $messageId = null, $page = 1, $limit = 5)
  644. {
  645. $type = Cache::get('message_id_bet_record_' . $memberId, 0);
  646. if ($type == 0) {
  647. $type = '';
  648. }
  649. $msg['chat_id'] = $memberId;
  650. $list = self::model()::with('items')->whereIn('type', [5, 6])->where('member_id', $memberId)->orderBy('id', 'desc')->forPage($page, $limit)->get();
  651. $count = self::model()::whereIn('type', [5, 6])->where('member_id', $memberId)->count();
  652. $keyboard = [];
  653. $total_amount = BalanceLogService::model()::where('member_id', $memberId)->where('change_type', '中奖')->sum('amount');
  654. $total_amount = number_format($total_amount, 2);
  655. $text = lang("历史注单") . " \n";
  656. $text .= lang("中奖总派彩") . ":{$total_amount} \n";
  657. foreach ($list as $k => $v) {
  658. if ($v->lottery_status == self::model()::STATUS_WIN || $v->lottery_status == self::model()::STATUS_LOSS) {
  659. $phase = $v->win_amount - $v->amount;
  660. } else {
  661. $phase = lang('待开奖');
  662. }
  663. $text .= "-------------------------------------\n";
  664. $text .= lang("期数") . ":{$v->issue} \n";
  665. $text .= lang("内容") . ":" . $v->items->pluck('number')->implode(',') . " \n";
  666. $text .= lang("金额") . ":{$v->amount} \n";
  667. $text .= lang("盈亏") . ":{$phase} \n";
  668. }
  669. $msg['text'] = $text;
  670. $keyboard[] = [
  671. ['text' => lang("全部"), 'callback_data' => "betRecordType@@0"],
  672. ['text' => lang("盈利"), 'callback_data' => "betRecordType@@1"],
  673. ['text' => lang("亏损"), 'callback_data' => "betRecordType@@2"]
  674. ];
  675. if ($page > 1) {
  676. $keyboard[] = [
  677. ['text' => "👆" . lang("上一页"), 'callback_data' => "betRecordNextPage@@" . ($page - 1)]
  678. ];
  679. }
  680. $allPage = ceil($count / $limit);
  681. if ($allPage > $page) {
  682. if ($page > 1) {
  683. $keyboard[count($keyboard) - 1][] = ['text' => "👇" . lang("下一页"), 'callback_data' => "betRecordNextPage@@" . ($page + 1)];
  684. } else {
  685. $keyboard[] = [
  686. ['text' => "👇" . lang("下一页"), 'callback_data' => "betRecordNextPage@@" . ($page + 1)]
  687. ];
  688. }
  689. }
  690. if ($messageId) {
  691. $msg['message_id'] = $messageId;
  692. }
  693. if ($keyboard) {
  694. $msg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  695. }
  696. return $msg;
  697. }
  698. /**
  699. * @description: 开奖失败退回投注的
  700. * @param {*} $issue_no
  701. * @return {*}
  702. */
  703. public static function betFail($issue_no)
  704. {
  705. $list = self::findAll(['issue' => $issue_no, 'lottery_status' => self::model()::STATUS_STAY]);
  706. foreach ($list->toArray() as $k => $v) {
  707. $profit = $v['amount'];
  708. // A couponed slip refunds only what the member paid for all its numbers, and the coupon comes back.
  709. if (!empty($v['coupon_id']) || bccomp((string) ($v['coupon_discount'] ?? 0), '0', 2) > 0) {
  710. $profit = PromotionCouponService::paid($v['total_amount'], $v['coupon_discount'] ?? 0);
  711. PromotionCouponService::release('lhc_order', (int) $v['id']);
  712. }
  713. WalletService::updateBalance($v['member_id'], $profit);
  714. $walletInfo = WalletService::findOne(['member_id' => $v['member_id']]);
  715. $balance = $walletInfo['available_balance'];
  716. BalanceLogService::addLog($v['member_id'], $profit, ($balance - $profit), $balance, '投注退分', $v['id'], '');
  717. $text = $issue_no . "期开奖失败 \n";
  718. $text .= "投注类型:" . LhcOrderItem::where('ordernum', $v['ordernum'])->pluck('number')->implode(',') . " \n";
  719. $text .= "投注金额:{$v['amount']} \n";
  720. $text .= "投注的资金已退回您的钱包 \n";
  721. if (!MemberAudience::isSimulatedMember($v['member_id'])) self::asyncSendMessage($v['member_id'], $text);
  722. $item = [];
  723. $item['lottery_status'] = self::model()::STATUS_LOSS;
  724. self::model()::where('id', $v['id'])->update($item);
  725. //下注项状态更新为未中奖
  726. LhcOrderItem::where('ordernum', $v['ordernum'])->update(['lottery_status' => self::model()::STATUS_LOSS]);
  727. \App\Services\Reporting\ReportContext::lotterySettled((int) $v['id']);
  728. AdminRealtime::record('lhc_order', $v['id']);
  729. }
  730. }
  731. /**
  732. * @description: 中奖结算
  733. * @param {*} $issue_no
  734. * @param {*} $awards
  735. * @return {*}
  736. */
  737. public static function betSettled($issue_no, $awards)
  738. {
  739. $list = self::findAll(['issue' => $issue_no, 'lottery_status' => self::model()::STATUS_STAY]);
  740. // 大小单双的
  741. // 后台模拟会员的注额不计入总注(总注决定真实玩家 13/14 的特殊赔率)
  742. $otherSum = MemberAudience::visibleMembers(self::model()::leftJoin('lhc_order_item', 'lhc_order_item.ordernum', '=', 'lhc_order.ordernum'), 'lhc_order.member_id')
  743. ->whereIn('lhc_order.type', [5, 6])
  744. ->where('lhc_order.issue', $issue_no)
  745. ->where('lhc_order.lottery_status', self::model()::STATUS_STAY)
  746. ->whereIn('lhc_order_item.number', ['大', '小', '单', '双'])
  747. ->sum('lhc_order.total_amount');
  748. $fakeOpenData = self::fakeLotteryDraw($issue_no, $awards, 0);
  749. $keywordsList = $fakeOpenData['keywordsList'];
  750. $fakeOtherSum = $fakeOpenData['sum'];
  751. $sum = $otherSum + $fakeOtherSum;
  752. $betNoticeNum = Config::where('field', 'bet_notice_num')->first()->val;
  753. $betNoticeNum = explode(',', $betNoticeNum);
  754. $betNoticeMini = max(1, (int)($betNoticeNum[0] ?? 26));
  755. $betNoticeMax = max($betNoticeMini, (int)($betNoticeNum[1] ?? 38));
  756. $noticeNum = rand($betNoticeMini, $betNoticeMax);
  757. $openList = [];
  758. $memberList = [];
  759. $simulatedMembers = [];
  760. foreach ($list as $k => $settlementOrder) {
  761. $v = $settlementOrder->toArray();
  762. // 后台模拟会员:照常结算派奖,但不进群播报、不发私聊、不累计活动投注
  763. $simulated = MemberAudience::isSimulatedMember($v['member_id']);
  764. if ($simulated) $simulatedMembers[$v['member_id']] = true;
  765. $order_item = LhcOrderItem::where('ordernum', $v['ordernum'])->get()->toArray();
  766. $total_amount = 0;
  767. foreach($order_item as $value) {
  768. $number = $value['number'];
  769. // Payout uses the full stake; net result and effective bet use what the member paid after the coupon.
  770. $paid = PromotionCouponService::paid($v['amount'], $value['coupon_discount'] ?? 0);
  771. if ($simulated) {
  772. // 不计入播报的各玩法注额
  773. } elseif (isset($keywordsList[$number])) {
  774. $keywordsList[$number] += $v['amount'];
  775. } else {
  776. $keywordsList[$number] = $v['amount'];
  777. }
  778. $lastStr = self::hideMiddleDigits($v['member_id'], 4);
  779. $item = [];
  780. $item['id'] = $value['id'];
  781. $item['lottery_status'] = self::model()::STATUS_LOSS;//未中奖
  782. $item['profit_and_loss'] = bcsub('0', $paid, 2);
  783. if (in_array($number, $awards)) {
  784. $amount = $v['amount'];
  785. $odds = $v['odds'];
  786. //玩 大单 小单 大双 小双 :如果开出13和14 总注小于10000 1.5赔率含本,大于等于10000退本金。
  787. if (in_array('13操', $awards) || in_array('14操', $awards)) {
  788. // 13 14特殊处理倍率
  789. if (in_array($number, self::$OTHER_BET_2)) {
  790. if ($sum < 10000) {
  791. $odds = 1.5;
  792. } else {
  793. $odds = 1;
  794. }
  795. }
  796. }
  797. $profit = bcmul($amount, $odds, 2); // 保留两位小数
  798. if ($profit > 1000000) {
  799. $profit = 1000000; // 单注最高奖金1000000
  800. }
  801. $item['lottery_status'] = self::model()::STATUS_WIN;//中奖
  802. $item['win_amount'] = $profit;
  803. $total_amount += $profit;
  804. $yl = bcsub($profit, $paid, 2); // 盈利
  805. $item['profit_and_loss'] = $yl;
  806. if (!$simulated && !in_array('13操', $awards) && !in_array('14操', $awards)) {
  807. ActivityUserService::updateBettingAmount($v['member_id'], $paid);
  808. }
  809. $memberList[$v['member_id']][] = [
  810. 'member_id' => $v['member_id'],
  811. 'keywords' => $number,
  812. 'amount' => $v['amount'],
  813. 'profit' => $profit,
  814. 'yl' => $yl,
  815. ];
  816. $walletInfo = WalletService::findOne(['member_id' => $v['member_id']]);
  817. $balance = $walletInfo['available_balance'];
  818. WalletService::updateBalance($v['member_id'], $profit);
  819. BalanceLogService::addLog($v['member_id'], $profit, $balance, ($balance + $profit), '中奖', $v['id'], "盈利:{$yl}");
  820. if (isset($openList[$v['member_id']])) {
  821. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  822. $openList[$v['member_id']]['amount'] += $v['amount'];
  823. $openList[$v['member_id']]['profit'] += $profit;
  824. $openList[$v['member_id']]['lastStr'] = $lastStr;
  825. $openList[$v['member_id']]['openKeywords'][] = $number . "({$odds}" . lang("倍率") . ")";
  826. $openList[$v['member_id']]['keywords'][] = $number;
  827. $openList[$v['member_id']]['win_amount'] += $v['amount'];
  828. } else {
  829. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  830. $openList[$v['member_id']]['amount'] = $v['amount'];
  831. $openList[$v['member_id']]['profit'] = $profit;
  832. $openList[$v['member_id']]['lastStr'] = $lastStr;
  833. $openList[$v['member_id']]['openKeywords'] = [];
  834. $openList[$v['member_id']]['keywords'] = [];
  835. $openList[$v['member_id']]['openKeywords'][] = $number . "({$odds}" . lang("倍率") . ")";
  836. $openList[$v['member_id']]['keywords'][] = $number;
  837. $openList[$v['member_id']]['win_amount'] = $v['amount'];
  838. $openList[$v['member_id']]['is_send'] = true;
  839. }
  840. } else {
  841. if (!$simulated && !in_array('13操', $awards) && !in_array('14操', $awards)) {
  842. ActivityUserService::updateBettingAmount($v['member_id'], $paid);
  843. }
  844. // 未命中的组合不应用 13/14 特殊赔率。
  845. $profit = 0;
  846. if (isset($openList[$v['member_id']])) {
  847. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  848. $openList[$v['member_id']]['amount'] += $v['amount'];
  849. $openList[$v['member_id']]['profit'] += $profit;
  850. $openList[$v['member_id']]['lastStr'] = $lastStr;
  851. $openList[$v['member_id']]['keywords'][] = $number;
  852. } else {
  853. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  854. $openList[$v['member_id']]['amount'] = $v['amount'];
  855. $openList[$v['member_id']]['profit'] = $profit;
  856. $openList[$v['member_id']]['lastStr'] = $lastStr;
  857. $openList[$v['member_id']]['openKeywords'] = [];
  858. $openList[$v['member_id']]['keywords'] = [];
  859. $openList[$v['member_id']]['keywords'][] = $number;
  860. $openList[$v['member_id']]['win_amount'] = 0;
  861. $openList[$v['member_id']]['is_send'] = true;
  862. }
  863. }
  864. LhcOrderItem::where('id', $value['id'])->update($item);
  865. }
  866. if ($total_amount > 0) {
  867. LhcOrder::where("id", $v['id'])->update(['lottery_status' => '2', 'win_amount' => $total_amount]);
  868. } else {
  869. LhcOrder::where("id", $v['id'])->update(['lottery_status' => '1', 'win_amount' => 0]);
  870. }
  871. \App\Services\Reporting\ReportContext::lotterySettled((int) $v['id']);
  872. AdminRealtime::record('lhc_order', $v['id']);
  873. }
  874. $openList = array_diff_key($openList, $simulatedMembers);
  875. $openList = array_merge($openList, $fakeOpenData['list']);
  876. self::lotteryNotice($openList, $issue_no, $keywordsList);
  877. }
  878. // 虚拟开奖
  879. public static function fakeLotteryDraw($issue_no, $awards, $rand_num = 30)
  880. {
  881. $fake_bet_list = Cache::get('fake_bet_' . $issue_no, []);
  882. $text = "";
  883. $keywordsList = [];
  884. $fakeOtherSum = 0;
  885. $openList = [];
  886. foreach ($fake_bet_list as $k => $v) {
  887. if (in_array($v['keywords'], ['大', '小', '单', '双'])) {
  888. $fakeOtherSum += $v['amount'];
  889. }
  890. if (isset($keywordsList[$v['keywords']])) {
  891. $keywordsList[$v['keywords']] += $v['amount'];
  892. } else {
  893. $keywordsList[$v['keywords']] = $v['amount'];
  894. }
  895. // $lastStr = self::getLastChar($v['first_name'], 1);
  896. $lastStr = self::hideMiddleDigits($v['member_id'], 4);
  897. if (in_array($v['keywords'], $awards)) {
  898. $amount = $v['amount'];
  899. $odds = $v['odds'];
  900. $profit = bcmul($amount, $odds, 2); // 保留两位小数
  901. if ($profit > 880000) {
  902. $profit = 880000; // 单注最高奖金880000
  903. }
  904. $item['profit'] = $profit;
  905. // $v['amount'] = number_format($amount,2);
  906. if (isset($openList[$v['member_id']])) {
  907. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  908. $openList[$v['member_id']]['amount'] += $v['amount'];
  909. $openList[$v['member_id']]['profit'] += $profit;
  910. $openList[$v['member_id']]['lastStr'] = $lastStr;
  911. $openList[$v['member_id']]['openKeywords'][] = $v['keywords'] . "({$odds}" . lang("倍率") . ")";
  912. $openList[$v['member_id']]['keywords'][] = $v['keywords'];
  913. $openList[$v['member_id']]['win_amount'] += $v['amount'];
  914. } else {
  915. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  916. $openList[$v['member_id']]['amount'] = $v['amount'];
  917. $openList[$v['member_id']]['profit'] = $profit;
  918. $openList[$v['member_id']]['lastStr'] = $lastStr;
  919. $openList[$v['member_id']]['openKeywords'] = [];
  920. $openList[$v['member_id']]['keywords'] = [];
  921. $openList[$v['member_id']]['openKeywords'][] = $v['keywords'] . "({$odds}" . lang("倍率") . ")";
  922. $openList[$v['member_id']]['keywords'][] = $v['keywords'];
  923. $openList[$v['member_id']]['win_amount'] = $v['amount'];
  924. $openList[$v['member_id']]['is_send'] = false;
  925. }
  926. } else {
  927. if (isset($openList[$v['member_id']])) {
  928. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  929. $openList[$v['member_id']]['amount'] += $v['amount'];
  930. $openList[$v['member_id']]['lastStr'] = $lastStr;
  931. $openList[$v['member_id']]['keywords'][] = $v['keywords'];
  932. } else {
  933. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  934. $openList[$v['member_id']]['amount'] = $v['amount'];
  935. $openList[$v['member_id']]['profit'] = 0;
  936. $openList[$v['member_id']]['lastStr'] = $lastStr;
  937. $openList[$v['member_id']]['openKeywords'] = [];
  938. $openList[$v['member_id']]['keywords'] = [];
  939. $openList[$v['member_id']]['keywords'][] = $v['keywords'];
  940. $openList[$v['member_id']]['win_amount'] = 0;
  941. $openList[$v['member_id']]['is_send'] = false;
  942. }
  943. }
  944. }
  945. return ['sum' => $fakeOtherSum, 'list' => $openList, 'keywordsList' => $keywordsList];
  946. }
  947. // 开奖通知
  948. public static function lotteryNotice($openList, $issue_no, $keywordsList = [])
  949. {
  950. $betNoticeNum = Config::where('field', 'bet_notice_num')->first()->val;
  951. $betNoticeNum = explode(',', $betNoticeNum);
  952. $betNoticeMini = max(1, (int)($betNoticeNum[0] ?? 26));
  953. $betNoticeMax = max($betNoticeMini, (int)($betNoticeNum[1] ?? 38));
  954. $noticeNum = rand($betNoticeMini, $betNoticeMax);
  955. // shuffle($openList);
  956. // Log::error('lotteryNotice openList', $openList);
  957. $lang = App::getLocale();
  958. $group_language = Config::where('field', 'group_language')->first()->val;
  959. App::setLocale($group_language);
  960. $text = "{$issue_no} " . lang("期开奖结果");
  961. $text .= "\n-----" . lang("本期开奖账单") . "----- \n";
  962. App::setLocale($lang);
  963. $noticeIndex = 0;
  964. $noticeRows = 0;
  965. foreach ($openList as $v) {
  966. $noticeIndex++;
  967. $amount = number_format($v['amount'], 2);
  968. $v['win_amount'] = number_format($v['win_amount'], 2);
  969. $profit = number_format($v['profit'], 2);
  970. $yl = bcsub($v['profit'], $v['amount'], 2); // 盈利
  971. if (empty($v['openKeywords'])) {
  972. $openKeyword = '-';
  973. } else {
  974. $openKeyword = implode(',', $v['openKeywords']);
  975. }
  976. if ($noticeIndex <= $noticeNum) {
  977. $noticeRows++;
  978. $lang = App::getLocale();
  979. $group_language = Config::where('field', 'group_language')->first()->val;
  980. App::setLocale($group_language);
  981. $text .= lang("用户ID") . ":{$v['lastStr']} \n";
  982. $text .= lang("下注类型") . ":[" . implode(',', $v['keywords']) . "] \n";
  983. $text .= lang('中奖类型') . ":[" . $openKeyword . "] \n";
  984. $text .= lang('投注金额') . ":{$amount} \n";
  985. $text .= lang('中奖金额') . ":{$v['win_amount']} \n";
  986. $text .= lang('派彩金额') . ":{$profit} \n";
  987. $text .= lang("盈亏金额") . ":{$yl} \n";
  988. $text .= "-------------------------------- \n";
  989. App::setLocale($lang);
  990. }
  991. //根据环境变量配置是否发送电报
  992. if ($v['is_send'] && config('services.telegram.send_enabled', false)) {
  993. $language = User::where('member_id', $v['member_id'])->first()->language;
  994. $wallet = WalletService::findOne(['member_id' => $v['member_id']]);
  995. App::setLocale($language);
  996. $text2 = lang("{issue_no}期开奖结果");
  997. $text2 = str_replace("{issue_no}", $issue_no, $text2);
  998. $text2 .= "\n";
  999. $text2 .= lang('下注类型') . ":[" . implode(',', $v['keywords']) . "] \n";
  1000. $text2 .= lang('中奖类型') . ":[" . $openKeyword . "] \n";
  1001. $text2 .= lang('投注金额') . ":{$amount} \n";
  1002. $text2 .= lang('中奖金额') . ":{$v['win_amount']} \n";
  1003. $text2 .= lang('派彩金额') . ":{$profit} \n";
  1004. $text2 .= lang("盈亏金额") . ":{$yl} \n";
  1005. $balance = floatval($wallet->available_balance);
  1006. $text2 .= "----------------\n";
  1007. $text2 .= "当前余额:{$balance} \n";
  1008. $keyboard = [];
  1009. $keyboard[] = [
  1010. ['text' => lang("开奖历史"), 'callback_data' => "showLotteryHistory@@" . $issue_no]
  1011. ];
  1012. // self::sendMessage($v['member_id'],$text2,$keyboard);
  1013. SendTelegramMessageJob::dispatch($v['member_id'], $text2, $keyboard)->afterCommit();
  1014. }
  1015. }
  1016. $inlineButton = self::getOperateButton();
  1017. //根据环境变量配置是否发送电报
  1018. if (config('services.telegram.send_enabled', false)) {
  1019. // 群通知
  1020. $pc28Switch = Config::where('field', 'pc28_switch')->first()->val;
  1021. if (($pc28Switch == 0 && is_numeric($issue_no)) || $pc28Switch == 1 && !is_numeric($issue_no)) {
  1022. Log::channel('issue')->info('结算列表群通知入队', [
  1023. 'issue_no' => $issue_no,
  1024. 'pc28_switch' => $pc28Switch,
  1025. 'text_length' => strlen($text),
  1026. 'open_list_count' => count($openList),
  1027. 'notice_num' => $noticeNum,
  1028. 'notice_rows' => $noticeRows,
  1029. ]);
  1030. SendTelegramGroupMessageJob::dispatch($text, $inlineButton, '', false, '--------------------------------', [
  1031. 'message_type' => 'settlement_list',
  1032. 'issue_no' => $issue_no,
  1033. 'open_list_count' => count($openList),
  1034. 'notice_rows' => $noticeRows,
  1035. ])->afterCommit();
  1036. } else {
  1037. Log::channel('issue')->info('结算列表群通知跳过', [
  1038. 'issue_no' => $issue_no,
  1039. 'pc28_switch' => $pc28Switch,
  1040. 'reason' => 'pc28_switch_not_match_issue_type',
  1041. ]);
  1042. }
  1043. } else {
  1044. Log::channel('issue')->info('结算列表群通知跳过', [
  1045. 'issue_no' => $issue_no,
  1046. 'reason' => 'send_telegram_disabled',
  1047. ]);
  1048. }
  1049. }
  1050. /**
  1051. * @description: 统计投注情况通知
  1052. * @param {*} $issue_no
  1053. * @return {*}
  1054. */
  1055. public static function statNotice($issue_no)
  1056. {
  1057. $keywordsList = [];
  1058. // 虚拟投注情况
  1059. $fake_bet_list = Cache::get('fake_bet_' . $issue_no, []);
  1060. foreach ($fake_bet_list as $k => $v) {
  1061. if (isset($keywordsList[$v['keywords']])) {
  1062. $keywordsList[$v['keywords']] += $v['amount'];
  1063. } else {
  1064. $keywordsList[$v['keywords']] = $v['amount'];
  1065. }
  1066. }
  1067. // 真实投注
  1068. $list = self::findAll(['issue_no' => $issue_no]);
  1069. foreach ($list->toArray() as $k => $v) {
  1070. if (isset($keywordsList[$v['keywords']])) {
  1071. $keywordsList[$v['keywords']] += $v['amount'];
  1072. } else {
  1073. $keywordsList[$v['keywords']] = $v['amount'];
  1074. }
  1075. }
  1076. $lang = App::getLocale();
  1077. $group_language = Config::where('field', 'group_language')->first()->val;
  1078. App::setLocale($group_language);
  1079. $text3 = "📝 {$issue_no}" . lang('期投注统计') . " \n";
  1080. $text3 .= lang("玩法") . " " . lang("总投") . " \n";
  1081. App::setLocale($lang);
  1082. if ($keywordsList) {
  1083. uksort($keywordsList, 'custom_sort');
  1084. // ksort($keywordsList);
  1085. foreach ($keywordsList as $k => $v) {
  1086. $text3 .= "{$k} {$v} \n";
  1087. }
  1088. }
  1089. $inlineButton = self::getOperateButton();
  1090. // 投注统计的消息不发了
  1091. // SendTelegramGroupMessageJob::dispatch($text3, $inlineButton, '');
  1092. }
  1093. public static function todayExchangeRate($chatId)
  1094. {
  1095. $exchangeRate = Config::where('field', 'exchange_rate_rmb')->first()->val;
  1096. $text = lang("今日汇率") . ":1USDT = {$exchangeRate} RMB \n";
  1097. // $botMsg = [
  1098. // 'chat_id' => "@{$chatId}",
  1099. // 'text' => $text
  1100. // ];
  1101. self::sendMessage($chatId, $text);
  1102. // return $botMsg;
  1103. }
  1104. }