Banner.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. // Both the row button and the editor write status; a stale compatibility alias must not override it.
  113. $manualStatus = $params['status'] ?? $params['manual_status'] ?? $manualStatus;
  114. }
  115. $banner->fill([
  116. 'title' => $params['title'],
  117. 'image' => Util::replacePartInUrl($params['image']),
  118. 'link' => $activityId ?? ($link === null ? null : (string) $link),
  119. 'type' => $params['type'],
  120. 'sort' => array_key_exists('sort', $params) ? ($params['sort'] ?? 0) : ($banner->sort ?? 0),
  121. 'lang' => $params['lang'],
  122. 'status' => $manualStatus,
  123. ])->save();
  124. DB::commit();
  125. } catch (ValidationException $e) {
  126. DB::rollBack();
  127. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  128. } catch (Exception $e) {
  129. DB::rollBack();
  130. return $this->error(intval($e->getCode()), $e->getMessage());
  131. }
  132. return $this->success();
  133. }
  134. /** Change manual publication without resubmitting the banner form. */
  135. public function status()
  136. {
  137. try {
  138. $params = request()->validate([
  139. 'id' => ['required', 'integer', 'min:1'],
  140. 'status' => ['required_without:manual_status', 'integer', 'in:0,1'],
  141. 'manual_status' => ['required_without:status', 'integer', 'in:0,1'],
  142. ]);
  143. DB::transaction(function () use ($params) {
  144. $banner = BannerModel::where('id', $params['id'])->lockForUpdate()->first();
  145. if (!$banner) throw new Exception('数据不存在', HttpStatus::CUSTOM_ERROR);
  146. if (BannerVisibilityService::activityId($banner->link) !== null) {
  147. throw new Exception('关联活动的 Banner 由活动状态自动控制,不能手动上下架', HttpStatus::CUSTOM_ERROR);
  148. }
  149. $banner->status = $params['status'] ?? $params['manual_status'];
  150. $banner->save();
  151. });
  152. } catch (ValidationException $e) {
  153. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  154. } catch (Exception $e) {
  155. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  156. }
  157. return $this->success();
  158. }
  159. /**
  160. * @api {post} /admin/banner/delete 删除
  161. * @apiGroup 轮播图管理
  162. * @apiUse result
  163. * @apiUse header
  164. * @apiVersion 1.0.0
  165. *
  166. * @apiParam {int} id 要删除的ID
  167. *
  168. */
  169. function delete()
  170. {
  171. DB::beginTransaction();
  172. try {
  173. request()->validate([
  174. 'id' => ['required', 'integer', 'min:1', 'max:99999999'],
  175. ]);
  176. $id = request()->input('id', 0);
  177. $info = BannerModel::where('id', $id)->first();
  178. if (!$info) throw new Exception("数据不存在", HttpStatus::CUSTOM_ERROR);
  179. $info->delete();
  180. DB::commit();
  181. } catch (ValidationException $e) {
  182. DB::rollBack();
  183. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  184. } catch (Exception $e) {
  185. DB::rollBack();
  186. return $this->error(intval($e->getCode()));
  187. }
  188. return $this->success();
  189. }
  190. }