ReportAdmin.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. <?php
  2. namespace App\Services\Reporting;
  3. use App\Services\OperationAuditService;
  4. use App\Services\Sharing\ShareMemberQualification;
  5. use App\Services\ThirdGameCommissionService;
  6. use App\Support\MaintenancePolicy;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Validator;
  9. use Illuminate\Validation\Rule;
  10. use Illuminate\Validation\ValidationException;
  11. class ReportAdmin
  12. {
  13. public function options(): array
  14. {
  15. return ['report_types' => ['business' => '营业报表', 'promotion' => '推广报表', 'sharing' => '分享赚钱'],
  16. 'categories' => ['all' => '所有订单'] + MaintenancePolicy::CATEGORIES,
  17. 'category_hidden_fields' => ReportReader::TOTAL_ONLY_FIELDS,
  18. 'platforms' => ['all', 'H5', 'PC', 'APP', 'unknown'], 'settlement_statuses' => ['all', 'pending', 'settled'],
  19. 'ranking_metrics' => ['deposit_amount', 'bet_amount', 'payout_amount', 'withdraw_amount', 'activity_minutes'],
  20. 'timezone' => 'Asia/Shanghai', 'currency' => (new ReportSync())->currency(), 'max_days' => 366,
  21. 'rules' => ['profit' => '已结算游戏毛利-三方游戏平台抽成-实发优惠-代理佣金-分享佣金-实际平台手续费',
  22. 'net_cash_flow' => '成功收款-实际对外打款-实际平台手续费', 'valid_member' => '范围内期间非撤销投注会员,按查询结束日已生效的分享赚钱规则,累计成功存款及累计已结算非撤销同币种有效投注均大于或等于对应门槛;累计包含查询开始日前记录,不受装置及游戏分类筛选影响',
  23. 'online_rate' => '期间活跃会员/范围内期末真实会员', 'public_costs' => '公共资金和成本只在所有订单展示,未知值为null']];
  24. }
  25. public function settings(?array $input = null): array
  26. {
  27. if ($input !== null) {
  28. throw ValidationException::withMessages(['valid_deposit_min' => '报表有效会员条件统一使用分享赚钱配置,请通过 /admin/shareEarning/settings/save 修改;报表设置仅供只读兼容']);
  29. }
  30. $settings = (array) DB::table('reporting_settings')->where('id', 1)->first();
  31. $policy = (new ShareMemberQualification())->read(now('Asia/Shanghai')->toDateString(), false)['policy_meta'];
  32. return array_replace($settings, ['valid_deposit_min' => $policy['min_deposit'], 'valid_effective_bet_min' => $policy['min_effective_bet'],
  33. 'valid_member_policy' => $policy]);
  34. }
  35. public function reconciliations(array $input): array
  36. {
  37. $p = Validator::make($input, ['page' => ['integer', 'min:1', 'max:1000000'], 'limit' => ['integer', 'min:1', 'max:100'],
  38. 'status' => ['nullable', Rule::in(['all', 'pending', 'verified'])], 'kind' => ['nullable', Rule::in(['deposit', 'withdraw', 'agent_withdraw'])]])->validate();
  39. $query = DB::table('reporting_events as e')->leftJoin('reporting_reconciliations as r', 'r.event_id', '=', 'e.id')->whereIn('e.kind', ['deposit', 'withdraw', 'agent_withdraw']);
  40. if (($p['status'] ?? 'all') === 'pending') $query->whereNull('r.id');
  41. if (($p['status'] ?? 'all') === 'verified') $query->whereNotNull('r.id');
  42. if (!empty($p['kind'])) $query->where('e.kind', $p['kind']);
  43. $total = (clone $query)->count();
  44. return ['total' => $total, 'data' => $query->select('e.*', 'r.actual_amount', 'r.external_fee', 'r.occurred_at as verified_at', 'r.evidence')
  45. ->orderByDesc('e.id')->forPage((int) ($p['page'] ?? 1), (int) ($p['limit'] ?? 20))->get()->map(fn ($r) => (array) $r)->all()];
  46. }
  47. public function reconcile(array $input): array
  48. {
  49. $rules = ['event_id' => ['required', 'integer', 'min:1'], 'actual_amount' => ['required', 'regex:/^\d{1,14}(?:\.\d{1,10})?$/D'],
  50. 'external_fee' => ['required', 'regex:/^\d{1,14}(?:\.\d{1,10})?$/D'], 'occurred_at' => ['required', 'date_format:Y-m-d H:i:s', 'before_or_equal:' . now('Asia/Shanghai')->toDateTimeString()],
  51. 'currency' => ['required', Rule::in([(new ReportSync())->currency()])], 'evidence' => ['required', 'string', 'max:1000']] + $this->attributionRules();
  52. $data = Validator::make($input, $rules)->validate();
  53. if (trim($data['evidence']) === '') throw ValidationException::withMessages(['evidence' => '请填写凭据或核对依据']);
  54. return DB::transaction(function () use ($data) {
  55. $event = DB::table('reporting_events')->where('id', $data['event_id'])->lockForUpdate()->first();
  56. if (!$event || !in_array($event->kind, ['deposit', 'withdraw', 'agent_withdraw'], true)) throw ValidationException::withMessages(['event_id' => '只能核对真实收付款记录']);
  57. $before = (array) DB::table('reporting_reconciliations')->where('event_id', $event->id)->first();
  58. $values = array_diff_key($data, array_flip(['agent_id', 'inviter_id', 'client_platform'])) + ['operator_id' => (int) (request()->user->id ?? 0), 'updated_at' => now()->toDateTimeString()];
  59. if (!$before) $values['created_at'] = now()->toDateTimeString();
  60. DB::table('reporting_reconciliations')->updateOrInsert(['event_id' => $event->id], $values);
  61. $attribution = $this->verifyAttribution($event->source, $event->source_id, (array) $event, $data, $event->candidate_at);
  62. if ($attribution) DB::table('reporting_events')->where('id', $event->id)->update($attribution);
  63. $after = (array) DB::table('reporting_reconciliations')->where('event_id', $event->id)->first();
  64. OperationAuditService::record('reporting_payment', (int) $event->id, $before ? 'update' : 'create', $before + ['event_attribution' => (array) $event], $after + ['event_attribution' => $attribution]);
  65. return $after;
  66. });
  67. }
  68. public function reconcileOrder(array $input): array
  69. {
  70. $data = Validator::make($input, ['id' => ['required', 'integer', 'min:1'],
  71. 'settled_at' => ['sometimes', 'required', 'date_format:Y-m-d H:i:s', 'before_or_equal:' . now('Asia/Shanghai')->toDateTimeString()],
  72. 'evidence' => ['required', 'string', 'max:1000']] + $this->attributionRules())->validate();
  73. if (trim($data['evidence']) === '') throw ValidationException::withMessages(['evidence' => '请填写核对依据']);
  74. return DB::transaction(function () use ($data) {
  75. $order = DB::table('reporting_orders')->where('id', $data['id'])->lockForUpdate()->first();
  76. if (!$order || (isset($data['settled_at']) && ((!$order->settled && !$order->voided) || $data['settled_at'] < $order->bet_at))) {
  77. throw ValidationException::withMessages(['id' => '已结算或撤销订单才能补录有效的结算时间']);
  78. }
  79. $before = (array) $order;
  80. $attribution = $this->verifyAttribution($order->parent_source, $order->parent_id, (array) $order, $data, $order->bet_at);
  81. if (!isset($data['settled_at']) && !$attribution) throw ValidationException::withMessages(['id' => '请提供核对时间或归属信息']);
  82. if ($attribution) DB::table('reporting_orders')->where('parent_source', $order->parent_source)->where('parent_id', $order->parent_id)->update($attribution);
  83. if (isset($data['settled_at'])) {
  84. $context = DB::table('reporting_contexts')->where('source', $order->parent_source)->where('source_id', $order->parent_id)->first();
  85. if (!$context) DB::table('reporting_contexts')->insert(['source' => $order->parent_source, 'source_id' => $order->parent_id,
  86. 'user_id' => $order->user_id, 'agent_id' => $order->agent_id, 'inviter_id' => $order->inviter_id,
  87. 'client_platform' => $order->client_platform, 'attribution_quality' => $order->attribution_quality,
  88. 'settlement_verified' => true, 'occurred_at' => $order->bet_at, 'succeeded_at' => $data['settled_at']]);
  89. else DB::table('reporting_contexts')->where('id', $context->id)->update(['succeeded_at' => $data['settled_at'], 'settlement_verified' => true]);
  90. DB::table('reporting_orders')->where('parent_source', $order->parent_source)->where('parent_id', $order->parent_id)
  91. ->where(function ($q) { $q->where('settled', 1)->orWhere('voided', 1); })
  92. ->update(['settled_at' => $data['settled_at'], 'time_quality' => 'confirmed', 'updated_at' => now()]);
  93. }
  94. OperationAuditService::record('reporting_order_time', (int) $order->id, 'update', $before, $data);
  95. return (array) DB::table('reporting_orders')->where('id', $order->id)->first();
  96. });
  97. }
  98. public function quality(array $input): array
  99. {
  100. $p = Validator::make($input, ['page' => ['integer', 'min:1', 'max:1000000'], 'limit' => ['integer', 'min:1', 'max:100']])->validate();
  101. return ['total' => DB::table('reporting_errors')->count(), 'data' => DB::table('reporting_errors')->orderByDesc('id')
  102. ->forPage((int) ($p['page'] ?? 1), (int) ($p['limit'] ?? 20))->get()->map(fn ($r) => (array) $r)->all(),
  103. 'sources' => DB::table('reporting_sync_state')->where('source', '<>', ThirdGameCommissionService::BACKFILL_STATE)
  104. ->orderBy('source')->get()->map(fn ($r) => ['source' => $r->source, 'state' => json_decode($r->state, true), 'updated_at' => $r->updated_at])->all()];
  105. }
  106. private function attributionRules(): array
  107. {
  108. return ['agent_id' => ['sometimes', 'nullable', 'integer', 'exists:agents,id'], 'inviter_id' => ['sometimes', 'nullable', 'integer', 'exists:users,id'],
  109. 'client_platform' => ['sometimes', 'required', Rule::in(['H5', 'PC', 'APP', 'unknown'])]];
  110. }
  111. private function verifyAttribution(string $source, string $sourceId, array $row, array $data, string $at): array
  112. {
  113. $values = array_intersect_key($data, array_flip(['agent_id', 'inviter_id', 'client_platform']));
  114. if (!$values) return [];
  115. if (empty($row['user_id']) && (array_key_exists('agent_id', $values) || array_key_exists('inviter_id', $values))) {
  116. throw ValidationException::withMessages(['agent_id' => '不能改写代理账户实际收付款接收人']);
  117. }
  118. if (isset($values['inviter_id']) && (int) $values['inviter_id'] === (int) $row['user_id']) {
  119. throw ValidationException::withMessages(['inviter_id' => '不能将会员自己设为邀请人']);
  120. }
  121. $context = (array) DB::table('reporting_contexts')->where('source', $source)->where('source_id', $sourceId)->lockForUpdate()->first();
  122. if (!$context) $context = ['source' => $source, 'source_id' => $sourceId, 'user_id' => $row['user_id'],
  123. 'agent_id' => $row['agent_id'], 'inviter_id' => $row['inviter_id'], 'client_platform' => $row['client_platform'], 'occurred_at' => $at, 'succeeded_at' => null];
  124. $context = array_replace($context, $values);
  125. $context['attribution_quality'] = array_key_exists('agent_id', $values) ? 'verified' : ($context['attribution_quality'] ?? $row['attribution_quality']);
  126. unset($context['id']);
  127. DB::table('reporting_contexts')->updateOrInsert(['source' => $source, 'source_id' => $sourceId], $context);
  128. return $values + ['attribution_quality' => $context['attribution_quality']];
  129. }
  130. }