PromotionAdminService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. <?php
  2. namespace App\Services;
  3. use App\Models\PromotionActivity;
  4. use App\Support\PromotionRules;
  5. use App\Support\PromotionTranslations;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Schema;
  8. use Illuminate\Support\Facades\Validator;
  9. use Illuminate\Validation\ValidationException;
  10. class PromotionAdminService
  11. {
  12. public function options(): array
  13. {
  14. $types = []; foreach (PromotionRules::types() as $value => $label) $types[] = compact('value', 'label');
  15. return ['types' => $types, 'languages' => [['value' => 'zh', 'label' => '中文'], ['value' => 'en', 'label' => '英文'], ['value' => 'vi', 'label' => '越南文']],
  16. 'create_types' => [['value' => PromotionRules::FIRST_DEPOSIT, 'label' => PromotionRules::types()[PromotionRules::FIRST_DEPOSIT]]],
  17. 'defaults' => [7 => PromotionRules::defaults(7), 8 => PromotionRules::defaults(8), 9 => PromotionRules::defaults(9)],
  18. 'prizes' => PromotionRules::PRIZES, 'tasks' => PromotionRules::TASKS];
  19. }
  20. public function listing(array $input): array
  21. {
  22. $input = Validator::make($input, ['page' => ['sometimes', 'integer', 'min:1'], 'limit' => ['sometimes', 'integer', 'between:1,100'],
  23. 'type' => ['sometimes', 'integer', 'in:7,8,9'], 'status' => ['sometimes', 'integer', 'in:0,1'], 'title' => ['sometimes', 'string', 'max:140']])->validate();
  24. $q = PromotionActivity::query();
  25. foreach (['type', 'status'] as $key) if (isset($input[$key])) $q->where($key, $input[$key]);
  26. if (!empty($input['title'])) $q->where('title', 'like', '%' . $input['title'] . '%');
  27. 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()];
  28. }
  29. public function detail(int $id): array
  30. {
  31. $row = PromotionActivity::find($id);
  32. if (!$row) throw ValidationException::withMessages(['id' => '独立活动不存在']);
  33. return $this->format($row);
  34. }
  35. private function format(PromotionActivity $row): array
  36. {
  37. $data = array_replace($row->toArray(), ['translations' => PromotionTranslations::all($row->toArray()), 'params' => json_decode($row->params, true),
  38. '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),
  39. 'first_published_at' => DB::table('promotion_campaigns')->where('activity_id', $row->id)->value('first_published_at')]);
  40. unset($data['sub_title']);
  41. if (in_array((int) $row->type, [PromotionRules::LOSS, PromotionRules::WHEEL], true)) unset($data['image']);
  42. return $data;
  43. }
  44. public function save(array $input): array
  45. {
  46. unset($input['sub_title']);
  47. if (isset($input['translations']) && is_array($input['translations'])) {
  48. foreach ($input['translations'] as &$text) if (is_array($text)) unset($text['sub_title']);
  49. unset($text);
  50. }
  51. if (in_array($input['type'] ?? null, [7, 9, '7', '9'], true)) unset($input['image']);
  52. $money = ['nullable', 'numeric', 'min:0', 'regex:/^\d{1,12}(\.\d{1,2})?$/'];
  53. $textRules = ['translations' => ['required', 'array:zh,en,vi']];
  54. $messages = ['translations.required' => '请完整填写中文、英文、越南文的标题和正文'];
  55. foreach (['zh' => '中文', 'en' => '英文', 'vi' => '越南文'] as $lang => $label) {
  56. $textRules['translations.' . $lang] = ['required', 'array:title,content'];
  57. $messages['translations.' . $lang . '.required'] = '请完整填写' . $label . '文本';
  58. foreach (['title' => ['标题', 140], 'content' => ['正文', 100000]] as $field => [$name, $max]) {
  59. $key = 'translations.' . $lang . '.' . $field;
  60. $textRules[$key] = ['required', 'string', 'max:' . $max];
  61. $messages[$key . '.required'] = $label . $name . '不能为空';
  62. }
  63. }
  64. $data = Validator::make($input, $textRules + ['id' => ['sometimes', 'integer', 'min:1'],
  65. 'type' => ['required', 'integer', 'in:7,8,9'], 'status' => ['required', 'integer', 'in:0,1'],
  66. 'start_time' => ['required', 'date'], 'end_time' => ['required', 'date', 'after:start_time'],
  67. 'sort' => ['sometimes', 'integer', 'between:0,4294967295'], 'params' => ['sometimes', 'array'],
  68. 'image' => ['sometimes', 'nullable', 'string', 'max:2048'], 'publish_platforms' => ['sometimes', 'array'], 'publish_platforms.*' => ['string', 'distinct', 'in:PC,H5,APP'],
  69. 'register_time_limited' => ['sometimes', 'boolean'], 'register_start_time' => ['nullable', 'required_if:register_time_limited,1', 'date'],
  70. 'register_end_time' => ['nullable', 'required_if:register_time_limited,1', 'date', 'after_or_equal:register_start_time'],
  71. 'register_platforms' => ['sometimes', 'array'], 'register_platforms.*' => ['string', 'distinct', 'in:PC,H5,APP'], 'deposit_limited' => ['sometimes', 'boolean'],
  72. 'deposit_min' => [...$money, 'required_if:deposit_limited,1'], 'deposit_max' => [...$money, 'required_if:deposit_limited,1', 'gte:deposit_min'],
  73. 'show_ineligible' => ['sometimes', 'boolean'], 'reward_quota' => ['sometimes', 'nullable', 'integer', 'between:0,2147483647'], 'budget' => ['sometimes', ...$money]], $messages)->validate();
  74. if (!isset($data['id']) && in_array((int) $data['type'], [PromotionRules::LOSS, PromotionRules::WHEEL], true)) {
  75. throw ValidationException::withMessages(['id' => '净亏和转盘活动不支持新增,请编辑现有活动']);
  76. }
  77. return DB::transaction(function () use ($data) {
  78. $row = isset($data['id']) ? PromotionActivity::where('id', $data['id'])->lockForUpdate()->first() : new PromotionActivity();
  79. if (!$row) throw ValidationException::withMessages(['id' => '独立活动不存在']);
  80. if ($row->exists && (int)$row->type !== (int)$data['type']) throw ValidationException::withMessages(['type' => '创建后不能变更活动类型']);
  81. $before = $row->exists ? $row->toArray() : [];
  82. $params = array_replace($row->params ? json_decode($row->params, true) : [], $data['params'] ?? []);
  83. $values = $data; unset($values['id']);
  84. $texts = $this->completeTexts($data['translations']);
  85. $values = array_replace($values, $texts['zh'], ['translations' => $texts, 'lang' => 'zh']);
  86. $values['params'] = json_encode(PromotionRules::normalize((int)$data['type'], $params));
  87. $values['start_time'] = strtotime($data['start_time']); $values['end_time'] = strtotime($data['end_time']);
  88. if ((int)$values['status'] === 1 && $values['end_time'] < now()->timestamp) throw ValidationException::withMessages(['end_time' => '活动已结束,不能上架']);
  89. if (!$row->exists) $values += ['lang' => 'zh', 'sort' => 0, 'publish_platforms' => [], 'register_platforms' => []];
  90. $row->fill($values); $row->save(); PromotionService::publish($row);
  91. if (Schema::hasTable('operation_audits')) OperationAuditService::record('promotion', $row->id, $before ? 'update' : 'create', $before, $row->toArray());
  92. return $this->format($row);
  93. }, 3);
  94. }
  95. private function completeTexts(array $texts): array
  96. {
  97. foreach (['zh' => '中文', 'en' => '英文', 'vi' => '越南文'] as $lang => $label) {
  98. foreach (['title' => '标题', 'content' => '正文'] as $field => $name) {
  99. $value = html_entity_decode(strip_tags($texts[$lang][$field]), ENT_QUOTES | ENT_HTML5, 'UTF-8');
  100. if (preg_replace('/[\s\p{Z}\x{200B}\x{FEFF}]+/u', '', $value) === '') {
  101. throw ValidationException::withMessages(['translations.' . $lang . '.' . $field => $label . $name . '不能为空']);
  102. }
  103. if ($field !== 'content') $texts[$lang][$field] = trim($texts[$lang][$field]);
  104. }
  105. }
  106. return $texts;
  107. }
  108. public function status(int $id, int $status): array
  109. {
  110. return DB::transaction(function () use ($id, $status) {
  111. $row = PromotionActivity::where('id', $id)->lockForUpdate()->first();
  112. if (!$row) throw ValidationException::withMessages(['id' => '独立活动不存在']);
  113. if ($status === 1) $this->completeTexts(PromotionTranslations::all($row->toArray()));
  114. if ($status === 1 && (int)$row->end_time < now()->timestamp) throw ValidationException::withMessages(['end_time' => '活动已结束,不能上架']);
  115. $before = $row->toArray(); $row->status = $status; $row->save(); PromotionService::publish($row);
  116. if (Schema::hasTable('operation_audits')) OperationAuditService::record('promotion', $id, 'status', $before, $row->toArray());
  117. return $this->format($row);
  118. }, 3);
  119. }
  120. /** Takes ended activities off the shelf; each change is audited like a manual status switch. */
  121. public static function expire(): int
  122. {
  123. $expired = 0;
  124. foreach (PromotionActivity::where('status', 1)->where('end_time', '<', now()->timestamp)->pluck('id') as $id) {
  125. $expired += DB::transaction(function () use ($id) {
  126. $row = PromotionActivity::where('id', $id)->lockForUpdate()->first();
  127. if (!$row || (int)$row->status !== 1 || (int)$row->end_time >= now()->timestamp) return 0;
  128. $before = $row->toArray(); $row->status = 0; $row->save();
  129. if (Schema::hasTable('operation_audits')) OperationAuditService::record('promotion', $id, 'expire', $before, $row->toArray(), null, ['operator_id' => null, 'operator_name' => '系统']);
  130. return 1;
  131. }, 3);
  132. }
  133. return $expired;
  134. }
  135. public function records(array $input): array
  136. {
  137. $input = Validator::make($input, ['activity_id' => ['required', 'integer', 'min:1'], 'user_id' => ['sometimes', 'integer', 'min:1'],
  138. 'kind' => ['required', 'in:accounts,rounds,tasks,spins,rewards'], 'page' => ['sometimes', 'integer', 'min:1'], 'limit' => ['sometimes', 'integer', 'between:1,100']])->validate();
  139. $q = DB::table('promotion_accounts as a')->where('a.activity_id', $input['activity_id']);
  140. if (isset($input['user_id'])) $q->where('a.user_id', $input['user_id']);
  141. if ($input['kind'] === 'accounts') $q->select('a.*')->orderByDesc('a.id');
  142. else {
  143. $table = match ($input['kind']) { 'rounds' => 'promotion_rounds', 'tasks' => 'promotion_task_grants', 'spins' => 'promotion_spins', 'rewards' => 'promotion_rewards' };
  144. $q->join($table . ' as r', 'r.account_id', '=', 'a.id')->select(['r.*', 'a.user_id', 'a.activity_id'])->orderByDesc('r.id');
  145. }
  146. return ['total' => $q->count(), 'data' => $q->forPage($input['page'] ?? 1, $input['limit'] ?? 20)->get()];
  147. }
  148. }