PromotionService.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. $start = $this->open($activity, $member, $platform); $account = $this->account($activity, $member); $round = null;
  121. if ((int)$activity->type === Rules::WHEEL) {
  122. $round = $this->round($account) ?? $this->newRound($account, $start);
  123. if ($round->status === 'active') $this->refreshWheel($activity, $member, $account, $round);
  124. }
  125. return $this->state($activity, $member, $account, $round, $lang);
  126. });
  127. }
  128. public function apply(int $activityId, int $userId, ?string $platform = null, ?string $lang = null): array
  129. {
  130. return $this->mutate($activityId, $userId, function ($activity, $member) use ($platform, $lang) {
  131. $start = $this->open($activity, $member, $platform);
  132. if ((int)$activity->type !== Rules::LOSS) $this->invalid('只有净亏邀请活动需要申请');
  133. $account = $this->account($activity, $member);
  134. if (!$account->applied_at) {
  135. $rules = $this->rules($activity); $policy = $this->facts->policy();
  136. $profit = $this->facts->betting([$member->id], $start)['profit'];
  137. $loss = bccomp($profit, '0', 10) < 0 ? bcsub('0', $profit, 10) : '0';
  138. if (bccomp($loss, $rules['loss_amount'], 10) < 0) $this->invalid('尚未达到净亏申请门槛');
  139. $account->applied_at = PromotionFacts::now();
  140. $account->application_snapshot = json_encode(['loss' => $loss, 'from' => $start, 'policy' => $policy, 'rules' => $rules,
  141. 'invite_user_cursor' => (int)DB::table('users')->max('id')]);
  142. DB::table('promotion_accounts')->where('id', $account->id)->update(['applied_at' => $account->applied_at,
  143. 'application_snapshot' => $account->application_snapshot, 'updated_at' => PromotionFacts::now()]);
  144. }
  145. return $this->state($activity, $member, $account, null, $lang);
  146. });
  147. }
  148. private function lossInvitees(User $member, object $account): array
  149. {
  150. if (!$account->applied_at) return [];
  151. $policy = $this->facts->policy(); $qualified = []; $snapshot = $this->json($account->application_snapshot);
  152. foreach ($this->facts->children($member->id) as $child) {
  153. 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'];
  154. }
  155. return $qualified;
  156. }
  157. private function grantTask(object $account, object $round, string $task, string $event, array $evidence): void
  158. {
  159. $inserted = DB::table('promotion_task_grants')->insertOrIgnore(['account_id' => $account->id, 'round_no' => $round->round_no,
  160. 'task' => $task, 'event_key' => $event, 'evidence' => json_encode($evidence), 'created_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]);
  161. if ($inserted) { ++$account->spins; DB::table('promotion_accounts')->where('id', $account->id)->update(['spins' => $account->spins, 'updated_at' => PromotionFacts::now()]); }
  162. }
  163. private function refreshWheel(PromotionActivity $activity, User $member, object $account, object $round): void
  164. {
  165. $rules = $this->rules($activity); $policy = $this->facts->policy();
  166. $completed = $this->json($round->completed_tasks);
  167. $campaignStart = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  168. // Daily tasks are campaign-wide. They survive round reset, but never grant twice on one day.
  169. foreach ($this->facts->logins($member->member_id, $campaignStart) as $day => $_) {
  170. $this->grantTask($account, $round, 'login', $day, ['day' => $day]); $completed['login'] = true;
  171. }
  172. foreach ($this->facts->online($member->id, $campaignStart) as $day => $seconds) if ($seconds >= $rules['online_seconds']) {
  173. $this->grantTask($account, $round, 'online', $day, ['day' => $day, 'seconds' => $seconds]); $completed['online'] = true;
  174. }
  175. $children = $this->facts->children($member->id);
  176. foreach ($children as $child) {
  177. if ($this->facts->qualified($child, $policy) && !$this->facts->qualified($child, $policy, $round->started_at)) {
  178. $this->grantTask($account, $round, 'invite', (string)$child['id'], ['user_id' => $child['id'], 'policy' => $policy]);
  179. }
  180. }
  181. // Only a grant belonging to this round can satisfy its resettable invitation task.
  182. $completed['invite'] = false; $childrenById = array_column($children, null, 'id');
  183. foreach (DB::table('promotion_task_grants')->where('account_id', $account->id)->where('round_no', $round->round_no)->where('task', 'invite')->get() as $grant) {
  184. $evidence = $this->json($grant->evidence); $child = $childrenById[$evidence['user_id']] ?? null;
  185. if ($child && $this->facts->qualified($child, $evidence['policy'])) $completed['invite'] = true;
  186. }
  187. $cursors = $this->json($round->bet_cursors);
  188. $teamDeposits = $teamBets = [];
  189. foreach ($children as $child) {
  190. $from = max($round->started_at, $child['bound_at']);
  191. foreach ($this->facts->deposits([$child['member_id']], $from, null, $round->deposit_cursor) as $day => $amount) $teamDeposits[$day] = bcadd($teamDeposits[$day] ?? '0', $amount, 10);
  192. foreach ($this->facts->betting([$child['id']], $from, null, $cursors)['effective'] as $day => $amount) $teamBets[$day] = bcadd($teamBets[$day] ?? '0', $amount, 10);
  193. }
  194. $metrics = [
  195. 'deposit' => $this->facts->deposits([$member->member_id], $round->started_at, null, $round->deposit_cursor),
  196. 'team_deposit' => $teamDeposits,
  197. 'bet' => $this->facts->betting([$member->id], $round->started_at, null, $cursors)['effective'],
  198. 'team_bet' => $teamBets,
  199. ];
  200. foreach ($metrics as $task => $days) {
  201. // Recompute qualification after corrections; daily amounts never carry across midnight.
  202. $completed[$task] = false;
  203. foreach ($days as $day => $amount) if (bccomp($amount, $rules[$task . '_amount'], 10) >= 0) {
  204. $this->grantTask($account, $round, $task, $round->round_no . ':' . $day, ['day' => $day, 'amount' => $amount, 'target' => $rules[$task . '_amount']]); $completed[$task] = true;
  205. }
  206. foreach (DB::table('promotion_task_grants')->where('account_id', $account->id)->where('round_no', $round->round_no)->where('task', $task)->get() as $grant) {
  207. $proof = $this->json($grant->evidence);
  208. if (bccomp($days[$proof['day']] ?? '0', $proof['target'] ?? $rules[$task . '_amount'], 10) >= 0) $completed[$task] = true;
  209. }
  210. }
  211. $round->completed_tasks = json_encode($completed);
  212. DB::table('promotion_rounds')->where('id', $round->id)->update(['completed_tasks' => $round->completed_tasks, 'updated_at' => PromotionFacts::now()]);
  213. }
  214. private function reserve(PromotionActivity $activity, User $member, object $account, int $roundNo, string $amount, array $rules): object
  215. {
  216. $this->capacity($activity, $member, $amount);
  217. $received = DB::table('promotion_rewards')->where('activity_id', $activity->id)->where('user_id', $member->id)->exists();
  218. DB::table('promotion_rewards')->insert(['activity_id' => $activity->id, 'user_id' => $member->id, 'account_id' => $account->id,
  219. 'round_no' => $roundNo, 'amount' => $amount, 'required_flow' => bcmul($amount, $rules['turnover_ratio'], 2),
  220. 'status' => 'reserved', 'rule_snapshot' => json_encode($rules), 'created_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]);
  221. if (!$received) ++$activity->rewarded_count;
  222. $activity->budget_used = bcadd((string)$activity->budget_used, $amount, 2); $activity->save();
  223. return DB::table('promotion_rewards')->where('account_id', $account->id)->where('round_no', $roundNo)->first();
  224. }
  225. private function capacity(PromotionActivity $activity, User $member, string $amount): void
  226. {
  227. $received = DB::table('promotion_rewards')->where('activity_id', $activity->id)->where('user_id', $member->id)->exists();
  228. if (!$received && $activity->reward_quota !== null && (int)$activity->rewarded_count >= (int)$activity->reward_quota) $this->invalid('活动获奖份数已用完');
  229. if ($activity->budget !== null && bccomp(bcadd((string)$activity->budget_used, $amount, 2), (string)$activity->budget, 2) > 0) $this->invalid('活动奖励额度不足');
  230. }
  231. public function spin(int $activityId, int $userId, string $requestKey, ?string $platform = null): array
  232. {
  233. return $this->mutate($activityId, $userId, function ($activity, $member) use ($requestKey, $platform) {
  234. $account = $this->account($activity, $member);
  235. $previous = DB::table('promotion_spins')->where('account_id', $account->id)->where('request_key', $requestKey)->first();
  236. if ($previous) return ['spin' => $this->spinRow($previous), 'spins' => $account->spins, 'replayed' => true];
  237. $start = $this->open($activity, $member, $platform);
  238. if ((int)$activity->type !== Rules::WHEEL) $this->invalid('该活动不是转盘活动');
  239. $round = $this->round($account) ?? $this->newRound($account, $start);
  240. if ($round->status !== 'active') $this->invalid('本轮已达到666,请先领取');
  241. $this->refreshWheel($activity, $member, $account, $round);
  242. if ($account->spins < 1) $this->invalid('抽奖次数不足');
  243. $rules = $this->rules($activity); $flags = $this->json($round->completed_tasks);
  244. $complete = count(array_filter(array_intersect_key($flags, array_flip(Rules::TASKS)))) === count(Rules::TASKS);
  245. // Capacity is checked before random sampling; a winning outcome is reserved immediately.
  246. if ($complete && bccomp($rules['completion_probability'], '0', 2) > 0) $this->capacity($activity, $member, '666.00');
  247. $draw = Rules::draw((int)$round->coins_cents, $complete, $rules['completion_probability']);
  248. if ($draw['reached']) $this->reserve($activity, $member, $account, $round->round_no, '666.00', $rules);
  249. $coins = $round->coins_cents + $draw['amount_cents']; $now = PromotionFacts::now();
  250. $id = DB::table('promotion_spins')->insertGetId(['account_id' => $account->id, 'round_no' => $round->round_no, 'request_key' => $requestKey,
  251. 'prize_index' => $draw['prize_index'], 'amount_cents' => $draw['amount_cents'], 'coins_cents' => $coins,
  252. 'conditions_complete' => $complete, 'probability' => $complete ? $rules['completion_probability'] : '0.00', 'created_at' => $now, 'updated_at' => $now]);
  253. DB::table('promotion_rounds')->where('id', $round->id)->update(['coins_cents' => $coins, 'status' => $draw['reached'] ? 'reached' : 'active', 'updated_at' => $now]);
  254. --$account->spins;
  255. DB::table('promotion_accounts')->where('id', $account->id)->update(['spins' => $account->spins, 'updated_at' => $now]);
  256. return ['spin' => $this->spinRow(DB::table('promotion_spins')->where('id', $id)->first()), 'spins' => $account->spins, 'replayed' => false];
  257. });
  258. }
  259. private function pay(object $reward, User $member, Wallet $wallet): object
  260. {
  261. if ($reward->status !== 'reserved') return $reward;
  262. $frozen = bccomp((string)$reward->required_flow, '0', 2) > 0;
  263. $field = $frozen ? 'frozen_balance' : 'available_balance';
  264. $before = (string)$wallet->$field; $wallet->$field = bcadd($before, (string)$reward->amount, 10); $wallet->save();
  265. $log = BalanceLog::create(['member_id' => $member->member_id, 'type' => $frozen ? 2 : 1, 'change_type' => '优惠活动',
  266. 'amount' => $reward->amount, 'before_balance' => $before, 'after_balance' => $wallet->$field, 'related_id' => $reward->id,
  267. // Frozen promotion rewards are intentionally unlocked by this service, never by the legacy 1x list.
  268. 'frozen_status' => $frozen ? 1 : null, 'remark' => '新活动奖励; activity=' . $reward->activity_id . '; round=' . $reward->round_no]);
  269. $now = PromotionFacts::now();
  270. DB::table('promotion_rewards')->where('id', $reward->id)->update(['status' => $frozen ? 'locked' : 'paid', 'credited_log_id' => $log->id,
  271. 'flow_snapshot' => json_encode(['from' => $now, 'cursors' => $this->facts->cursors()]), 'updated_at' => $now]);
  272. return DB::table('promotion_rewards')->where('id', $reward->id)->first();
  273. }
  274. public function claim(int $activityId, int $userId, int $roundNo, ?string $platform = null): array
  275. {
  276. return $this->mutate($activityId, $userId, function ($activity, $member, $wallet) use ($roundNo, $platform) {
  277. $account = $this->account($activity, $member);
  278. $reward = DB::table('promotion_rewards')->where('account_id', $account->id)->where('round_no', $roundNo)->lockForUpdate()->first();
  279. if ($reward && $reward->status !== 'reserved') return ['reward' => (array)$reward, 'round_no' => $account->round_no, 'spins' => $account->spins, 'replayed' => true];
  280. if ((int)$activity->type === Rules::LOSS) {
  281. $this->open($activity, $member, $platform);
  282. if ($roundNo !== 1 || !$account->applied_at) $this->invalid('请先申请活动');
  283. $snapshot = $this->json($account->application_snapshot); $rules = $snapshot['rules'];
  284. $qualified = $this->lossInvitees($member, $account);
  285. if (count($qualified) < $rules['invite_count']) $this->invalid('有效邀请人数不足');
  286. $reward ??= $this->reserve($activity, $member, $account, 1, $rules['reward_amount'], $rules + ['qualified_invitees' => $qualified]);
  287. } elseif ((int)$activity->type === Rules::WHEEL) {
  288. // A reserved, earned reward remains payable after the campaign is unpublished.
  289. $round = $this->round($account);
  290. if (!$reward || !$round || $round->round_no !== $roundNo || $round->status !== 'reached') $this->invalid('本轮尚未达到666');
  291. } else $this->invalid('首充奖励由充值成功后自动发放');
  292. $reward = $this->pay($reward, $member, $wallet);
  293. if ((int)$activity->type === Rules::WHEEL) {
  294. $flags = array_intersect_key($this->json($round->completed_tasks), array_flip(Rules::DAILY));
  295. DB::table('promotion_rounds')->where('id', $round->id)->update(['status' => 'claimed', 'claimed_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]);
  296. ++$account->round_no;
  297. DB::table('promotion_accounts')->where('id', $account->id)->update(['round_no' => $account->round_no, 'updated_at' => PromotionFacts::now()]);
  298. $this->newRound($account, PromotionFacts::now(), $flags, true);
  299. }
  300. return ['reward' => (array)$reward, 'round_no' => $account->round_no, 'spins' => $account->spins, 'replayed' => false];
  301. });
  302. }
  303. public function onDeposit(BalanceLog $deposit): void
  304. {
  305. 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;
  306. $member = User::where('member_id', $deposit->member_id)->first();
  307. if (!$member || (int)$member->from === 2) return;
  308. DB::transaction(function () use ($member, $deposit) {
  309. $wallet = Wallet::where('member_id', $member->member_id)->lockForUpdate()->first();
  310. if (!$wallet) $this->invalid('会员钱包不存在');
  311. $first = DB::table('balance_logs')->where('member_id', $member->member_id)->where('type', 1)->where('amount', '>', 0)
  312. ->whereIn('change_type', ['充值', '三方充值'])->orderBy('created_at')->orderBy('id')->value('id');
  313. if ((int)$first !== (int)$deposit->id) return;
  314. $inserted = DB::table('promotion_first_deposits')->insertOrIgnore(['user_id' => $member->id, 'deposit_log_id' => $deposit->id,
  315. 'created_at' => PromotionFacts::now(), 'updated_at' => PromotionFacts::now()]);
  316. if (!$inserted) return;
  317. $activities = PromotionActivity::where('type', Rules::FIRST_DEPOSIT)->where('status', 1)->where('start_time', '<=', now()->timestamp)
  318. ->where('end_time', '>=', now()->timestamp)->orderByDesc('sort')->orderByDesc('id')->get();
  319. foreach ($activities as $candidate) {
  320. $activity = $this->activity($candidate->id, true);
  321. if (!PromotionTranslations::select($activity->toArray(), $member->language ?: 'zh')) continue;
  322. if ((int)$activity->status !== 1 || (int)$activity->type !== Rules::FIRST_DEPOSIT) continue;
  323. $published = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  324. $creditedAt = (string)$deposit->getRawOriginal('created_at');
  325. if (!$published || $creditedAt < $published || strtotime($creditedAt) < (int)$activity->start_time || strtotime($creditedAt) > (int)$activity->end_time) continue;
  326. if (!ActivityEligibilityService::evaluate($activity, ActivityEligibilityService::memberContext($member->member_id))['is_eligible']) continue;
  327. $rules = $this->rules($activity);
  328. if (bccomp((string)$deposit->amount, $rules['min_deposit'], 10) < 0) continue;
  329. try { $this->capacity($activity, $member, $rules['reward_amount']); } catch (ValidationException $e) { continue; }
  330. $account = $this->account($activity, $member);
  331. $reward = $this->reserve($activity, $member, $account, 1, $rules['reward_amount'], $rules + ['deposit_log_id' => $deposit->id]);
  332. $this->pay($reward, $member, $wallet); break;
  333. }
  334. }, 3);
  335. }
  336. private function state(PromotionActivity $activity, User $member, ?object $account, ?object $round, ?string $lang = null): array
  337. {
  338. $rules = $this->rules($activity); $type = (int)$activity->type;
  339. $text = PromotionTranslations::select($activity->toArray(), $lang ?? ($member->language ?: 'zh'));
  340. if (!$text) $this->invalid('活动未配置所选语言');
  341. $result = ['activity_id' => $activity->id, 'type' => $type, 'rules' => $rules, 'account_id' => $account->id ?? null,
  342. 'round_no' => $account->round_no ?? 1, 'spins' => $account->spins ?? 0, 'server_time' => PromotionFacts::now()] + $text;
  343. if ($type === Rules::WHEEL) {
  344. $flags = $round ? $this->json($round->completed_tasks) : [];
  345. $result += ['coins' => $this->money($round->coins_cents ?? 0), 'remaining' => $this->money(66600 - ($round->coins_cents ?? 0)),
  346. 'status' => $round->status ?? 'not_started', 'completed_tasks' => $flags,
  347. 'conditions_complete' => count(array_filter(array_intersect_key($flags, array_flip(Rules::TASKS)))) === 7,
  348. 'prizes' => Rules::PRIZES, 'valid_member_policy' => $this->facts->policy(),
  349. 'ordinary_pool_rule' => '固定奖项仅在累计后小于666时参与普通奖池;普通奖池可用奖项等概率,浮动奖项按分等概率取值。'];
  350. $today = substr(PromotionFacts::now(), 0, 10);
  351. $result['today_granted_tasks'] = $account ? DB::table('promotion_task_grants')->where('account_id', $account->id)
  352. ->where(function ($q) use ($today, $account) { $q->where('event_key', $today)->orWhere('event_key', $account->round_no . ':' . $today); })->pluck('task')->all() : [];
  353. $result['tasks'] = $this->wheelToday($activity, $member, $account, $round, $flags, $result['today_granted_tasks']);
  354. } elseif ($type === Rules::LOSS) {
  355. $start = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  356. $profit = $this->facts->betting([$member->id], $start)['profit'];
  357. $result += ['loss' => bccomp($profit, '0', 10) < 0 ? bcsub('0', $profit, 2) : '0.00', 'applied_at' => $account->applied_at ?? null,
  358. 'qualified_invitees' => $account ? count($this->lossInvitees($member, $account)) : 0, 'valid_member_policy' => $this->facts->policy()];
  359. } else {
  360. $result['has_deposited'] = DB::table('balance_logs')->where('member_id', $member->member_id)->where('type', 1)->where('amount', '>', 0)->whereIn('change_type', ['充值', '三方充值'])->exists();
  361. }
  362. $result['rewards'] = $account ? DB::table('promotion_rewards')->where('account_id', $account->id)->orderByDesc('round_no')->limit(10)->get()->map(fn ($r) => (array)$r)->all() : [];
  363. if ($type === Rules::LOSS) {
  364. if ($account?->applied_at) $result['rules'] = $this->json($account->application_snapshot)['rules'];
  365. $result['status'] = $result['rewards'] ? 'claimed' : (!$account?->applied_at ? 'not_applied' : ($result['qualified_invitees'] >= $result['rules']['invite_count'] ? 'ready' : 'collecting'));
  366. }
  367. return $result;
  368. }
  369. private function wheelToday(PromotionActivity $activity, User $member, ?object $account, ?object $round, array $flags, array $granted): array
  370. {
  371. $rules = $this->rules($activity); $today = substr(PromotionFacts::now(), 0, 10);
  372. $published = DB::table('promotion_campaigns')->where('activity_id', $activity->id)->value('first_published_at');
  373. $dailyFrom = max($published, $today . ' 00:00:00'); $from = max($round->started_at ?? $published, $dailyFrom);
  374. $cursors = $round ? $this->json($round->bet_cursors) : []; $cursor = (int)($round->deposit_cursor ?? 0);
  375. $online = $this->facts->online($member->id, $dailyFrom); $logins = $this->facts->logins($member->member_id, $dailyFrom);
  376. $values = ['online' => $online[$today] ?? 0, 'login' => isset($logins[$today]) ? 1 : 0,
  377. 'invite' => $account ? DB::table('promotion_task_grants')->where('account_id', $account->id)->where('round_no', $account->round_no)->where('task', 'invite')->count() : 0,
  378. 'deposit' => $this->facts->total($this->facts->deposits([$member->member_id], $from, null, $cursor)),
  379. 'team_deposit' => '0', 'bet' => $this->facts->total($this->facts->betting([$member->id], $from, null, $cursors)['effective']), 'team_bet' => '0'];
  380. foreach ($this->facts->children($member->id) as $child) {
  381. $childFrom = max($from, $child['bound_at']);
  382. $values['team_deposit'] = bcadd($values['team_deposit'], $this->facts->total($this->facts->deposits([$child['member_id']], $childFrom, null, $cursor)), 10);
  383. $values['team_bet'] = bcadd($values['team_bet'], $this->facts->total($this->facts->betting([$child['id']], $childFrom, null, $cursors)['effective']), 10);
  384. }
  385. $tasks = [];
  386. foreach (Rules::TASKS as $key) {
  387. $target = match ($key) { 'online' => $rules['online_seconds'], 'login', 'invite' => 1, default => $rules[$key . '_amount'] };
  388. $tasks[] = ['key' => $key, 'round_completed' => (bool)($flags[$key] ?? false), 'value' => $values[$key], 'target' => $target,
  389. 'today_rewarded' => in_array($key, $granted, true), 'reward_spins' => 1,
  390. 'remaining_seconds' => $key === 'online' ? max(0, $target - $values[$key]) : null];
  391. }
  392. return $tasks;
  393. }
  394. private function spinRow(object $row): array
  395. {
  396. return ['id' => $row->id, 'round_no' => $row->round_no, 'prize_index' => $row->prize_index, 'prize' => Rules::PRIZES[$row->prize_index],
  397. 'amount' => $this->money($row->amount_cents), 'coins' => $this->money($row->coins_cents), 'reached' => (int)$row->coins_cents === 66600,
  398. 'conditions_complete' => (bool)$row->conditions_complete, 'probability' => (string)$row->probability, 'created_at' => $row->created_at];
  399. }
  400. public function records(int $activityId, int $userId, int $page = 1, int $limit = 20): array
  401. {
  402. $this->activity($activityId); $this->member($userId);
  403. $account = DB::table('promotion_accounts')->where('activity_id', $activityId)->where('user_id', $userId)->first();
  404. if (!$account) return ['total' => 0, 'data' => []];
  405. $q = DB::table('promotion_spins')->where('account_id', $account->id);
  406. return ['total' => $q->count(), 'data' => $q->orderByDesc('id')->forPage($page, $limit)->get()->map(fn ($r) => $this->spinRow($r))->all()];
  407. }
  408. public function broadcasts(int $activityId): array
  409. {
  410. $activity = $this->activity($activityId);
  411. if ((int)$activity->type !== Rules::WHEEL) $this->invalid('该活动不是转盘活动');
  412. $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')
  413. ->where('a.activity_id', $activityId);
  414. $map = fn ($r) => ['account' => substr((string)$r->member_id, 0, strlen((string)$r->member_id) >= 10 ? 4 : 1) . '****' . substr((string)$r->member_id, -1),
  415. 'amount' => $this->money($r->amount_cents), 'created_at' => $r->created_at];
  416. return ['ordinary' => (clone $q)->orderByDesc('s.id')->limit(50)->get(['u.member_id', 's.amount_cents', 's.created_at'])->map($map)->all(),
  417. '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()];
  418. }
  419. public function rewards(int $activityId, int $userId, int $page = 1, int $limit = 20): array
  420. {
  421. $this->activity($activityId); $this->member($userId);
  422. $q = DB::table('promotion_rewards')->where('activity_id', $activityId)->where('user_id', $userId);
  423. return ['total' => $q->count(), 'data' => $q->orderByDesc('id')->forPage($page, $limit)->get()];
  424. }
  425. public function unlock(int $userId): int
  426. {
  427. return DB::transaction(function () use ($userId) {
  428. $member = $this->member($userId); $wallet = Wallet::where('member_id', $member->member_id)->lockForUpdate()->first();
  429. if (!$wallet) return 0;
  430. $count = 0;
  431. foreach (DB::table('promotion_rewards')->where('user_id', $userId)->where('status', 'locked')->orderBy('id')->lockForUpdate()->get() as $reward) {
  432. $snapshot = $this->json($reward->flow_snapshot);
  433. $effective = $this->facts->total($this->facts->betting([$userId], $snapshot['from'], null, $snapshot['cursors'])['effective']);
  434. if (bccomp($effective, (string)$reward->required_flow, 10) < 0) continue;
  435. if (bccomp((string)$wallet->frozen_balance, (string)$reward->amount, 10) < 0) $this->invalid('冻结奖励余额不足');
  436. $beforeFrozen = (string)$wallet->frozen_balance; $before = (string)$wallet->available_balance;
  437. $wallet->frozen_balance = bcsub($beforeFrozen, (string)$reward->amount, 10); $wallet->available_balance = bcadd($before, (string)$reward->amount, 10); $wallet->save();
  438. BalanceLog::create(['member_id' => $member->member_id, 'type' => 2, 'change_type' => '流水解冻', 'amount' => bcsub('0', (string)$reward->amount, 2),
  439. 'before_balance' => $beforeFrozen, 'after_balance' => $wallet->frozen_balance, 'related_id' => $reward->id, 'remark' => '新活动奖励解冻']);
  440. $log = BalanceLog::create(['member_id' => $member->member_id, 'type' => 1, 'change_type' => '流水解冻', 'amount' => $reward->amount,
  441. 'before_balance' => $before, 'after_balance' => $wallet->available_balance, 'related_id' => $reward->id, 'remark' => '新活动奖励解冻']);
  442. DB::table('balance_logs')->where('id', $reward->credited_log_id)->update(['frozen_status' => 2]);
  443. 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;
  444. }
  445. return $count;
  446. }, 3);
  447. }
  448. }