12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- <?php
- namespace App\Http\Controllers\API;
- use App\Http\Controllers\Controller;
- use App\Http\Resources\API\NotificationResource;
- use App\Models\Enums\NotificationStatus;
- use App\Models\Notification;
- use App\Models\NotificationRecord;
- use Carbon\Carbon;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Auth;
- class NotificationController extends Controller
- {
- /**
- * 用户通知列表
- *
- * @param Request $request
- * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
- */
- public function index(Request $request)
- {
- $notifications = Notification::query()
- ->filter($request->all())
- ->join("notification_records", "notifications.id", "=", "notification_records.notification_id")
- ->where("notification_records.user_id", Auth::id())
- ->selectRaw("notifications.*,notification_records.read_at")
- ->orderByDesc("created_at")
- ->paginate();
- return NotificationResource::collection($notifications);
- }
- /**
- * 标记为已读
- *
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
- */
- public function markAsRead(Request $request)
- {
- $ids = $request->get("ids");
- if (! $ids) {
- return $this->badRequest("Data is empty");
- }
- NotificationRecord::query()
- ->where("user_id", Auth::id())
- ->whereIn("notification_id", $ids)
- ->whereNull("read_at")
- ->update([
- 'read_at' => Carbon::now(),
- ]);
- return $this->noContent();
- }
- /**
- * 未读消息
- *
- * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
- */
- public function unread()
- {
- $announcements = Notification::query()
- ->leftJoin("notification_records", "notifications.id", "=", "notification_records.notification_id")
- ->where("notification_records.user_id", Auth::id())
- ->where("notifications.status", NotificationStatus::RELEASE)
- ->where("notifications.start_at", "<", Carbon::now())
- ->where(fn($query) => $query->where("notifications.end_at", ">", Carbon::now())->orWhereNull("notifications.end_at"))
- ->whereNull("notification_records.id")
- ->selectRaw("notifications.id")
- ->get();
- foreach ($announcements as $announcement) {
- NotificationRecord::query()->firstOrCreate([
- 'notification_id' => $announcement->id,
- 'user_id' => Auth::id()
- ]);
- }
- $notifications = Notification::query()
- ->join("notification_records", "notifications.id", "=", "notification_records.notification_id")
- ->where("notification_records.user_id", Auth::id())
- ->whereNull("notification_records.read_at")
- ->selectRaw("notifications.*,notification_records.read_at")
- ->orderByDesc("created_at")
- ->paginate();
- return NotificationResource::collection($notifications);
- }
- }
|