Compare commits

...
Author SHA1 Message Date
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 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
137 changed files with 10552 additions and 1345 deletions

No files matched your search

+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))
# ---------------------------------------------------------------------------
# 细胞样本类型
# ---------------------------------------------------------------------------
+126 -32
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",
@@ -298,37 +298,7 @@ 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",
@@ -352,6 +322,30 @@ STATIC_MENU_TREE = [
"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",
},
},
@@ -376,6 +371,79 @@ 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",
@@ -631,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,
+5
View File
@@ -980,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()
@@ -1178,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")),
):
@@ -1194,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))
+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
+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)))
@@ -42,6 +42,7 @@ _BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"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)))
+545 -58
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
@@ -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(
@@ -919,7 +930,7 @@ def _deduct_fee_on_complete(db: Session, schedule_id: str, tenant_no: str, user_
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
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": "待开始",
@@ -3328,6 +3330,7 @@ _PRODUCTION_TAB_STEP_COUNT_KEYS = (
"inbound_research_donation",
"outbound_pilot_service",
"outbound_basic_experiment",
"outbound_contract_processing",
"temporary",
)
@@ -3351,6 +3354,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"
+3 -1
View File
@@ -199,6 +199,7 @@ def _wo_to_dict(wo: BizProductionWorkOrder) -> Dict[str, Any]:
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"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),
@@ -289,6 +290,7 @@ _BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"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(
+77 -34
View File
@@ -109,6 +109,7 @@ _OUTBOUND_BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"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 ""
+103
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)
+66 -1
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="备注")
@@ -2661,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="备注")
@@ -4182,11 +4229,29 @@ class BizPilotApplication(Base):
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="备注")
@@ -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,
+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()
@@ -28,7 +28,9 @@ _PAY_STATUS_LABELS = {
}
# 出库工单:输注计划缴费(临床科研 / 临床应用共用 biz_pilot_payment)
_OUTBOUND_FEE_BIZ_TYPES = frozenset({"basic_experiment", "clinical_application"})
_OUTBOUND_FEE_BIZ_TYPES = frozenset(
{"basic_experiment", "contract_processing", "clinical_application"}
)
def _is_outbound_fee_biz_type(biz_type: Optional[str]) -> bool:
@@ -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()
@@ -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")
@@ -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)
@@ -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,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,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;
+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[] }
+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
@@ -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
}) {
@@ -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>
+37 -18
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: {
...RESEARCH_LIKE_CONFIG,
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: '交付状态'
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)
}
+139 -2
View File
@@ -60,7 +60,7 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
},
// ═══════════════════════════════════════════════════════════════════════════
// 1. 市场 (menu:market)
// 二级菜单:存储服务、科研捐赠、市场基础信息、中试服务、临床科研、器械销售
// 二级菜单:存储服务、科研捐赠、市场基础信息、临床科研、器械销售
// (主推存储/捐赠在前;中试/临床科研及关联基础信息后置;器械销售在末位)
// ═══════════════════════════════════════════════════════════════════════════
{
@@ -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' }
@@ -644,6 +647,32 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
},
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' }
@@ -671,6 +701,85 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
]
},
// ── 委托加工(复用临床科研页面,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',
@@ -983,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',
+31
View File
@@ -495,6 +495,33 @@ declare namespace Api {
}
}
namespace PartnerCustomer {
interface Item {
id: string
customerName: string
customerContact: string
customerPhone: string
tenantNo: string
orderNum: number
remark: string
createTime: string
updateTime: string
}
}
namespace ContractProcessingCategory {
interface Item {
id: string
categoryName: string
bizType?: string
tenantNo: string
orderNum: number
remark: string
createTime: string
updateTime: string
}
}
namespace BizCustomer {
interface CustomerItem {
id: string
@@ -857,6 +884,10 @@ declare namespace Api {
id: string
specCode: string
specName: string
/** 细胞数量(单位:千万),存量可为空 */
cellCountQianwan: number | null
/** 分装体积(单位:ml),存量可为空 */
fillVolumeMl: number | null
tenantNo: string
orderNum: number
remark: string
@@ -25,7 +25,7 @@ describe('donation protocol status filter helpers', () => {
it('matchesProtocolStatusFilter semantics', () => {
assert.equal(matchesProtocolStatusFilter('yzf', undefined), true)
assert.equal(matchesProtocolStatusFilter('yzf', []), false)
assert.equal(matchesProtocolStatusFilter('yzf', []), true)
assert.equal(matchesProtocolStatusFilter('sxz', ['dsx', 'sxz']), true)
assert.equal(matchesProtocolStatusFilter('yzf', ['dsx', 'sxz']), false)
assert.equal(matchesProtocolStatusFilter('', ['dsx']), false)
@@ -18,7 +18,7 @@ export const DEFAULT_DONATION_PROTOCOL_STATUS_FILTER = ['dsx', 'sxz']
/**
* 拼协议状态查询参数。
* - 有选中:逗号串
* - 空数组:返回 ''(显式空;勿当 undefined)
* - 空数组:返回 ''(显式空=不限制;勿当 undefined,undefined 会走后端默认勾选)
*/
export function joinProtocolStatusFilter(statuses: string[]): string {
return statuses.map((s) => s.trim()).filter(Boolean).join(',')
@@ -27,13 +27,12 @@ export function joinProtocolStatusFilter(statuses: string[]): string {
/**
* 协议状态是否命中筛选。
* - filter === undefined:不限制
* - filter 为空数组:无匹配
* - filter 为空数组:不限制(显式清空)
*/
export function matchesProtocolStatusFilter(
status: string,
filter: string[] | undefined
): boolean {
if (filter === undefined) return true
if (!filter.length) return false
if (filter === undefined || !filter.length) return true
return filter.includes((status || '').trim())
}
@@ -0,0 +1,11 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { nextFilterOptionsEpoch } from './filter-options-epoch'
describe('nextFilterOptionsEpoch', () => {
it('bumps only when at least one assignment succeeded', () => {
assert.equal(nextFilterOptionsEpoch(3, 1), 4)
assert.equal(nextFilterOptionsEpoch(3, 2), 4)
assert.equal(nextFilterOptionsEpoch(3, 0), 3)
})
})
@@ -0,0 +1,4 @@
/** After successful assignment saves, bump so filter ProjectSelect reloads options. */
export function nextFilterOptionsEpoch(epoch: number, successCount: number) {
return successCount > 0 ? epoch + 1 : epoch
}
@@ -1,6 +1,7 @@
import type { OutboundQcDetail } from '@/api/qc-work-order'
import type { ViewField, ViewSection } from '@/components/business/system-view-dialog/index.vue'
import { maskIdCard } from '@/utils/mask-sensitive'
import { isResearchLikeBiz } from '@/utils/research-like-biz'
import {
applicationStatusLabel,
applicationStatusTagType,
@@ -18,6 +19,7 @@ export type OutboundViewContextVariant =
| 'pilot_service'
| 'clinical_application'
| 'basic_experiment'
| 'contract_processing'
const SECTION_TITLES: Record<
OutboundViewContextVariant,
@@ -34,6 +36,10 @@ const SECTION_TITLES: Record<
basic_experiment: {
application: '临床科研申请信息',
schedule: '交付计划信息'
},
contract_processing: {
application: '委托加工申请信息',
schedule: '交付计划信息'
}
}
@@ -56,7 +62,7 @@ function buildDefaultApplicationFields(
app: NonNullable<OutboundQcDetail['application']>,
variant: OutboundViewContextVariant
) {
if (variant === 'basic_experiment') {
if (isResearchLikeBiz(variant)) {
return buildBasicExperimentApplicationFields(app)
}
return [
@@ -82,6 +88,7 @@ export function buildOutboundPilotContextSections(
const schedule = detail.infusionSchedule
const products = detail.products || []
const titles = SECTION_TITLES[variant]
const researchLike = isResearchLikeBiz(variant)
const result: ViewSection[] = []
if (app) {
@@ -91,7 +98,7 @@ export function buildOutboundPilotContextSections(
})
}
if (patient && variant !== 'basic_experiment') {
if (patient && !researchLike) {
result.push({
title: '患者信息',
fields: [
@@ -113,7 +120,7 @@ export function buildOutboundPilotContextSections(
})
}
if (plan && variant !== 'basic_experiment') {
if (plan && !researchLike) {
result.push({
title: '输注方案信息',
fields: [
@@ -128,12 +135,12 @@ export function buildOutboundPilotContextSections(
}
if (schedule) {
const pickupLabel = variant === 'basic_experiment' ? '交付时间' : '输注时间'
const pickupLabel = researchLike ? '交付时间' : '输注时间'
const scheduleFields: ViewField[] = [
{ label: pickupLabel, value: schedule.infusionTime || '—' }
]
if (variant === 'basic_experiment') {
if (researchLike) {
scheduleFields.push({
label: '售卖金额',
value:
@@ -154,7 +161,7 @@ export function buildOutboundPilotContextSections(
tagType: scheduleStatusTagType(schedule.scheduleStatus || '') as ViewField['tagType']
})
if (variant !== 'basic_experiment') {
if (!researchLike) {
scheduleFields.push({
label: '输注状态',
value: infusionStatusLabel(schedule.infusionStatus || ''),
@@ -186,9 +193,9 @@ export function buildOutboundPilotContextSections(
}
export function resolveOutboundViewVariant(bizType?: string | null): OutboundViewContextVariant {
if (bizType === 'clinical_application' || bizType === 'basic_experiment') {
return bizType
}
if (bizType === 'clinical_application') return 'clinical_application'
if (bizType === 'contract_processing') return 'contract_processing'
if (bizType === 'basic_experiment') return 'basic_experiment'
return 'pilot_service'
}
@@ -6,7 +6,8 @@ import {
resolveTabKeyFromWorkOrder,
getProductionWorkOrderTab,
toWorkOrderListQuery,
isAllProductionWorkOrderTab
isAllProductionWorkOrderTab,
workOrderMatchesTab
} from '@/utils/production-work-order-tabs'
import { toAllTabListQuery, workOrderMatchesCategory } from '@/utils/production-work-order-category'
import { matchesWorkOrderStatusFilter } from '@/utils/status-tag-registry'
@@ -52,7 +53,7 @@ function keywordMatchesWorkOrder(
const fields =
tabKey === 'temporary'
? [row.remark]
: tabKey === 'outbound_basic_experiment'
: tabKey === 'outbound_basic_experiment' || tabKey === 'outbound_contract_processing'
? [
row.workOrderNo,
row.applicationNo,
@@ -231,9 +232,7 @@ export function filterMineEntriesByWorkOrderSearch(
const tabKey = filters.tabKey
return entries.filter((entry) => {
const row = entry.workOrder
if (!isAllProductionWorkOrderTab(tabKey) && resolveTabKeyFromWorkOrder(row) !== tabKey) {
return false
}
if (!workOrderMatchesTab(row, tabKey)) return false
if (
isAllProductionWorkOrderTab(tabKey) &&
!workOrderMatchesCategory(row, filters.productionCategory || '')
@@ -251,6 +251,19 @@ const CARD_META_BY_TAB: Record<ProductionWorkOrderTabKey, ProductionWorkOrderCar
allowEditRemark: true,
allowDelete: false
},
outbound_contract_processing: {
tabKey: 'outbound_contract_processing',
showCategoryTag: false,
showProtocolFeeSummary: false,
showOutboundFeeSummary: true,
showCellProducts: true,
metaFields: outboundBasicExperimentFields,
allowDispatchQc: true,
allowSampleReception: false,
allowDispatchComplete: true,
allowEditRemark: true,
allowDelete: false
},
outbound_clinical_application: {
tabKey: 'outbound_clinical_application',
showCategoryTag: false,
@@ -26,6 +26,7 @@ const CATEGORY_LABELS: Record<ProductionWorkOrderCategoryKey, string> = {
inbound_research_donation: '科研捐赠',
outbound_pilot_service: '中试服务',
outbound_basic_experiment: '临床科研',
outbound_contract_processing: '委托加工',
temporary: '临时'
}
@@ -34,6 +35,7 @@ const CATEGORY_TAG_TYPES: Record<ProductionWorkOrderCategoryKey, TagType> = {
inbound_research_donation: 'primary',
outbound_pilot_service: 'info',
outbound_basic_experiment: 'info',
outbound_contract_processing: 'info',
temporary: 'warning'
}
@@ -0,0 +1,39 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import {
PRODUCTION_WORK_ORDER_VISIBLE_TABS,
parseProductionWorkOrderTabKey,
workOrderMatchesTab,
isPilotServiceOutboundWorkOrder
} from './production-work-order-tabs'
import { PRODUCTION_WORK_ORDER_CATEGORY_OPTIONS } from './production-work-order-category'
describe('production work order tabs — hide pilot service', () => {
it('visible tabs exclude outbound_pilot_service', () => {
assert.ok(!PRODUCTION_WORK_ORDER_VISIBLE_TABS.some((t) => t.key === 'outbound_pilot_service'))
assert.ok(!PRODUCTION_WORK_ORDER_CATEGORY_OPTIONS.some((o) => o.key === 'outbound_pilot_service'))
})
it('parse: hidden pilot key and outbound alias fall back safely', () => {
assert.equal(parseProductionWorkOrderTabKey('outbound_pilot_service'), 'all')
assert.equal(parseProductionWorkOrderTabKey('outbound'), 'outbound_basic_experiment')
})
it('「所有」excludes pilot outbound (incl. default bizType)', () => {
const pilot = { workOrderType: 'outbound', bizType: 'pilot_service' }
const defaultPilot = { workOrderType: 'outbound' }
const basic = { workOrderType: 'outbound', bizType: 'basic_experiment' }
const contract = { workOrderType: 'outbound', bizType: 'contract_processing' }
assert.equal(isPilotServiceOutboundWorkOrder(pilot), true)
assert.equal(isPilotServiceOutboundWorkOrder(defaultPilot), true)
assert.equal(workOrderMatchesTab(pilot as any, 'all'), false)
assert.equal(workOrderMatchesTab(defaultPilot as any, 'all'), false)
assert.equal(workOrderMatchesTab(basic as any, 'all'), true)
assert.equal(workOrderMatchesTab(contract as any, 'all'), true)
assert.equal(workOrderMatchesTab(contract as any, 'outbound_contract_processing'), true)
})
it('visible tabs include contract processing', () => {
assert.ok(PRODUCTION_WORK_ORDER_VISIBLE_TABS.some((t) => t.key === 'outbound_contract_processing'))
})
})
@@ -6,6 +6,7 @@ export type ProductionWorkOrderTabKey =
| 'inbound_research_donation'
| 'outbound_pilot_service'
| 'outbound_basic_experiment'
| 'outbound_contract_processing'
| 'outbound_clinical_application'
| 'temporary'
@@ -17,7 +18,7 @@ export type ProductionWorkOrderTabConfig = {
group: ProductionWorkOrderTabGroup
workOrderType: 'inbound' | 'outbound' | 'temporary'
receptionSource?: 'cell_storage' | 'research_donation'
bizType?: 'pilot_service' | 'basic_experiment' | 'clinical_application'
bizType?: 'pilot_service' | 'basic_experiment' | 'contract_processing' | 'clinical_application'
listLayout: 'inbound-grouped' | 'standalone'
/** 侧栏 Tab 不展示(保留 key 供路由/数据解析) */
hidden?: boolean
@@ -53,7 +54,9 @@ export const PRODUCTION_WORK_ORDER_TABS: ProductionWorkOrderTabConfig[] = [
group: 'outbound',
workOrderType: 'outbound',
bizType: 'pilot_service',
listLayout: 'standalone'
listLayout: 'standalone',
/** 与市场中试菜单一致:侧栏 Tab 隐藏,保留 key 供历史工单解析 */
hidden: true
},
{
key: 'outbound_basic_experiment',
@@ -63,6 +66,14 @@ export const PRODUCTION_WORK_ORDER_TABS: ProductionWorkOrderTabConfig[] = [
bizType: 'basic_experiment',
listLayout: 'standalone'
},
{
key: 'outbound_contract_processing',
label: '委托加工生产',
group: 'outbound',
workOrderType: 'outbound',
bizType: 'contract_processing',
listLayout: 'standalone'
},
{
key: 'outbound_clinical_application',
label: '临床应用生产',
@@ -97,7 +108,7 @@ export function parseProductionWorkOrderTabKey(raw?: string | null): ProductionW
const tab = getProductionWorkOrderTab(k)
if (tab && !tab.hidden) return tab.key
if (k === 'inbound') return 'inbound_cell_storage'
if (k === 'outbound') return 'outbound_pilot_service'
if (k === 'outbound') return 'outbound_basic_experiment'
if (k === 'temporary') return 'temporary'
return DEFAULT_PRODUCTION_WORK_ORDER_TAB
}
@@ -127,6 +138,7 @@ export function resolveTabKeyFromWorkOrder(row: {
if (wt === 'outbound') {
const bt = row.bizType || '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'
}
@@ -138,18 +150,26 @@ export function resolveTabKeyFromWorkOrder(row: {
export function keywordPlaceholderForTab(tab: ProductionWorkOrderTabConfig): string {
if (tab.key === 'all') return '工单号 / 样本编码 / 申请单号 / 产品名称等'
if (tab.key === 'temporary') return '备注'
if (tab.key === 'outbound_basic_experiment') {
if (tab.key === 'outbound_basic_experiment' || tab.key === 'outbound_contract_processing') {
return '工单号/申请单号/课题名称/客户'
}
if (tab.group === 'outbound') return '工单号/申请单号/申请单名称/患者'
return '工单号/样本编码/入库编码'
}
/** 出库中试服务(含 bizType 缺省落成中试) */
export function isPilotServiceOutboundWorkOrder(row: {
workOrderType?: string
bizType?: string
}): boolean {
return resolveTabKeyFromWorkOrder(row) === 'outbound_pilot_service'
}
export function workOrderMatchesTab(
row: ProductionWorkOrderItem,
tabKey: ProductionWorkOrderTabKey
): boolean {
if (tabKey === 'all') return true
if (tabKey === 'all') return !isPilotServiceOutboundWorkOrder(row)
return resolveTabKeyFromWorkOrder(row) === tabKey
}
+18
View File
@@ -1,5 +1,23 @@
import type { BizType, ProjectRecord } from '@/api/project-management'
/**
* 项目新建/编辑弹窗「业务类型」选项。
* 中试服务已下线:默认不可选;若旧项目已含 pilot_service 则保留展示。
*/
export function projectBizTypeSelectLabels(
allLabels: Record<string, string>,
selectedBizTypes?: string[] | null
): Record<string, string> {
const selected = new Set((selectedBizTypes || []).filter(Boolean))
return Object.fromEntries(
Object.entries(allLabels).filter(([key]) => {
if (key === 'presign') return false
if (key === 'pilot_service') return selected.has('pilot_service')
return true
})
)
}
/** Drill-down uses the last successful statistics query, never unsaved filter edits. */
export function buildDrillFilters(
applied: ProjectRecord,
+11 -7
View File
@@ -10,7 +10,8 @@ import {
tabUsesInfusionTimeFilter,
getQcWorkOrderTab,
toWorkOrderListQuery,
isAllQcWorkOrderTab
isAllQcWorkOrderTab,
workOrderMatchesTab
} from '@/utils/qc-work-order-tabs'
import {
matchesAllTabTriggerSource,
@@ -26,13 +27,15 @@ export type QcTaskMineFilters = {
keyword?: string
taskType?: string
taskStatus?: string
/** 科研捐赠:协议状态逗号串;''=不限制;缺省不传 */
protocolStatus?: string
tabKey: QcWorkOrderTabKey
}
export type MineWorkOrderSearchFilters = {
keyword?: string
workOrderStatus?: string | string[]
/** 科研捐赠 Tab:协议/捐赠状态多选;undefined=不限制;[]=无匹配 */
/** 科研捐赠 Tab:协议/捐赠状态多选;undefined/[]=不限制 */
protocolStatus?: string[]
triggerSource?: string
qcCategory?: string
@@ -72,7 +75,7 @@ function keywordMatchesWorkOrder(
const fields =
tabKey === 'temporary'
? [row.workOrderNo, row.productionWorkOrderNo]
: tabKey === 'outbound_basic_experiment'
: tabKey === 'outbound_basic_experiment' || tabKey === 'outbound_contract_processing'
? [
row.workOrderNo,
row.applicationNo,
@@ -101,9 +104,7 @@ export function filterMineEntriesByWorkOrderSearch(
const tab = getQcWorkOrderTab(tabKey)!
return entries.filter((entry) => {
const row = entry.workOrder
if (!isAllQcWorkOrderTab(tabKey) && resolveTabKeyFromWorkOrder(row) !== tabKey) {
return false
}
if (!workOrderMatchesTab(row, tabKey)) return false
if (isAllQcWorkOrderTab(tabKey) && !workOrderMatchesCategory(row, filters.qcCategory || '')) {
return false
}
@@ -146,6 +147,8 @@ export async function fetchAllMineTasks(filters: QcTaskMineFilters): Promise<QcT
let page = 1
const all: QcTask[] = []
let total = 0
const protocolStatusParam =
filters.tabKey === 'inbound_research_donation' ? (filters.protocolStatus ?? '') : undefined
while (true) {
const res = await fetchMyQcTaskList({
page,
@@ -155,7 +158,8 @@ export async function fetchAllMineTasks(filters: QcTaskMineFilters): Promise<QcT
taskStatus: filters.taskStatus || undefined,
qcBizType: listQuery.workOrderType,
receptionSource: listQuery.receptionSource,
bizType: listQuery.bizType
bizType: listQuery.bizType,
...(protocolStatusParam !== undefined ? { protocolStatus: protocolStatusParam } : {})
})
const list = res.list || []
all.push(...list)
@@ -356,6 +356,20 @@ const CARD_META_BY_TAB: Record<QcWorkOrderTabKey, QcWorkOrderCardMetaConfig> = {
allowEditRemark: true,
allowDelete: false
},
outbound_contract_processing: {
tabKey: 'outbound_contract_processing',
listLayout: 'outbound-grouped',
showCategoryTag: false,
showTriggerTag: true,
showProtocolFeeSummary: false,
showOutboundFeeSummary: true,
showCellProducts: true,
metaFields: outboundGroupedFields,
buildGroupContextParts: buildOutboundBasicExperimentGroupContext,
allowEditTemporary: false,
allowEditRemark: true,
allowDelete: false
},
outbound_clinical_application: {
tabKey: 'outbound_clinical_application',
listLayout: 'standalone',
@@ -25,6 +25,7 @@ const CATEGORY_LABELS: Record<QcWorkOrderCategoryKey, string> = {
inbound_research_donation: '科研捐赠',
outbound_pilot_service: '中试服务',
outbound_basic_experiment: '临床科研',
outbound_contract_processing: '委托加工',
temporary: '临时'
}
@@ -33,6 +34,7 @@ const CATEGORY_TAG_TYPES: Record<QcWorkOrderCategoryKey, TagType> = {
inbound_research_donation: 'primary',
outbound_pilot_service: 'info',
outbound_basic_experiment: 'info',
outbound_contract_processing: 'info',
temporary: 'warning'
}
@@ -0,0 +1,40 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import {
QC_WORK_ORDER_VISIBLE_TABS,
parseQcWorkOrderTabKey,
workOrderMatchesTab,
isPilotServiceOutboundWorkOrder
} from './qc-work-order-tabs'
import { QC_WORK_ORDER_CATEGORY_OPTIONS } from './qc-work-order-category'
describe('qc work order tabs — hide pilot service', () => {
it('visible tabs exclude outbound_pilot_service', () => {
assert.ok(!QC_WORK_ORDER_VISIBLE_TABS.some((t) => t.key === 'outbound_pilot_service'))
assert.ok(!QC_WORK_ORDER_CATEGORY_OPTIONS.some((o) => o.key === 'outbound_pilot_service'))
})
it('parse: hidden pilot key and outbound alias fall back safely', () => {
// 质检默认 Tab 为细胞存储(「所有」本身也是 hidden)
assert.equal(parseQcWorkOrderTabKey('outbound_pilot_service'), 'inbound_cell_storage')
assert.equal(parseQcWorkOrderTabKey('outbound'), 'outbound_basic_experiment')
})
it('「所有」excludes pilot outbound (incl. default bizType)', () => {
const pilot = { workOrderType: 'outbound', bizType: 'pilot_service' }
const defaultPilot = { workOrderType: 'outbound' }
const basic = { workOrderType: 'outbound', bizType: 'basic_experiment' }
const contract = { workOrderType: 'outbound', bizType: 'contract_processing' }
assert.equal(isPilotServiceOutboundWorkOrder(pilot), true)
assert.equal(isPilotServiceOutboundWorkOrder(defaultPilot), true)
assert.equal(workOrderMatchesTab(pilot as any, 'all'), false)
assert.equal(workOrderMatchesTab(defaultPilot as any, 'all'), false)
assert.equal(workOrderMatchesTab(basic as any, 'all'), true)
assert.equal(workOrderMatchesTab(contract as any, 'all'), true)
assert.equal(workOrderMatchesTab(contract as any, 'outbound_contract_processing'), true)
})
it('visible tabs include contract processing', () => {
assert.ok(QC_WORK_ORDER_VISIBLE_TABS.some((t) => t.key === 'outbound_contract_processing'))
})
})
+28 -6
View File
@@ -6,6 +6,7 @@ export type QcWorkOrderTabKey =
| 'inbound_research_donation'
| 'outbound_pilot_service'
| 'outbound_basic_experiment'
| 'outbound_contract_processing'
| 'outbound_clinical_application'
| 'temporary'
@@ -17,7 +18,7 @@ export type QcWorkOrderTabConfig = {
group: QcWorkOrderTabGroup
workOrderType?: 'inbound' | 'outbound' | 'temporary'
receptionSource?: 'cell_storage' | 'research_donation'
bizType?: 'pilot_service' | 'basic_experiment' | 'clinical_application'
bizType?: 'pilot_service' | 'basic_experiment' | 'contract_processing' | 'clinical_application'
listLayout: 'inbound-grouped' | 'outbound-grouped' | 'standalone'
/** 侧栏 Tab 不展示(保留 key 供路由/数据解析) */
hidden?: boolean
@@ -53,7 +54,9 @@ export const QC_WORK_ORDER_TABS: QcWorkOrderTabConfig[] = [
group: 'outbound',
workOrderType: 'outbound',
bizType: 'pilot_service',
listLayout: 'outbound-grouped'
listLayout: 'outbound-grouped',
/** 与市场中试菜单一致:侧栏 Tab 隐藏,保留 key 供历史工单解析 */
hidden: true
},
{
key: 'outbound_basic_experiment',
@@ -63,6 +66,14 @@ export const QC_WORK_ORDER_TABS: QcWorkOrderTabConfig[] = [
bizType: 'basic_experiment',
listLayout: 'outbound-grouped'
},
{
key: 'outbound_contract_processing',
label: '委托加工质检',
group: 'outbound',
workOrderType: 'outbound',
bizType: 'contract_processing',
listLayout: 'outbound-grouped'
},
{
key: 'outbound_clinical_application',
label: '临床应用质检',
@@ -95,7 +106,7 @@ export function parseQcWorkOrderTabKey(raw?: string | null): QcWorkOrderTabKey {
const tab = getQcWorkOrderTab(k)
if (tab && !tab.hidden) return tab.key
if (k === 'inbound') return 'inbound_cell_storage'
if (k === 'outbound') return 'outbound_pilot_service'
if (k === 'outbound') return 'outbound_basic_experiment'
if (k === 'temporary') return 'temporary'
return DEFAULT_QC_WORK_ORDER_TAB
}
@@ -125,6 +136,7 @@ export function resolveTabKeyFromWorkOrder(row: {
if (wt === 'outbound') {
const bt = row.bizType || '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'
}
@@ -140,7 +152,7 @@ export function tabUsesInfusionTimeFilter(tab: QcWorkOrderTabConfig): boolean {
export function keywordPlaceholderForTab(tab: QcWorkOrderTabConfig): string {
if (tab.key === 'all') return '工单号 / 样本编码 / 母亲姓名 / 申请单号 / 产品名称等'
if (tab.key === 'temporary') return '工单号 / 外部编号'
if (tab.key === 'outbound_basic_experiment') {
if (tab.key === 'outbound_basic_experiment' || tab.key === 'outbound_contract_processing') {
return '工单号/申请单号/课题名称/客户'
}
if (tab.group === 'outbound') return '工单号/申请单号/申请单名称/患者'
@@ -155,13 +167,23 @@ export function keywordPlaceholderForTab(tab: QcWorkOrderTabConfig): string {
export function filterTimeLabelForTab(tab: QcWorkOrderTabConfig): string {
if (tab.key === 'all') return '创建时间'
if (tab.key === 'outbound_basic_experiment') return '交付时间'
if (tab.key === 'outbound_basic_experiment' || tab.key === 'outbound_contract_processing') {
return '交付时间'
}
if (tab.group === 'outbound') return '输注时间'
return '创建时间'
}
/** 出库中试服务(含 bizType 缺省落成中试) */
export function isPilotServiceOutboundWorkOrder(row: {
workOrderType?: string
bizType?: string
}): boolean {
return resolveTabKeyFromWorkOrder(row) === 'outbound_pilot_service'
}
export function workOrderMatchesTab(row: QcWorkOrder, tabKey: QcWorkOrderTabKey): boolean {
if (tabKey === 'all') return true
if (tabKey === 'all') return !isPilotServiceOutboundWorkOrder(row)
return resolveTabKeyFromWorkOrder(row) === tabKey
}
+12
View File
@@ -0,0 +1,12 @@
/** 临床科研 / 委托加工:共用申请、交付、缴费、出库流程 */
export const RESEARCH_LIKE_BIZ_TYPES = ['basic_experiment', 'contract_processing'] as const
export type ResearchLikeBizType = (typeof RESEARCH_LIKE_BIZ_TYPES)[number]
export function isResearchLikeBiz(bizType?: string | null): boolean {
return RESEARCH_LIKE_BIZ_TYPES.includes((bizType || '') as ResearchLikeBizType)
}
export function isContractProcessing(bizType?: string | null): boolean {
return (bizType || '') === 'contract_processing'
}
+28 -4
View File
@@ -3,6 +3,7 @@
*/
import { resolveVoidTypeLabel } from '@/utils/void-type-dict'
import { isResearchLikeBiz } from '@/utils/research-like-biz'
// ── 类型定义 ──────────────────────────────────────────────────────────────────
@@ -228,7 +229,8 @@ export const receptionSource: StatusRegistry = {
outbound: { label: '出库', tagType: 'primary' },
pilot_service: { label: '中试服务', tagType: 'primary' },
clinical_application: { label: '临床应用', tagType: 'warning' },
basic_experiment: { label: '临床科研', tagType: 'primary' }
basic_experiment: { label: '临床科研', tagType: 'primary' },
contract_processing: { label: '委托加工', tagType: 'primary' }
}
export const receptionSourceLabel = createLabelGetter(receptionSource)
export const receptionSourceTagType = createTagTypeGetter(receptionSource)
@@ -652,6 +654,26 @@ export function applicationStatusTagType(
return map[status] || 'info'
}
/** 临床科研/委托加工申请单审批状态 */
export function applicationApprovalStatusLabel(status: string): string {
const map: Record<string, string> = {
dsp: '待审批',
ytg: '已通过',
yth: '已驳回'
}
return map[status] || status || '-'
}
export function applicationApprovalStatusTagType(
status: string
): '' | 'success' | 'warning' | 'danger' | 'info' {
const map: Record<string, '' | 'success' | 'warning' | 'danger' | 'info'> = {
dsp: 'warning',
ytg: 'success',
yth: 'danger'
}
return map[status] || 'info'
}
// ========== 中试服务体检状态 ==========
export function checkupStatusLabel(status: string): string {
const map: Record<string, string> = {
@@ -761,7 +783,8 @@ export function bizTypeLabel(type: string): string {
const map: Record<string, string> = {
pilot_service: '中试服务',
clinical_application: '临床应用',
basic_experiment: '临床科研'
basic_experiment: '临床科研',
contract_processing: '委托加工'
}
return map[type] || type || '-'
}
@@ -769,14 +792,15 @@ export function bizTypeTagType(type: string): string {
const map: Record<string, string> = {
pilot_service: 'primary',
clinical_application: 'warning',
basic_experiment: 'primary'
basic_experiment: 'primary',
contract_processing: 'primary'
}
return map[type] || 'info'
}
// ========== 中试服务 - 产品状态 ==========
export function productStatusLabel(status: string, bizType?: string): string {
const isBasicExperiment = bizType === 'basic_experiment'
const isBasicExperiment = isResearchLikeBiz(bizType)
const map: Record<string, string> = {
dtz: isBasicExperiment ? '待交付' : '待输注',
yrqr: '已用户确认',
@@ -0,0 +1,433 @@
<!-- 合作客户基础信息 -->
<!-- eslint-disable vue/no-v-model-argument -->
<template>
<div class="partner-customer-tab">
<div class="filter-block">
<el-form :model="searchForm" class="filter-form" @submit.prevent>
<div class="filter-grid">
<el-form-item label="关键词">
<el-input
v-model="searchForm.keyword"
placeholder="客户名称/联系人/联系方式"
clearable
@keyup.enter="handleSearch"
/>
</el-form-item>
</div>
<div class="filter-actions-row">
<div class="filter-actions-end">
<el-button class="btn-ghost" @click="handleReset">
<el-icon><RefreshLeft /></el-icon>重置
</el-button>
<el-button class="btn-main" type="primary" @click="handleSearch">
<el-icon><Search /></el-icon>搜索
</el-button>
</div>
</div>
</el-form>
</div>
<div class="list-toolbar">
<div class="list-toolbar-row">
<div class="list-toolbar-selected">
已选 <span class="sel-num">{{ selectedRows.length }}</span> 项
</div>
<el-button class="btn-main" type="primary" @click="handleAdd">
<el-icon><Plus /></el-icon>
新增合作客户
</el-button>
<el-button
class="btn-ghost"
type="danger"
:disabled="selectedRows.length === 0"
@click="handleBatchDelete"
>
<el-icon><Delete /></el-icon>
批量删除
</el-button>
</div>
</div>
<div class="list-body list-wrap">
<el-table
class="list-table"
:data="tableData"
v-loading="loading"
stripe
row-key="id"
@selection-change="handleSelectionChange"
@row-dblclick="handleView"
>
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column
type="index"
label="序号"
min-width="68"
align="center"
header-align="center"
:index="(index: number) => (pagination.page - 1) * pagination.pageSize + index + 1"
/>
<el-table-column
prop="customerName"
label="客户名称"
min-width="160"
align="center"
header-align="center"
show-overflow-tooltip
/>
<el-table-column
prop="customerContact"
label="客户联系人"
min-width="140"
align="center"
header-align="center"
show-overflow-tooltip
/>
<el-table-column
prop="customerPhone"
label="客户联系方式"
min-width="140"
align="center"
header-align="center"
show-overflow-tooltip
/>
<el-table-column
prop="remark"
label="备注"
min-width="160"
show-overflow-tooltip
>
<template #default="{ row }">{{ row.remark || '—' }}</template>
</el-table-column>
<el-table-column
prop="createTime"
label="创建时间"
min-width="180"
align="center"
header-align="center"
>
<template #default="{ row }">{{ formatDisplayOrDash(row.createTime) }}</template>
</el-table-column>
<el-table-column
label="操作"
min-width="120"
fixed="right"
align="center"
header-align="center"
>
<template #default="{ row }">
<div style="display: flex; justify-content: center; gap: 8px">
<el-button class="btn-op-item" @click="handleView(row)">
<el-icon><View /></el-icon>查看
</el-button>
<el-dropdown
trigger="hover"
@command="(cmd: string) => handleDropdownCommand(cmd, row)"
>
<el-button class="btn-op-item">
<el-icon><More /></el-icon>
</el-button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item command="edit">
<el-icon><Edit /></el-icon>编辑
</el-dropdown-item>
<el-dropdown-item command="delete" divided>
<el-icon><Delete /></el-icon>删除
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</div>
</template>
</el-table-column>
</el-table>
<div class="pagination list-pager-bar">
<el-pagination
:current-page="pagination.page"
:page-size="pagination.pageSize"
:total="pagination.total"
:page-sizes="[10, 20, 50]"
layout="total, sizes, prev, pager, next"
@size-change="
(val: number) => ((pagination.page = 1), (pagination.pageSize = val), loadData())
"
@current-change="(val: number) => ((pagination.page = val), loadData())"
/>
</div>
</div>
<el-dialog
v-model="dialogVisible"
:title="dialogTitle"
width="640px"
class="dialog-form-layout"
align-center
append-to-body
modal-class="protocol-dialog-mask"
destroy-on-close
:close-on-click-modal="false"
>
<el-form
ref="formRef"
:model="formData"
:rules="formRules"
label-position="top"
class="biz-dialog-form"
scroll-to-error
:scroll-into-view-options="{ behavior: 'smooth', block: 'center' }"
>
<div class="form-grid-2">
<el-form-item label="客户名称" prop="customerName">
<el-input v-model="formData.customerName" placeholder="必填" />
</el-form-item>
<el-form-item label="客户联系人" prop="customerContact">
<el-input v-model="formData.customerContact" placeholder="必填" />
</el-form-item>
<el-form-item label="客户联系方式" prop="customerPhone" class="form-col-span-2">
<el-input v-model="formData.customerPhone" placeholder="必填" />
</el-form-item>
<el-form-item label="备注" class="form-col-span-2">
<el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="可选" />
</el-form-item>
</div>
</el-form>
<template #footer>
<el-button class="btn-ghost" @click="dialogVisible = false">
<el-icon><Close /></el-icon>
取消
</el-button>
<el-button class="btn-main" type="primary" :loading="submitLoading" @click="handleSubmit">
<el-icon><Check /></el-icon>
确定
</el-button>
</template>
</el-dialog>
<SystemViewDialog
v-model:visible="viewVisible"
:title="viewRow?.customerName || '合作客户详情'"
:icon="User"
:meta="viewRow?.createTime ? `创建时间:${viewRow.createTime}` : ''"
:sections="viewSections"
width="720px"
:grid-columns="2"
/>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
Check,
Close,
Delete,
Edit,
More,
Plus,
RefreshLeft,
Search,
User,
View
} from '@element-plus/icons-vue'
import {
fetchCreatePartnerCustomer,
fetchDeletePartnerCustomer,
fetchPartnerCustomerList,
fetchUpdatePartnerCustomer
} from '@/api/admin'
import SystemViewDialog from '@/components/business/system-view-dialog/index.vue'
import { formatDisplayOrDash } from '@/utils/datetime-display'
import { withFullscreenLoading, fullscreenLoadingText } from '@/utils/fullscreen-loading'
defineOptions({ name: 'PartnerCustomerTab' })
type PartnerRow = Api.PartnerCustomer.Item
const searchForm = reactive({ keyword: '' })
const tableData = ref<PartnerRow[]>([])
const selectedRows = ref<PartnerRow[]>([])
const loading = ref(false)
const pagination = reactive({ page: 1, pageSize: 10, total: 0 })
const dialogVisible = ref(false)
const dialogTitle = ref('新增合作客户')
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref()
const editingId = ref<string | null>(null)
const formData = reactive({
customerName: '',
customerContact: '',
customerPhone: '',
remark: ''
})
const formRules = {
customerName: [{ required: true, message: '请填写客户名称', trigger: 'blur' }],
customerContact: [{ required: true, message: '请填写客户联系人', trigger: 'blur' }],
customerPhone: [{ required: true, message: '请填写客户联系方式', trigger: 'blur' }]
}
const viewVisible = ref(false)
const viewRow = ref<PartnerRow | null>(null)
const viewSections = computed(() => {
const row = viewRow.value
if (!row) return []
return [
{
title: '基本信息',
fields: [
{ label: '客户名称', value: row.customerName },
{ label: '客户联系人', value: row.customerContact },
{ label: '客户联系方式', value: row.customerPhone },
{ label: '创建时间', value: row.createTime },
{ label: '备注', value: row.remark, span: true }
]
}
]
})
async function loadData() {
loading.value = true
try {
const res: any = await fetchPartnerCustomerList({
page: pagination.page,
pageSize: pagination.pageSize,
keyword: searchForm.keyword || undefined
})
const data = res?.data ?? res
tableData.value = data?.list ?? []
pagination.total = data?.total ?? 0
} catch (e) {
console.error(e)
tableData.value = []
pagination.total = 0
} finally {
loading.value = false
}
}
function handleSearch() {
pagination.page = 1
loadData()
}
function handleReset() {
searchForm.keyword = ''
pagination.page = 1
loadData()
}
function handleSelectionChange(rows: PartnerRow[]) {
selectedRows.value = rows
}
function resetForm() {
formData.customerName = ''
formData.customerContact = ''
formData.customerPhone = ''
formData.remark = ''
editingId.value = null
}
function handleAdd() {
isEdit.value = false
dialogTitle.value = '新增合作客户'
resetForm()
dialogVisible.value = true
}
function handleEdit(row: PartnerRow) {
isEdit.value = true
dialogTitle.value = '编辑合作客户'
editingId.value = row.id
formData.customerName = row.customerName || ''
formData.customerContact = row.customerContact || ''
formData.customerPhone = row.customerPhone || ''
formData.remark = row.remark || ''
dialogVisible.value = true
}
function handleView(row: PartnerRow) {
viewRow.value = row
viewVisible.value = true
}
function handleDropdownCommand(cmd: string, row: PartnerRow) {
if (cmd === 'edit') handleEdit(row)
if (cmd === 'delete') handleDelete(row)
}
async function handleSubmit() {
await formRef.value?.validate()
submitLoading.value = true
try {
const payload = {
customerName: formData.customerName.trim(),
customerContact: formData.customerContact.trim(),
customerPhone: formData.customerPhone.trim(),
remark: formData.remark.trim() || undefined
}
if (isEdit.value && editingId.value) {
await fetchUpdatePartnerCustomer(editingId.value, payload)
ElMessage.success('更新成功')
} else {
await fetchCreatePartnerCustomer(payload)
ElMessage.success('创建成功')
}
dialogVisible.value = false
loadData()
} catch (e: any) {
if (e !== false && e?.message) {
// request util already toasts most errors
}
} finally {
submitLoading.value = false
}
}
async function handleDelete(row: PartnerRow) {
try {
await ElMessageBox.confirm(`确定删除合作客户「${row.customerName}」吗?`, '提示', {
type: 'warning'
})
await withFullscreenLoading(() => fetchDeletePartnerCustomer(row.id), {
text: fullscreenLoadingText.delete
})
ElMessage.success('已删除')
loadData()
} catch (e) {
if (e !== 'cancel') console.error(e)
}
}
async function handleBatchDelete() {
if (!selectedRows.value.length) return
try {
await ElMessageBox.confirm(
`确定删除选中的 ${selectedRows.value.length} 个合作客户吗?`,
'提示',
{ type: 'warning' }
)
await withFullscreenLoading(
async () => {
for (const row of selectedRows.value) {
await fetchDeletePartnerCustomer(row.id)
}
},
{ text: fullscreenLoadingText.delete }
)
ElMessage.success('已删除')
selectedRows.value = []
loadData()
} catch (e) {
if (e !== 'cancel') console.error(e)
}
}
onMounted(() => {
loadData()
})
</script>
@@ -0,0 +1,847 @@
<!-- 存储客户基础信息 -->
<!-- eslint-disable vue/no-v-model-argument -->
<template>
<div class="storage-customer-tab">
<div class="filter-block">
<el-form :model="searchForm" class="filter-form" @submit.prevent>
<div class="filter-grid">
<el-form-item label="关键词">
<el-input
v-model="searchForm.keyword"
placeholder="姓名/电话/身份证/标签"
clearable
/>
</el-form-item>
<el-form-item label="创建时间">
<el-date-picker
v-model="createTimeRange"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
value-format="YYYY-MM-DD"
style="width: 100%"
/>
</el-form-item>
</div>
<div class="filter-actions-row">
<div class="filter-actions-end">
<el-button class="btn-ghost" @click="handleReset"
><el-icon><RefreshLeft /></el-icon>重置</el-button
>
<el-button class="btn-main" type="primary" @click="handleSearch"
><el-icon><Search /></el-icon>搜索</el-button
>
</div>
</div>
</el-form>
</div>
<div class="list-toolbar">
<div class="list-toolbar-row">
<div class="list-toolbar-selected">
已选 <span class="sel-num">{{ selectedRows.length }}</span> 项
</div>
<el-button class="btn-main" type="primary" @click="handleAdd">
<el-icon><Plus /></el-icon>
新增客户
</el-button>
<el-button
class="btn-ghost"
type="danger"
:disabled="selectedRows.length === 0"
@click="handleBatchDelete"
>
<el-icon><Delete /></el-icon>
批量删除
</el-button>
</div>
</div>
<div class="list-body list-wrap">
<el-table
class="list-table"
:data="tableData"
v-loading="loading"
stripe
row-key="id"
@selection-change="handleSelectionChange"
@row-dblclick="handleView"
>
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column
type="index"
label="序号"
min-width="68"
align="center"
header-align="center"
:index="(index) => (pagination.page - 1) * pagination.pageSize + index + 1"
/>
<el-table-column
prop="customerName"
label="客户姓名"
min-width="120"
align="center"
header-align="center"
/>
<el-table-column
prop="sex"
label="性别"
min-width="72"
align="center"
header-align="center"
>
<template #default="{ row }">{{ sexLabel(row.sex) }}</template>
</el-table-column>
<el-table-column
prop="idCardNo"
label="身份证号"
min-width="160"
align="center"
header-align="center"
/>
<el-table-column
prop="age"
label="年龄"
min-width="72"
align="center"
header-align="center"
/>
<el-table-column
prop="phoneNo"
label="联系电话"
min-width="140"
align="center"
header-align="center"
/>
<el-table-column
prop="birthYm"
label="出生年月"
min-width="110"
align="center"
header-align="center"
>
<template #default="{ row }">{{ formatBirthYm(row.birthYm) }}</template>
</el-table-column>
<el-table-column
prop="ethnic"
label="民族"
min-width="90"
align="center"
header-align="center"
show-overflow-tooltip
>
<template #default="{ row }">{{ row.ethnic || '—' }}</template>
</el-table-column>
<el-table-column
prop="email"
label="邮箱"
min-width="160"
align="center"
header-align="center"
show-overflow-tooltip
>
<template #default="{ row }">{{ row.email || '—' }}</template>
</el-table-column>
<el-table-column
prop="address"
label="家庭住址"
min-width="180"
align="center"
header-align="center"
show-overflow-tooltip
>
<template #default="{ row }">{{ row.address || '—' }}</template>
</el-table-column>
<el-table-column
prop="customerTags"
label="客户标签"
min-width="140"
show-overflow-tooltip
>
<template #default="{ row }">{{ row.customerTags || '—' }}</template>
</el-table-column>
<el-table-column
prop="remark"
label="备注"
min-width="140"
show-overflow-tooltip
>
<template #default="{ row }">{{ row.remark || '—' }}</template>
</el-table-column>
<el-table-column
prop="createTime"
label="创建时间"
min-width="180"
align="center"
header-align="center">
<template #default="{ row }">{{ formatDisplayOrDash(row.createTime) }}</template>
</el-table-column>
<el-table-column
label="操作"
min-width="120"
fixed="right"
align="center"
header-align="center"
>
<template #default="{ row }">
<div style="display: flex; justify-content: center; gap: 8px">
<el-button class="btn-op-item" @click="handleView(row)">
<el-icon><View /></el-icon>查看
</el-button>
<el-dropdown trigger="hover" @command="(cmd: string) => handleDropdownCommand(cmd, row)">
<el-button class="btn-op-item">
<el-icon><More /></el-icon>
</el-button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item command="edit">
<el-icon><Edit /></el-icon>编辑
</el-dropdown-item>
<el-dropdown-item command="delete" divided>
<el-icon><Delete /></el-icon>删除
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</div>
</template>
</el-table-column>
</el-table>
<div class="pagination list-pager-bar">
<el-pagination
:current-page="pagination.page"
:page-size="pagination.pageSize"
:total="pagination.total"
:page-sizes="[10, 20, 50]"
layout="total, sizes, prev, pager, next"
@size-change="(val) => ((pagination.page = 1), (pagination.pageSize = val), loadData())"
@current-change="(val) => ((pagination.page = val), loadData())"
/>
</div>
</div>
<el-dialog
v-model="dialogVisible"
:title="dialogTitle"
width="720px"
class="dialog-form-layout"
align-center
append-to-body
modal-class="protocol-dialog-mask"
destroy-on-close
:close-on-click-modal="false"
>
<el-form
ref="formRef"
:model="formData"
:rules="formRules"
label-position="top"
class="biz-dialog-form"
scroll-to-error
:scroll-into-view-options="{ behavior: 'smooth', block: 'center' }"
>
<div class="form-grid-2">
<el-form-item label="客户姓名" prop="customerName">
<el-input v-model="formData.customerName" placeholder="必填" />
</el-form-item>
<el-form-item label="性别" prop="sex">
<el-select v-model="formData.sex" placeholder="选择" style="width: 100%">
<el-option label="男" value="0" />
<el-option label="女" value="1" />
<el-option label="未知" value="2" />
</el-select>
</el-form-item>
<el-form-item label="身份证号" prop="idCardNo">
<el-input
v-model="formData.idCardNo"
placeholder="可选;填写后租户内不可重复"
clearable
/>
</el-form-item>
<el-form-item label="年龄">
<el-input
type="number"
step="any"
v-model="formData.age"
:min="0"
:max="150"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="联系电话">
<el-input v-model="formData.phoneNo" placeholder="可选" clearable />
</el-form-item>
<el-form-item label="出生年月">
<el-date-picker
v-model="formData.birthYm"
type="month"
value-format="YYYYMM"
format="YYYY-MM"
placeholder="选择月份"
clearable
style="width: 100%"
/>
</el-form-item>
<el-form-item label="民族">
<el-select
v-model="formData.ethnic"
class="w-full"
filterable
clearable
:loading="ethnicLoading"
placeholder="请选择或检索民族"
style="width: 100%"
>
<el-option
v-for="e in ethnicOptions"
:key="e.ethnicCode || e.ethnicName"
:label="e.ethnicName"
:value="e.ethnicName"
/>
</el-select>
</el-form-item>
<el-form-item label="邮箱">
<el-input v-model="formData.email" placeholder="可选" clearable />
</el-form-item>
<el-form-item label="家庭住址" class="form-col-span-2">
<el-input v-model="formData.address" placeholder="可选" />
</el-form-item>
<el-form-item label="客户标签" class="form-col-span-2">
<el-input v-model="formData.customerTags" placeholder="多个标签用英文逗号分隔" />
</el-form-item>
<el-form-item label="备注" class="form-col-span-2">
<el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="可选" />
</el-form-item>
</div>
</el-form>
<template #footer>
<el-button class="btn-ghost" @click="dialogVisible = false">
<el-icon><Close /></el-icon>
取消
</el-button>
<el-button class="btn-main" type="primary" @click="handleSubmit" :loading="submitLoading">
<el-icon><Check /></el-icon>
确定
</el-button>
</template>
</el-dialog>
<SystemViewDialog
v-model:visible="viewVisible"
:title="viewRow?.customerName || '客户详情'"
:icon="User"
:meta="`身份证:${viewRow?.idCardNo || '—'}${viewRow?.createTime ? ' · ' + viewRow.createTime : ''}`"
:sections="viewSections"
:loading="relationsLoading"
width="1100px"
:grid-columns="5"
>
<template #related-customers>
<div class="customer-relations">
<p v-if="!(relations?.relatedGroups || []).length" class="view-empty-hint">暂无关联客户</p>
<div
v-for="group in relations?.relatedGroups || []"
:key="`${group.bizType}-${group.protocolId}`"
class="rel-group"
>
<div class="rel-group-head">
<el-tag size="small" :type="group.bizType === 'cell_storage' ? 'primary' : 'success'">
{{ bizTypeLabel(group.bizType) }}
</el-tag>
<button type="button" class="rel-link" @click="openProtocol(group)">
{{ group.protocolNo || '—' }}
</button>
<span class="rel-muted">本客户角色:{{ roleLabel(group.myRole) }}</span>
</div>
<div class="view-subtable-wrap">
<el-table :data="group.members" stripe class="list-table view-subtable">
<el-table-column label="角色" min-width="90" align="center" header-align="center">
<template #default="{ row }">
{{ roleLabel(row.role) }}
<el-tag v-if="row.customerId && row.customerId === viewRow?.id" size="small" type="info">
本人
</el-tag>
</template>
</el-table-column>
<el-table-column label="姓名" min-width="110" align="center" header-align="center">
<template #default="{ row }">
<button
v-if="row.customerId && row.customerId !== viewRow?.id"
type="button"
class="rel-link"
@click="openRelatedCustomer(row)"
>
{{ row.name || '—' }}
</button>
<span v-else>{{ row.name || '—' }}</span>
</template>
</el-table-column>
<el-table-column prop="phone" label="电话" min-width="120" align="center" header-align="center">
<template #default="{ row }">{{ row.phone || '—' }}</template>
</el-table-column>
<el-table-column prop="idCardNo" label="身份证" min-width="160" align="center" header-align="center">
<template #default="{ row }">{{ row.idCardNo || '—' }}</template>
</el-table-column>
</el-table>
</div>
</div>
</div>
</template>
<template #related-protocols>
<div class="customer-relations">
<p v-if="!(relations?.protocols || []).length" class="view-empty-hint">暂无关联协议</p>
<div v-else class="view-subtable-wrap">
<el-table :data="relations?.protocols || []" stripe class="list-table view-subtable">
<el-table-column label="协议号" min-width="140" align="center" header-align="center">
<template #default="{ row }">
<button type="button" class="rel-link" @click="openProtocol(row)">
{{ row.protocolNo || '—' }}
</button>
</template>
</el-table-column>
<el-table-column label="类型" min-width="110" align="center" header-align="center">
<template #default="{ row }">
<el-tag size="small" :type="row.bizType === 'cell_storage' ? 'primary' : 'success'">
{{ bizTypeLabel(row.bizType) }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="状态" min-width="100" align="center" header-align="center">
<template #default="{ row }">
<el-tag size="small" :type="protocolTagType(row)">
{{ protocolLabel(row) }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="日期" min-width="110" align="center" header-align="center">
<template #default="{ row }">{{ formatRegisterDate(row.registerDate) }}</template>
</el-table-column>
<el-table-column label="本客户角色" min-width="100" align="center" header-align="center">
<template #default="{ row }">{{ roleLabel(row.myRole) }}</template>
</el-table-column>
</el-table>
</div>
</div>
</template>
</SystemViewDialog>
<ProtocolViewDialog
v-model="protocolViewVisible"
:protocol-id="viewProtocolId"
show-audit-history
/>
<DonationViewDialog
v-model="donationViewVisible"
:donation-id="viewDonationId"
show-audit-history
/>
</div>
</template>
<script setup lang="ts">
import { formatDisplayOrDash } from '@/utils/datetime-display'
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Close, Check, View, User, RefreshLeft, Search, More, Edit, Delete } from '@element-plus/icons-vue'
import { withFullscreenLoading, fullscreenLoadingText } from '@/utils/fullscreen-loading'
import {
fetchCustomerList,
fetchCreateCustomer,
fetchUpdateCustomer,
fetchDeleteCustomer,
fetchCustomerRelations
} from '@/api/admin'
import { fetchEthnicList, type EthnicOption } from '@/api/ethnic'
import SystemViewDialog from '@/components/business/system-view-dialog/index.vue'
import ProtocolViewDialog from '@/views/cell-storage/protocol/ProtocolViewDialog.vue'
import DonationViewDialog from '@/views/research-donation/list/DonationViewDialog.vue'
import {
sexLabel,
protocolStatusDisplayLabel,
protocolStatusTagType,
donationStatusDisplayLabel,
donationStatusTagType
} from '@/utils/status-tag-registry'
defineOptions({ name: 'StorageCustomerTab' })
const searchForm = reactive<{ keyword: string }>({ keyword: '' })
const createTimeRange = ref<[string, string] | null>(null)
const tableData = ref<Api.BizCustomer.CustomerItem[]>([])
const selectedRows = ref<Api.BizCustomer.CustomerItem[]>([])
const loading = ref(false)
const pagination = reactive({ page: 1, pageSize: 10, total: 0 })
const dialogVisible = ref(false)
const dialogTitle = ref('新增客户')
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref()
const editingId = ref<string | null>(null)
// ---- 查看弹窗 ----
const viewVisible = ref(false)
const viewRow = ref<Api.BizCustomer.CustomerItem | null>(null)
const relationsLoading = ref(false)
const relations = ref<Api.BizCustomer.CustomerRelations | null>(null)
const protocolViewVisible = ref(false)
const viewProtocolId = ref<string | null>(null)
const donationViewVisible = ref(false)
const viewDonationId = ref<string | null>(null)
function formatBirthYm(ym: string | undefined | null) {
const s = String(ym || '').trim()
if (/^\d{6}$/.test(s)) return `${s.slice(0, 4)}-${s.slice(4, 6)}`
return s || '—'
}
const viewSections = computed(() => {
const row = viewRow.value
if (!row) return []
return [
{
title: '基本信息',
fields: [
{ label: '客户姓名', value: row.customerName },
{ label: '性别', value: sexLabel(row.sex) },
{ label: '身份证号', value: row.idCardNo },
{ label: '年龄', value: row.age },
{ label: '联系电话', value: row.phoneNo },
{ label: '出生年月', value: formatBirthYm(row.birthYm) },
{ label: '民族', value: row.ethnic },
{ label: '邮箱', value: row.email },
{ label: '家庭住址', value: row.address },
{ label: '客户标签', value: row.customerTags },
{ label: '创建时间', value: row.createTime },
{ label: '备注', value: row.remark }
]
},
{
title: '关联客户',
fields: [],
slot: 'related-customers'
},
{
title: '关联协议',
fields: [],
slot: 'related-protocols'
}
]
})
function roleLabel(role: string) {
if (role === 'mother') return '母亲'
if (role === 'father') return '父亲'
if (role === 'newborn') return '子女'
return role || '—'
}
function bizTypeLabel(bizType: string) {
return bizType === 'research_donation' ? '科研捐赠' : '细胞存储'
}
function protocolLabel(row: Api.BizCustomer.ProtocolSummary) {
return row.bizType === 'research_donation'
? donationStatusDisplayLabel(row.protocolStatus)
: protocolStatusDisplayLabel(row.protocolStatus)
}
function protocolTagType(row: Api.BizCustomer.ProtocolSummary) {
return row.bizType === 'research_donation'
? donationStatusTagType(row.protocolStatus)
: protocolStatusTagType(row.protocolStatus)
}
function formatRegisterDate(val: string) {
const s = (val || '').trim()
if (/^\d{8}$/.test(s)) return `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}`
return formatDisplayOrDash(s)
}
async function handleView(row: Api.BizCustomer.CustomerItem) {
viewRow.value = row
viewVisible.value = true
relationsLoading.value = true
relations.value = null
try {
const data = await fetchCustomerRelations(row.id)
relations.value = data
if (data?.customer) viewRow.value = data.customer
} catch {
/* 全局处理 */
} finally {
relationsLoading.value = false
}
}
function openRelatedCustomer(member: Api.BizCustomer.RelationMember) {
if (!member.customerId) return
void handleView({
id: member.customerId,
customerName: member.name || '',
sex: '2',
idCardNo: member.idCardNo || '',
age: null,
phoneNo: member.phone || '',
customerTags: '',
tenantNo: '',
orderNum: 0,
remark: '',
createTime: '',
updateTime: ''
})
}
function openProtocol(
row: Pick<Api.BizCustomer.ProtocolSummary, 'bizType' | 'protocolId'>
) {
if (!row.protocolId) return
if (row.bizType === 'research_donation') {
viewDonationId.value = row.protocolId
donationViewVisible.value = true
return
}
viewProtocolId.value = row.protocolId
protocolViewVisible.value = true
}
const formData = reactive({
customerName: '',
sex: '0',
idCardNo: '',
age: null as number | null,
birthYm: '',
ethnic: '',
email: '',
address: '',
phoneNo: '',
customerTags: '',
orderNum: 0,
remark: ''
})
const ethnicOptions = ref<EthnicOption[]>([])
const ethnicLoading = ref(false)
async function loadEthnicOptions() {
if (ethnicOptions.value.length) return
ethnicLoading.value = true
try {
const res = await fetchEthnicList({ limit: 200 })
ethnicOptions.value = res.list || []
} finally {
ethnicLoading.value = false
}
}
function ensureEthnicOptionInList(name: string) {
const n = (name || '').trim()
if (!n) return
if (ethnicOptions.value.some((e) => e.ethnicName === n)) return
ethnicOptions.value = [
{ id: '', ethnicName: n, ethnicCode: '', orderNum: null },
...ethnicOptions.value
]
}
const formRules = {
customerName: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }]
}
const handleSelectionChange = (rows: Api.BizCustomer.CustomerItem[]) => {
selectedRows.value = rows
}
async function loadData() {
loading.value = true
try {
const res = await fetchCustomerList({
page: pagination.page,
pageSize: pagination.pageSize,
keyword: searchForm.keyword || undefined,
createTimeStart: createTimeRange.value?.[0] || undefined,
createTimeEnd: createTimeRange.value?.[1] || undefined
})
tableData.value = res.list || []
pagination.total = res.total ?? 0
} finally {
loading.value = false
}
}
function handleSearch() {
pagination.page = 1
loadData()
}
function handleReset() {
searchForm.keyword = ''
createTimeRange.value = null
pagination.page = 1
loadData()
}
function resetForm() {
formData.customerName = ''
formData.sex = '0'
formData.idCardNo = ''
formData.age = null
formData.birthYm = ''
formData.ethnic = ''
formData.email = ''
formData.address = ''
formData.phoneNo = ''
formData.customerTags = ''
formData.orderNum = 0
formData.remark = ''
editingId.value = null
}
function handleAdd() {
isEdit.value = false
dialogTitle.value = '新增客户'
resetForm()
void loadEthnicOptions()
dialogVisible.value = true
formRef.value?.clearValidate?.()
}
function handleEdit(row: Api.BizCustomer.CustomerItem) {
isEdit.value = true
dialogTitle.value = '编辑客户'
editingId.value = row.id
formData.customerName = row.customerName || ''
formData.sex = row.sex || '2'
formData.idCardNo = row.idCardNo || ''
formData.age = row.age ?? null
formData.birthYm = row.birthYm || ''
formData.ethnic = row.ethnic || ''
formData.email = row.email || ''
formData.address = row.address || ''
formData.phoneNo = row.phoneNo || ''
formData.customerTags = row.customerTags || ''
formData.orderNum = row.orderNum ?? 0
formData.remark = row.remark || ''
void loadEthnicOptions().then(() => ensureEthnicOptionInList(formData.ethnic))
dialogVisible.value = true
formRef.value?.clearValidate?.()
}
async function handleSubmit() {
await formRef.value?.validate?.()
submitLoading.value = true
try {
const payload = {
customerName: formData.customerName.trim(),
sex: formData.sex,
idCardNo: formData.idCardNo?.trim() || undefined,
age: formData.age,
birthYm: formData.birthYm?.trim() || undefined,
ethnic: formData.ethnic?.trim() || undefined,
email: formData.email?.trim() || undefined,
address: formData.address?.trim() || undefined,
phoneNo: formData.phoneNo?.trim() || undefined,
customerTags: formData.customerTags?.trim() || undefined,
orderNum: formData.orderNum,
remark: formData.remark?.trim() || undefined
}
if (isEdit.value && editingId.value) {
await fetchUpdateCustomer(editingId.value, payload)
} else {
await fetchCreateCustomer(payload)
}
ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
dialogVisible.value = false
await loadData()
} catch {
/* 全局处理 */
} finally {
submitLoading.value = false
}
}
function handleDropdownCommand(command: string, row: any) {
switch (command) {
case 'edit': handleEdit(row); break
case 'delete': handleDelete(row); break
}
}
async function handleDelete(row: Api.BizCustomer.CustomerItem) {
await ElMessageBox.confirm('确定要删除该客户吗?', '提示', { type: 'warning' })
await fetchDeleteCustomer(row.id)
ElMessage.success('删除成功')
await loadData()
}
async function handleBatchDelete() {
const ids = selectedRows.value.map((r) => r.id)
if (!ids.length) return
await ElMessageBox.confirm(`确定删除选中的 ${ids.length} 条客户吗?`, '提示', {
type: 'warning'
})
await withFullscreenLoading(async () => {
for (const id of ids) {
await fetchDeleteCustomer(id)
}
ElMessage.success('批量删除成功')
selectedRows.value = []
await loadData()
}, fullscreenLoadingText.batchDelete)
}
// 输入检索条件时自动搜索(防抖 300ms)
watchDebounced(
[searchForm, createTimeRange],
() => {
pagination.page = 1
loadData()
},
{ debounce: 300, deep: true }
)
onMounted(() => {
loadData()
})
</script>
<style scoped lang="scss">
.biz-dialog-form {
:deep(.el-form-item) {
margin-bottom: 0;
}
}
.customer-relations {
.rel-group {
margin-bottom: 14px;
&:last-child {
margin-bottom: 0;
}
}
.rel-group-head {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.rel-muted {
color: var(--mint-text-muted, #64748b);
font-size: 13px;
}
.rel-link {
padding: 0;
border: 0;
background: transparent;
color: var(--primary, #10b981);
cursor: pointer;
font: inherit;
text-decoration: underline;
text-underline-offset: 2px;
}
}
</style>
+31 -828
View File
@@ -1,849 +1,52 @@
<!-- 客户基础信息 -->
<!-- eslint-disable vue/no-v-model-argument -->
<!-- 客户基础信息:存储客户 / 合作客户 -->
<template>
<div class="page-container">
<section class="panel">
<div class="filter-block">
<el-form :model="searchForm" class="filter-form" @submit.prevent>
<div class="filter-grid">
<el-form-item label="关键词">
<el-input
v-model="searchForm.keyword"
placeholder="姓名/电话/身份证/标签"
clearable
/>
</el-form-item>
<el-form-item label="创建时间">
<el-date-picker
v-model="createTimeRange"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
value-format="YYYY-MM-DD"
style="width: 100%"
/>
</el-form-item>
</div>
<div class="filter-actions-row">
<div class="filter-actions-end">
<el-button class="btn-ghost" @click="handleReset"
><el-icon><RefreshLeft /></el-icon>重置</el-button
>
<el-button class="btn-main" type="primary" @click="handleSearch"
><el-icon><Search /></el-icon>搜索</el-button
>
</div>
</div>
</el-form>
</div>
<div class="list-toolbar">
<div class="list-toolbar-row">
<div class="list-toolbar-selected">
已选 <span class="sel-num">{{ selectedRows.length }}</span> 项
</div>
<el-button class="btn-main" type="primary" @click="handleAdd">
<el-icon><Plus /></el-icon>
新增客户
</el-button>
<el-button
class="btn-ghost"
type="danger"
:disabled="selectedRows.length === 0"
@click="handleBatchDelete"
<div class="panel-pill-tabs panel-pill-tabs--lg">
<div class="panel-pill-tabs__track" role="tablist" aria-label="客户类型">
<button
v-for="item in tabCards"
:key="item.key"
type="button"
role="tab"
class="panel-pill-tabs__btn"
:class="{ 'is-active': activeTab === item.key }"
:aria-selected="activeTab === item.key"
@click="activeTab = item.key"
>
<el-icon><Delete /></el-icon>
批量删除
</el-button>
{{ item.title }}
</button>
</div>
</div>
<div class="list-body list-wrap">
<el-table
class="list-table"
:data="tableData"
v-loading="loading"
stripe
row-key="id"
@selection-change="handleSelectionChange"
@row-dblclick="handleView"
>
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column
type="index"
label="序号"
min-width="68"
align="center"
header-align="center"
:index="(index) => (pagination.page - 1) * pagination.pageSize + index + 1"
/>
<el-table-column
prop="customerName"
label="客户姓名"
min-width="120"
align="center"
header-align="center"
/>
<el-table-column
prop="sex"
label="性别"
min-width="72"
align="center"
header-align="center"
>
<template #default="{ row }">{{ sexLabel(row.sex) }}</template>
</el-table-column>
<el-table-column
prop="idCardNo"
label="身份证号"
min-width="160"
align="center"
header-align="center"
/>
<el-table-column
prop="age"
label="年龄"
min-width="72"
align="center"
header-align="center"
/>
<el-table-column
prop="phoneNo"
label="联系电话"
min-width="140"
align="center"
header-align="center"
/>
<el-table-column
prop="birthYm"
label="出生年月"
min-width="110"
align="center"
header-align="center"
>
<template #default="{ row }">{{ formatBirthYm(row.birthYm) }}</template>
</el-table-column>
<el-table-column
prop="ethnic"
label="民族"
min-width="90"
align="center"
header-align="center"
show-overflow-tooltip
>
<template #default="{ row }">{{ row.ethnic || '—' }}</template>
</el-table-column>
<el-table-column
prop="email"
label="邮箱"
min-width="160"
align="center"
header-align="center"
show-overflow-tooltip
>
<template #default="{ row }">{{ row.email || '—' }}</template>
</el-table-column>
<el-table-column
prop="address"
label="家庭住址"
min-width="180"
align="center"
header-align="center"
show-overflow-tooltip
>
<template #default="{ row }">{{ row.address || '—' }}</template>
</el-table-column>
<el-table-column
prop="customerTags"
label="客户标签"
min-width="140"
show-overflow-tooltip
>
<template #default="{ row }">{{ row.customerTags || '—' }}</template>
</el-table-column>
<el-table-column
prop="remark"
label="备注"
min-width="140"
show-overflow-tooltip
>
<template #default="{ row }">{{ row.remark || '—' }}</template>
</el-table-column>
<el-table-column
prop="createTime"
label="创建时间"
min-width="180"
align="center"
header-align="center">
<template #default="{ row }">{{ formatDisplayOrDash(row.createTime) }}</template>
</el-table-column>
<el-table-column
label="操作"
min-width="120"
fixed="right"
align="center"
header-align="center"
>
<template #default="{ row }">
<div style="display: flex; justify-content: center; gap: 8px">
<el-button class="btn-op-item" @click="handleView(row)">
<el-icon><View /></el-icon>查看
</el-button>
<el-dropdown trigger="hover" @command="(cmd: string) => handleDropdownCommand(cmd, row)">
<el-button class="btn-op-item">
<el-icon><More /></el-icon>
</el-button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item command="edit">
<el-icon><Edit /></el-icon>编辑
</el-dropdown-item>
<el-dropdown-item command="delete" divided>
<el-icon><Delete /></el-icon>删除
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</div>
</template>
</el-table-column>
</el-table>
<div class="pagination list-pager-bar">
<el-pagination
:current-page="pagination.page"
:page-size="pagination.pageSize"
:total="pagination.total"
:page-sizes="[10, 20, 50]"
layout="total, sizes, prev, pager, next"
@size-change="(val) => ((pagination.page = 1), (pagination.pageSize = val), loadData())"
@current-change="(val) => ((pagination.page = val), loadData())"
/>
</div>
</div>
<el-dialog
v-model="dialogVisible"
:title="dialogTitle"
width="720px"
class="dialog-form-layout"
align-center
append-to-body
modal-class="protocol-dialog-mask"
destroy-on-close
:close-on-click-modal="false"
>
<el-form
ref="formRef"
:model="formData"
:rules="formRules"
label-position="top"
class="biz-dialog-form"
scroll-to-error
:scroll-into-view-options="{ behavior: 'smooth', block: 'center' }"
>
<div class="form-grid-2">
<el-form-item label="客户姓名" prop="customerName">
<el-input v-model="formData.customerName" placeholder="必填" />
</el-form-item>
<el-form-item label="性别" prop="sex">
<el-select v-model="formData.sex" placeholder="选择" style="width: 100%">
<el-option label="男" value="0" />
<el-option label="女" value="1" />
<el-option label="未知" value="2" />
</el-select>
</el-form-item>
<el-form-item label="身份证号" prop="idCardNo">
<el-input
v-model="formData.idCardNo"
placeholder="可选;填写后租户内不可重复"
clearable
/>
</el-form-item>
<el-form-item label="年龄">
<el-input
type="number"
step="any"
v-model="formData.age"
:min="0"
:max="150"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="联系电话">
<el-input v-model="formData.phoneNo" placeholder="可选" clearable />
</el-form-item>
<el-form-item label="出生年月">
<el-date-picker
v-model="formData.birthYm"
type="month"
value-format="YYYYMM"
format="YYYY-MM"
placeholder="选择月份"
clearable
style="width: 100%"
/>
</el-form-item>
<el-form-item label="民族">
<el-select
v-model="formData.ethnic"
class="w-full"
filterable
clearable
:loading="ethnicLoading"
placeholder="请选择或检索民族"
style="width: 100%"
>
<el-option
v-for="e in ethnicOptions"
:key="e.ethnicCode || e.ethnicName"
:label="e.ethnicName"
:value="e.ethnicName"
/>
</el-select>
</el-form-item>
<el-form-item label="邮箱">
<el-input v-model="formData.email" placeholder="可选" clearable />
</el-form-item>
<el-form-item label="家庭住址" class="form-col-span-2">
<el-input v-model="formData.address" placeholder="可选" />
</el-form-item>
<el-form-item label="客户标签" class="form-col-span-2">
<el-input v-model="formData.customerTags" placeholder="多个标签用英文逗号分隔" />
</el-form-item>
<el-form-item label="备注" class="form-col-span-2">
<el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="可选" />
</el-form-item>
</div>
</el-form>
<template #footer>
<el-button class="btn-ghost" @click="dialogVisible = false">
<el-icon><Close /></el-icon>
取消
</el-button>
<el-button class="btn-main" type="primary" @click="handleSubmit" :loading="submitLoading">
<el-icon><Check /></el-icon>
确定
</el-button>
</template>
</el-dialog>
<SystemViewDialog
v-model:visible="viewVisible"
:title="viewRow?.customerName || '客户详情'"
:icon="User"
:meta="`身份证:${viewRow?.idCardNo || '—'}${viewRow?.createTime ? ' · ' + viewRow.createTime : ''}`"
:sections="viewSections"
:loading="relationsLoading"
width="1100px"
:grid-columns="5"
>
<template #related-customers>
<div class="customer-relations">
<p v-if="!(relations?.relatedGroups || []).length" class="view-empty-hint">暂无关联客户</p>
<div
v-for="group in relations?.relatedGroups || []"
:key="`${group.bizType}-${group.protocolId}`"
class="rel-group"
>
<div class="rel-group-head">
<el-tag size="small" :type="group.bizType === 'cell_storage' ? 'primary' : 'success'">
{{ bizTypeLabel(group.bizType) }}
</el-tag>
<button type="button" class="rel-link" @click="openProtocol(group)">
{{ group.protocolNo || '—' }}
</button>
<span class="rel-muted">本客户角色:{{ roleLabel(group.myRole) }}</span>
</div>
<div class="view-subtable-wrap">
<el-table :data="group.members" stripe class="list-table view-subtable">
<el-table-column label="角色" min-width="90" align="center" header-align="center">
<template #default="{ row }">
{{ roleLabel(row.role) }}
<el-tag v-if="row.customerId && row.customerId === viewRow?.id" size="small" type="info">
本人
</el-tag>
</template>
</el-table-column>
<el-table-column label="姓名" min-width="110" align="center" header-align="center">
<template #default="{ row }">
<button
v-if="row.customerId && row.customerId !== viewRow?.id"
type="button"
class="rel-link"
@click="openRelatedCustomer(row)"
>
{{ row.name || '—' }}
</button>
<span v-else>{{ row.name || '—' }}</span>
</template>
</el-table-column>
<el-table-column prop="phone" label="电话" min-width="120" align="center" header-align="center">
<template #default="{ row }">{{ row.phone || '—' }}</template>
</el-table-column>
<el-table-column prop="idCardNo" label="身份证" min-width="160" align="center" header-align="center">
<template #default="{ row }">{{ row.idCardNo || '—' }}</template>
</el-table-column>
</el-table>
</div>
</div>
</div>
</template>
<template #related-protocols>
<div class="customer-relations">
<p v-if="!(relations?.protocols || []).length" class="view-empty-hint">暂无关联协议</p>
<div v-else class="view-subtable-wrap">
<el-table :data="relations?.protocols || []" stripe class="list-table view-subtable">
<el-table-column label="协议号" min-width="140" align="center" header-align="center">
<template #default="{ row }">
<button type="button" class="rel-link" @click="openProtocol(row)">
{{ row.protocolNo || '—' }}
</button>
</template>
</el-table-column>
<el-table-column label="类型" min-width="110" align="center" header-align="center">
<template #default="{ row }">
<el-tag size="small" :type="row.bizType === 'cell_storage' ? 'primary' : 'success'">
{{ bizTypeLabel(row.bizType) }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="状态" min-width="100" align="center" header-align="center">
<template #default="{ row }">
<el-tag size="small" :type="protocolTagType(row)">
{{ protocolLabel(row) }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="日期" min-width="110" align="center" header-align="center">
<template #default="{ row }">{{ formatRegisterDate(row.registerDate) }}</template>
</el-table-column>
<el-table-column label="本客户角色" min-width="100" align="center" header-align="center">
<template #default="{ row }">{{ roleLabel(row.myRole) }}</template>
</el-table-column>
</el-table>
</div>
</div>
</template>
</SystemViewDialog>
<ProtocolViewDialog
v-model="protocolViewVisible"
:protocol-id="viewProtocolId"
show-audit-history
/>
<DonationViewDialog
v-model="donationViewVisible"
:donation-id="viewDonationId"
show-audit-history
/>
<StorageCustomerTab v-if="activeTab === 'storage'" />
<PartnerCustomerTab v-else-if="activeTab === 'partner'" />
</section>
</div>
</template>
<script setup lang="ts">
import { formatDisplayOrDash } from '@/utils/datetime-display'
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Close, Check, View, User, RefreshLeft, Search, More, Edit, Delete } from '@element-plus/icons-vue'
import { withFullscreenLoading, fullscreenLoadingText } from '@/utils/fullscreen-loading'
import {
fetchCustomerList,
fetchCreateCustomer,
fetchUpdateCustomer,
fetchDeleteCustomer,
fetchCustomerRelations
} from '@/api/admin'
import { fetchEthnicList, type EthnicOption } from '@/api/ethnic'
import SystemViewDialog from '@/components/business/system-view-dialog/index.vue'
import ProtocolViewDialog from '@/views/cell-storage/protocol/ProtocolViewDialog.vue'
import DonationViewDialog from '@/views/research-donation/list/DonationViewDialog.vue'
import {
sexLabel,
protocolStatusDisplayLabel,
protocolStatusTagType,
donationStatusDisplayLabel,
donationStatusTagType
} from '@/utils/status-tag-registry'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import StorageCustomerTab from './StorageCustomerTab.vue'
import PartnerCustomerTab from './PartnerCustomerTab.vue'
defineOptions({ name: 'BizCustomer' })
const searchForm = reactive<{ keyword: string }>({ keyword: '' })
const createTimeRange = ref<[string, string] | null>(null)
const tableData = ref<Api.BizCustomer.CustomerItem[]>([])
const selectedRows = ref<Api.BizCustomer.CustomerItem[]>([])
const loading = ref(false)
const pagination = reactive({ page: 1, pageSize: 10, total: 0 })
const dialogVisible = ref(false)
const dialogTitle = ref('新增客户')
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref()
const editingId = ref<string | null>(null)
type TabKey = 'storage' | 'partner'
// ---- 查看弹窗 ----
const viewVisible = ref(false)
const viewRow = ref<Api.BizCustomer.CustomerItem | null>(null)
const relationsLoading = ref(false)
const relations = ref<Api.BizCustomer.CustomerRelations | null>(null)
const protocolViewVisible = ref(false)
const viewProtocolId = ref<string | null>(null)
const donationViewVisible = ref(false)
const viewDonationId = ref<string | null>(null)
const tabCards: Array<{ key: TabKey; title: string }> = [
{ key: 'storage', title: '存储客户基础信息' },
{ key: 'partner', title: '合作客户基础信息' }
]
function formatBirthYm(ym: string | undefined | null) {
const s = String(ym || '').trim()
if (/^\d{6}$/.test(s)) return `${s.slice(0, 4)}-${s.slice(4, 6)}`
return s || '—'
}
const viewSections = computed(() => {
const row = viewRow.value
if (!row) return []
return [
{
title: '基本信息',
fields: [
{ label: '客户姓名', value: row.customerName },
{ label: '性别', value: sexLabel(row.sex) },
{ label: '身份证号', value: row.idCardNo },
{ label: '年龄', value: row.age },
{ label: '联系电话', value: row.phoneNo },
{ label: '出生年月', value: formatBirthYm(row.birthYm) },
{ label: '民族', value: row.ethnic },
{ label: '邮箱', value: row.email },
{ label: '家庭住址', value: row.address },
{ label: '客户标签', value: row.customerTags },
{ label: '创建时间', value: row.createTime },
{ label: '备注', value: row.remark }
]
},
{
title: '关联客户',
fields: [],
slot: 'related-customers'
},
{
title: '关联协议',
fields: [],
slot: 'related-protocols'
}
]
})
function roleLabel(role: string) {
if (role === 'mother') return '母亲'
if (role === 'father') return '父亲'
if (role === 'newborn') return '子女'
return role || '—'
}
function bizTypeLabel(bizType: string) {
return bizType === 'research_donation' ? '科研捐赠' : '细胞存储'
}
function protocolLabel(row: Api.BizCustomer.ProtocolSummary) {
return row.bizType === 'research_donation'
? donationStatusDisplayLabel(row.protocolStatus)
: protocolStatusDisplayLabel(row.protocolStatus)
}
function protocolTagType(row: Api.BizCustomer.ProtocolSummary) {
return row.bizType === 'research_donation'
? donationStatusTagType(row.protocolStatus)
: protocolStatusTagType(row.protocolStatus)
}
function formatRegisterDate(val: string) {
const s = (val || '').trim()
if (/^\d{8}$/.test(s)) return `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}`
return formatDisplayOrDash(s)
}
async function handleView(row: Api.BizCustomer.CustomerItem) {
viewRow.value = row
viewVisible.value = true
relationsLoading.value = true
relations.value = null
try {
const data = await fetchCustomerRelations(row.id)
relations.value = data
if (data?.customer) viewRow.value = data.customer
} catch {
/* 全局处理 */
} finally {
relationsLoading.value = false
}
}
function openRelatedCustomer(member: Api.BizCustomer.RelationMember) {
if (!member.customerId) return
void handleView({
id: member.customerId,
customerName: member.name || '',
sex: '2',
idCardNo: member.idCardNo || '',
age: null,
phoneNo: member.phone || '',
customerTags: '',
tenantNo: '',
orderNum: 0,
remark: '',
createTime: '',
updateTime: ''
})
}
function openProtocol(
row: Pick<Api.BizCustomer.ProtocolSummary, 'bizType' | 'protocolId'>
) {
if (!row.protocolId) return
if (row.bizType === 'research_donation') {
viewDonationId.value = row.protocolId
donationViewVisible.value = true
return
}
viewProtocolId.value = row.protocolId
protocolViewVisible.value = true
}
const formData = reactive({
customerName: '',
sex: '0',
idCardNo: '',
age: null as number | null,
birthYm: '',
ethnic: '',
email: '',
address: '',
phoneNo: '',
customerTags: '',
orderNum: 0,
remark: ''
})
const ethnicOptions = ref<EthnicOption[]>([])
const ethnicLoading = ref(false)
async function loadEthnicOptions() {
if (ethnicOptions.value.length) return
ethnicLoading.value = true
try {
const res = await fetchEthnicList({ limit: 200 })
ethnicOptions.value = res.list || []
} finally {
ethnicLoading.value = false
}
}
function ensureEthnicOptionInList(name: string) {
const n = (name || '').trim()
if (!n) return
if (ethnicOptions.value.some((e) => e.ethnicName === n)) return
ethnicOptions.value = [
{ id: '', ethnicName: n, ethnicCode: '', orderNum: null },
...ethnicOptions.value
]
}
const formRules = {
customerName: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }]
}
const handleSelectionChange = (rows: Api.BizCustomer.CustomerItem[]) => {
selectedRows.value = rows
}
async function loadData() {
loading.value = true
try {
const res = await fetchCustomerList({
page: pagination.page,
pageSize: pagination.pageSize,
keyword: searchForm.keyword || undefined,
createTimeStart: createTimeRange.value?.[0] || undefined,
createTimeEnd: createTimeRange.value?.[1] || undefined
})
tableData.value = res.list || []
pagination.total = res.total ?? 0
} finally {
loading.value = false
}
}
function handleSearch() {
pagination.page = 1
loadData()
}
function handleReset() {
searchForm.keyword = ''
createTimeRange.value = null
pagination.page = 1
loadData()
}
function resetForm() {
formData.customerName = ''
formData.sex = '0'
formData.idCardNo = ''
formData.age = null
formData.birthYm = ''
formData.ethnic = ''
formData.email = ''
formData.address = ''
formData.phoneNo = ''
formData.customerTags = ''
formData.orderNum = 0
formData.remark = ''
editingId.value = null
}
function handleAdd() {
isEdit.value = false
dialogTitle.value = '新增客户'
resetForm()
void loadEthnicOptions()
dialogVisible.value = true
formRef.value?.clearValidate?.()
}
function handleEdit(row: Api.BizCustomer.CustomerItem) {
isEdit.value = true
dialogTitle.value = '编辑客户'
editingId.value = row.id
formData.customerName = row.customerName || ''
formData.sex = row.sex || '2'
formData.idCardNo = row.idCardNo || ''
formData.age = row.age ?? null
formData.birthYm = row.birthYm || ''
formData.ethnic = row.ethnic || ''
formData.email = row.email || ''
formData.address = row.address || ''
formData.phoneNo = row.phoneNo || ''
formData.customerTags = row.customerTags || ''
formData.orderNum = row.orderNum ?? 0
formData.remark = row.remark || ''
void loadEthnicOptions().then(() => ensureEthnicOptionInList(formData.ethnic))
dialogVisible.value = true
formRef.value?.clearValidate?.()
}
async function handleSubmit() {
await formRef.value?.validate?.()
submitLoading.value = true
try {
const payload = {
customerName: formData.customerName.trim(),
sex: formData.sex,
idCardNo: formData.idCardNo?.trim() || undefined,
age: formData.age,
birthYm: formData.birthYm?.trim() || undefined,
ethnic: formData.ethnic?.trim() || undefined,
email: formData.email?.trim() || undefined,
address: formData.address?.trim() || undefined,
phoneNo: formData.phoneNo?.trim() || undefined,
customerTags: formData.customerTags?.trim() || undefined,
orderNum: formData.orderNum,
remark: formData.remark?.trim() || undefined
}
if (isEdit.value && editingId.value) {
await fetchUpdateCustomer(editingId.value, payload)
} else {
await fetchCreateCustomer(payload)
}
ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
dialogVisible.value = false
await loadData()
} catch {
/* 全局处理 */
} finally {
submitLoading.value = false
}
}
function handleDropdownCommand(command: string, row: any) {
switch (command) {
case 'edit': handleEdit(row); break
case 'delete': handleDelete(row); break
}
}
async function handleDelete(row: Api.BizCustomer.CustomerItem) {
await ElMessageBox.confirm('确定要删除该客户吗?', '提示', { type: 'warning' })
await fetchDeleteCustomer(row.id)
ElMessage.success('删除成功')
await loadData()
}
async function handleBatchDelete() {
const ids = selectedRows.value.map((r) => r.id)
if (!ids.length) return
await ElMessageBox.confirm(`确定删除选中的 ${ids.length} 条客户吗?`, '提示', {
type: 'warning'
})
await withFullscreenLoading(async () => {
for (const id of ids) {
await fetchDeleteCustomer(id)
}
ElMessage.success('批量删除成功')
selectedRows.value = []
await loadData()
}, fullscreenLoadingText.batchDelete)
}
// 输入检索条件时自动搜索(防抖 300ms)
watchDebounced(
[searchForm, createTimeRange],
() => {
pagination.page = 1
loadData()
},
{ debounce: 300, deep: true }
)
const route = useRoute()
const activeTab = ref<TabKey>('storage')
onMounted(() => {
loadData()
const tab = String(route.query.tab || '')
if (tab === 'partner' || tab === 'storage') {
activeTab.value = tab
}
})
</script>
<style scoped lang="scss">
.biz-dialog-form {
:deep(.el-form-item) {
margin-bottom: 0;
}
}
.customer-relations {
.rel-group {
margin-bottom: 14px;
&:last-child {
margin-bottom: 0;
}
}
.rel-group-head {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.rel-muted {
color: var(--mint-text-muted, #64748b);
font-size: 13px;
}
.rel-link {
padding: 0;
border: 0;
background: transparent;
color: var(--primary, #10b981);
cursor: pointer;
font: inherit;
text-decoration: underline;
text-underline-offset: 2px;
}
}
</style>
@@ -76,6 +76,24 @@
align="center"
header-align="center"
/>
<el-table-column
prop="cellCountQianwan"
label="细胞数量(千万)"
min-width="140"
align="center"
header-align="center"
>
<template #default="{ row }">{{ formatNumberOrDash(row.cellCountQianwan) }}</template>
</el-table-column>
<el-table-column
prop="fillVolumeMl"
label="分装体积(ml)"
min-width="130"
align="center"
header-align="center"
>
<template #default="{ row }">{{ formatNumberOrDash(row.fillVolumeMl) }}</template>
</el-table-column>
<el-table-column
prop="remark"
label="备注"
@@ -166,7 +184,27 @@
<el-form-item label="规格名称" prop="specName">
<el-input v-model="formData.specName" placeholder="请输入规格名称" />
</el-form-item>
<el-form-item label="备注">
<el-form-item label="细胞数量(千万)" prop="cellCountQianwan">
<el-input-number
v-model="formData.cellCountQianwan"
:min="0.0001"
:precision="4"
:controls="false"
placeholder="请输入细胞数量"
class="w-full"
/>
</el-form-item>
<el-form-item label="分装体积(ml)" prop="fillVolumeMl">
<el-input-number
v-model="formData.fillVolumeMl"
:min="0.0001"
:precision="4"
:controls="false"
placeholder="请输入分装体积"
class="w-full"
/>
</el-form-item>
<el-form-item label="备注" class="form-col-span-2">
<el-input v-model="formData.remark" placeholder="可选" />
</el-form-item>
</div>
@@ -235,15 +273,46 @@
const viewVisible = ref(false)
const viewRow = ref<Api.CellProductSpec.CellProductSpecItem | null>(null)
const formData = reactive({
const formData = reactive<{
specCode: string
specName: string
cellCountQianwan: number | undefined
fillVolumeMl: number | undefined
remark: string
}>({
specCode: '',
specName: '',
cellCountQianwan: undefined,
fillVolumeMl: undefined,
remark: ''
})
const positiveNumberRule = (label: string) => ({
required: true,
validator: (_: unknown, value: number | undefined, callback: (e?: Error) => void) => {
if (value === undefined || value === null || Number.isNaN(Number(value))) {
callback(new Error(`请填写${label}`))
return
}
if (Number(value) <= 0) {
callback(new Error(`${label}必须大于0`))
return
}
callback()
},
trigger: 'blur'
})
const formRules = {
specCode: [{ required: true, message: '请输入规格编码', trigger: 'blur' }],
specName: [{ required: true, message: '请输入规格名称', trigger: 'blur' }]
specName: [{ required: true, message: '请输入规格名称', trigger: 'blur' }],
cellCountQianwan: [positiveNumberRule('细胞数量(千万)')],
fillVolumeMl: [positiveNumberRule('分装体积(ml)')]
}
function formatNumberOrDash(value: number | null | undefined) {
if (value === null || value === undefined || Number.isNaN(Number(value))) return '—'
return String(value)
}
const handleSelectionChange = (rows: Api.CellProductSpec.CellProductSpecItem[]) => {
@@ -259,6 +328,8 @@
fields: [
{ label: '规格编码', value: row.specCode },
{ label: '规格名称', value: row.specName },
{ label: '细胞数量(千万)', value: formatNumberOrDash(row.cellCountQianwan) },
{ label: '分装体积(ml)', value: formatNumberOrDash(row.fillVolumeMl) },
{ label: '备注', value: row.remark, span: true }
]
}
@@ -294,6 +365,8 @@
function resetForm() {
formData.specCode = ''
formData.specName = ''
formData.cellCountQianwan = undefined
formData.fillVolumeMl = undefined
formData.remark = ''
editingId.value = null
}
@@ -312,6 +385,14 @@
editingId.value = row.id
formData.specCode = row.specCode || ''
formData.specName = row.specName || ''
formData.cellCountQianwan =
row.cellCountQianwan === null || row.cellCountQianwan === undefined
? undefined
: Number(row.cellCountQianwan)
formData.fillVolumeMl =
row.fillVolumeMl === null || row.fillVolumeMl === undefined
? undefined
: Number(row.fillVolumeMl)
formData.remark = row.remark || ''
dialogVisible.value = true
formRef.value?.clearValidate?.()
@@ -324,6 +405,8 @@
const payload = {
specCode: formData.specCode.trim(),
specName: formData.specName.trim(),
cellCountQianwan: Number(formData.cellCountQianwan),
fillVolumeMl: Number(formData.fillVolumeMl),
remark: formData.remark?.trim() || undefined
}
if (isEdit.value && editingId.value) {
@@ -401,5 +484,17 @@
:deep(.el-form-item) {
margin-bottom: 0;
}
:deep(.el-input-number.w-full) {
width: 100%;
.el-input__inner {
text-align: left;
}
}
:deep(.el-form-item__error) {
text-align: left;
}
}
</style>
@@ -594,6 +594,7 @@
import ProtocolAttachmentReadonly from '@/views/cell-storage/protocol/ProtocolAttachmentReadonly.vue'
import { formatMoneyDisplay } from '@/utils/money-format'
import { getPilotBizConfig, resolvePilotBizType } from '@/config/pilot-biz-type'
import { isResearchLikeBiz } from '@/utils/research-like-biz'
defineOptions({ name: 'ClinicalRefundConfirmTab' })
@@ -602,7 +603,7 @@
const props = defineProps<{ bizType?: string }>()
const bizConfig = computed(() => getPilotBizConfig(props.bizType))
const isBasicExperiment = computed(
() => resolvePilotBizType(props.bizType) === 'basic_experiment'
() => isResearchLikeBiz(props.bizType)
)
const pickupTimeLabel = computed(() => bizConfig.value.pickupTimeLabel)
const keywordPlaceholder = computed(() =>
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more