radfusion/app/Services/Workflow/Manager.php
2025-01-08 17:23:15 +06:00

96 lines
2.3 KiB
PHP

<?php
namespace App\Services\Workflow;
use App\Domain\ACL\Permission;
use App\Domain\Report\ReportStatus;
use App\Models\Study;
use App\Models\User;
use Closure;
final class Manager
{
private ?User $user = null;
public function __construct(private readonly Study $study) {}
public static function of(Study $study): self
{
return new self($study);
}
public function by(User|int|null $user): self
{
$this->user = me($user);
return $this;
}
public function can(Permission $permission): bool
{
if (! $this->checkUserPermission($permission)) {
return false;
}
$prop = 'can' . $permission->name;
if (! method_exists($this, $prop)) {
return false;
}
return $this->{$prop}();
}
public function canAssignPhysician(): bool
{
return $this->activeStudy(fn () => $this->study->report_status <= ReportStatus::Preliminary);
}
public function canStudyHistoryEdit(): bool
{
return $this->activeStudy(fn () => $this->study->report_status <= ReportStatus::Preliminary);
}
public function canAttachmentUpload(): bool
{
return $this->activeStudy(fn () => $this->study->report_status <= ReportStatus::Preliminary);
}
public function canReportDownload(): bool
{
return $this->activeStudy(fn () => $this->study->report_status >= ReportStatus::Finalized);
}
public function canReportEdit(): bool
{
return $this->activeStudy(fn () => $this->study->isUnlocked() &&
$this->study->report_status <= ReportStatus::Preliminary &&
$this->study->isAssignedTo($this->user)
);
}
public function canUnlockReport(): bool
{
return $this->activeStudy(fn () => $this->study->isLocked() &&
$this->study->isLockedBy($this->user)
);
}
private function checkUserPermission(Permission $permission): bool
{
if (is_null($this->user)) {
$this->user = auth()->user();
}
return $this->user->may($permission);
}
private function activeStudy(Closure $fn): bool
{
if (! $this->study->isActive()) {
return false;
}
return $fn();
}
}