Compare commits
63
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0b4c8dfda8 | ||
|
|
7751cc0f4a | ||
|
|
0346bc0b1d | ||
|
|
76ddb81818 | ||
|
|
3f16a8ab3e | ||
|
|
14e733faf0 | ||
|
|
aac72e1fd9 | ||
|
|
f0a6abe538 | ||
|
|
a69dcc5bca | ||
|
|
0929164bf5 | ||
|
|
5ecde0c80d | ||
|
|
4024aad174 | ||
|
|
02811197c6 | ||
|
|
7b6a0523dd | ||
|
|
99562ee584 | ||
|
|
96773ae7a3 | ||
|
|
ef4d687d03 | ||
|
|
f5ab0c3167 | ||
|
|
e4b62d6406 | ||
|
|
808f7dcf03 | ||
|
|
50679fa75e | ||
|
|
2124ce9208 | ||
|
|
e7b3876db6 | ||
|
|
c0aba421da | ||
|
|
2aecb69cc4 | ||
|
|
2878c6889d | ||
|
|
4aee2b1fe5 | ||
|
|
5698a9dfc4 | ||
|
|
77d45d0bc5 | ||
|
|
dc0f8541c4 | ||
|
|
4fd6ef4be5 | ||
|
|
b3c191ee99 | ||
|
|
bbef46b645 | ||
|
|
5fe1193a2c | ||
|
|
58b252ce6b | ||
|
|
acb81cadd5 | ||
|
|
a64dd563bd | ||
|
|
377e0981ab | ||
|
|
4654678231 | ||
|
|
a6d3f6f610 | ||
|
|
6cd5ced688 | ||
|
|
843f44929c | ||
|
|
87a22880e8 | ||
|
|
529f36eac6 | ||
|
|
9dc6812393 | ||
|
|
e482980c7d | ||
|
|
900e957f25 | ||
|
|
15a20db725 | ||
|
|
3ac30a6c2c | ||
|
|
95d6b6025f | ||
|
|
d0eb97b167 | ||
|
|
476f744ee9 | ||
|
|
cec96ce480 | ||
|
|
77473a1738 | ||
|
|
db74cd64fe | ||
|
|
e1f0030403 | ||
|
|
5109d8b3e5 | ||
|
|
2a0a2ef72a | ||
|
|
3a396d79a2 | ||
|
|
9c4944702b | ||
|
|
e06f89dcf6 | ||
|
|
f343f12645 | ||
|
|
1032631318 |
No files matched your search
@@ -19,7 +19,7 @@ description: Use when starting a project, designing or prototyping project UI, i
|
||||
| 任务 | 读取 |
|
||||
| --- | --- |
|
||||
| 工单领取、并行会话、流程标签、转交、共享环境或合并排队 | [工单占用与隔离](references/issue-claims.md) |
|
||||
| 发送确认问题、请求用户操作、补发缺推荐或缺超时说明的旧题 | 先按[问题展示](references/planning.md#问题展示)在当前回复写出「待你确认」,完成[发问前检查](references/planning.md#发问前检查)后,再按[本地确认语音](references/question-notification.md)提醒 |
|
||||
| 发送确认问题、请求用户操作、补发缺推荐或缺超时说明的旧题 | 先按[问题展示](references/planning.md#问题展示)与 Cursor 宿主节在当前回复写出「待你确认」,完成[发问前检查](references/planning.md#发问前检查)后,再按[本地确认语音](references/question-notification.md)提醒;Cursor 下 `notify-question` 须为本轮最后一次工具且发问后停手 |
|
||||
| 关闭/恢复声音提醒 | [本地确认语音](references/question-notification.md) |
|
||||
| 空白工程、大需求、技术栈或架构变化 | [建设与规格](references/planning.md) |
|
||||
| 拉取工单、理解评论和截图、续接工单或交付前核对补充 | [工单全文、评论与图片](references/issue-context.md) |
|
||||
|
||||
@@ -43,6 +43,14 @@
|
||||
|
||||
必须等待的题,最后一行写「未回复时:本题保持等待。」宿主问题卡片可以同时使用,卡片内容与这份清单一致。回复正文里没有「待你确认」时,不播放提示音,也不开始 60 秒计时。
|
||||
|
||||
### Cursor / 工具先于正文的宿主
|
||||
|
||||
Cursor Agent 等同轮「先跑工具、再出最终回复」的宿主上:
|
||||
|
||||
1. 需要播音时,`notify-question` 只能作为本轮**最后一次**工具调用;最终可见回复必须以「待你确认」开头写全清单,本轮随后不得再编辑代码、开浏览器或继续依赖答复的实现。
|
||||
2. 承认提示音可能早于正文渲染数秒;用清单内一句「请在本会话回复;Queued 不是确认入口」消除错位。提示音整机可听,不保证当前聚焦会话就是发问会话。
|
||||
3. 工程若提供宿主适配说明(如 `docs/agents/cursor-question-visibility.md`),发问前按该说明执行;与本节冲突时以「用户必须看见清单」为准。
|
||||
|
||||
## 发问前检查
|
||||
|
||||
每次发送确认问题(含调用宿主提问工具)前,逐题完成以下检查;缺项先改题,再按[问题展示](#问题展示)写入当前回复。这里是 Agent 的执行步骤,尚无自动拦截宿主问题卡片的校验器。
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
|
||||
1. 先核对用户/工程的静音选择。当前回复已经写上「待你确认」清单后,记录该批问题的发送时间、推荐及范围,再播放。回复里还没有这份清单时不播放,也不把这一轮当作已经发问。
|
||||
2. 每批问题只播放一次,多题合并发送共用一次提醒。将“已尝试提醒/结果”记在现有任务记录;同一批等待、轮询、重试和会话恢复不重复播放。真正重新提出的新问题或用户要求再提醒时才播放下一次。
|
||||
3. 执行以下已安装入口。它只读取随包预生成的本地 WAV,并调用播放器;不联网、不调用语音生成服务、不在提问时临时生成语音。命令最多等待播放器 12 秒,不另开后台常驻进程。
|
||||
3. **Cursor 等「工具先于最终正文」的宿主**:不得在仍要继续工具批处理时播放。需要播放时,将 `notify-question` 放在本轮最后一次工具调用,并保证同轮最终正文以「待你确认」清单为主体且本轮停手。提示音在整机播放、不绑定聊天标签;Queued/Multitasking 队列不是确认入口。工程适配见 `docs/agents/cursor-question-visibility.md`(若存在)。
|
||||
4. 执行以下已安装入口。它只读取随包预生成的本地 WAV,并调用播放器;不联网、不调用语音生成服务、不在提问时临时生成语音。命令最多等待播放器 12 秒,不另开后台常驻进程。
|
||||
|
||||
```sh
|
||||
python3 .agents/skills/personal-dev/scripts/pda.py notify-question --project .
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
---
|
||||
description: 个人开发体系的工程任务入口
|
||||
description: 个人开发体系的工程任务入口(含 Cursor 确认可见性)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
工程建设、界面设计或原型、需求开发、Bug 修复、验收反馈或提交/push/合并续聊时,先读根 AGENTS.md,再读取工程根目录的 .agents/skills/personal-dev/SKILL.md 进行任务分级。仅咨询概念时直接回答。业务约束仍按目标目录的 AGENTS.md 查阅。
|
||||
工程建设、界面设计或原型、需求开发、Bug 修复、验收反馈或提交/push/合并续聊时,先读根 `AGENTS.md`,再读取工程根目录的 `.agents/skills/personal-dev/SKILL.md` 进行任务分级。仅咨询概念时直接回答。业务约束仍按目标目录的 `AGENTS.md` 查阅。
|
||||
|
||||
需要用户确认时,先在当前回复写出「待你确认」清单,再播放提示音。清单的写法以该 Skill 的问题展示规则为准。回复里没有这份清单时,不播放提示音。
|
||||
需要用户确认时:
|
||||
|
||||
1. 先读 [Cursor 确认可见性](../../docs/agents/cursor-question-visibility.md),再按 Skill 的问题展示规则发问。
|
||||
2. 本轮最终用户可见回复必须以「待你确认」清单为主体(含推荐与未回复处理);写完清单前不播放提示音。
|
||||
3. 若播放提示音:`notify-question` 必须是本轮最后一次工具调用,且本轮随后不再继续编辑/浏览器/实现类工具。
|
||||
4. 清单中写明请在本会话回复;底部 Queued / Multitasking 不是确认入口。
|
||||
5. 回复正文没有「待你确认」时,不播放提示音。
|
||||
@@ -45,11 +45,16 @@ from app.api.sample_storage_cert_qc import router as sample_storage_cert_qc_rout
|
||||
from app.api.customer_service_dict import router as customer_service_dict_router
|
||||
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",
|
||||
"menu_router",
|
||||
"admin_router",
|
||||
@@ -96,4 +101,5 @@ __all__ = [
|
||||
"customer_service_dict_router",
|
||||
"sample_cert_insurance_router",
|
||||
"sample_code_correction_router",
|
||||
"lab_sample_processing_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))
|
||||
@@ -0,0 +1,147 @@
|
||||
"""实验室样本处理数据台账 API"""
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
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_any_menu_code
|
||||
from app.core.response import error_response, success_response
|
||||
from app.crud import lab_sample_process as svc
|
||||
from app.models.models import SysUser
|
||||
from app.services import lab_sample_process as ledger
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["质检管理"])
|
||||
|
||||
# 市场/生产/质检三处菜单权限码不同,接口按并集鉴权
|
||||
LIST_MENU_CODES = (
|
||||
"biz:labSampleProcess:list",
|
||||
"production:labSampleProcess:list",
|
||||
"cellStorage:labSampleProcess:list",
|
||||
)
|
||||
SUPPLEMENT_MENU_CODES = (
|
||||
"biz:labSampleProcess:supplement",
|
||||
"production:labSampleProcess:supplement",
|
||||
"cellStorage:labSampleProcess:supplement",
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _user_id(user: dict) -> str:
|
||||
uid = user.get("user_id")
|
||||
if not uid:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
return str(uid)
|
||||
|
||||
|
||||
def _dept_id(user: dict) -> str:
|
||||
return str(user.get("dept_id") or user.get("create_dept_id") or "")
|
||||
|
||||
|
||||
class SupplementBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
lab_storage_code: str = Field(..., alias="labStorageCode")
|
||||
reception_source: str = Field(..., alias="receptionSource")
|
||||
sample_type_name: str = Field(..., alias="sampleTypeName")
|
||||
payload: Dict[str, Any] = Field(default_factory=dict)
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/lab-sample-process/list")
|
||||
def list_lab_sample_process(
|
||||
tabKey: str = Query(..., description="cell_hsc|donation_hsc|cell_msc|donation_msc"),
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=200),
|
||||
labStorageCode: Optional[str] = Query(None),
|
||||
motherName: Optional[str] = Query(None),
|
||||
createTimeStart: Optional[str] = Query(None),
|
||||
createTimeEnd: Optional[str] = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user=Depends(require_any_menu_code(*LIST_MENU_CODES)),
|
||||
):
|
||||
try:
|
||||
tenant_no = _tenant_no(db, user)
|
||||
items, total = svc.list_ledger(
|
||||
db,
|
||||
tab_key=tabKey,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
tenant_no=tenant_no,
|
||||
lab_storage_code=labStorageCode,
|
||||
mother_name=motherName,
|
||||
create_time_start=createTimeStart,
|
||||
create_time_end=createTimeEnd,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response(
|
||||
data={
|
||||
"list": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"pageSize": pageSize,
|
||||
"tabKey": tabKey,
|
||||
"tabMeta": ledger.TAB_META.get(tabKey),
|
||||
"supplementKeys": ledger.SUPPLEMENT_KEYS.get(tabKey, []),
|
||||
}
|
||||
)
|
||||
except PermissionError as e:
|
||||
return error_response(str(e), code=403)
|
||||
except ValueError as e:
|
||||
return error_response(str(e))
|
||||
except Exception as e:
|
||||
return error_response(f"查询失败:{e}")
|
||||
|
||||
|
||||
@router.get("/lab-sample-process/supplement")
|
||||
def get_supplement(
|
||||
labStorageCode: str = Query(...),
|
||||
db: Session = Depends(get_db),
|
||||
user=Depends(require_any_menu_code(*LIST_MENU_CODES)),
|
||||
):
|
||||
try:
|
||||
tenant_no = _tenant_no(db, user)
|
||||
data = svc.get_supplement(db, tenant_no=tenant_no, lab_storage_code=labStorageCode)
|
||||
return success_response(data=data or {"labStorageCode": labStorageCode, "payload": {}})
|
||||
except PermissionError as e:
|
||||
return error_response(str(e), code=403)
|
||||
except Exception as e:
|
||||
return error_response(f"查询补录失败:{e}")
|
||||
|
||||
|
||||
@router.put("/lab-sample-process/supplement")
|
||||
def save_supplement(
|
||||
body: SupplementBody,
|
||||
db: Session = Depends(get_db),
|
||||
user=Depends(require_any_menu_code(*SUPPLEMENT_MENU_CODES)),
|
||||
):
|
||||
try:
|
||||
tenant_no = _tenant_no(db, user)
|
||||
data = svc.upsert_supplement(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
user_id=_user_id(user),
|
||||
dept_id=_dept_id(user),
|
||||
lab_storage_code=body.lab_storage_code,
|
||||
reception_source=body.reception_source,
|
||||
sample_type_name=body.sample_type_name,
|
||||
payload=body.payload or {},
|
||||
remark=body.remark,
|
||||
)
|
||||
return success_response(data=data, message="补录已保存")
|
||||
except PermissionError as e:
|
||||
return error_response(str(e), code=403)
|
||||
except ValueError as e:
|
||||
return error_response(str(e))
|
||||
except Exception as e:
|
||||
return error_response(f"保存补录失败:{e}")
|
||||
@@ -0,0 +1,193 @@
|
||||
"""实验室样本处理数据 API"""
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
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_strict_any_menu_code
|
||||
from app.core.response import error_response, success_response
|
||||
from app.models.models import SysUser
|
||||
from app.services import lab_sample_processing as svc
|
||||
from app.services.lab_sample_processing_fields import (
|
||||
DATASETS,
|
||||
DATASET_LABELS,
|
||||
PERM_LIST,
|
||||
PERM_MANAGER,
|
||||
PERM_MARKET_EDIT,
|
||||
PERM_PRODUCTION_EDIT,
|
||||
PERM_QC_EDIT,
|
||||
schema_payload,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/web/admin/lab-sample-processing", tags=["实验室样本处理数据"])
|
||||
|
||||
# 列表/导出:有列表、主管或任一部门编辑权即可查看全部字段
|
||||
READ_MENUS = (
|
||||
PERM_LIST,
|
||||
PERM_MANAGER,
|
||||
PERM_MARKET_EDIT,
|
||||
PERM_PRODUCTION_EDIT,
|
||||
PERM_QC_EDIT,
|
||||
)
|
||||
# 更新:至少要有主管或某一部门编辑权(字段级 ACL 在服务内再收紧)
|
||||
WRITE_MENUS = (
|
||||
PERM_MANAGER,
|
||||
PERM_MARKET_EDIT,
|
||||
PERM_PRODUCTION_EDIT,
|
||||
PERM_QC_EDIT,
|
||||
)
|
||||
|
||||
|
||||
def _tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
row = db.query(SysUser).filter(SysUser.id == user_id, SysUser.del_flag == 0).first()
|
||||
if not row or not row.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return row.tenant_no
|
||||
|
||||
|
||||
def _ensure_dataset(dataset: str) -> Optional[str]:
|
||||
ds = (dataset or "").strip().lower()
|
||||
return ds if ds in DATASETS else None
|
||||
|
||||
|
||||
class UpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
payload: Dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
@router.get("/meta/{dataset}")
|
||||
async def get_meta(
|
||||
dataset: str,
|
||||
user: dict = Depends(require_strict_any_menu_code(*READ_MENUS)),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
ds = _ensure_dataset(dataset)
|
||||
if not ds:
|
||||
return error_response(400, "未知数据集")
|
||||
acl = svc.user_acl(db, user)
|
||||
return success_response(
|
||||
{
|
||||
"dataset": ds,
|
||||
"label": DATASET_LABELS.get(ds),
|
||||
"fields": schema_payload(ds),
|
||||
"acl": acl,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{dataset}/list")
|
||||
async def list_dataset(
|
||||
dataset: str,
|
||||
keyword: Optional[str] = Query(None),
|
||||
dateFrom: Optional[str] = Query(None),
|
||||
dateTo: Optional[str] = Query(None),
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(20, ge=1, le=200),
|
||||
user: dict = Depends(require_strict_any_menu_code(*READ_MENUS)),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
ds = _ensure_dataset(dataset)
|
||||
if not ds:
|
||||
return error_response(400, "未知数据集")
|
||||
tenant_no = _tenant_no(db, user)
|
||||
rows, total = svc.list_rows(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
dataset=ds,
|
||||
keyword=keyword,
|
||||
date_from=dateFrom,
|
||||
date_to=dateTo,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
)
|
||||
acl = svc.user_acl(db, user)
|
||||
return success_response(
|
||||
{
|
||||
"list": rows,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"pageSize": pageSize,
|
||||
"fields": schema_payload(ds),
|
||||
"acl": acl,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.put("/{dataset}/{sample_code}")
|
||||
async def update_dataset_row(
|
||||
dataset: str,
|
||||
sample_code: str,
|
||||
body: UpdateBody,
|
||||
user: dict = Depends(require_strict_any_menu_code(*WRITE_MENUS)),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
ds = _ensure_dataset(dataset)
|
||||
if not ds:
|
||||
return error_response(400, "未知数据集")
|
||||
tenant_no = _tenant_no(db, user)
|
||||
acl = svc.user_acl(db, user)
|
||||
editable = set(acl.get("editableDepts") or [])
|
||||
if not editable:
|
||||
return error_response(403, "无编辑权限")
|
||||
try:
|
||||
row = svc.update_row(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
dataset=ds,
|
||||
sample_code=sample_code,
|
||||
payload=body.payload or {},
|
||||
editable_depts=editable,
|
||||
operator_id=str(user.get("user_id") or ""),
|
||||
)
|
||||
except PermissionError as exc:
|
||||
return error_response(403, str(exc))
|
||||
except LookupError as exc:
|
||||
return error_response(404, str(exc))
|
||||
except ValueError as exc:
|
||||
return error_response(400, str(exc))
|
||||
return success_response(row)
|
||||
|
||||
|
||||
@router.get("/{dataset}/export")
|
||||
async def export_dataset(
|
||||
dataset: str,
|
||||
keyword: Optional[str] = Query(None),
|
||||
dateFrom: Optional[str] = Query(None),
|
||||
dateTo: Optional[str] = Query(None),
|
||||
user: dict = Depends(require_strict_any_menu_code(*READ_MENUS)),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
ds = _ensure_dataset(dataset)
|
||||
if not ds:
|
||||
return error_response(400, "未知数据集")
|
||||
tenant_no = _tenant_no(db, user)
|
||||
headers, body = svc.export_rows(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
dataset=ds,
|
||||
keyword=keyword,
|
||||
date_from=dateFrom,
|
||||
date_to=dateTo,
|
||||
)
|
||||
buf = io.StringIO()
|
||||
writer = csv.writer(buf)
|
||||
writer.writerow(headers)
|
||||
for row in body:
|
||||
writer.writerow(["" if v is None else v for v in row])
|
||||
raw = ("\ufeff" + buf.getvalue()).encode("utf-8")
|
||||
filename = f"lab-sample-{ds}.csv"
|
||||
return StreamingResponse(
|
||||
io.BytesIO(raw),
|
||||
media_type="text/csv; charset=utf-8",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||
)
|
||||
@@ -1,19 +1,28 @@
|
||||
"""样本储存证质检信息 API"""
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Dict, List, 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_any_menu_code, require_strict_any_menu_code
|
||||
from app.core.menu_guard import (
|
||||
require_any_menu_code,
|
||||
require_strict_any_menu_code,
|
||||
require_strict_menu_code,
|
||||
strict_user_has_any_menu_perm,
|
||||
strict_user_has_menu_perm,
|
||||
user_has_menu_perm,
|
||||
)
|
||||
from app.core.response import error_response, success_response
|
||||
from app.crud import sample_storage_cert_qc as svc
|
||||
from app.crud import sample_storage_cert_qc_acl as acl_svc
|
||||
from app.models.models import SysUser
|
||||
from app.services.sample_storage_cert_qc import ACL_CONFIG_MENU
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["储存证质检信息"])
|
||||
|
||||
# 市场 / 质检 / 生产三端共用读写(方案 A:完整表后写覆盖)
|
||||
# 市场 / 质检 / 生产三端共用读写
|
||||
READ_MENUS = (
|
||||
"biz:qcWorkOrder:list",
|
||||
"biz:myQcTask:list",
|
||||
@@ -41,6 +50,12 @@ def _get_current_user_id(user: dict) -> str:
|
||||
return str(user_id)
|
||||
|
||||
|
||||
def _can_configure_acl(db: Session, user: dict) -> bool:
|
||||
return user_has_menu_perm(db, user, ACL_CONFIG_MENU) or strict_user_has_menu_perm(
|
||||
db, user, ACL_CONFIG_MENU
|
||||
)
|
||||
|
||||
|
||||
class UpsertBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
@@ -48,6 +63,13 @@ class UpsertBody(BaseModel):
|
||||
qc_work_order_id: Optional[str] = Field(None, alias="qcWorkOrderId")
|
||||
|
||||
|
||||
class AclUpsertBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
field_keys: List[str] = Field(default_factory=list, alias="fieldKeys")
|
||||
user_ids: List[str] = Field(default_factory=list, alias="userIds")
|
||||
|
||||
|
||||
@router.get("/sample-storage-cert-qc/{sample_code}")
|
||||
async def get_sample_storage_cert_qc(
|
||||
sample_code: str,
|
||||
@@ -55,9 +77,19 @@ async def get_sample_storage_cert_qc(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
detail = svc.get_detail(db, tenant_no, sample_code)
|
||||
if detail is None:
|
||||
return error_response(404, "样本不存在")
|
||||
has_legacy_write = strict_user_has_any_menu_perm(db, user, WRITE_MENUS)
|
||||
svc.attach_acl_context(
|
||||
db,
|
||||
detail,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
has_legacy_write=has_legacy_write,
|
||||
can_configure_acl=_can_configure_acl(db, user),
|
||||
)
|
||||
return success_response(detail)
|
||||
|
||||
|
||||
@@ -70,6 +102,18 @@ async def put_sample_storage_cert_qc(
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
has_legacy_write = strict_user_has_any_menu_perm(db, user, WRITE_MENUS)
|
||||
# 先用空 sampleTypeKey 解析严格模式名单;类型在 upsert 内再收窄
|
||||
preview = svc.get_detail(db, tenant_no, sample_code)
|
||||
if preview is None:
|
||||
return error_response(404, "样本不存在")
|
||||
editable = acl_svc.resolve_editable_field_keys(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
sample_type_key=preview.get("sampleTypeKey"),
|
||||
has_legacy_write=has_legacy_write,
|
||||
)
|
||||
try:
|
||||
detail = svc.upsert(
|
||||
db,
|
||||
@@ -78,6 +122,54 @@ async def put_sample_storage_cert_qc(
|
||||
sample_code=sample_code,
|
||||
payload=body.payload,
|
||||
qc_work_order_id=body.qc_work_order_id,
|
||||
editable_field_keys=editable,
|
||||
)
|
||||
svc.attach_acl_context(
|
||||
db,
|
||||
detail,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
has_legacy_write=has_legacy_write,
|
||||
can_configure_acl=_can_configure_acl(db, user),
|
||||
)
|
||||
return success_response(detail, message="保存成功")
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.get("/sample-storage-cert-qc-acl/{scope}")
|
||||
async def get_sample_storage_cert_qc_acl(
|
||||
scope: str,
|
||||
user: dict = Depends(require_strict_menu_code(ACL_CONFIG_MENU, allow_super_admin=True)),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
detail = acl_svc.get_acl_detail(db, tenant_no, scope)
|
||||
return success_response(detail)
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/sample-storage-cert-qc-acl/{scope}")
|
||||
async def put_sample_storage_cert_qc_acl(
|
||||
scope: str,
|
||||
body: AclUpsertBody,
|
||||
user: dict = Depends(require_strict_menu_code(ACL_CONFIG_MENU, allow_super_admin=True)),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
try:
|
||||
detail = acl_svc.upsert_acl(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
scope=scope,
|
||||
field_keys=body.field_keys,
|
||||
user_ids=body.user_ids,
|
||||
)
|
||||
return success_response(detail, message="保存成功")
|
||||
except ValueError as e:
|
||||
|
||||
@@ -9,7 +9,19 @@ def unicode_ci(col):
|
||||
|
||||
|
||||
def eq_unicode(left, right):
|
||||
"""跨表字符串等值比较(JOIN / WHERE)时统一为 utf8mb4_unicode_ci。"""
|
||||
"""跨表字符串等值比较(JOIN / WHERE)时统一为 utf8mb4_unicode_ci。
|
||||
|
||||
列与列:两侧 collate。列与字面量:仅列侧 collate,避免连接 collation
|
||||
(常见 utf8mb4_general_ci)与列 collation(utf8mb4_unicode_ci)混用。
|
||||
"""
|
||||
left_is_str = isinstance(left, str)
|
||||
right_is_str = isinstance(right, str)
|
||||
if left_is_str and right_is_str:
|
||||
return left == right
|
||||
if left_is_str:
|
||||
return left == unicode_ci(right)
|
||||
if right_is_str:
|
||||
return unicode_ci(left) == right
|
||||
return unicode_ci(left) == unicode_ci(right)
|
||||
|
||||
|
||||
|
||||
@@ -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,
|
||||
@@ -2677,7 +2678,7 @@ def update_collection_protocol(
|
||||
next_status = protocol_status.strip()
|
||||
assert_protocol_status_transition(obj.protocol_status or "", next_status, kind="protocol")
|
||||
obj.protocol_status = next_status
|
||||
if next_status == "yzf" and from_status != "yzf":
|
||||
if next_status in ("yzf", "sdfq") and from_status not in ("yzf", "sdfq"):
|
||||
voided_now = True
|
||||
if next_status == "yzf" and void_time is not None:
|
||||
if void_type is None or not str(void_type).strip():
|
||||
|
||||
@@ -0,0 +1,764 @@
|
||||
"""实验室样本处理台账列表与补录 CRUD。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from sqlalchemy import and_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.data_scope import apply_data_scope
|
||||
from app.core.utils import generate_uuid
|
||||
from app.crud import sample_production_reception as prod_svc
|
||||
from app.models.models import (
|
||||
BizCellSampleType,
|
||||
BizCollectionHospital,
|
||||
BizCollectionProtocol,
|
||||
BizLabSampleProcessSupplement,
|
||||
BizProtocolCollectionInfo,
|
||||
BizProtocolPartyCustomer,
|
||||
BizProtocolSample,
|
||||
BizSampleProductionReception,
|
||||
BizSampleReception,
|
||||
BizSampleReceptionCheckResult,
|
||||
BizStorageReleaseReview,
|
||||
)
|
||||
from app.models.research_donation import (
|
||||
BizResearchDonation,
|
||||
BizResearchDonationCollection,
|
||||
BizResearchDonationParty,
|
||||
BizResearchDonationSample,
|
||||
)
|
||||
from app.services import lab_sample_process as ledger
|
||||
|
||||
|
||||
def _fmt_raw(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 _type_ids_by_name(db: Session, tenant_no: str, type_name: str) -> List[str]:
|
||||
rows = (
|
||||
db.query(BizCellSampleType.id)
|
||||
.filter(
|
||||
BizCellSampleType.tenant_no == tenant_no,
|
||||
BizCellSampleType.del_flag == 0,
|
||||
BizCellSampleType.type_name == type_name,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return [r.id for r in rows if r.id]
|
||||
|
||||
|
||||
def _get_supplement_map(
|
||||
db: Session, tenant_no: str, codes: List[str]
|
||||
) -> Dict[str, Dict[str, Any]]:
|
||||
codes = [c for c in {(x or "").strip() for x in codes} if c]
|
||||
if not codes:
|
||||
return {}
|
||||
rows = (
|
||||
db.query(BizLabSampleProcessSupplement)
|
||||
.filter(
|
||||
BizLabSampleProcessSupplement.tenant_no == tenant_no,
|
||||
BizLabSampleProcessSupplement.del_flag == 0,
|
||||
BizLabSampleProcessSupplement.lab_storage_code.in_(codes),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
out: Dict[str, Dict[str, Any]] = {}
|
||||
for row in rows:
|
||||
out[row.lab_storage_code] = {
|
||||
"id": row.id,
|
||||
"payload": ledger.parse_payload(row.payload),
|
||||
"remark": row.remark or "",
|
||||
"updateTime": _fmt_raw(row.update_time),
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def get_supplement(
|
||||
db: Session, *, tenant_no: str, lab_storage_code: str
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
code = (lab_storage_code or "").strip()
|
||||
if not code:
|
||||
return None
|
||||
row = (
|
||||
db.query(BizLabSampleProcessSupplement)
|
||||
.filter(
|
||||
BizLabSampleProcessSupplement.tenant_no == tenant_no,
|
||||
BizLabSampleProcessSupplement.lab_storage_code == code,
|
||||
BizLabSampleProcessSupplement.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not row:
|
||||
return None
|
||||
return {
|
||||
"id": row.id,
|
||||
"labStorageCode": row.lab_storage_code,
|
||||
"receptionSource": row.reception_source,
|
||||
"sampleTypeName": row.sample_type_name or "",
|
||||
"payload": ledger.parse_payload(row.payload),
|
||||
"remark": row.remark or "",
|
||||
"createTime": _fmt_raw(row.create_time),
|
||||
"updateTime": _fmt_raw(row.update_time),
|
||||
}
|
||||
|
||||
|
||||
def upsert_supplement(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
user_id: str,
|
||||
dept_id: str,
|
||||
lab_storage_code: str,
|
||||
reception_source: str,
|
||||
sample_type_name: str,
|
||||
payload: Dict[str, Any],
|
||||
remark: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
code = (lab_storage_code or "").strip()
|
||||
if not code:
|
||||
raise ValueError("实验室入库编码不能为空")
|
||||
src = (reception_source or "").strip() or "cell_storage"
|
||||
if src not in ("cell_storage", "research_donation"):
|
||||
raise ValueError("来源类型无效")
|
||||
type_name = (sample_type_name or "").strip()
|
||||
clean_payload = {
|
||||
str(k): ("" if v is None else str(v).strip())
|
||||
for k, v in (payload or {}).items()
|
||||
if str(k).strip()
|
||||
}
|
||||
|
||||
row = (
|
||||
db.query(BizLabSampleProcessSupplement)
|
||||
.filter(
|
||||
BizLabSampleProcessSupplement.tenant_no == tenant_no,
|
||||
BizLabSampleProcessSupplement.lab_storage_code == code,
|
||||
BizLabSampleProcessSupplement.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
now = datetime.now()
|
||||
if row:
|
||||
row.reception_source = src
|
||||
row.sample_type_name = type_name or row.sample_type_name
|
||||
row.payload = ledger.dumps_payload(clean_payload)
|
||||
if remark is not None:
|
||||
row.remark = (remark or "").strip() or None
|
||||
row.update_by = user_id
|
||||
row.update_time = now
|
||||
else:
|
||||
row = BizLabSampleProcessSupplement(
|
||||
id=generate_uuid(),
|
||||
lab_storage_code=code,
|
||||
reception_source=src,
|
||||
sample_type_name=type_name or None,
|
||||
payload=ledger.dumps_payload(clean_payload),
|
||||
tenant_no=tenant_no,
|
||||
remark=(remark or "").strip() or None,
|
||||
create_by=user_id,
|
||||
create_dept_id=dept_id or "",
|
||||
create_time=now,
|
||||
update_by=user_id,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
db.add(row)
|
||||
# 同步到新模块补充表/生产接收,保证实验室样本处理数据联动
|
||||
from app.services.lab_sample_processing import sync_legacy_supplement_to_processing
|
||||
|
||||
sync_legacy_supplement_to_processing(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
lab_storage_code=code,
|
||||
sample_type_name=type_name,
|
||||
payload=clean_payload,
|
||||
operator_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return get_supplement(db, tenant_no=tenant_no, lab_storage_code=code) or {}
|
||||
|
||||
|
||||
def _check_flag_map(db: Session, tenant_no: str, reception_ids: List[str]) -> Dict[str, Dict[str, bool]]:
|
||||
ids = [i for i in reception_ids if i]
|
||||
if not ids:
|
||||
return {}
|
||||
rows = (
|
||||
db.query(BizSampleReceptionCheckResult)
|
||||
.filter(
|
||||
BizSampleReceptionCheckResult.tenant_no == tenant_no,
|
||||
BizSampleReceptionCheckResult.del_flag == 0,
|
||||
BizSampleReceptionCheckResult.reception_id.in_(ids),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
out: Dict[str, Dict[str, bool]] = {}
|
||||
for r in rows:
|
||||
bucket = out.setdefault(r.reception_id, {})
|
||||
name = (r.item_name or "").strip()
|
||||
if name:
|
||||
bucket[name] = bool(r.checked)
|
||||
return out
|
||||
|
||||
|
||||
def _storage_status_map(db: Session, tenant_no: str, sample_codes: List[str]) -> Dict[str, str]:
|
||||
codes = [c for c in sample_codes if c]
|
||||
if not codes:
|
||||
return {}
|
||||
rows = (
|
||||
db.query(BizStorageReleaseReview.sample_code, BizStorageReleaseReview.storage_status)
|
||||
.filter(
|
||||
BizStorageReleaseReview.tenant_no == tenant_no,
|
||||
BizStorageReleaseReview.del_flag == 0,
|
||||
BizStorageReleaseReview.sample_code.in_(codes),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
labels = {"drk": "待入库", "yrk": "已入库"}
|
||||
return {r.sample_code: labels.get(r.storage_status or "", r.storage_status or "") for r in rows}
|
||||
|
||||
|
||||
def _hospital_name_map(db: Session, hospital_ids: List[str]) -> Dict[str, str]:
|
||||
ids = [i for i in hospital_ids if i]
|
||||
if not ids:
|
||||
return {}
|
||||
rows = (
|
||||
db.query(BizCollectionHospital.id, BizCollectionHospital.hospital_name)
|
||||
.filter(BizCollectionHospital.id.in_(ids), BizCollectionHospital.del_flag == 0)
|
||||
.all()
|
||||
)
|
||||
return {r.id: r.hospital_name or "" for r in rows}
|
||||
|
||||
|
||||
def _build_cell_system(
|
||||
*,
|
||||
tab_key: str,
|
||||
rec: BizSampleReception,
|
||||
sample: BizProtocolSample,
|
||||
party: Optional[BizProtocolPartyCustomer],
|
||||
coll: Optional[BizProtocolCollectionInfo],
|
||||
protocol: Optional[BizCollectionProtocol],
|
||||
prod: Optional[Dict[str, Any]],
|
||||
hospital_name: str,
|
||||
check_flags: Dict[str, bool],
|
||||
storage_status: str,
|
||||
qc_mother: Dict[str, str],
|
||||
qc_process: Dict[str, str],
|
||||
) -> Dict[str, Any]:
|
||||
prod = prod or {}
|
||||
maternal_time = coll.maternal_blood_collect_time if coll else None
|
||||
clear_flag = None
|
||||
for name, checked in check_flags.items():
|
||||
if "标识清晰" in name or "样本信息正确" in name:
|
||||
clear_flag = checked
|
||||
break
|
||||
|
||||
base: Dict[str, Any] = {
|
||||
"receptionId": rec.id,
|
||||
"sampleCode": (rec.sample_code or sample.sample_code or "").strip(),
|
||||
"labStorageCode": (rec.lab_storage_code or "").strip(),
|
||||
"motherName": (party.mother_name if party else "") or "",
|
||||
"collectionTime": ledger.format_cn_datetime(coll.sample_collect_time if coll else None),
|
||||
"collectionTimeRaw": _fmt_raw(coll.sample_collect_time if coll else None),
|
||||
"hospitalName": hospital_name,
|
||||
"receptionTime": ledger.format_cn_datetime(rec.reception_time),
|
||||
"receptionTimeRaw": _fmt_raw(rec.reception_time),
|
||||
"receiveTemperature": rec.receive_temperature or "",
|
||||
"handlerName": rec.handler_name or "",
|
||||
"remarkReception": rec.remark or "",
|
||||
"createTime": ledger.format_cn_datetime(rec.create_time),
|
||||
"createTimeRaw": _fmt_raw(rec.create_time),
|
||||
"operatorName": prod.get("handlerName") or "",
|
||||
"remarkProcess": prod.get("remark") or "",
|
||||
"storageStatus": storage_status,
|
||||
}
|
||||
|
||||
if tab_key == "cell_hsc":
|
||||
base.update(
|
||||
{
|
||||
"cellCode": (rec.lab_storage_code or "").strip(),
|
||||
"hasMaternalBlood": "是" if maternal_time else "否",
|
||||
"remeasureMaternalBlood": "",
|
||||
"consentForm": ledger.yes_no_from_urls(
|
||||
protocol.consent_form_urls if protocol else None
|
||||
),
|
||||
"transportPackingList": "",
|
||||
"cordBloodReceiveConfirm": "",
|
||||
"healthSurvey": ledger.yes_no_from_urls(
|
||||
protocol.health_survey_form_urls if protocol else None
|
||||
),
|
||||
"labelClear": ledger.yes_no_from_bool(clear_flag) if clear_flag is not None else "",
|
||||
"receiveCheckText": "",
|
||||
"originalBloodWeightG": prod.get("originalBloodWeightG"),
|
||||
"hesVolumeMl": prod.get("hesVolumeMl"),
|
||||
"bloodType": prod.get("bloodType") or "",
|
||||
"infectiousFourTestLabel": prod.get("infectiousFourTestResultLabel")
|
||||
or ledger.infectious_label(prod.get("infectiousFourTestResult")),
|
||||
"infectiousFourExternal": "",
|
||||
"preEnrichNucleatedCount": "",
|
||||
"enrichedBloodWeightG": prod.get("enrichedBloodWeightG"),
|
||||
"postEnrichNucleatedCount": "",
|
||||
"cryopreservationVolumeMl": prod.get("cryopreservationVolumeMl"),
|
||||
"cd34Count1e4": "",
|
||||
}
|
||||
)
|
||||
else: # cell_msc
|
||||
base.update(
|
||||
{
|
||||
"labFlowCode": (rec.lab_storage_code or "").strip(),
|
||||
"cordCollectTime": ledger.format_cn_datetime(
|
||||
coll.sample_collect_time if coll else None
|
||||
),
|
||||
"transportTempC": rec.receive_temperature or "",
|
||||
"cordReceiveTime": ledger.format_cn_datetime(rec.reception_time),
|
||||
"inoculationAmount": prod.get("inoculationAmount") or "",
|
||||
"cryopreservationTime": ledger.format_cn_datetime(prod.get("cryopreservationTime")),
|
||||
"storageTotalTubes": prod.get("storageTotalTubes"),
|
||||
"availableCellCount1e7": prod.get("availableCellCount1e7"),
|
||||
"remark": rec.remark or prod.get("remark") or "",
|
||||
"storageDateP2": "",
|
||||
}
|
||||
)
|
||||
base.update(qc_process)
|
||||
base.update(qc_mother)
|
||||
return base
|
||||
|
||||
|
||||
def _build_donation_system(
|
||||
*,
|
||||
tab_key: str,
|
||||
rec: BizSampleReception,
|
||||
sample: BizResearchDonationSample,
|
||||
party: Optional[BizResearchDonationParty],
|
||||
coll: Optional[BizResearchDonationCollection],
|
||||
prod: Optional[Dict[str, Any]],
|
||||
storage_status: str,
|
||||
qc_mother: Dict[str, str],
|
||||
qc_process: Dict[str, str],
|
||||
) -> Dict[str, Any]:
|
||||
prod = prod or {}
|
||||
base: Dict[str, Any] = {
|
||||
"receptionId": rec.id,
|
||||
"sampleCode": (rec.sample_code or sample.sample_code or "").strip(),
|
||||
"labStorageCode": (rec.lab_storage_code or "").strip(),
|
||||
"motherName": (party.mother_name if party else "") or "",
|
||||
"receptionTime": ledger.format_cn_datetime(rec.reception_time),
|
||||
"receptionTimeRaw": _fmt_raw(rec.reception_time),
|
||||
"receiveTemperature": rec.receive_temperature or "",
|
||||
"handlerName": rec.handler_name or "",
|
||||
"remarkReception": rec.remark or "",
|
||||
"createTime": ledger.format_cn_datetime(rec.create_time),
|
||||
"createTimeRaw": _fmt_raw(rec.create_time),
|
||||
"operatorName": prod.get("handlerName") or "",
|
||||
"remarkProcess": prod.get("remark") or "",
|
||||
"storageStatus": storage_status,
|
||||
}
|
||||
if tab_key == "donation_hsc":
|
||||
base.update(
|
||||
{
|
||||
"cellCode": (rec.lab_storage_code or "").strip(),
|
||||
"labMaterialCode": "",
|
||||
"inboundCode": (rec.lab_storage_code or "").strip(),
|
||||
"discardReason": "",
|
||||
"receiveCheckText": "",
|
||||
"originalBloodVolumeMl": prod.get("originalBloodVolumeMl"),
|
||||
"nucleatedCellCount1e8": prod.get("nucleatedCellCount1e8"),
|
||||
"preOpNucleatedCount": "",
|
||||
"infectiousFourTestLabel": prod.get("infectiousFourTestResultLabel")
|
||||
or ledger.infectious_label(prod.get("infectiousFourTestResult")),
|
||||
}
|
||||
)
|
||||
# 科研捐赠母血 5 项(不含核酸)
|
||||
for k in (
|
||||
"motherHbsag",
|
||||
"motherAntiHcv",
|
||||
"motherAntiTp",
|
||||
"motherAntiHiv",
|
||||
"motherCmvIgm",
|
||||
):
|
||||
if qc_mother.get(k):
|
||||
base[k] = qc_mother[k]
|
||||
else:
|
||||
base.update(
|
||||
{
|
||||
"labFlowCode": (rec.lab_storage_code or "").strip(),
|
||||
"cordCollectTime": ledger.format_cn_datetime(
|
||||
coll.sample_collect_time if coll else None
|
||||
),
|
||||
"transportTempC": rec.receive_temperature or "",
|
||||
"cordReceiveTime": ledger.format_cn_datetime(rec.reception_time),
|
||||
"inoculationAmount": prod.get("inoculationAmount") or "",
|
||||
"cryopreservationTime": ledger.format_cn_datetime(prod.get("cryopreservationTime")),
|
||||
"storageTotalTubes": prod.get("storageTotalTubes"),
|
||||
"availableCellCount1e7": prod.get("availableCellCount1e7"),
|
||||
"remark": rec.remark or prod.get("remark") or "",
|
||||
"storageDateP2": "",
|
||||
}
|
||||
)
|
||||
base.update(qc_process)
|
||||
base.update(qc_mother)
|
||||
return base
|
||||
|
||||
|
||||
def list_ledger(
|
||||
db: Session,
|
||||
*,
|
||||
tab_key: str,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
tenant_no: str,
|
||||
lab_storage_code: Optional[str] = None,
|
||||
mother_name: Optional[str] = None,
|
||||
create_time_start: Optional[str] = None,
|
||||
create_time_end: Optional[str] = None,
|
||||
user_info=None,
|
||||
) -> Tuple[List[Dict[str, Any]], int]:
|
||||
meta = ledger.TAB_META.get(tab_key)
|
||||
if not meta:
|
||||
raise ValueError("无效的 Tab")
|
||||
source = meta["source"]
|
||||
type_name = meta["sampleTypeName"]
|
||||
type_ids = _type_ids_by_name(db, tenant_no, type_name)
|
||||
if not type_ids:
|
||||
return [], 0
|
||||
|
||||
q = db.query(BizSampleReception).filter(
|
||||
BizSampleReception.tenant_no == tenant_no,
|
||||
BizSampleReception.del_flag == 0,
|
||||
BizSampleReception.reception_source == source,
|
||||
BizSampleReception.lab_storage_code.isnot(None),
|
||||
BizSampleReception.lab_storage_code != "",
|
||||
BizSampleReception.accept_conclusion == "js",
|
||||
)
|
||||
code_kw = (lab_storage_code or "").strip()
|
||||
if code_kw:
|
||||
q = q.filter(BizSampleReception.lab_storage_code.like(f"%{code_kw}%"))
|
||||
start = _normalize_bound(create_time_start)
|
||||
end = _normalize_bound(create_time_end, end_of_day=True)
|
||||
if start:
|
||||
q = q.filter(BizSampleReception.create_time >= start)
|
||||
if end:
|
||||
q = q.filter(BizSampleReception.create_time <= end)
|
||||
if user_info:
|
||||
q = apply_data_scope(q, BizSampleReception, user_info, db, tenant_no)
|
||||
|
||||
mother_kw = (mother_name or "").strip()
|
||||
|
||||
# 按来源限制样本类型,并可选母亲姓名
|
||||
if source == "cell_storage":
|
||||
sample_q = (
|
||||
db.query(BizProtocolSample.id)
|
||||
.join(
|
||||
BizCollectionProtocol,
|
||||
and_(
|
||||
BizCollectionProtocol.id == BizProtocolSample.collection_protocol_id,
|
||||
BizCollectionProtocol.del_flag == 0,
|
||||
BizCollectionProtocol.tenant_no == tenant_no,
|
||||
),
|
||||
)
|
||||
.filter(
|
||||
BizProtocolSample.tenant_no == tenant_no,
|
||||
BizProtocolSample.del_flag == 0,
|
||||
BizProtocolSample.sample_type_id.in_(type_ids),
|
||||
)
|
||||
)
|
||||
if mother_kw:
|
||||
sample_q = sample_q.join(
|
||||
BizProtocolPartyCustomer,
|
||||
and_(
|
||||
BizProtocolPartyCustomer.collection_protocol_id
|
||||
== BizProtocolSample.collection_protocol_id,
|
||||
BizProtocolPartyCustomer.del_flag == 0,
|
||||
BizProtocolPartyCustomer.tenant_no == tenant_no,
|
||||
),
|
||||
).filter(BizProtocolPartyCustomer.mother_name.like(f"%{mother_kw}%"))
|
||||
sample_ids = [r.id for r in sample_q.all()]
|
||||
if not sample_ids:
|
||||
return [], 0
|
||||
q = q.filter(BizSampleReception.protocol_sample_id.in_(sample_ids))
|
||||
else:
|
||||
sample_q = (
|
||||
db.query(BizResearchDonationSample.id)
|
||||
.join(
|
||||
BizResearchDonation,
|
||||
and_(
|
||||
BizResearchDonation.id == BizResearchDonationSample.research_donation_id,
|
||||
BizResearchDonation.del_flag == 0,
|
||||
BizResearchDonation.tenant_no == tenant_no,
|
||||
),
|
||||
)
|
||||
.filter(
|
||||
BizResearchDonationSample.tenant_no == tenant_no,
|
||||
BizResearchDonationSample.del_flag == 0,
|
||||
BizResearchDonationSample.sample_type_id.in_(type_ids),
|
||||
)
|
||||
)
|
||||
if mother_kw:
|
||||
sample_q = sample_q.join(
|
||||
BizResearchDonationParty,
|
||||
and_(
|
||||
BizResearchDonationParty.research_donation_id
|
||||
== BizResearchDonationSample.research_donation_id,
|
||||
BizResearchDonationParty.del_flag == 0,
|
||||
BizResearchDonationParty.tenant_no == tenant_no,
|
||||
),
|
||||
).filter(BizResearchDonationParty.mother_name.like(f"%{mother_kw}%"))
|
||||
sample_ids = [r.id for r in sample_q.all()]
|
||||
if not sample_ids:
|
||||
return [], 0
|
||||
q = q.filter(BizSampleReception.donation_sample_id.in_(sample_ids))
|
||||
|
||||
total = q.count()
|
||||
page = max(1, int(page or 1))
|
||||
page_size = min(max(1, int(page_size or 10)), 200)
|
||||
receptions = (
|
||||
q.order_by(BizSampleReception.create_time.desc(), BizSampleReception.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
if not receptions:
|
||||
return [], int(total)
|
||||
|
||||
reception_ids = [r.id for r in receptions]
|
||||
codes = [(r.lab_storage_code or "").strip() for r in receptions]
|
||||
sample_codes = [(r.sample_code or "").strip() for r in receptions]
|
||||
prod_map = _prod_map(db, tenant_no, reception_ids)
|
||||
check_map = _check_flag_map(db, tenant_no, reception_ids)
|
||||
storage_map = _storage_status_map(db, tenant_no, [c for c in sample_codes if c])
|
||||
sup_map = _get_supplement_map(db, tenant_no, codes)
|
||||
|
||||
items: List[Dict[str, Any]] = []
|
||||
if source == "cell_storage":
|
||||
items = _assemble_cell_rows(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
tab_key=tab_key,
|
||||
receptions=receptions,
|
||||
prod_map=prod_map,
|
||||
check_map=check_map,
|
||||
storage_map=storage_map,
|
||||
sup_map=sup_map,
|
||||
)
|
||||
else:
|
||||
items = _assemble_donation_rows(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
tab_key=tab_key,
|
||||
receptions=receptions,
|
||||
prod_map=prod_map,
|
||||
storage_map=storage_map,
|
||||
sup_map=sup_map,
|
||||
)
|
||||
return items, int(total)
|
||||
|
||||
|
||||
def _prod_map(db: Session, tenant_no: str, reception_ids: List[str]) -> Dict[str, Dict[str, Any]]:
|
||||
rows = (
|
||||
db.query(BizSampleProductionReception)
|
||||
.filter(
|
||||
BizSampleProductionReception.tenant_no == tenant_no,
|
||||
BizSampleProductionReception.del_flag == 0,
|
||||
BizSampleProductionReception.reception_id.in_(reception_ids),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return {r.reception_id: prod_svc._row_to_dict(r) for r in rows}
|
||||
|
||||
|
||||
def _assemble_cell_rows(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
tab_key: str,
|
||||
receptions: List[BizSampleReception],
|
||||
prod_map: Dict[str, Dict[str, Any]],
|
||||
check_map: Dict[str, Dict[str, bool]],
|
||||
storage_map: Dict[str, str],
|
||||
sup_map: Dict[str, Dict[str, Any]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
sample_ids = [r.protocol_sample_id for r in receptions if r.protocol_sample_id]
|
||||
samples = (
|
||||
db.query(BizProtocolSample)
|
||||
.filter(
|
||||
BizProtocolSample.tenant_no == tenant_no,
|
||||
BizProtocolSample.del_flag == 0,
|
||||
BizProtocolSample.id.in_(sample_ids),
|
||||
)
|
||||
.all()
|
||||
if sample_ids
|
||||
else []
|
||||
)
|
||||
sample_map = {s.id: s for s in samples}
|
||||
protocol_ids = list({s.collection_protocol_id for s in samples if s.collection_protocol_id})
|
||||
parties = (
|
||||
db.query(BizProtocolPartyCustomer)
|
||||
.filter(
|
||||
BizProtocolPartyCustomer.tenant_no == tenant_no,
|
||||
BizProtocolPartyCustomer.del_flag == 0,
|
||||
BizProtocolPartyCustomer.collection_protocol_id.in_(protocol_ids),
|
||||
)
|
||||
.all()
|
||||
if protocol_ids
|
||||
else []
|
||||
)
|
||||
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()
|
||||
if protocol_ids
|
||||
else []
|
||||
)
|
||||
coll_map = {c.collection_protocol_id: c for c in colls}
|
||||
protocols = (
|
||||
db.query(BizCollectionProtocol)
|
||||
.filter(
|
||||
BizCollectionProtocol.tenant_no == tenant_no,
|
||||
BizCollectionProtocol.del_flag == 0,
|
||||
BizCollectionProtocol.id.in_(protocol_ids),
|
||||
)
|
||||
.all()
|
||||
if protocol_ids
|
||||
else []
|
||||
)
|
||||
protocol_map = {p.id: p for p in protocols}
|
||||
hospital_ids = [c.hospital_id for c in colls if c.hospital_id]
|
||||
hospital_map = _hospital_name_map(db, hospital_ids)
|
||||
|
||||
out: List[Dict[str, Any]] = []
|
||||
for rec in receptions:
|
||||
sample = sample_map.get(rec.protocol_sample_id or "")
|
||||
if not sample:
|
||||
continue
|
||||
pid = sample.collection_protocol_id
|
||||
sample_code = (rec.sample_code or sample.sample_code or "").strip()
|
||||
tasks = ledger.load_qc_tasks_for_sample(db, tenant_no, sample_code)
|
||||
qc_mother = ledger.extract_mother_blood(tasks, include_nucleic=True)
|
||||
qc_process = ledger.extract_process_tests(tasks)
|
||||
system = _build_cell_system(
|
||||
tab_key=tab_key,
|
||||
rec=rec,
|
||||
sample=sample,
|
||||
party=party_map.get(pid),
|
||||
coll=coll_map.get(pid),
|
||||
protocol=protocol_map.get(pid),
|
||||
prod=prod_map.get(rec.id),
|
||||
hospital_name=hospital_map.get((coll_map.get(pid).hospital_id if coll_map.get(pid) else "") or "", ""),
|
||||
check_flags=check_map.get(rec.id, {}),
|
||||
storage_status=storage_map.get(sample_code, ""),
|
||||
qc_mother=qc_mother,
|
||||
qc_process=qc_process,
|
||||
)
|
||||
lab_code = system.get("labStorageCode") or ""
|
||||
merged = ledger.merge_row(
|
||||
tab_key=tab_key,
|
||||
system_values=system,
|
||||
supplement=(sup_map.get(lab_code) or {}).get("payload"),
|
||||
)
|
||||
merged["supplementId"] = (sup_map.get(lab_code) or {}).get("id") or ""
|
||||
merged["hasSupplement"] = bool((sup_map.get(lab_code) or {}).get("payload"))
|
||||
out.append(merged)
|
||||
return out
|
||||
|
||||
|
||||
def _assemble_donation_rows(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
tab_key: str,
|
||||
receptions: List[BizSampleReception],
|
||||
prod_map: Dict[str, Dict[str, Any]],
|
||||
storage_map: Dict[str, str],
|
||||
sup_map: Dict[str, Dict[str, Any]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
sample_ids = [r.donation_sample_id for r in receptions if r.donation_sample_id]
|
||||
samples = (
|
||||
db.query(BizResearchDonationSample)
|
||||
.filter(
|
||||
BizResearchDonationSample.tenant_no == tenant_no,
|
||||
BizResearchDonationSample.del_flag == 0,
|
||||
BizResearchDonationSample.id.in_(sample_ids),
|
||||
)
|
||||
.all()
|
||||
if sample_ids
|
||||
else []
|
||||
)
|
||||
sample_map = {s.id: s for s in samples}
|
||||
donation_ids = list({s.research_donation_id for s in samples if s.research_donation_id})
|
||||
parties = (
|
||||
db.query(BizResearchDonationParty)
|
||||
.filter(
|
||||
BizResearchDonationParty.tenant_no == tenant_no,
|
||||
BizResearchDonationParty.del_flag == 0,
|
||||
BizResearchDonationParty.research_donation_id.in_(donation_ids),
|
||||
)
|
||||
.all()
|
||||
if donation_ids
|
||||
else []
|
||||
)
|
||||
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()
|
||||
if donation_ids
|
||||
else []
|
||||
)
|
||||
coll_map = {c.research_donation_id: c for c in colls}
|
||||
|
||||
out: List[Dict[str, Any]] = []
|
||||
for rec in receptions:
|
||||
sample = sample_map.get(rec.donation_sample_id or "")
|
||||
if not sample:
|
||||
continue
|
||||
did = sample.research_donation_id
|
||||
sample_code = (rec.sample_code or sample.sample_code or "").strip()
|
||||
tasks = ledger.load_qc_tasks_for_sample(db, tenant_no, sample_code)
|
||||
qc_mother = ledger.extract_mother_blood(tasks, include_nucleic=True)
|
||||
qc_process = ledger.extract_process_tests(tasks)
|
||||
system = _build_donation_system(
|
||||
tab_key=tab_key,
|
||||
rec=rec,
|
||||
sample=sample,
|
||||
party=party_map.get(did),
|
||||
coll=coll_map.get(did),
|
||||
prod=prod_map.get(rec.id),
|
||||
storage_status=storage_map.get(sample_code, ""),
|
||||
qc_mother=qc_mother,
|
||||
qc_process=qc_process,
|
||||
)
|
||||
lab_code = system.get("labStorageCode") or ""
|
||||
merged = ledger.merge_row(
|
||||
tab_key=tab_key,
|
||||
system_values=system,
|
||||
supplement=(sup_map.get(lab_code) or {}).get("payload"),
|
||||
)
|
||||
merged["supplementId"] = (sup_map.get(lab_code) or {}).get("id") or ""
|
||||
merged["hasSupplement"] = bool((sup_map.get(lab_code) or {}).get("payload"))
|
||||
out.append(merged)
|
||||
return out
|
||||
@@ -576,12 +576,14 @@ def attach_presign_ledger_fields(
|
||||
}
|
||||
times_by_order: Dict[str, List[str]] = {}
|
||||
if order_ids:
|
||||
# 与 confirmedDepositAmount 一致:仅已确认到账(yjf)计入刷卡时间
|
||||
transfers = (
|
||||
db.query(BizPresignTransfer)
|
||||
.filter(
|
||||
BizPresignTransfer.presign_order_id.in_(order_ids),
|
||||
BizPresignTransfer.tenant_no == tenant_no,
|
||||
BizPresignTransfer.del_flag == 0,
|
||||
BizPresignTransfer.pay_status == "yjf",
|
||||
)
|
||||
.order_by(
|
||||
BizPresignTransfer.transfer_time.asc(),
|
||||
|
||||
@@ -94,7 +94,7 @@ def apply_planned_start_time_step_filter(
|
||||
planned_start_time_end: Optional[str] = None,
|
||||
mine_user_id: Optional[str] = None,
|
||||
):
|
||||
"""按活跃工单/任务下未完成工艺步骤的计划开始时间过滤。"""
|
||||
"""按工艺步骤计划开始时间过滤;工单/任务/步骤状态由外层检索条件组合控制。"""
|
||||
start = (planned_start_time_start or "").strip()
|
||||
end = (planned_start_time_end or "").strip()
|
||||
if not start and not end:
|
||||
@@ -104,15 +104,9 @@ def apply_planned_start_time_step_filter(
|
||||
BizProductionTaskStep.del_flag == 0,
|
||||
BizProductionTaskStep.tenant_no == tenant_no,
|
||||
BizProductionTaskStep.planned_start_time.isnot(None),
|
||||
BizProductionTaskStep.step_status != "ywc",
|
||||
BizProductionTask.id == BizProductionTaskStep.task_id,
|
||||
BizProductionTask.del_flag == 0,
|
||||
BizProductionTask.tenant_no == tenant_no,
|
||||
BizProductionTask.task_status.in_(("dpz", "jxz")),
|
||||
BizProductionWorkOrder.id == BizProductionTask.work_order_id,
|
||||
BizProductionWorkOrder.del_flag == 0,
|
||||
BizProductionWorkOrder.tenant_no == tenant_no,
|
||||
BizProductionWorkOrder.work_order_status.in_(("dpz", "jxz")),
|
||||
work_order_id_column == BizProductionTask.work_order_id,
|
||||
]
|
||||
if start:
|
||||
|
||||
@@ -49,6 +49,7 @@ from app.models.models import (
|
||||
BizPilotInfusionSchedule,
|
||||
BizPilotInfusionScheduleProduct,
|
||||
BizPilotPatient,
|
||||
BizProtocolCollectionInfo,
|
||||
BizProtocolPartyCustomer,
|
||||
BizProtocolSample,
|
||||
BizProductionTask,
|
||||
@@ -69,6 +70,7 @@ from app.models.models import (
|
||||
from app.models.qc_param import BizQcTaskResult
|
||||
from app.models.research_donation import (
|
||||
BizResearchDonation,
|
||||
BizResearchDonationCollection,
|
||||
BizResearchDonationParty,
|
||||
BizResearchDonationSample,
|
||||
)
|
||||
@@ -677,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:
|
||||
@@ -695,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 = (
|
||||
@@ -704,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 = (
|
||||
@@ -808,12 +811,39 @@ def _enrich_work_order_list_items(
|
||||
party.mother_name or "",
|
||||
party.newborn_name or "",
|
||||
)
|
||||
cell_maternal_map: Dict[str, str] = {}
|
||||
if cell_proto_ids:
|
||||
for coll in (
|
||||
db.query(BizProtocolCollectionInfo)
|
||||
.filter(
|
||||
BizProtocolCollectionInfo.collection_protocol_id.in_(cell_proto_ids),
|
||||
BizProtocolCollectionInfo.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
):
|
||||
cell_maternal_map[coll.collection_protocol_id] = _fmt_dt(
|
||||
coll.maternal_blood_collect_time
|
||||
)
|
||||
donation_maternal_map: Dict[str, str] = {}
|
||||
if donation_ids:
|
||||
for coll in (
|
||||
db.query(BizResearchDonationCollection)
|
||||
.filter(
|
||||
BizResearchDonationCollection.research_donation_id.in_(donation_ids),
|
||||
BizResearchDonationCollection.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
):
|
||||
donation_maternal_map[coll.research_donation_id] = _fmt_dt(
|
||||
coll.maternal_blood_collect_time
|
||||
)
|
||||
for item in items:
|
||||
if item.get("workOrderType") == "temporary":
|
||||
item["receptionSource"] = ""
|
||||
item["receptionSourceLabel"] = ""
|
||||
item["motherName"] = ""
|
||||
item["newbornName"] = ""
|
||||
item["maternalBloodCollectTime"] = ""
|
||||
continue
|
||||
rec = _resolve_reception(item)
|
||||
source = _effective_reception_source(item, rec)
|
||||
@@ -826,6 +856,7 @@ def _enrich_work_order_list_items(
|
||||
_mother, _newborn = donation_party_map.get(_did or "", ("", ""))
|
||||
item["motherName"] = _mother
|
||||
item["newbornName"] = _newborn
|
||||
item["maternalBloodCollectTime"] = donation_maternal_map.get(_did or "", "") or ""
|
||||
else:
|
||||
_pid = (
|
||||
(getattr(rec, "collection_protocol_id", None) if rec else None) or ""
|
||||
@@ -833,11 +864,35 @@ def _enrich_work_order_list_items(
|
||||
_mother, _newborn = cell_party_map.get(_pid or "", ("", ""))
|
||||
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 ""
|
||||
@@ -858,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()
|
||||
@@ -1140,6 +1196,7 @@ def _wo_to_dict(
|
||||
"receptionTime": "",
|
||||
"handlerName": "",
|
||||
"sampleTypeName": "",
|
||||
"maternalBloodCollectTime": "",
|
||||
"workOrderStatus": wo.work_order_status,
|
||||
"workOrderStatusLabel": _WORK_ORDER_STATUS_LABELS.get(
|
||||
wo.work_order_status or "", wo.work_order_status or ""
|
||||
@@ -2601,6 +2658,7 @@ def get_work_order_detail(
|
||||
"receptionSourceLabel": enriched.get("receptionSourceLabel", ""),
|
||||
"motherName": enriched.get("motherName", ""),
|
||||
"newbornName": enriched.get("newbornName", ""),
|
||||
"maternalBloodCollectTime": enriched.get("maternalBloodCollectTime", ""),
|
||||
"protocolStatus": enriched.get("protocolStatus", ""),
|
||||
"protocolStatusLabel": enriched.get("protocolStatusLabel", ""),
|
||||
"cellProductCode": enriched.get("cellProductCode", ""),
|
||||
|
||||
@@ -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,
|
||||
@@ -1702,7 +1703,8 @@ def change_status(
|
||||
)
|
||||
|
||||
db.add(obj)
|
||||
if ns == "yzf" and (current or "").strip() != "yzf":
|
||||
from_status = (current or "").strip()
|
||||
if ns in ("yzf", "sdfq") and from_status not in ("yzf", "sdfq"):
|
||||
from app.services.protocol_reception_discard_sync import after_protocol_voided
|
||||
|
||||
after_protocol_voided(
|
||||
|
||||
@@ -1045,12 +1045,11 @@ def create_sample_reception(
|
||||
user_id=user_id,
|
||||
create_dept_id=create_dept_id or "",
|
||||
)
|
||||
if conclusion == "bj":
|
||||
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
|
||||
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
|
||||
|
||||
after_sample_reception_saved(
|
||||
db, reception=obj, tenant_no=tenant_no, user_id=user_id
|
||||
)
|
||||
after_sample_reception_saved(
|
||||
db, reception=obj, tenant_no=tenant_no, user_id=user_id
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
@@ -1169,12 +1168,11 @@ def update_sample_reception(
|
||||
)
|
||||
check_result_svc.sync_legacy_columns_from_results(db, rec, saved_rows)
|
||||
db.add(rec)
|
||||
if conclusion == "bj":
|
||||
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
|
||||
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
|
||||
|
||||
after_sample_reception_saved(
|
||||
db, reception=rec, tenant_no=tenant_no, user_id=user_id
|
||||
)
|
||||
after_sample_reception_saved(
|
||||
db, reception=rec, tenant_no=tenant_no, user_id=user_id
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(rec)
|
||||
return rec
|
||||
|
||||
@@ -15,12 +15,14 @@ from app.models.models import (
|
||||
BizProtocolSample,
|
||||
BizSampleStorageCertQc,
|
||||
)
|
||||
from app.crud import sample_storage_cert_qc_acl as acl_svc
|
||||
from app.services.sample_storage_cert_qc import (
|
||||
dumps_payload,
|
||||
empty_detail,
|
||||
loads_payload,
|
||||
normalize_payload,
|
||||
merge_payload_with_acl,
|
||||
resolve_sample_type_key,
|
||||
sanitize_payload_for_type,
|
||||
)
|
||||
from app.services.sample_storage_cert_qc_prefill import collect_prefill
|
||||
|
||||
@@ -44,7 +46,7 @@ def _row_to_dict(
|
||||
"collectionProtocolId": row.collection_protocol_id or "",
|
||||
"qcWorkOrderId": row.qc_work_order_id or "",
|
||||
"filledFlag": str(row.filled_flag or "0") == "1",
|
||||
"payload": loads_payload(row.payload),
|
||||
"payload": sanitize_payload_for_type(loads_payload(row.payload), row.sample_type_key),
|
||||
"createTime": row.create_time.isoformat(sep=" ", timespec="seconds") if row.create_time else "",
|
||||
"updateTime": row.update_time.isoformat(sep=" ", timespec="seconds") if row.update_time else "",
|
||||
}
|
||||
@@ -165,6 +167,7 @@ def upsert(
|
||||
sample_code: str,
|
||||
payload: Any,
|
||||
qc_work_order_id: Optional[str] = None,
|
||||
editable_field_keys: Optional[list] = None,
|
||||
) -> Dict[str, Any]:
|
||||
ctx = _load_sample_context(db, tenant_no, sample_code)
|
||||
if not ctx:
|
||||
@@ -173,7 +176,6 @@ def upsert(
|
||||
key = resolve_sample_type_key(type_name)
|
||||
if not key:
|
||||
raise ValueError("该样本类型不支持填写储存证质检信息")
|
||||
clean = normalize_payload(payload)
|
||||
now = datetime.now()
|
||||
row = (
|
||||
db.query(BizSampleStorageCertQc)
|
||||
@@ -184,6 +186,14 @@ def upsert(
|
||||
)
|
||||
.first()
|
||||
)
|
||||
existing = loads_payload(row.payload) if row else {}
|
||||
allowed = list(editable_field_keys or [])
|
||||
clean = merge_payload_with_acl(
|
||||
existing=existing,
|
||||
incoming=payload,
|
||||
editable_keys=allowed,
|
||||
sample_type_key=key,
|
||||
)
|
||||
if not row:
|
||||
row = BizSampleStorageCertQc(
|
||||
id=generate_uuid(),
|
||||
@@ -220,3 +230,24 @@ def upsert(
|
||||
mother_name=mother_name,
|
||||
sample_type_name=type_name,
|
||||
)
|
||||
|
||||
|
||||
def attach_acl_context(
|
||||
db: Session,
|
||||
detail: Dict[str, Any],
|
||||
*,
|
||||
tenant_no: str,
|
||||
user_id: str,
|
||||
has_legacy_write: bool,
|
||||
can_configure_acl: bool,
|
||||
) -> Dict[str, Any]:
|
||||
detail["editableFieldKeys"] = acl_svc.resolve_editable_field_keys(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
sample_type_key=detail.get("sampleTypeKey"),
|
||||
has_legacy_write=has_legacy_write,
|
||||
)
|
||||
detail["canConfigureAcl"] = bool(can_configure_acl)
|
||||
detail["aclStrict"] = acl_svc.is_acl_strict(db, tenant_no)
|
||||
return detail
|
||||
@@ -0,0 +1,272 @@
|
||||
"""储存证质检字段 ACL CRUD。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional, Set
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.db_collation import eq_unicode, unicode_ci
|
||||
from app.core.utils import generate_uuid
|
||||
from app.crud.child_row_sync import sync_child_rows
|
||||
from app.models.models import BizStorageCertQcAcl, BizStorageCertQcAclUser, SysUser
|
||||
from app.services.sample_storage_cert_qc import (
|
||||
ACL_SCOPES,
|
||||
ALL_STORAGE_CERT_QC_FIELD_KEYS,
|
||||
dumps_field_keys,
|
||||
legal_field_keys_for_type,
|
||||
loads_field_keys,
|
||||
)
|
||||
|
||||
|
||||
def is_acl_strict(db: Session, tenant_no: str) -> bool:
|
||||
row = (
|
||||
db.query(BizStorageCertQcAcl.id)
|
||||
.filter(
|
||||
eq_unicode(BizStorageCertQcAcl.tenant_no, tenant_no),
|
||||
eq_unicode(BizStorageCertQcAcl.configured_flag, "1"),
|
||||
BizStorageCertQcAcl.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return row is not None
|
||||
|
||||
|
||||
def resolve_editable_field_keys(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
user_id: str,
|
||||
sample_type_key: Optional[str],
|
||||
has_legacy_write: bool,
|
||||
) -> List[str]:
|
||||
legal = legal_field_keys_for_type(sample_type_key)
|
||||
if not is_acl_strict(db, tenant_no):
|
||||
return sorted(legal) if has_legacy_write else []
|
||||
uid = (user_id or "").strip()
|
||||
if not uid:
|
||||
return []
|
||||
acls = (
|
||||
db.query(BizStorageCertQcAcl)
|
||||
.filter(
|
||||
eq_unicode(BizStorageCertQcAcl.tenant_no, tenant_no),
|
||||
eq_unicode(BizStorageCertQcAcl.configured_flag, "1"),
|
||||
BizStorageCertQcAcl.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
if not acls:
|
||||
return []
|
||||
acl_ids = [row.id for row in acls]
|
||||
membership = (
|
||||
db.query(BizStorageCertQcAclUser.acl_id)
|
||||
.filter(
|
||||
eq_unicode(BizStorageCertQcAclUser.tenant_no, tenant_no),
|
||||
unicode_ci(BizStorageCertQcAclUser.acl_id).in_(acl_ids),
|
||||
eq_unicode(BizStorageCertQcAclUser.user_id, uid),
|
||||
BizStorageCertQcAclUser.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
member_acl_ids = {row[0] for row in membership}
|
||||
keys: Set[str] = set()
|
||||
for acl in acls:
|
||||
if acl.id not in member_acl_ids:
|
||||
continue
|
||||
keys.update(loads_field_keys(acl.field_keys))
|
||||
return sorted(keys & legal)
|
||||
|
||||
|
||||
def _validate_scope(scope: str) -> str:
|
||||
value = (scope or "").strip()
|
||||
if value not in ACL_SCOPES:
|
||||
raise ValueError("scope 必须为 qc 或 production")
|
||||
return value
|
||||
|
||||
|
||||
def _validate_field_keys(field_keys: Any) -> List[str]:
|
||||
if not isinstance(field_keys, list):
|
||||
raise ValueError("fieldKeys 必须为数组")
|
||||
out: List[str] = []
|
||||
seen = set()
|
||||
for item in field_keys:
|
||||
key = str(item or "").strip()
|
||||
if not key or key in seen:
|
||||
continue
|
||||
if key not in ALL_STORAGE_CERT_QC_FIELD_KEYS:
|
||||
raise ValueError(f"非法字段: {key}")
|
||||
seen.add(key)
|
||||
out.append(key)
|
||||
return out
|
||||
|
||||
|
||||
def _validate_user_ids(db: Session, tenant_no: str, user_ids: Any) -> List[str]:
|
||||
if not isinstance(user_ids, list):
|
||||
raise ValueError("userIds 必须为数组")
|
||||
out: List[str] = []
|
||||
seen = set()
|
||||
for item in user_ids:
|
||||
uid = str(item or "").strip()
|
||||
if not uid or uid in seen:
|
||||
continue
|
||||
seen.add(uid)
|
||||
out.append(uid)
|
||||
if not out:
|
||||
return []
|
||||
rows = (
|
||||
db.query(SysUser.id)
|
||||
.filter(
|
||||
eq_unicode(SysUser.tenant_no, tenant_no),
|
||||
unicode_ci(SysUser.id).in_(out),
|
||||
SysUser.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
found = {row[0] for row in rows}
|
||||
missing = [uid for uid in out if uid not in found]
|
||||
if missing:
|
||||
raise ValueError(f"用户不存在或不属于当前租户: {','.join(missing[:5])}")
|
||||
return out
|
||||
|
||||
|
||||
def get_acl_detail(db: Session, tenant_no: str, scope: str) -> Dict[str, Any]:
|
||||
scope_key = _validate_scope(scope)
|
||||
row = (
|
||||
db.query(BizStorageCertQcAcl)
|
||||
.filter(
|
||||
eq_unicode(BizStorageCertQcAcl.tenant_no, tenant_no),
|
||||
eq_unicode(BizStorageCertQcAcl.scope, scope_key),
|
||||
BizStorageCertQcAcl.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not row:
|
||||
return {
|
||||
"scope": scope_key,
|
||||
"fieldKeys": [],
|
||||
"userIds": [],
|
||||
"users": [],
|
||||
"configuredFlag": False,
|
||||
"aclStrict": is_acl_strict(db, tenant_no),
|
||||
}
|
||||
users = (
|
||||
db.query(BizStorageCertQcAclUser, SysUser)
|
||||
.outerjoin(
|
||||
SysUser,
|
||||
eq_unicode(SysUser.id, BizStorageCertQcAclUser.user_id) & (SysUser.del_flag == 0),
|
||||
)
|
||||
.filter(
|
||||
eq_unicode(BizStorageCertQcAclUser.tenant_no, tenant_no),
|
||||
eq_unicode(BizStorageCertQcAclUser.acl_id, row.id),
|
||||
BizStorageCertQcAclUser.del_flag == 0,
|
||||
)
|
||||
.order_by(BizStorageCertQcAclUser.order_num.asc(), BizStorageCertQcAclUser.create_time.asc())
|
||||
.all()
|
||||
)
|
||||
user_ids: List[str] = []
|
||||
user_rows: List[Dict[str, str]] = []
|
||||
for link, user in users:
|
||||
uid = link.user_id or ""
|
||||
if not uid:
|
||||
continue
|
||||
user_ids.append(uid)
|
||||
user_rows.append(
|
||||
{
|
||||
"id": uid,
|
||||
"nickName": (user.nick_name if user else "") or "",
|
||||
"userName": (user.user_no if user else "") or "",
|
||||
}
|
||||
)
|
||||
return {
|
||||
"scope": scope_key,
|
||||
"fieldKeys": loads_field_keys(row.field_keys),
|
||||
"userIds": user_ids,
|
||||
"users": user_rows,
|
||||
"configuredFlag": str(row.configured_flag or "0") == "1",
|
||||
"aclStrict": is_acl_strict(db, tenant_no),
|
||||
}
|
||||
|
||||
|
||||
def upsert_acl(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
user_id: str,
|
||||
scope: str,
|
||||
field_keys: Any,
|
||||
user_ids: Any,
|
||||
) -> Dict[str, Any]:
|
||||
scope_key = _validate_scope(scope)
|
||||
keys = _validate_field_keys(field_keys)
|
||||
users = _validate_user_ids(db, tenant_no, user_ids)
|
||||
now = datetime.now()
|
||||
row = (
|
||||
db.query(BizStorageCertQcAcl)
|
||||
.filter(
|
||||
eq_unicode(BizStorageCertQcAcl.tenant_no, tenant_no),
|
||||
eq_unicode(BizStorageCertQcAcl.scope, scope_key),
|
||||
BizStorageCertQcAcl.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not row:
|
||||
row = BizStorageCertQcAcl(
|
||||
id=generate_uuid(),
|
||||
scope=scope_key,
|
||||
field_keys=dumps_field_keys(keys),
|
||||
configured_flag="1",
|
||||
tenant_no=tenant_no,
|
||||
create_by=user_id,
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
update_by=user_id,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
else:
|
||||
row.field_keys = dumps_field_keys(keys)
|
||||
row.configured_flag = "1"
|
||||
row.update_by = user_id
|
||||
row.update_time = now
|
||||
|
||||
def _build_row(new_id: str):
|
||||
return BizStorageCertQcAclUser(
|
||||
id=new_id,
|
||||
acl_id=row.id,
|
||||
user_id="",
|
||||
tenant_no=tenant_no,
|
||||
create_by=user_id,
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
update_by=user_id,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
|
||||
def _apply_fields(link, item: Dict[str, Any], index: int, ts: datetime):
|
||||
link.user_id = str(item.get("userId") or "").strip()
|
||||
link.tenant_no = tenant_no
|
||||
link.order_num = index
|
||||
link.update_by = user_id
|
||||
link.update_time = ts
|
||||
|
||||
sync_child_rows(
|
||||
db,
|
||||
BizStorageCertQcAclUser,
|
||||
parent_attr="acl_id",
|
||||
parent_id=row.id,
|
||||
items=[{"userId": uid} for uid in users],
|
||||
build_row=_build_row,
|
||||
apply_fields=_apply_fields,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
now=now,
|
||||
natural_key=lambda item: str(item.get("userId") or "").strip(),
|
||||
row_natural_key=lambda link: str(getattr(link, "user_id", "") or "").strip(),
|
||||
duplicate_message="人员重复",
|
||||
foreign_message="人员记录不属于当前 ACL",
|
||||
)
|
||||
db.commit()
|
||||
return get_acl_detail(db, tenant_no, scope_key)
|
||||
+4
-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, 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)
|
||||
@@ -157,6 +158,8 @@ app.include_router(sample_storage_cert_qc_router, prefix=settings.API_V1_PREFIX)
|
||||
app.include_router(customer_service_dict_router, prefix=settings.API_V1_PREFIX)
|
||||
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(project_management_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="特殊说明")
|
||||
@@ -1779,6 +1780,45 @@ class BizSampleStorageCertQc(Base):
|
||||
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
|
||||
|
||||
|
||||
class BizStorageCertQcAcl(Base):
|
||||
"""储存证质检字段 ACL 主表 biz_storage_cert_qc_acl"""
|
||||
|
||||
__tablename__ = "biz_storage_cert_qc_acl"
|
||||
|
||||
id = Column(String(64), primary_key=True, comment="主键ID")
|
||||
scope = Column(String(32), nullable=False, comment="qc|production")
|
||||
field_keys = Column(Text, nullable=False, comment="可编辑字段 key JSON 数组")
|
||||
configured_flag = Column(CHAR(1), nullable=False, default="0", comment="是否已正式配置 0否1是")
|
||||
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
|
||||
order_num = Column(Integer, nullable=True, comment="排序号")
|
||||
remark = Column(String(512), nullable=True, comment="备注")
|
||||
create_by = Column(String(64), nullable=True, comment="创建人id")
|
||||
create_dept_id = Column(String(64), nullable=False, default="", comment="创建人部门ID")
|
||||
create_time = Column(DateTime, nullable=False, default=datetime.now, comment="创建时间")
|
||||
update_by = Column(String(64), nullable=True, comment="更新人id")
|
||||
update_time = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment="更新时间")
|
||||
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
|
||||
|
||||
|
||||
class BizStorageCertQcAclUser(Base):
|
||||
"""储存证质检字段 ACL 人员子表 biz_storage_cert_qc_acl_user"""
|
||||
|
||||
__tablename__ = "biz_storage_cert_qc_acl_user"
|
||||
|
||||
id = Column(String(64), primary_key=True, comment="主键ID")
|
||||
acl_id = Column(String(64), nullable=False, comment="ACL 主表ID")
|
||||
user_id = Column(String(64), nullable=False, comment="可编辑用户ID")
|
||||
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
|
||||
order_num = Column(Integer, nullable=True, comment="排序号")
|
||||
remark = Column(String(512), nullable=True, comment="备注")
|
||||
create_by = Column(String(64), nullable=True, comment="创建人id")
|
||||
create_dept_id = Column(String(64), nullable=False, default="", comment="创建人部门ID")
|
||||
create_time = Column(DateTime, nullable=False, default=datetime.now, comment="创建时间")
|
||||
update_by = Column(String(64), nullable=True, comment="更新人id")
|
||||
update_time = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment="更新时间")
|
||||
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
|
||||
|
||||
|
||||
class BizSampleCodeCorrectionLog(Base):
|
||||
"""样本编码纠错审计日志 biz_sample_code_correction_log"""
|
||||
|
||||
@@ -1930,6 +1970,26 @@ class BizSampleReception(Base):
|
||||
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
|
||||
|
||||
|
||||
class BizLabSampleProcessingExtra(Base):
|
||||
"""实验室样本处理数据补充字段 biz_lab_sample_processing_extra"""
|
||||
|
||||
__tablename__ = "biz_lab_sample_processing_extra"
|
||||
|
||||
id = Column(String(64), primary_key=True, comment="主键ID")
|
||||
dataset = Column(String(16), nullable=False, comment="hsc|ubmc|msc")
|
||||
sample_code = Column(String(32), nullable=False, comment="样本编码")
|
||||
payload_json = Column(Text, nullable=True, comment="补充字段 JSON")
|
||||
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
|
||||
order_num = Column(Integer, nullable=True, comment="排序号")
|
||||
remark = Column(String(512), nullable=True, comment="备注")
|
||||
create_by = Column(String(64), nullable=True, comment="创建人id")
|
||||
create_dept_id = Column(String(64), nullable=False, default="", comment="创建人部门ID")
|
||||
create_time = Column(DateTime, nullable=False, default=datetime.now, comment="创建时间")
|
||||
update_by = Column(String(64), nullable=True, comment="更新人id")
|
||||
update_time = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment="更新时间")
|
||||
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
|
||||
|
||||
|
||||
class BizSampleProductionReception(Base):
|
||||
"""生产部门样本接收登记 biz_sample_production_reception"""
|
||||
|
||||
@@ -1968,6 +2028,29 @@ class BizSampleProductionReception(Base):
|
||||
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
|
||||
|
||||
|
||||
class BizLabSampleProcessSupplement(Base):
|
||||
"""实验室样本处理台账补录 biz_lab_sample_process_supplement(键:tenant_no + lab_storage_code)"""
|
||||
|
||||
__tablename__ = "biz_lab_sample_process_supplement"
|
||||
|
||||
id = Column(String(64), primary_key=True, comment="主键ID")
|
||||
lab_storage_code = Column(String(32), nullable=False, comment="实验室入库编码")
|
||||
reception_source = Column(
|
||||
String(20), nullable=False, default="cell_storage", comment="cell_storage|research_donation"
|
||||
)
|
||||
sample_type_name = Column(String(100), nullable=True, comment="样本类型名称快照")
|
||||
payload = Column(Text, nullable=False, comment="补录字段 JSON")
|
||||
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
|
||||
order_num = Column(Integer, nullable=True, comment="排序号")
|
||||
remark = Column(String(512), nullable=True, comment="备注")
|
||||
create_by = Column(String(64), nullable=True, comment="创建人id")
|
||||
create_dept_id = Column(String(64), nullable=False, default="", comment="创建人部门ID")
|
||||
create_time = Column(DateTime, nullable=False, default=datetime.now, comment="创建时间")
|
||||
update_by = Column(String(64), nullable=True, comment="更新人id")
|
||||
update_time = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment="更新时间")
|
||||
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
|
||||
|
||||
|
||||
class BizSampleSmsNotification(Base):
|
||||
__tablename__ = "biz_sample_sms_notification"
|
||||
|
||||
|
||||
@@ -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="特殊说明")
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
"""实验室样本处理台账:字段合并、质检参数匹配、中文时间格式。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, Iterable, List, Optional, Set
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.models import (
|
||||
BizQcTask,
|
||||
BizQcWorkOrder,
|
||||
BizQcWorkOrderInspectionBatch,
|
||||
)
|
||||
from app.models.qc_param import BizQcTaskResult
|
||||
from app.services.sample_storage_cert_qc_prefill import (
|
||||
_MOTHER_SEROLOGY_RULES,
|
||||
_process_qual_from_tasks,
|
||||
_serology_from_tasks,
|
||||
_stamp,
|
||||
batch_kind_from_name,
|
||||
normalize_negative_positive,
|
||||
qual_yin_yang,
|
||||
)
|
||||
|
||||
SAMPLE_TYPE_PERINATAL_HSC = "围产期造血干细胞"
|
||||
SAMPLE_TYPE_UC_MSC = "脐带间充质干细胞"
|
||||
|
||||
TAB_KEYS = (
|
||||
"cell_hsc",
|
||||
"donation_hsc",
|
||||
"cell_msc",
|
||||
"donation_msc",
|
||||
)
|
||||
|
||||
TAB_META = {
|
||||
"cell_hsc": {
|
||||
"source": "cell_storage",
|
||||
"sampleTypeName": SAMPLE_TYPE_PERINATAL_HSC,
|
||||
"label": "细胞存储·围产期造血干细胞",
|
||||
},
|
||||
"donation_hsc": {
|
||||
"source": "research_donation",
|
||||
"sampleTypeName": SAMPLE_TYPE_PERINATAL_HSC,
|
||||
"label": "科研捐赠·围产期造血干细胞",
|
||||
},
|
||||
"cell_msc": {
|
||||
"source": "cell_storage",
|
||||
"sampleTypeName": SAMPLE_TYPE_UC_MSC,
|
||||
"label": "细胞存储·脐带间充质干细胞",
|
||||
},
|
||||
"donation_msc": {
|
||||
"source": "research_donation",
|
||||
"sampleTypeName": SAMPLE_TYPE_UC_MSC,
|
||||
"label": "科研捐赠·脐带间充质干细胞",
|
||||
},
|
||||
}
|
||||
|
||||
# 各 Tab 可补录字段(系统空或口径需覆盖时写入)
|
||||
SUPPLEMENT_KEYS: Dict[str, List[str]] = {
|
||||
"cell_hsc": [
|
||||
"receiveCheckText",
|
||||
"hasMaternalBlood",
|
||||
"remeasureMaternalBlood",
|
||||
"transportPackingList",
|
||||
"cordBloodReceiveConfirm",
|
||||
"infectiousFourExternal",
|
||||
"preEnrichNucleatedCount",
|
||||
"postEnrichNucleatedCount",
|
||||
"cd34Count1e4",
|
||||
"remarkProcess",
|
||||
],
|
||||
"donation_hsc": [
|
||||
"labMaterialCode",
|
||||
"storageStatus",
|
||||
"discardReason",
|
||||
"receiveCheckText",
|
||||
"preOpNucleatedCount",
|
||||
"infectiousFourTestLabel",
|
||||
"motherHbsag",
|
||||
"motherAntiHcv",
|
||||
"motherAntiTp",
|
||||
"motherAntiHiv",
|
||||
"motherCmvIgm",
|
||||
"remarkProcess",
|
||||
],
|
||||
"cell_msc": [
|
||||
"storageStatus",
|
||||
"endotoxinTest",
|
||||
"bacteriaTest",
|
||||
"fungusTest",
|
||||
"mycoplasmaTest",
|
||||
"motherHbsag",
|
||||
"motherHbvDna",
|
||||
"motherAntiHcv",
|
||||
"motherHcvRna",
|
||||
"motherAntiTp",
|
||||
"motherCmvIgm",
|
||||
"motherAntiHiv",
|
||||
"motherHiv1Rna",
|
||||
"storageDateP2",
|
||||
"remark",
|
||||
],
|
||||
"donation_msc": [
|
||||
"storageStatus",
|
||||
"storageTotalTubes",
|
||||
"availableCellCount1e7",
|
||||
"endotoxinTest",
|
||||
"bacteriaTest",
|
||||
"fungusTest",
|
||||
"mycoplasmaTest",
|
||||
"motherHbsag",
|
||||
"motherHbvDna",
|
||||
"motherAntiHcv",
|
||||
"motherHcvRna",
|
||||
"motherAntiTp",
|
||||
"motherCmvIgm",
|
||||
"motherAntiHiv",
|
||||
"motherHiv1Rna",
|
||||
"storageDateP2",
|
||||
"remark",
|
||||
],
|
||||
}
|
||||
|
||||
# 补录优先覆盖系统推导值的字段
|
||||
SUPPLEMENT_OVERRIDE_KEYS: Dict[str, Set[str]] = {
|
||||
"cell_hsc": {"receiveCheckText"},
|
||||
"donation_hsc": {
|
||||
"receiveCheckText",
|
||||
"storageStatus",
|
||||
"infectiousFourTestLabel",
|
||||
"motherHbsag",
|
||||
"motherAntiHcv",
|
||||
"motherAntiTp",
|
||||
"motherAntiHiv",
|
||||
"motherCmvIgm",
|
||||
},
|
||||
"cell_msc": {
|
||||
"storageStatus",
|
||||
"endotoxinTest",
|
||||
"bacteriaTest",
|
||||
"fungusTest",
|
||||
"mycoplasmaTest",
|
||||
"motherHbsag",
|
||||
"motherHbvDna",
|
||||
"motherAntiHcv",
|
||||
"motherHcvRna",
|
||||
"motherAntiTp",
|
||||
"motherCmvIgm",
|
||||
"motherAntiHiv",
|
||||
"motherHiv1Rna",
|
||||
"storageDateP2",
|
||||
},
|
||||
"donation_msc": {
|
||||
"storageStatus",
|
||||
"storageTotalTubes",
|
||||
"availableCellCount1e7",
|
||||
"endotoxinTest",
|
||||
"bacteriaTest",
|
||||
"fungusTest",
|
||||
"mycoplasmaTest",
|
||||
"motherHbsag",
|
||||
"motherHbvDna",
|
||||
"motherAntiHcv",
|
||||
"motherHcvRna",
|
||||
"motherAntiTp",
|
||||
"motherCmvIgm",
|
||||
"motherAntiHiv",
|
||||
"motherHiv1Rna",
|
||||
"storageDateP2",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def format_cn_datetime(value: Any) -> str:
|
||||
"""统一展示:2026年11月12日 00时00分00秒"""
|
||||
if value is None or value == "":
|
||||
return ""
|
||||
if isinstance(value, datetime):
|
||||
dt = value
|
||||
else:
|
||||
text = str(value).strip().replace("T", " ")
|
||||
if not text:
|
||||
return ""
|
||||
dt = None
|
||||
for candidate, fmt in (
|
||||
(text[:19], "%Y-%m-%d %H:%M:%S"),
|
||||
(text[:16], "%Y-%m-%d %H:%M"),
|
||||
(text[:10], "%Y-%m-%d"),
|
||||
):
|
||||
try:
|
||||
dt = datetime.strptime(candidate, fmt)
|
||||
break
|
||||
except ValueError:
|
||||
continue
|
||||
if dt is None:
|
||||
return text
|
||||
return (
|
||||
f"{dt.year:04d}年{dt.month:02d}月{dt.day:02d}日 "
|
||||
f"{dt.hour:02d}时{dt.minute:02d}分{dt.second:02d}秒"
|
||||
)
|
||||
|
||||
|
||||
def parse_payload(raw: Any) -> Dict[str, Any]:
|
||||
if isinstance(raw, dict):
|
||||
return dict(raw)
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except (TypeError, ValueError, json.JSONDecodeError):
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def dumps_payload(payload: Dict[str, Any]) -> str:
|
||||
return json.dumps(payload or {}, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
def yes_no_from_urls(urls: Optional[str]) -> str:
|
||||
return "是" if (urls or "").strip() else "否"
|
||||
|
||||
|
||||
def yes_no_from_bool(flag: Optional[bool]) -> str:
|
||||
if flag is None:
|
||||
return ""
|
||||
return "是" if flag else "否"
|
||||
|
||||
|
||||
def merge_row(
|
||||
*,
|
||||
tab_key: str,
|
||||
system_values: Dict[str, Any],
|
||||
supplement: Optional[Dict[str, Any]],
|
||||
) -> Dict[str, Any]:
|
||||
"""系统值优先;override 键补录优先;空用补录填。"""
|
||||
out = dict(system_values or {})
|
||||
sup = supplement or {}
|
||||
overrides = SUPPLEMENT_OVERRIDE_KEYS.get(tab_key, set())
|
||||
for key, val in sup.items():
|
||||
text = "" if val is None else str(val).strip()
|
||||
if not text:
|
||||
continue
|
||||
cur = out.get(key)
|
||||
cur_empty = cur is None or (isinstance(cur, str) and not cur.strip())
|
||||
if key in overrides or cur_empty:
|
||||
out[key] = text
|
||||
return out
|
||||
|
||||
|
||||
def load_qc_tasks_for_sample(db: Session, tenant_no: str, sample_code: str) -> List[Dict[str, Any]]:
|
||||
code = (sample_code or "").strip()
|
||||
if not code:
|
||||
return []
|
||||
rows = (
|
||||
db.query(
|
||||
BizQcTask.id,
|
||||
BizQcTask.item_name,
|
||||
BizQcTask.completed_time,
|
||||
BizQcTask.update_time,
|
||||
BizQcWorkOrderInspectionBatch.batch_name,
|
||||
BizQcTaskResult.param_name,
|
||||
BizQcTaskResult.param_value,
|
||||
)
|
||||
.join(BizQcWorkOrder, BizQcWorkOrder.id == BizQcTask.work_order_id)
|
||||
.outerjoin(
|
||||
BizQcWorkOrderInspectionBatch,
|
||||
BizQcWorkOrderInspectionBatch.id == BizQcTask.batch_id,
|
||||
)
|
||||
.outerjoin(
|
||||
BizQcTaskResult,
|
||||
(BizQcTaskResult.task_id == BizQcTask.id) & (BizQcTaskResult.del_flag == 0),
|
||||
)
|
||||
.filter(
|
||||
BizQcWorkOrder.tenant_no == tenant_no,
|
||||
BizQcWorkOrder.sample_code == code,
|
||||
BizQcWorkOrder.del_flag == 0,
|
||||
BizQcTask.tenant_no == tenant_no,
|
||||
BizQcTask.del_flag == 0,
|
||||
BizQcTask.task_status == "ywc",
|
||||
)
|
||||
.all()
|
||||
)
|
||||
grouped: Dict[str, Dict[str, Any]] = {}
|
||||
for row in rows:
|
||||
task = grouped.setdefault(
|
||||
row.id,
|
||||
{
|
||||
"item_name": row.item_name or "",
|
||||
"batch_kind": batch_kind_from_name(row.batch_name),
|
||||
"stamp": _stamp(row.completed_time, row.update_time),
|
||||
"params": [],
|
||||
"values": [],
|
||||
},
|
||||
)
|
||||
if (row.param_name or "").strip() or (row.param_value or "").strip():
|
||||
task["params"].append((row.param_name or "", row.param_value or ""))
|
||||
if (row.param_value or "").strip():
|
||||
task["values"].append(row.param_value or "")
|
||||
return list(grouped.values())
|
||||
|
||||
|
||||
def extract_mother_blood(tasks: List[Dict[str, Any]], *, include_nucleic: bool = True) -> Dict[str, str]:
|
||||
rules = _MOTHER_SEROLOGY_RULES
|
||||
if not include_nucleic:
|
||||
rules = tuple(
|
||||
r
|
||||
for r in rules
|
||||
if r[0] not in {"mother_hbv_dna", "mother_hcv_rna", "mother_hiv1_rna"}
|
||||
)
|
||||
raw = _serology_from_tasks(tasks, rules)
|
||||
mapping = {
|
||||
"mother_hbsag": "motherHbsag",
|
||||
"mother_hbv_dna": "motherHbvDna",
|
||||
"mother_anti_hcv": "motherAntiHcv",
|
||||
"mother_hcv_rna": "motherHcvRna",
|
||||
"mother_anti_tp": "motherAntiTp",
|
||||
"mother_cmv_igm": "motherCmvIgm",
|
||||
"mother_anti_hiv": "motherAntiHiv",
|
||||
"mother_hiv1_rna": "motherHiv1Rna",
|
||||
}
|
||||
out: Dict[str, str] = {}
|
||||
for src, dst in mapping.items():
|
||||
val = normalize_negative_positive(raw.get(src) or "") or (raw.get(src) or "")
|
||||
if val:
|
||||
# 台账 Excel 多用「阴」
|
||||
if val in ("阴性", "阴"):
|
||||
out[dst] = "阴"
|
||||
elif val in ("阳性", "阳"):
|
||||
out[dst] = "阳"
|
||||
else:
|
||||
out[dst] = val
|
||||
return out
|
||||
|
||||
|
||||
def extract_process_tests(tasks: List[Dict[str, Any]]) -> Dict[str, str]:
|
||||
raw = _process_qual_from_tasks(tasks)
|
||||
bacteria_values: List[str] = []
|
||||
for task in tasks:
|
||||
name = task.get("item_name") or ""
|
||||
params = task.get("params") or []
|
||||
hit = "细菌" in name or any("细菌" in (pn or "") for pn, _ in params)
|
||||
if not hit:
|
||||
continue
|
||||
for _, pv in params:
|
||||
bacteria_values.append(pv)
|
||||
bacteria_values.extend(task.get("values") or [])
|
||||
bacteria = qual_yin_yang(bacteria_values)
|
||||
out = {
|
||||
"endotoxinTest": _to_yin(raw.get("endotoxin_test")),
|
||||
"fungusTest": _to_yin(raw.get("fungus_test")),
|
||||
"mycoplasmaTest": _to_yin(raw.get("mycoplasma_test")),
|
||||
}
|
||||
if bacteria:
|
||||
out["bacteriaTest"] = _to_yin(bacteria)
|
||||
return {k: v for k, v in out.items() if v}
|
||||
|
||||
|
||||
def _to_yin(value: Optional[str]) -> str:
|
||||
text = (value or "").strip()
|
||||
if text in ("阴性", "阴"):
|
||||
return "阴"
|
||||
if text in ("阳性", "阳"):
|
||||
return "阳"
|
||||
return text
|
||||
|
||||
|
||||
def infectious_label(code: Optional[str]) -> str:
|
||||
c = (code or "").strip()
|
||||
if c == "zc":
|
||||
return "正常"
|
||||
if c == "bzc":
|
||||
return "不正常"
|
||||
return c
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,176 @@
|
||||
"""实验室样本处理数据 — 字段目录与部门归属。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
DATASET_HSC = "hsc"
|
||||
DATASET_UBMC = "ubmc"
|
||||
DATASET_MSC = "msc"
|
||||
DATASETS = (DATASET_HSC, DATASET_UBMC, DATASET_MSC)
|
||||
|
||||
DEPT_MARKET = "market"
|
||||
DEPT_PRODUCTION = "production"
|
||||
DEPT_QC = "qc"
|
||||
DEPTS = (DEPT_MARKET, DEPT_PRODUCTION, DEPT_QC)
|
||||
|
||||
PERM_LIST = "lab:sample-processing:list"
|
||||
PERM_MARKET_EDIT = "lab:sample-processing:market:edit"
|
||||
PERM_PRODUCTION_EDIT = "lab:sample-processing:production:edit"
|
||||
PERM_QC_EDIT = "lab:sample-processing:qc:edit"
|
||||
PERM_MANAGER = "lab:sample-processing:manager"
|
||||
|
||||
DEPT_EDIT_PERMS = {
|
||||
DEPT_MARKET: PERM_MARKET_EDIT,
|
||||
DEPT_PRODUCTION: PERM_PRODUCTION_EDIT,
|
||||
DEPT_QC: PERM_QC_EDIT,
|
||||
}
|
||||
|
||||
SOURCE_PROTOCOL = "protocol"
|
||||
SOURCE_RECEPTION = "reception"
|
||||
SOURCE_PRODUCTION = "production_reception"
|
||||
SOURCE_EXTRA = "extra"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FieldDef:
|
||||
key: str
|
||||
label: str
|
||||
dept: str
|
||||
source: str
|
||||
attr: Optional[str] = None # ORM attr on source object when applicable
|
||||
|
||||
|
||||
def _f(key: str, label: str, dept: str, source: str, attr: Optional[str] = None) -> FieldDef:
|
||||
return FieldDef(key=key, label=label, dept=dept, source=source, attr=attr or key)
|
||||
|
||||
|
||||
HSC_FIELDS: Tuple[FieldDef, ...] = (
|
||||
_f("sampleCode", "细胞编码", DEPT_MARKET, SOURCE_PROTOCOL, "sample_code"),
|
||||
_f("motherName", "准妈妈姓名", DEPT_MARKET, SOURCE_PROTOCOL, "mother_name"),
|
||||
_f("collectTime", "采集时间", DEPT_MARKET, SOURCE_PROTOCOL, "sample_collect_time"),
|
||||
_f("collectHospital", "采集医院", DEPT_MARKET, SOURCE_PROTOCOL, "hospital_name"),
|
||||
_f("receptionTime", "接收时间", DEPT_PRODUCTION, SOURCE_RECEPTION, "reception_time"),
|
||||
_f("receiveTemperature", "样品温度到达/℃", DEPT_PRODUCTION, SOURCE_RECEPTION, "receive_temperature"),
|
||||
_f("receiveCheck", "收样检查", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("hasMaternalBlood", "是否有母血", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("remeasureMaternalBlood", "是否重采母血", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("hasConsent", "知情同意书或协议书", DEPT_MARKET, SOURCE_EXTRA),
|
||||
_f("hasPackingList", "脐血运输装箱清单", DEPT_MARKET, SOURCE_EXTRA),
|
||||
_f("hasReceiveConfirm", "脐带血接收确认单", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("hasHealthSurvey", "孕妇健康调查表", DEPT_MARKET, SOURCE_EXTRA),
|
||||
_f("labelClear", "标识清晰", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("receptionHandler", "接收登记人", DEPT_PRODUCTION, SOURCE_RECEPTION, "handler_name"),
|
||||
_f("receptionRemark", "备注", DEPT_PRODUCTION, SOURCE_RECEPTION, "remark"),
|
||||
_f("originalBloodWeightG", "原血重量/g", DEPT_PRODUCTION, SOURCE_PRODUCTION, "original_blood_weight_g"),
|
||||
_f("hesVolumeMl", "HES用量/ml", DEPT_PRODUCTION, SOURCE_PRODUCTION, "hes_volume_ml"),
|
||||
_f("bloodType", "血型", DEPT_PRODUCTION, SOURCE_PRODUCTION, "blood_type"),
|
||||
_f("infectiousFourCard", "传染四项检测(检测卡)", DEPT_QC, SOURCE_PRODUCTION, "infectious_four_test_result"),
|
||||
_f("infectiousFourExternal", "传染四项检测(外检)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("preEnrichTnc", "富集前有核细胞数/109/L", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("enrichedBloodWeightG", "富集后血量/g", DEPT_PRODUCTION, SOURCE_PRODUCTION, "enriched_blood_weight_g"),
|
||||
_f("postEnrichTnc", "富集后有核细胞数/109/L", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("cryoVolumeMl", "冻存液用量/ml", DEPT_PRODUCTION, SOURCE_PRODUCTION, "cryopreservation_volume_ml"),
|
||||
_f("cd34Count", "CD34+细胞计数/*10E4", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("operatorName", "操作人", DEPT_PRODUCTION, SOURCE_PRODUCTION, "handler_name"),
|
||||
_f("processRemark", "备注", DEPT_PRODUCTION, SOURCE_PRODUCTION, "remark"),
|
||||
)
|
||||
|
||||
UBMC_FIELDS: Tuple[FieldDef, ...] = (
|
||||
_f("sampleCode", "细胞编码", DEPT_MARKET, SOURCE_PROTOCOL, "sample_code"),
|
||||
_f("motherName", "准妈妈姓名", DEPT_MARKET, SOURCE_PROTOCOL, "mother_name"),
|
||||
_f("labMaterialCode", "实验室物料编码", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("labStorageCode", "入库编码", DEPT_PRODUCTION, SOURCE_RECEPTION, "lab_storage_code"),
|
||||
_f("storageStatus", "储存状态", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("discardReason", "废弃原因", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("receptionTime", "接收时间", DEPT_PRODUCTION, SOURCE_RECEPTION, "reception_time"),
|
||||
_f("receiveTemperature", "样品温度到达/℃", DEPT_PRODUCTION, SOURCE_RECEPTION, "receive_temperature"),
|
||||
_f("receiveCheck", "收样检查", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("receptionHandler", "接收登记人", DEPT_PRODUCTION, SOURCE_RECEPTION, "handler_name"),
|
||||
_f("receptionRemark", "备注", DEPT_PRODUCTION, SOURCE_RECEPTION, "remark"),
|
||||
_f("originalBloodVolumeMl", "原血体积/mL", DEPT_PRODUCTION, SOURCE_PRODUCTION, "original_blood_volume_ml"),
|
||||
_f("nucleatedCellCount1e8", "有核细胞数/108", DEPT_PRODUCTION, SOURCE_PRODUCTION, "nucleated_cell_count_1e8"),
|
||||
_f("preOpTnc", "操作前有核细胞数/109/L", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("infectiousFourCard", "传染四项检测(检测卡)", DEPT_QC, SOURCE_PRODUCTION, "infectious_four_test_result"),
|
||||
_f("hbsag", "乙型肝炎病毒表面抗原(HBsAg)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("antiHcv", "丙型肝炎病毒抗体(抗HCV)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("antiTp", "梅毒螺旋体特异性抗体(抗TP)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("antiHiv", "人类免疫缺陷病毒抗体(抗HIV-1/2)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("cmvIgm", "巨细胞病毒IgM 抗体 (CMV-IgM)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("operatorName", "操作人", DEPT_PRODUCTION, SOURCE_PRODUCTION, "handler_name"),
|
||||
_f("processRemark", "备注", DEPT_PRODUCTION, SOURCE_PRODUCTION, "remark"),
|
||||
)
|
||||
|
||||
MSC_FIELDS: Tuple[FieldDef, ...] = (
|
||||
_f("sampleCode", "实验室流转编码", DEPT_MARKET, SOURCE_PROTOCOL, "sample_code"),
|
||||
_f("motherName", "母亲姓名", DEPT_MARKET, SOURCE_PROTOCOL, "mother_name"),
|
||||
_f("collectTime", "脐带采集时间", DEPT_MARKET, SOURCE_PROTOCOL, "sample_collect_time"),
|
||||
_f("transportTempC", "运输温度/℃", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("receptionTime", "脐带接收时间", DEPT_PRODUCTION, SOURCE_RECEPTION, "reception_time"),
|
||||
_f("receptionHandler", "接收登记人", DEPT_PRODUCTION, SOURCE_RECEPTION, "handler_name"),
|
||||
_f("inoculationAmount", "接种量", DEPT_PRODUCTION, SOURCE_PRODUCTION, "inoculation_amount"),
|
||||
_f("storageStatus", "储存状态", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("cryoTime", "冻存时间", DEPT_PRODUCTION, SOURCE_PRODUCTION, "cryopreservation_time"),
|
||||
_f("storageTotalTubes", "储存总量(管)", DEPT_PRODUCTION, SOURCE_PRODUCTION, "storage_total_tubes"),
|
||||
_f("availableCellCount1e7", "可提供细胞数量/*10E7", DEPT_PRODUCTION, SOURCE_PRODUCTION, "available_cell_count_1e7"),
|
||||
_f("endotoxinTest", "内毒素检测", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("bacteriaTest", "细菌检测", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("fungusTest", "真菌检测", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("mycoplasmaTest", "支原体检测", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("operatorName", "操作人", DEPT_PRODUCTION, SOURCE_PRODUCTION, "handler_name"),
|
||||
_f("motherHbsag", "乙型肝炎病毒表面抗原(HBsAg)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("motherHbvDna", "乙型肝炎病毒核酸(HBV DNA)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("motherAntiHcv", "丙型肝炎病毒抗体(抗HCV)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("motherHcvRna", "丙型肝炎病毒核酸(HCV RNA)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("motherAntiTp", "梅毒螺旋体特异性抗体(抗TP)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("motherCmvIgm", "巨细胞病毒lgM 抗体 (CMV lgM)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("motherAntiHiv", "人类免疫缺陷病毒抗体(抗HIV-1/2)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("motherHiv1Rna", "人类免疫缺陷病毒核酸(1型) (HIV-1RNA)", DEPT_QC, SOURCE_EXTRA),
|
||||
_f("storageDateP2", "储存日期(P2冻存日期)", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||
_f("processRemark", "备注", DEPT_PRODUCTION, SOURCE_PRODUCTION, "remark"),
|
||||
)
|
||||
|
||||
FIELDS_BY_DATASET: Dict[str, Tuple[FieldDef, ...]] = {
|
||||
DATASET_HSC: HSC_FIELDS,
|
||||
DATASET_UBMC: UBMC_FIELDS,
|
||||
DATASET_MSC: MSC_FIELDS,
|
||||
}
|
||||
|
||||
DATASET_LABELS = {
|
||||
DATASET_HSC: "造血干细胞数据",
|
||||
DATASET_UBMC: "单个核数据",
|
||||
DATASET_MSC: "脐带间充质干细胞数据",
|
||||
}
|
||||
|
||||
|
||||
def fields_for(dataset: str) -> Tuple[FieldDef, ...]:
|
||||
return FIELDS_BY_DATASET.get(dataset) or ()
|
||||
|
||||
|
||||
def field_map(dataset: str) -> Dict[str, FieldDef]:
|
||||
return {f.key: f for f in fields_for(dataset)}
|
||||
|
||||
|
||||
def editable_depts_for_user(*, is_manager: bool, dept_flags: Dict[str, bool]) -> set:
|
||||
if is_manager:
|
||||
return set(DEPTS)
|
||||
return {d for d, ok in dept_flags.items() if ok}
|
||||
|
||||
|
||||
def resolve_dataset_by_type_name(name: Optional[str], sample_code: Optional[str] = None) -> Optional[str]:
|
||||
text = (name or "").strip()
|
||||
code = (sample_code or "").strip().upper()
|
||||
if "单个核" in text or "脐血单个核" in text or code.startswith("UBMC"):
|
||||
return DATASET_UBMC
|
||||
if "间充质" in text or code.startswith("BC") or code.startswith("UC"):
|
||||
return DATASET_MSC
|
||||
if "造血" in text or code.startswith("B"):
|
||||
return DATASET_HSC
|
||||
return None
|
||||
|
||||
|
||||
def schema_payload(dataset: str) -> List[Dict[str, str]]:
|
||||
return [
|
||||
{"key": f.key, "label": f.label, "dept": f.dept, "source": f.source}
|
||||
for f in fields_for(dataset)
|
||||
]
|
||||
@@ -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(
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
"""市场协议作废 ↔ 质检样本接收废弃双向联动。
|
||||
"""市场协议无效态 ↔ 样本接收废弃 / 样本状态作废联动。
|
||||
|
||||
规则(细胞存储 / 科研捐赠):
|
||||
1. 协议变为已作废(yzf)时,协议下全部样本接收结论自动为废弃(bj)。
|
||||
2. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。
|
||||
1. 单条样本接收结论为废弃(bj)时:仅该样本 `sample_status` 置为已作废(yzf)并写 `void_date`;
|
||||
协议状态保持不变。接收结论改回接收(js)且协议仍有效时:若该样本为 yzf,则清空状态与 void_date。
|
||||
2. 协议变为已作废(yzf)或属地废弃(sdfq)时:
|
||||
- 协议下全部样本接收结论自动为废弃(bj);
|
||||
- 协议下全部有效样本 `sample_status` 置为已作废(yzf),并写入 `void_date`。
|
||||
3. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。
|
||||
4. 人工【样本废弃】:仅将该样本置 yzf 并写 void_date/void_desc,不改接收结论;
|
||||
若协议下有效样本全部为 yzf,则自动作废协议(不联动接收结论)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.protocol_status_display import INACTIVE_PROTOCOL_STATUSES
|
||||
from app.core.utils import generate_uuid
|
||||
from app.models.models import (
|
||||
BizCollectionProtocol,
|
||||
@@ -23,9 +30,23 @@ from app.models.research_donation import BizResearchDonation, BizResearchDonatio
|
||||
LAB_VOID_TYPE_CODE = "sysfq"
|
||||
LAB_VOID_TYPE_LABEL = "实验室废弃"
|
||||
VOID_TYPE_DICT = "xyzflx"
|
||||
SAMPLE_VOID_STATUS = "yzf"
|
||||
|
||||
_AUTO_DISCARD_REMARK = "协议作废自动废弃"
|
||||
_AUTO_VOID_DESC = "全部样本接收废弃/拒收,系统自动作废"
|
||||
_AUTO_VOID_BY_SAMPLE_STATUS_DESC = "全部样本已作废,系统自动作废协议"
|
||||
|
||||
|
||||
def _void_date_yyyymmdd(
|
||||
*,
|
||||
void_time: Optional[datetime] = None,
|
||||
void_date: Optional[str] = None,
|
||||
) -> str:
|
||||
raw = (void_date or "").strip()
|
||||
if len(raw) == 8 and raw.isdigit():
|
||||
return raw
|
||||
ts = void_time or datetime.now()
|
||||
return ts.strftime("%Y%m%d")
|
||||
|
||||
|
||||
def ensure_lab_void_type(db: Session, *, tenant_no: str) -> str:
|
||||
@@ -204,7 +225,7 @@ def discard_receptions_for_voided_protocol(
|
||||
tenant_no: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> int:
|
||||
"""协议已作废后,将其下样本接收全部置为废弃。返回处理样本数。"""
|
||||
"""协议无效后,将其下样本接收全部置为废弃。返回处理样本数。"""
|
||||
src = (source or "").strip()
|
||||
pid = (protocol_id or "").strip()
|
||||
tenant = (tenant_no or "").strip()
|
||||
@@ -242,6 +263,75 @@ def discard_receptions_for_voided_protocol(
|
||||
return len(samples)
|
||||
|
||||
|
||||
def void_samples_for_inactive_protocol(
|
||||
db: Session,
|
||||
*,
|
||||
source: str,
|
||||
protocol_id: str,
|
||||
tenant_no: str,
|
||||
user_id: Optional[str] = None,
|
||||
void_time: Optional[datetime] = None,
|
||||
void_date: Optional[str] = None,
|
||||
) -> int:
|
||||
"""协议无效后,将其下有效样本状态一律置为已作废并写入 void_date。返回处理样本数。"""
|
||||
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 0
|
||||
|
||||
date_s = _void_date_yyyymmdd(void_time=void_time, void_date=void_date)
|
||||
now = datetime.now()
|
||||
if src == "cell_storage":
|
||||
samples: List[Union[BizProtocolSample, BizResearchDonationSample]] = list(
|
||||
_list_cell_samples(db, protocol_id=pid, tenant_no=tenant)
|
||||
)
|
||||
else:
|
||||
samples = list(_list_donation_samples(db, donation_id=pid, tenant_no=tenant))
|
||||
|
||||
for sample in samples:
|
||||
sample.sample_status = SAMPLE_VOID_STATUS
|
||||
sample.void_date = date_s
|
||||
sample.update_by = user_id
|
||||
sample.update_time = now
|
||||
db.add(sample)
|
||||
db.flush()
|
||||
return len(samples)
|
||||
|
||||
|
||||
def _resolve_protocol_void_time(
|
||||
db: Session,
|
||||
*,
|
||||
source: str,
|
||||
protocol_id: str,
|
||||
tenant_no: str,
|
||||
) -> Optional[datetime]:
|
||||
src = (source or "").strip()
|
||||
pid = (protocol_id or "").strip()
|
||||
tenant = (tenant_no or "").strip()
|
||||
if src == "cell_storage":
|
||||
obj = (
|
||||
db.query(BizCollectionProtocol)
|
||||
.filter(
|
||||
BizCollectionProtocol.id == pid,
|
||||
BizCollectionProtocol.tenant_no == tenant,
|
||||
BizCollectionProtocol.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return obj.void_time if obj else None
|
||||
obj = (
|
||||
db.query(BizResearchDonation)
|
||||
.filter(
|
||||
BizResearchDonation.id == pid,
|
||||
BizResearchDonation.tenant_no == tenant,
|
||||
BizResearchDonation.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return obj.void_time if obj else None
|
||||
|
||||
|
||||
def _all_samples_discarded(
|
||||
db: Session,
|
||||
*,
|
||||
@@ -299,7 +389,7 @@ def maybe_void_protocol_when_all_samples_discarded(
|
||||
if not obj:
|
||||
return False
|
||||
status = (obj.protocol_status or "").strip()
|
||||
if status in ("yzf", "sdfq"):
|
||||
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
|
||||
@@ -319,7 +409,8 @@ def maybe_void_protocol_when_all_samples_discarded(
|
||||
void_desc=_AUTO_VOID_DESC,
|
||||
void_type=void_type,
|
||||
commit=False,
|
||||
sync_reception_discard=False,
|
||||
# 接收已全部废弃;仍需同步样本状态为已作废
|
||||
sync_reception_discard=True,
|
||||
)
|
||||
return True
|
||||
|
||||
@@ -335,7 +426,7 @@ def maybe_void_protocol_when_all_samples_discarded(
|
||||
if not obj:
|
||||
return False
|
||||
status = (obj.donation_status or "").strip()
|
||||
if status in ("yzf", "sdfq"):
|
||||
if status in INACTIVE_PROTOCOL_STATUSES:
|
||||
return False
|
||||
|
||||
# 捐赠 change_status 默认 commit;此处内联等价逻辑避免提前提交。
|
||||
@@ -374,6 +465,169 @@ def maybe_void_protocol_when_all_samples_discarded(
|
||||
)
|
||||
db.add(obj)
|
||||
db.flush()
|
||||
# 接收已全部废弃;仍需同步样本状态为已作废
|
||||
after_protocol_voided(
|
||||
db,
|
||||
source="research_donation",
|
||||
protocol_id=pid,
|
||||
tenant_no=tenant,
|
||||
user_id=user_id,
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def _find_sample_for_reception(
|
||||
db: Session,
|
||||
*,
|
||||
reception: BizSampleReception,
|
||||
tenant_no: str,
|
||||
) -> tuple[str, Optional[Union[BizProtocolSample, BizResearchDonationSample]]]:
|
||||
source = (reception.reception_source or "cell_storage").strip() or "cell_storage"
|
||||
tenant = (tenant_no or "").strip()
|
||||
code = (reception.sample_code or "").strip()
|
||||
if source == "cell_storage":
|
||||
sid = (reception.protocol_sample_id or "").strip()
|
||||
if sid:
|
||||
obj = (
|
||||
db.query(BizProtocolSample)
|
||||
.filter(
|
||||
BizProtocolSample.id == sid,
|
||||
BizProtocolSample.tenant_no == tenant,
|
||||
BizProtocolSample.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if obj:
|
||||
return source, obj
|
||||
pid = (reception.collection_protocol_id or "").strip()
|
||||
if code and pid:
|
||||
return source, (
|
||||
db.query(BizProtocolSample)
|
||||
.filter(
|
||||
BizProtocolSample.collection_protocol_id == pid,
|
||||
BizProtocolSample.sample_code == code,
|
||||
BizProtocolSample.tenant_no == tenant,
|
||||
BizProtocolSample.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return source, None
|
||||
|
||||
sid = (reception.donation_sample_id or "").strip()
|
||||
if sid:
|
||||
obj = (
|
||||
db.query(BizResearchDonationSample)
|
||||
.filter(
|
||||
BizResearchDonationSample.id == sid,
|
||||
BizResearchDonationSample.tenant_no == tenant,
|
||||
BizResearchDonationSample.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if obj:
|
||||
return source, obj
|
||||
pid = (reception.research_donation_id or "").strip()
|
||||
if code and pid:
|
||||
return source, (
|
||||
db.query(BizResearchDonationSample)
|
||||
.filter(
|
||||
BizResearchDonationSample.research_donation_id == pid,
|
||||
BizResearchDonationSample.sample_code == code,
|
||||
BizResearchDonationSample.tenant_no == tenant,
|
||||
BizResearchDonationSample.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return source, None
|
||||
|
||||
|
||||
def _protocol_is_inactive(
|
||||
db: Session,
|
||||
*,
|
||||
source: str,
|
||||
protocol_id: str,
|
||||
tenant_no: str,
|
||||
) -> bool:
|
||||
src = (source or "").strip()
|
||||
pid = (protocol_id or "").strip()
|
||||
tenant = (tenant_no or "").strip()
|
||||
if not pid or not tenant:
|
||||
return False
|
||||
if src == "cell_storage":
|
||||
obj = (
|
||||
db.query(BizCollectionProtocol)
|
||||
.filter(
|
||||
BizCollectionProtocol.id == pid,
|
||||
BizCollectionProtocol.tenant_no == tenant,
|
||||
BizCollectionProtocol.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
status = (obj.protocol_status or "").strip() if obj else ""
|
||||
else:
|
||||
obj = (
|
||||
db.query(BizResearchDonation)
|
||||
.filter(
|
||||
BizResearchDonation.id == pid,
|
||||
BizResearchDonation.tenant_no == tenant,
|
||||
BizResearchDonation.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
status = (obj.donation_status or "").strip() if obj else ""
|
||||
return status in INACTIVE_PROTOCOL_STATUSES
|
||||
|
||||
|
||||
def void_sample_for_discarded_reception(
|
||||
db: Session,
|
||||
*,
|
||||
reception: BizSampleReception,
|
||||
tenant_no: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""单条接收废弃:仅将该样本置为已作废。"""
|
||||
_source, sample = _find_sample_for_reception(db, reception=reception, tenant_no=tenant_no)
|
||||
if not sample:
|
||||
return False
|
||||
now = datetime.now()
|
||||
sample.sample_status = SAMPLE_VOID_STATUS
|
||||
sample.void_date = _void_date_yyyymmdd(void_time=reception.reception_time or now)
|
||||
sample.update_by = user_id
|
||||
sample.update_time = now
|
||||
db.add(sample)
|
||||
db.flush()
|
||||
return True
|
||||
|
||||
|
||||
def clear_sample_void_for_accepted_reception(
|
||||
db: Session,
|
||||
*,
|
||||
reception: BizSampleReception,
|
||||
tenant_no: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""接收改回接收:协议仍有效且样本为 yzf 时,清空样本作废状态。"""
|
||||
source, sample = _find_sample_for_reception(db, reception=reception, tenant_no=tenant_no)
|
||||
if not sample:
|
||||
return False
|
||||
if (sample.sample_status or "").strip() != SAMPLE_VOID_STATUS:
|
||||
return False
|
||||
if source == "cell_storage":
|
||||
protocol_id = (reception.collection_protocol_id or "").strip()
|
||||
else:
|
||||
protocol_id = (reception.research_donation_id or "").strip()
|
||||
if _protocol_is_inactive(
|
||||
db, source=source, protocol_id=protocol_id, tenant_no=tenant_no
|
||||
):
|
||||
return False
|
||||
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)
|
||||
db.flush()
|
||||
return True
|
||||
|
||||
|
||||
@@ -384,23 +638,32 @@ def after_sample_reception_saved(
|
||||
tenant_no: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> None:
|
||||
"""样本接收保存后:若结论为废弃,尝试自动作废所属协议。"""
|
||||
if (reception.accept_conclusion or "").strip() != "bj":
|
||||
return
|
||||
"""样本接收保存后:同步该样本状态;若全部废弃则尝试自动作废协议。"""
|
||||
conclusion = (reception.accept_conclusion or "").strip()
|
||||
source = (reception.reception_source or "cell_storage").strip() or "cell_storage"
|
||||
if source == "cell_storage":
|
||||
protocol_id = (reception.collection_protocol_id or "").strip()
|
||||
else:
|
||||
protocol_id = (reception.research_donation_id or "").strip()
|
||||
if not protocol_id:
|
||||
|
||||
if conclusion == "bj":
|
||||
void_sample_for_discarded_reception(
|
||||
db, reception=reception, tenant_no=tenant_no, user_id=user_id
|
||||
)
|
||||
if protocol_id:
|
||||
maybe_void_protocol_when_all_samples_discarded(
|
||||
db,
|
||||
source=source,
|
||||
protocol_id=protocol_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
return
|
||||
maybe_void_protocol_when_all_samples_discarded(
|
||||
db,
|
||||
source=source,
|
||||
protocol_id=protocol_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
if conclusion == "js":
|
||||
clear_sample_void_for_accepted_reception(
|
||||
db, reception=reception, tenant_no=tenant_no, user_id=user_id
|
||||
)
|
||||
|
||||
|
||||
def after_protocol_voided(
|
||||
@@ -411,7 +674,7 @@ def after_protocol_voided(
|
||||
tenant_no: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> None:
|
||||
"""协议作废后:同步废弃其下全部样本接收。"""
|
||||
"""协议作废/属地废弃后:同步废弃样本接收,并将样本状态置为已作废。"""
|
||||
discard_receptions_for_voided_protocol(
|
||||
db,
|
||||
source=source,
|
||||
@@ -419,3 +682,234 @@ def after_protocol_voided(
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
void_samples_for_inactive_protocol(
|
||||
db,
|
||||
source=source,
|
||||
protocol_id=protocol_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
void_time=_resolve_protocol_void_time(
|
||||
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
|
||||
@@ -14,6 +14,7 @@ from app.models.models import (
|
||||
BizProtocolPaymentDetail,
|
||||
BizProtocolPaymentSchedule,
|
||||
BizProtocolPaymentTransfer,
|
||||
BizProtocolRefundRecord,
|
||||
BizProtocolSamplePayment,
|
||||
)
|
||||
|
||||
@@ -229,6 +230,197 @@ def _first_period_first_transfer_times(
|
||||
return {pid: _fmt_dt(t) for pid, t in earliest.items() if _fmt_dt(t)}
|
||||
|
||||
|
||||
def _received_amount_from_transfers(transfers: List[BizProtocolPaymentTransfer]) -> float:
|
||||
total = Decimal("0")
|
||||
for t in transfers:
|
||||
st = (t.pay_status or "").strip()
|
||||
if st in ("yjf", "jfqrz"):
|
||||
total += t.transfer_amount or Decimal("0")
|
||||
return float(total)
|
||||
|
||||
|
||||
def _v2_schedule_detail_rows(
|
||||
schedules: List[BizProtocolPaymentSchedule],
|
||||
transfers: List[BizProtocolPaymentTransfer],
|
||||
pay_mode: str,
|
||||
) -> List[Dict[str, Any]]:
|
||||
by_schedule: Dict[str, List[BizProtocolPaymentTransfer]] = {}
|
||||
for t in transfers:
|
||||
sid = (t.schedule_id or "").strip()
|
||||
if sid:
|
||||
by_schedule.setdefault(sid, []).append(t)
|
||||
active = [
|
||||
s
|
||||
for s in schedules
|
||||
if (s.schedule_status or "").strip() != "void"
|
||||
]
|
||||
active.sort(
|
||||
key=lambda s: (
|
||||
s.schedule_no if s.schedule_no is not None else 10_000,
|
||||
s.order_num if s.order_num is not None else 0,
|
||||
s.create_time or datetime.min,
|
||||
)
|
||||
)
|
||||
rows: List[Dict[str, Any]] = []
|
||||
for idx, sch in enumerate(active):
|
||||
sch_transfers = by_schedule.get(sch.id, [])
|
||||
paid = [
|
||||
t
|
||||
for t in sch_transfers
|
||||
if (t.pay_status or "").strip() in ("yjf", "jfqrz")
|
||||
]
|
||||
paid_amount = _received_amount_from_transfers(paid) if paid else None
|
||||
statuses = [(t.pay_status or "").strip() for t in sch_transfers if (t.pay_status or "").strip()]
|
||||
if "jfqrz" in statuses:
|
||||
st = "jfqrz"
|
||||
elif "yjf" in statuses and paid:
|
||||
st = "yjf"
|
||||
elif statuses:
|
||||
st = statuses[0]
|
||||
else:
|
||||
st = "dfj"
|
||||
times = [t.transfer_time for t in paid if t.transfer_time is not None]
|
||||
transfer_time = _fmt_dt(min(times)) if times else ""
|
||||
inst_no = sch.schedule_no
|
||||
if pay_mode in ("fq", "djfq") and inst_no is not None:
|
||||
label = f"第{inst_no}期"
|
||||
else:
|
||||
label = f"缴费{idx + 1}"
|
||||
rows.append(
|
||||
{
|
||||
"installmentNo": inst_no,
|
||||
"installmentLabel": label,
|
||||
"installmentDueDate": _fmt_ymd(sch.due_date),
|
||||
"dueAmount": _dec(sch.due_amount),
|
||||
"transferAmount": paid_amount,
|
||||
"refundAmount": None,
|
||||
"payStatus": st,
|
||||
"payStatusLabel": _PAY_STATUS_LABELS.get(st, st or "—"),
|
||||
"transferTime": transfer_time,
|
||||
}
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def _load_v2_protocol_payment_amounts(
|
||||
db: Session,
|
||||
protocol_ids: List[str],
|
||||
tenant_no: str,
|
||||
) -> Dict[str, Dict[str, Any]]:
|
||||
"""按协议汇总 V2 样本缴费合同额、已收、明细与退费(仅 list/export 摘要用)。"""
|
||||
ids = [x.strip() for x in protocol_ids if (x or "").strip()]
|
||||
if not ids:
|
||||
return {}
|
||||
samples = (
|
||||
db.query(BizProtocolSamplePayment)
|
||||
.filter(
|
||||
BizProtocolSamplePayment.collection_protocol_id.in_(ids),
|
||||
BizProtocolSamplePayment.tenant_no == tenant_no,
|
||||
BizProtocolSamplePayment.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
if not samples:
|
||||
return {}
|
||||
schedules = (
|
||||
db.query(BizProtocolPaymentSchedule)
|
||||
.filter(
|
||||
BizProtocolPaymentSchedule.collection_protocol_id.in_(ids),
|
||||
BizProtocolPaymentSchedule.tenant_no == tenant_no,
|
||||
BizProtocolPaymentSchedule.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
transfers = (
|
||||
db.query(BizProtocolPaymentTransfer)
|
||||
.filter(
|
||||
BizProtocolPaymentTransfer.collection_protocol_id.in_(ids),
|
||||
BizProtocolPaymentTransfer.tenant_no == tenant_no,
|
||||
BizProtocolPaymentTransfer.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
refunds = (
|
||||
db.query(BizProtocolRefundRecord)
|
||||
.filter(
|
||||
BizProtocolRefundRecord.collection_protocol_id.in_(ids),
|
||||
BizProtocolRefundRecord.tenant_no == tenant_no,
|
||||
BizProtocolRefundRecord.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
samples_by: Dict[str, List[BizProtocolSamplePayment]] = {}
|
||||
for sp in samples:
|
||||
samples_by.setdefault(sp.collection_protocol_id, []).append(sp)
|
||||
schedules_by: Dict[str, List[BizProtocolPaymentSchedule]] = {}
|
||||
for s in schedules:
|
||||
schedules_by.setdefault(s.collection_protocol_id, []).append(s)
|
||||
transfers_by: Dict[str, List[BizProtocolPaymentTransfer]] = {}
|
||||
for t in transfers:
|
||||
transfers_by.setdefault(t.collection_protocol_id, []).append(t)
|
||||
refund_by: Dict[str, float] = {}
|
||||
refund_seen: Dict[str, bool] = {}
|
||||
for r in refunds:
|
||||
amt = _dec(r.refund_amount)
|
||||
if amt is None:
|
||||
continue
|
||||
refund_seen[r.collection_protocol_id] = True
|
||||
refund_by[r.collection_protocol_id] = refund_by.get(r.collection_protocol_id, 0.0) + float(amt)
|
||||
|
||||
out: Dict[str, Dict[str, Any]] = {}
|
||||
for pid, sp_list in samples_by.items():
|
||||
modes = {(sp.pay_mode or "").strip() for sp in sp_list if (sp.pay_mode or "").strip()}
|
||||
ordered_modes = sorted(
|
||||
modes,
|
||||
key=lambda mode: ({"dj": 0, "fq": 1, "djfq": 2, "fgd": 3}.get(mode, 99), mode),
|
||||
)
|
||||
if modes == {"dj", "fq"}:
|
||||
pay_mode = "djfq"
|
||||
else:
|
||||
pay_mode = "+".join(ordered_modes) if ordered_modes else ""
|
||||
contract_total = Decimal("0")
|
||||
has_contract = False
|
||||
for sp in sp_list:
|
||||
if sp.contract_amount is not None:
|
||||
has_contract = True
|
||||
contract_total += sp.contract_amount or Decimal("0")
|
||||
contract = float(contract_total) if has_contract else None
|
||||
proto_transfers = transfers_by.get(pid, [])
|
||||
received = _received_amount_from_transfers(proto_transfers)
|
||||
pending = max(contract - received, 0) if contract is not None else None
|
||||
detail_rows = _v2_schedule_detail_rows(
|
||||
schedules_by.get(pid, []),
|
||||
proto_transfers,
|
||||
pay_mode,
|
||||
)
|
||||
statuses = [(t.pay_status or "").strip() for t in proto_transfers]
|
||||
overall = _protocol_overall_status(statuses, contract, pending)
|
||||
hint = _protocol_status_hint(pay_mode, statuses) or overall["overallPayStatusLabel"]
|
||||
installment_count = None
|
||||
if pay_mode in ("fq", "djfq"):
|
||||
installment_count = len(
|
||||
{
|
||||
d.get("installmentNo")
|
||||
for d in detail_rows
|
||||
if d.get("installmentNo") is not None
|
||||
}
|
||||
) or len(detail_rows)
|
||||
payload: Dict[str, Any] = {
|
||||
"payMode": pay_mode,
|
||||
"contractAmount": contract,
|
||||
"receivedAmount": received,
|
||||
"pendingAmount": pending,
|
||||
"statusHint": hint,
|
||||
"installmentCount": installment_count,
|
||||
"paymentDetails": detail_rows,
|
||||
**overall,
|
||||
}
|
||||
if refund_seen.get(pid):
|
||||
payload["refundAmount"] = refund_by.get(pid, 0.0)
|
||||
out[pid] = payload
|
||||
return out
|
||||
|
||||
|
||||
def build_protocol_payment_summaries(
|
||||
db: Session,
|
||||
protocol_ids: List[str],
|
||||
@@ -263,6 +455,7 @@ def build_protocol_payment_summaries(
|
||||
):
|
||||
details_by_payment.setdefault(d.payment_id, []).append(d)
|
||||
sample_modes: Dict[str, set] = {}
|
||||
v2_amounts: Dict[str, Dict[str, Any]] = {}
|
||||
if include_sample_payment_modes:
|
||||
for pid, mode in db.query(
|
||||
BizProtocolSamplePayment.collection_protocol_id,
|
||||
@@ -274,6 +467,7 @@ def build_protocol_payment_summaries(
|
||||
).all():
|
||||
if mode:
|
||||
sample_modes.setdefault(pid, set()).add(mode)
|
||||
v2_amounts = _load_v2_protocol_payment_amounts(db, ids, tenant_no)
|
||||
first_pay_map = _first_period_first_transfer_times(db, ids, tenant_no)
|
||||
out: Dict[str, Dict[str, Any]] = {}
|
||||
for pid in ids:
|
||||
@@ -285,7 +479,8 @@ def build_protocol_payment_summaries(
|
||||
)
|
||||
first_pay = first_pay_map.get(pid) or ""
|
||||
modes = sample_modes.get(pid, set())
|
||||
if not summary and not first_pay and not modes:
|
||||
v2 = v2_amounts.get(pid)
|
||||
if not summary and not first_pay and not modes and not v2:
|
||||
continue
|
||||
if not summary:
|
||||
summary = {
|
||||
@@ -294,6 +489,7 @@ def build_protocol_payment_summaries(
|
||||
"contractAmount": None,
|
||||
"receivedAmount": None,
|
||||
"pendingAmount": None,
|
||||
"refundAmount": None,
|
||||
"statusHint": "",
|
||||
"installmentCount": None,
|
||||
"paymentDetails": [],
|
||||
@@ -309,6 +505,27 @@ def build_protocol_payment_summaries(
|
||||
labels = {**_PAY_MODE_LABELS, "fgd": "分改趸"}
|
||||
summary["payMode"] = "djfq" if modes == {"dj", "fq"} else "+".join(ordered_modes)
|
||||
summary["payModeLabel"] = "+".join(labels.get(mode, mode) for mode in ordered_modes)
|
||||
# V1 摘要缺已收金额时,用 V2 样本缴费补齐(自存表导出 / 协议列表依赖)。
|
||||
if v2 and summary.get("receivedAmount") is None:
|
||||
if summary.get("contractAmount") is None:
|
||||
summary["contractAmount"] = v2.get("contractAmount")
|
||||
summary["receivedAmount"] = v2.get("receivedAmount")
|
||||
if summary.get("pendingAmount") is None:
|
||||
summary["pendingAmount"] = v2.get("pendingAmount")
|
||||
if not summary.get("paymentDetails"):
|
||||
summary["paymentDetails"] = v2.get("paymentDetails") or []
|
||||
if summary.get("installmentCount") is None:
|
||||
summary["installmentCount"] = v2.get("installmentCount")
|
||||
if summary.get("refundAmount") is None and "refundAmount" in v2:
|
||||
summary["refundAmount"] = v2.get("refundAmount")
|
||||
for key in (
|
||||
"statusHint",
|
||||
"overallPayStatus",
|
||||
"overallPayStatusLabel",
|
||||
"overallPayStatusTagType",
|
||||
):
|
||||
if not summary.get(key) and v2.get(key):
|
||||
summary[key] = v2.get(key)
|
||||
if first_pay:
|
||||
summary["firstPayTransferTime"] = first_pay
|
||||
out[pid] = summary
|
||||
|
||||
@@ -2,18 +2,78 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Dict, Iterable, List, Optional, Set
|
||||
|
||||
SAMPLE_TYPE_NAME_PERINATAL_HSC = "围产期造血干细胞"
|
||||
SAMPLE_TYPE_NAME_UC_MSC = "脐带间充质干细胞"
|
||||
SAMPLE_TYPE_KEY_PERINATAL_HSC = "perinatal_hsc"
|
||||
SAMPLE_TYPE_KEY_UC_MSC = "uc_msc"
|
||||
|
||||
ACL_SCOPE_QC = "qc"
|
||||
ACL_SCOPE_PRODUCTION = "production"
|
||||
ACL_SCOPES = frozenset({ACL_SCOPE_QC, ACL_SCOPE_PRODUCTION})
|
||||
ACL_CONFIG_MENU = "cell-storage:sample-info:storage-cert-qc-acl"
|
||||
|
||||
_NAME_TO_KEY = {
|
||||
SAMPLE_TYPE_NAME_PERINATAL_HSC: SAMPLE_TYPE_KEY_PERINATAL_HSC,
|
||||
SAMPLE_TYPE_NAME_UC_MSC: SAMPLE_TYPE_KEY_UC_MSC,
|
||||
}
|
||||
|
||||
# 与 web-admin STORAGE_CERT_QC_GROUPS 对齐的合法 payload 键(两类型并集)。
|
||||
ALL_STORAGE_CERT_QC_FIELD_KEYS = frozenset(
|
||||
{
|
||||
"collection_time",
|
||||
"transport_temp_c",
|
||||
"receive_time",
|
||||
"cryo_volume_ml",
|
||||
"tnc_1e8",
|
||||
"cd34_count_1e6",
|
||||
"cd34_cd45dim_1e5",
|
||||
"viability_pct",
|
||||
"bacteria_test",
|
||||
"hbsag",
|
||||
"anti_hcv",
|
||||
"anti_tp",
|
||||
"anti_hiv",
|
||||
"cmv_igm",
|
||||
"mother_hbsag",
|
||||
"mother_hbv_dna",
|
||||
"mother_anti_hcv",
|
||||
"mother_hcv_rna",
|
||||
"mother_anti_tp",
|
||||
"mother_cmv_igm",
|
||||
"mother_anti_hiv",
|
||||
"mother_hiv1_rna",
|
||||
"hla_typing",
|
||||
"storage_date",
|
||||
"storage_years",
|
||||
"result_comment",
|
||||
"report_issue_date",
|
||||
"storage_tube_count",
|
||||
"available_cell_type",
|
||||
"available_cell_count_1e7",
|
||||
"available_viability_pct",
|
||||
"endotoxin_test",
|
||||
"fungus_test",
|
||||
"mycoplasma_test",
|
||||
"available_cell_morphology",
|
||||
"available_immunophenotype",
|
||||
"result_judgment",
|
||||
"storage_date_p2",
|
||||
"freeze_method",
|
||||
"storage_temp",
|
||||
}
|
||||
)
|
||||
|
||||
# 脐带间充质储存证不收录母亲血液三项核酸检测。
|
||||
UC_MSC_EXCLUDED_PAYLOAD_KEYS = frozenset(
|
||||
{
|
||||
"mother_hbv_dna",
|
||||
"mother_hcv_rna",
|
||||
"mother_hiv1_rna",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def resolve_sample_type_key(sample_type_name: Optional[str]) -> Optional[str]:
|
||||
name = (sample_type_name or "").strip()
|
||||
@@ -24,6 +84,13 @@ def supports_storage_cert_qc(sample_type_name: Optional[str]) -> bool:
|
||||
return resolve_sample_type_key(sample_type_name) is not None
|
||||
|
||||
|
||||
def legal_field_keys_for_type(sample_type_key: Optional[str]) -> Set[str]:
|
||||
keys = set(ALL_STORAGE_CERT_QC_FIELD_KEYS)
|
||||
if sample_type_key == SAMPLE_TYPE_KEY_UC_MSC:
|
||||
keys -= UC_MSC_EXCLUDED_PAYLOAD_KEYS
|
||||
return keys
|
||||
|
||||
|
||||
def normalize_payload(payload: Any) -> Dict[str, Any]:
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("payload 必须为对象")
|
||||
@@ -38,6 +105,16 @@ def normalize_payload(payload: Any) -> Dict[str, Any]:
|
||||
return out
|
||||
|
||||
|
||||
def sanitize_payload_for_type(
|
||||
payload: Dict[str, Any],
|
||||
sample_type_key: Optional[str],
|
||||
) -> Dict[str, Any]:
|
||||
"""按样本类型去掉不应展示/落库的键。"""
|
||||
if sample_type_key != SAMPLE_TYPE_KEY_UC_MSC:
|
||||
return payload
|
||||
return {key: value for key, value in payload.items() if key not in UC_MSC_EXCLUDED_PAYLOAD_KEYS}
|
||||
|
||||
|
||||
def dumps_payload(payload: Dict[str, Any]) -> str:
|
||||
return json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
@@ -54,6 +131,62 @@ def loads_payload(raw: Optional[str]) -> Dict[str, Any]:
|
||||
return data
|
||||
|
||||
|
||||
def dumps_field_keys(keys: Iterable[str]) -> str:
|
||||
cleaned = sorted({str(k).strip() for k in keys if str(k).strip()})
|
||||
return json.dumps(cleaned, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
def loads_field_keys(raw: Optional[str]) -> List[str]:
|
||||
if not raw:
|
||||
return []
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except (TypeError, ValueError):
|
||||
return []
|
||||
if not isinstance(data, list):
|
||||
return []
|
||||
out: List[str] = []
|
||||
seen = set()
|
||||
for item in data:
|
||||
key = str(item or "").strip()
|
||||
if not key or key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append(key)
|
||||
return out
|
||||
|
||||
|
||||
def _payload_value_text(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def merge_payload_with_acl(
|
||||
*,
|
||||
existing: Dict[str, Any],
|
||||
incoming: Dict[str, Any],
|
||||
editable_keys: Iterable[str],
|
||||
sample_type_key: Optional[str],
|
||||
) -> Dict[str, Any]:
|
||||
"""仅合并有权字段;无权字段若相对原值变化则拒绝。"""
|
||||
allowed = {str(k).strip() for k in editable_keys if str(k).strip()}
|
||||
if not allowed:
|
||||
raise PermissionError("无字段编辑权限")
|
||||
clean_incoming = sanitize_payload_for_type(normalize_payload(incoming), sample_type_key)
|
||||
base = sanitize_payload_for_type(dict(existing or {}), sample_type_key)
|
||||
for key, value in clean_incoming.items():
|
||||
if key in allowed:
|
||||
continue
|
||||
if _payload_value_text(base.get(key)) != _payload_value_text(value):
|
||||
raise PermissionError(f"无权修改字段: {key}")
|
||||
merged = dict(base)
|
||||
for key in allowed:
|
||||
if key in clean_incoming:
|
||||
merged[key] = clean_incoming[key]
|
||||
return sanitize_payload_for_type(merged, sample_type_key)
|
||||
|
||||
|
||||
def empty_detail(
|
||||
*,
|
||||
sample_code: str,
|
||||
|
||||
@@ -168,6 +168,11 @@ _HSC_SEROLOGY_RULES = (
|
||||
)
|
||||
|
||||
_MOTHER_SEROLOGY_RULES = tuple(rule for rule in _HSC_SEROLOGY_RULES if str(rule[0]).startswith("mother_"))
|
||||
# 脐带间充质不预填母亲血液三项核酸。
|
||||
_UC_MSC_EXCLUDED_MOTHER_KEYS = frozenset({"mother_hbv_dna", "mother_hcv_rna", "mother_hiv1_rna"})
|
||||
_MOTHER_SEROLOGY_RULES_UC_MSC = tuple(
|
||||
rule for rule in _MOTHER_SEROLOGY_RULES if str(rule[0]) not in _UC_MSC_EXCLUDED_MOTHER_KEYS
|
||||
)
|
||||
|
||||
|
||||
def _serology_from_tasks(
|
||||
@@ -278,9 +283,19 @@ def _process_qual_from_tasks(tasks: List[Dict[str, Any]]) -> Dict[str, str]:
|
||||
return out
|
||||
|
||||
|
||||
def _fill_shared_mother(suggested: Dict[str, str], tasks: Optional[List[Dict[str, Any]]]) -> None:
|
||||
def _fill_shared_mother(
|
||||
suggested: Dict[str, str],
|
||||
tasks: Optional[List[Dict[str, Any]]],
|
||||
*,
|
||||
sample_type_key: str,
|
||||
) -> None:
|
||||
"""只补母亲血液空项。共享任务里的脐血不参与。"""
|
||||
shared = _serology_from_tasks(tasks or [], _MOTHER_SEROLOGY_RULES)
|
||||
rules = (
|
||||
_MOTHER_SEROLOGY_RULES_UC_MSC
|
||||
if sample_type_key == "uc_msc"
|
||||
else _MOTHER_SEROLOGY_RULES
|
||||
)
|
||||
shared = _serology_from_tasks(tasks or [], rules)
|
||||
for key, value in shared.items():
|
||||
suggested.setdefault(key, value)
|
||||
|
||||
@@ -330,7 +345,7 @@ def build_suggested(
|
||||
if count:
|
||||
suggested["available_cell_count_1e7"] = count
|
||||
suggested.update(_process_qual_from_tasks(process_tasks or []))
|
||||
suggested.update(_serology_from_tasks(gate_tasks or [], _MOTHER_SEROLOGY_RULES))
|
||||
suggested.update(_serology_from_tasks(gate_tasks or [], _MOTHER_SEROLOGY_RULES_UC_MSC))
|
||||
suggested.setdefault("bacteria_test", "阴性")
|
||||
suggested.setdefault("result_judgment", "合格")
|
||||
if freeze:
|
||||
@@ -338,7 +353,7 @@ def build_suggested(
|
||||
suggested.update(_FIXED_COMMON)
|
||||
suggested.update(_FIXED_UC_MSC)
|
||||
if sample_type_key in ("perinatal_hsc", "uc_msc"):
|
||||
_fill_shared_mother(suggested, shared_mother_tasks)
|
||||
_fill_shared_mother(suggested, shared_mother_tasks, sample_type_key=sample_type_key)
|
||||
return {key: value for key, value in suggested.items() if str(value).strip()}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,472 @@
|
||||
"""确保 UC 入库编码对应的 5 步内置工艺路线 / 任务组合存在。
|
||||
|
||||
步骤顺序(业务确认):
|
||||
1. 脐带MSC原代细胞培养
|
||||
2. 脐带MSC原代细胞培养半换液
|
||||
3. 脐带MSC原代二次贴壁
|
||||
4. 脐带MSC原代重铺操作
|
||||
5. 干细胞冻存
|
||||
|
||||
内容从既有「干细胞培养(内置模版)」按工序代码拷贝,排除传代。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.models import (
|
||||
BizProcessRoute,
|
||||
BizProcessRouteStep,
|
||||
BizProcessRouteStepConsumable,
|
||||
BizProcessRouteStepDataCollection,
|
||||
BizProcessRouteStepOutput,
|
||||
BizProcessRouteStepReagent,
|
||||
BizProductionTaskSet,
|
||||
BizProductionTaskSetItem,
|
||||
)
|
||||
from app.core.utils import generate_uuid
|
||||
from app.utils.lab_storage_code_task_set import (
|
||||
BC_MSC_BUILTIN_SET_NAME,
|
||||
UC_MSC_BUILTIN_SET_NAME,
|
||||
)
|
||||
|
||||
UC_MSC_ROUTE_CODE = "MSC原代-UC-BUILTIN"
|
||||
UC_MSC_ROUTE_NAME = UC_MSC_BUILTIN_SET_NAME
|
||||
SOURCE_MSC_ROUTE_CODE = "MSC培养-BUILTIN"
|
||||
SOURCE_MSC_ROUTE_NAME = BC_MSC_BUILTIN_SET_NAME
|
||||
|
||||
# process_code → 目标 step_order
|
||||
UC_MSC_STEP_ORDER: List[str] = [
|
||||
"SOP-SC-003-E01-01", # 原代细胞培养
|
||||
"SOP-SC-004-E01-01", # 半换液
|
||||
"SOP-SC-006-E01-01", # 二次贴壁
|
||||
"SOP-SC-005-E01-01", # 重铺
|
||||
"SOP-SC-008-E01-01", # 冻存
|
||||
]
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now()
|
||||
|
||||
|
||||
def get_uc_msc_builtin_set(
|
||||
db: Session, *, tenant_no: str
|
||||
) -> Optional[BizProductionTaskSet]:
|
||||
return (
|
||||
db.query(BizProductionTaskSet)
|
||||
.filter(
|
||||
BizProductionTaskSet.tenant_no == tenant_no,
|
||||
BizProductionTaskSet.set_name == UC_MSC_BUILTIN_SET_NAME,
|
||||
BizProductionTaskSet.is_builtin == "1",
|
||||
BizProductionTaskSet.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _find_source_route(db: Session, *, tenant_no: str) -> BizProcessRoute:
|
||||
route = (
|
||||
db.query(BizProcessRoute)
|
||||
.filter(
|
||||
BizProcessRoute.tenant_no == tenant_no,
|
||||
BizProcessRoute.route_code == SOURCE_MSC_ROUTE_CODE,
|
||||
BizProcessRoute.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if route:
|
||||
return route
|
||||
route = (
|
||||
db.query(BizProcessRoute)
|
||||
.filter(
|
||||
BizProcessRoute.tenant_no == tenant_no,
|
||||
BizProcessRoute.route_name == SOURCE_MSC_ROUTE_NAME,
|
||||
BizProcessRoute.is_builtin == "1",
|
||||
BizProcessRoute.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not route:
|
||||
raise ValueError(
|
||||
f"缺少源工艺路线 {SOURCE_MSC_ROUTE_CODE}/{SOURCE_MSC_ROUTE_NAME},无法创建 UC 模版"
|
||||
)
|
||||
return route
|
||||
|
||||
|
||||
def _clone_step_children(
|
||||
db: Session,
|
||||
*,
|
||||
src_step_id: str,
|
||||
dst_step_id: str,
|
||||
tenant_no: str,
|
||||
user_id: Optional[str],
|
||||
create_dept_id: str,
|
||||
now: datetime,
|
||||
) -> None:
|
||||
reagent_rows = (
|
||||
db.query(BizProcessRouteStepReagent)
|
||||
.filter(
|
||||
BizProcessRouteStepReagent.step_id == src_step_id,
|
||||
BizProcessRouteStepReagent.tenant_no == tenant_no,
|
||||
BizProcessRouteStepReagent.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for r in reagent_rows:
|
||||
db.add(
|
||||
BizProcessRouteStepReagent(
|
||||
id=generate_uuid(),
|
||||
step_id=dst_step_id,
|
||||
reagent_code=r.reagent_code,
|
||||
reagent_name=r.reagent_name,
|
||||
spec=r.spec,
|
||||
standard_usage=r.standard_usage,
|
||||
unit=r.unit,
|
||||
is_key_material=r.is_key_material,
|
||||
tenant_no=tenant_no,
|
||||
order_num=r.order_num,
|
||||
remark=r.remark,
|
||||
create_by=user_id,
|
||||
create_dept_id=create_dept_id or "",
|
||||
create_time=now,
|
||||
update_by=user_id,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
)
|
||||
|
||||
consumable_rows = (
|
||||
db.query(BizProcessRouteStepConsumable)
|
||||
.filter(
|
||||
BizProcessRouteStepConsumable.step_id == src_step_id,
|
||||
BizProcessRouteStepConsumable.tenant_no == tenant_no,
|
||||
BizProcessRouteStepConsumable.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for c in consumable_rows:
|
||||
db.add(
|
||||
BizProcessRouteStepConsumable(
|
||||
id=generate_uuid(),
|
||||
step_id=dst_step_id,
|
||||
consumable_code=c.consumable_code,
|
||||
consumable_name=c.consumable_name,
|
||||
spec_model=c.spec_model,
|
||||
standard_usage=c.standard_usage,
|
||||
unit=c.unit,
|
||||
is_required=c.is_required,
|
||||
remark=c.remark,
|
||||
tenant_no=tenant_no,
|
||||
order_num=c.order_num,
|
||||
create_by=user_id,
|
||||
create_dept_id=create_dept_id or "",
|
||||
create_time=now,
|
||||
update_by=user_id,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
)
|
||||
|
||||
output_rows = (
|
||||
db.query(BizProcessRouteStepOutput)
|
||||
.filter(
|
||||
BizProcessRouteStepOutput.step_id == src_step_id,
|
||||
BizProcessRouteStepOutput.tenant_no == tenant_no,
|
||||
BizProcessRouteStepOutput.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for o in output_rows:
|
||||
db.add(
|
||||
BizProcessRouteStepOutput(
|
||||
id=generate_uuid(),
|
||||
step_id=dst_step_id,
|
||||
output_type_id=o.output_type_id,
|
||||
output_name=o.output_name,
|
||||
output_barcode=o.output_barcode,
|
||||
tenant_no=tenant_no,
|
||||
order_num=o.order_num,
|
||||
remark=o.remark,
|
||||
create_by=user_id,
|
||||
create_dept_id=create_dept_id or "",
|
||||
create_time=now,
|
||||
update_by=user_id,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
)
|
||||
|
||||
dc_rows = (
|
||||
db.query(BizProcessRouteStepDataCollection)
|
||||
.filter(
|
||||
BizProcessRouteStepDataCollection.step_id == src_step_id,
|
||||
BizProcessRouteStepDataCollection.tenant_no == tenant_no,
|
||||
BizProcessRouteStepDataCollection.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for d in dc_rows:
|
||||
db.add(
|
||||
BizProcessRouteStepDataCollection(
|
||||
id=generate_uuid(),
|
||||
step_id=dst_step_id,
|
||||
collection_name=d.collection_name,
|
||||
unit=d.unit,
|
||||
tenant_no=tenant_no,
|
||||
order_num=d.order_num,
|
||||
remark=d.remark,
|
||||
create_by=user_id,
|
||||
create_dept_id=create_dept_id or "",
|
||||
create_time=now,
|
||||
update_by=user_id,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _source_steps_by_code(
|
||||
db: Session, *, route_id: str, tenant_no: str
|
||||
) -> Dict[str, BizProcessRouteStep]:
|
||||
rows = (
|
||||
db.query(BizProcessRouteStep)
|
||||
.filter(
|
||||
BizProcessRouteStep.route_id == route_id,
|
||||
BizProcessRouteStep.tenant_no == tenant_no,
|
||||
BizProcessRouteStep.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
out: Dict[str, BizProcessRouteStep] = {}
|
||||
for row in rows:
|
||||
code = (row.process_code or "").strip()
|
||||
if code and code not in out:
|
||||
out[code] = row
|
||||
return out
|
||||
|
||||
|
||||
def ensure_uc_msc_builtin_template(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
user_id: Optional[str] = None,
|
||||
create_dept_id: str = "",
|
||||
) -> Dict[str, Any]:
|
||||
"""幂等创建 UC 5 步内置路线与任务组合;已存在则直接返回。"""
|
||||
existing = get_uc_msc_builtin_set(db, tenant_no=tenant_no)
|
||||
if existing and (existing.status or "1") == "1":
|
||||
item = (
|
||||
db.query(BizProductionTaskSetItem)
|
||||
.filter(
|
||||
BizProductionTaskSetItem.set_id == existing.id,
|
||||
BizProductionTaskSetItem.tenant_no == tenant_no,
|
||||
BizProductionTaskSetItem.del_flag == 0,
|
||||
)
|
||||
.order_by(
|
||||
BizProductionTaskSetItem.order_num.asc(),
|
||||
BizProductionTaskSetItem.create_time.asc(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if item and item.route_id:
|
||||
route = (
|
||||
db.query(BizProcessRoute)
|
||||
.filter(
|
||||
BizProcessRoute.id == item.route_id,
|
||||
BizProcessRoute.tenant_no == tenant_no,
|
||||
BizProcessRoute.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
step_count = (
|
||||
db.query(BizProcessRouteStep.id)
|
||||
.filter(
|
||||
BizProcessRouteStep.route_id == item.route_id,
|
||||
BizProcessRouteStep.tenant_no == tenant_no,
|
||||
BizProcessRouteStep.del_flag == 0,
|
||||
)
|
||||
.count()
|
||||
)
|
||||
if route and step_count >= len(UC_MSC_STEP_ORDER):
|
||||
return {
|
||||
"created": False,
|
||||
"setId": existing.id,
|
||||
"setName": existing.set_name,
|
||||
"routeId": route.id,
|
||||
"routeCode": route.route_code,
|
||||
"stepCount": step_count,
|
||||
}
|
||||
|
||||
source = _find_source_route(db, tenant_no=tenant_no)
|
||||
by_code = _source_steps_by_code(db, route_id=source.id, tenant_no=tenant_no)
|
||||
missing = [c for c in UC_MSC_STEP_ORDER if c not in by_code]
|
||||
if missing:
|
||||
raise ValueError(
|
||||
"源工艺路线缺少工序,无法创建 UC 模版:" + "、".join(missing)
|
||||
)
|
||||
|
||||
now = _now()
|
||||
route = (
|
||||
db.query(BizProcessRoute)
|
||||
.filter(
|
||||
BizProcessRoute.tenant_no == tenant_no,
|
||||
BizProcessRoute.route_code == UC_MSC_ROUTE_CODE,
|
||||
BizProcessRoute.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not route:
|
||||
route = BizProcessRoute(
|
||||
id=generate_uuid(),
|
||||
route_code=UC_MSC_ROUTE_CODE,
|
||||
route_name=UC_MSC_ROUTE_NAME,
|
||||
product_type_id=source.product_type_id,
|
||||
version=source.version,
|
||||
is_current="0",
|
||||
equipment_ids=source.equipment_ids,
|
||||
equipment_name=source.equipment_name,
|
||||
tenant_no=tenant_no,
|
||||
order_num=0,
|
||||
remark="内置模版:UC 入库编码自动派发(5 步,不含传代)",
|
||||
is_builtin="1",
|
||||
create_by=user_id,
|
||||
create_dept_id=create_dept_id or "",
|
||||
create_time=now,
|
||||
update_by=user_id,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
db.add(route)
|
||||
db.flush()
|
||||
else:
|
||||
route.route_name = UC_MSC_ROUTE_NAME
|
||||
route.is_builtin = "1"
|
||||
route.update_by = user_id
|
||||
route.update_time = now
|
||||
db.add(route)
|
||||
|
||||
# 重建步骤(幂等:软删旧步骤后按目标顺序插入)
|
||||
old_steps = (
|
||||
db.query(BizProcessRouteStep)
|
||||
.filter(
|
||||
BizProcessRouteStep.route_id == route.id,
|
||||
BizProcessRouteStep.tenant_no == tenant_no,
|
||||
BizProcessRouteStep.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for s in old_steps:
|
||||
s.del_flag = 1
|
||||
s.update_by = user_id
|
||||
s.update_time = now
|
||||
db.add(s)
|
||||
db.flush()
|
||||
|
||||
for order, code in enumerate(UC_MSC_STEP_ORDER, start=1):
|
||||
src = by_code[code]
|
||||
new_step = BizProcessRouteStep(
|
||||
id=generate_uuid(),
|
||||
route_id=route.id,
|
||||
process_id=src.process_id,
|
||||
step_order=order,
|
||||
process_code=src.process_code,
|
||||
category_id=src.category_id,
|
||||
process_name=src.process_name,
|
||||
description=src.description,
|
||||
equipment_ids=src.equipment_ids,
|
||||
equipment_name=src.equipment_name,
|
||||
estimated_duration=src.estimated_duration,
|
||||
sop_ids=src.sop_ids,
|
||||
sop_content=src.sop_content,
|
||||
tenant_no=tenant_no,
|
||||
order_num=order,
|
||||
remark=src.remark,
|
||||
create_by=user_id,
|
||||
create_dept_id=create_dept_id or "",
|
||||
create_time=now,
|
||||
update_by=user_id,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
db.add(new_step)
|
||||
db.flush()
|
||||
_clone_step_children(
|
||||
db,
|
||||
src_step_id=src.id,
|
||||
dst_step_id=new_step.id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
create_dept_id=create_dept_id or "",
|
||||
now=now,
|
||||
)
|
||||
|
||||
header = existing or BizProductionTaskSet(
|
||||
id=generate_uuid(),
|
||||
set_name=UC_MSC_BUILTIN_SET_NAME,
|
||||
status="1",
|
||||
tenant_no=tenant_no,
|
||||
order_num=0,
|
||||
remark="内置模版:UC 入库编码自动派发",
|
||||
is_builtin="1",
|
||||
create_by=user_id,
|
||||
create_dept_id=create_dept_id or "",
|
||||
create_time=now,
|
||||
update_by=user_id,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
if existing:
|
||||
header.status = "1"
|
||||
header.is_builtin = "1"
|
||||
header.update_by = user_id
|
||||
header.update_time = now
|
||||
db.add(header)
|
||||
db.flush()
|
||||
|
||||
items = (
|
||||
db.query(BizProductionTaskSetItem)
|
||||
.filter(
|
||||
BizProductionTaskSetItem.set_id == header.id,
|
||||
BizProductionTaskSetItem.tenant_no == tenant_no,
|
||||
BizProductionTaskSetItem.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for it in items:
|
||||
it.del_flag = 1
|
||||
it.update_by = user_id
|
||||
it.update_time = now
|
||||
db.add(it)
|
||||
db.flush()
|
||||
|
||||
item = BizProductionTaskSetItem(
|
||||
id=generate_uuid(),
|
||||
set_id=header.id,
|
||||
task_name="{lab_storage_code}样本处理",
|
||||
route_id=route.id,
|
||||
route_name=route.route_name,
|
||||
description=UC_MSC_BUILTIN_SET_NAME,
|
||||
remark=None,
|
||||
tenant_no=tenant_no,
|
||||
order_num=1,
|
||||
create_by=user_id,
|
||||
create_dept_id=create_dept_id or "",
|
||||
create_time=now,
|
||||
update_by=user_id,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
db.add(item)
|
||||
db.flush()
|
||||
|
||||
return {
|
||||
"created": True,
|
||||
"setId": header.id,
|
||||
"setName": header.set_name,
|
||||
"routeId": route.id,
|
||||
"routeCode": route.route_code,
|
||||
"stepCount": len(UC_MSC_STEP_ORDER),
|
||||
}
|
||||
@@ -2,12 +2,20 @@
|
||||
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
# 科研捐赠脐带间充质:UC… → 5 步原代培养模版(与细胞存储 BC 的 6 步模版分离)
|
||||
UC_MSC_BUILTIN_SET_NAME = "脐带MSC原代培养(内置模版)"
|
||||
BC_MSC_BUILTIN_SET_NAME = "干细胞培养(内置模版)"
|
||||
HSC_BUILTIN_SET_NAME = "造血干样本处理(内置模版)"
|
||||
UBMC_BUILTIN_SET_NAME = "UBMC冻存(内置模版)"
|
||||
PBMC_BUILTIN_SET_NAME = "PBMC冻存(内置模版)"
|
||||
|
||||
# 最长前缀优先:BC 必须在 B 之前,避免 BC… 误匹配造血干
|
||||
_LAB_CODE_BUILTIN_SET_RULES: List[Tuple[str, str]] = [
|
||||
("UBMC", "UBMC冻存(内置模版)"),
|
||||
("PBMC", "PBMC冻存(内置模版)"),
|
||||
("BC", "干细胞培养(内置模版)"),
|
||||
("B", "造血干样本处理(内置模版)"),
|
||||
("UBMC", UBMC_BUILTIN_SET_NAME),
|
||||
("PBMC", PBMC_BUILTIN_SET_NAME),
|
||||
("UC", UC_MSC_BUILTIN_SET_NAME),
|
||||
("BC", BC_MSC_BUILTIN_SET_NAME),
|
||||
("B", HSC_BUILTIN_SET_NAME),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
#!/usr/bin/env python3
|
||||
"""为 UC 开头实验室入库编码的入库生产工单补派 5 步脐带MSC原代任务。
|
||||
|
||||
默认 dry-run;加 --apply 才写库。会先幂等确保内置模版存在。
|
||||
|
||||
用法(在 backend 目录、已配置可连目标库的 .env):
|
||||
python -m scripts.backfill_uc_msc_production_tasks
|
||||
python -m scripts.backfill_uc_msc_production_tasks --apply
|
||||
python -m scripts.backfill_uc_msc_production_tasks --tenant zkxw --apply
|
||||
|
||||
等价一次性 SQL(与种子脚本分开):
|
||||
docs/sql/migrations/2026-11-13-uc-msc-production-task-backfill.sql
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import SessionLocal
|
||||
from app.crud import production_task_set as production_task_set_svc
|
||||
from app.models.models import (
|
||||
BizProductionTask,
|
||||
BizProductionTaskSet,
|
||||
BizProductionWorkOrder,
|
||||
BizSampleReception,
|
||||
)
|
||||
from app.services.uc_msc_builtin_template import ensure_uc_msc_builtin_template
|
||||
from app.utils.lab_storage_code_task_set import UC_MSC_BUILTIN_SET_NAME
|
||||
|
||||
|
||||
def _list_candidate_work_orders(
|
||||
db: Session, *, tenant_no: str
|
||||
) -> List[Tuple[BizProductionWorkOrder, BizSampleReception]]:
|
||||
"""UC 接收记录关联的入库工单,且当前无有效生产任务。"""
|
||||
q = (
|
||||
db.query(BizProductionWorkOrder, BizSampleReception)
|
||||
.join(
|
||||
BizSampleReception,
|
||||
BizSampleReception.id == BizProductionWorkOrder.reception_id,
|
||||
)
|
||||
.filter(
|
||||
BizProductionWorkOrder.tenant_no == tenant_no,
|
||||
BizProductionWorkOrder.del_flag == 0,
|
||||
BizProductionWorkOrder.work_order_type == "inbound",
|
||||
BizProductionWorkOrder.work_order_status.in_(("dpz", "jxz")),
|
||||
BizSampleReception.tenant_no == tenant_no,
|
||||
BizSampleReception.del_flag == 0,
|
||||
BizSampleReception.accept_conclusion == "js",
|
||||
BizSampleReception.lab_storage_code.isnot(None),
|
||||
BizSampleReception.lab_storage_code != "",
|
||||
or_(
|
||||
BizSampleReception.lab_storage_code.like("UC%"),
|
||||
BizSampleReception.lab_storage_code.like("uc%"),
|
||||
),
|
||||
)
|
||||
.order_by(BizSampleReception.reception_time.asc())
|
||||
)
|
||||
rows = q.all()
|
||||
out: List[Tuple[BizProductionWorkOrder, BizSampleReception]] = []
|
||||
for wo, rec in rows:
|
||||
has_task = (
|
||||
db.query(BizProductionTask.id)
|
||||
.filter(
|
||||
BizProductionTask.work_order_id == wo.id,
|
||||
BizProductionTask.tenant_no == tenant_no,
|
||||
BizProductionTask.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if has_task:
|
||||
continue
|
||||
code = (rec.lab_storage_code or "").strip().upper()
|
||||
if not code.startswith("UC"):
|
||||
continue
|
||||
out.append((wo, rec))
|
||||
return out
|
||||
|
||||
|
||||
def _dispatch_one(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
user_id: Optional[str],
|
||||
create_dept_id: str,
|
||||
wo: BizProductionWorkOrder,
|
||||
rec: BizSampleReception,
|
||||
set_id: str,
|
||||
) -> Dict[str, Any]:
|
||||
result = production_task_set_svc.create_tasks_from_set(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
create_dept_id=create_dept_id or "",
|
||||
work_order_id=wo.id,
|
||||
set_id=set_id,
|
||||
)
|
||||
return {
|
||||
"workOrderId": wo.id,
|
||||
"workOrderNo": wo.work_order_no,
|
||||
"sampleCode": wo.sample_code or rec.sample_code,
|
||||
"labStorageCode": rec.lab_storage_code,
|
||||
"createdCount": result.get("createdCount"),
|
||||
"tasks": [
|
||||
{"id": t.get("id"), "taskName": t.get("taskName"), "routeId": t.get("routeId")}
|
||||
for t in (result.get("list") or [])
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def run(
|
||||
*,
|
||||
tenant_no: str,
|
||||
apply: bool,
|
||||
user_id: Optional[str],
|
||||
create_dept_id: str,
|
||||
) -> Dict[str, Any]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
ensure_info = ensure_uc_msc_builtin_template(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
create_dept_id=create_dept_id,
|
||||
)
|
||||
set_row = (
|
||||
db.query(BizProductionTaskSet)
|
||||
.filter(
|
||||
BizProductionTaskSet.tenant_no == tenant_no,
|
||||
BizProductionTaskSet.set_name == UC_MSC_BUILTIN_SET_NAME,
|
||||
BizProductionTaskSet.is_builtin == "1",
|
||||
BizProductionTaskSet.status == "1",
|
||||
BizProductionTaskSet.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not set_row:
|
||||
raise RuntimeError("UC 内置任务组合创建失败")
|
||||
|
||||
candidates = _list_candidate_work_orders(db, tenant_no=tenant_no)
|
||||
preview = [
|
||||
{
|
||||
"workOrderId": wo.id,
|
||||
"workOrderNo": wo.work_order_no,
|
||||
"workOrderStatus": wo.work_order_status,
|
||||
"sampleCode": wo.sample_code or rec.sample_code,
|
||||
"labStorageCode": rec.lab_storage_code,
|
||||
"receptionId": rec.id,
|
||||
"receptionTime": str(rec.reception_time) if rec.reception_time else None,
|
||||
}
|
||||
for wo, rec in candidates
|
||||
]
|
||||
|
||||
if not apply:
|
||||
db.rollback()
|
||||
return {
|
||||
"dryRun": True,
|
||||
"template": ensure_info,
|
||||
"candidateCount": len(preview),
|
||||
"candidates": preview,
|
||||
"message": "dry-run:未写库。确认后加 --apply 执行补派。",
|
||||
}
|
||||
|
||||
dispatched: List[Dict[str, Any]] = []
|
||||
errors: List[Dict[str, Any]] = []
|
||||
for wo, rec in candidates:
|
||||
try:
|
||||
dispatched.append(
|
||||
_dispatch_one(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
create_dept_id=create_dept_id,
|
||||
wo=wo,
|
||||
rec=rec,
|
||||
set_id=set_row.id,
|
||||
)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 - 汇总后继续
|
||||
errors.append(
|
||||
{
|
||||
"workOrderId": wo.id,
|
||||
"workOrderNo": wo.work_order_no,
|
||||
"labStorageCode": rec.lab_storage_code,
|
||||
"error": str(exc),
|
||||
}
|
||||
)
|
||||
db.commit()
|
||||
return {
|
||||
"dryRun": False,
|
||||
"template": ensure_info,
|
||||
"candidateCount": len(preview),
|
||||
"dispatchedCount": len(dispatched),
|
||||
"dispatched": dispatched,
|
||||
"errorCount": len(errors),
|
||||
"errors": errors,
|
||||
}
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="回补 UC 入库编码生产工单的 5 步脐带MSC原代任务"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--tenant",
|
||||
default="zkxw",
|
||||
help="租户编号,默认 zkxw",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--apply",
|
||||
action="store_true",
|
||||
help="实际写库;默认仅 dry-run",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--user-id",
|
||||
default=None,
|
||||
help="写库 create_by/update_by,可选",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--create-dept-id",
|
||||
default="",
|
||||
help="写库 create_dept_id,可选",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
result = run(
|
||||
tenant_no=(args.tenant or "zkxw").strip() or "zkxw",
|
||||
apply=bool(args.apply),
|
||||
user_id=(args.user_id or None),
|
||||
create_dept_id=(args.create_dept_id or ""),
|
||||
)
|
||||
import json
|
||||
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
|
||||
if result.get("errorCount"):
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,324 @@
|
||||
"""将会议 Excel 三张表导入实验室样本处理补充台账。
|
||||
|
||||
用法(工程/worktree 根或 backend 下):
|
||||
ENV_FILE=.../backend/.env python backend/scripts/import_lab_sample_processing_xlsx.py --xlsx PATH
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
# 允许直接脚本运行
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BACKEND = ROOT / "backend"
|
||||
if str(BACKEND) not in sys.path:
|
||||
sys.path.insert(0, str(BACKEND))
|
||||
|
||||
from sqlalchemy.orm import Session # noqa: E402
|
||||
|
||||
from app.core.config import settings # noqa: E402
|
||||
from app.core.database import SessionLocal # noqa: E402
|
||||
from app.services.lab_sample_processing import upsert_extra_payload # noqa: E402
|
||||
from app.services.lab_sample_processing_fields import ( # noqa: E402
|
||||
DATASET_HSC,
|
||||
DATASET_MSC,
|
||||
DATASET_UBMC,
|
||||
fields_for,
|
||||
)
|
||||
|
||||
NS = {
|
||||
"m": "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
|
||||
"r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
|
||||
}
|
||||
|
||||
SHEET_DATASET = {
|
||||
"造血干细胞数据": DATASET_HSC,
|
||||
"单个核数据": DATASET_UBMC,
|
||||
"脐带间充质干细胞数据": DATASET_MSC,
|
||||
}
|
||||
|
||||
LABEL_ALIASES = {
|
||||
"细胞编码": "sampleCode",
|
||||
"实验室流转编码": "sampleCode",
|
||||
"准妈妈姓名": "motherName",
|
||||
"母亲姓名": "motherName",
|
||||
"采集时间": "collectTime",
|
||||
"脐带采集时间": "collectTime",
|
||||
"采集医院": "collectHospital",
|
||||
"接收时间": "receptionTime",
|
||||
"脐带接收时间": "receptionTime",
|
||||
"样品温度到达/℃": "receiveTemperature",
|
||||
"运输温度/℃": "transportTempC",
|
||||
"运输温度\n/℃": "transportTempC",
|
||||
"收样检查": "receiveCheck",
|
||||
"是否有母血": "hasMaternalBlood",
|
||||
"是否重采母血": "remeasureMaternalBlood",
|
||||
"知情同意书或协议书": "hasConsent",
|
||||
"脐血运输装箱清单": "hasPackingList",
|
||||
"脐带血接收确认单": "hasReceiveConfirm",
|
||||
"孕妇健康调查表": "hasHealthSurvey",
|
||||
"标识清晰": "labelClear",
|
||||
"接收登记人": "receptionHandler",
|
||||
"原血重量/g": "originalBloodWeightG",
|
||||
"HES用量/ml": "hesVolumeMl",
|
||||
"血型": "bloodType",
|
||||
"传染四项检测(检测卡)": "infectiousFourCard",
|
||||
"传染四项检测(外检)": "infectiousFourExternal",
|
||||
"富集前有核细胞数/109/L": "preEnrichTnc",
|
||||
"富集后血量/g": "enrichedBloodWeightG",
|
||||
"富集后有核细胞数/109/L": "postEnrichTnc",
|
||||
"冻存液用量/ml": "cryoVolumeMl",
|
||||
"CD34+细胞计数/*10E4": "cd34Count",
|
||||
"操作人": "operatorName",
|
||||
"实验室物料编码": "labMaterialCode",
|
||||
"入库编码": "labStorageCode",
|
||||
"储存状态": "storageStatus",
|
||||
"废弃原因": "discardReason",
|
||||
"原血体积/mL": "originalBloodVolumeMl",
|
||||
"有核细胞数/108": "nucleatedCellCount1e8",
|
||||
"操作前有核细胞数/109/L": "preOpTnc",
|
||||
"乙型肝炎病毒表面抗原(HBsAg)": "hbsag",
|
||||
"丙型肝炎病毒抗体(抗HCV)": "antiHcv",
|
||||
"梅毒螺旋体特异性抗体(抗TP)": "antiTp",
|
||||
"人类免疫缺陷病毒抗体(抗HIV-1/2)": "antiHiv",
|
||||
"巨细胞病毒IgM 抗体 (CMV-IgM)": "cmvIgm",
|
||||
"接种量": "inoculationAmount",
|
||||
"冻存时间": "cryoTime",
|
||||
"储存总量(管)": "storageTotalTubes",
|
||||
"储存总量\n(管)": "storageTotalTubes",
|
||||
"可提供细胞数量/*10E7": "availableCellCount1e7",
|
||||
"内毒素检测": "endotoxinTest",
|
||||
"细菌检测": "bacteriaTest",
|
||||
"真菌检测": "fungusTest",
|
||||
"支原体检测": "mycoplasmaTest",
|
||||
"乙型肝炎病毒表面抗原(HBsAg):": "motherHbsag",
|
||||
"乙型肝炎病毒核酸(HBV DNA)": "motherHbvDna",
|
||||
"丙型肝炎病毒核酸(HCV RNA)": "motherHcvRna",
|
||||
"巨细胞病毒lgM 抗体 (CMV lgM)": "motherCmvIgm",
|
||||
"人类免疫缺陷病毒核酸(1型) (HIV-1RNA)": "motherHiv1Rna",
|
||||
"储存日期\n(P2冻存日期)": "storageDateP2",
|
||||
"储存日期(P2冻存日期)": "storageDateP2",
|
||||
}
|
||||
|
||||
|
||||
def _norm_label(s: str) -> str:
|
||||
return re.sub(r"\s+", "", (s or "").replace("\r", "").strip())
|
||||
|
||||
|
||||
def _col_row(ref: str):
|
||||
m = re.match(r"([A-Z]+)(\d+)", ref)
|
||||
col = m.group(1)
|
||||
row = int(m.group(2))
|
||||
n = 0
|
||||
for ch in col:
|
||||
n = n * 26 + ord(ch) - 64
|
||||
return n, row
|
||||
|
||||
|
||||
def read_sheet_matrix(z: zipfile.ZipFile, target: str):
|
||||
ss = []
|
||||
if "xl/sharedStrings.xml" in z.namelist():
|
||||
root = ET.fromstring(z.read("xl/sharedStrings.xml"))
|
||||
for si in root.findall("m:si", NS):
|
||||
texts = [
|
||||
t.text or ""
|
||||
for t in si.iter("{http://schemas.openxmlformats.org/spreadsheetml/2006/main}t")
|
||||
]
|
||||
ss.append("".join(texts))
|
||||
root = ET.fromstring(z.read(target))
|
||||
rows = {}
|
||||
for c in root.findall(".//m:sheetData/m:row/m:c", NS):
|
||||
ref = c.attrib.get("r")
|
||||
t = c.attrib.get("t")
|
||||
v = c.find("m:v", NS)
|
||||
if v is None or ref is None:
|
||||
continue
|
||||
val = v.text or ""
|
||||
if t == "s":
|
||||
try:
|
||||
val = ss[int(val)]
|
||||
except Exception:
|
||||
pass
|
||||
cn, rn = _col_row(ref)
|
||||
rows.setdefault(rn, {})[cn] = val
|
||||
if not rows:
|
||||
return []
|
||||
max_r = max(rows)
|
||||
max_c = max(max(cols) for cols in rows.values())
|
||||
matrix = []
|
||||
for rn in range(1, max_r + 1):
|
||||
line = [str(rows.get(rn, {}).get(c, "") or "").strip() for c in range(1, max_c + 1)]
|
||||
matrix.append(line)
|
||||
return matrix
|
||||
|
||||
|
||||
def build_header_map(header_rows: list, dataset: str):
|
||||
"""合并多行表头,按列映射到字段 key。"""
|
||||
width = max(len(r) for r in header_rows)
|
||||
merged = [""] * width
|
||||
for r in header_rows:
|
||||
for i in range(width):
|
||||
cell = r[i] if i < len(r) else ""
|
||||
if cell:
|
||||
merged[i] = cell if not merged[i] else merged[i]
|
||||
# MSC: 第二行填充分组子列
|
||||
if len(header_rows) >= 2:
|
||||
for i in range(width):
|
||||
top = header_rows[0][i] if i < len(header_rows[0]) else ""
|
||||
sub = header_rows[1][i] if i < len(header_rows[1]) else ""
|
||||
if sub:
|
||||
merged[i] = sub
|
||||
elif top and not merged[i]:
|
||||
merged[i] = top
|
||||
|
||||
label_to_key = {_norm_label(f.label): f.key for f in fields_for(dataset)}
|
||||
for alias, key in LABEL_ALIASES.items():
|
||||
label_to_key[_norm_label(alias)] = key
|
||||
|
||||
# 备注列:第一处 receptionRemark,第二处 processRemark
|
||||
remark_keys = []
|
||||
col_map = {}
|
||||
for idx, label in enumerate(merged):
|
||||
n = _norm_label(label)
|
||||
if not n or n in {"序号"}:
|
||||
continue
|
||||
if n == "备注":
|
||||
remark_keys.append(idx)
|
||||
continue
|
||||
# 母血相关与单项同名字段在 MSC 中优先 mother*
|
||||
key = label_to_key.get(n)
|
||||
if not key and n.endswith(":"):
|
||||
key = label_to_key.get(n[:-1])
|
||||
if key:
|
||||
col_map[idx] = key
|
||||
if remark_keys:
|
||||
col_map[remark_keys[0]] = "receptionRemark"
|
||||
if len(remark_keys) > 1:
|
||||
col_map[remark_keys[1]] = "processRemark"
|
||||
elif "processRemark" in {f.key for f in fields_for(dataset)} and dataset != DATASET_UBMC:
|
||||
# 单备注时,造血第二业务备注也可能只有一列;保留 receptionRemark
|
||||
pass
|
||||
# UBMC 仅一列备注时落到 receptionRemark;有操作备注需求时同步 processRemark
|
||||
return col_map, merged
|
||||
|
||||
|
||||
def parse_workbook(path: Path):
|
||||
out = {}
|
||||
with zipfile.ZipFile(path) as z:
|
||||
wb = ET.fromstring(z.read("xl/workbook.xml"))
|
||||
sheets = []
|
||||
for sh in wb.findall("m:sheets/m:sheet", NS):
|
||||
sheets.append(
|
||||
(
|
||||
sh.attrib.get("name"),
|
||||
sh.attrib.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"),
|
||||
)
|
||||
)
|
||||
rels = ET.fromstring(z.read("xl/_rels/workbook.xml.rels"))
|
||||
rid_to_target = {rel.attrib["Id"]: rel.attrib["Target"] for rel in rels}
|
||||
for name, rid in sheets:
|
||||
dataset = SHEET_DATASET.get(name)
|
||||
if not dataset:
|
||||
continue
|
||||
target = rid_to_target[rid]
|
||||
if not target.startswith("xl/"):
|
||||
target = "xl/" + target
|
||||
matrix = read_sheet_matrix(z, target)
|
||||
if not matrix:
|
||||
continue
|
||||
# MSC 两行表头;其他一行(UBMC 可能首列分组)
|
||||
if dataset == DATASET_MSC:
|
||||
header_rows = matrix[:2]
|
||||
data_rows = matrix[2:]
|
||||
else:
|
||||
header_rows = matrix[:1]
|
||||
data_rows = matrix[1:]
|
||||
col_map, merged = build_header_map(header_rows, dataset)
|
||||
records = []
|
||||
for row in data_rows:
|
||||
payload = {}
|
||||
for idx, key in col_map.items():
|
||||
val = row[idx] if idx < len(row) else ""
|
||||
if val != "":
|
||||
payload[key] = val
|
||||
code = str(payload.get("sampleCode") or "").strip()
|
||||
if not code:
|
||||
continue
|
||||
# UBMC 同名母血检测字段:Excel 用的是非 mother 前缀,已映射
|
||||
# MSC 母血字段别名
|
||||
if dataset == DATASET_MSC:
|
||||
if "antiHcv" in payload and "motherAntiHcv" not in payload:
|
||||
payload["motherAntiHcv"] = payload.pop("antiHcv")
|
||||
if "antiTp" in payload and "motherAntiTp" not in payload:
|
||||
payload["motherAntiTp"] = payload.pop("antiTp")
|
||||
if "antiHiv" in payload and "motherAntiHiv" not in payload:
|
||||
payload["motherAntiHiv"] = payload.pop("antiHiv")
|
||||
if "hbsag" in payload and "motherHbsag" not in payload:
|
||||
payload["motherHbsag"] = payload.pop("hbsag")
|
||||
payload["sampleCode"] = code
|
||||
records.append(payload)
|
||||
out[dataset] = {"headers": merged, "records": records, "col_map": col_map}
|
||||
return out
|
||||
|
||||
|
||||
def import_all(db: Session, tenant_no: str, parsed: dict) -> dict:
|
||||
summary = {}
|
||||
for dataset, pack in parsed.items():
|
||||
n = 0
|
||||
for payload in pack["records"]:
|
||||
upsert_extra_payload(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
dataset=dataset,
|
||||
sample_code=payload["sampleCode"],
|
||||
payload=payload,
|
||||
operator_id="excel-import",
|
||||
replace=True,
|
||||
)
|
||||
n += 1
|
||||
summary[dataset] = n
|
||||
db.commit()
|
||||
return summary
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--xlsx", required=True)
|
||||
parser.add_argument("--tenant", default=None)
|
||||
args = parser.parse_args()
|
||||
xlsx = Path(args.xlsx)
|
||||
if not xlsx.exists():
|
||||
raise SystemExit(f"xlsx not found: {xlsx}")
|
||||
|
||||
parsed = parse_workbook(xlsx)
|
||||
if not parsed:
|
||||
raise SystemExit("no sheets parsed")
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
tenant_no = args.tenant
|
||||
if not tenant_no:
|
||||
# 取库中任一有效租户
|
||||
from app.models.models import SysUser
|
||||
|
||||
u = (
|
||||
db.query(SysUser)
|
||||
.filter(SysUser.del_flag == 0, SysUser.status == "1", SysUser.tenant_no.isnot(None))
|
||||
.first()
|
||||
)
|
||||
tenant_no = (u.tenant_no if u else None) or "zkxw"
|
||||
summary = import_all(db, tenant_no, parsed)
|
||||
print("tenant", tenant_no)
|
||||
for ds, n in summary.items():
|
||||
print(f"imported {ds}={n}")
|
||||
print("ok")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,30 @@
|
||||
"""恢复被误软删的 Excel 补充字段(真菌/内毒素/CD34 等)并同步旧台账。
|
||||
|
||||
用法:
|
||||
ENV_FILE=.../backend/.env python backend/scripts/restore_lab_sample_processing_excel_extras.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BACKEND = ROOT / "backend"
|
||||
if str(BACKEND) not in sys.path:
|
||||
sys.path.insert(0, str(BACKEND))
|
||||
|
||||
from app.core.database import SessionLocal # noqa: E402
|
||||
from app.services.lab_sample_processing import restore_retired_excel_extras # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
result = restore_retired_excel_extras(db, tenant_no="zkxw")
|
||||
print(result)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""实验室样本处理台账:时间格式与字段合并。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
|
||||
from app.services.lab_sample_process import (
|
||||
format_cn_datetime,
|
||||
infectious_label,
|
||||
merge_row,
|
||||
)
|
||||
|
||||
|
||||
class LabSampleProcessServiceTests(unittest.TestCase):
|
||||
def test_format_cn_datetime(self):
|
||||
self.assertEqual(
|
||||
format_cn_datetime(datetime(2026, 11, 12, 0, 0, 0)),
|
||||
"2026年11月12日 00时00分00秒",
|
||||
)
|
||||
self.assertEqual(
|
||||
format_cn_datetime("2026-11-12 08:30:01"),
|
||||
"2026年11月12日 08时30分01秒",
|
||||
)
|
||||
self.assertEqual(format_cn_datetime(""), "")
|
||||
|
||||
def test_infectious_label(self):
|
||||
self.assertEqual(infectious_label("zc"), "正常")
|
||||
self.assertEqual(infectious_label("bzc"), "不正常")
|
||||
|
||||
def test_merge_row_system_first_and_override(self):
|
||||
merged = merge_row(
|
||||
tab_key="donation_hsc",
|
||||
system_values={"receiveCheckText": "系统汇总", "motherName": "张三"},
|
||||
supplement={"receiveCheckText": "补录文案", "labMaterialCode": "M001"},
|
||||
)
|
||||
self.assertEqual(merged["receiveCheckText"], "补录文案")
|
||||
self.assertEqual(merged["labMaterialCode"], "M001")
|
||||
self.assertEqual(merged["motherName"], "张三")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,230 @@
|
||||
import unittest
|
||||
|
||||
from app.services.lab_sample_processing_fields import (
|
||||
DATASET_HSC,
|
||||
DATASET_MSC,
|
||||
DATASET_UBMC,
|
||||
DEPT_MARKET,
|
||||
DEPT_PRODUCTION,
|
||||
DEPT_QC,
|
||||
editable_depts_for_user,
|
||||
field_map,
|
||||
resolve_dataset_by_type_name,
|
||||
schema_payload,
|
||||
)
|
||||
|
||||
|
||||
class LabSampleProcessingFieldsTest(unittest.TestCase):
|
||||
def test_resolve_dataset(self):
|
||||
self.assertEqual(resolve_dataset_by_type_name("围产期造血干细胞", "B0000001"), DATASET_HSC)
|
||||
self.assertEqual(resolve_dataset_by_type_name("脐带间充质干细胞", "BC0000003"), DATASET_MSC)
|
||||
self.assertEqual(resolve_dataset_by_type_name("", "UBMC2025001"), DATASET_UBMC)
|
||||
self.assertEqual(resolve_dataset_by_type_name("", "UC2026001"), DATASET_MSC)
|
||||
|
||||
def test_schema_not_empty(self):
|
||||
self.assertGreater(len(schema_payload(DATASET_HSC)), 10)
|
||||
self.assertGreater(len(schema_payload(DATASET_UBMC)), 10)
|
||||
self.assertGreater(len(schema_payload(DATASET_MSC)), 10)
|
||||
|
||||
def test_dept_acl(self):
|
||||
self.assertEqual(
|
||||
editable_depts_for_user(
|
||||
is_manager=True,
|
||||
dept_flags={DEPT_MARKET: False, DEPT_PRODUCTION: False, DEPT_QC: False},
|
||||
),
|
||||
{DEPT_MARKET, DEPT_PRODUCTION, DEPT_QC},
|
||||
)
|
||||
self.assertEqual(
|
||||
editable_depts_for_user(
|
||||
is_manager=False,
|
||||
dept_flags={DEPT_MARKET: False, DEPT_PRODUCTION: True, DEPT_QC: False},
|
||||
),
|
||||
{DEPT_PRODUCTION},
|
||||
)
|
||||
|
||||
def test_hsc_market_and_qc_fields(self):
|
||||
fmap = field_map(DATASET_HSC)
|
||||
self.assertEqual(fmap["motherName"].dept, DEPT_MARKET)
|
||||
self.assertEqual(fmap["cd34Count"].dept, DEPT_QC)
|
||||
self.assertEqual(fmap["originalBloodWeightG"].dept, DEPT_PRODUCTION)
|
||||
|
||||
def test_source_fields_not_overridden_by_extra(self):
|
||||
from datetime import datetime
|
||||
from app.services.lab_sample_processing import _build_row
|
||||
from types import SimpleNamespace
|
||||
|
||||
sample = SimpleNamespace(id="S1", sample_code="ZKZX34000865", collection_protocol_id="P1")
|
||||
party = SimpleNamespace(mother_name="真实妈妈")
|
||||
coll = SimpleNamespace(
|
||||
sample_collect_time=None,
|
||||
maternal_blood_collect_time=datetime(2026, 11, 4, 5, 20),
|
||||
)
|
||||
hospital = SimpleNamespace(hospital_name="真实医院")
|
||||
protocol = SimpleNamespace(
|
||||
consent_form_urls="protocol-consent/a",
|
||||
health_survey_form_urls="",
|
||||
)
|
||||
reception = SimpleNamespace(
|
||||
id="R1",
|
||||
reception_time=None,
|
||||
receive_temperature=None,
|
||||
handler_name="接收人",
|
||||
remark=None,
|
||||
lab_storage_code="B0000103",
|
||||
)
|
||||
production = SimpleNamespace(
|
||||
id="PR1",
|
||||
original_blood_weight_g=72.08,
|
||||
hes_volume_ml=None,
|
||||
blood_type="B",
|
||||
infectious_four_test_result="zc",
|
||||
enriched_blood_weight_g=None,
|
||||
cryopreservation_volume_ml=None,
|
||||
handler_name="操作人",
|
||||
remark=None,
|
||||
original_blood_volume_ml=None,
|
||||
nucleated_cell_count_1e8=None,
|
||||
inoculation_amount=None,
|
||||
cryopreservation_time=None,
|
||||
storage_total_tubes=None,
|
||||
available_cell_count_1e7=None,
|
||||
)
|
||||
row = _build_row(
|
||||
dataset=DATASET_HSC,
|
||||
sample=sample,
|
||||
type_name="围产期造血干细胞",
|
||||
party=party,
|
||||
coll=coll,
|
||||
hospital=hospital,
|
||||
reception=reception,
|
||||
production=production,
|
||||
extra={
|
||||
"motherName": "Excel妈妈",
|
||||
"originalBloodWeightG": 1,
|
||||
"cd34Count": "11.4",
|
||||
},
|
||||
protocol=protocol,
|
||||
check_flags={
|
||||
"健康调查表": True,
|
||||
"样本信息正确,标识清晰": True,
|
||||
"针路密闭": True,
|
||||
"容器无破损": True,
|
||||
},
|
||||
)
|
||||
self.assertEqual(row["sampleCode"], "B0000103")
|
||||
self.assertEqual(row["protocolSampleCode"], "ZKZX34000865")
|
||||
self.assertEqual(row["motherName"], "真实妈妈")
|
||||
self.assertEqual(row["originalBloodWeightG"], 72.08)
|
||||
self.assertEqual(row["bloodType"], "B")
|
||||
self.assertEqual(row["cd34Count"], "11.4")
|
||||
self.assertEqual(row["hasMaternalBlood"], "是")
|
||||
self.assertEqual(row["hasConsent"], "是")
|
||||
self.assertEqual(row["hasHealthSurvey"], "是")
|
||||
self.assertEqual(row["labelClear"], "是")
|
||||
self.assertEqual(row["infectiousFourCard"], "正常")
|
||||
self.assertIn("针路密闭", row["receiveCheck"] or "")
|
||||
self.assertFalse(row["fromExtraOnly"])
|
||||
|
||||
def test_infectious_code_roundtrip(self):
|
||||
from app.services.lab_sample_processing import _infectious_code, _infectious_label
|
||||
|
||||
self.assertEqual(_infectious_label("zc"), "正常")
|
||||
self.assertEqual(_infectious_label("bzc"), "不正常")
|
||||
self.assertEqual(_infectious_code("正常"), "zc")
|
||||
self.assertEqual(_infectious_code("不正常"), "bzc")
|
||||
|
||||
def test_extra_field_keys_include_fungus(self):
|
||||
from app.services.lab_sample_processing import _extra_field_keys
|
||||
|
||||
keys = _extra_field_keys(DATASET_MSC)
|
||||
self.assertIn("fungusTest", keys)
|
||||
self.assertIn("endotoxinTest", keys)
|
||||
self.assertIn("bacteriaTest", keys)
|
||||
self.assertIn("mycoplasmaTest", keys)
|
||||
|
||||
def test_msc_donation_collect_and_transport_fallback(self):
|
||||
from datetime import datetime
|
||||
from app.services.lab_sample_processing import _build_row
|
||||
from types import SimpleNamespace
|
||||
|
||||
sample = SimpleNamespace(id="D1", sample_code="KYJZ1", collection_protocol_id=None)
|
||||
party = SimpleNamespace(mother_name="孙玲")
|
||||
coll = SimpleNamespace(
|
||||
sample_collect_time=datetime(2026, 10, 10, 10, 5),
|
||||
maternal_blood_collect_time=None,
|
||||
)
|
||||
reception = SimpleNamespace(
|
||||
id="R1",
|
||||
reception_time=datetime(2026, 10, 10, 15, 40, 57),
|
||||
receive_temperature="23.1",
|
||||
handler_name="侯以婷",
|
||||
remark=None,
|
||||
lab_storage_code="UC2026006",
|
||||
)
|
||||
row = _build_row(
|
||||
dataset=DATASET_MSC,
|
||||
sample=sample,
|
||||
type_name="脐带间充质干细胞",
|
||||
party=party,
|
||||
coll=coll,
|
||||
hospital=None,
|
||||
reception=reception,
|
||||
production=None,
|
||||
extra={},
|
||||
)
|
||||
self.assertEqual(row["sampleCode"], "UC2026006")
|
||||
self.assertEqual(row["collectTime"], "2026-10-10 10:05:00")
|
||||
self.assertEqual(row["transportTempC"], "23.1")
|
||||
self.assertNotIn("导出自存", row["motherName"] or "")
|
||||
|
||||
def test_legacy_supplement_fills_empty_source_fields(self):
|
||||
from app.services.lab_sample_processing import _build_row, _merge_extra_with_legacy
|
||||
from types import SimpleNamespace
|
||||
|
||||
extra = _merge_extra_with_legacy(
|
||||
{},
|
||||
{"infectiousFourTestLabel": "正常", "labMaterialCode": "202611006"},
|
||||
)
|
||||
sample = SimpleNamespace(id="S1", sample_code="UBMC202611006", collection_protocol_id=None)
|
||||
reception = SimpleNamespace(
|
||||
id="R1",
|
||||
reception_time=None,
|
||||
receive_temperature=None,
|
||||
handler_name=None,
|
||||
remark=None,
|
||||
lab_storage_code="UBMC202611006",
|
||||
)
|
||||
production = SimpleNamespace(
|
||||
id="PR1",
|
||||
original_blood_weight_g=None,
|
||||
hes_volume_ml=None,
|
||||
blood_type=None,
|
||||
infectious_four_test_result=None,
|
||||
enriched_blood_weight_g=None,
|
||||
cryopreservation_volume_ml=None,
|
||||
handler_name=None,
|
||||
remark=None,
|
||||
original_blood_volume_ml=None,
|
||||
nucleated_cell_count_1e8=None,
|
||||
inoculation_amount=None,
|
||||
cryopreservation_time=None,
|
||||
storage_total_tubes=None,
|
||||
available_cell_count_1e7=None,
|
||||
)
|
||||
row = _build_row(
|
||||
dataset=DATASET_UBMC,
|
||||
sample=sample,
|
||||
type_name="脐血单个核细胞",
|
||||
party=None,
|
||||
coll=None,
|
||||
hospital=None,
|
||||
reception=reception,
|
||||
production=production,
|
||||
extra=extra,
|
||||
)
|
||||
self.assertEqual(row["infectiousFourCard"], "正常")
|
||||
self.assertEqual(row["labMaterialCode"], "202611006")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,19 +1,36 @@
|
||||
import unittest
|
||||
|
||||
from app.utils.lab_storage_code_task_set import match_builtin_task_set_name_by_lab_storage_code
|
||||
from app.utils.lab_storage_code_task_set import (
|
||||
BC_MSC_BUILTIN_SET_NAME,
|
||||
HSC_BUILTIN_SET_NAME,
|
||||
UC_MSC_BUILTIN_SET_NAME,
|
||||
match_builtin_task_set_name_by_lab_storage_code,
|
||||
)
|
||||
|
||||
|
||||
class TestMatchBuiltinTaskSetName(unittest.TestCase):
|
||||
def test_bc_before_b(self):
|
||||
self.assertEqual(
|
||||
match_builtin_task_set_name_by_lab_storage_code("BC20260101"),
|
||||
"干细胞培养(内置模版)",
|
||||
BC_MSC_BUILTIN_SET_NAME,
|
||||
)
|
||||
|
||||
def test_b_only(self):
|
||||
self.assertEqual(
|
||||
match_builtin_task_set_name_by_lab_storage_code("B20260101"),
|
||||
"造血干样本处理(内置模版)",
|
||||
HSC_BUILTIN_SET_NAME,
|
||||
)
|
||||
|
||||
def test_uc_msc(self):
|
||||
self.assertEqual(
|
||||
match_builtin_task_set_name_by_lab_storage_code("UC2026010"),
|
||||
UC_MSC_BUILTIN_SET_NAME,
|
||||
)
|
||||
|
||||
def test_uc_case_insensitive(self):
|
||||
self.assertEqual(
|
||||
match_builtin_task_set_name_by_lab_storage_code("uc2026016"),
|
||||
UC_MSC_BUILTIN_SET_NAME,
|
||||
)
|
||||
|
||||
def test_ubmc(self):
|
||||
@@ -35,7 +52,7 @@ class TestMatchBuiltinTaskSetName(unittest.TestCase):
|
||||
def test_bc_case_insensitive(self):
|
||||
self.assertEqual(
|
||||
match_builtin_task_set_name_by_lab_storage_code("bc99"),
|
||||
"干细胞培养(内置模版)",
|
||||
BC_MSC_BUILTIN_SET_NAME,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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'] == '专员'
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -2564,10 +2564,13 @@ def test_web_presign_list_includes_ledger_fields():
|
||||
order.mother_name = '陈影'
|
||||
transfer = _transfer('ledger-transfer', order_id='ledger-1', pay_status='yjf')
|
||||
transfer.transfer_time = datetime(2026, 4, 2, 16, 49, 42)
|
||||
pending = _transfer('ledger-pending', order_id='ledger-1', pay_status='dfj')
|
||||
pending.transfer_time = datetime(2026, 4, 1, 10, 0, 0)
|
||||
db.add_all(
|
||||
[
|
||||
order,
|
||||
transfer,
|
||||
pending,
|
||||
BizPresignOrderSampleType(
|
||||
id='ledger-type',
|
||||
presign_order_id='ledger-1',
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""计划开始时间筛选:不内置工单/任务/步骤状态限制,交给外层组合条件。"""
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.dialects import mysql
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.crud.production_work_order import apply_planned_start_time_step_filter
|
||||
from app.models.models import BizProductionWorkOrder
|
||||
|
||||
|
||||
def _compile_planned_start_sql() -> str:
|
||||
eng = create_engine("sqlite://")
|
||||
SessionLocal = sessionmaker(bind=eng)
|
||||
db = SessionLocal()
|
||||
try:
|
||||
q = db.query(BizProductionWorkOrder).filter(BizProductionWorkOrder.del_flag == 0)
|
||||
filtered = apply_planned_start_time_step_filter(
|
||||
q,
|
||||
tenant_no="zkxw",
|
||||
work_order_id_column=BizProductionWorkOrder.id,
|
||||
planned_start_time_start="2026-10-01",
|
||||
planned_start_time_end="2026-12-31",
|
||||
)
|
||||
return str(
|
||||
filtered.statement.compile(
|
||||
dialect=mysql.dialect(), compile_kwargs={"literal_binds": True}
|
||||
)
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_planned_start_filter_keeps_date_bounds_without_status_hardcodes():
|
||||
sql = _compile_planned_start_sql().lower()
|
||||
assert "planned_start_time" in sql
|
||||
assert "2026-10-01 00:00:00" in sql
|
||||
assert "2026-12-31 23:59:59" in sql
|
||||
# 不再在 EXISTS 内强制待配置/进行中或未完成步骤
|
||||
assert "work_order_status in (" not in sql
|
||||
assert "task_status in (" not in sql
|
||||
assert "step_status !=" not in sql
|
||||
assert "step_status <>" not in sql
|
||||
@@ -23,6 +23,7 @@ from app.models.research_donation import (
|
||||
)
|
||||
from app.services.protocol_reception_discard_sync import (
|
||||
LAB_VOID_TYPE_CODE,
|
||||
SAMPLE_VOID_STATUS,
|
||||
after_protocol_voided,
|
||||
after_sample_reception_saved,
|
||||
ensure_lab_void_type,
|
||||
@@ -77,6 +78,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
|
||||
id="p1",
|
||||
protocol_no="CP-1",
|
||||
protocol_status="sxz",
|
||||
void_time=now,
|
||||
tenant_no="tenant-a",
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
@@ -89,6 +91,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
|
||||
id="s1",
|
||||
collection_protocol_id="p1",
|
||||
sample_code="ZK001",
|
||||
sample_status="yrk",
|
||||
tenant_no="tenant-a",
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
@@ -101,6 +104,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
|
||||
id="s2",
|
||||
collection_protocol_id="p1",
|
||||
sample_code="ZK002",
|
||||
sample_status="jcz",
|
||||
tenant_no="tenant-a",
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
@@ -152,6 +156,16 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
|
||||
self.assertEqual(by_code["ZK001"], "bj")
|
||||
self.assertEqual(by_code["ZK002"], "bj")
|
||||
|
||||
samples = (
|
||||
db.query(BizProtocolSample)
|
||||
.filter(BizProtocolSample.collection_protocol_id == "p1")
|
||||
.all()
|
||||
)
|
||||
self.assertEqual(len(samples), 2)
|
||||
for s in samples:
|
||||
self.assertEqual(s.sample_status, SAMPLE_VOID_STATUS)
|
||||
self.assertEqual(s.void_date, "20261105")
|
||||
|
||||
def test_all_samples_discarded_auto_voids_protocol_with_lab_type(self):
|
||||
db = _session()
|
||||
now = _now()
|
||||
@@ -172,6 +186,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
|
||||
id="s3",
|
||||
collection_protocol_id="p2",
|
||||
sample_code="ZK003",
|
||||
sample_status="ycj",
|
||||
tenant_no="tenant-a",
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
@@ -212,6 +227,9 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
|
||||
self.assertEqual(proto.protocol_status, "yzf")
|
||||
self.assertEqual(proto.void_type, LAB_VOID_TYPE_CODE)
|
||||
self.assertIn("全部样本接收", proto.void_desc or "")
|
||||
sample = db.query(BizProtocolSample).filter(BizProtocolSample.id == "s3").one()
|
||||
self.assertEqual(sample.sample_status, SAMPLE_VOID_STATUS)
|
||||
self.assertTrue((sample.void_date or "").strip())
|
||||
|
||||
def test_partial_discard_does_not_void_protocol(self):
|
||||
db = _session()
|
||||
@@ -282,6 +300,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
|
||||
id="d1",
|
||||
donation_no="RD-1",
|
||||
donation_status="sxz",
|
||||
void_time=now,
|
||||
tenant_no="tenant-a",
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
@@ -294,6 +313,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
|
||||
id="ds1",
|
||||
research_donation_id="d1",
|
||||
sample_code="RD001",
|
||||
sample_status="yrk",
|
||||
tenant_no="tenant-a",
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
@@ -322,6 +342,199 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
|
||||
)
|
||||
self.assertEqual(rec.accept_conclusion, "bj")
|
||||
self.assertEqual(rec.research_donation_id, "d1")
|
||||
sample = (
|
||||
db.query(BizResearchDonationSample)
|
||||
.filter(BizResearchDonationSample.id == "ds1")
|
||||
.one()
|
||||
)
|
||||
self.assertEqual(sample.sample_status, SAMPLE_VOID_STATUS)
|
||||
self.assertEqual(sample.void_date, "20261105")
|
||||
|
||||
def test_sdfq_also_voids_sample_status(self):
|
||||
db = _session()
|
||||
now = _now()
|
||||
db.add(
|
||||
BizCollectionProtocol(
|
||||
id="p-sdfq",
|
||||
protocol_no="CP-SDFQ",
|
||||
protocol_status="sdfq",
|
||||
tenant_no="tenant-a",
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
)
|
||||
db.add(
|
||||
BizProtocolSample(
|
||||
id="s-sdfq",
|
||||
collection_protocol_id="p-sdfq",
|
||||
sample_code="ZKSDFQ",
|
||||
sample_status="ycj",
|
||||
tenant_no="tenant-a",
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
after_protocol_voided(
|
||||
db,
|
||||
source="cell_storage",
|
||||
protocol_id="p-sdfq",
|
||||
tenant_no="tenant-a",
|
||||
user_id="u1",
|
||||
)
|
||||
db.commit()
|
||||
|
||||
sample = db.query(BizProtocolSample).filter(BizProtocolSample.id == "s-sdfq").one()
|
||||
self.assertEqual(sample.sample_status, SAMPLE_VOID_STATUS)
|
||||
self.assertTrue((sample.void_date or "").strip())
|
||||
rec = (
|
||||
db.query(BizSampleReception)
|
||||
.filter(BizSampleReception.sample_code == "ZKSDFQ")
|
||||
.one()
|
||||
)
|
||||
self.assertEqual(rec.accept_conclusion, "bj")
|
||||
|
||||
def test_single_reception_discard_voids_only_that_sample(self):
|
||||
db = _session()
|
||||
now = _now()
|
||||
db.add(
|
||||
BizCollectionProtocol(
|
||||
id="p-multi",
|
||||
protocol_no="CP-MULTI",
|
||||
protocol_status="sxz",
|
||||
tenant_no="tenant-a",
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
)
|
||||
for sid, code, status in (
|
||||
("sa", "ZKA", "ycj"),
|
||||
("sb", "ZKB", "ycj"),
|
||||
("sc", "ZKC", "ycj"),
|
||||
):
|
||||
db.add(
|
||||
BizProtocolSample(
|
||||
id=sid,
|
||||
collection_protocol_id="p-multi",
|
||||
sample_code=code,
|
||||
sample_status=status,
|
||||
tenant_no="tenant-a",
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
)
|
||||
rec_a = BizSampleReception(
|
||||
id="ra",
|
||||
protocol_sample_id="sa",
|
||||
collection_protocol_id="p-multi",
|
||||
reception_time=now,
|
||||
accept_conclusion="bj",
|
||||
reception_source="cell_storage",
|
||||
sample_code="ZKA",
|
||||
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.add(rec_a)
|
||||
db.commit()
|
||||
|
||||
after_sample_reception_saved(
|
||||
db, reception=rec_a, tenant_no="tenant-a", user_id="u1"
|
||||
)
|
||||
db.commit()
|
||||
|
||||
proto = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p-multi").one()
|
||||
self.assertEqual(proto.protocol_status, "sxz")
|
||||
by_id = {
|
||||
s.id: s
|
||||
for s in db.query(BizProtocolSample)
|
||||
.filter(BizProtocolSample.collection_protocol_id == "p-multi")
|
||||
.all()
|
||||
}
|
||||
self.assertEqual(by_id["sa"].sample_status, SAMPLE_VOID_STATUS)
|
||||
self.assertEqual(by_id["sa"].void_date, "20261105")
|
||||
self.assertEqual(by_id["sb"].sample_status, "ycj")
|
||||
self.assertEqual(by_id["sc"].sample_status, "ycj")
|
||||
|
||||
def test_reception_accept_clears_sample_void_when_protocol_active(self):
|
||||
db = _session()
|
||||
now = _now()
|
||||
db.add(
|
||||
BizCollectionProtocol(
|
||||
id="p-clear",
|
||||
protocol_no="CP-CLEAR",
|
||||
protocol_status="sxz",
|
||||
tenant_no="tenant-a",
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
)
|
||||
db.add(
|
||||
BizProtocolSample(
|
||||
id="s-clear",
|
||||
collection_protocol_id="p-clear",
|
||||
sample_code="ZKCLR",
|
||||
sample_status=SAMPLE_VOID_STATUS,
|
||||
void_date="20261101",
|
||||
tenant_no="tenant-a",
|
||||
create_dept_id="",
|
||||
create_time=now,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
)
|
||||
rec = BizSampleReception(
|
||||
id="r-clear",
|
||||
protocol_sample_id="s-clear",
|
||||
collection_protocol_id="p-clear",
|
||||
reception_time=now,
|
||||
accept_conclusion="js",
|
||||
reception_source="cell_storage",
|
||||
sample_code="ZKCLR",
|
||||
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.add(rec)
|
||||
db.commit()
|
||||
|
||||
after_sample_reception_saved(
|
||||
db, reception=rec, tenant_no="tenant-a", user_id="u1"
|
||||
)
|
||||
db.commit()
|
||||
|
||||
sample = db.query(BizProtocolSample).filter(BizProtocolSample.id == "s-clear").one()
|
||||
self.assertFalse((sample.sample_status or "").strip())
|
||||
self.assertFalse((sample.void_date or "").strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
"""协议列表可显式读取 V2 样本方案,其他费用摘要消费者保持原行为。"""
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.models.base import Base
|
||||
from app.models.models import BizProtocolSamplePayment
|
||||
from app.models.models import (
|
||||
BizProtocolPaymentSchedule,
|
||||
BizProtocolPaymentTransfer,
|
||||
BizProtocolRefundRecord,
|
||||
BizProtocolSamplePayment,
|
||||
)
|
||||
from app.services.qc_work_order_fee_summary import build_protocol_payment_summaries
|
||||
|
||||
|
||||
@@ -31,3 +39,180 @@ def test_protocol_list_uses_active_tenant_v2_payment_modes(modes, expected, labe
|
||||
assert result['p1']['payModeLabel'] == label
|
||||
assert build_protocol_payment_summaries(db, ['p1'], 'tenant-a') == {}
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_protocol_list_fills_received_from_v2_sample_transfers():
|
||||
engine = create_engine('sqlite:///:memory:')
|
||||
Base.metadata.create_all(engine)
|
||||
with sessionmaker(bind=engine)() as db:
|
||||
db.add_all(
|
||||
[
|
||||
BizProtocolSamplePayment(
|
||||
id='sp-dj',
|
||||
collection_protocol_id='p-v2',
|
||||
sample_code='S1',
|
||||
pay_mode='dj',
|
||||
contract_amount=Decimal('12800'),
|
||||
tenant_no='tenant-a',
|
||||
del_flag=0,
|
||||
),
|
||||
BizProtocolSamplePayment(
|
||||
id='sp-fq',
|
||||
collection_protocol_id='p-v2',
|
||||
sample_code='S2',
|
||||
pay_mode='fq',
|
||||
contract_amount=Decimal('22880'),
|
||||
tenant_no='tenant-a',
|
||||
del_flag=0,
|
||||
),
|
||||
BizProtocolPaymentSchedule(
|
||||
id='sch-dj-1',
|
||||
sample_payment_id='sp-dj',
|
||||
collection_protocol_id='p-v2',
|
||||
sample_code='S1',
|
||||
schedule_no=1,
|
||||
due_amount=Decimal('12800'),
|
||||
due_date='20260915',
|
||||
schedule_status='cleared',
|
||||
tenant_no='tenant-a',
|
||||
del_flag=0,
|
||||
),
|
||||
BizProtocolPaymentSchedule(
|
||||
id='sch-fq-1',
|
||||
sample_payment_id='sp-fq',
|
||||
collection_protocol_id='p-v2',
|
||||
sample_code='S2',
|
||||
schedule_no=1,
|
||||
due_amount=Decimal('6480'),
|
||||
due_date='20260915',
|
||||
schedule_status='cleared',
|
||||
tenant_no='tenant-a',
|
||||
del_flag=0,
|
||||
),
|
||||
BizProtocolPaymentSchedule(
|
||||
id='sch-fq-2',
|
||||
sample_payment_id='sp-fq',
|
||||
collection_protocol_id='p-v2',
|
||||
sample_code='S2',
|
||||
schedule_no=2,
|
||||
due_amount=Decimal('16400'),
|
||||
due_date='20261015',
|
||||
schedule_status='open',
|
||||
tenant_no='tenant-a',
|
||||
del_flag=0,
|
||||
),
|
||||
BizProtocolPaymentTransfer(
|
||||
id='tr-dj',
|
||||
schedule_id='sch-dj-1',
|
||||
sample_payment_id='sp-dj',
|
||||
collection_protocol_id='p-v2',
|
||||
sample_code='S1',
|
||||
transfer_amount=Decimal('12800'),
|
||||
transfer_time=datetime(2026, 9, 15, 12, 0, 0),
|
||||
pay_status='yjf',
|
||||
tenant_no='tenant-a',
|
||||
del_flag=0,
|
||||
),
|
||||
BizProtocolPaymentTransfer(
|
||||
id='tr-fq',
|
||||
schedule_id='sch-fq-1',
|
||||
sample_payment_id='sp-fq',
|
||||
collection_protocol_id='p-v2',
|
||||
sample_code='S2',
|
||||
transfer_amount=Decimal('6480'),
|
||||
transfer_time=datetime(2026, 9, 15, 11, 13, 1),
|
||||
pay_status='yjf',
|
||||
tenant_no='tenant-a',
|
||||
del_flag=0,
|
||||
),
|
||||
BizProtocolPaymentTransfer(
|
||||
id='tr-pending',
|
||||
schedule_id='sch-fq-2',
|
||||
sample_payment_id='sp-fq',
|
||||
collection_protocol_id='p-v2',
|
||||
sample_code='S2',
|
||||
transfer_amount=None,
|
||||
transfer_time=None,
|
||||
pay_status='dfj',
|
||||
tenant_no='tenant-a',
|
||||
del_flag=0,
|
||||
),
|
||||
]
|
||||
)
|
||||
db.commit()
|
||||
result = build_protocol_payment_summaries(
|
||||
db, ['p-v2'], 'tenant-a', include_sample_payment_modes=True
|
||||
)
|
||||
summary = result['p-v2']
|
||||
assert summary['payMode'] == 'djfq'
|
||||
assert summary['contractAmount'] == 35680.0
|
||||
assert summary['receivedAmount'] == 19280.0
|
||||
assert summary['pendingAmount'] == 16400.0
|
||||
details = summary['paymentDetails']
|
||||
assert len(details) == 3
|
||||
first = [d for d in details if d['installmentNo'] == 1]
|
||||
assert sum(float(d['dueAmount'] or 0) for d in first) == 19280.0
|
||||
assert sum(float(d['transferAmount'] or 0) for d in first) == 19280.0
|
||||
# 未开启 include 时不补齐 V2 已收(质检费用摘要保持原语义)
|
||||
plain = build_protocol_payment_summaries(db, ['p-v2'], 'tenant-a')
|
||||
assert plain['p-v2'].get('receivedAmount') is None
|
||||
assert plain['p-v2'].get('paymentDetails') == []
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_protocol_list_fills_refund_amount_from_v2_refund_records():
|
||||
engine = create_engine('sqlite:///:memory:')
|
||||
Base.metadata.create_all(engine)
|
||||
with sessionmaker(bind=engine)() as db:
|
||||
db.add_all(
|
||||
[
|
||||
BizProtocolSamplePayment(
|
||||
id='sp-void',
|
||||
collection_protocol_id='p-void',
|
||||
sample_code='S9',
|
||||
pay_mode='dj',
|
||||
contract_amount=Decimal('5000'),
|
||||
tenant_no='tenant-a',
|
||||
del_flag=0,
|
||||
),
|
||||
BizProtocolPaymentSchedule(
|
||||
id='sch-void',
|
||||
sample_payment_id='sp-void',
|
||||
collection_protocol_id='p-void',
|
||||
sample_code='S9',
|
||||
schedule_no=1,
|
||||
due_amount=Decimal('5000'),
|
||||
due_date='20260918',
|
||||
schedule_status='cleared',
|
||||
tenant_no='tenant-a',
|
||||
del_flag=0,
|
||||
),
|
||||
BizProtocolPaymentTransfer(
|
||||
id='tr-void',
|
||||
schedule_id='sch-void',
|
||||
sample_payment_id='sp-void',
|
||||
collection_protocol_id='p-void',
|
||||
sample_code='S9',
|
||||
transfer_amount=Decimal('5000'),
|
||||
transfer_time=datetime(2026, 9, 18, 14, 55, 4),
|
||||
pay_status='yjf',
|
||||
tenant_no='tenant-a',
|
||||
del_flag=0,
|
||||
),
|
||||
BizProtocolRefundRecord(
|
||||
id='rf-void',
|
||||
collection_protocol_id='p-void',
|
||||
refund_amount=Decimal('5000'),
|
||||
refund_time=datetime(2026, 9, 19, 10, 0, 0),
|
||||
tenant_no='tenant-a',
|
||||
del_flag=0,
|
||||
),
|
||||
]
|
||||
)
|
||||
db.commit()
|
||||
summary = build_protocol_payment_summaries(
|
||||
db, ['p-void'], 'tenant-a', include_sample_payment_modes=True
|
||||
)['p-void']
|
||||
assert summary['receivedAmount'] == 5000.0
|
||||
assert summary['refundAmount'] == 5000.0
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,174 @@
|
||||
"""入库质检工单列表:从协议/捐赠采集信息补齐母血采集时间。"""
|
||||
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
from unittest import mock
|
||||
|
||||
import app.crud.qc_task # noqa: F401 先加载任务模块,避免与工单模块循环导入
|
||||
from app.crud import qc_work_order as qc_wo
|
||||
from app.crud.qc_work_order import _enrich_work_order_list_items
|
||||
from app.models.models import (
|
||||
BizCollectionProtocol,
|
||||
BizProtocolCollectionInfo,
|
||||
BizProtocolPartyCustomer,
|
||||
BizSampleReception,
|
||||
)
|
||||
from app.models.research_donation import (
|
||||
BizResearchDonation,
|
||||
BizResearchDonationCollection,
|
||||
BizResearchDonationParty,
|
||||
)
|
||||
|
||||
|
||||
def _item(**kwargs):
|
||||
data = {
|
||||
"id": "wo-1",
|
||||
"workOrderType": "inbound",
|
||||
"receptionId": "rec-1",
|
||||
"sampleCode": "S001",
|
||||
"collectionProtocolId": "proto-1",
|
||||
"receptionSource": "cell_storage",
|
||||
"protocolSampleId": "",
|
||||
"maternalBloodCollectTime": "",
|
||||
}
|
||||
data.update(kwargs)
|
||||
return data
|
||||
|
||||
|
||||
def _query_router(mapping):
|
||||
def _query(*entities):
|
||||
q = mock.Mock()
|
||||
q.filter.return_value = q
|
||||
q.order_by.return_value = q
|
||||
model = entities[0]
|
||||
# db.query(Model.col, ...) → first entity is InstrumentedAttribute
|
||||
cls = getattr(model, "class_", model)
|
||||
key = getattr(cls, "__name__", str(cls))
|
||||
rows = mapping.get(key, [])
|
||||
q.all.return_value = rows
|
||||
return q
|
||||
|
||||
return _query
|
||||
|
||||
|
||||
class TestEnrichWorkOrderMaternalBlood(unittest.TestCase):
|
||||
def test_cell_storage_fills_maternal_blood_collect_time(self):
|
||||
rec = mock.Mock(
|
||||
id="rec-1",
|
||||
sample_code="S001",
|
||||
reception_source="cell_storage",
|
||||
collection_protocol_id="proto-1",
|
||||
research_donation_id="",
|
||||
protocol_sample_id="",
|
||||
donation_sample_id="",
|
||||
reception_time=datetime(2026, 11, 8, 13, 30, 41),
|
||||
handler_name="质检员",
|
||||
lab_storage_code="",
|
||||
)
|
||||
coll = mock.Mock(
|
||||
collection_protocol_id="proto-1",
|
||||
maternal_blood_collect_time=datetime(2026, 11, 7, 9, 15, 0),
|
||||
del_flag=0,
|
||||
)
|
||||
db = mock.Mock()
|
||||
db.query.side_effect = _query_router(
|
||||
{
|
||||
BizSampleReception.__name__: [rec],
|
||||
BizProtocolCollectionInfo.__name__: [coll],
|
||||
BizProtocolPartyCustomer.__name__: [],
|
||||
BizCollectionProtocol.__name__: [],
|
||||
}
|
||||
)
|
||||
|
||||
with mock.patch.object(
|
||||
qc_wo, "_enrich_protocol_sibling_samples", side_effect=lambda _db, items: items
|
||||
), mock.patch.object(
|
||||
qc_wo, "apply_special_to_item_from_samples", side_effect=lambda item, **_k: item
|
||||
):
|
||||
items = _enrich_work_order_list_items(db, [_item()])
|
||||
|
||||
self.assertEqual(items[0]["maternalBloodCollectTime"], "2026-11-07 09:15:00")
|
||||
|
||||
def test_missing_maternal_blood_stays_empty(self):
|
||||
rec = mock.Mock(
|
||||
id="rec-1",
|
||||
sample_code="S001",
|
||||
reception_source="cell_storage",
|
||||
collection_protocol_id="proto-1",
|
||||
research_donation_id="",
|
||||
protocol_sample_id="",
|
||||
donation_sample_id="",
|
||||
reception_time=datetime(2026, 11, 8, 13, 30, 41),
|
||||
handler_name="质检员",
|
||||
lab_storage_code="",
|
||||
)
|
||||
db = mock.Mock()
|
||||
db.query.side_effect = _query_router(
|
||||
{
|
||||
BizSampleReception.__name__: [rec],
|
||||
BizProtocolCollectionInfo.__name__: [],
|
||||
BizProtocolPartyCustomer.__name__: [],
|
||||
BizCollectionProtocol.__name__: [],
|
||||
}
|
||||
)
|
||||
|
||||
with mock.patch.object(
|
||||
qc_wo, "_enrich_protocol_sibling_samples", side_effect=lambda _db, items: items
|
||||
), mock.patch.object(
|
||||
qc_wo, "apply_special_to_item_from_samples", side_effect=lambda item, **_k: item
|
||||
):
|
||||
items = _enrich_work_order_list_items(db, [_item()])
|
||||
|
||||
self.assertEqual(items[0]["maternalBloodCollectTime"], "")
|
||||
|
||||
def test_research_donation_fills_maternal_blood_collect_time(self):
|
||||
rec = mock.Mock(
|
||||
id="rec-2",
|
||||
sample_code="D001",
|
||||
reception_source="research_donation",
|
||||
collection_protocol_id="",
|
||||
research_donation_id="don-1",
|
||||
protocol_sample_id="",
|
||||
donation_sample_id="",
|
||||
reception_time=datetime(2026, 11, 8, 10, 0, 0),
|
||||
handler_name="质检员",
|
||||
lab_storage_code="",
|
||||
)
|
||||
coll = mock.Mock(
|
||||
research_donation_id="don-1",
|
||||
maternal_blood_collect_time=datetime(2026, 11, 6, 8, 0, 0),
|
||||
del_flag=0,
|
||||
)
|
||||
db = mock.Mock()
|
||||
db.query.side_effect = _query_router(
|
||||
{
|
||||
BizSampleReception.__name__: [rec],
|
||||
BizResearchDonationCollection.__name__: [coll],
|
||||
BizResearchDonationParty.__name__: [],
|
||||
BizResearchDonation.__name__: [],
|
||||
}
|
||||
)
|
||||
|
||||
with mock.patch.object(
|
||||
qc_wo, "_enrich_protocol_sibling_samples", side_effect=lambda _db, items: items
|
||||
), mock.patch.object(
|
||||
qc_wo, "apply_special_to_item_from_samples", side_effect=lambda item, **_k: item
|
||||
):
|
||||
items = _enrich_work_order_list_items(
|
||||
db,
|
||||
[
|
||||
_item(
|
||||
id="wo-2",
|
||||
receptionId="rec-2",
|
||||
sampleCode="D001",
|
||||
collectionProtocolId="don-1",
|
||||
receptionSource="research_donation",
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
self.assertEqual(items[0]["maternalBloodCollectTime"], "2026-11-06 08:00:00")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -8,8 +8,10 @@ from app.services.sample_storage_cert_qc import (
|
||||
SAMPLE_TYPE_KEY_PERINATAL_HSC,
|
||||
SAMPLE_TYPE_KEY_UC_MSC,
|
||||
empty_detail,
|
||||
merge_payload_with_acl,
|
||||
normalize_payload,
|
||||
resolve_sample_type_key,
|
||||
sanitize_payload_for_type,
|
||||
supports_storage_cert_qc,
|
||||
)
|
||||
from app.services.sample_storage_cert_qc_prefill import (
|
||||
@@ -51,6 +53,34 @@ class TestNormalizePayload(unittest.TestCase):
|
||||
self.assertNotIn(1, out)
|
||||
|
||||
|
||||
class TestSanitizePayloadForType(unittest.TestCase):
|
||||
def test_uc_msc_drops_mother_nucleic_acids(self):
|
||||
out = sanitize_payload_for_type(
|
||||
{
|
||||
"mother_hbsag": "阴性",
|
||||
"mother_hbv_dna": "阴性",
|
||||
"mother_hcv_rna": "阳性",
|
||||
"mother_hiv1_rna": "阴性",
|
||||
"mother_cmv_igm": "阴性",
|
||||
},
|
||||
SAMPLE_TYPE_KEY_UC_MSC,
|
||||
)
|
||||
self.assertEqual(out["mother_hbsag"], "阴性")
|
||||
self.assertEqual(out["mother_cmv_igm"], "阴性")
|
||||
self.assertNotIn("mother_hbv_dna", out)
|
||||
self.assertNotIn("mother_hcv_rna", out)
|
||||
self.assertNotIn("mother_hiv1_rna", out)
|
||||
|
||||
def test_perinatal_keeps_mother_nucleic_acids(self):
|
||||
payload = {
|
||||
"mother_hbv_dna": "阴性",
|
||||
"mother_hcv_rna": "阴性",
|
||||
"mother_hiv1_rna": "阴性",
|
||||
}
|
||||
out = sanitize_payload_for_type(payload, SAMPLE_TYPE_KEY_PERINATAL_HSC)
|
||||
self.assertEqual(out, payload)
|
||||
|
||||
|
||||
class TestEmptyDetail(unittest.TestCase):
|
||||
def test_shape(self):
|
||||
d = empty_detail(
|
||||
@@ -302,13 +332,13 @@ class TestStorageCertPrefill(unittest.TestCase):
|
||||
]
|
||||
suggested = build_suggested(sample_type_key="uc_msc", shared_mother_tasks=shared)
|
||||
self.assertEqual(suggested["mother_hbsag"], "阴性")
|
||||
self.assertEqual(suggested["mother_hbv_dna"], "阴性")
|
||||
self.assertNotIn("mother_hbv_dna", suggested)
|
||||
self.assertEqual(suggested["mother_anti_hcv"], "阴性")
|
||||
self.assertEqual(suggested["mother_hcv_rna"], "阴性")
|
||||
self.assertNotIn("mother_hcv_rna", suggested)
|
||||
self.assertEqual(suggested["mother_anti_tp"], "阴性")
|
||||
self.assertEqual(suggested["mother_cmv_igm"], "阴性")
|
||||
self.assertEqual(suggested["mother_anti_hiv"], "阴性")
|
||||
self.assertEqual(suggested["mother_hiv1_rna"], "阴性")
|
||||
self.assertNotIn("mother_hiv1_rna", suggested)
|
||||
self.assertNotIn("hbsag", suggested)
|
||||
|
||||
def test_own_mother_blood_wins_and_shared_only_fills_gaps(self):
|
||||
@@ -339,5 +369,35 @@ class TestStorageCertPrefill(unittest.TestCase):
|
||||
self.assertNotIn("hbsag", merged)
|
||||
|
||||
|
||||
class TestMergePayloadWithAcl(unittest.TestCase):
|
||||
def test_merges_only_editable_keys(self):
|
||||
merged = merge_payload_with_acl(
|
||||
existing={"receive_time": "a", "bacteria_test": "阴性"},
|
||||
incoming={"receive_time": "b", "bacteria_test": "阴性"},
|
||||
editable_keys=["receive_time"],
|
||||
sample_type_key=SAMPLE_TYPE_KEY_PERINATAL_HSC,
|
||||
)
|
||||
self.assertEqual(merged["receive_time"], "b")
|
||||
self.assertEqual(merged["bacteria_test"], "阴性")
|
||||
|
||||
def test_rejects_unauthorized_change(self):
|
||||
with self.assertRaises(PermissionError):
|
||||
merge_payload_with_acl(
|
||||
existing={"bacteria_test": "阴性"},
|
||||
incoming={"bacteria_test": "阳性"},
|
||||
editable_keys=["receive_time"],
|
||||
sample_type_key=SAMPLE_TYPE_KEY_PERINATAL_HSC,
|
||||
)
|
||||
|
||||
def test_rejects_empty_editable_keys(self):
|
||||
with self.assertRaises(PermissionError):
|
||||
merge_payload_with_acl(
|
||||
existing={},
|
||||
incoming={"receive_time": "x"},
|
||||
editable_keys=[],
|
||||
sample_type_key=SAMPLE_TYPE_KEY_PERINATAL_HSC,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,101 @@
|
||||
"""储存证质检字段 ACL:合法字段与 scope。"""
|
||||
import unittest
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from sqlalchemy.dialects import mysql
|
||||
|
||||
from app.crud import sample_storage_cert_qc_acl as acl_svc
|
||||
from app.models.models import BizStorageCertQcAcl, BizStorageCertQcAclUser, SysUser
|
||||
from app.services.sample_storage_cert_qc import (
|
||||
ACL_SCOPE_PRODUCTION,
|
||||
ACL_SCOPE_QC,
|
||||
ALL_STORAGE_CERT_QC_FIELD_KEYS,
|
||||
SAMPLE_TYPE_KEY_UC_MSC,
|
||||
dumps_field_keys,
|
||||
legal_field_keys_for_type,
|
||||
loads_field_keys,
|
||||
)
|
||||
|
||||
|
||||
class TestAclFieldKeys(unittest.TestCase):
|
||||
def test_uc_msc_excludes_mother_nucleic_acids(self):
|
||||
keys = legal_field_keys_for_type(SAMPLE_TYPE_KEY_UC_MSC)
|
||||
self.assertNotIn("mother_hbv_dna", keys)
|
||||
self.assertIn("mother_hbsag", keys)
|
||||
|
||||
def test_roundtrip_field_keys(self):
|
||||
raw = dumps_field_keys(["receive_time", "bacteria_test", "receive_time", ""])
|
||||
self.assertEqual(loads_field_keys(raw), ["bacteria_test", "receive_time"])
|
||||
|
||||
def test_all_keys_cover_common_fields(self):
|
||||
self.assertIn("receive_time", ALL_STORAGE_CERT_QC_FIELD_KEYS)
|
||||
self.assertIn("mother_anti_hiv", ALL_STORAGE_CERT_QC_FIELD_KEYS)
|
||||
|
||||
def test_scopes(self):
|
||||
self.assertEqual(ACL_SCOPE_QC, "qc")
|
||||
self.assertEqual(ACL_SCOPE_PRODUCTION, "production")
|
||||
|
||||
|
||||
class TestAclUserJoinCollation(unittest.TestCase):
|
||||
def test_detail_user_join_uses_unicode_collate(self):
|
||||
"""JOIN sys_user 时统一 utf8mb4_unicode_ci,避免 1267 mix of collations。"""
|
||||
acl = MagicMock()
|
||||
acl.id = "acl-1"
|
||||
acl.field_keys = "[]"
|
||||
acl.configured_flag = "1"
|
||||
|
||||
captured = {}
|
||||
|
||||
class _Query:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def filter(self, *args, **kwargs):
|
||||
captured.setdefault("filters", []).extend(args)
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return acl
|
||||
|
||||
def outerjoin(self, *args, **kwargs):
|
||||
captured["join_on"] = args[1] if len(args) > 1 else None
|
||||
return self
|
||||
|
||||
def order_by(self, *args, **kwargs):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return []
|
||||
|
||||
db = MagicMock()
|
||||
db.query.side_effect = lambda *args, **kwargs: _Query()
|
||||
|
||||
detail = acl_svc.get_acl_detail(db, "t1", "qc")
|
||||
self.assertEqual(detail["scope"], "qc")
|
||||
join_on = captured.get("join_on")
|
||||
self.assertIsNotNone(join_on)
|
||||
sql = str(
|
||||
join_on.compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True})
|
||||
).lower()
|
||||
self.assertIn("utf8mb4_unicode_ci", sql)
|
||||
filter_sql = " ".join(
|
||||
str(f.compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True})).lower()
|
||||
for f in captured.get("filters", [])
|
||||
)
|
||||
self.assertIn("utf8mb4_unicode_ci", filter_sql)
|
||||
self.assertIn("sys_user", SysUser.__tablename__)
|
||||
self.assertIn("biz_storage_cert_qc_acl_user", BizStorageCertQcAclUser.__tablename__)
|
||||
self.assertEqual(BizStorageCertQcAcl.__tablename__, "biz_storage_cert_qc_acl")
|
||||
|
||||
def test_eq_unicode_literal_only_collates_column(self):
|
||||
from app.core.db_collation import eq_unicode
|
||||
|
||||
expr = eq_unicode(BizStorageCertQcAcl.tenant_no, "t1")
|
||||
sql = str(
|
||||
expr.compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True})
|
||||
).lower()
|
||||
self.assertIn("utf8mb4_unicode_ci", sql)
|
||||
self.assertEqual(sql.count("utf8mb4_unicode_ci"), 1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,41 @@
|
||||
import os
|
||||
import unittest
|
||||
|
||||
# 避免导入 app.models 时 Settings 因缺 SECRET_KEY 失败
|
||||
os.environ.setdefault(
|
||||
"SECRET_KEY", "test-secret-key-for-uc-msc-unit-tests-32c"
|
||||
)
|
||||
|
||||
|
||||
class TestUcMscBuiltinTemplate(unittest.TestCase):
|
||||
def test_step_order_matches_business_five_nodes(self):
|
||||
from app.services.uc_msc_builtin_template import UC_MSC_STEP_ORDER
|
||||
|
||||
self.assertEqual(
|
||||
UC_MSC_STEP_ORDER,
|
||||
[
|
||||
"SOP-SC-003-E01-01",
|
||||
"SOP-SC-004-E01-01",
|
||||
"SOP-SC-006-E01-01",
|
||||
"SOP-SC-005-E01-01",
|
||||
"SOP-SC-008-E01-01",
|
||||
],
|
||||
)
|
||||
self.assertNotIn("SOP-SC-007-E01-01", UC_MSC_STEP_ORDER)
|
||||
|
||||
def test_uc_prefix_maps_to_uc_set_name(self):
|
||||
from app.services.uc_msc_builtin_template import UC_MSC_ROUTE_CODE
|
||||
from app.utils.lab_storage_code_task_set import (
|
||||
UC_MSC_BUILTIN_SET_NAME,
|
||||
match_builtin_task_set_name_by_lab_storage_code,
|
||||
)
|
||||
|
||||
self.assertEqual(UC_MSC_ROUTE_CODE, "MSC原代-UC-BUILTIN")
|
||||
self.assertEqual(
|
||||
match_builtin_task_set_name_by_lab_storage_code("UC2026010"),
|
||||
UC_MSC_BUILTIN_SET_NAME,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -60,6 +60,13 @@ Agent 需要你做决定时,会在当前回复里直接写出「待你确认
|
||||
|
||||
完整安装提供 `notify-question` 命令,由 Agent 在提问后调用,不是宿主自动弹窗钩子。当前支持用户 macOS 本机;其他系统或远程执行缺少本地播放条件时回退文字提醒,不代表你已听到。安装、更新、普通进度和结束答复不播放。细则见安装目录 `references/question-notification.md`。
|
||||
|
||||
### 在 Cursor 里听到提示音却看不到题时
|
||||
|
||||
- 提示音在整机播放,**不会自动跳到对应聊天**;请到正在跑 Agent 的会话里搜索「待你确认」。
|
||||
- 输入框上方的 **Queued / Start Multitasking** 是你排队的后续消息,**不是**确认清单。
|
||||
- Cursor 会先跑工具再刷出最终正文,声音可能比清单早响一两秒;清单应出现在该轮助手正文开头。多会话并行时,切换其他进行中会话再搜一次。
|
||||
- 工程内 Agent 适配约定见 [Cursor 确认可见性](cursor-question-visibility.md)。
|
||||
|
||||
## 日常开发怎么提需求
|
||||
|
||||
| 场景 | 可以直接发送的示例 |
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# Cursor 宿主:确认问题可见性
|
||||
|
||||
个人开发体系要求:先在用户可见回复写出「待你确认」,再播放本机提示音。Cursor Agent 的执行顺序与此不完全同构,本文件是工程内的 Cursor 适配约定;与安装目录 `references/planning.md`、`references/question-notification.md` 并用,冲突时以「用户必须先看见清单」为准。
|
||||
|
||||
## Cursor 执行顺序
|
||||
|
||||
1. 同轮内的**工具调用先执行**,最终助手正文后出现。
|
||||
2. `notify-question`(`afplay`)若作为工具调用,提示音可能比「待你确认」正文早数秒响起。
|
||||
3. 提示音在**整机**播放,不绑定当前聚焦的聊天标签;多会话并行时,声音来源会话可能不是眼前这个。
|
||||
4. 输入框上方的 **Queued / Start Multitasking** 是用户排队的后续消息,**不是** Agent 确认清单。
|
||||
|
||||
## Agent 必须遵守
|
||||
|
||||
发问当轮:
|
||||
|
||||
1. **先写清单**:该轮最终用户可见回复必须以「待你确认」开头(或紧接一句定位后立刻出现该标题),按问题展示规则写全题、推荐、理由与未回复处理。
|
||||
2. **同轮停手**:写出清单并(如需)播放提示音后,本轮不得再调用编辑、浏览器、继续实现等工具;依赖答复的工作等下一轮。允许的独立只读工作若与本题无关,应在发问**之前**做完,或放到用户答复之后。
|
||||
3. **提示音时机**:需要播放时,`notify-question` 必须是本轮**最后一次**工具调用,且本轮最终正文就是确认清单。禁止在仍计划继续工具批处理时提前播放。
|
||||
4. **正文定位**:清单首段或标题下用一句说明「请在本会话回复;提示音不念题目,底部 Queued 不是确认入口。」
|
||||
5. **无清单不播放**:最终正文没有「待你确认」时,不得调用 `notify-question`。
|
||||
6. **原生卡片**:若当前 Cursor 会话提供宿主提问/确认卡片,可与清单并用,卡片内容须与「待你确认」一致;不得只用卡片、省略正文清单。
|
||||
|
||||
## 用户侧核对
|
||||
|
||||
听到「有问题待确认」时:
|
||||
|
||||
1. 看**正在或刚结束工具步骤的那个聊天**(不必先看 Queued)。
|
||||
2. 在该会话搜索或上翻 **「待你确认」**;清单在工具时间线收折块之外的助手正文里。
|
||||
3. 若多聊天并行,切换到其他进行中会话再搜同一标题。
|
||||
|
||||
## 静音与一分钟策略
|
||||
|
||||
声音开关、一分钟默认选择仍按安装目录规则;本文件不改变其语义,只约束 Cursor 下的展示与播音顺序。
|
||||
@@ -79,10 +79,13 @@
|
||||
"evidence": "用户确认既有 Gitea/Drone Tag 打包已完成,本次不复查或修改流水线。"
|
||||
},
|
||||
"permissions": {
|
||||
"push_task_branch": false,
|
||||
"create_pr": false,
|
||||
"write_issue": false,
|
||||
"merge": false,
|
||||
"push_task_branch": true,
|
||||
"create_pr": true,
|
||||
"write_issue": true,
|
||||
"close_issue": true,
|
||||
"merge": true,
|
||||
"manage_claims": true,
|
||||
"update_issue_labels": true,
|
||||
"push_tag": false,
|
||||
"deploy": false
|
||||
},
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
-- =============================================================================
|
||||
-- 弱密码刷新说明:111111 → Zkxw@123
|
||||
-- 日期:2026-10-16
|
||||
-- =============================================================================
|
||||
--
|
||||
-- 重要:sys_user.password 存储 bcrypt 哈希(每次盐随机),
|
||||
-- 不能用下列语句命中弱密码用户:
|
||||
-- WHERE password = '111111' -- 无效
|
||||
-- WHERE password LIKE '%111111%' -- 无效
|
||||
--
|
||||
-- 推荐:用 Python 脚本,并通过变量指定目标库(勿依赖本机默认 .env 误连生产)。
|
||||
--
|
||||
-- cd backend && source venv/bin/activate
|
||||
--
|
||||
-- # 方式 A:完整 URL
|
||||
-- python scripts/reset_weak_password_111111.py \
|
||||
-- --database-url 'mysql+pymysql://USER:PASS@HOST:3306/DBNAME' --dry-run
|
||||
--
|
||||
-- # 方式 B:分项变量
|
||||
-- python scripts/reset_weak_password_111111.py \
|
||||
-- --db-host HOST --db-port 3306 --db-user USER --db-password 'PASS' --db-name DBNAME --dry-run
|
||||
--
|
||||
-- # 方式 C:指定环境文件
|
||||
-- python scripts/reset_weak_password_111111.py --env-file ./.env.test --dry-run
|
||||
--
|
||||
-- # 正式写入:去掉 --dry-run
|
||||
--
|
||||
-- 脚本行为:校验 del_flag=0 的用户口令是否为明文 111111(含停用账号),
|
||||
-- 命中则更新为 Zkxw@123 的新 bcrypt 哈希。
|
||||
--
|
||||
-- =============================================================================
|
||||
-- 以下仅为「已知单个用户 id」时的手工 UPDATE 模板。
|
||||
-- 哈希由本机生成示例(明文 Zkxw@123,bcrypt cost 12),部署前请用 Python 重新生成:
|
||||
-- python -c "from app.core.security import get_password_hash; print(get_password_hash('Zkxw@123'))"
|
||||
-- =============================================================================
|
||||
|
||||
-- 示例哈希(仅供手工单用户更新参考;批量请用脚本):
|
||||
-- $2b$12$ULvPCr6g9IUmI8K7nlGU5emk7hupaAz4WgFdEoQBe935Wh1pVYKCK
|
||||
|
||||
-- UPDATE sys_user
|
||||
-- SET password = '$2b$12$ULvPCr6g9IUmI8K7nlGU5emk7hupaAz4WgFdEoQBe935Wh1pVYKCK',
|
||||
-- update_time = NOW()
|
||||
-- WHERE id = '<user_id>'
|
||||
-- AND del_flag = 0;
|
||||
|
||||
-- 执行前请备份 sys_user;执行后通知用户使用新密码并建议登录后自行修改。
|
||||
@@ -1,6 +1,10 @@
|
||||
-- Issue #24:协议单操作过程日志(before / action / after)
|
||||
-- MySQL 5.7;可重复执行(CREATE IF NOT EXISTS)。上线前须备份并在目标副本验证。
|
||||
-- DDL 隐式提交;该脚本不作为自动应用启动步骤。
|
||||
--
|
||||
-- 注意:若目标库已存在同名「采集协议单操作日志」旧表(含 collection_protocol_id /
|
||||
-- operation_code 等列),本脚本会因 IF NOT EXISTS 直接跳过,不会纠偏。
|
||||
-- 生产纠偏请改用:2026-11-09-protocol-operation-log-rebuild.sql
|
||||
|
||||
CREATE TABLE IF NOT EXISTS biz_protocol_operation_log (
|
||||
id VARCHAR(64) NOT NULL,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
-- =============================================================================
|
||||
-- 协议操作日志:兼容生产旧表同名冲突,重建为 Issue #24 模型
|
||||
-- MySQL 5.7;可重复执行。上线前须备份,并在目标副本验证。
|
||||
--
|
||||
-- 背景:
|
||||
-- 生产曾有「采集协议单操作日志」同名表(collection_protocol_id / operation_*),
|
||||
-- 与当前代码(biz_type / before_json / after_json)不兼容。
|
||||
-- 旧脚本 2026-11-05-protocol-operation-log.sql 使用 CREATE IF NOT EXISTS,
|
||||
-- 遇到旧表会直接跳过,无法纠偏。本脚本用于生产纠偏与新环境兜底。
|
||||
--
|
||||
-- 行为:
|
||||
-- 1) 已是新模型(有 biz_type)→ 跳过结构变更
|
||||
-- 2) 旧模型且 0 行 → DROP 后按新模型 CREATE
|
||||
-- 3) 旧模型且有数据 → RENAME 为 biz_protocol_operation_log_legacy_20261109 再 CREATE
|
||||
-- 4) 表不存在 → 直接 CREATE
|
||||
-- =============================================================================
|
||||
|
||||
SET @db := DATABASE();
|
||||
|
||||
SET @table_exists := (
|
||||
SELECT COUNT(*) FROM information_schema.tables
|
||||
WHERE table_schema = @db AND table_name = 'biz_protocol_operation_log'
|
||||
);
|
||||
|
||||
SET @has_legacy_col := (
|
||||
SELECT COUNT(*) FROM information_schema.columns
|
||||
WHERE table_schema = @db
|
||||
AND table_name = 'biz_protocol_operation_log'
|
||||
AND column_name = 'collection_protocol_id'
|
||||
);
|
||||
|
||||
SET @has_new_col := (
|
||||
SELECT COUNT(*) FROM information_schema.columns
|
||||
WHERE table_schema = @db
|
||||
AND table_name = 'biz_protocol_operation_log'
|
||||
AND column_name = 'biz_type'
|
||||
);
|
||||
|
||||
SET @is_legacy := IF(@table_exists > 0 AND @has_legacy_col > 0 AND @has_new_col = 0, 1, 0);
|
||||
|
||||
SET @legacy_rows := 0;
|
||||
SET @cnt_sql := IF(
|
||||
@is_legacy = 1,
|
||||
'SET @legacy_rows = (SELECT COUNT(*) FROM `biz_protocol_operation_log`)',
|
||||
'SET @legacy_rows = 0'
|
||||
);
|
||||
PREPARE pol_stmt FROM @cnt_sql;
|
||||
EXECUTE pol_stmt;
|
||||
DEALLOCATE PREPARE pol_stmt;
|
||||
|
||||
-- 空旧表:直接删除
|
||||
SET @drop_sql := IF(
|
||||
@is_legacy = 1 AND @legacy_rows = 0,
|
||||
'DROP TABLE `biz_protocol_operation_log`',
|
||||
'SELECT ''skip drop empty legacy biz_protocol_operation_log'' AS migration_status'
|
||||
);
|
||||
PREPARE pol_stmt FROM @drop_sql;
|
||||
EXECUTE pol_stmt;
|
||||
DEALLOCATE PREPARE pol_stmt;
|
||||
|
||||
-- 有数据的旧表:改名保留,避免丢历史(当前生产为 0 行,通常不会走到这里)
|
||||
SET @legacy_backup_exists := (
|
||||
SELECT COUNT(*) FROM information_schema.tables
|
||||
WHERE table_schema = @db AND table_name = 'biz_protocol_operation_log_legacy_20261109'
|
||||
);
|
||||
SET @rename_sql := IF(
|
||||
@is_legacy = 1 AND @legacy_rows > 0 AND @legacy_backup_exists = 0,
|
||||
'RENAME TABLE `biz_protocol_operation_log` TO `biz_protocol_operation_log_legacy_20261109`',
|
||||
IF(
|
||||
@is_legacy = 1 AND @legacy_rows > 0 AND @legacy_backup_exists > 0,
|
||||
'SELECT ''ERROR: legacy backup biz_protocol_operation_log_legacy_20261109 already exists; resolve manually'' AS migration_status',
|
||||
'SELECT ''skip rename legacy biz_protocol_operation_log'' AS migration_status'
|
||||
)
|
||||
);
|
||||
PREPARE pol_stmt FROM @rename_sql;
|
||||
EXECUTE pol_stmt;
|
||||
DEALLOCATE PREPARE pol_stmt;
|
||||
|
||||
-- 新模型建表(纠偏后或全新环境)
|
||||
CREATE TABLE IF NOT EXISTS `biz_protocol_operation_log` (
|
||||
`id` VARCHAR(64) NOT NULL COMMENT '主键ID',
|
||||
`biz_type` VARCHAR(32) NOT NULL COMMENT '业务类型 cell_storage/research_donation',
|
||||
`biz_id` VARCHAR(64) NOT NULL COMMENT '协议单或捐赠单ID',
|
||||
`protocol_no` VARCHAR(64) NULL COMMENT '协议/捐赠编号快照',
|
||||
`action` VARCHAR(32) NOT NULL COMMENT '动作 create/update/delete/void/activate/expire/to_research/to_storage/audit',
|
||||
`client_channel` VARCHAR(16) NOT NULL DEFAULT 'web' COMMENT '来源端 web/mini',
|
||||
`before_json` MEDIUMTEXT NULL COMMENT '操作前协议信息JSON',
|
||||
`after_json` MEDIUMTEXT NULL COMMENT '操作后协议信息JSON',
|
||||
`operator_user_id` VARCHAR(64) NULL COMMENT '操作人用户ID',
|
||||
`operator_user_name` VARCHAR(64) NULL COMMENT '操作人姓名快照',
|
||||
`operate_time` DATETIME NOT NULL COMMENT '业务操作时间',
|
||||
`tenant_no` VARCHAR(64) NOT NULL COMMENT '租户编号',
|
||||
`order_num` INT NULL COMMENT '排序号',
|
||||
`remark` VARCHAR(512) NULL COMMENT '备注',
|
||||
`create_by` VARCHAR(64) NULL COMMENT '创建人id',
|
||||
`create_dept_id` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '创建人部门ID',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_by` VARCHAR(64) NULL COMMENT '更新人id',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`del_flag` SMALLINT NOT NULL DEFAULT 0 COMMENT '删除标记',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `ix_pol_biz` (`tenant_no`, `biz_type`, `biz_id`, `del_flag`),
|
||||
KEY `ix_pol_time` (`tenant_no`, `operate_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='协议单操作过程日志';
|
||||
|
||||
-- 验收:新模型关键列应存在
|
||||
SELECT
|
||||
COLUMN_NAME,
|
||||
COLUMN_TYPE,
|
||||
IS_NULLABLE,
|
||||
COLUMN_COMMENT
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = 'biz_protocol_operation_log'
|
||||
AND COLUMN_NAME IN (
|
||||
'biz_type', 'biz_id', 'action', 'before_json', 'after_json',
|
||||
'client_channel', 'operate_time', 'collection_protocol_id', 'operation_code'
|
||||
)
|
||||
ORDER BY ORDINAL_POSITION;
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Issue #97:将储存证质检 ACL 表 collation 对齐库默认 utf8mb4_unicode_ci。
|
||||
-- 修复与 sys_user 等表 JOIN 时 Illegal mix of collations。可重复执行。
|
||||
|
||||
ALTER TABLE biz_storage_cert_qc_acl
|
||||
CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
ALTER TABLE biz_storage_cert_qc_acl_user
|
||||
CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
SELECT table_name, table_collation
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name IN ('biz_storage_cert_qc_acl', 'biz_storage_cert_qc_acl_user')
|
||||
ORDER BY table_name;
|
||||
@@ -0,0 +1,108 @@
|
||||
-- Issue #93:储存证质检信息字段级 ACL(质检/生产)。MySQL 5.7,可重复执行。
|
||||
-- 菜单按钮「储存证质检字段权限配置」控制弹窗 footer 的「质检权限」「生产权限」入口;
|
||||
-- 本脚本会将该按钮授权给当前租户下全部有效角色。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS biz_storage_cert_qc_acl (
|
||||
id VARCHAR(64) NOT NULL,
|
||||
scope VARCHAR(32) NOT NULL COMMENT 'qc|production',
|
||||
field_keys TEXT NOT NULL COMMENT '可编辑字段 key JSON 数组',
|
||||
configured_flag CHAR(1) NOT NULL DEFAULT '0' COMMENT '是否已正式配置 0否1是',
|
||||
tenant_no VARCHAR(64) NOT NULL,
|
||||
order_num INT NULL,
|
||||
remark VARCHAR(512) NULL,
|
||||
create_by VARCHAR(64) NULL,
|
||||
create_dept_id VARCHAR(64) NOT NULL DEFAULT '',
|
||||
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
update_by VARCHAR(64) NULL,
|
||||
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
del_flag SMALLINT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (id),
|
||||
KEY ix_tenant_scope (tenant_no, scope, del_flag)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS biz_storage_cert_qc_acl_user (
|
||||
id VARCHAR(64) NOT NULL,
|
||||
acl_id VARCHAR(64) NOT NULL,
|
||||
user_id VARCHAR(64) NOT NULL,
|
||||
tenant_no VARCHAR(64) NOT NULL,
|
||||
order_num INT NULL,
|
||||
remark VARCHAR(512) NULL,
|
||||
create_by VARCHAR(64) NULL,
|
||||
create_dept_id VARCHAR(64) NOT NULL DEFAULT '',
|
||||
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
update_by VARCHAR(64) NULL,
|
||||
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
del_flag SMALLINT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (id),
|
||||
KEY ix_tenant_acl (tenant_no, acl_id, del_flag),
|
||||
KEY ix_tenant_user (tenant_no, user_id, del_flag)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
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('storage-cert-qc-acl:', parent.tenant_no, ':', parent.id)),
|
||||
13, 1, '3'), 17, 1, '8'),
|
||||
'储存证质检字段权限配置', parent.id, 'F', '', NULL,
|
||||
'cell-storage:sample-info:storage-cert-qc-acl', 1, '1', '1', parent.tenant_no, 95,
|
||||
'控制储存证质检弹窗中质检/生产字段与人员 ACL 配置入口',
|
||||
'migration', '', NOW(), 'migration', NOW(), 0
|
||||
FROM sys_menu AS parent
|
||||
WHERE parent.del_flag = 0 AND parent.status = '1'
|
||||
AND parent.perms = 'cell-storage:sample-info:list'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM sys_menu AS existing
|
||||
WHERE existing.parent_id = parent.id
|
||||
AND existing.tenant_no = parent.tenant_no
|
||||
AND existing.perms = 'cell-storage:sample-info:storage-cert-qc-acl'
|
||||
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('storage-cert-qc-acl-role:', r.tenant_no, ':', r.id, ':', m.id)),
|
||||
13, 1, '3'), 17, 1, '8'),
|
||||
r.id,
|
||||
m.id,
|
||||
r.tenant_no,
|
||||
NULL,
|
||||
'migration: grant storage-cert-qc-acl to all roles',
|
||||
'migration',
|
||||
'',
|
||||
NOW(),
|
||||
'migration',
|
||||
NOW(),
|
||||
0
|
||||
FROM sys_role AS r
|
||||
JOIN sys_menu AS m
|
||||
ON m.tenant_no = r.tenant_no
|
||||
AND m.perms = 'cell-storage:sample-info:storage-cert-qc-acl'
|
||||
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, perms, status
|
||||
FROM sys_menu
|
||||
WHERE perms = 'cell-storage:sample-info:storage-cert-qc-acl' AND del_flag = 0;
|
||||
|
||||
SELECT r.tenant_no, r.role_name, m.perms, rm.id AS role_menu_id
|
||||
FROM sys_role_menu AS rm
|
||||
JOIN sys_role AS r ON r.id = rm.role_id AND r.tenant_no = rm.tenant_no AND r.del_flag = 0
|
||||
JOIN sys_menu AS m ON m.id = rm.menu_id AND m.tenant_no = rm.tenant_no AND m.del_flag = 0
|
||||
WHERE m.perms = 'cell-storage:sample-info:storage-cert-qc-acl'
|
||||
AND rm.del_flag = 0
|
||||
ORDER BY r.tenant_no, r.role_name;
|
||||
@@ -0,0 +1,148 @@
|
||||
-- Issue #98:实验室样本处理数据台账(补录表 + 质检管理菜单)
|
||||
-- MySQL 5.7,可重复执行。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS biz_lab_sample_process_supplement (
|
||||
id VARCHAR(64) NOT NULL,
|
||||
lab_storage_code VARCHAR(32) NOT NULL COMMENT '实验室入库编码(唯一业务键)',
|
||||
reception_source VARCHAR(20) NOT NULL DEFAULT 'cell_storage' COMMENT 'cell_storage|research_donation',
|
||||
sample_type_name VARCHAR(100) NULL COMMENT '样本类型名称快照',
|
||||
payload TEXT NOT NULL COMMENT '补录字段 JSON',
|
||||
tenant_no VARCHAR(64) NOT NULL,
|
||||
order_num INT NULL,
|
||||
remark VARCHAR(512) NULL,
|
||||
create_by VARCHAR(64) NULL,
|
||||
create_dept_id VARCHAR(64) NOT NULL DEFAULT '',
|
||||
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
update_by VARCHAR(64) NULL,
|
||||
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
del_flag SMALLINT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (id),
|
||||
KEY ix_tenant_lab_code (tenant_no, lab_storage_code, del_flag),
|
||||
KEY ix_tenant_source_type (tenant_no, reception_source, sample_type_name, del_flag)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- 菜单:挂在「质检管理」下(以样本接收菜单同父节点为准)
|
||||
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('lab-sample-process:', parent.tenant_no, ':', parent.id)),
|
||||
13, 1, '3'), 17, 1, '8'),
|
||||
'实验室样本处理数据', parent.parent_id, 'C',
|
||||
'lab-sample-process',
|
||||
'quality-inspection/lab-sample-process/index',
|
||||
'biz:labSampleProcess:list',
|
||||
1, '1', '1', parent.tenant_no, 35,
|
||||
'质检管理-实验室样本处理数据台账',
|
||||
'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:labSampleProcess:list'
|
||||
AND existing.del_flag = 0
|
||||
);
|
||||
|
||||
-- 补录按钮
|
||||
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('lab-sample-process-sup:', m.tenant_no, ':', m.id)),
|
||||
13, 1, '3'), 17, 1, '8'),
|
||||
'补录', m.id, 'F', '', NULL,
|
||||
'biz:labSampleProcess:supplement',
|
||||
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:labSampleProcess: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:labSampleProcess:supplement'
|
||||
AND existing.del_flag = 0
|
||||
);
|
||||
|
||||
-- 导出按钮
|
||||
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('lab-sample-process-exp:', m.tenant_no, ':', m.id)),
|
||||
13, 1, '3'), 17, 1, '8'),
|
||||
'导出', m.id, 'F', '', NULL,
|
||||
'biz:labSampleProcess:export',
|
||||
1, '1', '1', m.tenant_no, 20,
|
||||
'实验室样本处理数据-导出',
|
||||
'migration', '', NOW(), 'migration', NOW(), 0
|
||||
FROM sys_menu AS m
|
||||
WHERE m.del_flag = 0 AND m.status = '1'
|
||||
AND m.perms = 'biz:labSampleProcess: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:labSampleProcess: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('lab-sample-process-rm:', r.tenant_no, ':', r.id, ':', m.id)),
|
||||
13, 1, '3'), 17, 1, '8'),
|
||||
r.id,
|
||||
m.id,
|
||||
r.tenant_no,
|
||||
NULL,
|
||||
'migration: grant lab sample process from sample reception 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:sampleReception:list'
|
||||
JOIN sys_menu AS m
|
||||
ON m.tenant_no = r.tenant_no
|
||||
AND m.perms IN (
|
||||
'biz:labSampleProcess:list',
|
||||
'biz:labSampleProcess:supplement',
|
||||
'biz:labSampleProcess: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
|
||||
FROM sys_menu
|
||||
WHERE perms LIKE 'biz:labSampleProcess:%' AND del_flag = 0
|
||||
ORDER BY tenant_no, order_num, perms;
|
||||
@@ -0,0 +1,175 @@
|
||||
-- Issue #102:实验室样本处理数据挂到市场/生产/质检,权限码分端
|
||||
-- 1) 质检管理:调到「入库放行审核」下方
|
||||
-- 2) 存储服务:挂到「缴费财务确认」下方(cellStorage:labSampleProcess:*)
|
||||
-- 3) 生产管理:挂到「废弃物管理」下方(production:labSampleProcess:*;若废弃物菜单缺失则先补齐)
|
||||
-- 4) 拥有 menu:market / menu:production / menu:quality 的角色,授予对应大菜单下入口
|
||||
-- MySQL 5.7,可重复执行
|
||||
|
||||
-- ── 0) 生产管理补齐「废弃物管理」(仅当缺失时,便于排序锚定)────────────────
|
||||
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('prod-waste-output:', p.tenant_no, ':', p.id)), 13, 1, '3'), 17, 1, '8'),
|
||||
'废弃物管理', p.id, 'C', 'waste-output',
|
||||
'/production/waste-output/index', 'production:waste-output:list',
|
||||
1, '1', '1', p.tenant_no,
|
||||
COALESCE((SELECT MAX(c.order_num) FROM sys_menu c WHERE c.parent_id = p.id AND c.del_flag = 0), 0) + 1,
|
||||
'issue#102 补齐生产废弃物管理以便台账排序',
|
||||
'migration', '', NOW(), 'migration', NOW(), 0
|
||||
FROM sys_menu p
|
||||
WHERE p.del_flag = 0 AND p.status = '1' AND p.menu_name = '生产管理'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM sys_menu e
|
||||
WHERE e.tenant_no = p.tenant_no AND e.parent_id = p.id
|
||||
AND e.perms = 'production:waste-output:list' AND e.del_flag = 0
|
||||
);
|
||||
|
||||
-- ── 1) 质检:调到入库放行审核下方(可重复;不连带改动其他菜单 order)────────
|
||||
UPDATE sys_menu lab
|
||||
JOIN sys_menu release_m
|
||||
ON release_m.parent_id = lab.parent_id
|
||||
AND release_m.del_flag = 0
|
||||
AND release_m.menu_name = '入库放行审核'
|
||||
AND release_m.perms = 'quality:storageReleaseReview:list'
|
||||
SET lab.order_num = release_m.order_num + 1,
|
||||
lab.update_by = 'migration',
|
||||
lab.update_time = NOW()
|
||||
WHERE lab.del_flag = 0
|
||||
AND lab.perms = 'biz:labSampleProcess:list'
|
||||
AND lab.path = 'lab-sample-process'
|
||||
AND (lab.order_num IS NULL OR lab.order_num <> release_m.order_num + 1);
|
||||
|
||||
-- ── 2) 存储服务:缴费财务确认下方 ───────────────────────────────────────────
|
||||
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('cell-lab-sample-process:', anchor.tenant_no, ':', anchor.id)), 13, 1, '3'), 17, 1, '8'),
|
||||
'实验室样本处理数据', anchor.parent_id, 'C', 'lab-sample-process',
|
||||
'quality-inspection/lab-sample-process/index', 'cellStorage:labSampleProcess:list',
|
||||
1, '1', '1', anchor.tenant_no, anchor.order_num + 1,
|
||||
'市场-存储服务-实验室样本处理数据',
|
||||
'migration', '', NOW(), 'migration', NOW(), 0
|
||||
FROM sys_menu anchor
|
||||
WHERE anchor.del_flag = 0 AND anchor.status = '1'
|
||||
AND anchor.perms = 'biz:cellStoragePaymentConfirm:list'
|
||||
AND anchor.menu_name = '缴费财务确认'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM sys_menu e
|
||||
WHERE e.tenant_no = anchor.tenant_no
|
||||
AND e.parent_id = anchor.parent_id
|
||||
AND e.perms = 'cellStorage:labSampleProcess:list'
|
||||
AND e.del_flag = 0
|
||||
);
|
||||
|
||||
-- ── 3) 生产管理:废弃物管理下方 ─────────────────────────────────────────────
|
||||
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('prod-lab-sample-process:', anchor.tenant_no, ':', anchor.id)), 13, 1, '3'), 17, 1, '8'),
|
||||
'实验室样本处理数据', anchor.parent_id, 'C', 'lab-sample-process',
|
||||
'quality-inspection/lab-sample-process/index', 'production:labSampleProcess:list',
|
||||
1, '1', '1', anchor.tenant_no, anchor.order_num + 1,
|
||||
'生产-生产管理-实验室样本处理数据',
|
||||
'migration', '', NOW(), 'migration', NOW(), 0
|
||||
FROM sys_menu anchor
|
||||
WHERE anchor.del_flag = 0 AND anchor.status = '1'
|
||||
AND anchor.perms = 'production:waste-output:list'
|
||||
AND anchor.menu_name = '废弃物管理'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM sys_menu e
|
||||
WHERE e.tenant_no = anchor.tenant_no
|
||||
AND e.parent_id = anchor.parent_id
|
||||
AND e.perms = 'production:labSampleProcess:list'
|
||||
AND e.del_flag = 0
|
||||
);
|
||||
|
||||
-- ── 4) 补录 / 导出按钮(三处列表菜单各挂一套)──────────────────────────────
|
||||
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('lab-sp-btn:', m.tenant_no, ':', m.id, ':', btn.perms)), 13, 1, '3'), 17, 1, '8'),
|
||||
btn.menu_name, m.id, 'F', '', NULL, btn.perms,
|
||||
1, '1', '1', m.tenant_no, btn.order_num, btn.remark,
|
||||
'migration', '', NOW(), 'migration', NOW(), 0
|
||||
FROM sys_menu m
|
||||
JOIN (
|
||||
SELECT '补录' AS menu_name, 'cellStorage:labSampleProcess:supplement' AS perms, 10 AS order_num,
|
||||
'存储服务-实验室样本处理数据-补录' AS remark, 'cellStorage:labSampleProcess:list' AS parent_perms
|
||||
UNION ALL
|
||||
SELECT '导出', 'cellStorage:labSampleProcess:export', 20,
|
||||
'存储服务-实验室样本处理数据-导出', 'cellStorage:labSampleProcess:list'
|
||||
UNION ALL
|
||||
SELECT '补录', 'production:labSampleProcess:supplement', 10,
|
||||
'生产-实验室样本处理数据-补录', 'production:labSampleProcess:list'
|
||||
UNION ALL
|
||||
SELECT '导出', 'production:labSampleProcess:export', 20,
|
||||
'生产-实验室样本处理数据-导出', 'production:labSampleProcess:list'
|
||||
) btn ON btn.parent_perms = m.perms
|
||||
WHERE m.del_flag = 0 AND m.status = '1'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM sys_menu e
|
||||
WHERE e.tenant_no = m.tenant_no AND e.parent_id = m.id
|
||||
AND e.perms = btn.perms AND e.del_flag = 0
|
||||
);
|
||||
|
||||
-- ── 5) 按顶级大菜单授权对应入口(含列表/补录/导出)─────────────────────────
|
||||
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('lab-sp-rm:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
|
||||
r.id, m.id, r.tenant_no, NULL,
|
||||
CONCAT('issue#102 grant from ', map.top_perms),
|
||||
'migration', '', NOW(), 'migration', NOW(), 0
|
||||
FROM (
|
||||
SELECT 'menu:market' AS top_perms, 'cellStorage:labSampleProcess:list' AS list_perms
|
||||
UNION ALL SELECT 'menu:market', 'cellStorage:labSampleProcess:supplement'
|
||||
UNION ALL SELECT 'menu:market', 'cellStorage:labSampleProcess:export'
|
||||
UNION ALL SELECT 'menu:production', 'production:labSampleProcess:list'
|
||||
UNION ALL SELECT 'menu:production', 'production:labSampleProcess:supplement'
|
||||
UNION ALL SELECT 'menu:production', 'production:labSampleProcess:export'
|
||||
UNION ALL SELECT 'menu:quality', 'biz:labSampleProcess:list'
|
||||
UNION ALL SELECT 'menu:quality', 'biz:labSampleProcess:supplement'
|
||||
UNION ALL SELECT 'menu:quality', 'biz:labSampleProcess:export'
|
||||
) map
|
||||
JOIN sys_role r ON r.del_flag = 0
|
||||
JOIN sys_role_menu src
|
||||
ON src.role_id = r.id AND src.tenant_no = r.tenant_no AND src.del_flag = 0
|
||||
JOIN sys_menu top
|
||||
ON top.id = src.menu_id AND top.tenant_no = src.tenant_no AND top.del_flag = 0
|
||||
AND top.perms = map.top_perms
|
||||
JOIN sys_menu m
|
||||
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
|
||||
AND m.perms = map.list_perms
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM sys_role_menu 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 p.menu_name AS parent_name, c.menu_name, c.path, c.perms, c.order_num
|
||||
FROM sys_menu c
|
||||
JOIN sys_menu p ON p.id = c.parent_id
|
||||
WHERE c.del_flag = 0
|
||||
AND (
|
||||
c.perms LIKE '%labSampleProcess%'
|
||||
OR (c.menu_name IN ('缴费财务确认', '废弃物管理', '入库放行审核')
|
||||
AND p.menu_name IN ('存储服务', '生产管理', '质检管理'))
|
||||
)
|
||||
ORDER BY p.menu_name, c.order_num, c.menu_name;
|
||||
@@ -0,0 +1,277 @@
|
||||
-- UC 入库编码自动派发:脐带MSC原代培养(内置模版)5 步
|
||||
-- 步骤:原代培养 → 半换液 → 二次贴壁 → 重铺 → 冻存(不含传代)
|
||||
-- 内容从既有「干细胞培养(内置模版)」/ MSC培养-BUILTIN 按 process_code 拷贝
|
||||
-- 幂等:已存在同名内置集合则跳过主数据创建-- 兼容:跨表比较统一 COLLATE utf8mb4_unicode_ci,避免 unicode_ci/general_ci 混用失败
|
||||
-- 生产历史空任务工单回补(二选一,勿重复对同一工单各跑一遍):
|
||||
-- SQL:docs/sql/migrations/2026-11-13-uc-msc-production-task-backfill.sql
|
||||
-- 或 Python:
|
||||
-- cd backend && python -m scripts.backfill_uc_msc_production_tasks
|
||||
-- cd backend && python -m scripts.backfill_uc_msc_production_tasks --apply
|
||||
|
||||
SET NAMES utf8mb4;
|
||||
|
||||
-- 1) 工艺路线头
|
||||
INSERT INTO biz_process_route (
|
||||
id, route_code, route_name, product_type_id, version, is_current,
|
||||
equipment_ids, equipment_name, tenant_no, order_num, remark, is_builtin,
|
||||
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
'UCMSCROUTEA5CC11F194118AC54085447A',
|
||||
'MSC原代-UC-BUILTIN',
|
||||
'脐带MSC原代培养(内置模版)',
|
||||
src.product_type_id,
|
||||
src.version,
|
||||
'0',
|
||||
src.equipment_ids,
|
||||
src.equipment_name,
|
||||
src.tenant_no,
|
||||
0,
|
||||
'内置模版:UC 入库编码自动派发(5 步,不含传代)',
|
||||
'1',
|
||||
src.create_by,
|
||||
IFNULL(src.create_dept_id, ''),
|
||||
NOW(),
|
||||
src.update_by,
|
||||
NOW(),
|
||||
0
|
||||
FROM biz_process_route src
|
||||
WHERE src.del_flag = 0
|
||||
AND (
|
||||
src.route_code = 'MSC培养-BUILTIN'
|
||||
OR (src.route_name = '干细胞培养(内置模版)' AND src.is_builtin = '1')
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM biz_process_route x
|
||||
WHERE x.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND x.del_flag = 0
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM biz_process_route x
|
||||
WHERE x.tenant_no COLLATE utf8mb4_unicode_ci = src.tenant_no COLLATE utf8mb4_unicode_ci
|
||||
AND x.route_code = 'MSC原代-UC-BUILTIN'
|
||||
AND x.del_flag = 0
|
||||
)
|
||||
ORDER BY CASE WHEN src.route_code = 'MSC培养-BUILTIN' THEN 0 ELSE 1 END
|
||||
LIMIT 1;
|
||||
|
||||
-- 2) 路线步骤(按目标顺序)
|
||||
-- step 1 SOP-SC-003
|
||||
INSERT INTO biz_process_route_step (
|
||||
id, route_id, process_id, step_order, process_code, category_id, process_name,
|
||||
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
|
||||
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
'UCMSCSTEP1A5CC11F194118AC54085447A',
|
||||
'UCMSCROUTEA5CC11F194118AC54085447A',
|
||||
s.process_id, 1, s.process_code, s.category_id, s.process_name,
|
||||
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
|
||||
s.tenant_no, 1, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
|
||||
FROM biz_process_route_step s
|
||||
JOIN biz_process_route r
|
||||
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
|
||||
AND r.del_flag = 0
|
||||
WHERE s.del_flag = 0
|
||||
AND s.process_code = 'SOP-SC-003-E01-01'
|
||||
AND (
|
||||
r.route_code = 'MSC培养-BUILTIN'
|
||||
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
|
||||
)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM biz_process_route nr
|
||||
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM biz_process_route_step x
|
||||
WHERE x.id = 'UCMSCSTEP1A5CC11F194118AC54085447A' AND x.del_flag = 0
|
||||
)
|
||||
LIMIT 1;
|
||||
|
||||
-- step 2 SOP-SC-004
|
||||
INSERT INTO biz_process_route_step (
|
||||
id, route_id, process_id, step_order, process_code, category_id, process_name,
|
||||
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
|
||||
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
'UCMSCSTEP2A5CC11F194118AC54085447A',
|
||||
'UCMSCROUTEA5CC11F194118AC54085447A',
|
||||
s.process_id, 2, s.process_code, s.category_id, s.process_name,
|
||||
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
|
||||
s.tenant_no, 2, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
|
||||
FROM biz_process_route_step s
|
||||
JOIN biz_process_route r
|
||||
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
|
||||
AND r.del_flag = 0
|
||||
WHERE s.del_flag = 0
|
||||
AND s.process_code = 'SOP-SC-004-E01-01'
|
||||
AND (
|
||||
r.route_code = 'MSC培养-BUILTIN'
|
||||
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
|
||||
)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM biz_process_route nr
|
||||
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM biz_process_route_step x
|
||||
WHERE x.id = 'UCMSCSTEP2A5CC11F194118AC54085447A' AND x.del_flag = 0
|
||||
)
|
||||
LIMIT 1;
|
||||
|
||||
-- step 3 SOP-SC-006 二次贴壁
|
||||
INSERT INTO biz_process_route_step (
|
||||
id, route_id, process_id, step_order, process_code, category_id, process_name,
|
||||
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
|
||||
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
'UCMSCSTEP3A5CC11F194118AC54085447A',
|
||||
'UCMSCROUTEA5CC11F194118AC54085447A',
|
||||
s.process_id, 3, s.process_code, s.category_id, s.process_name,
|
||||
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
|
||||
s.tenant_no, 3, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
|
||||
FROM biz_process_route_step s
|
||||
JOIN biz_process_route r
|
||||
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
|
||||
AND r.del_flag = 0
|
||||
WHERE s.del_flag = 0
|
||||
AND s.process_code = 'SOP-SC-006-E01-01'
|
||||
AND (
|
||||
r.route_code = 'MSC培养-BUILTIN'
|
||||
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
|
||||
)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM biz_process_route nr
|
||||
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM biz_process_route_step x
|
||||
WHERE x.id = 'UCMSCSTEP3A5CC11F194118AC54085447A' AND x.del_flag = 0
|
||||
)
|
||||
LIMIT 1;
|
||||
|
||||
-- step 4 SOP-SC-005 重铺
|
||||
INSERT INTO biz_process_route_step (
|
||||
id, route_id, process_id, step_order, process_code, category_id, process_name,
|
||||
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
|
||||
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
'UCMSCSTEP4A5CC11F194118AC54085447A',
|
||||
'UCMSCROUTEA5CC11F194118AC54085447A',
|
||||
s.process_id, 4, s.process_code, s.category_id, s.process_name,
|
||||
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
|
||||
s.tenant_no, 4, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
|
||||
FROM biz_process_route_step s
|
||||
JOIN biz_process_route r
|
||||
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
|
||||
AND r.del_flag = 0
|
||||
WHERE s.del_flag = 0
|
||||
AND s.process_code = 'SOP-SC-005-E01-01'
|
||||
AND (
|
||||
r.route_code = 'MSC培养-BUILTIN'
|
||||
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
|
||||
)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM biz_process_route nr
|
||||
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM biz_process_route_step x
|
||||
WHERE x.id = 'UCMSCSTEP4A5CC11F194118AC54085447A' AND x.del_flag = 0
|
||||
)
|
||||
LIMIT 1;
|
||||
|
||||
-- step 5 SOP-SC-008 冻存
|
||||
INSERT INTO biz_process_route_step (
|
||||
id, route_id, process_id, step_order, process_code, category_id, process_name,
|
||||
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
|
||||
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
'UCMSCSTEP5A5CC11F194118AC54085447A',
|
||||
'UCMSCROUTEA5CC11F194118AC54085447A',
|
||||
s.process_id, 5, s.process_code, s.category_id, s.process_name,
|
||||
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
|
||||
s.tenant_no, 5, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
|
||||
FROM biz_process_route_step s
|
||||
JOIN biz_process_route r
|
||||
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
|
||||
AND r.del_flag = 0
|
||||
WHERE s.del_flag = 0
|
||||
AND s.process_code = 'SOP-SC-008-E01-01'
|
||||
AND (
|
||||
r.route_code = 'MSC培养-BUILTIN'
|
||||
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
|
||||
)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM biz_process_route nr
|
||||
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM biz_process_route_step x
|
||||
WHERE x.id = 'UCMSCSTEP5A5CC11F194118AC54085447A' AND x.del_flag = 0
|
||||
)
|
||||
LIMIT 1;
|
||||
|
||||
-- 3) 任务组合头
|
||||
INSERT INTO biz_production_task_set (
|
||||
id, set_name, status, tenant_no, order_num, remark, is_builtin,
|
||||
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
'UCMSCSET00A5CC11F194118AC54085447A',
|
||||
'脐带MSC原代培养(内置模版)',
|
||||
'1',
|
||||
r.tenant_no,
|
||||
0,
|
||||
'内置模版:UC 入库编码自动派发',
|
||||
'1',
|
||||
r.create_by,
|
||||
IFNULL(r.create_dept_id, ''),
|
||||
NOW(),
|
||||
r.update_by,
|
||||
NOW(),
|
||||
0
|
||||
FROM biz_process_route r
|
||||
WHERE r.id = 'UCMSCROUTEA5CC11F194118AC54085447A'
|
||||
AND r.del_flag = 0
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM biz_production_task_set x
|
||||
WHERE x.tenant_no COLLATE utf8mb4_unicode_ci = r.tenant_no COLLATE utf8mb4_unicode_ci
|
||||
AND x.set_name = '脐带MSC原代培养(内置模版)'
|
||||
AND x.is_builtin = '1'
|
||||
AND x.del_flag = 0
|
||||
);
|
||||
|
||||
-- 4) 任务组合条目
|
||||
INSERT INTO biz_production_task_set_item (
|
||||
id, set_id, task_name, route_id, route_name, description, remark,
|
||||
tenant_no, order_num, create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
'UCMSCITEM0A5CC11F194118AC54085447A',
|
||||
s.id,
|
||||
'{lab_storage_code}样本处理',
|
||||
'UCMSCROUTEA5CC11F194118AC54085447A',
|
||||
'脐带MSC原代培养(内置模版)',
|
||||
'脐带MSC原代培养(内置模版)',
|
||||
NULL,
|
||||
s.tenant_no,
|
||||
1,
|
||||
s.create_by,
|
||||
IFNULL(s.create_dept_id, ''),
|
||||
NOW(),
|
||||
s.update_by,
|
||||
NOW(),
|
||||
0
|
||||
FROM biz_production_task_set s
|
||||
WHERE s.set_name = '脐带MSC原代培养(内置模版)'
|
||||
AND s.is_builtin = '1'
|
||||
AND s.del_flag = 0
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM biz_production_task_set_item x
|
||||
WHERE x.set_id COLLATE utf8mb4_unicode_ci = s.id COLLATE utf8mb4_unicode_ci
|
||||
AND x.del_flag = 0
|
||||
);
|
||||
@@ -0,0 +1,424 @@
|
||||
-- 【一次性回补】UC 开头实验室入库编码 → 补派「脐带MSC原代培养」5 步生产任务
|
||||
-- 与种子脚本分开:先执行 2026-11-13-uc-msc-builtin-task-set.sql(或确保模版已存在),再执行本文件。
|
||||
-- 等价于 backend/scripts/backfill_uc_msc_production_tasks.py --apply 的候选范围。
|
||||
--
|
||||
-- 候选条件(须全部满足):
|
||||
-- 1) 样本接收 accept_conclusion=js、del_flag=0
|
||||
-- 2) lab_storage_code 以 UC/uc 开头(非空)
|
||||
-- 3) 关联入库生产工单 work_order_type=inbound、状态 dpz/jxz、del_flag=0
|
||||
-- 4) 该工单当前无任何有效生产任务(已有任务如 UC2026010 跳过)
|
||||
--
|
||||
-- 动作:
|
||||
-- - 每工单插入 1 条 biz_production_task(状态 dpz,任务名 {入库编码}样本处理)
|
||||
-- - 从 UC 内置路线复制 5 个步骤到 biz_production_task_step(及试剂/耗材/产出/采集子表)
|
||||
-- - 工单状态 dpz → jxz(已是 jxz/ywc 的不改 ywc;本脚本候选不含 ywc)
|
||||
--
|
||||
-- 幂等:已有有效任务的工单不会进入候选;重复执行影响行数应为 0。
|
||||
-- 前置:biz_process_route.route_code='MSC原代-UC-BUILTIN'(或固定 id UCMSCROUTE…)及 5 步须已存在。
|
||||
-- MySQL 5.7 / utf8mb4。未在生产库执行;执行前请先跑下方「预览」SELECT。
|
||||
-- 兼容:
|
||||
-- 1) 跨表等值统一 COLLATE utf8mb4_general_ci,避免 unicode_ci/general_ci 混用失败
|
||||
-- 2) 多行 ID 用 MD5(业务键) 生成,避免同语句多行 UUID() 撞主键
|
||||
-- 3) task_no 序号用 UNSIGNED 整数拼接,避免用户变量浮点变成 RW…2.00
|
||||
|
||||
SET NAMES utf8mb4;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 0. 解析 UC 内置工艺路线
|
||||
-- ---------------------------------------------------------------------------
|
||||
SET @uc_route_id := (
|
||||
SELECT r.id
|
||||
FROM biz_process_route r
|
||||
WHERE r.del_flag = 0
|
||||
AND (
|
||||
r.id = 'UCMSCROUTEA5CC11F194118AC54085447A'
|
||||
OR r.route_code = 'MSC原代-UC-BUILTIN'
|
||||
OR (r.route_name = '脐带MSC原代培养(内置模版)' AND r.is_builtin = '1')
|
||||
)
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN r.id = 'UCMSCROUTEA5CC11F194118AC54085447A' THEN 0
|
||||
WHEN r.route_code = 'MSC原代-UC-BUILTIN' THEN 1
|
||||
ELSE 2
|
||||
END
|
||||
LIMIT 1
|
||||
);
|
||||
|
||||
SET @uc_step_count := (
|
||||
SELECT COUNT(*)
|
||||
FROM biz_process_route_step s
|
||||
WHERE s.route_id COLLATE utf8mb4_unicode_ci = @uc_route_id COLLATE utf8mb4_unicode_ci
|
||||
AND s.del_flag = 0
|
||||
);
|
||||
|
||||
-- 预览:模版是否就绪(应 route 非空且 step_count=5)
|
||||
SELECT @uc_route_id AS uc_route_id, @uc_step_count AS uc_step_count;
|
||||
|
||||
-- 若模版未就绪则主动失败(避免插入无步骤任务)
|
||||
SET @uc_ready := IF(@uc_route_id IS NOT NULL AND @uc_step_count = 5, 1, 0);
|
||||
-- 下面用 @uc_ready 约束所有写操作;为 0 时 INSERT 选不出行
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 1. 候选工单临时表
|
||||
-- ---------------------------------------------------------------------------
|
||||
DROP TEMPORARY TABLE IF EXISTS tmp_uc_wo_backfill;
|
||||
CREATE TEMPORARY TABLE tmp_uc_wo_backfill (
|
||||
seq INT NOT NULL AUTO_INCREMENT,
|
||||
work_order_id VARCHAR(64) NOT NULL,
|
||||
reception_id VARCHAR(64) NOT NULL,
|
||||
lab_storage_code VARCHAR(32) NOT NULL,
|
||||
tenant_no VARCHAR(64) NOT NULL,
|
||||
sample_code VARCHAR(32) NULL,
|
||||
task_id VARCHAR(64) NULL,
|
||||
task_no VARCHAR(32) NULL,
|
||||
route_id VARCHAR(64) NULL,
|
||||
PRIMARY KEY (seq),
|
||||
UNIQUE KEY uk_wo (work_order_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
INSERT INTO tmp_uc_wo_backfill (
|
||||
work_order_id, reception_id, lab_storage_code, tenant_no, sample_code, route_id
|
||||
)
|
||||
SELECT
|
||||
wo.id,
|
||||
rec.id,
|
||||
TRIM(rec.lab_storage_code),
|
||||
wo.tenant_no,
|
||||
wo.sample_code,
|
||||
@uc_route_id
|
||||
FROM biz_production_work_order wo
|
||||
INNER JOIN biz_sample_reception rec
|
||||
ON rec.id COLLATE utf8mb4_general_ci = wo.reception_id COLLATE utf8mb4_general_ci
|
||||
AND rec.tenant_no COLLATE utf8mb4_general_ci = wo.tenant_no COLLATE utf8mb4_general_ci
|
||||
AND rec.del_flag = 0
|
||||
WHERE @uc_ready = 1
|
||||
AND wo.del_flag = 0
|
||||
AND wo.work_order_type = 'inbound'
|
||||
AND wo.work_order_status IN ('dpz', 'jxz')
|
||||
AND rec.accept_conclusion = 'js'
|
||||
AND rec.lab_storage_code IS NOT NULL
|
||||
AND TRIM(rec.lab_storage_code) <> ''
|
||||
AND (
|
||||
rec.lab_storage_code LIKE 'UC%'
|
||||
OR rec.lab_storage_code LIKE 'uc%'
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM biz_production_task t
|
||||
WHERE t.work_order_id COLLATE utf8mb4_general_ci = wo.id COLLATE utf8mb4_general_ci
|
||||
AND t.tenant_no COLLATE utf8mb4_general_ci = wo.tenant_no COLLATE utf8mb4_general_ci
|
||||
AND t.del_flag = 0
|
||||
)
|
||||
ORDER BY rec.reception_time ASC, wo.create_time ASC;
|
||||
|
||||
-- 预览候选(执行写库前请核对)
|
||||
SELECT
|
||||
seq,
|
||||
work_order_id,
|
||||
lab_storage_code,
|
||||
sample_code,
|
||||
tenant_no,
|
||||
reception_id
|
||||
FROM tmp_uc_wo_backfill
|
||||
ORDER BY seq;
|
||||
|
||||
SELECT COUNT(*) AS candidate_count FROM tmp_uc_wo_backfill;
|
||||
|
||||
-- 分配 task_id / task_no(RW + yyyymmdd + 4 位序号,接当日已有最大序号)
|
||||
SET @task_day := DATE_FORMAT(NOW(), '%Y%m%d');
|
||||
SET @task_no_base := (
|
||||
SELECT IFNULL(MAX(CAST(SUBSTRING(t.task_no, 11) AS UNSIGNED)), 0)
|
||||
FROM biz_production_task t
|
||||
WHERE t.task_no REGEXP CONCAT('^RW', @task_day, '[0-9]{4}$')
|
||||
);
|
||||
SET @task_no_base := CAST(IFNULL(@task_no_base, 0) AS UNSIGNED);
|
||||
|
||||
UPDATE tmp_uc_wo_backfill
|
||||
SET
|
||||
task_id = UPPER(MD5(CONCAT('uc-msc-backfill-task:', work_order_id))),
|
||||
task_no = CONCAT('RW', @task_day, LPAD(@task_no_base + seq, 4, '0'));
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 2. 插入生产任务
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO biz_production_task (
|
||||
id, task_no, work_order_id, order_source, task_type, task_name, description,
|
||||
route_id, task_status, current_assignee_user_id, started_time, completed_time,
|
||||
conclusion, remark, attachments, equipment_ids, equipment_name,
|
||||
tenant_no, order_num, create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
c.task_id,
|
||||
c.task_no,
|
||||
c.work_order_id,
|
||||
'inbound',
|
||||
'cell_storage',
|
||||
CONCAT(c.lab_storage_code, '样本处理'),
|
||||
'脐带MSC原代培养(内置模版)',
|
||||
c.route_id,
|
||||
'dpz',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'一次性SQL回补:UC入库编码自动派发',
|
||||
NULL,
|
||||
r.equipment_ids,
|
||||
r.equipment_name,
|
||||
c.tenant_no,
|
||||
0,
|
||||
NULL,
|
||||
'',
|
||||
NOW(),
|
||||
NULL,
|
||||
NOW(),
|
||||
0
|
||||
FROM tmp_uc_wo_backfill c
|
||||
INNER JOIN biz_process_route r
|
||||
ON r.id COLLATE utf8mb4_unicode_ci = c.route_id COLLATE utf8mb4_unicode_ci
|
||||
AND r.del_flag = 0
|
||||
WHERE @uc_ready = 1
|
||||
AND c.task_id IS NOT NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM biz_production_task t
|
||||
WHERE t.work_order_id COLLATE utf8mb4_general_ci = c.work_order_id COLLATE utf8mb4_general_ci
|
||||
AND t.tenant_no COLLATE utf8mb4_general_ci = c.tenant_no COLLATE utf8mb4_general_ci
|
||||
AND t.del_flag = 0
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 3. 步骤映射:路线步骤 → 新任务步骤 ID
|
||||
-- ---------------------------------------------------------------------------
|
||||
DROP TEMPORARY TABLE IF EXISTS tmp_uc_step_map;
|
||||
CREATE TEMPORARY TABLE tmp_uc_step_map (
|
||||
task_id VARCHAR(64) NOT NULL,
|
||||
work_order_id VARCHAR(64) NOT NULL,
|
||||
tenant_no VARCHAR(64) NOT NULL,
|
||||
route_step_id VARCHAR(64) NOT NULL,
|
||||
task_step_id VARCHAR(64) NOT NULL,
|
||||
step_order INT NOT NULL,
|
||||
PRIMARY KEY (task_id, route_step_id),
|
||||
KEY ix_route_step (route_step_id),
|
||||
KEY ix_task_step (task_step_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
INSERT INTO tmp_uc_step_map (
|
||||
task_id, work_order_id, tenant_no, route_step_id, task_step_id, step_order
|
||||
)
|
||||
SELECT
|
||||
c.task_id,
|
||||
c.work_order_id,
|
||||
c.tenant_no,
|
||||
rs.id,
|
||||
UPPER(MD5(CONCAT('uc-msc-backfill-step:', c.work_order_id, ':', rs.id))),
|
||||
rs.step_order
|
||||
FROM tmp_uc_wo_backfill c
|
||||
INNER JOIN biz_process_route_step rs
|
||||
ON rs.route_id COLLATE utf8mb4_unicode_ci = c.route_id COLLATE utf8mb4_unicode_ci
|
||||
AND rs.del_flag = 0
|
||||
WHERE @uc_ready = 1
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM biz_production_task t
|
||||
WHERE t.id COLLATE utf8mb4_general_ci = c.task_id COLLATE utf8mb4_general_ci
|
||||
AND t.del_flag = 0
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 4. 插入任务步骤
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO biz_production_task_step (
|
||||
id, task_id, step_order, process_code, category_id, process_name, description,
|
||||
equipment_ids, equipment_name, estimated_duration, actual_duration,
|
||||
sop_ids, sop_content, step_status, planned_start_time, started_time,
|
||||
completed_time, completed_by, tenant_no, order_num, remark,
|
||||
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
m.task_step_id,
|
||||
m.task_id,
|
||||
rs.step_order,
|
||||
rs.process_code,
|
||||
rs.category_id,
|
||||
rs.process_name,
|
||||
rs.description,
|
||||
rs.equipment_ids,
|
||||
rs.equipment_name,
|
||||
rs.estimated_duration,
|
||||
NULL,
|
||||
rs.sop_ids,
|
||||
rs.sop_content,
|
||||
'dzx',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
m.tenant_no,
|
||||
IFNULL(rs.order_num, rs.step_order),
|
||||
NULL,
|
||||
NULL,
|
||||
'',
|
||||
NOW(),
|
||||
NULL,
|
||||
NOW(),
|
||||
0
|
||||
FROM tmp_uc_step_map m
|
||||
INNER JOIN biz_process_route_step rs
|
||||
ON rs.id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
|
||||
AND rs.del_flag = 0
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM biz_production_task_step x
|
||||
WHERE x.id COLLATE utf8mb4_general_ci = m.task_step_id COLLATE utf8mb4_general_ci
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 5. 复制路线步骤子表 → 任务步骤子表
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO biz_production_task_step_reagent (
|
||||
id, step_id, reagent_code, reagent_name, spec, standard_usage, unit,
|
||||
is_key_material, tenant_no, order_num, remark,
|
||||
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
UPPER(MD5(CONCAT('uc-msc-backfill-reag:', m.task_step_id, ':', src.id))),
|
||||
m.task_step_id,
|
||||
src.reagent_code,
|
||||
src.reagent_name,
|
||||
src.spec,
|
||||
src.standard_usage,
|
||||
src.unit,
|
||||
src.is_key_material,
|
||||
m.tenant_no,
|
||||
src.order_num,
|
||||
src.remark,
|
||||
NULL,
|
||||
'',
|
||||
NOW(),
|
||||
NULL,
|
||||
NOW(),
|
||||
0
|
||||
FROM tmp_uc_step_map m
|
||||
INNER JOIN biz_process_route_step_reagent src
|
||||
ON src.step_id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
|
||||
AND src.del_flag = 0;
|
||||
|
||||
INSERT INTO biz_production_task_step_consumable (
|
||||
id, step_id, consumable_code, consumable_name, spec_model, standard_usage,
|
||||
unit, is_required, remark, tenant_no, order_num,
|
||||
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
UPPER(MD5(CONCAT('uc-msc-backfill-cons:', m.task_step_id, ':', src.id))),
|
||||
m.task_step_id,
|
||||
src.consumable_code,
|
||||
src.consumable_name,
|
||||
src.spec_model,
|
||||
src.standard_usage,
|
||||
src.unit,
|
||||
src.is_required,
|
||||
src.remark,
|
||||
m.tenant_no,
|
||||
src.order_num,
|
||||
NULL,
|
||||
'',
|
||||
NOW(),
|
||||
NULL,
|
||||
NOW(),
|
||||
0
|
||||
FROM tmp_uc_step_map m
|
||||
INNER JOIN biz_process_route_step_consumable src
|
||||
ON src.step_id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
|
||||
AND src.del_flag = 0;
|
||||
|
||||
INSERT INTO biz_production_task_step_output (
|
||||
id, step_id, output_type_id, output_name, output_barcode,
|
||||
tenant_no, order_num, remark,
|
||||
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
UPPER(MD5(CONCAT('uc-msc-backfill-out:', m.task_step_id, ':', src.id))),
|
||||
m.task_step_id,
|
||||
src.output_type_id,
|
||||
src.output_name,
|
||||
src.output_barcode,
|
||||
m.tenant_no,
|
||||
src.order_num,
|
||||
src.remark,
|
||||
NULL,
|
||||
'',
|
||||
NOW(),
|
||||
NULL,
|
||||
NOW(),
|
||||
0
|
||||
FROM tmp_uc_step_map m
|
||||
INNER JOIN biz_process_route_step_output src
|
||||
ON src.step_id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
|
||||
AND src.del_flag = 0;
|
||||
|
||||
INSERT INTO biz_production_task_step_data_collection (
|
||||
id, step_id, collection_name, unit, tenant_no, order_num, remark,
|
||||
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||
)
|
||||
SELECT
|
||||
UPPER(MD5(CONCAT('uc-msc-backfill-dc:', m.task_step_id, ':', src.id))),
|
||||
m.task_step_id,
|
||||
src.collection_name,
|
||||
src.unit,
|
||||
m.tenant_no,
|
||||
src.order_num,
|
||||
src.remark,
|
||||
NULL,
|
||||
'',
|
||||
NOW(),
|
||||
NULL,
|
||||
NOW(),
|
||||
0
|
||||
FROM tmp_uc_step_map m
|
||||
INNER JOIN biz_process_route_step_data_collection src
|
||||
ON src.step_id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
|
||||
AND src.del_flag = 0;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 6. 回写工单状态:有任务则 jxz(不改 ywc)
|
||||
-- ---------------------------------------------------------------------------
|
||||
UPDATE biz_production_work_order wo
|
||||
INNER JOIN tmp_uc_wo_backfill c
|
||||
ON c.work_order_id COLLATE utf8mb4_general_ci = wo.id COLLATE utf8mb4_general_ci
|
||||
SET
|
||||
wo.work_order_status = 'jxz',
|
||||
wo.update_time = NOW()
|
||||
WHERE wo.del_flag = 0
|
||||
AND wo.work_order_status = 'dpz'
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM biz_production_task t
|
||||
WHERE t.work_order_id COLLATE utf8mb4_general_ci = wo.id COLLATE utf8mb4_general_ci
|
||||
AND t.tenant_no COLLATE utf8mb4_general_ci = wo.tenant_no COLLATE utf8mb4_general_ci
|
||||
AND t.del_flag = 0
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 7. 结果核对
|
||||
-- ---------------------------------------------------------------------------
|
||||
SELECT
|
||||
c.lab_storage_code,
|
||||
c.work_order_id,
|
||||
wo.work_order_no,
|
||||
wo.work_order_status,
|
||||
t.id AS task_id,
|
||||
t.task_no,
|
||||
t.task_name,
|
||||
(
|
||||
SELECT COUNT(*)
|
||||
FROM biz_production_task_step s
|
||||
WHERE s.task_id COLLATE utf8mb4_general_ci = t.id COLLATE utf8mb4_general_ci
|
||||
AND s.del_flag = 0
|
||||
) AS step_count
|
||||
FROM tmp_uc_wo_backfill c
|
||||
LEFT JOIN biz_production_work_order wo
|
||||
ON wo.id COLLATE utf8mb4_general_ci = c.work_order_id COLLATE utf8mb4_general_ci
|
||||
LEFT JOIN biz_production_task t
|
||||
ON t.id COLLATE utf8mb4_general_ci = c.task_id COLLATE utf8mb4_general_ci
|
||||
AND t.del_flag = 0
|
||||
ORDER BY c.seq;
|
||||
|
||||
DROP TEMPORARY TABLE IF EXISTS tmp_uc_step_map;
|
||||
DROP TEMPORARY TABLE IF EXISTS tmp_uc_wo_backfill;
|
||||
@@ -0,0 +1,54 @@
|
||||
-- Issue #127:已作废 / 属地废弃协议下样本状态回刷为已作废
|
||||
-- 细胞存储 + 科研捐赠;可重复执行。
|
||||
-- 规则:协议 status 为 yzf/sdfq 且样本未删除时,sample_status 置 yzf,
|
||||
-- void_date 为空时按协议 void_time / update_time 补齐 YYYYMMDD。
|
||||
|
||||
-- 细胞存储协议样本
|
||||
UPDATE biz_protocol_sample s
|
||||
INNER JOIN biz_collection_protocol p
|
||||
ON p.id = s.collection_protocol_id
|
||||
AND p.tenant_no = s.tenant_no
|
||||
AND p.del_flag = 0
|
||||
SET
|
||||
s.sample_status = 'yzf',
|
||||
s.void_date = CASE
|
||||
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
|
||||
WHEN p.void_time IS NOT NULL THEN DATE_FORMAT(p.void_time, '%Y%m%d')
|
||||
WHEN p.update_time IS NOT NULL THEN DATE_FORMAT(p.update_time, '%Y%m%d')
|
||||
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
|
||||
END,
|
||||
s.update_time = NOW()
|
||||
WHERE s.del_flag = 0
|
||||
AND p.protocol_status IN ('yzf', 'sdfq')
|
||||
AND (
|
||||
s.sample_status IS NULL
|
||||
OR TRIM(s.sample_status) = ''
|
||||
OR s.sample_status <> 'yzf'
|
||||
OR s.void_date IS NULL
|
||||
OR TRIM(s.void_date) = ''
|
||||
);
|
||||
|
||||
-- 科研捐赠样本
|
||||
UPDATE biz_research_donation_sample s
|
||||
INNER JOIN biz_research_donation d
|
||||
ON d.id = s.research_donation_id
|
||||
AND d.tenant_no = s.tenant_no
|
||||
AND d.del_flag = 0
|
||||
SET
|
||||
s.sample_status = 'yzf',
|
||||
s.void_date = CASE
|
||||
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
|
||||
WHEN d.void_time IS NOT NULL THEN DATE_FORMAT(d.void_time, '%Y%m%d')
|
||||
WHEN d.update_time IS NOT NULL THEN DATE_FORMAT(d.update_time, '%Y%m%d')
|
||||
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
|
||||
END,
|
||||
s.update_time = NOW()
|
||||
WHERE s.del_flag = 0
|
||||
AND d.donation_status IN ('yzf', 'sdfq')
|
||||
AND (
|
||||
s.sample_status IS NULL
|
||||
OR TRIM(s.sample_status) = ''
|
||||
OR s.sample_status <> 'yzf'
|
||||
OR s.void_date IS NULL
|
||||
OR TRIM(s.void_date) = ''
|
||||
);
|
||||
@@ -0,0 +1,67 @@
|
||||
-- Issue #129:样本接收结论已为废弃(bj)、但样本状态尚未作废的历史回刷
|
||||
-- 细胞存储 / 科研捐赠;可重复执行。
|
||||
-- 仅处理协议仍有效(非 yzf/sdfq)的样本行;已作废协议样本由 #127 回刷脚本覆盖。
|
||||
|
||||
-- 细胞存储
|
||||
UPDATE biz_protocol_sample s
|
||||
INNER JOIN biz_sample_reception r
|
||||
ON r.tenant_no = s.tenant_no
|
||||
AND r.del_flag = 0
|
||||
AND r.reception_source = 'cell_storage'
|
||||
AND r.accept_conclusion = 'bj'
|
||||
AND r.sample_code = s.sample_code
|
||||
AND r.collection_protocol_id = s.collection_protocol_id
|
||||
INNER JOIN biz_collection_protocol p
|
||||
ON p.id = s.collection_protocol_id
|
||||
AND p.tenant_no = s.tenant_no
|
||||
AND p.del_flag = 0
|
||||
SET
|
||||
s.sample_status = 'yzf',
|
||||
s.void_date = CASE
|
||||
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
|
||||
WHEN r.reception_time IS NOT NULL THEN DATE_FORMAT(r.reception_time, '%Y%m%d')
|
||||
WHEN s.update_time IS NOT NULL THEN DATE_FORMAT(s.update_time, '%Y%m%d')
|
||||
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
|
||||
END,
|
||||
s.update_time = NOW()
|
||||
WHERE s.del_flag = 0
|
||||
AND p.protocol_status NOT IN ('yzf', 'sdfq')
|
||||
AND (
|
||||
s.sample_status IS NULL
|
||||
OR TRIM(s.sample_status) = ''
|
||||
OR s.sample_status <> 'yzf'
|
||||
OR s.void_date IS NULL
|
||||
OR TRIM(s.void_date) = ''
|
||||
);
|
||||
|
||||
-- 科研捐赠
|
||||
UPDATE biz_research_donation_sample s
|
||||
INNER JOIN biz_sample_reception r
|
||||
ON r.tenant_no = s.tenant_no
|
||||
AND r.del_flag = 0
|
||||
AND r.reception_source = 'research_donation'
|
||||
AND r.accept_conclusion = 'bj'
|
||||
AND r.sample_code = s.sample_code
|
||||
AND r.research_donation_id = s.research_donation_id
|
||||
INNER JOIN biz_research_donation d
|
||||
ON d.id = s.research_donation_id
|
||||
AND d.tenant_no = s.tenant_no
|
||||
AND d.del_flag = 0
|
||||
SET
|
||||
s.sample_status = 'yzf',
|
||||
s.void_date = CASE
|
||||
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
|
||||
WHEN r.reception_time IS NOT NULL THEN DATE_FORMAT(r.reception_time, '%Y%m%d')
|
||||
WHEN s.update_time IS NOT NULL THEN DATE_FORMAT(s.update_time, '%Y%m%d')
|
||||
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
|
||||
END,
|
||||
s.update_time = NOW()
|
||||
WHERE s.del_flag = 0
|
||||
AND d.donation_status NOT IN ('yzf', 'sdfq')
|
||||
AND (
|
||||
s.sample_status IS NULL
|
||||
OR TRIM(s.sample_status) = ''
|
||||
OR s.sample_status <> 'yzf'
|
||||
OR s.void_date IS NULL
|
||||
OR TRIM(s.void_date) = ''
|
||||
);
|
||||
@@ -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;
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* 微信公众平台须为对应环境配置 request / 业务域名(HTTPS)
|
||||
*/
|
||||
export const APP_ENV = 'prod' // 'local' | 'test' | 'prod'
|
||||
export const APP_ENV = 'local' // 'local' | 'test' | 'prod'
|
||||
|
||||
const ENV_PRESETS = {
|
||||
local: {
|
||||
|
||||
@@ -25,6 +25,17 @@ export function fetchCreateReceiveAccount(data) {
|
||||
return post('/web/admin/oa-approval/receive-accounts', data)
|
||||
}
|
||||
|
||||
export function fetchUpdateReceiveAccount(id, data) {
|
||||
return put(`/web/admin/oa-approval/receive-accounts/${id}`, data)
|
||||
}
|
||||
|
||||
export function fetchDeleteReceiveAccount(id) {
|
||||
return request({
|
||||
url: `/web/admin/oa-approval/receive-accounts/${id}`,
|
||||
method: 'DELETE'
|
||||
})
|
||||
}
|
||||
|
||||
export function fetchRelatedCandidates(params) {
|
||||
return get('/web/admin/oa-approval/related-candidates', params)
|
||||
}
|
||||
|
||||
@@ -23,23 +23,11 @@
|
||||
</header>
|
||||
|
||||
<div class="market-list-card__fields">
|
||||
<div
|
||||
<MarketListField
|
||||
v-for="field in previewFields"
|
||||
:key="`${field.label}:${field.value}`"
|
||||
class="market-list-card__field"
|
||||
:class="{ 'is-wide': field.wide }"
|
||||
>
|
||||
<span>{{ field.label }}</span>
|
||||
<van-tag
|
||||
v-if="field.tag"
|
||||
class="market-tag"
|
||||
:type="resolveStatusTone(field.value, field.tagType)"
|
||||
size="medium"
|
||||
round
|
||||
:title="field.value"
|
||||
>{{ field.value }}</van-tag>
|
||||
<b v-else :class="{ 'is-money': field.money }">{{ field.value }}</b>
|
||||
</div>
|
||||
:field="field"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 每一期缴费:始终展示在「展开更多」上方,不收进总折叠 -->
|
||||
@@ -70,15 +58,11 @@
|
||||
</button>
|
||||
<div v-show="periodOpenKeys[block.key]" class="market-list-card__period-body">
|
||||
<div class="market-list-card__fields market-list-card__fields--compact">
|
||||
<div
|
||||
<MarketListField
|
||||
v-for="field in block.fields"
|
||||
:key="`${block.key}:${field.label}`"
|
||||
class="market-list-card__field"
|
||||
:class="{ 'is-wide': field.wide }"
|
||||
>
|
||||
<span>{{ field.label }}</span>
|
||||
<b :class="{ 'is-money': field.money }">{{ field.value }}</b>
|
||||
</div>
|
||||
:field="field"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -102,44 +86,20 @@
|
||||
<van-icon class="market-list-card__fields-toggle-chevron" name="arrow-down" />
|
||||
</button>
|
||||
<div v-show="fieldsOpen && collapsedFields.length" class="market-list-card__fields market-list-card__fields--folded">
|
||||
<div
|
||||
<MarketListField
|
||||
v-for="field in collapsedFields"
|
||||
:key="`more:${field.label}:${field.value}`"
|
||||
class="market-list-card__field"
|
||||
:class="{ 'is-wide': field.wide }"
|
||||
>
|
||||
<span>{{ field.label }}</span>
|
||||
<van-tag
|
||||
v-if="field.tag"
|
||||
class="market-tag"
|
||||
:type="resolveStatusTone(field.value, field.tagType)"
|
||||
size="medium"
|
||||
round
|
||||
:title="field.value"
|
||||
>{{ field.value }}</van-tag>
|
||||
<b v-else :class="{ 'is-money': field.money }">{{ field.value }}</b>
|
||||
</div>
|
||||
:field="field"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="card.footerFields?.length && showFoldedFooter" class="market-list-card__fields">
|
||||
<div
|
||||
<MarketListField
|
||||
v-for="field in card.footerFields"
|
||||
:key="`footer:${field.label}:${field.value}`"
|
||||
class="market-list-card__field"
|
||||
:class="{ 'is-wide': field.wide }"
|
||||
>
|
||||
<span>{{ field.label }}</span>
|
||||
<van-tag
|
||||
v-if="field.tag"
|
||||
class="market-tag"
|
||||
:type="resolveStatusTone(field.value, field.tagType)"
|
||||
size="medium"
|
||||
round
|
||||
:title="field.value"
|
||||
>{{ field.value }}</van-tag>
|
||||
<b v-else :class="{ 'is-money': field.money }">{{ field.value }}</b>
|
||||
</div>
|
||||
:field="field"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -181,15 +141,11 @@
|
||||
>{{ block.status }}</van-tag>
|
||||
</div>
|
||||
<div class="market-list-card__fields market-list-card__fields--compact">
|
||||
<div
|
||||
<MarketListField
|
||||
v-for="field in block.fields"
|
||||
:key="`${block.key}:${field.label}`"
|
||||
class="market-list-card__field"
|
||||
:class="{ 'is-wide': field.wide }"
|
||||
>
|
||||
<span>{{ field.label }}</span>
|
||||
<b>{{ field.value }}</b>
|
||||
</div>
|
||||
:field="field"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -222,6 +178,7 @@
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { actionLabel, buildMarketCard } from '../list-presenter.js'
|
||||
import { resolveStatusTone } from '../status-tone.js'
|
||||
import MarketListField from './MarketListField.vue'
|
||||
|
||||
const props = defineProps({
|
||||
item: { type: Object, required: true },
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<template>
|
||||
<div class="market-list-card__field" :class="{ 'is-wide': field.wide }">
|
||||
<span>{{ field.label }}</span>
|
||||
<span class="market-list-card__value">
|
||||
<van-tag
|
||||
v-if="field.tag"
|
||||
class="market-tag"
|
||||
:type="resolveStatusTone(field.value, field.tagType)"
|
||||
size="medium"
|
||||
round
|
||||
:title="field.value"
|
||||
>{{ field.value }}</van-tag>
|
||||
<b v-else :class="{ 'is-money': field.money }">{{ field.value }}</b>
|
||||
<button
|
||||
v-if="field.helpTitle"
|
||||
type="button"
|
||||
class="market-list-card__help"
|
||||
:aria-label="`查看${field.helpTitle}`"
|
||||
:title="field.helpTitle"
|
||||
@click="showHelp"
|
||||
>
|
||||
<van-icon name="question-o" />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { showDialog } from 'vant'
|
||||
import { resolveStatusTone } from '../status-tone.js'
|
||||
|
||||
const props = defineProps({
|
||||
field: { type: Object, required: true }
|
||||
})
|
||||
|
||||
function showHelp() {
|
||||
showDialog({
|
||||
title: props.field.helpTitle || '作废原因',
|
||||
message: props.field.helpText || '—',
|
||||
messageAlign: 'left',
|
||||
confirmButtonText: '知道了'
|
||||
})
|
||||
}
|
||||
</script>
|
||||
@@ -2,6 +2,7 @@ import { formatMoney } from './money.js'
|
||||
import {
|
||||
resolveStatusTag,
|
||||
samplePaymentProgress,
|
||||
sampleStatus,
|
||||
payMode,
|
||||
protocolStatus,
|
||||
donationStatus,
|
||||
@@ -94,6 +95,30 @@ const personName = (name, id) => {
|
||||
: referenceId ? '未知人员' : '—'
|
||||
}
|
||||
const field = (labelText, value, options = {}) => ({ label: labelText, value: text(value), ...options })
|
||||
|
||||
function sampleVoidReason(item) {
|
||||
if (item && Object.prototype.hasOwnProperty.call(item, 'sampleVoidDesc')) {
|
||||
return String(item.sampleVoidDesc ?? '').trim()
|
||||
}
|
||||
return String(item?.voidDesc ?? '').trim()
|
||||
}
|
||||
|
||||
/** 样本编码旁的样本状态;已作废时附带作废原因,供卡片问号展开 */
|
||||
function sampleStatusField(item) {
|
||||
const provided = String(item?.sampleStatusLabel ?? '').trim()
|
||||
const code = String(item?.sampleStatus ?? '').trim()
|
||||
if (!code && !provided) return field('样本状态', '')
|
||||
const resolved = resolveStatusTag(sampleStatus, code)
|
||||
const display = provided || resolved.label
|
||||
const voided = code === 'yzf' || display === '已作废'
|
||||
return field('样本状态', display, {
|
||||
tag: true,
|
||||
tagType: voided ? 'danger' : (code ? resolved.tagType : 'info'),
|
||||
...(voided
|
||||
? { helpTitle: '作废原因', helpText: sampleVoidReason(item) || '—' }
|
||||
: {})
|
||||
})
|
||||
}
|
||||
export function money(value) {
|
||||
return formatMoney(value)
|
||||
}
|
||||
@@ -134,6 +159,7 @@ function protocolCard(item) {
|
||||
field('所属项目', item.projectName || item.basic?.projectName || ((item.projectId || item.basic?.projectId) ? '历史项目' : '未归属')),
|
||||
field('项目组', item.teamName || item.basic?.teamName),
|
||||
field('样本编码', item.sampleCode || item.labStorageCode),
|
||||
sampleStatusField(item),
|
||||
field('采集日期', collectDate || item.donationDate),
|
||||
field('当月核量号', item.monthlyVerifyNo),
|
||||
field('实验室流转编号', item.labStorageCode || item.sampleCode),
|
||||
@@ -172,6 +198,7 @@ function protocolCard(item) {
|
||||
field('所属项目', item.projectName || item.basic?.projectName || ((item.projectId || item.basic?.projectId) ? '历史项目' : '未归属')),
|
||||
field('项目组', item.teamName || item.basic?.teamName),
|
||||
field('样本编码', item.sampleCode),
|
||||
sampleStatusField(item),
|
||||
field('登记日期', item.registerDate || item.donationDate),
|
||||
field('母亲电话', item.motherPhone),
|
||||
field('母亲身份证号', item.motherIdCard),
|
||||
@@ -212,6 +239,7 @@ function chaseCard(item) {
|
||||
field('客户', item.motherName),
|
||||
field('联系电话', item.motherPhone),
|
||||
field('样本编码', item.sampleCode),
|
||||
sampleStatusField(item),
|
||||
field('市场专员', personName(item.salesUserName, item.salesUserId)),
|
||||
field('缴费方式', mode.label, { tag: true, tagType: mode.tagType }),
|
||||
field('期次', `第 ${text(item.scheduleNo, '1')} 期`),
|
||||
@@ -281,7 +309,7 @@ function paymentCard(item) {
|
||||
statusTone: progress.tagType,
|
||||
fields: [
|
||||
field('姓名', item.motherName), field('手机号', item.motherPhone),
|
||||
field('样本编码', item.sampleCode), field('签署日期', item.signDate),
|
||||
field('样本编码', item.sampleCode), sampleStatusField(item), field('签署日期', item.signDate),
|
||||
field('存储项目', item.sampleTypeName), field('合同总额', money(item.contractAmount), { money: true }),
|
||||
field('缴费方式', mode.label, { tag: true, tagType: mode.tagType }),
|
||||
field('应收总额', money(item.receivableAmount), { money: true })
|
||||
@@ -311,6 +339,7 @@ function freightSampleBlock(row, index) {
|
||||
field('母亲姓名', row?.motherName),
|
||||
field('子女姓名', row?.newbornName),
|
||||
field('样本编码', row?.sampleCode, { wide: true }),
|
||||
sampleStatusField(row),
|
||||
field('样本类型', row?.sampleTypeName, { wide: true })
|
||||
]
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ test('research donation protocol card matches excel-parity field set', () => {
|
||||
const labels = card.fields.map((f) => f.label)
|
||||
assert.equal(labels[2], '样本编码')
|
||||
for (const label of [
|
||||
'样本编码', '当月核量号', '实验室流转编号', '废弃原因', '样本类型',
|
||||
'样本编码', '样本状态', '当月核量号', '实验室流转编号', '废弃原因', '样本类型',
|
||||
'采集地区', '采集医院', '分娩时间', '采集时间', '市场专员', '地区经理',
|
||||
'运输方式', '新生儿性别', '新生儿体重', '分娩方式', '胎次', '母血采集时间',
|
||||
'知情同意书', '传染病检测报告', '协议书', '备注'
|
||||
@@ -245,11 +245,70 @@ test('freight card shows the scope-safe visible count and collapsible sample blo
|
||||
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '母亲姓名').value, '周雨桐')
|
||||
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '子女姓名').value, '宝宝乙')
|
||||
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '样本编码').value, 'S-2')
|
||||
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '样本状态').value, '—')
|
||||
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '样本类型').value, '脐带')
|
||||
assert.ok(manager.fields.some((field) => field.label === '更新时间' && field.value === '2026-10-13 10:00:00'))
|
||||
assert.ok(manager.fields.some((field) => field.label === '备注' && field.value === '同批送达'))
|
||||
})
|
||||
|
||||
test('sample-coded list cards show sample status and a void reason affordance', () => {
|
||||
const cases = [
|
||||
['protocol', { source: 'cell_storage', sampleCode: 'S-1', sampleStatus: 'yrk', sampleStatusLabel: '已入库' }],
|
||||
['payment-chase', { sampleCode: 'S-1', sampleStatus: 'jcz' }],
|
||||
['payment', { sampleCode: 'S-1', motherName: '周雨桐', sampleStatus: 'ycj', sampleStatusLabel: '已采集' }]
|
||||
]
|
||||
for (const [module, item] of cases) {
|
||||
const card = buildMarketCard(module, 'specialist', item)
|
||||
const status = card.fields.find((field) => field.label === '样本状态')
|
||||
assert.ok(status, module)
|
||||
assert.equal(status.tag, true)
|
||||
assert.equal(status.helpTitle, undefined)
|
||||
}
|
||||
assert.equal(
|
||||
buildMarketCard('protocol', 'specialist', {
|
||||
source: 'cell_storage', sampleCode: 'S-1', sampleStatus: 'yrk', sampleStatusLabel: '已入库'
|
||||
}).fields.find((field) => field.label === '样本状态').value,
|
||||
'已入库'
|
||||
)
|
||||
assert.equal(
|
||||
buildMarketCard('payment-chase', 'specialist', {
|
||||
sampleCode: 'S-1', sampleStatus: 'jcz'
|
||||
}).fields.find((field) => field.label === '样本状态').value,
|
||||
'检测中'
|
||||
)
|
||||
|
||||
const voided = buildMarketCard('payment', 'specialist', {
|
||||
motherName: '作废客户',
|
||||
sampleCode: 'S-VOID',
|
||||
sampleStatus: 'yzf',
|
||||
voidDesc: '客户放弃存储'
|
||||
})
|
||||
const voidField = voided.fields.find((field) => field.label === '样本状态')
|
||||
assert.equal(voidField.value, '已作废')
|
||||
assert.equal(voidField.tagType, 'danger')
|
||||
assert.equal(voidField.helpTitle, '作废原因')
|
||||
assert.equal(voidField.helpText, '客户放弃存储')
|
||||
|
||||
const donation = buildMarketCard('protocol', 'specialist', {
|
||||
source: 'research_donation',
|
||||
sampleCode: 'S-D',
|
||||
sampleStatus: 'yzf',
|
||||
sampleStatusLabel: '已作废',
|
||||
voidDesc: '协议级废弃说明',
|
||||
sampleVoidDesc: '样本溶血'
|
||||
})
|
||||
assert.equal(donation.fields.find((field) => field.label === '废弃原因').value, '协议级废弃说明')
|
||||
assert.equal(donation.fields.find((field) => field.label === '样本状态').helpText, '样本溶血')
|
||||
|
||||
const freight = buildMarketCard('freight', 'manager', {
|
||||
freightNo: 'YF-VOID',
|
||||
items: [{ sampleCode: 'S-V', sampleStatus: 'yzf', voidDesc: '运输破损' }]
|
||||
})
|
||||
const sampleStatus = freight.sampleBlocks[0].fields.find((field) => field.label === '样本状态')
|
||||
assert.equal(sampleStatus.value, '已作废')
|
||||
assert.equal(sampleStatus.helpText, '运输破损')
|
||||
})
|
||||
|
||||
test('action labels cover module-specific operations', () => {
|
||||
assert.equal(actionLabel('link'), '关联样本')
|
||||
assert.equal(actionLabel('unlink'), '取消样本关联')
|
||||
|
||||
@@ -84,6 +84,7 @@ test('market list visual contract keeps search white, tags filled and actions ri
|
||||
'./components/MarketDetailSection.vue',
|
||||
'./components/MarketDetailNestedCard.vue',
|
||||
'./components/MarketListCard.vue',
|
||||
'./components/MarketListField.vue',
|
||||
'./components/PresignOrderCard.vue',
|
||||
'./components/PresignTransferCard.vue',
|
||||
'./components/ProtocolSamplePaymentPanel.vue',
|
||||
@@ -541,6 +542,16 @@ test('payment detail hosts PaymentDetailTransfersPanel and hides transfer bottom
|
||||
assert.match(panel, /应缴批次/)
|
||||
})
|
||||
|
||||
test('voided sample status uses a question icon and vant dialog', () => {
|
||||
const field = source('./components/MarketListField.vue')
|
||||
const card = source('./components/MarketListCard.vue')
|
||||
assert.match(field, /name="question-o"/)
|
||||
assert.match(field, /showDialog/)
|
||||
assert.match(field, /field\.helpTitle/)
|
||||
assert.match(field, /class="market-tag"/)
|
||||
assert.match(card, /MarketListField/)
|
||||
})
|
||||
|
||||
test('payment cards reproduce the Web Excel columns and operation labels', () => {
|
||||
const presenter = source('./list-presenter.js')
|
||||
const card = source('./components/MarketListCard.vue')
|
||||
@@ -590,7 +601,7 @@ test('protocol cards expose the same business fields as the web list', async ()
|
||||
})
|
||||
|
||||
assert.deepEqual(card.fields.map((field) => field.label), [
|
||||
'所属项目', '项目组', '样本编码', '登记日期', '母亲电话', '母亲身份证号', '父亲姓名',
|
||||
'所属项目', '项目组', '样本编码', '样本状态', '登记日期', '母亲电话', '母亲身份证号', '父亲姓名',
|
||||
'新生儿性别', '分娩方式', '新生儿体重(克)', '采集地区', '采集医院',
|
||||
'市场专员', '样本采集时间', '创建时间'
|
||||
])
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import vm from 'node:vm'
|
||||
import * as Vue from 'vue'
|
||||
import { compile } from '@vue/compiler-dom'
|
||||
import { projectValidation } from './project-assignment.js'
|
||||
|
||||
const source = readFileSync(new URL('../views/market/MarketModuleForm.vue', import.meta.url), 'utf8')
|
||||
// Render the real loop/slot/ref structure; native host nodes need no browser or service.
|
||||
const template = source.slice(source.indexOf('<template v-for="section in leadingSections"'), source.indexOf('\n\n <section'))
|
||||
const render = new Function('Vue', compile(template, { prefixIdentifiers: true }).code)(Vue)
|
||||
const submitSource = source.slice(source.indexOf('async function submit()'), source.indexOf('\nasync function confirmLeave()'))
|
||||
const renderer = Vue.createRenderer({
|
||||
createElement: () => ({}), createText: () => ({}), createComment: () => ({}),
|
||||
insert(node, parent, anchor = null) {
|
||||
parent.children ||= []
|
||||
node.parent = parent
|
||||
const index = parent.children.indexOf(anchor)
|
||||
parent.children.splice(index < 0 ? parent.children.length : index, 0, node)
|
||||
},
|
||||
remove(node) {
|
||||
const siblings = node.parent?.children || []
|
||||
const index = siblings.indexOf(node)
|
||||
if (index >= 0) siblings.splice(index, 1)
|
||||
},
|
||||
setText() {}, setElementText() {}, patchProp() {},
|
||||
parentNode: (node) => node.parent,
|
||||
nextSibling: (node) => {
|
||||
const siblings = node.parent?.children || []
|
||||
return siblings[siblings.indexOf(node) + 1] || null
|
||||
}
|
||||
})
|
||||
|
||||
async function mountForm({ role, mode = 'create', projectId = 'project-1', loading = false, error = '' }) {
|
||||
const projectAssignment = Vue.ref(null)
|
||||
const formData = Vue.ref({ source: 'research_donation', projectId })
|
||||
const messages = [], requests = []
|
||||
let validations = 0
|
||||
const ProjectAssignmentField = {
|
||||
setup(_, { expose }) {
|
||||
expose({ validate() {
|
||||
validations++
|
||||
return projectValidation({ editing: mode === 'edit', required: true, projectId, loading, error })
|
||||
} })
|
||||
return () => Vue.h('div')
|
||||
}
|
||||
}
|
||||
const Section = { setup: (_, { slots }) => () => slots.insert?.() }
|
||||
const context = Vue.ref({ module: 'protocol', marketRole: role })
|
||||
const app = renderer.createApp({
|
||||
components: { MarketFormSection: Section, ProjectAssignmentField },
|
||||
setup: () => ({
|
||||
projectAssignment, context, formData, mode,
|
||||
leadingSections: [{ key: 'customer' }, { key: 'protocol' }],
|
||||
formOptions: {}, fieldsLocked: false, dirty: false,
|
||||
sectionValue: () => ({}), searchProtocolCustomers() {}, setSectionValue() {},
|
||||
uploadField() {}, handleFieldChange() {}, handleCustomerSelect() {}
|
||||
}), render
|
||||
})
|
||||
app.mount({})
|
||||
await Vue.nextTick()
|
||||
const scope = {
|
||||
projectAssignment, context, formData, mode: Vue.ref(mode),
|
||||
submitting: Vue.ref(false), uploadPending: Vue.ref(0), isProtocolV2: Vue.ref(false),
|
||||
isProtocolV1: Vue.ref(false), id: Vue.ref(mode === 'edit' ? 'record-1' : ''),
|
||||
action: Vue.ref(mode), visibleSections: Vue.ref([]), dirty: Vue.ref(true),
|
||||
showToast: (text) => messages.push(text), showSuccessToast: (text) => messages.push(text),
|
||||
validateRequiredFields: () => '', buildMarketActionPayload: (_module, _action, data) => data,
|
||||
sanitizeMarketPayload: (data) => data, buildPayload: () => formData.value,
|
||||
AbortController, submitController: null, allowLeave: false,
|
||||
saveMarketRecord: async (...args) => { requests.push(args); return { id: 'saved' } },
|
||||
mountGuard: { isCurrent: () => true }, mountToken: 1,
|
||||
resolveMarketSavedDetailId: () => 'saved', router: { replace: async () => {} },
|
||||
route: { query: {} }, marketRecordNavigationQuery: () => ({}),
|
||||
marketErrorMessage: (cause) => cause.message
|
||||
}
|
||||
const submit = vm.runInNewContext(`${submitSource}\nsubmit`, scope)
|
||||
return { submit, messages, requests, app, validations: () => validations }
|
||||
}
|
||||
|
||||
for (const role of ['specialist', 'manager']) {
|
||||
for (const mode of ['create', 'edit']) {
|
||||
test(`${role} ${mode}: a valid project reaches the save request`, async () => {
|
||||
const form = await mountForm({ role, mode })
|
||||
try {
|
||||
await form.submit()
|
||||
assert.equal(form.validations(), 1)
|
||||
assert.equal(form.requests.length, 1)
|
||||
assert.equal(form.requests[0][0].marketRole, role)
|
||||
assert.deepEqual(form.messages, ['保存成功'])
|
||||
} finally { form.app.unmount() }
|
||||
})
|
||||
}
|
||||
for (const [state, message] of [
|
||||
[{ projectId: '' }, '请选择所属项目'],
|
||||
[{ loading: true }, '项目选项加载中,请稍后保存'],
|
||||
[{ error: 'network' }, '项目选项加载失败,请重试后保存']
|
||||
]) {
|
||||
test(`${role}: ${message}`, async () => {
|
||||
const form = await mountForm({ role, ...state })
|
||||
try {
|
||||
await form.submit()
|
||||
assert.equal(form.validations(), 1)
|
||||
assert.equal(form.requests.length, 0)
|
||||
assert.deepEqual(form.messages, [message])
|
||||
} finally { form.app.unmount() }
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,14 @@ export const receptionSource = createRegistry({
|
||||
basic_experiment: { label: '基础实验', tagType: 'primary' }
|
||||
})
|
||||
|
||||
/** 协议/捐赠样本状态;与 Web sampleStatus 保持一致 */
|
||||
export const sampleStatus = createRegistry({
|
||||
ycj: { label: '已采集', tagType: 'primary' },
|
||||
jcz: { label: '检测中', tagType: 'warning' },
|
||||
yrk: { label: '已入库', tagType: 'success' },
|
||||
yzf: { label: '已作废', tagType: 'danger' }
|
||||
})
|
||||
|
||||
export const presignOrderStatus = createRegistry({
|
||||
draft: { label: '草稿', tagType: 'info' },
|
||||
active: { label: '进行中', tagType: 'warning' },
|
||||
|
||||
@@ -8,10 +8,19 @@ import {
|
||||
payMode,
|
||||
presignOrderStatus,
|
||||
receptionSource,
|
||||
sampleStatus,
|
||||
transportType,
|
||||
auditStatus
|
||||
} from './status-tag-registry.js'
|
||||
|
||||
test('sample status yzf is 已作废/danger', () => {
|
||||
assert.deepEqual(resolveStatusTag(sampleStatus, 'yzf'), {
|
||||
label: '已作废',
|
||||
tagType: 'danger'
|
||||
})
|
||||
assert.equal(resolveStatusTag(sampleStatus, 'yrk').label, '已入库')
|
||||
})
|
||||
|
||||
test('sample progress dfj is 待缴费/info not 待缴清', () => {
|
||||
assert.deepEqual(resolveStatusTag(samplePaymentProgress, 'dfj'), {
|
||||
label: '待缴费',
|
||||
|
||||
@@ -150,6 +150,7 @@ import {
|
||||
uploadAttachment
|
||||
} from '../../api/oa.js'
|
||||
import OaCommentFileCards from './OaCommentFileCards.vue'
|
||||
import { hasOaCommentDraft } from '../oa-comment-draft.js'
|
||||
import { attachmentFullUrl } from '../../utils/attachment.js'
|
||||
import { isHarmonyWechat } from '../../utils/harmony-file-picker.js'
|
||||
import HarmonyFileSource from '../../components/HarmonyFileSource.vue'
|
||||
@@ -516,12 +517,25 @@ function confirmMention() {
|
||||
mentionVisible.value = false
|
||||
}
|
||||
|
||||
async function onSend() {
|
||||
const content = draft.value.trim()
|
||||
if (!content && !mentionUsers.value.length && !picked.value.length) {
|
||||
showToast('请填写评论、@人员或添加附件')
|
||||
return
|
||||
function draftPending() {
|
||||
return hasOaCommentDraft({
|
||||
content: draft.value,
|
||||
mentionCount: mentionUsers.value.length,
|
||||
attachmentCount: picked.value.length
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 审批动作前冲刷未发送草稿:无草稿直接成功;有草稿则等同点击「发送」。
|
||||
* @returns {Promise<boolean>} false 表示发送失败或忙碌,调用方应中止审批动作
|
||||
*/
|
||||
async function flushDraft(opts = {}) {
|
||||
if (!draftPending()) return true
|
||||
if (sending.value || uploading.value) {
|
||||
showToast(uploading.value ? '附件上传中,请稍后再试' : '评论发送中,请稍后再试')
|
||||
return false
|
||||
}
|
||||
const content = draft.value.trim()
|
||||
sending.value = true
|
||||
try {
|
||||
await fetchCreateOaComment(props.instanceId, {
|
||||
@@ -533,15 +547,27 @@ async function onSend() {
|
||||
picked.value = []
|
||||
mentionUsers.value = []
|
||||
closeAtSuggest()
|
||||
showToast('已发送')
|
||||
if (!opts.quiet) showToast('已发送')
|
||||
emit('refresh')
|
||||
return true
|
||||
} catch (e) {
|
||||
showToast(e?.message || '发送失败')
|
||||
return false
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function onSend() {
|
||||
if (!draftPending()) {
|
||||
showToast('请填写评论、@人员或添加附件')
|
||||
return
|
||||
}
|
||||
await flushDraft()
|
||||
}
|
||||
|
||||
defineExpose({ flushDraft, draftPending })
|
||||
|
||||
onMounted(() => {
|
||||
void ensureUserCache()
|
||||
})
|
||||
|
||||
@@ -52,6 +52,24 @@
|
||||
<div class="oa-sheet-row__title">{{ a.label }}</div>
|
||||
<div v-if="a.sub" class="oa-sheet-row__meta">{{ a.sub }}</div>
|
||||
</div>
|
||||
<div class="oa-sheet-row__actions" @click.stop>
|
||||
<button
|
||||
type="button"
|
||||
class="oa-sheet-row__icon is-edit"
|
||||
aria-label="编辑"
|
||||
@click="openEdit(a.id)"
|
||||
>
|
||||
<van-icon name="edit" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="oa-sheet-row__icon is-delete"
|
||||
aria-label="删除"
|
||||
@click="confirmDelete(a.id)"
|
||||
>
|
||||
<van-icon name="delete-o" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</van-checkbox-group>
|
||||
<van-empty v-if="!loading && !filtered.length" description="暂无本人的收款账户" />
|
||||
@@ -63,17 +81,17 @@
|
||||
</div>
|
||||
</van-popup>
|
||||
|
||||
<van-popup v-model:show="createVisible" position="bottom" round>
|
||||
<van-popup v-model:show="formVisible" position="bottom" round>
|
||||
<div class="oa-recv__sheet oa-recv__sheet--create">
|
||||
<div class="oa-recv__hd">
|
||||
<span @click="createVisible = false">取消</span>
|
||||
<strong>新增收款账户</strong>
|
||||
<span @click="formVisible = false">取消</span>
|
||||
<strong>{{ formTitle }}</strong>
|
||||
<span
|
||||
class="oa-recv__ok"
|
||||
:class="{ 'is-busy': createLoading }"
|
||||
@click="submitCreate"
|
||||
:class="{ 'is-busy': formLoading }"
|
||||
@click="submitForm"
|
||||
>
|
||||
{{ createLoading ? '提交中' : '确定' }}
|
||||
{{ formLoading ? '提交中' : '确定' }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="oa-recv__form">
|
||||
@@ -87,45 +105,45 @@
|
||||
<label class="oa-recv-field">
|
||||
<span class="oa-recv-field__label">户名<b>*</b></span>
|
||||
<span class="oa-recv-field__box">
|
||||
<input v-model="createForm.accountName" maxlength="128" placeholder="请输入户名" />
|
||||
<input v-model="formModel.accountName" maxlength="128" placeholder="请输入户名" />
|
||||
</span>
|
||||
</label>
|
||||
<label class="oa-recv-field">
|
||||
<span class="oa-recv-field__label">账号<b>*</b></span>
|
||||
<span class="oa-recv-field__box">
|
||||
<input v-model="createForm.accountNo" maxlength="128" placeholder="请输入账号" />
|
||||
<input v-model="formModel.accountNo" maxlength="128" placeholder="请输入账号" />
|
||||
</span>
|
||||
</label>
|
||||
<template v-if="createForm.accountType !== 'alipay'">
|
||||
<template v-if="formModel.accountType !== 'alipay'">
|
||||
<label class="oa-recv-field">
|
||||
<span class="oa-recv-field__label">银行<b>*</b></span>
|
||||
<span class="oa-recv-field__box">
|
||||
<input v-model="createForm.bankName" maxlength="128" placeholder="如:中国工商银行" />
|
||||
<input v-model="formModel.bankName" maxlength="128" placeholder="如:中国工商银行" />
|
||||
</span>
|
||||
</label>
|
||||
<label class="oa-recv-field">
|
||||
<span class="oa-recv-field__label">银行所在省<b>*</b></span>
|
||||
<span class="oa-recv-field__box">
|
||||
<input v-model="createForm.bankProvince" maxlength="64" placeholder="如:安徽省" />
|
||||
<input v-model="formModel.bankProvince" maxlength="64" placeholder="如:安徽省" />
|
||||
</span>
|
||||
</label>
|
||||
<label class="oa-recv-field">
|
||||
<span class="oa-recv-field__label">银行所在市<b>*</b></span>
|
||||
<span class="oa-recv-field__box">
|
||||
<input v-model="createForm.bankCity" maxlength="64" placeholder="如:合肥市" />
|
||||
<input v-model="formModel.bankCity" maxlength="64" placeholder="如:合肥市" />
|
||||
</span>
|
||||
</label>
|
||||
<label class="oa-recv-field">
|
||||
<span class="oa-recv-field__label">银行支行<b>*</b></span>
|
||||
<span class="oa-recv-field__box">
|
||||
<input v-model="createForm.bankBranch" maxlength="256" placeholder="请输入开户支行全称" />
|
||||
<input v-model="formModel.bankBranch" maxlength="256" placeholder="请输入开户支行全称" />
|
||||
</span>
|
||||
</label>
|
||||
</template>
|
||||
<label class="oa-recv-field">
|
||||
<span class="oa-recv-field__label">备注</span>
|
||||
<span class="oa-recv-field__box oa-recv-field__box--area">
|
||||
<textarea v-model="createForm.remark" maxlength="512" rows="2" placeholder="选填" />
|
||||
<textarea v-model="formModel.remark" maxlength="512" rows="2" placeholder="选填" />
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
@@ -135,7 +153,7 @@
|
||||
<van-popup v-model:show="typePickerVisible" position="bottom" round>
|
||||
<van-picker
|
||||
:columns="accountTypeColumns"
|
||||
:model-value="[createForm.accountType]"
|
||||
:model-value="[formModel.accountType]"
|
||||
@confirm="onTypeConfirm"
|
||||
@cancel="typePickerVisible = false"
|
||||
/>
|
||||
@@ -145,8 +163,13 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { showToast } from 'vant'
|
||||
import { fetchCreateReceiveAccount, fetchReceiveAccountOptions } from '../../api/oa.js'
|
||||
import { showConfirmDialog, showToast } from 'vant'
|
||||
import {
|
||||
fetchCreateReceiveAccount,
|
||||
fetchDeleteReceiveAccount,
|
||||
fetchReceiveAccountOptions,
|
||||
fetchUpdateReceiveAccount
|
||||
} from '../../api/oa.js'
|
||||
import {
|
||||
ACCOUNT_TYPE_LABEL,
|
||||
formatReceiveAccountLine,
|
||||
@@ -170,17 +193,19 @@ const keyword = ref('')
|
||||
const pendingIds = ref([])
|
||||
const snapshotMap = ref(new Map())
|
||||
const accountOptions = ref([])
|
||||
const createVisible = ref(false)
|
||||
const createLoading = ref(false)
|
||||
const formVisible = ref(false)
|
||||
const formLoading = ref(false)
|
||||
const formMode = ref('create')
|
||||
const editingId = ref('')
|
||||
const typePickerVisible = ref(false)
|
||||
const accountTypeColumns = [
|
||||
{ text: '支付宝', value: 'alipay' },
|
||||
{ text: '个人银行卡', value: 'personal' },
|
||||
{ text: '对公银行账户', value: 'corporate' }
|
||||
]
|
||||
const createForm = ref(emptyCreateForm())
|
||||
const formModel = ref(emptyForm())
|
||||
|
||||
function emptyCreateForm() {
|
||||
function emptyForm() {
|
||||
return {
|
||||
accountType: 'alipay',
|
||||
accountName: '',
|
||||
@@ -193,8 +218,12 @@ function emptyCreateForm() {
|
||||
}
|
||||
}
|
||||
|
||||
const formTitle = computed(() =>
|
||||
formMode.value === 'edit' ? '编辑收款账户' : '新增收款账户'
|
||||
)
|
||||
|
||||
const accountTypeLabel = computed(
|
||||
() => ACCOUNT_TYPE_LABEL[createForm.value.accountType] || ''
|
||||
() => ACCOUNT_TYPE_LABEL[formModel.value.accountType] || ''
|
||||
)
|
||||
|
||||
const normalized = computed(() => normalizeReceiveAccountModelValue(props.modelValue))
|
||||
@@ -260,26 +289,78 @@ function optionFromSnap(snap) {
|
||||
}
|
||||
}
|
||||
|
||||
function upsertLocalSnap(snap) {
|
||||
if (!snap.id) return
|
||||
const map = new Map(snapshotMap.value)
|
||||
map.set(snap.id, snap)
|
||||
snapshotMap.value = map
|
||||
const opt = optionFromSnap(snap)
|
||||
const idx = accountOptions.value.findIndex((x) => x.id === snap.id)
|
||||
if (idx >= 0) {
|
||||
const next = [...accountOptions.value]
|
||||
next[idx] = opt
|
||||
accountOptions.value = next
|
||||
} else {
|
||||
accountOptions.value = [...accountOptions.value, opt]
|
||||
}
|
||||
}
|
||||
|
||||
function fillFormFromSnap(snap) {
|
||||
const form = {
|
||||
accountType: snap.accountType || 'alipay',
|
||||
accountName: snap.accountName || '',
|
||||
accountNo: snap.accountNo || '',
|
||||
bankName: snap.bankName || '',
|
||||
bankProvince: snap.bankProvince || '',
|
||||
bankCity: snap.bankCity || '',
|
||||
bankBranch: snap.bankBranch || '',
|
||||
remark: snap.remark || ''
|
||||
}
|
||||
if (form.accountType === 'alipay') {
|
||||
form.bankName = ''
|
||||
form.bankProvince = ''
|
||||
form.bankCity = ''
|
||||
form.bankBranch = ''
|
||||
}
|
||||
formModel.value = form
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
createForm.value = emptyCreateForm()
|
||||
formMode.value = 'create'
|
||||
editingId.value = ''
|
||||
formModel.value = emptyForm()
|
||||
typePickerVisible.value = false
|
||||
createVisible.value = true
|
||||
formVisible.value = true
|
||||
}
|
||||
|
||||
function openEdit(id) {
|
||||
const tid = String(id || '').trim()
|
||||
const snap = snapshotMap.value.get(tid)
|
||||
if (!snap) {
|
||||
showToast('账户不存在或已删除')
|
||||
return
|
||||
}
|
||||
formMode.value = 'edit'
|
||||
editingId.value = tid
|
||||
fillFormFromSnap(snap)
|
||||
typePickerVisible.value = false
|
||||
formVisible.value = true
|
||||
}
|
||||
|
||||
function onTypeConfirm({ selectedOptions }) {
|
||||
const next = selectedOptions?.[0]?.value || 'alipay'
|
||||
const form = { ...createForm.value, accountType: next }
|
||||
const form = { ...formModel.value, accountType: next }
|
||||
if (next === 'alipay') {
|
||||
form.bankName = ''
|
||||
form.bankProvince = ''
|
||||
form.bankCity = ''
|
||||
form.bankBranch = ''
|
||||
}
|
||||
createForm.value = form
|
||||
formModel.value = form
|
||||
typePickerVisible.value = false
|
||||
}
|
||||
|
||||
function validateCreate(form) {
|
||||
function validateForm(form) {
|
||||
if (!form.accountName.trim()) return '请输入户名'
|
||||
if (!form.accountNo.trim()) return '请输入账号'
|
||||
if (form.accountType !== 'alipay') {
|
||||
@@ -291,14 +372,7 @@ function validateCreate(form) {
|
||||
return ''
|
||||
}
|
||||
|
||||
async function submitCreate() {
|
||||
if (createLoading.value) return
|
||||
const form = createForm.value
|
||||
const invalid = validateCreate(form)
|
||||
if (invalid) {
|
||||
showToast(invalid)
|
||||
return
|
||||
}
|
||||
function buildPayload(form) {
|
||||
const payload = {
|
||||
accountType: form.accountType,
|
||||
accountName: form.accountName.trim(),
|
||||
@@ -316,36 +390,80 @@ async function submitCreate() {
|
||||
payload.bankCity = form.bankCity.trim()
|
||||
payload.bankBranch = form.bankBranch.trim()
|
||||
}
|
||||
createLoading.value = true
|
||||
return payload
|
||||
}
|
||||
|
||||
async function submitForm() {
|
||||
if (formLoading.value) return
|
||||
const form = formModel.value
|
||||
const invalid = validateForm(form)
|
||||
if (invalid) {
|
||||
showToast(invalid)
|
||||
return
|
||||
}
|
||||
const payload = buildPayload(form)
|
||||
formLoading.value = true
|
||||
try {
|
||||
const created = await fetchCreateReceiveAccount(payload)
|
||||
const snap = snapshotFromRow(created)
|
||||
const row =
|
||||
formMode.value === 'edit' && editingId.value
|
||||
? await fetchUpdateReceiveAccount(editingId.value, payload)
|
||||
: await fetchCreateReceiveAccount(payload)
|
||||
const snap = snapshotFromRow(row)
|
||||
if (!snap.id) {
|
||||
showToast('创建成功但未返回账户 ID')
|
||||
showToast(formMode.value === 'edit' ? '更新成功但未返回账户 ID' : '创建成功但未返回账户 ID')
|
||||
return
|
||||
}
|
||||
await loadOptions()
|
||||
if (!snapshotMap.value.has(snap.id)) {
|
||||
const map = new Map(snapshotMap.value)
|
||||
map.set(snap.id, snap)
|
||||
snapshotMap.value = map
|
||||
if (!accountOptions.value.some((x) => x.id === snap.id)) {
|
||||
accountOptions.value = [...accountOptions.value, optionFromSnap(snap)]
|
||||
upsertLocalSnap(snap)
|
||||
if (formMode.value === 'edit') {
|
||||
const selected = normalized.value.map((x) => x.id)
|
||||
if (selected.includes(snap.id)) {
|
||||
emitItems(selected.map((id) => snapshotMap.value.get(id)).filter(Boolean))
|
||||
}
|
||||
showToast('更新成功')
|
||||
} else {
|
||||
const selected = new Set(normalized.value.map((x) => x.id))
|
||||
selected.add(snap.id)
|
||||
emitItems([...selected].map((id) => snapshotMap.value.get(id)).filter(Boolean))
|
||||
if (!pendingIds.value.includes(snap.id)) {
|
||||
pendingIds.value = [...pendingIds.value, snap.id]
|
||||
}
|
||||
keyword.value = ''
|
||||
showToast('创建成功')
|
||||
}
|
||||
const selected = new Set(normalized.value.map((x) => x.id))
|
||||
selected.add(snap.id)
|
||||
emitItems([...selected].map((id) => snapshotMap.value.get(id)).filter(Boolean))
|
||||
if (!pendingIds.value.includes(snap.id)) {
|
||||
pendingIds.value = [...pendingIds.value, snap.id]
|
||||
}
|
||||
keyword.value = ''
|
||||
createVisible.value = false
|
||||
showToast('创建成功')
|
||||
formVisible.value = false
|
||||
} catch (e) {
|
||||
showToast(e?.message || '新增收款账户失败')
|
||||
showToast(e?.message || (formMode.value === 'edit' ? '编辑收款账户失败' : '新增收款账户失败'))
|
||||
} finally {
|
||||
createLoading.value = false
|
||||
formLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmDelete(id) {
|
||||
const tid = String(id || '').trim()
|
||||
const snap = snapshotMap.value.get(tid)
|
||||
const name = snap?.accountName || tid
|
||||
try {
|
||||
await showConfirmDialog({
|
||||
title: '删除收款账户',
|
||||
message: `确定删除收款账户「${name}」吗?删除后不可再选;已提交单据中的账户快照仍保留。`
|
||||
})
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await fetchDeleteReceiveAccount(tid)
|
||||
await loadOptions()
|
||||
const nextSelected = normalized.value
|
||||
.map((x) => x.id)
|
||||
.filter((x) => x !== tid)
|
||||
.map((x) => snapshotMap.value.get(x))
|
||||
.filter(Boolean)
|
||||
emitItems(nextSelected)
|
||||
pendingIds.value = pendingIds.value.filter((x) => x !== tid)
|
||||
showToast('删除成功')
|
||||
} catch (e) {
|
||||
showToast(e?.message || '删除收款账户失败')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -411,6 +529,39 @@ onMounted(() => {
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.oa-sheet-row__actions {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.oa-sheet-row__icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
font-size: 18px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.oa-sheet-row__icon.is-edit {
|
||||
background: #ecfdf5;
|
||||
color: var(--brand-green-dark, #16a34a);
|
||||
}
|
||||
|
||||
.oa-sheet-row__icon.is-delete {
|
||||
background: #fef2f2;
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.oa-recv__add {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
/** 评论区是否有未发送草稿(文字 / @ / 附件) */
|
||||
export function hasOaCommentDraft(input = {}) {
|
||||
const content = String(input.content || '').trim()
|
||||
const mentionCount = Number(input.mentionCount || 0)
|
||||
const attachmentCount = Number(input.attachmentCount || 0)
|
||||
return !!(content || mentionCount > 0 || attachmentCount > 0)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { hasOaCommentDraft } from './oa-comment-draft.js'
|
||||
|
||||
test('empty draft is false', () => {
|
||||
assert.equal(hasOaCommentDraft({}), false)
|
||||
assert.equal(hasOaCommentDraft({ content: ' ', mentionCount: 0, attachmentCount: 0 }), false)
|
||||
})
|
||||
|
||||
test('text / mention / attachment counts as draft', () => {
|
||||
assert.equal(hasOaCommentDraft({ content: '@test' }), true)
|
||||
assert.equal(hasOaCommentDraft({ mentionCount: 1 }), true)
|
||||
assert.equal(hasOaCommentDraft({ attachmentCount: 2 }), true)
|
||||
})
|
||||
@@ -631,6 +631,29 @@ body.van-toast--unclickable .presign-order-page * {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.market-list-card__value {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.market-list-card__help {
|
||||
display: inline-flex;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
flex: 0 0 44px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin: -10px -8px -10px -4px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--market-primary-dark, #087f57);
|
||||
font-size: 18px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.market-list-card__samples {
|
||||
margin: 0 0 12px;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
@refresh="reloadDetail"
|
||||
/>
|
||||
<OaCommentComposer
|
||||
ref="commentComposerRef"
|
||||
:instance-id="instanceId"
|
||||
:instance-status="detail?.status || ''"
|
||||
@refresh="reloadDetail"
|
||||
@@ -238,6 +239,7 @@ const currentUserId = ref('')
|
||||
const currentUserName = ref('')
|
||||
const autoPrinted = ref(false)
|
||||
|
||||
const commentComposerRef = ref(null)
|
||||
const commentVisible = ref(false)
|
||||
const commentKind = ref('approve') // approve | reject | return
|
||||
const commentText = ref('')
|
||||
@@ -492,8 +494,16 @@ function goCopyRestart() {
|
||||
})
|
||||
}
|
||||
|
||||
function openComment(kind) {
|
||||
/** 同意/拒绝/打回前先发送评论区未提交草稿 */
|
||||
async function flushPendingComment() {
|
||||
const flush = commentComposerRef.value?.flushDraft
|
||||
if (!flush) return true
|
||||
return await flush()
|
||||
}
|
||||
|
||||
async function openComment(kind) {
|
||||
if (!myPendingTask.value) return
|
||||
if (!(await flushPendingComment())) return
|
||||
commentKind.value = kind
|
||||
commentText.value = defaultComment(kind)
|
||||
commentVisible.value = true
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
>
|
||||
<template #insert>
|
||||
<ProjectAssignmentField
|
||||
ref="projectAssignment"
|
||||
:ref="(instance) => (projectAssignment = instance)"
|
||||
embedded
|
||||
v-model="formData.projectId"
|
||||
:biz-type="formData.source"
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-12
|
||||
@@ -0,0 +1,23 @@
|
||||
## Context
|
||||
|
||||
附件三张表字段覆盖市场采集信息、实验室接收/处理与质检结果。系统内对应源主要为:
|
||||
|
||||
- 市场:`biz_protocol_party_customer`、`biz_protocol_collection_info`、`biz_collection_hospital`、`biz_protocol_sample`
|
||||
- 生产/接收:`biz_sample_reception`、`biz_sample_production_reception`
|
||||
- 质检:生产接收传染四项、储存证质检 payload、检查项结果;缺口进补充表
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **数据集**:`hsc`(造血)、`ubmc`(单个核)、`msc`(脐带间充质),以样本类型名 / 编码前缀识别。
|
||||
2. **权限码**:
|
||||
- 列表:`lab:sample-processing:list`(三子页共用读)
|
||||
- 部门编辑:`lab:sample-processing:market:edit` / `production:edit` / `qc:edit`
|
||||
- 主管:`lab:sample-processing:manager`(可编辑全部部门字段)
|
||||
3. **读写**:列表聚合只读源表 + 补充 JSON;更新时按字段 `source` 回写源表或补充表,服务端强制部门 ACL。
|
||||
4. **UI**:P01 列表 + 筛选 + 导出;行内编辑弹窗按部门分区,无权字段只读。
|
||||
5. **Figma**:MCP 授权不可用,按现有 Fresh Mint 列表页实现;合入后用户做视觉验收。
|
||||
|
||||
## Risks
|
||||
|
||||
- 历史 Excel 手工列与系统字段不完全一一对应,未映射列落补充表,避免阻断上线。
|
||||
- 菜单种子不自动授权角色,需管理员分配。
|
||||
@@ -0,0 +1,27 @@
|
||||
## Why
|
||||
|
||||
2026-11-04 需求会议要求按线上三张实验室样本处理表(造血干细胞 / 单个核 / 脐带间充质)在系统中单独建模块,按市场、生产、质检拆分可编辑字段,支持筛选与导出。现有业务数据分散在协议、样本接收、生产接收与质检等表,缺少统一台账视图。
|
||||
|
||||
## What Changes
|
||||
|
||||
- 新增 Web 一级模块「实验室样本处理数据」,下挂三个子模块对应三张表。
|
||||
- 按样本编码从现有业务表聚合展示全字段;部门员工可读全部、只写本部门字段;主管可写全部部门字段。
|
||||
- 支持关键词/时间筛选与 Excel 导出。
|
||||
- 无法直接回写源表的字段写入补充表 `biz_lab_sample_processing_extra`。
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `lab-sample-processing-data`: 实验室样本处理数据聚合台账、部门字段 ACL、筛选导出
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- (无)
|
||||
|
||||
## Impact
|
||||
|
||||
- **backend**:聚合服务、API、补充表、菜单权限
|
||||
- **web-admin**:三子模块列表页、编辑弹窗、导出
|
||||
- **docs/sql**:结构 + 菜单种子
|
||||
- **不改** mobile-h5 / mobile-oa-h5
|
||||
@@ -0,0 +1,33 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: 三子模块台账
|
||||
|
||||
系统 SHALL 提供「实验室样本处理数据」模块,包含造血干细胞、单个核、脐带间充质三个子模块;每个子模块按样本展示该表全部约定字段。
|
||||
|
||||
#### Scenario: 按数据集查询
|
||||
|
||||
- **WHEN** 用户打开造血干细胞子模块并具备列表权限
|
||||
- **THEN** 系统仅返回造血干细胞数据集样本行,并包含市场/生产/质检字段聚合结果
|
||||
|
||||
### Requirement: 部门字段编辑权限
|
||||
|
||||
系统 SHALL 允许具备列表权限的用户查看全部字段;普通员工仅可编辑本部门字段;具备主管权限的用户可编辑全部部门字段。服务端 MUST 拒绝无权字段写入。
|
||||
|
||||
#### Scenario: 生产员工改市场字段被拒
|
||||
|
||||
- **WHEN** 仅有生产编辑权限的用户提交市场部门字段变更
|
||||
- **THEN** 系统拒绝该请求且不持久化无权字段
|
||||
|
||||
#### Scenario: 主管可改全部
|
||||
|
||||
- **WHEN** 具备主管权限的用户提交跨部门字段变更
|
||||
- **THEN** 系统接受并回写对应数据源或补充表
|
||||
|
||||
### Requirement: 筛选与导出
|
||||
|
||||
系统 SHALL 支持按样本编码、姓名关键词及接收/采集时间范围筛选,并导出当前筛选结果为 Excel。
|
||||
|
||||
#### Scenario: 导出当前筛选
|
||||
|
||||
- **WHEN** 用户在筛选条件下点击导出
|
||||
- **THEN** 下载的表格列与当前子模块字段目录一致,行集与列表筛选一致
|
||||
@@ -0,0 +1,21 @@
|
||||
## 1. 规格与数据
|
||||
|
||||
- [x] 1.1 建立 OpenSpec 变更与字段/权限设计
|
||||
- [x] 1.2 定义三数据集字段目录与部门归属、回写源
|
||||
|
||||
## 2. 后端
|
||||
|
||||
- [x] 2.1 补充表模型与迁移 SQL、菜单种子
|
||||
- [x] 2.2 聚合列表 / 详情 / 更新 / 导出 API 与部门 ACL
|
||||
- [x] 2.3 单元测试:数据集识别、字段 ACL、无权拒绝
|
||||
|
||||
## 3. 前端
|
||||
|
||||
- [x] 3.1 共享列表页组件(筛选、编辑、导出)
|
||||
- [x] 3.2 三子模块路由与菜单码
|
||||
- [x] 3.3 API 客户端
|
||||
|
||||
## 4. 验证
|
||||
|
||||
- [x] 4.1 受影响单元测试
|
||||
- [ ] 4.2 字段一致性/菜单说明回写工单(凭据就绪后)
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-11
|
||||
@@ -0,0 +1,47 @@
|
||||
## Context
|
||||
|
||||
储存证质检信息由 `biz_sample_storage_cert_qc.payload` JSON 保存,Web 共用 `storage-cert-qc-dialog`,API 以菜单码控制读写且保存为整单覆盖。业务现要求按「质检 / 生产」拆分字段编辑权,并可由管理员配置人员。
|
||||
|
||||
已确认:方案 A(租户级配置 + 按人授权);配置入口独立菜单码;未配置前兼容旧写权限;同人字段并集;修改端为 web-admin + backend。
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
|
||||
- 租户可配置质检、生产两套「字段 + 人员」ACL
|
||||
- 前端按字段只读/可写;后端 merge 强制执行
|
||||
- 三处入口行为一致;配置 UI 符合 Fresh Mint 弹窗规范
|
||||
|
||||
**Non-Goals:**
|
||||
|
||||
- 不按样本、不按工单单独配置 ACL
|
||||
- 不引入角色绑定作为本期主路径(人员勾选)
|
||||
- 不改造 mobile-h5 / mobile-oa-h5
|
||||
- 不改变 payload 字段语义与预填逻辑(仅限制谁能改)
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **存储**:主表 `biz_storage_cert_qc_acl`(`tenant_no`+`scope` 唯一,`field_keys` JSON,`configured_flag`)+ 子表 `biz_storage_cert_qc_acl_user`(`acl_id`+`user_id`,软删同步)。相对单 JSON 大包,子表便于人员校验与审计扩展。
|
||||
2. **权限解析**:用户可编辑字段 = 其所属各已配置 scope 的 field_keys 并集;严格模式在「任一 scope 的 configured_flag=1」时启用;否则有原 WRITE_MENUS 即可编辑全部合法字段。
|
||||
3. **写路径**:**BREAKING 行为**:`PUT` 从整单覆盖改为服务端 merge——仅更新 `editableFieldKeys` 内键;无任何可写字段拒绝保存;提交中含无权键且值相对库内有变化则 403。
|
||||
4. **配置权限**:独立菜单码(建议 `cell-storage:sample-info:storage-cert-qc-acl`);与业务填写菜单分离。按钮仅在 `canConfigureAcl=true` 时展示。
|
||||
5. **字段候选**:前后端共用类型字段清单(与 `STORAGE_CERT_QC_GROUPS` / 后端 type keys 对齐);配置 UI 展示两样本类型字段并集,非法 key 拒绝保存。
|
||||
6. **UI**:主弹窗 footer 左侧配置按钮、右侧取消/确定;配置子弹两个 Tab(字段勾选 / 人员多选)。先 Figma 确认再编码。
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- [未配置→已配置切换瞬间全员变严] → 上线说明;兼容期默认未配置仍可写;配置保存前可预览影响(可选,本期不做强制)。
|
||||
- [人员名单维护成本] → 接受方案 A;后续可加角色扩展,不阻塞本期。
|
||||
- [整单覆盖客户端旧代码] → 后端 merge 兼容旧客户端:无权字段被忽略或在变更时 403;推荐 403 以便发现错误集成。
|
||||
- [超级管理员] → 不默认绕过 ACL;仅配置菜单控制谁能改 ACL。若需超管旁路,另开需求。
|
||||
|
||||
## Migration Plan
|
||||
|
||||
1. 执行 SQL 建表;部署后端(读接口先返回兼容态 editableFieldKeys=全部或空+aclStrict=false)。
|
||||
2. 部署前端(无配置权限时 UI 与现网接近)。
|
||||
3. 管理员配置质检/生产后该租户进入严格模式。
|
||||
4. 回滚:保留表数据;回退代码后配置表闲置;严格模式逻辑随代码回退消失。
|
||||
|
||||
## Open Questions
|
||||
|
||||
- 无(关键项已在对话确认:租户级、独立配置菜单、兼容期、字段并集、先 Figma)。
|
||||
@@ -0,0 +1,28 @@
|
||||
## Why
|
||||
|
||||
「填写储存证质检信息」弹窗目前只要具备菜单写权限即可改全部字段,无法按质检 / 生产职责拆分。业务需要:质检与生产各自配置可编辑字段与人员,范围外用户仅可查看,且服务端必须强制校验。
|
||||
|
||||
## What Changes
|
||||
|
||||
- 新增租户级储存证质检字段 ACL:两个 scope(`qc` / `production`),各自保存可编辑字段列表与可编辑人员。
|
||||
- 详情接口返回当前用户 `editableFieldKeys` 等权限上下文;保存改为服务端按权限 merge,拒绝无权字段篡改。
|
||||
- 主弹窗 footer 左侧增加「质检权限」「生产权限」入口(仅配置权限可见);配置子弹含「勾选字段」「配置人员」两个 Tab。
|
||||
- 未对任一 scope 保存过配置时,兼容现有菜单写权限(可改全部);任一 scope 首次配置后该租户进入严格 ACL。
|
||||
- **不改**小程序 / mobile-oa-h5;三处 Web 入口(客户服务、质检工单、生产工单)共用同一弹窗组件一并生效。
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `storage-cert-qc-field-acl`: 储存证质检信息字段级编辑权限(配置、解析、读写强制)
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- (无;`openspec/specs/` 尚未建立长期基线中的对应能力)
|
||||
|
||||
## Impact
|
||||
|
||||
- **backend**:新表与 CRUD/API;`sample_storage_cert_qc` 读/写路径;菜单码与鉴权
|
||||
- **web-admin**:`storage-cert-qc-dialog`、ACL 配置子弹、API 客户端
|
||||
- **docs/sql**:结构迁移脚本
|
||||
- **权限**:租户隔离;配置入口独立菜单码;写入不信任客户端字段权限声明
|
||||
@@ -0,0 +1,76 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: 租户级质检与生产字段 ACL 配置
|
||||
|
||||
系统 SHALL 按租户维护储存证质检信息的两套编辑权限配置,scope 分别为 `qc`(质检)与 `production`(生产)。每套配置 SHALL 包含可编辑字段 key 列表与可编辑用户列表。字段 key MUST 属于该业务已定义的合法 payload 键集合。
|
||||
|
||||
#### Scenario: 管理员保存质检权限
|
||||
|
||||
- **WHEN** 具备 ACL 配置菜单权限的用户保存 scope=`qc` 的字段列表与人员列表
|
||||
- **THEN** 系统持久化该租户的质检 ACL,并将该 scope 标记为已配置
|
||||
|
||||
#### Scenario: 非法字段被拒绝
|
||||
|
||||
- **WHEN** 配置请求包含不在合法 payload 键集合中的 field key
|
||||
- **THEN** 系统拒绝保存并返回错误,不部分写入
|
||||
|
||||
### Requirement: 按当前用户解析可编辑字段
|
||||
|
||||
系统在返回储存证质检详情时 SHALL 附带当前用户可编辑字段集合。可编辑字段 MUST 为用户所属各 scope 字段列表的并集。未出现在任一 ACL 人员名单中的用户,在严格模式下 MUST 得到空的可编辑字段集合(仍可只读查看详情)。
|
||||
|
||||
#### Scenario: 同属两 scope 取并集
|
||||
|
||||
- **WHEN** 用户同时在质检与生产人员名单中,且两 scope 勾选了不同字段
|
||||
- **THEN** 详情中的可编辑字段为两 scope 字段的并集
|
||||
|
||||
#### Scenario: 未授权用户只读
|
||||
|
||||
- **WHEN** 租户已进入严格 ACL,且当前用户不在任一 scope 人员名单中
|
||||
- **THEN** 可编辑字段为空,用户可查看已有数据但不能修改
|
||||
|
||||
### Requirement: 未配置前兼容菜单写权限
|
||||
|
||||
当租户的质检与生产 scope 均未被标记为已配置时,系统 SHALL 保持兼容行为:只要用户具备既有储存证质检写菜单权限,即可编辑全部合法字段。当任一 scope 被标记为已配置后,该租户 MUST 进入严格 ACL,不再仅凭菜单写权限获得全字段编辑权。
|
||||
|
||||
#### Scenario: 全新租户未配置
|
||||
|
||||
- **WHEN** 租户两 scope 均未配置,且用户具备既有写菜单权限
|
||||
- **THEN** 详情返回全部合法字段为可编辑,保存可更新这些字段
|
||||
|
||||
#### Scenario: 首次配置后收紧
|
||||
|
||||
- **WHEN** 管理员首次成功保存任一 scope 的 ACL
|
||||
- **THEN** 之后该租户按严格 ACL 解析可编辑字段与保存权限
|
||||
|
||||
### Requirement: 保存时服务端强制 merge
|
||||
|
||||
储存证质检保存接口 MUST 仅更新当前用户有权编辑的字段;无权字段 MUST 保留库中原值。若请求试图修改无权字段的值,系统 MUST 拒绝该请求。当用户没有任何可编辑字段时,系统 MUST 拒绝保存。
|
||||
|
||||
#### Scenario: 部分字段可写
|
||||
|
||||
- **WHEN** 用户仅对字段集合 A 有编辑权并提交包含 A 与其他字段的 payload
|
||||
- **THEN** 仅 A 中相对原值有权限的变更被写入,其他键保持原值;若其他键相对原值发生变化则整单拒绝
|
||||
|
||||
#### Scenario: 无可写字段
|
||||
|
||||
- **WHEN** 当前用户可编辑字段为空并调用保存接口
|
||||
- **THEN** 系统拒绝保存
|
||||
|
||||
### Requirement: 配置入口与主弹窗交互
|
||||
|
||||
Web 管理端储存证质检弹窗在用户具备 ACL 配置权限时,SHALL 在 footer 左侧提供「质检权限」「生产权限」入口。配置界面 SHALL 提供两个 Tab:勾选可编辑字段、配置可编辑人员。不具备配置权限的用户 MUST 看不到上述入口。不具备字段编辑权的用户打开业务弹窗时 MUST 以只读方式展示字段,且不得出现可提交业务保存的主按钮(或等价禁用)。
|
||||
|
||||
#### Scenario: 管理员可见配置按钮
|
||||
|
||||
- **WHEN** 具备 ACL 配置菜单权限的用户打开填写弹窗
|
||||
- **THEN** footer 左侧显示质检权限与生产权限按钮
|
||||
|
||||
#### Scenario: 普通填写人不可见配置
|
||||
|
||||
- **WHEN** 不具备 ACL 配置菜单权限的用户打开填写弹窗
|
||||
- **THEN** 不显示质检权限与生产权限按钮
|
||||
|
||||
#### Scenario: 三处入口一致
|
||||
|
||||
- **WHEN** 用户从客户服务、质检工单或生产工单打开同一储存证质检弹窗
|
||||
- **THEN** 字段可编辑性与配置入口可见性均按同一 ACL 与菜单规则生效
|
||||
@@ -0,0 +1,26 @@
|
||||
## 1. 数据与后端 ACL
|
||||
|
||||
- [x] 1.1 新增 `docs/sql/` 迁移:`biz_storage_cert_qc_acl`、`biz_storage_cert_qc_acl_user`(租户、软删、标准审计字段)
|
||||
- [x] 1.2 新增 ORM / CRUD:按 tenant+scope 读写字段列表与人员;保存时校验合法 field key、同步子行
|
||||
- [x] 1.3 实现当前用户可编辑字段解析(兼容模式 vs 严格模式、两 scope 并集)
|
||||
- [x] 1.4 扩展 GET 详情:返回 `editableFieldKeys`、`canConfigureAcl`、`aclStrict`
|
||||
- [x] 1.5 改造 PUT 保存为服务端 merge,无权字段变更拒绝,无可写字段拒绝
|
||||
- [x] 1.6 新增 ACL GET/PUT API,鉴权独立配置菜单码
|
||||
- [x] 1.7 补充/调整 `backend/tests/test_sample_storage_cert_qc.py`(及 ACL 用例)覆盖兼容、严格、并集、拒绝篡改
|
||||
|
||||
## 2. Web 主弹窗与配置弹窗
|
||||
|
||||
- [x] 2.1 按已确认 Figma 原型调整 `storage-cert-qc-dialog` footer(左侧配置按钮、右侧取消/确定)与字段只读态
|
||||
- [x] 2.2 新增 ACL 配置弹窗(质检/生产):Tab1 分组勾选字段,Tab2 选人,保存调 ACL API
|
||||
- [x] 2.3 接入 API 客户端与菜单码;无配置权限不展示入口;无可写字段隐藏业务确定
|
||||
- [x] 2.4 核对客户服务 / 质检工单 / 生产工单三处入口共用行为
|
||||
|
||||
## 3. 权限种子与文档回写
|
||||
|
||||
- [x] 3.1 增加配置菜单码种子/SQL(命名与路由约定一致),说明仅管理员授予
|
||||
- [ ] 3.2 工单回写:OpenSpec 路径、Figma 链接、验收要点;原型确认结论
|
||||
|
||||
## 4. 验证
|
||||
|
||||
- [x] 4.1 在任务 worktree 运行受影响后端单元测试并记录结果
|
||||
- [x] 4.2 源码级对照已确认原型(footer 布局、双 Tab、按钮主次、只读态)
|
||||
@@ -0,0 +1,27 @@
|
||||
import request from '@/utils/http'
|
||||
|
||||
export type SampleVoidTarget = {
|
||||
receptionSource: 'cell_storage' | 'research_donation'
|
||||
sampleId?: string
|
||||
sampleCode?: string
|
||||
protocolId?: string
|
||||
}
|
||||
|
||||
export type VoidBusinessSamplePayload = SampleVoidTarget & {
|
||||
voidDesc: string
|
||||
}
|
||||
|
||||
export type VoidBusinessSampleResult = {
|
||||
id: string
|
||||
sampleCode: string
|
||||
sampleStatus: string
|
||||
voidDate: string
|
||||
voidDesc: string
|
||||
}
|
||||
|
||||
export function fetchVoidBusinessSample(data: VoidBusinessSamplePayload) {
|
||||
return request.put<VoidBusinessSampleResult>({
|
||||
url: '/web/admin/business-samples/void',
|
||||
data
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import request from '@/utils/http'
|
||||
|
||||
export type LabSampleProcessTabKey =
|
||||
| 'cell_hsc'
|
||||
| 'donation_hsc'
|
||||
| 'cell_msc'
|
||||
| 'donation_msc'
|
||||
|
||||
export interface LabSampleProcessListParams {
|
||||
tabKey: LabSampleProcessTabKey
|
||||
page?: number
|
||||
pageSize?: number
|
||||
labStorageCode?: string
|
||||
motherName?: string
|
||||
createTimeStart?: string
|
||||
createTimeEnd?: string
|
||||
}
|
||||
|
||||
export function fetchLabSampleProcessList(params: LabSampleProcessListParams) {
|
||||
return request.get<{
|
||||
list: Record<string, unknown>[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
tabKey: string
|
||||
supplementKeys: string[]
|
||||
}>({
|
||||
url: '/web/admin/lab-sample-process/list',
|
||||
params
|
||||
})
|
||||
}
|
||||
|
||||
export function fetchLabSampleProcessSupplement(labStorageCode: string) {
|
||||
return request.get<{
|
||||
labStorageCode?: string
|
||||
payload?: Record<string, string>
|
||||
remark?: string
|
||||
}>({
|
||||
url: '/web/admin/lab-sample-process/supplement',
|
||||
params: { labStorageCode }
|
||||
})
|
||||
}
|
||||
|
||||
export function saveLabSampleProcessSupplement(body: {
|
||||
labStorageCode: string
|
||||
receptionSource: string
|
||||
sampleTypeName: string
|
||||
payload: Record<string, string>
|
||||
remark?: string
|
||||
}) {
|
||||
return request.put({
|
||||
url: '/web/admin/lab-sample-process/supplement',
|
||||
data: body
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import request from '@/utils/http'
|
||||
|
||||
export type LabSampleDataset = 'hsc' | 'ubmc' | 'msc'
|
||||
|
||||
export interface LabSampleFieldMeta {
|
||||
key: string
|
||||
label: string
|
||||
dept: 'market' | 'production' | 'qc'
|
||||
source: string
|
||||
}
|
||||
|
||||
export interface LabSampleAcl {
|
||||
canList?: boolean
|
||||
isManager?: boolean
|
||||
editableDepts?: string[]
|
||||
deptFlags?: Record<string, boolean>
|
||||
}
|
||||
|
||||
export function fetchLabSampleMeta(dataset: LabSampleDataset) {
|
||||
return request.get<{
|
||||
dataset: LabSampleDataset
|
||||
label: string
|
||||
fields: LabSampleFieldMeta[]
|
||||
acl: LabSampleAcl
|
||||
}>({
|
||||
url: `/web/admin/lab-sample-processing/meta/${dataset}`
|
||||
})
|
||||
}
|
||||
|
||||
export function fetchLabSampleList(
|
||||
dataset: LabSampleDataset,
|
||||
params: {
|
||||
keyword?: string
|
||||
dateFrom?: string
|
||||
dateTo?: string
|
||||
page?: number
|
||||
pageSize?: number
|
||||
}
|
||||
) {
|
||||
return request.get<{
|
||||
list: Record<string, any>[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
fields: LabSampleFieldMeta[]
|
||||
acl: LabSampleAcl
|
||||
}>({
|
||||
url: `/web/admin/lab-sample-processing/${dataset}/list`,
|
||||
params
|
||||
})
|
||||
}
|
||||
|
||||
export function updateLabSampleRow(
|
||||
dataset: LabSampleDataset,
|
||||
sampleCode: string,
|
||||
payload: Record<string, any>
|
||||
) {
|
||||
return request.put<Record<string, any>>({
|
||||
url: `/web/admin/lab-sample-processing/${dataset}/${encodeURIComponent(sampleCode)}`,
|
||||
data: { payload }
|
||||
})
|
||||
}
|
||||
|
||||
export function exportLabSampleUrl(
|
||||
dataset: LabSampleDataset,
|
||||
params: { keyword?: string; dateFrom?: string; dateTo?: string }
|
||||
) {
|
||||
const q = new URLSearchParams()
|
||||
if (params.keyword) q.set('keyword', params.keyword)
|
||||
if (params.dateFrom) q.set('dateFrom', params.dateFrom)
|
||||
if (params.dateTo) q.set('dateTo', params.dateTo)
|
||||
const qs = q.toString()
|
||||
return `/api/web/admin/lab-sample-processing/${dataset}/export${qs ? `?${qs}` : ''}`
|
||||
}
|
||||
@@ -17,6 +17,10 @@ export interface ProductionWorkOrderItem {
|
||||
workOrderType?: string
|
||||
protocolNo?: string
|
||||
sampleCode?: string
|
||||
sampleStatus?: string
|
||||
voidDesc?: string
|
||||
protocolSampleId?: string
|
||||
collectionProtocolId?: string
|
||||
receptionSource?: string
|
||||
receptionSourceLabel?: string
|
||||
sampleTypeName?: string
|
||||
|
||||
@@ -100,6 +100,8 @@ export type QcWorkOrder = {
|
||||
collectionProtocolId: string
|
||||
protocolNo: string
|
||||
sampleCode: string
|
||||
sampleStatus?: string
|
||||
voidDesc?: string
|
||||
labStorageCode?: string
|
||||
receptionSource?: string
|
||||
receptionSourceLabel?: string
|
||||
@@ -141,6 +143,8 @@ export type QcWorkOrder = {
|
||||
patientName?: string
|
||||
/** 入库工单(细胞存储/科研捐赠):母亲姓名 */
|
||||
motherName?: string
|
||||
/** 协议单母血采集时间;未录入时为空,前端展示为 — */
|
||||
maternalBloodCollectTime?: string
|
||||
/** 入库工单(细胞存储/科研捐赠):新生儿姓名 */
|
||||
newbornName?: string
|
||||
/** 出库工单:当前为第几次输注计划 */
|
||||
|
||||
@@ -5,6 +5,8 @@ export type SampleFreightItem = {
|
||||
sampleId: string
|
||||
protocolId?: string
|
||||
sampleCode?: string
|
||||
sampleStatus?: string
|
||||
voidDesc?: string
|
||||
protocolNo?: string
|
||||
sampleTypeName?: string
|
||||
motherName?: string
|
||||
|
||||
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user