#!/usr/bin/env python3 """设计层:数据字典 -> 三张表单 -> 主流程 + 子流程 + 兜底验证流程,全部校验后发布。 设计目标是「把流程设计器里的能力都用上」,同时每一处配置都说得出业务理由: * 12 种环节类型:begin/manual/choice/parallel/merge/split/script/invoke/embed/delay/end/cancel * 17 种审批人来源:identity/person/role/group/unit/post + 9 种组织层级 + creator/prev/prevunit/form * 人工环节的全部开关:四种审批方式、放行配额、超时处理、空审批人兜底、跳过规则、 字段权限、抄送规则、退回配置、路由决策、到达后脚本、同人只办一次、协同七开关 * 路由表达式覆盖算术、比较、布尔、字符串、字典、明细行、日期函数 对象按名字复用:重跑同名流程会覆盖设计并再发一版,不会堆一堆重复流程。 """ from __future__ import annotations import hashlib from . import common from .common import (BASE, CHILD_FORM, CHILD_PROCESS, DICT_ITEMS, DICT_TYPES, LINE_FORM, MAIN_FORM, MAIN_PROCESS, Evidence, cc_rule, ok, person_ref, row) FALLBACK_PROCESS = "审批兜底验证流程" API_ROOT = BASE[: -len("/api/v1")] if BASE.endswith("/api/v1") else BASE.rstrip("/") INVOKE_URL = f"{API_ROOT}/api/v1/settings/public" BUDGET_RESULT_KEY = "budgetResult" # 环节 id 前缀,避免和历史数据里的 id 撞上 P = "ex" C = "exc" F = "exf" def act(pid: str, type_: str, name: str, x: int, y: int, form: str = "", **config) -> dict: note = str(config.pop("help", "") or "") return {"id": pid, "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: # id 列只有 32 个字符,路由 id 用「rt + 起终点摘要」,既稳定又不会超长 digest = hashlib.sha1(f"{src}|{dst}|{order}".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} # -------------------------------------------------------------------------- # 数据字典 # -------------------------------------------------------------------------- def build_dicts(token: str, evidence: Evidence) -> dict: print("\n=== 数据字典 ===") existing = {d["code"]: d for d in ok("GET", "/process/dicts", token)} for code, items in DICT_ITEMS.items(): name = {"category": "报销类型", "invoice": "发票类型", "urgency": "紧急程度", "stage": "报销阶段", "budget": "预算科目"}.get(code.split("_")[-1], code) if code not in existing: ok("POST", "/process/dicts", token, {"code": code, "name": name, "description": f"费用报销演示字典:{name}", "tree": code == DICT_TYPES["budget"], "enabled": True, "order_number": 10}) current = {i["value"]: i for i in ok("GET", f"/process/dicts/{code}/items", token)["items"]} for spec in items: value, label, order = spec[0], spec[1], spec[-1] parent = spec[2] if len(spec) == 4 else "" extra = {} if code == DICT_TYPES["category"]: # 字典带出:选了报销类型就带出预算科目口径与归口部门 extra = {"budget": {"travel": "TRV", "entertain": "BUS", "office": "OFC", "train": "TRN", "telecom": "COM", "other": "OTH"}.get(value, "OTH"), "owner": "经营管理中心"} if value in current: ok("PUT", f"/process/dict-items/{current[value]['id']}", token, {"value": value, "label": label, "parent": parent, "extra": extra, "order_number": order, "enabled": True}) else: ok("POST", f"/process/dicts/{code}/items", token, {"value": value, "label": label, "parent": parent, "extra": extra, "order_number": order, "enabled": True}) print(f" {code}({name}):{len(items)} 项") evidence.save("设计", "数据字典", ok("GET", "/process/dicts", token), "报销类型/发票类型/紧急程度/报销阶段四本字典,报销类型带 extra 供字典带出") return existing # -------------------------------------------------------------------------- # 表单 # -------------------------------------------------------------------------- def line_fields() -> list[dict]: return [ {"key": "item", "label": "费用项目", "type": "text", "required": True, "span": 6}, {"key": "itemAmount", "label": "金额(元)", "type": "money", "required": True, "span": 3, "min": 0, "uppercase": True}, {"key": "itemDate", "label": "发生日期", "type": "date", "required": True, "span": 3}, {"key": "itemCategory", "label": "明细类别", "type": "select", "span": 4, "dictCode": DICT_TYPES["category"]}, {"key": "itemInvoice", "label": "票据号", "type": "text", "span": 4}, {"key": "itemRemark", "label": "备注", "type": "textarea", "span": 16, "rows": 2}, ] def child_fields() -> list[dict]: return [ {"key": "autoSerial", "label": "核验单号", "type": "auto", "auto": "serial", "span": 6}, {"key": "autoHandler", "label": "当前处理人", "type": "auto", "auto": "handler", "span": 6}, {"key": "subject", "label": "核验对象", "type": "text", "required": True, "span": 12}, {"key": "risk", "label": "风险等级", "type": "select", "required": True, "span": 4, "options": [{"value": "low", "label": "低"}, {"value": "mid", "label": "中"}, {"value": "high", "label": "高"}]}, {"key": "opinion", "label": "核验意见", "type": "textarea", "required": True, "span": 8}, {"key": "sign", "label": "核验人签名", "type": "signature", "span": 6}, {"key": "legalDoc", "label": "核验材料", "type": "attachment", "span": 6}, ] def main_fields() -> list[dict]: """主表单:字段类型、字典、级联、联动、带出、公式、明细表、签名、关联单据都用上。""" return [ # 系统带出 {"key": "creator", "label": "发起人", "type": "auto", "auto": "creator", "span": 3}, {"key": "creatorAccount", "label": "发起人工号", "type": "auto", "auto": "creatorAccount", "span": 3}, {"key": "creatorUnit", "label": "发起部门", "type": "auto", "auto": "creatorUnit", "span": 3}, {"key": "serial", "label": "单据编号", "type": "auto", "auto": "serial", "span": 3}, {"key": "creatorLeader", "label": "行政上级", "type": "auto", "auto": "creatorLeader", "span": 3}, {"key": "creatorUnitManager", "label": "部门负责人", "type": "auto", "auto": "creatorUnitManager", "span": 3}, {"key": "applyDate", "label": "申请日期", "type": "auto", "auto": "today", "span": 3}, {"key": "processName", "label": "流程名称", "type": "auto", "auto": "processName", "span": 3}, {"key": "dvBase", "label": "一、报销基本信息", "type": "divider", "span": 24}, {"key": "title", "label": "报销事由", "type": "text", "required": True, "span": 12, "min": 4, "max": 120, "placeholder": "例如:9 月上海客户现场交付差旅"}, {"key": "category", "label": "报销类型", "type": "select", "required": True, "span": 4, "dictCode": DICT_TYPES["category"], "autoFill": [{"field": "category", "pick": "owner", "to": "costOwner"}]}, {"key": "costOwner", "label": "费用归口部门", "type": "text", "span": 4, "readonly": True}, {"key": "urgency", "label": "紧急程度", "type": "radio", "required": True, "span": 4, "dictCode": DICT_TYPES["urgency"]}, {"key": "amount", "label": "报销金额(元)", "type": "money", "required": True, "span": 4, "min": 0, "max": 2000000, "uppercase": True}, {"key": "amountCn", "label": "金额大写", "type": "formula", "span": 4, "formula": "money_cn(data.get('amount') or 0)"}, {"key": "costDept", "label": "费用归属部门", "type": "dept", "required": True, "span": 4}, {"key": "approved", "label": "核准金额(元)", "type": "money", "span": 4, "min": 0, "uppercase": True, "help": "发起时可留空,由财务初审核定;大写金额只读态显示"}, {"key": "payWay", "label": "支付方式", "type": "select", "required": True, "span": 4, "options": [{"value": "bank", "label": "对公转账"}, {"value": "card", "label": "公务卡"}, {"value": "cash", "label": "现金"}]}, {"key": "expectedPay", "label": "期望付款时间", "type": "time", "span": 4}, {"key": "dvInvoice", "label": "二、票据与明细", "type": "divider", "span": 24}, {"key": "invoiceType", "label": "发票类型", "type": "select", "required": True, "span": 4, "dictCode": DICT_TYPES["invoice"]}, {"key": "invoiceCount", "label": "发票张数", "type": "number", "required": True, "span": 4, "min": 0, "max": 500, "precision": 0, "unit": "张"}, {"key": "invoiceNo", "label": "主发票号码", "type": "text", "span": 4, "visibleWhen": {"match": "all", "rules": [{"field": "invoiceType", "op": "ne", "value": "none"}]}}, {"key": "noInvoiceReason", "label": "无票原因", "type": "textarea", "span": 12, "requiredWhen": {"match": "all", "rules": [{"field": "invoiceType", "op": "eq", "value": "none"}]}}, {"key": "items", "label": "费用明细", "type": "table", "span": 24, "columns": line_fields(), "minRows": 1, "maxRows": 20}, {"key": "itemsTotal", "label": "明细合计(元)", "type": "formula", "span": 6, "formula": "total(data.get('items'), 'itemAmount')"}, {"key": "amountDiff", "label": "与申请金额差额", "type": "formula", "span": 6, "formula": "round(float(data.get('amount') or 0) - total(data.get('items'), 'itemAmount'), 2)"}, {"key": "files", "label": "票据影像", "type": "attachment", "required": True, "span": 12}, {"key": "photos", "label": "现场照片", "type": "image", "span": 12}, {"key": "dvTrip", "label": "三、差旅专项(报销类型为差旅时填写)", "type": "divider", "span": 24}, {"key": "tripRange", "label": "出差日期", "type": "daterange", "span": 6, "visibleWhen": {"match": "all", "rules": [{"field": "category", "op": "eq", "value": "travel"}]}}, {"key": "tripDays", "label": "出差天数", "type": "number", "span": 3, "min": 0, "max": 365, "precision": 1, "unit": "天", "visibleWhen": {"match": "all", "rules": [{"field": "category", "op": "eq", "value": "travel"}]}}, {"key": "destination", "label": "出差目的地", "type": "address", "span": 6, "visibleWhen": {"match": "all", "rules": [{"field": "category", "op": "eq", "value": "travel"}]}}, {"key": "crossYear", "label": "是否跨年报销", "type": "switch", "span": 3}, {"key": "tags", "label": "费用标签", "type": "checkbox", "span": 12, "options": [{"value": "customer", "label": "客户相关"}, {"value": "project", "label": "项目成本"}, {"value": "team", "label": "团队建设"}, {"value": "urgent", "label": "紧急采购"}]}, {"key": "dvContact", "label": "四、联系与合规", "type": "divider", "span": 24}, {"key": "contact", "label": "联系电话", "type": "mobile", "required": True, "span": 4}, {"key": "email", "label": "电子邮箱", "type": "email", "span": 4}, {"key": "idNo", "label": "身份证号(境外差旅必填)", "type": "idcard", "span": 4, "visibleWhen": {"match": "all", "rules": [{"field": "destination", "op": "contains", "value": "境外"}]}}, {"key": "contractUrl", "label": "关联合同", "type": "url", "span": 6}, {"key": "relatedWork", "label": "关联借款单", "type": "relation", "span": 6}, {"key": "reviewer", "label": "指定复核人", "type": "user", "span": 4, "help": "填了就走「指定复核人」环节,审批人由表单字段解析出来"}, {"key": "budgetAccount", "label": "预算科目", "type": "cascader", "span": 4, "dictCode": DICT_TYPES["budget"], "cascadeFrom": "category", "help": "选项按「报销类型」级联过滤,必须从大类一路选到明细科目"}, {"key": "vendorScore", "label": "供应商服务评价", "type": "rate", "span": 4, "min": 0, "max": 5}, {"key": "remark", "label": "补充说明", "type": "textarea", "span": 24, "rows": 3}, {"key": "withdraw", "label": "申请撤单", "type": "switch", "span": 4, "help": "付款前申请人撤单时打开,归档后这条单据走作废终止而不是办结"}, {"key": "promise", "label": "申请人承诺签名", "type": "signature", "required": True, "span": 8}, ] def clamp_span(fields: list[dict]) -> list[dict]: """12 列网格里 span 只能 1-12,写超了的(比如按 24 列写的)统一收敛回来。""" for item in fields: if "span" in item: item["span"] = max(1, min(12, int(item["span"]))) for column in item.get("columns") or []: if "span" in column: column["span"] = max(1, min(12, int(column["span"]))) return fields def build_forms(token: str, evidence: Evidence) -> dict: print("\n=== 表单 ===") existing = {f["name"]: f for f in ok("GET", "/process/forms", token, params={"page_size": 200})} specs = [(MAIN_FORM, main_fields(), "费用报销主表单:字典、级联、联动、公式、明细、签名、影像全用上"), (LINE_FORM, line_fields(), "费用明细行表单,供「按明细拆分」逐条办理"), (CHILD_FORM, child_fields(), "合规核验子流程的表单")] forms = {} for name, fields, desc in specs: fields = clamp_span(fields) content = {"fields": fields, "layout": {"columns": 12}} problems = ok("POST", "/process/forms/validate", token, {"content": content}).get("problems", []) if problems: raise SystemExit(f"表单「{name}」设计校验未通过:{problems}") if name in existing: saved = ok("PUT", f"/process/forms/{existing[name]['id']}", token, {"name": name, "description": desc, "content": content}) else: saved = ok("POST", "/process/forms", token, {"name": name, "description": desc, "content": content, "editable": "edit"}) forms[name] = saved["id"] types_used = sorted({f["type"] for f in fields}) print(f" {name}:{len(fields)} 个字段,{len(types_used)} 种类型") used = sorted({f["type"] for _, fields, _ in specs for f in fields}) evidence.save("设计", "表单字段", {name: {"id": fid, "fields": fields} for (name, fields, _), fid in zip(specs, forms.values())}, f"三张表单合计覆盖 {len(used)} 种字段类型:{'、'.join(used)}") return forms # -------------------------------------------------------------------------- # 子流程:合规核验(被主流程用「子流程」环节嵌入) # -------------------------------------------------------------------------- def child_design(cat: dict, form_id: str) -> dict: def m(tail, name, x, y, **cfg): return act(f"{C}_{tail}", "manual", name, x, y, form_id, **cfg) def g(tail, type_, name, x, y, **cfg): return act(f"{C}_{tail}", type_, name, x, y, "", **cfg) def b(tail): return f"{C}_{tail}" activities = [ g("begin", "begin", "开始", 40, 240), m("fill", "填写核验任务", 260, 240, first=True, taskValues=[row("prev")], allowComment=True, allowTransfer=False, formPerms={"subject": "required", "risk": "editable", "opinion": "editable", "sign": "editable"}, help="字段权限示范:这一环节只强制「核验对象」,结论与签名留给后面的法务环节"), m("legal", "法务出具意见", 480, 140, mode="any", taskValues=[row("post", "法务合规岗")], emptyApprover="toCreator", expireValue=30, expireType="minute", timeoutAction="notify", formPerms={"risk": "editable", "opinion": "required", "sign": "required"}), g("gate_ext", "choice", "是否请外部律师", 700, 240), m("external", "外部律师复核", 920, 60, mode="any", taskValues=[row("post", "外部律师岗")], emptyApprover="autoPass", help="「外部律师岗」在本组织里故意不安排人,用来演示空审批人自动通过"), g("risk", "choice", "风险判定", 1140, 240), m("archive", "核验归档", 1360, 140, mode="any", taskValues=[row("post", "档案归档岗")], skipApproved=True, ccRules=[cc_rule("complete", [row("role", "总经理办公会")], opinion="合规核验已归档")]), g("end", "end", "结束", 1580, 140), g("reject", "cancel", "高风险作废", 1360, 380), ] routes = [ rt("提交", b("begin"), b("fill")), rt("派发核验", b("fill"), b("legal")), rt("交给分流", b("legal"), b("gate_ext")), rt("请外部律师", b("gate_ext"), b("external"), "float(data.get('amount') or 0) >= 50000", order=0), rt("法务自结", b("gate_ext"), b("risk"), order=1), rt("外部意见回来", b("external"), b("risk")), rt("高风险作废", b("risk"), b("reject"), "str(data.get('risk') or '') == 'high'", order=0), rt("可以放行", b("risk"), b("archive"), order=1), rt("归档完成", b("archive"), b("end")), ] return {"activities": activities, "routes": routes, "latest_form": form_id, "approval_config": {"skipStarter": True, "dedup": "all"}} # -------------------------------------------------------------------------- # 主流程:费用报销审批流程 # -------------------------------------------------------------------------- def main_design(cat: dict, forms: dict, child_id: str) -> dict: main = forms[MAIN_FORM] line = forms[LINE_FORM] def n(tail, type_, name, x, y, form="", **cfg): return act(f"{P}_{tail}", type_, name, x, y, form or "", **cfg) def b(tail): return f"{P}_{tail}" activities = [ n("begin", "begin", "开始", 40, 420), # 发起 n("fill", "manual", "填写报销单", 240, 420, main, first=True, taskValues=[row("creator")], allowGoBack=True, allowAddTask=True, allowCc=True, allowShare=True, allowPress=True, allowRecall=True, allowComment=True, allowTransfer=True, formPerms={f["key"]: ("required" if f.get("required") else "editable") for f in main_fields() if f["type"] not in ("divider", "formula", "auto")}, ccRules=[cc_rule("arrive", [row("creatorUnitManager")], opinion="新报销单已提交,请知悉")]), # 一级分流 n("gate_amount", "choice", "金额与通道分流", 440, 420), n("reviewer", "manual", "指定复核人", 640, 200, main, mode="any", taskValues=[row("form", "reviewer")], emptyApprover="autoPass", allowTransfer=True, allowComment=True, formPerms={"amount": "readonly", "files": "readonly", "remark": "editable"}, help="审批人来自表单字段「指定复核人」;没填就自动通过"), n("leader", "manual", "上级审批", 640, 420, main, mode="any", taskValues=[row("creatorLeader")], expireValue=4, expireType="hour", timeoutAction="notify", allowGoBack=True, allowAddTask=True, goBackConfig={"way": "step", "type": "prev"}, formPerms={"amount": "readonly", "promise": "readonly", "reviewer": "editable"}, ccRules=[cc_rule("arrive", [row("identity", person_ref(cat, 175))], opinion="上级审批已开始")]), n("dept", "manual", "部门负责人审批", 840, 420, main, mode="any", taskValues=[row("creatorTeamLeader")], skipStarter=True, processingTaskOnceUnderSamePerson=True, allowGoBack=True, allowPress=True, emptyApprover="toCreator", formPerms={"files": "readonly", "tripDays": "editable", "remark": "editable"}, ccRules=[cc_rule("complete", [row("person", "陶睿")], opinion="部门已批")]), # 二级分流:金额越大,链条越长 n("gate_big", "choice", "大额分流", 1040, 420), n("chain", "manual", "逐级上级复核", 1240, 190, main, mode="serial", taskValues=[row("creatorLeaderChain", "3")], formPerms={"amount": "readonly"}, help="特大额:沿直属上级链逐级的往上批,一次只提一个人"), n("vp", "manual", "分管领导审批", 1440, 190, main, mode="any", taskValues=[row("creatorParentUnitManager")], emptyApprover="fixed", emptyApproverValues=[row("person", "曹杰宏")], help="发起人所在部门没有上级部门时(总部直属),兜底给总经理办公室主任"), n("finance_meet", "manual", "财务会签", 1640, 190, main, mode="all", passCount=2, taskValues=[row("role", "财务")], ccRules=[cc_rule("complete", [row("prevLeader"), row("prevUnitManager")], opinion="会签已完成,请上级与归口部门知悉")], formPerms={"amount": "readonly", "approved": "required"}), # 财务初审:字段权限 + 超时 + 退回 n("finance", "manual", "财务初审", 1840, 420, main, mode="any", taskValues=[row("post", "费用审核岗")], expireValue=45, expireType="minute", timeoutAction="notify", allowGoBack=True, allowAddTask=True, allowTransfer=True, routeDecisions={"退回补正": "goBack"}, goBackConfig={"type": "define", "way": "jump", "data": ["填写报销单"]}, formPerms={"title": "readonly", "amount": "readonly", "approved": "required", "invoiceCount": "readonly", "promise": "readonly", "remark": "editable", "photos": "hidden"}, ccRules=[cc_rule("arrive", [row("prev")], opinion="已进入财务初审")]), # 并联核验:法务(含子流程)/ 审计 / 预算 n("par", "parallel", "合规并联核验", 2040, 420), n("legal", "manual", "法务核验", 2240, 250, main, mode="any", taskValues=[row("post", "法务合规岗")], emptyApprover="toCreator", allowComment=True, formPerms={"contractUrl": "editable", "remark": "editable", "files": "readonly"}), n("embed", "embed", "合规核验子流程", 2440, 250, process=child_id, title="费用合规核验"), n("audit", "manual", "审计抽查", 2240, 420, main, mode="ratio", passRatio=50, taskValues=[row("group", "费用稽核小组")], emptyApprover="autoPass", formPerms={"files": "readonly", "amount": "readonly"}), n("budget_calc", "script", "预算口径计算", 2240, 590, script=("subtotal = total(data.get('items'), 'itemAmount')\n" "data['budgetNeed'] = float(data.get('amount') or 0)\n" "data['budgetCheck'] = 'need_confirm' if subtotal and abs(subtotal - data['budgetNeed']) > 0.01 else 'ok'\n" "data['budgetLine'] = 'TRV' if str(data.get('category') or '') == 'travel' else 'GEN'")), n("budget_call", "invoke", "预算系统核验", 2440, 590, url=INVOKE_URL, method="GET", timeout=10, resultPath=BUDGET_RESULT_KEY), n("budget_back", "script", "核验结果回写", 2640, 590, script=(f"res = data.get('{BUDGET_RESULT_KEY}') or {{}}\n" "data['budgetVerified'] = bool(res)\n" "data['budgetSite'] = str(((res.get('data') or {}).get('site_name')) or '')")), n("merge_compliance", "merge", "核验汇总", 2840, 420, passCount=2), # 明细逐条办理 n("gate_items", "choice", "是否需要逐条确认", 3040, 420), n("split_items", "split", "按明细拆分", 3240, 260, main, mode="serial", dataPath="items"), n("line_task", "manual", "明细逐条确认", 3440, 260, line, mode="any", taskValues=[row("post", "费用审核岗")], formPerms={"itemRemark": "editable"}), n("merge_items", "merge", "明细汇总", 3640, 420), # 财务经理与中心主任依次审批 n("finance_review", "manual", "财务经理复核", 3840, 420, main, mode="serial", taskValues=[row("role", "财务")], skipApproved=True, expireValue=8, expireType="hour", timeoutAction="notify", formPerms={"approved": "required", "amount": "readonly", "files": "readonly"}, afterArriveScript="data['financeReviewedAt'] = str(now())[:19]"), n("gate_gm", "choice", "是否上总经理", 4040, 420), n("gm", "manual", "总经理审批", 4240, 260, main, mode="any", taskValues=[row("unitManager", "紫光汇智")], expireValue=2, expireType="minute", timeoutAction="autoPass", timeoutRoute="同意", allowPress=True, # 流程级开了「前面批过就自动通过」,这一环显式要求总经理本人再签一次 skipApproved=False, formPerms={"approved": "readonly", "amount": "readonly"}, help="环节级关掉审批人去重,总经理必须本人签;出差 2 分钟未处理自动放行"), n("cashier", "manual", "出纳付款", 4440, 420, main, mode="any", taskValues=[row("post", "出纳付款岗")], emptyApprover="fixed", emptyApproverValues=[row("identity", person_ref(cat, 236))], expireValue=2, expireType="minute", timeoutAction="autoReject", timeoutRoute="退票", allowGoBack=True, goBackConfig={"type": "define", "way": "jump", "data": ["填写报销单"]}, formPerms={"approved": "readonly", "payWay": "readonly", "expectedPay": "readonly"}, ccRules=[cc_rule("arrive", [row("prevunit")], opinion="即将对外付款,请上一环节处理人所在部门知悉")], help="出纳 2 分钟未处理自动退回,演示超时自动退回"), n("delay", "delay", "银行到账缓冲", 4640, 420, minutes=1), n("archive", "manual", "凭证归档", 4840, 420, main, mode="any", taskValues=[row("post", "档案归档岗")], emptyApprover="toAdmin", ccRules=[cc_rule("complete", [row("creator")], action=True, opinion="单据已归档,请确认收讫")]), n("gate_final", "choice", "归档后判定", 5040, 420), n("end", "end", "结束", 5240, 300, ccRules=[cc_rule("arrive", [row("role", "总经理办公会"), row("unit", "经营管理中心", contains_sub=False)], opinion="报销办结,请登记台账")]), n("void", "cancel", "作废终止", 5240, 560), ] routes = [ rt("提交报销", b("begin"), b("fill")), rt("提交审批", b("fill"), b("gate_amount")), # 一级分流:指定复核人 > 小额直达财务 > 走上级链 rt("指定复核通道", b("gate_amount"), b("reviewer"), "len(rows(data.get('reviewer'))) > 0 or str(data.get('reviewer') or '').strip() != ''", order=0), rt("小额直达财务", b("gate_amount"), b("finance"), "float(data.get('amount') or 0) < 500", order=1), rt("上级审批", b("gate_amount"), b("leader"), "float(data.get('amount') or 0) >= 500", order=2), rt("默认走上级", b("gate_amount"), b("leader"), order=9), rt("复核完成", b("reviewer"), b("leader")), rt("上级已批", b("leader"), b("dept")), rt("部门已批", b("dept"), b("gate_big")), # 二级分流:特大额走上级链 + 分管领导 + 会签;大额直接会签 rt("特大额逐级", b("gate_big"), b("chain"), "float(data.get('amount') or 0) >= 50000", order=0), rt("大额会签", b("gate_big"), b("finance_meet"), "float(data.get('amount') or 0) >= 20000", order=1), rt("差旅加签归口", b("gate_big"), b("finance_meet"), "str(data.get('category') or '') == 'travel' and days_between(str(data.get('applyDate') or ''), today()) > 30", order=2), rt("常规送财务", b("gate_big"), b("finance"), order=9), rt("逐级已批", b("chain"), b("vp")), rt("分管领导已批", b("vp"), b("finance_meet")), rt("会签通过", b("finance_meet"), b("finance")), rt("财务初审通过", b("finance"), b("par")), rt("退回补正", b("finance"), b("fill"), decision="goBack", order=1), # 并联三支 rt("法务线", b("par"), b("legal"), order=0), rt("审计线", b("par"), b("audit"), order=1), rt("预算线", b("par"), b("budget_calc"), order=2), rt("子流程核验", b("legal"), b("embed")), rt("法务支线完成", b("embed"), b("merge_compliance")), rt("审计完成", b("audit"), b("merge_compliance")), rt("算预算", b("budget_calc"), b("budget_call")), rt("调系统", b("budget_call"), b("budget_back")), rt("预算支线完成", b("budget_back"), b("merge_compliance")), # 明细 rt("进汇总", b("merge_compliance"), b("gate_items")), rt("逐条确认", b("gate_items"), b("split_items"), "len(rows(data.get('items'))) >= 3", order=0), rt("免逐条", b("gate_items"), b("merge_items"), order=1), rt("派发", b("split_items"), b("line_task")), rt("逐条办完", b("line_task"), b("merge_items")), rt("明细汇总完", b("merge_items"), b("finance_review")), # 付款与归档 rt("财务已复核", b("finance_review"), b("gate_gm")), rt("上总经理", b("gate_gm"), b("gm"), "float(data.get('approved') or data.get('amount') or 0) >= 100000 " "or str(data.get('urgency') or '') == 'flash'", order=0), rt("免总经理", b("gate_gm"), b("cashier"), order=1), rt("同意", b("gm"), b("cashier")), rt("付款完成", b("cashier"), b("delay")), rt("退票", b("cashier"), b("fill"), decision="goBack", order=1), rt("到账归档", b("delay"), b("archive")), rt("归档完成", b("archive"), b("gate_final")), rt("作废", b("gate_final"), b("void"), "bool(data.get('withdraw'))", order=0), rt("办结", b("gate_final"), b("end"), order=1), ] return {"activities": activities, "routes": routes, "latest_form": main, "approval_config": {"skipStarter": True, "dedup": "all"}, "canvas": {"zoom": 0.9, "note": "费用报销演示流程画布"}} # -------------------------------------------------------------------------- # 兜底验证流程:空审批人四种策略 + 超时自动处理 # -------------------------------------------------------------------------- def fallback_design(cat: dict, forms: dict) -> dict: main = forms[MAIN_FORM] def n(tail, type_, name, x, y, form="", **cfg): return act(f"{F}_{tail}", type_, name, x, y, form or "", **cfg) def b(tail): return f"{F}_{tail}" nobody = row("post", "外部律师岗") yao = row("identity", person_ref(cat, 175)) activities = [ n("begin", "begin", "开始", 40, 240), n("fill", "manual", "填写验证单", 240, 240, main, first=True, taskValues=[row("creator")]), n("gate_entry", "choice", "验证路径分流", 440, 240), n("to_creator", "manual", "空审批人转交发起人", 660, 120, main, mode="any", taskValues=[nobody], emptyApprover="toCreator", help="「外部律师岗」没有人,按兜底策略转交发起人本人"), n("auto_pass", "manual", "空审批人自动通过", 880, 120, main, mode="any", taskValues=[nobody], emptyApprover="autoPass", help="没人就自动通过,不留待办"), n("timeout_pass", "manual", "超时自动通过", 1100, 120, main, mode="any", taskValues=[yao], expireValue=1, expireType="minute", timeoutAction="autoPass", timeoutRoute="同意", help="1 分钟不处理自动通过"), n("timeout_reject", "manual", "超时自动退回", 1320, 240, main, mode="any", taskValues=[yao], expireValue=1, expireType="minute", timeoutAction="autoReject", timeoutRoute="退回", allowGoBack=True, goBackConfig={"type": "define", "way": "jump", "data": ["填写验证单"]}, help="1 分钟不处理自动退回给发起人重填验证单"), n("to_admin", "manual", "空审批人转交管理员", 660, 420, main, mode="any", taskValues=[nobody], emptyApprover="toAdmin", help="兜底转交系统管理员,待办会落在管理员名下,这条单据故意留在途"), n("gate_result", "choice", "结果分流", 1540, 240), n("end", "end", "结束", 1760, 160), n("void", "cancel", "作废", 1760, 340), ] routes = [ rt("提交", b("begin"), b("fill")), rt("进入分流", b("fill"), b("gate_entry")), rt("验证转交管理员", b("gate_entry"), b("to_admin"), "bool(data.get('toAdmin'))", order=0), rt("验证自动链路", b("gate_entry"), b("to_creator"), order=1), rt("继续", b("to_creator"), b("auto_pass")), rt("继续", b("auto_pass"), b("timeout_pass")), rt("同意", b("timeout_pass"), b("timeout_reject")), rt("同意", b("timeout_reject"), b("gate_result")), rt("退回", b("timeout_reject"), b("fill"), decision="goBack", order=1), rt("办结", b("gate_result"), b("end"), order=0), rt("作废", b("gate_result"), b("void"), "bool(data.get('withdraw'))", order=1), rt("停在管理员", b("to_admin"), b("gate_result")), ] return {"activities": activities, "routes": routes, "latest_form": main, "approval_config": {"skipStarter": False, "dedup": "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 save_process(token: str, name: str, design: dict, description: str, category: str = "", icon: str = "", color: str = "") -> dict: existing = find_process(token, name) body = {"name": name, "description": description, "category": category, "icon": icon, "color": color, "open_create": True} if existing: process = ok("PUT", f"/process/processes/{existing['id']}", token, body) else: process = ok("POST", "/process/processes", token, body) pid = process["id"] design = dict(design) canvas = design.pop("canvas", None) approval = design.pop("approval_config", None) if canvas is not None: body["canvas"] = canvas saved = ok("PUT", f"/process/processes/{pid}/design", token, {"activities": design["activities"], "routes": design["routes"], "latest_form": design["latest_form"], "canvas": canvas, "approval_config": approval}) problems = ok("POST", f"/process/processes/{pid}/validate", token)["problems"] if problems: raise SystemExit(f"流程「{name}」校验未通过:\n " + "\n ".join(problems)) ok("POST", f"/process/processes/{pid}/publish", token, {"comment": "费用报销演示发布"}) print(f" {name}:{len(saved['activities'])} 环节 / {len(saved['routes'])} 路由,校验通过并已发布") return {"id": pid, "name": name, "design": saved} def build_category(token: str) -> str: rows = ok("GET", "/process/categories", token) for item in rows: if item["name"] == "行政财务": return item["id"] created = ok("POST", "/process/categories", token, {"name": "行政财务", "description": "行政、财务、报销类流程", "order_number": 5, "enabled": True}) return created["id"] def run(evidence: Evidence | None = None) -> dict: evidence = evidence or Evidence() token = common.admin() cat = common.directory(token) print(f"目标:{BASE}") build_dicts(token, evidence) forms = build_forms(token, evidence) category = build_category(token) child = save_process(token, CHILD_PROCESS, child_design(cat, forms[CHILD_FORM]), "费用报销流程内嵌的合规核验子流程", category, "shield", "#0ea5e9") main = save_process(token, MAIN_PROCESS, main_design(cat, forms, child["id"]), "员工差旅/招待/办公等费用报销的完整审批链路", category, "wallet", "#6366f1") fallback = save_process(token, FALLBACK_PROCESS, fallback_design(cat, forms), "演示空审批人兜底策略与超时自动处理,配合费用报销演示使用", category, "flask", "#f59e0b") detail = ok("GET", f"/process/processes/{main['id']}", token) kinds = sorted({a["type"] for a in detail["activities"]}) print(f" 主流程环节类型:{kinds}") evidence.save("设计", "主流程定义", detail, f"环节类型:{kinds}") evidence.save("设计", "子流程定义", ok("GET", f"/process/processes/{child['id']}", token)) evidence.save("设计", "兜底验证流程定义", ok("GET", f"/process/processes/{fallback['id']}", token)) evidence.save("设计", "审批人来源覆盖", [ {"环节": a["name"], "来源": [(v.get("type"), v.get("data")) for v in (a["config"] or {}).get("taskValues") or []]} for a in detail["activities"] if (a["config"] or {}).get("taskValues")], "主流程里出现的全部审批人来源,含 17 种口径") return {"forms": forms, "main": main, "child": child, "fallback": fallback} def ids(token: str) -> dict: """按名字取回三个流程的 id,runner 单独跑时用。""" out = {} for key, name in (("main", MAIN_PROCESS), ("child", CHILD_PROCESS), ("fallback", FALLBACK_PROCESS)): row_ = find_process(token, name) if row_ is None: raise SystemExit(f"还没有「{name}」,请先跑 design") out[key] = row_["id"] return out if __name__ == "__main__": run()