Compare commits

...
Author SHA1 Message Date
zlwuandCursor 3e32ba9085 chore(scripts): 增加合同重复单与接收下游补建修复脚本
供运维 dry-run/--apply 修历史数据,不改日常接口路径。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-12-02 15:21:27 +08:00
zlwuandCursor f843ad917a feat(qc): 编辑接收时同步改写下游实验室入库编码副本
避免只改接收表编码后,生产/质检/库位等关联副本仍保留旧码。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-12-02 15:21:26 +08:00
cykj bb9d46deb3 Merge branch 'codex/task-assign-filter-refresh-8633c5f0f5b1' into V2.0 2026-12-02 14:34:50 +08:00
cykjandCursor f50c55f7b6 fix(ops): 降低 SQL/请求日志噪声并改善 500 恢复
SQL 回显与 DEBUG 解耦;API 请求日志按字节截断并失败降级;可恢复初始化错误不永久锁死,500 页可重试;修复生产任务 in_ 多余 subquery;补充本地登录态清理页。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-12-01 17:58:49 +08:00
cykjandCursor d7611a1bd6 fix(web-admin): 历史归属维护列表支持每页条数选择
表格下方分页增加 10/20/30/50 可选,默认每页 10 条。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-12-01 16:51:40 +08:00
cykjandCursor 608a225c78 fix(web-admin): 质检工单与我的任务列表默认每页 10 条
两页共用 useQcWorkOrderTabPage,将默认 pageSize 从 100 改为 10。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-12-01 16:46:45 +08:00
cykjandCursor dfcef6f81f feat(qc): 工单级附件与取消第三方检测材料必填
质检工单卡片右上角可上传/查看附件;第三方任务材料改为选填,校验与前端必填一并取消。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-12-01 16:36:18 +08:00
cykj 7792c28893 feat(qc): 样本接收已接收支持按样本类型与是否废弃筛选
已接收列表增加 sampleTypeId、isVoided 查询参数与前端检索栏,便于质检进一步筛选样本。
2026-12-01 11:24:01 +08:00
cykjandCursor c22a0d1eb0 feat(market): 完善临床科研与委托加工上线能力
补齐项目组负责人审批、费用信息、合作客户、生产出库菜单、申请单号 LCKY 前缀及配套 SQL 迁移,并同步相关前后端与单测。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-30 18:51:37 +08:00
cykjandCursor 7a3c58ed99 fix(web-admin): refresh assignment filter project options after save
归属调整成功后递增 ProjectSelect refreshKey,立即重拉筛选区项目组/项目选项。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-25 15:55:13 +08:00
cykjandCursor d2f37985cb fix(web-admin): refresh assignment filter project options after save
归属调整成功后递增 ProjectSelect refreshKey,立即重拉筛选区项目组/项目选项。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-25 15:51:00 +08:00
cykjandCursor 9b5e68f4ae feat(market): 新增委托加工业务并复用临床科研流程
独立 biz_type=contract_processing,申请/缴费/出库与临床科研共用逻辑;
业务子类型支持胎盘冻干粉/脂肪外泌体/NK/MSC/其他自定义,并补充菜单与生产质检 Tab。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-23 12:28:23 +08:00
cykj 964384108a fix(qc): 我的质检任务关键词与工单列表口径对齐 (#168)
fix(qc): 我的质检任务关键词与工单列表口径对齐

Merge pull request #168 from codex/issue-167-mine-kw-filter-88f5de9f0988
2026-11-20 22:53:45 +00:00
zlwuandCursor 5a011926d7 fix(qc): 我的质检任务关键词与工单列表口径对齐
抽取共用关键词条件,mine 接口在保留任务号/检测项外,按工单号、
协议号、入库编码、母亲姓名、出库申请字段等检索,避免占位符失效。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-21 06:52:36 +08:00
cykj 0ac8c924aa fix(qc): 科研捐赠协议状态空选不限制,mine 请求带上过滤 (#166)
fix(qc): 科研捐赠协议状态空选不限制,mine 请求带上过滤

Merge pull request #166 from codex/issue-165-qc-protocol-filter-4d4a72f74c72
2026-11-20 22:35:08 +00:00
zlwuandCursor 2bc20e695f fix(qc): 科研捐赠协议状态空选不限制,mine 请求带上过滤
空协议状态改为不限制而非无结果,避免搜索像失效;我的质检任务
mine 接口与前端请求补传 protocolStatus,与质检工单列表语义对齐。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-21 06:33:51 +08:00
zlwu 95b07639e8 Merge branch 'codex/issue-prod-cell-outbound-5ff2a9ccf69c' into V2.0 2026-11-20 17:05:47 +08:00
zlwuandCursor f3672d3cc2 feat(production): 临床科研出库细胞改由生产确认
市场出库交接对 basic_experiment 保留细胞只读并不改库存;生产工单新增确认出库细胞 API/弹窗,从细胞产品库勾选并联动已售状态。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 17:03:45 +08:00
zlwu 4de69c37ff Merge branch 'codex/issue-clinical-research-channel-5d20f51468ed' into V2.0 2026-11-20 16:06:37 +08:00
zlwuandCursor 9242ed0538 feat(pilot): 临床科研申请单增加必填渠道
开通 showChannel,保存校验并回写 channel_id/name;表单/列表/详情展示渠道,不绑定服务订单。用户确认免除 Figma。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 16:05:05 +08:00
zlwu 2e741b1284 Merge branch 'codex/issue-research-category-552c89fcb0a6' into V2.0 2026-11-20 15:52:47 +08:00
zlwuandCursor 6b1bf8a1d2 feat(pilot): 临床科研申请单新增业务类型字段
在申请单信息中增加 researchCategory(生物新技术临床科研/临床课题联合申报/生物制药研发),贯通 SQL、后端校验与 Web 表单/列表/详情;用户确认免除 Figma。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 15:51:19 +08:00
cykj ef3e015ff9 Merge pull request 'fix(web-admin): 项目业务类型下拉去掉中试服务可选 (#162)' (#163) from codex/issue-162-hide-project-pilot-7d830f6b021e into V2.0
fix(web-admin): 项目业务类型下拉去掉中试服务可选 (#162)

Merged from PR #163
2026-11-20 07:17:18 +00:00
zlwuandCursor a598b17ab9 fix(web-admin): 项目业务类型下拉去掉中试服务可选 (#162)
新建不可选中试;旧项目已含 pilot_service 时编辑仍展示该选项。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 15:15:54 +08:00
cykjandCursor f7890f5560 Merge pull request 'refactor: 将基础实验展示名统一改为临床科研' (#155) from codex/issue-rename-basic-experiment-96cc7a73d023 into V2.0
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 15:05:02 +08:00
cykj 6ea3aed8db Merge pull request 'fix(web-admin): 隐藏生产/质检中试服务 Tab 并从「所有」排除 (#160)' (#161) from codex/issue-160-hide-pilot-tabs-8fb0018cdfea into V2.0
fix(web-admin): 隐藏生产/质检中试服务 Tab 并从「所有」排除 (#160)

Merged from PR #161
2026-11-20 06:51:05 +00:00
zlwuandCursor 8349b0ce73 fix(web-admin): 隐藏生产/质检中试服务 Tab 并从「所有」排除 (#160)
客户已下线中试业务:侧栏不再展示中试 Tab,前端在「所有」列表过滤出库中试数据(含 bizType 缺省)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 14:48:58 +08:00
cykj 85fe63fa9f fix(web-admin): 下线市场侧栏中试服务菜单 (#158)
fix(web-admin): 下线市场侧栏中试服务菜单 (#158)

Merge pull request #159
2026-11-20 06:35:05 +00:00
zlwuandCursor 77cdeede15 fix(web-admin): 下线市场侧栏中试服务菜单
超管在 frontend 模式下走静态路由全量展示,仅解绑 sys_role_menu 无效;同步移除 sqxp/STATIC_MENU_TREE 并软删对应 sys_menu。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 14:33:31 +08:00
cykj 4dc352e4f4 fix(sql): 解除市场中试服务菜单与角色绑定 (#156)
fix(sql): 解除市场中试服务菜单与角色绑定 (#156)

Merge pull request #157
2026-11-20 06:26:18 +00:00
zlwuandCursor c5f26912bd fix(sql): 解除市场中试服务菜单与角色绑定
软删市场→中试服务目录及其全部子菜单/按钮在 sys_role_menu 上的有效授权,菜单本身保留,避免误伤其他业务线下的同名菜单。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 14:24:39 +08:00
zlwuandCursor e85645a649 refactor: 将基础实验展示名统一改为临床科研
保留 basic_experiment 等内部编码与业务逻辑,全量替换用户可见及源码中文;新增 sys_menu REPLACE 迁移(不改 perms/path)。Gitea 工单因凭据 401 待补关联。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 13:51:27 +08:00
cykj 5ec997228d Merge pull request 'feat(qc): 修改记录同次提交合并节点并附件化展示 (#153)' (#154) from codex/issue-153-chg-group-fc14c4ae0ee7 into V2.0
continuous-integration/drone/tag Build is passing
feat(qc): 修改记录同次提交合并节点并附件化展示 (#153)\n\nMerge pull request #154
2026-11-20 05:25:22 +00:00
zlwu fb4bceb6b0 merge(V2.0): 同步集成分支后再合入 #153 2026-11-20 13:24:46 +08:00
zlwuandCursor cc17ac2425 feat(qc): 修改记录同次提交合并节点并附件化展示
批量保存写入 operateBatchId;弹窗按批次合并时间线,检测材料复用附件只读组件。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 13:23:26 +08:00
zlwuandCursor 70ebd4eff7 feat(web-admin): 市场侧栏新增器械销售菜单与施工中占位页
在市场模块末位注册器械销售目录及三类/二类医疗器械、化妆品子路由,同步后端静态菜单与 SQL 迁移写入 sys_menu 并向已有市场权限角色授权;子页面暂用统一施工中占位。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 13:17:02 +08:00
cykj 4d4856d4c2 Merge pull request 'fix(qc): 修改记录图标、空列表与弹窗尺寸 (#151)' (#152) from codex/issue-151-qc-hist-icon-7be0e4fa7247 into V2.0
fix(qc): 修改记录图标、空列表与弹窗尺寸 (#151)

Merge pull request #152
2026-11-20 03:57:14 +00:00
zlwuandCursor fb67f3dbd7 fix(web-admin): 放大质检修改记录弹窗宽高
验收反馈:弹窗过小;宽度 560→800,正文区 min-height 480 并限制可滚动高度。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 11:55:26 +08:00
zlwuandCursor 38bad4232a fix(qc): 修改记录批量查询避免路由误匹配并空列表返回
/qc-tasks/result-change-logs 须先于 /qc-tasks/{task_id} 注册;
无留痕时返回 [],不再因路径被当成任务 ID 报「任务不存在」。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 11:53:13 +08:00
zlwuandCursor e396b1a6eb fix(web-admin): 质检任务卡片修改记录改为右上角图标
验收反馈 #151:去掉底部文字按钮,改用 Clock 图标固定在卡片右上角。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 11:51:20 +08:00
cykj 7640052c96 Merge pull request 'feat(qc): 检测结果默认已完成/通过并记录修改历史 (#148/#149)' (#150) from codex/issue-148-qc-result-hist-dd33d3d3b407 into V2.0
feat(qc): 检测结果默认已完成/通过并记录修改历史 (#148/#149)

Closes related delivery for #148 #149 via PR.
2026-11-20 03:41:06 +00:00
168 changed files with 13066 additions and 1483 deletions

No files matched your search

+3 -1
View File
@@ -17,6 +17,8 @@ SECRET_KEY=
# 应用配置示例
# APP_NAME=陇耘鲜达
# DEBUG=true
# SQL 回显与 DEBUG 解耦;需要排查 SQL 时再打开
# SQLALCHEMY_ECHO=false
# 浏览器跨域:若设置 BACKEND_CORS_ORIGINS,须为 JSON 数组,会整体覆盖代码默认值,例如:
# BACKEND_CORS_ORIGINS=["http://localhost:5173","http://localhost:3006","http://127.0.0.1:3006"]
@@ -86,7 +88,7 @@ SECRET_KEY=
# WX_MP_TPL_PROGRESS_FIELD_APPROVER=thing6
# WX_MP_TPL_PROGRESS_FIELD_RESULT=const4
# WX_MP_TPL_PROGRESS_FIELD_TIME=time11
# 基础实验交付日前一天提醒(出库提醒模板)
# 临床科研交付日前一天提醒(出库提醒模板)
# WX_MP_TEMPLATE_BASIC_EXPERIMENT_DELIVERY=oQNU3t0Q5kwc4KPJ8Z6yPA-k6qlsH9pikSCIb4eAwgM
# WX_MP_TPL_BE_DELIVERY_FIELD_CUSTOMER=thing6
# WX_MP_TPL_BE_DELIVERY_FIELD_PRODUCT=thing10
+130
View File
@@ -15,12 +15,14 @@ from app.crud import collection_region as region_svc
from app.crud import collection_protocol as collection_protocol_svc
from app.crud import collection_protocol_no as protocol_no_svc
from app.crud import customer as customer_svc
from app.crud import partner_customer as partner_customer_svc
from app.crud import sample_code as sample_code_svc
from app.models.models import (
BizCellSampleType,
BizCollectionProtocolNo,
BizCollectionRegion,
BizCustomer,
BizPartnerCustomer,
BizSampleCode,
SysUser,
)
@@ -218,6 +220,134 @@ async def delete_customer(
return error_response(400, str(e))
# ---------------------------------------------------------------------------
# 合作客户(临床科研 / 委托加工)
# ---------------------------------------------------------------------------
class PartnerCustomerCreateBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
customer_name: str = Field(..., alias="customerName")
customer_contact: str = Field(..., alias="customerContact")
customer_phone: str = Field(..., alias="customerPhone")
order_num: Optional[int] = Field(0, alias="orderNum")
remark: Optional[str] = None
class PartnerCustomerUpdateBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
customer_name: Optional[str] = Field(None, alias="customerName")
customer_contact: Optional[str] = Field(None, alias="customerContact")
customer_phone: Optional[str] = Field(None, alias="customerPhone")
order_num: Optional[int] = Field(None, alias="orderNum")
remark: Optional[str] = None
@router.get("/partner-customers")
async def list_partner_customers(
page: int = Query(1, ge=1),
pageSize: int = Query(10, ge=1, le=200, alias="pageSize"),
keyword: Optional[str] = None,
user: dict = Depends(require_menu_code("biz:customer:list")),
db: Session = Depends(get_db),
):
tenant_no = _get_tenant_no(db, user)
query = db.query(BizPartnerCustomer).filter(
BizPartnerCustomer.del_flag == 0,
BizPartnerCustomer.tenant_no == tenant_no,
)
if keyword:
kw = keyword.strip()
if kw:
like = f"%{kw}%"
query = query.filter(
or_(
BizPartnerCustomer.customer_name.like(like),
BizPartnerCustomer.customer_contact.like(like),
BizPartnerCustomer.customer_phone.like(like),
)
)
query = apply_data_scope(query, BizPartnerCustomer, user, db, tenant_no)
total = query.count()
items = (
query.order_by(BizPartnerCustomer.create_time.desc())
.offset((page - 1) * pageSize)
.limit(pageSize)
.all()
)
result_list = [partner_customer_svc._row_to_dict(r) for r in items]
tp = partner_customer_svc.total_pages(total, pageSize)
return success_response(
{"list": result_list, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp}
)
@router.post("/partner-customers")
async def create_partner_customer(
body: PartnerCustomerCreateBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
obj = partner_customer_svc.create_partner_customer(
db,
customer_name=body.customer_name,
customer_contact=body.customer_contact,
customer_phone=body.customer_phone,
tenant_no=tenant_no,
order_num=body.order_num,
remark=body.remark,
user_id=user.get("user_id"),
create_dept_id=user.get("dept_id") or "",
)
return success_response(partner_customer_svc._row_to_dict(obj), message="创建成功")
except ValueError as e:
return error_response(400, str(e))
@router.put("/partner-customers/{customer_id}")
async def update_partner_customer(
customer_id: str,
body: PartnerCustomerUpdateBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
payload: dict[str, Any] = body.model_dump(exclude_unset=True, by_alias=False)
obj = partner_customer_svc.update_partner_customer(
db,
customer_id,
customer_name=payload.get("customer_name"),
customer_contact=payload.get("customer_contact"),
customer_phone=payload.get("customer_phone"),
order_num=payload.get("order_num"),
remark=payload.get("remark"),
user_id=user.get("user_id"),
tenant_no=tenant_no,
)
return success_response(partner_customer_svc._row_to_dict(obj), message="更新成功")
except ValueError as e:
return error_response(400, str(e))
@router.delete("/partner-customers/{customer_id}")
async def delete_partner_customer(
customer_id: str,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
partner_customer_svc.soft_delete_partner_customer(db, customer_id, tenant_no=tenant_no)
return success_response(None, message="删除成功")
except ValueError as e:
return error_response(400, str(e))
# ---------------------------------------------------------------------------
# 细胞样本类型
# ---------------------------------------------------------------------------
+178 -36
View File
@@ -7,7 +7,7 @@ from app.core.response import success_response
router = APIRouter(prefix="/web/menu", tags=["菜单管理"])
# 与 web-admin/src/router/modules/sqxp.ts 一致:6 个一级菜单分组
# 市场二级顺序:存储服务、科研捐赠、市场基础信息、中试服务、基础实验
# 市场二级顺序:存储服务、科研捐赠、市场基础信息、临床科研、器械销售
STATIC_MENU_TREE = [
{
"id": "TOP00000000000000000000000000006",
@@ -199,7 +199,7 @@ STATIC_MENU_TREE = [
],
},
# 市场基础信息(前段:存储/捐赠相关;后段:中试/基础实验相关)
# 市场基础信息(前段:存储/捐赠相关;后段:中试/临床科研相关)
{
"id": "MKT00000000000000000000000000001",
"name": "MarketInfo",
@@ -298,44 +298,14 @@ STATIC_MENU_TREE = [
],
},
# 中试服务
{
"id": "PIL00000000000000000000000000001",
"name": "PilotService",
"path": "pilot-service",
"component": "",
"meta": {
"title": "中试服务",
"icon": "ri:flask-line",
"keepAlive": False,
"roles": ["admin"],
},
"children": [
{
"id": "80000000000000000000000000000010",
"name": "PilotApplication",
"path": "pilot-application",
"component": "/pilot-service/pilot-application/index",
"meta": {"title": "中试服务申请单", "keepAlive": True, "menuCode": "pilot-service:pilot-application:list"},
},
{
"id": "PIL00000000000000000000000000004",
"name": "PilotOutboundRelease",
"path": "outbound-release-review",
"component": "/pilot-service/outbound-release-review/index",
"meta": {"title": "出库放行审核", "keepAlive": True, "menuCode": "pilot-service:outbound-release-review:list"},
},
],
},
# 基础实验
# 临床科研(与 sqxp.ts / 委托加工成对:申请、审批、费用、出库放行)
{
"id": "BEX00000000000000000000000000001",
"name": "BasicExperiment",
"path": "basic-experiment",
"component": "",
"meta": {
"title": "基础实验",
"title": "临床科研",
"icon": "ri:flask-line",
"keepAlive": False,
"roles": ["admin"],
@@ -347,11 +317,35 @@ STATIC_MENU_TREE = [
"path": "application",
"component": "/pilot-service/pilot-application/index",
"meta": {
"title": "基础实验申请单",
"title": "临床科研申请单",
"keepAlive": True,
"menuCode": "basic-experiment:application:list",
},
},
{
"id": "BEX00000000000000000000000000006",
"name": "BasicExperimentApproval",
"path": "approval",
"component": "/pilot-service/pilot-application/index",
"meta": {
"title": "临床科研审批",
"keepAlive": True,
"menuCode": "basic-experiment:approval:list",
"bizType": "basic_experiment",
"approvalOnly": True,
},
},
{
"id": "BEX00000000000000000000000000005",
"name": "BasicExperimentFeeInfo",
"path": "fee-info",
"component": "/pilot-service/fee-info/index",
"meta": {
"title": "费用信息",
"keepAlive": True,
"menuCode": "basic-experiment:fee-info:list",
},
},
{
"id": "BEX00000000000000000000000000003",
"name": "BasicExperimentPaymentConfirm",
@@ -360,6 +354,7 @@ STATIC_MENU_TREE = [
"meta": {
"title": "缴退费财务确认",
"keepAlive": True,
"isHide": True,
"menuCode": "basic-experiment:payment-confirm:list",
},
},
@@ -375,7 +370,128 @@ STATIC_MENU_TREE = [
},
},
],
}
},
# 委托加工(复用临床科研页面,bizType=contract_processing)
{
"id": "CPG00000000000000000000000000001",
"name": "ContractProcessing",
"path": "contract-processing",
"component": "",
"meta": {
"title": "委托加工",
"icon": "ri:tools-line",
"keepAlive": False,
"roles": ["admin"],
},
"children": [
{
"id": "CPG00000000000000000000000000002",
"name": "ContractProcessingApplication",
"path": "application",
"component": "/pilot-service/pilot-application/index",
"meta": {
"title": "委托加工申请单",
"keepAlive": True,
"menuCode": "contract-processing:application:list",
},
},
{
"id": "CPG00000000000000000000000000006",
"name": "ContractProcessingApproval",
"path": "approval",
"component": "/pilot-service/pilot-application/index",
"meta": {
"title": "委托加工审批",
"keepAlive": True,
"menuCode": "contract-processing:approval:list",
"bizType": "contract_processing",
"approvalOnly": True,
},
},
{
"id": "CPG00000000000000000000000000005",
"name": "ContractProcessingFeeInfo",
"path": "fee-info",
"component": "/pilot-service/fee-info/index",
"meta": {
"title": "费用信息",
"keepAlive": True,
"menuCode": "contract-processing:fee-info:list",
},
},
{
"id": "CPG00000000000000000000000000003",
"name": "ContractProcessingPaymentConfirm",
"path": "payment-confirm",
"component": "/pilot-service/clinical-payment-confirm/index",
"meta": {
"title": "缴退费财务确认",
"keepAlive": True,
"isHide": True,
"menuCode": "contract-processing:payment-confirm:list",
},
},
{
"id": "CPG00000000000000000000000000004",
"name": "ContractProcessingOutboundRelease",
"path": "outbound-release-review",
"component": "/pilot-service/outbound-release-review/index",
"meta": {
"title": "出库放行审核",
"keepAlive": True,
"menuCode": "contract-processing:outbound-release-review:list",
},
},
],
},
# 器械销售(市场侧栏末位)
{
"id": "DEV00000000000000000000000000001",
"name": "DeviceSales",
"path": "device-sales",
"component": "",
"meta": {
"title": "器械销售",
"icon": "ri:shopping-bag-3-line",
"keepAlive": False,
"roles": ["admin"],
},
"children": [
{
"id": "DEV00000000000000000000000000002",
"name": "DeviceSalesClassIii",
"path": "class-iii",
"component": "/device-sales/under-construction/index",
"meta": {
"title": "三类医疗器械",
"keepAlive": False,
"menuCode": "device-sales:class-iii:list",
},
},
{
"id": "DEV00000000000000000000000000003",
"name": "DeviceSalesClassIi",
"path": "class-ii",
"component": "/device-sales/under-construction/index",
"meta": {
"title": "二类医疗器械",
"keepAlive": False,
"menuCode": "device-sales:class-ii:list",
},
},
{
"id": "DEV00000000000000000000000000004",
"name": "DeviceSalesCosmetics",
"path": "cosmetics",
"component": "/device-sales/under-construction/index",
"meta": {
"title": "化妆品产品",
"keepAlive": False,
"menuCode": "device-sales:cosmetics:list",
},
},
],
},
],
},
@@ -583,6 +699,32 @@ STATIC_MENU_TREE = [
"menuCode": "production:waste-output:list",
},
},
{
"id": "PRD00000000000000000000000000001",
"name": "ProductionBasicExperimentOutbound",
"path": "basic-experiment-outbound",
"component": "/pilot-service/pilot-application/index",
"meta": {
"title": "临床科研出库",
"keepAlive": True,
"menuCode": "production:basic-experiment-outbound:list",
"bizType": "basic_experiment",
"productionOutbound": True,
},
},
{
"id": "PRD00000000000000000000000000002",
"name": "ProductionContractProcessingOutbound",
"path": "contract-processing-outbound",
"component": "/pilot-service/pilot-application/index",
"meta": {
"title": "委托加工出库",
"keepAlive": True,
"menuCode": "production:contract-processing-outbound:list",
"bizType": "contract_processing",
"productionOutbound": True,
},
},
],
},
# 生产基础信息
+243 -5
View File
@@ -25,6 +25,35 @@ def _get_tenant_no(db: Session, user: dict) -> str:
return sys_user.tenant_no
def _access_pilot_application(
db: Session,
tenant_no: str,
user: dict,
app_id: str,
*,
lock: bool = False,
for_approval: bool = False,
):
"""科研类走项目组可见性;其它业务走通用数据权限。"""
q = db.query(BizPilotApplication).filter(
BizPilotApplication.id == app_id,
BizPilotApplication.tenant_no == tenant_no,
BizPilotApplication.del_flag == 0,
)
if lock:
q = q.populate_existing().with_for_update()
row = q.first()
if row is None:
raise HTTPException(404, "单据不存在或无权访问")
if pilot_application.requires_leader_approval(row.biz_type):
if not pilot_application.user_can_access_research_application(
db, tenant_no, user, row, for_approval=for_approval
):
raise HTTPException(404, "单据不存在或无权访问")
return row
return accessible_order(db, BizPilotApplication, tenant_no, user, app_id, lock=lock)
# ---------------------------------------------------------------------------
# Pydantic Schemas
# ---------------------------------------------------------------------------
@@ -53,6 +82,7 @@ class ApplicationCreateBody(BaseModel):
customer_name: Optional[str] = Field(None, alias="customerName")
customer_contact: Optional[str] = Field(None, alias="customerContact")
customer_phone: Optional[str] = Field(None, alias="customerPhone")
research_category: Optional[str] = Field(None, alias="researchCategory")
class ApplicationUpdateBody(BaseModel):
@@ -65,6 +95,7 @@ class ApplicationUpdateBody(BaseModel):
customer_name: Optional[str] = Field(None, alias="customerName")
customer_contact: Optional[str] = Field(None, alias="customerContact")
customer_phone: Optional[str] = Field(None, alias="customerPhone")
research_category: Optional[str] = Field(None, alias="researchCategory")
class PatientSaveBody(BaseModel):
@@ -206,6 +237,7 @@ class ApplicationSaveBody(BaseModel):
customer_name: Optional[str] = Field(None, alias="customerName")
customer_contact: Optional[str] = Field(None, alias="customerContact")
customer_phone: Optional[str] = Field(None, alias="customerPhone")
research_category: Optional[str] = Field(None, alias="researchCategory")
remark: Optional[str] = None
consent_form_urls: Optional[str] = Field(None, alias="consentFormUrls")
consent_attachments: Optional[list] = Field(None, alias="consentAttachments")
@@ -233,8 +265,11 @@ async def api_list_applications(
keyword: Optional[str] = Query(None, alias="keyword"),
channelId: Optional[str] = Query(None, alias="channelId"),
applicationStatus: Optional[str] = Query(None, alias="applicationStatus"),
approvalStatus: Optional[str] = Query(None, alias="approvalStatus"),
pendingMine: Optional[bool] = Query(False, alias="pendingMine"),
channelServiceOrderId: Optional[str] = Query(None, alias="channelServiceOrderId"),
bizType: Optional[str] = Query(None, alias="bizType"),
forApproval: Optional[bool] = Query(False, alias="forApproval"),
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
@@ -248,10 +283,13 @@ async def api_list_applications(
page_size=pageSize,
channel_id=channelId,
application_status=applicationStatus,
approval_status=approvalStatus,
pending_mine=bool(pendingMine),
channel_service_order_id=channelServiceOrderId,
keyword=keyword,
biz_type=bizType,
user_info=user,
for_approval=bool(forApproval),
)
return success_response(result)
@@ -263,7 +301,10 @@ async def api_get_application(
db: Session = Depends(get_db),
):
tenant_no = _get_tenant_no(db, user)
accessible_order(db, BizPilotApplication, tenant_no, user, id)
try:
_access_pilot_application(db, tenant_no, user, id)
except HTTPException as e:
return error_response(e.status_code, e.detail)
result = pilot_application.get_application(db, app_id=id, tenant_no=tenant_no)
if result is None:
return error_response(404, "申请单不存在")
@@ -287,6 +328,7 @@ async def api_create_application(
"customerName": body.customer_name,
"customerContact": body.customer_contact,
"customerPhone": body.customer_phone,
"researchCategory": body.research_category,
}
result = pilot_application.create_application(
db,
@@ -308,7 +350,7 @@ async def api_update_application(
):
try:
tenant_no = _get_tenant_no(db, user)
accessible_order(db, BizPilotApplication, tenant_no, user, body.id, lock=True)
_access_pilot_application(db, tenant_no, user, body.id, lock=True)
data = {}
if "project_id" in body.model_fields_set:
data["projectId"] = body.project_id
@@ -322,12 +364,16 @@ async def api_update_application(
data["customerContact"] = body.customer_contact
if body.customer_phone is not None:
data["customerPhone"] = body.customer_phone
if body.research_category is not None:
data["researchCategory"] = body.research_category
result = pilot_application.update_application(
db, app_id=body.id, data=data, tenant_no=tenant_no
)
return success_response(result, message="更新成功")
except ValueError as e:
return error_response(400, str(e))
except HTTPException as e:
return error_response(e.status_code, e.detail)
@router.post("/pilot-application/save")
@@ -364,6 +410,8 @@ async def api_save_application(
app_data["customerContact"] = body.customer_contact
if body.customer_phone is not None:
app_data["customerPhone"] = body.customer_phone
if body.research_category is not None:
app_data["researchCategory"] = body.research_category
if body.consent_attachments is not None:
app_data["consentAttachments"] = body.consent_attachments
elif body.consent_form_urls is not None:
@@ -375,16 +423,20 @@ async def api_save_application(
if (
not is_edit
and biz_type not in ("clinical_application", "basic_experiment")
and biz_type not in ("clinical_application", "basic_experiment", "contract_processing")
and not app_data["channelServiceOrderId"]
):
return error_response(400, "请选择渠道服务订单")
if not is_edit and biz_type == "clinical_application" and not app_data["channelId"]:
if (
not is_edit
and biz_type == "clinical_application"
and not app_data["channelId"]
):
return error_response(400, "请选择渠道")
if is_edit:
accessible_order(db, BizPilotApplication, tenant_no, user, body.id, lock=True)
_access_pilot_application(db, tenant_no, user, body.id, lock=True)
if is_edit:
app_result = pilot_application.update_application(
db,
@@ -505,6 +557,41 @@ async def api_start_application(
return error_response(400, str(e))
class ApplicationApproveBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
id: str
approval_status: str = Field(..., alias="approvalStatus")
approval_remark: Optional[str] = Field(None, alias="approvalRemark")
@router.post("/pilot-application/approve")
async def api_approve_application(
body: ApplicationApproveBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
_access_pilot_application(
db, tenant_no, user, body.id, lock=True, for_approval=True
)
result = pilot_application.approve_application(
db,
app_id=body.id,
tenant_no=tenant_no,
user_id=user.get("user_id"),
approval_status=body.approval_status,
approval_remark=body.approval_remark,
is_super_admin=pilot_application._is_super_admin_user(user),
)
return success_response(result, message="审批成功")
except ValueError as e:
return error_response(400, str(e))
except HTTPException as e:
return error_response(e.status_code, e.detail)
@router.post("/pilot-application/complete")
async def api_complete_application(
body: IdBody,
@@ -857,6 +944,32 @@ class ScheduleIdBody(BaseModel):
scheduleId: str
def _assert_schedule_app_approved(db: Session, schedule_id: str, tenant_no: str) -> None:
from app.models.models import BizPilotInfusionPlan, BizPilotInfusionSchedule
row = (
db.query(BizPilotApplication)
.join(
BizPilotInfusionPlan,
BizPilotInfusionPlan.pilot_application_id == BizPilotApplication.id,
)
.join(
BizPilotInfusionSchedule,
BizPilotInfusionSchedule.infusion_plan_id == BizPilotInfusionPlan.id,
)
.filter(
BizPilotInfusionSchedule.id == schedule_id,
BizPilotInfusionSchedule.tenant_no == tenant_no,
BizPilotInfusionSchedule.del_flag == 0,
BizPilotInfusionPlan.del_flag == 0,
BizPilotApplication.del_flag == 0,
)
.first()
)
if row:
pilot_application.assert_research_leader_approved(row)
@router.post("/pilot-infusion-schedule/create-production-work-order")
async def api_create_outbound_production(
body: ScheduleIdBody,
@@ -865,6 +978,7 @@ async def api_create_outbound_production(
):
try:
tenant_no = _get_tenant_no(db, user)
_assert_schedule_app_approved(db, body.scheduleId, tenant_no)
from app.crud import production_work_order as pwo_svc
from app.crud.qc_work_order import resolve_outbound_biz_type_for_schedule
@@ -903,6 +1017,7 @@ async def api_create_outbound_qc(
):
try:
tenant_no = _get_tenant_no(db, user)
_assert_schedule_app_approved(db, body.scheduleId, tenant_no)
from app.crud import qc_work_order as qc_svc
from app.crud.qc_work_order import resolve_outbound_biz_type_for_schedule
@@ -925,3 +1040,126 @@ async def api_create_outbound_qc(
except Exception as e:
db.rollback()
return error_response(400, str(e))
# ---------------------------------------------------------------------------
# 临床科研 / 委托加工 · 自定义业务类型
# ---------------------------------------------------------------------------
class ContractProcessingCategoryCreateBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
category_name: str = Field(..., alias="categoryName")
biz_type: str = Field(..., alias="bizType", description="basic_experiment | contract_processing")
order_num: Optional[int] = Field(None, alias="orderNum")
remark: Optional[str] = None
class ContractProcessingCategoryUpdateBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
category_name: Optional[str] = Field(None, alias="categoryName")
order_num: Optional[int] = Field(None, alias="orderNum")
remark: Optional[str] = None
@router.get("/contract-processing-categories")
async def list_contract_processing_categories(
page: int = Query(1, ge=1),
pageSize: int = Query(100, ge=1, le=200, alias="pageSize"),
keyword: Optional[str] = None,
bizType: str = Query(..., alias="bizType", description="basic_experiment | contract_processing"),
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
from app.crud import contract_processing_category as cat_svc
try:
tenant_no = _get_tenant_no(db, user)
rows, total = cat_svc.list_categories(
db,
page=page,
page_size=pageSize,
keyword=keyword,
tenant_no=tenant_no,
biz_type=bizType,
)
return success_response(
{
"list": rows,
"total": total,
"page": page,
"pageSize": pageSize,
"totalPages": cat_svc.total_pages(total, pageSize),
}
)
except ValueError as e:
return error_response(400, str(e))
@router.post("/contract-processing-categories")
async def create_contract_processing_category(
body: ContractProcessingCategoryCreateBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
from app.crud import contract_processing_category as cat_svc
try:
tenant_no = _get_tenant_no(db, user)
obj = cat_svc.create_category(
db,
category_name=body.category_name,
biz_type=body.biz_type,
tenant_no=tenant_no,
order_num=body.order_num,
remark=body.remark,
user_id=user.get("user_id"),
create_dept_id=user.get("dept_id") or "",
)
return success_response(cat_svc._row_to_dict(obj), message="创建成功")
except ValueError as e:
return error_response(400, str(e))
@router.put("/contract-processing-categories/{category_id}")
async def update_contract_processing_category(
category_id: str,
body: ContractProcessingCategoryUpdateBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
from app.crud import contract_processing_category as cat_svc
try:
tenant_no = _get_tenant_no(db, user)
payload = body.model_dump(exclude_unset=True, by_alias=False)
obj = cat_svc.update_category(
db,
category_id,
category_name=payload.get("category_name"),
order_num=payload.get("order_num"),
remark=payload.get("remark"),
user_id=user.get("user_id"),
tenant_no=tenant_no,
)
return success_response(cat_svc._row_to_dict(obj), message="更新成功")
except ValueError as e:
return error_response(400, str(e))
@router.delete("/contract-processing-categories/{category_id}")
async def delete_contract_processing_category(
category_id: str,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
from app.crud import contract_processing_category as cat_svc
try:
tenant_no = _get_tenant_no(db, user)
cat_svc.soft_delete_category(db, category_id, tenant_no=tenant_no)
return success_response(None, message="删除成功")
except ValueError as e:
return error_response(400, str(e))
+8
View File
@@ -136,6 +136,8 @@ class CellProductSpecCreateBody(BaseModel):
spec_code: str = Field(..., alias="specCode")
spec_name: str = Field(..., alias="specName")
cell_count_qianwan: float = Field(..., alias="cellCountQianwan")
fill_volume_ml: float = Field(..., alias="fillVolumeMl")
order_num: Optional[int] = Field(0, alias="orderNum")
remark: Optional[str] = None
@@ -145,6 +147,8 @@ class CellProductSpecUpdateBody(BaseModel):
spec_code: Optional[str] = Field(None, alias="specCode")
spec_name: Optional[str] = Field(None, alias="specName")
cell_count_qianwan: Optional[float] = Field(None, alias="cellCountQianwan")
fill_volume_ml: Optional[float] = Field(None, alias="fillVolumeMl")
order_num: Optional[int] = Field(None, alias="orderNum")
remark: Optional[str] = None
@@ -179,6 +183,8 @@ async def create_cell_product_spec(
db,
spec_code=body.spec_code,
spec_name=body.spec_name,
cell_count_qianwan=body.cell_count_qianwan,
fill_volume_ml=body.fill_volume_ml,
tenant_no=tenant_no,
order_num=body.order_num,
remark=body.remark,
@@ -204,6 +210,8 @@ async def update_cell_product_spec(
row_id,
spec_code=payload.get("spec_code"),
spec_name=payload.get("spec_name"),
cell_count_qianwan=payload.get("cell_count_qianwan"),
fill_volume_ml=payload.get("fill_volume_ml"),
order_num=payload.get("order_num"),
remark=payload.get("remark"),
user_id=user.get("user_id"),
+4 -4
View File
@@ -56,7 +56,7 @@ class ProjectBody(Body):
class PreviewBody(Body):
bizType: Literal['presign', 'cell_storage', 'research_donation', 'pilot_service', 'basic_experiment']
bizType: Literal['presign', 'cell_storage', 'research_donation', 'pilot_service', 'basic_experiment', 'contract_processing']
id: str
projectId: str
@@ -68,7 +68,7 @@ class Snapshot(BaseModel):
class AssignmentBody(PreviewBody):
reason: str = Field(min_length=1, max_length=512)
reason: Optional[str] = Field(default='', max_length=512)
expectedAssignments: List[Snapshot]
@@ -162,7 +162,7 @@ def records(bizType: str, page: int=Query(1, ge=1), pageSize: int=Query(20, ge=1
@router.get(PREFIX + '/statistics/records')
def statistics_records(
bizType: Literal['cell_storage', 'research_donation', 'pilot_service', 'basic_experiment'],
bizType: Literal['cell_storage', 'research_donation', 'pilot_service', 'basic_experiment', 'contract_processing'],
page: int = Query(1, ge=1), pageSize: int = Query(20, ge=1, le=200),
teamId: Optional[str] = None, projectId: Optional[str] = None,
unassigned: bool = False, status: Optional[str] = None, keyword: Optional[str] = None,
@@ -182,7 +182,7 @@ def preview(body: PreviewBody, ctx=Depends(guard('project:assignment:edit')), db
@router.get(PREFIX + '/assignments/records')
def assignment_records(
bizType: Literal['cell_storage', 'research_donation', 'pilot_service', 'basic_experiment'],
bizType: Literal['cell_storage', 'research_donation', 'pilot_service', 'basic_experiment', 'contract_processing'],
page: int = Query(1, ge=1), pageSize: int = Query(20, ge=1, le=200),
teamId: Optional[str] = None, projectId: Optional[str] = None,
unassigned: bool = False, status: Optional[str] = None, keyword: Optional[str] = None,
+31 -23
View File
@@ -449,6 +449,7 @@ class TaskCompleteWithResultBody(BaseModel):
third_party_attachments: Optional[str] = Field(None, alias="thirdPartyAttachments")
material_usages: Optional[List[Dict[str, Any]]] = Field(None, alias="materialUsages")
task_status: Optional[str] = Field(None, alias="taskStatus")
operate_batch_id: Optional[str] = Field(None, alias="operateBatchId")
@router.get("/qc-lab-test-items")
@@ -979,6 +980,7 @@ async def update_qc_work_order(
external_target_code=body.external_target_code,
work_order_status=body.work_order_status,
qc_conclusion=body.qc_conclusion,
attachments=body.attachments,
remark=body.remark,
)
db.commit()
@@ -1177,6 +1179,9 @@ async def list_my_qc_tasks(
qcBizType: Optional[str] = None,
receptionSource: Optional[str] = Query(None, alias="receptionSource"),
bizType: Optional[str] = Query(None, alias="bizType"),
protocolStatus: Optional[str] = Query(
None, alias="protocolStatus", description="协议/捐赠状态,多个用英文逗号分隔"
),
db: Session = Depends(get_db),
user: dict = Depends(require_menu_code("biz:myQcTask:list")),
):
@@ -1193,6 +1198,7 @@ async def list_my_qc_tasks(
qc_biz_type=qcBizType,
reception_source=receptionSource,
biz_type=bizType,
protocol_status=protocolStatus,
tenant_no=tenant_no,
)
return success_response(_page_payload(items, total, page, pageSize))
@@ -1235,6 +1241,29 @@ async def list_qc_tasks(
return error_response(400, str(e))
@router.get("/qc-tasks/result-change-logs")
async def list_qc_task_result_change_logs_batch(
taskIds: str = Query("", description="逗号分隔的任务ID"),
db: Session = Depends(get_db),
user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
):
"""批量查询检测结果修改记录。须注册在 /qc-tasks/{task_id} 之前,避免被当成任务 ID。"""
try:
tenant_no = _get_tenant_no(db, user)
ids = [x.strip() for x in (taskIds or "").split(",") if x.strip()]
if not ids:
return success_response([])
return success_response(
result_change_log_svc.list_task_result_change_logs_by_task_ids(
db, task_ids=ids, tenant_no=tenant_no
)
)
except PermissionError as e:
return error_response(403, str(e))
except Exception as e:
return error_response(400, str(e))
@router.get("/qc-tasks/{task_id}")
async def get_qc_task_detail(
task_id: str,
@@ -1350,26 +1379,6 @@ async def get_task_material_usages(
return error_response(400, str(e))
@router.get("/qc-tasks/result-change-logs")
async def list_qc_task_result_change_logs_batch(
taskIds: str = Query(..., description="逗号分隔的任务ID"),
db: Session = Depends(get_db),
user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
):
try:
tenant_no = _get_tenant_no(db, user)
ids = [x.strip() for x in (taskIds or "").split(",") if x.strip()]
return success_response(
result_change_log_svc.list_task_result_change_logs_by_task_ids(
db, task_ids=ids, tenant_no=tenant_no
)
)
except PermissionError as e:
return error_response(403, str(e))
except Exception as e:
return error_response(400, str(e))
@router.get("/qc-tasks/{task_id}/result-change-logs")
async def list_qc_task_result_change_logs(
task_id: str,
@@ -1378,9 +1387,7 @@ async def list_qc_task_result_change_logs(
):
try:
tenant_no = _get_tenant_no(db, user)
t = task_svc.get_task(db, task_id, tenant_no=tenant_no)
if not t:
return error_response(404, "任务不存在")
# 无任务或无留痕均返回空列表,避免前端把“暂无记录”当成错误
return success_response(
result_change_log_svc.list_task_result_change_logs(
db, task_id=task_id, tenant_no=tenant_no
@@ -1437,6 +1444,7 @@ async def complete_task_with_result(
operator_user_name=str(user.get("nickName") or user.get("nick_name") or ""),
before=before,
after=after,
operate_batch_id=body.operate_batch_id,
)
db.commit()
db.refresh(obj)
+6
View File
@@ -241,6 +241,8 @@ async def list_received_samples(
pageSize: int = Query(10, ge=1, le=100),
keyword: Optional[str] = None,
sourceType: Optional[str] = None,
sampleTypeId: Optional[str] = Query(None, alias="sampleTypeId"),
isVoided: Optional[str] = Query(None, alias="isVoided"),
receptionTimeStart: Optional[str] = Query(None, alias="receptionTimeStart"),
receptionTimeEnd: Optional[str] = Query(None, alias="receptionTimeEnd"),
db: Session = Depends(get_db),
@@ -251,6 +253,8 @@ async def list_received_samples(
items, total = sr_svc.list_received_protocol_samples(
db, page=page, page_size=pageSize, tenant_no=tenant_no, keyword=keyword,
source_type=sourceType,
sample_type_id=sampleTypeId,
is_voided=sr_svc.parse_optional_bool(isVoided),
reception_time_start=receptionTimeStart,
reception_time_end=receptionTimeEnd,
user_info=user,
@@ -258,6 +262,8 @@ async def list_received_samples(
return success_response(_page_payload(items, total, page, pageSize))
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))
View File
Whitespace-only changes.
+51
View File
@@ -0,0 +1,51 @@
"""中试/临床/科研类申请单业务类型辅助。"""
from typing import Optional
# 临床科研与委托加工共用申请/交付/缴费/出库流程
RESEARCH_LIKE_BIZ_TYPES = ("basic_experiment", "contract_processing")
BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}
APPLICATION_NO_PREFIX = {
"clinical_application": "LCSQ",
"basic_experiment": "LCKY",
"contract_processing": "WTJG",
"pilot_service": "ZSSQ",
}
# 申请单项目组负责人审批(后续规则引擎可覆盖审批人,本期固定项目组负责人)
APPROVAL_PENDING = "dsp"
APPROVAL_PASSED = "ytg"
APPROVAL_REJECTED = "yth"
APPROVAL_STATUS_LABELS = {
APPROVAL_PENDING: "待审批",
APPROVAL_PASSED: "已通过",
APPROVAL_REJECTED: "已驳回",
}
def is_research_like_biz(biz_type: Optional[str]) -> bool:
return (biz_type or "") in RESEARCH_LIKE_BIZ_TYPES
def biz_type_label(biz_type: Optional[str]) -> str:
key = biz_type or ""
return BIZ_TYPE_LABELS.get(key, key or "")
def application_no_prefix(biz_type: Optional[str]) -> str:
key = biz_type or "pilot_service"
return APPLICATION_NO_PREFIX.get(key, APPLICATION_NO_PREFIX["pilot_service"])
def requires_leader_approval(biz_type: Optional[str]) -> bool:
return is_research_like_biz(biz_type)
def is_leader_approval_passed(approval_status: Optional[str]) -> bool:
return (approval_status or "") == APPROVAL_PASSED
@@ -0,0 +1,73 @@
"""申请单业务子类型(research_category)。
临床科研保留历史三项;委托加工使用产品四项,并支持「其他」自定义文本。
"""
from typing import Optional
from app.constants.pilot_biz import is_research_like_biz
CLINICAL_RESEARCH_CATEGORY_LABELS = {
"bio_tech_clinical": "生物新技术临床科研",
"joint_topic_declare": "临床课题联合申报",
"bio_pharma_rd": "生物制药研发",
}
CONTRACT_PROCESSING_CATEGORY_LABELS = {
"placenta_freeze_dried": "胎盘冻干粉",
"adipose_exosome": "脂肪外泌体",
"nk": "NK",
"msc": "MSC",
}
# 兼容旧导入名
RESEARCH_CATEGORY_LABELS = {
**CLINICAL_RESEARCH_CATEGORY_LABELS,
**CONTRACT_PROCESSING_CATEGORY_LABELS,
}
RESEARCH_CATEGORY_CODES = tuple(RESEARCH_CATEGORY_LABELS.keys())
CUSTOM_CATEGORY_MAX_LEN = 64
def research_category_label(code: Optional[str]) -> str:
if not code:
return ""
return RESEARCH_CATEGORY_LABELS.get(code, code)
def validate_research_category(
code: Optional[str],
required: bool = False,
*,
biz_type: Optional[str] = "basic_experiment",
) -> str:
value = (code or "").strip()
if not value:
if required:
raise ValueError("请选择业务类型")
return ""
bt = biz_type or "basic_experiment"
if bt == "contract_processing":
if value in CONTRACT_PROCESSING_CATEGORY_LABELS:
return value
if len(value) > CUSTOM_CATEGORY_MAX_LEN:
raise ValueError(f"业务类型不能超过{CUSTOM_CATEGORY_MAX_LEN}个字符")
# 自定义原文;禁止占用临床科研预置码
if value in CLINICAL_RESEARCH_CATEGORY_LABELS:
raise ValueError("业务类型无效")
return value
if bt == "basic_experiment" or is_research_like_biz(bt):
if value in CLINICAL_RESEARCH_CATEGORY_LABELS:
return value
if len(value) > CUSTOM_CATEGORY_MAX_LEN:
raise ValueError(f"业务类型不能超过{CUSTOM_CATEGORY_MAX_LEN}个字符")
# 自定义原文;禁止占用委托加工预置码
if value in CONTRACT_PROCESSING_CATEGORY_LABELS:
raise ValueError("业务类型无效")
return value
if value not in RESEARCH_CATEGORY_LABELS:
raise ValueError("业务类型无效")
return value
+54 -2
View File
@@ -40,6 +40,25 @@ def _truncate(s: str, max_len: int) -> str:
return s[:max_len] + f"\n... [truncated, total {len(s)} chars]"
def _truncate_utf8_bytes(s: Optional[str], max_bytes: int) -> Optional[str]:
"""按 UTF-8 字节截断,适配 MySQL TEXT 字节上限。"""
if not s:
return s
raw = s.encode("utf-8")
if len(raw) <= max_bytes:
return s
cut = raw[:max_bytes]
while cut:
try:
text = cut.decode("utf-8")
break
except UnicodeDecodeError:
cut = cut[:-1]
else:
return None
return text + f"\n... [truncated, total {len(raw)} bytes]"
def _redact_obj(obj: Any) -> Any:
if isinstance(obj, dict):
out = {}
@@ -135,6 +154,10 @@ def _persist_log(
from app.core.utils import generate_id
from app.models.models import SysApiRequestLog
max_db = settings.API_REQUEST_LOG_DB_MAX_BYTES
req_body = _truncate_utf8_bytes(request_body, max_db)
resp_body = _truncate_utf8_bytes(response_body, max_db)
db = SessionLocal()
try:
row = SysApiRequestLog(
@@ -142,8 +165,8 @@ def _persist_log(
http_method=http_method,
path=_truncate(path, 500),
query_string=_truncate(query_string or "", 2000) or None,
request_body=request_body,
response_body=response_body,
request_body=req_body,
response_body=resp_body,
status_code=status_code,
duration_ms=duration_ms,
user_id=user_id,
@@ -161,6 +184,32 @@ def _persist_log(
except Exception as e:
logger.warning("api_request_log persist failed: %s", e)
db.rollback()
# 字段过长/字符集异常时降级为空 body,保留审计元数据
try:
row = SysApiRequestLog(
id=generate_id(),
http_method=http_method,
path=_truncate(path, 500),
query_string=_truncate(query_string or "", 2000) or None,
request_body=None,
response_body=None,
status_code=status_code,
duration_ms=duration_ms,
user_id=user_id,
username=_truncate(username or "", 100) if username else None,
role=role,
ip_address=ip_address,
user_agent=_truncate(user_agent or "", 500) if user_agent else None,
is_del=0,
create_at=datetime.now(),
create_by=None,
create_name=None,
)
db.add(row)
db.commit()
except Exception as e2:
logger.warning("api_request_log persist fallback failed: %s", e2)
db.rollback()
finally:
db.close()
@@ -180,6 +229,9 @@ def _schedule_persist_log(**kwargs) -> None:
task = loop.create_task(asyncio.to_thread(_persist_log, **kwargs))
def _on_done(t: asyncio.Task) -> None:
if t.cancelled():
# reload / shutdown 取消未完成写入任务,属预期
return
try:
t.result()
except Exception as e:
+10 -5
View File
@@ -28,6 +28,8 @@ class Settings(BaseSettings):
# 应用基础配置
APP_NAME: str = "zkxw 管理骨架"
DEBUG: bool = True
# SQLAlchemy 引擎 SQL 回显;默认关闭,避免 DEBUG=true 时终端被 SQL 刷屏
SQLALCHEMY_ECHO: bool = False
API_V1_PREFIX: str = "/api"
# 数据库配置
@@ -136,14 +138,14 @@ class Settings(BaseSettings):
WX_TEMPLATE_DELIVERY_WARNING: str = "" # 配送时效预警模板ID
# 微信服务号(OA 审批/抄送通知)
# 总开关:false 时不发送审批/抄送/申请人进度/评论@提到/基础实验交付提醒/样本采集通知模板消息
# 总开关:false 时不发送审批/抄送/申请人进度/评论@提到/临床科研交付提醒/样本采集通知模板消息
WX_MP_NOTIFY_ENABLED: bool = False
WX_MP_APPID: str = ""
WX_MP_SECRET: str = ""
WX_MP_TEMPLATE_APPROVAL: str = ""
WX_MP_TEMPLATE_CC: str = ""
WX_MP_TEMPLATE_APPLICANT_PROGRESS: str = ""
# 基础实验交付日前一天提醒(出库提醒模板)
# 临床科研交付日前一天提醒(出库提醒模板)
WX_MP_TEMPLATE_BASIC_EXPERIMENT_DELIVERY: str = (
"oQNU3t0Q5kwc4KPJ8Z6yPA-k6qlsH9pikSCIb4eAwgM"
)
@@ -171,7 +173,7 @@ class Settings(BaseSettings):
WX_MP_TPL_PROGRESS_FIELD_APPROVER: str = "thing6"
WX_MP_TPL_PROGRESS_FIELD_RESULT: str = "const4"
WX_MP_TPL_PROGRESS_FIELD_TIME: str = "time11"
# 基础实验交付提醒:客户名称/产品名称/件数/收货联系人/出库时间
# 临床科研交付提醒:客户名称/产品名称/件数/收货联系人/出库时间
WX_MP_TPL_BE_DELIVERY_FIELD_CUSTOMER: str = "thing6"
WX_MP_TPL_BE_DELIVERY_FIELD_PRODUCT: str = "thing10"
WX_MP_TPL_BE_DELIVERY_FIELD_QTY: str = "character_string8"
@@ -201,8 +203,11 @@ class Settings(BaseSettings):
# 全量 API 请求日志(中间件写入 sys_api_request_log)
API_REQUEST_LOG_ENABLED: bool = True
API_REQUEST_LOG_MAX_BODY: int = 65536
API_REQUEST_LOG_MAX_BODY_BYTES: int = 131072
# MySQL TEXT 上限约 65535 字节;按字符截断会因中文多字节溢出,默认按安全字符上限
API_REQUEST_LOG_MAX_BODY: int = 16000
API_REQUEST_LOG_MAX_BODY_BYTES: int = 48000
# 写入库时再按 UTF-8 字节截断,避免 Data too long
API_REQUEST_LOG_DB_MAX_BYTES: int = 60000
# Web API 请求/响应加密配置
API_ENCRYPT_ENABLED: bool = False
+1 -1
View File
@@ -8,7 +8,7 @@ engine = create_engine(
settings.DATABASE_URL,
pool_pre_ping=True,
pool_recycle=3600,
echo=settings.DEBUG,
echo=settings.SQLALCHEMY_ECHO,
)
# 避免 commit 后 ORM 实例自动过期,导致读取字段时回表 SELECT(高频接口会显著拖慢)
+2 -2
View File
@@ -23,14 +23,14 @@ def resolve_research_donation_protocol_status_filter(
Returns:
("in", statuses) — 按所选状态 IN 过滤
("none", []) — 显式空选择,无匹配结果
("all", []) — 显式空选择,不限制协议状态
("default", DEFAULT_QC_DONATION_PROTOCOL_STATUSES) — 未传参,与列表默认一致
"""
if protocol_status is None:
return ("default", list(DEFAULT_QC_DONATION_PROTOCOL_STATUSES))
statuses = [s.strip() for s in str(protocol_status).split(",") if s.strip()]
if not statuses:
return ("none", [])
return ("all", [])
return ("in", statuses)
_PROTOCOL_STATUS_LABELS = {
+2 -2
View File
@@ -100,14 +100,14 @@ def _enrich_payment(db: Session, row: BizPilotPayment) -> Dict[str, Any]:
"applicationNo": app_row.application_no if app_row else "",
"applicationName": app_row.application_name if app_row else "",
"channelName": app_row.channel_name if app_row else "",
"patientName": "" if app_biz == "basic_experiment" else (patient_row.patient_name if patient_row else ""),
"patientName": "" if app_biz in ("basic_experiment", "contract_processing") else (patient_row.patient_name if patient_row else ""),
"cellType": cell_type,
"specText": spec_text,
"cellTypeSpec": cell_type_spec,
"paymentAmount": float(row.amount) if row.amount else 0,
"infusionTime": schedule_row.infusion_time.strftime("%Y-%m-%d %H:%M:%S") if schedule_row and schedule_row.infusion_time else "",
}
if app_biz == "basic_experiment" and app_row:
if app_biz in ("basic_experiment", "contract_processing") and app_row:
extra["projectTitle"] = app_row.project_title or ""
extra["customerName"] = app_row.customer_name or ""
extra["customerContact"] = app_row.customer_contact or ""
@@ -0,0 +1,257 @@
"""临床科研/委托加工自定义业务类型 CRUD(biz_contract_processing_category)"""
from __future__ import annotations
import math
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy import and_, func
from sqlalchemy.orm import Session
from app.constants.research_category import (
CLINICAL_RESEARCH_CATEGORY_LABELS,
CONTRACT_PROCESSING_CATEGORY_LABELS,
CUSTOM_CATEGORY_MAX_LEN,
)
from app.core.utils import generate_uuid
from app.models.models import BizContractProcessingCategory
_DEFAULT_BIZ_TYPE = "contract_processing"
_ALLOWED_BIZ_TYPES = ("basic_experiment", "contract_processing")
_RESERVED_NAMES = {
*CONTRACT_PROCESSING_CATEGORY_LABELS.keys(),
*CONTRACT_PROCESSING_CATEGORY_LABELS.values(),
*CLINICAL_RESEARCH_CATEGORY_LABELS.keys(),
*CLINICAL_RESEARCH_CATEGORY_LABELS.values(),
"__other__",
"其他",
}
def _normalize_biz_type(biz_type: Optional[str]) -> str:
value = (biz_type or _DEFAULT_BIZ_TYPE).strip()
if value not in _ALLOWED_BIZ_TYPES:
raise ValueError("业务类型所属业务线无效")
return value
def _row_to_dict(row: BizContractProcessingCategory) -> Dict[str, Any]:
return {
"id": row.id,
"categoryName": row.category_name or "",
"bizType": getattr(row, "biz_type", None) or _DEFAULT_BIZ_TYPE,
"tenantNo": row.tenant_no,
"orderNum": row.order_num if row.order_num is not None else 0,
"remark": row.remark or "",
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
"updateTime": row.update_time.strftime("%Y-%m-%d %H:%M:%S") if row.update_time else "",
}
def _normalize_name(name: Optional[str]) -> str:
return (name or "").strip()
def _assert_valid_name(name: str) -> str:
value = _normalize_name(name)
if not value:
raise ValueError("业务类型名称不能为空")
if len(value) > CUSTOM_CATEGORY_MAX_LEN:
raise ValueError(f"业务类型不能超过{CUSTOM_CATEGORY_MAX_LEN}个字符")
if value in _RESERVED_NAMES:
raise ValueError("该名称与系统预置业务类型冲突,请更换")
return value
def _exists_name(
db: Session,
tenant_no: str,
name: str,
*,
biz_type: str,
exclude_id: Optional[str] = None,
) -> bool:
q = db.query(BizContractProcessingCategory.id).filter(
BizContractProcessingCategory.del_flag == 0,
BizContractProcessingCategory.tenant_no == tenant_no,
BizContractProcessingCategory.biz_type == biz_type,
BizContractProcessingCategory.category_name == name,
)
if exclude_id:
q = q.filter(BizContractProcessingCategory.id != exclude_id)
return q.first() is not None
def list_categories(
db: Session,
*,
page: int = 1,
page_size: int = 100,
keyword: Optional[str] = None,
tenant_no: Optional[str] = None,
biz_type: Optional[str] = None,
) -> Tuple[List[Dict[str, Any]], int]:
bt = _normalize_biz_type(biz_type)
def _filtered():
q0 = db.query(BizContractProcessingCategory).filter(
BizContractProcessingCategory.del_flag == 0,
BizContractProcessingCategory.biz_type == bt,
)
if tenant_no:
q0 = q0.filter(BizContractProcessingCategory.tenant_no == tenant_no)
kw = (keyword or "").strip()
if kw:
q0 = q0.filter(BizContractProcessingCategory.category_name.like(f"%{kw}%"))
return q0
total = (
_filtered()
.order_by(None)
.with_entities(func.count(BizContractProcessingCategory.id))
.scalar()
or 0
)
page = max(1, page)
page_size = min(max(1, page_size), 200)
rows = (
_filtered()
.order_by(
BizContractProcessingCategory.order_num.asc(),
BizContractProcessingCategory.create_time.desc(),
)
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return [_row_to_dict(x) for x in rows], int(total)
def list_all_categories(
db: Session, *, tenant_no: str, biz_type: Optional[str] = None
) -> List[Dict[str, Any]]:
bt = _normalize_biz_type(biz_type)
rows = (
db.query(BizContractProcessingCategory)
.filter(
BizContractProcessingCategory.del_flag == 0,
BizContractProcessingCategory.tenant_no == tenant_no,
BizContractProcessingCategory.biz_type == bt,
)
.order_by(
BizContractProcessingCategory.order_num.asc(),
BizContractProcessingCategory.create_time.desc(),
)
.all()
)
return [_row_to_dict(x) for x in rows]
def get_category(
db: Session, category_id: str, tenant_no: Optional[str] = None
) -> Optional[BizContractProcessingCategory]:
q = db.query(BizContractProcessingCategory).filter(
and_(
BizContractProcessingCategory.id == category_id,
BizContractProcessingCategory.del_flag == 0,
)
)
if tenant_no:
q = q.filter(BizContractProcessingCategory.tenant_no == tenant_no)
return q.first()
def create_category(
db: Session,
*,
category_name: str,
tenant_no: str = "zkxw",
biz_type: Optional[str] = None,
order_num: Optional[int] = None,
remark: Optional[str] = None,
user_id: Optional[str] = None,
create_dept_id: str = "",
commit: bool = True,
) -> BizContractProcessingCategory:
bt = _normalize_biz_type(biz_type)
name = _assert_valid_name(category_name)
if _exists_name(db, tenant_no, name, biz_type=bt):
raise ValueError("业务类型已存在")
obj = BizContractProcessingCategory(
id=generate_uuid(),
category_name=name,
biz_type=bt,
tenant_no=tenant_no,
order_num=order_num if order_num is not None else 0,
remark=(remark or "").strip() or None,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=datetime.now(),
update_by=user_id,
update_time=datetime.now(),
del_flag=0,
)
db.add(obj)
if commit:
db.commit()
db.refresh(obj)
else:
db.flush()
return obj
def update_category(
db: Session,
category_id: str,
*,
category_name: Optional[str] = None,
order_num: Optional[int] = None,
remark: Optional[str] = None,
user_id: Optional[str] = None,
tenant_no: Optional[str] = None,
) -> BizContractProcessingCategory:
obj = get_category(db, category_id, tenant_no=tenant_no)
if not obj:
raise ValueError("业务类型不存在")
bt = _normalize_biz_type(getattr(obj, "biz_type", None) or _DEFAULT_BIZ_TYPE)
if category_name is not None:
name = _assert_valid_name(category_name)
if _exists_name(db, obj.tenant_no, name, biz_type=bt, exclude_id=obj.id):
raise ValueError("业务类型已存在")
obj.category_name = name
if order_num is not None:
obj.order_num = order_num
if remark is not None:
obj.remark = remark.strip() or None
obj.update_by = user_id
obj.update_time = datetime.now()
db.add(obj)
db.commit()
db.refresh(obj)
return obj
def soft_delete_category(
db: Session,
category_id: str,
tenant_no: Optional[str] = None,
*,
commit: bool = True,
) -> None:
obj = get_category(db, category_id, tenant_no=tenant_no)
if not obj:
raise ValueError("业务类型不存在")
obj.del_flag = 1
obj.update_time = datetime.now()
db.add(obj)
if commit:
db.commit()
else:
db.flush()
def total_pages(total: int, page_size: int) -> int:
if total <= 0:
return 0
return int(math.ceil(total / float(page_size)))
+2 -1
View File
@@ -41,7 +41,8 @@ _QC_STATUS_LABELS = {
_BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "基础实验",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}
+187
View File
@@ -0,0 +1,187 @@
"""合作客户 CRUD(biz_partner_customer)"""
from __future__ import annotations
import math
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy import and_, func, or_
from sqlalchemy.orm import Session
from app.core.utils import generate_uuid
from app.models.models import BizPartnerCustomer
def _row_to_dict(row: BizPartnerCustomer) -> Dict[str, Any]:
return {
"id": row.id,
"customerName": row.customer_name or "",
"customerContact": row.customer_contact or "",
"customerPhone": row.customer_phone or "",
"tenantNo": row.tenant_no,
"orderNum": row.order_num if row.order_num is not None else 0,
"remark": row.remark or "",
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
"updateTime": row.update_time.strftime("%Y-%m-%d %H:%M:%S") if row.update_time else "",
}
def list_partner_customers(
db: Session,
*,
page: int = 1,
page_size: int = 10,
keyword: Optional[str] = None,
tenant_no: Optional[str] = None,
) -> Tuple[List[Dict[str, Any]], int]:
def _filtered():
q0 = db.query(BizPartnerCustomer).filter(BizPartnerCustomer.del_flag == 0)
if tenant_no:
q0 = q0.filter(BizPartnerCustomer.tenant_no == tenant_no)
kw = (keyword or "").strip()
if kw:
like = f"%{kw}%"
q0 = q0.filter(
or_(
BizPartnerCustomer.customer_name.like(like),
BizPartnerCustomer.customer_contact.like(like),
BizPartnerCustomer.customer_phone.like(like),
)
)
return q0
total = _filtered().order_by(None).with_entities(func.count(BizPartnerCustomer.id)).scalar() or 0
page = max(1, page)
page_size = min(max(1, page_size), 200)
rows = (
_filtered()
.order_by(BizPartnerCustomer.create_time.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return [_row_to_dict(x) for x in rows], int(total)
def get_partner_customer(
db: Session, customer_id: str, tenant_no: Optional[str] = None
) -> Optional[BizPartnerCustomer]:
q = db.query(BizPartnerCustomer).filter(
and_(BizPartnerCustomer.id == customer_id, BizPartnerCustomer.del_flag == 0)
)
if tenant_no:
q = q.filter(BizPartnerCustomer.tenant_no == tenant_no)
return q.first()
def create_partner_customer(
db: Session,
*,
customer_name: str,
customer_contact: str,
customer_phone: str,
tenant_no: str = "zkxw",
order_num: Optional[int] = None,
remark: Optional[str] = None,
user_id: Optional[str] = None,
create_dept_id: str = "",
commit: bool = True,
) -> BizPartnerCustomer:
name = (customer_name or "").strip()
contact = (customer_contact or "").strip()
phone = (customer_phone or "").strip()
if not name:
raise ValueError("客户名称不能为空")
if not contact:
raise ValueError("客户联系人不能为空")
if not phone:
raise ValueError("客户联系方式不能为空")
obj = BizPartnerCustomer(
id=generate_uuid(),
customer_name=name,
customer_contact=contact,
customer_phone=phone,
tenant_no=tenant_no,
order_num=order_num if order_num is not None else 0,
remark=(remark or "").strip() or None,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=datetime.now(),
update_by=user_id,
update_time=datetime.now(),
del_flag=0,
)
db.add(obj)
if commit:
db.commit()
db.refresh(obj)
else:
db.flush()
return obj
def update_partner_customer(
db: Session,
customer_id: str,
*,
customer_name: Optional[str] = None,
customer_contact: Optional[str] = None,
customer_phone: Optional[str] = None,
order_num: Optional[int] = None,
remark: Optional[str] = None,
user_id: Optional[str] = None,
tenant_no: Optional[str] = None,
) -> BizPartnerCustomer:
obj = get_partner_customer(db, customer_id, tenant_no=tenant_no)
if not obj:
raise ValueError("合作客户不存在")
if customer_name is not None:
name = customer_name.strip()
if not name:
raise ValueError("客户名称不能为空")
obj.customer_name = name
if customer_contact is not None:
contact = customer_contact.strip()
if not contact:
raise ValueError("客户联系人不能为空")
obj.customer_contact = contact
if customer_phone is not None:
phone = customer_phone.strip()
if not phone:
raise ValueError("客户联系方式不能为空")
obj.customer_phone = phone
if order_num is not None:
obj.order_num = order_num
if remark is not None:
obj.remark = remark.strip() or None
obj.update_by = user_id
obj.update_time = datetime.now()
db.add(obj)
db.commit()
db.refresh(obj)
return obj
def soft_delete_partner_customer(
db: Session,
customer_id: str,
tenant_no: Optional[str] = None,
*,
commit: bool = True,
) -> None:
obj = get_partner_customer(db, customer_id, tenant_no=tenant_no)
if not obj:
raise ValueError("合作客户不存在")
obj.del_flag = 1
obj.update_time = datetime.now()
db.add(obj)
if commit:
db.commit()
else:
db.flush()
def total_pages(total: int, page_size: int) -> int:
if total <= 0:
return 0
return int(math.ceil(total / float(page_size)))
+547 -60
View File
@@ -25,6 +25,17 @@ from app.models.models import (
)
from app.crud import pilot_checkup
from app.crud.collection_protocol import attachments_to_urls, urls_to_attachment_list
from app.constants.pilot_biz import (
APPROVAL_PASSED,
APPROVAL_PENDING,
APPROVAL_REJECTED,
application_no_prefix,
is_leader_approval_passed,
is_research_like_biz,
requires_leader_approval,
)
from app.constants.research_category import validate_research_category
from app.models.project_management import Project, ProjectTeam, ProjectTeamMember
# ────────────────────────────────────────────
@@ -76,12 +87,7 @@ def _release_application_no_for_soft_delete(application_no: str, row_id: str) ->
def _generate_application_no(db: Session, tenant_no: str, biz_type: str = "pilot_service") -> str:
today_str = datetime.now().strftime("%Y%m%d")
if biz_type == "clinical_application":
prefix = f"LCSQ{today_str}"
elif biz_type == "basic_experiment":
prefix = f"JCSY{today_str}"
else:
prefix = f"ZSSQ{today_str}"
prefix = f"{application_no_prefix(biz_type)}{today_str}"
existing = (
db.query(BizPilotApplication.application_no)
.filter(
@@ -114,7 +120,14 @@ def _resolve_application_attachment_payload(raw: dict) -> None:
raw["attachmentUrls"] = (raw["attachmentUrls"] or "").strip()
def _row_to_dict_application(row, db=None, tenant_no=None) -> Dict[str, Any]:
def _row_to_dict_application(
row,
db=None,
tenant_no=None,
current_user_id: Optional[str] = None,
*,
is_super_admin: bool = False,
) -> Dict[str, Any]:
tn = tenant_no or row.tenant_no
d: Dict[str, Any] = {
"id": row.id,
@@ -125,7 +138,16 @@ def _row_to_dict_application(row, db=None, tenant_no=None) -> Dict[str, Any]:
"customerName": row.customer_name or "",
"customerContact": row.customer_contact or "",
"customerPhone": row.customer_phone or "",
"researchCategory": getattr(row, "research_category", None) or "",
"applicationStatus": row.application_status or "",
"approvalStatus": getattr(row, "approval_status", None) or "",
"approvalUserId": getattr(row, "approval_user_id", None) or "",
"approvalTime": (
row.approval_time.strftime("%Y-%m-%d %H:%M:%S")
if getattr(row, "approval_time", None)
else ""
),
"approvalRemark": getattr(row, "approval_remark", None) or "",
"bizType": row.biz_type or "pilot_service",
"channelServiceOrderId": row.channel_service_order_id or "",
"channelId": row.channel_id or "",
@@ -192,6 +214,21 @@ def _row_to_dict_application(row, db=None, tenant_no=None) -> Dict[str, Any]:
d["serviceOrderNo"] = ""
d["orderType"] = ""
project_leader_uid = _project_leader_user_id(db, tenant_no, row.project_id)
team_leader_uid = _team_leader_user_id(db, tenant_no, row.project_id)
d["projectLeaderUserId"] = project_leader_uid
d["teamLeaderUserId"] = team_leader_uid
approval = (getattr(row, "approval_status", None) or "").strip()
uid = (current_user_id or "").strip()
# 项目组负责人或超管可批;待审批/已通过/已驳回均可改结论(data_scope=1 不可代批)
d["canApprove"] = bool(
requires_leader_approval(row.biz_type)
and (getattr(row, "application_status", None) or "") != "yzf"
and approval in (APPROVAL_PENDING, APPROVAL_PASSED, APPROVAL_REJECTED)
and team_leader_uid
and (is_super_admin or (uid and team_leader_uid == uid))
)
return d
@@ -318,6 +355,213 @@ def _row_to_dict_infusion_schedule(row, cell_products: Optional[List[Dict[str, A
# ────────────────────────────────────────────
def _is_super_admin_user(user_info: Optional[dict]) -> bool:
"""科研可见/审批跨组仅认超级管理员;角色 data_scope=1 不放开。"""
return bool(user_info) and (user_info.get("role") or "") == "super_admin"
def _led_team_ids(db: Session, tenant_no: str, user_id: str) -> List[str]:
rows = (
db.query(ProjectTeam.id)
.filter(
ProjectTeam.tenant_no == tenant_no,
ProjectTeam.del_flag == 0,
ProjectTeam.leader_user_id == user_id,
)
.all()
)
return [r[0] for r in rows if r[0]]
def _member_team_ids(db: Session, tenant_no: str, user_id: str) -> List[str]:
rows = (
db.query(ProjectTeamMember.team_id)
.filter(
ProjectTeamMember.tenant_no == tenant_no,
ProjectTeamMember.del_flag == 0,
ProjectTeamMember.user_id == user_id,
)
.all()
)
return [r[0] for r in rows if r[0]]
def _project_ids_for_teams(db: Session, tenant_no: str, team_ids: List[str]):
if not team_ids:
return db.query(Project.id).filter(False)
return db.query(Project.id).filter(
Project.tenant_no == tenant_no,
Project.del_flag == 0,
Project.team_id.in_(team_ids),
)
def apply_research_like_visibility(
q,
db: Session,
tenant_no: str,
user_info: Optional[dict],
*,
for_approval: bool = False,
):
"""临床科研/委托加工可见性:成员仅本人创建;项目组负责人看本项目组;仅超管全量。
审批列表(for_approval):仅项目组负责人看本项目组;成员为空;仅超管全量。
角色 data_scope=1 不视为跨组管理员。
"""
if _is_super_admin_user(user_info):
return q
uid = ((user_info or {}).get("user_id") or "").strip()
if not uid:
return q.filter(False)
led_ids = _led_team_ids(db, tenant_no, uid)
if for_approval:
if not led_ids:
return q.filter(False)
return q.filter(
BizPilotApplication.project_id.in_(
_project_ids_for_teams(db, tenant_no, led_ids)
)
)
member_ids = _member_team_ids(db, tenant_no, uid)
conditions = []
if led_ids:
conditions.append(
BizPilotApplication.project_id.in_(
_project_ids_for_teams(db, tenant_no, led_ids)
)
)
if member_ids:
conditions.append(
and_(
BizPilotApplication.create_by == uid,
BizPilotApplication.project_id.in_(
_project_ids_for_teams(db, tenant_no, member_ids)
),
)
)
if not conditions:
return q.filter(False)
return q.filter(or_(*conditions))
def user_can_access_research_application(
db: Session,
tenant_no: str,
user_info: Optional[dict],
app: BizPilotApplication,
*,
for_approval: bool = False,
) -> bool:
if not requires_leader_approval(getattr(app, "biz_type", None)):
return True
if _is_super_admin_user(user_info):
return True
uid = ((user_info or {}).get("user_id") or "").strip()
if not uid:
return False
team_leader = _team_leader_user_id(db, tenant_no, app.project_id)
if for_approval:
return bool(team_leader and team_leader == uid)
if team_leader and team_leader == uid:
return True
if (app.create_by or "").strip() != uid:
return False
# 本人创建:须仍属于该项目所在项目组(负责人或成员)
project = (
db.query(Project.team_id)
.filter(
Project.id == app.project_id,
Project.tenant_no == tenant_no,
Project.del_flag == 0,
)
.first()
)
if not project or not project[0]:
return False
team_id = project[0]
if team_id in _led_team_ids(db, tenant_no, uid):
return True
return team_id in _member_team_ids(db, tenant_no, uid)
def _require_research_project_with_leader(
db: Session, tenant_no: str, project_id: Optional[str]
) -> Project:
pid = (project_id or "").strip()
if not pid:
raise ValueError("请选择项目")
project = (
db.query(Project)
.filter(
Project.id == pid,
Project.tenant_no == tenant_no,
Project.del_flag == 0,
)
.first()
)
if not project:
raise ValueError("项目不存在")
team = (
db.query(ProjectTeam)
.filter(
ProjectTeam.id == project.team_id,
ProjectTeam.tenant_no == tenant_no,
ProjectTeam.del_flag == 0,
)
.first()
)
if not team or not (team.leader_user_id or "").strip():
raise ValueError("所选项目所属项目组未设置负责人,无法提交审批")
return project
def assert_research_leader_approved(app: BizPilotApplication) -> None:
"""未通过项目组负责人审批时,禁止开始/建交付计划/派发工单。"""
if not requires_leader_approval(getattr(app, "biz_type", None)):
return
if not is_leader_approval_passed(getattr(app, "approval_status", None)):
raise ValueError("申请单尚未通过项目组负责人审批,无法派发生产/质检工单")
def _project_leader_user_id(db: Session, tenant_no: str, project_id: Optional[str]) -> str:
if not project_id:
return ""
project = (
db.query(Project.leader_user_id)
.filter(
Project.id == project_id,
Project.tenant_no == tenant_no,
Project.del_flag == 0,
)
.first()
)
return (project[0] if project else "") or ""
def _team_leader_user_id(db: Session, tenant_no: str, project_id: Optional[str]) -> str:
if not project_id:
return ""
row = (
db.query(ProjectTeam.leader_user_id)
.join(
Project,
and_(
Project.team_id == ProjectTeam.id,
Project.tenant_no == tenant_no,
Project.del_flag == 0,
),
)
.filter(
Project.id == project_id,
ProjectTeam.tenant_no == tenant_no,
ProjectTeam.del_flag == 0,
)
.first()
)
return (row[0] if row else "") or ""
def list_applications(
db: Session,
tenant_no: str,
@@ -328,24 +572,47 @@ def list_applications(
page_size: int = 10,
channel_id: Optional[str] = None,
application_status: Optional[str] = None,
approval_status: Optional[str] = None,
pending_mine: bool = False,
channel_service_order_id: Optional[str] = None,
keyword: Optional[str] = None,
biz_type: Optional[str] = None,
for_approval: bool = False,
):
q = db.query(BizPilotApplication).filter(
BizPilotApplication.tenant_no == tenant_no,
BizPilotApplication.del_flag == 0,
)
q = filter_assignment(q, BizPilotApplication, db, tenant_no, project_id, team_id)
research_like = is_research_like_biz(biz_type)
if user_info is not None:
from app.core.data_scope import apply_data_scope
q = apply_data_scope(q, BizPilotApplication, user_info, db, tenant_no)
if research_like:
q = apply_research_like_visibility(
q, db, tenant_no, user_info, for_approval=for_approval
)
else:
from app.core.data_scope import apply_data_scope
q = apply_data_scope(q, BizPilotApplication, user_info, db, tenant_no)
if channel_id:
q = q.filter(BizPilotApplication.channel_id == channel_id)
if application_status:
statuses = [s.strip() for s in application_status.split(",") if s.strip()]
if statuses:
q = q.filter(BizPilotApplication.application_status.in_(statuses))
if approval_status:
statuses = [s.strip() for s in approval_status.split(",") if s.strip()]
if statuses:
q = q.filter(BizPilotApplication.approval_status.in_(statuses))
if pending_mine and user_info is not None:
uid = (user_info.get("user_id") or "").strip()
led_ids = _led_team_ids(db, tenant_no, uid)
q = q.filter(
BizPilotApplication.approval_status == APPROVAL_PENDING,
BizPilotApplication.project_id.in_(
_project_ids_for_teams(db, tenant_no, led_ids)
),
)
if channel_service_order_id:
q = q.filter(BizPilotApplication.channel_service_order_id == channel_service_order_id)
if biz_type:
@@ -390,7 +657,17 @@ def list_applications(
.limit(page_size)
.all()
)
items = [_row_to_dict_application(r, db, tenant_no) for r in rows]
current_uid = ""
is_admin = False
if user_info is not None:
current_uid = (user_info.get("user_id") or "").strip()
is_admin = _is_super_admin_user(user_info)
items = [
_row_to_dict_application(
r, db, tenant_no, current_user_id=current_uid, is_super_admin=is_admin
)
for r in rows
]
return {
"list": items,
"pagination": {"page": page, "pageSize": page_size, "total": total},
@@ -423,7 +700,10 @@ def get_application(db: Session, app_id: str, tenant_no: str) -> Optional[Dict[s
plan_id = plan.get("id")
if plan_id:
result["infusionSchedules"] = list_schedules_by_plan(db, plan_id, tenant_no)
if row.biz_type in ("clinical_application", "basic_experiment") and result["infusionSchedules"]:
if (
row.biz_type in ("clinical_application", "basic_experiment", "contract_processing")
and result["infusionSchedules"]
):
from app.crud import clinical_payment
payment_map = clinical_payment.map_payments_by_schedule_id(
@@ -455,9 +735,10 @@ def create_application(
customer_name = ""
customer_contact = ""
customer_phone = ""
research_category = ""
consent_form_urls = data.get("consentFormUrls") or None
if biz_type == "basic_experiment":
if is_research_like_biz(biz_type):
if not (data.get("projectTitle") or "").strip():
raise ValueError("请填写课题名称")
if not (data.get("customerName") or "").strip():
@@ -466,13 +747,30 @@ def create_application(
raise ValueError("请填写客户联系人")
if not (data.get("customerPhone") or "").strip():
raise ValueError("请填写客户联系方式")
research_category = validate_research_category(
data.get("researchCategory"), required=True, biz_type=biz_type
)
project_title = (data.get("projectTitle") or "").strip()
customer_name = (data.get("customerName") or "").strip()
customer_contact = (data.get("customerContact") or "").strip()
customer_phone = (data.get("customerPhone") or "").strip()
channel_service_order_id = ""
channel_id = ""
# 临床科研/委托加工申请单不再要求渠道
channel_id = (data.get("channelId") or "").strip()
channel_name = ""
if channel_id:
ch = (
db.query(BizChannel)
.filter(
BizChannel.id == channel_id,
BizChannel.tenant_no == tenant_no,
BizChannel.del_flag == 0,
)
.first()
)
if not ch:
raise ValueError("渠道不存在")
channel_name = ch.channel_name or ""
consent_form_urls = None
elif not channel_service_order_id and biz_type != "clinical_application":
raise ValueError("请选择渠道服务订单")
@@ -517,9 +815,14 @@ def create_application(
now = datetime.now()
application_no = _generate_application_no(db, tenant_no, biz_type=biz_type)
project_id = data.get("projectId", data.get("project_id")) or None
approval_status = None
if requires_leader_approval(biz_type):
_require_research_project_with_leader(db, tenant_no, project_id)
approval_status = APPROVAL_PENDING
row = BizPilotApplication(
project_id=data.get("projectId", data.get("project_id")) or None,
project_id=project_id,
id=str(uuid.uuid4()),
application_no=application_no,
application_name=data.get("applicationName") or "",
@@ -527,7 +830,9 @@ def create_application(
customer_name=customer_name or None,
customer_contact=customer_contact or None,
customer_phone=customer_phone or None,
research_category=research_category or None,
application_status="dks",
approval_status=approval_status,
channel_service_order_id=channel_service_order_id or "",
channel_id=(
(svc_order.channel_id or "" if svc_order else "")
@@ -586,11 +891,74 @@ def update_application(db: Session, app_id: str, data: dict, tenant_no: str) ->
row.customer_contact = (data["customerContact"] or "").strip() or None
if "customerPhone" in data and data["customerPhone"] is not None:
row.customer_phone = (data["customerPhone"] or "").strip() or None
if "researchCategory" in data and data["researchCategory"] is not None:
row_biz = row.biz_type or ""
if is_research_like_biz(row_biz):
row.research_category = validate_research_category(
data.get("researchCategory"), required=True, biz_type=row_biz
) or None
else:
row.research_category = validate_research_category(
data.get("researchCategory"), required=False, biz_type=row_biz
) or None
if "channelId" in data and data["channelId"] is not None:
row_biz = row.biz_type or ""
if is_research_like_biz(row_biz):
# 临床科研/委托加工允许清空或保留渠道(表单已去掉渠道栏)
new_channel_id = (data.get("channelId") or "").strip()
if not new_channel_id:
row.channel_id = ""
row.channel_name = ""
else:
ch = (
db.query(BizChannel)
.filter(
BizChannel.id == new_channel_id,
BizChannel.tenant_no == tenant_no,
BizChannel.del_flag == 0,
)
.first()
)
if not ch:
raise ValueError("渠道不存在")
row.channel_id = new_channel_id
row.channel_name = ch.channel_name or ""
row.channel_service_order_id = ""
elif row_biz == "clinical_application":
new_channel_id = (data.get("channelId") or "").strip()
if not new_channel_id:
raise ValueError("请选择渠道")
ch = (
db.query(BizChannel)
.filter(
BizChannel.id == new_channel_id,
BizChannel.tenant_no == tenant_no,
BizChannel.del_flag == 0,
)
.first()
)
if not ch:
raise ValueError("渠道不存在")
row.channel_id = new_channel_id
row.channel_name = ch.channel_name or ""
if "consentFormUrls" in data:
row.consent_form_urls = data.get("consentFormUrls") or None
if "attachmentUrls" in data:
row.attachment_urls = data.get("attachmentUrls") or None
# 驳回后保存即重新提交待审批(后续规则引擎可在此切换审批人)
if (
requires_leader_approval(row.biz_type)
and (row.approval_status or "") == APPROVAL_REJECTED
and row.application_status == "dks"
):
_require_research_project_with_leader(db, tenant_no, row.project_id)
row.approval_status = APPROVAL_PENDING
row.approval_user_id = None
row.approval_time = None
row.approval_remark = None
row.update_time = datetime.now()
db.commit()
db.refresh(row)
return _row_to_dict_application(row, db, tenant_no)
@@ -631,6 +999,7 @@ def start_application(db: Session, app_id: str, tenant_no: str, user_id: str) ->
raise ValueError("申请单不存在")
if row.application_status != "dks":
raise ValueError("当前状态不允许开始")
assert_research_leader_approved(row)
row.application_status = "jxz"
row.update_by = user_id
@@ -640,6 +1009,118 @@ def start_application(db: Session, app_id: str, tenant_no: str, user_id: str) ->
return _row_to_dict_application(row, db, tenant_no)
def approve_application(
db: Session,
app_id: str,
tenant_no: str,
user_id: str,
*,
approval_status: str,
approval_remark: Optional[str] = None,
is_super_admin: bool = False,
) -> Dict[str, Any]:
"""项目组负责人审批申请单。结论:ytg 通过 / yth 驳回。
普通用户仅该申请单所属项目组的负责人可批;仅超级管理员可代批(data_scope=1 不可代批)。
"""
conclusion = (approval_status or "").strip()
if conclusion not in (APPROVAL_PASSED, APPROVAL_REJECTED):
raise ValueError("请选择通过或驳回")
row = (
db.query(BizPilotApplication)
.filter(
BizPilotApplication.id == app_id,
BizPilotApplication.tenant_no == tenant_no,
BizPilotApplication.del_flag == 0,
)
.first()
)
if not row:
raise ValueError("申请单不存在")
if not requires_leader_approval(row.biz_type):
raise ValueError("当前业务类型无需项目组负责人审批")
if row.application_status == "yzf":
raise ValueError("已作废申请单不可审批")
current_approval = (row.approval_status or "").strip()
# 待审批、已通过、已驳回均可改结论(例如驳回后改为通过)
if current_approval not in (APPROVAL_PENDING, APPROVAL_PASSED, APPROVAL_REJECTED):
raise ValueError("当前审批状态不可提交结论")
_require_research_project_with_leader(db, tenant_no, row.project_id)
team_leader_uid = _team_leader_user_id(db, tenant_no, row.project_id)
if not is_super_admin and team_leader_uid != (user_id or "").strip():
raise ValueError("仅该项目组的负责人可审批")
now = datetime.now()
row.approval_status = conclusion
row.approval_user_id = user_id
row.approval_time = now
row.approval_remark = (approval_remark or "").strip() or None
row.update_by = user_id
row.update_time = now
if conclusion == APPROVAL_PASSED:
_backfill_outbound_work_orders_for_application(
db,
app=row,
tenant_no=tenant_no,
user_id=user_id,
dept_id=row.create_dept_id or "",
)
db.commit()
db.refresh(row)
return _row_to_dict_application(row, db, tenant_no)
def _backfill_outbound_work_orders_for_application(
db: Session,
*,
app: BizPilotApplication,
tenant_no: str,
user_id: str,
dept_id: str,
) -> None:
"""审批通过后,为已有交付计划补建出库生产/质检工单。"""
from app.crud import production_work_order as pwo_svc
from app.crud import qc_work_order as qc_svc
schedule_ids = (
db.query(BizPilotInfusionSchedule.id)
.join(
BizPilotInfusionPlan,
and_(
BizPilotInfusionSchedule.infusion_plan_id == BizPilotInfusionPlan.id,
BizPilotInfusionPlan.del_flag == 0,
),
)
.filter(
BizPilotInfusionPlan.pilot_application_id == app.id,
BizPilotInfusionPlan.tenant_no == tenant_no,
BizPilotInfusionSchedule.tenant_no == tenant_no,
BizPilotInfusionSchedule.del_flag == 0,
)
.all()
)
biz_type = app.biz_type or "pilot_service"
for (schedule_id,) in schedule_ids:
pwo_svc.create_outbound_production_work_order(
db,
schedule_id=schedule_id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=biz_type,
)
qc_svc.create_outbound_qc_work_order(
db,
schedule_id=schedule_id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=biz_type,
)
def complete_application(db: Session, app_id: str, tenant_no: str, user_id: str) -> Dict[str, Any]:
row = (
db.query(BizPilotApplication)
@@ -1161,12 +1642,18 @@ def auto_generate_schedules(
.first()
)
schedule_biz_type = (_app.biz_type if _app else None) or "pilot_service"
approval_ok = (not _app) or is_leader_approval_passed(
getattr(_app, "approval_status", None)
) or not requires_leader_approval(schedule_biz_type)
total = plan.total_course_count or 0
if total <= 0:
raise ValueError("总疗程数必须大于0")
now = datetime.now()
from app.crud import production_work_order as pwo_svc
from app.crud import qc_work_order as qc_svc
for i in range(1, total + 1):
sched = BizPilotInfusionSchedule(
id=str(uuid.uuid4()),
@@ -1187,26 +1674,23 @@ def auto_generate_schedules(
del_flag=0,
)
db.add(sched)
from app.crud import production_work_order as pwo_svc
pwo_svc.create_outbound_production_work_order(
db,
schedule_id=sched.id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
from app.crud import qc_work_order as qc_svc
qc_svc.create_outbound_qc_work_order(
db,
schedule_id=sched.id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
if approval_ok:
pwo_svc.create_outbound_production_work_order(
db,
schedule_id=sched.id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
qc_svc.create_outbound_qc_work_order(
db,
schedule_id=sched.id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
db.commit()
return {"generatedCount": total}
@@ -1284,6 +1768,9 @@ def create_schedule(
.first()
) if _plan else None
schedule_biz_type = (_app.biz_type if _app else None) or "pilot_service"
approval_ok = (not _app) or is_leader_approval_passed(
getattr(_app, "approval_status", None)
) or not requires_leader_approval(schedule_biz_type)
row = BizPilotInfusionSchedule(
id=schedule_id,
@@ -1314,35 +1801,35 @@ def create_schedule(
products = _create_schedule_products(
db, schedule_id, cell_products, tenant_no, user_id, dept_id, now
)
# 自动创建出库生产工单
from app.crud import production_work_order as pwo_svc
# 科研类未审批通过前不派发生产/质检工单(审批通过后补建)
if approval_ok:
from app.crud import production_work_order as pwo_svc
from app.crud import qc_work_order as qc_svc
pwo_svc.create_outbound_production_work_order(
db,
schedule_id=schedule_id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
# 自动创建出库质检工单
from app.crud import qc_work_order as qc_svc
qc_svc.create_outbound_qc_work_order(
db,
schedule_id=schedule_id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
pwo_svc.create_outbound_production_work_order(
db,
schedule_id=schedule_id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
qc_svc.create_outbound_qc_work_order(
db,
schedule_id=schedule_id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
# 临床应用自动创建缴费记录
plan_row = _plan
if plan_row:
application = _app
if (
application
and application.biz_type in ("clinical_application", "basic_experiment")
and application.biz_type
in ("clinical_application", "basic_experiment", "contract_processing")
and data.get("amount")
):
from app.crud.clinical_payment import auto_create_payment
@@ -1601,7 +2088,7 @@ def _get_or_create_infusion_plan(
user_id: str,
dept_id: str,
) -> BizPilotInfusionPlan:
"""获取或创建申请单下的输注/售卖方案(基础实验批量创建售卖计划用)。"""
"""获取或创建申请单下的输注/售卖方案(临床科研批量创建售卖计划用)。"""
plans = list_infusion_plans(db, application_id, tenant_no)
if plans:
plan_row = (
@@ -1647,7 +2134,7 @@ def create_basic_experiment_sale_schedules(
user_id: str,
dept_id: str,
) -> List[Dict[str, Any]]:
"""基础实验:每个产品行创建一条售卖计划(一产品一计划)。"""
"""临床科研:每个产品行创建一条售卖计划(一产品一计划)。"""
app = (
db.query(BizPilotApplication)
.filter(
@@ -1659,8 +2146,8 @@ def create_basic_experiment_sale_schedules(
)
if not app:
raise ValueError("申请单不存在")
if (app.biz_type or "") != "basic_experiment":
raise ValueError("仅基础实验申请单可批量创建售卖计划")
if not is_research_like_biz(app.biz_type):
raise ValueError("仅临床科研/委托加工申请单可批量创建售卖计划")
if not product_lines:
raise ValueError("请至少添加一行售卖产品")
@@ -78,6 +78,8 @@ def _row_to_dict_schedule(
"infusionStatus": row.infusion_status or "",
"cancelReason": row.cancel_reason or "",
"qcStatus": row.qc_status or "",
# 申请单费用(交付计划金额);勿与缴费 payment.amount 混淆
"feeAmount": float(row.amount) if row.amount is not None else None,
"attachments": row.attachments or "",
"remark": row.remark or "",
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
@@ -385,17 +387,26 @@ def list_infusion_schedules_mgmt(
products = _get_products_for_schedule(db, row.id, tenant_no)
plan_meta = plan_course_meta.get(row.infusion_plan_id) if row.infusion_plan_id else None
items.append(
_row_to_dict_schedule(
row,
application,
plan_row,
patient,
products,
service_order,
plan_meta=plan_meta,
)
item = _row_to_dict_schedule(
row,
application,
plan_row,
patient,
products,
service_order,
plan_meta=plan_meta,
)
if products:
primary = products[0] or {}
item["projectName"] = primary.get("projectName") or ""
item["agreementPrice"] = primary.get("agreementPrice")
item["actualPrice"] = primary.get("actualPrice")
item["quantity"] = primary.get("quantity")
if not item.get("cellType"):
item["cellType"] = primary.get("cellTypeName") or ""
if not item.get("specText"):
item["specText"] = primary.get("specText") or ""
items.append(item)
schedule_ids = [item["id"] for item in items if item.get("id")]
if schedule_ids:
@@ -560,7 +571,7 @@ def get_infusion_schedule_detail(
"outboundHandover": handover_svc.get_outbound_handover_view(db, schedule_id, tenant_no),
"infusionConfirm": confirm_svc.get_confirm_by_schedule(db, schedule_id, tenant_no) or {},
}
if application and (application.biz_type or "") in ("clinical_application", "basic_experiment"):
if application and (application.biz_type or "") in ("clinical_application", "basic_experiment", "contract_processing"):
from app.crud import clinical_payment
payment = clinical_payment.get_payment_by_schedule(
@@ -918,8 +929,8 @@ def _deduct_fee_on_complete(db: Session, schedule_id: str, tenant_no: str, user_
if not application:
raise ValueError("中试申请单不存在")
# 临床应用/基础实验走缴费模块,不走服务订单扣费
if (application.biz_type or "") in ("clinical_application", "basic_experiment"):
# 临床应用/临床科研走缴费模块,不走服务订单扣费
if (application.biz_type or "") in ("clinical_application", "basic_experiment", "contract_processing"):
return
if not application.channel_service_order_id:
@@ -13,7 +13,7 @@ from app.models.models import (
)
_OUTBOUND_BIZ_TYPES = ("pilot_service", "clinical_application", "basic_experiment")
_OUTBOUND_BIZ_TYPES = ("pilot_service", "clinical_application", "basic_experiment", "contract_processing")
def _is_pilot_outbound_production(wo: BizProductionWorkOrder) -> bool:
+56 -2
View File
@@ -172,11 +172,34 @@ def soft_delete_cell_product_type(db, type_id, tenant_no=None):
# Entity 2: BizCellProductSpec 细胞产品规格
# ────────────────────────────────────────────
def _format_decimal(value) -> Optional[float]:
if value is None:
return None
try:
return float(value)
except (TypeError, ValueError):
return None
def _require_positive_decimal(value, label: str):
if value is None or value == "":
raise ValueError(f"请填写{label}")
try:
num = float(value)
except (TypeError, ValueError):
raise ValueError(f"{label}必须是数字")
if num <= 0:
raise ValueError(f"{label}必须大于0")
return num
def _row_to_dict_cell_product_spec(row) -> Dict[str, Any]:
return {
"id": row.id,
"specCode": row.spec_code or "",
"specName": row.spec_name or "",
"cellCountQianwan": _format_decimal(getattr(row, "cell_count_qianwan", None)),
"fillVolumeMl": _format_decimal(getattr(row, "fill_volume_ml", None)),
"tenantNo": row.tenant_no or "",
"orderNum": row.order_num if row.order_num is not None else 0,
"remark": row.remark or "",
@@ -229,13 +252,28 @@ def cell_product_spec_code_exists(db, code, tenant_no, exclude_id=None):
return db.query(q.exists()).scalar()
def create_cell_product_spec(db, *, spec_code, spec_name, tenant_no="zkxw", order_num=None, remark=None, user_id=None):
def create_cell_product_spec(
db,
*,
spec_code,
spec_name,
cell_count_qianwan,
fill_volume_ml,
tenant_no="zkxw",
order_num=None,
remark=None,
user_id=None,
):
if cell_product_spec_code_exists(db, spec_code, tenant_no):
raise ValueError(f"规格编码 {spec_code} 已存在")
cell_count = _require_positive_decimal(cell_count_qianwan, "细胞数量(千万)")
fill_volume = _require_positive_decimal(fill_volume_ml, "分装体积(ml)")
obj = BizCellProductSpec(
id=generate_uuid(),
spec_code=spec_code,
spec_name=spec_name,
cell_count_qianwan=cell_count,
fill_volume_ml=fill_volume,
tenant_no=tenant_no,
order_num=order_num or 0,
remark=remark or "",
@@ -251,7 +289,19 @@ def create_cell_product_spec(db, *, spec_code, spec_name, tenant_no="zkxw", orde
return obj
def update_cell_product_spec(db, spec_id, *, spec_code=None, spec_name=None, order_num=None, remark=None, user_id=None, tenant_no=None):
def update_cell_product_spec(
db,
spec_id,
*,
spec_code=None,
spec_name=None,
cell_count_qianwan=None,
fill_volume_ml=None,
order_num=None,
remark=None,
user_id=None,
tenant_no=None,
):
obj = get_cell_product_spec(db, spec_id, tenant_no)
if not obj:
raise ValueError("记录不存在")
@@ -261,6 +311,10 @@ def update_cell_product_spec(db, spec_id, *, spec_code=None, spec_name=None, ord
obj.spec_code = spec_code
if spec_name is not None:
obj.spec_name = spec_name
if cell_count_qianwan is not None:
obj.cell_count_qianwan = _require_positive_decimal(cell_count_qianwan, "细胞数量(千万)")
if fill_volume_ml is not None:
obj.fill_volume_ml = _require_positive_decimal(fill_volume_ml, "分装体积(ml)")
if order_num is not None:
obj.order_num = order_num
if remark is not None:
+5 -3
View File
@@ -91,6 +91,8 @@ _RECEPTION_SOURCE_LABELS = {
_OUTBOUND_BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}
_APPLICATION_STATUS_LABELS = {
"dks": "待开始",
@@ -1262,7 +1264,6 @@ def list_production_tasks(
BizProductionTaskStep.del_flag == 0,
)
.distinct()
.subquery()
)
q = q.filter(
or_(
@@ -1280,7 +1281,6 @@ def list_production_tasks(
BizProductionTaskHandover.del_flag == 0,
)
.distinct()
.subquery()
)
q = q.filter(
BizProductionTask.current_assignee_user_id != mh_uid,
@@ -3328,6 +3328,7 @@ _PRODUCTION_TAB_STEP_COUNT_KEYS = (
"inbound_research_donation",
"outbound_pilot_service",
"outbound_basic_experiment",
"outbound_contract_processing",
"temporary",
)
@@ -3351,6 +3352,8 @@ def _resolve_production_tab_key(
bt = (biz_type or "pilot_service").strip() or "pilot_service"
if bt == "basic_experiment":
return "outbound_basic_experiment"
if bt == "contract_processing":
return "outbound_contract_processing"
if bt == "clinical_application":
return None
return "outbound_pilot_service"
@@ -3429,7 +3432,6 @@ def _base_active_step_count_query(
BizProductionTaskStep.del_flag == 0,
)
.distinct()
.subquery()
)
q = q.filter(
or_(
+5 -3
View File
@@ -198,7 +198,8 @@ def _wo_to_dict(wo: BizProductionWorkOrder) -> Dict[str, Any]:
"bizTypeLabel": {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "基础实验",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}.get(getattr(wo, "biz_type", None) or "", ""),
"workOrderStatus": wo.work_order_status,
"workOrderStatusLabel": _WORK_ORDER_STATUS_LABELS.get(wo.work_order_status, wo.work_order_status),
@@ -288,7 +289,8 @@ def _enrich_inbound_qc_conclusions(
_BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "基础实验",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}
@@ -545,7 +547,7 @@ def _attach_outbound_detail(
schedule_id = getattr(wo, "infusion_schedule_id", None) or ""
biz_type = getattr(wo, "biz_type", None) or ""
if schedule_id and biz_type in ("pilot_service", "clinical_application", "basic_experiment"):
if schedule_id and biz_type in ("pilot_service", "clinical_application", "basic_experiment", "contract_processing"):
pilot_ctx = build_outbound_pilot_context_by_schedule(
db, schedule_id, wo.tenant_no or ""
)
+25 -15
View File
@@ -19,6 +19,8 @@ from app.crud.qc_work_order import (
_sample_type_name_for_reception,
_work_order_qc_biz_type,
_OUTBOUND_BIZ_TYPE_LABELS,
apply_research_donation_protocol_status_filter,
build_qc_work_order_keyword_conditions,
build_work_order_list_summaries,
)
from app.core.db_collation import eq_unicode, unicode_ci
@@ -574,6 +576,7 @@ def list_mine_tasks(
qc_biz_type: Optional[str] = None,
reception_source: Optional[str] = None,
biz_type: Optional[str] = None,
protocol_status: Optional[str] = None,
tenant_no: Optional[str] = None,
) -> Tuple[List[Dict[str, Any]], int]:
def _filtered():
@@ -601,14 +604,21 @@ def list_mine_tasks(
kw = (keyword or "").strip()
if kw:
like = f"%{kw}%"
q0 = q0.filter(
or_(
BizQcTask.task_no.like(like),
BizQcTask.item_name.like(like),
BizQcWorkOrder.work_order_no.like(like),
BizQcWorkOrder.sample_code.like(like),
)
)
wt = (qc_biz_type or "").strip()
# temporary Tab 的 qcBizType=temporary,与工单 work_order_type 对齐
wo_type = "temporary" if wt == "temporary" else (wt or None)
keyword_conditions = [
BizQcTask.task_no.like(like),
BizQcTask.item_name.like(like),
*build_qc_work_order_keyword_conditions(
db,
tenant_no=tenant_no,
keyword=kw,
work_order_type=wo_type,
reception_source=(reception_source or "").strip() or None,
),
]
q0 = q0.filter(or_(*keyword_conditions))
tt = (task_type or "").strip()
if tt:
q0 = q0.filter(BizQcTask.task_type == tt)
@@ -632,6 +642,11 @@ def list_mine_tasks(
bt_out = (biz_type or "").strip()
if bt_out:
q0 = q0.filter(BizQcWorkOrder.biz_type == bt_out)
q0 = apply_research_donation_protocol_status_filter(
q0,
protocol_status,
reception_source=reception_source,
)
return q0
total = _filtered().order_by(None).with_entities(func.count(BizQcTask.id)).scalar() or 0
@@ -770,13 +785,8 @@ def _set_task_remark(t: BizQcTask, remark: Optional[str]) -> None:
def _require_dsfjc_attachments(t: BizQcTask, *, for_status: str = "ywc") -> None:
"""第三方检测且任务状态为已完成时,须至少有一个检测材料附件。"""
if (t.task_type or "").strip() != "dsfjc":
return
if (for_status or "").strip() != "ywc":
return
if not (t.third_party_attachments or "").strip():
raise ValueError("第三方检测须上传检测材料附件")
"""历史校验入口:第三方检测材料改为选填,工单级附件在工单卡片维护。"""
return
def complete_task(
@@ -144,12 +144,14 @@ def append_task_result_change_log(
before: Dict[str, Any],
after: Dict[str, Any],
operate_time: Optional[datetime] = None,
operate_batch_id: Optional[str] = None,
) -> BizQcTaskResultChangeLog:
"""追加一条检测结果保存留痕(不 commit)。无字段差异也写入。"""
now = operate_time or datetime.now()
changes = build_result_changes(before, after)
has_change = "1" if changes else "0"
name = _resolve_operator_name(db, user_id, operator_user_name)
batch_id = _norm_text(operate_batch_id) or None
obj = BizQcTaskResultChangeLog(
id=generate_uuid(),
task_id=task.id,
@@ -159,6 +161,7 @@ def append_task_result_change_log(
operate_time=now,
operator_user_id=user_id,
operator_user_name=name or None,
operate_batch_id=batch_id,
has_field_change=has_change,
changes_json=json.dumps(changes, ensure_ascii=False),
tenant_no=tenant_no,
@@ -194,6 +197,7 @@ def _row_to_dict(row: BizQcTaskResultChangeLog) -> Dict[str, Any]:
"operateTime": _fmt_dt(row.operate_time),
"operatorUserId": row.operator_user_id or "",
"operatorUserName": row.operator_user_name or "",
"operateBatchId": row.operate_batch_id or "",
"hasFieldChange": row.has_field_change == "1",
"changes": changes,
"createTime": _fmt_dt(row.create_time),
+78 -35
View File
@@ -108,7 +108,8 @@ _CONCLUSION_LABELS = {"tg": "通过", "btg": "不通过"}
_OUTBOUND_BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "基础实验",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}
_OUTBOUND_BIZ_TYPES = tuple(_OUTBOUND_BIZ_TYPE_LABELS.keys())
@@ -560,6 +561,56 @@ def _inbound_qc_work_order_ids_by_mother_name(
return list(ids)
def build_qc_work_order_keyword_conditions(
db: Optional[Session],
*,
tenant_no: Optional[str],
keyword: str,
work_order_type: Optional[str] = None,
reception_source: Optional[str] = None,
) -> List[Any]:
"""质检工单列表关键词 OR 条件(工单号/样本/协议号/外部编号 + 入库编码/母亲/出库申请字段)。
供质检工单列表与「我的质检任务」共用,避免两端口径漂移。
"""
kw = (keyword or "").strip()
if not kw:
return []
like = f"%{kw}%"
wt = (work_order_type or "").strip()
rs = (reception_source or "").strip()
conditions: List[Any] = [
BizQcWorkOrder.work_order_no.like(like),
BizQcWorkOrder.sample_code.like(like),
BizQcWorkOrder.protocol_no.like(like),
BizQcWorkOrder.external_target_code.like(like),
]
if db is not None and tenant_no:
from app.crud import sample_reception as reception_svc
rec_ids = reception_svc.reception_ids_matching_lab_storage_keyword(
db, tenant_no, kw
)
if rec_ids:
conditions.append(BizQcWorkOrder.reception_id.in_(rec_ids))
lab_codes = reception_svc.sample_codes_matching_lab_storage_keyword(
db, tenant_no, kw
)
if lab_codes:
conditions.append(BizQcWorkOrder.sample_code.in_(lab_codes))
if wt == "outbound" or not wt:
outbound_ids = _outbound_qc_work_order_ids_by_keyword(db, tenant_no, kw)
if outbound_ids:
conditions.append(BizQcWorkOrder.id.in_(outbound_ids))
if not wt or wt == "inbound":
inbound_mother_ids = _inbound_qc_work_order_ids_by_mother_name(
db, tenant_no, kw, reception_source=rs or None
)
if inbound_mother_ids:
conditions.append(BizQcWorkOrder.id.in_(inbound_mother_ids))
return conditions
def _accept_conclusion_label(v: Optional[str]) -> str:
key = (v or "").strip()
return _ACCEPT_CONCLUSION_LABELS.get(key, key)
@@ -1213,6 +1264,7 @@ def _wo_to_dict(
"configuredBy": wo.configured_by or "",
"configuredByName": configured_by_name or wo.configured_by or "",
"thirdPartyFeeTotal": _dec(wo.third_party_fee_total),
"attachments": (getattr(wo, "attachments", None) or "").strip(),
"remark": wo.remark or "",
"createTime": _fmt_dt(wo.create_time),
"updateTime": _fmt_dt(wo.update_time),
@@ -1718,8 +1770,8 @@ def apply_research_donation_protocol_status_filter(
return query
mode, statuses = resolve_research_donation_protocol_status_filter(protocol_status)
if mode == "none":
return query.filter(BizQcWorkOrder.id.in_([]))
if mode == "all":
return query
if mode == "in":
return query.filter(_research_donation_status_exists(statuses))
# default:与前端默认勾选一致
@@ -1791,37 +1843,15 @@ def list_work_orders(
q0 = q0.filter(BizQcWorkOrder.trigger_source == ts)
kw = (keyword or "").strip()
if kw:
like = f"%{kw}%"
keyword_conditions = [
BizQcWorkOrder.work_order_no.like(like),
BizQcWorkOrder.sample_code.like(like),
BizQcWorkOrder.protocol_no.like(like),
BizQcWorkOrder.external_target_code.like(like),
]
if tenant_no:
from app.crud import sample_reception as reception_svc
rec_ids = reception_svc.reception_ids_matching_lab_storage_keyword(
db, tenant_no, kw
)
if rec_ids:
keyword_conditions.append(BizQcWorkOrder.reception_id.in_(rec_ids))
lab_codes = reception_svc.sample_codes_matching_lab_storage_keyword(
db, tenant_no, kw
)
if lab_codes:
keyword_conditions.append(BizQcWorkOrder.sample_code.in_(lab_codes))
if tenant_no and (wt == "outbound" or not wt):
outbound_ids = _outbound_qc_work_order_ids_by_keyword(db, tenant_no, kw)
if outbound_ids:
keyword_conditions.append(BizQcWorkOrder.id.in_(outbound_ids))
if tenant_no and (not wt or wt == "inbound"):
inbound_mother_ids = _inbound_qc_work_order_ids_by_mother_name(
db, tenant_no, kw, reception_source=rs or None
)
if inbound_mother_ids:
keyword_conditions.append(BizQcWorkOrder.id.in_(inbound_mother_ids))
q0 = q0.filter(or_(*keyword_conditions))
keyword_conditions = build_qc_work_order_keyword_conditions(
db,
tenant_no=tenant_no,
keyword=kw,
work_order_type=wt or None,
reception_source=rs or None,
)
if keyword_conditions:
q0 = q0.filter(or_(*keyword_conditions))
st_raw = (work_order_status or "").strip()
if st_raw:
statuses = [s.strip() for s in st_raw.split(",") if s.strip()]
@@ -1975,6 +2005,7 @@ _QC_TAB_COUNT_KEYS = (
"inbound_research_donation",
"outbound_pilot_service",
"outbound_basic_experiment",
"outbound_contract_processing",
"temporary",
)
@@ -1995,6 +2026,8 @@ def _resolve_wo_tab_key(
bt = (biz_type or "pilot_service").strip() or "pilot_service"
if bt == "basic_experiment":
return "outbound_basic_experiment"
if bt == "contract_processing":
return "outbound_contract_processing"
if bt == "clinical_application":
return "outbound_clinical_application"
return "outbound_pilot_service"
@@ -3315,6 +3348,7 @@ def update_qc_work_order(
external_target_code: Optional[str] = None,
work_order_status: Optional[str] = None,
qc_conclusion: Optional[str] = None,
attachments: Optional[str] = None,
remark: Optional[str] = None,
) -> BizQcWorkOrder:
"""编辑质检工单:入库/出库可改备注、状态与质检结论;临时可改备注与质检对象"""
@@ -3345,6 +3379,15 @@ def update_qc_work_order(
if conc and conc not in _VALID_QC_WORK_ORDER_CONCLUSIONS:
raise ValueError("质检结论无效")
wo.conclusion = conc or None
if attachments is not None:
urls = ",".join(
p.strip()
for p in (attachments or "").replace(",", ",").split(",")
if p.strip()
)
if len(urls) > 4000:
raise ValueError("工单附件过多,请减少后重试")
wo.attachments = urls or None
if remark is not None:
wo.remark = (remark or "").strip() or None
wo.update_by = user_id
@@ -3685,7 +3728,7 @@ def build_outbound_pilot_context_by_schedule(
"bizType": app_biz,
"bizTypeLabel": _OUTBOUND_BIZ_TYPE_LABELS.get(app_biz, app_biz),
}
if app_biz == "basic_experiment":
if app_biz in ("basic_experiment", "contract_processing"):
out["application"]["projectTitle"] = app.project_title or ""
out["application"]["customerName"] = app.customer_name or ""
out["application"]["customerContact"] = app.customer_contact or ""
+116
View File
@@ -574,6 +574,99 @@ def list_pending_protocol_samples(
return page_items, int(total)
def parse_optional_bool(value: Optional[str]) -> Optional[bool]:
"""解析查询参数中的可选布尔:空=不限,true/1=是,false/0=否。"""
if value is None:
return None
text = str(value).strip().lower()
if not text:
return None
if text in ("1", "true", "yes", "y"):
return True
if text in ("0", "false", "no", "n"):
return False
raise ValueError(f"invalid boolean query value: {value}")
def _apply_received_sample_type_and_void_filters(
db: Session,
q_rec,
*,
tenant_no: str,
sample_type_id: Optional[str] = None,
is_voided: Optional[bool] = None,
):
"""按样本类型、是否废弃(协议/捐赠状态=yzf)过滤已接收记录。"""
type_id = (sample_type_id or "").strip()
if not type_id and is_voided is None:
return q_rec
cell_q = (
db.query(BizProtocolSample.id)
.join(
BizCollectionProtocol,
and_(
BizCollectionProtocol.id == BizProtocolSample.collection_protocol_id,
BizCollectionProtocol.del_flag == 0,
),
)
.filter(
BizProtocolSample.del_flag == 0,
BizProtocolSample.tenant_no == tenant_no,
BizCollectionProtocol.tenant_no == tenant_no,
)
)
donation_q = (
db.query(_donation_sample_id_col(BizResearchDonationSample.id))
.join(
BizResearchDonation,
and_(
BizResearchDonation.id == BizResearchDonationSample.research_donation_id,
BizResearchDonation.del_flag == 0,
),
)
.filter(
BizResearchDonationSample.del_flag == 0,
BizResearchDonationSample.tenant_no == tenant_no,
BizResearchDonation.tenant_no == tenant_no,
)
)
if type_id:
cell_q = cell_q.filter(BizProtocolSample.sample_type_id == type_id)
donation_q = donation_q.filter(BizResearchDonationSample.sample_type_id == type_id)
if is_voided is True:
cell_q = cell_q.filter(BizCollectionProtocol.protocol_status == "yzf")
donation_q = donation_q.filter(BizResearchDonation.donation_status == "yzf")
elif is_voided is False:
cell_q = cell_q.filter(
or_(
BizCollectionProtocol.protocol_status.is_(None),
BizCollectionProtocol.protocol_status != "yzf",
)
)
donation_q = donation_q.filter(
or_(
BizResearchDonation.donation_status.is_(None),
BizResearchDonation.donation_status != "yzf",
)
)
cell_ids = cell_q.subquery()
donation_ids = donation_q.subquery()
return q_rec.filter(
or_(
and_(
BizSampleReception.reception_source == "cell_storage",
BizSampleReception.protocol_sample_id.in_(cell_ids),
),
and_(
BizSampleReception.reception_source == "research_donation",
BizSampleReception.donation_sample_id.in_(donation_ids),
),
)
)
def list_received_protocol_samples(
db: Session,
*,
@@ -582,6 +675,8 @@ def list_received_protocol_samples(
tenant_no: Optional[str] = None,
keyword: Optional[str] = None,
source_type: Optional[str] = None,
sample_type_id: Optional[str] = None,
is_voided: Optional[bool] = None,
reception_time_start: Optional[str] = None,
reception_time_end: Optional[str] = None,
user_info=None,
@@ -637,6 +732,14 @@ def list_received_protocol_samples(
)
)
q_rec = _apply_received_sample_type_and_void_filters(
db,
q_rec,
tenant_no=tenant_no,
sample_type_id=sample_type_id,
is_voided=is_voided,
)
if user_info:
from app.core.data_scope import apply_data_scope
q_rec = apply_data_scope(q_rec, BizSampleReception, user_info, db, tenant_no)
@@ -1110,7 +1213,9 @@ def update_sample_reception(
raise ValueError("接收结论无效")
from app.crud import sample_reception_lab_code as lab_code_svc
from app.services.lab_storage_code_rename import rename_lab_storage_code_copies
old_lab_code = (rec.lab_storage_code or "").strip()
code_raw = (lab_storage_code or "").strip()
if conclusion == "js":
parsed_code = lab_code_svc.validate_lab_storage_code(code_raw)
@@ -1131,7 +1236,18 @@ def update_sample_reception(
)
rec.lab_storage_code = parsed_code
else:
parsed_code = None
rec.lab_storage_code = None
new_lab_code = (parsed_code or "").strip()
if old_lab_code and new_lab_code and old_lab_code != new_lab_code:
rename_lab_storage_code_copies(
db,
tenant_no=tenant_no,
reception_id=reception_id,
old_code=old_lab_code,
new_code=new_lab_code,
user_id=user_id,
)
handler_display = (handler_name or "").strip()
if handler_user_id and not handler_display:
+71 -5
View File
@@ -351,6 +351,50 @@ class BizCustomer(Base):
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizPartnerCustomer(Base):
"""合作客户 biz_partner_customer(临床科研/委托加工)"""
__tablename__ = "biz_partner_customer"
id = Column(String(64), primary_key=True, comment="主键ID")
customer_name = Column(String(200), nullable=False, comment="客户名称")
customer_contact = Column(String(100), nullable=False, comment="客户联系人")
customer_phone = Column(String(32), nullable=False, comment="客户联系方式")
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 BizContractProcessingCategory(Base):
"""临床科研/委托加工自定义业务类型 biz_contract_processing_category"""
__tablename__ = "biz_contract_processing_category"
id = Column(String(64), primary_key=True, comment="主键ID")
category_name = Column(String(64), nullable=False, comment="业务类型名称(写入申请单 research_category)")
biz_type = Column(
String(32),
nullable=False,
default="contract_processing",
comment="业务线 basic_experiment / contract_processing",
)
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 BizCellSampleType(Base):
"""细胞样本类型 biz_cell_sample_type"""
@@ -2260,6 +2304,7 @@ class BizQcWorkOrder(Base):
configured_time = Column(DateTime, nullable=True, comment="配置时间")
configured_by = Column(String(64), nullable=True, comment="配置人")
third_party_fee_total = Column(Numeric(18, 2), nullable=True, comment="第三方费用合计")
attachments = Column(String(4000), nullable=True, comment="工单附件(逗号分隔URL)")
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注")
@@ -2407,6 +2452,7 @@ class BizQcTaskResultChangeLog(Base):
operate_time = Column(DateTime, nullable=False, comment="业务操作时间")
operator_user_id = Column(String(64), nullable=True, comment="操作人用户ID")
operator_user_name = Column(String(64), nullable=True, comment="操作人姓名快照")
operate_batch_id = Column(String(64), nullable=True, comment="同一次保存批次ID(多任务共用)")
has_field_change = Column(CHAR(1), nullable=False, default="0", comment="1有字段变更 0仅保存无变更")
changes_json = Column(Text, nullable=True, comment="变更明细JSON")
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
@@ -2660,6 +2706,8 @@ class BizCellProductSpec(Base):
id = Column(String(64), primary_key=True, comment="主键ID")
spec_code = Column(String(64), nullable=False, comment="规格编码")
spec_name = Column(String(200), nullable=False, comment="规格名称")
cell_count_qianwan = Column(Numeric(18, 4), nullable=True, comment="细胞数量(单位:千万)")
fill_volume_ml = Column(Numeric(18, 4), nullable=True, comment="分装体积(单位:ml)")
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注")
@@ -4177,15 +4225,33 @@ class BizPilotApplication(Base):
project_id = Column(String(64), nullable=True, index=True, comment="所属统计项目ID")
application_no = Column(String(64), nullable=True, comment="申请单号(自动生成,前缀ZSSQ)")
application_name = Column(String(200), nullable=True, comment="申请单名称")
project_title = Column(String(200), nullable=True, comment="课题名称(基础实验)")
customer_name = Column(String(200), nullable=True, comment="客户名称(基础实验)")
customer_contact = Column(String(100), nullable=True, comment="客户联系人(基础实验)")
customer_phone = Column(String(32), nullable=True, comment="客户联系方式(基础实验)")
project_title = Column(String(200), nullable=True, comment="课题名称(临床科研)")
customer_name = Column(String(200), nullable=True, comment="客户名称(临床科研)")
customer_contact = Column(String(100), nullable=True, comment="客户联系人(临床科研)")
customer_phone = Column(String(32), nullable=True, comment="客户联系方式(临床科研)")
research_category = Column(
String(64),
nullable=True,
comment="业务子类型;临床科研三项码/委托加工产品码或自定义其他",
)
application_status = Column(String(16), nullable=False, default="dks", comment="dks待开始 jxz进行中 ywc已完成 yzf已作废")
approval_status = Column(
String(16),
nullable=True,
comment="审批状态 dsp待审批 ytg已通过 yth已驳回;非科研类可空",
)
approval_user_id = Column(String(64), nullable=True, comment="审批人用户ID")
approval_time = Column(DateTime, nullable=True, comment="审批时间")
approval_remark = Column(String(1000), nullable=True, comment="审批备注")
channel_service_order_id = Column(String(64), nullable=False, comment="渠道服务购买订单ID")
channel_id = Column(String(64), nullable=True, comment="渠道ID(缓存自服务订单)")
channel_name = Column(String(200), nullable=True, comment="渠道名称(缓存)")
biz_type = Column(String(20), nullable=False, default="pilot_service", comment="业务类型: pilot_service=中试服务, clinical_application=临床应用, basic_experiment=基础实验")
biz_type = Column(
String(20),
nullable=False,
default="pilot_service",
comment="业务类型: pilot_service/clinical_application/basic_experiment/contract_processing",
)
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注")
+3
View File
@@ -111,4 +111,7 @@ class QcWorkOrderUpdateBody(BaseModel):
qc_conclusion: Optional[str] = Field(
None, alias="qcConclusion", description="质检结论 tg合格 btg不合格,空串清空"
)
attachments: Optional[str] = Field(
None, description="工单附件(逗号分隔URL),空串清空"
)
remark: Optional[str] = Field(None, description="备注")
@@ -1,4 +1,4 @@
"""基础实验交付日前一天:服务号模板提醒。"""
"""临床科研交付日前一天:服务号模板提醒。"""
from __future__ import annotations
import logging
@@ -126,7 +126,7 @@ def _iter_candidate_schedules(db: Session, *, delivery_day: date) -> List[Any]:
& (BizPilotInfusionScheduleProduct.del_flag == 0),
)
.filter(
BizPilotApplication.biz_type == "basic_experiment",
BizPilotApplication.biz_type in ("basic_experiment", "contract_processing"),
BizPilotApplication.del_flag == 0,
BizPilotInfusionPlan.del_flag == 0,
BizPilotInfusionSchedule.del_flag == 0,
@@ -137,7 +137,7 @@ def _iter_candidate_schedules(db: Session, *, delivery_day: date) -> List[Any]:
.order_by(BizPilotInfusionSchedule.infusion_time.asc())
.all()
)
# 一计划多产品时取首条产品行(基础实验通常一行)
# 一计划多产品时取首条产品行(临床科研通常一行)
seen: set = set()
out = []
for sched, app, prod in rows:
@@ -0,0 +1,399 @@
"""编辑样本接收时,把实验室入库编码同步到已落库的关联副本。"""
from __future__ import annotations
from datetime import datetime
from typing import Iterable, List, Optional, Sequence
from sqlalchemy.orm import Session
from app.models.models import (
BizCellProduct,
BizLabSampleProcessingExtra,
BizLabSampleProcessSupplement,
BizOutboundReleaseCell,
BizProductionTask,
BizProductionTaskInput,
BizProductionTaskOutput,
BizProductionTaskStep,
BizProductionTaskStepOutput,
BizProductionWorkOrder,
BizQcWorkOrder,
BizQcWorkOrderInspectionBatch,
BizSampleReception,
BizStorageSlotOccupancy,
)
DUPLICATE_MESSAGE = "实验室入库编码已存在"
def _ascii_alnum(ch: str) -> bool:
return bool(ch) and ch.isascii() and ch.isalnum()
def replace_lab_code_token(text: Optional[str], old: str, new: str) -> Optional[str]:
"""替换完整编码。前后紧挨 ASCII 字母或数字时不替换,避免改掉更长的编码。"""
if text is None or not old or old == new or old not in text:
return text
out: List[str] = []
i = 0
size = len(old)
while i < len(text):
if text.startswith(old, i):
prev_ok = i == 0 or not _ascii_alnum(text[i - 1])
end = i + size
next_ok = end == len(text) or not _ascii_alnum(text[end])
if prev_ok and next_ok:
out.append(new)
i = end
continue
out.append(text[i])
i += 1
return "".join(out)
def _occupies_new_code(value: Optional[str], new: str) -> bool:
"""批次名等于新编码,或是「新编码 + 非字母数字后缀」。"""
text = (value or "").strip()
if not text or not new:
return False
if text == new:
return True
if not text.startswith(new) or len(text) == len(new):
return False
return not _ascii_alnum(text[len(new)])
def _like_prefix(code: str) -> str:
escaped = code.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
return escaped + "%"
def _ids(values: Iterable[str]) -> List[str]:
return [v for v in values if v]
def _touch(row, user_id: Optional[str], now: datetime) -> None:
row.update_by = user_id
row.update_time = now
def _rewrite_fields(row, fields: Sequence[str], old: str, new: str, user_id: Optional[str], now: datetime) -> bool:
changed = False
for field in fields:
current = getattr(row, field)
updated = replace_lab_code_token(current, old, new)
if updated != current:
setattr(row, field, updated)
changed = True
if changed:
_touch(row, user_id, now)
return changed
def _raise_if_duplicate() -> None:
raise ValueError(DUPLICATE_MESSAGE)
def rename_lab_storage_code_copies(
db: Session,
*,
tenant_no: str,
reception_id: str,
old_code: str,
new_code: str,
user_id: Optional[str] = None,
) -> int:
"""把本条接收记录关联出去的旧编码副本改成新编码。冲突时不写任何副本。"""
old = (old_code or "").strip()
new = (new_code or "").strip()
if not old or not new or old == new:
return 0
other_reception = (
db.query(BizSampleReception.id)
.filter(
BizSampleReception.tenant_no == tenant_no,
BizSampleReception.del_flag == 0,
BizSampleReception.lab_storage_code == new,
BizSampleReception.id != reception_id,
)
.first()
)
if other_reception:
_raise_if_duplicate()
prod_orders = (
db.query(BizProductionWorkOrder)
.filter(
BizProductionWorkOrder.tenant_no == tenant_no,
BizProductionWorkOrder.del_flag == 0,
BizProductionWorkOrder.reception_id == reception_id,
)
.all()
)
qc_orders = (
db.query(BizQcWorkOrder)
.filter(
BizQcWorkOrder.tenant_no == tenant_no,
BizQcWorkOrder.del_flag == 0,
BizQcWorkOrder.reception_id == reception_id,
)
.all()
)
prod_ids = [row.id for row in prod_orders]
qc_ids = [row.id for row in qc_orders]
tasks = (
db.query(BizProductionTask)
.filter(
BizProductionTask.tenant_no == tenant_no,
BizProductionTask.del_flag == 0,
BizProductionTask.work_order_id.in_(prod_ids),
)
.all()
if prod_ids
else []
)
task_ids = [row.id for row in tasks]
steps = (
db.query(BizProductionTaskStep)
.filter(
BizProductionTaskStep.tenant_no == tenant_no,
BizProductionTaskStep.del_flag == 0,
BizProductionTaskStep.task_id.in_(task_ids),
)
.all()
if task_ids
else []
)
step_ids = [row.id for row in steps]
inputs = (
db.query(BizProductionTaskInput)
.filter(
BizProductionTaskInput.tenant_no == tenant_no,
BizProductionTaskInput.del_flag == 0,
BizProductionTaskInput.task_id.in_(task_ids),
)
.all()
if task_ids
else []
)
task_outputs = (
db.query(BizProductionTaskOutput)
.filter(
BizProductionTaskOutput.tenant_no == tenant_no,
BizProductionTaskOutput.del_flag == 0,
BizProductionTaskOutput.task_id.in_(task_ids),
)
.all()
if task_ids
else []
)
step_outputs = (
db.query(BizProductionTaskStepOutput)
.filter(
BizProductionTaskStepOutput.tenant_no == tenant_no,
BizProductionTaskStepOutput.del_flag == 0,
BizProductionTaskStepOutput.step_id.in_(step_ids),
)
.all()
if step_ids
else []
)
products = (
db.query(BizCellProduct)
.filter(
BizCellProduct.tenant_no == tenant_no,
BizCellProduct.del_flag == 0,
BizCellProduct.production_task_id.in_(task_ids),
)
.all()
if task_ids
else []
)
product_ids = [row.id for row in products]
occupancies = (
db.query(BizStorageSlotOccupancy)
.filter(
BizStorageSlotOccupancy.tenant_no == tenant_no,
BizStorageSlotOccupancy.del_flag == 0,
BizStorageSlotOccupancy.item_id.in_(product_ids),
)
.all()
if product_ids
else []
)
outbound_cells = (
db.query(BizOutboundReleaseCell)
.filter(
BizOutboundReleaseCell.tenant_no == tenant_no,
BizOutboundReleaseCell.del_flag == 0,
BizOutboundReleaseCell.cell_product_id.in_(product_ids),
)
.all()
if product_ids
else []
)
batches = (
db.query(BizQcWorkOrderInspectionBatch)
.filter(
BizQcWorkOrderInspectionBatch.tenant_no == tenant_no,
BizQcWorkOrderInspectionBatch.del_flag == 0,
BizQcWorkOrderInspectionBatch.work_order_id.in_(qc_ids),
)
.all()
if qc_ids
else []
)
supplements = (
db.query(BizLabSampleProcessSupplement)
.filter(
BizLabSampleProcessSupplement.tenant_no == tenant_no,
BizLabSampleProcessSupplement.del_flag == 0,
BizLabSampleProcessSupplement.lab_storage_code == old,
)
.all()
)
extras = (
db.query(BizLabSampleProcessingExtra)
.filter(
BizLabSampleProcessingExtra.tenant_no == tenant_no,
BizLabSampleProcessingExtra.del_flag == 0,
BizLabSampleProcessingExtra.sample_code == old,
)
.all()
)
_assert_copies_available(
db,
tenant_no=tenant_no,
new=new,
product_ids=product_ids,
task_output_ids=[row.id for row in task_outputs],
step_output_ids=[row.id for row in step_outputs],
occupancy_ids=[row.id for row in occupancies],
qc_ids=qc_ids,
)
if (
db.query(BizLabSampleProcessSupplement.id)
.filter(
BizLabSampleProcessSupplement.tenant_no == tenant_no,
BizLabSampleProcessSupplement.del_flag == 0,
BizLabSampleProcessSupplement.lab_storage_code == new,
)
.first()
):
_raise_if_duplicate()
if (
db.query(BizLabSampleProcessingExtra.id)
.filter(
BizLabSampleProcessingExtra.tenant_no == tenant_no,
BizLabSampleProcessingExtra.del_flag == 0,
BizLabSampleProcessingExtra.sample_code == new,
)
.first()
):
_raise_if_duplicate()
now = datetime.now()
changed = 0
for row in tasks:
if _rewrite_fields(row, ("task_name", "description", "remark"), old, new, user_id, now):
changed += 1
for row in steps:
if _rewrite_fields(row, ("description", "remark", "sop_content"), old, new, user_id, now):
changed += 1
for row in inputs:
if _rewrite_fields(row, ("input_name", "input_code"), old, new, user_id, now):
changed += 1
for row in task_outputs:
if _rewrite_fields(row, ("output_name", "output_barcode"), old, new, user_id, now):
changed += 1
for row in step_outputs:
if _rewrite_fields(row, ("output_name", "output_barcode"), old, new, user_id, now):
changed += 1
for row in products:
if _rewrite_fields(row, ("product_code", "product_name", "batch_no"), old, new, user_id, now):
changed += 1
for row in occupancies:
if _rewrite_fields(row, ("item_code", "item_name"), old, new, user_id, now):
changed += 1
for row in outbound_cells:
if _rewrite_fields(row, ("product_code", "product_name", "batch_no"), old, new, user_id, now):
changed += 1
for row in batches:
if _rewrite_fields(row, ("batch_name",), old, new, user_id, now):
changed += 1
for row in supplements:
row.lab_storage_code = new
_touch(row, user_id, now)
changed += 1
for row in extras:
row.sample_code = new
_touch(row, user_id, now)
changed += 1
if changed:
db.flush()
return changed
def _assert_copies_available(
db: Session,
*,
tenant_no: str,
new: str,
product_ids: Sequence[str],
task_output_ids: Sequence[str],
step_output_ids: Sequence[str],
occupancy_ids: Sequence[str],
qc_ids: Sequence[str],
) -> None:
product_q = db.query(BizCellProduct.id).filter(
BizCellProduct.tenant_no == tenant_no,
BizCellProduct.del_flag == 0,
BizCellProduct.product_code == new,
)
if product_ids:
product_q = product_q.filter(~BizCellProduct.id.in_(_ids(product_ids)))
if product_q.first():
_raise_if_duplicate()
task_barcode_q = db.query(BizProductionTaskOutput.id).filter(
BizProductionTaskOutput.tenant_no == tenant_no,
BizProductionTaskOutput.del_flag == 0,
BizProductionTaskOutput.output_barcode == new,
)
if task_output_ids:
task_barcode_q = task_barcode_q.filter(~BizProductionTaskOutput.id.in_(_ids(task_output_ids)))
if task_barcode_q.first():
_raise_if_duplicate()
step_barcode_q = db.query(BizProductionTaskStepOutput.id).filter(
BizProductionTaskStepOutput.tenant_no == tenant_no,
BizProductionTaskStepOutput.del_flag == 0,
BizProductionTaskStepOutput.output_barcode == new,
)
if step_output_ids:
step_barcode_q = step_barcode_q.filter(~BizProductionTaskStepOutput.id.in_(_ids(step_output_ids)))
if step_barcode_q.first():
_raise_if_duplicate()
occupancy_q = db.query(BizStorageSlotOccupancy.id).filter(
BizStorageSlotOccupancy.tenant_no == tenant_no,
BizStorageSlotOccupancy.del_flag == 0,
BizStorageSlotOccupancy.item_code == new,
)
if occupancy_ids:
occupancy_q = occupancy_q.filter(~BizStorageSlotOccupancy.id.in_(_ids(occupancy_ids)))
if occupancy_q.first():
_raise_if_duplicate()
batch_q = db.query(BizQcWorkOrderInspectionBatch.batch_name).filter(
BizQcWorkOrderInspectionBatch.tenant_no == tenant_no,
BizQcWorkOrderInspectionBatch.del_flag == 0,
BizQcWorkOrderInspectionBatch.batch_name.like(_like_prefix(new), escape="\\"),
)
if qc_ids:
batch_q = batch_q.filter(~BizQcWorkOrderInspectionBatch.work_order_id.in_(_ids(qc_ids)))
for (name,) in batch_q.all():
if _occupies_new_code(name, new):
_raise_if_duplicate()
+4 -1
View File
@@ -5,12 +5,15 @@ from app.core.config import settings
def create_assignment(db, tenant_no, user, project_id, biz_type):
from app.services.project_management import validate_assignment
from app.constants.pilot_biz import requires_leader_approval
if biz_type == 'clinical_application':
if project_id:
raise HTTPException(400, '临床应用不支持项目归属')
return None
# 临床科研/委托加工须绑定项目,供项目组负责人审批
required = True if requires_leader_approval(biz_type) else settings.PROJECT_ASSIGNMENT_REQUIRED
return validate_assignment(db, tenant_no, user, project_id, biz_type,
required=settings.PROJECT_ASSIGNMENT_REQUIRED)
required=required)
def guard_project_edit(row, payload):
+3 -3
View File
@@ -19,6 +19,7 @@ BUSINESS = {
'research_donation': (BizResearchDonation, 'donation_no', 'donation_status'),
'pilot_service': (BizPilotApplication, 'application_no', 'application_status'),
'basic_experiment': (BizPilotApplication, 'application_no', 'application_status'),
'contract_processing': (BizPilotApplication, 'application_no', 'application_status'),
}
COUNT_TYPES = tuple(k for k in BUSINESS if k != 'presign')
ALL_PROJECTS_PERMISSION = 'project:project:all'
@@ -215,8 +216,7 @@ def preview_assignment(db, tenant, user, kind, row_id, project_id):
def assign(db, tenant, user, kind, row_id, project_id, reason, expected):
check_permission(db, tenant, user, 'project:assignment:edit')
if not reason or not reason.strip():
raise HTTPException(400, '请填写调整原因')
reason_text = (reason or '').strip()
rows = linked_records(db, tenant, user, kind, row_id, lock=True)
actual = {(k, r.id, r.project_id) for k, r in rows}
refreshed = linked_records(db, tenant, user, kind, row_id, current_read=True)
@@ -228,7 +228,7 @@ def assign(db, tenant, user, kind, row_id, project_id, reason, expected):
new_name = project_brief(db, tenant, project_id)['projectName']
operator = scoped(db, SysUser, tenant).filter(SysUser.id == user.get('user_id')).first()
for k, row in rows:
db.add(ProjectAssignmentAudit(id=generate_uuid(), tenant_no=tenant, biz_type=k, biz_id=row.id, old_project_id=row.project_id, new_project_id=project_id, old_project_name=project_brief(db, tenant, row.project_id)['projectName'], new_project_name=new_name, reason=reason.strip(), operator_name=operator.nick_name if operator else user.get('user_id'), create_by=user.get('user_id'), create_dept_id=user.get('dept_id') or ''))
db.add(ProjectAssignmentAudit(id=generate_uuid(), tenant_no=tenant, biz_type=k, biz_id=row.id, old_project_id=row.project_id, new_project_id=project_id, old_project_name=project_brief(db, tenant, row.project_id)['projectName'], new_project_name=new_name, reason=reason_text, operator_name=operator.nick_name if operator else user.get('user_id'), create_by=user.get('user_id'), create_dept_id=user.get('dept_id') or ''))
row.project_id = project_id
row.update_by = user.get('user_id')
row.update_time = datetime.now()
@@ -1,4 +1,4 @@
"""质检工单 · 用户费用摘要(采集协议 / 基础实验)"""
"""质检工单 · 用户费用摘要(采集协议 / 临床科研)"""
from __future__ import annotations
from decimal import Decimal
@@ -27,8 +27,10 @@ _PAY_STATUS_LABELS = {
"ytf": "已退费",
}
# 出库工单:输注计划缴费(基础实验 / 临床应用共用 biz_pilot_payment)
_OUTBOUND_FEE_BIZ_TYPES = frozenset({"basic_experiment", "clinical_application"})
# 出库工单:输注计划缴费(临床科研 / 临床应用共用 biz_pilot_payment)
_OUTBOUND_FEE_BIZ_TYPES = frozenset(
{"basic_experiment", "contract_processing", "clinical_application"}
)
def _is_outbound_fee_biz_type(biz_type: Optional[str]) -> bool:
+1 -1
View File
@@ -246,7 +246,7 @@ def send_basic_experiment_delivery_remind(
time_text: str,
pagepath: str = "",
) -> dict:
"""基础实验:交付日前一天出库提醒。"""
"""临床科研:交付日前一天出库提醒。"""
data: Dict[str, Dict[str, str]] = {}
customer_key = (settings.WX_MP_TPL_BE_DELIVERY_FIELD_CUSTOMER or "").strip()
product_key = (settings.WX_MP_TPL_BE_DELIVERY_FIELD_PRODUCT or "").strip()
@@ -0,0 +1,467 @@
#!/usr/bin/env python3
"""作废「已完成合同审批」中未被付款审批关联的重复单。
背景:发起人误提两张相同合同审批,其中一张已被付款单通过 oa_relation 关联,
另一张未关联。产品撤回 API 仅允许 running→cancelled,无法作废已完成单。
本脚本:
1) 按申请人昵称 + 流程名「合同审批」定位候选实例
2) 用 oa_relation.to_instance_id 区分已关联 / 未关联
3) 断言恰好 1 张已关联、1 张未关联后,对未关联单软删除作废
用法(backend 目录、已配置目标库):
python -m scripts.repair_oa_void_unlinked_contract_duplicate \\
--nick-name 胡倩茜 --create-time '2026-11-25 12:00:56'
python -m scripts.repair_oa_void_unlinked_contract_duplicate \\
--nick-name 胡倩茜 --create-time '2026-11-25 12:00:56' --apply
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from datetime import datetime
from typing import Any, Dict, List, Optional
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sqlalchemy.orm import Session
from app.core.database import SessionLocal
from app.core.utils import generate_uuid
from app.models.models import (
OaApp,
OaInstance,
OaInstanceEvent,
OaRelation,
SysUser,
)
CONTRACT_APP_NAME = "合同审批"
PAYMENT_APP_NAME = "付款审批"
def _parse_create_time(raw: Optional[str]) -> Optional[datetime]:
text = (raw or "").strip()
if not text:
return None
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
try:
return datetime.strptime(text, fmt)
except ValueError:
continue
raise RuntimeError(
f"无法解析 --create-time={raw!r},请用 'YYYY-MM-DD HH:MM:SS'"
)
def _find_user(db: Session, *, nick_name: str, tenant_no: Optional[str]) -> SysUser:
q = db.query(SysUser).filter(
SysUser.del_flag == 0,
SysUser.nick_name == nick_name,
)
if tenant_no:
q = q.filter(SysUser.tenant_no == tenant_no)
rows = q.all()
if not rows:
raise RuntimeError(f"未找到用户 nick_name={nick_name!r}")
if len(rows) > 1 and not tenant_no:
raise RuntimeError(
"匹配到多名用户,请加 --tenant。"
f" 候选: {[{'id': u.id, 'tenantNo': u.tenant_no, 'userNo': u.user_no} for u in rows]}"
)
return rows[0]
def _find_app(db: Session, *, app_name: str, tenant_no: str) -> OaApp:
row = (
db.query(OaApp)
.filter(
OaApp.del_flag == 0,
OaApp.tenant_no == tenant_no,
OaApp.app_name == app_name,
)
.first()
)
if not row:
# 宽松匹配,便于生产命名略有差异时定位
cands = (
db.query(OaApp)
.filter(
OaApp.del_flag == 0,
OaApp.tenant_no == tenant_no,
OaApp.app_name.like(f"%{app_name}%"),
)
.all()
)
names = [a.app_name for a in cands]
raise RuntimeError(
f"未找到应用 app_name={app_name!r} tenant={tenant_no!r};近似: {names}"
)
return row
def _list_contract_instances(
db: Session,
*,
user: SysUser,
contract_app: OaApp,
create_time: Optional[datetime],
) -> List[OaInstance]:
q = db.query(OaInstance).filter(
OaInstance.del_flag == 0,
OaInstance.tenant_no == user.tenant_no,
OaInstance.app_id == contract_app.id,
OaInstance.initiator_user_id == user.id,
OaInstance.status == "completed",
)
if create_time is not None:
q = q.filter(OaInstance.create_time == create_time)
rows = q.order_by(OaInstance.create_time.asc(), OaInstance.id.asc()).all()
if not rows:
raise RuntimeError(
"未找到已完成的合同审批实例。"
f" user={user.nick_name} app={contract_app.app_name}"
f" create_time={create_time}"
)
if len(rows) < 2:
raise RuntimeError(
f"仅找到 {len(rows)} 张已完成合同审批,预期至少 2 张重复单。"
f" ids={[r.id for r in rows]}"
)
if create_time is None and len(rows) > 2:
raise RuntimeError(
f"未指定 --create-time 时匹配到 {len(rows)} 张,请加上精确申请时间缩小范围。"
f" ids={[r.id for r in rows]}"
)
return rows
def _linked_contract_ids(
db: Session, *, contract_ids: List[str], tenant_no: str
) -> Dict[str, List[Dict[str, Any]]]:
"""返回 contract_id -> 关联边摘要(付款 from → 合同 to)。"""
if not contract_ids:
return {}
rels = (
db.query(OaRelation)
.filter(
OaRelation.del_flag == 0,
OaRelation.tenant_no == tenant_no,
OaRelation.to_instance_id.in_(contract_ids),
)
.all()
)
out: Dict[str, List[Dict[str, Any]]] = {cid: [] for cid in contract_ids}
if not rels:
return out
from_ids = list({r.from_instance_id for r in rels})
from_inst = {
i.id: i
for i in db.query(OaInstance)
.filter(OaInstance.id.in_(from_ids), OaInstance.del_flag == 0)
.all()
}
app_ids = list({i.app_id for i in from_inst.values()})
apps = {
a.id: a
for a in db.query(OaApp).filter(OaApp.id.in_(app_ids), OaApp.del_flag == 0).all()
}
for r in rels:
fi = from_inst.get(r.from_instance_id)
app = apps.get(fi.app_id) if fi else None
out.setdefault(r.to_instance_id, []).append(
{
"relationId": r.id,
"paymentInstanceId": r.from_instance_id,
"paymentStatus": getattr(fi, "status", None),
"paymentAppName": getattr(app, "app_name", None),
"fieldKey": r.field_key,
"relationCreateTime": str(r.create_time) if r.create_time else None,
}
)
return out
def _void_instance(
db: Session,
*,
inst: OaInstance,
actor_user_id: Optional[str],
mode: str,
) -> Dict[str, Any]:
now = datetime.now()
before = {"id": inst.id, "status": inst.status, "delFlag": inst.del_flag}
if mode == "soft-delete":
inst.del_flag = 1
inst.status = "cancelled"
elif mode == "cancel":
inst.status = "cancelled"
else:
raise RuntimeError(f"未知 --mode={mode!r}")
inst.update_by = actor_user_id
inst.update_time = now
remark = (
"生产数据修复:重复合同审批未关联付款,软删除作废"
if mode == "soft-delete"
else "生产数据修复:重复合同审批未关联付款,状态改为已撤销"
)
if not (inst.remark or "").strip():
inst.remark = remark
db.add(inst)
ev = OaInstanceEvent(
id=generate_uuid(),
instance_id=inst.id,
round_no=int(getattr(inst, "current_round", None) or 1),
event_type="withdraw",
actor_user_id=actor_user_id,
task_id=None,
node_key=None,
comment_text=remark,
tenant_no=inst.tenant_no,
order_num=0,
remark="repair_oa_void_unlinked_contract_duplicate",
create_by=actor_user_id,
create_dept_id=inst.initiator_dept_id or "",
create_time=now,
update_by=actor_user_id,
update_time=now,
del_flag=0,
)
db.add(ev)
return {
"before": before,
"after": {"id": inst.id, "status": inst.status, "delFlag": inst.del_flag},
"eventId": ev.id,
"mode": mode,
}
def analyze(
db: Session,
*,
nick_name: str,
create_time: Optional[datetime],
tenant_no: Optional[str],
contract_app_name: str,
) -> Dict[str, Any]:
user = _find_user(db, nick_name=nick_name, tenant_no=tenant_no)
tn = user.tenant_no
contract_app = _find_app(db, app_name=contract_app_name, tenant_no=tn)
payment_app = (
db.query(OaApp)
.filter(
OaApp.del_flag == 0,
OaApp.tenant_no == tn,
OaApp.app_name == PAYMENT_APP_NAME,
)
.first()
)
instances = _list_contract_instances(
db, user=user, contract_app=contract_app, create_time=create_time
)
ids = [i.id for i in instances]
links = _linked_contract_ids(db, contract_ids=ids, tenant_no=tn)
linked_ids: List[str] = [cid for cid, rels in links.items() if rels]
unlinked_ids: List[str] = [cid for cid in ids if cid not in linked_ids]
candidates = [
{
"id": i.id,
"title": i.title,
"status": i.status,
"createTime": str(i.create_time) if i.create_time else None,
"updateTime": str(i.update_time) if i.update_time else None,
"linkedPayments": links.get(i.id) or [],
"decision": "keep" if i.id in linked_ids else "void_candidate",
}
for i in instances
]
errors: List[str] = []
if len(linked_ids) != 1:
errors.append(
f"期望恰好 1 张已被付款关联的合同,实际 {len(linked_ids)}: {linked_ids}"
)
if len(unlinked_ids) != 1:
errors.append(
f"期望恰好 1 张未关联合同待作废,实际 {len(unlinked_ids)}: {unlinked_ids}"
)
# 关联来源最好是付款审批(非硬失败,仅警告)
warnings: List[str] = []
for cid in linked_ids:
for rel in links.get(cid) or []:
pname = (rel.get("paymentAppName") or "").strip()
if payment_app and pname and pname != PAYMENT_APP_NAME:
warnings.append(
f"合同 {cid} 被非付款应用关联: {pname} ({rel.get('paymentInstanceId')})"
)
if not pname:
warnings.append(
f"合同 {cid} 关联来源应用名未知: {rel.get('paymentInstanceId')}"
)
return {
"user": {
"id": user.id,
"nickName": user.nick_name,
"userNo": user.user_no,
"tenantNo": tn,
},
"contractApp": {"id": contract_app.id, "appName": contract_app.app_name},
"paymentApp": (
{"id": payment_app.id, "appName": payment_app.app_name}
if payment_app
else None
),
"createTimeFilter": str(create_time) if create_time else None,
"candidates": candidates,
"linkedContractIds": linked_ids,
"unlinkedContractIds": unlinked_ids,
"voidTargetId": unlinked_ids[0] if len(unlinked_ids) == 1 else None,
"keepTargetId": linked_ids[0] if len(linked_ids) == 1 else None,
"errors": errors,
"warnings": warnings,
"safeToApply": len(errors) == 0,
}
def run(
*,
nick_name: str,
create_time_raw: Optional[str],
tenant_no: Optional[str],
contract_app_name: str,
apply: bool,
mode: str,
actor_user_id: Optional[str],
) -> Dict[str, Any]:
create_time = _parse_create_time(create_time_raw)
db = SessionLocal()
try:
report = analyze(
db,
nick_name=nick_name.strip(),
create_time=create_time,
tenant_no=(tenant_no or "").strip() or None,
contract_app_name=(contract_app_name or CONTRACT_APP_NAME).strip()
or CONTRACT_APP_NAME,
)
if not apply:
db.rollback()
return {
"dryRun": True,
"mode": mode,
"analysis": report,
"message": (
"dry-run:未写库。"
"确认 voidTargetId 正确且 safeToApply=true 后加 --apply。"
),
}
if not report.get("safeToApply"):
db.rollback()
return {
"dryRun": False,
"applied": False,
"mode": mode,
"analysis": report,
"message": "分析未通过安全断言,已回滚,未写库。",
}
target_id = report["voidTargetId"]
inst = (
db.query(OaInstance)
.filter(
OaInstance.id == target_id,
OaInstance.del_flag == 0,
)
.one()
)
# 二次校验:写库前再确认仍未被关联
still_linked = (
db.query(OaRelation.id)
.filter(
OaRelation.del_flag == 0,
OaRelation.tenant_no == inst.tenant_no,
OaRelation.to_instance_id == inst.id,
)
.first()
)
if still_linked:
db.rollback()
raise RuntimeError(
f"写库前发现目标 {inst.id} 已被关联,中止作废以防误伤"
)
actor = actor_user_id or inst.initiator_user_id
void_result = _void_instance(
db, inst=inst, actor_user_id=actor, mode=mode
)
db.commit()
return {
"dryRun": False,
"applied": True,
"mode": mode,
"analysis": report,
"voidResult": void_result,
"message": "已作废未关联合同审批;已关联付款的合同未改动。",
}
except Exception:
db.rollback()
raise
finally:
db.close()
def main(argv: Optional[List[str]] = None) -> int:
parser = argparse.ArgumentParser(
description="作废未被付款关联的重复已完成合同审批"
)
parser.add_argument("--nick-name", required=True, help="申请人昵称,如 胡倩茜")
parser.add_argument(
"--create-time",
default=None,
help="申请时间,精确匹配 oa_instance.create_time,如 '2026-11-25 12:00:56'",
)
parser.add_argument("--tenant", default=None, help="租户编号;重名用户时必填")
parser.add_argument(
"--contract-app-name",
default=CONTRACT_APP_NAME,
help=f"合同审批应用名,默认 {CONTRACT_APP_NAME}",
)
parser.add_argument(
"--mode",
choices=("soft-delete", "cancel"),
default="soft-delete",
help="soft-delete=列表消失(默认);cancel=仅改为已撤销仍可见",
)
parser.add_argument("--apply", action="store_true", help="实际写库;默认 dry-run")
parser.add_argument(
"--actor-user-id",
default=None,
help="事件操作人;默认用发起人",
)
args = parser.parse_args(argv)
result = run(
nick_name=args.nick_name,
create_time_raw=args.create_time,
tenant_no=args.tenant,
contract_app_name=args.contract_app_name,
apply=bool(args.apply),
mode=args.mode,
actor_user_id=args.actor_user_id,
)
print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
analysis = result.get("analysis") or {}
if analysis.get("errors"):
return 2
if result.get("dryRun") is False and not result.get("applied"):
return 2
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,308 @@
#!/usr/bin/env python3
"""补建「先废弃后改接收」漏掉的下游单据。
样本接收编辑接口不会重复创建质检/生产工单、入库放行与内置任务派发。
本脚本对指定接收记录回放首次「接收」路径(幂等):
1) 质检工单 create_work_order_from_reception
2) 生产工单 create_production_work_order_from_reception
3) UBMC/UC/... 内置任务 try_auto_dispatch_builtin_tasks_after_reception
4) 入库放行审核 create_review_from_reception(已存在则跳过)
5) after_sample_reception_saved(清样本作废态)
用法(在 backend 目录、已配置目标库连接):
python -m scripts.repair_reception_downstream_after_bj_to_js \\
--sample-code KYJZ2026110105 --lab-storage-code UBMC202611048
# 确认输出后写库
python -m scripts.repair_reception_downstream_after_bj_to_js \\
--sample-code KYJZ2026110105 --lab-storage-code UBMC202611048 --apply
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from typing import Any, Dict, Optional
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
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.crud import production_work_order as prod_wo_svc
from app.crud import qc_work_order as qc_wo_svc
from app.crud import storage_release_review as srr_svc
from app.models.models import (
BizProductionTask,
BizProductionWorkOrder,
BizQcWorkOrder,
BizResearchDonation,
BizResearchDonationSample,
BizSampleReception,
BizStorageReleaseReview,
)
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
def _find_reception(
db: Session,
*,
sample_code: str,
lab_storage_code: str,
tenant_no: Optional[str],
) -> BizSampleReception:
q = db.query(BizSampleReception).filter(
BizSampleReception.del_flag == 0,
BizSampleReception.sample_code == sample_code,
BizSampleReception.lab_storage_code == lab_storage_code,
)
if tenant_no:
q = q.filter(BizSampleReception.tenant_no == tenant_no)
rows = q.order_by(BizSampleReception.create_time.desc()).all()
if not rows:
raise RuntimeError(
f"未找到接收记录 sample_code={sample_code!r} "
f"lab_storage_code={lab_storage_code!r}"
)
if len(rows) > 1 and not tenant_no:
tenants = sorted({r.tenant_no for r in rows})
raise RuntimeError(
f"匹配到多条接收记录,请加 --tenant。tenant_no 候选: {tenants}"
)
return rows[0]
def _srr_snapshot(db: Session, rec: BizSampleReception) -> Dict[str, str]:
protocol_no = ""
sample_name = ""
source = (rec.reception_source or "cell_storage").strip() or "cell_storage"
if source == "research_donation":
d = (
db.query(BizResearchDonation)
.filter(
BizResearchDonation.id == (rec.research_donation_id or ""),
BizResearchDonation.del_flag == 0,
)
.first()
)
if d:
protocol_no = d.donation_no or ""
ds = (
db.query(BizResearchDonationSample)
.filter(
BizResearchDonationSample.id == (rec.donation_sample_id or ""),
BizResearchDonationSample.del_flag == 0,
)
.first()
)
if ds:
sample_name = ds.sample_code or ""
else:
sample_name = rec.sample_code or ""
protocol_no = ""
return {"protocol_no": protocol_no, "sample_name": sample_name}
def _existing_summary(db: Session, *, rec: BizSampleReception) -> Dict[str, Any]:
tn = rec.tenant_no
qc = (
db.query(BizQcWorkOrder)
.filter(
BizQcWorkOrder.reception_id == rec.id,
BizQcWorkOrder.tenant_no == tn,
BizQcWorkOrder.del_flag == 0,
)
.first()
)
prod = (
db.query(BizProductionWorkOrder)
.filter(
BizProductionWorkOrder.reception_id == rec.id,
BizProductionWorkOrder.tenant_no == tn,
BizProductionWorkOrder.del_flag == 0,
)
.first()
)
task_count = 0
if prod:
task_count = (
db.query(BizProductionTask.id)
.filter(
BizProductionTask.work_order_id == prod.id,
BizProductionTask.tenant_no == tn,
BizProductionTask.del_flag == 0,
)
.count()
)
srr = (
db.query(BizStorageReleaseReview)
.filter(
BizStorageReleaseReview.reception_id == rec.id,
BizStorageReleaseReview.tenant_no == tn,
BizStorageReleaseReview.del_flag == 0,
)
.first()
)
return {
"receptionId": rec.id,
"tenantNo": tn,
"acceptConclusion": rec.accept_conclusion,
"receptionSource": rec.reception_source,
"qcWorkOrderNo": getattr(qc, "work_order_no", None),
"productionWorkOrderNo": getattr(prod, "work_order_no", None),
"productionTaskCount": task_count,
"storageReleaseReviewId": getattr(srr, "id", None),
"storageStatus": getattr(srr, "storage_status", None),
}
def run(
*,
sample_code: str,
lab_storage_code: str,
tenant_no: Optional[str],
apply: bool,
user_id: Optional[str],
create_dept_id: Optional[str],
) -> Dict[str, Any]:
db = SessionLocal()
try:
rec = _find_reception(
db,
sample_code=sample_code.strip(),
lab_storage_code=lab_storage_code.strip(),
tenant_no=(tenant_no or "").strip() or None,
)
before = _existing_summary(db, rec=rec)
conclusion = (rec.accept_conclusion or "").strip()
if conclusion != "js":
raise RuntimeError(
f"接收结论当前为 {conclusion!r},须先为 js(接收)再回补下游"
)
uid = user_id if user_id is not None else rec.create_by
dept = (
create_dept_id
if create_dept_id is not None
else (rec.create_dept_id or "")
)
tn = rec.tenant_no
if not apply:
db.rollback()
return {
"dryRun": True,
"before": before,
"message": (
"dry-run:未写库。确认 before 后加 --apply。"
"将补建缺失的质检/生产工单、内置任务与入库放行。"
),
}
qc = qc_wo_svc.create_work_order_from_reception(
db,
reception=rec,
tenant_no=tn,
user_id=uid,
create_dept_id=dept or "",
)
prod = prod_wo_svc.create_production_work_order_from_reception(
db,
reception=rec,
tenant_no=tn,
user_id=uid,
create_dept_id=dept or "",
)
dispatch = None
if prod is not None:
dispatch = production_task_set_svc.try_auto_dispatch_builtin_tasks_after_reception(
db,
tenant_no=tn,
user_id=uid,
create_dept_id=dept or "",
work_order=prod,
lab_storage_code=rec.lab_storage_code,
)
srr_row = (
db.query(BizStorageReleaseReview)
.filter(
BizStorageReleaseReview.reception_id == rec.id,
BizStorageReleaseReview.tenant_no == tn,
BizStorageReleaseReview.del_flag == 0,
)
.first()
)
srr_created = False
if srr_row is None:
snap = _srr_snapshot(db, rec)
srr_row = srr_svc.create_review_from_reception(
db,
reception=rec,
protocol_no=snap["protocol_no"],
sample_name=snap["sample_name"],
tenant_no=tn,
user_id=uid,
create_dept_id=dept or "",
)
srr_created = True
after_sample_reception_saved(
db, reception=rec, tenant_no=tn, user_id=uid
)
db.commit()
after = _existing_summary(db, rec=rec)
return {
"dryRun": False,
"before": before,
"after": after,
"qcWorkOrderNo": getattr(qc, "work_order_no", None),
"productionWorkOrderNo": getattr(prod, "work_order_no", None),
"dispatch": dispatch,
"storageReleaseReviewId": getattr(srr_row, "id", None),
"storageReleaseCreated": srr_created,
}
except Exception:
db.rollback()
raise
finally:
db.close()
def main(argv: Optional[list] = None) -> int:
parser = argparse.ArgumentParser(
description="补建样本接收 bj→js 后缺失的质检/生产/入库放行下游"
)
parser.add_argument("--sample-code", required=True, help="样本编码")
parser.add_argument("--lab-storage-code", required=True, help="实验室入库编码")
parser.add_argument("--tenant", default=None, help="租户编号;多租户命中时必填")
parser.add_argument(
"--apply",
action="store_true",
help="实际写库;默认仅 dry-run",
)
parser.add_argument("--user-id", default=None, help="写库 create_by;默认用接收记录")
parser.add_argument(
"--create-dept-id",
default=None,
help="写库 create_dept_id;默认用接收记录",
)
args = parser.parse_args(argv)
result = run(
sample_code=args.sample_code,
lab_storage_code=args.lab_storage_code,
tenant_no=args.tenant,
apply=bool(args.apply),
user_id=args.user_id,
create_dept_id=args.create_dept_id,
)
print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,140 @@
"""一次性造数:临床科研 / 委托加工申请单各 5 条(本地开发用)。
用法(工程 backend 目录):
.\\venv\\Scripts\\python.exe scripts\\seed_research_like_applications.py
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from app.core.database import SessionLocal # noqa: E402
from app.crud import pilot_application as crud # noqa: E402
from app.models.models import SysUser # noqa: E402
from app.models.project_management import Project # noqa: E402
TENANT = "zkxw"
COUNT = 5
CLINICAL_CATEGORIES = [
"bio_tech_clinical",
"joint_topic_declare",
"bio_pharma_rd",
"bio_tech_clinical",
"joint_topic_declare",
]
CONTRACT_CATEGORIES = ["msc", "nk", "placenta_freeze_dried", "adipose_exosome", "msc"]
def _pick_admin(db) -> tuple[str, str]:
row = (
db.query(SysUser)
.filter(SysUser.tenant_no == TENANT, SysUser.del_flag == 0, SysUser.status == "1")
.order_by(SysUser.create_time.asc())
.first()
)
if not row:
raise SystemExit("未找到可用用户")
return row.id, row.dept_id or ""
def _pick_projects(db, need: int) -> list[Project]:
rows = (
db.query(Project)
.filter(
Project.tenant_no == TENANT,
Project.del_flag == 0,
Project.leader_user_id.isnot(None),
Project.leader_user_id != "",
)
.order_by(Project.create_time.desc())
.limit(max(need, 20))
.all()
)
rows = [p for p in rows if (p.leader_user_id or "").strip()]
if not rows:
raise SystemExit("未找到已设置项目负责人的项目,请先在项目管理中维护")
# 循环复用
out: list[Project] = []
i = 0
while len(out) < need:
out.append(rows[i % len(rows)])
i += 1
return out
def _seed_one(
db,
*,
biz_type: str,
idx: int,
project: Project,
user_id: str,
dept_id: str,
category: str,
) -> dict:
label = "临床科研" if biz_type == "basic_experiment" else "委托加工"
data = {
"bizType": biz_type,
"projectId": project.id,
"researchCategory": category,
"projectTitle": f"种子{label}课题{idx:02d}",
"customerName": f"种子客户{label}{idx:02d}",
"customerContact": f"联系人{idx}",
"customerPhone": f"1380000{idx:04d}",
"applicationName": f"种子{label}申请单{idx:02d}",
"remark": "seed-script-2026-11-27",
}
return crud.create_application(
db, data=data, tenant_no=TENANT, user_id=user_id, dept_id=dept_id
)
def main() -> None:
db = SessionLocal()
try:
user_id, dept_id = _pick_admin(db)
projects = _pick_projects(db, COUNT * 2)
created = []
for i in range(COUNT):
created.append(
_seed_one(
db,
biz_type="basic_experiment",
idx=i + 1,
project=projects[i],
user_id=user_id,
dept_id=dept_id,
category=CLINICAL_CATEGORIES[i],
)
)
for i in range(COUNT):
created.append(
_seed_one(
db,
biz_type="contract_processing",
idx=i + 1,
project=projects[COUNT + i],
user_id=user_id,
dept_id=dept_id,
category=CONTRACT_CATEGORIES[i],
)
)
print(f"created={len(created)}")
for row in created:
print(
f"{row.get('bizType')}\t{row.get('applicationNo')}\t"
f"{row.get('projectTitle')}\t{row.get('approvalStatus')}\t"
f"project={row.get('projectName') or row.get('projectId')}"
)
finally:
db.close()
if __name__ == "__main__":
main()
@@ -1,4 +1,4 @@
"""基础实验申请单与售卖计划批量创建"""
"""临床科研申请单与售卖计划批量创建"""
import unittest
from unittest.mock import MagicMock, patch
@@ -18,9 +18,9 @@ class TestBasicExperimentApplicationNo(unittest.TestCase):
result = crud._generate_application_no(db, "zkxw", biz_type="basic_experiment")
self.assertTrue(result.startswith("JCSY"))
self.assertNotIn("JCSQ", result)
self.assertEqual(result, "JCSY202606100001")
self.assertTrue(result.startswith("LCKY"))
self.assertNotIn("JCSY", result)
self.assertEqual(result, "LCKY202606100001")
class TestBasicExperimentCreateValidation(unittest.TestCase):
@@ -28,6 +28,8 @@ class TestBasicExperimentCreateValidation(unittest.TestCase):
db = MagicMock()
data = {
"bizType": "basic_experiment",
"researchCategory": "bio_tech_clinical",
"channelId": "ch-1",
"projectTitle": "课题A",
"customerName": "",
"customerContact": "张三",
@@ -43,6 +45,47 @@ class TestBasicExperimentCreateValidation(unittest.TestCase):
)
self.assertIn("客户名称", str(ctx.exception))
def test_create_basic_experiment_requires_research_category(self):
db = MagicMock()
data = {
"bizType": "basic_experiment",
"channelId": "ch-1",
"projectTitle": "课题A",
"customerName": "客户A",
"customerContact": "张三",
"customerPhone": "13800000000",
}
with self.assertRaises(ValueError) as ctx:
crud.create_application(
db,
data=data,
tenant_no="zkxw",
user_id="user-1",
dept_id="dept-1",
)
self.assertIn("业务类型", str(ctx.exception))
def test_create_basic_experiment_allows_missing_channel(self):
"""临床科研申请单不再要求渠道;缺项目负责人时仍会失败。"""
db = MagicMock()
data = {
"bizType": "basic_experiment",
"researchCategory": "bio_tech_clinical",
"projectTitle": "课题A",
"customerName": "客户A",
"customerContact": "张三",
"customerPhone": "13800000000",
}
with self.assertRaises(ValueError) as ctx:
crud.create_application(
db,
data=data,
tenant_no="zkxw",
user_id="user-1",
dept_id="dept-1",
)
self.assertNotIn("渠道", str(ctx.exception))
class TestBasicExperimentSaleSchedules(unittest.TestCase):
@patch("app.crud.pilot_application.create_schedule")
@@ -1,4 +1,4 @@
"""基础实验交付日前一天服务号提醒单测。"""
"""临床科研交付日前一天服务号提醒单测。"""
from datetime import date, datetime
from unittest.mock import MagicMock, patch
@@ -0,0 +1,81 @@
"""委托加工申请单:编号前缀、业务子类型校验、复用临床科研创建校验。"""
import unittest
from unittest.mock import MagicMock, patch
from app.constants.research_category import validate_research_category
from app.crud import pilot_application as crud
class TestContractProcessingApplicationNo(unittest.TestCase):
@patch("app.crud.pilot_application.datetime")
def test_generate_application_no_contract_processing_prefix(self, mock_dt):
mock_dt.now.return_value.strftime.return_value = "20261123"
db = MagicMock()
mock_query = MagicMock()
db.query.return_value = mock_query
mock_query.filter.return_value = mock_query
mock_query.order_by.return_value = mock_query
mock_query.first.return_value = None
result = crud._generate_application_no(db, "zkxw", biz_type="contract_processing")
self.assertEqual(result, "WTJG202611230001")
class TestContractProcessingResearchCategory(unittest.TestCase):
def test_fixed_categories(self):
self.assertEqual(
validate_research_category("placenta_freeze_dried", required=True, biz_type="contract_processing"),
"placenta_freeze_dried",
)
self.assertEqual(
validate_research_category("nk", required=True, biz_type="contract_processing"),
"nk",
)
def test_custom_other_text(self):
self.assertEqual(
validate_research_category("自定义产品A", required=True, biz_type="contract_processing"),
"自定义产品A",
)
def test_clinical_codes_rejected_for_contract_processing(self):
with self.assertRaises(ValueError):
validate_research_category(
"bio_tech_clinical", required=True, biz_type="contract_processing"
)
def test_clinical_still_uses_legacy_codes(self):
self.assertEqual(
validate_research_category("bio_tech_clinical", required=True, biz_type="basic_experiment"),
"bio_tech_clinical",
)
with self.assertRaises(ValueError):
validate_research_category("nk", required=True, biz_type="basic_experiment")
class TestContractProcessingCreateValidation(unittest.TestCase):
def test_create_requires_customer_fields(self):
db = MagicMock()
data = {
"bizType": "contract_processing",
"researchCategory": "msc",
"channelId": "ch-1",
"projectTitle": "课题A",
"customerName": "",
"customerContact": "张三",
"customerPhone": "13800000000",
}
with self.assertRaises(ValueError) as ctx:
crud.create_application(
db,
data=data,
tenant_no="zkxw",
user_id="user-1",
dept_id="dept-1",
)
self.assertIn("客户名称", str(ctx.exception))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,62 @@
"""委托加工自定义业务类型 CRUD"""
import unittest
from unittest.mock import MagicMock, patch
from app.crud import contract_processing_category as crud
class TestContractProcessingCategoryValidation(unittest.TestCase):
def test_reject_reserved_fixed_code(self):
with self.assertRaises(ValueError) as ctx:
crud._assert_valid_name("nk")
self.assertIn("预置", str(ctx.exception))
def test_reject_reserved_fixed_label(self):
with self.assertRaises(ValueError) as ctx:
crud._assert_valid_name("胎盘冻干粉")
self.assertIn("预置", str(ctx.exception))
def test_reject_empty(self):
with self.assertRaises(ValueError):
crud._assert_valid_name(" ")
def test_accept_custom(self):
self.assertEqual(crud._assert_valid_name(" 外泌体定制A "), "外泌体定制A")
class TestContractProcessingCategoryCreate(unittest.TestCase):
@patch("app.crud.contract_processing_category._exists_name", return_value=False)
@patch("app.crud.contract_processing_category.generate_uuid", return_value="cat-1")
def test_create_ok(self, _uuid, _exists):
db = MagicMock()
obj = crud.create_category(
db,
category_name="定制产品B",
tenant_no="zkxw",
biz_type="contract_processing",
user_id="u1",
commit=False,
)
self.assertEqual(obj.category_name, "定制产品B")
self.assertEqual(obj.biz_type, "contract_processing")
db.add.assert_called()
db.flush.assert_called()
@patch("app.crud.contract_processing_category._exists_name", return_value=False)
@patch("app.crud.contract_processing_category.generate_uuid", return_value="cat-bex")
def test_create_basic_experiment_ok(self, _uuid, _exists):
db = MagicMock()
obj = crud.create_category(
db,
category_name="定制科研课题A",
tenant_no="zkxw",
biz_type="basic_experiment",
user_id="u1",
commit=False,
)
self.assertEqual(obj.biz_type, "basic_experiment")
self.assertEqual(obj.category_name, "定制科研课题A")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,53 @@
"""市场下「中试服务」已从静态菜单树下线(Issue #158)。"""
import ast
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
MENU_PY = ROOT / "backend/app/api/menu.py"
SQXP_TS = ROOT / "web-admin/src/router/modules/sqxp.ts"
HIDE_SQL = ROOT / "docs/sql/migrations/2026-11-20-hide-market-pilot-service-menus.sql"
def _market_children_titles_from_menu_py() -> list[str]:
source = MENU_PY.read_text(encoding="utf-8")
tree_match = re.search(r"STATIC_MENU_TREE\s*=\s*(\[[\s\S]*?\n\])\s*\n", source)
assert tree_match, "STATIC_MENU_TREE not found"
tree = ast.literal_eval(tree_match.group(1))
market = next(
node
for node in tree
if isinstance(node, dict) and (node.get("meta") or {}).get("menuCode") == "menu:market"
)
titles = []
for child in market.get("children") or []:
meta = child.get("meta") or {}
titles.append(str(meta.get("title") or ""))
return titles
def test_backend_static_menu_has_no_market_pilot_service():
titles = _market_children_titles_from_menu_py()
assert "中试服务" not in titles
assert "中试服务申请单" not in titles
def test_frontend_sqxp_has_no_market_pilot_service_block():
text = SQXP_TS.read_text(encoding="utf-8")
assert "name: 'PilotService'" not in text
assert "id: 'PIL00000000000000000000000000001'" not in text
assert "pilot-service:pilot-application:list" not in text
# 基础实验 / 临床仍可复用出库放行组件与权限码前缀
assert "basic-experiment:outbound-release-review:list" in text
assert "clinical-application:outbound-release-review:list" in text
def test_hide_sql_soft_deletes_sys_menu_only_under_market_pilot():
sql = HIDE_SQL.read_text(encoding="utf-8")
compact = re.sub(r"\s+", " ", re.sub(r"--[^\n]*", "", sql))
assert re.search(r"UPDATE\s+sys_menu", compact, re.IGNORECASE)
assert re.search(r"SET\s+m\.del_flag\s*=\s*1", compact, re.IGNORECASE)
assert "menu:market" in compact
assert "中试服务" in compact
assert not re.search(r"DELETE\s+FROM\s+sys_menu", compact, re.IGNORECASE)
@@ -0,0 +1,460 @@
"""编辑样本接收时同步实验室入库编码副本。"""
from datetime import datetime
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.crud import sample_reception as reception_svc
from app.models.base import Base
from app.models.models import (
BizCellProduct,
BizLabSampleProcessingExtra,
BizLabSampleProcessSupplement,
BizOutboundReleaseCell,
BizProductionTask,
BizProductionTaskInput,
BizProductionTaskOutput,
BizProductionTaskStep,
BizProductionTaskStepOutput,
BizProductionWorkOrder,
BizQcWorkOrder,
BizQcWorkOrderInspectionBatch,
BizSampleReception,
BizSampleReceptionCheckResult,
BizStorageSlotOccupancy,
)
from app.services.lab_storage_code_rename import replace_lab_code_token
def _session():
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(
engine,
tables=[
BizSampleReception.__table__,
BizSampleReceptionCheckResult.__table__,
BizProductionWorkOrder.__table__,
BizProductionTask.__table__,
BizProductionTaskInput.__table__,
BizProductionTaskStep.__table__,
BizProductionTaskStepOutput.__table__,
BizProductionTaskOutput.__table__,
BizCellProduct.__table__,
BizStorageSlotOccupancy.__table__,
BizOutboundReleaseCell.__table__,
BizQcWorkOrder.__table__,
BizQcWorkOrderInspectionBatch.__table__,
BizLabSampleProcessSupplement.__table__,
BizLabSampleProcessingExtra.__table__,
],
)
return sessionmaker(bind=engine)()
def _now():
return datetime(2026, 11, 20, 9, 33, 18)
def _seed(db):
now = _now()
db.add(
BizSampleReception(
id="recv-1",
protocol_sample_id="ps-1",
collection_protocol_id="cp-1",
reception_time=now,
accept_conclusion="js",
reception_source="cell_storage",
sample_code="ZKZX34000957",
lab_storage_code="B00001112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionWorkOrder(
id="pwo-1",
work_order_no="SC202611200001",
reception_id="recv-1",
sample_code="ZKZX34000957",
work_order_status="ywc",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionTask(
id="task-1",
task_no="T-1",
work_order_id="pwo-1",
task_name="B00001112样本处理",
description="编码B00001112",
task_status="ywc",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionTask(
id="task-other",
task_no="T-2",
work_order_id="pwo-other",
task_name="B00001112样本处理",
task_status="ywc",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionTaskInput(
id="in-1",
task_id="task-1",
input_name="B0000112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionTaskStep(
id="step-1",
task_id="task-1",
sop_content="请处理 B00001112,不要改 B000011120",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionTaskStepOutput(
id="so-1",
step_id="step-1",
output_name="脐血",
output_barcode="B0000112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionTaskOutput(
id="out-1",
task_id="task-1",
output_name="B00001112",
output_barcode="B00001112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizCellProduct(
id="cp-1",
product_code="B00001112",
product_name="B00001112",
batch_no="B00001112",
production_task_id="task-1",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizCellProduct(
id="cp-long",
product_code="B000011120",
product_name="其他更长编码",
production_task_id="task-other",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizStorageSlotOccupancy(
id="occ-1",
slot_id="slot-1",
item_type="cell_product",
item_id="cp-1",
item_code="B00001112",
item_name="B00001112",
occupancy_status="stored",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizOutboundReleaseCell(
id="ob-1",
material_id="mat-1",
infusion_schedule_id="inf-1",
cell_product_id="cp-1",
product_code="B00001112",
product_name="B00001112",
batch_no="B00001112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizQcWorkOrder(
id="qc-1",
work_order_no="ZJ202611200001",
reception_id="recv-1",
sample_code="ZKZX34000957",
work_order_status="ypz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizQcWorkOrderInspectionBatch(
id="batch-1",
work_order_id="qc-1",
batch_no="B1",
batch_name="B00001112-脐血",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizQcWorkOrderInspectionBatch(
id="batch-2",
work_order_id="qc-1",
batch_no="B2",
batch_name="B00001112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizLabSampleProcessSupplement(
id="sup-1",
lab_storage_code="B00001112",
payload="{}",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizLabSampleProcessingExtra(
id="extra-1",
dataset="hsc",
sample_code="B00001112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.commit()
def test_replace_keeps_longer_code_and_chinese_suffix():
assert replace_lab_code_token("B00001112样本处理", "B00001112", "B0000112") == "B0000112样本处理"
assert replace_lab_code_token("B00001112-脐血", "B00001112", "B0000112") == "B0000112-脐血"
assert replace_lab_code_token("B000011120", "B00001112", "B0000112") == "B000011120"
assert replace_lab_code_token("B00001112", "B0000112", "B0000999") == "B00001112"
def test_edit_renames_linked_copies_and_skips_unrelated_rows(monkeypatch):
db = _session()
_seed(db)
monkeypatch.setattr(reception_svc, "_can_edit_sample_reception", lambda *args, **kwargs: True)
monkeypatch.setattr(
"app.crud.sample_reception_check_result.save_reception_check_results",
lambda *args, **kwargs: None,
)
monkeypatch.setattr(
"app.services.protocol_reception_discard_sync.after_sample_reception_saved",
lambda *args, **kwargs: None,
)
reception_svc.update_sample_reception(
db,
reception_id="recv-1",
tenant_no="tenant-a",
user_id="user-1",
reception_time=_now(),
handler_user_id=None,
handler_name="质检主管",
receive_temperature="4",
checks=[],
accept_conclusion="js",
receive_attachments=None,
remark=None,
lab_storage_code="B0000112",
)
rec = db.query(BizSampleReception).filter_by(id="recv-1").one()
task = db.query(BizProductionTask).filter_by(id="task-1").one()
other = db.query(BizProductionTask).filter_by(id="task-other").one()
step = db.query(BizProductionTaskStep).filter_by(id="step-1").one()
step_out = db.query(BizProductionTaskStepOutput).filter_by(id="so-1").one()
output = db.query(BizProductionTaskOutput).filter_by(id="out-1").one()
product = db.query(BizCellProduct).filter_by(id="cp-1").one()
longer = db.query(BizCellProduct).filter_by(id="cp-long").one()
occ = db.query(BizStorageSlotOccupancy).filter_by(id="occ-1").one()
outbound = db.query(BizOutboundReleaseCell).filter_by(id="ob-1").one()
batches = {
row.id: row.batch_name
for row in db.query(BizQcWorkOrderInspectionBatch).all()
}
wo = db.query(BizProductionWorkOrder).filter_by(id="pwo-1").one()
qc = db.query(BizQcWorkOrder).filter_by(id="qc-1").one()
supplement = db.query(BizLabSampleProcessSupplement).filter_by(id="sup-1").one()
extra = db.query(BizLabSampleProcessingExtra).filter_by(id="extra-1").one()
kept_input = db.query(BizProductionTaskInput).filter_by(id="in-1").one()
assert rec.lab_storage_code == "B0000112"
assert rec.sample_code == "ZKZX34000957"
assert task.task_name == "B0000112样本处理"
assert task.description == "编码B0000112"
assert other.task_name == "B00001112样本处理"
assert step.sop_content == "请处理 B0000112,不要改 B000011120"
assert step_out.output_barcode == "B0000112"
assert kept_input.input_name == "B0000112"
assert output.output_name == "B0000112"
assert output.output_barcode == "B0000112"
assert product.product_code == "B0000112"
assert product.batch_no == "B0000112"
assert longer.product_code == "B000011120"
assert occ.item_code == "B0000112"
assert outbound.product_code == "B0000112"
assert batches["batch-1"] == "B0000112-脐血"
assert batches["batch-2"] == "B0000112"
assert wo.sample_code == "ZKZX34000957"
assert qc.sample_code == "ZKZX34000957"
assert supplement.lab_storage_code == "B0000112"
assert extra.sample_code == "B0000112"
def test_unchanged_code_does_not_rewrite_copies(monkeypatch):
db = _session()
_seed(db)
monkeypatch.setattr(reception_svc, "_can_edit_sample_reception", lambda *args, **kwargs: True)
monkeypatch.setattr(
"app.crud.sample_reception_check_result.save_reception_check_results",
lambda *args, **kwargs: None,
)
monkeypatch.setattr(
"app.services.protocol_reception_discard_sync.after_sample_reception_saved",
lambda *args, **kwargs: None,
)
before = db.query(BizProductionTask).filter_by(id="task-1").one().update_time
reception_svc.update_sample_reception(
db,
reception_id="recv-1",
tenant_no="tenant-a",
user_id="user-1",
reception_time=_now(),
handler_user_id=None,
handler_name="质检主管",
receive_temperature="4",
checks=[],
accept_conclusion="js",
receive_attachments=None,
remark=None,
lab_storage_code="B00001112",
)
task = db.query(BizProductionTask).filter_by(id="task-1").one()
assert task.task_name == "B00001112样本处理"
assert task.update_time == before
def test_duplicate_product_code_rejects_and_keeps_old_copies(monkeypatch):
db = _session()
_seed(db)
now = _now()
db.add(
BizCellProduct(
id="cp-taken",
product_code="B0000112",
product_name="已被占用",
production_task_id="task-other",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.commit()
monkeypatch.setattr(reception_svc, "_can_edit_sample_reception", lambda *args, **kwargs: True)
monkeypatch.setattr(
"app.crud.sample_reception_check_result.save_reception_check_results",
lambda *args, **kwargs: None,
)
monkeypatch.setattr(
"app.services.protocol_reception_discard_sync.after_sample_reception_saved",
lambda *args, **kwargs: None,
)
with pytest.raises(ValueError, match="实验室入库编码已存在"):
reception_svc.update_sample_reception(
db,
reception_id="recv-1",
tenant_no="tenant-a",
user_id="user-1",
reception_time=_now(),
handler_user_id=None,
handler_name="质检主管",
receive_temperature="4",
checks=[],
accept_conclusion="js",
receive_attachments=None,
remark=None,
lab_storage_code="B0000112",
)
db.rollback()
rec = db.query(BizSampleReception).filter_by(id="recv-1").one()
task = db.query(BizProductionTask).filter_by(id="task-1").one()
assert rec.lab_storage_code == "B00001112"
assert task.task_name == "B00001112样本处理"
@@ -17,8 +17,8 @@ def test_explicit_statuses_returned():
assert resolve_research_donation_protocol_status_filter("dsx,sxz") == ("in", ["dsx", "sxz"])
def test_explicit_empty_means_none():
assert resolve_research_donation_protocol_status_filter("") == ("none", [])
def test_explicit_empty_means_all():
assert resolve_research_donation_protocol_status_filter("") == ("all", [])
def test_missing_means_default_dsx_sxz():
@@ -27,5 +27,5 @@ def test_missing_means_default_dsx_sxz():
assert statuses == ["dsx", "sxz"]
def test_whitespace_only_means_none():
assert resolve_research_donation_protocol_status_filter(" , ") == ("none", [])
def test_whitespace_only_means_all():
assert resolve_research_donation_protocol_status_filter(" , ") == ("all", [])
@@ -0,0 +1,142 @@
"""质检工单附件:序列化与第三方材料必填取消。"""
import os
# 避免导入 app 时 Settings 因缺 SECRET_KEY 失败
os.environ.setdefault(
"SECRET_KEY", "test-secret-key-for-qc-wo-attach-unit-tests-32c"
)
import unittest
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
class TestQcWorkOrderAttachmentsDict(unittest.TestCase):
@classmethod
def setUpClass(cls):
# 先导入 qc_task 打破与 qc_work_order 的循环依赖
import app.crud.qc_task # noqa: F401
from app.crud import qc_work_order as wo_mod
cls.wo_mod = wo_mod
def _base_wo(self, **overrides):
wo = SimpleNamespace(
id="wo-1",
work_order_no="QC001",
work_order_type="inbound",
reception_id=None,
protocol_sample_id=None,
collection_protocol_id=None,
protocol_no="",
sample_code="S1",
reception_source="cell_storage",
qc_biz_type="inbound",
biz_type="",
cell_product_id=None,
external_target_code=None,
trigger_source="reception",
production_work_order_id=None,
production_task_id=None,
production_step_output_id=None,
infusion_schedule_id=None,
work_order_status="jxz",
conclusion=None,
has_lab="1",
has_third_party="0",
configured_time=None,
configured_by=None,
third_party_fee_total=None,
attachments=None,
remark=None,
create_time=None,
update_time=None,
)
for k, v in overrides.items():
setattr(wo, k, v)
return wo
def test_wo_to_dict_includes_attachments(self):
data = self.wo_mod._wo_to_dict(
self._base_wo(attachments="https://a/x.pdf, https://b/y.png")
)
self.assertEqual(data["attachments"], "https://a/x.pdf, https://b/y.png")
def test_wo_to_dict_attachments_default_empty(self):
data = self.wo_mod._wo_to_dict(self._base_wo(attachments=None, sample_code=""))
self.assertEqual(data["attachments"], "")
class TestRequireDsfjcAttachmentsOptional(unittest.TestCase):
def test_complete_without_third_party_attachments_ok(self):
from app.crud.qc_task import _require_dsfjc_attachments
task = SimpleNamespace(task_type="dsfjc", third_party_attachments="")
# 不再抛错
_require_dsfjc_attachments(task, for_status="ywc")
class TestUpdateQcWorkOrderAttachments(unittest.TestCase):
@patch("app.crud.qc_work_order.get_work_order")
def test_update_normalizes_and_sets_attachments(self, mock_get):
from app.crud.qc_work_order import update_qc_work_order
wo = SimpleNamespace(
id="wo-3",
work_order_type="inbound",
attachments=None,
remark=None,
work_order_status="jxz",
conclusion=None,
cell_product_id=None,
external_target_code=None,
update_by=None,
update_time=None,
)
mock_get.return_value = wo
db = MagicMock()
update_qc_work_order(
db,
"wo-3",
tenant_no="zkxw",
user_id="u1",
attachments=" https://a/1.pdf , https://b/2.pdf , ",
)
self.assertEqual(wo.attachments, "https://a/1.pdf,https://b/2.pdf")
self.assertEqual(wo.update_by, "u1")
db.add.assert_called()
db.flush.assert_called()
@patch("app.crud.qc_work_order.get_work_order")
def test_update_clear_attachments(self, mock_get):
from app.crud.qc_work_order import update_qc_work_order
wo = SimpleNamespace(
id="wo-4",
work_order_type="inbound",
attachments="https://a/1.pdf",
remark=None,
work_order_status="jxz",
conclusion=None,
cell_product_id=None,
external_target_code=None,
update_by=None,
update_time=None,
)
mock_get.return_value = wo
db = MagicMock()
update_qc_work_order(
db,
"wo-4",
tenant_no="zkxw",
user_id="u1",
attachments="",
)
self.assertIsNone(wo.attachments)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,34 @@
"""质检工单 / 我的质检任务共用关键词条件(无库路径)。"""
# qc_work_order ↔ qc_task 存在循环依赖:先经 qc_task 再取 helper
import app.crud.qc_task # noqa: F401
from app.crud.qc_work_order import build_qc_work_order_keyword_conditions
from app.models.models import BizQcWorkOrder
def test_empty_keyword_returns_no_conditions():
assert build_qc_work_order_keyword_conditions(
None, tenant_no=None, keyword=""
) == []
assert build_qc_work_order_keyword_conditions(
None, tenant_no="t1", keyword=" "
) == []
def test_base_conditions_without_tenant_cover_list_fields():
conds = build_qc_work_order_keyword_conditions(
None,
tenant_no=None,
keyword="ABC",
work_order_type="inbound",
reception_source="cell_storage",
)
assert len(conds) == 4
# 与质检工单列表一致的四列(无租户时不做入库/母亲/出库扩展)
cols = {str(c.left) for c in conds}
assert str(BizQcWorkOrder.work_order_no) in cols or any(
"work_order_no" in str(c) for c in conds
)
assert any("sample_code" in str(c) for c in conds)
assert any("protocol_no" in str(c) for c in conds)
assert any("external_target_code" in str(c) for c in conds)
@@ -0,0 +1,266 @@
"""临床科研/委托加工:项目组负责人审批卡点。"""
import unittest
from unittest.mock import MagicMock, patch
from app.constants.pilot_biz import (
APPROVAL_PASSED,
APPROVAL_PENDING,
APPROVAL_REJECTED,
)
from app.crud import pilot_application as crud
class TestResearchLeaderApprovalGate(unittest.TestCase):
def test_assert_blocks_when_pending(self):
app = MagicMock()
app.biz_type = "basic_experiment"
app.approval_status = APPROVAL_PENDING
with self.assertRaises(ValueError) as ctx:
crud.assert_research_leader_approved(app)
self.assertIn("项目组负责人审批", str(ctx.exception))
def test_assert_allows_when_passed(self):
app = MagicMock()
app.biz_type = "contract_processing"
app.approval_status = APPROVAL_PASSED
crud.assert_research_leader_approved(app)
def test_assert_skips_non_research(self):
app = MagicMock()
app.biz_type = "pilot_service"
app.approval_status = None
crud.assert_research_leader_approved(app)
class TestApproveApplication(unittest.TestCase):
def test_reject_requires_leader(self):
db = MagicMock()
app = MagicMock()
app.biz_type = "basic_experiment"
app.application_status = "dks"
app.approval_status = APPROVAL_PENDING
app.project_id = "proj-1"
app.create_dept_id = "dept-1"
project = MagicMock()
project.leader_user_id = "leader-1"
q_app = MagicMock()
q_app.filter.return_value = q_app
q_app.first.return_value = app
q_proj = MagicMock()
q_proj.filter.return_value = q_proj
q_proj.first.return_value = project
def query_side_effect(model, *args, **kwargs):
name = getattr(model, "__name__", str(model))
if "BizPilotApplication" in name or model is crud.BizPilotApplication:
return q_app
return q_proj
db.query.side_effect = query_side_effect
with patch.object(crud, "_require_research_project_with_leader", return_value=project):
with patch.object(crud, "_team_leader_user_id", return_value="team-leader-1"):
with patch.object(crud, "_row_to_dict_application", return_value={"id": "a1"}):
with self.assertRaises(ValueError) as ctx:
crud.approve_application(
db,
app_id="a1",
tenant_no="zkxw",
user_id="other-user",
approval_status=APPROVAL_REJECTED,
is_super_admin=False,
)
self.assertIn("项目组", str(ctx.exception))
def test_leader_can_pass(self):
db = MagicMock()
app = MagicMock()
app.biz_type = "contract_processing"
app.application_status = "dks"
app.approval_status = APPROVAL_PENDING
app.project_id = "proj-1"
app.create_dept_id = "dept-1"
app.id = "a1"
project = MagicMock()
project.leader_user_id = "leader-1"
q_app = MagicMock()
q_app.filter.return_value = q_app
q_app.first.return_value = app
db.query.return_value = q_app
with patch.object(crud, "_require_research_project_with_leader", return_value=project):
with patch.object(crud, "_team_leader_user_id", return_value="team-leader-1"):
with patch.object(crud, "_backfill_outbound_work_orders_for_application") as backfill:
with patch.object(crud, "_row_to_dict_application", return_value={"id": "a1"}):
result = crud.approve_application(
db,
app_id="a1",
tenant_no="zkxw",
user_id="team-leader-1",
approval_status=APPROVAL_PASSED,
approval_remark="ok",
is_super_admin=False,
)
self.assertEqual(app.approval_status, APPROVAL_PASSED)
backfill.assert_called_once()
self.assertEqual(result["id"], "a1")
def test_leader_can_change_rejected_to_passed(self):
db = MagicMock()
app = MagicMock()
app.biz_type = "basic_experiment"
app.application_status = "dks"
app.approval_status = APPROVAL_REJECTED
app.project_id = "proj-1"
app.create_dept_id = "dept-1"
app.id = "a1"
project = MagicMock()
project.leader_user_id = "leader-1"
q_app = MagicMock()
q_app.filter.return_value = q_app
q_app.first.return_value = app
db.query.return_value = q_app
with patch.object(crud, "_require_research_project_with_leader", return_value=project):
with patch.object(crud, "_team_leader_user_id", return_value="team-leader-1"):
with patch.object(crud, "_backfill_outbound_work_orders_for_application") as backfill:
with patch.object(crud, "_row_to_dict_application", return_value={"id": "a1"}):
crud.approve_application(
db,
app_id="a1",
tenant_no="zkxw",
user_id="team-leader-1",
approval_status=APPROVAL_PASSED,
is_super_admin=False,
)
self.assertEqual(app.approval_status, APPROVAL_PASSED)
backfill.assert_called_once()
def test_super_admin_can_approve_others_project(self):
db = MagicMock()
app = MagicMock()
app.biz_type = "basic_experiment"
app.application_status = "dks"
app.approval_status = APPROVAL_PENDING
app.project_id = "proj-1"
app.create_dept_id = "dept-1"
app.id = "a1"
project = MagicMock()
project.leader_user_id = "leader-1"
q_app = MagicMock()
q_app.filter.return_value = q_app
q_app.first.return_value = app
db.query.return_value = q_app
with patch.object(crud, "_require_research_project_with_leader", return_value=project):
with patch.object(crud, "_team_leader_user_id", return_value="team-leader-1"):
with patch.object(crud, "_backfill_outbound_work_orders_for_application") as backfill:
with patch.object(crud, "_row_to_dict_application", return_value={"id": "a1"}):
crud.approve_application(
db,
app_id="a1",
tenant_no="zkxw",
user_id="super-admin-user",
approval_status=APPROVAL_PASSED,
is_super_admin=True,
)
self.assertEqual(app.approval_status, APPROVAL_PASSED)
backfill.assert_called_once()
class TestResearchVisibilityScope(unittest.TestCase):
def test_super_admin_bypasses_visibility(self):
q = MagicMock()
out = crud.apply_research_like_visibility(
q,
MagicMock(),
"zkxw",
{"user_id": "u1", "role": "super_admin"},
for_approval=True,
)
self.assertIs(out, q)
def test_data_scope_admin_does_not_bypass_visibility(self):
q = MagicMock()
q.filter.return_value = "filtered"
db = MagicMock()
with patch.object(crud, "_led_team_ids", return_value=[]):
out = crud.apply_research_like_visibility(
q,
db,
"zkxw",
{"user_id": "leader-a", "role": "admin"},
for_approval=True,
)
self.assertEqual(out, "filtered")
q.filter.assert_called_once_with(False)
def test_data_scope_admin_cannot_access_other_team_for_approval(self):
app = MagicMock()
app.biz_type = "basic_experiment"
app.project_id = "proj-other"
app.create_by = "other"
with patch.object(crud, "_team_leader_user_id", return_value="team-leader-other"):
ok = crud.user_can_access_research_application(
MagicMock(),
"zkxw",
{"user_id": "leader-a", "role": "admin"},
app,
for_approval=True,
)
self.assertFalse(ok)
def test_super_admin_can_access_any_for_approval(self):
app = MagicMock()
app.biz_type = "basic_experiment"
app.project_id = "proj-other"
ok = crud.user_can_access_research_application(
MagicMock(),
"zkxw",
{"user_id": "sa", "role": "super_admin"},
app,
for_approval=True,
)
self.assertTrue(ok)
def test_is_super_admin_user_ignores_data_scope_roles(self):
self.assertTrue(crud._is_super_admin_user({"role": "super_admin"}))
self.assertFalse(crud._is_super_admin_user({"role": "admin"}))
self.assertFalse(crud._is_super_admin_user(None))
class TestCreateRequiresProject(unittest.TestCase):
def test_contract_processing_requires_project(self):
db = MagicMock()
data = {
"bizType": "contract_processing",
"researchCategory": "msc",
"channelId": "ch-1",
"projectTitle": "课题A",
"customerName": "客户",
"customerContact": "张三",
"customerPhone": "13800000000",
}
with patch.object(crud, "_generate_application_no", return_value="WTJG1"):
with self.assertRaises(ValueError) as ctx:
crud.create_application(
db,
data=data,
tenant_no="zkxw",
user_id="user-1",
dept_id="dept-1",
)
self.assertIn("项目", str(ctx.exception))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,62 @@
"""Static checks for market/pilot-service role-menu revoke migration (#156)."""
import re
from pathlib import Path
MIGRATION = (
Path(__file__).resolve().parents[2]
/ "docs/sql/migrations/2026-11-20-revoke-market-pilot-service-role-menus.sql"
)
def _sql() -> str:
return MIGRATION.read_text(encoding="utf-8")
def _compact(sql: str) -> str:
return re.sub(r"\s+", " ", sql)
def _without_comments(sql: str) -> str:
return re.sub(r"--[^\n]*", "", sql)
def test_migration_file_exists():
assert MIGRATION.is_file()
def test_scopes_to_market_pilot_service_tree():
compact = _compact(_without_comments(_sql()))
assert "menu:market" in compact
assert "中试服务" in compact
assert re.search(r"pilot\.menu_name\s*=\s*'中试服务'", compact)
assert re.search(r"market\.perms\s*=\s*'menu:market'", compact)
def test_revokes_role_menu_by_soft_delete_only():
compact = _compact(_without_comments(_sql()))
assert re.search(r"UPDATE\s+sys_role_menu", compact, re.IGNORECASE)
assert re.search(
r"UPDATE\s+sys_role_menu\s+rm\b.*SET\s+rm\.del_flag\s*=\s*1",
compact,
re.IGNORECASE,
)
assert not re.search(r"DELETE\s+FROM\s+sys_role_menu", compact, re.IGNORECASE)
assert not re.search(r"UPDATE\s+sys_menu\s+SET\s+del_flag\s*=\s*1", compact, re.IGNORECASE)
assert not re.search(r"DELETE\s+FROM\s+sys_menu", compact, re.IGNORECASE)
def test_includes_children_and_button_descendants():
compact = _compact(_without_comments(_sql()))
assert re.search(r"child\.parent_id\s*=\s*pilot\.id", compact)
assert re.search(r"btn\.parent_id\s*=\s*child\.id", compact)
assert compact.count("UNION") >= 2
def test_update_only_touches_active_bindings():
compact = _compact(_without_comments(_sql()))
assert re.search(
r"SET\s+rm\.del_flag\s*=\s*1[\s\S]*WHERE\s+rm\.del_flag\s*=\s*0",
compact,
re.IGNORECASE,
)
@@ -0,0 +1,28 @@
"""样本接收已接收列表:样本类型 / 是否废弃筛选参数解析。"""
import unittest
from app.crud.sample_reception import parse_optional_bool
class TestSampleReceptionReceivedFilters(unittest.TestCase):
def test_parse_optional_bool_true_variants(self):
for raw in ("true", "TRUE", "1", "yes", "Y"):
self.assertIs(parse_optional_bool(raw), True)
def test_parse_optional_bool_false_variants(self):
for raw in ("false", "FALSE", "0", "no", "N"):
self.assertIs(parse_optional_bool(raw), False)
def test_parse_optional_bool_empty_means_unrestricted(self):
self.assertIsNone(parse_optional_bool(None))
self.assertIsNone(parse_optional_bool(""))
self.assertIsNone(parse_optional_bool(" "))
def test_parse_optional_bool_rejects_invalid(self):
with self.assertRaises(ValueError):
parse_optional_bool("maybe")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,26 @@
-- 软删「中试服务」模块菜单定义(一级及其直接子菜单)。
-- 背景:仅收回 sys_role_menu 后,super_admin 仍因前端静态菜单全量展示可见;
-- 侧栏已对静态路由加 isHide,本脚本同步测试库菜单定义。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
UPDATE sys_menu m
SET m.del_flag = 1,
m.update_by = 'migration',
m.update_time = NOW()
WHERE m.del_flag = 0
AND (
m.id = 'PIL00000000000000000000000000001'
OR m.parent_id = 'PIL00000000000000000000000000001'
OR m.parent_id IN (
SELECT id FROM (
SELECT id FROM sys_menu WHERE parent_id = 'PIL00000000000000000000000000001'
) t
)
);
-- 核对:中试服务树应无有效菜单
SELECT id, menu_name, path, del_flag
FROM sys_menu
WHERE id = 'PIL00000000000000000000000000001'
OR parent_id = 'PIL00000000000000000000000000001'
ORDER BY menu_name;
@@ -0,0 +1,76 @@
-- 撤销所有角色对「中试服务」模块(一级菜单及其子孙)的菜单授权。
-- 范围:menu_name='中试服务' 且 path='pilot-service' 的模块树;
-- 不含市场基础信息中 perms 前缀为 pilot-service: 的其它菜单。
-- 仅软删 sys_role_menu,不删除菜单定义。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
-- 1) 软删角色授权
UPDATE sys_role_menu rm
INNER JOIN (
SELECT m.id AS menu_id
FROM sys_menu m
WHERE m.del_flag = 0
AND (
(m.menu_name = '中试服务' AND m.path = 'pilot-service')
OR m.parent_id IN (
SELECT r.id FROM sys_menu r
WHERE r.del_flag = 0 AND r.menu_name = '中试服务' AND r.path = 'pilot-service'
)
OR m.parent_id IN (
SELECT c.id FROM sys_menu c
WHERE c.del_flag = 0
AND c.parent_id IN (
SELECT r.id FROM sys_menu r
WHERE r.del_flag = 0 AND r.menu_name = '中试服务' AND r.path = 'pilot-service'
)
)
)
) tgt ON tgt.menu_id = rm.menu_id
SET rm.del_flag = 1,
rm.update_by = 'migration',
rm.update_time = NOW()
WHERE rm.del_flag = 0;
-- 2) 核对:中试服务树下有效授权应为 0
SELECT r.role_name, m.menu_name, m.path, m.perms, rm.del_flag
FROM sys_role_menu rm
JOIN sys_role r ON r.id = rm.role_id AND r.del_flag = 0
JOIN sys_menu m ON m.id = rm.menu_id
WHERE rm.del_flag = 0
AND (
(m.menu_name = '中试服务' AND m.path = 'pilot-service')
OR m.parent_id IN (
SELECT x.id FROM sys_menu x
WHERE x.del_flag = 0 AND x.menu_name = '中试服务' AND x.path = 'pilot-service'
)
OR m.parent_id IN (
SELECT c.id FROM sys_menu c
WHERE c.del_flag = 0
AND c.parent_id IN (
SELECT x.id FROM sys_menu x
WHERE x.del_flag = 0 AND x.menu_name = '中试服务' AND x.path = 'pilot-service'
)
)
)
ORDER BY r.role_name, m.menu_name;
SELECT
(SELECT COUNT(*) FROM sys_role_menu rm
JOIN sys_menu m ON m.id = rm.menu_id
WHERE rm.del_flag = 0
AND (
(m.menu_name = '中试服务' AND m.path = 'pilot-service')
OR m.parent_id IN (
SELECT x.id FROM sys_menu x
WHERE x.del_flag = 0 AND x.menu_name = '中试服务' AND x.path = 'pilot-service'
)
OR m.parent_id IN (
SELECT c.id FROM sys_menu c
WHERE c.del_flag = 0
AND c.parent_id IN (
SELECT x.id FROM sys_menu x
WHERE x.del_flag = 0 AND x.menu_name = '中试服务' AND x.path = 'pilot-service'
)
)
)
) AS remaining_active_grants;
@@ -0,0 +1,164 @@
-- 市场模块新增「器械销售」及三个子菜单;授权给已有 menu:market 的角色。
-- 不新建角色/用户;用户经现有 sys_user_role 自动带上菜单。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
-- 1) 二级目录:器械销售(挂在市场下,order_num=6 末位)
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
'DEV00000000000000000000000000001',
'器械销售',
m.id,
'M',
'device-sales',
NULL,
'menu:device-sales',
1, '1', '1', m.tenant_no, 6,
'市场-器械销售',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu m
WHERE m.del_flag = 0 AND m.perms = 'menu:market'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'DEV00000000000000000000000000001' AND e.del_flag = 0
);
-- 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
x.id, x.menu_name, 'DEV00000000000000000000000000001', 'C', x.path,
'device-sales/under-construction/index', x.perms,
1, '1', '1', p.tenant_no, x.order_num, x.remark,
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
JOIN (
SELECT 'DEV00000000000000000000000000002' AS id, '三类医疗器械' AS menu_name,
'class-iii' AS path, 'device-sales:class-iii:list' AS perms, 1 AS order_num,
'市场-器械销售-三类医疗器械' AS remark
UNION ALL
SELECT 'DEV00000000000000000000000000003', '二类医疗器械',
'class-ii', 'device-sales:class-ii:list', 2,
'市场-器械销售-二类医疗器械'
UNION ALL
SELECT 'DEV00000000000000000000000000004', '化妆品产品',
'cosmetics', 'device-sales:cosmetics:list', 3,
'市场-器械销售-化妆品产品'
) x ON 1 = 1
WHERE p.del_flag = 0 AND p.id = 'DEV00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e WHERE e.id = x.id AND e.del_flag = 0
);
-- 3) 给已有「市场」顶级菜单授权的角色,授予器械销售目录+三个子菜单
-- (含祖先目录,满足选中子菜单须含祖先)
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('device-sales-rm:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
'grant device-sales from menu:market',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
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 = 'menu:market'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id IN (
'DEV00000000000000000000000000001',
'DEV00000000000000000000000000002',
'DEV00000000000000000000000000003',
'DEV00000000000000000000000000004'
)
WHERE r.del_flag = 0
AND 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
);
-- 3b) 超级管理员同步授予(角色管理勾选与超管侧栏数据一致)
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('device-sales-sa:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
'grant device-sales to super admin',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
JOIN sys_menu m
ON m.del_flag = 0 AND m.status = '1'
AND m.id IN (
'DEV00000000000000000000000000001',
'DEV00000000000000000000000000002',
'DEV00000000000000000000000000003',
'DEV00000000000000000000000000004'
)
WHERE r.del_flag = 0 AND r.role_name = '超级管理员'
AND 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
);
-- 3c) 恢复已挂到上述角色、但被软删的用户-角色关联(打通 用户→角色→菜单)
UPDATE sys_user_role ur
JOIN sys_role r ON r.id = ur.role_id AND r.del_flag = 0
JOIN sys_role_menu rm
ON rm.role_id = r.id AND rm.del_flag = 0
AND rm.menu_id = 'DEV00000000000000000000000000001'
JOIN sys_user u ON u.id = ur.user_id AND u.del_flag = 0
SET ur.del_flag = 0,
ur.update_by = 'migration',
ur.update_time = NOW()
WHERE ur.del_flag = 1;
-- 4) 核对
SELECT id, menu_name, parent_id, path, perms, order_num, visible, del_flag
FROM sys_menu
WHERE id LIKE 'DEV0000000000000000000000000000%'
ORDER BY order_num, menu_name;
SELECT COUNT(DISTINCT rm.role_id) AS roles_granted,
COUNT(*) AS role_menu_rows
FROM sys_role_menu rm
WHERE rm.del_flag = 0
AND rm.menu_id IN (
'DEV00000000000000000000000000001',
'DEV00000000000000000000000000002',
'DEV00000000000000000000000000003',
'DEV00000000000000000000000000004'
);
-- 抽样:有市场权限的用户是否能通过角色落到器械销售菜单
SELECT u.nick_name, u.phone_no, r.role_name, m.menu_name, m.perms
FROM sys_user u
JOIN sys_user_role ur ON ur.user_id = u.id AND ur.del_flag = 0
JOIN sys_role r ON r.id = ur.role_id AND r.del_flag = 0
JOIN sys_role_menu rm ON rm.role_id = r.id AND rm.del_flag = 0
JOIN sys_menu m ON m.id = rm.menu_id AND m.del_flag = 0
WHERE u.del_flag = 0
AND m.id IN (
'DEV00000000000000000000000000002',
'DEV00000000000000000000000000003',
'DEV00000000000000000000000000004'
)
ORDER BY u.nick_name, m.order_num
LIMIT 30;
@@ -0,0 +1,59 @@
-- 中试服务:收回全部角色菜单授权,菜单定义保留并设为隐藏。
-- 范围:menu_name='中试服务' 且 path='pilot-service' 的模块树;
-- 不含市场基础信息中 perms 前缀为 pilot-service: 的其它菜单。
-- 不做:不删业务代码;不软删 sys_menu(菜单管理/角色管理仍可见,显示为「隐藏」)。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
-- 目标菜单 ID(中试服务模块树;可按库内实际子节点增补)
-- PIL00000000000000000000000000001 中试服务
-- 80000000000000000000000000000010 中试服务申请单
-- PIL00000000000000000000000000004 出库放行审核
-- 1) 菜单定义:保留记录,visible=0(隐藏)
UPDATE sys_menu
SET visible = '0',
update_by = 'migration',
update_time = NOW()
WHERE del_flag = 0
AND id IN (
'PIL00000000000000000000000000001',
'80000000000000000000000000000010',
'PIL00000000000000000000000000004'
);
-- 2) 软删角色-菜单授权(断开关系)
UPDATE sys_role_menu
SET del_flag = 1,
update_by = 'migration',
update_time = NOW()
WHERE del_flag = 0
AND menu_id IN (
'PIL00000000000000000000000000001',
'80000000000000000000000000000010',
'PIL00000000000000000000000000004'
);
-- 3) 核对
SELECT id, menu_name, path, del_flag, visible
FROM sys_menu
WHERE del_flag = 0
AND (
(menu_name = '中试服务' AND path = 'pilot-service')
OR parent_id IN (
SELECT id FROM sys_menu
WHERE del_flag = 0 AND menu_name = '中试服务' AND path = 'pilot-service'
)
)
ORDER BY menu_name;
SELECT COUNT(*) AS remaining_active_grants
FROM sys_role_menu rm
JOIN sys_menu m ON m.id = rm.menu_id AND m.del_flag = 0
WHERE rm.del_flag = 0
AND (
(m.menu_name = '中试服务' AND m.path = 'pilot-service')
OR m.parent_id IN (
SELECT id FROM sys_menu
WHERE del_flag = 0 AND menu_name = '中试服务' AND path = 'pilot-service'
)
);
@@ -0,0 +1,45 @@
-- 恢复「中试服务」模块菜单定义及此前 migration 软删的角色授权。
-- 对应回滚:2026-11-16-revoke-pilot-service-role-menus.sql、
-- 2026-11-16-hide-pilot-service-menus.sql
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
UPDATE sys_menu
SET del_flag = 0,
update_by = 'migration-restore',
update_time = NOW()
WHERE del_flag = 1
AND id IN (
'PIL00000000000000000000000000001',
'80000000000000000000000000000010',
'PIL00000000000000000000000000004'
);
UPDATE sys_role_menu
SET del_flag = 0,
update_by = 'migration-restore',
update_time = NOW()
WHERE del_flag = 1
AND update_by = 'migration'
AND menu_id IN (
'PIL00000000000000000000000000001',
'80000000000000000000000000000010',
'PIL00000000000000000000000000004'
);
SELECT id, menu_name, path, del_flag
FROM sys_menu
WHERE id IN (
'PIL00000000000000000000000000001',
'80000000000000000000000000000010',
'PIL00000000000000000000000000004'
)
ORDER BY menu_name;
SELECT COUNT(*) AS active_grants
FROM sys_role_menu
WHERE del_flag = 0
AND menu_id IN (
'PIL00000000000000000000000000001',
'80000000000000000000000000000010',
'PIL00000000000000000000000000004'
);
@@ -0,0 +1,129 @@
-- 软删【市场】下【中试服务】目录及其子菜单(含按钮),与前端静态路由下线对齐。
-- Issue #158(承接 #156:仅解绑角色对超管侧栏无效)
-- MySQL 5.7,可重复执行;不影响基础实验/临床应用下同名菜单。
-- 0) 预览目标菜单
SELECT
m.tenant_no,
m.id AS menu_id,
m.menu_name,
m.menu_type,
m.perms,
m.parent_id,
m.del_flag
FROM sys_menu m
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = m.id
AND tgt.tenant_no = m.tenant_no
WHERE m.del_flag = 0
ORDER BY m.tenant_no, m.menu_type, m.order_num, m.menu_name;
-- 1) 软删目标菜单
UPDATE sys_menu m
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = m.id
AND tgt.tenant_no = m.tenant_no
SET
m.del_flag = 1,
m.update_by = 'migration',
m.update_time = NOW()
WHERE m.del_flag = 0;
-- 2) 核对:市场下不应再有有效「中试服务」目录(期望 0 行)
SELECT
market.tenant_no,
pilot.id,
pilot.menu_name,
pilot.del_flag
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market';
@@ -0,0 +1,20 @@
-- 临床科研申请单:业务子类型 research_category
-- MySQL 5.7,可重复执行。
SET @col_exists := (
SELECT COUNT(*)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_pilot_application'
AND COLUMN_NAME = 'research_category'
);
SET @sql := IF(
@col_exists = 0,
"ALTER TABLE biz_pilot_application ADD COLUMN research_category VARCHAR(32) NULL COMMENT '临床科研业务子类型: bio_tech_clinical/joint_topic_declare/bio_pharma_rd' AFTER customer_phone",
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -0,0 +1,8 @@
-- 质检检测结果留痕:同一次批量保存共用 operate_batch_id(Issue #153)
-- 历史行可为空;前端对无批次号的旧数据做短时窗口合并兜底。
ALTER TABLE `biz_qc_task_result_change_log`
ADD COLUMN `operate_batch_id` varchar(64) DEFAULT NULL COMMENT '同一次保存批次ID(多任务共用)' AFTER `operator_user_name`;
ALTER TABLE `biz_qc_task_result_change_log`
ADD KEY `idx_qc_result_chg_batch` (`tenant_no`, `operate_batch_id`, `del_flag`);
@@ -0,0 +1,14 @@
-- 展示名:基础实验 → 临床科研(仅中文;不改 perms / path / component / id)
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
UPDATE sys_menu
SET
menu_name = REPLACE(menu_name, '基础实验', '临床科研'),
remark = REPLACE(IFNULL(remark, ''), '基础实验', '临床科研'),
update_by = 'migration',
update_time = NOW()
WHERE del_flag = 0
AND (
menu_name LIKE '%基础实验%'
OR IFNULL(remark, '') LIKE '%基础实验%'
);
@@ -0,0 +1,64 @@
-- 纠正:市场「中试服务」应保留在菜单管理中,仅 hidden(visible=0),不要软删。
-- 用于回滚误执行的软删脚本(如 2026-11-16-hide-pilot-service-menus.sql /
-- 2026-11-20-hide-market-pilot-service-menus.sql)之后的状态。
-- MySQL 5.7,可重复执行。不改 perms/path/id;不恢复角色授权(侧栏仍不展示)。
UPDATE sys_menu m
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.menu_name = '中试服务'
AND pilot.path = 'pilot-service'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.menu_name = '中试服务'
AND pilot.path = 'pilot-service'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.menu_name = '中试服务'
AND pilot.path = 'pilot-service'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = m.id
AND tgt.tenant_no = m.tenant_no
SET m.del_flag = 0,
m.visible = '0',
m.update_by = 'migration',
m.update_time = NOW()
WHERE m.del_flag = 1
OR IFNULL(m.visible, '1') <> '0';
-- 核对
SELECT id, menu_name, path, visible, del_flag
FROM sys_menu
WHERE menu_name = '中试服务'
OR parent_id IN (
SELECT id FROM sys_menu
WHERE menu_name = '中试服务' AND path = 'pilot-service'
)
ORDER BY menu_name, path;
@@ -0,0 +1,256 @@
-- 解除【市场】下【中试服务】目录及其全部子菜单(含按钮)与角色的绑定。
-- Issue #156
-- 仅软删 sys_role_menu(del_flag=1),不删除/隐藏菜单本身。
-- 按树定位:menu:market → menu_name=中试服务 → 直系子菜单 → 孙级按钮;
-- 不匹配基础实验/临床应用等其他目录下的同名「出库放行审核」。
-- MySQL 5.7,可重复执行(只处理 del_flag=0 的绑定)。
-- ---------------------------------------------------------------------------
-- 0) 预览:将要解绑的目标菜单(目录 + 子菜单 + 按钮)
-- ---------------------------------------------------------------------------
SELECT
m.tenant_no,
m.id AS menu_id,
m.menu_name,
m.menu_type,
m.perms,
m.parent_id,
m.path
FROM sys_menu m
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = m.id
AND tgt.tenant_no = m.tenant_no
WHERE m.del_flag = 0
ORDER BY m.tenant_no, m.menu_type, m.order_num, m.menu_name;
-- ---------------------------------------------------------------------------
-- 1) 预览:将要软删的角色-菜单绑定
-- ---------------------------------------------------------------------------
SELECT
rm.tenant_no,
r.id AS role_id,
r.role_name,
m.id AS menu_id,
m.menu_name,
m.menu_type,
m.perms,
rm.id AS role_menu_id
FROM sys_role_menu rm
JOIN sys_role r
ON r.id = rm.role_id
AND r.tenant_no = rm.tenant_no
AND r.del_flag = 0
JOIN sys_menu m
ON m.id = rm.menu_id
AND m.tenant_no = rm.tenant_no
AND m.del_flag = 0
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = rm.menu_id
AND tgt.tenant_no = rm.tenant_no
WHERE rm.del_flag = 0
ORDER BY rm.tenant_no, r.role_name, m.menu_name;
-- ---------------------------------------------------------------------------
-- 2) 软删绑定(可重复执行)
-- ---------------------------------------------------------------------------
UPDATE sys_role_menu rm
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = rm.menu_id
AND tgt.tenant_no = rm.tenant_no
SET
rm.del_flag = 1,
rm.update_by = 'migration',
rm.update_time = NOW()
WHERE rm.del_flag = 0;
-- ---------------------------------------------------------------------------
-- 3) 核对:目标菜单上不应再有有效角色绑定(期望 0 行)
-- ---------------------------------------------------------------------------
SELECT
rm.tenant_no,
r.role_name,
m.menu_name,
m.perms,
COUNT(*) AS active_role_menu_rows
FROM sys_role_menu rm
JOIN sys_role r
ON r.id = rm.role_id
AND r.tenant_no = rm.tenant_no
AND r.del_flag = 0
JOIN sys_menu m
ON m.id = rm.menu_id
AND m.tenant_no = rm.tenant_no
AND m.del_flag = 0
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = rm.menu_id
AND tgt.tenant_no = rm.tenant_no
WHERE rm.del_flag = 0
GROUP BY rm.tenant_no, r.role_name, m.menu_name, m.perms;
@@ -0,0 +1,20 @@
-- 细胞产品规格:增加细胞数量(千万)、分装体积(ml),供临床科研/委托加工后期按千万细胞结算。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
-- 存量允许为空;新建/编辑由应用层必填。
SET @col_count := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_cell_product_spec'
AND COLUMN_NAME = 'cell_count_qianwan'
);
SET @sql := IF(
@col_count = 0,
'ALTER TABLE biz_cell_product_spec
ADD COLUMN cell_count_qianwan DECIMAL(18,4) NULL COMMENT ''细胞数量(单位:千万)'' AFTER spec_name,
ADD COLUMN fill_volume_ml DECIMAL(18,4) NULL COMMENT ''分装体积(单位:ml)'' AFTER cell_count_qianwan',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -0,0 +1,97 @@
-- 委托加工:市场菜单(复用临床科研页面组件)+ research_category 加长以支持「其他」自定义。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
-- 1) research_category 加长(自定义「其他」文本)
ALTER TABLE biz_pilot_application
MODIFY COLUMN research_category VARCHAR(64) NULL
COMMENT '业务子类型;临床科研三项码/委托加工产品码或自定义其他';
-- 2) 二级目录:委托加工(挂在市场下,order_num=5,器械销售前)
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
'CPG00000000000000000000000000001',
'委托加工',
m.id,
'M',
'contract-processing',
NULL,
'menu:contract-processing',
1, '1', '1', m.tenant_no, 5,
'市场-委托加工',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu m
WHERE m.del_flag = 0 AND m.perms = 'menu:market'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'CPG00000000000000000000000000001' 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
x.id, x.menu_name, 'CPG00000000000000000000000000001', 'C', x.path,
x.component, x.perms,
1, '1', '1', p.tenant_no, x.order_num, x.remark,
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
JOIN (
SELECT 'CPG00000000000000000000000000002' AS id, '委托加工申请单' AS menu_name,
'application' AS path,
'pilot-service/pilot-application/index' AS component,
'contract-processing:application:list' AS perms, 1 AS order_num,
'市场-委托加工-申请单' AS remark
UNION ALL
SELECT 'CPG00000000000000000000000000003', '缴退费财务确认',
'payment-confirm',
'pilot-service/clinical-payment-confirm/index',
'contract-processing:payment-confirm:list', 2,
'市场-委托加工-缴退费财务确认'
UNION ALL
SELECT 'CPG00000000000000000000000000004', '出库放行审核',
'outbound-release-review',
'pilot-service/outbound-release-review/index',
'contract-processing:outbound-release-review:list', 3,
'市场-委托加工-出库放行审核'
) x ON 1 = 1
WHERE p.del_flag = 0 AND p.id = 'CPG00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e WHERE e.id = x.id AND e.del_flag = 0
);
-- 4) 给已有「市场」顶级菜单授权的角色,授予委托加工目录+子菜单
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('contract-processing-rm:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
'grant contract-processing from menu:market',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
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 = 'menu:market'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id IN (
'CPG00000000000000000000000000001',
'CPG00000000000000000000000000002',
'CPG00000000000000000000000000003',
'CPG00000000000000000000000000004'
)
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e
WHERE e.role_id = r.id AND e.menu_id = m.id AND e.tenant_no = r.tenant_no AND e.del_flag = 0
);
@@ -0,0 +1,31 @@
-- 临床科研/委托加工:申请单项目负责人审批字段。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
-- 存量科研类单据视为已通过,避免卡住已在途流程。
-- 1) 审批字段
SET @col_exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_pilot_application'
AND COLUMN_NAME = 'approval_status'
);
SET @sql := IF(
@col_exists = 0,
'ALTER TABLE biz_pilot_application
ADD COLUMN approval_status VARCHAR(16) NULL COMMENT ''审批状态 dsp待审批 ytg已通过 yth已驳回;非科研类可空'' AFTER application_status,
ADD COLUMN approval_user_id VARCHAR(64) NULL COMMENT ''审批人用户ID'' AFTER approval_status,
ADD COLUMN approval_time DATETIME NULL COMMENT ''审批时间'' AFTER approval_user_id,
ADD COLUMN approval_remark VARCHAR(1000) NULL COMMENT ''审批备注'' AFTER approval_time',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- 2) 存量临床科研/委托加工:视为已通过(不回溯)
UPDATE biz_pilot_application
SET approval_status = 'ytg',
update_time = NOW()
WHERE del_flag = 0
AND biz_type IN ('basic_experiment', 'contract_processing')
AND (approval_status IS NULL OR approval_status = '');
@@ -0,0 +1,57 @@
-- 委托加工自定义业务类型;并从历史申请单回填「非预置码」的 research_category。
-- MySQL 5.7,可重复执行。
CREATE TABLE IF NOT EXISTS biz_contract_processing_category (
id VARCHAR(64) NOT NULL COMMENT '主键ID',
category_name VARCHAR(64) NOT NULL COMMENT '业务类型名称(写入申请单 research_category)',
tenant_no VARCHAR(64) NOT NULL DEFAULT 'zkxw' 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 idx_cpc_tenant (tenant_no, del_flag),
KEY idx_cpc_name (tenant_no, category_name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='委托加工自定义业务类型';
-- 回填:申请单中已写入的自定义文本(排除四项预置码)
INSERT INTO biz_contract_processing_category (
id, category_name, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('cpc:', a.tenant_no, ':', a.category_name)), 13, 1, '3'), 17, 1, '8'),
a.category_name,
a.tenant_no,
0,
'seed from pilot application',
'migration',
'',
NOW(),
'migration',
NOW(),
0
FROM (
SELECT DISTINCT
tenant_no,
TRIM(research_category) AS category_name
FROM biz_pilot_application
WHERE del_flag = 0
AND biz_type = 'contract_processing'
AND research_category IS NOT NULL
AND TRIM(research_category) <> ''
AND TRIM(research_category) NOT IN (
'placenta_freeze_dried', 'adipose_exosome', 'nk', 'msc'
)
) a
WHERE NOT EXISTS (
SELECT 1
FROM biz_contract_processing_category e
WHERE e.del_flag = 0
AND e.tenant_no COLLATE utf8mb4_unicode_ci = a.tenant_no COLLATE utf8mb4_unicode_ci
AND e.category_name COLLATE utf8mb4_unicode_ci = a.category_name COLLATE utf8mb4_unicode_ci
);
@@ -0,0 +1,24 @@
-- 临床科研 / 委托加工:隐藏「缴退费财务确认」菜单(visible=0,保留菜单定义与授权)。
-- 申请单内「缴费信息」Tab 由前端 showPayment=false 控制,不在此脚本范围。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
UPDATE sys_menu
SET visible = '0',
update_by = 'migration',
update_time = NOW()
WHERE del_flag = 0
AND perms IN (
'basic-experiment:payment-confirm:list',
'contract-processing:payment-confirm:list'
)
AND visible <> '0';
-- 核对
SELECT id, menu_name, perms, path, visible, del_flag
FROM sys_menu
WHERE del_flag = 0
AND perms IN (
'basic-experiment:payment-confirm:list',
'contract-processing:payment-confirm:list'
)
ORDER BY perms;
@@ -0,0 +1,71 @@
-- 合作客户主数据表;并从临床科研/委托加工申请单回填去重数据。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
CREATE TABLE IF NOT EXISTS biz_partner_customer (
id VARCHAR(64) NOT NULL COMMENT '主键ID',
customer_name VARCHAR(200) NOT NULL COMMENT '客户名称',
customer_contact VARCHAR(100) NOT NULL COMMENT '客户联系人',
customer_phone VARCHAR(32) NOT NULL COMMENT '客户联系方式',
tenant_no VARCHAR(64) NOT NULL DEFAULT 'zkxw' 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 idx_partner_customer_tenant (tenant_no, del_flag),
KEY idx_partner_customer_name (tenant_no, customer_name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='合作客户(临床科研/委托加工)';
-- 从申请单回填(同租户同名称+联系人+电话去重;已存在则跳过)
-- 比较字段显式 COLLATE,避免与申请单表排序规则不一致报 1267
INSERT INTO biz_partner_customer (
id, customer_name, customer_contact, customer_phone, tenant_no,
order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('pc:', a.tenant_no, ':', a.customer_name, '|', IFNULL(a.customer_contact, ''), '|', IFNULL(a.customer_phone, ''))), 13, 1, '3'), 17, 1, '8'),
TRIM(a.customer_name),
TRIM(IFNULL(a.customer_contact, '')),
TRIM(IFNULL(a.customer_phone, '')),
a.tenant_no,
0,
'seed from pilot application',
'migration',
'',
NOW(),
'migration',
NOW(),
0
FROM (
SELECT DISTINCT
tenant_no,
TRIM(customer_name) AS customer_name,
TRIM(IFNULL(customer_contact, '')) AS customer_contact,
TRIM(IFNULL(customer_phone, '')) AS customer_phone
FROM biz_pilot_application
WHERE del_flag = 0
AND biz_type IN ('basic_experiment', 'contract_processing')
AND customer_name IS NOT NULL
AND TRIM(customer_name) <> ''
AND customer_contact IS NOT NULL
AND TRIM(customer_contact) <> ''
AND customer_phone IS NOT NULL
AND TRIM(customer_phone) <> ''
) a
WHERE NOT EXISTS (
SELECT 1
FROM biz_partner_customer e
WHERE e.del_flag = 0
AND e.tenant_no COLLATE utf8mb4_unicode_ci = a.tenant_no COLLATE utf8mb4_unicode_ci
AND e.customer_name COLLATE utf8mb4_unicode_ci = a.customer_name COLLATE utf8mb4_unicode_ci
AND e.customer_contact COLLATE utf8mb4_unicode_ci = a.customer_contact COLLATE utf8mb4_unicode_ci
AND e.customer_phone COLLATE utf8mb4_unicode_ci = a.customer_phone COLLATE utf8mb4_unicode_ci
);
SELECT COUNT(*) AS partner_customer_count
FROM biz_partner_customer
WHERE del_flag = 0;
@@ -0,0 +1,138 @@
-- 生产管理:临床科研出库、委托加工出库菜单;授权给已有「预产及在途样本」或生产管理父菜单角色。
-- 排序:挂在「实验室样本处理数据」之前(倒数第三 / 倒数第二)。
-- MySQL 5.7,可重复执行。
-- 已入库环境若需改序,另执行 2026-11-25-reorder-production-outbound-menus.sql。
-- 1) 临床科研出库
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
'PRD00000000000000000000000000001',
'临床科研出库',
p.id,
'C',
'basic-experiment-outbound',
'pilot-service/pilot-application/index',
'production:basic-experiment-outbound:list',
1, '1', '1', p.tenant_no,
COALESCE((
SELECT MIN(w.order_num) + 1
FROM sys_menu w
WHERE w.parent_id = p.id AND w.del_flag = 0
AND w.menu_name = '废弃物管理'
AND w.perms = 'production:waste-output:list'
), 9),
'生产-生产管理-临床科研出库',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.id = 'PRM00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'PRD00000000000000000000000000001' AND e.del_flag = 0
);
-- 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
'PRD00000000000000000000000000002',
'委托加工出库',
p.id,
'C',
'contract-processing-outbound',
'pilot-service/pilot-application/index',
'production:contract-processing-outbound:list',
1, '1', '1', p.tenant_no,
COALESCE((
SELECT MIN(w.order_num) + 2
FROM sys_menu w
WHERE w.parent_id = p.id AND w.del_flag = 0
AND w.menu_name = '废弃物管理'
AND w.perms = 'production:waste-output:list'
), 10),
'生产-生产管理-委托加工出库',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.id = 'PRM00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'PRD00000000000000000000000000002' AND e.del_flag = 0
);
-- 2.1) 实验室样本处理数据保持末位(废弃物 + 3)
UPDATE sys_menu lab
JOIN sys_menu waste
ON waste.parent_id = lab.parent_id
AND waste.tenant_no = lab.tenant_no
AND waste.del_flag = 0
AND waste.menu_name = '废弃物管理'
AND waste.perms = 'production:waste-output:list'
SET lab.order_num = waste.order_num + 3,
lab.update_by = 'migration',
lab.update_time = NOW()
WHERE lab.del_flag = 0
AND lab.parent_id = 'PRM00000000000000000000000000001'
AND lab.menu_name = '实验室样本处理数据'
AND lab.perms = 'production:labSampleProcess:list';
-- 3) 角色授权:已有预产及在途样本权限的角色
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
REPLACE(UUID(), '-', ''),
r.id, m.id, r.tenant_no, NULL,
'grant production research outbound from pre-transit',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
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 srcm
ON srcm.id = src.menu_id AND srcm.tenant_no = src.tenant_no AND srcm.del_flag = 0
AND srcm.perms = 'production:preTransitSample:list'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id IN (
'PRD00000000000000000000000000001',
'PRD00000000000000000000000000002'
)
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e
WHERE e.role_id = r.id AND e.menu_id = m.id AND e.tenant_no = r.tenant_no AND e.del_flag = 0
);
-- 4) 角色授权:已有生产管理父目录权限、但无预产菜单的角色(兜底)
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
REPLACE(UUID(), '-', ''),
r.id, m.id, r.tenant_no, NULL,
'grant production research outbound from production manage',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
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 parent
ON parent.id = src.menu_id AND parent.tenant_no = src.tenant_no AND parent.del_flag = 0
AND parent.id = 'PRM00000000000000000000000000001'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id IN (
'PRD00000000000000000000000000001',
'PRD00000000000000000000000000002'
)
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e
WHERE e.role_id = r.id AND e.menu_id = m.id AND e.tenant_no = r.tenant_no AND e.del_flag = 0
);
@@ -0,0 +1,50 @@
-- 生产管理:临床科研出库、委托加工出库移到倒数第三 / 倒数第二(实验室样本处理数据之前)。
-- 锚定「废弃物管理」:临床=废弃物+1,委托=废弃物+2,实验室样本=废弃物+3。
-- MySQL 5.7,可重复执行。
UPDATE sys_menu clinical
JOIN sys_menu waste
ON waste.parent_id = clinical.parent_id
AND waste.tenant_no = clinical.tenant_no
AND waste.del_flag = 0
AND waste.menu_name = '废弃物管理'
AND waste.perms = 'production:waste-output:list'
SET clinical.order_num = waste.order_num + 1,
clinical.update_by = 'migration',
clinical.update_time = NOW()
WHERE clinical.id = 'PRD00000000000000000000000000001'
AND clinical.del_flag = 0;
UPDATE sys_menu contract
JOIN sys_menu waste
ON waste.parent_id = contract.parent_id
AND waste.tenant_no = contract.tenant_no
AND waste.del_flag = 0
AND waste.menu_name = '废弃物管理'
AND waste.perms = 'production:waste-output:list'
SET contract.order_num = waste.order_num + 2,
contract.update_by = 'migration',
contract.update_time = NOW()
WHERE contract.id = 'PRD00000000000000000000000000002'
AND contract.del_flag = 0;
UPDATE sys_menu lab
JOIN sys_menu waste
ON waste.parent_id = lab.parent_id
AND waste.tenant_no = lab.tenant_no
AND waste.del_flag = 0
AND waste.menu_name = '废弃物管理'
AND waste.perms = 'production:waste-output:list'
SET lab.order_num = waste.order_num + 3,
lab.update_by = 'migration',
lab.update_time = NOW()
WHERE lab.del_flag = 0
AND lab.parent_id = 'PRM00000000000000000000000000001'
AND lab.menu_name = '实验室样本处理数据'
AND lab.perms = 'production:labSampleProcess:list';
-- 核验
SELECT id, menu_name, path, order_num
FROM sys_menu
WHERE del_flag = 0 AND parent_id = 'PRM00000000000000000000000000001'
ORDER BY order_num, menu_name;
@@ -0,0 +1,110 @@
-- 临床科研 / 委托加工:新增「费用信息」子菜单,并授权给已有父菜单角色。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
-- 1) 临床科研 · 费用信息
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
'BEX00000000000000000000000000005',
'费用信息',
p.id,
'C',
'fee-info',
'pilot-service/fee-info/index',
'basic-experiment:fee-info:list',
1, '1', '1', p.tenant_no, 2,
'市场-临床科研-费用信息',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.id = 'BEX00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'BEX00000000000000000000000000005' AND e.del_flag = 0
);
-- 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
'CPG00000000000000000000000000005',
'费用信息',
p.id,
'C',
'fee-info',
'pilot-service/fee-info/index',
'contract-processing:fee-info:list',
1, '1', '1', p.tenant_no, 2,
'市场-委托加工-费用信息',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.id = 'CPG00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'CPG00000000000000000000000000005' AND e.del_flag = 0
);
-- 3) 角色授权:已有临床科研目录权限的角色
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('fee-info-rm:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
'grant basic-experiment fee-info from parent',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
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 parent
ON parent.id = src.menu_id AND parent.tenant_no = src.tenant_no AND parent.del_flag = 0
AND parent.id = 'BEX00000000000000000000000000001'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id = 'BEX00000000000000000000000000005'
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e
WHERE e.role_id = r.id AND e.menu_id = m.id AND e.tenant_no = r.tenant_no AND e.del_flag = 0
);
-- 4) 角色授权:已有委托加工目录权限的角色
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('fee-info-rm:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
'grant contract-processing fee-info from parent',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
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 parent
ON parent.id = src.menu_id AND parent.tenant_no = src.tenant_no AND parent.del_flag = 0
AND parent.id = 'CPG00000000000000000000000000001'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id = 'CPG00000000000000000000000000005'
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e
WHERE e.role_id = r.id AND e.menu_id = m.id AND e.tenant_no = r.tenant_no AND e.del_flag = 0
);
-- 核对
SELECT id, menu_name, parent_id, perms, path, order_num, visible, del_flag
FROM sys_menu
WHERE del_flag = 0
AND id IN (
'BEX00000000000000000000000000005',
'CPG00000000000000000000000000005'
)
ORDER BY id;
@@ -0,0 +1,176 @@
-- 临床科研 / 委托加工:在申请单后增加审批子菜单;授权给已有对应申请单权限的角色。
-- 排序:申请单之后(order_num = 申请单 + 1),其后同级菜单整体后移。
-- MySQL 5.7,可重复执行。
-- 0) 腾出申请单后的排序位(仅首次;审批菜单不存在时)
UPDATE sys_menu m
JOIN sys_menu app
ON app.id = 'BEX00000000000000000000000000002'
AND app.parent_id = m.parent_id
AND app.tenant_no = m.tenant_no
AND app.del_flag = 0
LEFT JOIN sys_menu existed
ON existed.id = 'BEX00000000000000000000000000006'
AND existed.del_flag = 0
SET m.order_num = m.order_num + 1,
m.update_by = 'migration',
m.update_time = NOW()
WHERE m.del_flag = 0
AND m.parent_id = 'BEX00000000000000000000000000001'
AND m.order_num > app.order_num
AND m.id <> 'BEX00000000000000000000000000006'
AND existed.id IS NULL;
UPDATE sys_menu m
JOIN sys_menu app
ON app.id = 'CPG00000000000000000000000000002'
AND app.parent_id = m.parent_id
AND app.tenant_no = m.tenant_no
AND app.del_flag = 0
LEFT JOIN sys_menu existed
ON existed.id = 'CPG00000000000000000000000000006'
AND existed.del_flag = 0
SET m.order_num = m.order_num + 1,
m.update_by = 'migration',
m.update_time = NOW()
WHERE m.del_flag = 0
AND m.parent_id = 'CPG00000000000000000000000000001'
AND m.order_num > app.order_num
AND m.id <> 'CPG00000000000000000000000000006'
AND existed.id IS NULL;
-- 1) 临床科研审批
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
'BEX00000000000000000000000000006',
'临床科研审批',
p.id,
'C',
'approval',
'pilot-service/pilot-application/index',
'basic-experiment:approval:list',
1, '1', '1', p.tenant_no,
COALESCE((
SELECT app.order_num + 1
FROM sys_menu app
WHERE app.id = 'BEX00000000000000000000000000002' AND app.del_flag = 0
LIMIT 1
), 2),
'市场-临床科研-审批',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.id = 'BEX00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'BEX00000000000000000000000000006' AND e.del_flag = 0
);
-- 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
'CPG00000000000000000000000000006',
'委托加工审批',
p.id,
'C',
'approval',
'pilot-service/pilot-application/index',
'contract-processing:approval:list',
1, '1', '1', p.tenant_no,
COALESCE((
SELECT app.order_num + 1
FROM sys_menu app
WHERE app.id = 'CPG00000000000000000000000000002' AND app.del_flag = 0
LIMIT 1
), 2),
'市场-委托加工-审批',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.id = 'CPG00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'CPG00000000000000000000000000006' AND e.del_flag = 0
);
-- 2.1) 已存在时校正排序(可重复)
UPDATE sys_menu approval
JOIN sys_menu app
ON app.id = 'BEX00000000000000000000000000002'
AND app.parent_id = approval.parent_id
AND app.tenant_no = approval.tenant_no
AND app.del_flag = 0
SET approval.order_num = app.order_num + 1,
approval.update_by = 'migration',
approval.update_time = NOW()
WHERE approval.id = 'BEX00000000000000000000000000006'
AND approval.del_flag = 0;
UPDATE sys_menu approval
JOIN sys_menu app
ON app.id = 'CPG00000000000000000000000000002'
AND app.parent_id = approval.parent_id
AND app.tenant_no = approval.tenant_no
AND app.del_flag = 0
SET approval.order_num = app.order_num + 1,
approval.update_by = 'migration',
approval.update_time = NOW()
WHERE approval.id = 'CPG00000000000000000000000000006'
AND approval.del_flag = 0;
-- 3) 角色授权:已有对应申请单权限的角色
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
CONCAT(
'a',
SUBSTRING(SHA1(CONCAT('approval-rm-v1:', r.tenant_no, ':', r.id, ':', m.id)), 1, 31)
),
r.id, m.id, r.tenant_no, NULL,
'grant research-like approval from application list',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
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 srcm
ON srcm.id = src.menu_id AND srcm.tenant_no = src.tenant_no AND srcm.del_flag = 0
AND (
(srcm.perms = 'basic-experiment:application:list' AND srcm.id = 'BEX00000000000000000000000000002')
OR (srcm.perms = 'contract-processing:application:list' AND srcm.id = 'CPG00000000000000000000000000002')
)
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND (
(srcm.id = 'BEX00000000000000000000000000002' AND m.id = 'BEX00000000000000000000000000006')
OR (srcm.id = 'CPG00000000000000000000000000002' AND m.id = 'CPG00000000000000000000000000006')
)
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e
WHERE e.role_id = r.id AND e.menu_id = m.id AND e.tenant_no = r.tenant_no AND e.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e2
WHERE e2.id = CONCAT(
'a',
SUBSTRING(SHA1(CONCAT('approval-rm-v1:', r.tenant_no, ':', r.id, ':', m.id)), 1, 31)
)
);
-- 核验
SELECT id, menu_name, path, perms, order_num, visible
FROM sys_menu
WHERE del_flag = 0
AND parent_id IN (
'BEX00000000000000000000000000001',
'CPG00000000000000000000000000001'
)
ORDER BY parent_id, order_num, menu_name;
@@ -0,0 +1,67 @@
-- 自定义业务类型增加 biz_type,支持临床科研 / 委托加工分业务维护。
-- MySQL 5.7,可重复执行。
SET @col_exists := (
SELECT COUNT(*)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_contract_processing_category'
AND COLUMN_NAME = 'biz_type'
);
SET @sql := IF(
@col_exists = 0,
'ALTER TABLE biz_contract_processing_category
ADD COLUMN biz_type VARCHAR(32) NOT NULL DEFAULT ''contract_processing''
COMMENT ''业务线 basic_experiment / contract_processing'' AFTER category_name,
ADD KEY idx_cpc_biz_type (tenant_no, biz_type, del_flag)',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
UPDATE biz_contract_processing_category
SET biz_type = 'contract_processing'
WHERE (biz_type IS NULL OR biz_type = '')
AND del_flag = 0;
-- 回填临床科研申请单中已写入的自定义文本(排除三项预置码)
INSERT INTO biz_contract_processing_category (
id, category_name, biz_type, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('bex-cat:', a.tenant_no, ':', a.category_name)), 13, 1, '3'), 17, 1, '8'),
a.category_name,
'basic_experiment',
a.tenant_no,
0,
'seed from pilot application',
'migration',
'',
NOW(),
'migration',
NOW(),
0
FROM (
SELECT DISTINCT
tenant_no,
TRIM(research_category) AS category_name
FROM biz_pilot_application
WHERE del_flag = 0
AND biz_type = 'basic_experiment'
AND research_category IS NOT NULL
AND TRIM(research_category) <> ''
AND TRIM(research_category) NOT IN (
'bio_tech_clinical', 'joint_topic_declare', 'bio_pharma_rd'
)
) a
WHERE NOT EXISTS (
SELECT 1
FROM biz_contract_processing_category e
WHERE e.del_flag = 0
AND e.biz_type = 'basic_experiment'
AND e.tenant_no COLLATE utf8mb4_unicode_ci = a.tenant_no COLLATE utf8mb4_unicode_ci
AND e.category_name COLLATE utf8mb4_unicode_ci = a.category_name COLLATE utf8mb4_unicode_ci
);
@@ -0,0 +1,8 @@
-- 临床科研申请单号前缀:JCSY → LCKY
-- 目标库:zkxw-sc(及需同步的环境)
-- 说明:仅改写 application_no 前四位;序号与日期部分保持不变。
UPDATE biz_pilot_application
SET application_no = CONCAT('LCKY', SUBSTRING(application_no, 5))
WHERE application_no LIKE 'JCSY%'
AND biz_type = 'basic_experiment';
@@ -0,0 +1,831 @@
-- =============================================================================
-- 上线脚本:临床科研 / 委托加工及相关能力(对照生产数据导入后的 zkxw-sc)
-- MySQL 5.7,尽量可重复执行。
--
-- 对照 2026-11-30 生产 dump 导入后的 zkxw-sc,当前缺口:
-- 1) biz_pilot_application 缺 research_category、审批四字段
-- 2) biz_cell_product_spec 缺 cell_count_qianwan / fill_volume_ml
-- 3) 缺表 biz_partner_customer、biz_contract_processing_category
-- 4) 菜单仍为「基础实验」,无委托加工 / 费用信息 / 审批 / 生产出库菜单
--
-- 执行前:备份库;在目标库执行(USE `zkxw-sc`; 或客户端选中该库)
-- 执行后:核对文末 SELECT;再发布对应前后端版本
-- =============================================================================
-- -----------------------------------------------------------------------------
-- A. 表结构
-- -----------------------------------------------------------------------------
-- A1) research_category(生产库整列缺失,直接加 VARCHAR(64))
SET @col_exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_pilot_application'
AND COLUMN_NAME = 'research_category'
);
SET @sql := IF(
@col_exists = 0,
'ALTER TABLE biz_pilot_application
ADD COLUMN research_category VARCHAR(64) NULL
COMMENT ''业务子类型;临床科研三项码/委托加工产品码或自定义其他''
AFTER customer_phone',
'ALTER TABLE biz_pilot_application
MODIFY COLUMN research_category VARCHAR(64) NULL
COMMENT ''业务子类型;临床科研三项码/委托加工产品码或自定义其他'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- A2) 申请单审批字段
SET @col_exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_pilot_application'
AND COLUMN_NAME = 'approval_status'
);
SET @sql := IF(
@col_exists = 0,
'ALTER TABLE biz_pilot_application
ADD COLUMN approval_status VARCHAR(16) NULL COMMENT ''审批状态 dsp待审批 ytg已通过 yth已驳回;非科研类可空'' AFTER application_status,
ADD COLUMN approval_user_id VARCHAR(64) NULL COMMENT ''审批人用户ID'' AFTER approval_status,
ADD COLUMN approval_time DATETIME NULL COMMENT ''审批时间'' AFTER approval_user_id,
ADD COLUMN approval_remark VARCHAR(1000) NULL COMMENT ''审批备注'' AFTER approval_time',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- 存量临床科研/委托加工:视为已通过,避免卡住在途流程
UPDATE biz_pilot_application
SET approval_status = 'ytg',
update_time = NOW()
WHERE del_flag = 0
AND biz_type IN ('basic_experiment', 'contract_processing')
AND (approval_status IS NULL OR approval_status = '');
-- A3) 细胞产品规格:细胞数量(千万)、分装体积(ml)
SET @col_count := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_cell_product_spec'
AND COLUMN_NAME = 'cell_count_qianwan'
);
SET @sql := IF(
@col_count = 0,
'ALTER TABLE biz_cell_product_spec
ADD COLUMN cell_count_qianwan DECIMAL(18,4) NULL COMMENT ''细胞数量(单位:千万)'' AFTER spec_name,
ADD COLUMN fill_volume_ml DECIMAL(18,4) NULL COMMENT ''分装体积(单位:ml)'' AFTER cell_count_qianwan',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- A4) 合作客户
CREATE TABLE IF NOT EXISTS biz_partner_customer (
id VARCHAR(64) NOT NULL COMMENT '主键ID',
customer_name VARCHAR(200) NOT NULL COMMENT '客户名称',
customer_contact VARCHAR(100) NOT NULL COMMENT '客户联系人',
customer_phone VARCHAR(32) NOT NULL COMMENT '客户联系方式',
tenant_no VARCHAR(64) NOT NULL DEFAULT 'zkxw' 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 idx_partner_customer_tenant (tenant_no, del_flag),
KEY idx_partner_customer_name (tenant_no, customer_name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='合作客户(临床科研/委托加工)';
-- A5) 自定义业务类型(含 biz_type,临床科研/委托加工共用)
CREATE TABLE IF NOT EXISTS biz_contract_processing_category (
id VARCHAR(64) NOT NULL COMMENT '主键ID',
category_name VARCHAR(64) NOT NULL COMMENT '业务类型名称(写入申请单 research_category)',
biz_type VARCHAR(32) NOT NULL DEFAULT 'contract_processing'
COMMENT '业务线 basic_experiment / contract_processing',
tenant_no VARCHAR(64) NOT NULL DEFAULT 'zkxw' 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 idx_cpc_tenant (tenant_no, del_flag),
KEY idx_cpc_name (tenant_no, category_name),
KEY idx_cpc_biz_type (tenant_no, biz_type, del_flag)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='临床科研/委托加工自定义业务类型';
-- 若旧环境已建表但无 biz_type,则补列
SET @col_exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_contract_processing_category'
AND COLUMN_NAME = 'biz_type'
);
SET @sql := IF(
@col_exists = 0,
'ALTER TABLE biz_contract_processing_category
ADD COLUMN biz_type VARCHAR(32) NOT NULL DEFAULT ''contract_processing''
COMMENT ''业务线 basic_experiment / contract_processing'' AFTER category_name,
ADD KEY idx_cpc_biz_type (tenant_no, biz_type, del_flag)',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- -----------------------------------------------------------------------------
-- B. 数据回填
-- -----------------------------------------------------------------------------
INSERT INTO biz_partner_customer (
id, customer_name, customer_contact, customer_phone, tenant_no,
order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('pc:', a.tenant_no, ':', a.customer_name, '|', IFNULL(a.customer_contact, ''), '|', IFNULL(a.customer_phone, ''))), 13, 1, '3'), 17, 1, '8'),
TRIM(a.customer_name),
TRIM(IFNULL(a.customer_contact, '')),
TRIM(IFNULL(a.customer_phone, '')),
a.tenant_no,
0,
'seed from pilot application',
'migration',
'',
NOW(),
'migration',
NOW(),
0
FROM (
SELECT DISTINCT
tenant_no,
TRIM(customer_name) AS customer_name,
TRIM(IFNULL(customer_contact, '')) AS customer_contact,
TRIM(IFNULL(customer_phone, '')) AS customer_phone
FROM biz_pilot_application
WHERE del_flag = 0
AND biz_type IN ('basic_experiment', 'contract_processing')
AND customer_name IS NOT NULL AND TRIM(customer_name) <> ''
AND customer_contact IS NOT NULL AND TRIM(customer_contact) <> ''
AND customer_phone IS NOT NULL AND TRIM(customer_phone) <> ''
) a
WHERE NOT EXISTS (
SELECT 1 FROM biz_partner_customer e
WHERE e.del_flag = 0
AND e.tenant_no COLLATE utf8mb4_unicode_ci = a.tenant_no COLLATE utf8mb4_unicode_ci
AND e.customer_name COLLATE utf8mb4_unicode_ci = a.customer_name COLLATE utf8mb4_unicode_ci
AND e.customer_contact COLLATE utf8mb4_unicode_ci = a.customer_contact COLLATE utf8mb4_unicode_ci
AND e.customer_phone COLLATE utf8mb4_unicode_ci = a.customer_phone COLLATE utf8mb4_unicode_ci
);
UPDATE biz_contract_processing_category
SET biz_type = 'contract_processing'
WHERE (biz_type IS NULL OR biz_type = '')
AND del_flag = 0;
INSERT INTO biz_contract_processing_category (
id, category_name, biz_type, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('cpc:', a.tenant_no, ':', a.category_name)), 13, 1, '3'), 17, 1, '8'),
a.category_name,
'contract_processing',
a.tenant_no,
0,
'seed from pilot application',
'migration', '', NOW(), 'migration', NOW(), 0
FROM (
SELECT DISTINCT tenant_no, TRIM(research_category) AS category_name
FROM biz_pilot_application
WHERE del_flag = 0
AND biz_type = 'contract_processing'
AND research_category IS NOT NULL AND TRIM(research_category) <> ''
AND TRIM(research_category) NOT IN (
'placenta_freeze_dried', 'adipose_exosome', 'nk', 'msc'
)
) a
WHERE NOT EXISTS (
SELECT 1 FROM biz_contract_processing_category e
WHERE e.del_flag = 0
AND e.biz_type = 'contract_processing'
AND e.tenant_no COLLATE utf8mb4_unicode_ci = a.tenant_no COLLATE utf8mb4_unicode_ci
AND e.category_name COLLATE utf8mb4_unicode_ci = a.category_name COLLATE utf8mb4_unicode_ci
);
INSERT INTO biz_contract_processing_category (
id, category_name, biz_type, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('bex-cat:', a.tenant_no, ':', a.category_name)), 13, 1, '3'), 17, 1, '8'),
a.category_name,
'basic_experiment',
a.tenant_no,
0,
'seed from pilot application',
'migration', '', NOW(), 'migration', NOW(), 0
FROM (
SELECT DISTINCT tenant_no, TRIM(research_category) AS category_name
FROM biz_pilot_application
WHERE del_flag = 0
AND biz_type = 'basic_experiment'
AND research_category IS NOT NULL AND TRIM(research_category) <> ''
AND TRIM(research_category) NOT IN (
'bio_tech_clinical', 'joint_topic_declare', 'bio_pharma_rd'
)
) a
WHERE NOT EXISTS (
SELECT 1 FROM biz_contract_processing_category e
WHERE e.del_flag = 0
AND e.biz_type = 'basic_experiment'
AND e.tenant_no COLLATE utf8mb4_unicode_ci = a.tenant_no COLLATE utf8mb4_unicode_ci
AND e.category_name COLLATE utf8mb4_unicode_ci = a.category_name COLLATE utf8mb4_unicode_ci
);
-- -----------------------------------------------------------------------------
-- C. 菜单:基础实验 → 临床科研(仅展示名)
-- -----------------------------------------------------------------------------
UPDATE sys_menu
SET
menu_name = REPLACE(menu_name, '基础实验', '临床科研'),
remark = REPLACE(IFNULL(remark, ''), '基础实验', '临床科研'),
update_by = 'migration',
update_time = NOW()
WHERE del_flag = 0
AND (
menu_name LIKE '%基础实验%'
OR IFNULL(remark, '') LIKE '%基础实验%'
);
-- -----------------------------------------------------------------------------
-- D. 菜单:委托加工(挂市场)
-- -----------------------------------------------------------------------------
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
'CPG00000000000000000000000000001',
'委托加工',
m.id,
'M',
'contract-processing',
NULL,
'menu:contract-processing',
1, '1', '1', m.tenant_no, 5,
'市场-委托加工',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu m
WHERE m.del_flag = 0 AND m.perms = 'menu:market'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'CPG00000000000000000000000000001' AND e.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
x.id, x.menu_name, 'CPG00000000000000000000000000001', 'C', x.path,
x.component, x.perms,
1, '1', '1', p.tenant_no, x.order_num, x.remark,
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
JOIN (
SELECT 'CPG00000000000000000000000000002' AS id, '委托加工申请单' AS menu_name,
'application' AS path,
'pilot-service/pilot-application/index' AS component,
'contract-processing:application:list' AS perms, 1 AS order_num,
'市场-委托加工-申请单' AS remark
UNION ALL
SELECT 'CPG00000000000000000000000000003', '缴退费财务确认',
'payment-confirm',
'pilot-service/clinical-payment-confirm/index',
'contract-processing:payment-confirm:list', 2,
'市场-委托加工-缴退费财务确认'
UNION ALL
SELECT 'CPG00000000000000000000000000004', '出库放行审核',
'outbound-release-review',
'pilot-service/outbound-release-review/index',
'contract-processing:outbound-release-review:list', 3,
'市场-委托加工-出库放行审核'
) x ON 1 = 1
WHERE p.del_flag = 0 AND p.id = 'CPG00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e WHERE e.id = x.id AND e.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('contract-processing-rm:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
'grant contract-processing from menu:market',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
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 = 'menu:market'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id IN (
'CPG00000000000000000000000000001',
'CPG00000000000000000000000000002',
'CPG00000000000000000000000000003',
'CPG00000000000000000000000000004'
)
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e
WHERE e.role_id = r.id AND e.menu_id = m.id AND e.tenant_no = r.tenant_no AND e.del_flag = 0
);
-- -----------------------------------------------------------------------------
-- E. 费用信息菜单
-- -----------------------------------------------------------------------------
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
'BEX00000000000000000000000000005',
'费用信息',
p.id,
'C',
'fee-info',
'pilot-service/fee-info/index',
'basic-experiment:fee-info:list',
1, '1', '1', p.tenant_no, 2,
'市场-临床科研-费用信息',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.id = 'BEX00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'BEX00000000000000000000000000005' AND e.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
'CPG00000000000000000000000000005',
'费用信息',
p.id,
'C',
'fee-info',
'pilot-service/fee-info/index',
'contract-processing:fee-info:list',
1, '1', '1', p.tenant_no, 2,
'市场-委托加工-费用信息',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.id = 'CPG00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'CPG00000000000000000000000000005' AND e.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('fee-info-rm:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
'grant basic-experiment fee-info from parent',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
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 parent
ON parent.id = src.menu_id AND parent.tenant_no = src.tenant_no AND parent.del_flag = 0
AND parent.id = 'BEX00000000000000000000000000001'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id = 'BEX00000000000000000000000000005'
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e
WHERE e.role_id = r.id AND e.menu_id = m.id AND e.tenant_no = r.tenant_no AND e.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('fee-info-rm:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
'grant contract-processing fee-info from parent',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
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 parent
ON parent.id = src.menu_id AND parent.tenant_no = src.tenant_no AND parent.del_flag = 0
AND parent.id = 'CPG00000000000000000000000000001'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id = 'CPG00000000000000000000000000005'
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e
WHERE e.role_id = r.id AND e.menu_id = m.id AND e.tenant_no = r.tenant_no AND e.del_flag = 0
);
-- -----------------------------------------------------------------------------
-- F. 隐藏缴退费财务确认
-- -----------------------------------------------------------------------------
UPDATE sys_menu
SET visible = '0',
update_by = 'migration',
update_time = NOW()
WHERE del_flag = 0
AND perms IN (
'basic-experiment:payment-confirm:list',
'contract-processing:payment-confirm:list'
)
AND visible <> '0';
-- -----------------------------------------------------------------------------
-- G. 审批子菜单(插在申请单后)
-- -----------------------------------------------------------------------------
UPDATE sys_menu m
JOIN sys_menu app
ON app.id = 'BEX00000000000000000000000000002'
AND app.parent_id = m.parent_id
AND app.tenant_no = m.tenant_no
AND app.del_flag = 0
LEFT JOIN sys_menu existed
ON existed.id = 'BEX00000000000000000000000000006'
AND existed.del_flag = 0
SET m.order_num = m.order_num + 1,
m.update_by = 'migration',
m.update_time = NOW()
WHERE m.del_flag = 0
AND m.parent_id = 'BEX00000000000000000000000000001'
AND m.order_num > app.order_num
AND m.id <> 'BEX00000000000000000000000000006'
AND existed.id IS NULL;
UPDATE sys_menu m
JOIN sys_menu app
ON app.id = 'CPG00000000000000000000000000002'
AND app.parent_id = m.parent_id
AND app.tenant_no = m.tenant_no
AND app.del_flag = 0
LEFT JOIN sys_menu existed
ON existed.id = 'CPG00000000000000000000000000006'
AND existed.del_flag = 0
SET m.order_num = m.order_num + 1,
m.update_by = 'migration',
m.update_time = NOW()
WHERE m.del_flag = 0
AND m.parent_id = 'CPG00000000000000000000000000001'
AND m.order_num > app.order_num
AND m.id <> 'CPG00000000000000000000000000006'
AND existed.id IS NULL;
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
'BEX00000000000000000000000000006',
'临床科研审批',
p.id,
'C',
'approval',
'pilot-service/pilot-application/index',
'basic-experiment:approval:list',
1, '1', '1', p.tenant_no,
COALESCE((
SELECT app.order_num + 1
FROM sys_menu app
WHERE app.id = 'BEX00000000000000000000000000002' AND app.del_flag = 0
LIMIT 1
), 2),
'市场-临床科研-审批',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.id = 'BEX00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'BEX00000000000000000000000000006' AND e.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
'CPG00000000000000000000000000006',
'委托加工审批',
p.id,
'C',
'approval',
'pilot-service/pilot-application/index',
'contract-processing:approval:list',
1, '1', '1', p.tenant_no,
COALESCE((
SELECT app.order_num + 1
FROM sys_menu app
WHERE app.id = 'CPG00000000000000000000000000002' AND app.del_flag = 0
LIMIT 1
), 2),
'市场-委托加工-审批',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.id = 'CPG00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'CPG00000000000000000000000000006' AND e.del_flag = 0
);
UPDATE sys_menu approval
JOIN sys_menu app
ON app.id = 'BEX00000000000000000000000000002'
AND app.parent_id = approval.parent_id
AND app.tenant_no = approval.tenant_no
AND app.del_flag = 0
SET approval.order_num = app.order_num + 1,
approval.update_by = 'migration',
approval.update_time = NOW()
WHERE approval.id = 'BEX00000000000000000000000000006'
AND approval.del_flag = 0;
UPDATE sys_menu approval
JOIN sys_menu app
ON app.id = 'CPG00000000000000000000000000002'
AND app.parent_id = approval.parent_id
AND app.tenant_no = approval.tenant_no
AND app.del_flag = 0
SET approval.order_num = app.order_num + 1,
approval.update_by = 'migration',
approval.update_time = NOW()
WHERE approval.id = 'CPG00000000000000000000000000006'
AND approval.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
CONCAT(
'a',
SUBSTRING(SHA1(CONCAT('approval-rm-v1:', r.tenant_no, ':', r.id, ':', m.id)), 1, 31)
),
r.id, m.id, r.tenant_no, NULL,
'grant research-like approval from application list',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
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 srcm
ON srcm.id = src.menu_id AND srcm.tenant_no = src.tenant_no AND srcm.del_flag = 0
AND (
(srcm.perms = 'basic-experiment:application:list' AND srcm.id = 'BEX00000000000000000000000000002')
OR (srcm.perms = 'contract-processing:application:list' AND srcm.id = 'CPG00000000000000000000000000002')
)
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND (
(srcm.id = 'BEX00000000000000000000000000002' AND m.id = 'BEX00000000000000000000000000006')
OR (srcm.id = 'CPG00000000000000000000000000002' AND m.id = 'CPG00000000000000000000000000006')
)
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e
WHERE e.role_id = r.id AND e.menu_id = m.id AND e.tenant_no = r.tenant_no AND e.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e2
WHERE e2.id = CONCAT(
'a',
SUBSTRING(SHA1(CONCAT('approval-rm-v1:', r.tenant_no, ':', r.id, ':', m.id)), 1, 31)
)
);
-- -----------------------------------------------------------------------------
-- H. 生产管理:临床科研出库 / 委托加工出库
-- -----------------------------------------------------------------------------
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
'PRD00000000000000000000000000001',
'临床科研出库',
p.id,
'C',
'basic-experiment-outbound',
'pilot-service/pilot-application/index',
'production:basic-experiment-outbound:list',
1, '1', '1', p.tenant_no,
COALESCE((
SELECT MIN(w.order_num) + 1
FROM sys_menu w
WHERE w.parent_id = p.id AND w.del_flag = 0
AND w.menu_name = '废弃物管理'
AND w.perms = 'production:waste-output:list'
), 9),
'生产-生产管理-临床科研出库',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.id = 'PRM00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'PRD00000000000000000000000000001' AND e.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
'PRD00000000000000000000000000002',
'委托加工出库',
p.id,
'C',
'contract-processing-outbound',
'pilot-service/pilot-application/index',
'production:contract-processing-outbound:list',
1, '1', '1', p.tenant_no,
COALESCE((
SELECT MIN(w.order_num) + 2
FROM sys_menu w
WHERE w.parent_id = p.id AND w.del_flag = 0
AND w.menu_name = '废弃物管理'
AND w.perms = 'production:waste-output:list'
), 10),
'生产-生产管理-委托加工出库',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.id = 'PRM00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'PRD00000000000000000000000000002' AND e.del_flag = 0
);
UPDATE sys_menu clinical
JOIN sys_menu waste
ON waste.parent_id = clinical.parent_id
AND waste.tenant_no = clinical.tenant_no
AND waste.del_flag = 0
AND waste.menu_name = '废弃物管理'
AND waste.perms = 'production:waste-output:list'
SET clinical.order_num = waste.order_num + 1,
clinical.update_by = 'migration',
clinical.update_time = NOW()
WHERE clinical.id = 'PRD00000000000000000000000000001'
AND clinical.del_flag = 0;
UPDATE sys_menu contract
JOIN sys_menu waste
ON waste.parent_id = contract.parent_id
AND waste.tenant_no = contract.tenant_no
AND waste.del_flag = 0
AND waste.menu_name = '废弃物管理'
AND waste.perms = 'production:waste-output:list'
SET contract.order_num = waste.order_num + 2,
contract.update_by = 'migration',
contract.update_time = NOW()
WHERE contract.id = 'PRD00000000000000000000000000002'
AND contract.del_flag = 0;
UPDATE sys_menu lab
JOIN sys_menu waste
ON waste.parent_id = lab.parent_id
AND waste.tenant_no = lab.tenant_no
AND waste.del_flag = 0
AND waste.menu_name = '废弃物管理'
AND waste.perms = 'production:waste-output:list'
SET lab.order_num = waste.order_num + 3,
lab.update_by = 'migration',
lab.update_time = NOW()
WHERE lab.del_flag = 0
AND lab.parent_id = 'PRM00000000000000000000000000001'
AND lab.menu_name = '实验室样本处理数据'
AND lab.perms = 'production:labSampleProcess:list';
-- 注意:同一 SELECT 中 UUID() 可能重复导致主键冲突;用 SHA1 + DISTINCT
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
CONCAT('p', SUBSTRING(SHA1(CONCAT('prd-out-pre-v2:', x.tenant_no, ':', x.role_id, ':', x.menu_id)), 1, 31)),
x.role_id, x.menu_id, x.tenant_no, NULL,
'grant production research outbound from pre-transit',
'migration', '', NOW(), 'migration', NOW(), 0
FROM (
SELECT DISTINCT r.id AS role_id, r.tenant_no, m.id AS menu_id
FROM sys_role r
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 srcm
ON srcm.id = src.menu_id AND srcm.tenant_no = src.tenant_no AND srcm.del_flag = 0
AND srcm.perms = 'production:preTransitSample:list'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id IN (
'PRD00000000000000000000000000001',
'PRD00000000000000000000000000002'
)
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e
WHERE e.role_id = r.id AND e.menu_id = m.id AND e.tenant_no = r.tenant_no AND e.del_flag = 0
)
) x;
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
CONCAT('q', SUBSTRING(SHA1(CONCAT('prd-out-mgr-v2:', x.tenant_no, ':', x.role_id, ':', x.menu_id)), 1, 31)),
x.role_id, x.menu_id, x.tenant_no, NULL,
'grant production research outbound from production manage',
'migration', '', NOW(), 'migration', NOW(), 0
FROM (
SELECT DISTINCT r.id AS role_id, r.tenant_no, m.id AS menu_id
FROM sys_role r
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 parent
ON parent.id = src.menu_id AND parent.tenant_no = src.tenant_no AND parent.del_flag = 0
AND parent.id = 'PRM00000000000000000000000000001'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id IN (
'PRD00000000000000000000000000001',
'PRD00000000000000000000000000002'
)
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu e
WHERE e.role_id = r.id AND e.menu_id = m.id AND e.tenant_no = r.tenant_no AND e.del_flag = 0
)
) x;
-- -----------------------------------------------------------------------------
-- I. 核验
-- -----------------------------------------------------------------------------
SELECT 'pilot_cols' AS chk, COLUMN_NAME, COLUMN_TYPE
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_pilot_application'
AND COLUMN_NAME IN (
'research_category', 'approval_status', 'approval_user_id',
'approval_time', 'approval_remark'
)
ORDER BY COLUMN_NAME;
SELECT 'spec_cols' AS chk, COLUMN_NAME, COLUMN_TYPE
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_cell_product_spec'
AND COLUMN_NAME IN ('cell_count_qianwan', 'fill_volume_ml')
ORDER BY COLUMN_NAME;
SELECT 'tables' AS chk, TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME IN ('biz_partner_customer', 'biz_contract_processing_category')
ORDER BY TABLE_NAME;
SELECT id, menu_name, perms, path, order_num, visible
FROM sys_menu
WHERE del_flag = 0
AND parent_id IN (
'BEX00000000000000000000000000001',
'CPG00000000000000000000000000001',
'PRM00000000000000000000000000001'
)
ORDER BY parent_id, order_num, menu_name;
@@ -0,0 +1,18 @@
-- 质检工单:工单级附件(逗号分隔 URL),供卡片右上角上传/查看。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
SET @col_count := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_qc_work_order'
AND COLUMN_NAME = 'attachments'
);
SET @sql := IF(
@col_count = 0,
'ALTER TABLE biz_qc_work_order
ADD COLUMN attachments VARCHAR(4000) NULL COMMENT ''工单附件(逗号分隔URL)'' AFTER third_party_fee_total',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -103,7 +103,7 @@ export const receptionSource = createRegistry({
outbound: { label: '出库', tagType: 'primary' },
pilot_service: { label: '中试服务', tagType: 'primary' },
clinical_application: { label: '临床应用', tagType: 'warning' },
basic_experiment: { label: '基础实验', tagType: 'primary' }
basic_experiment: { label: '临床科研', tagType: 'primary' }
})
/** 协议/捐赠样本状态;与 Web sampleStatus 保持一致 */
@@ -12,7 +12,7 @@
用户明确采用 [Figma 原型 v2](https://www.figma.com/design/wOQLDAhr1gdlQEXnVaFO9S?node-id=13-23)。范围为 Web 历史归属维护及其后端读取接口,沿用用户先合入 V2.0 再自测的安排。复用 P02 列表和 `pilot-service/pilot-application/index.vue` 的 `panel-pill-tabs`,操作列固定右侧,搜索右对齐。
`RecordList` 仅在 assignment 模式显示四类正式业务 tab 和业务识别列。细胞存储/科研捐赠展示母亲姓名、电话、采集医院、市场专员及采集/捐赠日期;中试展示申请名称、渠道、服务订单名称、患者姓名/电话;基础实验展示课题、客户名称/联系人/电话。公共列保留序号、主单号、状态、项目组、所属项目、创建时间。多个有效子记录以稳定顺序去重连接展示,缺失值显示破折号,采集日期来自采集信息的样本采集时间。
`RecordList` 仅在 assignment 模式显示四类正式业务 tab 和业务识别列。细胞存储/科研捐赠展示母亲姓名、电话、采集医院、市场专员及采集/捐赠日期;中试展示申请名称、渠道、服务订单名称、患者姓名/电话;临床科研展示课题、客户名称/联系人/电话。公共列保留序号、主单号、状态、项目组、所属项目、创建时间。多个有效子记录以稳定顺序去重连接展示,缺失值显示破折号,采集日期来自采集信息的样本采集时间。
新增 `GET /web/admin/project-management/assignments/records`,严格要求 `project:assignment:edit`,仅接受四类正式业务。原 `/records` 继续服务统计明细,不扩展联系信息;移动接口不变。专用服务复用主单租户、软删除、数据权限和归属筛选。关键词支持单号、姓名/电话、医院/专员、渠道/服务订单名称、课题/客户信息(日期使用现有创建日期条件);子表使用同租户未删除记录 EXISTS 匹配,不增加主单行数。分页后批量补充项目、医院、人员、患者和服务订单资料,避免逐行查询。
@@ -20,7 +20,7 @@
## 模块边界
新增 models/project_management.py、services/project_management.py、api/project_management.py。现有四种主表(预签约、采集协议、科研捐赠、中试/基础实验申请)增加可空 project_id,不向下游样本表复制归属。不更改已有课题名称 project_title。
新增 models/project_management.py、services/project_management.py、api/project_management.py。现有四种主表(预签约、采集协议、科研捐赠、中试/临床科研申请)增加可空 project_id,不向下游样本表复制归属。不更改已有课题名称 project_title。
项目组包含 teamName、leaderUserId、members[{id?,userId}]、regions[{id?,regionId}]、hospitals[{id?,hospitalId}]、enabled、remark。子行按 sync_child_rows 与自然键更新。负责人应计入可选项目成员判断。项目包含 projectNo、projectName、teamId、leaderUserId、bizTypes[]、startDate、endDate、status(pending/active/completed/disabled)、remark。编号服务端生成。项目已有业务后禁止换组;引用中的项目和组只能停用,不能删除。所有引用租户内校验。
@@ -61,7 +61,7 @@ project_brief(db, tenant_no, project_id) -> dict # projectId/projectName/teamId
预签约转协议继承归属;存储/捐赠互转继承。归属维护将同租户的预签约→协议→捐赠转换记录组成关联集合,循环防重,锁定顺序固定;任一关联记录不可访问则拒绝整个操作,返回信息不暴露无权查看单据。历史软删除记录不参与活跃统计,不复活。
正式存储按协议、捐赠按主单、中试和基础实验按对应 biz_type 申请单计数;预签约另列,不把四类数量称为独立客户数。日期按创建日期(起日含、结束日次日不含),状态显示当前状态。查询先按租户、软删除、原有数据权限过滤,再聚合,不联接子行产生重复;金额不在本期。
正式存储按协议、捐赠按主单、中试和临床科研按对应 biz_type 申请单计数;预签约另列,不把四类数量称为独立客户数。日期按创建日期(起日含、结束日次日不含),状态显示当前状态。查询先按租户、软删除、原有数据权限过滤,再聚合,不联接子行产生重复;金额不在本期。
## 界面与验证
@@ -1,7 +1,7 @@
## ADDED Requirements
### Requirement: 按业务识别历史归属单据
历史归属维护 SHALL 按细胞存储、科研捐赠、中试服务、基础实验展示四个 tab,并提供对应业务识别字段和关键词搜索;列表保持主单分页,右侧固定归属与审计操作。
历史归属维护 SHALL 按细胞存储、科研捐赠、中试服务、临床科研展示四个 tab,并提供对应业务识别字段和关键词搜索;列表保持主单分页,右侧固定归属与审计操作。
#### Scenario: 存储和捐赠以样本编码识别
- **WHEN** 查看细胞存储或科研捐赠 tab
- **THEN** 展示样本编码列而非协议单号/捐赠单号列;多个有效编码在同一主单行去重展示,无编码显示破折号,支持按任一编码搜索;跨租户或已删除的样本不用于展示和匹配,分页和归属仍以主单为单位。
@@ -54,7 +54,7 @@ Web SHALL 使用“项目 → 项目管理 → 项目组管理 / 项目管理 /
- **WHEN** 用户打开某项目的某类业务明细
- **THEN** 明细总数与相同筛选条件汇总一致,不因子行联接重复计数。
#### Scenario: 四类统计明细展示业务字段
- **WHEN** 点击细胞存储、科研捐赠、中试服务、基础实验的统计数量
- **WHEN** 点击细胞存储、科研捐赠、中试服务、临床科研的统计数量
- **THEN** 原明细弹窗复用历史归属维护对应 tab 的业务列与关键词能力,存储/捐赠显示样本编码,保留汇总传入的筛选条件和只读权限,不显示归属维护操作;预签约仍沿用原行为。
### Requirement: 沿用现有界面样式
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>清理本地登录状态</title>
</head>
<body>
<p>正在清理本地缓存并跳转登录页…</p>
<script>
try {
localStorage.clear()
sessionStorage.clear()
} catch (e) {}
location.replace('/#/auth/login')
</script>
</body>
</html>
+74
View File
@@ -940,6 +940,73 @@ export function fetchCustomerRelations(id: string) {
})
}
export function fetchPartnerCustomerList(params?: {
page?: number
pageSize?: number
keyword?: string
}) {
return request.get<PageResult<Api.PartnerCustomer.Item>>({
url: '/web/admin/partner-customers',
params
})
}
export function fetchCreatePartnerCustomer(data: {
customerName: string
customerContact: string
customerPhone: string
remark?: string
}) {
return request.post({ url: '/web/admin/partner-customers', params: data })
}
export function fetchUpdatePartnerCustomer(
id: string,
data: Partial<{
customerName: string
customerContact: string
customerPhone: string
remark: string
}>
) {
return request.put({ url: `/web/admin/partner-customers/${id}`, params: data })
}
export function fetchDeletePartnerCustomer(id: string) {
return request.del({ url: `/web/admin/partner-customers/${id}` })
}
export function fetchContractProcessingCategoryList(params: {
page?: number
pageSize?: number
keyword?: string
bizType: 'basic_experiment' | 'contract_processing'
}) {
return request.get<PageResult<Api.ContractProcessingCategory.Item>>({
url: '/web/admin/contract-processing-categories',
params
})
}
export function fetchCreateContractProcessingCategory(data: {
categoryName: string
remark?: string
bizType: 'basic_experiment' | 'contract_processing'
}) {
return request.post({ url: '/web/admin/contract-processing-categories', params: data })
}
export function fetchUpdateContractProcessingCategory(
id: string,
data: Partial<{ categoryName: string; remark: string }>
) {
return request.put({ url: `/web/admin/contract-processing-categories/${id}`, params: data })
}
export function fetchDeleteContractProcessingCategory(id: string) {
return request.del({ url: `/web/admin/contract-processing-categories/${id}` })
}
export function fetchCellSampleTypeList(params?: {
page?: number
pageSize?: number
@@ -2269,6 +2336,13 @@ export function voidPilotApplication(data: any) {
export function savePilotApplication(data: any) {
return request.post({ url: '/web/admin/pilot-application/save', params: data })
}
export function approvePilotApplication(data: {
id: string
approvalStatus: 'ytg' | 'yth'
approvalRemark?: string
}) {
return request.post({ url: '/web/admin/pilot-application/approve', params: data })
}
export function createBasicExperimentSaleSchedules(
applicationId: string,
data: { productLines: any[] }
+2 -2
View File
@@ -56,9 +56,9 @@ export interface ProductionWorkOrderItem {
/** 出库工单:输注计划总次数 */
totalCourseCount?: number | null
infusionTime?: string
/** 基础实验出库:课题名称(列表 enrich) */
/** 临床科研出库:课题名称(列表 enrich) */
projectTitle?: string
/** 基础实验出库:客户名称(列表 enrich) */
/** 临床科研出库:客户名称(列表 enrich) */
customerName?: string
/** 出库工单:输注计划细胞类型(列表 enrich,无产品明细时兜底) */
cellType?: string
+11 -1
View File
@@ -5,13 +5,23 @@ export type BizType =
| 'research_donation'
| 'pilot_service'
| 'basic_experiment'
| 'contract_processing'
export const bizLabels: Record<BizType, string> = {
presign: '预签约',
cell_storage: '细胞存储',
research_donation: '科研捐赠',
pilot_service: '中试服务',
basic_experiment: '基础实验'
basic_experiment: '临床科研',
contract_processing: '委托加工'
}
/** 项目管理界面暂不展示;保留枚举与历史数据兼容 */
export const hiddenProjectBizTypes: readonly BizType[] = ['pilot_service']
export function isProjectBizTypeVisible(bizType: BizType): boolean {
return !hiddenProjectBizTypes.includes(bizType)
}
export const visibleBizLabels = Object.fromEntries(
Object.entries(bizLabels).filter(([key]) => isProjectBizTypeVisible(key as BizType))
) as Partial<Record<BizType, string>>
export type ProjectOption = {
id: string
projectName: string
+2
View File
@@ -51,6 +51,7 @@ export function fetchCompleteTaskWithResult(
remark?: string
thirdPartyAttachments?: string
taskStatus?: 'dzx' | 'jxz' | 'ywc'
operateBatchId?: string
materialUsages?: Array<{
requisitionUsageId: string
qty: number
@@ -83,6 +84,7 @@ export type QcTaskResultChangeLog = {
operateTime: string
operatorUserId?: string
operatorUserName?: string
operateBatchId?: string
hasFieldChange: boolean
changes: QcTaskResultChangeItem[]
createTime?: string
+2
View File
@@ -170,6 +170,8 @@ export function fetchMyQcTaskList(params?: {
qcBizType?: string
receptionSource?: string
bizType?: string
/** 科研捐赠:协议/捐赠状态,多个逗号分隔;空串=不限制 */
protocolStatus?: string
}) {
return request.get<PageList<QcTask>>({
url: '/web/admin/qc-tasks/mine',
+3
View File
@@ -129,6 +129,8 @@ export type QcWorkOrder = {
configuredBy?: string
configuredByName?: string
thirdPartyFeeTotal?: number
/** 工单级附件(逗号分隔 URL) */
attachments?: string
remark?: string
createTime?: string
updateTime?: string
@@ -311,6 +313,7 @@ export function fetchUpdateQcWorkOrder(
externalTargetCode?: string
workOrderStatus?: string
qcConclusion?: string
attachments?: string
remark?: string
}
) {
+3
View File
@@ -27,6 +27,9 @@ export function fetchSampleReceptionReceivedList(params?: {
pageSize?: number
keyword?: string
sourceType?: string
sampleTypeId?: string
/** true=已作废(yzf),false=非已作废,不传=全部 */
isVoided?: boolean
receptionTimeStart?: string
receptionTimeEnd?: string
}) {
Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

+1 -1
View File
@@ -751,7 +751,7 @@ body {
}
}
// 面板级步骤胶囊 Tab(样本信息管理 / 采集协议单 / 中试·基础实验申请单等)
// 面板级步骤胶囊 Tab(样本信息管理 / 采集协议单 / 中试·临床科研申请单等)
.pill-tab-nav {
padding: 16px 20px 0;
display: flex;
@@ -55,6 +55,8 @@
bizType?: BizType
disabled?: boolean
projectName?: string
/** Bump to reload options without remounting (e.g. after assignment). */
refreshKey?: number | string
}>()
const emit = defineEmits<{
'update:modelValue': [value: string]
@@ -79,7 +81,7 @@
retry = ref(0)
let version = 0
watch(
() => [props.bizType, props.disabled, props.filter, retry.value],
() => [props.bizType, props.disabled, props.filter, props.refreshKey, retry.value],
async () => {
const requestVersion = ++version
if (props.disabled) {
@@ -284,6 +284,7 @@
protocolStatusTagType
} from '@/utils/protocol-payment-labels'
import { formatMoneyDisplay } from '@/utils/money-format'
import { isResearchLikeBiz } from '@/utils/research-like-biz'
const props = withDefaults(
defineProps<{
@@ -393,7 +394,7 @@
)
const isBasicExperiment = computed(
() => String(props.detail?.bizType || '') === 'basic_experiment'
() => isResearchLikeBiz(props.bizType || detail?.bizType)
)
const pickupTimeLabel = computed(() =>
@@ -103,6 +103,7 @@
import { formatMoneyDisplay } from '@/utils/money-format'
import { payStatusLabel, payStatusTagType } from '@/utils/status-tag-registry'
import { getPilotBizConfig } from '@/config/pilot-biz-type'
import { isResearchLikeBiz } from '@/utils/research-like-biz'
const props = withDefaults(
defineProps<{
@@ -143,7 +144,7 @@
}
const isBasicExperiment = computed(
() => String(props.detail?.bizType || '') === 'basic_experiment'
() => isResearchLikeBiz(props.bizType || detail?.bizType)
)
const pickupTimeLabel = computed(() =>
@@ -4,10 +4,16 @@
<div class="outbound-material-form-sections">
<div class="material-sections">
<!-- 出库细胞 -->
<section class="section-card">
<section v-if="showCells" class="section-card">
<div class="section-head">
<h3 class="section-title section-title--mint-bar">出库细胞</h3>
<el-button type="primary" size="small" class="btn-main" @click="openCellSelect">
<el-button
v-if="!cellsReadonly"
type="primary"
size="small"
class="btn-main"
@click="openCellSelect"
>
<el-icon><Plus /></el-icon>
添加细胞产品
</el-button>
@@ -18,7 +24,7 @@
class="list-table inner-table"
stripe
max-height="280"
empty-text="请从细胞产品库勾选"
:empty-text="cellsReadonly ? '暂无出库细胞' : '请从细胞产品库勾选'"
>
<el-table-column type="index" label="序号" min-width="56" align="center" />
<el-table-column
@@ -56,7 +62,13 @@
<span v-else>—</span>
</template>
</el-table-column>
<el-table-column label="操作" min-width="80" align="center" fixed="right">
<el-table-column
v-if="!cellsReadonly && !hideCellOps"
label="操作"
min-width="80"
align="center"
fixed="right"
>
<template #default="{ $index }">
<el-button type="danger" link size="small" @click="removeCellRow($index)">
<el-icon><Delete /></el-icon>
@@ -69,7 +81,7 @@
</section>
<!-- 使用的物料 -->
<section class="section-card">
<section v-if="showMaterials" class="section-card">
<div class="section-head">
<h3 class="section-title section-title--mint-bar">使用的物料</h3>
<el-button type="primary" size="small" class="btn-main" @click="addMaterialRow">
@@ -145,7 +157,7 @@
</section>
<!-- 纸质材料 -->
<section class="section-card">
<section v-if="showPapers" class="section-card">
<div class="section-head">
<h3 class="section-title section-title--mint-bar">纸质材料</h3>
<el-button type="primary" size="small" class="btn-main" @click="addPaperRow">
@@ -289,7 +301,7 @@
<p v-else class="section-empty-hint">点击「添加纸质材料」逐条填写名称、份数并上传附件;仅作台账留存,不扣库存</p>
</section>
<el-form label-position="top" class="biz-dialog-form">
<el-form v-if="showRemark" label-position="top" class="biz-dialog-form">
<el-form-item label="备注">
<el-input
v-model="formRemark"
@@ -424,9 +436,23 @@
defineProps<{
/** 出库交接等需扣库存场景:仅允许选择已冻存细胞,且已选行保留可选 */
requireFrozenCellProduct?: boolean
/** 出库细胞只读展示(隐藏添加/删除) */
cellsReadonly?: boolean
/** 隐藏细胞行操作列(仍可显示添加) */
hideCellOps?: boolean
showCells?: boolean
showMaterials?: boolean
showPapers?: boolean
showRemark?: boolean
}>(),
{
requireFrozenCellProduct: false
requireFrozenCellProduct: false,
cellsReadonly: false,
hideCellOps: false,
showCells: true,
showMaterials: true,
showPapers: true,
showRemark: true
}
)
@@ -785,34 +811,38 @@
}
function validateMaterial() {
if (paperRows.value.some((r) => r._uploading)) {
if (props.showPapers && paperRows.value.some((r) => r._uploading)) {
ElMessage.warning('纸质材料附件上传中,请稍候')
return false
}
for (const row of materialRows.value) {
if (!row.materialId) {
ElMessage.warning('请为每条物料选择名称')
return false
}
const qty = row.qty
if (qty == null || !Number.isFinite(Number(qty)) || Number(qty) <= 0) {
ElMessage.warning('物料计划用量须大于 0')
return false
if (props.showMaterials) {
for (const row of materialRows.value) {
if (!row.materialId) {
ElMessage.warning('请为每条物料选择名称')
return false
}
const qty = row.qty
if (qty == null || !Number.isFinite(Number(qty)) || Number(qty) <= 0) {
ElMessage.warning('物料计划用量须大于 0')
return false
}
}
}
for (const row of paperRows.value) {
if (!row.paperName?.trim()) {
ElMessage.warning('请填写每条纸质材料的名称')
return false
}
const copies = row.copies
if (copies == null || !Number.isFinite(Number(copies)) || Number(copies) <= 0) {
ElMessage.warning('纸质材料份数须大于 0')
return false
}
if (!row.attachments.length) {
ElMessage.warning('请为每条纸质材料上传附件')
return false
if (props.showPapers) {
for (const row of paperRows.value) {
if (!row.paperName?.trim()) {
ElMessage.warning('请填写每条纸质材料的名称')
return false
}
const copies = row.copies
if (copies == null || !Number.isFinite(Number(copies)) || Number(copies) <= 0) {
ElMessage.warning('纸质材料份数须大于 0')
return false
}
if (!row.attachments.length) {
ElMessage.warning('请为每条纸质材料上传附件')
return false
}
}
}
return true
@@ -56,6 +56,20 @@
</el-tag>
</template>
</el-table-column>
<el-table-column
label="操作"
min-width="110"
align="center"
header-align="center"
fixed="right"
>
<template #default="{ row }">
<el-button type="primary" link @click="openLineageQc(row)">
<el-icon><View /></el-icon>
查看质检
</el-button>
</template>
</el-table-column>
</el-table>
</div>
</div>
@@ -210,11 +224,14 @@
/>
</div>
</el-dialog>
<CellProductLineageQcDialog v-model="lineageQcVisible" :product-id="lineageQcProductId" />
</div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Download, View, VideoPlay } from '@element-plus/icons-vue'
import type {
OutboundReleaseCellRow,
@@ -227,6 +244,7 @@
} from '@/utils/status-tag-registry'
import { downloadAttachmentFile } from '@/utils/download-attachment'
import { resolveCellProductSpecDisplay } from '@/utils/cell-product-spec'
import CellProductLineageQcDialog from '@/components/business/cell-product-lineage-qc-dialog/index.vue'
defineOptions({ name: 'OutboundMaterialReadonlyPanel' })
@@ -253,6 +271,8 @@
const previewVisible = ref(false)
const previewUrl = ref('')
const previewType = ref<'image' | 'video'>('image')
const lineageQcVisible = ref(false)
const lineageQcProductId = ref('')
const minioBaseUrl = (import.meta.env.VITE_MINIO_BASE_URL || '').replace(/\/$/, '')
const cells = computed<OutboundReleaseCellRow[]>(() => props.material?.cells || [])
@@ -356,6 +376,16 @@
{ fullFileUrl: attachmentFullUrl }
)
}
function openLineageQc(row: OutboundReleaseCellRow) {
const id = String(row.cellProductId || '')
if (!id) {
ElMessage.warning('缺少细胞产品信息')
return
}
lineageQcProductId.value = id
lineageQcVisible.value = true
}
</script>
<style lang="scss" scoped>
@@ -50,11 +50,12 @@
import ExceptionIllustration from './ExceptionIllustration.vue'
import { useCommon } from '@/hooks/core/useCommon'
import { useUserStore } from '@/store/modules/user'
import { resetRouteInitState } from '@/router/guards/beforeEach'
const router = useRouter()
const userStore = useUserStore()
withDefaults(
const props = withDefaults(
defineProps<{
code: string
title: string
@@ -72,7 +73,15 @@
const { homePath } = useCommon()
/** 500 页允许在后端恢复后重新拉菜单/用户信息 */
const clearInitLockIfServerError = () => {
if (props.variant === 'server-error') {
resetRouteInitState()
}
}
const goBack = () => {
clearInitLockIfServerError()
if (window.history.length > 1) {
router.back()
return
@@ -81,6 +90,7 @@
}
const backHome = () => {
clearInitLockIfServerError()
const targetHomePath = homePath.value || '/'
if (!userStore.isLogin) {
+38 -19
View File
@@ -1,4 +1,8 @@
export type PilotBizType = 'pilot_service' | 'clinical_application' | 'basic_experiment'
export type PilotBizType =
| 'pilot_service'
| 'clinical_application'
| 'basic_experiment'
| 'contract_processing'
export interface PilotBizTypeConfig {
label: string
@@ -20,6 +24,26 @@ export interface PilotBizTypeConfig {
statusLabel: string
}
const RESEARCH_LIKE_CONFIG: PilotBizTypeConfig = {
label: '临床科研',
applicationNoPrefix: 'LCKY',
showChannel: true,
showPatient: false,
showConsent: false,
showOtherAttachments: false,
showStandardAttachments: true,
showCheckup: false,
showInfusionConfirm: false,
showDelivery: true,
showPayment: false,
planLabel: '交付计划',
scheduleLabel: '交付计划',
pickupTimeLabel: '交付时间',
locationLabel: '交付地点',
methodLabel: '交付方式',
statusLabel: '交付状态'
}
export const PILOT_BIZ_TYPE_CONFIG: Record<PilotBizType, PilotBizTypeConfig> = {
pilot_service: {
label: '中试服务',
@@ -60,23 +84,14 @@ export const PILOT_BIZ_TYPE_CONFIG: Record<PilotBizType, PilotBizTypeConfig> = {
statusLabel: '输注状态'
},
basic_experiment: {
label: '基础实验',
applicationNoPrefix: 'JCSY',
showChannel: false,
showPatient: false,
showConsent: false,
showOtherAttachments: false,
showStandardAttachments: true,
showCheckup: false,
showInfusionConfirm: false,
showDelivery: true,
showPayment: true,
planLabel: '交付计划',
scheduleLabel: '交付计划',
pickupTimeLabel: '交付时间',
locationLabel: '交付地点',
methodLabel: '交付方式',
statusLabel: '交付状态'
...RESEARCH_LIKE_CONFIG,
label: '临床科研',
applicationNoPrefix: 'LCKY'
},
contract_processing: {
...RESEARCH_LIKE_CONFIG,
label: '委托加工',
applicationNoPrefix: 'WTJG'
}
}
@@ -86,7 +101,11 @@ export function getPilotBizConfig(bizType?: string): PilotBizTypeConfig {
}
export function resolvePilotBizType(bizType?: string): PilotBizType {
if (bizType === 'clinical_application' || bizType === 'basic_experiment') {
if (
bizType === 'clinical_application' ||
bizType === 'basic_experiment' ||
bizType === 'contract_processing'
) {
return bizType
}
return 'pilot_service'
@@ -0,0 +1,67 @@
/** 临床科研申请单 · 业务子类型(researchCategory) */
export const CLINICAL_RESEARCH_CATEGORY_OPTIONS = [
{ value: 'bio_tech_clinical', label: '生物新技术临床科研' },
{ value: 'joint_topic_declare', label: '临床课题联合申报' },
{ value: 'bio_pharma_rd', label: '生物制药研发' }
] as const
export type ClinicalResearchCategory =
(typeof CLINICAL_RESEARCH_CATEGORY_OPTIONS)[number]['value']
/** 委托加工 · 产品业务类型 */
export const CONTRACT_PROCESSING_CATEGORY_OPTIONS = [
{ value: 'placenta_freeze_dried', label: '胎盘冻干粉' },
{ value: 'adipose_exosome', label: '脂肪外泌体' },
{ value: 'nk', label: 'NK' },
{ value: 'msc', label: 'MSC' }
] as const
export type ContractProcessingCategory =
(typeof CONTRACT_PROCESSING_CATEGORY_OPTIONS)[number]['value']
/** @deprecated 已由维护弹窗自定义类型取代,保留兼容旧数据回显 */
export const RESEARCH_CATEGORY_OTHER_VALUE = '__other__'
const LABEL_MAP = Object.fromEntries(
[
...CLINICAL_RESEARCH_CATEGORY_OPTIONS,
...CONTRACT_PROCESSING_CATEGORY_OPTIONS
].map((o) => [o.value, o.label])
) as Record<string, string>
export function clinicalResearchCategoryLabel(code?: string | null): string {
if (!code) return ''
return LABEL_MAP[code] || code
}
export type ResearchCategoryOption = { value: string; label: string }
export function researchCategoryOptionsForBiz(
bizType?: string | null,
customOptions: ResearchCategoryOption[] = []
): ResearchCategoryOption[] {
const fixedSource =
bizType === 'contract_processing'
? CONTRACT_PROCESSING_CATEGORY_OPTIONS
: CLINICAL_RESEARCH_CATEGORY_OPTIONS
const fixed = fixedSource.map((o) => ({
value: o.value,
label: o.label
}))
const seen = new Set(fixed.map((o) => o.value))
const customs = customOptions.filter((o) => o.value && !seen.has(o.value))
return [...fixed, ...customs]
}
export function isFixedContractProcessingCategory(code?: string | null): boolean {
return CONTRACT_PROCESSING_CATEGORY_OPTIONS.some((o) => o.value === code)
}
export function isFixedClinicalResearchCategory(code?: string | null): boolean {
return CLINICAL_RESEARCH_CATEGORY_OPTIONS.some((o) => o.value === code)
}
export function isFixedResearchCategory(bizType?: string | null, code?: string | null): boolean {
if (bizType === 'contract_processing') return isFixedContractProcessingCategory(code)
return isFixedClinicalResearchCategory(code)
}
+20 -3
View File
@@ -368,8 +368,6 @@ async function handleDynamicRoutes(
return
}
// 标记初始化失败,防止死循环
routeInitFailed = true
routeInitInProgress = false
// 输出详细错误信息,便于排查
@@ -377,7 +375,14 @@ async function handleDynamicRoutes(
console.error(`[RouteGuard] 错误码: ${error.code}, 消息: ${error.message}`)
}
// 跳转到 500 页面,使用 replace 避免产生历史记录
// 后端短暂不可达/超时:展示 500,但不永久锁定,便于服务恢复后点「返回首页」重试
if (isRecoverableInitError(error)) {
next({ name: 'Exception500', replace: true })
return
}
// 其它初始化失败:标记失败,防止死循环(刷新页面或重新登录可重置)
routeInitFailed = true
next({ name: 'Exception500', replace: true })
}
}
@@ -448,3 +453,15 @@ function handleRootPathRedirect(to: RouteLocationNormalized, next: NavigationGua
function isUnauthorizedError(error: unknown): boolean {
return isHttpError(error) && error.code === ApiStatus.unauthorized
}
/** 后端暂不可达类错误:允许用户在服务恢复后重试初始化 */
function isRecoverableInitError(error: unknown): boolean {
if (!isHttpError(error)) return false
return (
error.code === ApiStatus.networkError ||
error.code === ApiStatus.requestTimeout ||
error.code === ApiStatus.badGateway ||
error.code === ApiStatus.serviceUnavailable ||
error.code === ApiStatus.gatewayTimeout
)
}
+193 -7
View File
@@ -60,8 +60,8 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
},
// ═══════════════════════════════════════════════════════════════════════════
// 1. 市场 (menu:market)
// 二级菜单:存储服务、科研捐赠、市场基础信息、中试服务、基础实验
// (主推存储/捐赠在前;中试/基础实验及关联基础信息后置)
// 二级菜单:存储服务、科研捐赠、市场基础信息、临床科研、器械销售
// (主推存储/捐赠在前;中试/临床科研及关联基础信息后置;器械销售在末位)
// ═══════════════════════════════════════════════════════════════════════════
{
id: 'TOP00000000000000000000000000001',
@@ -329,7 +329,7 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
]
},
// ── 市场基础信息(前段:存储/捐赠相关;后段:中试/基础实验相关)──
// ── 市场基础信息(前段:存储/捐赠相关;后段:中试/临床科研相关)──
{
id: 'MKT00000000000000000000000000001',
name: 'MarketInfo',
@@ -553,7 +553,7 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
]
},
// ── 中试服务 ──────────────────────────────────────────────────────────
// ── 中试服务(侧栏隐藏;菜单定义保留为「隐藏」,角色授权已收回)────────
{
id: 'PIL00000000000000000000000000001',
name: 'PilotService',
@@ -563,6 +563,7 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
title: '中试服务',
icon: 'ri:flask-line',
keepAlive: false,
isHide: true,
roles: ['admin']
},
children: [
@@ -574,6 +575,7 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
meta: {
title: '中试服务申请单',
keepAlive: true,
isHide: true,
menuCode: 'pilot-service:pilot-application:list'
},
props: { bizType: 'pilot_service' }
@@ -612,6 +614,7 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
meta: {
title: '出库放行审核',
keepAlive: true,
isHide: true,
menuCode: 'pilot-service:outbound-release-review:list'
},
props: { bizType: 'pilot_service' }
@@ -619,14 +622,14 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
]
},
// ── 基础实验 ──────────────────────────────────────────────────────────
// ── 临床科研 ──────────────────────────────────────────────────────────
{
id: 'BEX00000000000000000000000000001',
name: 'BasicExperiment',
path: 'basic-experiment',
component: '',
meta: {
title: '基础实验',
title: '临床科研',
icon: 'ri:flask-line',
keepAlive: false,
roles: ['admin']
@@ -638,12 +641,38 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
path: 'application',
component: '/pilot-service/pilot-application/index',
meta: {
title: '基础实验申请单',
title: '临床科研申请单',
keepAlive: true,
menuCode: 'basic-experiment:application:list'
},
props: { bizType: 'basic_experiment' }
},
{
id: 'BEX00000000000000000000000000006',
name: 'BasicExperimentApproval',
path: 'approval',
component: '/pilot-service/pilot-application/index',
meta: {
title: '临床科研审批',
keepAlive: true,
menuCode: 'basic-experiment:approval:list',
bizType: 'basic_experiment',
approvalOnly: true
},
props: { bizType: 'basic_experiment', approvalOnly: true }
},
{
id: 'BEX00000000000000000000000000005',
name: 'BasicExperimentFeeInfo',
path: 'fee-info',
component: '/pilot-service/fee-info/index',
meta: {
title: '费用信息',
keepAlive: true,
menuCode: 'basic-experiment:fee-info:list'
},
props: { bizType: 'basic_experiment' }
},
{
id: 'BEX00000000000000000000000000003',
name: 'BasicExperimentPaymentConfirm',
@@ -652,6 +681,7 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
meta: {
title: '缴退费财务确认',
keepAlive: true,
isHide: true,
menuCode: 'basic-experiment:payment-confirm:list'
},
props: { bizType: 'basic_experiment' }
@@ -669,6 +699,134 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
props: { bizType: 'basic_experiment' }
}
]
},
// ── 委托加工(复用临床科研页面,bizType=contract_processing)──────────
{
id: 'CPG00000000000000000000000000001',
name: 'ContractProcessing',
path: 'contract-processing',
component: '',
meta: {
title: '委托加工',
icon: 'ri:tools-line',
keepAlive: false,
roles: ['admin']
},
children: [
{
id: 'CPG00000000000000000000000000002',
name: 'ContractProcessingApplication',
path: 'application',
component: '/pilot-service/pilot-application/index',
meta: {
title: '委托加工申请单',
keepAlive: true,
menuCode: 'contract-processing:application:list'
},
props: { bizType: 'contract_processing' }
},
{
id: 'CPG00000000000000000000000000006',
name: 'ContractProcessingApproval',
path: 'approval',
component: '/pilot-service/pilot-application/index',
meta: {
title: '委托加工审批',
keepAlive: true,
menuCode: 'contract-processing:approval:list',
bizType: 'contract_processing',
approvalOnly: true
},
props: { bizType: 'contract_processing', approvalOnly: true }
},
{
id: 'CPG00000000000000000000000000005',
name: 'ContractProcessingFeeInfo',
path: 'fee-info',
component: '/pilot-service/fee-info/index',
meta: {
title: '费用信息',
keepAlive: true,
menuCode: 'contract-processing:fee-info:list'
},
props: { bizType: 'contract_processing' }
},
{
id: 'CPG00000000000000000000000000003',
name: 'ContractProcessingPaymentConfirm',
path: 'payment-confirm',
component: '/pilot-service/clinical-payment-confirm/index',
meta: {
title: '缴退费财务确认',
keepAlive: true,
isHide: true,
menuCode: 'contract-processing:payment-confirm:list'
},
props: { bizType: 'contract_processing' }
},
{
id: 'CPG00000000000000000000000000004',
name: 'ContractProcessingOutboundRelease',
path: 'outbound-release-review',
component: '/pilot-service/outbound-release-review/index',
meta: {
title: '出库放行审核',
keepAlive: true,
menuCode: 'contract-processing:outbound-release-review:list'
},
props: { bizType: 'contract_processing' }
}
]
},
// ── 器械销售(市场侧栏末位;占位页待完善)────────────────────────────
{
id: 'DEV00000000000000000000000000001',
name: 'DeviceSales',
path: 'device-sales',
component: '',
meta: {
title: '器械销售',
icon: 'ri:shopping-bag-3-line',
keepAlive: false,
roles: ['admin']
},
children: [
{
id: 'DEV00000000000000000000000000002',
name: 'DeviceSalesClassIii',
path: 'class-iii',
component: '/device-sales/under-construction/index',
meta: {
title: '三类医疗器械',
keepAlive: false,
menuCode: 'device-sales:class-iii:list'
}
},
{
id: 'DEV00000000000000000000000000003',
name: 'DeviceSalesClassIi',
path: 'class-ii',
component: '/device-sales/under-construction/index',
meta: {
title: '二类医疗器械',
keepAlive: false,
menuCode: 'device-sales:class-ii:list'
}
},
{
id: 'DEV00000000000000000000000000004',
name: 'DeviceSalesCosmetics',
path: 'cosmetics',
component: '/device-sales/under-construction/index',
meta: {
title: '化妆品产品',
keepAlive: false,
menuCode: 'device-sales:cosmetics:list'
}
}
]
}
]
},
@@ -934,6 +1092,34 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
menuCode: 'production:waste-output:list'
}
},
{
id: 'PRD00000000000000000000000000001',
name: 'ProductionBasicExperimentOutbound',
path: 'basic-experiment-outbound',
component: '/pilot-service/pilot-application/index',
meta: {
title: '临床科研出库',
keepAlive: true,
menuCode: 'production:basic-experiment-outbound:list',
bizType: 'basic_experiment',
productionOutbound: true
},
props: { bizType: 'basic_experiment', productionOutbound: true }
},
{
id: 'PRD00000000000000000000000000002',
name: 'ProductionContractProcessingOutbound',
path: 'contract-processing-outbound',
component: '/pilot-service/pilot-application/index',
meta: {
title: '委托加工出库',
keepAlive: true,
menuCode: 'production:contract-processing-outbound:list',
bizType: 'contract_processing',
productionOutbound: true
},
props: { bizType: 'contract_processing', productionOutbound: true }
},
{
id: 'PRM0000000000000000000000000LSP1',
name: 'ProductionLabSampleProcess',
Loaded 100 of 168 files, more files were not shown because too many files have changed in this diff. Show more