""" Сервисы для работы с формой Ф-5. Содержит: - FormF5Service - CRUD операции - FormF5Parser - парсинг Excel """ import logging from typing import Any from apps.core.excel import ( BaseExcelParser, ColumnMapping, ParseResult, RowData, ) from apps.core.reporting import ReportingPeriodParserMixin, VersionedReportServiceMixin from apps.core.services import BaseService, BulkOperationsMixin from apps.form_5.models import FormF5Record from apps.organization.services import OrganizationService from django.db import transaction from django.db.models import Count, Max logger = logging.getLogger(__name__) class FormF5Service( BulkOperationsMixin, VersionedReportServiceMixin[FormF5Record], BaseService[FormF5Record], ): """Сервис для работы с записями формы Ф-5.""" model = FormF5Record @classmethod def get_by_organization(cls, organization_id): """Получить записи организации.""" return cls.get_queryset().filter(organization_id=organization_id) @classmethod def get_by_batch(cls, batch_id: int): return cls.get_queryset().filter(load_batch=batch_id) @classmethod def get_by_load_batch(cls, batch_id: int): """Совместимость со старым API сервиса.""" return cls.get_by_batch(batch_id) @classmethod def delete_by_load_batch(cls, batch_id: int) -> int: """Удалить записи по номеру загрузки.""" deleted_count, _ = cls.get_queryset().filter(load_batch=batch_id).delete() return deleted_count @classmethod def get_next_batch_id(cls) -> int: max_batch = cls.model.objects.aggregate(max_batch=Max("load_batch")) return (max_batch["max_batch"] or 0) + 1 @classmethod def get_batches(cls) -> list[dict[str, Any]]: return list( cls.model.objects.values("load_batch") .annotate(count=Count("id"), created_at=Max("created_at")) .order_by("-load_batch") ) class FormF5Parser(ReportingPeriodParserMixin, BaseExcelParser[FormF5Record]): """Парсер Excel файла формы Ф-5 (Инвентаризация оборудования).""" ORG_NAME_COLUMN = 0 OKPO_COLUMN = 1 OGRN_COLUMN = 2 INN_COLUMN = 3 def get_column_mappings(self) -> list[ColumnMapping]: return [ # Идентификация ColumnMapping(4, "Идентификационный код", "equipment_id", field_type="str"), ColumnMapping(5, "Инвентарный номер", "inventory_number", field_type="str"), ColumnMapping(6, "Наименование оборудования", "name", field_type="str"), ColumnMapping(7, "Модель", "model", field_type="str"), # Производитель ColumnMapping(8, "Производитель", "manufacturer", field_type="str"), ColumnMapping( 9, "Страна происхождения", "country_origin", field_type="str" ), ColumnMapping( 10, "Отечественное производство", "is_domestic", field_type="bool" ), # Технические характеристики ColumnMapping(11, "Год выпуска", "year_manufacture", field_type="int"), ColumnMapping(12, "Наличие ЧПУ", "has_cnc", field_type="bool"), ColumnMapping(13, "Тип оборудования", "equipment_type", field_type="str"), ColumnMapping( 14, "Категория оборудования", "equipment_category", field_type="str" ), # Эксплуатация ColumnMapping( 15, "Дата ввода в эксплуатацию", "commissioning_date", field_type="date" ), ColumnMapping(16, "Местонахождение", "location", field_type="str"), ColumnMapping( 17, "Производственный участок", "production_site", field_type="str" ), # Состояние ColumnMapping( 18, "Коэффициент использования", "utilization_rate", field_type="decimal", ), ColumnMapping( 19, "Фактический износ, %", "physical_wear_percent", field_type="decimal", ), ColumnMapping( 20, "В рабочем состоянии", "is_operational", field_type="bool" ), ColumnMapping(21, "Требует ремонта", "requires_repair", field_type="bool"), ColumnMapping( 22, "Требует замены", "requires_replacement", field_type="bool" ), # Стоимость ColumnMapping( 23, "Первоначальная стоимость", "initial_cost", field_type="decimal" ), ColumnMapping( 24, "Остаточная стоимость", "residual_value", field_type="decimal" ), # Примечания ColumnMapping(25, "Примечания", "notes", field_type="str"), ] def get_next_batch_id(self) -> int: return FormF5Service.get_next_batch_id() @transaction.atomic def create_record( self, row_data: RowData | dict[str, Any], batch_id: int | None = None, ) -> FormF5Record: row_data = self._normalize_row_data(row_data) batch_id = batch_id or getattr(self, "load_batch", self.get_next_batch_id()) org = OrganizationService.get_required_by_inn(row_data.inn) return FormF5Service.create_versioned_record( organization=org, load_batch=batch_id, report_year=self.report_year, report_quarter=self.report_quarter, **row_data.fields, ) def parse_form_f5_file( file, *, report_year: int, report_quarter: int | None = None, ) -> ParseResult: parser = FormF5Parser(report_year=report_year, report_quarter=report_quarter) return parser.parse(file)