供运维 dry-run/--apply 修历史数据,不改日常接口路径。 Co-authored-by: Cursor <cursoragent@cursor.com>
468 lines
15 KiB
Python
468 lines
15 KiB
Python
#!/usr/bin/env python3
|
||
"""作废「已完成合同审批」中未被付款审批关联的重复单。
|
||
|
||
背景:发起人误提两张相同合同审批,其中一张已被付款单通过 oa_relation 关联,
|
||
另一张未关联。产品撤回 API 仅允许 running→cancelled,无法作废已完成单。
|
||
|
||
本脚本:
|
||
1) 按申请人昵称 + 流程名「合同审批」定位候选实例
|
||
2) 用 oa_relation.to_instance_id 区分已关联 / 未关联
|
||
3) 断言恰好 1 张已关联、1 张未关联后,对未关联单软删除作废
|
||
|
||
用法(backend 目录、已配置目标库):
|
||
python -m scripts.repair_oa_void_unlinked_contract_duplicate \\
|
||
--nick-name 胡倩茜 --create-time '2026-11-25 12:00:56'
|
||
|
||
python -m scripts.repair_oa_void_unlinked_contract_duplicate \\
|
||
--nick-name 胡倩茜 --create-time '2026-11-25 12:00:56' --apply
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import os
|
||
import sys
|
||
from datetime import datetime
|
||
from typing import Any, Dict, List, Optional
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
from sqlalchemy.orm import Session
|
||
|
||
from app.core.database import SessionLocal
|
||
from app.core.utils import generate_uuid
|
||
from app.models.models import (
|
||
OaApp,
|
||
OaInstance,
|
||
OaInstanceEvent,
|
||
OaRelation,
|
||
SysUser,
|
||
)
|
||
|
||
CONTRACT_APP_NAME = "合同审批"
|
||
PAYMENT_APP_NAME = "付款审批"
|
||
|
||
|
||
def _parse_create_time(raw: Optional[str]) -> Optional[datetime]:
|
||
text = (raw or "").strip()
|
||
if not text:
|
||
return None
|
||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
|
||
try:
|
||
return datetime.strptime(text, fmt)
|
||
except ValueError:
|
||
continue
|
||
raise RuntimeError(
|
||
f"无法解析 --create-time={raw!r},请用 'YYYY-MM-DD HH:MM:SS'"
|
||
)
|
||
|
||
|
||
def _find_user(db: Session, *, nick_name: str, tenant_no: Optional[str]) -> SysUser:
|
||
q = db.query(SysUser).filter(
|
||
SysUser.del_flag == 0,
|
||
SysUser.nick_name == nick_name,
|
||
)
|
||
if tenant_no:
|
||
q = q.filter(SysUser.tenant_no == tenant_no)
|
||
rows = q.all()
|
||
if not rows:
|
||
raise RuntimeError(f"未找到用户 nick_name={nick_name!r}")
|
||
if len(rows) > 1 and not tenant_no:
|
||
raise RuntimeError(
|
||
"匹配到多名用户,请加 --tenant。"
|
||
f" 候选: {[{'id': u.id, 'tenantNo': u.tenant_no, 'userNo': u.user_no} for u in rows]}"
|
||
)
|
||
return rows[0]
|
||
|
||
|
||
def _find_app(db: Session, *, app_name: str, tenant_no: str) -> OaApp:
|
||
row = (
|
||
db.query(OaApp)
|
||
.filter(
|
||
OaApp.del_flag == 0,
|
||
OaApp.tenant_no == tenant_no,
|
||
OaApp.app_name == app_name,
|
||
)
|
||
.first()
|
||
)
|
||
if not row:
|
||
# 宽松匹配,便于生产命名略有差异时定位
|
||
cands = (
|
||
db.query(OaApp)
|
||
.filter(
|
||
OaApp.del_flag == 0,
|
||
OaApp.tenant_no == tenant_no,
|
||
OaApp.app_name.like(f"%{app_name}%"),
|
||
)
|
||
.all()
|
||
)
|
||
names = [a.app_name for a in cands]
|
||
raise RuntimeError(
|
||
f"未找到应用 app_name={app_name!r} tenant={tenant_no!r};近似: {names}"
|
||
)
|
||
return row
|
||
|
||
|
||
def _list_contract_instances(
|
||
db: Session,
|
||
*,
|
||
user: SysUser,
|
||
contract_app: OaApp,
|
||
create_time: Optional[datetime],
|
||
) -> List[OaInstance]:
|
||
q = db.query(OaInstance).filter(
|
||
OaInstance.del_flag == 0,
|
||
OaInstance.tenant_no == user.tenant_no,
|
||
OaInstance.app_id == contract_app.id,
|
||
OaInstance.initiator_user_id == user.id,
|
||
OaInstance.status == "completed",
|
||
)
|
||
if create_time is not None:
|
||
q = q.filter(OaInstance.create_time == create_time)
|
||
rows = q.order_by(OaInstance.create_time.asc(), OaInstance.id.asc()).all()
|
||
if not rows:
|
||
raise RuntimeError(
|
||
"未找到已完成的合同审批实例。"
|
||
f" user={user.nick_name} app={contract_app.app_name}"
|
||
f" create_time={create_time}"
|
||
)
|
||
if len(rows) < 2:
|
||
raise RuntimeError(
|
||
f"仅找到 {len(rows)} 张已完成合同审批,预期至少 2 张重复单。"
|
||
f" ids={[r.id for r in rows]}"
|
||
)
|
||
if create_time is None and len(rows) > 2:
|
||
raise RuntimeError(
|
||
f"未指定 --create-time 时匹配到 {len(rows)} 张,请加上精确申请时间缩小范围。"
|
||
f" ids={[r.id for r in rows]}"
|
||
)
|
||
return rows
|
||
|
||
|
||
def _linked_contract_ids(
|
||
db: Session, *, contract_ids: List[str], tenant_no: str
|
||
) -> Dict[str, List[Dict[str, Any]]]:
|
||
"""返回 contract_id -> 关联边摘要(付款 from → 合同 to)。"""
|
||
if not contract_ids:
|
||
return {}
|
||
rels = (
|
||
db.query(OaRelation)
|
||
.filter(
|
||
OaRelation.del_flag == 0,
|
||
OaRelation.tenant_no == tenant_no,
|
||
OaRelation.to_instance_id.in_(contract_ids),
|
||
)
|
||
.all()
|
||
)
|
||
out: Dict[str, List[Dict[str, Any]]] = {cid: [] for cid in contract_ids}
|
||
if not rels:
|
||
return out
|
||
|
||
from_ids = list({r.from_instance_id for r in rels})
|
||
from_inst = {
|
||
i.id: i
|
||
for i in db.query(OaInstance)
|
||
.filter(OaInstance.id.in_(from_ids), OaInstance.del_flag == 0)
|
||
.all()
|
||
}
|
||
app_ids = list({i.app_id for i in from_inst.values()})
|
||
apps = {
|
||
a.id: a
|
||
for a in db.query(OaApp).filter(OaApp.id.in_(app_ids), OaApp.del_flag == 0).all()
|
||
}
|
||
for r in rels:
|
||
fi = from_inst.get(r.from_instance_id)
|
||
app = apps.get(fi.app_id) if fi else None
|
||
out.setdefault(r.to_instance_id, []).append(
|
||
{
|
||
"relationId": r.id,
|
||
"paymentInstanceId": r.from_instance_id,
|
||
"paymentStatus": getattr(fi, "status", None),
|
||
"paymentAppName": getattr(app, "app_name", None),
|
||
"fieldKey": r.field_key,
|
||
"relationCreateTime": str(r.create_time) if r.create_time else None,
|
||
}
|
||
)
|
||
return out
|
||
|
||
|
||
def _void_instance(
|
||
db: Session,
|
||
*,
|
||
inst: OaInstance,
|
||
actor_user_id: Optional[str],
|
||
mode: str,
|
||
) -> Dict[str, Any]:
|
||
now = datetime.now()
|
||
before = {"id": inst.id, "status": inst.status, "delFlag": inst.del_flag}
|
||
if mode == "soft-delete":
|
||
inst.del_flag = 1
|
||
inst.status = "cancelled"
|
||
elif mode == "cancel":
|
||
inst.status = "cancelled"
|
||
else:
|
||
raise RuntimeError(f"未知 --mode={mode!r}")
|
||
inst.update_by = actor_user_id
|
||
inst.update_time = now
|
||
remark = (
|
||
"生产数据修复:重复合同审批未关联付款,软删除作废"
|
||
if mode == "soft-delete"
|
||
else "生产数据修复:重复合同审批未关联付款,状态改为已撤销"
|
||
)
|
||
if not (inst.remark or "").strip():
|
||
inst.remark = remark
|
||
db.add(inst)
|
||
ev = OaInstanceEvent(
|
||
id=generate_uuid(),
|
||
instance_id=inst.id,
|
||
round_no=int(getattr(inst, "current_round", None) or 1),
|
||
event_type="withdraw",
|
||
actor_user_id=actor_user_id,
|
||
task_id=None,
|
||
node_key=None,
|
||
comment_text=remark,
|
||
tenant_no=inst.tenant_no,
|
||
order_num=0,
|
||
remark="repair_oa_void_unlinked_contract_duplicate",
|
||
create_by=actor_user_id,
|
||
create_dept_id=inst.initiator_dept_id or "",
|
||
create_time=now,
|
||
update_by=actor_user_id,
|
||
update_time=now,
|
||
del_flag=0,
|
||
)
|
||
db.add(ev)
|
||
return {
|
||
"before": before,
|
||
"after": {"id": inst.id, "status": inst.status, "delFlag": inst.del_flag},
|
||
"eventId": ev.id,
|
||
"mode": mode,
|
||
}
|
||
|
||
|
||
def analyze(
|
||
db: Session,
|
||
*,
|
||
nick_name: str,
|
||
create_time: Optional[datetime],
|
||
tenant_no: Optional[str],
|
||
contract_app_name: str,
|
||
) -> Dict[str, Any]:
|
||
user = _find_user(db, nick_name=nick_name, tenant_no=tenant_no)
|
||
tn = user.tenant_no
|
||
contract_app = _find_app(db, app_name=contract_app_name, tenant_no=tn)
|
||
payment_app = (
|
||
db.query(OaApp)
|
||
.filter(
|
||
OaApp.del_flag == 0,
|
||
OaApp.tenant_no == tn,
|
||
OaApp.app_name == PAYMENT_APP_NAME,
|
||
)
|
||
.first()
|
||
)
|
||
instances = _list_contract_instances(
|
||
db, user=user, contract_app=contract_app, create_time=create_time
|
||
)
|
||
ids = [i.id for i in instances]
|
||
links = _linked_contract_ids(db, contract_ids=ids, tenant_no=tn)
|
||
|
||
linked_ids: List[str] = [cid for cid, rels in links.items() if rels]
|
||
unlinked_ids: List[str] = [cid for cid in ids if cid not in linked_ids]
|
||
|
||
candidates = [
|
||
{
|
||
"id": i.id,
|
||
"title": i.title,
|
||
"status": i.status,
|
||
"createTime": str(i.create_time) if i.create_time else None,
|
||
"updateTime": str(i.update_time) if i.update_time else None,
|
||
"linkedPayments": links.get(i.id) or [],
|
||
"decision": "keep" if i.id in linked_ids else "void_candidate",
|
||
}
|
||
for i in instances
|
||
]
|
||
|
||
errors: List[str] = []
|
||
if len(linked_ids) != 1:
|
||
errors.append(
|
||
f"期望恰好 1 张已被付款关联的合同,实际 {len(linked_ids)}: {linked_ids}"
|
||
)
|
||
if len(unlinked_ids) != 1:
|
||
errors.append(
|
||
f"期望恰好 1 张未关联合同待作废,实际 {len(unlinked_ids)}: {unlinked_ids}"
|
||
)
|
||
# 关联来源最好是付款审批(非硬失败,仅警告)
|
||
warnings: List[str] = []
|
||
for cid in linked_ids:
|
||
for rel in links.get(cid) or []:
|
||
pname = (rel.get("paymentAppName") or "").strip()
|
||
if payment_app and pname and pname != PAYMENT_APP_NAME:
|
||
warnings.append(
|
||
f"合同 {cid} 被非付款应用关联: {pname} ({rel.get('paymentInstanceId')})"
|
||
)
|
||
if not pname:
|
||
warnings.append(
|
||
f"合同 {cid} 关联来源应用名未知: {rel.get('paymentInstanceId')}"
|
||
)
|
||
|
||
return {
|
||
"user": {
|
||
"id": user.id,
|
||
"nickName": user.nick_name,
|
||
"userNo": user.user_no,
|
||
"tenantNo": tn,
|
||
},
|
||
"contractApp": {"id": contract_app.id, "appName": contract_app.app_name},
|
||
"paymentApp": (
|
||
{"id": payment_app.id, "appName": payment_app.app_name}
|
||
if payment_app
|
||
else None
|
||
),
|
||
"createTimeFilter": str(create_time) if create_time else None,
|
||
"candidates": candidates,
|
||
"linkedContractIds": linked_ids,
|
||
"unlinkedContractIds": unlinked_ids,
|
||
"voidTargetId": unlinked_ids[0] if len(unlinked_ids) == 1 else None,
|
||
"keepTargetId": linked_ids[0] if len(linked_ids) == 1 else None,
|
||
"errors": errors,
|
||
"warnings": warnings,
|
||
"safeToApply": len(errors) == 0,
|
||
}
|
||
|
||
|
||
def run(
|
||
*,
|
||
nick_name: str,
|
||
create_time_raw: Optional[str],
|
||
tenant_no: Optional[str],
|
||
contract_app_name: str,
|
||
apply: bool,
|
||
mode: str,
|
||
actor_user_id: Optional[str],
|
||
) -> Dict[str, Any]:
|
||
create_time = _parse_create_time(create_time_raw)
|
||
db = SessionLocal()
|
||
try:
|
||
report = analyze(
|
||
db,
|
||
nick_name=nick_name.strip(),
|
||
create_time=create_time,
|
||
tenant_no=(tenant_no or "").strip() or None,
|
||
contract_app_name=(contract_app_name or CONTRACT_APP_NAME).strip()
|
||
or CONTRACT_APP_NAME,
|
||
)
|
||
if not apply:
|
||
db.rollback()
|
||
return {
|
||
"dryRun": True,
|
||
"mode": mode,
|
||
"analysis": report,
|
||
"message": (
|
||
"dry-run:未写库。"
|
||
"确认 voidTargetId 正确且 safeToApply=true 后加 --apply。"
|
||
),
|
||
}
|
||
if not report.get("safeToApply"):
|
||
db.rollback()
|
||
return {
|
||
"dryRun": False,
|
||
"applied": False,
|
||
"mode": mode,
|
||
"analysis": report,
|
||
"message": "分析未通过安全断言,已回滚,未写库。",
|
||
}
|
||
target_id = report["voidTargetId"]
|
||
inst = (
|
||
db.query(OaInstance)
|
||
.filter(
|
||
OaInstance.id == target_id,
|
||
OaInstance.del_flag == 0,
|
||
)
|
||
.one()
|
||
)
|
||
# 二次校验:写库前再确认仍未被关联
|
||
still_linked = (
|
||
db.query(OaRelation.id)
|
||
.filter(
|
||
OaRelation.del_flag == 0,
|
||
OaRelation.tenant_no == inst.tenant_no,
|
||
OaRelation.to_instance_id == inst.id,
|
||
)
|
||
.first()
|
||
)
|
||
if still_linked:
|
||
db.rollback()
|
||
raise RuntimeError(
|
||
f"写库前发现目标 {inst.id} 已被关联,中止作废以防误伤"
|
||
)
|
||
actor = actor_user_id or inst.initiator_user_id
|
||
void_result = _void_instance(
|
||
db, inst=inst, actor_user_id=actor, mode=mode
|
||
)
|
||
db.commit()
|
||
return {
|
||
"dryRun": False,
|
||
"applied": True,
|
||
"mode": mode,
|
||
"analysis": report,
|
||
"voidResult": void_result,
|
||
"message": "已作废未关联合同审批;已关联付款的合同未改动。",
|
||
}
|
||
except Exception:
|
||
db.rollback()
|
||
raise
|
||
finally:
|
||
db.close()
|
||
|
||
|
||
def main(argv: Optional[List[str]] = None) -> int:
|
||
parser = argparse.ArgumentParser(
|
||
description="作废未被付款关联的重复已完成合同审批"
|
||
)
|
||
parser.add_argument("--nick-name", required=True, help="申请人昵称,如 胡倩茜")
|
||
parser.add_argument(
|
||
"--create-time",
|
||
default=None,
|
||
help="申请时间,精确匹配 oa_instance.create_time,如 '2026-11-25 12:00:56'",
|
||
)
|
||
parser.add_argument("--tenant", default=None, help="租户编号;重名用户时必填")
|
||
parser.add_argument(
|
||
"--contract-app-name",
|
||
default=CONTRACT_APP_NAME,
|
||
help=f"合同审批应用名,默认 {CONTRACT_APP_NAME}",
|
||
)
|
||
parser.add_argument(
|
||
"--mode",
|
||
choices=("soft-delete", "cancel"),
|
||
default="soft-delete",
|
||
help="soft-delete=列表消失(默认);cancel=仅改为已撤销仍可见",
|
||
)
|
||
parser.add_argument("--apply", action="store_true", help="实际写库;默认 dry-run")
|
||
parser.add_argument(
|
||
"--actor-user-id",
|
||
default=None,
|
||
help="事件操作人;默认用发起人",
|
||
)
|
||
args = parser.parse_args(argv)
|
||
|
||
result = run(
|
||
nick_name=args.nick_name,
|
||
create_time_raw=args.create_time,
|
||
tenant_no=args.tenant,
|
||
contract_app_name=args.contract_app_name,
|
||
apply=bool(args.apply),
|
||
mode=args.mode,
|
||
actor_user_id=args.actor_user_id,
|
||
)
|
||
print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
|
||
analysis = result.get("analysis") or {}
|
||
if analysis.get("errors"):
|
||
return 2
|
||
if result.get("dryRun") is False and not result.get("applied"):
|
||
return 2
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|