Эх сурвалжийг харах

feat(student): enhance getAll method to filter students by contract dates

ebagabee 3 долоо хоног өмнө
parent
commit
2e82dda7bf

+ 4 - 1
app/Http/Controllers/StudentController.php

@@ -16,7 +16,10 @@ public function __construct(
 
     public function index(): JsonResponse
     {
-        $items = $this->service->getAll(Auth::user());
+        $items = $this->service->getAll(Auth::user(), request()->only([
+            'contract_start_date',
+            'contract_end_date',
+        ]));
         return $this->successResponse(payload: StudentResource::collection($items));
     }
 

+ 20 - 1
app/Services/StudentService.php

@@ -11,11 +11,30 @@
 
 class StudentService
 {
-    public function getAll(User $user): Collection
+    public function getAll(User $user, array $filters = []): Collection
     {
         $unitId = $this->resolveUnitId($user);
+        $startDate = $filters['contract_start_date'] ?? null;
+        $endDate = $filters['contract_end_date'] ?? null;
 
         return Student::where('unit_id', $unitId)
+            ->when($startDate || $endDate, function ($query) use ($startDate, $endDate) {
+                $query->whereHas('contracts', function ($contractQuery) use ($startDate, $endDate) {
+                    $contractQuery->where('status', 'active');
+
+                    if ($endDate) {
+                        $contractQuery->where('started_date', '<=', $endDate);
+                    }
+
+                    if ($startDate) {
+                        $contractQuery->where(function ($periodQuery) use ($startDate) {
+                            $periodQuery
+                                ->whereNull('end_date')
+                                ->orWhere('end_date', '>=', $startDate);
+                        });
+                    }
+                });
+            })
             ->orderBy('created_at', 'desc')
             ->get();
     }