Banner.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. <?php
  2. namespace App\Http\Controllers\admin;
  3. use App\Constants\Util;
  4. use App\Constants\HttpStatus;
  5. use App\Http\Controllers\Controller;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Validation\ValidationException;
  8. use Exception;
  9. use App\Models\Banner as BannerModel;
  10. use App\Services\BannerVisibilityService;
  11. class Banner extends Controller
  12. {
  13. /**
  14. * @api {get} /admin/banner/index 轮播图列表
  15. * @apiGroup 轮播图管理
  16. * @apiUse result
  17. * @apiUse header
  18. * @apiVersion 1.0.0
  19. *
  20. * @apiParam {int} [page=1]
  21. * @apiParam {int} [limit=10]
  22. *
  23. */
  24. function index()
  25. {
  26. try {
  27. $params = request()->validate([
  28. 'page' => ['sometimes', 'integer', 'min:1'],
  29. 'limit' => ['sometimes', 'integer', 'min:1', 'max:200'],
  30. 'type' => ['nullable', 'in:pc,app'],
  31. 'platform' => ['nullable', 'in:pc,h5'],
  32. 'status' => ['nullable', 'integer', 'in:0,1'],
  33. 'lang' => ['nullable', 'string', 'max:10'],
  34. ]);
  35. $page = request()->input('page', 1);
  36. $limit = request()->input('limit', 15);
  37. $type = $params['type'] ?? '';
  38. if (isset($params['platform']) && $params['platform'] !== '') {
  39. // The existing mobile banner enum is "app"; H5 filtering preserves that storage contract.
  40. $platformType = $params['platform'] === 'pc' ? 'pc' : 'app';
  41. if ($type !== '' && $type !== $platformType) {
  42. throw ValidationException::withMessages(['platform' => '平台与原类型筛选不一致']);
  43. }
  44. $type = $platformType;
  45. }
  46. $query = BannerModel::query();
  47. if ($type !== '') {
  48. $query->where('type', $type);
  49. }
  50. if (isset($params['lang']) && $params['lang'] !== '') {
  51. $query->where('lang', $params['lang']);
  52. }
  53. $query->orderByDesc('sort')->orderByDesc('id');
  54. if (isset($params['status']) && $params['status'] !== '') {
  55. // Stored manual status is not the linked activity's actual status. Filter before pagination.
  56. $rows = BannerVisibilityService::decorate($query->get());
  57. $rows = array_values(array_filter($rows, static fn ($row) => $row['status'] === (int) $params['status']));
  58. $count = count($rows);
  59. $list = array_slice($rows, ((int) $page - 1) * (int) $limit, (int) $limit);
  60. } else {
  61. $count = $query->count();
  62. $list = BannerVisibilityService::decorate($query->forPage($page, $limit)->get());
  63. }
  64. } catch (ValidationException $e) {
  65. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  66. } catch (Exception $e) {
  67. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  68. }
  69. return $this->success(['total' => $count, 'data' => $list]);
  70. }
  71. /**
  72. * @api {post} /admin/banner/update 修改
  73. * @apiDescription 更新或者新增都用这个接口
  74. * @apiGroup 轮播图管理
  75. * @apiUse result
  76. * @apiUse header
  77. * @apiVersion 1.0.0
  78. *
  79. */
  80. public function update()
  81. {
  82. DB::beginTransaction();
  83. try {
  84. $params = request()->validate([
  85. 'id' => ['nullable', 'integer', 'min:1'],
  86. 'title' => ['required'],
  87. 'image' => ['required'],
  88. 'link' => ['nullable', function ($attribute, $value, $fail) {
  89. if ((!is_string($value) && !is_int($value)) || strlen((string) $value) > 191) {
  90. $fail('跳转ID或链接格式错误');
  91. }
  92. }],
  93. 'type' => ['required', 'in:pc,app'],
  94. 'sort' => ['nullable', 'integer'],
  95. 'lang' => ['required'],
  96. 'status' => ['sometimes', 'integer', 'in:0,1'],
  97. 'manual_status' => ['nullable', 'integer', 'in:0,1'],
  98. ]);
  99. $id = $params['id'] ?? null;
  100. $banner = $id === null ? new BannerModel() : BannerModel::where('id', $id)->lockForUpdate()->first();
  101. if (!$banner) throw new Exception('数据不存在', HttpStatus::CUSTOM_ERROR);
  102. $link = array_key_exists('link', $params) ? $params['link'] : $banner->link;
  103. $activityId = BannerVisibilityService::activityId($link);
  104. $previousActivityId = BannerVisibilityService::activityId($banner->link);
  105. if ($activityId !== null && (!$banner->exists || $activityId !== $previousActivityId)) {
  106. if (!DB::table('activity_rewards')->where('id', $activityId)->exists()) {
  107. throw ValidationException::withMessages(['link' => '绑定的活动不存在']);
  108. }
  109. }
  110. $manualStatus = $banner->status ?? 1;
  111. if ($activityId === null) {
  112. $manualStatus = $params['manual_status'] ?? $params['status'] ?? $manualStatus;
  113. }
  114. $banner->fill([
  115. 'title' => $params['title'],
  116. 'image' => Util::replacePartInUrl($params['image']),
  117. 'link' => $activityId ?? ($link === null ? null : (string) $link),
  118. 'type' => $params['type'],
  119. 'sort' => array_key_exists('sort', $params) ? ($params['sort'] ?? 0) : ($banner->sort ?? 0),
  120. 'lang' => $params['lang'],
  121. 'status' => $manualStatus,
  122. ])->save();
  123. DB::commit();
  124. } catch (ValidationException $e) {
  125. DB::rollBack();
  126. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  127. } catch (Exception $e) {
  128. DB::rollBack();
  129. return $this->error(intval($e->getCode()), $e->getMessage());
  130. }
  131. return $this->success();
  132. }
  133. /** Change manual publication without resubmitting the banner form. */
  134. public function status()
  135. {
  136. try {
  137. $params = request()->validate([
  138. 'id' => ['required', 'integer', 'min:1'],
  139. 'status' => ['required_without:manual_status', 'integer', 'in:0,1'],
  140. 'manual_status' => ['required_without:status', 'integer', 'in:0,1'],
  141. ]);
  142. DB::transaction(function () use ($params) {
  143. $banner = BannerModel::where('id', $params['id'])->lockForUpdate()->first();
  144. if (!$banner) throw new Exception('数据不存在', HttpStatus::CUSTOM_ERROR);
  145. if (BannerVisibilityService::activityId($banner->link) !== null) {
  146. throw new Exception('关联活动的 Banner 由活动状态自动控制,不能手动上下架', HttpStatus::CUSTOM_ERROR);
  147. }
  148. $banner->status = $params['manual_status'] ?? $params['status'];
  149. $banner->save();
  150. });
  151. } catch (ValidationException $e) {
  152. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  153. } catch (Exception $e) {
  154. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  155. }
  156. return $this->success();
  157. }
  158. /**
  159. * @api {post} /admin/banner/delete 删除
  160. * @apiGroup 轮播图管理
  161. * @apiUse result
  162. * @apiUse header
  163. * @apiVersion 1.0.0
  164. *
  165. * @apiParam {int} id 要删除的ID
  166. *
  167. */
  168. function delete()
  169. {
  170. DB::beginTransaction();
  171. try {
  172. request()->validate([
  173. 'id' => ['required', 'integer', 'min:1', 'max:99999999'],
  174. ]);
  175. $id = request()->input('id', 0);
  176. $info = BannerModel::where('id', $id)->first();
  177. if (!$info) throw new Exception("数据不存在", HttpStatus::CUSTOM_ERROR);
  178. $info->delete();
  179. DB::commit();
  180. } catch (ValidationException $e) {
  181. DB::rollBack();
  182. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  183. } catch (Exception $e) {
  184. DB::rollBack();
  185. return $this->error(intval($e->getCode()));
  186. }
  187. return $this->success();
  188. }
  189. }