PromotionAdminService.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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 (!$row->exists) $values += ['lang' => 'zh', 'sort' => 0, 'publish_platforms' => [], 'register_platforms' => []];
  89. $row->fill($values); $row->save(); PromotionService::publish($row);
  90. if (Schema::hasTable('operation_audits')) OperationAuditService::record('promotion', $row->id, $before ? 'update' : 'create', $before, $row->toArray());
  91. return $this->format($row);
  92. }, 3);
  93. }
  94. private function completeTexts(array $texts): array
  95. {
  96. foreach (['zh' => '中文', 'en' => '英文', 'vi' => '越南文'] as $lang => $label) {
  97. foreach (['title' => '标题', 'content' => '正文'] as $field => $name) {
  98. $value = html_entity_decode(strip_tags($texts[$lang][$field]), ENT_QUOTES | ENT_HTML5, 'UTF-8');
  99. if (preg_replace('/[\s\p{Z}\x{200B}\x{FEFF}]+/u', '', $value) === '') {
  100. throw ValidationException::withMessages(['translations.' . $lang . '.' . $field => $label . $name . '不能为空']);
  101. }
  102. if ($field !== 'content') $texts[$lang][$field] = trim($texts[$lang][$field]);
  103. }
  104. }
  105. return $texts;
  106. }
  107. public function status(int $id, int $status): array
  108. {
  109. return DB::transaction(function () use ($id, $status) {
  110. $row = PromotionActivity::where('id', $id)->lockForUpdate()->first();
  111. if (!$row) throw ValidationException::withMessages(['id' => '独立活动不存在']);
  112. if ($status === 1) $this->completeTexts(PromotionTranslations::all($row->toArray()));
  113. $before = $row->toArray(); $row->status = $status; $row->save(); PromotionService::publish($row);
  114. if (Schema::hasTable('operation_audits')) OperationAuditService::record('promotion', $id, 'status', $before, $row->toArray());
  115. return $this->format($row);
  116. }, 3);
  117. }
  118. public function records(array $input): array
  119. {
  120. $input = Validator::make($input, ['activity_id' => ['required', 'integer', 'min:1'], 'user_id' => ['sometimes', 'integer', 'min:1'],
  121. 'kind' => ['required', 'in:accounts,rounds,tasks,spins,rewards'], 'page' => ['sometimes', 'integer', 'min:1'], 'limit' => ['sometimes', 'integer', 'between:1,100']])->validate();
  122. $q = DB::table('promotion_accounts as a')->where('a.activity_id', $input['activity_id']);
  123. if (isset($input['user_id'])) $q->where('a.user_id', $input['user_id']);
  124. if ($input['kind'] === 'accounts') $q->select('a.*')->orderByDesc('a.id');
  125. else {
  126. $table = match ($input['kind']) { 'rounds' => 'promotion_rounds', 'tasks' => 'promotion_task_grants', 'spins' => 'promotion_spins', 'rewards' => 'promotion_rewards' };
  127. $q->join($table . ' as r', 'r.account_id', '=', 'a.id')->select(['r.*', 'a.user_id', 'a.activity_id'])->orderByDesc('r.id');
  128. }
  129. return ['total' => $q->count(), 'data' => $q->forPage($input['page'] ?? 1, $input['limit'] ?? 20)->get()];
  130. }
  131. }