fix: align reporting forms and demo analytics
All checks were successful
CI/CD Pipeline / Code Quality Checks (push) Successful in 2m21s
CI/CD Pipeline / Run Tests (push) Successful in 4m23s
CI/CD Pipeline / Build and Push Dev Images (push) Successful in 32s
CI/CD Pipeline / Deploy Dev via Compose (push) Successful in 52s

This commit is contained in:
2026-07-28 11:07:47 +02:00
parent ff0b2bdfca
commit df0f41b9c0
31 changed files with 1627 additions and 328 deletions

View File

@@ -49,10 +49,6 @@ def _amount(value) -> int:
return int(_dec(value))
def _amount_thousands(value) -> int:
return int(_dec(value) / THOUSAND)
def _ratio(value) -> float:
return round(float(_dec(value)), 1)
@@ -87,8 +83,18 @@ def _direction(current, previous) -> str:
return "unchanged"
def _period_rank(report_quarter: int | None) -> int:
return 5 if report_quarter is None else report_quarter
def _period_rank(record) -> int:
"""Rank the reporting period represented by a record within its year."""
report_month = getattr(record, "report_month", None)
if report_month is not None:
return int(report_month)
report_half_year = getattr(record, "report_half_year", None)
if report_half_year is not None:
return int(report_half_year) * 6
report_quarter = getattr(record, "report_quarter", None)
if report_quarter is not None:
return int(report_quarter) * 3
return 13
def _pick_record(
@@ -106,7 +112,7 @@ def _pick_record(
return max(
year_records,
key=lambda record: (_period_rank(record.report_quarter), record.created_at),
key=lambda record: (_period_rank(record), record.created_at),
)
@@ -331,7 +337,7 @@ class OrganizationAnalyticsService:
"assets": "rub_thousands",
"capex": "rub_thousands",
"rd_expenses": "rub_thousands",
"revenue_per_employee": "rub_per_employee",
"revenue_per_employee": "rub_thousands_per_employee",
}
@staticmethod
@@ -368,23 +374,24 @@ class OrganizationAnalyticsService:
if metric == "loans":
if f4 is not None and f4.loans_rsbu is not None:
return _dec(f4.loans_rsbu)
return _dec(getattr(f2, "borrowings_non_current", ZERO)) + _dec(
getattr(f2, "borrowings_current", ZERO)
)
return (
_dec(getattr(f2, "borrowings_non_current", ZERO))
+ _dec(getattr(f2, "borrowings_current", ZERO))
) / THOUSAND
primary, fallback = field_map.get(metric, (ZERO, ZERO))
return _dec(primary or fallback)
if primary is not None:
return _dec(primary)
return _dec(fallback) / THOUSAND
@classmethod
def _economics_display_value(cls, metric: str, f2, f4, f1) -> int:
if metric == "revenue_per_employee":
employees = _dec(getattr(f1, "avg_payroll_employees", ZERO))
if employees == ZERO:
employees = _dec(getattr(f1, "avg_employees", ZERO))
employees = _dec(getattr(f1, "avg_employees", ZERO))
if employees == ZERO:
return 0
return _amount(cls._economics_metric_value("revenue", f2, f4) / employees)
return _amount_thousands(cls._economics_metric_value(metric, f2, f4))
return _amount(cls._economics_metric_value(metric, f2, f4))
@classmethod
def get_economics(
@@ -405,12 +412,13 @@ class OrganizationAnalyticsService:
cls._f1_records(organization), from_year, to_year
)
periods = sorted(set(f2_by_year) | set(f4_by_year) | set(f1_by_year))
periods = sorted(set(f2_by_year) | set(f4_by_year))
if not periods:
return {
"organization_id": str(organization.id),
"group": group,
"periods": [],
"report_periods": [],
"data_available": False,
"message": "Данные отсутствуют",
"kpis": {},
@@ -438,6 +446,15 @@ class OrganizationAnalyticsService:
"organization_id": str(organization.id),
"group": group,
"periods": periods,
"report_periods": [
{
"year": year,
"report_half_year": getattr(
f4_by_year.get(year), "report_half_year", None
),
}
for year in periods
],
"data_available": True,
"message": None,
"kpis": {
@@ -475,7 +492,18 @@ class OrganizationAnalyticsService:
"ratios": [
{
"period": report_year,
"ros": _ratio(getattr(f4_by_year.get(report_year), "ros", ZERO)),
"ros": _share_percent(
cls._economics_metric_value(
"net_profit",
f2_by_year.get(report_year),
f4_by_year.get(report_year),
),
cls._economics_metric_value(
"revenue",
f2_by_year.get(report_year),
f4_by_year.get(report_year),
),
),
"roa": _ratio(getattr(f4_by_year.get(report_year), "roa", ZERO)),
"roe": _ratio(getattr(f4_by_year.get(report_year), "roe", ZERO)),
"ebitda_margin": _share_percent(
@@ -504,95 +532,103 @@ class OrganizationAnalyticsService:
report_year: int,
history_years: int,
) -> dict[str, object]:
f1_records = cls._f1_records(organization)
f3_records = cls._f3_records(organization)
report_year = _resolve_report_year(f3_records, report_year)
current_f3 = cls._require_record(
_pick_record(f3_records, report_year),
report_year = _resolve_report_year(f1_records, report_year)
current_f1 = cls._require_record(
_pick_record(f1_records, report_year),
entity="Personnel",
)
current_f1 = _pick_record(cls._f1_records(organization), report_year)
current_f3 = _pick_record(f3_records, report_year)
years = list(range(report_year - history_years + 1, report_year + 1))
history_records = _best_records_by_year(f3_records, years[0], years[-1])
history_f1_records = _best_records_by_year(
cls._f1_records(organization), years[0], years[-1]
history_f1_records = _best_records_by_year(f1_records, years[0], years[-1])
history_f3_records = _best_records_by_year(f3_records, years[0], years[-1])
def optional_int(record, field_name: str) -> int | None:
value = getattr(record, field_name, None) if record is not None else None
return int(_dec(value)) if value is not None else None
def age_distribution_for(record) -> list[dict[str, int]]:
return [
{
"age_group": "under_30",
"employees_count": (optional_int(record, "employees_under_20") or 0)
+ (optional_int(record, "employees_20_29") or 0),
},
{
"age_group": "30_50",
"employees_count": (optional_int(record, "employees_30_39") or 0)
+ (optional_int(record, "employees_40_49") or 0),
},
{
"age_group": "over_50",
"employees_count": (optional_int(record, "employees_50_59") or 0)
+ (optional_int(record, "employees_over_60") or 0),
},
]
age_distribution = age_distribution_for(current_f3)
average_age = (
_ratio(current_f3.average_employee_age)
if current_f3 is not None and current_f3.average_employee_age is not None
else None
)
average_employees = int(_dec(current_f3.avg_employees))
under_30 = int(average_employees * 0.29)
from_30_to_50 = int(average_employees * 0.49)
over_50 = max(0, average_employees - under_30 - from_30_to_50)
age_distribution = [
{"age_group": "under_30", "employees_count": under_30},
{"age_group": "30_50", "employees_count": from_30_to_50},
{"age_group": "over_50", "employees_count": over_50},
]
return {
"organization_id": str(organization.id),
"report_year": report_year,
"average_age": _weighted_average_age(age_distribution),
"report_month": current_f1.report_month,
"average_age": average_age,
"headcount": {
"average_employees": average_employees,
"average_employees": int(_dec(current_f1.avg_employees)),
"avg_payroll_employees": int(
_dec(getattr(current_f1, "avg_payroll_employees", ZERO))
),
"payroll_fund": _amount(getattr(current_f1, "payroll_fund", ZERO)),
"production_workers": int(_dec(current_f3.production_workers)),
"engineering_workers": int(_dec(current_f3.engineering_workers)),
"administrative_workers": int(_dec(current_f3.administrative_workers)),
"workers_needed": int(_dec(current_f3.workers_needed)),
"payroll_fund": _amount(
_dec(getattr(current_f1, "payroll_fund", ZERO)) * THOUSAND
),
"production_workers": optional_int(current_f3, "production_workers"),
"engineering_workers": optional_int(current_f3, "engineering_workers"),
"administrative_workers": optional_int(
current_f3, "administrative_workers"
),
"workers_needed": optional_int(current_f3, "workers_needed"),
},
"age_distribution": age_distribution,
"history": [
{
"year": year,
"average_employees": int(_dec(history_records[year].avg_employees)),
"report_month": history_f1_records[year].report_month,
"average_employees": int(
_dec(history_f1_records[year].avg_employees)
),
"avg_payroll_employees": int(
_dec(
getattr(
history_f1_records.get(year),
history_f1_records[year],
"avg_payroll_employees",
ZERO,
)
)
),
"average_age": _weighted_average_age(
[
{
"age_group": "under_30",
"employees_count": int(
_dec(history_records[year].avg_employees)
* Decimal("0.29")
),
},
{
"age_group": "30_50",
"employees_count": int(
_dec(history_records[year].avg_employees)
* Decimal("0.49")
),
},
{
"age_group": "over_50",
"employees_count": int(
_dec(history_records[year].avg_employees)
* Decimal("0.22")
),
},
]
"average_age": (
_ratio(history_f3_records[year].average_employee_age)
if year in history_f3_records
and history_f3_records[year].average_employee_age is not None
else None
),
"payroll_fund": _amount(
getattr(history_f1_records.get(year), "payroll_fund", ZERO)
_dec(getattr(history_f1_records[year], "payroll_fund", ZERO))
* THOUSAND
),
}
for year in years
if year in history_records
if year in history_f1_records
],
}
@classmethod
def get_equipment(
def get_equipment( # noqa: C901
cls,
*,
organization: Organization,
@@ -616,6 +652,40 @@ class OrganizationAnalyticsService:
report_year=report_year,
)
def weighted_metric(records, value_field: str, weight_field: str):
weighted_sum = ZERO
total_weight = 0
for record in records:
value = getattr(record, value_field, None)
weight = int(_dec(getattr(record, weight_field, ZERO)))
if value is None or weight <= 0:
continue
weighted_sum += _dec(value) * weight
total_weight += weight
if total_weight == 0:
return None
return weighted_sum / Decimal(str(total_weight))
def record_age_metric(record, suffix: str):
weighted_sum = ZERO
total_weight = 0
for prefix in (
"age_under_5",
"age_5_10",
"age_10_15",
"age_15_20",
"age_over_20",
):
value = getattr(record, f"{prefix}_{suffix}", None)
weight = int(_dec(getattr(record, prefix, ZERO)))
if value is None or weight <= 0:
continue
weighted_sum += _dec(value) * weight
total_weight += weight
if total_weight == 0:
return None
return weighted_sum / Decimal(str(total_weight))
if f6_records:
age_distribution = [
{
@@ -690,51 +760,44 @@ class OrganizationAnalyticsService:
"15_20_years": "age_15_20",
"over_20_years": "age_over_20",
}
total_age_units = sum(item["units_count"] for item in age_distribution)
for item in age_distribution:
bucket = item["bucket"]
if f6_records:
bucket_units_by_record = [
int(_dec(getattr(record, bucket_fields[bucket], ZERO)))
for record in f6_records
]
bucket_field = bucket_fields[bucket]
imported_equipment = sum(
round(
int(_dec(record.imported_equipment))
* units
/ max(1, int(_dec(record.total_equipment)))
)
for record, units in zip(
f6_records, bucket_units_by_record, strict=True
)
int(_dec(getattr(record, f"{bucket_field}_imported", ZERO)))
for record in f6_records
)
utilization_rate = weighted_metric(
f6_records,
f"{bucket_field}_utilization_rate",
bucket_field,
)
lease_share = weighted_metric(
f6_records,
f"{bucket_field}_lease_share_itn_percent",
bucket_field,
)
weighted_units = sum(bucket_units_by_record)
utilization_rate = sum(
_dec(record.utilization_rate) * units
for record, units in zip(
f6_records, bucket_units_by_record, strict=True
)
) / max(1, weighted_units)
weighted_wear = sum(
_dec(record.physical_wear_percent) * units
for record, units in zip(
f6_records, bucket_units_by_record, strict=True
)
) / max(1, weighted_units)
else:
imported_equipment = round(
int(_dec(current_f3.imported_equipment))
* item["units_count"]
/ max(1, total_age_units)
imported_equipment = None
utilization_rate = (
_dec(current_f3.utilization_rate)
if current_f3.utilization_rate is not None
else None
)
utilization_rate = _dec(current_f3.utilization_rate)
weighted_wear = _dec(current_f3.physical_wear_percent)
lease_share = None
item.update(
{
"imported_equipment": imported_equipment,
"utilization_rate": round(float(utilization_rate / 100), 2),
"lease_share_itn_percent": None,
"weighted_wear_percent": _ratio(weighted_wear),
"utilization_rate": (
round(float(utilization_rate / 100), 2)
if utilization_rate is not None
else None
),
"lease_share_itn_percent": (
_ratio(lease_share) if lease_share is not None else None
),
"weighted_wear_percent": None,
}
)
@@ -743,11 +806,13 @@ class OrganizationAnalyticsService:
{
"equipment_category": record.category,
"total_equipment": record.total_equipment,
"domestic_equipment": record.domestic_equipment,
"domestic_equipment": None,
"imported_equipment": record.imported_equipment,
"physical_wear_percent": record.physical_wear_percent,
"utilization_rate": record.utilization_rate,
"lease_share_itn_percent": None,
"physical_wear_percent": None,
"utilization_rate": record_age_metric(record, "utilization_rate"),
"lease_share_itn_percent": record_age_metric(
record, "lease_share_itn_percent"
),
}
for record in f6_records
]
@@ -776,47 +841,115 @@ class OrganizationAnalyticsService:
.order_by("equipment_category")
)
f3_by_year = _best_records_by_year(
f3_records,
min(record.report_year for record in f3_records),
max(record.report_year for record in f3_records),
)
dynamics_years = sorted(f3_by_year)
commissioned_by_year = {
year: FormF5Record.objects.filter(
all_f6_records = list(
FormF6Record.objects.filter(
organization=organization,
is_active_version=True,
report_year=year,
commissioning_date__year=year,
).count()
for year in dynamics_years
}
decommissioned_by_year = {
year: FormF5Record.objects.filter(
organization=organization,
is_active_version=True,
report_year=year,
)
.filter(Q(is_operational=False) | Q(requires_replacement=True))
.count()
for year in dynamics_years
}
)
f6_by_year: dict[int, list[FormF6Record]] = defaultdict(list)
for record in all_f6_records:
f6_by_year[record.report_year].append(record)
if f6_by_year:
dynamics_years = sorted(f6_by_year)
total_by_year = {
year: sum(int(_dec(record.total_equipment)) for record in year_records)
for year, year_records in f6_by_year.items()
}
commissioned_by_year = {
year: sum(
int(_dec(record.commissioned_equipment)) for record in year_records
)
for year, year_records in f6_by_year.items()
}
decommissioned_by_year = {
year: sum(
int(_dec(record.decommissioned_equipment))
for record in year_records
)
for year, year_records in f6_by_year.items()
}
else:
f3_by_year = _best_records_by_year(
f3_records,
min(record.report_year for record in f3_records),
max(record.report_year for record in f3_records),
)
dynamics_years = sorted(f3_by_year)
total_by_year = {
year: int(_dec(f3_by_year[year].total_equipment))
for year in dynamics_years
}
commissioned_by_year = {
year: FormF5Record.objects.filter(
organization=organization,
is_active_version=True,
report_year=year,
commissioning_date__year=year,
).count()
for year in dynamics_years
}
decommissioned_by_year = {
year: FormF5Record.objects.filter(
organization=organization,
is_active_version=True,
report_year=year,
)
.filter(Q(is_operational=False) | Q(requires_replacement=True))
.count()
for year in dynamics_years
}
total_equipment = (
sum(int(_dec(record.total_equipment)) for record in f6_records)
if f6_records
else int(_dec(current_f3.total_equipment))
)
imported_equipment = (
sum(int(_dec(record.imported_equipment)) for record in f6_records)
if f6_records
else int(_dec(current_f3.imported_equipment))
)
average_shift = (
weighted_metric(f6_records, "avg_shift_work", "total_equipment")
if f6_records
else getattr(current_f3, "avg_shift_work", None)
)
return {
"organization_id": str(organization.id),
"report_year": report_year,
"summary": {
"total_equipment": int(_dec(current_f3.total_equipment)),
"machine_tools_and_equipment": int(_dec(current_f3.total_equipment)),
"domestic_equipment": int(_dec(current_f3.domestic_equipment)),
"imported_equipment": int(_dec(current_f3.imported_equipment)),
"physical_wear_percent": _ratio(current_f3.physical_wear_percent),
"weighted_wear_percent": _ratio(current_f3.physical_wear_percent),
"utilization_rate": round(
float(_dec(current_f3.utilization_rate) / Decimal("100")), 2
"total_equipment": total_equipment,
"machine_tools_and_equipment": int(
_dec(
getattr(current_f3, "machine_tools_and_equipment", None)
or current_f3.total_equipment
)
),
"domestic_equipment": (
None if f6_records else int(_dec(current_f3.domestic_equipment))
),
"imported_equipment": imported_equipment,
"physical_wear_percent": _ratio(current_f3.physical_wear_percent),
"weighted_wear_percent": None,
"utilization_rate": (
round(
float(_dec(current_f3.utilization_rate) / Decimal("100")),
2,
)
if current_f3.utilization_rate is not None
else None
),
"avg_shift_work": (
_ratio(average_shift) if average_shift is not None else None
),
"equipment_needed": (
int(_dec(current_f3.equipment_needed))
if current_f3.equipment_needed is not None
else None
),
"avg_shift_work": _ratio(current_f3.avg_shift_work),
"equipment_needed": int(_dec(current_f3.equipment_needed)),
"average_age_years": _weighted_average_age(age_distribution),
"commissioned_equipment": commissioned_by_year.get(report_year, 0),
"decommissioned_equipment": decommissioned_by_year.get(report_year, 0),
@@ -826,16 +959,28 @@ class OrganizationAnalyticsService:
{
"category": row["equipment_category"] or "Без категории",
"total_equipment": int(_dec(row["total_equipment"])),
"domestic_equipment": int(_dec(row["domestic_equipment"])),
"domestic_equipment": (
int(_dec(row["domestic_equipment"]))
if row["domestic_equipment"] is not None
else None
),
"imported_equipment": int(_dec(row["imported_equipment"])),
"physical_wear_percent": _ratio(row["physical_wear_percent"]),
"weighted_wear_percent": _ratio(row["physical_wear_percent"]),
"physical_wear_percent": (
_ratio(row["physical_wear_percent"])
if row["physical_wear_percent"] is not None
else None
),
"weighted_wear_percent": None,
"utilization_rate": round(
float(_dec(row.get("utilization_rate")) / Decimal("100")), 2
)
if row.get("utilization_rate") is not None
else None,
"lease_share_itn_percent": row.get("lease_share_itn_percent"),
"lease_share_itn_percent": (
_ratio(row["lease_share_itn_percent"])
if row.get("lease_share_itn_percent") is not None
else None
),
}
for row in category_rows
],
@@ -846,7 +991,7 @@ class OrganizationAnalyticsService:
"points": [
{
"period": year,
"value": int(_dec(f3_by_year[year].total_equipment)),
"value": total_by_year[year],
}
for year in dynamics_years
],

View File

@@ -90,10 +90,16 @@ class EconomicsRatioNormativesSerializer(serializers.Serializer):
ebitda_margin = serializers.FloatField(allow_null=True)
class EconomicsReportPeriodSerializer(serializers.Serializer):
year = serializers.IntegerField()
report_half_year = serializers.IntegerField(allow_null=True)
class EconomicsResponseSerializer(serializers.Serializer):
organization_id = serializers.UUIDField()
group = serializers.CharField()
periods = serializers.ListField(child=serializers.IntegerField())
report_periods = EconomicsReportPeriodSerializer(many=True)
data_available = serializers.BooleanField()
message = serializers.CharField(allow_null=True)
kpis = EconomicsKpisSerializer()
@@ -106,10 +112,10 @@ class PersonnelHeadcountSerializer(serializers.Serializer):
average_employees = serializers.IntegerField()
avg_payroll_employees = serializers.IntegerField()
payroll_fund = serializers.IntegerField()
production_workers = serializers.IntegerField()
engineering_workers = serializers.IntegerField()
administrative_workers = serializers.IntegerField()
workers_needed = serializers.IntegerField()
production_workers = serializers.IntegerField(allow_null=True)
engineering_workers = serializers.IntegerField(allow_null=True)
administrative_workers = serializers.IntegerField(allow_null=True)
workers_needed = serializers.IntegerField(allow_null=True)
class PersonnelAgeDistributionSerializer(serializers.Serializer):
@@ -119,16 +125,18 @@ class PersonnelAgeDistributionSerializer(serializers.Serializer):
class PersonnelHistorySerializer(serializers.Serializer):
year = serializers.IntegerField()
report_month = serializers.IntegerField(allow_null=True)
average_employees = serializers.IntegerField()
avg_payroll_employees = serializers.IntegerField()
average_age = serializers.FloatField()
average_age = serializers.FloatField(allow_null=True)
payroll_fund = serializers.IntegerField()
class PersonnelResponseSerializer(serializers.Serializer):
organization_id = serializers.UUIDField()
report_year = serializers.IntegerField()
average_age = serializers.FloatField()
report_month = serializers.IntegerField(allow_null=True)
average_age = serializers.FloatField(allow_null=True)
headcount = PersonnelHeadcountSerializer()
age_distribution = PersonnelAgeDistributionSerializer(many=True)
history = PersonnelHistorySerializer(many=True)
@@ -137,13 +145,13 @@ class PersonnelResponseSerializer(serializers.Serializer):
class EquipmentSummarySerializer(serializers.Serializer):
total_equipment = serializers.IntegerField()
machine_tools_and_equipment = serializers.IntegerField()
domestic_equipment = serializers.IntegerField()
domestic_equipment = serializers.IntegerField(allow_null=True)
imported_equipment = serializers.IntegerField()
physical_wear_percent = serializers.FloatField()
weighted_wear_percent = serializers.FloatField()
utilization_rate = serializers.FloatField()
avg_shift_work = serializers.FloatField()
equipment_needed = serializers.IntegerField()
weighted_wear_percent = serializers.FloatField(allow_null=True)
utilization_rate = serializers.FloatField(allow_null=True)
avg_shift_work = serializers.FloatField(allow_null=True)
equipment_needed = serializers.IntegerField(allow_null=True)
average_age_years = serializers.FloatField()
commissioned_equipment = serializers.IntegerField()
decommissioned_equipment = serializers.IntegerField()
@@ -152,19 +160,19 @@ class EquipmentSummarySerializer(serializers.Serializer):
class EquipmentAgeDistributionSerializer(serializers.Serializer):
bucket = serializers.CharField()
units_count = serializers.IntegerField()
imported_equipment = serializers.IntegerField()
utilization_rate = serializers.FloatField()
imported_equipment = serializers.IntegerField(allow_null=True)
utilization_rate = serializers.FloatField(allow_null=True)
lease_share_itn_percent = serializers.FloatField(allow_null=True)
weighted_wear_percent = serializers.FloatField()
weighted_wear_percent = serializers.FloatField(allow_null=True)
class EquipmentCategorySerializer(serializers.Serializer):
category = serializers.CharField()
total_equipment = serializers.IntegerField()
domestic_equipment = serializers.IntegerField()
domestic_equipment = serializers.IntegerField(allow_null=True)
imported_equipment = serializers.IntegerField()
physical_wear_percent = serializers.FloatField()
weighted_wear_percent = serializers.FloatField()
physical_wear_percent = serializers.FloatField(allow_null=True)
weighted_wear_percent = serializers.FloatField(allow_null=True)
utilization_rate = serializers.FloatField(allow_null=True)
lease_share_itn_percent = serializers.FloatField(allow_null=True)