47 lines
1.3 KiB
Python
47 lines
1.3 KiB
Python
"""Цены компонентов для analytics."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Dict, List, Optional
|
|
|
|
from sqlalchemy import select
|
|
|
|
from app import db
|
|
from app.models import Component
|
|
|
|
|
|
def component_prices(
|
|
*,
|
|
component_ids: Optional[List[str]] = None,
|
|
names: Optional[List[str]] = None,
|
|
) -> Dict[str, float]:
|
|
"""component_id или имя -> price руб/кг."""
|
|
prices: Dict[str, float] = {}
|
|
ids = [x for x in (component_ids or []) if x]
|
|
if ids:
|
|
rows = db.session.execute(
|
|
select(Component).where(
|
|
Component.id.in_(ids),
|
|
Component.is_deleted.is_(False),
|
|
)
|
|
).scalars().all()
|
|
for row in rows:
|
|
prices[row.id] = float(row.price or 0)
|
|
for name in names or []:
|
|
if not name or name in prices:
|
|
continue
|
|
row = db.session.execute(
|
|
select(Component)
|
|
.where(Component.name == name, Component.is_deleted.is_(False))
|
|
.limit(1)
|
|
).scalar_one_or_none()
|
|
if row:
|
|
prices[name] = float(row.price or 0)
|
|
return prices
|
|
|
|
|
|
def price_for(*, prices: Dict[str, float], component_id: Optional[str], name: str) -> float:
|
|
if component_id and component_id in prices:
|
|
return prices[component_id]
|
|
return prices.get(name, 0.0)
|