ReportAdmin.php 11 KB

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