Add initial implementations for forms and organization apps with serializers, factories, and admin configurations
Some checks failed
CI/CD Pipeline / Code Quality Checks (push) Failing after 5m5s
CI/CD Pipeline / Run Tests (push) Failing after 5m5s
CI/CD Pipeline / Build Docker Images (push) Has been skipped
CI/CD Pipeline / Push to Gitea Registry (push) Has been skipped
CI/CD Pipeline / Deploy to Server (push) Has been skipped

This commit is contained in:
2026-02-17 09:26:08 +01:00
parent fd2adf9ab4
commit 8ed3e1175c
119 changed files with 9091 additions and 0 deletions

114
src/apps/form_5/services.py Normal file
View File

@@ -0,0 +1,114 @@
"""
Сервисы для работы с формой Ф-5.
Содержит:
- FormF5Service - CRUD операции
- FormF5Parser - парсинг Excel
"""
import logging
from typing import Any
from apps.core.excel import (
BaseExcelParser,
ColumnMapping,
ParseResult,
RowData,
)
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, BaseService[FormF5Record]):
"""Сервис для работы с записями формы Ф-5."""
model = FormF5Record
@classmethod
def get_by_batch(cls, batch_id: int):
return cls.get_queryset().filter(load_batch=batch_id)
@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(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, batch_id: int) -> FormF5Record:
org, _ = OrganizationService.get_or_create_by_inn(
inn=row_data.inn,
defaults={
"name": row_data.organization_name,
"ogrn": row_data.ogrn or "",
"okpo": row_data.okpo or "",
"kpp": row_data.kpp or "",
},
)
return FormF5Record.objects.create(
organization=org,
load_batch=batch_id,
**row_data.fields,
)
def parse_form_f5_file(file) -> ParseResult:
parser = FormF5Parser()
return parser.parse(file)