Merge pull request 'feat(qc): 新增月度样本信息总览列表与导出 (#192)' (#193) from feat/monthly-sample-overview into V2.0
Merge pull request 'feat(qc): 新增月度样本信息总览列表与导出 (#192)' (#193) from feat/monthly-sample-overview into V2.0
This commit was merged in pull request #193.
This commit is contained in:
commit
be5b66e224
9 files changed
+983
-1
No files matched your search
@@ -47,6 +47,7 @@ from app.api.sample_cert_insurance import router as sample_cert_insurance_router
|
||||
from app.api.sample_code_correction import router as sample_code_correction_router
|
||||
from app.api.lab_sample_process import router as lab_sample_process_router
|
||||
from app.api.lab_sample_processing import router as lab_sample_processing_router
|
||||
from app.api.monthly_sample_overview import router as monthly_sample_overview_router
|
||||
from app.api.business_sample import router as business_sample_router
|
||||
|
||||
from app.api.project_management import router as project_management_router
|
||||
@@ -55,6 +56,7 @@ __all__ = [
|
||||
"business_sample_router",
|
||||
"project_management_router",
|
||||
"lab_sample_process_router",
|
||||
"monthly_sample_overview_router",
|
||||
"public_router",
|
||||
"menu_router",
|
||||
"admin_router",
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""月度样本信息总览 API"""
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.menu_guard import require_menu_code
|
||||
from app.core.response import error_response, success_response
|
||||
from app.crud import monthly_sample_overview as svc
|
||||
from app.models.models import SysUser
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["质检管理"])
|
||||
|
||||
LIST_MENU = "biz:monthlySampleOverview:list"
|
||||
|
||||
|
||||
def _tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
@router.get("/monthly-sample-overview/list")
|
||||
def list_monthly_sample_overview(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=200),
|
||||
receptionTimeStart: Optional[str] = Query(None, description="接收时间起,含首日"),
|
||||
receptionTimeEnd: Optional[str] = Query(None, description="接收时间止,含末日整天"),
|
||||
keyword: Optional[str] = Query(None, description="入库编码/母亲姓名"),
|
||||
db: Session = Depends(get_db),
|
||||
user=Depends(require_menu_code(LIST_MENU)),
|
||||
):
|
||||
try:
|
||||
tenant_no = _tenant_no(db, user)
|
||||
items, total = svc.list_overview(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
reception_time_start=receptionTimeStart,
|
||||
reception_time_end=receptionTimeEnd,
|
||||
keyword=keyword,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response(
|
||||
data={
|
||||
"list": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"pageSize": pageSize,
|
||||
}
|
||||
)
|
||||
except PermissionError as e:
|
||||
return error_response(str(e), code=403)
|
||||
except ValueError as e:
|
||||
return error_response(str(e), code=400)
|
||||
@@ -0,0 +1,336 @@
|
||||
"""月度样本信息总览:接收记录列表组装。"""
|
||||
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
|
||||
+2
-1
@@ -13,7 +13,7 @@ from app.core.database import SessionLocal
|
||||
from app.core.api_request_log_middleware import ApiRequestLogMiddleware
|
||||
from app.core.api_crypto_middleware import ApiCryptoMiddleware
|
||||
from app.models import models # noqa: F401
|
||||
from app.api import public_router, menu_router, admin_router, workflow_router, basic_info_router, collection_protocol_router, protocol_sample_payment_router, protocol_refund_record_router, presign_order_router, sample_freight_router, leave_router, operations_router, ethnic_router, sample_reception_router, sample_production_reception_router, qc_router, research_donation_router, production_router, pilot_service_router, insurance_company_router, material_router, storage_release_review_router, sample_sms_notification_router, storage_entry_sms_notification_router, qc_sms_notification_router, protocol_sample_collection_router, research_donation_sample_collection_router, pilot_application_router, pilot_checkup_router, pilot_delivery_router, pilot_infusion_confirm_router, pilot_infusion_schedule_mgmt_router, outbound_release_review_router, clinical_payment_router, env_detect_router, cleanroom_garment_router, market_router, pre_transit_sample_router, oa_approval_router, mini_auth_router, mini_menu_router, market_mobile_router, sample_storage_cert_qc_router, customer_service_dict_router, sample_cert_insurance_router, sample_code_correction_router, lab_sample_process_router, lab_sample_processing_router, project_management_router, business_sample_router
|
||||
from app.api import public_router, menu_router, admin_router, workflow_router, basic_info_router, collection_protocol_router, protocol_sample_payment_router, protocol_refund_record_router, presign_order_router, sample_freight_router, leave_router, operations_router, ethnic_router, sample_reception_router, sample_production_reception_router, qc_router, research_donation_router, production_router, pilot_service_router, insurance_company_router, material_router, storage_release_review_router, sample_sms_notification_router, storage_entry_sms_notification_router, qc_sms_notification_router, protocol_sample_collection_router, research_donation_sample_collection_router, pilot_application_router, pilot_checkup_router, pilot_delivery_router, pilot_infusion_confirm_router, pilot_infusion_schedule_mgmt_router, outbound_release_review_router, clinical_payment_router, env_detect_router, cleanroom_garment_router, market_router, pre_transit_sample_router, oa_approval_router, mini_auth_router, mini_menu_router, market_mobile_router, sample_storage_cert_qc_router, customer_service_dict_router, sample_cert_insurance_router, sample_code_correction_router, lab_sample_process_router, lab_sample_processing_router, monthly_sample_overview_router, project_management_router, business_sample_router
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -160,6 +160,7 @@ app.include_router(sample_cert_insurance_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(sample_code_correction_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(lab_sample_process_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(lab_sample_processing_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(monthly_sample_overview_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(project_management_router, prefix=settings.API_V1_PREFIX)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
"""月度样本信息总览:时间边界与行组装。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from app.crud.monthly_sample_overview import _assemble_rows, _normalize_bound
|
||||
|
||||
|
||||
class NormalizeBoundTests(unittest.TestCase):
|
||||
def test_start_of_day_and_end_of_day(self):
|
||||
self.assertEqual(
|
||||
_normalize_bound("2026-12-01"),
|
||||
datetime(2026, 12, 1, 0, 0, 0),
|
||||
)
|
||||
self.assertEqual(
|
||||
_normalize_bound("2026-12-31", end_of_day=True),
|
||||
datetime(2026, 12, 31, 23, 59, 59),
|
||||
)
|
||||
self.assertEqual(
|
||||
_normalize_bound("2026-12-15 08:30:01"),
|
||||
datetime(2026, 12, 15, 8, 30, 1),
|
||||
)
|
||||
self.assertIsNone(_normalize_bound(""))
|
||||
self.assertIsNone(_normalize_bound(None))
|
||||
|
||||
|
||||
class AssembleRowTests(unittest.TestCase):
|
||||
def test_empty_production_fields_when_missing(self):
|
||||
rec = SimpleNamespace(
|
||||
id="r1",
|
||||
lab_storage_code="B0000108",
|
||||
reception_time=datetime(2026, 12, 3, 10, 0, 0),
|
||||
remark="溶血观察",
|
||||
reception_source="cell_storage",
|
||||
accept_conclusion="js",
|
||||
protocol_sample_id="ps1",
|
||||
collection_protocol_id="cp1",
|
||||
donation_sample_id=None,
|
||||
research_donation_id=None,
|
||||
)
|
||||
party = SimpleNamespace(mother_name="张母", collection_protocol_id="cp1")
|
||||
coll = SimpleNamespace(sales_user_id="u1", collection_protocol_id="cp1")
|
||||
sample = SimpleNamespace(id="ps1", collection_protocol_id="cp1")
|
||||
|
||||
db = MagicMock()
|
||||
|
||||
def query_side_effect(*args):
|
||||
q = MagicMock()
|
||||
q.filter.return_value = q
|
||||
first = args[0] if args else None
|
||||
name = getattr(first, "__name__", None) or getattr(
|
||||
getattr(first, "class_", None), "__name__", None
|
||||
)
|
||||
if name == "BizProtocolSample":
|
||||
q.all.return_value = [sample]
|
||||
elif name == "BizProtocolPartyCustomer":
|
||||
q.all.return_value = [party]
|
||||
elif name == "BizProtocolCollectionInfo":
|
||||
q.all.return_value = [coll]
|
||||
elif name == "BizSampleProductionReception":
|
||||
q.all.return_value = []
|
||||
elif name == "SysUser" or (
|
||||
len(args) >= 2 and "SysUser" in str(args[0])
|
||||
):
|
||||
q.all.return_value = [SimpleNamespace(id="u1", nick_name="销售甲")]
|
||||
else:
|
||||
# SysUser.id / SysUser.nick_name columns
|
||||
entity = getattr(first, "entity", None) or getattr(first, "table", None)
|
||||
if entity is not None or "nick_name" in str(args):
|
||||
q.all.return_value = [SimpleNamespace(id="u1", nick_name="销售甲")]
|
||||
else:
|
||||
q.all.return_value = []
|
||||
return q
|
||||
|
||||
db.query.side_effect = query_side_effect
|
||||
|
||||
with patch(
|
||||
"app.crud.monthly_sample_overview.prod_svc._dec",
|
||||
side_effect=lambda v: "" if v is None else str(v),
|
||||
):
|
||||
rows = _assemble_rows(db, tenant_no="zkxw", receptions=[rec])
|
||||
|
||||
self.assertEqual(len(rows), 1)
|
||||
row = rows[0]
|
||||
self.assertEqual(row["labStorageCode"], "B0000108")
|
||||
self.assertEqual(row["motherName"], "张母")
|
||||
self.assertEqual(row["salesUserName"], "销售甲")
|
||||
self.assertEqual(row["remark"], "溶血观察")
|
||||
self.assertEqual(row["originalBloodVolumeMl"], "")
|
||||
self.assertEqual(row["originalBloodWeightG"], "")
|
||||
self.assertEqual(row["cordLengthCm"], "")
|
||||
self.assertEqual(row["receptionTime"], "2026-12-03 10:00:00")
|
||||
|
||||
def test_production_fields_filled_when_present(self):
|
||||
rec = SimpleNamespace(
|
||||
id="r2",
|
||||
lab_storage_code="B0000200",
|
||||
reception_time=datetime(2026, 12, 2, 9, 0, 0),
|
||||
remark="",
|
||||
reception_source="research_donation",
|
||||
accept_conclusion="bj",
|
||||
protocol_sample_id="",
|
||||
collection_protocol_id="",
|
||||
donation_sample_id="ds1",
|
||||
research_donation_id="rd1",
|
||||
)
|
||||
party = SimpleNamespace(mother_name="李母", research_donation_id="rd1")
|
||||
coll = SimpleNamespace(sales_user_id="u2", research_donation_id="rd1")
|
||||
sample = SimpleNamespace(id="ds1", research_donation_id="rd1")
|
||||
prod = SimpleNamespace(
|
||||
reception_id="r2",
|
||||
original_blood_volume_ml=Decimal("120.5"),
|
||||
original_blood_weight_g=Decimal("130"),
|
||||
cord_length_cm=Decimal("45"),
|
||||
)
|
||||
|
||||
db = MagicMock()
|
||||
|
||||
def query_side_effect(*args):
|
||||
q = MagicMock()
|
||||
q.filter.return_value = q
|
||||
first = args[0] if args else None
|
||||
name = getattr(first, "__name__", None) or getattr(
|
||||
getattr(first, "class_", None), "__name__", None
|
||||
)
|
||||
if name == "BizResearchDonationSample":
|
||||
q.all.return_value = [sample]
|
||||
elif name == "BizResearchDonationParty":
|
||||
q.all.return_value = [party]
|
||||
elif name == "BizResearchDonationCollection":
|
||||
q.all.return_value = [coll]
|
||||
elif name == "BizSampleProductionReception":
|
||||
q.all.return_value = [prod]
|
||||
elif name == "SysUser" or "nick_name" in str(args):
|
||||
q.all.return_value = [SimpleNamespace(id="u2", nick_name="销售乙")]
|
||||
else:
|
||||
q.all.return_value = []
|
||||
return q
|
||||
|
||||
db.query.side_effect = query_side_effect
|
||||
|
||||
with patch(
|
||||
"app.crud.monthly_sample_overview.prod_svc._dec",
|
||||
side_effect=lambda v: "" if v is None else float(v),
|
||||
):
|
||||
rows = _assemble_rows(db, tenant_no="zkxw", receptions=[rec])
|
||||
|
||||
self.assertEqual(len(rows), 1)
|
||||
row = rows[0]
|
||||
self.assertEqual(row["motherName"], "李母")
|
||||
self.assertEqual(row["salesUserName"], "销售乙")
|
||||
self.assertEqual(row["originalBloodVolumeMl"], 120.5)
|
||||
self.assertEqual(row["originalBloodWeightG"], 130.0)
|
||||
self.assertEqual(row["cordLengthCm"], 45.0)
|
||||
self.assertEqual(row["acceptConclusion"], "bj")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,125 @@
|
||||
-- Issue #192:质检管理「月度样本信息总览」菜单(列表 + 导出)
|
||||
-- MySQL 5.7,可重复执行。挂在「实验室样本处理数据」同级下方,授权对齐 labSampleProcess 角色。
|
||||
|
||||
-- 列表菜单:与样本接收同父节点;order_num 取「实验室样本处理数据」同值,名称排序紧随其后
|
||||
INSERT INTO sys_menu (
|
||||
id, menu_name, parent_id, menu_type, path, component, perms,
|
||||
is_frame, visible, status, tenant_no, order_num, remark,
|
||||
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
INSERT(INSERT(MD5(CONCAT('monthly-sample-overview:', parent.tenant_no, ':', parent.id)),
|
||||
13, 1, '3'), 17, 1, '8'),
|
||||
'月度样本信息总览', parent.parent_id, 'C',
|
||||
'monthly-sample-overview',
|
||||
'quality-inspection/monthly-sample-overview/index',
|
||||
'biz:monthlySampleOverview:list',
|
||||
1, '1', '1', parent.tenant_no,
|
||||
COALESCE((
|
||||
SELECT lab.order_num
|
||||
FROM sys_menu AS lab
|
||||
WHERE lab.del_flag = 0
|
||||
AND lab.tenant_no = parent.tenant_no
|
||||
AND lab.parent_id = parent.parent_id
|
||||
AND lab.perms = 'biz:labSampleProcess:list'
|
||||
LIMIT 1
|
||||
), 4),
|
||||
'质检管理-月度样本信息总览',
|
||||
'migration', '', NOW(), 'migration', NOW(), 0
|
||||
FROM sys_menu AS parent
|
||||
WHERE parent.del_flag = 0 AND parent.status = '1'
|
||||
AND parent.perms = 'biz:sampleReception:list'
|
||||
AND parent.parent_id IS NOT NULL
|
||||
AND parent.parent_id != ''
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM sys_menu AS existing
|
||||
WHERE existing.tenant_no = parent.tenant_no
|
||||
AND existing.perms = 'biz:monthlySampleOverview:list'
|
||||
AND existing.del_flag = 0
|
||||
);
|
||||
|
||||
-- 幂等纠正:已存在菜单的排序与实验室样本处理数据对齐
|
||||
UPDATE sys_menu AS m
|
||||
JOIN sys_menu AS lab
|
||||
ON lab.tenant_no = m.tenant_no
|
||||
AND lab.parent_id = m.parent_id
|
||||
AND lab.perms = 'biz:labSampleProcess:list'
|
||||
AND lab.del_flag = 0
|
||||
SET m.order_num = lab.order_num,
|
||||
m.update_by = 'migration',
|
||||
m.update_time = NOW()
|
||||
WHERE m.perms = 'biz:monthlySampleOverview:list'
|
||||
AND m.del_flag = 0
|
||||
AND (m.order_num IS NULL OR m.order_num <> lab.order_num);
|
||||
|
||||
-- 导出按钮
|
||||
INSERT INTO sys_menu (
|
||||
id, menu_name, parent_id, menu_type, path, component, perms,
|
||||
is_frame, visible, status, tenant_no, order_num, remark,
|
||||
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
INSERT(INSERT(MD5(CONCAT('monthly-sample-overview-exp:', m.tenant_no, ':', m.id)),
|
||||
13, 1, '3'), 17, 1, '8'),
|
||||
'导出', m.id, 'F', '', NULL,
|
||||
'biz:monthlySampleOverview:export',
|
||||
1, '1', '1', m.tenant_no, 10,
|
||||
'月度样本信息总览-导出',
|
||||
'migration', '', NOW(), 'migration', NOW(), 0
|
||||
FROM sys_menu AS m
|
||||
WHERE m.del_flag = 0 AND m.status = '1'
|
||||
AND m.perms = 'biz:monthlySampleOverview:list'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM sys_menu AS existing
|
||||
WHERE existing.parent_id = m.id
|
||||
AND existing.tenant_no = m.tenant_no
|
||||
AND existing.perms = 'biz:monthlySampleOverview:export'
|
||||
AND existing.del_flag = 0
|
||||
);
|
||||
|
||||
-- 授权给拥有实验室样本处理列表权限的角色
|
||||
INSERT INTO sys_role_menu (
|
||||
id, role_id, menu_id, tenant_no, order_num, remark,
|
||||
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
INSERT(INSERT(MD5(CONCAT('monthly-sample-overview-rm:', r.tenant_no, ':', r.id, ':', m.id)),
|
||||
13, 1, '3'), 17, 1, '8'),
|
||||
r.id,
|
||||
m.id,
|
||||
r.tenant_no,
|
||||
NULL,
|
||||
'migration: grant monthly sample overview from lab sample process roles',
|
||||
'migration',
|
||||
'',
|
||||
NOW(),
|
||||
'migration',
|
||||
NOW(),
|
||||
0
|
||||
FROM sys_role AS r
|
||||
JOIN sys_role_menu AS src
|
||||
ON src.role_id = r.id AND src.tenant_no = r.tenant_no AND src.del_flag = 0
|
||||
JOIN sys_menu AS srcm
|
||||
ON srcm.id = src.menu_id AND srcm.tenant_no = src.tenant_no AND srcm.del_flag = 0
|
||||
AND srcm.perms = 'biz:labSampleProcess:list'
|
||||
JOIN sys_menu AS m
|
||||
ON m.tenant_no = r.tenant_no
|
||||
AND m.perms IN (
|
||||
'biz:monthlySampleOverview:list',
|
||||
'biz:monthlySampleOverview:export'
|
||||
)
|
||||
AND m.del_flag = 0
|
||||
AND m.status = '1'
|
||||
WHERE r.del_flag = 0
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM sys_role_menu AS existing
|
||||
WHERE existing.role_id = r.id
|
||||
AND existing.menu_id = m.id
|
||||
AND existing.tenant_no = r.tenant_no
|
||||
AND existing.del_flag = 0
|
||||
);
|
||||
|
||||
SELECT tenant_no, parent_id, id, menu_name, path, component, perms, order_num
|
||||
FROM sys_menu
|
||||
WHERE perms LIKE 'biz:monthlySampleOverview:%' AND del_flag = 0
|
||||
ORDER BY tenant_no, order_num, perms;
|
||||
@@ -0,0 +1,35 @@
|
||||
import request from '@/utils/http'
|
||||
|
||||
export interface MonthlySampleOverviewListParams {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
receptionTimeStart?: string
|
||||
receptionTimeEnd?: string
|
||||
keyword?: string
|
||||
}
|
||||
|
||||
export interface MonthlySampleOverviewRow {
|
||||
id: string
|
||||
labStorageCode: string
|
||||
receptionTime: string
|
||||
motherName: string
|
||||
salesUserName: string
|
||||
remark: string
|
||||
originalBloodVolumeMl: number | string | null
|
||||
originalBloodWeightG: number | string | null
|
||||
cordLengthCm: number | string | null
|
||||
receptionSource?: string
|
||||
acceptConclusion?: string
|
||||
}
|
||||
|
||||
export function fetchMonthlySampleOverviewList(params: MonthlySampleOverviewListParams) {
|
||||
return request.get<{
|
||||
list: MonthlySampleOverviewRow[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}>({
|
||||
url: '/web/admin/monthly-sample-overview/list',
|
||||
params
|
||||
})
|
||||
}
|
||||
@@ -1409,6 +1409,17 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
|
||||
keepAlive: true,
|
||||
menuCode: 'biz:labSampleProcess:list'
|
||||
}
|
||||
},
|
||||
{
|
||||
id: '70000000000000000000000000000016',
|
||||
name: 'QualityInspectionMonthlySampleOverview',
|
||||
path: 'monthly-sample-overview',
|
||||
component: '/quality-inspection/monthly-sample-overview/index',
|
||||
meta: {
|
||||
title: '月度样本信息总览',
|
||||
keepAlive: true,
|
||||
menuCode: 'biz:monthlySampleOverview:list'
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
<!-- 月度样本信息总览:按接收时间筛选列表 + Excel 导出 -->
|
||||
<template>
|
||||
<div class="page-container">
|
||||
<section class="panel">
|
||||
<div class="panel-top">
|
||||
<h2 class="title-bar-heading">月度样本信息总览</h2>
|
||||
</div>
|
||||
|
||||
<div class="filter-block">
|
||||
<el-form :model="searchForm" class="filter-form" @submit.prevent>
|
||||
<div class="filter-grid">
|
||||
<el-form-item label="接收时间">
|
||||
<el-date-picker
|
||||
v-model="searchForm.receptionTimeRange"
|
||||
type="daterange"
|
||||
value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期"
|
||||
end-placeholder="结束日期"
|
||||
clearable
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="关键词">
|
||||
<el-input
|
||||
v-model="searchForm.keyword"
|
||||
placeholder="入库编码 / 母亲姓名"
|
||||
clearable
|
||||
/>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="filter-actions-row">
|
||||
<div class="filter-actions-end">
|
||||
<el-button class="btn-ghost" @click="handleReset"
|
||||
><el-icon><RefreshLeft /></el-icon>重置</el-button
|
||||
>
|
||||
<el-button class="btn-main" type="primary" @click="handleSearch"
|
||||
><el-icon><Search /></el-icon>搜索</el-button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
|
||||
<div class="list-toolbar">
|
||||
<div class="list-toolbar-row">
|
||||
<div class="list-toolbar-selected">共 {{ pagination.total }} 条</div>
|
||||
<el-button
|
||||
v-if="canExport"
|
||||
class="btn-main"
|
||||
type="primary"
|
||||
:loading="exporting"
|
||||
@click="handleExport"
|
||||
>
|
||||
<el-icon><Download /></el-icon>
|
||||
导出
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="list-body list-wrap">
|
||||
<el-table class="list-table" :data="tableData" v-loading="loading" stripe row-key="id">
|
||||
<el-table-column
|
||||
type="index"
|
||||
label="序号"
|
||||
min-width="68"
|
||||
align="center"
|
||||
header-align="center"
|
||||
:index="(index) => (pagination.page - 1) * pagination.pageSize + index + 1"
|
||||
/>
|
||||
<el-table-column
|
||||
v-for="col in columns"
|
||||
:key="col.prop"
|
||||
:prop="col.prop"
|
||||
:label="col.label"
|
||||
:min-width="col.minWidth"
|
||||
align="center"
|
||||
header-align="center"
|
||||
show-overflow-tooltip
|
||||
>
|
||||
<template #default="{ row }">{{ displayCell(row[col.prop]) }}</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="pagination list-pager-bar">
|
||||
<el-pagination
|
||||
v-model:current-page="pagination.page"
|
||||
v-model:page-size="pagination.pageSize"
|
||||
:total="pagination.total"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
layout="total, sizes, prev, pager, next, jumper"
|
||||
background
|
||||
@size-change="handleSizeChange"
|
||||
@current-change="handlePageChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Download, RefreshLeft, Search } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import * as XLSX from 'xlsx'
|
||||
import {
|
||||
fetchMonthlySampleOverviewList,
|
||||
type MonthlySampleOverviewRow
|
||||
} from '@/api/monthly-sample-overview'
|
||||
import { useMenuPerm } from '@/hooks/core/useMenuPerm'
|
||||
|
||||
defineOptions({ name: 'QualityInspectionMonthlySampleOverview' })
|
||||
|
||||
const { hasMenuPerm } = useMenuPerm()
|
||||
const canExport = computed(() => hasMenuPerm('biz:monthlySampleOverview:export'))
|
||||
|
||||
const columns = [
|
||||
{ prop: 'labStorageCode', label: '样本编号', minWidth: 140 },
|
||||
{ prop: 'receptionTime', label: '到库时间', minWidth: 170 },
|
||||
{ prop: 'motherName', label: '产妇姓名', minWidth: 110 },
|
||||
{ prop: 'salesUserName', label: '销售专员', minWidth: 110 },
|
||||
{ prop: 'remark', label: '接收备注', minWidth: 160 },
|
||||
{ prop: 'originalBloodVolumeMl', label: '原血体积/ml', minWidth: 120 },
|
||||
{ prop: 'originalBloodWeightG', label: '原血重量/g', minWidth: 120 },
|
||||
{ prop: 'cordLengthCm', label: '脐带长度/cm', minWidth: 120 }
|
||||
] as const
|
||||
|
||||
function currentMonthRange(): [string, string] {
|
||||
const now = new Date()
|
||||
const y = now.getFullYear()
|
||||
const m = now.getMonth()
|
||||
const start = new Date(y, m, 1)
|
||||
const end = new Date(y, m + 1, 0)
|
||||
const fmt = (d: Date) => {
|
||||
const mm = String(d.getMonth() + 1).padStart(2, '0')
|
||||
const dd = String(d.getDate()).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${mm}-${dd}`
|
||||
}
|
||||
return [fmt(start), fmt(end)]
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const exporting = ref(false)
|
||||
const tableData = ref<MonthlySampleOverviewRow[]>([])
|
||||
const searchForm = reactive({
|
||||
receptionTimeRange: currentMonthRange() as [string, string] | null,
|
||||
keyword: ''
|
||||
})
|
||||
const pagination = reactive({
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
total: 0
|
||||
})
|
||||
|
||||
function displayCell(value: unknown) {
|
||||
if (value === null || value === undefined || value === '') return '—'
|
||||
return String(value)
|
||||
}
|
||||
|
||||
function listParams(page: number, pageSize: number) {
|
||||
const range = searchForm.receptionTimeRange
|
||||
return {
|
||||
page,
|
||||
pageSize,
|
||||
receptionTimeStart: range?.[0],
|
||||
receptionTimeEnd: range?.[1],
|
||||
keyword: searchForm.keyword || undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function loadData() {
|
||||
loading.value = true
|
||||
try {
|
||||
const res = await fetchMonthlySampleOverviewList(
|
||||
listParams(pagination.page, pagination.pageSize)
|
||||
)
|
||||
tableData.value = (res?.list || []) as MonthlySampleOverviewRow[]
|
||||
pagination.total = Number(res?.total || 0)
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || '加载失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleSearch() {
|
||||
pagination.page = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
searchForm.receptionTimeRange = currentMonthRange()
|
||||
searchForm.keyword = ''
|
||||
handleSearch()
|
||||
}
|
||||
|
||||
function handleSizeChange() {
|
||||
pagination.page = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
function handlePageChange() {
|
||||
loadData()
|
||||
}
|
||||
|
||||
async function handleExport() {
|
||||
if (!canExport.value) {
|
||||
ElMessage.warning('无导出权限')
|
||||
return
|
||||
}
|
||||
exporting.value = true
|
||||
try {
|
||||
const pageSize = 200
|
||||
let page = 1
|
||||
let total = Number.POSITIVE_INFINITY
|
||||
const rows: MonthlySampleOverviewRow[] = []
|
||||
while (rows.length < total) {
|
||||
const res = await fetchMonthlySampleOverviewList(listParams(page, pageSize))
|
||||
total = Number(res?.total ?? 0)
|
||||
const batch = (res?.list || []) as MonthlySampleOverviewRow[]
|
||||
rows.push(...batch)
|
||||
if (!batch.length || batch.length < pageSize) break
|
||||
page += 1
|
||||
if (page > 500) break
|
||||
}
|
||||
const headers = ['序号', ...columns.map((c) => c.label)]
|
||||
const sheetRows = rows.map((row, idx) => {
|
||||
const line: Record<string, string | number> = { 序号: idx + 1 }
|
||||
columns.forEach((c) => {
|
||||
const v = row[c.prop as keyof MonthlySampleOverviewRow]
|
||||
line[c.label] = v === null || v === undefined || v === '' ? '' : String(v)
|
||||
})
|
||||
return line
|
||||
})
|
||||
const sheet = XLSX.utils.json_to_sheet(sheetRows, { header: headers })
|
||||
const workbook = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(workbook, sheet, '月度样本信息总览')
|
||||
const stamp = new Date().toISOString().slice(0, 19).replace(/[:T]/g, '')
|
||||
XLSX.writeFile(workbook, `月度样本信息总览_${stamp}.xlsx`)
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || '导出失败')
|
||||
} finally {
|
||||
exporting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadData()
|
||||
})
|
||||
</script>
|
||||
Reference in new issue
Block a user