BetFactSynchronizer.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. <?php
  2. namespace App\Services\Sharing;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Schema;
  5. use InvalidArgumentException;
  6. use RuntimeException;
  7. /** The only importer of current real-money orders into the new sharing facts. */
  8. class BetFactSynchronizer
  9. {
  10. private array $users = [];
  11. private const LOTTERY_NAMES = [1 => '新澳门六合彩', 2 => '香港六合彩', 3 => '澳门六合彩', 4 => '极速六合彩',
  12. 5 => '加拿大28', 6 => '极速28', 7 => '极速赛车', 8 => '极速时时彩', 9 => '极速飞艇',
  13. 10 => 'SG时时彩', 11 => 'SG飞艇', 12 => '极速快3', 13 => 'SG快3'];
  14. private const REPAIR_BACKOFF_SECONDS = 3600;
  15. /** Read-only projection shared with reports; does not publish or alter sharing facts. */
  16. public function projectForReporting(string $source, object $order): array
  17. {
  18. if (!in_array($source, ['lhc_order', 'sport_order', 'sport_game_order', 'third_game_orders'], true)) throw new InvalidArgumentException('Unsupported reporting source');
  19. if ((int) ($order->is_faker ?? 0) === 1) return [];
  20. $this->users = [];
  21. return $source === 'lhc_order' ? $this->lotteryOrder($order, false)['facts'] : array_values(array_filter([$this->singleOrder($source, $order)]));
  22. }
  23. public function sync(?string $from = null, ?string $to = null, bool $write = false): array
  24. {
  25. foreach ([$from, $to] as $date) {
  26. if ($date !== null && (!preg_match('/^\d{4}-\d{2}-\d{2}$/D', $date)
  27. || \Carbon\Carbon::parse($date)->toDateString() !== $date)) {
  28. throw new InvalidArgumentException('Dates must use Y-m-d');
  29. }
  30. }
  31. if ($from !== null && $to !== null && $from > $to) throw new InvalidArgumentException('Invalid date range');
  32. $result = ['scanned' => 0, 'created' => 0, 'updated' => 0, 'unchanged' => 0, 'skipped' => 0,
  33. 'errors' => [], 'changed_dates' => [], 'write' => $write];
  34. $this->users = [];
  35. foreach (['lhc_order', 'sport_game_order', 'sport_order', 'third_game_orders'] as $table) {
  36. if (!Schema::hasTable($table)) continue;
  37. $cursorColumn = $table === 'sport_order' ? 'update_time' : 'updated_at';
  38. $cursorEnabled = $write && $from === null && $to === null && Schema::hasColumn($table, $cursorColumn);
  39. $startedAt = now()->setTimezone('Asia/Shanghai')->format('Y-m-d H:i:s');
  40. $highestIdAtStart = $cursorEnabled ? (int) DB::table($table)->max('id') : 0;
  41. $errorCount = count($result['errors']);
  42. $query = DB::table($table);
  43. $legacyMaxId = $table === 'lhc_order' ? (int) config('sharing.lottery_legacy_max_id', 0) : 0;
  44. $hasLotteryItems = $table === 'lhc_order' && Schema::hasTable('lhc_order_item');
  45. $legacyBackfillMaxId = $hasLotteryItems ? $legacyMaxId : 0;
  46. if ($legacyMaxId > 0) {
  47. $query->where(function ($query) use ($legacyMaxId, $hasLotteryItems) {
  48. $query->where('id', '>', $legacyMaxId);
  49. if ($hasLotteryItems) {
  50. $query->orWhereExists(DB::table('lhc_order_item')->selectRaw('1')
  51. ->whereColumn('lhc_order_item.ordernum', 'lhc_order.ordernum'));
  52. }
  53. });
  54. }
  55. $lastRun = null;
  56. $reconciledLegacyId = 0;
  57. $scannedIds = [];
  58. $process = function (int $id) use ($table, $from, $to, $write, &$result) {
  59. $result['scanned']++;
  60. try {
  61. $changes = $this->synchronizeOrder($table, $id, $from, $to, $write);
  62. foreach (['created', 'updated', 'unchanged', 'skipped'] as $key) $result[$key] += $changes[$key];
  63. foreach ($changes['changed_dates'] as $date) $result['changed_dates'][$date] = $date;
  64. $result['errors'] = array_merge($result['errors'], $changes['errors']);
  65. } catch (\Throwable $e) {
  66. $result['skipped']++;
  67. $result['errors'][] = ['source' => $table, 'source_id' => (string) $id, 'reason' => $e->getMessage()];
  68. }
  69. };
  70. if ($cursorEnabled) {
  71. $lastRun = DB::table('share_system_state')->where('key', 'facts_cursor:' . $table)->value('value');
  72. if ($lastRun) {
  73. $cursor = json_decode($lastRun, true, 512, JSON_THROW_ON_ERROR);
  74. $reconciledLegacyId = (int) ($cursor['lottery_children_checked_through'] ?? 0);
  75. $cutoff = EffectiveBet::time($cursor['updated_at'])->subMinutes(5);
  76. $cutoffValue = in_array($table, ['lhc_order', 'sport_order'], true)
  77. ? $cutoff->timestamp : $cutoff->setTimezone('Asia/Shanghai')->format('Y-m-d H:i:s');
  78. $query->where(function ($query) use ($cursorColumn, $cutoffValue, $cursor, $legacyBackfillMaxId, $reconciledLegacyId) {
  79. $query->where($cursorColumn, '>=', $cutoffValue)->orWhereNull($cursorColumn)
  80. ->orWhere('id', '>', (int) $cursor['last_id']);
  81. // Old cursors skipped this ID range even when child bets existed. Catch it up once.
  82. if ($legacyBackfillMaxId > $reconciledLegacyId) {
  83. $query->orWhereBetween('id', [$reconciledLegacyId + 1, $legacyBackfillMaxId]);
  84. }
  85. });
  86. }
  87. }
  88. $query->orderBy('id')->chunkById(200, function ($orders) use ($process, $lastRun, &$scannedIds) {
  89. foreach ($orders as $order) {
  90. if ($lastRun) $scannedIds[(int) $order->id] = true;
  91. $process((int) $order->id);
  92. }
  93. });
  94. if ($cursorEnabled && count($result['errors']) === $errorCount) {
  95. $cursor = ['updated_at' => $startedAt, 'last_id' => $highestIdAtStart];
  96. if ($legacyBackfillMaxId > 0 || $reconciledLegacyId > 0) {
  97. $cursor['lottery_children_checked_through'] = max($legacyBackfillMaxId, $reconciledLegacyId);
  98. }
  99. DB::table('share_system_state')->updateOrInsert(['key' => 'facts_cursor:' . $table],
  100. ['value' => json_encode($cursor),
  101. 'updated_at' => $startedAt, 'created_at' => $startedAt]);
  102. }
  103. // Runs after the cursor is saved: a source that keeps failing here must not hold the cursor back.
  104. if ($lastRun && ($table !== 'lhc_order' || $hasLotteryItems)) {
  105. $this->repairFinishedOrders($table, $scannedIds, $process, $result);
  106. }
  107. }
  108. $result['changed_dates'] = array_values($result['changed_dates']);
  109. sort($result['changed_dates']);
  110. return $result;
  111. }
  112. /**
  113. * Re-sync finished orders whose facts are still open. An order whose repair changes nothing or fails
  114. * (quarantined source, a child bet that never settled) waits an hour before the next attempt, so it
  115. * is not re-locked and re-reported every minute.
  116. */
  117. private function repairFinishedOrders(string $table, array $scannedIds, callable $process, array &$result): void
  118. {
  119. $key = 'facts_repair_backoff:' . $table;
  120. $now = now()->timestamp;
  121. $stored = DB::table('share_system_state')->where('key', $key)->value('value');
  122. $backoff = $stored ? json_decode($stored, true, 512, JSON_THROW_ON_ERROR) : [];
  123. $next = [];
  124. foreach ($this->finishedOrdersWithOpenFacts($table) as $id) {
  125. if (isset($scannedIds[$id])) continue;
  126. if (($backoff[$id] ?? 0) > $now) { $next[$id] = $backoff[$id]; continue; }
  127. $changed = $result['created'] + $result['updated'];
  128. $errors = count($result['errors']);
  129. $process($id);
  130. if ($result['created'] + $result['updated'] === $changed || count($result['errors']) !== $errors) {
  131. $next[$id] = $now + self::REPAIR_BACKOFF_SECONDS;
  132. }
  133. }
  134. // Only orders still waiting are kept, so the state stays as small as the stuck set.
  135. if ($next !== $backoff) {
  136. $at = now()->setTimezone('Asia/Shanghai')->format('Y-m-d H:i:s');
  137. DB::table('share_system_state')->updateOrInsert(['key' => $key],
  138. ['value' => json_encode($next, JSON_FORCE_OBJECT), 'updated_at' => $at, 'created_at' => $at]);
  139. }
  140. }
  141. /**
  142. * Source orders that are already settled or refunded while their published facts are still open.
  143. *
  144. * melbet settles lottery and football orders with ThinkPHP `Model::where()->update()`, which does not
  145. * touch updated_at / update_time, so the cursor never sees a bet that settles more than a few minutes
  146. * after it was placed. Without this its fact stays unsettled and neither 笔笔返 nor 打码量 count it.
  147. *
  148. * @return list<int>
  149. */
  150. private function finishedOrdersWithOpenFacts(string $table): array
  151. {
  152. if (!in_array($table, ['lhc_order', 'sport_order', 'sport_game_order'], true)) return [];
  153. $ids = [];
  154. DB::table('share_bet_facts')->where('settled', 0)->where('voided', 0)
  155. ->where('source', $table === 'lhc_order' ? 'lhc_order_item' : $table)
  156. ->select(['id', 'source_id'])->orderBy('id')
  157. ->chunkById(1000, function ($facts) use ($table, &$ids) {
  158. $sourceIds = $facts->pluck('source_id')->filter(fn ($id) => ctype_digit((string) $id))->map(fn ($id) => (int) $id)->values()->all();
  159. if ($sourceIds === []) return;
  160. if ($table === 'lhc_order') {
  161. $query = DB::table('lhc_order')->where('lottery_status', '<>', 0)
  162. ->whereIn('ordernum', DB::table('lhc_order_item')->whereIn('id', $sourceIds)->distinct()->pluck('ordernum')->all());
  163. } elseif ($table === 'sport_order') {
  164. $query = DB::table('sport_order')->whereIn('id', $sourceIds)
  165. ->where(fn ($q) => $q->where('settlement_status', 1)->orWhere('status', 2)->orWhere('return_status', 2));
  166. } else {
  167. $query = DB::table('sport_game_order')->whereIn('id', $sourceIds)->whereIn('status', [1, 2, 3]);
  168. }
  169. foreach ($query->pluck('id') as $id) $ids[(int) $id] = true;
  170. });
  171. $ids = array_keys($ids);
  172. sort($ids);
  173. return $ids;
  174. }
  175. /** A source order and all of its child facts are one publication unit. */
  176. private function synchronizeOrder(string $table, int $id, ?string $from, ?string $to, bool $write): array
  177. {
  178. $operation = function () use ($table, $id, $from, $to, $write) {
  179. if ($write) {
  180. // Use the same first lock as settlement, relation binding and policy changes.
  181. $guard = DB::table('share_system_state')->where('key', 'relations_lock')->lockForUpdate()->first();
  182. if (!$guard) throw new RuntimeException('Sharing migration/relations lock is missing');
  183. $this->users = [];
  184. }
  185. // The chunk row may predate a lock wait or a concurrent source correction.
  186. $query = DB::table($table)->where('id', $id);
  187. $order = ($write ? $query->lockForUpdate() : $query)->first();
  188. if (!$order) throw new RuntimeException('Source order disappeared before synchronization');
  189. $result = ['created' => 0, 'updated' => 0, 'unchanged' => 0, 'skipped' => 0, 'changed_dates' => [], 'errors' => []];
  190. if ((int) ($order->is_faker ?? 0) === 1) { $result['skipped']++; return $result; }
  191. try {
  192. $facts = $table === 'lhc_order' ? $this->lotteryOrder($order, $write)['facts'] : [$this->singleOrder($table, $order)];
  193. } catch (\Throwable $e) {
  194. $isolated = $this->quarantine($table, $order, $e->getMessage(), $write);
  195. $result['updated'] = $isolated['updated'];
  196. $result['changed_dates'] = $isolated['changed_dates'];
  197. $result['skipped']++;
  198. $result['errors'][] = ['source' => $table, 'source_id' => (string) $id, 'reason' => $e->getMessage(),
  199. 'isolated_facts' => $isolated['updated']];
  200. return $result;
  201. }
  202. if ($facts === []) { $result['skipped']++; return $result; }
  203. foreach ($facts as $fact) {
  204. if ($fact === null || ($from !== null && $fact['bet_date'] < $from)
  205. || ($to !== null && $fact['bet_date'] > $to)) { $result['skipped']++; continue; }
  206. $change = $this->persist($fact, $write);
  207. $result[$change['status']]++;
  208. $result['changed_dates'] = array_merge($result['changed_dates'], $change['dates']);
  209. }
  210. return $result;
  211. };
  212. return $write ? DB::transaction($operation, 3) : $operation();
  213. }
  214. /** Also used by the guarded historical PC28 rebate recalculation. */
  215. public function lotteryOrder(object $order, bool $lock = false): array
  216. {
  217. $type = (int) ($order->type ?? 0);
  218. if (!isset(self::LOTTERY_NAMES[$type])) throw new RuntimeException('Unknown lottery type');
  219. $betAt = $this->time($order->created_at ?? null);
  220. $base = ['member_id' => (string) $order->member_id, 'bet_at' => $betAt, 'date' => EffectiveBet::newYorkDate($order->created_at ?? null),
  221. 'total_bet' => EffectiveBet::zero(), 'facts' => [], 'unsettled' => false];
  222. if (trim((string) ($order->ordernum ?? '')) === '') throw new RuntimeException('Missing lottery order number');
  223. if (DB::table('lhc_order')->where('ordernum', $order->ordernum)->count() !== 1) {
  224. throw new RuntimeException('Ambiguous lottery parent order number');
  225. }
  226. $itemQuery = DB::table('lhc_order_item')->where('ordernum', $order->ordernum)->orderBy('id');
  227. $items = ($lock ? $itemQuery->lockForUpdate() : $itemQuery)->get();
  228. if ($items->isEmpty()) throw new RuntimeException('Lottery order has no identifiable child bets');
  229. $bet = EffectiveBet::decimal($order->amount);
  230. if (bccomp($bet, '0', EffectiveBet::SCALE) <= 0) throw new RuntimeException('Lottery stake is not positive');
  231. $total = bcmul($bet, (string) $items->count(), EffectiveBet::SCALE);
  232. if (isset($order->total_amount) && bccomp((string) $order->total_amount, $total, EffectiveBet::SCALE) !== 0) {
  233. throw new RuntimeException('Lottery total does not match child stakes');
  234. }
  235. // Coupon discounts reduce what the member paid; payouts were computed on the full stake.
  236. $paidTotal = bcsub($total, EffectiveBet::decimal($order->coupon_discount ?? '0'), EffectiveBet::SCALE);
  237. $base['total_bet'] = $paidTotal;
  238. $refund = $this->refundAmount($order, [self::LOTTERY_NAMES[$type] . '退款', '投注退分']);
  239. if (bccomp($refund, '0', EffectiveBet::SCALE) > 0 && bccomp($refund, $paidTotal, EffectiveBet::SCALE) !== 0
  240. && !in_array((int) $order->lottery_status, [3, 4], true)) {
  241. throw new RuntimeException('Partial or inconsistent lottery refund requires review');
  242. }
  243. $parentVoid = in_array((int) $order->lottery_status, [3, 4], true) || bccomp($refund, '0', EffectiveBet::SCALE) > 0;
  244. $user = $this->user((string) $order->member_id);
  245. if ($user === null) return $base;
  246. foreach ($items as $item) {
  247. if ((string) ($item->member_id ?? '') !== (string) $order->member_id) throw new RuntimeException('Lottery child member mismatch');
  248. $void = $parentVoid || in_array((int) $item->lottery_status, [3, 4], true);
  249. $paid = bcsub($bet, EffectiveBet::decimal($item->coupon_discount ?? '0'), EffectiveBet::SCALE);
  250. $settled = !$void && in_array((int) $order->lottery_status, [1, 2], true)
  251. && in_array((int) $item->lottery_status, [1, 2], true);
  252. $base['unsettled'] = $base['unsettled'] || (!$settled && !$void);
  253. $profit = $settled ? ((int) $item->lottery_status === 1 ? bcsub('0', $paid, EffectiveBet::SCALE)
  254. : bcsub(EffectiveBet::decimal($item->win_amount ?? null), $paid, EffectiveBet::SCALE)) : EffectiveBet::zero();
  255. $base['facts'][] = $this->fact('lhc_order_item', (string) $item->id, $user, 'self:lottery', $betAt,
  256. $settled || $void ? $this->time($item->updated_at ?? $order->updated_at ?? null) : null,
  257. $paid, $profit, $settled, $void, $this->nativeCurrency());
  258. }
  259. return $base;
  260. }
  261. private function singleOrder(string $table, object $order): ?array
  262. {
  263. $previous = null;
  264. if ($table === 'third_game_orders' && !empty($order->order_key) && Schema::hasTable('share_bet_facts')) {
  265. $previous = DB::table('share_bet_facts')->where('source', $table)->where('source_id', $order->order_key)->first();
  266. }
  267. $member = (string) ($table === 'sport_order' ? $order->user_id : ($order->member_id ?? ''));
  268. $user = $this->user($member, $table === 'third_game_orders' ? ($order->user_id ?? $previous->user_id ?? null) : null);
  269. if ($user === null) return null;
  270. $sourceId = (string) $order->id;
  271. $void = false;
  272. if ($table === 'third_game_orders') {
  273. $sourceId = (string) ($order->order_key ?? '');
  274. if (!preg_match('/^[a-f0-9]{64}$/D', $sourceId)) throw new RuntimeException('Third-party order key is invalid');
  275. $type = (int) $order->game_type;
  276. $settled = (int) $order->status === 1;
  277. $void = in_array((int) $order->status, [2, 3], true);
  278. if (($type < 1 || $type > 7) && !$previous) throw new RuntimeException('Unknown third-party category');
  279. $category = $type >= 1 && $type <= 7 ? 'third:' . $type : $previous->category;
  280. $bet = EffectiveBet::decimal($order->bet_amount ?? (!$settled ? ($previous->bet_amount ?? '0') : null));
  281. $profit = $settled ? EffectiveBet::decimal($order->settled_amount) : EffectiveBet::zero();
  282. $betAt = $this->time($order->bet_time ?? $previous->bet_at ?? null);
  283. $settledAt = $settled || $void ? $this->time($order->last_update_time ?? $order->updated_at ?? null) : null;
  284. $currency = strtoupper(trim((string) ($order->currency ?? $previous->currency ?? '')));
  285. if ($currency === '') throw new RuntimeException('Third-party currency is missing');
  286. } else {
  287. $category = 'self:sport';
  288. // The member paid the stake minus any coupon discount; payouts were computed on the full stake.
  289. $bet = bcsub(EffectiveBet::decimal($order->amount), EffectiveBet::decimal($order->coupon_discount ?? '0'), EffectiveBet::SCALE);
  290. $betAt = $this->time($table === 'sport_order' ? ($order->create_time ?? null) : ($order->created_at ?? null));
  291. if ($table === 'sport_order') {
  292. $void = (int) $order->status === 2 || (int) ($order->return_status ?? 0) === 2
  293. || bccomp($this->refundAmount($order, ['体彩退款'], $member), '0', EffectiveBet::SCALE) > 0;
  294. $settled = !$void && (int) $order->status === 1 && (int) ($order->pay_status ?? 0) === 1
  295. && (int) ($order->settlement_status ?? 0) === 1;
  296. $profit = $settled ? bcsub(bcadd(EffectiveBet::decimal($order->win_amount ?? '0'),
  297. EffectiveBet::decimal($order->return_amount ?? '0'), EffectiveBet::SCALE), $bet, EffectiveBet::SCALE) : EffectiveBet::zero();
  298. $settledAt = $settled || $void ? $this->time($void
  299. ? (($order->return_operation_time ?? null) ?: ($order->update_time ?? null)) : ($order->settlement_time ?? null)) : null;
  300. } else {
  301. $void = (int) $order->status === 3 || bccomp($this->refundAmount($order, ['足球游戏退款']), '0', EffectiveBet::SCALE) > 0;
  302. $settled = !$void && in_array((int) $order->status, [1, 2], true);
  303. $profit = !$settled ? EffectiveBet::zero() : ((int) $order->status === 1 ? bcsub('0', $bet, EffectiveBet::SCALE)
  304. : bcsub(EffectiveBet::decimal($order->win_amount), $bet, EffectiveBet::SCALE));
  305. $settledAt = $settled || $void ? $this->time($order->updated_at ?? null) : null;
  306. }
  307. $currency = $this->nativeCurrency();
  308. }
  309. return $this->fact($table, $sourceId, $user, $category, $betAt, $settledAt, $bet, $profit, $settled, $void, $currency);
  310. }
  311. private function fact(string $source, string $id, object $user, string $category, string $betAt, ?string $settledAt,
  312. string $bet, string $profit, bool $settled, bool $void, string $currency): array
  313. {
  314. if (bccomp($bet, '0', EffectiveBet::SCALE) < 0) throw new RuntimeException('Negative stake');
  315. $fact = ['source' => $source, 'source_id' => $id, 'user_id' => (int) $user->id,
  316. 'member_id' => (string) $user->member_id, 'category' => $category, 'bet_at' => $betAt,
  317. 'bet_date' => substr($betAt, 0, 10), 'settled_at' => $settledAt, 'bet_amount' => $bet,
  318. 'net_profit' => $profit, 'effective_amount' => EffectiveBet::amount($bet, $profit, $settled, $void),
  319. 'settled' => $settled, 'voided' => $void, 'currency' => $currency];
  320. $fact['source_version'] = hash('sha256', json_encode($fact, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
  321. return $fact;
  322. }
  323. private function user(string $member, $userId = null): ?object
  324. {
  325. $key = $userId !== null ? 'id:' . $userId : 'member:' . $member;
  326. if (array_key_exists($key, $this->users)) return $this->users[$key];
  327. $query = DB::table('users');
  328. $rows = ($userId !== null ? $query->where('id', $userId) : $query->where('member_id', $member))->limit(2)->get();
  329. if ($rows->count() !== 1) throw new RuntimeException('User mapping is missing or ambiguous');
  330. $user = $rows->first();
  331. if ($member !== '' && (string) $user->member_id !== $member) throw new RuntimeException('User identity mismatch');
  332. return $this->users[$key] = ((int) ($user->from ?? 0) === 2 ? null : $user);
  333. }
  334. private function refundAmount(object $order, array $types, ?string $member = null): string
  335. {
  336. if (!Schema::hasTable('balance_logs')) return EffectiveBet::zero();
  337. return EffectiveBet::decimal(DB::table('balance_logs')->where('member_id', $member ?? $order->member_id)
  338. ->where('related_id', $order->id)->whereIn('change_type', $types)->where('amount', '>', 0)->sum('amount'));
  339. }
  340. private function time($value): string
  341. {
  342. return EffectiveBet::time($value)->setTimezone('Asia/Shanghai')->format('Y-m-d H:i:s');
  343. }
  344. private function nativeCurrency(): string
  345. {
  346. return strtoupper(trim((string) config('third_game.currency', 'CNY')));
  347. }
  348. private function persist(array $fact, bool $write): array
  349. {
  350. if ($write && DB::transactionLevel() === 0) {
  351. throw new RuntimeException('Fact publication requires its source order transaction');
  352. }
  353. $query = DB::table('share_bet_facts')->where('source', $fact['source'])->where('source_id', $fact['source_id']);
  354. $existing = ($write ? $query->lockForUpdate() : $query)->first();
  355. if ($existing && hash_equals((string) $existing->source_version, $fact['source_version'])) {
  356. return ['status' => 'unchanged', 'dates' => []];
  357. }
  358. $dates = array_values(array_unique(array_filter([$existing->bet_date ?? null, $fact['bet_date']])));
  359. if ($write) {
  360. $now = now()->setTimezone('Asia/Shanghai')->format('Y-m-d H:i:s');
  361. if ($existing) DB::table('share_bet_facts')->where('id', $existing->id)->update($fact + ['updated_at' => $now]);
  362. else DB::table('share_bet_facts')->insert($fact + ['created_at' => $now, 'updated_at' => $now]);
  363. $this->markDirty($dates, $now);
  364. }
  365. return ['status' => $existing ? 'updated' : 'created', 'dates' => $dates];
  366. }
  367. /** Only quarantine previously published facts identifiable from the current source row. */
  368. private function quarantine(string $table, object $order, string $reason, bool $write): array
  369. {
  370. if ($table === 'lhc_order') {
  371. if (trim((string) ($order->ordernum ?? '')) === '' || !Schema::hasTable('lhc_order_item')) {
  372. return ['updated' => 0, 'changed_dates' => []];
  373. }
  374. $items = DB::table('lhc_order_item')->where('ordernum', $order->ordernum)->orderBy('id');
  375. $ids = ($write ? $items->lockForUpdate() : $items)->pluck('id')->map(fn ($id) => (string) $id)->all();
  376. $source = 'lhc_order_item';
  377. } else {
  378. $ids = [(string) ($table === 'third_game_orders' ? ($order->order_key ?? '') : $order->id)];
  379. $source = $table;
  380. }
  381. $ids = array_values(array_filter($ids, fn ($id) => $id !== ''));
  382. if ($ids === []) return ['updated' => 0, 'changed_dates' => []];
  383. $query = DB::table('share_bet_facts')->where('source', $source)->whereIn('source_id', $ids)->orderBy('id');
  384. $facts = ($write ? $query->lockForUpdate() : $query)->get();
  385. $now = now()->setTimezone('Asia/Shanghai')->format('Y-m-d H:i:s');
  386. $updated = 0; $dates = [];
  387. foreach ($facts as $fact) {
  388. $version = hash('sha256', json_encode(['invalid_source' => $source, 'source_id' => $fact->source_id,
  389. 'reason' => $reason, 'order' => $order], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR));
  390. if ((string) $fact->source_version === $version && !(bool) $fact->settled
  391. && bccomp((string) $fact->effective_amount, '0', EffectiveBet::SCALE) === 0) continue;
  392. $updated++; $dates[] = $fact->bet_date;
  393. if ($write) DB::table('share_bet_facts')->where('id', $fact->id)->update([
  394. 'settled' => false, 'effective_amount' => EffectiveBet::zero(), 'source_version' => $version, 'updated_at' => $now]);
  395. }
  396. $dates = array_values(array_unique($dates));
  397. if ($write && $dates !== []) $this->markDirty($dates, $now);
  398. return ['updated' => $updated, 'changed_dates' => $dates];
  399. }
  400. private function markDirty(array $dates, string $now): void
  401. {
  402. DB::table('share_system_state')->insertOrIgnore(['key' => 'facts_dirty_dates', 'value' => '[]', 'created_at' => $now, 'updated_at' => $now]);
  403. $state = DB::table('share_system_state')->where('key', 'facts_dirty_dates')->lockForUpdate()->first();
  404. $dirty = json_decode($state->value, true, 512, JSON_THROW_ON_ERROR);
  405. $dirty = array_values(array_unique(array_merge($dirty, $dates)));
  406. sort($dirty);
  407. DB::table('share_system_state')->where('key', 'facts_dirty_dates')->update(['value' => json_encode($dirty), 'updated_at' => $now]);
  408. }
  409. }