Compare commits

...
Author SHA1 Message Date
zlwuandCursor ac9db561a4 fix(web-admin): 补齐捐赠查看操作日志接线并保留审核动作语义
修复 DonationViewDialog 缺失的操作日志状态与加载调用,清理误插入的重置语句,并避免显式 audit 动作被状态映射覆盖。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 12:15:10 +08:00
zlwuandCursor 4a12d92631 feat(protocol): 记录协议单操作前后快照便于责任追溯
为细胞存储与科研捐赠协议增加 append-only 操作日志,覆盖 Web/小程序 create/update/delete/状态类动作,并在查看弹窗与移动详情提供操作日志入口(Issue #24)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 12:11:34 +08:00
cykj 1fb25f4fc2 Merge pull request 'fix(backend): 协议作废与样本接收废弃双向联动' (#40) from codex/issue-31-discard-sync-d7063ae6ff97 into V2.0
fix(backend): 协议作废与样本接收废弃双向联动

Merge PR #40 for issue #31.
2026-11-05 03:44:15 +00:00
zlwuandCursor e2e9059c17 fix(backend): sync protocol void with sample reception discard
When a cell-storage or research-donation protocol is voided, mark all
related sample receptions as discarded; when every sample is discarded,
auto-void the protocol as 实验室废弃 (sysfq). Covers issue #31.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 11:37:58 +08:00
cykj 65aaaae885 Merge pull request 'fix(web-admin): 样本接收是否接收选项拒收改为废弃' (#39) from codex/issue-27-reject-to-discard-f4470ba481b0 into V2.0
Merge pull request 'fix(web-admin): 样本接收是否接收选项拒收改为废弃' (#39) from codex/issue-27-reject-to-discard-f4470ba481b0 into V2.0
2026-11-05 03:14:35 +00:00
zlwuandCursor 71051461a2 fix(web-admin): 样本接收「是否接收」选项拒收改为废弃
质检样本接收登记弹窗与结论标签文案对齐工单 #27,取值 bj 不变。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 11:08:18 +08:00
zlwuandCursor 25c12ad4ff chore(agents): point Figma config to web and mobile design systems
Replace the demo Figma reference with the confirmed web/mobile authority files and status notes so agent UI work follows the current design systems.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 11:00:53 +08:00
zlwu 5b440df17e Merge origin/V2.0: include list column order fix from #37 2026-11-05 10:55:34 +08:00
cykj 67846493fa Merge pull request 'fix(web-admin): 列表所属项目/项目组列移到序号之后' (#37) from codex/issue-34-list-col-order-20662a540e4e into V2.0
fix(web-admin): 列表所属项目/项目组列移到序号之后 (#37)

Refs: #34
2026-11-05 02:55:07 +00:00
zlwu 81154f4c94 Merge remote-tracking branch 'origin/V2.0' into V2.0 2026-11-05 10:50:41 +08:00
cykj 125398a3f5 Merge pull request 'fix(web): 加宽项目组新增编辑弹窗并调整字段布局' (#36) from codex/issue-33-team-dialog into V2.0 2026-11-05 02:49:53 +00:00
zlwu af730ad050 Merge remote-tracking branch 'origin/V2.0' into codex/issue-33-team-dialog 2026-11-05 10:48:32 +08:00
zlwu 2e21884d65 Merge remote-tracking branch 'origin/V2.0' into V2.0 2026-11-05 10:40:34 +08:00
cykj 6292badf8e Merge pull request 'fix(oa): 审批单 PDF 补齐评论、提及及附件链接' (#35) from codex/issue-30-oa-print-comments into V2.0
User explicitly requested merging issue #30 before user testing. Acceptance remains pending; keep issue open.
2026-11-05 02:40:21 +00:00
zlwu 5a55e9f574 fix(web): widen project team edit dialogs and give multi-select fields full rows 2026-11-05 10:35:08 +08:00
zlwu a511004812 fix(oa): include discussion comments and attachment links in approval PDFs
Merge discussion comments into the existing printed approval flow on Web and mobile OA, preserving detail timeline order and hiding revoked content. Include mentions and absolute attachment URLs, and add PDF link annotations so rasterized exports retain usable links. Add regression tests for ordering, attachments, mentions and revoked comments. Related to Gitea issue #30.
2026-11-05 10:27:39 +08:00
zlwu f1b4a5ce26 fix(web-admin): place project columns after index in lists
Move 所属项目/项目组 after selection and serial-number columns so multi-select and index stay leftmost across affected business lists.
2026-11-05 10:26:59 +08:00
zlwuandCursor 01fef051da chore(cursor): enable the Figma plugin
The screen baseline is drawn in the shared Figma file, so the workspace plugin needs to stay enabled.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 06:45:27 +08:00
cykj 7ac2ff282c Merge pull request 'feat(project): add a standalone presign statistics column' (#22) from codex/issue-13-project-statistics into V2.0 2026-11-04 06:55:22 +00:00
40 changed files with 2405 additions and 59 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{
"plugins": {
"figma": {
"enabled": true
}
}
}
+70
View File
@@ -16,6 +16,7 @@ from app.core.response import error_response, success_response
from app.core.utils import parse_datetime
from app.crud import collection_protocol as cp_svc
from app.crud import collection_region as region_svc
from app.crud import protocol_operation_log as op_log
from app.models.models import (
BizCollectionProtocol,
BizProtocolPartyCustomer,
@@ -442,6 +443,16 @@ async def create_collection_protocol(
commit=True,
)
db.refresh(obj)
op_log.record_cell_operation(
db,
protocol_id=protocol_id,
action=op_log.ACTION_CREATE,
tenant_no=tenant_no,
user_id=user_id,
client_channel=op_log.CHANNEL_WEB,
before=None,
)
db.commit()
schedule_sample_collect_notify(
tenant_no=tenant_no,
protocol_id=protocol_id,
@@ -510,6 +521,9 @@ async def update_collection_protocol(
before_codes = sample_codes_from_orm_rows(
cp_svc.list_samples(db, protocol_id, tenant_no)
)
before_snap = op_log.snapshot_cell_protocol(
db, protocol_id=protocol_id, tenant_no=tenant_no
)
obj = cp_svc.update_collection_protocol(
db,
protocol_id,
@@ -540,6 +554,16 @@ async def update_collection_protocol(
commit=True,
)
db.refresh(obj)
op_log.record_cell_operation(
db,
protocol_id=protocol_id,
action=op_log.ACTION_UPDATE,
tenant_no=tenant_no,
user_id=user_id,
client_channel=op_log.CHANNEL_WEB,
before=before_snap,
)
db.commit()
schedule_sample_collect_notify(
tenant_no=tenant_no,
protocol_id=protocol_id,
@@ -568,12 +592,26 @@ async def delete_collection_protocol(
if not _protocol_accessible(db, protocol_id, tenant_no, user):
return error_response(404, "协议单不存在或无权操作")
try:
before_snap = op_log.snapshot_cell_protocol(
db, protocol_id=protocol_id, tenant_no=tenant_no
)
cp_svc.soft_delete_collection_protocol(
db,
protocol_id,
tenant_no=tenant_no,
user_id=user_id,
)
op_log.record_cell_operation(
db,
protocol_id=protocol_id,
action=op_log.ACTION_DELETE,
tenant_no=tenant_no,
user_id=user_id,
client_channel=op_log.CHANNEL_WEB,
before=before_snap,
after=None,
)
db.commit()
return success_response(None, message="删除成功")
except ValueError as e:
return error_response(400, str(e))
@@ -627,6 +665,9 @@ async def submit_collection_protocol_audit(
if not _protocol_accessible(db, protocol_id, tenant_no, user):
return error_response(403, "无权访问该协议或协议不存在")
try:
before_snap = op_log.snapshot_cell_protocol(
db, protocol_id=protocol_id, tenant_no=tenant_no
)
cp_svc.create_audit(
db,
collection_protocol_id=protocol_id,
@@ -635,6 +676,17 @@ async def submit_collection_protocol_audit(
tenant_no=tenant_no,
user_id=user.get("user_id"),
)
op_log.record_cell_operation(
db,
protocol_id=protocol_id,
action=op_log.ACTION_AUDIT,
tenant_no=tenant_no,
user_id=user.get("user_id"),
client_channel=op_log.CHANNEL_WEB,
before=before_snap,
remark=(body.audit_remark or "").strip() or None,
)
db.commit()
p = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == protocol_id).first()
pn = (p.protocol_no if p else "") or ""
return success_response({"protocolNo": pn}, message="审核已提交")
@@ -659,6 +711,24 @@ async def list_collection_protocol_status_changes(
return success_response({"list": items})
@router.get("/collection-protocols/{protocol_id}/operation-logs")
async def list_collection_protocol_operation_logs(
protocol_id: str,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
tenant_no = _get_tenant_no(db, user)
if not _protocol_accessible(db, protocol_id, tenant_no, user):
return error_response(403, "无权访问该协议或协议不存在")
items = op_log.list_protocol_operation_logs(
db,
biz_type=op_log.BIZ_CELL,
biz_id=protocol_id,
tenant_no=tenant_no,
)
return success_response({"list": items})
# ---------------------------------------------------------------------------
# 收款确认
# ---------------------------------------------------------------------------
+116 -1
View File
@@ -12,6 +12,7 @@ from app.core.database import get_db
from app.core.menu_guard import require_admin_or_super_admin
from app.core.response import error_response, success_response
from app.crud import research_donation as rd_svc
from app.crud import protocol_operation_log as op_log
from app.models.models import SysUser
from app.models.research_donation import BizResearchDonation
from app.services.sample_collect_wx_notify import (
@@ -272,6 +273,16 @@ async def create_research_donation(
tenant_no=tenant_no,
user_id=user_id,
)
op_log.record_donation_operation(
db,
donation_id=obj.id,
action=op_log.ACTION_CREATE,
tenant_no=tenant_no,
user_id=user_id,
client_channel=op_log.CHANNEL_WEB,
before=None,
)
db.commit()
schedule_sample_collect_notify(
tenant_no=tenant_no,
protocol_id=obj.id,
@@ -312,6 +323,9 @@ async def update_research_donation(
before_codes = sample_codes_from_orm_rows(
rd_svc.list_samples(db, donation_id, tenant_no)
)
before_snap = op_log.snapshot_donation(
db, donation_id=donation_id, tenant_no=tenant_no
)
unset_fields = body.model_dump(exclude_unset=True)
obj = rd_svc.update_donation(
db,
@@ -320,6 +334,16 @@ async def update_research_donation(
tenant_no=tenant_no,
user_id=user_id,
)
op_log.record_donation_operation(
db,
donation_id=donation_id,
action=op_log.ACTION_UPDATE,
tenant_no=tenant_no,
user_id=user_id,
client_channel=op_log.CHANNEL_WEB,
before=before_snap,
)
db.commit()
schedule_sample_collect_notify(
tenant_no=tenant_no,
protocol_id=obj.id,
@@ -353,12 +377,26 @@ async def delete_research_donation(
tenant_no = _get_tenant_no(db, user)
user_id = _get_current_user_id(user)
try:
before_snap = op_log.snapshot_donation(
db, donation_id=donation_id, tenant_no=tenant_no
)
rd_svc.delete_donation(
db,
donation_id,
tenant_no=tenant_no,
user_id=user_id,
)
op_log.record_donation_operation(
db,
donation_id=donation_id,
action=op_log.ACTION_DELETE,
tenant_no=tenant_no,
user_id=user_id,
client_channel=op_log.CHANNEL_WEB,
before=before_snap,
after=None,
)
db.commit()
return success_response(None, message="删除成功")
except ValueError as e:
return error_response(400, str(e))
@@ -403,6 +441,9 @@ async def submit_donation_audit(
):
tenant_no = _get_tenant_no(db, user)
try:
before_snap = op_log.snapshot_donation(
db, donation_id=donation_id, tenant_no=tenant_no
)
rd_svc.submit_audit(
db,
donation_id,
@@ -411,6 +452,17 @@ async def submit_donation_audit(
user_id=user.get("user_id"),
tenant_no=tenant_no,
)
op_log.record_donation_operation(
db,
donation_id=donation_id,
action=op_log.ACTION_AUDIT,
tenant_no=tenant_no,
user_id=user.get("user_id"),
client_channel=op_log.CHANNEL_WEB,
before=before_snap,
remark=(body.audit_remark or "").strip() or None,
)
db.commit()
d = (
db.query(BizResearchDonation)
.filter(BizResearchDonation.id == donation_id)
@@ -437,6 +489,9 @@ async def change_donation_status(
tenant_no = _get_tenant_no(db, user)
user_id = _get_current_user_id(user)
try:
before_snap = op_log.snapshot_donation(
db, donation_id=donation_id, tenant_no=tenant_no
)
obj = rd_svc.change_status(
db,
donation_id,
@@ -447,6 +502,17 @@ async def change_donation_status(
user_id=user_id,
tenant_no=tenant_no,
)
op_log.record_donation_operation(
db,
donation_id=donation_id,
action=op_log.ACTION_UPDATE,
tenant_no=tenant_no,
user_id=user_id,
client_channel=op_log.CHANNEL_WEB,
before=before_snap,
remark=(body.desc or "").strip() or None,
)
db.commit()
return success_response(
rd_svc._donation_to_dict(obj, db, tenant_no),
message="状态变更成功",
@@ -481,6 +547,33 @@ async def list_research_donation_status_changes(
return success_response({"list": items})
@router.get("/research-donations/{donation_id}/operation-logs")
async def list_research_donation_operation_logs(
donation_id: str,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
tenant_no = _get_tenant_no(db, user)
obj = (
db.query(BizResearchDonation)
.filter(
BizResearchDonation.id == donation_id,
BizResearchDonation.tenant_no == tenant_no,
BizResearchDonation.del_flag == 0,
)
.first()
)
if not obj:
return error_response(404, "捐赠单不存在")
items = op_log.list_protocol_operation_logs(
db,
biz_type=op_log.BIZ_DONATION,
biz_id=donation_id,
tenant_no=tenant_no,
)
return success_response({"list": items})
# ---------------------------------------------------------------------------
# 10. 细胞存储 → 科研捐赠
# ---------------------------------------------------------------------------
@@ -496,12 +589,35 @@ async def convert_from_storage(
user_id = _get_current_user_id(user)
try:
accessible_order(db, BizCollectionProtocol, tenant_no, user, body.protocol_id, lock=True)
before_cell = op_log.snapshot_cell_protocol(
db, protocol_id=body.protocol_id, tenant_no=tenant_no
)
obj = rd_svc.convert_from_storage(
db,
body.protocol_id,
tenant_no=tenant_no,
user_id=user_id,
)
op_log.record_cell_operation(
db,
protocol_id=body.protocol_id,
action=op_log.ACTION_TO_RESEARCH,
tenant_no=tenant_no,
user_id=user_id,
client_channel=op_log.CHANNEL_WEB,
before=before_cell,
)
op_log.record_donation_operation(
db,
donation_id=obj.id,
action=op_log.ACTION_CREATE,
tenant_no=tenant_no,
user_id=user_id,
client_channel=op_log.CHANNEL_WEB,
before=None,
remark="convert_from_storage",
)
db.commit()
return success_response(
rd_svc._donation_to_dict(obj, db, tenant_no),
message="转换成功",
@@ -509,7 +625,6 @@ async def convert_from_storage(
except ValueError as e:
return error_response(400, str(e))
# ---------------------------------------------------------------------------
# 11. 科研捐赠 → 细胞存储
# ---------------------------------------------------------------------------
@@ -53,6 +53,7 @@ _DONATION_STATUS_LABELS = {
_VOID_TYPE_FALLBACK_LABELS = {
"khhc": "客户毁存",
"jcbhg": "检测不合格",
"sysfq": "实验室废弃",
}
# 非法来源状态视为终态,不允许再转出
+14
View File
@@ -2642,6 +2642,7 @@ def update_collection_protocol(
source_presign_order_id: Optional[str] = None,
remark: Optional[str] = None,
commit: bool = True,
sync_reception_discard: bool = True,
) -> BizCollectionProtocol:
obj = get_collection_protocol(
db, protocol_id, tenant_no, scope_collector_user_id=scope_collector_user_id
@@ -2650,6 +2651,7 @@ def update_collection_protocol(
raise ValueError("协议单不存在或无权操作")
from_status = (obj.protocol_status or "").strip()
status_log_payload: Optional[Dict[str, Any]] = None
voided_now = False
if protocol_no is not None:
pn = protocol_no.strip()
if pn != (obj.protocol_no or ""):
@@ -2660,6 +2662,8 @@ def update_collection_protocol(
next_status = protocol_status.strip()
assert_protocol_status_transition(obj.protocol_status or "", next_status, kind="protocol")
obj.protocol_status = next_status
if next_status == "yzf" and from_status != "yzf":
voided_now = True
if next_status == "yzf" and void_time is not None:
if void_type is None or not str(void_type).strip():
raise ValueError("请选择作废类型")
@@ -2749,6 +2753,16 @@ def update_collection_protocol(
tenant_no=tenant_no,
user_id=user_id,
)
if voided_now and sync_reception_discard:
from app.services.protocol_reception_discard_sync import after_protocol_voided
after_protocol_voided(
db,
source="cell_storage",
protocol_id=obj.id,
tenant_no=tenant_no,
user_id=user_id,
)
if commit:
db.commit()
db.refresh(obj)
+352
View File
@@ -0,0 +1,352 @@
"""协议单操作过程日志(Issue #24)。
记录细胞存储 / 科研捐赠协议在 Web、小程序端的 create/update/delete/状态类动作,
保存操作前、动作、操作后快照,供责任归属追溯。append-only,不 commit。
"""
from __future__ import annotations
import json
from datetime import datetime
from typing import Any, Dict, List, Optional
from sqlalchemy.orm import Session
from app.core.utils import generate_uuid
from app.models.models import BizCollectionProtocol, BizProtocolOperationLog, SysUser
BIZ_CELL = "cell_storage"
BIZ_DONATION = "research_donation"
ACTION_CREATE = "create"
ACTION_UPDATE = "update"
ACTION_DELETE = "delete"
ACTION_VOID = "void"
ACTION_ACTIVATE = "activate"
ACTION_EXPIRE = "expire"
ACTION_TO_RESEARCH = "to_research"
ACTION_TO_STORAGE = "to_storage"
ACTION_AUDIT = "audit"
CHANNEL_WEB = "web"
CHANNEL_MINI = "mini"
_STATUS_ACTION_MAP = {
"sxz": ACTION_ACTIVATE,
"ygq": ACTION_EXPIRE,
"yzf": ACTION_VOID,
"zyk": ACTION_TO_RESEARCH,
"zcck": ACTION_TO_STORAGE,
}
def _json_dumps(payload: Optional[Dict[str, Any]]) -> Optional[str]:
if payload is None:
return None
return json.dumps(payload, ensure_ascii=False, default=str, separators=(",", ":"))
def _json_loads(raw: Optional[str]) -> Optional[Dict[str, Any]]:
if not raw:
return None
try:
value = json.loads(raw)
except (TypeError, ValueError, json.JSONDecodeError):
return None
return value if isinstance(value, dict) else None
def resolve_action_from_status(
*,
default_action: str,
before_status: Optional[str] = None,
after_status: Optional[str] = None,
) -> str:
"""仅对 update 默认动作按状态流转细化;显式动作(create/delete/audit 等)保持原值。"""
action = (default_action or "").strip() or ACTION_UPDATE
if action != ACTION_UPDATE:
return action
before = (before_status or "").strip()
after = (after_status or "").strip()
if after and after != before and after in _STATUS_ACTION_MAP:
return _STATUS_ACTION_MAP[after]
return action
def _operator_name(db: Session, user_id: Optional[str]) -> str:
uid = (user_id or "").strip()
if not uid:
return ""
row = db.query(SysUser.nick_name).filter(SysUser.id == uid).first()
if not row:
return ""
return (row[0] or "").strip()
def snapshot_cell_protocol(
db: Session,
*,
protocol_id: str,
tenant_no: str,
include_deleted: bool = False,
) -> Optional[Dict[str, Any]]:
"""采集协议主表 + 当事人 + 采集信息 + 样本快照。"""
from app.crud import collection_protocol as cell_crud
pid = (protocol_id or "").strip()
if not pid:
return None
q = db.query(BizCollectionProtocol).filter(
BizCollectionProtocol.id == pid,
BizCollectionProtocol.tenant_no == tenant_no,
)
if not include_deleted:
q = q.filter(BizCollectionProtocol.del_flag == 0)
row = q.first()
if not row:
return None
party = cell_crud.get_party_customer(db, pid, tenant_no)
collection = cell_crud.get_collection_info(db, pid, tenant_no)
samples = cell_crud.list_samples(db, pid, tenant_no)
return {
"protocol": cell_crud._protocol_to_dict(row, db),
"partyCustomer": cell_crud._party_customer_to_dict(party) if party else None,
"collectionInfo": cell_crud._collection_info_to_dict(collection)
if collection
else None,
"samples": [cell_crud._sample_to_dict(s) for s in samples],
}
def snapshot_donation(
db: Session,
*,
donation_id: str,
tenant_no: str,
include_deleted: bool = False,
) -> Optional[Dict[str, Any]]:
"""科研捐赠主表 + 当事人 + 采集信息 + 样本快照。"""
from app.crud import research_donation as donation_crud
from app.models.research_donation import BizResearchDonation
did = (donation_id or "").strip()
if not did:
return None
q = db.query(BizResearchDonation).filter(
BizResearchDonation.id == did,
BizResearchDonation.tenant_no == tenant_no,
)
if not include_deleted:
q = q.filter(BizResearchDonation.del_flag == 0)
row = q.first()
if not row:
return None
party = donation_crud.get_party(db, did, tenant_no)
collection = donation_crud.get_collection(db, did, tenant_no)
samples = donation_crud.list_samples(db, did, tenant_no)
return {
"donation": donation_crud._donation_to_dict(row, db, tenant_no),
"party": donation_crud._party_to_dict(party) if party else None,
"collection": donation_crud._collection_to_dict(collection)
if collection
else None,
"samples": [donation_crud._sample_to_dict(s) for s in samples],
}
def _protocol_no_from_snapshot(
biz_type: str, snapshot: Optional[Dict[str, Any]]
) -> Optional[str]:
if not snapshot:
return None
if biz_type == BIZ_CELL:
protocol = snapshot.get("protocol") or {}
return (protocol.get("protocolNo") or "").strip() or None
donation = snapshot.get("donation") or {}
return (donation.get("donationNo") or "").strip() or None
def _status_from_snapshot(
biz_type: str, snapshot: Optional[Dict[str, Any]]
) -> Optional[str]:
if not snapshot:
return None
if biz_type == BIZ_CELL:
protocol = snapshot.get("protocol") or {}
return (protocol.get("protocolStatus") or "").strip() or None
donation = snapshot.get("donation") or {}
return (donation.get("donationStatus") or "").strip() or None
def append_protocol_operation_log(
db: Session,
*,
biz_type: str,
biz_id: str,
action: str,
client_channel: str = CHANNEL_WEB,
before: Optional[Dict[str, Any]] = None,
after: Optional[Dict[str, Any]] = None,
tenant_no: str,
user_id: Optional[str] = None,
operator_user_name: Optional[str] = None,
operate_time: Optional[datetime] = None,
remark: Optional[str] = None,
create_dept_id: str = "",
) -> BizProtocolOperationLog:
"""追加一条操作日志(不 commit)。"""
now = operate_time or datetime.now()
name = (operator_user_name or "").strip() or _operator_name(db, user_id)
protocol_no = _protocol_no_from_snapshot(biz_type, after) or _protocol_no_from_snapshot(
biz_type, before
)
obj = BizProtocolOperationLog(
id=generate_uuid(),
biz_type=(biz_type or "").strip(),
biz_id=(biz_id or "").strip(),
protocol_no=protocol_no,
action=(action or "").strip() or ACTION_UPDATE,
client_channel=(client_channel or CHANNEL_WEB).strip() or CHANNEL_WEB,
before_json=_json_dumps(before),
after_json=_json_dumps(after),
operator_user_id=(user_id or "").strip() or None,
operator_user_name=name or None,
operate_time=now,
tenant_no=tenant_no,
order_num=0,
remark=(remark or "").strip() or None,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(obj)
return obj
def record_cell_operation(
db: Session,
*,
protocol_id: str,
action: str,
tenant_no: str,
user_id: Optional[str] = None,
client_channel: str = CHANNEL_WEB,
before: Optional[Dict[str, Any]] = None,
after: Optional[Dict[str, Any]] = None,
remark: Optional[str] = None,
create_dept_id: str = "",
) -> Optional[BizProtocolOperationLog]:
"""记录细胞存储协议操作;after 缺省时按当前库态补齐。"""
pid = (protocol_id or "").strip()
if not pid:
return None
after_snap = after
if after_snap is None and action != ACTION_DELETE:
after_snap = snapshot_cell_protocol(db, protocol_id=pid, tenant_no=tenant_no)
resolved = resolve_action_from_status(
default_action=action,
before_status=_status_from_snapshot(BIZ_CELL, before),
after_status=_status_from_snapshot(BIZ_CELL, after_snap),
)
return append_protocol_operation_log(
db,
biz_type=BIZ_CELL,
biz_id=pid,
action=resolved,
client_channel=client_channel,
before=before,
after=after_snap,
tenant_no=tenant_no,
user_id=user_id,
remark=remark,
create_dept_id=create_dept_id,
)
def record_donation_operation(
db: Session,
*,
donation_id: str,
action: str,
tenant_no: str,
user_id: Optional[str] = None,
client_channel: str = CHANNEL_WEB,
before: Optional[Dict[str, Any]] = None,
after: Optional[Dict[str, Any]] = None,
remark: Optional[str] = None,
create_dept_id: str = "",
) -> Optional[BizProtocolOperationLog]:
"""记录科研捐赠协议操作;after 缺省时按当前库态补齐。"""
did = (donation_id or "").strip()
if not did:
return None
after_snap = after
if after_snap is None and action != ACTION_DELETE:
after_snap = snapshot_donation(db, donation_id=did, tenant_no=tenant_no)
resolved = resolve_action_from_status(
default_action=action,
before_status=_status_from_snapshot(BIZ_DONATION, before),
after_status=_status_from_snapshot(BIZ_DONATION, after_snap),
)
return append_protocol_operation_log(
db,
biz_type=BIZ_DONATION,
biz_id=did,
action=resolved,
client_channel=client_channel,
before=before,
after=after_snap,
tenant_no=tenant_no,
user_id=user_id,
remark=remark,
create_dept_id=create_dept_id,
)
def _row_to_dict(row: BizProtocolOperationLog) -> Dict[str, Any]:
return {
"id": row.id,
"bizType": row.biz_type,
"bizId": row.biz_id,
"protocolNo": row.protocol_no or "",
"action": row.action,
"clientChannel": row.client_channel or CHANNEL_WEB,
"before": _json_loads(row.before_json),
"after": _json_loads(row.after_json),
"operatorUserId": row.operator_user_id or "",
"operatorUserName": row.operator_user_name or "",
"operateTime": row.operate_time.strftime("%Y-%m-%d %H:%M:%S")
if row.operate_time
else "",
"tenantNo": row.tenant_no,
"remark": row.remark or "",
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S")
if row.create_time
else "",
}
def list_protocol_operation_logs(
db: Session,
*,
biz_type: str,
biz_id: str,
tenant_no: str,
) -> List[Dict[str, Any]]:
rows = (
db.query(BizProtocolOperationLog)
.filter(
BizProtocolOperationLog.biz_type == (biz_type or "").strip(),
BizProtocolOperationLog.biz_id == (biz_id or "").strip(),
BizProtocolOperationLog.tenant_no == tenant_no,
BizProtocolOperationLog.del_flag == 0,
)
.order_by(
BizProtocolOperationLog.operate_time.asc(),
BizProtocolOperationLog.create_time.asc(),
)
.all()
)
return [_row_to_dict(r) for r in rows]
+10
View File
@@ -1686,6 +1686,16 @@ def change_status(
)
db.add(obj)
if ns == "yzf" and (current or "").strip() != "yzf":
from app.services.protocol_reception_discard_sync import after_protocol_voided
after_protocol_voided(
db,
source="research_donation",
protocol_id=obj.id,
tenant_no=tenant_no,
user_id=user_id,
)
db.commit()
db.refresh(obj)
return obj
+12
View File
@@ -1033,6 +1033,12 @@ def create_sample_reception(
user_id=user_id,
create_dept_id=create_dept_id or "",
)
if conclusion == "bj":
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
after_sample_reception_saved(
db, reception=obj, tenant_no=tenant_no, user_id=user_id
)
db.commit()
db.refresh(obj)
return obj
@@ -1151,6 +1157,12 @@ def update_sample_reception(
)
check_result_svc.sync_legacy_columns_from_results(db, rec, saved_rows)
db.add(rec)
if conclusion == "bj":
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
after_sample_reception_saved(
db, reception=rec, tenant_no=tenant_no, user_id=user_id
)
db.commit()
db.refresh(rec)
return rec
+27
View File
@@ -1149,6 +1149,33 @@ class BizProtocolStatusChange(Base):
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizProtocolOperationLog(Base):
"""协议单操作过程日志 biz_protocol_operation_log(Issue #24)"""
__tablename__ = "biz_protocol_operation_log"
id = Column(String(64), primary_key=True, comment="主键ID")
biz_type = Column(String(32), nullable=False, comment="业务类型 cell_storage/research_donation")
biz_id = Column(String(64), nullable=False, comment="协议单或捐赠单ID")
protocol_no = Column(String(64), nullable=True, comment="协议/捐赠编号快照")
action = Column(String(32), nullable=False, comment="动作 create/update/delete/void/...")
client_channel = Column(String(16), nullable=False, default="web", comment="来源端 web/mini")
before_json = Column(Text, nullable=True, comment="操作前协议信息JSON")
after_json = Column(Text, nullable=True, comment="操作后协议信息JSON")
operator_user_id = Column(String(64), nullable=True, comment="操作人用户ID")
operator_user_name = Column(String(64), nullable=True, comment="操作人姓名快照")
operate_time = Column(DateTime, 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 BizStorageReleaseReview(Base):
"""入库放行审核 biz_storage_release_review"""
+91
View File
@@ -22,6 +22,7 @@ from app.core.protocol_status_display import (
resolve_void_type_label,
)
from app.crud import collection_protocol as cell_crud
from app.crud import protocol_operation_log as op_log
from app.crud import protocol_sample_payment as psp_crud
from app.crud import research_donation as donation_crud
from app.crud import sample_freight as sample_freight_crud
@@ -1531,6 +1532,12 @@ def _cell_detail(db: Session, row: BizCollectionProtocol, tenant_no: str) -> dic
collection_protocol_id=row.id,
tenant_no=tenant_no,
),
'operationLogs': op_log.list_protocol_operation_logs(
db,
biz_type=op_log.BIZ_CELL,
biz_id=row.id,
tenant_no=tenant_no,
),
'attachments': {
'protocolAttachments': row.protocol_attachments or '',
'consentFormUrls': row.consent_form_urls or '',
@@ -1571,6 +1578,12 @@ def _donation_detail(
research_donation_id=row.id,
tenant_no=tenant_no,
),
'operationLogs': op_log.list_protocol_operation_logs(
db,
biz_type=op_log.BIZ_DONATION,
biz_id=row.id,
tenant_no=tenant_no,
),
'attachments': {
'consentFormUrls': basic.get('consentFormUrls') or '',
'attachmentUrls': basic.get('attachmentUrls') or '',
@@ -1841,17 +1854,45 @@ def delete_protocol(
_lock_cell_protocol_access(
db, protocol_id, ctx, user_info=user_info
)
before_snap = op_log.snapshot_cell_protocol(
db, protocol_id=protocol_id, tenant_no=ctx.tenant_no
)
cell_crud.soft_delete_collection_protocol(
db, protocol_id, ctx.tenant_no, user_id=ctx.user_id
)
op_log.record_cell_operation(
db,
protocol_id=protocol_id,
action=op_log.ACTION_DELETE,
tenant_no=ctx.tenant_no,
user_id=ctx.user_id,
client_channel=op_log.CHANNEL_MINI,
before=before_snap,
after=None,
)
db.commit()
return
if source == SOURCE_DONATION:
_lock_donation_access(
db, protocol_id, ctx, user_info=user_info
)
before_snap = op_log.snapshot_donation(
db, donation_id=protocol_id, tenant_no=ctx.tenant_no
)
donation_crud.delete_donation(
db, protocol_id, ctx.tenant_no, user_id=ctx.user_id
)
op_log.record_donation_operation(
db,
donation_id=protocol_id,
action=op_log.ACTION_DELETE,
tenant_no=ctx.tenant_no,
user_id=ctx.user_id,
client_channel=op_log.CHANNEL_MINI,
before=before_snap,
after=None,
)
db.commit()
return
raise ValueError('不支持的协议来源')
@@ -1958,6 +1999,17 @@ def create_protocol(
assert_cell_protocol_access(db, row.id, ctx, user_info=user_info)
db.commit()
db.refresh(row)
op_log.record_cell_operation(
db,
protocol_id=row.id,
action=op_log.ACTION_CREATE,
tenant_no=ctx.tenant_no,
user_id=ctx.user_id,
client_channel=op_log.CHANNEL_MINI,
before=None,
create_dept_id=dept_id,
)
db.commit()
schedule_sample_collect_notify(
tenant_no=ctx.tenant_no,
protocol_id=row.id,
@@ -2013,6 +2065,17 @@ def create_protocol(
assert_donation_access(db, row.id, ctx, user_info=user_info)
db.commit()
db.refresh(row)
op_log.record_donation_operation(
db,
donation_id=row.id,
action=op_log.ACTION_CREATE,
tenant_no=ctx.tenant_no,
user_id=ctx.user_id,
client_channel=op_log.CHANNEL_MINI,
before=None,
create_dept_id=dept_id,
)
db.commit()
schedule_sample_collect_notify(
tenant_no=ctx.tenant_no,
protocol_id=row.id,
@@ -2050,6 +2113,9 @@ def update_protocol(
db, protocol_id, ctx, user_info=user_info
)
guard_project_edit(row, _dump(body))
before_snap = op_log.snapshot_cell_protocol(
db, protocol_id=row.id, tenant_no=ctx.tenant_no
)
current_collection = cell_crud.get_collection_info(
db, row.id, ctx.tenant_no
)
@@ -2178,6 +2244,17 @@ def update_protocol(
)
db.commit()
db.refresh(row)
op_log.record_cell_operation(
db,
protocol_id=row.id,
action=op_log.ACTION_UPDATE,
tenant_no=ctx.tenant_no,
user_id=ctx.user_id,
client_channel=op_log.CHANNEL_MINI,
before=before_snap,
create_dept_id=dept_id,
)
db.commit()
schedule_sample_collect_notify(
tenant_no=ctx.tenant_no,
protocol_id=row.id,
@@ -2195,6 +2272,9 @@ def update_protocol(
db, protocol_id, ctx, user_info=user_info
)
guard_project_edit(row, _dump(body))
before_snap = op_log.snapshot_donation(
db, donation_id=row.id, tenant_no=ctx.tenant_no
)
current_collection = donation_crud.get_collection(
db, row.id, ctx.tenant_no
)
@@ -2278,6 +2358,17 @@ def update_protocol(
row = assert_donation_access(db, row.id, ctx, user_info=user_info)
db.commit()
db.refresh(row)
op_log.record_donation_operation(
db,
donation_id=row.id,
action=op_log.ACTION_UPDATE,
tenant_no=ctx.tenant_no,
user_id=ctx.user_id,
client_channel=op_log.CHANNEL_MINI,
before=before_snap,
create_dept_id=dept_id,
)
db.commit()
schedule_sample_collect_notify(
tenant_no=ctx.tenant_no,
protocol_id=row.id,
@@ -0,0 +1,421 @@
"""市场协议作废 ↔ 质检样本接收废弃双向联动。
规则(细胞存储 / 科研捐赠):
1. 协议变为已作废(yzf)时,协议下全部样本接收结论自动为废弃(bj)。
2. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。
"""
from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy.orm import Session
from app.core.utils import generate_uuid
from app.models.models import (
BizCollectionProtocol,
BizProtocolSample,
BizSampleReception,
SysDictData,
)
from app.models.research_donation import BizResearchDonation, BizResearchDonationSample
LAB_VOID_TYPE_CODE = "sysfq"
LAB_VOID_TYPE_LABEL = "实验室废弃"
VOID_TYPE_DICT = "xyzflx"
_AUTO_DISCARD_REMARK = "协议作废自动废弃"
_AUTO_VOID_DESC = "全部样本接收废弃/拒收,系统自动作废"
def ensure_lab_void_type(db: Session, *, tenant_no: str) -> str:
"""确保租户字典 xyzflx 存在「实验室废弃」,返回 dict_value。"""
tenant = (tenant_no or "").strip()
if not tenant:
raise ValueError("租户编号不能为空")
by_value = (
db.query(SysDictData)
.filter(
SysDictData.dict_type == VOID_TYPE_DICT,
SysDictData.dict_value == LAB_VOID_TYPE_CODE,
SysDictData.tenant_no == tenant,
SysDictData.del_flag == 0,
)
.first()
)
if by_value:
return LAB_VOID_TYPE_CODE
by_label = (
db.query(SysDictData)
.filter(
SysDictData.dict_type == VOID_TYPE_DICT,
SysDictData.dict_label == LAB_VOID_TYPE_LABEL,
SysDictData.tenant_no == tenant,
SysDictData.del_flag == 0,
)
.first()
)
if by_label and (by_label.dict_value or "").strip():
return (by_label.dict_value or "").strip()
now = datetime.now()
db.add(
SysDictData(
id=generate_uuid(),
dict_label=LAB_VOID_TYPE_LABEL,
dict_value=LAB_VOID_TYPE_CODE,
dict_type=VOID_TYPE_DICT,
tenant_no=tenant,
order_num=90,
remark="issue#31 实验室废弃自动作废类型",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.flush()
return LAB_VOID_TYPE_CODE
def _list_cell_samples(db: Session, *, protocol_id: str, tenant_no: str) -> List[BizProtocolSample]:
return (
db.query(BizProtocolSample)
.filter(
BizProtocolSample.collection_protocol_id == protocol_id,
BizProtocolSample.tenant_no == tenant_no,
BizProtocolSample.del_flag == 0,
)
.order_by(BizProtocolSample.order_num.asc(), BizProtocolSample.create_time.asc())
.all()
)
def _list_donation_samples(
db: Session, *, donation_id: str, tenant_no: str
) -> List[BizResearchDonationSample]:
return (
db.query(BizResearchDonationSample)
.filter(
BizResearchDonationSample.research_donation_id == donation_id,
BizResearchDonationSample.tenant_no == tenant_no,
BizResearchDonationSample.del_flag == 0,
)
.order_by(
BizResearchDonationSample.order_num.asc(),
BizResearchDonationSample.create_time.asc(),
)
.all()
)
def _find_reception(
db: Session,
*,
tenant_no: str,
source: str,
sample_code: str,
) -> Optional[BizSampleReception]:
code = (sample_code or "").strip()
if not code:
return None
return (
db.query(BizSampleReception)
.filter(
BizSampleReception.tenant_no == tenant_no,
BizSampleReception.del_flag == 0,
BizSampleReception.reception_source == source,
BizSampleReception.sample_code == code,
)
.first()
)
def _upsert_discard_reception(
db: Session,
*,
source: str,
tenant_no: str,
user_id: Optional[str],
sample_code: str,
protocol_sample_id: str = "",
collection_protocol_id: str = "",
donation_sample_id: Optional[str] = None,
research_donation_id: Optional[str] = None,
now: Optional[datetime] = None,
) -> None:
code = (sample_code or "").strip()
if not code:
return
ts = now or datetime.now()
rec = _find_reception(db, tenant_no=tenant_no, source=source, sample_code=code)
if rec:
if (rec.accept_conclusion or "").strip() == "bj":
return
rec.accept_conclusion = "bj"
rec.update_by = user_id
rec.update_time = ts
if not (rec.remark or "").strip():
rec.remark = _AUTO_DISCARD_REMARK
db.add(rec)
return
obj = BizSampleReception(
id=generate_uuid(),
protocol_sample_id=protocol_sample_id or "",
collection_protocol_id=collection_protocol_id or "",
reception_time=ts,
handler_user_id=user_id,
handler_name=None,
receive_temperature=None,
accept_conclusion="bj",
receive_attachments=None,
reception_source=source,
donation_sample_id=donation_sample_id,
research_donation_id=research_donation_id,
sample_code=code,
lab_storage_code=None,
tenant_no=tenant_no,
remark=_AUTO_DISCARD_REMARK,
create_by=user_id,
create_dept_id="",
update_by=user_id,
create_time=ts,
update_time=ts,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
db.add(obj)
def discard_receptions_for_voided_protocol(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
user_id: Optional[str] = None,
) -> int:
"""协议已作废后,将其下样本接收全部置为废弃。返回处理样本数。"""
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if src not in ("cell_storage", "research_donation") or not pid or not tenant:
return 0
now = datetime.now()
if src == "cell_storage":
samples = _list_cell_samples(db, protocol_id=pid, tenant_no=tenant)
for sample in samples:
_upsert_discard_reception(
db,
source=src,
tenant_no=tenant,
user_id=user_id,
sample_code=sample.sample_code or "",
protocol_sample_id=sample.id,
collection_protocol_id=pid,
now=now,
)
else:
samples = _list_donation_samples(db, donation_id=pid, tenant_no=tenant)
for sample in samples:
_upsert_discard_reception(
db,
source=src,
tenant_no=tenant,
user_id=user_id,
sample_code=sample.sample_code or "",
donation_sample_id=sample.id,
research_donation_id=pid,
now=now,
)
db.flush()
return len(samples)
def _all_samples_discarded(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
) -> bool:
src = (source or "").strip()
if src == "cell_storage":
samples = _list_cell_samples(db, protocol_id=protocol_id, tenant_no=tenant_no)
else:
samples = _list_donation_samples(db, donation_id=protocol_id, tenant_no=tenant_no)
if not samples:
return False
for sample in samples:
code = (sample.sample_code or "").strip()
if not code:
return False
rec = _find_reception(db, tenant_no=tenant_no, source=src, sample_code=code)
if not rec or (rec.accept_conclusion or "").strip() != "bj":
return False
return True
def maybe_void_protocol_when_all_samples_discarded(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
user_id: Optional[str] = None,
) -> bool:
"""若协议下样本全部废弃,则自动作废协议(作废类型=实验室废弃)。返回是否执行了作废。"""
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if src not in ("cell_storage", "research_donation") or not pid or not tenant:
return False
if not _all_samples_discarded(db, source=src, protocol_id=pid, tenant_no=tenant):
return False
void_type = ensure_lab_void_type(db, tenant_no=tenant)
now = datetime.now()
if src == "cell_storage":
obj = (
db.query(BizCollectionProtocol)
.filter(
BizCollectionProtocol.id == pid,
BizCollectionProtocol.tenant_no == tenant,
BizCollectionProtocol.del_flag == 0,
)
.first()
)
if not obj:
return False
status = (obj.protocol_status or "").strip()
if status in ("yzf", "sdfq"):
return False
from app.core.protocol_status_display import assert_protocol_status_transition
from app.crud.collection_protocol import update_collection_protocol
try:
assert_protocol_status_transition(status, "yzf", kind="protocol")
except ValueError:
return False
update_collection_protocol(
db,
pid,
tenant_no=tenant,
user_id=user_id,
protocol_status="yzf",
void_time=now,
void_desc=_AUTO_VOID_DESC,
void_type=void_type,
commit=False,
sync_reception_discard=False,
)
return True
obj = (
db.query(BizResearchDonation)
.filter(
BizResearchDonation.id == pid,
BizResearchDonation.tenant_no == tenant,
BizResearchDonation.del_flag == 0,
)
.first()
)
if not obj:
return False
status = (obj.donation_status or "").strip()
if status in ("yzf", "sdfq"):
return False
# 捐赠 change_status 默认 commit;此处内联等价逻辑避免提前提交。
from app.core.protocol_status_display import assert_protocol_status_transition
from app.crud.dict_data import normalize_void_type
from app.crud.research_donation import (
_DONATION_STATUS_CHANGE_TYPE,
append_donation_status_change,
)
current = obj.donation_status or ""
try:
assert_protocol_status_transition(current, "yzf", kind="donation")
except ValueError:
return False
normalized = normalize_void_type(db, value=void_type, tenant_no=tenant)
obj.donation_status = "yzf"
obj.void_time = now
obj.void_desc = _AUTO_VOID_DESC
obj.void_type = normalized
obj.update_by = user_id
obj.update_time = now
change_type = _DONATION_STATUS_CHANGE_TYPE.get("yzf")
if change_type:
append_donation_status_change(
db,
research_donation_id=obj.id,
change_type=change_type,
from_status=current,
to_status="yzf",
change_time=now,
change_desc=_AUTO_VOID_DESC,
void_type=normalized,
tenant_no=tenant,
user_id=user_id,
)
db.add(obj)
db.flush()
return True
def after_sample_reception_saved(
db: Session,
*,
reception: BizSampleReception,
tenant_no: str,
user_id: Optional[str] = None,
) -> None:
"""样本接收保存后:若结论为废弃,尝试自动作废所属协议。"""
if (reception.accept_conclusion or "").strip() != "bj":
return
source = (reception.reception_source or "cell_storage").strip() or "cell_storage"
if source == "cell_storage":
protocol_id = (reception.collection_protocol_id or "").strip()
else:
protocol_id = (reception.research_donation_id or "").strip()
if not protocol_id:
return
maybe_void_protocol_when_all_samples_discarded(
db,
source=source,
protocol_id=protocol_id,
tenant_no=tenant_no,
user_id=user_id,
)
def after_protocol_voided(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
user_id: Optional[str] = None,
) -> None:
"""协议作废后:同步废弃其下全部样本接收。"""
discard_receptions_for_voided_protocol(
db,
source=source,
protocol_id=protocol_id,
tenant_no=tenant_no,
user_id=user_id,
)
@@ -0,0 +1,148 @@
"""Issue #24:协议操作过程日志 append-only 与动作映射。"""
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
def _session():
from app.models.models import (
BizCollectionProtocol,
BizProtocolCollectionInfo,
BizProtocolOperationLog,
BizProtocolPartyCustomer,
BizProtocolSample,
SysUser,
)
engine = create_engine("sqlite:///:memory:")
BizCollectionProtocol.__table__.create(engine)
BizProtocolPartyCustomer.__table__.create(engine)
BizProtocolCollectionInfo.__table__.create(engine)
BizProtocolSample.__table__.create(engine)
BizProtocolOperationLog.__table__.create(engine)
SysUser.__table__.create(engine)
return sessionmaker(bind=engine, autoflush=False, autocommit=False)(), engine
def test_record_cell_update_appends_before_after_and_maps_void_action():
from app.crud import protocol_operation_log as op_log
from app.models.models import BizCollectionProtocol, BizProtocolPartyCustomer, SysUser
db, engine = _session()
try:
now = datetime(2026, 11, 5, 10, 0, 0)
db.add(
SysUser(
id="u1",
user_no="u1",
nick_name="采集员甲",
tenant_no="zkxw",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizCollectionProtocol(
id="p1",
protocol_no="XY2401",
protocol_status="sxz",
tenant_no="zkxw",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolPartyCustomer(
id="party1",
collection_protocol_id="p1",
mother_name="旧姓名",
tenant_no="zkxw",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.commit()
before = op_log.snapshot_cell_protocol(db, protocol_id="p1", tenant_no="zkxw")
assert before is not None
assert before["protocol"]["protocolStatus"] == "sxz"
assert before["partyCustomer"]["motherName"] == "旧姓名"
row = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p1").one()
row.protocol_status = "yzf"
party = (
db.query(BizProtocolPartyCustomer)
.filter(BizProtocolPartyCustomer.collection_protocol_id == "p1")
.one()
)
party.mother_name = "新姓名"
db.add(row)
db.add(party)
db.flush()
op_log.record_cell_operation(
db,
protocol_id="p1",
action=op_log.ACTION_UPDATE,
tenant_no="zkxw",
user_id="u1",
client_channel=op_log.CHANNEL_MINI,
before=before,
)
db.commit()
items = op_log.list_protocol_operation_logs(
db, biz_type=op_log.BIZ_CELL, biz_id="p1", tenant_no="zkxw"
)
assert len(items) == 1
item = items[0]
assert item["action"] == "void"
assert item["clientChannel"] == "mini"
assert item["operatorUserName"] == "采集员甲"
assert item["before"]["partyCustomer"]["motherName"] == "旧姓名"
assert item["after"]["partyCustomer"]["motherName"] == "新姓名"
assert item["after"]["protocol"]["protocolStatus"] == "yzf"
finally:
db.close()
engine.dispose()
def test_resolve_action_from_status_keeps_default_when_unchanged():
from app.crud.protocol_operation_log import (
ACTION_AUDIT,
ACTION_UPDATE,
ACTION_VOID,
resolve_action_from_status,
)
assert (
resolve_action_from_status(
default_action=ACTION_UPDATE,
before_status="sxz",
after_status="sxz",
)
== ACTION_UPDATE
)
assert (
resolve_action_from_status(
default_action=ACTION_UPDATE,
before_status="sxz",
after_status="yzf",
)
== ACTION_VOID
)
assert (
resolve_action_from_status(
default_action=ACTION_AUDIT,
before_status="dsx",
after_status="sxz",
)
== ACTION_AUDIT
)
@@ -0,0 +1,328 @@
"""协议作废 ↔ 样本接收废弃双向联动。"""
from __future__ import annotations
import unittest
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.core.database import Base
from app.models.models import (
BizCollectionProtocol,
BizProtocolSample,
BizProtocolStatusChange,
BizSampleReception,
SysDictData,
)
from app.models.research_donation import (
BizDonationStatusChange,
BizResearchDonation,
BizResearchDonationSample,
)
from app.services.protocol_reception_discard_sync import (
LAB_VOID_TYPE_CODE,
after_protocol_voided,
after_sample_reception_saved,
ensure_lab_void_type,
)
def _session():
engine = create_engine("sqlite://")
Base.metadata.create_all(
bind=engine,
tables=[
SysDictData.__table__,
BizCollectionProtocol.__table__,
BizProtocolSample.__table__,
BizProtocolStatusChange.__table__,
BizSampleReception.__table__,
BizResearchDonation.__table__,
BizResearchDonationSample.__table__,
BizDonationStatusChange.__table__,
],
)
return sessionmaker(bind=engine)()
def _now():
return datetime(2026, 11, 5, 12, 0, 0)
class TestProtocolReceptionDiscardSync(unittest.TestCase):
def test_ensure_lab_void_type_creates_dict_row(self):
db = _session()
code = ensure_lab_void_type(db, tenant_no="tenant-a")
self.assertEqual(code, LAB_VOID_TYPE_CODE)
row = (
db.query(SysDictData)
.filter(
SysDictData.tenant_no == "tenant-a",
SysDictData.dict_type == "xyzflx",
SysDictData.dict_value == LAB_VOID_TYPE_CODE,
)
.one()
)
self.assertEqual(row.dict_label, "实验室废弃")
# idempotent
self.assertEqual(ensure_lab_void_type(db, tenant_no="tenant-a"), LAB_VOID_TYPE_CODE)
def test_protocol_void_marks_all_sample_receptions_discarded(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p1",
protocol_no="CP-1",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="s1",
collection_protocol_id="p1",
sample_code="ZK001",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="s2",
collection_protocol_id="p1",
sample_code="ZK002",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizSampleReception(
id="r1",
protocol_sample_id="s1",
collection_protocol_id="p1",
reception_time=now,
accept_conclusion="js",
reception_source="cell_storage",
sample_code="ZK001",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
)
db.commit()
after_protocol_voided(
db,
source="cell_storage",
protocol_id="p1",
tenant_no="tenant-a",
user_id="u1",
)
db.commit()
rows = (
db.query(BizSampleReception)
.filter(BizSampleReception.tenant_no == "tenant-a", BizSampleReception.del_flag == 0)
.all()
)
self.assertEqual(len(rows), 2)
by_code = {r.sample_code: r.accept_conclusion for r in rows}
self.assertEqual(by_code["ZK001"], "bj")
self.assertEqual(by_code["ZK002"], "bj")
def test_all_samples_discarded_auto_voids_protocol_with_lab_type(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p2",
protocol_no="CP-2",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="s3",
collection_protocol_id="p2",
sample_code="ZK003",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
rec = BizSampleReception(
id="r2",
protocol_sample_id="s3",
collection_protocol_id="p2",
reception_time=now,
accept_conclusion="bj",
reception_source="cell_storage",
sample_code="ZK003",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
db.add(rec)
db.commit()
after_sample_reception_saved(
db, reception=rec, tenant_no="tenant-a", user_id="u1"
)
db.commit()
proto = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p2").one()
self.assertEqual(proto.protocol_status, "yzf")
self.assertEqual(proto.void_type, LAB_VOID_TYPE_CODE)
self.assertIn("全部样本接收", proto.void_desc or "")
def test_partial_discard_does_not_void_protocol(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p3",
protocol_no="CP-3",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
for sid, code in (("s4", "ZK004"), ("s5", "ZK005")):
db.add(
BizProtocolSample(
id=sid,
collection_protocol_id="p3",
sample_code=code,
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
rec = BizSampleReception(
id="r3",
protocol_sample_id="s4",
collection_protocol_id="p3",
reception_time=now,
accept_conclusion="bj",
reception_source="cell_storage",
sample_code="ZK004",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
db.add(rec)
db.commit()
after_sample_reception_saved(
db, reception=rec, tenant_no="tenant-a", user_id="u1"
)
db.commit()
proto = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p3").one()
self.assertEqual(proto.protocol_status, "sxz")
self.assertFalse(proto.void_type)
def test_donation_void_creates_discard_receptions(self):
db = _session()
now = _now()
db.add(
BizResearchDonation(
id="d1",
donation_no="RD-1",
donation_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizResearchDonationSample(
id="ds1",
research_donation_id="d1",
sample_code="RD001",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.commit()
after_protocol_voided(
db,
source="research_donation",
protocol_id="d1",
tenant_no="tenant-a",
user_id="u1",
)
db.commit()
rec = (
db.query(BizSampleReception)
.filter(
BizSampleReception.sample_code == "RD001",
BizSampleReception.reception_source == "research_donation",
)
.one()
)
self.assertEqual(rec.accept_conclusion, "bj")
self.assertEqual(rec.research_donation_id, "d1")
if __name__ == "__main__":
unittest.main()
+10 -2
View File
@@ -60,9 +60,17 @@
},
"figma": {
"references": [
"https://www.figma.com/design/jc7D8Fe7lKNTVj4jM3AoGW?node-id=2-2"
"https://www.figma.com/design/M9XtXqXRCAKccMWD7BivIL",
"https://www.figma.com/design/W3yXdlX4TbQP0PVhFG8cBB"
],
"status": "user-confirmed-demo-only"
"status": "web-and-mobile-design-systems-v1",
"authority": {
"web-admin": "https://www.figma.com/design/M9XtXqXRCAKccMWD7BivIL",
"mobile-h5": "https://www.figma.com/design/W3yXdlX4TbQP0PVhFG8cBB",
"mobile-oa-h5": "https://www.figma.com/design/W3yXdlX4TbQP0PVhFG8cBB"
},
"archive": null,
"notes": "Web 用 Fresh Mint(#10b981);移动端用独立 Mobile Design System(规范品牌绿 #0a9f6d),禁止混色。旧整页镜像文件已删除。Figma 色板按规范,不以 styles/tokens.scss 的 #22c55e 覆盖。已补高频状态:Web StateBlock/FormAlert(P01 旁展示);Mobile Empty/ConfirmDialog/WebViewState。"
},
"delivery": {
"provider": "drone",
@@ -0,0 +1,29 @@
-- Issue #24:协议单操作过程日志(before / action / after)
-- MySQL 5.7;可重复执行(CREATE IF NOT EXISTS)。上线前须备份并在目标副本验证。
-- DDL 隐式提交;该脚本不作为自动应用启动步骤。
CREATE TABLE IF NOT EXISTS biz_protocol_operation_log (
id VARCHAR(64) NOT NULL,
biz_type VARCHAR(32) NOT NULL COMMENT '业务类型 cell_storage/research_donation',
biz_id VARCHAR(64) NOT NULL COMMENT '协议单或捐赠单ID',
protocol_no VARCHAR(64) NULL COMMENT '协议/捐赠编号快照',
action VARCHAR(32) NOT NULL COMMENT '动作 create/update/delete/void/activate/expire/to_research/to_storage/audit',
client_channel VARCHAR(16) NOT NULL DEFAULT 'web' COMMENT '来源端 web/mini',
before_json MEDIUMTEXT NULL COMMENT '操作前协议信息JSON',
after_json MEDIUMTEXT NULL COMMENT '操作后协议信息JSON',
operator_user_id VARCHAR(64) NULL COMMENT '操作人用户ID',
operator_user_name VARCHAR(64) NULL COMMENT '操作人姓名快照',
operate_time DATETIME NOT NULL COMMENT '业务操作时间',
tenant_no VARCHAR(64) NOT NULL,
order_num INT NULL,
remark VARCHAR(512) NULL,
create_by VARCHAR(64) NULL,
create_dept_id VARCHAR(64) NOT NULL DEFAULT '',
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
update_by VARCHAR(64) NULL,
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
del_flag SMALLINT NOT NULL DEFAULT 0,
PRIMARY KEY (id),
KEY ix_pol_biz (tenant_no, biz_type, biz_id, del_flag),
KEY ix_pol_time (tenant_no, operate_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
@@ -0,0 +1,32 @@
-- Issue #31:作废类型字典补充「实验室废弃」(sysfq)
-- 为已有 xyzflx 字典的租户补齐;可重复执行。
INSERT INTO sys_dict_data (
id, dict_label, dict_value, dict_type, tenant_no, order_num, remark,
create_dept_id, create_time, update_time, del_flag
)
SELECT
MD5(CONCAT(t.tenant_no, ':xyzflx:sysfq')),
'实验室废弃',
'sysfq',
'xyzflx',
t.tenant_no,
90,
'issue#31 实验室废弃',
'',
NOW(),
NOW(),
0
FROM (
SELECT DISTINCT tenant_no
FROM sys_dict_data
WHERE dict_type = 'xyzflx' AND del_flag = 0
) t
WHERE NOT EXISTS (
SELECT 1
FROM sys_dict_data existing
WHERE existing.tenant_no = t.tenant_no
AND existing.dict_type = 'xyzflx'
AND existing.dict_value = 'sysfq'
AND existing.del_flag = 0
);
@@ -117,7 +117,8 @@ test('protocol adapters preserve nested detail sections', () => {
'refundRecords',
'audits',
'attachments',
'statusChange'
'statusChange',
'operationLog'
])
const protocolLabels = protocol.flatMap((section) => (section.fields || []).map((field) => field.label))
assert.ok(!protocolLabels.includes('协议编号'))
@@ -125,7 +126,7 @@ test('protocol adapters preserve nested detail sections', () => {
assert.ok(protocolLabels.includes('父亲姓名'))
assert.ok(protocolLabels.includes('母亲联系电话'))
assert.ok(!protocolLabels.includes('新生儿评分(5分钟)'))
assert.equal(protocol.at(-1).key, 'statusChange')
assert.equal(protocol.at(-1).key, 'operationLog')
})
test('attachment-bearing detail adapters expose typed values instead of path text', () => {
+71 -1
View File
@@ -127,6 +127,66 @@ function statusChangeDescText(row) {
return desc || '—'
}
function operationActionLabel(action) {
const map = {
create: '创建',
update: '修改',
delete: '删除',
void: '作废',
activate: '生效',
expire: '过期',
to_research: '转科研',
to_storage: '转细胞存储',
audit: '审核'
}
return map[action] || action || '—'
}
function operationChannelLabel(channel) {
if (channel === 'mini') return '小程序'
if (channel === 'web') return 'Web'
return channel || '—'
}
function buildOperationLogCards(rows) {
return (Array.isArray(rows) ? rows : []).map((row, index) => {
const action = String(row?.action || '')
const before = row?.before || {}
const after = row?.after || {}
const beforeProto = before.protocol || before.donation || {}
const afterProto = after.protocol || after.donation || {}
const beforeParty = before.partyCustomer || before.party || {}
const afterParty = after.partyCustomer || after.party || {}
const beforeStatus = String(beforeProto.protocolStatus || beforeProto.donationStatus || '')
const afterStatus = String(afterProto.protocolStatus || afterProto.donationStatus || '')
let summary = ''
if (beforeStatus && afterStatus && beforeStatus !== afterStatus) summary = `状态 ${beforeStatus}→${afterStatus}`
else if (afterStatus) summary = `状态 ${afterStatus}`
for (const key of ['motherName', 'customerName', 'donorName', 'name']) {
const b = String(beforeParty[key] || '').trim()
const a = String(afterParty[key] || '').trim()
if (b || a) {
const namePart = b && a && b !== a ? `姓名 ${b}→${a}` : a ? `姓名 ${a}` : ''
summary = summary ? `${summary};${namePart}` : namePart
break
}
}
if (!summary) summary = String(row?.remark || '').trim() || '见前后快照'
return {
key: `operation-log-${row?.id || index}`,
title: `${index + 1}. ${operationActionLabel(action)}`,
fields: [
{ label: '来源端', value: operationChannelLabel(String(row?.clientChannel || '')) },
{ label: '操作时间', value: row?.operateTime || '—' },
{ label: '操作人', value: row?.operatorUserName || '—' },
{ label: '变更摘要', value: summary }
]
}
})
}
function buildStatusChangeCards(rows, statusRegistry) {
return (rows || []).map((row, index) => {
const changeType = String(row?.changeType || '')
@@ -683,6 +743,8 @@ export default {
? detail.statusChanges
: synthesizeStatusChangesFromBasic(basic, source)
const statusChangeCards = buildStatusChangeCards(statusChangeRows, statusRegistry)
const operationLogRows = Array.isArray(detail?.operationLogs) ? detail.operationLogs : []
const operationLogCards = buildOperationLogCards(operationLogRows)
values.push({
key: 'statusChange',
title: '状态变更记录',
@@ -690,9 +752,17 @@ export default {
? []
: [{ label: '记录', value: '暂无状态变更记录' }],
cards: statusChangeCards
},
{
key: 'operationLog',
title: '操作日志',
fields: operationLogCards.length
? []
: [{ label: '记录', value: '暂无操作日志' }],
cards: operationLogCards
})
if (isDonation) {
const order = ['protocol', 'collection', 'samples', 'customer', 'audits', 'attachments', 'statusChange']
const order = ['protocol', 'collection', 'samples', 'customer', 'audits', 'attachments', 'statusChange', 'operationLog']
const byKey = new Map(values.map((section) => [section.key, section]))
return order.map((key) => byKey.get(key)).filter(Boolean)
}
@@ -123,7 +123,7 @@ test('donation detail follows the web view and omits price and payment', () => {
attachments: { protocolAttachments: 'a.pdf', healthSurveyFormUrls: 'h.pdf', consentFormUrls: 'c.pdf' }
})
assert.deepEqual(sections.map((section) => section.key), [
'protocol', 'collection', 'samples', 'customer', 'audits', 'attachments', 'statusChange'
'protocol', 'collection', 'samples', 'customer', 'audits', 'attachments', 'statusChange', 'operationLog'
])
assert.equal(sections[0].title, '基本信息')
assert.deepEqual(sections[0].fields.map((field) => field.label), [
@@ -1,3 +1,4 @@
import { attachmentFullUrl } from '../../utils/attachment.js'
/**
* OA 审批单移动端打印(S6)
* 对齐 web-admin `oa-approval-print.ts` 字段/流程结构;支持 html2canvas + jsPDF 导出。
@@ -66,7 +67,6 @@ function escapeHtml(s) {
.replace(/"/g, '&quot;')
}
function formatDateOnly(createTime) {
const raw = String(createTime || '').trim()
if (!raw) return '-'
@@ -99,10 +99,12 @@ function formatScalar(value, sep = '、') {
return String(value)
}
if (Array.isArray(value)) {
return value
.map((x) => formatScalar(x, sep))
.filter((x) => x && x !== '-')
.join(sep) || '-'
return (
value
.map((x) => formatScalar(x, sep))
.filter((x) => x && x !== '-')
.join(sep) || '-'
)
}
if (typeof value === 'object') {
if (value.name != null) return String(value.name)
@@ -397,7 +399,13 @@ export function buildOaPrintModel(detail, opts = {}) {
stampClass,
stampText,
rows: [...headerRows, ...buildFormRows(detail)],
flowItems: buildFlowItems(detail),
flowItems: buildFlowItems(detail, (url) => {
try {
return new URL(attachmentFullUrl(url), window.location.origin).href
} catch {
return ''
}
}),
printTime,
printerName,
watermarkName: printerName === '-' ? '审批' : printerName
@@ -435,6 +443,9 @@ function flowCellHtml(f) {
} else if (f.comment) {
html += `<div class="oa-print-flow__comment">意见:${escapeHtml(f.comment)}</div>`
}
for (const url of f.attachmentLinks || []) {
html += `<div class="oa-print-url"><a data-oa-print-link href="${escapeHtml(url)}">${escapeHtml(url)}</a></div>`
}
return html
}
@@ -472,9 +483,10 @@ function buildPrintStylesContent() {
line-height: 1.5; word-break: break-all; }
.oa-print-table th { width: 118px; font-weight: 400; text-align: left; background: #fff; }
.oa-print-text { white-space: pre-wrap; }
.oa-print-url a { color: inherit; }
.oa-print-url { color: #3370ff; word-break: break-all; }
.oa-print-flow__row { display: flex; justify-content: space-between; gap: 12px; }
.oa-print-flow__left { flex: 1; min-width: 0; }
.oa-print-flow__left { white-space: pre-wrap; overflow-wrap: anywhere; flex: 1; min-width: 0; }
.oa-print-flow__right { flex: 0 0 auto; color: #646464; white-space: nowrap; }
.oa-print-flow__person-lines { margin-top: 4px; padding-left: 8px; }
.oa-print-flow__person-line { margin-top: 2px; font-size: 12px; }
@@ -602,7 +614,7 @@ function renderPageLabelCanvas(text) {
return c
}
async function canvasToPdfBlob(canvas) {
async function canvasToPdfBlob(canvas, sheet) {
const pdf = new jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' })
const pageWidth = pdf.internal.pageSize.getWidth()
const pageHeight = pdf.internal.pageSize.getHeight()
@@ -620,6 +632,23 @@ async function canvasToPdfBlob(canvas) {
const position = -pageIndex * pageHeight
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
// html2canvas 只保留像素,单独把附件链接写为 PDF 注解;跨页部分按页裁切。
const sheetRect = sheet.getBoundingClientRect()
const ratio = pageWidth / sheetRect.width
for (const link of sheet.querySelectorAll('a[data-oa-print-link]')) {
if (!/^https?:\/\//i.test(link.href)) continue
for (const rect of link.getClientRects()) {
const top = (rect.top - sheetRect.top) * ratio - pageIndex * pageHeight
const bottom = Math.min(pageHeight, top + rect.height * ratio)
const y = Math.max(0, top)
if (bottom > y) {
pdf.link((rect.left - sheetRect.left) * ratio, y, rect.width * ratio, bottom - y, {
url: link.href
})
}
}
}
const label = `第${pageIndex + 1}页`
const labelCanvas = renderPageLabelCanvas(label)
if (labelCanvas.width > 1) {
@@ -664,7 +693,7 @@ export async function generateOaApprovalPdfBlob(detail, opts = {}) {
windowWidth: el.scrollWidth,
windowHeight: el.scrollHeight
})
const blob = await canvasToPdfBlob(canvas)
const blob = await canvasToPdfBlob(canvas, el)
return { blob, filename }
} finally {
host.remove()
@@ -0,0 +1,95 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { buildFlowItems } from './oa-print-flow.js'
describe('打印讨论评论', () => {
it('按时间展示正文、提及和附件,并排在待审节点前', () => {
const items = buildFlowItems({
progress: [
{
kind: 'submit',
title: '发起人',
status: 'submitted',
timestamp: '2026-11-01 10:00:00'
},
{
kind: 'pending_node',
title: '审批人',
status: 'pending',
timestamp: '2026-11-01 10:00:00'
}
],
comments: [
{
id: '2',
createByName: '李四',
createTime: '2026-11-01 12:00:00',
content: '',
attachmentRefs: [{ url: 'https://example.com/file.pdf', fileName: '附件.pdf' }]
},
{
id: '1',
createByName: '张三',
createTime: '2026-11-01 11:00:00',
content: '@李四 请处理\n第二行',
mentions: [{ userId: 'u2', userName: '李四' }]
}
]
})
assert.equal(items.length, 4)
assert.equal(items[1].left, '【评论】 张三')
assert.equal(items[1].right, '2026-11-01 11:00:00')
assert.deepEqual(items[1].personLines, [
{ left: '@李四 请处理\n第二行', right: '' },
{ left: '提到:@李四', right: '' }
])
assert.deepEqual(items[2].attachmentLinks, ['https://example.com/file.pdf'])
assert.match(items[3].left, /待处理/)
})
it('撤回评论不泄露正文、提及和附件', () => {
const [item] = buildFlowItems({
comments: [
{
id: '1',
createBy: 'u1',
status: 'revoked',
content: 'secret',
mentions: [{ userName: 'secret' }],
attachmentRefs: [{ url: 'https://example.com/secret' }]
}
]
})
assert.equal(item.left, '【评论】 u1 已撤回')
assert.equal(JSON.stringify(item).includes('secret'), false)
})
it('安全过滤附件协议,保留纯附件与纯提及评论', () => {
const items = buildFlowItems({
comments: [
{
id: '1',
mentions: [{ userId: 'u1' }],
attachmentRefs: [{ url: 'javascript:alert(1)' }, { url: 'https://example.com/a?x=1&y=2' }]
}
]
})
assert.deepEqual(items[0].attachmentLinks, ['https://example.com/a?x=1&y=2'])
assert.deepEqual(items[0].personLines, [{ left: '提到:@u1', right: '' }])
})
})
it('同秒节点使用详情页的稳定排序键', () => {
const progress = Array.from({ length: 12 }, (_, index) => ({
kind: 'task',
nodeKey: `node-${String(11 - index).padStart(2, '0')}`,
title: `节点${11 - index}`,
status: 'approved',
timestamp: '2026-11-01 10:00:00'
}))
const items = buildFlowItems({
progress,
comments: [{ id: 'comment', content: '讨论', createTime: '2026-11-01 10:00:00' }]
})
assert.equal(items[0].left, '【节点0】 已同意')
assert.equal(items[11].left, '【节点11】 已同意')
assert.equal(items[12].left, '【评论】 评论')
})
+46 -8
View File
@@ -1,3 +1,4 @@
import { mergeProgressWithComments } from '../oa-progress-merge-comments.js'
/**
* 移动端打印「审批流程」行组装(无 html2canvas/API 副作用,便于单测)
*/
@@ -37,16 +38,22 @@ function isCcProgressItem(p) {
const taskType = String(p?.taskType || p?.task_type || '').trim()
const signMode = String(p?.signMode || p?.sign_mode || '').trim()
const title = String(p?.title || p?.nodeName || '').trim()
return (
taskType === 'cc' ||
signMode === 'cc' ||
title === '抄送人' ||
/^抄送/.test(title)
)
return taskType === 'cc' || signMode === 'cc' || title === '抄送人' || /^抄送/.test(title)
}
export function buildFlowItems(detail) {
const list = Array.isArray(detail?.progress) ? detail.progress : []
export function buildFlowItems(detail, resolveUrl = (url) => url) {
const progress = Array.isArray(detail?.progress) ? detail.progress : []
// 沿用详情页的时间顺序;无讨论时保持原有审批节点顺序。
const list =
Array.isArray(detail?.comments) && detail.comments.length
? mergeProgressWithComments(
progress.map((p, index) => ({
...p,
key: `${p.kind}-${p.nodeKey || p.taskId || index}-${p.roundNo || 1}`
})),
detail.comments
)
: progress
const items = []
let ccBuf = null
const flushCc = () => {
@@ -70,6 +77,37 @@ export function buildFlowItems(detail) {
const signMode = String(p.signMode || p.sign_mode || '')
const signLabel = signMode === 'and' ? '会签' : signMode === 'or' ? '或签' : ''
if (kind === 'comment') {
flushCc()
const revoked = p.status === 'revoked'
const author = String(p.assignee || p.title || '评论').trim()
const item = {
left: `【评论】 ${author}${revoked ? ' 已撤回' : ''}`,
right: ts
}
if (!revoked) {
const lines = []
if (comment) lines.push({ left: comment, right: '' })
const mentions = (p.mentions || [])
.map((m) => String(m.userName || m.userId || '').trim())
.filter(Boolean)
if (mentions.length)
lines.push({
left: `提到:${mentions.map((name) => `@${name}`).join('、')}`,
right: ''
})
if (lines.length) item.personLines = lines
const links = (p.attachmentRefs || [])
.map((file) => String(file.url || '').trim())
.filter((url) => url && !/^(?!https?:)[a-z][a-z0-9+.-]*:/i.test(url))
.map(resolveUrl)
.filter((url) => /^https?:\/\//i.test(url))
if (links.length) item.attachmentLinks = links
}
items.push(item)
continue
}
if (isCcProgressItem(p)) {
if (!ccBuf) ccBuf = { names: [], ts }
if (names.length) ccBuf.names.push(...names)
+6
View File
@@ -59,6 +59,12 @@ export function fetchCollectionProtocolStatusChanges(protocolId: string) {
})
}
export function fetchCollectionProtocolOperationLogs(protocolId: string) {
return request.get<{ list: Array<Record<string, unknown>> }>({
url: `/web/admin/collection-protocols/${protocolId}/operation-logs`
})
}
export function fetchCollectionProtocolAuditList(params?: {
page?: number
pageSize?: number
+6
View File
@@ -118,6 +118,12 @@ export function fetchDonationStatusChanges(donationId: string) {
})
}
export function fetchDonationOperationLogs(donationId: string) {
return request.get<{ list: Array<Record<string, unknown>> }>({
url: `/web/admin/research-donations/${donationId}/operation-logs`
})
}
// 状态变更
export function fetchDonationStatusChange(
donationId: string,
@@ -86,6 +86,9 @@
<div v-else-if="f.comment" class="oa-print-flow__comment">
意见:{{ f.comment }}
</div>
<div v-for="url in f.attachmentLinks" :key="url" class="oa-print-url">
<a :href="url" data-oa-print-link>{{ url }}</a>
</div>
</td>
</tr>
</template>
@@ -221,6 +224,10 @@
background: #fff;
}
.oa-print-url a {
color: inherit;
}
.oa-print-url {
color: #3370ff;
word-break: break-all;
@@ -248,6 +255,8 @@
}
.oa-print-flow__left {
white-space: pre-wrap;
overflow-wrap: anywhere;
flex: 1 1 auto;
min-width: 0;
}
@@ -0,0 +1,90 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { buildFlowItems } from './oa-approval-print-flow'
describe('打印讨论评论', () => {
it('按时间展示正文、提及和附件,并排在待审节点前', () => {
const items = buildFlowItems({
progress: [
{ kind: 'submit', title: '发起人', status: 'submitted', timestamp: '2026-11-01 10:00:00' },
{
kind: 'pending_node',
title: '审批人',
status: 'pending',
timestamp: '2026-11-01 10:00:00'
}
],
comments: [
{
id: '2',
createByName: '李四',
createTime: '2026-11-01 12:00:00',
content: '',
attachmentRefs: [{ url: 'https://example.com/file.pdf', fileName: '附件.pdf' }]
},
{
id: '1',
createByName: '张三',
createTime: '2026-11-01 11:00:00',
content: '@李四 请处理\n第二行',
mentions: [{ userId: 'u2', userName: '李四' }]
}
]
})
assert.equal(items.length, 4)
assert.equal(items[1].left, '【评论】 张三')
assert.equal(items[1].right, '2026-11-01 11:00:00')
assert.deepEqual(items[1].personLines, [
{ left: '@李四 请处理\n第二行', right: '' },
{ left: '提到:@李四', right: '' }
])
assert.deepEqual(items[2].attachmentLinks, ['https://example.com/file.pdf'])
assert.match(items[3].left, /待处理/)
})
it('撤回评论不泄露正文、提及和附件', () => {
const [item] = buildFlowItems({
comments: [
{
id: '1',
createBy: 'u1',
status: 'revoked',
content: 'secret',
mentions: [{ userName: 'secret' }],
attachmentRefs: [{ url: 'https://example.com/secret' }]
}
]
})
assert.equal(item.left, '【评论】 u1 已撤回')
assert.equal(JSON.stringify(item).includes('secret'), false)
})
it('安全过滤附件协议,保留纯附件与纯提及评论', () => {
const items = buildFlowItems({
comments: [
{
id: '1',
mentions: [{ userId: 'u1' }],
attachmentRefs: [{ url: 'javascript:alert(1)' }, { url: 'https://example.com/a?x=1&y=2' }]
}
]
})
assert.deepEqual(items[0].attachmentLinks, ['https://example.com/a?x=1&y=2'])
assert.deepEqual(items[0].personLines, [{ left: '提到:@u1', right: '' }])
})
})
it('同秒节点使用详情页的稳定排序键', () => {
const progress = Array.from({ length: 12 }, (_, index) => ({
kind: 'task',
nodeKey: `node-${String(11 - index).padStart(2, '0')}`,
title: `节点${11 - index}`,
status: 'approved',
timestamp: '2026-11-01 10:00:00'
}))
const items = buildFlowItems({
progress,
comments: [{ id: 'comment', content: '讨论', createTime: '2026-11-01 10:00:00' }]
})
assert.equal(items[0].left, '【节点0】 已同意')
assert.equal(items[11].left, '【节点11】 已同意')
assert.equal(items[12].left, '【评论】 评论')
})
+50 -8
View File
@@ -1,3 +1,4 @@
import { mergeProgressWithComments } from './oa-progress-merge-comments'
/**
* OA 打印「审批流程」行组装(无 Vue/canvas 副作用,便于单测)
*/
@@ -11,6 +12,7 @@ export type OaPrintPersonLine = {
export type OaPrintFlowItem = {
left: string
right: string
attachmentLinks?: string[]
/** @deprecated 多人节点改用 personLines;单人/发起人可保留 */
comment?: string
/** 或签/会签按人行:左侧文案 + 右侧时间(右对齐) */
@@ -66,20 +68,29 @@ function isCcProgressItem(p: any): boolean {
const taskType = String(p?.taskType || p?.task_type || '').trim()
const signMode = String(p?.signMode || p?.sign_mode || '').trim()
const title = String(p?.title || p?.nodeName || '').trim()
return (
taskType === 'cc' ||
signMode === 'cc' ||
title === '抄送人' ||
/^抄送/.test(title)
)
return taskType === 'cc' || signMode === 'cc' || title === '抄送人' || /^抄送/.test(title)
}
/**
* 从 progress 组装审批流程行;抄送节点聚合为「抄送A, B, C」对齐钉钉导出。
* 若 progress 漏抄送,则用 tasks 兜底补一行。
*/
export function buildFlowItems(detail: any): OaPrintFlowItem[] {
const list = Array.isArray(detail?.progress) ? detail.progress : []
export function buildFlowItems(
detail: any,
resolveUrl: (url: string) => string = (url) => url
): OaPrintFlowItem[] {
const progress = Array.isArray(detail?.progress) ? detail.progress : []
// 沿用详情页的时间顺序;无讨论时保持原有审批节点顺序。
const list =
Array.isArray(detail?.comments) && detail.comments.length
? mergeProgressWithComments(
progress.map((p: any, index: number) => ({
...p,
key: `${p.kind}-${p.nodeKey || p.taskId || index}-${p.roundNo || 1}`
})),
detail.comments
)
: progress
const items: OaPrintFlowItem[] = []
let ccBuf: { names: string[]; ts: string } | null = null
@@ -104,6 +115,37 @@ export function buildFlowItems(detail: any): OaPrintFlowItem[] {
const signMode = String(p.signMode || p.sign_mode || '')
const signLabel = signMode === 'and' ? '会签' : signMode === 'or' ? '或签' : ''
if (kind === 'comment') {
flushCc()
const revoked = p.status === 'revoked'
const author = String(p.assignee || p.title || '评论').trim()
const item: OaPrintFlowItem = {
left: `【评论】 ${author}${revoked ? ' 已撤回' : ''}`,
right: ts
}
if (!revoked) {
const lines = []
if (comment) lines.push({ left: comment, right: '' })
const mentions = (p.mentions || [])
.map((m: any) => String(m.userName || m.userId || '').trim())
.filter(Boolean)
if (mentions.length)
lines.push({
left: `提到:${mentions.map((name: string) => `@${name}`).join('、')}`,
right: ''
})
if (lines.length) item.personLines = lines
const links = (p.attachmentRefs || [])
.map((file: any) => String(file.url || '').trim())
.filter((url: string) => url && !/^(?!https?:)[a-z][a-z0-9+.-]*:/i.test(url))
.map(resolveUrl)
.filter((url: string) => /^https?:\/\//i.test(url))
if (links.length) item.attachmentLinks = links
}
items.push(item)
continue
}
if (isCcProgressItem(p)) {
if (!ccBuf) ccBuf = { names: [], ts }
if (names.length) ccBuf.names.push(...names)
+27 -3
View File
@@ -1,3 +1,4 @@
import { attachmentFullUrl } from '@/composables/useAttachmentActions'
/**
* OA 审批单钉钉风格 PDF 导出
*/
@@ -398,7 +399,13 @@ export async function buildOaPrintModel(
stampClass,
stampText,
rows: [...headerRows, ...formRows],
flowItems: buildFlowItems(detail),
flowItems: buildFlowItems(detail, (url) => {
try {
return new URL(attachmentFullUrl(url), window.location.origin).href
} catch {
return ''
}
}),
printTime,
printerName,
watermarkName: printerName === '-' ? '审批' : printerName
@@ -447,7 +454,7 @@ function renderPageLabelCanvas(text: string): HTMLCanvasElement {
return c
}
async function canvasToPdf(canvas: HTMLCanvasElement, filename: string) {
async function canvasToPdf(canvas: HTMLCanvasElement, filename: string, sheet: HTMLElement) {
const pdf = new jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' })
const pageWidth = pdf.internal.pageSize.getWidth()
const pageHeight = pdf.internal.pageSize.getHeight()
@@ -466,6 +473,23 @@ async function canvasToPdf(canvas: HTMLCanvasElement, filename: string) {
const position = -pageIndex * pageHeight
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
// html2canvas 只保留像素,单独把附件链接写为 PDF 注解;跨页部分按页裁切。
const sheetRect = sheet.getBoundingClientRect()
const ratio = pageWidth / sheetRect.width
for (const link of sheet.querySelectorAll<HTMLAnchorElement>('a[data-oa-print-link]')) {
if (!/^https?:\/\//i.test(link.href)) continue
for (const rect of link.getClientRects()) {
const top = (rect.top - sheetRect.top) * ratio - pageIndex * pageHeight
const bottom = Math.min(pageHeight, top + rect.height * ratio)
const y = Math.max(0, top)
if (bottom > y) {
pdf.link((rect.left - sheetRect.left) * ratio, y, rect.width * ratio, bottom - y, {
url: link.href
})
}
}
}
const label = `第${pageIndex + 1}页`
const labelCanvas = renderPageLabelCanvas(label)
if (labelCanvas.width > 1) {
@@ -526,7 +550,7 @@ export async function exportOaApprovalPdf(
windowWidth: el.scrollWidth,
windowHeight: el.scrollHeight
})
await canvasToPdf(canvas, filename)
await canvasToPdf(canvas, filename, el)
} finally {
app.unmount()
host.remove()
+1 -1
View File
@@ -363,7 +363,7 @@ export const taskStatusTagType = createTagTypeGetter(taskStatus)
export const acceptConclusion: StatusRegistry = {
js: { label: '接收', tagType: 'success' },
bj: { label: '拒收', tagType: 'danger' }
bj: { label: '废弃', tagType: 'danger' }
}
export const acceptConclusionLabel = createLabelGetter(acceptConclusion)
export const acceptConclusionTagType = createTagTypeGetter(acceptConclusion)
+2 -1
View File
@@ -6,7 +6,8 @@ export const VOID_TYPE_DICT = 'xyzflx'
const FALLBACK_LABELS: Record<string, string> = {
khhc: '客户毁存',
jcbhg: '检测不合格'
jcbhg: '检测不合格',
sysfq: '实验室废弃'
}
function buildFallbackOptions(): Api.Dict.DictDataOption[] {
@@ -69,8 +69,7 @@
@selection-change="(rows: any[]) => (selectedRows = rows)"
@row-dblclick="handleEdit"
>
<el-table-column prop="projectName" label="所属项目" min-width="160"/><el-table-column prop="teamName" label="项目组" min-width="150"/>
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column
type="index"
label="序号"
@@ -79,6 +78,8 @@
header-align="center"
:index="(index) => (pagination.page - 1) * pagination.pageSize + index + 1"
/>
<el-table-column prop="projectName" label="所属项目" min-width="160" />
<el-table-column prop="teamName" label="项目组" min-width="150" />
<el-table-column
prop="orderDate"
label="业务日期"
@@ -132,11 +132,12 @@
@selection-change="handleSelectionChange"
@row-dblclick="handleRowDblClick"
>
<el-table-column prop="projectName" label="所属项目" min-width="160"/><el-table-column prop="teamName" label="项目组" min-width="150"/>
<el-table-column type="selection" min-width="48" align="center" header-align="center" />
<el-table-column type="selection" min-width="48" align="center" header-align="center" />
<el-table-column label="序号" min-width="64" align="center" header-align="center">
<template #default="{ $index }">{{ $index + 1 }}</template>
</el-table-column>
<el-table-column prop="projectName" label="所属项目" min-width="160" />
<el-table-column prop="teamName" label="项目组" min-width="150" />
<el-table-column
prop="collectDate"
label="采集日期"
@@ -144,11 +144,12 @@
@selection-change="handleSelectionChange"
@row-dblclick="handleRowDblClick"
>
<el-table-column prop="projectName" label="所属项目" min-width="160"/><el-table-column prop="teamName" label="项目组" min-width="150"/>
<el-table-column type="selection" min-width="48" align="center" header-align="center" />
<el-table-column type="selection" min-width="48" align="center" header-align="center" />
<el-table-column label="序号" min-width="64" align="center" header-align="center">
<template #default="{ $index }">{{ $index + 1 }}</template>
</el-table-column>
<el-table-column prop="projectName" label="所属项目" min-width="160" />
<el-table-column prop="teamName" label="项目组" min-width="150" />
<el-table-column
prop="collectDate"
label="采集日期"
@@ -1174,6 +1174,41 @@
</el-table>
</div>
</div>
<!-- 操作日志(Issue #24) -->
<div id="view-section-operation-log" class="section-card section-card--white">
<div class="section-title section-title--banner"><h3>操作日志</h3></div>
<div class="list-body list-wrap view-inner-table-wrap">
<el-table
v-loading="operationLogLoading"
class="list-table inner-table"
:data="operationLogRecords"
stripe
empty-text="暂无操作日志"
>
<el-table-column type="index" label="序号" min-width="68" align="center" header-align="center" />
<el-table-column label="动作" min-width="100" align="center" header-align="center">
<template #default="{ row }">
<el-tag :type="operationActionTagType(String(row.action || ''))" size="small">
{{ operationActionLabel(String(row.action || '')) }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="来源端" min-width="90" align="center" header-align="center">
<template #default="{ row }">{{ operationChannelLabel(String(row.clientChannel || '')) }}</template>
</el-table-column>
<el-table-column label="操作时间" min-width="170" align="center" header-align="center">
<template #default="{ row }">{{ dash(row.operateTime) }}</template>
</el-table-column>
<el-table-column label="操作人" min-width="120" align="center" header-align="center">
<template #default="{ row }">{{ dash(row.operatorUserName) }}</template>
</el-table-column>
<el-table-column label="变更摘要" min-width="260" align="left" header-align="center" show-overflow-tooltip>
<template #default="{ row }">{{ operationSummary(row) }}</template>
</el-table-column>
</el-table>
</div>
</div>
</div>
</template>
</div>
@@ -1226,6 +1261,7 @@
fetchCollectionProtocolAuditList,
fetchCollectionProtocolDetail,
fetchCollectionProtocolStatusChanges,
fetchCollectionProtocolOperationLogs,
type CollectionProtocolRow
} from '@/api/collection-protocol'
import {
@@ -1317,6 +1353,7 @@
}
tabs.push({ key: 'attachment', label: '附件信息' })
tabs.push({ key: 'status-change', label: '状态变更记录' })
tabs.push({ key: 'operation-log', label: '操作日志' })
return tabs
})
@@ -1327,6 +1364,90 @@
const bundle = ref<Record<string, any> | null>(null)
const auditRecords = ref<Array<Record<string, unknown>>>([])
const statusChangeRecords = ref<Array<Record<string, unknown>>>([])
const operationLogLoading = ref(false)
const operationLogRecords = ref<Array<Record<string, unknown>>>([])
const OPERATION_ACTION_LABEL: Record<string, string> = {
create: '创建',
update: '修改',
delete: '删除',
void: '作废',
activate: '生效',
expire: '过期',
to_research: '转科研',
to_storage: '转细胞存储',
audit: '审核'
}
const OPERATION_ACTION_TAG: Record<string, 'success' | 'warning' | 'danger' | 'primary' | 'info'> = {
create: 'success',
update: 'primary',
delete: 'danger',
void: 'danger',
activate: 'success',
expire: 'warning',
to_research: 'primary',
to_storage: 'primary',
audit: 'info'
}
function operationActionLabel(action: string) {
return OPERATION_ACTION_LABEL[action] || action || '—'
}
function operationActionTagType(action: string) {
return OPERATION_ACTION_TAG[action] || 'info'
}
function operationChannelLabel(channel: string) {
if (channel === 'mini') return '小程序'
if (channel === 'web') return 'Web'
return channel || '—'
}
function operationSummary(row: Record<string, unknown>) {
const before = (row.before || {}) as Record<string, any>
const after = (row.after || {}) as Record<string, any>
const beforeProto = (before.protocol || before.donation || {}) as Record<string, any>
const afterProto = (after.protocol || after.donation || {}) as Record<string, any>
const beforeParty = (before.partyCustomer || before.party || {}) as Record<string, any>
const afterParty = (after.partyCustomer || after.party || {}) as Record<string, any>
const parts: string[] = []
const beforeStatus = String(beforeProto.protocolStatus || beforeProto.donationStatus || '')
const afterStatus = String(afterProto.protocolStatus || afterProto.donationStatus || '')
if (beforeStatus || afterStatus) {
if (beforeStatus && afterStatus && beforeStatus !== afterStatus) {
parts.push(`状态 ${beforeStatus}→${afterStatus}`)
} else if (afterStatus) {
parts.push(`状态 ${afterStatus}`)
}
}
for (const key of ['motherName', 'customerName', 'donorName', 'name']) {
const b = String(beforeParty[key] || '').trim()
const a = String(afterParty[key] || '').trim()
if (b || a) {
if (b && a && b !== a) parts.push(`姓名 ${b}→${a}`)
else if (a && !b) parts.push(`姓名 ${a}`)
break
}
}
const beforeSamples = Array.isArray(before.samples) ? before.samples : []
const afterSamples = Array.isArray(after.samples) ? after.samples : []
if (beforeSamples.length || afterSamples.length) {
const pick = (list: any[]) =>
list
.map((s) => `${s?.sampleCode || ''}:${s?.sampleStatus || s?.status || ''}`)
.filter((x) => x !== ':')
.join(',')
const bs = pick(beforeSamples)
const as = pick(afterSamples)
if (bs || as) {
if (bs && as && bs !== as) parts.push(`样本 ${bs}→${as}`)
else if (as) parts.push(`样本 ${as}`)
}
}
if (!parts.length) {
const remark = String(row.remark || '').trim()
return remark || '见前后快照'
}
return parts.join(';')
}
const STATUS_CHANGE_TYPE_LABEL: Record<string, string> = {
activate: '生效',
@@ -2088,6 +2209,22 @@
}
}
async function loadOperationLogRecords() {
if (!props.protocolId) {
operationLogRecords.value = []
return
}
operationLogLoading.value = true
try {
const res = await fetchCollectionProtocolOperationLogs(props.protocolId)
operationLogRecords.value = res.list || []
} catch {
operationLogRecords.value = []
} finally {
operationLogLoading.value = false
}
}
async function loadAuditRecords() {
if (!props.showAuditHistory || !props.protocolId) {
auditRecords.value = []
@@ -2115,10 +2252,12 @@
bundle.value = null
auditRecords.value = []
statusChangeRecords.value = []
operationLogRecords.value = []
const baseLookupsPromise = loadBaseLookups().catch(() => {})
const auditPromise = props.showAuditHistory ? loadAuditRecords() : null
const statusChangePromise = loadStatusChangeRecords()
const operationLogPromise = loadOperationLogRecords()
let data: Record<string, any> | null = null
try {
@@ -2136,6 +2275,7 @@
void finishLookups(data, baseLookupsPromise)
void auditPromise
void statusChangePromise
void operationLogPromise
if (props.highlightSampleCode) {
nextTick(() => {
document
@@ -2159,6 +2299,7 @@
bundle.value = null
auditRecords.value = []
statusChangeRecords.value = []
operationLogRecords.value = []
activeTab.value = 'basic'
detailLoading.value = false
lookupLoading.value = false
@@ -105,8 +105,7 @@
@selection-change="handleSelectionChange"
@row-dblclick="handleView"
>
<el-table-column prop="projectName" label="所属项目" min-width="160"/><el-table-column prop="teamName" label="项目组" min-width="150"/>
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column
type="index"
label="序号"
@@ -115,6 +114,8 @@
header-align="center"
:index="(index) => (pagination.page - 1) * pagination.pageSize + index + 1"
/>
<el-table-column prop="projectName" label="所属项目" min-width="160" />
<el-table-column prop="teamName" label="项目组" min-width="150" />
<el-table-column
prop="protocolStatus"
label="状态"
@@ -116,9 +116,7 @@
@selection-change="handleSelectionChange"
@row-dblclick="handleView"
>
<el-table-column v-if="!isClinical" prop="projectName" label="所属项目" min-width="160" />
<el-table-column v-if="!isClinical" prop="teamName" label="项目组" min-width="150" />
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column
type="index"
label="序号"
@@ -127,6 +125,8 @@
header-align="center"
:index="(index) => (pagination.page - 1) * pagination.pageSize + index + 1"
/>
<el-table-column v-if="!isClinical" prop="projectName" label="所属项目" min-width="160" />
<el-table-column v-if="!isClinical" prop="teamName" label="项目组" min-width="150" />
<el-table-column
prop="applicationNo"
label="申请单号"
@@ -118,7 +118,7 @@
<el-dialog
v-model="visible"
:title="`${readonly ? '查看' : editingId ? '编辑' : '新增'}${isTeam ? '项目组' : '项目'}`"
width="720px"
:width="isTeam && !readonly ? '960px' : '720px'"
class="dialog-form-layout"
append-to-body
modal-class="protocol-dialog-mask"
@@ -163,7 +163,7 @@
:label="user.name" /></el-select
></el-form-item>
<template v-if="isTeam">
<el-form-item label="成员"
<el-form-item label="成员" :class="{ 'form-col-span-2': !readonly }"
><el-select v-model="memberIds" multiple filterable
><el-option
v-for="user in refs.users"
@@ -171,7 +171,7 @@
:value="user.id"
:label="user.name" /></el-select
></el-form-item>
<el-form-item label="负责地区(信息记录)"
<el-form-item label="负责地区(信息记录)" :class="{ 'form-col-span-2': !readonly }"
><el-select v-model="regionIds" multiple filterable
><el-option
v-for="region in refs.regions"
@@ -179,7 +179,7 @@
:value="region.id"
:label="region.name" /></el-select
></el-form-item>
<el-form-item label="负责医院(信息记录)"
<el-form-item label="负责医院(信息记录)" :class="{ 'form-col-span-2': !readonly }"
><el-select v-model="hospitalIds" multiple filterable
><el-option
v-for="hospital in refs.hospitals"
@@ -187,7 +187,9 @@
:value="hospital.id"
:label="hospital.name" /></el-select
></el-form-item>
<el-form-item label="启用"><el-switch v-model="form.enabled" /></el-form-item>
<el-form-item label="启用" :class="{ 'form-col-span-2': !readonly }"
><el-switch v-model="form.enabled"
/></el-form-item>
<div class="form-tip form-col-span-2"
>地区、医院仅记录项目组职责,不改变业务地点候选或数据权限。</div
>
@@ -290,7 +290,7 @@
@change="onReceiveAcceptConclusionChange"
>
<el-radio value="js">接收</el-radio>
<el-radio value="bj">拒收</el-radio>
<el-radio value="bj">废弃</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="实验室入库编码" prop="labStorageCode">
@@ -643,7 +643,7 @@
@change="() => onBatchAcceptConclusionChange(entry)"
>
<el-radio value="js">接收</el-radio>
<el-radio value="bj">拒收</el-radio>
<el-radio value="bj">废弃</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item
@@ -482,6 +482,41 @@
</el-table>
</div>
</div>
<!-- 操作日志(Issue #24) -->
<div id="view-section-operation-log" class="section-card section-card--white">
<div class="section-title section-title--banner"><h3>操作日志</h3></div>
<div class="list-body list-wrap view-inner-table-wrap">
<el-table
v-loading="operationLogLoading"
class="list-table inner-table"
:data="operationLogRecords"
stripe
empty-text="暂无操作日志"
>
<el-table-column type="index" label="序号" min-width="68" align="center" header-align="center" />
<el-table-column label="动作" min-width="100" align="center" header-align="center">
<template #default="{ row }">
<el-tag :type="operationActionTagType(String(row.action || ''))" size="small">
{{ operationActionLabel(String(row.action || '')) }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="来源端" min-width="90" align="center" header-align="center">
<template #default="{ row }">{{ operationChannelLabel(String(row.clientChannel || '')) }}</template>
</el-table-column>
<el-table-column label="操作时间" min-width="170" align="center" header-align="center">
<template #default="{ row }">{{ dash(row.operateTime) }}</template>
</el-table-column>
<el-table-column label="操作人" min-width="120" align="center" header-align="center">
<template #default="{ row }">{{ dash(row.operatorUserName) }}</template>
</el-table-column>
<el-table-column label="变更摘要" min-width="260" align="left" header-align="center" show-overflow-tooltip>
<template #default="{ row }">{{ operationSummary(row) }}</template>
</el-table-column>
</el-table>
</div>
</div>
</div>
</template>
</div>
@@ -532,6 +567,7 @@
import SampleStorageReleaseInfo from '@/components/business/sample-storage-release-info/index.vue'
import {
fetchDonationStatusChanges,
fetchDonationOperationLogs,
fetchResearchDonationAuditList,
fetchResearchDonationDetail,
type ResearchDonationRow
@@ -593,16 +629,79 @@
tabs.push({ key: 'audit', label: '审核记录' })
}
tabs.push({ key: 'attachment', label: '附件信息' })
tabs.push({ key: 'status-change', label: '状态变更记录' })
tabs.push({ key: 'status-change', label: '状态变更记录' }, { key: 'operation-log', label: '操作日志' })
return tabs
})
const loading = ref(false)
const auditLoading = ref(false)
const statusChangeLoading = ref(false)
const operationLogLoading = ref(false)
const bundle = ref<Record<string, any> | null>(null)
const auditRecords = ref<Array<Record<string, unknown>>>([])
const statusChangeRecords = ref<Array<Record<string, unknown>>>([])
const operationLogRecords = ref<Array<Record<string, unknown>>>([])
const OPERATION_ACTION_LABEL: Record<string, string> = {
create: '创建',
update: '修改',
delete: '删除',
void: '作废',
activate: '生效',
expire: '过期',
to_research: '转科研',
to_storage: '转细胞存储',
audit: '审核'
}
const OPERATION_ACTION_TAG: Record<
string,
'success' | 'warning' | 'danger' | 'primary' | 'info'
> = {
create: 'success',
update: 'primary',
delete: 'danger',
void: 'danger',
activate: 'success',
expire: 'warning',
to_research: 'primary',
to_storage: 'primary',
audit: 'info'
}
function operationActionLabel(action: string) {
return OPERATION_ACTION_LABEL[action] || action || '—'
}
function operationActionTagType(action: string) {
return OPERATION_ACTION_TAG[action] || 'info'
}
function operationChannelLabel(channel: string) {
if (channel === 'mini') return '小程序'
if (channel === 'web') return 'Web'
return channel || '—'
}
function operationSummary(row: Record<string, unknown>) {
const before = (row.before || {}) as Record<string, any>
const after = (row.after || {}) as Record<string, any>
const beforeProto = (before.donation || before.protocol || {}) as Record<string, any>
const afterProto = (after.donation || after.protocol || {}) as Record<string, any>
const beforeParty = (before.party || before.partyCustomer || {}) as Record<string, any>
const afterParty = (after.party || after.partyCustomer || {}) as Record<string, any>
const parts: string[] = []
const bs = String(beforeProto.donationStatus || beforeProto.protocolStatus || '')
const as = String(afterProto.donationStatus || afterProto.protocolStatus || '')
if (bs && as && bs !== as) parts.push(`状态 ${bs}→${as}`)
else if (as) parts.push(`状态 ${as}`)
for (const key of ['motherName', 'customerName', 'donorName', 'name']) {
const b = String(beforeParty[key] || '').trim()
const a = String(afterParty[key] || '').trim()
if (b || a) {
if (b && a && b !== a) parts.push(`姓名 ${b}→${a}`)
else if (a && !b) parts.push(`姓名 ${a}`)
break
}
}
return parts.join(';') || String(row.remark || '').trim() || '见前后快照'
}
const STATUS_CHANGE_TYPE_LABEL: Record<string, string> = {
activate: '生效',
@@ -959,6 +1058,22 @@
}
}
async function loadOperationLogRecords() {
if (!props.donationId) {
operationLogRecords.value = []
return
}
operationLogLoading.value = true
try {
const res = await fetchDonationOperationLogs(props.donationId)
operationLogRecords.value = res.list || []
} catch {
operationLogRecords.value = []
} finally {
operationLogLoading.value = false
}
}
async function loadAuditRecords() {
if (!props.showAuditHistory || !props.donationId) {
auditRecords.value = []
@@ -985,12 +1100,17 @@
bundle.value = null
auditRecords.value = []
statusChangeRecords.value = []
operationLogRecords.value = []
void loadVoidTypeDict()
try {
const data = await fetchResearchDonationDetail(props.donationId)
bundle.value = data as Record<string, any>
await loadLookups(data as Record<string, any>)
await Promise.all([loadAuditRecords(), loadStatusChangeRecords()])
await Promise.all([
loadAuditRecords(),
loadStatusChangeRecords(),
loadOperationLogRecords()
])
if (props.highlightSampleCode) {
nextTick(() => {
document
@@ -1017,10 +1137,12 @@
bundle.value = null
auditRecords.value = []
statusChangeRecords.value = []
operationLogRecords.value = []
activeTab.value = 'basic'
loading.value = false
auditLoading.value = false
statusChangeLoading.value = false
operationLogLoading.value = false
}
watch(
@@ -93,8 +93,7 @@
@selection-change="handleSelectionChange"
@row-dblclick="handleView"
>
<el-table-column prop="projectName" label="所属项目" min-width="160"/><el-table-column prop="teamName" label="项目组" min-width="150"/>
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column
type="index"
label="序号"
@@ -103,6 +102,8 @@
header-align="center"
:index="(index) => (pagination.page - 1) * pagination.pageSize + index + 1"
/>
<el-table-column prop="projectName" label="所属项目" min-width="160" />
<el-table-column prop="teamName" label="项目组" min-width="150" />
<el-table-column
prop="donationStatus"
label="状态"