86 خطوط
2.8 KiB
PHP
86 خطوط
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Http\Resources\NotificationResource;
|
|
use App\Http\Responses\ApiResponse;
|
|
use App\Models\Notification;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Gate;
|
|
|
|
class NotificationController extends Controller
|
|
{
|
|
public function index(Request $request): JsonResponse
|
|
{
|
|
$query = Notification::where('user_id', auth()->id());
|
|
if ($request->boolean('archived')) {
|
|
$query->whereNotNull('archived_at');
|
|
} else {
|
|
$query->whereNull('archived_at');
|
|
}
|
|
if ($request->filled('type')) {
|
|
$query->where('type', $request->string('type'));
|
|
}
|
|
if ($request->has('unread')) {
|
|
$query->where('is_read', $request->boolean('unread') ? false : true);
|
|
}
|
|
$paginator = $query
|
|
->orderByDesc('created_at')
|
|
->paginate(20);
|
|
|
|
return ApiResponse::paginated($paginator, fn (Notification $notification) => $this->resource($notification));
|
|
}
|
|
|
|
public function markRead(Notification $notification): JsonResponse
|
|
{
|
|
Gate::authorize('update', $notification);
|
|
$notification->update(['is_read' => true, 'read_at' => $notification->read_at ?? now()]);
|
|
|
|
return ApiResponse::success($this->resource($notification), message: 'اعلان خوانده شد.');
|
|
}
|
|
|
|
public function markAllRead(): JsonResponse
|
|
{
|
|
Notification::where('user_id', auth()->id())
|
|
->where('is_read', false)
|
|
->whereNull('archived_at')
|
|
->update(['is_read' => true, 'read_at' => now()]);
|
|
|
|
return ApiResponse::success(null, message: 'همه اعلانها خوانده شد.');
|
|
}
|
|
|
|
public function unreadCount(): JsonResponse
|
|
{
|
|
$count = Notification::where('user_id', auth()->id())->where('is_read', false)->whereNull('archived_at')->count();
|
|
|
|
return ApiResponse::success($count);
|
|
}
|
|
|
|
public function archive(Notification $notification): JsonResponse
|
|
{
|
|
Gate::authorize('update', $notification);
|
|
$notification->update([
|
|
'archived_at' => now(),
|
|
'is_read' => true,
|
|
'read_at' => $notification->read_at ?? now(),
|
|
]);
|
|
|
|
return ApiResponse::success($this->resource($notification), message: 'اعلان بایگانی شد.');
|
|
}
|
|
|
|
public function destroy(Notification $notification): JsonResponse
|
|
{
|
|
Gate::authorize('delete', $notification);
|
|
$notification->delete();
|
|
|
|
return ApiResponse::success(null, message: 'اعلان حذف شد.');
|
|
}
|
|
|
|
private function resource(Notification $notification): array
|
|
{
|
|
return (new NotificationResource($notification))->resolve(request());
|
|
}
|
|
}
|