按接收时间筛选细胞存储/科研捐赠接收记录(含废弃),组装母亲、销售专员与生产接收三字段,并挂质检管理菜单。 Co-authored-by: Cursor <cursoragent@cursor.com>
337 lines
12 KiB
Python
337 lines
12 KiB
Python
"""月度样本信息总览:接收记录列表组装。"""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from decimal import Decimal
|
|
from typing import Any, Dict, List, Optional, Tuple
|
|
|
|
from sqlalchemy import or_
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.data_scope import apply_data_scope
|
|
from app.crud import sample_production_reception as prod_svc
|
|
from app.models.models import (
|
|
BizProtocolCollectionInfo,
|
|
BizProtocolPartyCustomer,
|
|
BizProtocolSample,
|
|
BizSampleProductionReception,
|
|
BizSampleReception,
|
|
SysUser,
|
|
)
|
|
from app.models.research_donation import (
|
|
BizResearchDonationCollection,
|
|
BizResearchDonationParty,
|
|
BizResearchDonationSample,
|
|
)
|
|
|
|
|
|
def _fmt_dt(dt: Optional[datetime]) -> str:
|
|
return dt.strftime("%Y-%m-%d %H:%M:%S") if dt else ""
|
|
|
|
|
|
def _normalize_bound(value: Optional[str], *, end_of_day: bool = False) -> Optional[datetime]:
|
|
text = (value or "").strip()
|
|
if not text:
|
|
return None
|
|
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
|
|
try:
|
|
dt = datetime.strptime(text[:19] if " " in text else text[:10], fmt)
|
|
if end_of_day and fmt == "%Y-%m-%d":
|
|
return dt.replace(hour=23, minute=59, second=59)
|
|
return dt
|
|
except ValueError:
|
|
continue
|
|
return None
|
|
|
|
|
|
def _user_name_map(db: Session, user_ids: List[str]) -> Dict[str, str]:
|
|
ids = list({(x or "").strip() for x in user_ids if (x or "").strip()})
|
|
if not ids:
|
|
return {}
|
|
rows = db.query(SysUser.id, SysUser.nick_name).filter(SysUser.id.in_(ids)).all()
|
|
return {r.id: (r.nick_name or r.id) for r in rows}
|
|
|
|
|
|
def _mother_matched_reception_ids(
|
|
db: Session, *, tenant_no: str, keyword: str
|
|
) -> List[str]:
|
|
"""按母亲姓名模糊匹配,返回接收记录 ID(细胞存储 + 科研捐赠)。"""
|
|
kw = f"%{keyword}%"
|
|
cell_ids = [
|
|
r.id
|
|
for r in (
|
|
db.query(BizSampleReception.id)
|
|
.join(
|
|
BizProtocolSample,
|
|
BizProtocolSample.id == BizSampleReception.protocol_sample_id,
|
|
)
|
|
.join(
|
|
BizProtocolPartyCustomer,
|
|
BizProtocolPartyCustomer.collection_protocol_id
|
|
== BizProtocolSample.collection_protocol_id,
|
|
)
|
|
.filter(
|
|
BizSampleReception.tenant_no == tenant_no,
|
|
BizSampleReception.del_flag == 0,
|
|
BizSampleReception.reception_source == "cell_storage",
|
|
BizProtocolSample.tenant_no == tenant_no,
|
|
BizProtocolSample.del_flag == 0,
|
|
BizProtocolPartyCustomer.tenant_no == tenant_no,
|
|
BizProtocolPartyCustomer.del_flag == 0,
|
|
BizProtocolPartyCustomer.mother_name.like(kw),
|
|
)
|
|
.all()
|
|
)
|
|
]
|
|
donation_ids = [
|
|
r.id
|
|
for r in (
|
|
db.query(BizSampleReception.id)
|
|
.join(
|
|
BizResearchDonationSample,
|
|
BizResearchDonationSample.id == BizSampleReception.donation_sample_id,
|
|
)
|
|
.join(
|
|
BizResearchDonationParty,
|
|
BizResearchDonationParty.research_donation_id
|
|
== BizResearchDonationSample.research_donation_id,
|
|
)
|
|
.filter(
|
|
BizSampleReception.tenant_no == tenant_no,
|
|
BizSampleReception.del_flag == 0,
|
|
BizSampleReception.reception_source == "research_donation",
|
|
BizResearchDonationSample.tenant_no == tenant_no,
|
|
BizResearchDonationSample.del_flag == 0,
|
|
BizResearchDonationParty.tenant_no == tenant_no,
|
|
BizResearchDonationParty.del_flag == 0,
|
|
BizResearchDonationParty.mother_name.like(kw),
|
|
)
|
|
.all()
|
|
)
|
|
]
|
|
return list({*cell_ids, *donation_ids})
|
|
|
|
|
|
def _assemble_rows(
|
|
db: Session, *, tenant_no: str, receptions: List[BizSampleReception]
|
|
) -> List[Dict[str, Any]]:
|
|
if not receptions:
|
|
return []
|
|
|
|
cell_recs = [r for r in receptions if (r.reception_source or "") == "cell_storage"]
|
|
donation_recs = [
|
|
r for r in receptions if (r.reception_source or "") == "research_donation"
|
|
]
|
|
|
|
protocol_ids: List[str] = []
|
|
sample_protocol_map: Dict[str, str] = {}
|
|
cell_sample_ids = [r.protocol_sample_id for r in cell_recs if r.protocol_sample_id]
|
|
if cell_sample_ids:
|
|
samples = (
|
|
db.query(BizProtocolSample)
|
|
.filter(
|
|
BizProtocolSample.tenant_no == tenant_no,
|
|
BizProtocolSample.del_flag == 0,
|
|
BizProtocolSample.id.in_(cell_sample_ids),
|
|
)
|
|
.all()
|
|
)
|
|
for s in samples:
|
|
if s.collection_protocol_id:
|
|
sample_protocol_map[s.id] = s.collection_protocol_id
|
|
protocol_ids.append(s.collection_protocol_id)
|
|
for r in cell_recs:
|
|
if r.collection_protocol_id:
|
|
protocol_ids.append(r.collection_protocol_id)
|
|
protocol_ids = list({p for p in protocol_ids if p})
|
|
|
|
party_map: Dict[str, BizProtocolPartyCustomer] = {}
|
|
coll_map: Dict[str, BizProtocolCollectionInfo] = {}
|
|
if protocol_ids:
|
|
parties = (
|
|
db.query(BizProtocolPartyCustomer)
|
|
.filter(
|
|
BizProtocolPartyCustomer.tenant_no == tenant_no,
|
|
BizProtocolPartyCustomer.del_flag == 0,
|
|
BizProtocolPartyCustomer.collection_protocol_id.in_(protocol_ids),
|
|
)
|
|
.all()
|
|
)
|
|
party_map = {p.collection_protocol_id: p for p in parties}
|
|
colls = (
|
|
db.query(BizProtocolCollectionInfo)
|
|
.filter(
|
|
BizProtocolCollectionInfo.tenant_no == tenant_no,
|
|
BizProtocolCollectionInfo.del_flag == 0,
|
|
BizProtocolCollectionInfo.collection_protocol_id.in_(protocol_ids),
|
|
)
|
|
.all()
|
|
)
|
|
coll_map = {c.collection_protocol_id: c for c in colls}
|
|
|
|
donation_ids: List[str] = []
|
|
sample_donation_map: Dict[str, str] = {}
|
|
donation_sample_ids = [r.donation_sample_id for r in donation_recs if r.donation_sample_id]
|
|
if donation_sample_ids:
|
|
samples = (
|
|
db.query(BizResearchDonationSample)
|
|
.filter(
|
|
BizResearchDonationSample.tenant_no == tenant_no,
|
|
BizResearchDonationSample.del_flag == 0,
|
|
BizResearchDonationSample.id.in_(donation_sample_ids),
|
|
)
|
|
.all()
|
|
)
|
|
for s in samples:
|
|
if s.research_donation_id:
|
|
sample_donation_map[s.id] = s.research_donation_id
|
|
donation_ids.append(s.research_donation_id)
|
|
for r in donation_recs:
|
|
if r.research_donation_id:
|
|
donation_ids.append(r.research_donation_id)
|
|
donation_ids = list({d for d in donation_ids if d})
|
|
|
|
donation_party_map: Dict[str, BizResearchDonationParty] = {}
|
|
donation_coll_map: Dict[str, BizResearchDonationCollection] = {}
|
|
if donation_ids:
|
|
parties = (
|
|
db.query(BizResearchDonationParty)
|
|
.filter(
|
|
BizResearchDonationParty.tenant_no == tenant_no,
|
|
BizResearchDonationParty.del_flag == 0,
|
|
BizResearchDonationParty.research_donation_id.in_(donation_ids),
|
|
)
|
|
.all()
|
|
)
|
|
donation_party_map = {p.research_donation_id: p for p in parties}
|
|
colls = (
|
|
db.query(BizResearchDonationCollection)
|
|
.filter(
|
|
BizResearchDonationCollection.tenant_no == tenant_no,
|
|
BizResearchDonationCollection.del_flag == 0,
|
|
BizResearchDonationCollection.research_donation_id.in_(donation_ids),
|
|
)
|
|
.all()
|
|
)
|
|
donation_coll_map = {c.research_donation_id: c for c in colls}
|
|
|
|
sales_ids: List[str] = []
|
|
for c in coll_map.values():
|
|
if c.sales_user_id:
|
|
sales_ids.append(c.sales_user_id)
|
|
for c in donation_coll_map.values():
|
|
if c.sales_user_id:
|
|
sales_ids.append(c.sales_user_id)
|
|
name_map = _user_name_map(db, sales_ids)
|
|
|
|
reception_ids = [r.id for r in receptions]
|
|
prod_rows = (
|
|
db.query(BizSampleProductionReception)
|
|
.filter(
|
|
BizSampleProductionReception.tenant_no == tenant_no,
|
|
BizSampleProductionReception.del_flag == 0,
|
|
BizSampleProductionReception.reception_id.in_(reception_ids),
|
|
)
|
|
.all()
|
|
if reception_ids
|
|
else []
|
|
)
|
|
prod_map = {p.reception_id: p for p in prod_rows}
|
|
|
|
out: List[Dict[str, Any]] = []
|
|
for rec in receptions:
|
|
mother_name = ""
|
|
sales_user_name = ""
|
|
source = rec.reception_source or "cell_storage"
|
|
if source == "cell_storage":
|
|
pid = (
|
|
sample_protocol_map.get(rec.protocol_sample_id or "")
|
|
or rec.collection_protocol_id
|
|
or ""
|
|
)
|
|
party = party_map.get(pid)
|
|
coll = coll_map.get(pid)
|
|
mother_name = (party.mother_name if party else "") or ""
|
|
sid = (coll.sales_user_id if coll else "") or ""
|
|
sales_user_name = name_map.get(sid, "") if sid else ""
|
|
else:
|
|
did = (
|
|
sample_donation_map.get(rec.donation_sample_id or "")
|
|
or rec.research_donation_id
|
|
or ""
|
|
)
|
|
party = donation_party_map.get(did)
|
|
coll = donation_coll_map.get(did)
|
|
mother_name = (party.mother_name if party else "") or ""
|
|
sid = (coll.sales_user_id if coll else "") or ""
|
|
sales_user_name = name_map.get(sid, "") if sid else ""
|
|
|
|
prod = prod_map.get(rec.id)
|
|
vol: Optional[Decimal] = prod.original_blood_volume_ml if prod else None
|
|
weight: Optional[Decimal] = prod.original_blood_weight_g if prod else None
|
|
cord: Optional[Decimal] = getattr(prod, "cord_length_cm", None) if prod else None
|
|
|
|
out.append(
|
|
{
|
|
"id": rec.id,
|
|
"labStorageCode": rec.lab_storage_code or "",
|
|
"receptionTime": _fmt_dt(rec.reception_time),
|
|
"motherName": mother_name,
|
|
"salesUserName": sales_user_name,
|
|
"remark": rec.remark or "",
|
|
"originalBloodVolumeMl": prod_svc._dec(vol),
|
|
"originalBloodWeightG": prod_svc._dec(weight),
|
|
"cordLengthCm": prod_svc._dec(cord),
|
|
"receptionSource": source,
|
|
"acceptConclusion": rec.accept_conclusion or "",
|
|
}
|
|
)
|
|
return out
|
|
|
|
|
|
def list_overview(
|
|
db: Session,
|
|
*,
|
|
tenant_no: str,
|
|
page: int = 1,
|
|
page_size: int = 10,
|
|
reception_time_start: Optional[str] = None,
|
|
reception_time_end: Optional[str] = None,
|
|
keyword: Optional[str] = None,
|
|
user_info=None,
|
|
) -> Tuple[List[Dict[str, Any]], int]:
|
|
q = db.query(BizSampleReception).filter(
|
|
BizSampleReception.tenant_no == tenant_no,
|
|
BizSampleReception.del_flag == 0,
|
|
BizSampleReception.reception_source.in_(["cell_storage", "research_donation"]),
|
|
)
|
|
start = _normalize_bound(reception_time_start)
|
|
end = _normalize_bound(reception_time_end, end_of_day=True)
|
|
if start:
|
|
q = q.filter(BizSampleReception.reception_time >= start)
|
|
if end:
|
|
q = q.filter(BizSampleReception.reception_time <= end)
|
|
if user_info:
|
|
q = apply_data_scope(q, BizSampleReception, user_info, db, tenant_no)
|
|
|
|
kw = (keyword or "").strip()
|
|
if kw:
|
|
mother_ids = _mother_matched_reception_ids(db, tenant_no=tenant_no, keyword=kw)
|
|
code_like = BizSampleReception.lab_storage_code.like(f"%{kw}%")
|
|
if mother_ids:
|
|
q = q.filter(or_(code_like, BizSampleReception.id.in_(mother_ids)))
|
|
else:
|
|
q = q.filter(code_like)
|
|
|
|
total = q.count()
|
|
rows = (
|
|
q.order_by(
|
|
BizSampleReception.reception_time.desc(),
|
|
BizSampleReception.create_time.desc(),
|
|
)
|
|
.offset(max(page - 1, 0) * page_size)
|
|
.limit(page_size)
|
|
.all()
|
|
)
|
|
return _assemble_rows(db, tenant_no=tenant_no, receptions=rows), total
|