53 lines
1.7 KiB
Python
53 lines
1.7 KiB
Python
"""Сериализация параметров методики норм на профиле."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any
|
|
|
|
from app.lab.calc.norms_resolver import NormsParams
|
|
from app.lab.models import LabAnimalProfile
|
|
|
|
|
|
def load_norms_params(profile: LabAnimalProfile) -> NormsParams:
|
|
raw = profile.norms_params_json
|
|
if not raw:
|
|
return NormsParams()
|
|
try:
|
|
data = json.loads(raw)
|
|
except (json.JSONDecodeError, TypeError):
|
|
return NormsParams()
|
|
return NormsParams.from_dict(data if isinstance(data, dict) else {})
|
|
|
|
|
|
def save_norms_params(profile: LabAnimalProfile, params: NormsParams | dict[str, Any] | None) -> None:
|
|
if params is None:
|
|
profile.norms_params_json = None
|
|
return
|
|
if isinstance(params, NormsParams):
|
|
payload = {
|
|
k: v
|
|
for k, v in (
|
|
("milkFatPct", params.milk_fat_pct),
|
|
("lactationNo", params.lactation_no),
|
|
("lactationStage", params.lactation_stage),
|
|
("bodyCondition", params.body_condition),
|
|
("housingSystem", params.housing_system),
|
|
("koncOeSv", params.konc_oe_sv),
|
|
)
|
|
if v is not None
|
|
}
|
|
else:
|
|
payload = dict(params)
|
|
profile.norms_params_json = json.dumps(payload, ensure_ascii=False) if payload else None
|
|
|
|
|
|
def norms_params_api(profile: LabAnimalProfile) -> dict[str, Any]:
|
|
if not profile.norms_params_json:
|
|
return {}
|
|
try:
|
|
data = json.loads(profile.norms_params_json)
|
|
return data if isinstance(data, dict) else {}
|
|
except (json.JSONDecodeError, TypeError):
|
|
return {}
|