diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py index fbc1f236..fc885dfb 100644 --- a/backend/app/api/__init__.py +++ b/backend/app/api/__init__.py @@ -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", diff --git a/backend/app/api/business_sample.py b/backend/app/api/business_sample.py new file mode 100644 index 00000000..15b754d2 --- /dev/null +++ b/backend/app/api/business_sample.py @@ -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)) diff --git a/backend/app/crud/collection_protocol.py b/backend/app/crud/collection_protocol.py index 9b7d675d..3b56e567 100644 --- a/backend/app/crud/collection_protocol.py +++ b/backend/app/crud/collection_protocol.py @@ -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, diff --git a/backend/app/crud/qc_work_order.py b/backend/app/crud/qc_work_order.py index 275527ca..d5a69711 100644 --- a/backend/app/crud/qc_work_order.py +++ b/backend/app/crud/qc_work_order.py @@ -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() diff --git a/backend/app/crud/research_donation.py b/backend/app/crud/research_donation.py index 8fdabb4a..a6826844 100644 --- a/backend/app/crud/research_donation.py +++ b/backend/app/crud/research_donation.py @@ -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, diff --git a/backend/app/main.py b/backend/app/main.py index 1eb60a4f..6a3fd4d9 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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) diff --git a/backend/app/models/models.py b/backend/app/models/models.py index 78a8e098..9b296777 100644 --- a/backend/app/models/models.py +++ b/backend/app/models/models.py @@ -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="特殊说明") diff --git a/backend/app/models/research_donation.py b/backend/app/models/research_donation.py index 90b3dfc4..564d29bc 100644 --- a/backend/app/models/research_donation.py +++ b/backend/app/models/research_donation.py @@ -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="特殊说明") diff --git a/backend/app/services/market_freight.py b/backend/app/services/market_freight.py index 812c3abb..1c113172 100644 --- a/backend/app/services/market_freight.py +++ b/backend/app/services/market_freight.py @@ -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]: diff --git a/backend/app/services/market_payment.py b/backend/app/services/market_payment.py index 31ee78a8..0ccc016d 100644 --- a/backend/app/services/market_payment.py +++ b/backend/app/services/market_payment.py @@ -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 '', '' diff --git a/backend/app/services/market_protocol.py b/backend/app/services/market_protocol.py index c6eea5fa..9bc3896d 100644 --- a/backend/app/services/market_protocol.py +++ b/backend/app/services/market_protocol.py @@ -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( diff --git a/backend/app/services/protocol_reception_discard_sync.py b/backend/app/services/protocol_reception_discard_sync.py index 512f3286..b225335f 100644 --- a/backend/app/services/protocol_reception_discard_sync.py +++ b/backend/app/services/protocol_reception_discard_sync.py @@ -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 diff --git a/backend/tests/test_business_sample_void.py b/backend/tests/test_business_sample_void.py new file mode 100644 index 00000000..18c33853 --- /dev/null +++ b/backend/tests/test_business_sample_void.py @@ -0,0 +1,211 @@ +"""人工样本废弃:写状态/原因,全作废则协议作废,不联动接收。""" + +from __future__ import annotations + +import unittest +from datetime import datetime + +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from app.core.database import Base +from app.models.models import ( + BizCollectionProtocol, + BizProtocolSample, + BizProtocolStatusChange, + BizSampleReception, + SysDictData, +) +from app.services.protocol_reception_discard_sync import ( + LAB_VOID_TYPE_CODE, + SAMPLE_VOID_STATUS, + void_sample_manually, +) + + +def _session(): + engine = create_engine("sqlite://") + Base.metadata.create_all( + bind=engine, + tables=[ + SysDictData.__table__, + BizCollectionProtocol.__table__, + BizProtocolSample.__table__, + BizProtocolStatusChange.__table__, + BizSampleReception.__table__, + ], + ) + return sessionmaker(bind=engine)() + + +def _now(): + return datetime(2026, 11, 19, 12, 0, 0) + + +class TestBusinessSampleVoid(unittest.TestCase): + def test_void_one_sample_keeps_protocol_and_skips_reception(self): + db = _session() + now = _now() + db.add( + BizCollectionProtocol( + id="p1", + protocol_no="CP-1", + protocol_status="sxz", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizProtocolSample( + id="sa", + collection_protocol_id="p1", + sample_code="A001", + sample_status="ycj", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizProtocolSample( + id="sb", + collection_protocol_id="p1", + sample_code="B001", + sample_status="ycj", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizSampleReception( + id="ra", + protocol_sample_id="sa", + collection_protocol_id="p1", + reception_time=now, + accept_conclusion="js", + reception_source="cell_storage", + sample_code="A001", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + check_packaging=0, + check_sealing=0, + check_no_damage=0, + check_no_leakage=0, + check_color=0, + check_tying_rope=0, + check_no_stratification=0, + ) + ) + db.commit() + + void_sample_manually( + db, + source="cell_storage", + tenant_no="tenant-a", + void_desc="质检发现污染", + user_id="u1", + sample_id="sa", + ) + + a = db.query(BizProtocolSample).filter(BizProtocolSample.id == "sa").one() + b = db.query(BizProtocolSample).filter(BizProtocolSample.id == "sb").one() + proto = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p1").one() + rec = db.query(BizSampleReception).filter(BizSampleReception.id == "ra").one() + self.assertEqual(a.sample_status, SAMPLE_VOID_STATUS) + self.assertEqual(a.void_desc, "质检发现污染") + self.assertTrue((a.void_date or "").strip()) + self.assertEqual(b.sample_status, "ycj") + self.assertEqual(proto.protocol_status, "sxz") + self.assertEqual(rec.accept_conclusion, "js") + + def test_void_all_samples_auto_voids_protocol_without_reception_change(self): + db = _session() + now = _now() + db.add( + BizCollectionProtocol( + id="p2", + protocol_no="CP-2", + protocol_status="sxz", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + for sid, code in (("s1", "C001"), ("s2", "C002")): + db.add( + BizProtocolSample( + id=sid, + collection_protocol_id="p2", + sample_code=code, + sample_status="ycj", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizSampleReception( + id="r1", + protocol_sample_id="s1", + collection_protocol_id="p2", + reception_time=now, + accept_conclusion="js", + reception_source="cell_storage", + sample_code="C001", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + check_packaging=0, + check_sealing=0, + check_no_damage=0, + check_no_leakage=0, + check_color=0, + check_tying_rope=0, + check_no_stratification=0, + ) + ) + db.commit() + + void_sample_manually( + db, + source="cell_storage", + tenant_no="tenant-a", + void_desc="原因1", + sample_id="s1", + commit=True, + ) + void_sample_manually( + db, + source="cell_storage", + tenant_no="tenant-a", + void_desc="原因2", + sample_id="s2", + commit=True, + ) + + proto = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p2").one() + rec = db.query(BizSampleReception).filter(BizSampleReception.id == "r1").one() + self.assertEqual(proto.protocol_status, "yzf") + self.assertEqual(proto.void_type, LAB_VOID_TYPE_CODE) + self.assertEqual(rec.accept_conclusion, "js") + + +if __name__ == "__main__": + unittest.main() diff --git a/backend/tests/test_market_freight_scope.py b/backend/tests/test_market_freight_scope.py index 216d1b89..6eb68d03 100644 --- a/backend/tests/test_market_freight_scope.py +++ b/backend/tests/test_market_freight_scope.py @@ -99,12 +99,20 @@ def test_specialist_sees_shared_batch_but_only_own_items_and_count(): from app.services.market_freight import get_freight_detail, list_freights db = _session() own, own_parent = _sample(db, 'own') + own.sample_status = 'yzf' + own.void_desc = '冷链中断' + db.commit() other, other_parent = _sample(db, 'other', sales='u2') freight = _freight(db, 'mixed', [('cell_storage', own, own_parent), ('cell_storage', other, other_parent)]) rows, total = list_freights(db, ctx=_ctx(), user_info=_user(), include_items=True) detail = get_freight_detail(db, freight.id, ctx=_ctx(), user_info=_user()) assert total == 1 and rows[0]['visibleItemCount'] == 1 assert [item['sampleCode'] for item in rows[0]['items']] == ['C-own'] + assert rows[0]['items'][0]['sampleStatus'] == 'yzf' + assert rows[0]['items'][0]['sampleStatusLabel'] == '已作废' + assert rows[0]['items'][0]['voidDesc'] == '冷链中断' + assert detail['items'][0]['sampleStatus'] == 'yzf' + assert detail['items'][0]['voidDesc'] == '冷链中断' assert [item['sampleCode'] for item in detail['items']] == ['C-own'] assert rows[0]['createBy'] == detail['createBy'] == 'u1' assert rows[0]['createByName'] == detail['createByName'] == '专员' diff --git a/backend/tests/test_market_payment_api.py b/backend/tests/test_market_payment_api.py index 30f6c42d..2cd81c96 100644 --- a/backend/tests/test_market_payment_api.py +++ b/backend/tests/test_market_payment_api.py @@ -674,6 +674,33 @@ def test_chase_filters_counts_orders_and_pages_in_sql_before_materialization(): ) +def test_payment_and_chase_lists_include_sample_status_when_coded(): + from app.services.market_payment import list_payment_chase, list_payments + + db = _session() + today = date(2026, 10, 11) + _payment_tree(db, 'void-sample', due_date=today.strftime('%Y%m%d')) + sample = db.get(BizProtocolSample, 'sample-void-sample') + sample.sample_status = 'yzf' + sample.void_desc = '客户放弃' + db.commit() + + payments, payment_total = list_payments(db, ctx=_ctx(), user_info=_user()) + chase, chase_total = list_payment_chase( + db, ctx=_ctx(), user_info=_user(), today=today + ) + + assert payment_total == 1 + assert payments[0]['sampleCode'] == 'S-void-sample' + assert payments[0]['sampleStatus'] == 'yzf' + assert payments[0]['sampleStatusLabel'] == '已作废' + assert payments[0]['voidDesc'] == '客户放弃' + assert chase_total == 1 + assert chase[0]['sampleStatus'] == 'yzf' + assert chase[0]['sampleStatusLabel'] == '已作废' + assert chase[0]['voidDesc'] == '客户放弃' + + def test_payment_list_includes_legacy_models_and_uses_parent_scope_not_transfer_department(): from app.services.market_payment import list_payments diff --git a/backend/tests/test_market_protocol_api.py b/backend/tests/test_market_protocol_api.py index 9cdda2f4..e64f4a49 100644 --- a/backend/tests/test_market_protocol_api.py +++ b/backend/tests/test_market_protocol_api.py @@ -3604,6 +3604,10 @@ def test_protocol_list_contains_mobile_card_fields(): assert items[0]['deliveryMode'] == 'sc' assert items[0]['newbornWeightGram'] == 3200 assert items[0]['salesUserName'] == '当前用户' + assert items[0]['sampleStatus'] == '' + assert items[0]['sampleStatusLabel'] == '' + assert items[0]['sampleVoidDesc'] == '' + assert items[0]['voidDesc'] == '' by_customer, customer_total = list_protocols( db, ctx=_ctx('specialist'), user_info=_user(), keyword='李安然' @@ -3626,6 +3630,54 @@ def test_protocol_list_contains_mobile_card_fields(): } == {row.id} +def test_protocol_list_returns_sample_status_without_replacing_donation_void_desc(): + from app.services.market_protocol import list_protocols + + db = _session() + cell = _cell(db, 'status-cell') + db.add( + BizProtocolSample( + id='sample-status-cell', + collection_protocol_id=cell.id, + sample_code='S-CELL', + sample_status='yzf', + void_desc='试管破裂', + tenant_no='tenant-a', + create_dept_id='', + del_flag=0, + ) + ) + donation = _donation(db, 'status-don') + donation.void_desc = '协议作废说明' + db.add( + BizResearchDonationSample( + id='sample-status-don', + research_donation_id=donation.id, + sample_code='S-DON', + sample_status='yrk', + void_desc='样本溶血', + tenant_no='tenant-a', + create_dept_id='', + del_flag=0, + ) + ) + db.commit() + + items, total = list_protocols(db, ctx=_ctx('specialist'), user_info=_user()) + + assert total == 2 + by_id = {item['id']: item for item in items} + assert by_id['status-cell']['sampleCode'] == 'S-CELL' + assert by_id['status-cell']['sampleStatus'] == 'yzf' + assert by_id['status-cell']['sampleStatusLabel'] == '已作废' + assert by_id['status-cell']['voidDesc'] == '试管破裂' + assert by_id['status-cell']['sampleVoidDesc'] == '试管破裂' + assert by_id['status-don']['sampleStatus'] == 'yrk' + assert by_id['status-don']['sampleStatusLabel'] == '已入库' + assert by_id['status-don']['voidDesc'] == '协议作废说明' + assert by_id['status-don']['sampleVoidDesc'] == '样本溶血' + + @pytest.mark.parametrize('source', ['cell_storage', 'research_donation']) def test_protocol_list_and_detail_resolve_tenant_void_type_label(source): from app.services.market_protocol import get_protocol, list_protocols diff --git a/docs/sql/migrations/2026-11-19-sample-void-desc.sql b/docs/sql/migrations/2026-11-19-sample-void-desc.sql new file mode 100644 index 00000000..e97a550c --- /dev/null +++ b/docs/sql/migrations/2026-11-19-sample-void-desc.sql @@ -0,0 +1,26 @@ +-- Issue #131:样本作废原因字段 void_desc +-- 细胞存储 / 科研捐赠样本表;按列是否已存在可重复执行。 + +SET @db := DATABASE(); + +SET @exists := ( + SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'biz_protocol_sample' AND COLUMN_NAME = 'void_desc' +); +SET @sql := IF( + @exists = 0, + 'ALTER TABLE biz_protocol_sample ADD COLUMN void_desc VARCHAR(512) NULL COMMENT ''样本作废原因'' AFTER void_date', + 'SELECT 1' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +SET @exists := ( + SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'biz_research_donation_sample' AND COLUMN_NAME = 'void_desc' +); +SET @sql := IF( + @exists = 0, + 'ALTER TABLE biz_research_donation_sample ADD COLUMN void_desc VARCHAR(512) NULL COMMENT ''样本作废原因'' AFTER void_date', + 'SELECT 1' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/mobile-oa-h5/src/market/components/MarketListCard.vue b/mobile-oa-h5/src/market/components/MarketListCard.vue index d882af73..9215aadc 100644 --- a/mobile-oa-h5/src/market/components/MarketListCard.vue +++ b/mobile-oa-h5/src/market/components/MarketListCard.vue @@ -23,23 +23,11 @@