feat(sample): 展示样本状态并支持样本废弃与作废原因
生产/质检入库卡片展示样本状态并支持【样本废弃】;市场 Web 列表与移动市场部卡片补充样本状态及问号查看作废原因;样本表新增 void_desc,人工作废不联动接收但全部作废时自动作废协议(#131)。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
7751cc0f4a
commit
0b4c8dfda8
53 files changed
+1527
-82
No files matched your search
@@ -47,10 +47,12 @@ 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.business_sample import router as business_sample_router
|
||||
|
||||
from app.api.project_management import router as project_management_router
|
||||
|
||||
__all__ = [
|
||||
"business_sample_router",
|
||||
"project_management_router",
|
||||
"lab_sample_process_router",
|
||||
"public_router",
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""业务样本:人工作废等跨模块入口。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.menu_guard import require_admin_or_super_admin
|
||||
from app.core.response import error_response, success_response
|
||||
from app.models.models import SysUser
|
||||
from app.services.protocol_reception_discard_sync import SAMPLE_VOID_STATUS, void_sample_manually
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["业务样本"])
|
||||
|
||||
|
||||
class VoidSampleBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
reception_source: str = Field(..., alias="receptionSource")
|
||||
void_desc: str = Field(..., alias="voidDesc")
|
||||
sample_id: Optional[str] = Field(None, alias="sampleId")
|
||||
sample_code: Optional[str] = Field(None, alias="sampleCode")
|
||||
protocol_id: Optional[str] = Field(None, alias="protocolId")
|
||||
|
||||
|
||||
def _get_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
|
||||
|
||||
|
||||
def _get_current_user_id(user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
return str(user_id)
|
||||
|
||||
|
||||
@router.put("/business-samples/void")
|
||||
async def void_business_sample(
|
||||
body: VoidSampleBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
sample = void_sample_manually(
|
||||
db,
|
||||
source=body.reception_source,
|
||||
tenant_no=tenant_no,
|
||||
void_desc=body.void_desc,
|
||||
user_id=user_id,
|
||||
sample_id=body.sample_id,
|
||||
sample_code=body.sample_code,
|
||||
protocol_id=body.protocol_id,
|
||||
commit=True,
|
||||
)
|
||||
return success_response(
|
||||
{
|
||||
"id": sample.id,
|
||||
"sampleCode": getattr(sample, "sample_code", None) or "",
|
||||
"sampleStatus": SAMPLE_VOID_STATUS,
|
||||
"voidDate": getattr(sample, "void_date", None) or "",
|
||||
"voidDesc": getattr(sample, "void_desc", None) or "",
|
||||
}
|
||||
)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
@@ -739,6 +739,7 @@ def _sample_to_dict(s: BizProtocolSample) -> Dict[str, Any]:
|
||||
"storageInDate": (s.storage_in_date or "").strip() if s.storage_in_date else "",
|
||||
"detectStartDate": (s.detect_start_date or "").strip() if s.detect_start_date else "",
|
||||
"voidDate": (s.void_date or "").strip() if s.void_date else "",
|
||||
"voidDesc": (getattr(s, "void_desc", None) or "").strip() if (getattr(s, "void_desc", None) or "").strip() else "",
|
||||
"storageExpireDate": (s.storage_expire_date or "").strip() if s.storage_expire_date else "",
|
||||
**sample_special_to_dict(s),
|
||||
"tenantNo": s.tenant_no,
|
||||
|
||||
@@ -679,9 +679,6 @@ def _enrich_work_order_list_items(
|
||||
code = (r.sample_code or "").strip()
|
||||
if code and code not in sample_code_rec_map:
|
||||
sample_code_rec_map[code] = r
|
||||
if not rec_map and not sample_code_rec_map:
|
||||
return items
|
||||
|
||||
def _resolve_reception(item: Dict[str, Any]) -> Optional[BizSampleReception]:
|
||||
rec = rec_map.get(item.get("receptionId") or "")
|
||||
if rec:
|
||||
@@ -697,7 +694,9 @@ def _enrich_work_order_list_items(
|
||||
rec = _resolve_reception(item)
|
||||
source = _effective_reception_source(item, rec)
|
||||
if source == "research_donation":
|
||||
dsid = _effective_donation_sample_id(item, rec)
|
||||
dsid = _effective_donation_sample_id(item, rec) or (
|
||||
item.get("protocolSampleId") or ""
|
||||
).strip()
|
||||
if dsid:
|
||||
donation_sample_ids.append(dsid)
|
||||
did = (
|
||||
@@ -706,7 +705,9 @@ def _enrich_work_order_list_items(
|
||||
if did:
|
||||
donation_ids.append(did)
|
||||
else:
|
||||
psid = _effective_protocol_sample_id(item, rec)
|
||||
psid = _effective_protocol_sample_id(item, rec) or (
|
||||
item.get("protocolSampleId") or ""
|
||||
).strip()
|
||||
if psid:
|
||||
cell_sample_ids.append(psid)
|
||||
pid = (
|
||||
@@ -864,11 +865,34 @@ def _enrich_work_order_list_items(
|
||||
item["motherName"] = _mother
|
||||
item["newbornName"] = _newborn
|
||||
item["maternalBloodCollectTime"] = cell_maternal_map.get(_pid or "", "") or ""
|
||||
def _apply_sample_status_fields() -> None:
|
||||
sample_obj = None
|
||||
if source == "research_donation":
|
||||
dsid = _effective_donation_sample_id(item, rec) or (
|
||||
item.get("protocolSampleId") or ""
|
||||
).strip()
|
||||
sample_obj = donation_samples.get(dsid) if dsid else None
|
||||
else:
|
||||
psid = _effective_protocol_sample_id(item, rec) or (
|
||||
item.get("protocolSampleId") or ""
|
||||
).strip()
|
||||
sample_obj = protocol_samples.get(psid) if psid else None
|
||||
item["sampleStatus"] = (
|
||||
(sample_obj.sample_status or "").strip() if sample_obj else ""
|
||||
)
|
||||
item["voidDesc"] = (
|
||||
(getattr(sample_obj, "void_desc", None) or "").strip() if sample_obj else ""
|
||||
)
|
||||
item["voidDate"] = (
|
||||
(sample_obj.void_date or "").strip() if sample_obj else ""
|
||||
)
|
||||
|
||||
if not rec:
|
||||
item.setdefault("receptionTime", "")
|
||||
item.setdefault("handlerName", "")
|
||||
item.setdefault("sampleTypeName", "")
|
||||
item.setdefault("labStorageCode", "")
|
||||
_apply_sample_status_fields()
|
||||
continue
|
||||
item["receptionTime"] = _fmt_dt(rec.reception_time)
|
||||
item["handlerName"] = rec.handler_name or ""
|
||||
@@ -889,6 +913,7 @@ def _enrich_work_order_list_items(
|
||||
protocol_samples=protocol_samples,
|
||||
donation_samples=donation_samples,
|
||||
)
|
||||
_apply_sample_status_fields()
|
||||
if source == "research_donation":
|
||||
_did = (
|
||||
(getattr(rec, "research_donation_id", None) or "").strip()
|
||||
|
||||
@@ -535,6 +535,7 @@ def _sample_to_dict(s: BizResearchDonationSample) -> Dict[str, Any]:
|
||||
"storageInDate": (s.storage_in_date or "").strip() if s.storage_in_date else "",
|
||||
"detectStartDate": (s.detect_start_date or "").strip() if s.detect_start_date else "",
|
||||
"voidDate": (s.void_date or "").strip() if s.void_date else "",
|
||||
"voidDesc": (getattr(s, "void_desc", None) or "").strip() if (getattr(s, "void_desc", None) or "").strip() else "",
|
||||
"storageExpireDate": (s.storage_expire_date or "").strip() if s.storage_expire_date else "",
|
||||
**sample_special_to_dict(s),
|
||||
"tenantNo": s.tenant_no,
|
||||
|
||||
+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
|
||||
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
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -125,6 +125,7 @@ app.include_router(leave_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(operations_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(ethnic_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(sample_reception_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(business_sample_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(sample_production_reception_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(qc_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(research_donation_router, prefix=settings.API_V1_PREFIX)
|
||||
|
||||
@@ -1597,6 +1597,7 @@ class BizProtocolSample(Base):
|
||||
storage_in_date = Column(CHAR(8), nullable=True, comment="入库日期YYYYMMDD")
|
||||
detect_start_date = Column(CHAR(8), nullable=True, comment="检测开始日期YYYYMMDD")
|
||||
void_date = Column(CHAR(8), nullable=True, comment="作废日期YYYYMMDD")
|
||||
void_desc = Column(String(512), nullable=True, comment="样本作废原因")
|
||||
storage_expire_date = Column(CHAR(8), nullable=True, comment="存储到期日期YYYYMMDD")
|
||||
is_special = Column(SmallInteger, nullable=False, default=0, comment="是否特殊样本:0否 1是")
|
||||
special_remark = Column(String(256), nullable=True, comment="特殊说明")
|
||||
|
||||
@@ -175,6 +175,7 @@ class BizResearchDonationSample(Base):
|
||||
storage_in_date = Column(String(8), nullable=True, comment="入库日期YYYYMMDD")
|
||||
detect_start_date = Column(String(8), nullable=True, comment="检测开始日期YYYYMMDD")
|
||||
void_date = Column(String(8), nullable=True, comment="作废日期YYYYMMDD")
|
||||
void_desc = Column(String(512), nullable=True, comment="样本作废原因")
|
||||
storage_expire_date = Column(String(8), nullable=True, comment="存储到期日期YYYYMMDD")
|
||||
is_special = Column(SmallInteger, nullable=False, default=0, comment="是否特殊样本:0否 1是")
|
||||
special_remark = Column(String(256), nullable=True, comment="特殊说明")
|
||||
|
||||
@@ -56,6 +56,12 @@ from app.services.web_auth_roles import (
|
||||
CELL = 'cell_storage'
|
||||
DONATION = 'research_donation'
|
||||
SOURCES = (CELL, DONATION)
|
||||
_SAMPLE_STATUS_LABELS = {
|
||||
'ycj': '已采集',
|
||||
'jcz': '检测中',
|
||||
'yrk': '已入库',
|
||||
'yzf': '已作废',
|
||||
}
|
||||
|
||||
|
||||
def _current_tenant_user_info(
|
||||
@@ -265,18 +271,25 @@ def _visible_rows(db: Session, freight_ids: List[str], ctx: MarketFieldContext,
|
||||
def _item_dict(row) -> Dict[str, Any]:
|
||||
item, sample, parent, party, sample_type = row
|
||||
source = item.sample_source
|
||||
return {
|
||||
sample_code = sample.sample_code or ''
|
||||
payload = {
|
||||
'id': item.id,
|
||||
'freightId': item.freight_id,
|
||||
'sampleSource': source,
|
||||
'sampleId': sample.id,
|
||||
'sampleCode': sample.sample_code or '',
|
||||
'sampleCode': sample_code,
|
||||
'protocolId': parent.id,
|
||||
'protocolNo': (parent.protocol_no if source == CELL else parent.donation_no) or '',
|
||||
'sampleTypeName': sample_type.type_name if sample_type else '',
|
||||
'motherName': party.mother_name if party else '',
|
||||
'newbornName': party.newborn_name if party else '',
|
||||
}
|
||||
if sample_code:
|
||||
status = str(getattr(sample, 'sample_status', None) or '').strip()
|
||||
payload['sampleStatus'] = status
|
||||
payload['sampleStatusLabel'] = _SAMPLE_STATUS_LABELS.get(status, '')
|
||||
payload['voidDesc'] = str(getattr(sample, 'void_desc', None) or '')
|
||||
return payload
|
||||
|
||||
|
||||
def _label_map(db: Session, tenant_no: str, values: List[str]) -> Dict[str, str]:
|
||||
|
||||
@@ -40,6 +40,51 @@ from app.services.market_support import (
|
||||
)
|
||||
|
||||
|
||||
_SAMPLE_STATUS_LABELS = {
|
||||
'ycj': '已采集',
|
||||
'jcz': '检测中',
|
||||
'yrk': '已入库',
|
||||
'yzf': '已作废',
|
||||
}
|
||||
|
||||
|
||||
def _sample_status_by_code(
|
||||
db: Session,
|
||||
tenant_no: str,
|
||||
sample_codes: List[str],
|
||||
) -> Dict[str, Dict[str, str]]:
|
||||
"""按租户 + 样本编码取样本状态;同一编码多行时保留最近更新的一条。"""
|
||||
wanted = [code for code in {str(code or '').strip() for code in sample_codes} if code]
|
||||
if not wanted:
|
||||
return {}
|
||||
rows = (
|
||||
db.query(BizProtocolSample)
|
||||
.filter(
|
||||
BizProtocolSample.tenant_no == tenant_no,
|
||||
BizProtocolSample.del_flag == 0,
|
||||
BizProtocolSample.sample_code.in_(wanted),
|
||||
)
|
||||
.order_by(
|
||||
BizProtocolSample.update_time.desc(),
|
||||
BizProtocolSample.create_time.desc(),
|
||||
BizProtocolSample.id.desc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
result: Dict[str, Dict[str, str]] = {}
|
||||
for sample in rows:
|
||||
code = str(sample.sample_code or '').strip()
|
||||
if not code or code in result:
|
||||
continue
|
||||
status = str(sample.sample_status or '').strip()
|
||||
result[code] = {
|
||||
'sampleStatus': status,
|
||||
'sampleStatusLabel': _SAMPLE_STATUS_LABELS.get(status, ''),
|
||||
'voidDesc': sample.void_desc or '',
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def _current_dept_id(user_info: dict) -> str:
|
||||
return str(
|
||||
user_info.get('dept_id')
|
||||
@@ -104,12 +149,16 @@ def _load_sample_meta(
|
||||
discount = None
|
||||
if original is not None and current is not None and original > current:
|
||||
discount = original - current
|
||||
status = str(sample.sample_status or '').strip()
|
||||
result.setdefault(
|
||||
sample.sample_code or '',
|
||||
{
|
||||
'storageYears': sample.storage_years,
|
||||
'sampleTypeName': sample_type.type_name if sample_type else '',
|
||||
'discountAmount': _money(discount),
|
||||
'sampleStatus': status,
|
||||
'sampleStatusLabel': _SAMPLE_STATUS_LABELS.get(status, ''),
|
||||
'voidDesc': sample.void_desc or '',
|
||||
},
|
||||
)
|
||||
return result
|
||||
@@ -235,7 +284,8 @@ def _payment_dict(
|
||||
'bfyj': '部分已缴',
|
||||
'dfj': '待缴费',
|
||||
}[progress_code]
|
||||
return {
|
||||
sample_code = payment.sample_code or ''
|
||||
payload = {
|
||||
'id': payment.id,
|
||||
'collectionProtocolId': protocol.id,
|
||||
'protocolNo': protocol.protocol_no or '',
|
||||
@@ -243,7 +293,7 @@ def _payment_dict(
|
||||
'paymentModelVersion': int(getattr(protocol, 'payment_model_version', None) or 1),
|
||||
'motherName': (party.mother_name if party else '') or '',
|
||||
'motherPhone': (party.mother_phone if party else '') or '',
|
||||
'sampleCode': payment.sample_code or '',
|
||||
'sampleCode': sample_code,
|
||||
'payMode': payment.pay_mode or '',
|
||||
'contractAmount': _money(payment.contract_amount),
|
||||
'signDate': _display_ymd(getattr(protocol, 'register_date', None)),
|
||||
@@ -262,6 +312,11 @@ def _payment_dict(
|
||||
'periods': periods,
|
||||
'schedules': schedule_rows,
|
||||
}
|
||||
if sample_code:
|
||||
payload['sampleStatus'] = meta.get('sampleStatus') or ''
|
||||
payload['sampleStatusLabel'] = meta.get('sampleStatusLabel') or ''
|
||||
payload['voidDesc'] = meta.get('voidDesc') or ''
|
||||
return payload
|
||||
|
||||
|
||||
def _scoped_payment_query(
|
||||
@@ -733,6 +788,14 @@ def list_payment_chase(
|
||||
)
|
||||
}
|
||||
rows: List[Dict[str, Any]] = []
|
||||
status_by_code = _sample_status_by_code(
|
||||
db,
|
||||
ctx.tenant_no,
|
||||
[
|
||||
payment.sample_code or schedule.sample_code or ''
|
||||
for schedule, payment, _, _, _, _ in candidates
|
||||
],
|
||||
)
|
||||
for schedule, payment, protocol, party, collection, paid in candidates:
|
||||
due_date = parse_due_date_ymd(schedule.due_date)
|
||||
if due_date is None:
|
||||
@@ -741,6 +804,8 @@ def list_payment_chase(
|
||||
due_value = Decimal(str(schedule.due_amount or 0))
|
||||
arrears = max(due_value - paid_value, Decimal('0'))
|
||||
is_overdue = due_date < today_value
|
||||
sample_code = payment.sample_code or schedule.sample_code or ''
|
||||
sample_state = status_by_code.get(sample_code, {}) if sample_code else {}
|
||||
rows.append(
|
||||
{
|
||||
'scheduleId': schedule.id,
|
||||
@@ -750,7 +815,16 @@ def list_payment_chase(
|
||||
'protocolStatus': protocol.protocol_status or '',
|
||||
'motherName': (party.mother_name if party else '') or '',
|
||||
'motherPhone': (party.mother_phone if party else '') or '',
|
||||
'sampleCode': payment.sample_code or schedule.sample_code or '',
|
||||
'sampleCode': sample_code,
|
||||
**(
|
||||
{
|
||||
'sampleStatus': sample_state.get('sampleStatus', ''),
|
||||
'sampleStatusLabel': sample_state.get('sampleStatusLabel', ''),
|
||||
'voidDesc': sample_state.get('voidDesc', ''),
|
||||
}
|
||||
if sample_code
|
||||
else {}
|
||||
),
|
||||
'salesUserId': collection.sales_user_id or '',
|
||||
'salesUserName': sales_user_names.get(
|
||||
collection.sales_user_id or '', ''
|
||||
|
||||
@@ -641,6 +641,14 @@ def _party_name_donation(db: Session, ids: List[str], tenant_no: str) -> dict:
|
||||
return {row.research_donation_id: row.mother_name or '' for row in rows}
|
||||
|
||||
|
||||
_SAMPLE_STATUS_LABELS = {
|
||||
'ycj': '已采集',
|
||||
'jcz': '检测中',
|
||||
'yrk': '已入库',
|
||||
'yzf': '已作废',
|
||||
}
|
||||
|
||||
|
||||
def _enrich_protocol_cards(
|
||||
db: Session, items: List[dict], tenant_no: str
|
||||
) -> None:
|
||||
@@ -795,6 +803,11 @@ def _enrich_protocol_cards(
|
||||
payment_summary = payment_summaries.get(item['id']) or {}
|
||||
transport = transport_by_sample.get(getattr(sample, 'id', ''))
|
||||
sample_code = getattr(sample, 'sample_code', '') or ''
|
||||
sample_status = ''
|
||||
sample_void_desc = ''
|
||||
if sample_code:
|
||||
sample_status = str(getattr(sample, 'sample_status', None) or '').strip()
|
||||
sample_void_desc = str(getattr(sample, 'void_desc', None) or '')
|
||||
region_manager_name = user_names.get(
|
||||
getattr(collection, 'region_manager_user_id', ''), ''
|
||||
)
|
||||
@@ -844,6 +857,11 @@ def _enrich_protocol_cards(
|
||||
str(item.get('voidType') or ''), ''
|
||||
),
|
||||
)
|
||||
if sample_code:
|
||||
# 样本作废原因与协议级 voidDesc 分开,捐赠列表「废弃原因」仍读协议描述。
|
||||
item['sampleStatus'] = sample_status
|
||||
item['sampleStatusLabel'] = _SAMPLE_STATUS_LABELS.get(sample_status, '')
|
||||
item['sampleVoidDesc'] = sample_void_desc
|
||||
|
||||
|
||||
def list_protocols(
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
- 协议下全部样本接收结论自动为废弃(bj);
|
||||
- 协议下全部有效样本 `sample_status` 置为已作废(yzf),并写入 `void_date`。
|
||||
3. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。
|
||||
4. 人工【样本废弃】:仅将该样本置 yzf 并写 void_date/void_desc,不改接收结论;
|
||||
若协议下有效样本全部为 yzf,则自动作废协议(不联动接收结论)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -32,6 +34,7 @@ SAMPLE_VOID_STATUS = "yzf"
|
||||
|
||||
_AUTO_DISCARD_REMARK = "协议作废自动废弃"
|
||||
_AUTO_VOID_DESC = "全部样本接收废弃/拒收,系统自动作废"
|
||||
_AUTO_VOID_BY_SAMPLE_STATUS_DESC = "全部样本已作废,系统自动作废协议"
|
||||
|
||||
|
||||
def _void_date_yyyymmdd(
|
||||
@@ -620,6 +623,7 @@ def clear_sample_void_for_accepted_reception(
|
||||
now = datetime.now()
|
||||
sample.sample_status = None
|
||||
sample.void_date = None
|
||||
sample.void_desc = None
|
||||
sample.update_by = user_id
|
||||
sample.update_time = now
|
||||
db.add(sample)
|
||||
@@ -688,3 +692,224 @@ def after_protocol_voided(
|
||||
db, source=source, protocol_id=protocol_id, tenant_no=tenant_no
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _all_samples_status_voided(
|
||||
db: Session,
|
||||
*,
|
||||
source: str,
|
||||
protocol_id: str,
|
||||
tenant_no: str,
|
||||
) -> bool:
|
||||
src = (source or "").strip()
|
||||
if src == "cell_storage":
|
||||
samples = _list_cell_samples(db, protocol_id=protocol_id, tenant_no=tenant_no)
|
||||
else:
|
||||
samples = _list_donation_samples(db, donation_id=protocol_id, tenant_no=tenant_no)
|
||||
if not samples:
|
||||
return False
|
||||
for sample in samples:
|
||||
if (sample.sample_status or "").strip() != SAMPLE_VOID_STATUS:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def maybe_void_protocol_when_all_samples_status_voided(
|
||||
db: Session,
|
||||
*,
|
||||
source: str,
|
||||
protocol_id: str,
|
||||
tenant_no: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""若协议下有效样本全部已作废,则自动作废协议;不联动接收结论。"""
|
||||
src = (source or "").strip()
|
||||
pid = (protocol_id or "").strip()
|
||||
tenant = (tenant_no or "").strip()
|
||||
if src not in ("cell_storage", "research_donation") or not pid or not tenant:
|
||||
return False
|
||||
if not _all_samples_status_voided(db, source=src, protocol_id=pid, tenant_no=tenant):
|
||||
return False
|
||||
|
||||
void_type = ensure_lab_void_type(db, tenant_no=tenant)
|
||||
now = datetime.now()
|
||||
|
||||
if src == "cell_storage":
|
||||
obj = (
|
||||
db.query(BizCollectionProtocol)
|
||||
.filter(
|
||||
BizCollectionProtocol.id == pid,
|
||||
BizCollectionProtocol.tenant_no == tenant,
|
||||
BizCollectionProtocol.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not obj:
|
||||
return False
|
||||
status = (obj.protocol_status or "").strip()
|
||||
if status in INACTIVE_PROTOCOL_STATUSES:
|
||||
return False
|
||||
from app.core.protocol_status_display import assert_protocol_status_transition
|
||||
from app.crud.collection_protocol import update_collection_protocol
|
||||
|
||||
try:
|
||||
assert_protocol_status_transition(status, "yzf", kind="protocol")
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
update_collection_protocol(
|
||||
db,
|
||||
pid,
|
||||
tenant_no=tenant,
|
||||
user_id=user_id,
|
||||
protocol_status="yzf",
|
||||
void_time=now,
|
||||
void_desc=_AUTO_VOID_BY_SAMPLE_STATUS_DESC,
|
||||
void_type=void_type,
|
||||
commit=False,
|
||||
sync_reception_discard=False,
|
||||
)
|
||||
return True
|
||||
|
||||
obj = (
|
||||
db.query(BizResearchDonation)
|
||||
.filter(
|
||||
BizResearchDonation.id == pid,
|
||||
BizResearchDonation.tenant_no == tenant,
|
||||
BizResearchDonation.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not obj:
|
||||
return False
|
||||
status = (obj.donation_status or "").strip()
|
||||
if status in INACTIVE_PROTOCOL_STATUSES:
|
||||
return False
|
||||
|
||||
from app.core.protocol_status_display import assert_protocol_status_transition
|
||||
from app.crud.dict_data import normalize_void_type
|
||||
from app.crud.research_donation import (
|
||||
_DONATION_STATUS_CHANGE_TYPE,
|
||||
append_donation_status_change,
|
||||
)
|
||||
|
||||
current = obj.donation_status or ""
|
||||
try:
|
||||
assert_protocol_status_transition(current, "yzf", kind="donation")
|
||||
except ValueError:
|
||||
return False
|
||||
normalized = normalize_void_type(db, value=void_type, tenant_no=tenant)
|
||||
obj.donation_status = "yzf"
|
||||
obj.void_time = now
|
||||
obj.void_desc = _AUTO_VOID_BY_SAMPLE_STATUS_DESC
|
||||
obj.void_type = normalized
|
||||
obj.update_by = user_id
|
||||
obj.update_time = now
|
||||
change_type = _DONATION_STATUS_CHANGE_TYPE.get("yzf")
|
||||
if change_type:
|
||||
append_donation_status_change(
|
||||
db,
|
||||
research_donation_id=obj.id,
|
||||
change_type=change_type,
|
||||
from_status=current,
|
||||
to_status="yzf",
|
||||
change_time=now,
|
||||
change_desc=_AUTO_VOID_BY_SAMPLE_STATUS_DESC,
|
||||
void_type=normalized,
|
||||
tenant_no=tenant,
|
||||
user_id=user_id,
|
||||
)
|
||||
db.add(obj)
|
||||
db.flush()
|
||||
return True
|
||||
|
||||
|
||||
def void_sample_manually(
|
||||
db: Session,
|
||||
*,
|
||||
source: str,
|
||||
tenant_no: str,
|
||||
void_desc: str,
|
||||
user_id: Optional[str] = None,
|
||||
sample_id: Optional[str] = None,
|
||||
sample_code: Optional[str] = None,
|
||||
protocol_id: Optional[str] = None,
|
||||
commit: bool = True,
|
||||
) -> Union[BizProtocolSample, BizResearchDonationSample]:
|
||||
"""人工样本废弃:写 yzf/void_date/void_desc;不改接收;全作废则自动作废协议。"""
|
||||
src = (source or "").strip()
|
||||
tenant = (tenant_no or "").strip()
|
||||
reason = (void_desc or "").strip()
|
||||
sid = (sample_id or "").strip()
|
||||
code = (sample_code or "").strip()
|
||||
pid = (protocol_id or "").strip()
|
||||
if src not in ("cell_storage", "research_donation"):
|
||||
raise ValueError("来源类型无效")
|
||||
if not tenant:
|
||||
raise ValueError("租户编号不能为空")
|
||||
if not reason:
|
||||
raise ValueError("请填写作废原因")
|
||||
if not sid and not code:
|
||||
raise ValueError("样本标识不能为空")
|
||||
|
||||
now = datetime.now()
|
||||
sample: Optional[Union[BizProtocolSample, BizResearchDonationSample]] = None
|
||||
parent_id = ""
|
||||
|
||||
if src == "cell_storage":
|
||||
q = db.query(BizProtocolSample).filter(
|
||||
BizProtocolSample.tenant_no == tenant,
|
||||
BizProtocolSample.del_flag == 0,
|
||||
)
|
||||
if sid:
|
||||
q = q.filter(BizProtocolSample.id == sid)
|
||||
else:
|
||||
q = q.filter(BizProtocolSample.sample_code == code)
|
||||
if pid:
|
||||
q = q.filter(BizProtocolSample.collection_protocol_id == pid)
|
||||
sample = q.first()
|
||||
if not sample:
|
||||
raise ValueError("样本不存在")
|
||||
parent_id = (sample.collection_protocol_id or "").strip()
|
||||
else:
|
||||
q = db.query(BizResearchDonationSample).filter(
|
||||
BizResearchDonationSample.tenant_no == tenant,
|
||||
BizResearchDonationSample.del_flag == 0,
|
||||
)
|
||||
if sid:
|
||||
q = q.filter(BizResearchDonationSample.id == sid)
|
||||
else:
|
||||
q = q.filter(BizResearchDonationSample.sample_code == code)
|
||||
if pid:
|
||||
q = q.filter(BizResearchDonationSample.research_donation_id == pid)
|
||||
sample = q.first()
|
||||
if not sample:
|
||||
raise ValueError("样本不存在")
|
||||
parent_id = (sample.research_donation_id or "").strip()
|
||||
|
||||
if _protocol_is_inactive(db, source=src, protocol_id=parent_id, tenant_no=tenant):
|
||||
raise ValueError("所属协议已作废或属地废弃,无法操作")
|
||||
|
||||
sample.sample_status = SAMPLE_VOID_STATUS
|
||||
sample.void_date = _void_date_yyyymmdd(void_time=now)
|
||||
sample.void_desc = reason
|
||||
sample.update_by = user_id
|
||||
sample.update_time = now
|
||||
db.add(sample)
|
||||
db.flush()
|
||||
|
||||
if parent_id:
|
||||
maybe_void_protocol_when_all_samples_status_voided(
|
||||
db,
|
||||
source=src,
|
||||
protocol_id=parent_id,
|
||||
tenant_no=tenant,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
if commit:
|
||||
db.commit()
|
||||
db.refresh(sample)
|
||||
else:
|
||||
db.flush()
|
||||
return sample
|
||||
Reference in new issue
Block a user