Files
econom-calculator/app/Support/MedicalReport/DatabaseStructuredTemplateFactory.php
brusnitsyn 3edc8e667e
Some checks failed
tests / ci (8.5) (push) Has been cancelled
linter / quality (push) Has been cancelled
tests / ci (8.3) (push) Has been cancelled
tests / ci (8.4) (push) Has been cancelled
first commit
2026-04-03 17:20:05 +09:00

85 lines
3.0 KiB
PHP

<?php
namespace App\Support\MedicalReport;
use App\Models\Department;
use App\Models\HospitalUnit;
use App\Models\MedicalReportFormTemplate;
class DatabaseStructuredTemplateFactory
{
/**
* @return array<string, mixed>|null
*/
public function templateForDepartment(string $reportDepartmentKey): ?array
{
$hospitalUnitId = HospitalUnit::query()
->where('slug', $reportDepartmentKey)
->value('id');
$template = MedicalReportFormTemplate::query()
->where(function ($query) use ($hospitalUnitId, $reportDepartmentKey): void {
if ($hospitalUnitId !== null) {
$query->where('hospital_unit_id', $hospitalUnitId)
->orWhere('department_key', $reportDepartmentKey);
return;
}
$query->where('department_key', $reportDepartmentKey);
})
->where('is_active', true)
->first();
if ($template === null) {
return null;
}
/** @var array<string, mixed> $schema */
$schema = $template->schema ?? [];
return [
'key' => $reportDepartmentKey.'-builder-template',
'title' => $schema['title'] ?? $template->name,
'description' => $schema['description'] ?? $template->description ?? '',
'department_options' => $this->departmentOptions(),
'sections' => collect($schema['sections'] ?? [])
->map(function (array $section) use ($schema): array {
$fields = array_values($section['fields'] ?? []);
$emptyEntry = collect($fields)
->mapWithKeys(fn (array $field): array => [$field['key'] => ''])
->all();
$defaultEntries = array_values($section['default_entries'] ?? []);
return [
'key' => (string) $section['key'],
'title' => (string) $section['title'],
'economist_label' => (string) ($section['economist_label'] ?? (($schema['title'] ?? 'Шаблон').' / '.($section['title'] ?? 'Секция'))),
'fields' => $fields,
'export_metrics' => array_values($section['export_metrics'] ?? []),
'empty_entry' => $emptyEntry,
'default_entries' => $defaultEntries === [] ? [$emptyEntry] : $defaultEntries,
];
})
->values()
->all(),
];
}
/**
* @return list<array{id: int, name: string}>
*/
private function departmentOptions(): array
{
return Department::query()
->where('is_active', true)
->orderBy('name')
->get(['id', 'name'])
->map(fn (Department $department): array => [
'id' => $department->id,
'name' => $department->name,
])
->all();
}
}