Переглянути джерело

feat(student): add calculateStatus and updateStatus methods based on contract validity

alvesantos 1 тиждень тому
батько
коміт
d7fb3183f1
1 змінених файлів з 49 додано та 0 видалено
  1. 49 0
      app/Models/Student.php

+ 49 - 0
app/Models/Student.php

@@ -76,6 +76,11 @@ class Student extends Model
 {
     use HasFactory, SoftDeletes;
 
+    public const STATUS_ACTIVE = 'active';
+    public const STATUS_EX_STUDENT = 'ex_student';
+    public const STATUS_LOCKED = 'locked';
+    public const STATUS_LEAD = 'lead';
+
     private ?array $responsibleForCreation = null;
 
     protected $table = 'students';
@@ -98,6 +103,9 @@ protected static function booted(): void
                     'responsible' => __('validation.minor_requires_responsible'),
                 ]);
             }
+            if (empty($student->status)) {
+                $student->status = self::STATUS_LEAD;
+            }
         });
 
         static::deleting(function (Student $student): void {
@@ -126,6 +134,47 @@ public function hasActiveContract(): bool
         return $this->contracts()->latestVersion()->where('status', 'active')->exists();
     }
 
+    public function calculateStatus(): string
+    {
+        $contracts = $this->contracts()->latestVersion()->get();
+
+        if ($contracts->isEmpty()) {
+            return self::STATUS_LEAD;
+        }
+
+        $today = now()->startOfDay();
+
+        $hasActive = $contracts->contains(function ($contract) use ($today) {
+            return $contract->status === 'active' &&
+                   $contract->end_date &&
+                   $contract->end_date->startOfDay()->gte($today);
+        });
+
+        if ($hasActive) {
+            return self::STATUS_ACTIVE;
+        }
+
+        $hasLocked = $contracts->contains(function ($contract) {
+            return $contract->status === 'frozen';
+        });
+
+        if ($hasLocked) {
+            return self::STATUS_LOCKED;
+        }
+
+        return self::STATUS_EX_STUDENT;
+    }
+
+    public function updateStatus(): void
+    {
+        $newStatus = $this->calculateStatus();
+
+        if ($this->status !== $newStatus) {
+            $this->status = $newStatus;
+            $this->saveQuietly();
+        }
+    }
+
     public function contracts(): HasMany
     {
         return $this->hasMany(StudentContract::class);