PromotionService.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <?php
  2. namespace App\Services;
  3. use App\Models\PromotionActivity;
  4. use App\Models\BalanceLog;
  5. use App\Models\User;
  6. use App\Models\Wallet;
  7. use App\Support\PromotionRules as Rules;
  8. use App\Support\PromotionTranslations;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Schema;
  11. use Illuminate\Validation\ValidationException;
  12. /** Backend jobs and deposit awards. Member HTTP APIs are owned by melbet_sport-api. */
  13. class PromotionService
  14. {
  15. private PromotionFacts $facts;
  16. public function __construct(?PromotionFacts $facts = null) { $this->facts = $facts ?? new PromotionFacts(); }
  17. public static function publish(PromotionActivity $activity): void
  18. {
  19. if (!Rules::supports((int)$activity->type)) return;
  20. $now = PromotionFacts::now();
  21. DB::table('promotion_campaigns')->insertOrIgnore(['activity_id' => $activity->id, 'first_published_at' => null, 'created_at' => $now, 'updated_at' => $now]);
  22. if ((int)$activity->status === 1) DB::table('promotion_campaigns')->where('activity_id', $activity->id)->whereNull('first_published_at')
  23. ->update(['first_published_at' => $now, 'updated_at' => $now]);
  24. }
  25. private function invalid(string $message): void { throw ValidationException::withMessages(['promotion' => $message]); }
  26. private function json($value): array { return is_array($value) ? $value : (json_decode((string)$value, true) ?: []); }
  27. private function rules(PromotionActivity $activity): array { return Rules::normalize((int)$activity->type, $this->json($activity->params)); }
  28. private function money(int $cents): string { return bcdiv((string)$cents, '100', 2); }
  29. public function heartbeat(int $userId, string $token, string $platform): array
  30. {
  31. $this->member($userId);
  32. $now = PromotionFacts::now(); $bucket = substr($now, 0, 16) . ':00';
  33. DB::table('promotion_presence')->insertOrIgnore(['user_id' => $userId, 'session_hash' => hash('sha256', $token . ':' . $platform), 'observed_at' => $bucket]);
  34. return ['recorded' => true, 'server_time' => $now, 'interval_seconds' => 60];
  35. }
  36. public function listing(int $userId, string $platform, string $lang = 'zh', ?int $type = null): array
  37. {
  38. $member = $this->member($userId); $context = ActivityEligibilityService::memberContext($member->member_id);
  39. $q = PromotionActivity::where('status', 1)->where('start_time', '<=', now()->timestamp)->where('end_time', '>=', now()->timestamp);
  40. if ($type !== null) $q->where('type', $type);
  41. $data = [];
  42. foreach ($q->orderByDesc('sort')->orderByDesc('id')->get() as $activity) {
  43. $text = PromotionTranslations::select($activity->toArray(), $lang);
  44. if (!$text) continue;
  45. if (!ActivityEligibilityService::isPublishedOn($activity, $platform)) continue;
  46. $eligibility = ActivityEligibilityService::evaluate($activity, $context);
  47. if (!$eligibility['is_eligible'] && !$activity->show_ineligible) continue;
  48. $item = ['activity_id' => $activity->id, 'type' => (int)$activity->type, 'type_name' => $activity->type_name,
  49. 'start_time' => (int)$activity->start_time, 'end_time' => (int)$activity->end_time, 'rules' => $this->rules($activity)] + $text + $eligibility;
  50. if ((int) $activity->type === Rules::FIRST_DEPOSIT) $item['image'] = $activity->image;
  51. $data[] = $item;
  52. }
  53. return ['total' => count($data), 'data' => $data];
  54. }
  55. private function activity(int $id, bool $lock = false): PromotionActivity
  56. {
  57. $query = PromotionActivity::where('id', $id);
  58. $row = ($lock ? $query->lockForUpdate() : $query)->first();
  59. if (!$row || !Rules::supports((int)$row->type)) $this->invalid('活动不存在');
  60. return $row;
  61. }
  62. private function member(int $id): User
  63. {
  64. $member = User::find($id);
  65. if (!$member || (int)$member->from === 2 || !empty($member->getAttributes()['delete_time']) || (int)($member->getAttributes()['is_banned'] ?? 0) === 1) $this->invalid('会员不可参与活动');
  66. return $member;
  67. }
  68. private function open(PromotionActivity $activity, User $member, ?string $platform = null): string
  69. {
  70. $now = now('Asia/Shanghai')->timestamp;
  71. if ((int)$activity->status !== 1 || (int)$activity->getRawOriginal('start_time') > $now || (int)$activity->getRawOriginal('end_time') < $now) $this->invalid('活动未上架或不在活动时间内');
  72. $eligibility = ActivityEligibilityService::evaluate($activity, ActivityEligibilityService::memberContext($member->member_id));
  73. if (!$eligibility['is_eligible']) $this->invalid($eligibility['ineligible_reason']);
  74. if ($platform !== null && !ActivityEligibilityService::isPublishedOn($activity, $platform)) $this->invalid('此客户端不可参与该活动');
  75. $published = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  76. if (!$published) $this->invalid('活动尚未正式开启');
  77. return $published;
  78. }
  79. private function mutate(int $activityId, int $userId, callable $callback): array
  80. {
  81. return DB::transaction(function () use ($activityId, $userId, $callback) {
  82. $member = $this->member($userId);
  83. $wallet = Wallet::where('member_id', $member->member_id)->lockForUpdate()->first();
  84. if (!$wallet) $this->invalid('会员钱包不存在');
  85. $activity = $this->activity($activityId, true);
  86. return $callback($activity, $member, $wallet);
  87. }, 3);
  88. }
  89. private function account(PromotionActivity $activity, User $member): object
  90. {
  91. $now = PromotionFacts::now();
  92. DB::table('promotion_accounts')->insertOrIgnore(['activity_id' => $activity->id, 'user_id' => $member->id,
  93. 'round_no' => 1, 'spins' => 0, 'created_at' => $now, 'updated_at' => $now]);
  94. return DB::table('promotion_accounts')->where('activity_id', $activity->id)->where('user_id', $member->id)->lockForUpdate()->first();
  95. }
  96. private function newRound(object $account, string $start, array $completed = [], bool $reset = false): object
  97. {
  98. $now = PromotionFacts::now();
  99. DB::table('promotion_rounds')->insert(['account_id' => $account->id, 'round_no' => $account->round_no,
  100. 'coins_cents' => 0, 'status' => 'active', 'started_at' => $start,
  101. 'deposit_cursor' => $reset ? (int)DB::table('balance_logs')->max('id') : 0,
  102. 'bet_cursors' => json_encode($reset ? $this->facts->cursors() : []), 'completed_tasks' => json_encode($completed), 'created_at' => $now, 'updated_at' => $now]);
  103. return $this->round($account);
  104. }
  105. private function round(object $account): ?object
  106. {
  107. return DB::table('promotion_rounds')->where('account_id', $account->id)->where('round_no', $account->round_no)->lockForUpdate()->first();
  108. }
  109. public function detail(int $activityId, int $userId, ?string $platform = null, ?string $lang = null): array
  110. {
  111. $activity = $this->activity($activityId); $member = $this->member($userId);
  112. $this->open($activity, $member, $platform);
  113. $account = DB::table('promotion_accounts')->where('activity_id', $activityId)->where('user_id', $userId)->first();
  114. $round = $account ? DB::table('promotion_rounds')->where('account_id', $account->id)->where('round_no', $account->round_no)->first() : null;
  115. return $this->state($activity, $member, $account, $round, $lang);
  116. }
  117. public function progress(int $activityId, int $userId, ?string $platform = null, ?string $lang = null): array
  118. {
  119. return $this->mutate($activityId, $userId, function ($activity, $member) use ($platform, $lang) {
  120. return $this->facts->snapshot(function () use ($activity, $member, $platform, $lang) {
  121. [$account, $round] = $this->refreshProgress($activity, $member, $platform);
  122. return $this->state($activity, $member, $account, $round, $lang);
  123. });
  124. });
  125. }
  126. /** Background synchronization needs task writes, without building member-facing daily metrics. */
  127. public function syncAccount(int $activityId, int $userId): void
  128. {
  129. $this->mutate($activityId, $userId, fn ($activity, $member) => $this->facts->snapshot(
  130. fn () => $this->refreshProgress($activity, $member)
  131. ));
  132. }
  133. private function refreshProgress(PromotionActivity $activity, User $member, ?string $platform = null): array
  134. {
  135. $start = $this->open($activity, $member, $platform); $account = $this->account($activity, $member); $round = null;
  136. if ((int)$activity->type === Rules::WHEEL) {
  137. $round = $this->round($account) ?? $this->newRound($account, $start);
  138. if ($round->status === 'active') $this->refreshWheel($activity, $member, $account, $round);
  139. }
  140. return [$account, $round];
  141. }
  142. public function apply(int $activityId, int $userId, ?string $platform = null, ?string $lang = null): array
  143. {
  144. return $this->mutate($activityId, $userId, function ($activity, $member) use ($platform, $lang) {
  145. $start = $this->open($activity, $member, $platform);
  146. if ((int)$activity->type !== Rules::LOSS) $this->invalid('只有净亏邀请活动需要申请');
  147. $account = $this->account($activity, $member);
  148. if (!$account->applied_at) {
  149. $start = $this->lossStart($account, $start);
  150. $rules = $this->rules($activity); $policy = $this->facts->policy();
  151. $profit = $this->facts->betting([$member->id], $start)['profit'];
  152. $loss = bccomp($profit, '0', 10) < 0 ? bcsub('0', $profit, 10) : '0';
  153. if (bccomp($loss, $rules['loss_amount'], 10) < 0) $this->invalid('尚未达到净亏申请门槛');
  154. $account->applied_at = PromotionFacts::now();
  155. $account->application_snapshot = json_encode(['loss' => $loss, 'from' => $start, 'policy' => $policy, 'rules' => $rules,
  156. 'invite_user_cursor' => (int)DB::table('users')->max('id')]);
  157. DB::table('promotion_accounts')->where('id', $account->id)->update(['applied_at' => $account->applied_at,
  158. 'application_snapshot' => $account->application_snapshot, 'updated_at' => PromotionFacts::now()]);
  159. }
  160. return $this->state($activity, $member, $account, null, $lang);
  161. });
  162. }
  163. private function lossInvitees(User $member, object $account): array
  164. {
  165. if (!$account->applied_at) return [];
  166. $policy = $this->facts->policy(); $qualified = []; $snapshot = $this->json($account->application_snapshot);
  167. foreach ($this->facts->children($member->id) as $child) {
  168. if ((int)$child['id'] > ($snapshot['invite_user_cursor'] ?? 0) && $child['created_at'] >= $account->applied_at && $child['bound_at'] >= $account->applied_at && $this->facts->qualified($child, $policy)) $qualified[] = (int)$child['id'];
  169. }
  170. return $qualified;
  171. }
  172. /** Each loss-invite round counts net loss from the previous claim; the first round from the campaign's first publication. */
  173. private function lossStart(object $account, string $published): string
  174. {
  175. if ((int)$account->round_no <= 1) return $published;
  176. return (string)(DB::table('promotion_rewards')->where('account_id', $account->id)->where('round_no', (int)$account->round_no - 1)->value('created_at') ?: $published);
  177. }
  178. private function grantTask(object $account, object $round, string $task, string $event, array $evidence, array &$known): bool
  179. {
  180. $key = $task . ':' . $event;
  181. if (isset($known[$key])) return false;
  182. $inserted = DB::table('promotion_task_grants')->insertOrIgnore(['account_id' => $account->id, 'round_no' => $round->round_no,
  183. 'task' => $task, 'event_key' => $event, 'evidence' => json_encode($evidence), 'created_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]);
  184. $known[$key] = true;
  185. if ($inserted) { ++$account->spins; DB::table('promotion_accounts')->where('id', $account->id)->update(['spins' => $account->spins, 'updated_at' => PromotionFacts::now()]); }
  186. return $inserted > 0;
  187. }
  188. private function refreshWheel(PromotionActivity $activity, User $member, object $account, object $round): void
  189. {
  190. $this->facts->snapshot(fn () => $this->refreshWheelTasks($activity, $member, $account, $round));
  191. }
  192. private function refreshWheelTasks(PromotionActivity $activity, User $member, object $account, object $round): void
  193. {
  194. $rules = $this->rules($activity); $policy = $this->facts->policy();
  195. $completed = $this->json($round->completed_tasks);
  196. $grants = DB::table('promotion_task_grants')->where('account_id', $account->id)
  197. ->where(fn ($q) => $q->where('round_no', $round->round_no)->orWhereIn('task', ['login', 'online']))->get();
  198. $known = [];
  199. foreach ($grants as $grant) $known[$grant->task . ':' . $grant->event_key] = true;
  200. $roundGrants = $grants->where('round_no', $round->round_no)->groupBy('task');
  201. $campaignStart = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  202. // Daily tasks are campaign-wide. They survive round reset, but never grant twice on one day.
  203. foreach ($this->facts->logins($member->member_id, $campaignStart) as $day => $_) {
  204. $this->grantTask($account, $round, 'login', $day, ['day' => $day], $known); $completed['login'] = true;
  205. }
  206. foreach ($this->facts->online($member->id, $campaignStart) as $day => $seconds) if ($seconds >= $rules['online_seconds']) {
  207. $this->grantTask($account, $round, 'online', $day, ['day' => $day, 'seconds' => $seconds], $known); $completed['online'] = true;
  208. }
  209. $children = $this->facts->children($member->id);
  210. $newInvite = false;
  211. foreach ($children as $child) {
  212. if ($this->facts->qualified($child, $policy) && !$this->facts->qualified($child, $policy, $round->started_at)) {
  213. $newInvite = $this->grantTask($account, $round, 'invite', (string)$child['id'], ['user_id' => $child['id'], 'policy' => $policy], $known) || $newInvite;
  214. }
  215. }
  216. // Only a grant belonging to this round can satisfy its resettable invitation task.
  217. $completed['invite'] = $newInvite; $childrenById = array_column($children, null, 'id');
  218. foreach ($roundGrants->get('invite', []) as $grant) {
  219. $evidence = $this->json($grant->evidence); $child = $childrenById[$evidence['user_id']] ?? null;
  220. if ($child && $this->facts->qualified($child, $evidence['policy'])) $completed['invite'] = true;
  221. }
  222. $cursors = $this->json($round->bet_cursors);
  223. $teamDeposits = $teamBets = [];
  224. foreach ($children as $child) {
  225. $from = max($round->started_at, $child['bound_at']);
  226. foreach ($this->facts->deposits([$child['member_id']], $from, null, $round->deposit_cursor) as $day => $amount) $teamDeposits[$day] = bcadd($teamDeposits[$day] ?? '0', $amount, 10);
  227. foreach ($this->facts->betting([$child['id']], $from, null, $cursors)['effective'] as $day => $amount) $teamBets[$day] = bcadd($teamBets[$day] ?? '0', $amount, 10);
  228. }
  229. $metrics = [
  230. 'deposit' => $this->facts->deposits([$member->member_id], $round->started_at, null, $round->deposit_cursor),
  231. 'team_deposit' => $teamDeposits,
  232. 'bet' => $this->facts->betting([$member->id], $round->started_at, null, $cursors)['effective'],
  233. 'team_bet' => $teamBets,
  234. ];
  235. foreach ($metrics as $task => $days) {
  236. // Recompute qualification after corrections; daily amounts never carry across midnight.
  237. $completed[$task] = false;
  238. foreach ($days as $day => $amount) if (bccomp($amount, $rules[$task . '_amount'], 10) >= 0) {
  239. $this->grantTask($account, $round, $task, $round->round_no . ':' . $day, ['day' => $day, 'amount' => $amount, 'target' => $rules[$task . '_amount']], $known); $completed[$task] = true;
  240. }
  241. foreach ($roundGrants->get($task, []) as $grant) {
  242. $proof = $this->json($grant->evidence);
  243. if (bccomp($days[$proof['day']] ?? '0', $proof['target'] ?? $rules[$task . '_amount'], 10) >= 0) $completed[$task] = true;
  244. }
  245. }
  246. $encoded = json_encode($completed);
  247. if ($encoded !== $round->completed_tasks) DB::table('promotion_rounds')->where('id', $round->id)->update(['completed_tasks' => $encoded, 'updated_at' => PromotionFacts::now()]);
  248. $round->completed_tasks = $encoded;
  249. }
  250. /** $budget defaults to $amount; coupon rewards also charge the invitee coupons they issue. */
  251. private function reserve(PromotionActivity $activity, User $member, object $account, int $roundNo, string $amount, array $rules, ?string $budget = null): object
  252. {
  253. $budget ??= $amount;
  254. $this->capacity($activity, $member, $budget);
  255. $received = DB::table('promotion_rewards')->where('activity_id', $activity->id)->where('user_id', $member->id)->exists();
  256. DB::table('promotion_rewards')->insert(['activity_id' => $activity->id, 'user_id' => $member->id, 'account_id' => $account->id,
  257. 'round_no' => $roundNo, 'amount' => $amount,
  258. 'required_flow' => ($rules['reward_mode'] ?? 'cash') === 'coupon' ? '0.00' : bcmul($amount, $rules['turnover_ratio'], 2),
  259. 'status' => 'reserved', 'rule_snapshot' => json_encode($rules), 'created_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]);
  260. if (!$received) ++$activity->rewarded_count;
  261. $activity->budget_used = bcadd((string)$activity->budget_used, $budget, 2); $activity->save();
  262. return DB::table('promotion_rewards')->where('account_id', $account->id)->where('round_no', $roundNo)->first();
  263. }
  264. private function capacity(PromotionActivity $activity, User $member, string $amount): void
  265. {
  266. $received = DB::table('promotion_rewards')->where('activity_id', $activity->id)->where('user_id', $member->id)->exists();
  267. if (!$received && $activity->reward_quota !== null && (int)$activity->rewarded_count >= (int)$activity->reward_quota) $this->invalid('活动获奖份数已用完');
  268. if ($activity->budget !== null && bccomp(bcadd((string)$activity->budget_used, $amount, 2), (string)$activity->budget, 2) > 0) $this->invalid('活动奖励额度不足');
  269. }
  270. public function spin(int $activityId, int $userId, string $requestKey, ?string $platform = null): array
  271. {
  272. return $this->mutate($activityId, $userId, function ($activity, $member) use ($requestKey, $platform) {
  273. $account = $this->account($activity, $member);
  274. $previous = DB::table('promotion_spins')->where('account_id', $account->id)->where('request_key', $requestKey)->first();
  275. if ($previous) return ['spin' => $this->spinRow($previous), 'spins' => $account->spins, 'replayed' => true];
  276. $start = $this->open($activity, $member, $platform);
  277. if ((int)$activity->type !== Rules::WHEEL) $this->invalid('该活动不是转盘活动');
  278. $round = $this->round($account) ?? $this->newRound($account, $start);
  279. if ($round->status !== 'active') $this->invalid('本轮已达到666,请先领取');
  280. $this->refreshWheel($activity, $member, $account, $round);
  281. if ($account->spins < 1) $this->invalid('抽奖次数不足');
  282. $rules = $this->rules($activity); $flags = $this->json($round->completed_tasks);
  283. $complete = count(array_filter(array_intersect_key($flags, array_flip(Rules::TASKS)))) === count(Rules::TASKS);
  284. // Capacity is checked before random sampling; a winning outcome is reserved immediately.
  285. if ($complete && bccomp($rules['completion_probability'], '0', 2) > 0) $this->capacity($activity, $member, '666.00');
  286. $draw = Rules::draw((int)$round->coins_cents, $complete, $rules['completion_probability']);
  287. if ($draw['reached']) $this->reserve($activity, $member, $account, $round->round_no, '666.00', $rules);
  288. $coins = $round->coins_cents + $draw['amount_cents']; $now = PromotionFacts::now();
  289. $id = DB::table('promotion_spins')->insertGetId(['account_id' => $account->id, 'round_no' => $round->round_no, 'request_key' => $requestKey,
  290. 'prize_index' => $draw['prize_index'], 'amount_cents' => $draw['amount_cents'], 'coins_cents' => $coins,
  291. 'conditions_complete' => $complete, 'probability' => $complete ? $rules['completion_probability'] : '0.00', 'created_at' => $now, 'updated_at' => $now]);
  292. DB::table('promotion_rounds')->where('id', $round->id)->update(['coins_cents' => $coins, 'status' => $draw['reached'] ? 'reached' : 'active', 'updated_at' => $now]);
  293. --$account->spins;
  294. DB::table('promotion_accounts')->where('id', $account->id)->update(['spins' => $account->spins, 'updated_at' => $now]);
  295. return ['spin' => $this->spinRow(DB::table('promotion_spins')->where('id', $id)->first()), 'spins' => $account->spins, 'replayed' => false];
  296. });
  297. }
  298. private function pay(object $reward, User $member, Wallet $wallet): object
  299. {
  300. if ($reward->status !== 'reserved') return $reward;
  301. $frozen = bccomp((string)$reward->required_flow, '0', 2) > 0;
  302. $field = $frozen ? 'frozen_balance' : 'available_balance';
  303. $before = (string)$wallet->$field; $wallet->$field = bcadd($before, (string)$reward->amount, 10); $wallet->save();
  304. $log = BalanceLog::create(['member_id' => $member->member_id, 'type' => $frozen ? 2 : 1, 'change_type' => '优惠活动',
  305. 'amount' => $reward->amount, 'before_balance' => $before, 'after_balance' => $wallet->$field, 'related_id' => $reward->id,
  306. // Frozen promotion rewards are intentionally unlocked by this service, never by the legacy 1x list.
  307. 'frozen_status' => $frozen ? 1 : null, 'remark' => '新活动奖励; activity=' . $reward->activity_id . '; round=' . $reward->round_no]);
  308. $now = PromotionFacts::now();
  309. DB::table('promotion_rewards')->where('id', $reward->id)->update(['status' => $frozen ? 'locked' : 'paid', 'credited_log_id' => $log->id,
  310. 'flow_snapshot' => json_encode(['from' => $now, 'cursors' => $this->facts->cursors()]), 'updated_at' => $now]);
  311. return DB::table('promotion_rewards')->where('id', $reward->id)->first();
  312. }
  313. /** Coupon rewards credit no money; the reserved face value is consumed by the coupons themselves. */
  314. private function issueCoupons(object $reward, User $member): object
  315. {
  316. if ($reward->status !== 'reserved') return $reward;
  317. $rules = $this->json($reward->rule_snapshot); $now = PromotionFacts::now();
  318. $holders = [[(int)$member->id, (string)$member->member_id, 'inviter', $rules['inviter_coupons']]];
  319. foreach (DB::table('users')->whereIn('id', $rules['coupon_invitees'] ?: [0])->orderBy('id')->get(['id', 'member_id']) as $child) {
  320. $holders[] = [(int)$child->id, (string)$child->member_id, 'invitee', $rules['invitee_coupons']];
  321. }
  322. $rows = [];
  323. foreach ($holders as [$userId, $memberId, $role, $tiers]) {
  324. $seq = 0;
  325. foreach ($tiers as $tier) for ($i = 0; $i < $tier['quantity']; $i++) {
  326. $rows[] = ['activity_id' => $reward->activity_id, 'reward_id' => $reward->id, 'user_id' => $userId, 'member_id' => $memberId,
  327. 'role' => $role, 'inviter_user_id' => $member->id, 'seq' => ++$seq, 'min_amount' => $tier['min_amount'], 'discount' => $tier['discount'],
  328. 'categories' => json_encode($rules['coupon_categories']), 'valid_from' => $rules['coupon_valid_from'], 'valid_until' => $rules['coupon_valid_until'],
  329. 'status' => 'unused', 'created_at' => $now, 'updated_at' => $now];
  330. }
  331. }
  332. foreach (array_chunk($rows, 500) as $chunk) DB::table('promotion_coupons')->insertOrIgnore($chunk);
  333. DB::table('promotion_rewards')->where('id', $reward->id)->update(['status' => 'paid', 'updated_at' => $now]);
  334. return DB::table('promotion_rewards')->where('id', $reward->id)->first();
  335. }
  336. public function claim(int $activityId, int $userId, ?int $roundNo = null, ?string $platform = null): array
  337. {
  338. return $this->mutate($activityId, $userId, function ($activity, $member, $wallet) use ($roundNo, $platform) {
  339. $account = $this->account($activity, $member);
  340. // Loss invite ignores the client's round: it claims the current round, or replays the last claim when a retry
  341. // arrives after the account already moved on to an unapplied next round.
  342. if ((int)$activity->type === Rules::LOSS) $roundNo = (int)$account->round_no - (!$account->applied_at && (int)$account->round_no > 1 ? 1 : 0);
  343. elseif ($roundNo === null) $this->invalid('round_no必须为正整数');
  344. $reward = DB::table('promotion_rewards')->where('account_id', $account->id)->where('round_no', $roundNo)->lockForUpdate()->first();
  345. if ($reward && $reward->status !== 'reserved') return ['reward' => (array)$reward, 'round_no' => $account->round_no, 'spins' => $account->spins, 'replayed' => true];
  346. if ((int)$activity->type === Rules::LOSS) {
  347. $this->open($activity, $member, $platform);
  348. if ($roundNo !== (int)$account->round_no || !$account->applied_at) $this->invalid('请先申请活动');
  349. $snapshot = $this->json($account->application_snapshot); $rules = $snapshot['rules'];
  350. $qualified = $this->lossInvitees($member, $account);
  351. if (count($qualified) < $rules['invite_count']) $this->invalid('有效邀请人数不足');
  352. // The application is cleared for the next round, so the reward keeps it for history.
  353. $history = ['qualified_invitees' => $qualified, 'application' => ['applied_at' => $account->applied_at] + array_diff_key($snapshot, ['rules' => true])];
  354. if (($rules['reward_mode'] ?? 'cash') === 'coupon') {
  355. // Exactly the invitees counted toward the target receive invitee coupons, earliest registrations first.
  356. sort($qualified); $counted = array_slice($qualified, 0, $rules['invite_count']);
  357. // The reward amount is the inviter's own coupons; invitee coupons only count toward the budget.
  358. $own = Rules::faceValue($rules['inviter_coupons']);
  359. $total = bcadd($own, bcmul(Rules::faceValue($rules['invitee_coupons']), (string)count($counted), 2), 2);
  360. $reward ??= $this->reserve($activity, $member, $account, $roundNo, $own, $rules + $history + ['coupon_invitees' => $counted, 'coupon_face_value' => $total], $total);
  361. } else $reward ??= $this->reserve($activity, $member, $account, $roundNo, $rules['reward_amount'], $rules + $history);
  362. } elseif ((int)$activity->type === Rules::WHEEL) {
  363. // A reserved, earned reward remains payable after the campaign is unpublished.
  364. $round = $this->round($account);
  365. if (!$reward || !$round || $round->round_no !== $roundNo || $round->status !== 'reached') $this->invalid('本轮尚未达到666');
  366. } else $this->invalid('首充奖励由充值成功后自动发放');
  367. $reward = ($this->json($reward->rule_snapshot)['reward_mode'] ?? 'cash') === 'coupon' ? $this->issueCoupons($reward, $member) : $this->pay($reward, $member, $wallet);
  368. if ((int)$activity->type === Rules::LOSS) {
  369. // Loss invite repeats: the next round needs a new application, net loss from now and new invitees.
  370. ++$account->round_no;
  371. DB::table('promotion_accounts')->where('id', $account->id)->update(['round_no' => $account->round_no, 'applied_at' => null,
  372. 'application_snapshot' => null, 'updated_at' => PromotionFacts::now()]);
  373. }
  374. if ((int)$activity->type === Rules::WHEEL) {
  375. $flags = array_intersect_key($this->json($round->completed_tasks), array_flip(Rules::DAILY));
  376. DB::table('promotion_rounds')->where('id', $round->id)->update(['status' => 'claimed', 'claimed_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]);
  377. ++$account->round_no;
  378. DB::table('promotion_accounts')->where('id', $account->id)->update(['round_no' => $account->round_no, 'updated_at' => PromotionFacts::now()]);
  379. $this->newRound($account, PromotionFacts::now(), $flags, true);
  380. }
  381. return ['reward' => (array)$reward, 'round_no' => $account->round_no, 'spins' => $account->spins, 'replayed' => false];
  382. });
  383. }
  384. public function onDeposit(BalanceLog $deposit): void
  385. {
  386. if (!DB::connection()->getSchemaBuilder()->hasTable('promotion_first_deposits') || (int)$deposit->type !== 1 || !in_array($deposit->change_type, ['充值', '三方充值'], true) || bccomp((string)$deposit->amount, '0', 10) <= 0) return;
  387. $member = User::where('member_id', $deposit->member_id)->first();
  388. if (!$member || (int)$member->from === 2) return;
  389. DB::transaction(function () use ($member, $deposit) {
  390. $wallet = Wallet::where('member_id', $member->member_id)->lockForUpdate()->first();
  391. if (!$wallet) $this->invalid('会员钱包不存在');
  392. $first = DB::table('balance_logs')->where('member_id', $member->member_id)->where('type', 1)->where('amount', '>', 0)
  393. ->whereIn('change_type', ['充值', '三方充值'])->orderBy('created_at')->orderBy('id')->value('id');
  394. if ((int)$first !== (int)$deposit->id) return;
  395. $inserted = DB::table('promotion_first_deposits')->insertOrIgnore(['user_id' => $member->id, 'deposit_log_id' => $deposit->id,
  396. 'created_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]);
  397. if (!$inserted) return;
  398. $activities = PromotionActivity::where('type', Rules::FIRST_DEPOSIT)->where('status', 1)->where('start_time', '<=', now()->timestamp)
  399. ->where('end_time', '>=', now()->timestamp)->orderByDesc('sort')->orderByDesc('id')->get();
  400. foreach ($activities as $candidate) {
  401. $activity = $this->activity($candidate->id, true);
  402. if (!PromotionTranslations::select($activity->toArray(), $member->language ?: 'zh')) continue;
  403. if ((int)$activity->status !== 1 || (int)$activity->type !== Rules::FIRST_DEPOSIT) continue;
  404. $published = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  405. $creditedAt = (string)$deposit->getRawOriginal('created_at');
  406. if (!$published || $creditedAt < $published || strtotime($creditedAt) < (int)$activity->start_time || strtotime($creditedAt) > (int)$activity->end_time) continue;
  407. if (!ActivityEligibilityService::evaluate($activity, ActivityEligibilityService::memberContext($member->member_id))['is_eligible']) continue;
  408. $rules = $this->rules($activity);
  409. if (bccomp((string)$deposit->amount, $rules['min_deposit'], 10) < 0) continue;
  410. try { $this->capacity($activity, $member, $rules['reward_amount']); } catch (ValidationException $e) { continue; }
  411. $account = $this->account($activity, $member);
  412. $reward = $this->reserve($activity, $member, $account, 1, $rules['reward_amount'], $rules + ['deposit_log_id' => $deposit->id]);
  413. $this->pay($reward, $member, $wallet); break;
  414. }
  415. }, 3);
  416. }
  417. private function state(PromotionActivity $activity, User $member, ?object $account, ?object $round, ?string $lang = null): array
  418. {
  419. $rules = $this->rules($activity); $type = (int)$activity->type;
  420. $text = PromotionTranslations::select($activity->toArray(), $lang ?? ($member->language ?: 'zh'));
  421. if (!$text) $this->invalid('活动未配置所选语言');
  422. $result = ['activity_id' => $activity->id, 'type' => $type, 'rules' => $rules, 'account_id' => $account->id ?? null,
  423. 'round_no' => $account->round_no ?? 1, 'spins' => $account->spins ?? 0, 'server_time' => PromotionFacts::now()] + $text;
  424. if ($type === Rules::WHEEL) {
  425. $flags = $round ? $this->json($round->completed_tasks) : [];
  426. $result += ['coins' => $this->money($round->coins_cents ?? 0), 'remaining' => $this->money(66600 - ($round->coins_cents ?? 0)),
  427. 'status' => $round->status ?? 'not_started', 'completed_tasks' => $flags,
  428. 'conditions_complete' => count(array_filter(array_intersect_key($flags, array_flip(Rules::TASKS)))) === 7,
  429. 'prizes' => Rules::PRIZES, 'valid_member_policy' => $this->facts->policy(),
  430. 'ordinary_pool_rule' => '固定奖项仅在累计后小于666时参与普通奖池;普通奖池可用奖项等概率,浮动奖项按分等概率取值。'];
  431. $today = substr(PromotionFacts::now(), 0, 10);
  432. $result['today_granted_tasks'] = $account ? DB::table('promotion_task_grants')->where('account_id', $account->id)
  433. ->where(function ($q) use ($today, $account) { $q->where('event_key', $today)->orWhere('event_key', $account->round_no . ':' . $today); })->pluck('task')->all() : [];
  434. $result['tasks'] = $this->wheelToday($activity, $member, $account, $round, $flags, $result['today_granted_tasks']);
  435. } elseif ($type === Rules::LOSS) {
  436. $start = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  437. if ($account && $start) $start = $this->lossStart($account, $start);
  438. $profit = $this->facts->betting([$member->id], $start)['profit'];
  439. $result += ['loss' => bccomp($profit, '0', 10) < 0 ? bcsub('0', $profit, 2) : '0.00', 'applied_at' => $account->applied_at ?? null,
  440. 'qualified_invitees' => $account ? count($this->lossInvitees($member, $account)) : 0, 'valid_member_policy' => $this->facts->policy()];
  441. } else {
  442. $result['has_deposited'] = DB::table('balance_logs')->where('member_id', $member->member_id)->where('type', 1)->where('amount', '>', 0)->whereIn('change_type', ['充值', '三方充值'])->exists();
  443. }
  444. $result['rewards'] = $account ? DB::table('promotion_rewards')->where('account_id', $account->id)->orderByDesc('round_no')->limit(10)->get()->map(fn ($r) => (array)$r)->all() : [];
  445. if ($type === Rules::LOSS) {
  446. // Applications made before coupon mode existed snapshot cash rules without the coupon keys.
  447. if ($account?->applied_at) $result['rules'] = array_replace(Rules::defaults(Rules::LOSS), $this->json($account->application_snapshot)['rules']);
  448. $result['coupons'] = $this->couponSummary((int)$activity->id, (int)$member->id);
  449. // Status is for the current round; earlier rounds are in rewards.
  450. $result['status'] = !$account?->applied_at ? 'not_applied' : ($result['qualified_invitees'] >= $result['rules']['invite_count'] ? 'ready' : 'collecting');
  451. $result['loss_from'] = $start;
  452. }
  453. return $result;
  454. }
  455. /** The member's own coupons from this activity, grouped by tier. */
  456. private function couponSummary(int $activityId, int $userId): array
  457. {
  458. return DB::table('promotion_coupons')->where('activity_id', $activityId)->where('user_id', $userId)
  459. ->selectRaw("role, min_amount, discount, valid_from, valid_until, count(*) as quantity, sum(case when status = 'unused' then 1 else 0 end) as unused")
  460. ->groupBy('role', 'min_amount', 'discount', 'valid_from', 'valid_until')->orderBy('role')->orderBy('min_amount')->get()
  461. ->map(fn ($r) => ['role' => $r->role, 'min_amount' => (string)$r->min_amount, 'discount' => (string)$r->discount, 'valid_from' => $r->valid_from,
  462. 'valid_until' => $r->valid_until, 'quantity' => (int)$r->quantity, 'unused' => (int)$r->unused])->all();
  463. }
  464. private function wheelToday(PromotionActivity $activity, User $member, ?object $account, ?object $round, array $flags, array $granted): array
  465. {
  466. $rules = $this->rules($activity); $today = substr(PromotionFacts::now(), 0, 10);
  467. $published = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  468. $dailyFrom = max($published, $today . ' 00:00:00'); $from = max($round->started_at ?? $published, $dailyFrom);
  469. $cursors = $round ? $this->json($round->bet_cursors) : []; $cursor = (int)($round->deposit_cursor ?? 0);
  470. $online = $this->facts->online($member->id, $dailyFrom); $logins = $this->facts->logins($member->member_id, $dailyFrom);
  471. $values = ['online' => $online[$today] ?? 0, 'login' => isset($logins[$today]) ? 1 : 0,
  472. 'invite' => $account ? DB::table('promotion_task_grants')->where('account_id', $account->id)->where('round_no', $account->round_no)->where('task', 'invite')->count() : 0,
  473. 'deposit' => $this->facts->total($this->facts->deposits([$member->member_id], $from, null, $cursor)),
  474. 'team_deposit' => '0', 'bet' => $this->facts->total($this->facts->betting([$member->id], $from, null, $cursors)['effective']), 'team_bet' => '0'];
  475. foreach ($this->facts->children($member->id) as $child) {
  476. $childFrom = max($from, $child['bound_at']);
  477. $values['team_deposit'] = bcadd($values['team_deposit'], $this->facts->total($this->facts->deposits([$child['member_id']], $childFrom, null, $cursor)), 10);
  478. $values['team_bet'] = bcadd($values['team_bet'], $this->facts->total($this->facts->betting([$child['id']], $childFrom, null, $cursors)['effective']), 10);
  479. }
  480. $tasks = [];
  481. foreach (Rules::TASKS as $key) {
  482. $target = match ($key) { 'online' => $rules['online_seconds'], 'login', 'invite' => 1, default => $rules[$key . '_amount'] };
  483. $tasks[] = ['key' => $key, 'round_completed' => (bool)($flags[$key] ?? false), 'value' => $values[$key], 'target' => $target,
  484. 'today_rewarded' => in_array($key, $granted, true), 'reward_spins' => 1,
  485. 'remaining_seconds' => $key === 'online' ? max(0, $target - $values[$key]) : null];
  486. }
  487. return $tasks;
  488. }
  489. private function spinRow(object $row): array
  490. {
  491. return ['id' => $row->id, 'round_no' => $row->round_no, 'prize_index' => $row->prize_index, 'prize' => Rules::PRIZES[$row->prize_index],
  492. 'amount' => $this->money($row->amount_cents), 'coins' => $this->money($row->coins_cents), 'reached' => (int)$row->coins_cents === 66600,
  493. 'conditions_complete' => (bool)$row->conditions_complete, 'probability' => (string)$row->probability, 'created_at' => $row->created_at];
  494. }
  495. public function records(int $activityId, int $userId, int $page = 1, int $limit = 20): array
  496. {
  497. $this->activity($activityId); $this->member($userId);
  498. $account = DB::table('promotion_accounts')->where('activity_id', $activityId)->where('user_id', $userId)->first();
  499. if (!$account) return ['total' => 0, 'data' => []];
  500. $q = DB::table('promotion_spins')->where('account_id', $account->id);
  501. return ['total' => $q->count(), 'data' => $q->orderByDesc('id')->forPage($page, $limit)->get()->map(fn ($r) => $this->spinRow($r))->all()];
  502. }
  503. public function broadcasts(int $activityId): array
  504. {
  505. $activity = $this->activity($activityId);
  506. if ((int)$activity->type !== Rules::WHEEL) $this->invalid('该活动不是转盘活动');
  507. $q = DB::table('promotion_spins as s')->join('promotion_accounts as a', 'a.id', '=', 's.account_id')->join('users as u', 'u.id', '=', 'a.user_id')
  508. ->where('a.activity_id', $activityId);
  509. $map = fn ($r) => ['account' => substr((string)$r->member_id, 0, strlen((string)$r->member_id) >= 10 ? 4 : 1) . '****' . substr((string)$r->member_id, -1),
  510. 'amount' => $this->money($r->amount_cents), 'created_at' => $r->created_at];
  511. return ['ordinary' => (clone $q)->orderByDesc('s.id')->limit(50)->get(['u.member_id', 's.amount_cents', 's.created_at'])->map($map)->all(),
  512. 'reached_666' => $q->where('s.coins_cents', 66600)->orderByDesc('s.id')->limit(50)->get(['u.member_id', 's.amount_cents', 's.created_at'])->map(fn ($r) => array_replace($map($r), ['amount' => '666.00']))->all()];
  513. }
  514. public function rewards(int $activityId, int $userId, int $page = 1, int $limit = 20): array
  515. {
  516. $this->activity($activityId); $this->member($userId);
  517. $q = DB::table('promotion_rewards')->where('activity_id', $activityId)->where('user_id', $userId);
  518. return ['total' => $q->count(), 'data' => $q->orderByDesc('id')->forPage($page, $limit)->get()];
  519. }
  520. public function unlock(int $userId): int
  521. {
  522. return DB::transaction(function () use ($userId) {
  523. $member = $this->member($userId); $wallet = Wallet::where('member_id', $member->member_id)->lockForUpdate()->first();
  524. if (!$wallet) return 0;
  525. $count = 0;
  526. foreach (DB::table('promotion_rewards')->where('user_id', $userId)->where('status', 'locked')->orderBy('id')->lockForUpdate()->get() as $reward) {
  527. $snapshot = $this->json($reward->flow_snapshot);
  528. $effective = $this->facts->total($this->facts->betting([$userId], $snapshot['from'], null, $snapshot['cursors'])['effective']);
  529. if (bccomp($effective, (string)$reward->required_flow, 10) < 0) continue;
  530. if (bccomp((string)$wallet->frozen_balance, (string)$reward->amount, 10) < 0) $this->invalid('冻结奖励余额不足');
  531. $beforeFrozen = (string)$wallet->frozen_balance; $before = (string)$wallet->available_balance;
  532. $wallet->frozen_balance = bcsub($beforeFrozen, (string)$reward->amount, 10); $wallet->available_balance = bcadd($before, (string)$reward->amount, 10); $wallet->save();
  533. BalanceLog::create(['member_id' => $member->member_id, 'type' => 2, 'change_type' => '流水解冻', 'amount' => bcsub('0', (string)$reward->amount, 2),
  534. 'before_balance' => $beforeFrozen, 'after_balance' => $wallet->frozen_balance, 'related_id' => $reward->id, 'remark' => '新活动奖励解冻']);
  535. $log = BalanceLog::create(['member_id' => $member->member_id, 'type' => 1, 'change_type' => '流水解冻', 'amount' => $reward->amount,
  536. 'before_balance' => $before, 'after_balance' => $wallet->available_balance, 'related_id' => $reward->id, 'remark' => '新活动奖励解冻']);
  537. DB::table('balance_logs')->where('id', $reward->credited_log_id)->update(['frozen_status' => 2]);
  538. DB::table('promotion_rewards')->where('id', $reward->id)->update(['status' => 'paid', 'unlocked_log_id' => $log->id, 'unlocked_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]); ++$count;
  539. }
  540. return $count;
  541. }, 3);
  542. }
  543. }