Compare commits

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

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

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

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

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

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

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

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

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

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

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

Merge pull request #168 from codex/issue-167-mine-kw-filter-88f5de9f0988
2026-11-20 22:53:45 +00:00
140 changed files with 11346 additions and 1923 deletions

No files matched your search

+2
View File
@@ -17,6 +17,8 @@ SECRET_KEY=
# 应用配置示例
# APP_NAME=陇耘鲜达
# DEBUG=true
# SQL 回显与 DEBUG 解耦;需要排查 SQL 时再打开
# SQLALCHEMY_ECHO=false
# 浏览器跨域:若设置 BACKEND_CORS_ORIGINS,须为 JSON 数组,会整体覆盖代码默认值,例如:
# BACKEND_CORS_ORIGINS=["http://localhost:5173","http://localhost:3006","http://127.0.0.1:3006"]
+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))
# ---------------------------------------------------------------------------
# 细胞样本类型
# ---------------------------------------------------------------------------
+125 -1
View File
@@ -298,7 +298,7 @@ STATIC_MENU_TREE = [
],
},
# 临床科研
# 临床科研(与 sqxp.ts / 委托加工成对:申请、审批、费用、出库放行)
{
"id": "BEX00000000000000000000000000001",
"name": "BasicExperiment",
@@ -322,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",
@@ -330,6 +354,7 @@ STATIC_MENU_TREE = [
"meta": {
"title": "缴退费财务确认",
"keepAlive": True,
"isHide": True,
"menuCode": "basic-experiment:payment-confirm:list",
},
},
@@ -346,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",
@@ -601,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,
},
},
],
},
# 生产基础信息
+231 -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
# ---------------------------------------------------------------------------
@@ -236,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),
):
@@ -251,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)
@@ -266,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, "申请单不存在")
@@ -312,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
@@ -334,6 +372,8 @@ async def api_update_application(
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")
@@ -383,20 +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 in ("clinical_application", "basic_experiment")
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,
@@ -517,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,
@@ -869,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,
@@ -877,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
@@ -915,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
@@ -937,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"),
-52
View File
@@ -49,9 +49,7 @@ from app.schemas.production_work_order import (
ProductionWorkOrderCreate,
ProductionWorkOrderConfigureBody,
ProductionWorkOrderUpdate,
ProductionDeliveryCellOutboundBody,
)
from app.crud import outbound_handover as outbound_handover_svc
from app.schemas.production_task_set import (
ProductionTaskSetCreateBody,
ProductionTaskSetFromWorkOrderBody,
@@ -2027,56 +2025,6 @@ async def list_production_work_order_cell_product_options(
return error_response(400, str(e))
@router.get("/production-work-orders/{wo_id}/delivery-cell-outbound")
async def get_production_delivery_cell_outbound_api(
wo_id: str,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
"""临床科研出库工单 — 获取已确认的交付出库细胞。"""
try:
tenant_no = _get_tenant_no(db, user)
data = outbound_handover_svc.get_production_delivery_cell_outbound(
db, wo_id, tenant_no
)
return success_response(data)
except HTTPException as e:
return error_response(e.status_code, e.detail)
except ValueError as e:
return error_response(400, str(e))
@router.put("/production-work-orders/{wo_id}/delivery-cell-outbound")
async def save_production_delivery_cell_outbound_api(
wo_id: str,
body: ProductionDeliveryCellOutboundBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
"""临床科研出库工单 — 确认出库细胞(写台账并联动库存)。"""
try:
tenant_no = _get_tenant_no(db, user)
data = outbound_handover_svc.save_production_delivery_cell_outbound(
db,
wo_id,
cells=body.cells or [],
tenant_no=tenant_no,
user_id=user.get("user_id") or "",
create_dept_id=user.get("dept_id") or "",
)
db.commit()
return success_response(data, message="出库细胞已确认")
except HTTPException as e:
db.rollback()
return error_response(e.status_code, e.detail)
except ValueError as e:
db.rollback()
return error_response(400, str(e))
except Exception as e:
db.rollback()
return error_response(400, str(e))
@router.get("/production-work-orders/{wo_id}/qc-info")
async def get_production_work_order_qc_info_api(
wo_id: str,
+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,
+1
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()
+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))
+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
+49 -3
View File
@@ -1,14 +1,33 @@
"""临床科研申请单 · 业务子类型(research_category)"""
"""申请单业务子类型(research_category)。
临床科研保留历史三项;委托加工使用产品四项,并支持「其他」自定义文本。
"""
from typing import Optional
RESEARCH_CATEGORY_LABELS = {
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:
@@ -16,12 +35,39 @@ def research_category_label(code: Optional[str]) -> str:
return RESEARCH_CATEGORY_LABELS.get(code, code)
def validate_research_category(code: Optional[str], required: bool = False) -> str:
def validate_research_category(
code: Optional[str],
required: bool = False,
*,
biz_type: Optional[str] = "basic_experiment",
) -> str:
value = (code or "").strip()
if not value:
if required:
raise ValueError("请选择业务类型")
return ""
bt = biz_type or "basic_experiment"
if bt == "contract_processing":
if value in CONTRACT_PROCESSING_CATEGORY_LABELS:
return value
if len(value) > CUSTOM_CATEGORY_MAX_LEN:
raise ValueError(f"业务类型不能超过{CUSTOM_CATEGORY_MAX_LEN}个字符")
# 自定义原文;禁止占用临床科研预置码
if value in CLINICAL_RESEARCH_CATEGORY_LABELS:
raise ValueError("业务类型无效")
return value
if bt == "basic_experiment" or is_research_like_biz(bt):
if value in CLINICAL_RESEARCH_CATEGORY_LABELS:
return value
if len(value) > CUSTOM_CATEGORY_MAX_LEN:
raise ValueError(f"业务类型不能超过{CUSTOM_CATEGORY_MAX_LEN}个字符")
# 自定义原文;禁止占用委托加工预置码
if value in CONTRACT_PROCESSING_CATEGORY_LABELS:
raise ValueError("业务类型无效")
return value
if value not in RESEARCH_CATEGORY_LABELS:
raise ValueError("业务类型无效")
return value
+54 -2
View File
@@ -40,6 +40,25 @@ def _truncate(s: str, max_len: int) -> str:
return s[:max_len] + f"\n... [truncated, total {len(s)} chars]"
def _truncate_utf8_bytes(s: Optional[str], max_bytes: int) -> Optional[str]:
"""按 UTF-8 字节截断,适配 MySQL TEXT 字节上限。"""
if not s:
return s
raw = s.encode("utf-8")
if len(raw) <= max_bytes:
return s
cut = raw[:max_bytes]
while cut:
try:
text = cut.decode("utf-8")
break
except UnicodeDecodeError:
cut = cut[:-1]
else:
return None
return text + f"\n... [truncated, total {len(raw)} bytes]"
def _redact_obj(obj: Any) -> Any:
if isinstance(obj, dict):
out = {}
@@ -135,6 +154,10 @@ def _persist_log(
from app.core.utils import generate_id
from app.models.models import SysApiRequestLog
max_db = settings.API_REQUEST_LOG_DB_MAX_BYTES
req_body = _truncate_utf8_bytes(request_body, max_db)
resp_body = _truncate_utf8_bytes(response_body, max_db)
db = SessionLocal()
try:
row = SysApiRequestLog(
@@ -142,8 +165,8 @@ def _persist_log(
http_method=http_method,
path=_truncate(path, 500),
query_string=_truncate(query_string or "", 2000) or None,
request_body=request_body,
response_body=response_body,
request_body=req_body,
response_body=resp_body,
status_code=status_code,
duration_ms=duration_ms,
user_id=user_id,
@@ -161,6 +184,32 @@ def _persist_log(
except Exception as e:
logger.warning("api_request_log persist failed: %s", e)
db.rollback()
# 字段过长/字符集异常时降级为空 body,保留审计元数据
try:
row = SysApiRequestLog(
id=generate_id(),
http_method=http_method,
path=_truncate(path, 500),
query_string=_truncate(query_string or "", 2000) or None,
request_body=None,
response_body=None,
status_code=status_code,
duration_ms=duration_ms,
user_id=user_id,
username=_truncate(username or "", 100) if username else None,
role=role,
ip_address=ip_address,
user_agent=_truncate(user_agent or "", 500) if user_agent else None,
is_del=0,
create_at=datetime.now(),
create_by=None,
create_name=None,
)
db.add(row)
db.commit()
except Exception as e2:
logger.warning("api_request_log persist fallback failed: %s", e2)
db.rollback()
finally:
db.close()
@@ -180,6 +229,9 @@ def _schedule_persist_log(**kwargs) -> None:
task = loop.create_task(asyncio.to_thread(_persist_log, **kwargs))
def _on_done(t: asyncio.Task) -> None:
if t.cancelled():
# reload / shutdown 取消未完成写入任务,属预期
return
try:
t.result()
except Exception as e:
+7 -2
View File
@@ -28,6 +28,8 @@ class Settings(BaseSettings):
# 应用基础配置
APP_NAME: str = "zkxw 管理骨架"
DEBUG: bool = True
# SQLAlchemy 引擎 SQL 回显;默认关闭,避免 DEBUG=true 时终端被 SQL 刷屏
SQLALCHEMY_ECHO: bool = False
API_V1_PREFIX: str = "/api"
# 数据库配置
@@ -201,8 +203,11 @@ class Settings(BaseSettings):
# 全量 API 请求日志(中间件写入 sys_api_request_log)
API_REQUEST_LOG_ENABLED: bool = True
API_REQUEST_LOG_MAX_BODY: int = 65536
API_REQUEST_LOG_MAX_BODY_BYTES: int = 131072
# MySQL TEXT 上限约 65535 字节;按字符截断会因中文多字节溢出,默认按安全字符上限
API_REQUEST_LOG_MAX_BODY: int = 16000
API_REQUEST_LOG_MAX_BODY_BYTES: int = 48000
# 写入库时再按 UTF-8 字节截断,避免 Data too long
API_REQUEST_LOG_DB_MAX_BYTES: int = 60000
# Web API 请求/响应加密配置
API_ENCRYPT_ENABLED: bool = False
+1 -1
View File
@@ -8,7 +8,7 @@ engine = create_engine(
settings.DATABASE_URL,
pool_pre_ping=True,
pool_recycle=3600,
echo=settings.DEBUG,
echo=settings.SQLALCHEMY_ECHO,
)
# 避免 commit 后 ORM 实例自动过期,导致读取字段时回表 SELECT(高频接口会显著拖慢)
+2 -2
View File
@@ -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)))
+4 -127
View File
@@ -179,38 +179,23 @@ def save_outbound_handover(
handover_person = handover_user_id
om = outbound_material or {}
cells = om.get("cells") or []
qc_materials = om.get("qcMaterials") or om.get("qc_materials") or []
paper_materials = om.get("paperMaterials") or om.get("paper_materials") or []
material_remark = om.get("remark")
biz_type = (detail.get("bizType") or "").strip()
if not biz_type:
biz_type = ((detail.get("application") or {}).get("bizType") or "").strip()
# 临床科研:细胞出库由生产工单确认,市场交接只维护物料/交接信息
cells_owned_by_production = biz_type == "basic_experiment"
# 读取保存前台账,用于回滚上次出库交接的库存/状态变更
previous_material = orm_material_svc.get_outbound_material(db, schedule_id, tenant_no)
previous_cells = previous_material.get("cells") or []
previous_cell_ids = [
(c.get("cellProductId") or c.get("cell_product_id") or "").strip()
for c in previous_cells
for c in (previous_material.get("cells") or [])
]
had_previous_handover = get_handover_by_schedule(db, schedule_id, tenant_no) is not None
if cells_owned_by_production:
cells = previous_cells
revert_cell_ids: List[str] = []
apply_cells: List[Any] = []
else:
cells = om.get("cells") or []
revert_cell_ids = previous_cell_ids if had_previous_handover else []
apply_cells = cells
handover_inv_svc.revert_handover_inventory(
db,
schedule_id,
cell_product_ids=revert_cell_ids,
cell_product_ids=previous_cell_ids if had_previous_handover else [],
tenant_no=tenant_no,
user_id=user_id,
)
@@ -231,7 +216,7 @@ def save_outbound_handover(
handover_inv_svc.apply_handover_inventory(
db,
schedule_id,
cells=apply_cells,
cells=cells,
qc_materials=qc_materials,
tenant_no=tenant_no,
user_id=user_id,
@@ -270,111 +255,3 @@ def save_outbound_handover(
db.flush()
return get_outbound_handover(db, schedule_id, tenant_no)
def _assert_basic_experiment_outbound_wo(wo: Any) -> str:
"""校验临床科研出库工单,返回关联交付计划 ID。"""
if not wo:
raise HTTPException(status_code=404, detail="工单不存在")
if (getattr(wo, "work_order_type", None) or "") != "outbound":
raise HTTPException(status_code=400, detail="仅出库工单可确认出库细胞")
if (getattr(wo, "biz_type", None) or "") != "basic_experiment":
raise HTTPException(status_code=400, detail="仅临床科研出库工单可确认出库细胞")
if (getattr(wo, "work_order_status", None) or "") == "yzf":
raise HTTPException(status_code=400, detail="已作废工单不可确认出库细胞")
schedule_id = (getattr(wo, "infusion_schedule_id", None) or "").strip()
if not schedule_id:
raise HTTPException(status_code=400, detail="工单未关联交付计划,无法确认出库细胞")
return schedule_id
def get_production_delivery_cell_outbound(
db: Session,
work_order_id: str,
tenant_no: str,
) -> Dict[str, Any]:
"""生产工单 — 临床科研交付出库细胞编辑数据。"""
from app.crud import production_work_order as production_work_order_svc
wo = production_work_order_svc.get_production_work_order(db, work_order_id, tenant_no)
schedule_id = _assert_basic_experiment_outbound_wo(wo)
detail = schedule_mgmt_svc.get_infusion_schedule_detail(db, schedule_id, tenant_no)
if not detail:
raise HTTPException(status_code=404, detail="交付计划不存在")
outbound_material = orm_material_svc.get_outbound_material(db, schedule_id, tenant_no)
return {
"workOrderId": wo.id,
"workOrderNo": wo.work_order_no or "",
"infusionScheduleId": schedule_id,
"scheduleSummary": {
"applicationNo": detail.get("applicationNo") or "",
"patientName": detail.get("patientName") or "",
"infusionTime": detail.get("infusionTime") or "",
"projectTitle": detail.get("projectTitle")
or ((detail.get("application") or {}).get("projectTitle") or ""),
"customerName": detail.get("customerName")
or ((detail.get("application") or {}).get("customerName") or ""),
},
"cells": outbound_material.get("cells") or [],
}
def save_production_delivery_cell_outbound(
db: Session,
work_order_id: str,
*,
cells: List[Dict[str, Any]],
tenant_no: str,
user_id: str,
create_dept_id: str = "",
) -> Dict[str, Any]:
"""生产确认临床科研交付出库细胞:写台账并联动细胞产品库存(不 commit)。"""
from app.crud import production_work_order as production_work_order_svc
wo = production_work_order_svc.get_production_work_order(db, work_order_id, tenant_no)
schedule_id = _assert_basic_experiment_outbound_wo(wo)
detail = schedule_mgmt_svc.get_infusion_schedule_detail(db, schedule_id, tenant_no)
if not detail:
raise HTTPException(status_code=404, detail="交付计划不存在")
previous_material = orm_material_svc.get_outbound_material(db, schedule_id, tenant_no)
previous_cell_ids = [
(c.get("cellProductId") or c.get("cell_product_id") or "").strip()
for c in (previous_material.get("cells") or [])
]
# 仅回滚细胞;市场物料扣减由出库交接维护,不可一并撤销
handover_inv_svc.revert_handover_inventory(
db,
schedule_id,
cell_product_ids=previous_cell_ids,
tenant_no=tenant_no,
user_id=user_id,
skip_materials=True,
)
orm_material_svc.save_outbound_material(
db,
schedule_id,
paper_attachments=None,
paper_materials=previous_material.get("paperMaterials") or [],
remark=previous_material.get("remark"),
cells=cells or [],
qc_materials=previous_material.get("qcMaterials") or [],
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=create_dept_id,
)
handover_inv_svc.apply_handover_inventory(
db,
schedule_id,
cells=cells or [],
qc_materials=[],
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=create_dept_id,
receiver_person="",
)
return get_production_delivery_cell_outbound(db, work_order_id, tenant_no)
+17 -22
View File
@@ -264,35 +264,30 @@ def revert_handover_inventory(
cell_product_ids: Iterable[str],
tenant_no: str,
user_id: Optional[str] = None,
skip_materials: bool = False,
) -> None:
"""回滚本输注计划上次出库交接产生的库存/状态变更(不 commit)。
skip_materials=True 时仅回滚细胞产品状态(临床科研由生产单独出库细胞时使用)。
"""
"""回滚本输注计划上次出库交接产生的库存/状态变更(不 commit)。"""
sid = (schedule_id or "").strip()
if not sid:
return
remark_prefix = _handover_usage_remark_prefix(sid)
now = datetime.now()
if not skip_materials:
_revert_legacy_qc_handover_usages(
db,
schedule_id=sid,
tenant_no=tenant_no,
user_id=user_id,
remark_prefix=remark_prefix,
now=now,
)
_revert_market_handover_usages(
db,
schedule_id=sid,
tenant_no=tenant_no,
user_id=user_id,
remark_prefix=remark_prefix,
now=now,
)
_revert_legacy_qc_handover_usages(
db,
schedule_id=sid,
tenant_no=tenant_no,
user_id=user_id,
remark_prefix=remark_prefix,
now=now,
)
_revert_market_handover_usages(
db,
schedule_id=sid,
tenant_no=tenant_no,
user_id=user_id,
remark_prefix=remark_prefix,
now=now,
)
seen: Set[str] = set()
for raw_id in cell_product_ids:
@@ -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)))
+515 -77
View File
@@ -25,7 +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
# ────────────────────────────────────────────
@@ -77,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(
@@ -115,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,
@@ -128,6 +140,14 @@ def _row_to_dict_application(row, db=None, tenant_no=None) -> Dict[str, Any]:
"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 "",
@@ -194,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
@@ -320,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,
@@ -330,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:
@@ -392,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},
@@ -425,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(
@@ -460,7 +738,7 @@ def create_application(
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():
@@ -470,28 +748,29 @@ def create_application(
if not (data.get("customerPhone") or "").strip():
raise ValueError("请填写客户联系方式")
research_category = validate_research_category(
data.get("researchCategory"), required=True
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 = (data.get("channelId") or "").strip()
if not channel_id:
raise ValueError("请选择渠道")
ch = (
db.query(BizChannel)
.filter(
BizChannel.id == channel_id,
BizChannel.tenant_no == tenant_no,
BizChannel.del_flag == 0,
channel_name = ""
if channel_id:
ch = (
db.query(BizChannel)
.filter(
BizChannel.id == channel_id,
BizChannel.tenant_no == tenant_no,
BizChannel.del_flag == 0,
)
.first()
)
.first()
)
if not ch:
raise ValueError("渠道不存在")
channel_name = ch.channel_name or ""
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("请选择渠道服务订单")
@@ -536,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 "",
@@ -548,6 +832,7 @@ def create_application(
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 "")
@@ -607,16 +892,39 @@ def update_application(db: Session, app_id: str, data: dict, tenant_no: str) ->
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:
if (row.biz_type or "") == "basic_experiment":
row_biz = row.biz_type or ""
if is_research_like_biz(row_biz):
row.research_category = validate_research_category(
data.get("researchCategory"), required=True
data.get("researchCategory"), required=True, biz_type=row_biz
) or None
else:
row.research_category = validate_research_category(
data.get("researchCategory"), required=False
data.get("researchCategory"), required=False, biz_type=row_biz
) or None
if "channelId" in data and data["channelId"] is not None:
if (row.biz_type or "") in ("basic_experiment", "clinical_application"):
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("请选择渠道")
@@ -633,13 +941,24 @@ def update_application(db: Session, app_id: str, data: dict, tenant_no: str) ->
raise ValueError("渠道不存在")
row.channel_id = new_channel_id
row.channel_name = ch.channel_name or ""
if (row.biz_type or "") == "basic_experiment":
row.channel_service_order_id = ""
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)
@@ -680,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
@@ -689,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)
@@ -1210,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()),
@@ -1236,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}
@@ -1333,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,
@@ -1363,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
@@ -1708,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 -3
View File
@@ -91,6 +91,8 @@ _RECEPTION_SOURCE_LABELS = {
_OUTBOUND_BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}
_APPLICATION_STATUS_LABELS = {
"dks": "待开始",
@@ -1262,7 +1264,6 @@ def list_production_tasks(
BizProductionTaskStep.del_flag == 0,
)
.distinct()
.subquery()
)
q = q.filter(
or_(
@@ -1280,7 +1281,6 @@ def list_production_tasks(
BizProductionTaskHandover.del_flag == 0,
)
.distinct()
.subquery()
)
q = q.filter(
BizProductionTask.current_assignee_user_id != mh_uid,
@@ -3328,6 +3328,7 @@ _PRODUCTION_TAB_STEP_COUNT_KEYS = (
"inbound_research_donation",
"outbound_pilot_service",
"outbound_basic_experiment",
"outbound_contract_processing",
"temporary",
)
@@ -3351,6 +3352,8 @@ def _resolve_production_tab_key(
bt = (biz_type or "pilot_service").strip() or "pilot_service"
if bt == "basic_experiment":
return "outbound_basic_experiment"
if bt == "contract_processing":
return "outbound_contract_processing"
if bt == "clinical_application":
return None
return "outbound_pilot_service"
@@ -3429,7 +3432,6 @@ def _base_active_step_count_query(
BizProductionTaskStep.del_flag == 0,
)
.distinct()
.subquery()
)
q = q.filter(
or_(
+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 ""
)
+2 -7
View File
@@ -785,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(
+16 -1
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())
@@ -1263,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),
@@ -2003,6 +2005,7 @@ _QC_TAB_COUNT_KEYS = (
"inbound_research_donation",
"outbound_pilot_service",
"outbound_basic_experiment",
"outbound_contract_processing",
"temporary",
)
@@ -2023,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"
@@ -3343,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:
"""编辑质检工单:入库/出库可改备注、状态与质检结论;临时可改备注与质检对象"""
@@ -3373,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
@@ -3713,7 +3728,7 @@ def build_outbound_pilot_context_by_schedule(
"bizType": app_biz,
"bizTypeLabel": _OUTBOUND_BIZ_TYPE_LABELS.get(app_biz, app_biz),
}
if app_biz == "basic_experiment":
if app_biz in ("basic_experiment", "contract_processing"):
out["application"]["projectTitle"] = app.project_title or ""
out["application"]["customerName"] = app.customer_name or ""
out["application"]["customerContact"] = app.customer_contact or ""
+116
View File
@@ -574,6 +574,99 @@ def list_pending_protocol_samples(
return page_items, int(total)
def parse_optional_bool(value: Optional[str]) -> Optional[bool]:
"""解析查询参数中的可选布尔:空=不限,true/1=是,false/0=否。"""
if value is None:
return None
text = str(value).strip().lower()
if not text:
return None
if text in ("1", "true", "yes", "y"):
return True
if text in ("0", "false", "no", "n"):
return False
raise ValueError(f"invalid boolean query value: {value}")
def _apply_received_sample_type_and_void_filters(
db: Session,
q_rec,
*,
tenant_no: str,
sample_type_id: Optional[str] = None,
is_voided: Optional[bool] = None,
):
"""按样本类型、是否废弃(协议/捐赠状态=yzf)过滤已接收记录。"""
type_id = (sample_type_id or "").strip()
if not type_id and is_voided is None:
return q_rec
cell_q = (
db.query(BizProtocolSample.id)
.join(
BizCollectionProtocol,
and_(
BizCollectionProtocol.id == BizProtocolSample.collection_protocol_id,
BizCollectionProtocol.del_flag == 0,
),
)
.filter(
BizProtocolSample.del_flag == 0,
BizProtocolSample.tenant_no == tenant_no,
BizCollectionProtocol.tenant_no == tenant_no,
)
)
donation_q = (
db.query(_donation_sample_id_col(BizResearchDonationSample.id))
.join(
BizResearchDonation,
and_(
BizResearchDonation.id == BizResearchDonationSample.research_donation_id,
BizResearchDonation.del_flag == 0,
),
)
.filter(
BizResearchDonationSample.del_flag == 0,
BizResearchDonationSample.tenant_no == tenant_no,
BizResearchDonation.tenant_no == tenant_no,
)
)
if type_id:
cell_q = cell_q.filter(BizProtocolSample.sample_type_id == type_id)
donation_q = donation_q.filter(BizResearchDonationSample.sample_type_id == type_id)
if is_voided is True:
cell_q = cell_q.filter(BizCollectionProtocol.protocol_status == "yzf")
donation_q = donation_q.filter(BizResearchDonation.donation_status == "yzf")
elif is_voided is False:
cell_q = cell_q.filter(
or_(
BizCollectionProtocol.protocol_status.is_(None),
BizCollectionProtocol.protocol_status != "yzf",
)
)
donation_q = donation_q.filter(
or_(
BizResearchDonation.donation_status.is_(None),
BizResearchDonation.donation_status != "yzf",
)
)
cell_ids = cell_q.subquery()
donation_ids = donation_q.subquery()
return q_rec.filter(
or_(
and_(
BizSampleReception.reception_source == "cell_storage",
BizSampleReception.protocol_sample_id.in_(cell_ids),
),
and_(
BizSampleReception.reception_source == "research_donation",
BizSampleReception.donation_sample_id.in_(donation_ids),
),
)
)
def list_received_protocol_samples(
db: Session,
*,
@@ -582,6 +675,8 @@ def list_received_protocol_samples(
tenant_no: Optional[str] = None,
keyword: Optional[str] = None,
source_type: Optional[str] = None,
sample_type_id: Optional[str] = None,
is_voided: Optional[bool] = None,
reception_time_start: Optional[str] = None,
reception_time_end: Optional[str] = None,
user_info=None,
@@ -637,6 +732,14 @@ def list_received_protocol_samples(
)
)
q_rec = _apply_received_sample_type_and_void_filters(
db,
q_rec,
tenant_no=tenant_no,
sample_type_id=sample_type_id,
is_voided=is_voided,
)
if user_info:
from app.core.data_scope import apply_data_scope
q_rec = apply_data_scope(q_rec, BizSampleReception, user_info, db, tenant_no)
@@ -1110,7 +1213,9 @@ def update_sample_reception(
raise ValueError("接收结论无效")
from app.crud import sample_reception_lab_code as lab_code_svc
from app.services.lab_storage_code_rename import rename_lab_storage_code_copies
old_lab_code = (rec.lab_storage_code or "").strip()
code_raw = (lab_storage_code or "").strip()
if conclusion == "js":
parsed_code = lab_code_svc.validate_lab_storage_code(code_raw)
@@ -1131,7 +1236,18 @@ def update_sample_reception(
)
rec.lab_storage_code = parsed_code
else:
parsed_code = None
rec.lab_storage_code = None
new_lab_code = (parsed_code or "").strip()
if old_lab_code and new_lab_code and old_lab_code != new_lab_code:
rename_lab_storage_code_copies(
db,
tenant_no=tenant_no,
reception_id=reception_id,
old_code=old_lab_code,
new_code=new_lab_code,
user_id=user_id,
)
handler_display = (handler_name or "").strip()
if handler_user_id and not handler_display:
+63 -3
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="备注")
@@ -4183,15 +4230,28 @@ class BizPilotApplication(Base):
customer_contact = Column(String(100), nullable=True, comment="客户联系人(临床科研)")
customer_phone = Column(String(32), nullable=True, comment="客户联系方式(临床科研)")
research_category = Column(
String(32),
String(64),
nullable=True,
comment="临床科研业务子类型: bio_tech_clinical/joint_topic_declare/bio_pharma_rd",
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="备注")
+1 -9
View File
@@ -1,5 +1,5 @@
from pydantic import BaseModel, ConfigDict, Field
from typing import Any, Dict, List, Optional
from typing import Optional
from datetime import datetime
@@ -57,11 +57,3 @@ class ProductionWorkOrderConfigureBody(BaseModel):
route_id: Optional[str] = Field(None, alias="routeId")
description: Optional[str] = Field("", alias="description")
remark: Optional[str] = Field("", alias="remark")
class ProductionDeliveryCellOutboundBody(BaseModel):
"""临床科研出库工单 — 确认出库细胞。"""
model_config = ConfigDict(populate_by_name=True)
cells: List[Dict[str, Any]] = Field(default_factory=list, description="出库细胞产品列表")
+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,
@@ -0,0 +1,399 @@
"""编辑样本接收时,把实验室入库编码同步到已落库的关联副本。"""
from __future__ import annotations
from datetime import datetime
from typing import Iterable, List, Optional, Sequence
from sqlalchemy.orm import Session
from app.models.models import (
BizCellProduct,
BizLabSampleProcessingExtra,
BizLabSampleProcessSupplement,
BizOutboundReleaseCell,
BizProductionTask,
BizProductionTaskInput,
BizProductionTaskOutput,
BizProductionTaskStep,
BizProductionTaskStepOutput,
BizProductionWorkOrder,
BizQcWorkOrder,
BizQcWorkOrderInspectionBatch,
BizSampleReception,
BizStorageSlotOccupancy,
)
DUPLICATE_MESSAGE = "实验室入库编码已存在"
def _ascii_alnum(ch: str) -> bool:
return bool(ch) and ch.isascii() and ch.isalnum()
def replace_lab_code_token(text: Optional[str], old: str, new: str) -> Optional[str]:
"""替换完整编码。前后紧挨 ASCII 字母或数字时不替换,避免改掉更长的编码。"""
if text is None or not old or old == new or old not in text:
return text
out: List[str] = []
i = 0
size = len(old)
while i < len(text):
if text.startswith(old, i):
prev_ok = i == 0 or not _ascii_alnum(text[i - 1])
end = i + size
next_ok = end == len(text) or not _ascii_alnum(text[end])
if prev_ok and next_ok:
out.append(new)
i = end
continue
out.append(text[i])
i += 1
return "".join(out)
def _occupies_new_code(value: Optional[str], new: str) -> bool:
"""批次名等于新编码,或是「新编码 + 非字母数字后缀」。"""
text = (value or "").strip()
if not text or not new:
return False
if text == new:
return True
if not text.startswith(new) or len(text) == len(new):
return False
return not _ascii_alnum(text[len(new)])
def _like_prefix(code: str) -> str:
escaped = code.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
return escaped + "%"
def _ids(values: Iterable[str]) -> List[str]:
return [v for v in values if v]
def _touch(row, user_id: Optional[str], now: datetime) -> None:
row.update_by = user_id
row.update_time = now
def _rewrite_fields(row, fields: Sequence[str], old: str, new: str, user_id: Optional[str], now: datetime) -> bool:
changed = False
for field in fields:
current = getattr(row, field)
updated = replace_lab_code_token(current, old, new)
if updated != current:
setattr(row, field, updated)
changed = True
if changed:
_touch(row, user_id, now)
return changed
def _raise_if_duplicate() -> None:
raise ValueError(DUPLICATE_MESSAGE)
def rename_lab_storage_code_copies(
db: Session,
*,
tenant_no: str,
reception_id: str,
old_code: str,
new_code: str,
user_id: Optional[str] = None,
) -> int:
"""把本条接收记录关联出去的旧编码副本改成新编码。冲突时不写任何副本。"""
old = (old_code or "").strip()
new = (new_code or "").strip()
if not old or not new or old == new:
return 0
other_reception = (
db.query(BizSampleReception.id)
.filter(
BizSampleReception.tenant_no == tenant_no,
BizSampleReception.del_flag == 0,
BizSampleReception.lab_storage_code == new,
BizSampleReception.id != reception_id,
)
.first()
)
if other_reception:
_raise_if_duplicate()
prod_orders = (
db.query(BizProductionWorkOrder)
.filter(
BizProductionWorkOrder.tenant_no == tenant_no,
BizProductionWorkOrder.del_flag == 0,
BizProductionWorkOrder.reception_id == reception_id,
)
.all()
)
qc_orders = (
db.query(BizQcWorkOrder)
.filter(
BizQcWorkOrder.tenant_no == tenant_no,
BizQcWorkOrder.del_flag == 0,
BizQcWorkOrder.reception_id == reception_id,
)
.all()
)
prod_ids = [row.id for row in prod_orders]
qc_ids = [row.id for row in qc_orders]
tasks = (
db.query(BizProductionTask)
.filter(
BizProductionTask.tenant_no == tenant_no,
BizProductionTask.del_flag == 0,
BizProductionTask.work_order_id.in_(prod_ids),
)
.all()
if prod_ids
else []
)
task_ids = [row.id for row in tasks]
steps = (
db.query(BizProductionTaskStep)
.filter(
BizProductionTaskStep.tenant_no == tenant_no,
BizProductionTaskStep.del_flag == 0,
BizProductionTaskStep.task_id.in_(task_ids),
)
.all()
if task_ids
else []
)
step_ids = [row.id for row in steps]
inputs = (
db.query(BizProductionTaskInput)
.filter(
BizProductionTaskInput.tenant_no == tenant_no,
BizProductionTaskInput.del_flag == 0,
BizProductionTaskInput.task_id.in_(task_ids),
)
.all()
if task_ids
else []
)
task_outputs = (
db.query(BizProductionTaskOutput)
.filter(
BizProductionTaskOutput.tenant_no == tenant_no,
BizProductionTaskOutput.del_flag == 0,
BizProductionTaskOutput.task_id.in_(task_ids),
)
.all()
if task_ids
else []
)
step_outputs = (
db.query(BizProductionTaskStepOutput)
.filter(
BizProductionTaskStepOutput.tenant_no == tenant_no,
BizProductionTaskStepOutput.del_flag == 0,
BizProductionTaskStepOutput.step_id.in_(step_ids),
)
.all()
if step_ids
else []
)
products = (
db.query(BizCellProduct)
.filter(
BizCellProduct.tenant_no == tenant_no,
BizCellProduct.del_flag == 0,
BizCellProduct.production_task_id.in_(task_ids),
)
.all()
if task_ids
else []
)
product_ids = [row.id for row in products]
occupancies = (
db.query(BizStorageSlotOccupancy)
.filter(
BizStorageSlotOccupancy.tenant_no == tenant_no,
BizStorageSlotOccupancy.del_flag == 0,
BizStorageSlotOccupancy.item_id.in_(product_ids),
)
.all()
if product_ids
else []
)
outbound_cells = (
db.query(BizOutboundReleaseCell)
.filter(
BizOutboundReleaseCell.tenant_no == tenant_no,
BizOutboundReleaseCell.del_flag == 0,
BizOutboundReleaseCell.cell_product_id.in_(product_ids),
)
.all()
if product_ids
else []
)
batches = (
db.query(BizQcWorkOrderInspectionBatch)
.filter(
BizQcWorkOrderInspectionBatch.tenant_no == tenant_no,
BizQcWorkOrderInspectionBatch.del_flag == 0,
BizQcWorkOrderInspectionBatch.work_order_id.in_(qc_ids),
)
.all()
if qc_ids
else []
)
supplements = (
db.query(BizLabSampleProcessSupplement)
.filter(
BizLabSampleProcessSupplement.tenant_no == tenant_no,
BizLabSampleProcessSupplement.del_flag == 0,
BizLabSampleProcessSupplement.lab_storage_code == old,
)
.all()
)
extras = (
db.query(BizLabSampleProcessingExtra)
.filter(
BizLabSampleProcessingExtra.tenant_no == tenant_no,
BizLabSampleProcessingExtra.del_flag == 0,
BizLabSampleProcessingExtra.sample_code == old,
)
.all()
)
_assert_copies_available(
db,
tenant_no=tenant_no,
new=new,
product_ids=product_ids,
task_output_ids=[row.id for row in task_outputs],
step_output_ids=[row.id for row in step_outputs],
occupancy_ids=[row.id for row in occupancies],
qc_ids=qc_ids,
)
if (
db.query(BizLabSampleProcessSupplement.id)
.filter(
BizLabSampleProcessSupplement.tenant_no == tenant_no,
BizLabSampleProcessSupplement.del_flag == 0,
BizLabSampleProcessSupplement.lab_storage_code == new,
)
.first()
):
_raise_if_duplicate()
if (
db.query(BizLabSampleProcessingExtra.id)
.filter(
BizLabSampleProcessingExtra.tenant_no == tenant_no,
BizLabSampleProcessingExtra.del_flag == 0,
BizLabSampleProcessingExtra.sample_code == new,
)
.first()
):
_raise_if_duplicate()
now = datetime.now()
changed = 0
for row in tasks:
if _rewrite_fields(row, ("task_name", "description", "remark"), old, new, user_id, now):
changed += 1
for row in steps:
if _rewrite_fields(row, ("description", "remark", "sop_content"), old, new, user_id, now):
changed += 1
for row in inputs:
if _rewrite_fields(row, ("input_name", "input_code"), old, new, user_id, now):
changed += 1
for row in task_outputs:
if _rewrite_fields(row, ("output_name", "output_barcode"), old, new, user_id, now):
changed += 1
for row in step_outputs:
if _rewrite_fields(row, ("output_name", "output_barcode"), old, new, user_id, now):
changed += 1
for row in products:
if _rewrite_fields(row, ("product_code", "product_name", "batch_no"), old, new, user_id, now):
changed += 1
for row in occupancies:
if _rewrite_fields(row, ("item_code", "item_name"), old, new, user_id, now):
changed += 1
for row in outbound_cells:
if _rewrite_fields(row, ("product_code", "product_name", "batch_no"), old, new, user_id, now):
changed += 1
for row in batches:
if _rewrite_fields(row, ("batch_name",), old, new, user_id, now):
changed += 1
for row in supplements:
row.lab_storage_code = new
_touch(row, user_id, now)
changed += 1
for row in extras:
row.sample_code = new
_touch(row, user_id, now)
changed += 1
if changed:
db.flush()
return changed
def _assert_copies_available(
db: Session,
*,
tenant_no: str,
new: str,
product_ids: Sequence[str],
task_output_ids: Sequence[str],
step_output_ids: Sequence[str],
occupancy_ids: Sequence[str],
qc_ids: Sequence[str],
) -> None:
product_q = db.query(BizCellProduct.id).filter(
BizCellProduct.tenant_no == tenant_no,
BizCellProduct.del_flag == 0,
BizCellProduct.product_code == new,
)
if product_ids:
product_q = product_q.filter(~BizCellProduct.id.in_(_ids(product_ids)))
if product_q.first():
_raise_if_duplicate()
task_barcode_q = db.query(BizProductionTaskOutput.id).filter(
BizProductionTaskOutput.tenant_no == tenant_no,
BizProductionTaskOutput.del_flag == 0,
BizProductionTaskOutput.output_barcode == new,
)
if task_output_ids:
task_barcode_q = task_barcode_q.filter(~BizProductionTaskOutput.id.in_(_ids(task_output_ids)))
if task_barcode_q.first():
_raise_if_duplicate()
step_barcode_q = db.query(BizProductionTaskStepOutput.id).filter(
BizProductionTaskStepOutput.tenant_no == tenant_no,
BizProductionTaskStepOutput.del_flag == 0,
BizProductionTaskStepOutput.output_barcode == new,
)
if step_output_ids:
step_barcode_q = step_barcode_q.filter(~BizProductionTaskStepOutput.id.in_(_ids(step_output_ids)))
if step_barcode_q.first():
_raise_if_duplicate()
occupancy_q = db.query(BizStorageSlotOccupancy.id).filter(
BizStorageSlotOccupancy.tenant_no == tenant_no,
BizStorageSlotOccupancy.del_flag == 0,
BizStorageSlotOccupancy.item_code == new,
)
if occupancy_ids:
occupancy_q = occupancy_q.filter(~BizStorageSlotOccupancy.id.in_(_ids(occupancy_ids)))
if occupancy_q.first():
_raise_if_duplicate()
batch_q = db.query(BizQcWorkOrderInspectionBatch.batch_name).filter(
BizQcWorkOrderInspectionBatch.tenant_no == tenant_no,
BizQcWorkOrderInspectionBatch.del_flag == 0,
BizQcWorkOrderInspectionBatch.batch_name.like(_like_prefix(new), escape="\\"),
)
if qc_ids:
batch_q = batch_q.filter(~BizQcWorkOrderInspectionBatch.work_order_id.in_(_ids(qc_ids)))
for (name,) in batch_q.all():
if _occupies_new_code(name, new):
_raise_if_duplicate()
+4 -1
View File
@@ -5,12 +5,15 @@ from app.core.config import settings
def create_assignment(db, tenant_no, user, project_id, biz_type):
from app.services.project_management import validate_assignment
from app.constants.pilot_biz import requires_leader_approval
if biz_type == 'clinical_application':
if project_id:
raise HTTPException(400, '临床应用不支持项目归属')
return None
# 临床科研/委托加工须绑定项目,供项目组负责人审批
required = True if requires_leader_approval(biz_type) else settings.PROJECT_ASSIGNMENT_REQUIRED
return validate_assignment(db, tenant_no, user, project_id, biz_type,
required=settings.PROJECT_ASSIGNMENT_REQUIRED)
required=required)
def guard_project_edit(row, payload):
+3 -3
View File
@@ -19,6 +19,7 @@ BUSINESS = {
'research_donation': (BizResearchDonation, 'donation_no', 'donation_status'),
'pilot_service': (BizPilotApplication, 'application_no', 'application_status'),
'basic_experiment': (BizPilotApplication, 'application_no', 'application_status'),
'contract_processing': (BizPilotApplication, 'application_no', 'application_status'),
}
COUNT_TYPES = tuple(k for k in BUSINESS if k != 'presign')
ALL_PROJECTS_PERMISSION = 'project:project:all'
@@ -215,8 +216,7 @@ def preview_assignment(db, tenant, user, kind, row_id, project_id):
def assign(db, tenant, user, kind, row_id, project_id, reason, expected):
check_permission(db, tenant, user, 'project:assignment:edit')
if not reason or not reason.strip():
raise HTTPException(400, '请填写调整原因')
reason_text = (reason or '').strip()
rows = linked_records(db, tenant, user, kind, row_id, lock=True)
actual = {(k, r.id, r.project_id) for k, r in rows}
refreshed = linked_records(db, tenant, user, kind, row_id, current_read=True)
@@ -228,7 +228,7 @@ def assign(db, tenant, user, kind, row_id, project_id, reason, expected):
new_name = project_brief(db, tenant, project_id)['projectName']
operator = scoped(db, SysUser, tenant).filter(SysUser.id == user.get('user_id')).first()
for k, row in rows:
db.add(ProjectAssignmentAudit(id=generate_uuid(), tenant_no=tenant, biz_type=k, biz_id=row.id, old_project_id=row.project_id, new_project_id=project_id, old_project_name=project_brief(db, tenant, row.project_id)['projectName'], new_project_name=new_name, reason=reason.strip(), operator_name=operator.nick_name if operator else user.get('user_id'), create_by=user.get('user_id'), create_dept_id=user.get('dept_id') or ''))
db.add(ProjectAssignmentAudit(id=generate_uuid(), tenant_no=tenant, biz_type=k, biz_id=row.id, old_project_id=row.project_id, new_project_id=project_id, old_project_name=project_brief(db, tenant, row.project_id)['projectName'], new_project_name=new_name, reason=reason_text, operator_name=operator.nick_name if operator else user.get('user_id'), create_by=user.get('user_id'), create_dept_id=user.get('dept_id') or ''))
row.project_id = project_id
row.update_by = user.get('user_id')
row.update_time = datetime.now()
@@ -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,467 @@
#!/usr/bin/env python3
"""作废「已完成合同审批」中未被付款审批关联的重复单。
背景:发起人误提两张相同合同审批,其中一张已被付款单通过 oa_relation 关联,
另一张未关联。产品撤回 API 仅允许 running→cancelled,无法作废已完成单。
本脚本:
1) 按申请人昵称 + 流程名「合同审批」定位候选实例
2) 用 oa_relation.to_instance_id 区分已关联 / 未关联
3) 断言恰好 1 张已关联、1 张未关联后,对未关联单软删除作废
用法(backend 目录、已配置目标库):
python -m scripts.repair_oa_void_unlinked_contract_duplicate \\
--nick-name 胡倩茜 --create-time '2026-11-25 12:00:56'
python -m scripts.repair_oa_void_unlinked_contract_duplicate \\
--nick-name 胡倩茜 --create-time '2026-11-25 12:00:56' --apply
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from datetime import datetime
from typing import Any, Dict, List, Optional
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sqlalchemy.orm import Session
from app.core.database import SessionLocal
from app.core.utils import generate_uuid
from app.models.models import (
OaApp,
OaInstance,
OaInstanceEvent,
OaRelation,
SysUser,
)
CONTRACT_APP_NAME = "合同审批"
PAYMENT_APP_NAME = "付款审批"
def _parse_create_time(raw: Optional[str]) -> Optional[datetime]:
text = (raw or "").strip()
if not text:
return None
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
try:
return datetime.strptime(text, fmt)
except ValueError:
continue
raise RuntimeError(
f"无法解析 --create-time={raw!r},请用 'YYYY-MM-DD HH:MM:SS'"
)
def _find_user(db: Session, *, nick_name: str, tenant_no: Optional[str]) -> SysUser:
q = db.query(SysUser).filter(
SysUser.del_flag == 0,
SysUser.nick_name == nick_name,
)
if tenant_no:
q = q.filter(SysUser.tenant_no == tenant_no)
rows = q.all()
if not rows:
raise RuntimeError(f"未找到用户 nick_name={nick_name!r}")
if len(rows) > 1 and not tenant_no:
raise RuntimeError(
"匹配到多名用户,请加 --tenant。"
f" 候选: {[{'id': u.id, 'tenantNo': u.tenant_no, 'userNo': u.user_no} for u in rows]}"
)
return rows[0]
def _find_app(db: Session, *, app_name: str, tenant_no: str) -> OaApp:
row = (
db.query(OaApp)
.filter(
OaApp.del_flag == 0,
OaApp.tenant_no == tenant_no,
OaApp.app_name == app_name,
)
.first()
)
if not row:
# 宽松匹配,便于生产命名略有差异时定位
cands = (
db.query(OaApp)
.filter(
OaApp.del_flag == 0,
OaApp.tenant_no == tenant_no,
OaApp.app_name.like(f"%{app_name}%"),
)
.all()
)
names = [a.app_name for a in cands]
raise RuntimeError(
f"未找到应用 app_name={app_name!r} tenant={tenant_no!r};近似: {names}"
)
return row
def _list_contract_instances(
db: Session,
*,
user: SysUser,
contract_app: OaApp,
create_time: Optional[datetime],
) -> List[OaInstance]:
q = db.query(OaInstance).filter(
OaInstance.del_flag == 0,
OaInstance.tenant_no == user.tenant_no,
OaInstance.app_id == contract_app.id,
OaInstance.initiator_user_id == user.id,
OaInstance.status == "completed",
)
if create_time is not None:
q = q.filter(OaInstance.create_time == create_time)
rows = q.order_by(OaInstance.create_time.asc(), OaInstance.id.asc()).all()
if not rows:
raise RuntimeError(
"未找到已完成的合同审批实例。"
f" user={user.nick_name} app={contract_app.app_name}"
f" create_time={create_time}"
)
if len(rows) < 2:
raise RuntimeError(
f"仅找到 {len(rows)} 张已完成合同审批,预期至少 2 张重复单。"
f" ids={[r.id for r in rows]}"
)
if create_time is None and len(rows) > 2:
raise RuntimeError(
f"未指定 --create-time 时匹配到 {len(rows)} 张,请加上精确申请时间缩小范围。"
f" ids={[r.id for r in rows]}"
)
return rows
def _linked_contract_ids(
db: Session, *, contract_ids: List[str], tenant_no: str
) -> Dict[str, List[Dict[str, Any]]]:
"""返回 contract_id -> 关联边摘要(付款 from → 合同 to)。"""
if not contract_ids:
return {}
rels = (
db.query(OaRelation)
.filter(
OaRelation.del_flag == 0,
OaRelation.tenant_no == tenant_no,
OaRelation.to_instance_id.in_(contract_ids),
)
.all()
)
out: Dict[str, List[Dict[str, Any]]] = {cid: [] for cid in contract_ids}
if not rels:
return out
from_ids = list({r.from_instance_id for r in rels})
from_inst = {
i.id: i
for i in db.query(OaInstance)
.filter(OaInstance.id.in_(from_ids), OaInstance.del_flag == 0)
.all()
}
app_ids = list({i.app_id for i in from_inst.values()})
apps = {
a.id: a
for a in db.query(OaApp).filter(OaApp.id.in_(app_ids), OaApp.del_flag == 0).all()
}
for r in rels:
fi = from_inst.get(r.from_instance_id)
app = apps.get(fi.app_id) if fi else None
out.setdefault(r.to_instance_id, []).append(
{
"relationId": r.id,
"paymentInstanceId": r.from_instance_id,
"paymentStatus": getattr(fi, "status", None),
"paymentAppName": getattr(app, "app_name", None),
"fieldKey": r.field_key,
"relationCreateTime": str(r.create_time) if r.create_time else None,
}
)
return out
def _void_instance(
db: Session,
*,
inst: OaInstance,
actor_user_id: Optional[str],
mode: str,
) -> Dict[str, Any]:
now = datetime.now()
before = {"id": inst.id, "status": inst.status, "delFlag": inst.del_flag}
if mode == "soft-delete":
inst.del_flag = 1
inst.status = "cancelled"
elif mode == "cancel":
inst.status = "cancelled"
else:
raise RuntimeError(f"未知 --mode={mode!r}")
inst.update_by = actor_user_id
inst.update_time = now
remark = (
"生产数据修复:重复合同审批未关联付款,软删除作废"
if mode == "soft-delete"
else "生产数据修复:重复合同审批未关联付款,状态改为已撤销"
)
if not (inst.remark or "").strip():
inst.remark = remark
db.add(inst)
ev = OaInstanceEvent(
id=generate_uuid(),
instance_id=inst.id,
round_no=int(getattr(inst, "current_round", None) or 1),
event_type="withdraw",
actor_user_id=actor_user_id,
task_id=None,
node_key=None,
comment_text=remark,
tenant_no=inst.tenant_no,
order_num=0,
remark="repair_oa_void_unlinked_contract_duplicate",
create_by=actor_user_id,
create_dept_id=inst.initiator_dept_id or "",
create_time=now,
update_by=actor_user_id,
update_time=now,
del_flag=0,
)
db.add(ev)
return {
"before": before,
"after": {"id": inst.id, "status": inst.status, "delFlag": inst.del_flag},
"eventId": ev.id,
"mode": mode,
}
def analyze(
db: Session,
*,
nick_name: str,
create_time: Optional[datetime],
tenant_no: Optional[str],
contract_app_name: str,
) -> Dict[str, Any]:
user = _find_user(db, nick_name=nick_name, tenant_no=tenant_no)
tn = user.tenant_no
contract_app = _find_app(db, app_name=contract_app_name, tenant_no=tn)
payment_app = (
db.query(OaApp)
.filter(
OaApp.del_flag == 0,
OaApp.tenant_no == tn,
OaApp.app_name == PAYMENT_APP_NAME,
)
.first()
)
instances = _list_contract_instances(
db, user=user, contract_app=contract_app, create_time=create_time
)
ids = [i.id for i in instances]
links = _linked_contract_ids(db, contract_ids=ids, tenant_no=tn)
linked_ids: List[str] = [cid for cid, rels in links.items() if rels]
unlinked_ids: List[str] = [cid for cid in ids if cid not in linked_ids]
candidates = [
{
"id": i.id,
"title": i.title,
"status": i.status,
"createTime": str(i.create_time) if i.create_time else None,
"updateTime": str(i.update_time) if i.update_time else None,
"linkedPayments": links.get(i.id) or [],
"decision": "keep" if i.id in linked_ids else "void_candidate",
}
for i in instances
]
errors: List[str] = []
if len(linked_ids) != 1:
errors.append(
f"期望恰好 1 张已被付款关联的合同,实际 {len(linked_ids)}: {linked_ids}"
)
if len(unlinked_ids) != 1:
errors.append(
f"期望恰好 1 张未关联合同待作废,实际 {len(unlinked_ids)}: {unlinked_ids}"
)
# 关联来源最好是付款审批(非硬失败,仅警告)
warnings: List[str] = []
for cid in linked_ids:
for rel in links.get(cid) or []:
pname = (rel.get("paymentAppName") or "").strip()
if payment_app and pname and pname != PAYMENT_APP_NAME:
warnings.append(
f"合同 {cid} 被非付款应用关联: {pname} ({rel.get('paymentInstanceId')})"
)
if not pname:
warnings.append(
f"合同 {cid} 关联来源应用名未知: {rel.get('paymentInstanceId')}"
)
return {
"user": {
"id": user.id,
"nickName": user.nick_name,
"userNo": user.user_no,
"tenantNo": tn,
},
"contractApp": {"id": contract_app.id, "appName": contract_app.app_name},
"paymentApp": (
{"id": payment_app.id, "appName": payment_app.app_name}
if payment_app
else None
),
"createTimeFilter": str(create_time) if create_time else None,
"candidates": candidates,
"linkedContractIds": linked_ids,
"unlinkedContractIds": unlinked_ids,
"voidTargetId": unlinked_ids[0] if len(unlinked_ids) == 1 else None,
"keepTargetId": linked_ids[0] if len(linked_ids) == 1 else None,
"errors": errors,
"warnings": warnings,
"safeToApply": len(errors) == 0,
}
def run(
*,
nick_name: str,
create_time_raw: Optional[str],
tenant_no: Optional[str],
contract_app_name: str,
apply: bool,
mode: str,
actor_user_id: Optional[str],
) -> Dict[str, Any]:
create_time = _parse_create_time(create_time_raw)
db = SessionLocal()
try:
report = analyze(
db,
nick_name=nick_name.strip(),
create_time=create_time,
tenant_no=(tenant_no or "").strip() or None,
contract_app_name=(contract_app_name or CONTRACT_APP_NAME).strip()
or CONTRACT_APP_NAME,
)
if not apply:
db.rollback()
return {
"dryRun": True,
"mode": mode,
"analysis": report,
"message": (
"dry-run:未写库。"
"确认 voidTargetId 正确且 safeToApply=true 后加 --apply。"
),
}
if not report.get("safeToApply"):
db.rollback()
return {
"dryRun": False,
"applied": False,
"mode": mode,
"analysis": report,
"message": "分析未通过安全断言,已回滚,未写库。",
}
target_id = report["voidTargetId"]
inst = (
db.query(OaInstance)
.filter(
OaInstance.id == target_id,
OaInstance.del_flag == 0,
)
.one()
)
# 二次校验:写库前再确认仍未被关联
still_linked = (
db.query(OaRelation.id)
.filter(
OaRelation.del_flag == 0,
OaRelation.tenant_no == inst.tenant_no,
OaRelation.to_instance_id == inst.id,
)
.first()
)
if still_linked:
db.rollback()
raise RuntimeError(
f"写库前发现目标 {inst.id} 已被关联,中止作废以防误伤"
)
actor = actor_user_id or inst.initiator_user_id
void_result = _void_instance(
db, inst=inst, actor_user_id=actor, mode=mode
)
db.commit()
return {
"dryRun": False,
"applied": True,
"mode": mode,
"analysis": report,
"voidResult": void_result,
"message": "已作废未关联合同审批;已关联付款的合同未改动。",
}
except Exception:
db.rollback()
raise
finally:
db.close()
def main(argv: Optional[List[str]] = None) -> int:
parser = argparse.ArgumentParser(
description="作废未被付款关联的重复已完成合同审批"
)
parser.add_argument("--nick-name", required=True, help="申请人昵称,如 胡倩茜")
parser.add_argument(
"--create-time",
default=None,
help="申请时间,精确匹配 oa_instance.create_time,如 '2026-11-25 12:00:56'",
)
parser.add_argument("--tenant", default=None, help="租户编号;重名用户时必填")
parser.add_argument(
"--contract-app-name",
default=CONTRACT_APP_NAME,
help=f"合同审批应用名,默认 {CONTRACT_APP_NAME}",
)
parser.add_argument(
"--mode",
choices=("soft-delete", "cancel"),
default="soft-delete",
help="soft-delete=列表消失(默认);cancel=仅改为已撤销仍可见",
)
parser.add_argument("--apply", action="store_true", help="实际写库;默认 dry-run")
parser.add_argument(
"--actor-user-id",
default=None,
help="事件操作人;默认用发起人",
)
args = parser.parse_args(argv)
result = run(
nick_name=args.nick_name,
create_time_raw=args.create_time,
tenant_no=args.tenant,
contract_app_name=args.contract_app_name,
apply=bool(args.apply),
mode=args.mode,
actor_user_id=args.actor_user_id,
)
print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
analysis = result.get("analysis") or {}
if analysis.get("errors"):
return 2
if result.get("dryRun") is False and not result.get("applied"):
return 2
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,308 @@
#!/usr/bin/env python3
"""补建「先废弃后改接收」漏掉的下游单据。
样本接收编辑接口不会重复创建质检/生产工单、入库放行与内置任务派发。
本脚本对指定接收记录回放首次「接收」路径(幂等):
1) 质检工单 create_work_order_from_reception
2) 生产工单 create_production_work_order_from_reception
3) UBMC/UC/... 内置任务 try_auto_dispatch_builtin_tasks_after_reception
4) 入库放行审核 create_review_from_reception(已存在则跳过)
5) after_sample_reception_saved(清样本作废态)
用法(在 backend 目录、已配置目标库连接):
python -m scripts.repair_reception_downstream_after_bj_to_js \\
--sample-code KYJZ2026110105 --lab-storage-code UBMC202611048
# 确认输出后写库
python -m scripts.repair_reception_downstream_after_bj_to_js \\
--sample-code KYJZ2026110105 --lab-storage-code UBMC202611048 --apply
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from typing import Any, Dict, Optional
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sqlalchemy.orm import Session
from app.core.database import SessionLocal
from app.crud import production_task_set as production_task_set_svc
from app.crud import production_work_order as prod_wo_svc
from app.crud import qc_work_order as qc_wo_svc
from app.crud import storage_release_review as srr_svc
from app.models.models import (
BizProductionTask,
BizProductionWorkOrder,
BizQcWorkOrder,
BizResearchDonation,
BizResearchDonationSample,
BizSampleReception,
BizStorageReleaseReview,
)
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
def _find_reception(
db: Session,
*,
sample_code: str,
lab_storage_code: str,
tenant_no: Optional[str],
) -> BizSampleReception:
q = db.query(BizSampleReception).filter(
BizSampleReception.del_flag == 0,
BizSampleReception.sample_code == sample_code,
BizSampleReception.lab_storage_code == lab_storage_code,
)
if tenant_no:
q = q.filter(BizSampleReception.tenant_no == tenant_no)
rows = q.order_by(BizSampleReception.create_time.desc()).all()
if not rows:
raise RuntimeError(
f"未找到接收记录 sample_code={sample_code!r} "
f"lab_storage_code={lab_storage_code!r}"
)
if len(rows) > 1 and not tenant_no:
tenants = sorted({r.tenant_no for r in rows})
raise RuntimeError(
f"匹配到多条接收记录,请加 --tenant。tenant_no 候选: {tenants}"
)
return rows[0]
def _srr_snapshot(db: Session, rec: BizSampleReception) -> Dict[str, str]:
protocol_no = ""
sample_name = ""
source = (rec.reception_source or "cell_storage").strip() or "cell_storage"
if source == "research_donation":
d = (
db.query(BizResearchDonation)
.filter(
BizResearchDonation.id == (rec.research_donation_id or ""),
BizResearchDonation.del_flag == 0,
)
.first()
)
if d:
protocol_no = d.donation_no or ""
ds = (
db.query(BizResearchDonationSample)
.filter(
BizResearchDonationSample.id == (rec.donation_sample_id or ""),
BizResearchDonationSample.del_flag == 0,
)
.first()
)
if ds:
sample_name = ds.sample_code or ""
else:
sample_name = rec.sample_code or ""
protocol_no = ""
return {"protocol_no": protocol_no, "sample_name": sample_name}
def _existing_summary(db: Session, *, rec: BizSampleReception) -> Dict[str, Any]:
tn = rec.tenant_no
qc = (
db.query(BizQcWorkOrder)
.filter(
BizQcWorkOrder.reception_id == rec.id,
BizQcWorkOrder.tenant_no == tn,
BizQcWorkOrder.del_flag == 0,
)
.first()
)
prod = (
db.query(BizProductionWorkOrder)
.filter(
BizProductionWorkOrder.reception_id == rec.id,
BizProductionWorkOrder.tenant_no == tn,
BizProductionWorkOrder.del_flag == 0,
)
.first()
)
task_count = 0
if prod:
task_count = (
db.query(BizProductionTask.id)
.filter(
BizProductionTask.work_order_id == prod.id,
BizProductionTask.tenant_no == tn,
BizProductionTask.del_flag == 0,
)
.count()
)
srr = (
db.query(BizStorageReleaseReview)
.filter(
BizStorageReleaseReview.reception_id == rec.id,
BizStorageReleaseReview.tenant_no == tn,
BizStorageReleaseReview.del_flag == 0,
)
.first()
)
return {
"receptionId": rec.id,
"tenantNo": tn,
"acceptConclusion": rec.accept_conclusion,
"receptionSource": rec.reception_source,
"qcWorkOrderNo": getattr(qc, "work_order_no", None),
"productionWorkOrderNo": getattr(prod, "work_order_no", None),
"productionTaskCount": task_count,
"storageReleaseReviewId": getattr(srr, "id", None),
"storageStatus": getattr(srr, "storage_status", None),
}
def run(
*,
sample_code: str,
lab_storage_code: str,
tenant_no: Optional[str],
apply: bool,
user_id: Optional[str],
create_dept_id: Optional[str],
) -> Dict[str, Any]:
db = SessionLocal()
try:
rec = _find_reception(
db,
sample_code=sample_code.strip(),
lab_storage_code=lab_storage_code.strip(),
tenant_no=(tenant_no or "").strip() or None,
)
before = _existing_summary(db, rec=rec)
conclusion = (rec.accept_conclusion or "").strip()
if conclusion != "js":
raise RuntimeError(
f"接收结论当前为 {conclusion!r},须先为 js(接收)再回补下游"
)
uid = user_id if user_id is not None else rec.create_by
dept = (
create_dept_id
if create_dept_id is not None
else (rec.create_dept_id or "")
)
tn = rec.tenant_no
if not apply:
db.rollback()
return {
"dryRun": True,
"before": before,
"message": (
"dry-run:未写库。确认 before 后加 --apply。"
"将补建缺失的质检/生产工单、内置任务与入库放行。"
),
}
qc = qc_wo_svc.create_work_order_from_reception(
db,
reception=rec,
tenant_no=tn,
user_id=uid,
create_dept_id=dept or "",
)
prod = prod_wo_svc.create_production_work_order_from_reception(
db,
reception=rec,
tenant_no=tn,
user_id=uid,
create_dept_id=dept or "",
)
dispatch = None
if prod is not None:
dispatch = production_task_set_svc.try_auto_dispatch_builtin_tasks_after_reception(
db,
tenant_no=tn,
user_id=uid,
create_dept_id=dept or "",
work_order=prod,
lab_storage_code=rec.lab_storage_code,
)
srr_row = (
db.query(BizStorageReleaseReview)
.filter(
BizStorageReleaseReview.reception_id == rec.id,
BizStorageReleaseReview.tenant_no == tn,
BizStorageReleaseReview.del_flag == 0,
)
.first()
)
srr_created = False
if srr_row is None:
snap = _srr_snapshot(db, rec)
srr_row = srr_svc.create_review_from_reception(
db,
reception=rec,
protocol_no=snap["protocol_no"],
sample_name=snap["sample_name"],
tenant_no=tn,
user_id=uid,
create_dept_id=dept or "",
)
srr_created = True
after_sample_reception_saved(
db, reception=rec, tenant_no=tn, user_id=uid
)
db.commit()
after = _existing_summary(db, rec=rec)
return {
"dryRun": False,
"before": before,
"after": after,
"qcWorkOrderNo": getattr(qc, "work_order_no", None),
"productionWorkOrderNo": getattr(prod, "work_order_no", None),
"dispatch": dispatch,
"storageReleaseReviewId": getattr(srr_row, "id", None),
"storageReleaseCreated": srr_created,
}
except Exception:
db.rollback()
raise
finally:
db.close()
def main(argv: Optional[list] = None) -> int:
parser = argparse.ArgumentParser(
description="补建样本接收 bj→js 后缺失的质检/生产/入库放行下游"
)
parser.add_argument("--sample-code", required=True, help="样本编码")
parser.add_argument("--lab-storage-code", required=True, help="实验室入库编码")
parser.add_argument("--tenant", default=None, help="租户编号;多租户命中时必填")
parser.add_argument(
"--apply",
action="store_true",
help="实际写库;默认仅 dry-run",
)
parser.add_argument("--user-id", default=None, help="写库 create_by;默认用接收记录")
parser.add_argument(
"--create-dept-id",
default=None,
help="写库 create_dept_id;默认用接收记录",
)
args = parser.parse_args(argv)
result = run(
sample_code=args.sample_code,
lab_storage_code=args.lab_storage_code,
tenant_no=args.tenant,
apply=bool(args.apply),
user_id=args.user_id,
create_dept_id=args.create_dept_id,
)
print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,140 @@
"""一次性造数:临床科研 / 委托加工申请单各 5 条(本地开发用)。
用法(工程 backend 目录):
.\\venv\\Scripts\\python.exe scripts\\seed_research_like_applications.py
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from app.core.database import SessionLocal # noqa: E402
from app.crud import pilot_application as crud # noqa: E402
from app.models.models import SysUser # noqa: E402
from app.models.project_management import Project # noqa: E402
TENANT = "zkxw"
COUNT = 5
CLINICAL_CATEGORIES = [
"bio_tech_clinical",
"joint_topic_declare",
"bio_pharma_rd",
"bio_tech_clinical",
"joint_topic_declare",
]
CONTRACT_CATEGORIES = ["msc", "nk", "placenta_freeze_dried", "adipose_exosome", "msc"]
def _pick_admin(db) -> tuple[str, str]:
row = (
db.query(SysUser)
.filter(SysUser.tenant_no == TENANT, SysUser.del_flag == 0, SysUser.status == "1")
.order_by(SysUser.create_time.asc())
.first()
)
if not row:
raise SystemExit("未找到可用用户")
return row.id, row.dept_id or ""
def _pick_projects(db, need: int) -> list[Project]:
rows = (
db.query(Project)
.filter(
Project.tenant_no == TENANT,
Project.del_flag == 0,
Project.leader_user_id.isnot(None),
Project.leader_user_id != "",
)
.order_by(Project.create_time.desc())
.limit(max(need, 20))
.all()
)
rows = [p for p in rows if (p.leader_user_id or "").strip()]
if not rows:
raise SystemExit("未找到已设置项目负责人的项目,请先在项目管理中维护")
# 循环复用
out: list[Project] = []
i = 0
while len(out) < need:
out.append(rows[i % len(rows)])
i += 1
return out
def _seed_one(
db,
*,
biz_type: str,
idx: int,
project: Project,
user_id: str,
dept_id: str,
category: str,
) -> dict:
label = "临床科研" if biz_type == "basic_experiment" else "委托加工"
data = {
"bizType": biz_type,
"projectId": project.id,
"researchCategory": category,
"projectTitle": f"种子{label}课题{idx:02d}",
"customerName": f"种子客户{label}{idx:02d}",
"customerContact": f"联系人{idx}",
"customerPhone": f"1380000{idx:04d}",
"applicationName": f"种子{label}申请单{idx:02d}",
"remark": "seed-script-2026-11-27",
}
return crud.create_application(
db, data=data, tenant_no=TENANT, user_id=user_id, dept_id=dept_id
)
def main() -> None:
db = SessionLocal()
try:
user_id, dept_id = _pick_admin(db)
projects = _pick_projects(db, COUNT * 2)
created = []
for i in range(COUNT):
created.append(
_seed_one(
db,
biz_type="basic_experiment",
idx=i + 1,
project=projects[i],
user_id=user_id,
dept_id=dept_id,
category=CLINICAL_CATEGORIES[i],
)
)
for i in range(COUNT):
created.append(
_seed_one(
db,
biz_type="contract_processing",
idx=i + 1,
project=projects[COUNT + i],
user_id=user_id,
dept_id=dept_id,
category=CONTRACT_CATEGORIES[i],
)
)
print(f"created={len(created)}")
for row in created:
print(
f"{row.get('bizType')}\t{row.get('applicationNo')}\t"
f"{row.get('projectTitle')}\t{row.get('approvalStatus')}\t"
f"project={row.get('projectName') or row.get('projectId')}"
)
finally:
db.close()
if __name__ == "__main__":
main()
@@ -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):
@@ -65,7 +65,8 @@ class TestBasicExperimentCreateValidation(unittest.TestCase):
)
self.assertIn("业务类型", str(ctx.exception))
def test_create_basic_experiment_requires_channel(self):
def test_create_basic_experiment_allows_missing_channel(self):
"""临床科研申请单不再要求渠道;缺项目负责人时仍会失败。"""
db = MagicMock()
data = {
"bizType": "basic_experiment",
@@ -83,7 +84,7 @@ class TestBasicExperimentCreateValidation(unittest.TestCase):
user_id="user-1",
dept_id="dept-1",
)
self.assertIn("渠道", str(ctx.exception))
self.assertNotIn("渠道", str(ctx.exception))
class TestBasicExperimentSaleSchedules(unittest.TestCase):
@@ -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,460 @@
"""编辑样本接收时同步实验室入库编码副本。"""
from datetime import datetime
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.crud import sample_reception as reception_svc
from app.models.base import Base
from app.models.models import (
BizCellProduct,
BizLabSampleProcessingExtra,
BizLabSampleProcessSupplement,
BizOutboundReleaseCell,
BizProductionTask,
BizProductionTaskInput,
BizProductionTaskOutput,
BizProductionTaskStep,
BizProductionTaskStepOutput,
BizProductionWorkOrder,
BizQcWorkOrder,
BizQcWorkOrderInspectionBatch,
BizSampleReception,
BizSampleReceptionCheckResult,
BizStorageSlotOccupancy,
)
from app.services.lab_storage_code_rename import replace_lab_code_token
def _session():
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(
engine,
tables=[
BizSampleReception.__table__,
BizSampleReceptionCheckResult.__table__,
BizProductionWorkOrder.__table__,
BizProductionTask.__table__,
BizProductionTaskInput.__table__,
BizProductionTaskStep.__table__,
BizProductionTaskStepOutput.__table__,
BizProductionTaskOutput.__table__,
BizCellProduct.__table__,
BizStorageSlotOccupancy.__table__,
BizOutboundReleaseCell.__table__,
BizQcWorkOrder.__table__,
BizQcWorkOrderInspectionBatch.__table__,
BizLabSampleProcessSupplement.__table__,
BizLabSampleProcessingExtra.__table__,
],
)
return sessionmaker(bind=engine)()
def _now():
return datetime(2026, 11, 20, 9, 33, 18)
def _seed(db):
now = _now()
db.add(
BizSampleReception(
id="recv-1",
protocol_sample_id="ps-1",
collection_protocol_id="cp-1",
reception_time=now,
accept_conclusion="js",
reception_source="cell_storage",
sample_code="ZKZX34000957",
lab_storage_code="B00001112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionWorkOrder(
id="pwo-1",
work_order_no="SC202611200001",
reception_id="recv-1",
sample_code="ZKZX34000957",
work_order_status="ywc",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionTask(
id="task-1",
task_no="T-1",
work_order_id="pwo-1",
task_name="B00001112样本处理",
description="编码B00001112",
task_status="ywc",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionTask(
id="task-other",
task_no="T-2",
work_order_id="pwo-other",
task_name="B00001112样本处理",
task_status="ywc",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionTaskInput(
id="in-1",
task_id="task-1",
input_name="B0000112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionTaskStep(
id="step-1",
task_id="task-1",
sop_content="请处理 B00001112,不要改 B000011120",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionTaskStepOutput(
id="so-1",
step_id="step-1",
output_name="脐血",
output_barcode="B0000112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProductionTaskOutput(
id="out-1",
task_id="task-1",
output_name="B00001112",
output_barcode="B00001112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizCellProduct(
id="cp-1",
product_code="B00001112",
product_name="B00001112",
batch_no="B00001112",
production_task_id="task-1",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizCellProduct(
id="cp-long",
product_code="B000011120",
product_name="其他更长编码",
production_task_id="task-other",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizStorageSlotOccupancy(
id="occ-1",
slot_id="slot-1",
item_type="cell_product",
item_id="cp-1",
item_code="B00001112",
item_name="B00001112",
occupancy_status="stored",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizOutboundReleaseCell(
id="ob-1",
material_id="mat-1",
infusion_schedule_id="inf-1",
cell_product_id="cp-1",
product_code="B00001112",
product_name="B00001112",
batch_no="B00001112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizQcWorkOrder(
id="qc-1",
work_order_no="ZJ202611200001",
reception_id="recv-1",
sample_code="ZKZX34000957",
work_order_status="ypz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizQcWorkOrderInspectionBatch(
id="batch-1",
work_order_id="qc-1",
batch_no="B1",
batch_name="B00001112-脐血",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizQcWorkOrderInspectionBatch(
id="batch-2",
work_order_id="qc-1",
batch_no="B2",
batch_name="B00001112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizLabSampleProcessSupplement(
id="sup-1",
lab_storage_code="B00001112",
payload="{}",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizLabSampleProcessingExtra(
id="extra-1",
dataset="hsc",
sample_code="B00001112",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.commit()
def test_replace_keeps_longer_code_and_chinese_suffix():
assert replace_lab_code_token("B00001112样本处理", "B00001112", "B0000112") == "B0000112样本处理"
assert replace_lab_code_token("B00001112-脐血", "B00001112", "B0000112") == "B0000112-脐血"
assert replace_lab_code_token("B000011120", "B00001112", "B0000112") == "B000011120"
assert replace_lab_code_token("B00001112", "B0000112", "B0000999") == "B00001112"
def test_edit_renames_linked_copies_and_skips_unrelated_rows(monkeypatch):
db = _session()
_seed(db)
monkeypatch.setattr(reception_svc, "_can_edit_sample_reception", lambda *args, **kwargs: True)
monkeypatch.setattr(
"app.crud.sample_reception_check_result.save_reception_check_results",
lambda *args, **kwargs: None,
)
monkeypatch.setattr(
"app.services.protocol_reception_discard_sync.after_sample_reception_saved",
lambda *args, **kwargs: None,
)
reception_svc.update_sample_reception(
db,
reception_id="recv-1",
tenant_no="tenant-a",
user_id="user-1",
reception_time=_now(),
handler_user_id=None,
handler_name="质检主管",
receive_temperature="4",
checks=[],
accept_conclusion="js",
receive_attachments=None,
remark=None,
lab_storage_code="B0000112",
)
rec = db.query(BizSampleReception).filter_by(id="recv-1").one()
task = db.query(BizProductionTask).filter_by(id="task-1").one()
other = db.query(BizProductionTask).filter_by(id="task-other").one()
step = db.query(BizProductionTaskStep).filter_by(id="step-1").one()
step_out = db.query(BizProductionTaskStepOutput).filter_by(id="so-1").one()
output = db.query(BizProductionTaskOutput).filter_by(id="out-1").one()
product = db.query(BizCellProduct).filter_by(id="cp-1").one()
longer = db.query(BizCellProduct).filter_by(id="cp-long").one()
occ = db.query(BizStorageSlotOccupancy).filter_by(id="occ-1").one()
outbound = db.query(BizOutboundReleaseCell).filter_by(id="ob-1").one()
batches = {
row.id: row.batch_name
for row in db.query(BizQcWorkOrderInspectionBatch).all()
}
wo = db.query(BizProductionWorkOrder).filter_by(id="pwo-1").one()
qc = db.query(BizQcWorkOrder).filter_by(id="qc-1").one()
supplement = db.query(BizLabSampleProcessSupplement).filter_by(id="sup-1").one()
extra = db.query(BizLabSampleProcessingExtra).filter_by(id="extra-1").one()
kept_input = db.query(BizProductionTaskInput).filter_by(id="in-1").one()
assert rec.lab_storage_code == "B0000112"
assert rec.sample_code == "ZKZX34000957"
assert task.task_name == "B0000112样本处理"
assert task.description == "编码B0000112"
assert other.task_name == "B00001112样本处理"
assert step.sop_content == "请处理 B0000112,不要改 B000011120"
assert step_out.output_barcode == "B0000112"
assert kept_input.input_name == "B0000112"
assert output.output_name == "B0000112"
assert output.output_barcode == "B0000112"
assert product.product_code == "B0000112"
assert product.batch_no == "B0000112"
assert longer.product_code == "B000011120"
assert occ.item_code == "B0000112"
assert outbound.product_code == "B0000112"
assert batches["batch-1"] == "B0000112-脐血"
assert batches["batch-2"] == "B0000112"
assert wo.sample_code == "ZKZX34000957"
assert qc.sample_code == "ZKZX34000957"
assert supplement.lab_storage_code == "B0000112"
assert extra.sample_code == "B0000112"
def test_unchanged_code_does_not_rewrite_copies(monkeypatch):
db = _session()
_seed(db)
monkeypatch.setattr(reception_svc, "_can_edit_sample_reception", lambda *args, **kwargs: True)
monkeypatch.setattr(
"app.crud.sample_reception_check_result.save_reception_check_results",
lambda *args, **kwargs: None,
)
monkeypatch.setattr(
"app.services.protocol_reception_discard_sync.after_sample_reception_saved",
lambda *args, **kwargs: None,
)
before = db.query(BizProductionTask).filter_by(id="task-1").one().update_time
reception_svc.update_sample_reception(
db,
reception_id="recv-1",
tenant_no="tenant-a",
user_id="user-1",
reception_time=_now(),
handler_user_id=None,
handler_name="质检主管",
receive_temperature="4",
checks=[],
accept_conclusion="js",
receive_attachments=None,
remark=None,
lab_storage_code="B00001112",
)
task = db.query(BizProductionTask).filter_by(id="task-1").one()
assert task.task_name == "B00001112样本处理"
assert task.update_time == before
def test_duplicate_product_code_rejects_and_keeps_old_copies(monkeypatch):
db = _session()
_seed(db)
now = _now()
db.add(
BizCellProduct(
id="cp-taken",
product_code="B0000112",
product_name="已被占用",
production_task_id="task-other",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.commit()
monkeypatch.setattr(reception_svc, "_can_edit_sample_reception", lambda *args, **kwargs: True)
monkeypatch.setattr(
"app.crud.sample_reception_check_result.save_reception_check_results",
lambda *args, **kwargs: None,
)
monkeypatch.setattr(
"app.services.protocol_reception_discard_sync.after_sample_reception_saved",
lambda *args, **kwargs: None,
)
with pytest.raises(ValueError, match="实验室入库编码已存在"):
reception_svc.update_sample_reception(
db,
reception_id="recv-1",
tenant_no="tenant-a",
user_id="user-1",
reception_time=_now(),
handler_user_id=None,
handler_name="质检主管",
receive_temperature="4",
checks=[],
accept_conclusion="js",
receive_attachments=None,
remark=None,
lab_storage_code="B0000112",
)
db.rollback()
rec = db.query(BizSampleReception).filter_by(id="recv-1").one()
task = db.query(BizProductionTask).filter_by(id="task-1").one()
assert rec.lab_storage_code == "B00001112"
assert task.task_name == "B00001112样本处理"
@@ -1,172 +0,0 @@
"""临床科研:生产确认出库细胞 / 市场交接不改细胞库存。"""
import unittest
from unittest.mock import MagicMock, patch
from fastapi import HTTPException
class TestAssertBasicExperimentOutboundWo(unittest.TestCase):
def test_rejects_non_outbound(self):
from app.crud.outbound_handover import _assert_basic_experiment_outbound_wo
wo = MagicMock(
work_order_type="inbound",
biz_type="basic_experiment",
work_order_status="jxz",
infusion_schedule_id="s1",
)
with self.assertRaises(HTTPException) as ctx:
_assert_basic_experiment_outbound_wo(wo)
self.assertEqual(ctx.exception.status_code, 400)
def test_rejects_other_biz_type(self):
from app.crud.outbound_handover import _assert_basic_experiment_outbound_wo
wo = MagicMock(
work_order_type="outbound",
biz_type="pilot_service",
work_order_status="jxz",
infusion_schedule_id="s1",
)
with self.assertRaises(HTTPException) as ctx:
_assert_basic_experiment_outbound_wo(wo)
self.assertEqual(ctx.exception.status_code, 400)
def test_ok_returns_schedule_id(self):
from app.crud.outbound_handover import _assert_basic_experiment_outbound_wo
wo = MagicMock(
work_order_type="outbound",
biz_type="basic_experiment",
work_order_status="jxz",
infusion_schedule_id="sched-1",
)
self.assertEqual(_assert_basic_experiment_outbound_wo(wo), "sched-1")
class TestSaveOutboundHandoverBasicExperiment(unittest.TestCase):
@patch("app.crud.outbound_handover.handover_inv_svc")
@patch("app.crud.outbound_handover.orm_material_svc")
@patch("app.crud.outbound_handover.get_outbound_handover")
@patch("app.crud.outbound_handover.get_handover_by_schedule")
@patch("app.crud.outbound_handover.schedule_mgmt_svc")
def test_market_keeps_previous_cells_and_skips_cell_inventory(
self,
schedule_mgmt_svc,
get_handover_by_schedule,
get_outbound_handover,
orm_material_svc,
handover_inv_svc,
):
from app.crud.outbound_handover import save_outbound_handover
schedule_mgmt_svc.get_infusion_schedule_detail.return_value = {
"bizType": "basic_experiment",
"applicationNo": "A1",
}
previous_cells = [{"cellProductId": "cp-prod", "productCode": "P1"}]
orm_material_svc.get_outbound_material.return_value = {
"cells": previous_cells,
"qcMaterials": [],
"paperMaterials": [],
"remark": "",
}
get_handover_by_schedule.return_value = None
get_outbound_handover.return_value = {"ok": True}
db = MagicMock()
sys_user = MagicMock(nick_name="张三", user_no="u1", del_flag=0)
db.query.return_value.filter.return_value.first.return_value = sys_user
save_outbound_handover(
db,
"sched-1",
outbound_material={
"cells": [{"cellProductId": "cp-market-tamper"}],
"qcMaterials": [{"materialId": "m1", "qty": 1}],
"paperMaterials": [],
},
handover={
"handoverUserId": "u1",
"receiverPerson": "李四",
"handoverTime": "2026-11-20 10:00:00",
},
tenant_no="t1",
user_id="u1",
)
handover_inv_svc.revert_handover_inventory.assert_called_once()
revert_kwargs = handover_inv_svc.revert_handover_inventory.call_args.kwargs
self.assertEqual(revert_kwargs["cell_product_ids"], [])
save_kwargs = orm_material_svc.save_outbound_material.call_args.kwargs
self.assertEqual(save_kwargs["cells"], previous_cells)
apply_kwargs = handover_inv_svc.apply_handover_inventory.call_args.kwargs
self.assertEqual(apply_kwargs["cells"], [])
self.assertEqual(apply_kwargs["qc_materials"], [{"materialId": "m1", "qty": 1}])
class TestSaveProductionDeliveryCellOutbound(unittest.TestCase):
@patch("app.crud.outbound_handover.get_production_delivery_cell_outbound")
@patch("app.crud.outbound_handover.handover_inv_svc")
@patch("app.crud.outbound_handover.orm_material_svc")
@patch("app.crud.outbound_handover.schedule_mgmt_svc")
@patch("app.crud.production_work_order.get_production_work_order")
def test_reverts_cells_only_then_applies(
self,
get_wo,
schedule_mgmt_svc,
orm_material_svc,
handover_inv_svc,
get_delivery,
):
from app.crud.outbound_handover import save_production_delivery_cell_outbound
get_wo.return_value = MagicMock(
id="wo1",
work_order_no="WO1",
work_order_type="outbound",
biz_type="basic_experiment",
work_order_status="jxz",
infusion_schedule_id="sched-1",
)
schedule_mgmt_svc.get_infusion_schedule_detail.return_value = {
"bizType": "basic_experiment"
}
orm_material_svc.get_outbound_material.return_value = {
"cells": [{"cellProductId": "old-cp"}],
"qcMaterials": [{"materialId": "m1", "qty": 2}],
"paperMaterials": [{"paperName": "出库单", "copies": 1}],
"remark": "keep",
}
get_delivery.return_value = {"cells": []}
cells = [{"cellProductId": "new-cp"}]
save_production_delivery_cell_outbound(
MagicMock(),
"wo1",
cells=cells,
tenant_no="t1",
user_id="u1",
create_dept_id="d1",
)
revert_kwargs = handover_inv_svc.revert_handover_inventory.call_args.kwargs
self.assertEqual(revert_kwargs["cell_product_ids"], ["old-cp"])
self.assertTrue(revert_kwargs["skip_materials"])
save_kwargs = orm_material_svc.save_outbound_material.call_args.kwargs
self.assertEqual(save_kwargs["cells"], cells)
self.assertEqual(save_kwargs["qc_materials"], [{"materialId": "m1", "qty": 2}])
self.assertEqual(
save_kwargs["paper_materials"], [{"paperName": "出库单", "copies": 1}]
)
apply_kwargs = handover_inv_svc.apply_handover_inventory.call_args.kwargs
self.assertEqual(apply_kwargs["cells"], cells)
self.assertEqual(apply_kwargs["qc_materials"], [])
if __name__ == "__main__":
unittest.main()
@@ -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,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,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,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,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;
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>清理本地登录状态</title>
</head>
<body>
<p>正在清理本地缓存并跳转登录页…</p>
<script>
try {
localStorage.clear()
sessionStorage.clear()
} catch (e) {}
location.replace('/#/auth/login')
</script>
</body>
</html>
+74
View File
@@ -940,6 +940,73 @@ export function fetchCustomerRelations(id: string) {
})
}
export function fetchPartnerCustomerList(params?: {
page?: number
pageSize?: number
keyword?: string
}) {
return request.get<PageResult<Api.PartnerCustomer.Item>>({
url: '/web/admin/partner-customers',
params
})
}
export function fetchCreatePartnerCustomer(data: {
customerName: string
customerContact: string
customerPhone: string
remark?: string
}) {
return request.post({ url: '/web/admin/partner-customers', params: data })
}
export function fetchUpdatePartnerCustomer(
id: string,
data: Partial<{
customerName: string
customerContact: string
customerPhone: string
remark: string
}>
) {
return request.put({ url: `/web/admin/partner-customers/${id}`, params: data })
}
export function fetchDeletePartnerCustomer(id: string) {
return request.del({ url: `/web/admin/partner-customers/${id}` })
}
export function fetchContractProcessingCategoryList(params: {
page?: number
pageSize?: number
keyword?: string
bizType: 'basic_experiment' | 'contract_processing'
}) {
return request.get<PageResult<Api.ContractProcessingCategory.Item>>({
url: '/web/admin/contract-processing-categories',
params
})
}
export function fetchCreateContractProcessingCategory(data: {
categoryName: string
remark?: string
bizType: 'basic_experiment' | 'contract_processing'
}) {
return request.post({ url: '/web/admin/contract-processing-categories', params: data })
}
export function fetchUpdateContractProcessingCategory(
id: string,
data: Partial<{ categoryName: string; remark: string }>
) {
return request.put({ url: `/web/admin/contract-processing-categories/${id}`, params: data })
}
export function fetchDeleteContractProcessingCategory(id: string) {
return request.del({ url: `/web/admin/contract-processing-categories/${id}` })
}
export function fetchCellSampleTypeList(params?: {
page?: number
pageSize?: number
@@ -2269,6 +2336,13 @@ export function voidPilotApplication(data: any) {
export function savePilotApplication(data: any) {
return request.post({ url: '/web/admin/pilot-application/save', params: data })
}
export function approvePilotApplication(data: {
id: string
approvalStatus: 'ytg' | 'yth'
approvalRemark?: string
}) {
return request.post({ url: '/web/admin/pilot-application/approve', params: data })
}
export function createBasicExperimentSaleSchedules(
applicationId: string,
data: { productLines: any[] }
@@ -316,45 +316,3 @@ export function fetchMineProductionWorkOrderTabStepCountsDeduped() {
}
return mineTabStepCountsInflight
}
/** 临床科研出库工单 — 交付出库细胞 */
export type ProductionDeliveryCellOutbound = {
workOrderId?: string
workOrderNo?: string
infusionScheduleId?: string
scheduleSummary?: {
applicationNo?: string
patientName?: string
infusionTime?: string
projectTitle?: string
customerName?: string
}
cells?: Array<{
cellProductId?: string
productCode?: string
productName?: string
productTypeName?: string
specName?: string
passage?: string
batchNo?: string
storageSlotName?: string
productStatus?: string
remark?: string
}>
}
export function fetchProductionDeliveryCellOutbound(workOrderId: string) {
return request.get<ProductionDeliveryCellOutbound>({
url: `/web/admin/production-work-orders/${workOrderId}/delivery-cell-outbound`
})
}
export function saveProductionDeliveryCellOutbound(
workOrderId: string,
data: { cells: Array<{ cellProductId: string; remark?: string }> }
) {
return request.put<ProductionDeliveryCellOutbound>({
url: `/web/admin/production-work-orders/${workOrderId}/delivery-cell-outbound`,
data
})
}
+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
+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(() =>
@@ -24,7 +24,7 @@
class="list-table inner-table"
stripe
max-height="280"
:empty-text="cellsReadonly ? '暂无生产确认的出库细胞' : '请从细胞产品库勾选'"
:empty-text="cellsReadonly ? '暂无出库细胞' : '请从细胞产品库勾选'"
>
<el-table-column type="index" label="序号" min-width="56" align="center" />
<el-table-column
@@ -63,7 +63,7 @@
</template>
</el-table-column>
<el-table-column
v-if="!cellsReadonly"
v-if="!cellsReadonly && !hideCellOps"
label="操作"
min-width="80"
align="center"
@@ -436,8 +436,10 @@
defineProps<{
/** 出库交接等需扣库存场景:仅允许选择已冻存细胞,且已选行保留可选 */
requireFrozenCellProduct?: boolean
/** 临床科研市场交接:细胞由生产确认,仅只读展示 */
/** 出库细胞只读展示(隐藏添加/删除) */
cellsReadonly?: boolean
/** 隐藏细胞行操作列(仍可显示添加) */
hideCellOps?: boolean
showCells?: boolean
showMaterials?: boolean
showPapers?: boolean
@@ -446,6 +448,7 @@
{
requireFrozenCellProduct: false,
cellsReadonly: false,
hideCellOps: false,
showCells: true,
showMaterials: true,
showPapers: true,
@@ -56,6 +56,20 @@
</el-tag>
</template>
</el-table-column>
<el-table-column
label="操作"
min-width="110"
align="center"
header-align="center"
fixed="right"
>
<template #default="{ row }">
<el-button type="primary" link @click="openLineageQc(row)">
<el-icon><View /></el-icon>
查看质检
</el-button>
</template>
</el-table-column>
</el-table>
</div>
</div>
@@ -210,11 +224,14 @@
/>
</div>
</el-dialog>
<CellProductLineageQcDialog v-model="lineageQcVisible" :product-id="lineageQcProductId" />
</div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Download, View, VideoPlay } from '@element-plus/icons-vue'
import type {
OutboundReleaseCellRow,
@@ -227,6 +244,7 @@
} from '@/utils/status-tag-registry'
import { downloadAttachmentFile } from '@/utils/download-attachment'
import { resolveCellProductSpecDisplay } from '@/utils/cell-product-spec'
import CellProductLineageQcDialog from '@/components/business/cell-product-lineage-qc-dialog/index.vue'
defineOptions({ name: 'OutboundMaterialReadonlyPanel' })
@@ -253,6 +271,8 @@
const previewVisible = ref(false)
const previewUrl = ref('')
const previewType = ref<'image' | 'video'>('image')
const lineageQcVisible = ref(false)
const lineageQcProductId = ref('')
const minioBaseUrl = (import.meta.env.VITE_MINIO_BASE_URL || '').replace(/\/$/, '')
const cells = computed<OutboundReleaseCellRow[]>(() => props.material?.cells || [])
@@ -356,6 +376,16 @@
{ fullFileUrl: attachmentFullUrl }
)
}
function openLineageQc(row: OutboundReleaseCellRow) {
const id = String(row.cellProductId || '')
if (!id) {
ElMessage.warning('缺少细胞产品信息')
return
}
lineageQcProductId.value = id
lineageQcVisible.value = true
}
</script>
<style lang="scss" scoped>
@@ -50,11 +50,12 @@
import ExceptionIllustration from './ExceptionIllustration.vue'
import { useCommon } from '@/hooks/core/useCommon'
import { useUserStore } from '@/store/modules/user'
import { resetRouteInitState } from '@/router/guards/beforeEach'
const router = useRouter()
const userStore = useUserStore()
withDefaults(
const props = withDefaults(
defineProps<{
code: string
title: string
@@ -72,7 +73,15 @@
const { homePath } = useCommon()
/** 500 页允许在后端恢复后重新拉菜单/用户信息 */
const clearInitLockIfServerError = () => {
if (props.variant === 'server-error') {
resetRouteInitState()
}
}
const goBack = () => {
clearInitLockIfServerError()
if (window.history.length > 1) {
router.back()
return
@@ -81,6 +90,7 @@
}
const backHome = () => {
clearInitLockIfServerError()
const targetHomePath = homePath.value || '/'
if (!userStore.isLogin) {
+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: true,
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'
@@ -8,11 +8,60 @@ export const CLINICAL_RESEARCH_CATEGORY_OPTIONS = [
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.map((o) => [o.value, o.label])
[
...CLINICAL_RESEARCH_CATEGORY_OPTIONS,
...CONTRACT_PROCESSING_CATEGORY_OPTIONS
].map((o) => [o.value, o.label])
) as Record<string, string>
export function clinicalResearchCategoryLabel(code?: string | null): string {
if (!code) return ''
return LABEL_MAP[code] || code
}
export type ResearchCategoryOption = { value: string; label: string }
export function researchCategoryOptionsForBiz(
bizType?: string | null,
customOptions: ResearchCategoryOption[] = []
): ResearchCategoryOption[] {
const fixedSource =
bizType === 'contract_processing'
? CONTRACT_PROCESSING_CATEGORY_OPTIONS
: CLINICAL_RESEARCH_CATEGORY_OPTIONS
const fixed = fixedSource.map((o) => ({
value: o.value,
label: o.label
}))
const seen = new Set(fixed.map((o) => o.value))
const customs = customOptions.filter((o) => o.value && !seen.has(o.value))
return [...fixed, ...customs]
}
export function isFixedContractProcessingCategory(code?: string | null): boolean {
return CONTRACT_PROCESSING_CATEGORY_OPTIONS.some((o) => o.value === code)
}
export function isFixedClinicalResearchCategory(code?: string | null): boolean {
return CLINICAL_RESEARCH_CATEGORY_OPTIONS.some((o) => o.value === code)
}
export function isFixedResearchCategory(bizType?: string | null, code?: string | null): boolean {
if (bizType === 'contract_processing') return isFixedContractProcessingCategory(code)
return isFixedClinicalResearchCategory(code)
}
+20 -3
View File
@@ -368,8 +368,6 @@ async function handleDynamicRoutes(
return
}
// 标记初始化失败,防止死循环
routeInitFailed = true
routeInitInProgress = false
// 输出详细错误信息,便于排查
@@ -377,7 +375,14 @@ async function handleDynamicRoutes(
console.error(`[RouteGuard] 错误码: ${error.code}, 消息: ${error.message}`)
}
// 跳转到 500 页面,使用 replace 避免产生历史记录
// 后端短暂不可达/超时:展示 500,但不永久锁定,便于服务恢复后点「返回首页」重试
if (isRecoverableInitError(error)) {
next({ name: 'Exception500', replace: true })
return
}
// 其它初始化失败:标记失败,防止死循环(刷新页面或重新登录可重置)
routeInitFailed = true
next({ name: 'Exception500', replace: true })
}
}
@@ -448,3 +453,15 @@ function handleRootPathRedirect(to: RouteLocationNormalized, next: NavigationGua
function isUnauthorizedError(error: unknown): boolean {
return isHttpError(error) && error.code === ApiStatus.unauthorized
}
/** 后端暂不可达类错误:允许用户在服务恢复后重试初始化 */
function isRecoverableInitError(error: unknown): boolean {
if (!isHttpError(error)) return false
return (
error.code === ApiStatus.networkError ||
error.code === ApiStatus.requestTimeout ||
error.code === ApiStatus.badGateway ||
error.code === ApiStatus.serviceUnavailable ||
error.code === ApiStatus.gatewayTimeout
)
}
+203
View File
@@ -553,6 +553,75 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
]
},
// ── 中试服务(侧栏隐藏;菜单定义保留为「隐藏」,角色授权已收回)────────
{
id: 'PIL00000000000000000000000000001',
name: 'PilotService',
path: 'pilot-service',
component: '',
meta: {
title: '中试服务',
icon: 'ri:flask-line',
keepAlive: false,
isHide: true,
roles: ['admin']
},
children: [
{
id: '80000000000000000000000000000010',
name: 'PilotApplication',
path: 'pilot-application',
component: '/pilot-service/pilot-application/index',
meta: {
title: '中试服务申请单',
keepAlive: true,
isHide: true,
menuCode: 'pilot-service:pilot-application:list'
},
props: { bizType: 'pilot_service' }
},
{
id: 'PIL00000000000000000000000000002',
name: 'PilotCheckupManagement',
path: 'checkup-management',
component: '/pilot-service/checkup-management/index',
meta: {
title: '体检管理',
keepAlive: false,
isHide: true,
menuCode: 'pilot-service:checkup-management:list'
},
props: { bizType: 'pilot_service' }
},
{
id: 'PIL00000000000000000000000000003',
name: 'PilotInfusionSchedule',
path: 'infusion-schedule-management',
component: '/pilot-service/infusion-schedule-management/index',
meta: {
title: '输注计划管理',
keepAlive: false,
isHide: true,
menuCode: 'pilot-service:infusion-schedule-management:list'
},
props: { bizType: 'pilot_service' }
},
{
id: 'PIL00000000000000000000000000004',
name: 'PilotOutboundRelease',
path: 'outbound-release-review',
component: '/pilot-service/outbound-release-review/index',
meta: {
title: '出库放行审核',
keepAlive: true,
isHide: true,
menuCode: 'pilot-service:outbound-release-review:list'
},
props: { bizType: 'pilot_service' }
}
]
},
// ── 临床科研 ──────────────────────────────────────────────────────────
{
id: 'BEX00000000000000000000000000001',
@@ -578,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',
@@ -586,6 +681,7 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
meta: {
title: '缴退费财务确认',
keepAlive: true,
isHide: true,
menuCode: 'basic-experiment:payment-confirm:list'
},
props: { bizType: 'basic_experiment' }
@@ -605,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',
@@ -917,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
@@ -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'
}
@@ -53,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,
@@ -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'
}
@@ -23,10 +23,17 @@ describe('production work order tabs — hide pilot service', () => {
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
@@ -54,7 +55,7 @@ export const PRODUCTION_WORK_ORDER_TABS: ProductionWorkOrderTabConfig[] = [
workOrderType: 'outbound',
bizType: 'pilot_service',
listLayout: 'standalone',
/** 客户已下线中试业务:侧栏不展示,路由 key 保留供历史解析 */
/** 与市场中试菜单一致:侧栏 Tab 隐藏,保留 key 供历史工单解析 */
hidden: true
},
{
@@ -65,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: '临床应用生产',
@@ -129,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'
}
@@ -140,7 +150,7 @@ 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 '工单号/申请单号/申请单名称/患者'
+1 -1
View File
@@ -75,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,
@@ -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'
}
@@ -24,10 +24,17 @@ describe('qc work order tabs — hide pilot service', () => {
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'))
})
})
+16 -4
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
@@ -54,7 +55,7 @@ export const QC_WORK_ORDER_TABS: QcWorkOrderTabConfig[] = [
workOrderType: 'outbound',
bizType: 'pilot_service',
listLayout: 'outbound-grouped',
/** 客户已下线中试业务:侧栏不展示,路由 key 保留供历史解析 */
/** 与市场中试菜单一致:侧栏 Tab 隐藏,保留 key 供历史工单解析 */
hidden: true
},
{
@@ -65,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: '临床应用质检',
@@ -127,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'
}
@@ -142,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 '工单号/申请单号/申请单名称/患者'
@@ -157,7 +167,9 @@ 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 '创建时间'
}
+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>
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff. Show more