PromotionAdminService.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. <?php
  2. namespace App\Services;
  3. use App\Models\PromotionActivity;
  4. use App\Services\Sharing\ShareDefaults;
  5. use App\Support\PromotionRules;
  6. use App\Support\PromotionTranslations;
  7. use App\Support\ActivityPeriod;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Schema;
  10. use Illuminate\Support\Facades\Validator;
  11. use Illuminate\Validation\ValidationException;
  12. class PromotionAdminService
  13. {
  14. public function options(): array
  15. {
  16. $types = []; foreach (PromotionRules::types() as $value => $label) $types[] = compact('value', 'label');
  17. return ['types' => $types, 'languages' => [['value' => 'zh', 'label' => '中文'], ['value' => 'en', 'label' => '英文'], ['value' => 'vi', 'label' => '越南文']],
  18. 'create_types' => [['value' => PromotionRules::FIRST_DEPOSIT, 'label' => PromotionRules::types()[PromotionRules::FIRST_DEPOSIT]]],
  19. 'defaults' => [7 => PromotionRules::defaults(7), 8 => PromotionRules::defaults(8), 9 => PromotionRules::defaults(9), 10 => PromotionRules::defaults(10)],
  20. 'share_levels' => $this->shareLevels(),
  21. 'prizes' => PromotionRules::PRIZES, 'tasks' => PromotionRules::TASKS,
  22. 'reward_modes' => [['value' => 'cash', 'label' => '现金'], ['value' => 'coupon', 'label' => '优惠券']],
  23. 'coupon_categories' => array_map(fn ($value) => ['value' => $value, 'label' => ShareDefaults::categories()[$value]], PromotionRules::COUPON_CATEGORIES)];
  24. }
  25. /** 全部首充活动共用的“禁止投注游戏大类”设置;选项与返佣规则的游戏大类一致。 */
  26. public function firstDepositRestriction(): array
  27. {
  28. return ['categories' => PromotionRules::forbiddenSetting(), 'options' => $this->forbiddenOptions(ShareDefaults::commissionCategories())];
  29. }
  30. public function saveFirstDepositRestriction(array $input): array
  31. {
  32. if (!array_key_exists('categories', $input)) throw ValidationException::withMessages(['categories' => '请传categories,不限制时传空数组']);
  33. $categories = PromotionRules::forbiddenCategories($input['categories']);
  34. if (count($categories) === count(ShareDefaults::commissionCategories())) {
  35. throw ValidationException::withMessages(['categories' => '至少保留一个可投注的游戏大类']);
  36. }
  37. DB::transaction(function () use ($categories) {
  38. $before = PromotionRules::forbiddenSetting();
  39. DB::table('config')->updateOrInsert(['field' => PromotionRules::FORBIDDEN_CONFIG], ['val' => json_encode($categories)]);
  40. if (Schema::hasTable('operation_audits')) {
  41. OperationAuditService::record('promotion_first_deposit_restriction', null, 'update', ['categories' => $before], ['categories' => $categories]);
  42. }
  43. }, 3);
  44. return $this->firstDepositRestriction();
  45. }
  46. private function forbiddenOptions(array $categories): array
  47. {
  48. $options = [];
  49. foreach ($categories as $value => $label) $options[] = ['value' => $value, 'label' => $label];
  50. return $options;
  51. }
  52. public function listing(array $input): array
  53. {
  54. $input = Validator::make($input, ['page' => ['sometimes', 'integer', 'min:1'], 'limit' => ['sometimes', 'integer', 'between:1,100'],
  55. 'type' => ['sometimes', 'integer', 'in:7,8,9,10'], 'status' => ['sometimes', 'integer', 'in:0,1'], 'title' => ['sometimes', 'string', 'max:140']])->validate();
  56. $q = PromotionActivity::query();
  57. foreach (['type', 'status'] as $key) if (isset($input[$key])) $q->where($key, $input[$key]);
  58. if (!empty($input['title'])) $q->where('title', 'like', '%' . $input['title'] . '%');
  59. return ['total' => $q->count(), 'data' => $q->orderByDesc('sort')->orderByDesc('id')->forPage($input['page'] ?? 1, $input['limit'] ?? 20)->get()->map(fn ($r) => $this->format($r))->all()];
  60. }
  61. /** Fixed activities (loss invite, wheel, upgrade invite) have one row, so the flat edit form can load it by type alone. */
  62. public function detail(?int $id, ?int $type = null): array
  63. {
  64. if ($id === null && !in_array($type, PromotionRules::FIXED, true)) {
  65. throw ValidationException::withMessages(['type' => '仅净亏邀请、转盘活动和邀请升级奖励可按type读取']);
  66. }
  67. $row = $id !== null ? PromotionActivity::find($id) : PromotionActivity::where('type', $type)->orderBy('id')->first();
  68. if (!$row) throw ValidationException::withMessages(['id' => '独立活动不存在']);
  69. return $this->format($row);
  70. }
  71. private function format(PromotionActivity $row): array
  72. {
  73. $data = array_replace($row->toArray(), ['translations' => PromotionTranslations::all($row->toArray()), 'params' => json_decode($row->params, true),
  74. 'start_time' => $row->start_time === null ? null : date('Y-m-d H:i:s', (int)$row->start_time), 'end_time' => $row->end_time === null ? null : date('Y-m-d H:i:s', (int)$row->end_time),
  75. 'first_published_at' => DB::table('promotion_campaigns')->where('activity_id', $row->id)->value('first_published_at')]);
  76. unset($data['sub_title']);
  77. // 禁止投注的游戏大类改为全部首充活动共用的设置,不在单个活动里返回旧值。
  78. if ((int) $row->type === PromotionRules::FIRST_DEPOSIT && is_array($data['params'])) unset($data['params']['forbidden_categories']);
  79. if (in_array((int) $row->type, PromotionRules::FIXED, true)) unset($data['image']);
  80. if (PromotionTranslations::fields((int) $row->type) === ['content']) {
  81. foreach ($data['translations'] as &$text) unset($text['title']);
  82. unset($text);
  83. }
  84. return $data;
  85. }
  86. public function save(array $input): array
  87. {
  88. unset($input['sub_title']);
  89. $type = (int)(is_scalar($input['type'] ?? null) ? $input['type'] : 0);
  90. $fields = PromotionTranslations::fields($type);
  91. if (isset($input['translations']) && is_array($input['translations'])) {
  92. foreach ($input['translations'] as &$text) if (is_array($text)) { unset($text['sub_title']); if (!in_array('title', $fields, true)) unset($text['title']); }
  93. unset($text);
  94. }
  95. if (in_array((string)($input['type'] ?? ''), array_map('strval', PromotionRules::FIXED), true)) unset($input['image']);
  96. $money = ['nullable', 'numeric', 'min:0', 'regex:/^\d{1,12}(\.\d{1,2})?$/'];
  97. $textRules = ['translations' => ['required', 'array:zh,en,vi']];
  98. $messages = ['start_time.required_with' => '活动开始和结束时间必须同时填写或同时留空', 'end_time.required_with' => '活动开始和结束时间必须同时填写或同时留空', 'translations.required' => '请完整填写中文、英文、越南文的' . ($fields === ['content'] ? '正文' : '标题和正文')];
  99. foreach (['zh' => '中文', 'en' => '英文', 'vi' => '越南文'] as $lang => $label) {
  100. $textRules['translations.' . $lang] = ['required', 'array:' . implode(',', $fields)];
  101. $messages['translations.' . $lang . '.required'] = '请完整填写' . $label . '文本';
  102. foreach (array_intersect_key(['title' => ['标题', 140], 'content' => ['正文', 100000]], array_flip($fields)) as $field => [$name, $max]) {
  103. $key = 'translations.' . $lang . '.' . $field;
  104. $textRules[$key] = ['required', 'string', 'max:' . $max];
  105. $messages[$key . '.required'] = $label . $name . '不能为空';
  106. }
  107. }
  108. $data = Validator::make($input, $textRules + ['id' => ['sometimes', 'integer', 'min:1'],
  109. 'type' => ['required', 'integer', 'in:7,8,9,10'], 'status' => ['required', 'integer', 'in:0,1'],
  110. 'start_time' => ['nullable', 'required_with:end_time', 'date'], 'end_time' => ['nullable', 'required_with:start_time', 'date', 'after:start_time'],
  111. 'sort' => ['sometimes', 'integer', 'between:0,4294967295'], 'params' => ['sometimes', 'array'],
  112. 'image' => ['sometimes', 'nullable', 'string', 'max:2048'], 'publish_platforms' => ['sometimes', 'array'], 'publish_platforms.*' => ['string', 'distinct', 'in:PC,H5,APP'],
  113. 'register_time_limited' => ['sometimes', 'boolean'], 'register_start_time' => ['nullable', 'required_if:register_time_limited,1', 'date'],
  114. 'register_end_time' => ['nullable', 'required_if:register_time_limited,1', 'date', 'after_or_equal:register_start_time'],
  115. 'register_platforms' => ['sometimes', 'array'], 'register_platforms.*' => ['string', 'distinct', 'in:PC,H5,APP'], 'deposit_limited' => ['sometimes', 'boolean'],
  116. 'deposit_min' => [...$money, 'required_if:deposit_limited,1'], 'deposit_max' => [...$money, 'required_if:deposit_limited,1', 'gte:deposit_min'],
  117. 'show_ineligible' => ['sometimes', 'boolean'], 'reward_quota' => ['sometimes', 'nullable', 'integer', 'between:0,2147483647'], 'budget' => ['sometimes', ...$money]], $messages)->validate();
  118. if (!isset($data['id']) && in_array((int) $data['type'], PromotionRules::FIXED, true)) {
  119. throw ValidationException::withMessages(['id' => '净亏、转盘和邀请升级活动不支持新增,请编辑现有活动']);
  120. }
  121. return DB::transaction(function () use ($data) {
  122. $row = isset($data['id']) ? PromotionActivity::where('id', $data['id'])->lockForUpdate()->first() : new PromotionActivity();
  123. if (!$row) throw ValidationException::withMessages(['id' => '独立活动不存在']);
  124. if ($row->exists && (int)$row->type !== (int)$data['type']) throw ValidationException::withMessages(['type' => '创建后不能变更活动类型']);
  125. $before = $row->exists ? $row->toArray() : [];
  126. $params = array_replace($row->params ? json_decode($row->params, true) : [], $data['params'] ?? []);
  127. $values = $data; unset($values['id']);
  128. $texts = $this->completeTexts($data['translations'], (int)$data['type']);
  129. $values = array_replace($values, $texts['zh'], ['translations' => $texts, 'lang' => 'zh']);
  130. // Content-only activities keep the type name in the required title column for admin lists.
  131. if ($values['title'] === '') $values['title'] = PromotionRules::types()[(int)$data['type']];
  132. $rules = PromotionRules::normalize((int)$data['type'], $params);
  133. if ((int)$data['type'] === PromotionRules::UPGRADE_INVITE) $this->checkUpgradeTiers($rules, (int)$values['status'] === 1);
  134. $values['params'] = json_encode($rules);
  135. $values = array_replace($values, ActivityPeriod::forSave($data, $row->exists, true));
  136. $endTime = array_key_exists('end_time', $values) ? $values['end_time'] : $row->end_time;
  137. if ((int)$values['status'] === 1 && $endTime !== null && $endTime < now()->timestamp) throw ValidationException::withMessages(['end_time' => '活动已结束,不能上架']);
  138. if (!$row->exists) $values += ['lang' => 'zh', 'sort' => 0, 'publish_platforms' => [], 'register_platforms' => []];
  139. $row->fill($values); $row->save(); PromotionService::publish($row);
  140. if (Schema::hasTable('operation_audits')) OperationAuditService::record('promotion', $row->id, $before ? 'update' : 'create', $before, $row->toArray());
  141. return $this->format($row);
  142. }, 3);
  143. }
  144. /** Tier levels must be configured share levels; an empty tier list may be saved but not published. */
  145. private function checkUpgradeTiers(array $rules, bool $publishing): void
  146. {
  147. if ($publishing && !$rules['tiers']) throw ValidationException::withMessages(['params' => '请至少配置一档升级奖励']);
  148. $levels = array_column($this->shareLevels(), 'level');
  149. foreach ($rules['tiers'] as $tier) {
  150. if (!in_array($tier['level'], $levels, true)) throw ValidationException::withMessages(['params' => '分享等级' . $tier['level'] . '不存在']);
  151. }
  152. }
  153. private function shareLevels(): array
  154. {
  155. if (!Schema::hasTable('share_levels')) return [];
  156. return DB::table('share_levels')->orderBy('level')->get(['level', 'name'])
  157. ->map(fn ($row) => ['level' => (int)$row->level, 'name' => (string)$row->name])->all();
  158. }
  159. private function completeTexts(array $texts, int $type): array
  160. {
  161. $fields = PromotionTranslations::fields($type);
  162. foreach (['zh' => '中文', 'en' => '英文', 'vi' => '越南文'] as $lang => $label) {
  163. $texts[$lang] += ['title' => ''];
  164. foreach (array_intersect_key(['title' => '标题', 'content' => '正文'], array_flip($fields)) as $field => $name) {
  165. $value = html_entity_decode(strip_tags($texts[$lang][$field]), ENT_QUOTES | ENT_HTML5, 'UTF-8');
  166. if (preg_replace('/[\s\p{Z}\x{200B}\x{FEFF}]+/u', '', $value) === '') {
  167. throw ValidationException::withMessages(['translations.' . $lang . '.' . $field => $label . $name . '不能为空']);
  168. }
  169. if ($field !== 'content') $texts[$lang][$field] = trim($texts[$lang][$field]);
  170. }
  171. }
  172. return $texts;
  173. }
  174. public function status(int $id, int $status): array
  175. {
  176. return DB::transaction(function () use ($id, $status) {
  177. $row = PromotionActivity::where('id', $id)->lockForUpdate()->first();
  178. if (!$row) throw ValidationException::withMessages(['id' => '独立活动不存在']);
  179. if ($status === 1) $this->completeTexts(PromotionTranslations::all($row->toArray()), (int)$row->type);
  180. if ($status === 1 && $row->end_time !== null && (int)$row->end_time < now()->timestamp) throw ValidationException::withMessages(['end_time' => '活动已结束,不能上架']);
  181. if ($status === 1 && (int)$row->type === PromotionRules::UPGRADE_INVITE) {
  182. $this->checkUpgradeTiers(PromotionRules::normalize(PromotionRules::UPGRADE_INVITE, json_decode($row->params, true) ?: []), true);
  183. }
  184. $before = $row->toArray(); $row->status = $status; $row->save(); PromotionService::publish($row);
  185. if (Schema::hasTable('operation_audits')) OperationAuditService::record('promotion', $id, 'status', $before, $row->toArray());
  186. return $this->format($row);
  187. }, 3);
  188. }
  189. /** Takes ended activities off the shelf; each change is audited like a manual status switch. */
  190. public static function expire(): int
  191. {
  192. $expired = 0;
  193. foreach (PromotionActivity::where('status', 1)->where('end_time', '<', now()->timestamp)->pluck('id') as $id) {
  194. $expired += DB::transaction(function () use ($id) {
  195. $row = PromotionActivity::where('id', $id)->lockForUpdate()->first();
  196. if (!$row || (int)$row->status !== 1 || $row->end_time === null || (int)$row->end_time >= now()->timestamp) return 0;
  197. $before = $row->toArray(); $row->status = 0; $row->save();
  198. if (Schema::hasTable('operation_audits')) OperationAuditService::record('promotion', $id, 'expire', $before, $row->toArray(), null, ['operator_id' => null, 'operator_name' => '系统']);
  199. return 1;
  200. }, 3);
  201. }
  202. return $expired;
  203. }
  204. public function records(array $input): array
  205. {
  206. $input = Validator::make($input, ['activity_id' => ['required', 'integer', 'min:1'], 'type' => ['sometimes', 'integer', 'in:7,8,9,10'], 'user_id' => ['sometimes', 'integer', 'min:1'],
  207. 'kind' => ['required', 'in:accounts,rounds,tasks,spins,rewards,coupons,upgrades'], 'status' => ['sometimes', 'in:unused,used'],
  208. 'page' => ['sometimes', 'integer', 'min:1'], 'limit' => ['sometimes', 'integer', 'between:1,100']])->validate();
  209. // An explicit type guards against a misconfigured activity_id showing another campaign's records.
  210. $type = DB::table('promotion_activities')->where('id', $input['activity_id'])->value('type');
  211. if ($type === null) throw ValidationException::withMessages(['activity_id' => '独立活动不存在']);
  212. if (isset($input['type']) && (int)$input['type'] !== (int)$type) throw ValidationException::withMessages(['type' => 'activity_id与type不匹配']);
  213. if ($input['kind'] === 'upgrades' && (int)$type !== PromotionRules::UPGRADE_INVITE) throw ValidationException::withMessages(['kind' => 'upgrades仅用于邀请升级奖励']);
  214. if ($input['kind'] === 'coupons') {
  215. // Invitee coupons belong to the invitee, so they are found by activity rather than by the inviter's account.
  216. $q = DB::table('promotion_coupons')->where('activity_id', $input['activity_id']);
  217. if (isset($input['user_id'])) $q->where(fn ($q) => $q->where('user_id', $input['user_id'])->orWhere('inviter_user_id', $input['user_id']));
  218. if (isset($input['status'])) $q->where('status', $input['status']);
  219. $rows = (clone $q)->orderByDesc('id')->forPage($input['page'] ?? 1, $input['limit'] ?? 20)->get()
  220. ->map(function ($row) { $row->categories = json_decode($row->categories, true); return $row; });
  221. $accounts = $this->recordAccounts($rows->flatMap(fn ($row) => [$row->user_id, $row->inviter_user_id])->all());
  222. foreach ($rows as $row) {
  223. $row->account = $accounts[(int)$row->user_id] ?? null;
  224. $row->inviter_account = $accounts[(int)$row->inviter_user_id] ?? null;
  225. }
  226. return ['total' => $q->count(), 'data' => $rows];
  227. }
  228. if ($input['kind'] === 'upgrades') return $this->upgradeGrants($input);
  229. $q = DB::table('promotion_accounts as a')->where('a.activity_id', $input['activity_id']);
  230. if (isset($input['user_id'])) $q->where('a.user_id', $input['user_id']);
  231. if ($input['kind'] === 'accounts') $q->select('a.*')->orderByDesc('a.id');
  232. else {
  233. $table = match ($input['kind']) { 'rounds' => 'promotion_rounds', 'tasks' => 'promotion_task_grants', 'spins' => 'promotion_spins', 'rewards' => 'promotion_rewards' };
  234. $q->join($table . ' as r', 'r.account_id', '=', 'a.id')->select(['r.*', 'a.user_id', 'a.activity_id'])->orderByDesc('r.id');
  235. }
  236. $total = (clone $q)->count();
  237. $rows = $q->forPage($input['page'] ?? 1, $input['limit'] ?? 20)->get();
  238. if (in_array($input['kind'], ['accounts', 'rewards'], true) && $rows->isNotEmpty() && (int)$type === PromotionRules::LOSS) {
  239. $this->lossRecordPeople($rows, $input['kind']);
  240. }
  241. return ['total' => $total, 'data' => $rows];
  242. }
  243. /** Upgrade invite payouts, one row per invitee tier; user_id matches either the inviter or the invitee. */
  244. private function upgradeGrants(array $input): array
  245. {
  246. $q = DB::table('promotion_upgrade_grants')->where('activity_id', $input['activity_id']);
  247. if (isset($input['user_id'])) $q->where(fn ($q) => $q->where('inviter_user_id', $input['user_id'])->orWhere('invitee_user_id', $input['user_id']));
  248. $rows = (clone $q)->orderByDesc('id')->forPage($input['page'] ?? 1, $input['limit'] ?? 20)->get();
  249. $accounts = $this->recordAccounts($rows->flatMap(fn ($row) => [$row->inviter_user_id, $row->invitee_user_id])->all());
  250. $names = array_column($this->shareLevels(), 'name', 'level');
  251. foreach ($rows as $row) {
  252. $row->inviter_account = $accounts[(int)$row->inviter_user_id] ?? null;
  253. $row->invitee_account = $accounts[(int)$row->invitee_user_id] ?? null;
  254. $row->level_name = $names[(int)$row->level] ?? null;
  255. $row->invitee_level_name = $names[(int)$row->invitee_level] ?? null;
  256. }
  257. return ['total' => $q->count(), 'data' => $rows];
  258. }
  259. /** Loss-invite record display only: historical recipients and actual issued coupon quantities. */
  260. private function lossRecordPeople($rows, string $kind): void
  261. {
  262. // Loss invite repeats; an application row shows its latest claim, and applied_at belongs to the current round.
  263. $all = $kind === 'rewards' ? $rows : DB::table('promotion_rewards')->whereIn('account_id', $rows->pluck('id'))->orderBy('round_no')->get();
  264. $claimed = $all->countBy('account_id');
  265. $rewards = $kind === 'rewards' ? $rows : $all->keyBy('account_id')->values();
  266. $byAccount = $rewards->keyBy('account_id');
  267. $couponRewards = $rewards->filter(fn ($reward) => ($this->recordSnapshot($reward->rule_snapshot)['reward_mode'] ?? 'cash') === 'coupon');
  268. $groups = $couponRewards->isEmpty() ? collect() : DB::table('promotion_coupons')->whereIn('reward_id', $couponRewards->pluck('id'))
  269. ->select(['reward_id', 'user_id', 'role', 'min_amount', 'discount'])->selectRaw('COUNT(*) AS quantity')
  270. ->groupBy('reward_id', 'user_id', 'role', 'min_amount', 'discount')->orderBy('min_amount')->orderBy('discount')->get();
  271. $coupons = $issuedInvitees = [];
  272. $people = $rows->pluck('user_id')->all();
  273. foreach ($groups as $group) {
  274. $coupons[(int)$group->reward_id][(int)$group->user_id][$group->role][] = [
  275. 'min_amount' => bcadd((string)$group->min_amount, '0', 2), 'discount' => bcadd((string)$group->discount, '0', 2), 'quantity' => (int)$group->quantity,
  276. ];
  277. if ($group->role === 'invitee') $issuedInvitees[(int)$group->reward_id][] = (int)$group->user_id;
  278. $people[] = (int)$group->user_id;
  279. }
  280. $contexts = [];
  281. foreach ($rows as $row) {
  282. $reward = $kind === 'rewards' ? $row : $byAccount->get($row->id);
  283. $application = $this->recordSnapshot($row->application_snapshot ?? null);
  284. $rules = $reward ? $this->recordSnapshot($reward->rule_snapshot) : ($application['rules'] ?? []);
  285. if (!is_array($rules)) $rules = [];
  286. $mode = ($reward || $rules) ? ($rules['reward_mode'] ?? 'cash') : null;
  287. $ids = $mode === 'coupon' && isset($rules['coupon_invitees']) ? $rules['coupon_invitees'] : ($rules['qualified_invitees'] ?? []);
  288. $ids = $this->recordIds(array_merge(is_array($ids) ? $ids : [], $issuedInvitees[(int)($reward->id ?? 0)] ?? []));
  289. $contexts[] = [$row, $reward, in_array($mode, ['cash', 'coupon'], true) ? $mode : null, $ids];
  290. $people = array_merge($people, $ids);
  291. }
  292. $accounts = $this->recordAccounts($people);
  293. foreach ($contexts as [$row, $reward, $mode, $ids]) {
  294. $rewardId = (int)($reward->id ?? 0); $owner = (int)$row->user_id;
  295. $row->reward_mode = $mode;
  296. if ($kind === 'accounts') {
  297. $row->reward_id = $reward ? (int)$reward->id : null;
  298. $row->reward_status = $reward ? $reward->status : null;
  299. $row->reward_round_no = $reward ? (int)$reward->round_no : null;
  300. $row->claimed_count = (int)($claimed[$row->id] ?? 0);
  301. }
  302. $row->inviter = ['id' => $owner, 'account' => $accounts[$owner] ?? null, 'coupons' => $coupons[$rewardId][$owner]['inviter'] ?? []];
  303. $row->invitees = array_map(fn ($id) => ['id' => $id, 'account' => $accounts[$id] ?? null,
  304. 'coupons' => $coupons[$rewardId][$id]['invitee'] ?? []], $ids);
  305. }
  306. }
  307. private function recordSnapshot($value): array
  308. {
  309. $value = is_string($value) ? json_decode($value, true) : $value;
  310. return is_array($value) ? $value : [];
  311. }
  312. private function recordIds(array $ids): array
  313. {
  314. $valid = [];
  315. foreach ($ids as $id) {
  316. $id = is_int($id) || is_string($id) ? filter_var($id, FILTER_VALIDATE_INT) : false;
  317. if ($id !== false && $id > 0) $valid[$id] = $id;
  318. }
  319. return array_values($valid);
  320. }
  321. private function recordAccounts(array $ids): array
  322. {
  323. $accounts = [];
  324. foreach (array_chunk($this->recordIds($ids), 1000) as $chunk) {
  325. foreach (DB::table('users')->whereIn('id', $chunk)->get(['id', 'account']) as $user) {
  326. $accounts[(int)$user->id] = $user->account === null || $user->account === '' ? null : (string)$user->account;
  327. }
  328. }
  329. return $accounts;
  330. }
  331. }