PromotionAdminService.php 22 KB

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