| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239 |
- <?php
- namespace App\Http\Controllers\admin;
- use App\Constants\Util;
- use App\Constants\HttpStatus;
- use App\Http\Controllers\Controller;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Validation\ValidationException;
- use Exception;
- use App\Models\Banner as BannerModel;
- use App\Services\BannerVisibilityService;
- use App\Support\ContentLink;
- class Banner extends Controller
- {
- public const CLICK_TYPES = ['none' => '无链接', 'activity' => '跳转活动', 'external' => '外站链接', 'internal' => '站内相对路径'];
- /**
- * Resolve the submitted jump target. Omitting every link field keeps the saved one; old clients that
- * only send `link` get the type inferred from it (activity ID, `/path` or full URL).
- */
- private static function clickBehavior(array $params, BannerModel $banner): array
- {
- $current = $banner->exists ? BannerVisibilityService::links($banner->getAttributes())
- : ['click_type' => 'none', 'link' => null, 'link_pc' => null, 'link_h5' => null];
- $input = array_intersect_key($params, array_flip(ContentLink::FIELDS));
- if (!$input) return $current;
- if (array_key_exists('link', $input) && $input['link'] !== null) $input['link'] = trim((string) $input['link']);
- if (!array_key_exists('click_type', $input)) {
- $input['click_type'] = array_key_exists('link', $input)
- ? BannerVisibilityService::clickType(null, $input['link']) : $current['click_type'];
- }
- if ($input['click_type'] === 'activity') {
- $link = array_key_exists('link', $input) ? $input['link'] : ($current['click_type'] === 'activity' ? $current['link'] : null);
- $id = BannerVisibilityService::activityId($link);
- if ($id === null) throw ValidationException::withMessages(['link' => '请填写跳转活动ID']);
- return ['click_type' => 'activity', 'link' => $id, 'link_pc' => null, 'link_h5' => null];
- }
- // An activity-type row has no reusable external/internal link, so forSave sees it as "none".
- return ContentLink::forSave($input, $current['click_type'] === 'activity' ? [] : $current);
- }
- /**
- * @api {get} /admin/banner/index 轮播图列表
- * @apiGroup 轮播图管理
- * @apiUse result
- * @apiUse header
- * @apiVersion 1.0.0
- *
- * @apiParam {int} [page=1]
- * @apiParam {int} [limit=10]
- *
- */
- function index()
- {
- try {
- $params = request()->validate([
- 'page' => ['sometimes', 'integer', 'min:1'],
- 'limit' => ['sometimes', 'integer', 'min:1', 'max:200'],
- 'type' => ['nullable', 'in:pc,app'],
- 'platform' => ['nullable', 'in:pc,h5'],
- 'status' => ['nullable', 'integer', 'in:0,1'],
- 'lang' => ['nullable', 'string', 'max:10'],
- ]);
- $page = request()->input('page', 1);
- $limit = request()->input('limit', 15);
- $type = $params['type'] ?? '';
- if (isset($params['platform']) && $params['platform'] !== '') {
- // The existing mobile banner enum is "app"; H5 filtering preserves that storage contract.
- $platformType = $params['platform'] === 'pc' ? 'pc' : 'app';
- if ($type !== '' && $type !== $platformType) {
- throw ValidationException::withMessages(['platform' => '平台与原类型筛选不一致']);
- }
- $type = $platformType;
- }
- $query = BannerModel::query();
- if ($type !== '') {
- $query->where('type', $type);
- }
- if (isset($params['lang']) && $params['lang'] !== '') {
- $query->where('lang', $params['lang']);
- }
- $query->orderByDesc('sort')->orderByDesc('id');
- if (isset($params['status']) && $params['status'] !== '') {
- // Stored manual status is not the linked activity's actual status. Filter before pagination.
- $rows = BannerVisibilityService::decorate($query->get());
- $rows = array_values(array_filter($rows, static fn ($row) => $row['status'] === (int) $params['status']));
- $count = count($rows);
- $list = array_slice($rows, ((int) $page - 1) * (int) $limit, (int) $limit);
- } else {
- $count = $query->count();
- $list = BannerVisibilityService::decorate($query->forPage($page, $limit)->get());
- }
- } catch (ValidationException $e) {
- return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
- } catch (Exception $e) {
- return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
- }
- return $this->success(['total' => $count, 'data' => $list]);
- }
- /**
- * @api {post} /admin/banner/update 修改
- * @apiDescription 更新或者新增都用这个接口
- * @apiGroup 轮播图管理
- * @apiUse result
- * @apiUse header
- * @apiVersion 1.0.0
- *
- */
- public function update()
- {
- DB::beginTransaction();
- try {
- $params = request()->validate([
- 'id' => ['nullable', 'integer', 'min:1'],
- 'title' => ['required'],
- 'image' => ['required'],
- 'click_type' => ['sometimes', 'string', 'in:' . implode(',', array_keys(self::CLICK_TYPES))],
- 'link' => ['nullable', function ($attribute, $value, $fail) {
- if ((!is_string($value) && !is_int($value)) || strlen((string) $value) > 2048) {
- $fail('跳转ID或链接格式错误');
- }
- }],
- 'link_pc' => ['nullable', 'string', 'max:2048'],
- 'link_h5' => ['nullable', 'string', 'max:2048'],
- 'type' => ['required', 'in:pc,app'],
- 'sort' => ['nullable', 'integer'],
- 'lang' => ['required'],
- 'status' => ['sometimes', 'integer', 'in:0,1'],
- 'manual_status' => ['nullable', 'integer', 'in:0,1'],
- ], ['click_type.in' => '点击方式仅支持无链接、跳转活动、外站链接、站内相对路径']);
- $id = $params['id'] ?? null;
- $banner = $id === null ? new BannerModel() : BannerModel::where('id', $id)->lockForUpdate()->first();
- if (!$banner) throw new Exception('数据不存在', HttpStatus::CUSTOM_ERROR);
- $links = self::clickBehavior($params, $banner);
- $activityId = BannerVisibilityService::boundActivityId($links['click_type'], $links['link']);
- $previousActivityId = BannerVisibilityService::boundActivityId($banner->click_type, $banner->link);
- if ($activityId !== null && (!$banner->exists || $activityId !== $previousActivityId)) {
- if (!DB::table('activity_rewards')->where('id', $activityId)->exists()) {
- throw ValidationException::withMessages(['link' => '绑定的活动不存在']);
- }
- }
- $manualStatus = $banner->status ?? 1;
- if ($activityId === null) {
- // Both the row button and the editor write status; a stale compatibility alias must not override it.
- $manualStatus = $params['status'] ?? $params['manual_status'] ?? $manualStatus;
- }
- $banner->fill([
- 'title' => $params['title'],
- 'image' => Util::replacePartInUrl($params['image']),
- 'click_type' => $links['click_type'],
- 'link' => $links['link'],
- 'link_pc' => $links['link_pc'],
- 'link_h5' => $links['link_h5'],
- 'type' => $params['type'],
- 'sort' => array_key_exists('sort', $params) ? ($params['sort'] ?? 0) : ($banner->sort ?? 0),
- 'lang' => $params['lang'],
- 'status' => $manualStatus,
- ])->save();
- DB::commit();
- } catch (ValidationException $e) {
- DB::rollBack();
- return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
- } catch (Exception $e) {
- DB::rollBack();
- return $this->error(intval($e->getCode()), $e->getMessage());
- }
- return $this->success();
- }
- /** Change manual publication without resubmitting the banner form. */
- public function status()
- {
- try {
- $params = request()->validate([
- 'id' => ['required', 'integer', 'min:1'],
- 'status' => ['required_without:manual_status', 'integer', 'in:0,1'],
- 'manual_status' => ['required_without:status', 'integer', 'in:0,1'],
- ]);
- DB::transaction(function () use ($params) {
- $banner = BannerModel::where('id', $params['id'])->lockForUpdate()->first();
- if (!$banner) throw new Exception('数据不存在', HttpStatus::CUSTOM_ERROR);
- if (BannerVisibilityService::boundActivityId($banner->click_type, $banner->link) !== null) {
- throw new Exception('关联活动的 Banner 由活动状态自动控制,不能手动上下架', HttpStatus::CUSTOM_ERROR);
- }
- $banner->status = $params['status'] ?? $params['manual_status'];
- $banner->save();
- });
- } catch (ValidationException $e) {
- return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
- } catch (Exception $e) {
- return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
- }
- return $this->success();
- }
- /**
- * @api {post} /admin/banner/delete 删除
- * @apiGroup 轮播图管理
- * @apiUse result
- * @apiUse header
- * @apiVersion 1.0.0
- *
- * @apiParam {int} id 要删除的ID
- *
- */
- function delete()
- {
- DB::beginTransaction();
- try {
- request()->validate([
- 'id' => ['required', 'integer', 'min:1', 'max:99999999'],
- ]);
- $id = request()->input('id', 0);
- $info = BannerModel::where('id', $id)->first();
- if (!$info) throw new Exception("数据不存在", HttpStatus::CUSTOM_ERROR);
- $info->delete();
- DB::commit();
- } catch (ValidationException $e) {
- DB::rollBack();
- return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
- } catch (Exception $e) {
- DB::rollBack();
- return $this->error(intval($e->getCode()));
- }
- return $this->success();
- }
- }
|