PromotionService.php 36 KB

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