160 lines
7.9 KiB
Python
160 lines
7.9 KiB
Python
#!/usr/bin/env python3
|
||
"""「票据核验系统」在这一侧的替身:只会三件事,而且全走 OA 的开放接口。
|
||
|
||
刻意不 import 后端任何 service——替身一旦能直接改库,演练就退化成"自己验自己"。
|
||
它手上只有一把带 ``check:write`` / ``check:read`` / ``task:write`` 的 key,能做的事与
|
||
真对方系统一字不差:
|
||
|
||
* 从发件箱拿到的那份报文里有一条**清单**链接,匿名 GET 就能换回附件清单与 10 分钟地址
|
||
(``GET /open/checks/files``、``GET /open/attachments/{id}/download``);
|
||
* 审完把结论回传(``POST /open/checks/report``)——**它改不了流转**,只能改台账;
|
||
* 想替财务把那条待办直接办掉(``POST /open/tasks/{id}/execute``),与 OA 页面抢同一条待办。
|
||
|
||
每一次调用都记在 ``calls`` 里,留档时原样贴出去,对方系统照这份清单就能对接。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
from typing import Any
|
||
|
||
from . import common
|
||
from .common import APP_CODE, SCENE, ok
|
||
|
||
|
||
class InvoiceSystem:
|
||
"""票据系统的视角。方法名用它的话说:收单、出结论、查批次、办待办。"""
|
||
|
||
def __init__(self, app_key: str, app_secret: str, checker: str = "票据系统·初审岗") -> None:
|
||
self.app_key = app_key
|
||
self.app_secret = app_secret
|
||
self.checker = checker
|
||
self._token = ""
|
||
self.calls: list[dict] = []
|
||
|
||
# -- 令牌 ---------------------------------------------------------------
|
||
|
||
def token(self, force: bool = False) -> str:
|
||
if self._token and not force:
|
||
return self._token
|
||
data = ok("POST", "/open/token", "", {"appKey": self.app_key, "appSecret": self.app_secret})
|
||
self._token = data["accessToken"]
|
||
print(f" [票据系统] 换来访问令牌,scopes={','.join(data.get('scopes') or [])}")
|
||
return self._token
|
||
|
||
def _call(self, method: str, path: str, body: dict | None = None,
|
||
params: dict | None = None) -> tuple[int, dict]:
|
||
status, payload = common.api(method, path, self.token(), body, params)
|
||
self.calls.append({"method": method, "path": path, "body": body,
|
||
"status": status, "data": payload.get("data") if status == 200 else payload})
|
||
return status, payload
|
||
|
||
# -- 结论回传 -----------------------------------------------------------
|
||
|
||
def report(self, biz_key: str, status: str, *, reason: str = "", items: list[dict] | None = None,
|
||
serial: str = "", version: int | None = None, external_ref: str = "",
|
||
checker: str = "", checked_at: str = "", scene: str = SCENE,
|
||
expect: str = "") -> dict:
|
||
"""回传一个结论。``expect`` 是演练想看到的字样(会打印出来,不匹配就报警)。
|
||
|
||
回的是 ``data`` 那一段:里面有 ``changed`` / ``duplicate`` / ``late`` / ``droppedItems``,
|
||
这三种"什么都没改"的下场正是这一路最需要被演清楚的东西。
|
||
"""
|
||
body: dict[str, Any] = {
|
||
"provider": common.SOURCE_OUT, "bizKey": biz_key, "status": status,
|
||
"reason": reason, "items": items or [], "checker": checker or self.checker,
|
||
"scene": scene,
|
||
}
|
||
if serial:
|
||
body["serial"] = serial
|
||
if version is not None:
|
||
body["version"] = version
|
||
if external_ref:
|
||
body["externalRef"] = external_ref
|
||
if checked_at:
|
||
body["checkedAt"] = checked_at
|
||
code, payload = self._call("POST", "/open/checks/report", body)
|
||
if code != 200 or payload.get("code") != 0:
|
||
message = str(payload.get("message") or json.dumps(payload, ensure_ascii=False))[:300]
|
||
if expect and expect in message:
|
||
print(f" [票据系统] 回传被拒(演练预期):{message}")
|
||
return {"rejected": True, "message": message}
|
||
raise AssertionError(f"回传结论失败:HTTP {code} {message}")
|
||
data = payload["data"]
|
||
flag = ("重复回传" if data.get("duplicate") else
|
||
"迟到丢弃" if data.get("late") else "已落库" if data.get("changed") else "收下未改")
|
||
print(f" [票据系统] 回传 {biz_key} → {status}:{flag};{data.get('note') or ''}")
|
||
if expect and expect not in json.dumps(data, ensure_ascii=False):
|
||
raise AssertionError(f"回传的答复里没有「{expect}」:{json.dumps(data, ensure_ascii=False)[:300]}")
|
||
return data
|
||
|
||
def passed(self, biz_key: str, receipts: list[dict], *, amount_total: float = 0.0,
|
||
reason: str = "", version: int | None = None) -> dict:
|
||
"""整批通过:逐票结论要一张一张给,界面与打印件上那句摘要靠它算。"""
|
||
return self.report(biz_key, "passed", reason=reason or "票面、抬头、税号与报销单一致,予以通过",
|
||
items=[self._item(row_, "passed", amount_total, version) for row_ in receipts],
|
||
version=version)
|
||
|
||
def rejected(self, biz_key: str, receipts: list[dict], bad: int = 0, *,
|
||
reason: str = "", version: int | None = None) -> dict:
|
||
"""整批驳回:``bad`` 那几张给具体原因,其余给"随整批驳回"。"""
|
||
rows = []
|
||
for index, receipt in enumerate(receipts):
|
||
if index == bad:
|
||
rows.append(self._item(receipt, "rejected", 0.0, version,
|
||
reason="购买方名称与报销单位不一致,这张不能报"))
|
||
else:
|
||
rows.append(self._item(receipt, "rejected", 0.0, version, reason="随整批退回,待补正"))
|
||
return self.report(biz_key, "rejected",
|
||
reason=reason or "有一张发票的购买方名称与报销单位不符",
|
||
items=rows, version=version)
|
||
|
||
@staticmethod
|
||
def _item(receipt: dict, status: str, amount_total: float, version: int | None,
|
||
reason: str = "") -> dict:
|
||
return {
|
||
"attachmentId": receipt.get("id", ""),
|
||
"invoiceNo": f"FP{str(receipt.get('id', ''))[-6:]}".upper(),
|
||
"name": receipt.get("name", ""),
|
||
"status": status,
|
||
"amount": round(amount_total / 2, 2) if amount_total and status == "passed" else 0,
|
||
"reason": reason,
|
||
"checkedVersion": version,
|
||
}
|
||
|
||
# -- 查批次 / 取附件 ----------------------------------------------------
|
||
|
||
def batch(self, biz_key: str) -> dict:
|
||
code, payload = self._call("GET", f"/open/checks/{biz_key}", params={"provider": common.SOURCE_OUT})
|
||
if code != 200 or payload.get("code") != 0:
|
||
raise AssertionError(f"查批次失败:HTTP {code} {payload.get('message')}")
|
||
return payload["data"]
|
||
|
||
def no_token_get(self, url: str) -> tuple[int, dict]:
|
||
"""匿名 GET:签名链接那两条要的就是"没有令牌也能进、改了参数就进不来"。"""
|
||
return common.raw_get_json(url)
|
||
|
||
def download(self, url: str) -> tuple[int, str, bytes]:
|
||
return common.raw_get(url)
|
||
|
||
# -- 与 OA 抢同一条待办 -------------------------------------------------
|
||
|
||
def execute_task(self, task_id: str, identity: str, route: str = "",
|
||
opinion: str = "") -> tuple[int, dict]:
|
||
"""代财务办单。回 ``(status, payload)``:这一条既要演成功也要演"已被人办掉"。"""
|
||
code, payload = self._call("POST", f"/open/tasks/{task_id}/execute",
|
||
{"identity": identity, "route": route, "opinion": opinion})
|
||
if code == 200 and payload.get("code") == 0:
|
||
print(f" [票据系统] 代 {identity} 办了待办 {task_id},出口「{route}」")
|
||
else:
|
||
print(f" [票据系统] 代办的答复:HTTP {code} {payload.get('message')}")
|
||
return code, payload
|
||
|
||
|
||
def api_root() -> str:
|
||
return common.API_ROOT
|
||
|
||
|
||
def app_code() -> str:
|
||
return APP_CODE
|