141 lines
4.9 KiB
Python
141 lines
4.9 KiB
Python
"""Small shared helpers for resource routers (label joins, lookups, export)."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from typing import Any
|
||
|
||
from sqlalchemy import select
|
||
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
||
from ..core.deps import department_subtree
|
||
|
||
|
||
async def dept_filter_ids(session: AsyncSession, raw: str | None,
|
||
subtree: bool = True) -> list[int]:
|
||
"""把 ?department_id=3,7 解析成部门 id 集合(subtree 时展开下级)。"""
|
||
picked = [int(x) for x in (raw or "").split(",") if x.strip().isdigit()]
|
||
if not picked:
|
||
return []
|
||
if not subtree:
|
||
return picked
|
||
out: set[int] = set()
|
||
for one in picked:
|
||
out.update(await department_subtree(session, one))
|
||
return sorted(out)
|
||
|
||
|
||
async def attach_labels(session: AsyncSession, rows: list[Any],
|
||
specs: list[tuple[str, type, str, str]]) -> None:
|
||
"""Fill ``row.<target>`` with the referenced record's label.
|
||
|
||
``specs`` entries are ``(target_attr, ReferencedModel, local_fk_attr, label_attr)``.
|
||
One batched query per spec keeps list endpoints free of N+1 round trips.
|
||
"""
|
||
if not rows:
|
||
return
|
||
for target, ref_model, fk_attr, label_attr in specs:
|
||
ids = {getattr(r, fk_attr, None) for r in rows}
|
||
ids.discard(None)
|
||
if not ids:
|
||
continue
|
||
rows_map = dict((
|
||
await session.execute(select(ref_model.id, getattr(ref_model, label_attr))
|
||
.where(ref_model.id.in_(ids)))
|
||
).all())
|
||
for r in rows:
|
||
value = rows_map.get(getattr(r, fk_attr, None))
|
||
try:
|
||
setattr(r, target, value)
|
||
except (AttributeError, TypeError):
|
||
pass
|
||
|
||
|
||
async def label_map(session: AsyncSession, model: type, label_attr: str = "name") -> dict[int, str]:
|
||
rows = (await session.execute(select(model.id, getattr(model, label_attr)))).all()
|
||
return {r[0]: r[1] for r in rows}
|
||
|
||
|
||
async def counts_by(session: AsyncSession, model: type, fk_attr: str) -> dict[int, int]:
|
||
from sqlalchemy import func
|
||
|
||
col = getattr(model, fk_attr)
|
||
rows = (await session.execute(select(col, func.count()).where(col.is_not(None)).group_by(col))).all()
|
||
return {r[0]: int(r[1]) for r in rows}
|
||
|
||
|
||
async def employee_dept_names(session: AsyncSession, rows: list[Any], fk: str = "employee_id") -> None:
|
||
"""Resolve ``department_name`` through the employee relation.
|
||
|
||
Payroll / benefits rows carry an ``employee_id`` but no department of their own,
|
||
so the two-hop lookup happens here once per page instead of per row.
|
||
"""
|
||
from ..models.employee import Employee
|
||
from ..models.org import Department
|
||
|
||
emp_ids = {getattr(r, fk) for r in rows if getattr(r, fk, None)}
|
||
if not emp_ids:
|
||
return
|
||
emps = {e.id: e for e in (await session.execute(
|
||
select(Employee).where(Employee.id.in_(emp_ids)))).scalars().all()}
|
||
depts = await label_map(session, Department)
|
||
for r in rows:
|
||
emp = emps.get(getattr(r, fk))
|
||
if emp is not None:
|
||
try:
|
||
r.department_name = depts.get(emp.department_id)
|
||
except (AttributeError, TypeError):
|
||
pass
|
||
|
||
|
||
async def one_scalar(session: AsyncSession, stmt) -> int:
|
||
return int((await session.execute(stmt)).scalar() or 0)
|
||
|
||
|
||
def xlsx_response(headers: list[str], rows: list[list[Any]], filename: str):
|
||
"""Stream a workbook as an attachment (used by roster / payslip exports)."""
|
||
import io
|
||
|
||
from fastapi.responses import StreamingResponse
|
||
from openpyxl import Workbook
|
||
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = "Sheet1"
|
||
ws.append(headers)
|
||
for row in rows:
|
||
ws.append([v.isoformat() if hasattr(v, "isoformat") else v for v in row])
|
||
for idx, title in enumerate(headers, start=1):
|
||
ws.column_dimensions[ws.cell(row=1, column=idx).column_letter].width = max(
|
||
12, min(32, len(str(title)) * 2 + 6)
|
||
)
|
||
buffer = io.BytesIO()
|
||
wb.save(buffer)
|
||
buffer.seek(0)
|
||
from urllib.parse import quote
|
||
|
||
return StreamingResponse(
|
||
buffer,
|
||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||
headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename)}"},
|
||
)
|
||
|
||
|
||
def parse_xlsx(data: bytes) -> list[dict[str, Any]]:
|
||
"""First worksheet -> list of dicts keyed by the header row."""
|
||
import io
|
||
|
||
from openpyxl import load_workbook
|
||
|
||
wb = load_workbook(io.BytesIO(data), data_only=True, read_only=True)
|
||
ws = wb.active
|
||
rows = list(ws.iter_rows(values_only=True))
|
||
if not rows:
|
||
return []
|
||
headers = [str(h).strip() if h is not None else "" for h in rows[0]]
|
||
out = []
|
||
for raw in rows[1:]:
|
||
if raw is None or all(c in (None, "") for c in raw):
|
||
continue
|
||
out.append({headers[i]: raw[i] for i in range(min(len(headers), len(raw))) if headers[i]})
|
||
return out
|