81 lines
2.9 KiB
PHP
81 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Consultant;
|
|
use App\Models\DataCentre;
|
|
use App\Models\DataCentreConsultantAssignment;
|
|
use App\Models\User;
|
|
use Illuminate\Support\Carbon;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class AssignmentService
|
|
{
|
|
/**
|
|
* Tugaskan perunding kepada pusat data.
|
|
*
|
|
* Peraturan: satu pusat data hanya boleh ada SATU perunding aktif pada satu masa.
|
|
* Penugasan terdahulu ditamatkan (end_date diisi, is_active=false) dan disimpan
|
|
* dalam sejarah penugasan.
|
|
*/
|
|
public function assign(DataCentre $dataCentre, Consultant $consultant, User $officer, ?string $startDate = null, ?string $reason = null): DataCentreConsultantAssignment
|
|
{
|
|
return DB::transaction(function () use ($dataCentre, $consultant, $officer, $startDate, $reason) {
|
|
$start = $startDate ? Carbon::parse($startDate) : now();
|
|
|
|
// Tamatkan semua penugasan aktif sedia ada untuk pusat data ini.
|
|
$dataCentre->assignments()
|
|
->where('is_active', true)
|
|
->get()
|
|
->each(function (DataCentreConsultantAssignment $existing) use ($start) {
|
|
$existing->update([
|
|
'is_active' => false,
|
|
'end_date' => $existing->end_date ?? $start->copy()->subDay(),
|
|
]);
|
|
});
|
|
|
|
$assignment = $dataCentre->assignments()->create([
|
|
'consultant_id' => $consultant->id,
|
|
'start_date' => $start,
|
|
'reason' => $reason,
|
|
'assigned_by' => $officer->id,
|
|
'is_active' => true,
|
|
]);
|
|
|
|
$dataCentre->update(['current_consultant_id' => $consultant->id]);
|
|
|
|
activity('penugasan')
|
|
->performedOn($dataCentre)
|
|
->causedBy($officer)
|
|
->withProperties([
|
|
'consultant_id' => $consultant->id,
|
|
'consultant' => $consultant->nama_perunding,
|
|
'reason' => $reason,
|
|
])
|
|
->log('Perunding ditugaskan kepada pusat data');
|
|
|
|
return $assignment;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Tamatkan penugasan aktif tanpa menggantikan dengan perunding baharu.
|
|
*/
|
|
public function endActive(DataCentre $dataCentre, User $officer, ?string $reason = null): void
|
|
{
|
|
DB::transaction(function () use ($dataCentre, $officer, $reason) {
|
|
$dataCentre->assignments()->where('is_active', true)->update([
|
|
'is_active' => false,
|
|
'end_date' => now(),
|
|
'reason' => $reason,
|
|
]);
|
|
$dataCentre->update(['current_consultant_id' => null]);
|
|
|
|
activity('penugasan')
|
|
->performedOn($dataCentre)
|
|
->causedBy($officer)
|
|
->log('Penugasan perunding ditamatkan');
|
|
});
|
|
}
|
|
}
|