unis-oa/backend/scripts/invoice_demo/design.py

418 lines
22 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""设计层:表单 → 两条数据源 → 两条送审模板 → 流程(含闸门配置)→ 开放平台那把钥匙。
刻意做小:五环节五出口的直线流程,力气全花在"闸门这一件事配得对不对"上。
* **闸门挂在起草环节**(``config.gate``):提交那一刻判的就是这一段,配置形状与
``docs/invoice-review-integration-design.md`` §5.1 一字不差。部门负责人那一环也挂同一段
(只判「同意」那条出口),用来演"结论拿到之后又换了附件"与"退回永远不挡";
* **两条数据源都是 ``provider=mock``**:送审那条方向是"往外写",报文照渲染、照进发件箱、
照留档,就是不打出去(``outbox.send`` 认这一条);查询那条只回"初审中",于是每一次提交
都会真问一次(现场回源这条通道是活的),而结论只能由对方回传落地;
* **两条送审模板绑表单**:报文用的是 ``{form._checkBizKey}`` / ``{form._checkFiles}`` 那几个
只在渲染这一刻存在的合成键——正好把"模板绑了表单还能不能用合成键"验一遍;
* **开放平台一把 key**:``check:write`` 回传结论、``check:read`` 查批次、``task:write``
代财务办单(与 OA 页面抢同一条待办)。**密钥不落进 docs/**:每次跑重置一把,
留档只留 appKey 与 hint。
对象按名字复用:重跑同名对象是覆盖设计,不堆重复数据。
"""
from __future__ import annotations
import hashlib
from . import common
from .common import (APP_CODE, APP_NAME, CATEGORY, FLAG, MAIN_FORM, MAIN_PROCESS, SCENE, SNAPSHOT,
SOURCE_OUT, SOURCE_QUERY, TPL_SUBMIT, TPL_WITHDRAW, Evidence, ok, row)
#: 环节 id 前缀(避免与历史数据撞)
P = "iv"
#: 替身上游的假地址:mock 通道不会真打,但它得像个地址(幂等键、留痕、报文预览都要用)
INVOICE_SITE = "https://invoice.example.com/api"
ROUTE_SUBMIT = "提交审批"
ROUTE_AGREE = "同意"
ROUTE_BACK = "退回补正"
ROUTE_PASS = "通过"
def act(aid: str, type_: str, name: str, x: int, y: int, form: str = "", **config) -> dict:
note = str(config.pop("help", "") or "")
return {"id": aid, "type": type_, "name": name, "alias": name, "description": note,
"x": x, "y": y, "form": form, "order_number": x, "config": config}
def rt(name: str, src: str, dst: str, expression: str = "", decision: str = "",
order: int = 0) -> dict:
digest = hashlib.sha1(f"{src}|{dst}|{order}|{name}".encode("utf-8")).hexdigest()[:18]
return {"id": f"rt{digest}", "name": name, "alias": name, "from_activity": src,
"to_activity": dst, "decision": decision, "expression": expression,
"order_number": order}
# --------------------------------------------------------------------------
# 闸门配置:方案 §5.1 那一段的落地形状
# --------------------------------------------------------------------------
def gate_config(on: str = ROUTE_SUBMIT) -> dict:
"""环节上那一段闸门配置。每一项都在演练里被真跑到过,没有"配了但没人验"的键。"""
return {
"enabled": True,
"scene": SCENE,
# L1:送审报文与现场回源都从这儿走
"source": SOURCE_OUT,
"submitTemplate": TPL_SUBMIT,
"withdrawTemplate": TPL_WITHDRAW,
# 只判这一条出口:退回永不挡(分寸见 service/gate.py 模块开头)
"on": [on],
"pass": ["passed"],
# 8 张里 1 张异常算不算过:演练用 warn(放行但永久留痕),业务口径见方案 §13 第 8 问
"partial": "warn",
"mode": "block",
# 判之前先回源问一次,不吃 cache_seconds:要的是"现在"这一秒的答案
"refresh": True,
"query": {
"source": SOURCE_QUERY,
"args": {"bizKey": "{form._checkBizKey}", "serial": "{work.serial}"},
"statusPath": "data.status",
"reasonPath": "data.reason",
"itemsPath": "data.items",
"checkerPath": "data.checker",
"versionPath": "data.version",
# 上游的词表与我们的状态词对不上是常态,翻译这一层就是给它的
"verdictMap": {"PASS": "passed", "PARTIAL": "partial",
"CHECKING": "checking", "REJECT": "rejected"},
},
# 问不到就挡:宁可让人等,不能让一张没人审过的单子蒙混过去
"onError": "block",
"maxAgeMinutes": 0,
"flag": FLAG,
"snapshot": dict(SNAPSHOT),
# 逐票清单每行读哪三列:系统没有内置默认,这一种核验自己点明
"item": {"id": "invoiceNo", "name": "fileName", "amount": "amount"},
# 应急放行时除了发起人还要知会谁(这一行 oa_role 由 common.ensure_post 维护)
"notifyRoles": [common.POST_NAME],
}
# --------------------------------------------------------------------------
# 表单
# --------------------------------------------------------------------------
def form_fields() -> list[dict]:
"""一张够小的报销单:凭证 + 结论快照那几格 + 一个闸门标记格。"""
return [
{"key": "serial", "label": "单据编号", "type": "auto", "auto": "serial", "span": 3},
{"key": "creator", "label": "发起人", "type": "auto", "auto": "creator", "span": 3},
{"key": "creatorUnit", "label": "发起部门", "type": "auto", "auto": "creatorUnit", "span": 3},
{"key": "applyDate", "label": "申请日期", "type": "auto", "auto": "today", "span": 3},
{"key": "dvBase", "label": "一、报销信息", "type": "divider", "span": 12},
{"key": "title", "label": "报销事由", "type": "text", "required": True, "span": 6,
"min": 4, "max": 120},
{"key": "amount", "label": "报销金额(元)", "type": "money", "required": True,
"span": 3, "min": 0, "uppercase": True},
{"key": "invoiceCount", "label": "发票张数", "type": "number", "required": True,
"span": 3, "min": 0, "max": 500, "precision": 0, "unit": "张"},
{"key": "remark", "label": "补充说明", "type": "textarea", "span": 12, "rows": 2},
{"key": "files", "label": "发票影像", "type": "attachment", "required": True, "span": 12,
"help": "送审核验送的就是这一批;换过发票要重新送审,旧的初审结论不算数"},
{"key": "dvCheck", "label": "二、票据初审(系统写入,人不用填)", "type": "divider", "span": 12},
{"key": SNAPSHOT["status"], "label": "初审结论", "type": "text", "span": 3, "readonly": True},
{"key": SNAPSHOT["batch"], "label": "核验批次号", "type": "text", "span": 3, "readonly": True},
{"key": SNAPSHOT["summary"], "label": "初审摘要", "type": "text", "span": 3, "readonly": True},
{"key": SNAPSHOT["checker"], "label": "初审人", "type": "text", "span": 3, "readonly": True},
{"key": SNAPSHOT["checkedAt"], "label": "初审时间", "type": "text", "span": 4, "readonly": True},
{"key": SNAPSHOT["reason"], "label": "初审说明", "type": "textarea", "span": 8,
"rows": 2, "readonly": True},
# 闸门判定结果:条件分支、页签角标、打印件读的都是这一格
{"key": FLAG, "label": "闸门判定", "type": "hidden"},
{"key": SNAPSHOT["items"], "label": "逐票结论", "type": "hidden"},
]
def build_form(token: str, evidence: Evidence) -> str:
print("\n=== 表单 ===")
existing = {f["name"]: f for f in ok("GET", "/process/forms", token, params={"page_size": 200})}
content = {"fields": form_fields(), "layout": {"columns": 12}}
problems = ok("POST", "/process/forms/validate", token, {"content": content}).get("problems", [])
if problems:
raise SystemExit(f"表单「{MAIN_FORM}」设计校验未通过:{problems}")
if MAIN_FORM in existing:
saved = ok("PUT", f"/process/forms/{existing[MAIN_FORM]['id']}", token,
{"name": MAIN_FORM, "description": "票据初审闸门演练表单:凭证 + 结论快照 + 闸门标记",
"content": content})
else:
saved = ok("POST", "/process/forms", token,
{"name": MAIN_FORM, "description": "票据初审闸门演练表单:凭证 + 结论快照 + 闸门标记",
"content": content, "editable": "edit"})
print(f" {MAIN_FORM}:{len(form_fields())} 个字段")
evidence.save("设计", "表单字段", {"name": MAIN_FORM, "id": saved["id"],
"fields": form_fields()},
"凭证一格(files)+ 结论快照七格 + 闸门标记格(invoiceGate)")
return saved["id"]
# --------------------------------------------------------------------------
# L1 数据源:一张往外写、一张往里查,都是样例通道
# --------------------------------------------------------------------------
SOURCES: list[dict] = [
{
"code": SOURCE_OUT, "name": "票据核验系统(送审通道)", "system": "票据核验系统",
"kind": "fetch", "provider": "mock", "direction": "out", "enabled": True,
"method": "POST", "url": INVOICE_SITE,
"mock_payload": {"code": 0, "message": "accepted",
"data": {"batch": "(样例通道不真发,报文见发件箱)"}},
"success_path": "code", "success_value": "0", "message_path": "message",
"ref_path": "data.batch", "timeout_seconds": 10, "retries": 2,
"description": "送审 / 撤回报文走这条。样例通道 = 报文照渲染照留档,不真发(演练替身)",
},
{
"code": SOURCE_QUERY, "name": "票据核验系统(查结论)", "system": "票据核验系统",
"kind": "fetch", "provider": "mock", "direction": "in", "enabled": True,
"method": "POST", "url": INVOICE_SITE,
# 故意只回"初审中":现场回源这条通道每次都真跑,而结论只能由对方回传落地
"mock_payload": {"code": 0, "message": "ok",
"data": {"status": "CHECKING", "reason": "初审中,请稍后", "items": [],
"checker": "票据系统·样例通道", "version": 1}},
"timeout_seconds": 10, "retries": 1,
"description": "提交时现场回源与定时对账走这条。样例响应固定回 CHECKING",
},
]
def build_sources(token: str, evidence: Evidence) -> None:
print("\n=== 数据源(L1)===")
existing = {item["code"]: item for item in ok("GET", "/design/data-sources", token)}
for spec in SOURCES:
if spec["code"] in existing:
ok("PATCH", f"/design/data-sources/{spec['code']}", token, spec)
print(f" 更新 {spec['code']}({spec['name']})")
else:
ok("POST", "/design/data-sources", token, spec)
print(f" 新建 {spec['code']}({spec['name']})")
evidence.save("设计", "数据源", [item for item in ok("GET", "/design/data-sources", token)
if item["code"] in {s["code"] for s in SOURCES}],
"provider=mock:送审那条方向是往外写,查询那条固定回「初审中」")
# --------------------------------------------------------------------------
# L2 送审 / 撤回报文
# --------------------------------------------------------------------------
def submit_payload() -> dict:
"""方案 §8.1 那张合成键表在报文里的样子:批次号、修订号、附件清单、一次性清单入口。"""
return {
"method": "POST", "path": "/checks/submit",
"fields": [
{"to": "bizKey", "from": "{form._checkBizKey}"},
{"to": "scene", "from": "{form._checkScene}"},
{"to": "revision", "from": "{form._checkRevision}"},
{"to": "serial", "from": "{work.serial}"},
{"to": "title", "from": "{work.title}"},
{"to": "applicant", "from": "{work.creator_person}"},
{"to": "unit", "from": "{work.creator_unit_name}"},
{"to": "amount", "from": "{form.amount}"},
{"to": "invoiceCount", "from": "{form.invoiceCount}"},
# 附件不进报文内容,只给 id / 名字 / 大小,字节由对方按 manifestUrl 现取
{"to": "files", "from": "{form._checkFiles}"},
{"to": "manifestUrl", "from": "{form._checkManifestUrl}"},
],
}
def withdraw_payload() -> dict:
return {
"method": "POST", "path": "/checks/withdraw",
"fields": [
{"to": "bizKey", "from": "{form._checkBizKey}"},
{"to": "serial", "from": "{work.serial}"},
{"to": "revision", "from": "{form._checkRevision}"},
{"to": "reason", "from": "{form._checkReason}"},
],
}
def templates(form_id: str) -> list[dict]:
return [
{"code": TPL_SUBMIT, "name": "票据初审·送审", "enabled": True, "source": SOURCE_OUT,
"biz_form": form_id, "trigger_event": "manual", "payload": submit_payload(),
"on_failure": "continue", "retries": 5,
"remark": "由「送审核验」按钮入队(event=check),不参与办结/环节写回"},
{"code": TPL_WITHDRAW, "name": "票据初审·撤回", "enabled": True, "source": SOURCE_OUT,
"biz_form": form_id, "trigger_event": "manual", "payload": withdraw_payload(),
"on_failure": "continue", "retries": 5,
"remark": "撤了这一批就要请对方把初审任务一起作废,否则那边留下一张没人认领的单"},
]
def build_templates(token: str, evidence: Evidence, form_id: str) -> None:
print("\n=== 送审模板(L2)===")
existing = {item["code"]: item for item in ok("GET", "/design/integrations", token)}
for spec in templates(form_id):
# 用"还没保存的那份配置"过一遍设计期校验:报文里那几个 _check* 合成键
# 绑着表单也存得进去,这条正好在这里验掉
checked = ok("POST", "/design/integrations/validate", token, {"template": spec})
if checked.get("problems"):
raise SystemExit(f"模板「{spec['code']}」校验未通过:{checked['problems']}")
if spec["code"] in existing:
ok("PATCH", f"/design/integrations/{spec['code']}", token, spec)
print(f" 更新 {spec['code']}({spec['name']})")
else:
ok("POST", "/design/integrations", token, spec)
print(f" 新建 {spec['code']}({spec['name']})")
evidence.save("设计", "送审模板", [item for item in ok("GET", "/design/integrations", token)
if item["code"] in {TPL_SUBMIT, TPL_WITHDRAW}],
"两条都绑了表单:报文里的 _check* 是只在渲染这一刻存在的合成键")
# --------------------------------------------------------------------------
# 流程
# --------------------------------------------------------------------------
def design() -> dict:
def b(tail: str) -> str:
return f"{P}_{tail}"
activities = [
act(b("begin"), "begin", "开始", 40, 240),
act(b("fill"), "manual", common.ACTIVITY_FILL, 260, 240, "", first=True,
taskValues=[row("creator")],
gate=gate_config(ROUTE_SUBMIT),
allowGoBack=True, allowComment=True, allowTransfer=True, allowPress=True,
formPerms={"files": "required", "title": "required", "amount": "required",
"invoiceCount": "required", "remark": "editable"},
help="上传发票 → 点「送审核验」→ 结论回来后提交;没过初审,提交这条路是走不通的"),
act(b("dept"), "manual", common.ACTIVITY_DEPT, 500, 240, "", mode="any",
taskValues=[row("creatorLeader")], emptyApprover="toCreator",
gate=gate_config(ROUTE_AGREE),
routeDecisions={ROUTE_BACK: "goBack"},
formPerms={"files": "readonly", "remark": "editable"},
help="同一场景在这里也挂一道闸:只判「同意」。结论拿到之后又换了附件,这里照样挡"),
act(b("finance"), "manual", common.ACTIVITY_FINANCE, 740, 240, "", mode="any",
taskValues=[row("post", common.POST_NAME)], emptyApprover="toCreator",
routeDecisions={ROUTE_BACK: "goBack"},
formPerms={"files": "readonly", "remark": "editable",
SNAPSHOT["status"]: "readonly", SNAPSHOT["reason"]: "readonly",
SNAPSHOT["summary"]: "readonly", SNAPSHOT["batch"]: "readonly"},
help="财务在这里看票据:右栏那块面板 + 表单上那几格快照 + 逐票原因"),
act(b("end"), "end", "结束", 980, 240),
]
routes = [
rt("发起", b("begin"), b("fill"), order=0),
rt(ROUTE_SUBMIT, b("fill"), b("dept"), order=0),
rt(ROUTE_BACK, b("dept"), b("fill"), decision="goBack", order=1),
rt(ROUTE_AGREE, b("dept"), b("finance"), order=0),
rt(ROUTE_BACK, b("finance"), b("fill"), decision="goBack", order=1),
rt(ROUTE_PASS, b("finance"), b("end"), order=0),
]
return {"activities": activities, "routes": routes,
# 三条去重规则全关:开着「发起人不重复审批」会把「起草填报」连同发起人待办
# 一起吞掉(闸门就挂在这一环上,吞掉等于演练没主角);开着「审批人去重」会让
# 退回后重走的「部门负责人审批」自动通过,第五个场景就演不出来了
"approval_config": {"skipStarter": False, "dedup": "none", "dedupAhead": "none"}}
def find_process(token: str, name: str) -> dict | None:
for item in ok("GET", "/process/processes", token, params={"page_size": 200}):
if item["name"] == name:
return item
return None
def build_category(token: str) -> str:
for item in ok("GET", "/process/categories", token):
if item["name"] == CATEGORY:
return item["id"]
return ok("POST", "/process/categories", token,
{"name": CATEGORY, "description": "行政、财务、报销类流程", "order_number": 5,
"enabled": True})["id"]
def build_process(token: str, evidence: Evidence, form_id: str) -> dict:
print("\n=== 流程 ===")
category = build_category(token)
body = {"name": MAIN_PROCESS, "description": "报销单附件送票据系统初审,初审过了才让提交",
"category": category, "icon": "receipt", "color": "#0ea5e9", "open_create": True}
existing = find_process(token, MAIN_PROCESS)
process = (ok("PUT", f"/process/processes/{existing['id']}", token, body) if existing
else ok("POST", "/process/processes", token, body))
pid = process["id"]
graph = design()
ok("PUT", f"/process/processes/{pid}/design", token,
{"activities": [{**item, "form": item["form"] or form_id} for item in graph["activities"]],
"routes": graph["routes"], "latest_form": form_id,
"approval_config": graph["approval_config"]})
problems = ok("POST", f"/process/processes/{pid}/validate", token)["problems"]
if problems:
raise SystemExit("流程校验未通过:\n " + "\n ".join(problems))
ok("POST", f"/process/processes/{pid}/publish", token, {"comment": "票据初审闸门演练发布"})
detail = ok("GET", f"/process/processes/{pid}", token)
print(f" {MAIN_PROCESS}:{len(detail['activities'])} 环节 / {len(detail['routes'])} 路由,已发布")
evidence.save("设计", "流程定义", detail,
"起草环节挂闸门(判「提交审批」);部门负责人也挂(只判「同意」)")
return {"id": pid, "detail": detail}
# --------------------------------------------------------------------------
# 开放平台那把钥匙
# --------------------------------------------------------------------------
def ensure_app(token: str, evidence: Evidence) -> dict:
"""建(或复用)那把 key,并**每次重置密钥**:密钥只在这次运行内存里活着,不落 docs/。"""
print("\n=== 开放平台 ===")
apps = ok("GET", "/design/open/apps", token)["items"]
app = next((item for item in apps if item["code"] == APP_CODE), None)
body = {"code": APP_CODE, "name": APP_NAME, "enabled": True,
"scopes": ["check:read", "check:write", "task:write", "work:read"],
"rate_limit_qpm": 300, "token_ttl_seconds": 7200,
"remark": "票据核验系统演练替身:回传结论、查批次、代财务办待办"}
if app is None:
created = ok("POST", "/design/open/apps", token, body)
print(f" 新建应用 {APP_CODE}:scopes={','.join(created['scopes'])}")
view = created
else:
view = ok("PUT", f"/design/open/apps/{APP_CODE}", token, body)
print(f" 复用应用 {APP_CODE}:scopes={','.join(view['scopes'])}")
rotated = ok("POST", f"/design/open/apps/{APP_CODE}/secret", token)
print(f" 重置密钥(本次有效):{rotated['appKey']} / {rotated['secretHint']}")
evidence.save("设计", "开放平台应用", {
"code": view["code"], "name": view["name"], "appKey": view["appKey"],
"secretHint": rotated["secretHint"], "scopes": view["scopes"],
"note": "appSecret 不落 docs/:每次跑重置一把,只在这次运行的内存里",
}, "回传结论 check:write / 查批次 check:read / 代财务办单 task:write")
return {"appKey": rotated["appKey"], "appSecret": rotated["appSecret"]}
# --------------------------------------------------------------------------
def run(evidence: Evidence | None = None) -> dict:
evidence = evidence or Evidence()
token = common.admin()
common.CAT.update(common.directory(token))
print(f"目标:{common.BASE}")
form_id = build_form(token, evidence)
build_sources(token, evidence)
build_templates(token, evidence, form_id)
process = build_process(token, evidence, form_id)
app = ensure_app(token, evidence)
return {"form": form_id, "process": process["id"], "detail": process["detail"], **app}
def ids(token: str) -> dict:
"""单独跑 run 时用:按名字取回流程与 key(密钥拿不到就重置一把)。"""
process = find_process(token, MAIN_PROCESS)
if process is None:
raise SystemExit(f"还没有「{MAIN_PROCESS}」,请先跑 design")
return {"process": process["id"]}