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

View File

@@ -0,0 +1 @@
"""Приложение формы Ф-5 (Инвентаризация оборудования)."""

45
src/apps/form_5/admin.py Normal file
View File

@@ -0,0 +1,45 @@
"""Админка формы Ф-5."""
from apps.form_5.models import FormF5Record
from django.contrib import admin
@admin.register(FormF5Record)
class FormF5RecordAdmin(admin.ModelAdmin):
"""Админка записей формы Ф-5."""
list_display = [
"organization", "load_batch", "equipment_id", "name",
"year_manufacture", "physical_wear_percent", "created_at",
]
list_filter = ["load_batch", "is_domestic", "has_cnc", "is_operational", "created_at"]
search_fields = ["organization__name", "organization__inn", "equipment_id", "inventory_number", "name"]
readonly_fields = ["id", "created_at", "updated_at"]
raw_id_fields = ["organization"]
ordering = ["-created_at"]
fieldsets = [
("Основная информация", {"fields": ["id", "organization", "load_batch"]}),
("Идентификация оборудования", {
"fields": ["equipment_id", "inventory_number", "name", "model"],
}),
("Производитель", {
"fields": ["manufacturer", "country_origin", "is_domestic"],
}),
("Технические характеристики", {
"fields": ["year_manufacture", "has_cnc", "equipment_type", "equipment_category"],
}),
("Эксплуатация", {
"fields": ["commissioning_date", "location", "production_site"],
"classes": ["collapse"],
}),
("Состояние и использование", {
"fields": [
"utilization_rate", "physical_wear_percent",
"is_operational", "requires_repair", "requires_replacement",
],
}),
("Стоимость", {"fields": ["initial_cost", "residual_value"], "classes": ["collapse"]}),
("Примечания", {"fields": ["notes"], "classes": ["collapse"]}),
("Системные поля", {"fields": ["created_at", "updated_at"], "classes": ["collapse"]}),
]

58
src/apps/form_5/api.py Normal file
View File

@@ -0,0 +1,58 @@
"""API формы Ф-5."""
import logging
from apps.core.viewsets import BaseViewSet
from apps.form_5.models import FormF5Record
from apps.form_5.serializers import (
FormF5ParseResultSerializer,
FormF5RecordListSerializer,
FormF5RecordSerializer,
FormF5UploadSerializer,
)
from apps.form_5.services import FormF5Service, parse_form_f5_file
from apps.form_5.tasks import process_form_f5_file
from rest_framework import status
from rest_framework.parsers import MultiPartParser
from rest_framework.response import Response
from rest_framework.views import APIView
logger = logging.getLogger(__name__)
BACKGROUND_THRESHOLD = 1024 * 1024
class FormF5UploadView(APIView):
parser_classes = [MultiPartParser]
def post(self, request):
serializer = FormF5UploadSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
file = serializer.validated_data["file"]
if file.size > BACKGROUND_THRESHOLD:
task = process_form_f5_file.delay(file.read(), file.name)
return Response(
{"success": True, "message": "Файл поставлен в очередь", "task_id": task.id},
status=status.HTTP_202_ACCEPTED,
)
try:
result = parse_form_f5_file(file)
return Response({"success": True, "data": FormF5ParseResultSerializer(result).data})
except Exception as e:
logger.exception("Ошибка обработки файла Ф-5")
return Response({"success": False, "error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
class FormF5RecordViewSet(BaseViewSet):
queryset = FormF5Record.objects.select_related("organization").all()
serializer_class = FormF5RecordSerializer
service_class = FormF5Service
def get_serializer_class(self):
return FormF5RecordListSerializer if self.action == "list" else FormF5RecordSerializer
def get_queryset(self):
qs = super().get_queryset()
batch_id = self.request.query_params.get("batch_id")
return qs.filter(load_batch=batch_id) if batch_id else qs

11
src/apps/form_5/apps.py Normal file
View File

@@ -0,0 +1,11 @@
"""Конфигурация приложения form_5."""
from django.apps import AppConfig
class Form5Config(AppConfig):
"""Конфигурация приложения формы Ф-5."""
default_auto_field = "django.db.models.BigAutoField"
name = "apps.form_5"
verbose_name = "Форма Ф-5 (Инвентаризация оборудования)"

View File

@@ -0,0 +1,70 @@
# Generated by Django 3.2.25 on 2026-02-06 12:49
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('organization', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='FormF5Record',
fields=[
('created_at', models.DateTimeField(auto_now_add=True, db_index=True, help_text='Дата и время создания записи', verbose_name='создано')),
('updated_at', models.DateTimeField(auto_now=True, help_text='Дата и время последнего обновления', verbose_name='обновлено')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')),
('load_batch', models.PositiveIntegerField(db_index=True, help_text='Идентификатор пакета загрузки', verbose_name='номер загрузки')),
('equipment_id', models.CharField(blank=True, default='', max_length=50, verbose_name='идентификационный код')),
('inventory_number', models.CharField(blank=True, default='', max_length=50, verbose_name='инвентарный номер')),
('name', models.CharField(blank=True, default='', max_length=500, verbose_name='наименование оборудования')),
('model', models.CharField(blank=True, default='', max_length=200, verbose_name='модель')),
('manufacturer', models.CharField(blank=True, default='', max_length=300, verbose_name='производитель')),
('country_origin', models.CharField(blank=True, default='', max_length=100, verbose_name='страна происхождения')),
('is_domestic', models.BooleanField(blank=True, null=True, verbose_name='отечественное производство')),
('year_manufacture', models.PositiveIntegerField(blank=True, null=True, verbose_name='год выпуска')),
('has_cnc', models.BooleanField(blank=True, null=True, verbose_name='наличие ЧПУ')),
('equipment_type', models.CharField(blank=True, default='', max_length=200, verbose_name='тип оборудования')),
('equipment_category', models.CharField(blank=True, default='', max_length=200, verbose_name='категория оборудования')),
('commissioning_date', models.DateField(blank=True, null=True, verbose_name='дата ввода в эксплуатацию')),
('location', models.CharField(blank=True, default='', max_length=300, verbose_name='местонахождение')),
('production_site', models.CharField(blank=True, default='', max_length=200, verbose_name='производственный участок')),
('utilization_rate', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True, verbose_name='коэффициент использования')),
('physical_wear_percent', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True, verbose_name='фактический износ, %')),
('is_operational', models.BooleanField(blank=True, null=True, verbose_name='в рабочем состоянии')),
('requires_repair', models.BooleanField(blank=True, null=True, verbose_name='требует ремонта')),
('requires_replacement', models.BooleanField(blank=True, null=True, verbose_name='требует замены')),
('initial_cost', models.DecimalField(blank=True, decimal_places=2, max_digits=20, null=True, verbose_name='первоначальная стоимость')),
('residual_value', models.DecimalField(blank=True, decimal_places=2, max_digits=20, null=True, verbose_name='остаточная стоимость')),
('notes', models.TextField(blank=True, default='', verbose_name='примечания')),
('organization', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='form_f5_records', to='organization.organization', verbose_name='организация')),
],
options={
'verbose_name': 'запись Ф-5',
'verbose_name_plural': 'записи Ф-5',
'ordering': ['-created_at'],
},
),
migrations.AddIndex(
model_name='formf5record',
index=models.Index(fields=['organization', 'load_batch'], name='form_5_form_organiz_20eb33_idx'),
),
migrations.AddIndex(
model_name='formf5record',
index=models.Index(fields=['load_batch'], name='form_5_form_load_ba_814dbb_idx'),
),
migrations.AddIndex(
model_name='formf5record',
index=models.Index(fields=['equipment_id'], name='form_5_form_equipme_4eedfe_idx'),
),
migrations.AddIndex(
model_name='formf5record',
index=models.Index(fields=['inventory_number'], name='form_5_form_invento_4c3fd9_idx'),
),
]

View File

155
src/apps/form_5/models.py Normal file
View File

@@ -0,0 +1,155 @@
"""
Модели формы Ф-5 (Инвентаризация оборудования).
Содержит:
- FormF5Record - запись формы Ф-5 (детальная информация по единице оборудования)
"""
import uuid
from apps.core.mixins import TimestampMixin
from apps.organization.models import Organization
from django.db import models
from django.utils.translation import gettext_lazy as _
class FormF5Record(TimestampMixin, models.Model):
"""
Запись формы Ф-5 (Инвентаризация оборудования).
Детальная информация по каждой единице оборудования.
"""
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False,
verbose_name=_("ID"),
)
organization = models.ForeignKey(
Organization,
on_delete=models.CASCADE,
related_name="form_f5_records",
verbose_name=_("организация"),
)
load_batch = models.PositiveIntegerField(
_("номер загрузки"),
db_index=True,
help_text=_("Идентификатор пакета загрузки"),
)
# === Идентификация оборудования ===
equipment_id = models.CharField(
_("идентификационный код"),
max_length=50, blank=True, default="",
)
inventory_number = models.CharField(
_("инвентарный номер"),
max_length=50, blank=True, default="",
)
name = models.CharField(
_("наименование оборудования"),
max_length=500, blank=True, default="",
)
model = models.CharField(
_("модель"),
max_length=200, blank=True, default="",
)
# === Производитель ===
manufacturer = models.CharField(
_("производитель"),
max_length=300, blank=True, default="",
)
country_origin = models.CharField(
_("страна происхождения"),
max_length=100, blank=True, default="",
)
is_domestic = models.BooleanField(
_("отечественное производство"),
null=True, blank=True,
)
# === Технические характеристики ===
year_manufacture = models.PositiveIntegerField(
_("год выпуска"),
null=True, blank=True,
)
has_cnc = models.BooleanField(
_("наличие ЧПУ"),
null=True, blank=True,
)
equipment_type = models.CharField(
_("тип оборудования"),
max_length=200, blank=True, default="",
)
equipment_category = models.CharField(
_("категория оборудования"),
max_length=200, blank=True, default="",
)
# === Эксплуатация ===
commissioning_date = models.DateField(
_("дата ввода в эксплуатацию"),
null=True, blank=True,
)
location = models.CharField(
_("местонахождение"),
max_length=300, blank=True, default="",
)
production_site = models.CharField(
_("производственный участок"),
max_length=200, blank=True, default="",
)
# === Состояние и использование ===
utilization_rate = models.DecimalField(
_("коэффициент использования"),
max_digits=5, decimal_places=2, null=True, blank=True,
)
physical_wear_percent = models.DecimalField(
_("фактический износ, %"),
max_digits=5, decimal_places=2, null=True, blank=True,
)
is_operational = models.BooleanField(
_("в рабочем состоянии"),
null=True, blank=True,
)
requires_repair = models.BooleanField(
_("требует ремонта"),
null=True, blank=True,
)
requires_replacement = models.BooleanField(
_("требует замены"),
null=True, blank=True,
)
# === Стоимость ===
initial_cost = models.DecimalField(
_("первоначальная стоимость"),
max_digits=20, decimal_places=2, null=True, blank=True,
)
residual_value = models.DecimalField(
_("остаточная стоимость"),
max_digits=20, decimal_places=2, null=True, blank=True,
)
# === Дополнительная информация ===
notes = models.TextField(
_("примечания"),
blank=True, default="",
)
class Meta:
verbose_name = _("запись Ф-5")
verbose_name_plural = _("записи Ф-5")
ordering = ["-created_at"]
indexes = [
models.Index(fields=["organization", "load_batch"]),
models.Index(fields=["load_batch"]),
models.Index(fields=["equipment_id"]),
models.Index(fields=["inventory_number"]),
]
def __str__(self) -> str:
return f"Ф-5: {self.name or self.inventory_number} ({self.organization.name})"

View File

@@ -0,0 +1,58 @@
"""Сериализаторы формы Ф-5."""
from apps.form_5.models import FormF5Record
from apps.organization.serializers import OrganizationSerializer
from rest_framework import serializers
class FormF5RecordSerializer(serializers.ModelSerializer):
organization = OrganizationSerializer(read_only=True)
class Meta:
model = FormF5Record
fields = "__all__"
read_only_fields = ["id", "created_at", "updated_at"]
class FormF5RecordListSerializer(serializers.ModelSerializer):
organization_name = serializers.CharField(source="organization.name", read_only=True)
organization_inn = serializers.CharField(source="organization.inn", read_only=True)
class Meta:
model = FormF5Record
fields = [
"id", "organization_name", "organization_inn", "load_batch",
"equipment_id", "name", "model", "year_manufacture", "physical_wear_percent",
"created_at",
]
class FormF5UploadSerializer(serializers.Serializer):
file = serializers.FileField(help_text="Excel файл формы Ф-5 (.xlsx)")
def validate_file(self, value):
if not value.name.endswith((".xlsx", ".xls")):
raise serializers.ValidationError("Неподдерживаемый формат файла")
if value.size > 50 * 1024 * 1024:
raise serializers.ValidationError("Размер файла превышает 50MB")
return value
class FieldErrorSerializer(serializers.Serializer):
field = serializers.CharField()
message = serializers.CharField()
class RowValidationErrorSerializer(serializers.Serializer):
row = serializers.IntegerField()
inn = serializers.CharField(allow_null=True)
kpp = serializers.CharField(allow_null=True)
organization_name = serializers.CharField(allow_null=True)
errors = FieldErrorSerializer(many=True)
class FormF5ParseResultSerializer(serializers.Serializer):
batch_id = serializers.IntegerField()
loaded_count = serializers.IntegerField()
skipped_count = serializers.IntegerField()
errors = RowValidationErrorSerializer(many=True)

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)

19
src/apps/form_5/tasks.py Normal file
View File

@@ -0,0 +1,19 @@
"""Celery задачи для формы Ф-5."""
import logging
from io import BytesIO
from apps.core.tasks import TrackedTask
from apps.form_5.services import FormF5Parser
from celery import shared_task
logger = logging.getLogger(__name__)
@shared_task(bind=True, base=TrackedTask)
def process_form_f5_file(self, file_content: bytes, file_name: str) -> dict:
logger.info(f"Начало обработки файла Ф-5: {file_name}")
parser = FormF5Parser()
result = parser.parse(BytesIO(file_content))
logger.info(f"Обработка Ф-5 завершена: {result.loaded_count} загружено, {result.skipped_count} пропущено")
return result.to_dict()

13
src/apps/form_5/urls.py Normal file
View File

@@ -0,0 +1,13 @@
"""URL маршруты формы Ф-5."""
from apps.form_5.api import FormF5RecordViewSet, FormF5UploadView
from django.urls import include, path
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register("records", FormF5RecordViewSet, basename="form-f5-records")
urlpatterns = [
path("upload/", FormF5UploadView.as_view(), name="form-f5-upload"),
path("", include(router.urls)),
]