Files
onboard/app/Services/AutoReportService.php
2026-05-06 22:32:11 +09:00

125 lines
4.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Services;
use App\Models\Department;
use App\Models\MedicalHistorySnapshot;
use App\Models\MetrikaResult;
use App\Models\ObservationPatient;
use App\Models\Report;
use App\Models\UnwantedEvent;
use App\Models\User;
use Carbon\CarbonPeriod;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class AutoReportService
{
public function __construct(
mixed $dateRangeService = null,
mixed $reportSavePathService = null,
) {
if ($dateRangeService instanceof ReportService) {
$this->dateRangeService = $reportSavePathService instanceof DateRangeService
? $reportSavePathService
: app(DateRangeService::class);
$this->reportService = $dateRangeService;
return;
}
$this->dateRangeService = $dateRangeService instanceof DateRangeService
? $dateRangeService
: app(DateRangeService::class);
$this->reportService = $reportSavePathService instanceof ReportService
? $reportSavePathService
: app(ReportService::class);
}
protected DateRangeService $dateRangeService;
protected ReportService $reportService;
/**
* Заполнить отчеты для пользователя за период
*/
public function fillReportsForUser(
User $user,
string $startDate,
string $endDate,
Department $department,
bool $force = false
): int {
$createdCount = 0;
$start = \Carbon\Carbon::createFromFormat('Y-m-d', $startDate, 'Asia/Yakutsk');
$end = \Carbon\Carbon::createFromFormat('Y-m-d', $endDate, 'Asia/Yakutsk');
// Создаем период по дням
$period = CarbonPeriod::create($start->toDateString(), $end->toDateString());
foreach ($period as $date) {
$dateRange = $this->dateRangeService->getNormalizedDateRange($user, $date, $date);
try {
$reportCreated = $this->createReportForDate($user, $department, $dateRange, $force);
if ($reportCreated) {
$createdCount++;
}
} catch (\Exception $e) {
Log::error("Ошибка создания отчета для {$user->id} на {$date->format('Y-m-d')}: {$e->getMessage()}");
throw $e; // или continue в зависимости от требований
}
}
return $createdCount;
}
/**
* Создать отчет для конкретной даты
*/
public function createReportForDate(User $user, Department $department, DateRange $dateRange, bool $force = false): bool
{
$scopedUser = $this->scopeUserToDepartment($user, $department);
// Проверяем, существует ли уже отчет на эту дату
$existingReport = Report::where('rf_department_id', $department->department_id)
->exactPeriod($dateRange->startSql(), $dateRange->endSql())
->first();
if ($existingReport && ! $force) {
return false; // Отчет уже существует
}
// Если есть существующий отчет и force=true - удаляем его
if ($existingReport && $force) {
$this->deleteExistingReport($existingReport);
}
$payload = $this->reportService->buildAutoFillReportPayload($scopedUser, $department, $dateRange);
$this->reportService->storeReport($payload, $scopedUser, true);
return true;
}
private function scopeUserToDepartment(User $user, Department $department): User
{
$scopedUser = clone $user;
$scopedUser->rf_department_id = $department->department_id;
$scopedUser->setRelation('department', $department);
return $scopedUser;
}
private function deleteExistingReport(Report $report): void
{
DB::transaction(function () use ($report) {
MetrikaResult::where('rf_report_id', $report->report_id)->delete();
MedicalHistorySnapshot::where('rf_report_id', $report->report_id)->delete();
UnwantedEvent::where('rf_report_id', $report->report_id)->delete();
ObservationPatient::where('rf_report_id', $report->report_id)->delete();
DB::table('reports')->where('report_id', $report->report_id)->delete();
});
}
}