ReportSync.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. <?php
  2. namespace App\Services\Reporting;
  3. use App\Services\Sharing\BetFactSynchronizer;
  4. use App\Services\Sharing\EffectiveBet as Money;
  5. use Carbon\Carbon;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Schema;
  8. /** Reporting projections only. Never settles orders, moves money or publishes sharing facts. */
  9. class ReportSync
  10. {
  11. public const ORDER_SOURCES = ['lhc_order', 'sport_game_order', 'sport_order', 'third_game_orders', 'bets', 'jisu_game_order'];
  12. public const MONEY_SOURCES = ['balance_logs', 'withdraws', 'payment_orders', 'agent_withdrawals', 'agent_balance_logs', 'share_ledger', 'agent_rebate_records'];
  13. public function sync(bool $full = false): array
  14. {
  15. $result = ['scanned' => 0, 'published' => 0, 'errors' => 0, 'sources' => []];
  16. foreach (array_merge(self::ORDER_SOURCES, self::MONEY_SOURCES, ['lhc_order_item']) as $source) {
  17. if (!Schema::hasTable($source)) { $result['sources'][$source] = 'absent'; continue; }
  18. $start = now('Asia/Shanghai')->format('Y-m-d H:i:s');
  19. $state = DB::table('reporting_sync_state')->where('source', $source)->first();
  20. $cursor = $state ? json_decode($state->state, true, 512, JSON_THROW_ON_ERROR) : null;
  21. $query = DB::table($source); $hasUpdate = Schema::hasColumn($source, 'updated_at');
  22. $column = $source === 'sport_order' ? 'update_time' : 'updated_at';
  23. if (!$full && $cursor && ($hasUpdate || $source === 'sport_order')) {
  24. $cut = Carbon::parse($cursor['checked_at'], 'Asia/Shanghai')->subMinutes(5);
  25. $value = in_array($source, ['lhc_order', 'lhc_order_item', 'sport_order'], true) ? $cut->timestamp : $cut->format('Y-m-d H:i:s');
  26. $query->where(function ($q) use ($column, $value, $cursor) { $q->where($column, '>=', $value)->orWhereNull($column)->orWhere('id', '>', $cursor['last_id']); });
  27. } elseif (!$full && $cursor && in_array($source, ['share_ledger', 'agent_balance_logs'], true)) $query->where('id', '>', $cursor['last_id']);
  28. $max = (int) DB::table($source)->max('id'); $errors = 0;
  29. $query->where('id', '<=', $max)->orderBy('id')->chunkById(200, function ($rows) use ($source, &$result, &$errors) {
  30. foreach ($rows as $row) {
  31. ++$result['scanned'];
  32. try {
  33. if ($source === 'lhc_order_item') {
  34. $parents = DB::table('lhc_order')->where('ordernum', $row->ordernum)->limit(2)->get();
  35. if ($parents->count() !== 1) throw new \RuntimeException('六合彩子单对应的父单不明确');
  36. $this->publish('lhc_order', (int) $parents[0]->id);
  37. DB::table('reporting_errors')->where('source', $source)->where('source_id', (string) $row->id)->delete();
  38. } else $this->publish($source, (int) $row->id);
  39. ++$result['published'];
  40. }
  41. catch (\Throwable $e) {
  42. ++$errors; ++$result['errors'];
  43. DB::table('reporting_errors')->updateOrInsert(['source' => $source, 'source_id' => (string) $row->id],
  44. ['candidate_at' => $this->time($row->created_at ?? $row->create_time ?? null), 'reason' => mb_substr($e->getMessage(), 0, 500), 'created_at' => now(), 'updated_at' => now()]);
  45. }
  46. }
  47. });
  48. if (!$errors) DB::table('reporting_sync_state')->updateOrInsert(['source' => $source], ['state' => json_encode(['checked_at' => $start, 'last_id' => $max]), 'updated_at' => $start]);
  49. $result['sources'][$source] = $errors ? 'errors' : 'ready';
  50. }
  51. DB::table('reporting_sync_state')->updateOrInsert(['source' => '__run__'], ['state' => json_encode(['complete' => $result['errors'] === 0, 'sources' => $result['sources']]), 'updated_at' => now()]);
  52. return $result;
  53. }
  54. public function publish(string $source, int $id): void
  55. {
  56. if (!in_array($source, array_merge(self::ORDER_SOURCES, self::MONEY_SOURCES), true)) throw new \InvalidArgumentException('不支持的数据来源');
  57. DB::transaction(function () use ($source, $id) {
  58. $record = DB::table($source)->where('id', $id)->lockForUpdate()->first();
  59. if (!$record) throw new \RuntimeException('原记录不存在');
  60. $row = (array) $record;
  61. $member = $row['member_id'] ?? null;
  62. $virtual = $member !== null && DB::table('users')->where('member_id', (string) $member)->where('from', 2)->exists();
  63. if ($virtual) {
  64. DB::table('reporting_orders')->where('parent_source', $source)->where('parent_id', (string) $id)->delete();
  65. DB::table('reporting_events')->where('source', $source)->where('source_id', (string) $id)->delete();
  66. DB::table('reporting_errors')->where('source', $source)->where('source_id', (string) $id)->delete(); return;
  67. }
  68. if (in_array($source, self::ORDER_SOURCES, true)) $this->orders($source, $row);
  69. else $this->money($source, $row);
  70. DB::table('reporting_errors')->where('source', $source)->where('source_id', (string) $id)->delete();
  71. });
  72. }
  73. private function orders(string $source, array $row): void
  74. {
  75. $at = $this->time($row['created_at'] ?? $row['create_time'] ?? null);
  76. if ((int) ($row['is_faker'] ?? 0) === 1) { DB::table('reporting_orders')->where('parent_source', $source)->where('parent_id', (string) $row['id'])->delete(); return; }
  77. $facts = [];
  78. if (in_array($source, ['bets', 'jisu_game_order'], true)) {
  79. $identity = ReportContext::identity($row, $at ?? now()->toDateTimeString(), $source);
  80. if ($identity['user_id'] === null || $at === null) throw new \RuntimeException('旧订单缺少会员或下单时间');
  81. $bet = Money::decimal($row['amount']);
  82. $settled = $source === 'bets' ? (int) $row['status'] === 2 : in_array((int) $row['status'], [1, 2], true);
  83. $void = (int) $row['status'] === 3;
  84. $payout = $settled ? Money::decimal($source === 'bets' ? ($row['profit'] ?? 0) : ($row['win_amount'] ?? 0)) : Money::zero();
  85. $facts[] = ['source' => $source, 'source_id' => (string) $row['id'], 'user_id' => $identity['user_id'],
  86. 'category' => 'self:lottery', 'bet_at' => $at, 'bet_amount' => $bet, 'settled' => $settled, 'voided' => $void,
  87. 'net_profit' => $settled ? bcsub($payout, $bet, 10) : Money::zero(), 'currency' => $this->currency()];
  88. } else $facts = (new BetFactSynchronizer())->projectForReporting($source, (object) $row);
  89. $keys = [];
  90. foreach ($facts as $fact) {
  91. $identity = ReportContext::identity($row + ['report_user_id' => $fact['user_id']], $fact['bet_at'], $source);
  92. $context = DB::table('reporting_contexts')->where('source', $source)->where('source_id', (string) $row['id'])->first();
  93. $settledAt = $context->succeeded_at ?? null;
  94. if (!(bool) ($context->settlement_verified ?? false)) {
  95. if ($source === 'third_game_orders') $settledAt = $this->time($row['last_update_time'] ?? null);
  96. if ($source === 'sport_order') $settledAt = $this->time($row['settlement_time'] ?? null) ?? $this->time($row['return_operation_time'] ?? null) ?? $settledAt;
  97. }
  98. $settledAt = $fact['settled'] || $fact['voided'] ? $settledAt : null;
  99. $payout = $fact['settled'] ? bcadd($fact['bet_amount'], $fact['net_profit'], 10) : Money::zero();
  100. $refund = $fact['voided'] ? $fact['bet_amount'] : Money::zero();
  101. if ($source === 'sport_order' && $fact['settled']) {
  102. $refund = Money::decimal($row['return_amount'] ?? 0);
  103. if (bccomp($refund, '0', 10) < 0 || bccomp($refund, $fact['bet_amount'], 10) > 0) throw new \RuntimeException('部分退款金额不正确');
  104. $payout = bcsub($payout, $refund, 10);
  105. }
  106. if (bccomp($payout, '0', 10) < 0) throw new \RuntimeException('派奖金额不能为负');
  107. $key = ['source' => $fact['source'], 'source_id' => $fact['source_id']]; $keys[] = $fact['source_id'];
  108. $values = $identity + ['parent_source' => $source, 'parent_id' => (string) $row['id'], 'category' => $fact['category'],
  109. 'currency' => $source === 'third_game_orders' ? $fact['currency'] : $this->currency(), 'bet_at' => $fact['bet_at'], 'settled_at' => $settledAt,
  110. 'settlement_candidate_at' => $this->time($row['updated_at'] ?? $row['update_time'] ?? null),
  111. 'bet_amount' => $fact['bet_amount'], 'payout_amount' => $payout, 'net_profit' => $fact['net_profit'],
  112. 'refund_amount' => $refund, 'settled' => (int) $fact['settled'], 'voided' => (int) $fact['voided'],
  113. 'time_quality' => (!$fact['settled'] && !$fact['voided']) || $settledAt !== null ? 'confirmed' : 'missing_settlement_time'];
  114. $old = DB::table('reporting_orders')->where($key)->first();
  115. if (!$old) $values['created_at'] = now(); $values['updated_at'] = now();
  116. DB::table('reporting_orders')->updateOrInsert($key, $values);
  117. }
  118. DB::table('reporting_orders')->where('parent_source', $source)->where('parent_id', (string) $row['id'])->when($keys, fn ($q) => $q->whereNotIn('source_id', $keys))->delete();
  119. }
  120. private function money(string $source, array $row): void
  121. {
  122. $candidate = $this->time($row['created_at'] ?? null);
  123. if ($candidate === null) throw new \RuntimeException('资金记录缺少创建时间');
  124. $context = DB::table('reporting_contexts')->where('source', $source)->where('source_id', (string) $row['id'])->first();
  125. $at = $context->succeeded_at ?? null; $kind = null; $amount = null; $customerFee = Money::zero(); $configuredFee = null;
  126. $category = null; $identityRow = $row;
  127. if ($source === 'balance_logs') {
  128. $amount = Money::decimal($row['amount']); $type = (string) $row['change_type'];
  129. if (bccomp($amount, '0', 10) > 0 && in_array($type, ['充值', '三方充值'], true)) $kind = 'deposit';
  130. elseif (bccomp($amount, '0', 10) > 0 && in_array($type, ['注册赠送', '优惠活动', '即充即送', '充值返现', '老用户回归', '比比返', '笔笔返', '返水', '回水', '余额宝利息', '流水解冻'], true) && (int) ($row['type'] ?? 1) === 1) $kind = 'bonus';
  131. elseif ($type === '人工充值') $kind = isset($row['related_id']) && (string) $row['related_id'] === '0' ? 'bonus' : 'manual_credit';
  132. elseif ($type === '人工扣款') { $kind = 'manual_debit'; $amount = bcsub('0', $amount, 10); }
  133. elseif ($type === '分享佣金领取') {
  134. $claim = DB::table('share_claims')->where('credited_log_id', $row['id'])->where('status', 'approved')->first();
  135. if (!$claim) throw new \RuntimeException('分享领取缺少审核通过的原记录');
  136. $kind = 'share_commission';
  137. }
  138. $at = $candidate;
  139. if ($kind === 'deposit' && ($row['related_id'] ?? null)) {
  140. $origin = $type === '三方充值' ? 'payment_orders' : 'recharges';
  141. $originContext = DB::table('reporting_contexts')->where('source', $origin)->where('source_id', (string) $row['related_id'])->first();
  142. if ($originContext && !$context) $context = $originContext;
  143. if ($origin === 'payment_orders' && Schema::hasTable($origin)) {
  144. $original = DB::table($origin)->where('id', $row['related_id'])->where('member_id', $row['member_id'])->whereIn('type', [1, 3])->where('status', 2)->first();
  145. if ($original) $configuredFee = $original->fee ?? null;
  146. }
  147. }
  148. } elseif ($source === 'withdraws' && (int) $row['status'] === 1) {
  149. $kind = 'withdraw'; $rate = Money::decimal($row['exchange_rate']);
  150. if (bccomp($rate, '0', 10) <= 0) throw new \RuntimeException('提现历史汇率无效');
  151. $amount = isset($row['to_account']) && is_numeric($row['to_account']) ? bcmul((string) $row['to_account'], $rate, 10) : null;
  152. $customerFee = bcmul(Money::decimal($row['service_charge'] ?? 0), $rate, 10);
  153. } elseif ($source === 'payment_orders' && (int) $row['status'] === 2 && in_array((int) $row['type'], [2, 4], true)) {
  154. $kind = 'withdraw'; $amount = (int) $row['type'] === 2 ? Money::decimal($row['amount']) : null; $configuredFee = $row['fee'] ?? null;
  155. } elseif ($source === 'agent_withdrawals' && $row['status'] === 'paid') {
  156. $kind = 'agent_withdraw'; $amount = Money::decimal($row['actual_amount']); $customerFee = Money::decimal($row['fee'] ?? 0); $at = $this->time($row['paid_at'] ?? null);
  157. } elseif ($source === 'agent_balance_logs' && $row['type'] === 'commission' && $row['reference_type'] === 'agent_rebate_record') {
  158. $kind = 'agent_commission'; $amount = Money::decimal($row['amount']); $at = $candidate;
  159. $record = DB::table('agent_rebate_records')->where('id', $row['reference_id'])->first();
  160. if ($record) $category = $this->agentCategory((string) $record->platform, (int) $record->game_type);
  161. } elseif ($source === 'share_ledger') {
  162. $kind = 'share_accrual'; $amount = Money::decimal($row['amount']); $at = $row['bet_date'] . ' 00:00:00'; $category = $row['category'];
  163. $identityRow['report_user_id'] = $row['user_id'];
  164. } elseif ($source === 'agent_rebate_records') {
  165. $kind = 'agent_accrual'; $amount = Money::zero(); $at = $row['settlement_date'] . ' 00:00:00';
  166. foreach (['flow', 'profit'] as $part) $amount = bcadd($amount, (string) $row[$part . '_commission'], 10);
  167. $category = $this->agentCategory((string) $row['platform'], (int) $row['game_type']);
  168. }
  169. if (!$kind) {
  170. $existing = DB::table('reporting_events')->where('source', $source)->where('source_id', (string) $row['id'])->first();
  171. $verified = $existing ? DB::table('reporting_reconciliations')->where('event_id', $existing->id)->first() : null;
  172. if ($verified) {
  173. if (bccomp($verified->actual_amount, '0', 10) !== 0) throw new \RuntimeException('来源状态与已核实的收付款冲突,请重新核对');
  174. return; // Confirmed zero payout may still have an actual external fee; preserve its audit and event identity.
  175. }
  176. DB::table('reporting_events')->where('source', $source)->where('source_id', (string) $row['id'])->delete(); return;
  177. }
  178. $identity = ReportContext::identity($identityRow, $at ?? $candidate, $source);
  179. if ($context) $identity = ['user_id' => $context->user_id, 'agent_id' => $context->agent_id, 'inviter_id' => $context->inviter_id,
  180. 'client_platform' => $context->client_platform, 'attribution_quality' => $context->attribution_quality];
  181. if (in_array($source, ['agent_withdrawals', 'agent_balance_logs', 'agent_rebate_records'], true)) $identity['agent_id'] = (int) $row['agent_id'];
  182. if ($identity['user_id'] === null && $identity['agent_id'] === null) throw new \RuntimeException('资金记录没有可识别的归属');
  183. $key = ['source' => $source, 'source_id' => (string) $row['id'], 'kind' => $kind];
  184. $old = DB::table('reporting_events')->where($key)->first();
  185. $values = $identity + ['category' => $category, 'currency' => $this->currency(), 'amount' => $amount,
  186. 'customer_fee' => $customerFee, 'configured_fee' => $configuredFee, 'occurred_at' => $at, 'candidate_at' => $candidate, 'updated_at' => now()];
  187. if (!$old) $values['created_at'] = now();
  188. DB::table('reporting_events')->updateOrInsert($key, $values);
  189. }
  190. private function agentCategory(string $platform, int $type): ?string
  191. {
  192. if ($platform === 'sport') return 'self:sport';
  193. if (in_array($platform, ['lhc', 'jisu', 'pc28'], true)) return 'self:lottery';
  194. return $type >= 1 && $type <= 7 && $platform !== 'legacy' ? 'third:' . $type : null;
  195. }
  196. public function currency(): string { return strtoupper((string) config('reporting.currency', 'CNY')); }
  197. public function time($value): ?string
  198. {
  199. if ($value === null || $value === '' || $value === 0 || $value === '0') return null;
  200. try { return Money::time($value)->setTimezone('Asia/Shanghai')->format('Y-m-d H:i:s'); } catch (\Throwable $e) { return null; }
  201. }
  202. }