357 lines
19 KiB
Python
357 lines
19 KiB
Python
"""按四张 OA 截图建「印章使用 / 备用金 / 财务及资质材料 / 工作联络单」四张表单。
|
||
|
||
字段类型对着截图配:下拉、单选、多选、人员、部门、金额、日期区间、明细表、附件、
|
||
自动编号都落到平台已有控件上,「一行两栏 / 一行一栏」照截图排在 12 列网格里。
|
||
打的是**正在跑的开发接口**(默认 http://127.0.0.1:8000),走和界面完全一样的保存
|
||
路径,服务端那套校验(api/design.py 的 form_problems)没过就当场报错,不直写库。
|
||
|
||
python scripts/oa_forms.py # 建 / 覆盖更新这四张表单
|
||
python scripts/oa_forms.py --bind # 已有同名流程时把表单设成它的默认表单
|
||
python scripts/oa_forms.py --create-process # 顺带建四条草稿流程,环节留给设计器配
|
||
python scripts/oa_forms.py --base http://host/api/v1 --account x --password y
|
||
|
||
按表单名幂等:库里已经有同名表单就走 PUT 覆盖,跑多少遍都只有一套。
|
||
|
||
两处照搬不了的地方,已经写在对应字段的 help 里,界面上点开就能看到:
|
||
· 「描述/说明」原系统是个富文本编辑器,平台目前只有多行文本,先用 textarea 顶着;
|
||
· 附件「最大 20M/个」「最大 100M/个」是原系统的单字段限制,本平台的上传上限是全局的
|
||
(config 的 max_upload_mb),这里只在 help 里写清口径,不做成字段级开关。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
|
||
BASE = "http://127.0.0.1:8000/api/v1"
|
||
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||
|
||
#: 排版口径与库里既有的「费用报销单」保持一致:12 列网格,标签列 110px。
|
||
LAYOUT = {"grid": 12, "columns": 12, "label_width": 110}
|
||
|
||
#: 四张单子的标题都照截图那串长样子生成:流程名称(部门)-发起人姓名工号-日期。
|
||
TITLE_RULE = {
|
||
"mode": "template",
|
||
"template": "{流程名称}({部门})-{发起人}{工号}-{日期}",
|
||
"maxLength": 80,
|
||
"editable": True,
|
||
"refresh": False,
|
||
}
|
||
|
||
|
||
def field(row: int, col: int, span: int, key: str, label: str, type_: str, **rest) -> dict:
|
||
"""一个格子 = 12 列网格上的一段合并单元格;rest 放类型自己的配置。"""
|
||
return {"key": key, "label": label, "type": type_, "row": row, "col": col, "span": span, **rest}
|
||
|
||
|
||
def title_field(row: int, col: int, span: int, label: str = "标题") -> dict:
|
||
return field(row, col, span, "title", label, "title", required=True,
|
||
titleMode="rule", titleRule=dict(TITLE_RULE),
|
||
placeholder="系统按「流程名称(部门)-发起人-日期」生成,可以改")
|
||
|
||
|
||
def options(*pairs: tuple[str, str]) -> list[dict]:
|
||
return [{"value": value, "label": label} for value, label in pairs]
|
||
|
||
|
||
#: 借款类型:主表一个下拉、明细表一列下拉,两边同一套口径,改的时候改一处。
|
||
LOAN_TYPES = options(
|
||
("petty", "备用金"), ("travel", "差旅费借款"), ("project", "项目借款"),
|
||
("purchase", "采购借款"), ("other", "其它"),
|
||
)
|
||
|
||
#: 收款方式:截图默认那格写的是「银行存款」,把它排在第一个。
|
||
PAY_WAYS = options(
|
||
("bank", "银行存款"), ("cash", "现金"), ("cheque", "支票"),
|
||
("transfer", "电汇"), ("other", "其它"),
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 一、印章使用申请流程
|
||
# ---------------------------------------------------------------------------
|
||
|
||
SEAL_FIELDS = [
|
||
title_field(1, 1, 12),
|
||
field(2, 1, 6, "applyDept", "申请部门", "dept"),
|
||
field(2, 7, 6, "handler", "经办人", "user"),
|
||
field(3, 1, 6, "sealCategory", "印章申请分类", "select", required=True,
|
||
options=options(
|
||
("contract", "合同类"), ("bid", "投标类"), ("license", "证照办理类"),
|
||
("finance", "财务报表类"), ("bank", "银行结算类"), ("other", "其它"),
|
||
),
|
||
help="截图里下拉是空的、取不到原系统的字典,先按用印场景给一套占位选项,可在设计器里改"),
|
||
field(3, 7, 6, "sealCount", "用印数量(一式几份)", "number", required=True,
|
||
min=1, max=999, precision=0, unit="份"),
|
||
field(4, 1, 12, "sealTypes", "用印类型", "checkbox", required=True,
|
||
options=options(
|
||
("official", "公章"), ("legal", "法人章"), ("contract", "合同专用章"),
|
||
("project", "项目章"), ("legalSign", "法人签名章"), ("gmSign", "总经理签名章"),
|
||
("finance", "财务专用章"), ("other", "其它"),
|
||
)),
|
||
field(5, 1, 12, "sealForm", "印章形式", "radio", required=True,
|
||
options=options(("ink", "油墨印章"), ("ca", "CA印章"), ("electronic", "电子印章"))),
|
||
field(6, 1, 12, "attachment", "附件上传", "attachment", help="单个附件最大 20M"),
|
||
field(7, 1, 12, "reason", "申请事由", "textarea", required=True),
|
||
field(8, 1, 12, "remark", "备注", "textarea"),
|
||
]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 二、备用金申请流程
|
||
# ---------------------------------------------------------------------------
|
||
|
||
LOAN_FIELDS = [
|
||
title_field(1, 1, 12),
|
||
field(2, 1, 6, "applyTime", "申请时间", "auto", auto="now", autoRule={"date": "YYYY-MM-DD"}),
|
||
field(2, 7, 6, "processNo", "流程编号", "auto", auto="serial",
|
||
autoRule={"prefix": "BYJ", "date": "YYYYMMDD", "length": 4, "period": "day"}),
|
||
field(3, 1, 6, "applicant", "申请人", "user"),
|
||
field(3, 7, 6, "applyDept", "申请部门", "auto", auto="creatorUnit"),
|
||
field(4, 1, 6, "unoffsetAmount", "剩余未冲金额", "money", min=0, uppercase=True,
|
||
help="既往借款还没冲掉的钱;本平台暂不跨单据取数,发起时按台账手工填"),
|
||
field(4, 7, 6, "loanType", "借款类型", "select", required=True, options=list(LOAN_TYPES)),
|
||
field(5, 1, 12, "loanReason", "借款理由", "textarea"),
|
||
field(6, 1, 12, "attachment", "附件", "attachment", help="单个附件最大 20M"),
|
||
# 截图里「借款信息」「收款信息」是两截小节标题,这里直接由明细表自己的标题行承担。
|
||
field(7, 1, 12, "loanItems", "借款信息", "table", minRows=1, maxRows=20, columns=[
|
||
{"key": "loanNote", "label": "借款说明", "type": "text", "required": True, "span": 2},
|
||
{"key": "loanType", "label": "借款类型", "type": "select", "span": 2,
|
||
"options": list(LOAN_TYPES)},
|
||
{"key": "loanTypeName", "label": "借款类型说明", "type": "text", "required": True, "span": 2},
|
||
{"key": "loanAmount", "label": "借款金额", "type": "money", "required": True, "min": 0, "span": 2},
|
||
{"key": "adjustDetail", "label": "调整明细", "type": "text", "span": 2},
|
||
{"key": "returnDate", "label": "归还日期", "type": "date", "required": True, "span": 2},
|
||
]),
|
||
field(8, 7, 6, "loanAmountTotal", "借款金额合计为", "formula",
|
||
formula="total(data.get('loanItems'), 'loanAmount')"),
|
||
field(9, 1, 12, "payItems", "收款信息", "table", minRows=1, maxRows=20, columns=[
|
||
{"key": "payee", "label": "收款人", "type": "user", "span": 2},
|
||
{"key": "bankName", "label": "开户银行", "type": "text", "span": 3},
|
||
{"key": "bankAccount", "label": "银行帐号", "type": "text", "span": 3},
|
||
{"key": "payAmount", "label": "收款金额", "type": "money", "min": 0, "span": 2},
|
||
{"key": "payWay", "label": "收款方式", "type": "select", "span": 2,
|
||
"options": list(PAY_WAYS)},
|
||
]),
|
||
]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 三、财务及资质材料使用申请流程
|
||
# ---------------------------------------------------------------------------
|
||
|
||
MATERIAL_FIELDS = [
|
||
title_field(1, 1, 12),
|
||
field(2, 1, 6, "handler", "经办人", "user"),
|
||
field(2, 7, 6, "applyDept", "申请部门", "dept"),
|
||
field(3, 1, 12, "project", "申请项目", "text", required=True),
|
||
field(4, 1, 12, "financeMaterials", "财务资料", "checkbox",
|
||
options=options(("auditReport", "审计报告及财务报表(具体要求请补充到备注)"))),
|
||
field(5, 1, 12, "qualificationMaterials", "资质资料", "checkbox",
|
||
options=options(
|
||
("licenseOriginal", "营业执照(正本)"),
|
||
("licenseCopy", "营业执照(副本)"),
|
||
("safetyOriginal", "安全生产许可证(正本)"),
|
||
("safetyCopy", "安全生产许可证(副本)"),
|
||
("intellectOriginal", "电子与智能化工程专业承包贰级(正本)"),
|
||
("intellectCopy", "电子与智能化工程专业承包贰级(副本)"),
|
||
("qualityCopy", "质量管理体系认证证书(副本)"),
|
||
("environmentCopy", "环境管理体系认证证书(副本)"),
|
||
("ohsmsCopy", "职业健康安全管理体系认证证书(副本)"),
|
||
("ismsCopy", "信息安全管理体系认证证书(副本)"),
|
||
("itsmsCopy", "信息技术服务管理体系认证证书(副本)"),
|
||
("cqAnfangFirst", "重庆市安防工程从业资格壹级证书"),
|
||
("cqTefangMember", "重庆市公共安全技术防范协会会员证书"),
|
||
("top100Honor", "中国安防百强工程商荣誉证书"),
|
||
("advancedUnit", "中国安防工程建设先进单位奖"),
|
||
("softwareCopyright", "软件著作权(AI智慧环保工地监管平台)"),
|
||
("other", "其它(其它要求请补充到备注)"),
|
||
)),
|
||
field(6, 1, 12, "staffMaterials", "人员资料", "checkbox",
|
||
options=options(("staffCertificate", "人员证书"),
|
||
("staffSocialSecurity", "人员社保(具体要求请补充到备注)"))),
|
||
field(7, 1, 12, "performanceMaterials", "业绩资料", "checkbox",
|
||
options=options(("salesPerformance", "公司销售业绩(具体要求请补充到备注)"))),
|
||
field(8, 1, 12, "materialType", "材料类型", "checkbox", required=True,
|
||
options=options(("original", "原件(如选择,具体要求请补充到备注)"),
|
||
("electronic", "电子档"))),
|
||
field(9, 1, 12, "validRange", "申请有效期", "daterange", required=True),
|
||
field(10, 1, 12, "reason", "申请事由", "textarea"),
|
||
field(11, 1, 12, "remark", "备注", "textarea"),
|
||
]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 四、工作联络单流程
|
||
# ---------------------------------------------------------------------------
|
||
|
||
LIAISON_FIELDS = [
|
||
title_field(1, 1, 6),
|
||
field(1, 7, 6, "fillTime", "填表时间", "auto", auto="now", autoRule={"date": "YYYY-MM-DD"}),
|
||
field(2, 1, 6, "creator", "发起人", "user"),
|
||
field(2, 7, 6, "creatorDept", "发起人部门", "dept"),
|
||
field(3, 1, 6, "costDept", "费用归属部门", "dept", required=True),
|
||
field(3, 7, 6, "executor", "执行人", "user", required=True),
|
||
field(4, 1, 6, "auditor", "审核人", "user", required=True),
|
||
field(4, 7, 6, "ccUsers", "抄送人", "user"),
|
||
field(5, 1, 6, "amount", "金额", "money", required=True, min=0, uppercase=True),
|
||
field(5, 7, 6, "feedbackTime", "反馈时间", "date"),
|
||
field(6, 1, 12, "attachment", "附件", "attachment", help="单个附件最大 100M"),
|
||
field(7, 1, 12, "description", "描述/说明", "textarea",
|
||
help="原系统是富文本编辑器,本平台先用多行文本承载"),
|
||
]
|
||
|
||
|
||
FORMS = [
|
||
{"name": "印章使用申请流程", "order_number": 10, "fields": SEAL_FIELDS,
|
||
"description": "按「印章使用申请流程」截图建:申请部门与经办人、印章申请分类、用印数量、"
|
||
"用印类型多选、印章形式单选、附件、申请事由与备注。"},
|
||
{"name": "备用金申请流程", "order_number": 20, "fields": LOAN_FIELDS,
|
||
"description": "按「备用金申请流程」截图建:申请时间与流程编号自动生成、剩余未冲金额、借款类型、"
|
||
"借款理由与附件,外加借款信息、收款信息两张明细表,借款金额由明细表汇总。"},
|
||
{"name": "财务及资质材料使用申请流程", "order_number": 30, "fields": MATERIAL_FIELDS,
|
||
"description": "按「财务及资质材料使用申请流程」截图建:申请项目,财务 / 资质 / 人员 / 业绩四组材料多选,"
|
||
"材料类型、申请有效期区间,最后附申请事由与备注。"},
|
||
{"name": "工作联络单流程", "order_number": 40, "fields": LIAISON_FIELDS,
|
||
"description": "按「工作联络单流程」截图建:填表时间自动生成,发起人与发起人部门、费用归属部门、"
|
||
"执行人、审核人、抄送人、金额与反馈时间,附件与描述说明。"},
|
||
]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 接口
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def call(method: str, path: str, token: str = "", body: dict | None = None,
|
||
params: dict | None = None) -> tuple[int, dict]:
|
||
url = f"{BASE}{path}"
|
||
if params:
|
||
url += "?" + urllib.parse.urlencode({k: v for k, v in params.items() if v not in (None, "")})
|
||
request = urllib.request.Request(
|
||
url, data=json.dumps(body).encode() if body is not None else None, method=method)
|
||
request.add_header("Content-Type", "application/json")
|
||
if token:
|
||
request.add_header("Authorization", f"Bearer {token}")
|
||
try:
|
||
with OPENER.open(request, timeout=90) as response:
|
||
return response.status, json.loads(response.read().decode() or "{}")
|
||
except urllib.error.HTTPError as exc:
|
||
raw = exc.read().decode() or "{}"
|
||
try:
|
||
return exc.code, json.loads(raw)
|
||
except ValueError:
|
||
return exc.code, {"code": exc.code, "message": raw}
|
||
|
||
|
||
def must(name: str, method: str, token: str, path: str, body: dict | None = None,
|
||
params: dict | None = None):
|
||
_status, payload = call(method, path, token, body, params)
|
||
if payload.get("code") != 0:
|
||
raise SystemExit(f"{name}失败: {json.dumps(payload, ensure_ascii=False)[:400]}")
|
||
return payload["data"]
|
||
|
||
|
||
def login(account: str, password: str) -> str:
|
||
return must("登录", "POST", "", "/auth/login", {"account": account, "password": password})["access_token"]
|
||
|
||
|
||
def save_form(token: str, spec: dict) -> tuple[str, bool]:
|
||
"""同名就覆盖、没有就新建,返回 (表单 id, 是否新建)。"""
|
||
body = {"name": spec["name"], "description": spec["description"],
|
||
"order_number": spec["order_number"],
|
||
"content": {"fields": spec["fields"], "layout": dict(LAYOUT)}}
|
||
for row in must("读表单", "GET", token, "/process/forms"):
|
||
if row.get("name") != spec["name"]:
|
||
continue
|
||
must("改表单", "PUT", token, f"/process/forms/{row['id']}", body)
|
||
return row["id"], False
|
||
return must("建表单", "POST", token, "/process/forms", body)["id"], True
|
||
|
||
|
||
def check_form(token: str, spec: dict) -> list[str]:
|
||
"""比对库里的表单与脚本里这份字段清单,看有没有走偏。
|
||
|
||
脚本改完忘了跑、或者有人直接在界面里动了表单,都会在这里露出来。
|
||
"""
|
||
row = next((item for item in must("读表单", "GET", token, "/process/forms")
|
||
if item.get("name") == spec["name"]), None)
|
||
if row is None:
|
||
return [f"{spec['name']}:库里没有这张表单"]
|
||
content = must("读表单详情", "GET", token, f"/process/forms/{row['id']}")["content"] or {}
|
||
want = {item["key"]: item for item in spec["fields"]}
|
||
got = {item.get("key"): item for item in content.get("fields") or []}
|
||
problems = [f"{spec['name']}:库里有脚本没有的字段 {sorted(set(got) - set(want))}"
|
||
if set(got) - set(want) else "",
|
||
f"{spec['name']}:脚本里有库里没有的字段 {sorted(set(want) - set(got))}"
|
||
if set(want) - set(got) else ""]
|
||
for key, field in want.items():
|
||
if got.get(key) != field:
|
||
problems.append(f"{spec['name']}.{key}:与脚本不一致(库里 {got.get(key)})")
|
||
layout = content.get("layout") or {}
|
||
if {k: layout.get(k) for k in LAYOUT} != LAYOUT:
|
||
problems.append(f"{spec['name']}:排版不是 12 列网格(库里 {layout})")
|
||
return [item for item in problems if item]
|
||
|
||
|
||
def bind_process(token: str, name: str, form_id: str) -> str:
|
||
"""已有同名流程时把这张表单设成它的默认表单;只动 latest_form,环节配置一律不碰。"""
|
||
for row in must("读流程", "GET", token, "/process/processes"):
|
||
if row.get("name") != name:
|
||
continue
|
||
if row.get("latest_form") == form_id:
|
||
return f"流程「{name}」的默认表单已经是它"
|
||
must("绑流程", "PUT", token, f"/process/processes/{row['id']}", {"latest_form": form_id})
|
||
return f"已把表单设为流程「{name}」的默认表单"
|
||
return "库里没有同名流程,表单先作为通用表单放着"
|
||
|
||
|
||
def create_process(token: str, spec: dict, form_id: str) -> str:
|
||
"""建一条草稿流程:默认表单就是刚建的这张,审批环节留给设计器点。"""
|
||
row = must("建流程", "POST", token, "/process/processes", {
|
||
"name": spec["name"], "description": spec["description"],
|
||
"order_number": spec["order_number"], "latest_form": form_id,
|
||
})
|
||
return f"已建草稿流程「{spec['name']}」(id {row['id']}),审批环节待配置"
|
||
|
||
|
||
def main() -> int:
|
||
global BASE
|
||
parser = argparse.ArgumentParser(description="按截图建四张 OA 流程表单")
|
||
parser.add_argument("--base", default=BASE, help="接口地址,默认本机开发库")
|
||
parser.add_argument("--account", default="localadmin")
|
||
parser.add_argument("--password", default="admin123")
|
||
parser.add_argument("--check", action="store_true", help="只比对库里的表单与脚本是否一致,不写入")
|
||
parser.add_argument("--bind", action="store_true", help="已有同名流程时把它设为该流程的默认表单")
|
||
parser.add_argument("--create-process", action="store_true", help="顺带建四条草稿流程")
|
||
args = parser.parse_args()
|
||
BASE = args.base
|
||
|
||
token = login(args.account, args.password)
|
||
if args.check:
|
||
drifted = [(spec["name"], issues) for spec in FORMS
|
||
for issues in [check_form(token, spec)] if issues]
|
||
for name, issues in drifted:
|
||
for issue in issues:
|
||
print(f" 偏差:{issue}")
|
||
print("检查结果:" + ("四张表单与脚本完全一致" if not drifted
|
||
else f"{len(drifted)} 张表单有偏差,跑一次 python scripts/oa_forms.py 覆盖回去"))
|
||
return 1 if drifted else 0
|
||
for spec in FORMS:
|
||
form_id, created = save_form(token, spec)
|
||
marks = [f"{'新建' if created else '更新'}「{spec['name']}」:{len(spec['fields'])} 个字段,id {form_id}"]
|
||
if args.create_process:
|
||
marks.append(create_process(token, spec, form_id))
|
||
elif args.bind:
|
||
marks.append(bind_process(token, spec["name"], form_id))
|
||
print(" " + ";".join(marks))
|
||
print("完成:四张表单都走服务端校验存进库,可在「流程设计 - 表单」里直接打开。")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|