PromotionService.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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 Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Schema;
  10. use Illuminate\Validation\ValidationException;
  11. /** One wallet writer for both clients. Wallet -> activity -> account is the lock order. */
  12. class PromotionService
  13. {
  14. private PromotionFacts $facts;
  15. public function __construct(?PromotionFacts $facts = null) { $this->facts = $facts ?? new PromotionFacts(); }
  16. public static function publish(PromotionActivity $activity): void
  17. {
  18. if (!Rules::supports((int)$activity->type)) return;
  19. $now = PromotionFacts::now();
  20. DB::table('promotion_campaigns')->insertOrIgnore(['activity_id' => $activity->id, 'first_published_at' => null, 'created_at' => $now, 'updated_at' => $now]);
  21. if ((int)$activity->status === 1) DB::table('promotion_campaigns')->where('activity_id', $activity->id)->whereNull('first_published_at')
  22. ->update(['first_published_at' => $now, 'updated_at' => $now]);
  23. }
  24. private function invalid(string $message): void { throw ValidationException::withMessages(['promotion' => $message]); }
  25. private function json($value): array { return is_array($value) ? $value : (json_decode((string)$value, true) ?: []); }
  26. private function rules(PromotionActivity $activity): array { return Rules::normalize((int)$activity->type, $this->json($activity->params)); }
  27. private function money(int $cents): string { return bcdiv((string)$cents, '100', 2); }
  28. public function heartbeat(int $userId, string $token, string $platform): array
  29. {
  30. $this->member($userId);
  31. $now = PromotionFacts::now(); $bucket = substr($now, 0, 16) . ':00';
  32. DB::table('promotion_presence')->insertOrIgnore(['user_id' => $userId, 'session_hash' => hash('sha256', $token . ':' . $platform), 'observed_at' => $bucket]);
  33. return ['recorded' => true, 'server_time' => $now, 'interval_seconds' => 60];
  34. }
  35. public function listing(int $userId, string $platform, string $lang = 'zh', ?int $type = null): array
  36. {
  37. $member = $this->member($userId); $context = ActivityEligibilityService::memberContext($member->member_id);
  38. $q = PromotionActivity::where('status', 1)->where('lang', $lang)->where('start_time', '<=', now()->timestamp)->where('end_time', '>=', now()->timestamp);
  39. if ($type !== null) $q->where('type', $type);
  40. $data = [];
  41. foreach ($q->orderByDesc('sort')->orderByDesc('id')->get() as $activity) {
  42. if (!ActivityEligibilityService::isPublishedOn($activity, $platform)) continue;
  43. $eligibility = ActivityEligibilityService::evaluate($activity, $context);
  44. if (!$eligibility['is_eligible'] && !$activity->show_ineligible) continue;
  45. $data[] = ['activity_id' => $activity->id, 'type' => (int)$activity->type, 'type_name' => $activity->type_name,
  46. 'title' => $activity->title, 'sub_title' => $activity->sub_title, 'image' => $activity->image, 'content' => $activity->content,
  47. 'start_time' => (int)$activity->start_time, 'end_time' => (int)$activity->end_time, 'rules' => $this->rules($activity)] + $eligibility;
  48. }
  49. return ['total' => count($data), 'data' => $data];
  50. }
  51. private function activity(int $id, bool $lock = false): PromotionActivity
  52. {
  53. $query = PromotionActivity::where('id', $id);
  54. $row = ($lock ? $query->lockForUpdate() : $query)->first();
  55. if (!$row || !Rules::supports((int)$row->type)) $this->invalid('活动不存在');
  56. return $row;
  57. }
  58. private function member(int $id): User
  59. {
  60. $member = User::find($id);
  61. if (!$member || (int)$member->from === 2 || !empty($member->getAttributes()['delete_time']) || (int)($member->getAttributes()['is_banned'] ?? 0) === 1) $this->invalid('会员不可参与活动');
  62. return $member;
  63. }
  64. private function open(PromotionActivity $activity, User $member, ?string $platform = null): string
  65. {
  66. $now = now('Asia/Shanghai')->timestamp;
  67. if ((int)$activity->status !== 1 || (int)$activity->getRawOriginal('start_time') > $now || (int)$activity->getRawOriginal('end_time') < $now) $this->invalid('活动未上架或不在活动时间内');
  68. $eligibility = ActivityEligibilityService::evaluate($activity, ActivityEligibilityService::memberContext($member->member_id));
  69. if (!$eligibility['is_eligible']) $this->invalid($eligibility['ineligible_reason']);
  70. if ($platform !== null && !ActivityEligibilityService::isPublishedOn($activity, $platform)) $this->invalid('此客户端不可参与该活动');
  71. $published = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  72. if (!$published) $this->invalid('活动尚未正式开启');
  73. return $published;
  74. }
  75. private function mutate(int $activityId, int $userId, callable $callback): array
  76. {
  77. return DB::transaction(function () use ($activityId, $userId, $callback) {
  78. $member = $this->member($userId);
  79. $wallet = Wallet::where('member_id', $member->member_id)->lockForUpdate()->first();
  80. if (!$wallet) $this->invalid('会员钱包不存在');
  81. $activity = $this->activity($activityId, true);
  82. return $callback($activity, $member, $wallet);
  83. }, 3);
  84. }
  85. private function account(PromotionActivity $activity, User $member): object
  86. {
  87. $now = PromotionFacts::now();
  88. DB::table('promotion_accounts')->insertOrIgnore(['activity_id' => $activity->id, 'user_id' => $member->id,
  89. 'round_no' => 1, 'spins' => 0, 'created_at' => $now, 'updated_at' => $now]);
  90. return DB::table('promotion_accounts')->where('activity_id', $activity->id)->where('user_id', $member->id)->lockForUpdate()->first();
  91. }
  92. private function newRound(object $account, string $start, array $completed = [], bool $reset = false): object
  93. {
  94. $now = PromotionFacts::now();
  95. DB::table('promotion_rounds')->insert(['account_id' => $account->id, 'round_no' => $account->round_no,
  96. 'coins_cents' => 0, 'status' => 'active', 'started_at' => $start,
  97. 'deposit_cursor' => $reset ? (int)DB::table('balance_logs')->max('id') : 0,
  98. 'bet_cursors' => json_encode($reset ? $this->facts->cursors() : []), 'completed_tasks' => json_encode($completed), 'created_at' => $now, 'updated_at' => $now]);
  99. return $this->round($account);
  100. }
  101. private function round(object $account): ?object
  102. {
  103. return DB::table('promotion_rounds')->where('account_id', $account->id)->where('round_no', $account->round_no)->lockForUpdate()->first();
  104. }
  105. public function detail(int $activityId, int $userId, ?string $platform = null): array
  106. {
  107. $activity = $this->activity($activityId); $member = $this->member($userId);
  108. $this->open($activity, $member, $platform);
  109. $account = DB::table('promotion_accounts')->where('activity_id', $activityId)->where('user_id', $userId)->first();
  110. $round = $account ? DB::table('promotion_rounds')->where('account_id', $account->id)->where('round_no', $account->round_no)->first() : null;
  111. return $this->state($activity, $member, $account, $round);
  112. }
  113. public function progress(int $activityId, int $userId, ?string $platform = null): array
  114. {
  115. return $this->mutate($activityId, $userId, function ($activity, $member) use ($platform) {
  116. $start = $this->open($activity, $member, $platform); $account = $this->account($activity, $member); $round = null;
  117. if ((int)$activity->type === Rules::WHEEL) {
  118. $round = $this->round($account) ?? $this->newRound($account, $start);
  119. if ($round->status === 'active') $this->refreshWheel($activity, $member, $account, $round);
  120. }
  121. return $this->state($activity, $member, $account, $round);
  122. });
  123. }
  124. public function apply(int $activityId, int $userId, ?string $platform = null): array
  125. {
  126. return $this->mutate($activityId, $userId, function ($activity, $member) use ($platform) {
  127. $start = $this->open($activity, $member, $platform);
  128. if ((int)$activity->type !== Rules::LOSS) $this->invalid('只有净亏邀请活动需要申请');
  129. $account = $this->account($activity, $member);
  130. if (!$account->applied_at) {
  131. $rules = $this->rules($activity); $policy = $this->facts->policy();
  132. $profit = $this->facts->betting([$member->id], $start)['profit'];
  133. $loss = bccomp($profit, '0', 10) < 0 ? bcsub('0', $profit, 10) : '0';
  134. if (bccomp($loss, $rules['loss_amount'], 10) < 0) $this->invalid('尚未达到净亏申请门槛');
  135. $account->applied_at = PromotionFacts::now();
  136. $account->application_snapshot = json_encode(['loss' => $loss, 'from' => $start, 'policy' => $policy, 'rules' => $rules,
  137. 'invite_user_cursor' => (int)DB::table('users')->max('id')]);
  138. DB::table('promotion_accounts')->where('id', $account->id)->update(['applied_at' => $account->applied_at,
  139. 'application_snapshot' => $account->application_snapshot, 'updated_at' => PromotionFacts::now()]);
  140. }
  141. return $this->state($activity, $member, $account, null);
  142. });
  143. }
  144. private function lossInvitees(User $member, object $account): array
  145. {
  146. if (!$account->applied_at) return [];
  147. $policy = $this->facts->policy(); $qualified = []; $snapshot = $this->json($account->application_snapshot);
  148. foreach ($this->facts->children($member->id) as $child) {
  149. 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'];
  150. }
  151. return $qualified;
  152. }
  153. private function grantTask(object $account, object $round, string $task, string $event, array $evidence): void
  154. {
  155. $inserted = DB::table('promotion_task_grants')->insertOrIgnore(['account_id' => $account->id, 'round_no' => $round->round_no,
  156. 'task' => $task, 'event_key' => $event, 'evidence' => json_encode($evidence), 'created_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]);
  157. if ($inserted) { ++$account->spins; DB::table('promotion_accounts')->where('id', $account->id)->update(['spins' => $account->spins, 'updated_at' => PromotionFacts::now()]); }
  158. }
  159. private function refreshWheel(PromotionActivity $activity, User $member, object $account, object $round): void
  160. {
  161. $rules = $this->rules($activity); $policy = $this->facts->policy();
  162. $completed = $this->json($round->completed_tasks);
  163. $campaignStart = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  164. // Daily tasks are campaign-wide. They survive round reset, but never grant twice on one day.
  165. foreach ($this->facts->logins($member->member_id, $campaignStart) as $day => $_) {
  166. $this->grantTask($account, $round, 'login', $day, ['day' => $day]); $completed['login'] = true;
  167. }
  168. foreach ($this->facts->online($member->id, $campaignStart) as $day => $seconds) if ($seconds >= $rules['online_seconds']) {
  169. $this->grantTask($account, $round, 'online', $day, ['day' => $day, 'seconds' => $seconds]); $completed['online'] = true;
  170. }
  171. $children = $this->facts->children($member->id);
  172. foreach ($children as $child) {
  173. if ($this->facts->qualified($child, $policy) && !$this->facts->qualified($child, $policy, $round->started_at)) {
  174. $this->grantTask($account, $round, 'invite', (string)$child['id'], ['user_id' => $child['id'], 'policy' => $policy]);
  175. }
  176. }
  177. // Only a grant belonging to this round can satisfy its resettable invitation task.
  178. $completed['invite'] = false; $childrenById = array_column($children, null, 'id');
  179. foreach (DB::table('promotion_task_grants')->where('account_id', $account->id)->where('round_no', $round->round_no)->where('task', 'invite')->get() as $grant) {
  180. $evidence = $this->json($grant->evidence); $child = $childrenById[$evidence['user_id']] ?? null;
  181. if ($child && $this->facts->qualified($child, $evidence['policy'])) $completed['invite'] = true;
  182. }
  183. $cursors = $this->json($round->bet_cursors);
  184. $teamDeposits = $teamBets = [];
  185. foreach ($children as $child) {
  186. $from = max($round->started_at, $child['bound_at']);
  187. foreach ($this->facts->deposits([$child['member_id']], $from, null, $round->deposit_cursor) as $day => $amount) $teamDeposits[$day] = bcadd($teamDeposits[$day] ?? '0', $amount, 10);
  188. foreach ($this->facts->betting([$child['id']], $from, null, $cursors)['effective'] as $day => $amount) $teamBets[$day] = bcadd($teamBets[$day] ?? '0', $amount, 10);
  189. }
  190. $metrics = [
  191. 'deposit' => $this->facts->deposits([$member->member_id], $round->started_at, null, $round->deposit_cursor),
  192. 'team_deposit' => $teamDeposits,
  193. 'bet' => $this->facts->betting([$member->id], $round->started_at, null, $cursors)['effective'],
  194. 'team_bet' => $teamBets,
  195. ];
  196. foreach ($metrics as $task => $days) {
  197. // Recompute qualification after corrections; daily amounts never carry across midnight.
  198. $completed[$task] = false;
  199. foreach ($days as $day => $amount) if (bccomp($amount, $rules[$task . '_amount'], 10) >= 0) {
  200. $this->grantTask($account, $round, $task, $round->round_no . ':' . $day, ['day' => $day, 'amount' => $amount, 'target' => $rules[$task . '_amount']]); $completed[$task] = true;
  201. }
  202. foreach (DB::table('promotion_task_grants')->where('account_id', $account->id)->where('round_no', $round->round_no)->where('task', $task)->get() as $grant) {
  203. $proof = $this->json($grant->evidence);
  204. if (bccomp($days[$proof['day']] ?? '0', $proof['target'] ?? $rules[$task . '_amount'], 10) >= 0) $completed[$task] = true;
  205. }
  206. }
  207. $round->completed_tasks = json_encode($completed);
  208. DB::table('promotion_rounds')->where('id', $round->id)->update(['completed_tasks' => $round->completed_tasks, 'updated_at' => PromotionFacts::now()]);
  209. }
  210. private function reserve(PromotionActivity $activity, User $member, object $account, int $roundNo, string $amount, array $rules): object
  211. {
  212. $this->capacity($activity, $member, $amount);
  213. $received = DB::table('promotion_rewards')->where('activity_id', $activity->id)->where('user_id', $member->id)->exists();
  214. DB::table('promotion_rewards')->insert(['activity_id' => $activity->id, 'user_id' => $member->id, 'account_id' => $account->id,
  215. 'round_no' => $roundNo, 'amount' => $amount, 'required_flow' => bcmul($amount, $rules['turnover_ratio'], 2),
  216. 'status' => 'reserved', 'rule_snapshot' => json_encode($rules), 'created_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]);
  217. if (!$received) ++$activity->rewarded_count;
  218. $activity->budget_used = bcadd((string)$activity->budget_used, $amount, 2); $activity->save();
  219. return DB::table('promotion_rewards')->where('account_id', $account->id)->where('round_no', $roundNo)->first();
  220. }
  221. private function capacity(PromotionActivity $activity, User $member, string $amount): void
  222. {
  223. $received = DB::table('promotion_rewards')->where('activity_id', $activity->id)->where('user_id', $member->id)->exists();
  224. if (!$received && $activity->reward_quota !== null && (int)$activity->rewarded_count >= (int)$activity->reward_quota) $this->invalid('活动获奖份数已用完');
  225. if ($activity->budget !== null && bccomp(bcadd((string)$activity->budget_used, $amount, 2), (string)$activity->budget, 2) > 0) $this->invalid('活动奖励额度不足');
  226. }
  227. public function spin(int $activityId, int $userId, string $requestKey, ?string $platform = null): array
  228. {
  229. return $this->mutate($activityId, $userId, function ($activity, $member) use ($requestKey, $platform) {
  230. $account = $this->account($activity, $member);
  231. $previous = DB::table('promotion_spins')->where('account_id', $account->id)->where('request_key', $requestKey)->first();
  232. if ($previous) return ['spin' => $this->spinRow($previous), 'spins' => $account->spins, 'replayed' => true];
  233. $start = $this->open($activity, $member, $platform);
  234. if ((int)$activity->type !== Rules::WHEEL) $this->invalid('该活动不是转盘活动');
  235. $round = $this->round($account) ?? $this->newRound($account, $start);
  236. if ($round->status !== 'active') $this->invalid('本轮已达到666,请先领取');
  237. $this->refreshWheel($activity, $member, $account, $round);
  238. if ($account->spins < 1) $this->invalid('抽奖次数不足');
  239. $rules = $this->rules($activity); $flags = $this->json($round->completed_tasks);
  240. $complete = count(array_filter(array_intersect_key($flags, array_flip(Rules::TASKS)))) === count(Rules::TASKS);
  241. // Capacity is checked before random sampling; a winning outcome is reserved immediately.
  242. if ($complete && bccomp($rules['completion_probability'], '0', 2) > 0) $this->capacity($activity, $member, '666.00');
  243. $draw = Rules::draw((int)$round->coins_cents, $complete, $rules['completion_probability']);
  244. if ($draw['reached']) $this->reserve($activity, $member, $account, $round->round_no, '666.00', $rules);
  245. $coins = $round->coins_cents + $draw['amount_cents']; $now = PromotionFacts::now();
  246. $id = DB::table('promotion_spins')->insertGetId(['account_id' => $account->id, 'round_no' => $round->round_no, 'request_key' => $requestKey,
  247. 'prize_index' => $draw['prize_index'], 'amount_cents' => $draw['amount_cents'], 'coins_cents' => $coins,
  248. 'conditions_complete' => $complete, 'probability' => $complete ? $rules['completion_probability'] : '0.00', 'created_at' => $now, 'updated_at' => $now]);
  249. DB::table('promotion_rounds')->where('id', $round->id)->update(['coins_cents' => $coins, 'status' => $draw['reached'] ? 'reached' : 'active', 'updated_at' => $now]);
  250. --$account->spins;
  251. DB::table('promotion_accounts')->where('id', $account->id)->update(['spins' => $account->spins, 'updated_at' => $now]);
  252. return ['spin' => $this->spinRow(DB::table('promotion_spins')->where('id', $id)->first()), 'spins' => $account->spins, 'replayed' => false];
  253. });
  254. }
  255. private function pay(object $reward, User $member, Wallet $wallet): object
  256. {
  257. if ($reward->status !== 'reserved') return $reward;
  258. $frozen = bccomp((string)$reward->required_flow, '0', 2) > 0;
  259. $field = $frozen ? 'frozen_balance' : 'available_balance';
  260. $before = (string)$wallet->$field; $wallet->$field = bcadd($before, (string)$reward->amount, 10); $wallet->save();
  261. $log = BalanceLog::create(['member_id' => $member->member_id, 'type' => $frozen ? 2 : 1, 'change_type' => '优惠活动',
  262. 'amount' => $reward->amount, 'before_balance' => $before, 'after_balance' => $wallet->$field, 'related_id' => $reward->id,
  263. // Frozen promotion rewards are intentionally unlocked by this service, never by the legacy 1x list.
  264. 'frozen_status' => $frozen ? 1 : null, 'remark' => '新活动奖励; activity=' . $reward->activity_id . '; round=' . $reward->round_no]);
  265. $now = PromotionFacts::now();
  266. DB::table('promotion_rewards')->where('id', $reward->id)->update(['status' => $frozen ? 'locked' : 'paid', 'credited_log_id' => $log->id,
  267. 'flow_snapshot' => json_encode(['from' => $now, 'cursors' => $this->facts->cursors()]), 'updated_at' => $now]);
  268. return DB::table('promotion_rewards')->where('id', $reward->id)->first();
  269. }
  270. public function claim(int $activityId, int $userId, int $roundNo, ?string $platform = null): array
  271. {
  272. return $this->mutate($activityId, $userId, function ($activity, $member, $wallet) use ($roundNo, $platform) {
  273. $account = $this->account($activity, $member);
  274. $reward = DB::table('promotion_rewards')->where('account_id', $account->id)->where('round_no', $roundNo)->lockForUpdate()->first();
  275. if ($reward && $reward->status !== 'reserved') return ['reward' => (array)$reward, 'round_no' => $account->round_no, 'spins' => $account->spins, 'replayed' => true];
  276. if ((int)$activity->type === Rules::LOSS) {
  277. $this->open($activity, $member, $platform);
  278. if ($roundNo !== 1 || !$account->applied_at) $this->invalid('请先申请活动');
  279. $snapshot = $this->json($account->application_snapshot); $rules = $snapshot['rules'];
  280. $qualified = $this->lossInvitees($member, $account);
  281. if (count($qualified) < $rules['invite_count']) $this->invalid('有效邀请人数不足');
  282. $reward ??= $this->reserve($activity, $member, $account, 1, $rules['reward_amount'], $rules + ['qualified_invitees' => $qualified]);
  283. } elseif ((int)$activity->type === Rules::WHEEL) {
  284. // A reserved, earned reward remains payable after the campaign is unpublished.
  285. $round = $this->round($account);
  286. if (!$reward || !$round || $round->round_no !== $roundNo || $round->status !== 'reached') $this->invalid('本轮尚未达到666');
  287. } else $this->invalid('首充奖励由充值成功后自动发放');
  288. $reward = $this->pay($reward, $member, $wallet);
  289. if ((int)$activity->type === Rules::WHEEL) {
  290. $flags = array_intersect_key($this->json($round->completed_tasks), array_flip(Rules::DAILY));
  291. DB::table('promotion_rounds')->where('id', $round->id)->update(['status' => 'claimed', 'claimed_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]);
  292. ++$account->round_no;
  293. DB::table('promotion_accounts')->where('id', $account->id)->update(['round_no' => $account->round_no, 'updated_at' => PromotionFacts::now()]);
  294. $this->newRound($account, PromotionFacts::now(), $flags, true);
  295. }
  296. return ['reward' => (array)$reward, 'round_no' => $account->round_no, 'spins' => $account->spins, 'replayed' => false];
  297. });
  298. }
  299. public function onDeposit(BalanceLog $deposit): void
  300. {
  301. 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;
  302. $member = User::where('member_id', $deposit->member_id)->first();
  303. if (!$member || (int)$member->from === 2) return;
  304. DB::transaction(function () use ($member, $deposit) {
  305. $wallet = Wallet::where('member_id', $member->member_id)->lockForUpdate()->first();
  306. if (!$wallet) $this->invalid('会员钱包不存在');
  307. $first = DB::table('balance_logs')->where('member_id', $member->member_id)->where('type', 1)->where('amount', '>', 0)
  308. ->whereIn('change_type', ['充值', '三方充值'])->orderBy('created_at')->orderBy('id')->value('id');
  309. if ((int)$first !== (int)$deposit->id) return;
  310. $inserted = DB::table('promotion_first_deposits')->insertOrIgnore(['user_id' => $member->id, 'deposit_log_id' => $deposit->id,
  311. 'created_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]);
  312. if (!$inserted) return;
  313. $activities = PromotionActivity::where('type', Rules::FIRST_DEPOSIT)->where('status', 1)->where('start_time', '<=', now()->timestamp)
  314. ->where('end_time', '>=', now()->timestamp)->where('lang', $member->language ?: 'zh')->orderByDesc('sort')->orderByDesc('id')->get();
  315. foreach ($activities as $candidate) {
  316. $activity = $this->activity($candidate->id, true);
  317. if ((int)$activity->status !== 1 || (int)$activity->type !== Rules::FIRST_DEPOSIT) continue;
  318. $published = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  319. $creditedAt = (string)$deposit->getRawOriginal('created_at');
  320. if (!$published || $creditedAt < $published || strtotime($creditedAt) < (int)$activity->start_time || strtotime($creditedAt) > (int)$activity->end_time) continue;
  321. if (!ActivityEligibilityService::evaluate($activity, ActivityEligibilityService::memberContext($member->member_id))['is_eligible']) continue;
  322. $rules = $this->rules($activity);
  323. if (bccomp((string)$deposit->amount, $rules['min_deposit'], 10) < 0) continue;
  324. try { $this->capacity($activity, $member, $rules['reward_amount']); } catch (ValidationException $e) { continue; }
  325. $account = $this->account($activity, $member);
  326. $reward = $this->reserve($activity, $member, $account, 1, $rules['reward_amount'], $rules + ['deposit_log_id' => $deposit->id]);
  327. $this->pay($reward, $member, $wallet); break;
  328. }
  329. }, 3);
  330. }
  331. private function state(PromotionActivity $activity, User $member, ?object $account, ?object $round): array
  332. {
  333. $rules = $this->rules($activity); $type = (int)$activity->type;
  334. $result = ['activity_id' => $activity->id, 'type' => $type, 'rules' => $rules, 'account_id' => $account->id ?? null,
  335. 'round_no' => $account->round_no ?? 1, 'spins' => $account->spins ?? 0, 'server_time' => PromotionFacts::now()];
  336. if ($type === Rules::WHEEL) {
  337. $flags = $round ? $this->json($round->completed_tasks) : [];
  338. $result += ['coins' => $this->money($round->coins_cents ?? 0), 'remaining' => $this->money(66600 - ($round->coins_cents ?? 0)),
  339. 'status' => $round->status ?? 'not_started', 'completed_tasks' => $flags,
  340. 'conditions_complete' => count(array_filter(array_intersect_key($flags, array_flip(Rules::TASKS)))) === 7,
  341. 'prizes' => Rules::PRIZES, 'valid_member_policy' => $this->facts->policy(),
  342. 'ordinary_pool_rule' => '固定奖项仅在累计后小于666时参与普通奖池;普通奖池可用奖项等概率,浮动奖项按分等概率取值。'];
  343. $today = substr(PromotionFacts::now(), 0, 10);
  344. $result['today_granted_tasks'] = $account ? DB::table('promotion_task_grants')->where('account_id', $account->id)
  345. ->where(function ($q) use ($today, $account) { $q->where('event_key', $today)->orWhere('event_key', $account->round_no . ':' . $today); })->pluck('task')->all() : [];
  346. $result['tasks'] = $this->wheelToday($activity, $member, $account, $round, $flags, $result['today_granted_tasks']);
  347. } elseif ($type === Rules::LOSS) {
  348. $start = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  349. $profit = $this->facts->betting([$member->id], $start)['profit'];
  350. $result += ['loss' => bccomp($profit, '0', 10) < 0 ? bcsub('0', $profit, 2) : '0.00', 'applied_at' => $account->applied_at ?? null,
  351. 'qualified_invitees' => $account ? count($this->lossInvitees($member, $account)) : 0, 'valid_member_policy' => $this->facts->policy()];
  352. } else {
  353. $result['has_deposited'] = DB::table('balance_logs')->where('member_id', $member->member_id)->where('type', 1)->where('amount', '>', 0)->whereIn('change_type', ['充值', '三方充值'])->exists();
  354. }
  355. $result['rewards'] = $account ? DB::table('promotion_rewards')->where('account_id', $account->id)->orderByDesc('round_no')->limit(10)->get()->map(fn ($r) => (array)$r)->all() : [];
  356. if ($type === Rules::LOSS) {
  357. if ($account?->applied_at) $result['rules'] = $this->json($account->application_snapshot)['rules'];
  358. $result['status'] = $result['rewards'] ? 'claimed' : (!$account?->applied_at ? 'not_applied' : ($result['qualified_invitees'] >= $result['rules']['invite_count'] ? 'ready' : 'collecting'));
  359. }
  360. return $result;
  361. }
  362. private function wheelToday(PromotionActivity $activity, User $member, ?object $account, ?object $round, array $flags, array $granted): array
  363. {
  364. $rules = $this->rules($activity); $today = substr(PromotionFacts::now(), 0, 10);
  365. $published = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  366. $dailyFrom = max($published, $today . ' 00:00:00'); $from = max($round->started_at ?? $published, $dailyFrom);
  367. $cursors = $round ? $this->json($round->bet_cursors) : []; $cursor = (int)($round->deposit_cursor ?? 0);
  368. $online = $this->facts->online($member->id, $dailyFrom); $logins = $this->facts->logins($member->member_id, $dailyFrom);
  369. $values = ['online' => $online[$today] ?? 0, 'login' => isset($logins[$today]) ? 1 : 0,
  370. 'invite' => $account ? DB::table('promotion_task_grants')->where('account_id', $account->id)->where('round_no', $account->round_no)->where('task', 'invite')->count() : 0,
  371. 'deposit' => $this->facts->total($this->facts->deposits([$member->member_id], $from, null, $cursor)),
  372. 'team_deposit' => '0', 'bet' => $this->facts->total($this->facts->betting([$member->id], $from, null, $cursors)['effective']), 'team_bet' => '0'];
  373. foreach ($this->facts->children($member->id) as $child) {
  374. $childFrom = max($from, $child['bound_at']);
  375. $values['team_deposit'] = bcadd($values['team_deposit'], $this->facts->total($this->facts->deposits([$child['member_id']], $childFrom, null, $cursor)), 10);
  376. $values['team_bet'] = bcadd($values['team_bet'], $this->facts->total($this->facts->betting([$child['id']], $childFrom, null, $cursors)['effective']), 10);
  377. }
  378. $tasks = [];
  379. foreach (Rules::TASKS as $key) {
  380. $target = match ($key) { 'online' => $rules['online_seconds'], 'login', 'invite' => 1, default => $rules[$key . '_amount'] };
  381. $tasks[] = ['key' => $key, 'round_completed' => (bool)($flags[$key] ?? false), 'value' => $values[$key], 'target' => $target,
  382. 'today_rewarded' => in_array($key, $granted, true), 'reward_spins' => 1,
  383. 'remaining_seconds' => $key === 'online' ? max(0, $target - $values[$key]) : null];
  384. }
  385. return $tasks;
  386. }
  387. private function spinRow(object $row): array
  388. {
  389. return ['id' => $row->id, 'round_no' => $row->round_no, 'prize_index' => $row->prize_index, 'prize' => Rules::PRIZES[$row->prize_index],
  390. 'amount' => $this->money($row->amount_cents), 'coins' => $this->money($row->coins_cents), 'reached' => (int)$row->coins_cents === 66600,
  391. 'conditions_complete' => (bool)$row->conditions_complete, 'probability' => (string)$row->probability, 'created_at' => $row->created_at];
  392. }
  393. public function records(int $activityId, int $userId, int $page = 1, int $limit = 20): array
  394. {
  395. $this->activity($activityId); $this->member($userId);
  396. $account = DB::table('promotion_accounts')->where('activity_id', $activityId)->where('user_id', $userId)->first();
  397. if (!$account) return ['total' => 0, 'data' => []];
  398. $q = DB::table('promotion_spins')->where('account_id', $account->id);
  399. return ['total' => $q->count(), 'data' => $q->orderByDesc('id')->forPage($page, $limit)->get()->map(fn ($r) => $this->spinRow($r))->all()];
  400. }
  401. public function broadcasts(int $activityId): array
  402. {
  403. $activity = $this->activity($activityId);
  404. if ((int)$activity->type !== Rules::WHEEL) $this->invalid('该活动不是转盘活动');
  405. $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')
  406. ->where('a.activity_id', $activityId);
  407. $map = fn ($r) => ['account' => substr((string)$r->member_id, 0, strlen((string)$r->member_id) >= 10 ? 4 : 1) . '****' . substr((string)$r->member_id, -1),
  408. 'amount' => $this->money($r->amount_cents), 'created_at' => $r->created_at];
  409. return ['ordinary' => (clone $q)->orderByDesc('s.id')->limit(50)->get(['u.member_id', 's.amount_cents', 's.created_at'])->map($map)->all(),
  410. '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()];
  411. }
  412. public function rewards(int $activityId, int $userId, int $page = 1, int $limit = 20): array
  413. {
  414. $this->activity($activityId); $this->member($userId);
  415. $q = DB::table('promotion_rewards')->where('activity_id', $activityId)->where('user_id', $userId);
  416. return ['total' => $q->count(), 'data' => $q->orderByDesc('id')->forPage($page, $limit)->get()];
  417. }
  418. public function unlock(int $userId): int
  419. {
  420. return DB::transaction(function () use ($userId) {
  421. $member = $this->member($userId); $wallet = Wallet::where('member_id', $member->member_id)->lockForUpdate()->first();
  422. if (!$wallet) return 0;
  423. $count = 0;
  424. foreach (DB::table('promotion_rewards')->where('user_id', $userId)->where('status', 'locked')->orderBy('id')->lockForUpdate()->get() as $reward) {
  425. $snapshot = $this->json($reward->flow_snapshot);
  426. $effective = $this->facts->total($this->facts->betting([$userId], $snapshot['from'], null, $snapshot['cursors'])['effective']);
  427. if (bccomp($effective, (string)$reward->required_flow, 10) < 0) continue;
  428. if (bccomp((string)$wallet->frozen_balance, (string)$reward->amount, 10) < 0) $this->invalid('冻结奖励余额不足');
  429. $beforeFrozen = (string)$wallet->frozen_balance; $before = (string)$wallet->available_balance;
  430. $wallet->frozen_balance = bcsub($beforeFrozen, (string)$reward->amount, 10); $wallet->available_balance = bcadd($before, (string)$reward->amount, 10); $wallet->save();
  431. BalanceLog::create(['member_id' => $member->member_id, 'type' => 2, 'change_type' => '流水解冻', 'amount' => bcsub('0', (string)$reward->amount, 2),
  432. 'before_balance' => $beforeFrozen, 'after_balance' => $wallet->frozen_balance, 'related_id' => $reward->id, 'remark' => '新活动奖励解冻']);
  433. $log = BalanceLog::create(['member_id' => $member->member_id, 'type' => 1, 'change_type' => '流水解冻', 'amount' => $reward->amount,
  434. 'before_balance' => $before, 'after_balance' => $wallet->available_balance, 'related_id' => $reward->id, 'remark' => '新活动奖励解冻']);
  435. DB::table('balance_logs')->where('id', $reward->credited_log_id)->update(['frozen_status' => 2]);
  436. 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;
  437. }
  438. return $count;
  439. }, 3);
  440. }
  441. }