SystemNotificationController.php 2.31 KB
<?php

namespace App\Http\Container\AppSection\Controllers;

use App\Helpers\JsonResource;
use App\Models\BrokerPushLevelRecordItem;
use App\Models\BrokerPushMatchRecord;
use App\Models\NotificationUser;
use Auth;
use Hikoon\LaravelApi\Support\ApiController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Str;

class SystemNotificationController extends ApiController
{
    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function __invoke(Request $request): JsonResponse
    {
        $attribute = $request->validate(
            ['items' => 'required|array', 'items.*.type' => 'required|string', 'items.*.value' => 'required|numeric'],
            ['items.*' => '参数异常', 'items.*.type.*' => '消息类型参数异常', 'items.*.value.*' => '消息值参数异常']
        );

        Collection::make($attribute['items'])->groupBy('type')
            ->each(function ($items, $type) {
                $method = Str::of($type)->prepend('update_')->camel()->toString();
                if ($method && method_exists($this, $method)) {
                    $this->{$method}($items->pluck('value')->toArray());
                }
            });

        return JsonResource::success(JsonResource::UPDATE_SUCCESS);
    }

    /**
     * @param array $ids
     * @return int
     */
    private function updateSystemNotification(array $ids): int
    {
        return NotificationUser::query()->whereIn('notification_id', $ids)
            ->where('user_id', Auth::id())->whereNull('read_at')
            ->update(['read_at' => now()->toDateTimeString()]);
    }

    /**
     * @param array $ids
     * @return int
     */
    private function updateBrokerLevelRecord(array $ids): int
    {
        return BrokerPushLevelRecordItem::query()->whereIn('record_id', $ids)
            ->where('user_id', Auth::id())->whereNull('read_at')
            ->update(['read_at' => now()->toDateTimeString()]);
    }

    /**
     * @param array $ids
     * @return int
     */
    private function updateBrokerMatchRecord(array $ids): int
    {
        return BrokerPushMatchRecord::query()->whereIn('id', $ids)
            ->where('user_id', Auth::id())->whereNull('read_at')
            ->update(['read_at' => now()->toDateTimeString()]);
    }
}