9.6 KiB
Handoff: миграция отчётов на Domain-архитектуру
Дата: 2026-04-26
Что уже сделано
0. Обновление от 2026-04-27
Выполнен следующий шаг из handoff:
- добавлен
Infrastructure/Reports/Services/ReportStatisticsReadService ReportService::getReportStatisticsтеперь делегирует в новый read-service- из
ReportServiceудалены legacy-private методы статистики:getStatisticsFromSnapshotsgetStatisticsFromReplicagetMetrikaResultCount
- добавлена константа
MetrikaConfig::STAFF_COUNT - добавлены unit-тесты
ReportStatisticsReadServiceTest
Выполнено продолжение:
- добавлен
Infrastructure/Reports/Services/ManualPatientManagementService - из
ReportServiceвынесена orchestration manual/special пациентов:- создание пациента
- исход пациента
- редактирование
- привязка к МИС
- операции manual/special пациента
- синхронизация manual-снапшотов
ReportServiceсохраняет совместимые публичные методы, но теперь делегирует их в новый сервис
Выполнено финальное сужение legacy-фасада:
- добавлен
Infrastructure/Reports/Services/ReanimationIndicatorService - добавлен
Infrastructure/Reports/Services/ReportMetadataReadService - добавлен
Infrastructure/Reports/Services/ReportRuntimeService - добавлен
Infrastructure/Reports/Services/ReportSaveOrchestrator - добавлен
Infrastructure/Reports/Services/ObservationPatientManagementService - добавлен
Infrastructure/Reports/Services/ReportClinicalSearchService - legacy save fallback в
ReportSavePathServiceбольше не идёт черезReportService LegacyReportServiceAdapterбольше не зависит отReportServiceReportServiceтеперь совместимый фасад: публичные методы сохранены, бизнес-логика делегируется в новые сервисы
Проверка:
php artisan test tests/Unit/Reports
Результат: 19 passed.
1. Базовый каркас Domain / Application / Infrastructure
Добавлены новые слои:
app/Domain/Reportsapp/Application/Reportsapp/Infrastructure/Reports
Ключевые элементы:
Domain/Reports/ValueObjects/MetrikaConfigDomain/Reports/Models/ReportSnapshotDomain/Reports/Contracts/*Application/Reports/DTO/*Application/Reports/GenerateReportUseCaseApplication/Reports/CompareLegacyAndNewReportUseCaseInfrastructure/Reports/Repositories/EloquentReportRepositoryInfrastructure/Reports/Adapters/LegacyReportServiceAdapterInfrastructure/Reports/Logging/ReportsAuditLogger
2. Save-path уже переведён на strangler-схему
Новый save-flow работает рядом со старым кодом:
- старый
ReportServiceне удалён - новый путь включается через feature-flag
- legacy остаётся fallback
- сравнение old/new идёт через comparator и audit logger
Точки входа уже знают про новый flow:
app/Http/Controllers/Web/ReportController.phpapp/Http/Controllers/Api/ReportController.phpapp/Services/AutoReportService.php
3. Вынесена существенная часть persistence и orchestration
Из ReportService уже выделены:
Infrastructure/Reports/Services/ReportStorageServiceInfrastructure/Reports/Services/ReportMetricsFinalizerInfrastructure/Reports/Services/CalculatedMetricsSynchronizerInfrastructure/Reports/Services/SnapshotPersistenceServiceInfrastructure/Reports/Services/AutoFillReportPayloadBuilderInfrastructure/Reports/Services/ManualPatientManagementServiceInfrastructure/Reports/Services/ReanimationIndicatorServiceInfrastructure/Reports/Services/ReportMetadataReadServiceInfrastructure/Reports/Services/ReportRuntimeServiceInfrastructure/Reports/Services/ReportSaveOrchestratorInfrastructure/Reports/Services/ObservationPatientManagementServiceInfrastructure/Reports/Services/ReportClinicalSearchService
4. Вынесены источники данных
Сейчас выделены отдельные источники:
Infrastructure/Reports/Sources/MisPatientSourceInfrastructure/Reports/Sources/SpecialPatientSourceInfrastructure/Reports/Sources/SnapshotPatientSourceInfrastructure/Reports/Sources/MisClinicalDataSourceInfrastructure/Reports/Sources/LegacyAutoFillPatientSource
5. Вынесены Domain-calculators
Сейчас в Domain уже есть:
BedDaysCalculatorPreoperativeDaysCalculatorDepartmentLoadCalculator
6. Read-path пациентов тоже вынесен
Добавлены:
Infrastructure/Reports/Services/ReportPatientsReadServiceInfrastructure/Reports/Services/ReportReadContextResolver
Теперь ReportService уже делегирует туда:
getPatientsByStatusgetPatientsCountByStatusgetPatientsCountsMapgetPatientsFromSnapshots
Это важный шаг: ReportService постепенно становится legacy facade, а не местом, где живёт вся логика.
Что ещё специально НЕ сделано
- старый
ReportServiceне удалён, но теперь это совместимый фасад - полный cutover на новую архитектуру не выполнен
- контроллеры и
ReportPageServiceвсё ещё обращаются кReportService, их можно переводить на конкретные сервисы после ручной проверки - integration tests на SQLite здесь не гонялись, потому что в окружении нет
pdo_sqlite
Проверки и тесты
Проходит:
php artisan test tests/Unit/Reports
Сейчас зелёные unit-тесты для:
MetrikaConfigReportSnapshotGenerateReportUseCaseCompareLegacyAndNewReportUseCaseReportInputFactoryReportPatientsReadService- domain calculators
Важный контекст по БД и тестам
Основное приложение работает с pgsql из .env, но тесты не обязаны использовать это окружение.
Важно:
- в
phpunit.xmlтестовый runtime жёстко переключён наsqlite - в текущем окружении отсутствует
pdo_sqlite - поэтому feature/integration тесты здесь не были полноценно прогнаны
Если завтра нужно будет запускать integration-тесты на PostgreSQL, надо отдельно переводить test-конфиг.
Дополнительные важные замечания
1. В worktree есть изменённые файлы
Нужно быть осторожным и не перетирать чужие правки.
Особенно внимательно смотреть на:
app/Http/Controllers/Api/ReportController.phpapp/Services/ReportService.phpapp/Services/Reports/PatientQueryBuilder.php
2. Есть защитный фикс в конфиге Excel
Ранее был добавлен безопасный guard в config/excel.php, чтобы bootstrap не падал, если в окружении нет нужных excel-классов.
3. Комментарии в новом слое частично русифицированы
Русифицированы PHPDoc в основных новых infrastructure/application классах миграции. При желании можно отдельным проходом довести до конца все новые DTO, адаптеры и domain models.
Самый логичный следующий шаг
Следующая итерация:
- Перевести контроллеры и
ReportPageServiceсReportServiceна конкретные application/infrastructure сервисы. - После ручной проверки удалить
ReportServiceкак совместимый фасад. - После полного cutover удалить
LegacyAutoFillPatientSource/legacy comparison-обвязку или оставить только как диагностический инструмент.
Рекомендуемое направление:
ReportServiceуже оставлен тонким фасадом- переиспользовать
ReportReadContextResolverдля периодов и snapshot-vs-replica решений - не удалять legacy save-flow до полного cutover и сравнения old/new
Если нужно быстро продолжить завтра
Сначала открыть:
docs/report-domain-migration-handoff.mdapp/Services/ReportService.phpapp/Infrastructure/Reports/Services/ReportPatientsReadService.phpapp/Infrastructure/Reports/Services/ReportReadContextResolver.php
Потом проверить:
php artisan test tests/Unit/Reports
И дальше брать следующий шаг:
- перевод контроллеров с
ReportServiceна конкретные сервисы