411 lines
21 KiB
Python
411 lines
21 KiB
Python
#!/usr/bin/env python3
|
||
"""只读那一屏点开嵌页面:只沿用对方已有那一页,没建过就还是卡片,一次接口都不打。
|
||
|
||
PYTHONPATH=. python3 scripts/check_embed_readonly_auto.py
|
||
|
||
用户那句原话是「嵌入页『打开就看到已有那一页』这一档,是根据配置的查看页面么?」——
|
||
问的是「我的发起 / 我的已办 / 单据详情」那种**回看屏**:那一屏点开那一格,既不该
|
||
在第三方那边又建出一页,也不该因为"这一格在当前环节是隐藏的"被拒在门外。
|
||
|
||
``embed.readonly`` 从两档变成三档之后,中间那一档 ``auto``(新默认)干的就是这件事:
|
||
界面只问"库里有没有这一页",**一次建页接口都不打、一条免登短码都不发、一笔留痕都不记**;
|
||
库里没货就退回那张卡片。契约是 ``EmbedLaunchBody`` 上新加的那两句,两句都只让后端
|
||
**少做事 / 只往严收窄**,所以可以听前端:
|
||
|
||
* ``reuse_only``:只允许沿用已有那一页。没存过就回 ``{"held": false}``;
|
||
* ``view_only``:这一屏是回看屏。``link=auto`` 不再问"他手上还有没有待办",一律给查看页;
|
||
当前环节把这一格藏了也不再把这一屏拒在门外(那一屏本来就把整张表单摊开给他看)。
|
||
|
||
钉这十一句,一句都对得上一种看得见的坏法:
|
||
|
||
1. 库里没这一页时问一句「只沿用」:回 ``held: false``,**建页接口一次都没被打**;
|
||
2. 那一句也没留下会话与短码——没建页就不该有凭据,第三方日志里多出的那几趟就是这么来的;
|
||
3. 「只沿用」没有把可见性放宽:与这张单没关系的人问同一句,照样一句"看不到这一格";
|
||
4. 同一格正常打开一次之后,再问「只沿用」就回对面第一次建的那一页,一次接口都不多打;
|
||
5. 回看屏要的是**查看页**那一条地址(配置的查看页那一路),不是发起人的编辑页;
|
||
6. 同一张单、同一个人,``view_only`` 只改给哪一条地址,不改对面那一页;
|
||
7. 不给 ``view_only`` 时发起人还压着待办,照旧是编辑页——这一句只往严收,不放宽;
|
||
8. 当前环节把这一格藏了:办这一环的人(办理屏)照旧 403,两边说同一句话;
|
||
9. 同一个人同一时刻换成回看屏(带 ``view_only``)就打得开——他手上那条待办在别的环节;
|
||
10. 没有待办的发起人从「我的发起」点开,即使当前环节藏了这一格也打得开;
|
||
11. 认不出来的 ``readonly`` 值退回 ``auto``,不把人踢回"每张单都要亲手点一次"。
|
||
|
||
跑完连自己造的源、会话、页面账、单据、流程与留痕一起删干净。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import pathlib
|
||
import sys
|
||
import threading
|
||
from datetime import datetime
|
||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
|
||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
|
||
|
||
from sqlalchemy import delete, func, or_, select # noqa: E402
|
||
from starlette.testclient import TestClient # noqa: E402
|
||
|
||
from app import models # noqa: E402
|
||
from app.db import SessionLocal # noqa: E402
|
||
from app.db import engine as db_engine # noqa: E402
|
||
from app.main import app # noqa: E402
|
||
from app.security import create_access_token # noqa: E402
|
||
from app.service import embed, personref # noqa: E402
|
||
|
||
STAMP = datetime.now().strftime("%m%d%H%M%S")
|
||
#: 只沿用这一路要试的那一格
|
||
FIELD_RO = "embedRoPage"
|
||
#: 环节上被藏起来的那一格:两道屏(办理 / 回看)对它的说法不一样
|
||
FIELD_HOLD = "embedHoldPage"
|
||
|
||
PASSED = 0
|
||
FAILS: list[str] = []
|
||
|
||
|
||
def check(label: str, condition, detail: str = "") -> None:
|
||
global PASSED
|
||
if condition:
|
||
PASSED += 1
|
||
print(f"[通过] {label}")
|
||
else:
|
||
FAILS.append(label)
|
||
print(f"[FAIL] {label}{f' -> {detail}' if detail else ''}")
|
||
|
||
|
||
def note(text: str) -> None:
|
||
print(f"[跳过] {text}")
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 第三方那一头:每调一次建一张页,一次回编辑页与查看页两条地址
|
||
# ---------------------------------------------------------------------------
|
||
|
||
class PageServer(ThreadingHTTPServer):
|
||
daemon_threads = True
|
||
|
||
def __init__(self, handler: type[BaseHTTPRequestHandler]) -> None:
|
||
super().__init__(("127.0.0.1", 0), handler)
|
||
self.calls = 0
|
||
self.pages: dict[str, int] = {}
|
||
|
||
|
||
class Handler(BaseHTTPRequestHandler):
|
||
def do_POST(self) -> None: # noqa: N802 - BaseHTTPRequestHandler 的命名
|
||
length = int(self.headers.get("Content-Length") or 0)
|
||
try:
|
||
no = str(json.loads(self.rfile.read(length).decode("utf-8", "replace")).get("no") or "")
|
||
except (ValueError, AttributeError):
|
||
no = ""
|
||
server = self.server # type: ignore[attr-defined]
|
||
server.calls += 1
|
||
page = server.pages.setdefault(no, len(server.pages) + 1)
|
||
base = f"http://127.0.0.1:{server.server_address[1]}/page"
|
||
body = json.dumps({"code": 0, "data": {
|
||
"url": f"{base}/edit?no={no}&page={page}",
|
||
"viewUrl": f"{base}/view?no={no}&page={page}",
|
||
}}).encode()
|
||
self.send_response(200)
|
||
self.send_header("Content-Type", "application/json")
|
||
self.send_header("Content-Length", str(len(body)))
|
||
self.end_headers()
|
||
self.wfile.write(body)
|
||
|
||
def log_message(self, *_args) -> None:
|
||
return
|
||
|
||
|
||
def page_no(url: object) -> str:
|
||
text = str(url or "")
|
||
marker = "page="
|
||
return text.split(marker, 1)[1].split("&", 1)[0] if marker in text else ""
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 这一趟用的那条源、那张表单与那张流程图
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def make_source(client: TestClient, headers: dict, port: int) -> str:
|
||
code = f"embed_ro_{STAMP}"
|
||
response = client.post("/api/v1/design/data-sources", headers=headers, json={
|
||
"code": code, "name": "只读只沿用·ERP 建页接口", "system": "ERP", "kind": "fetch",
|
||
"provider": "embed", "url": f"http://127.0.0.1:{port}/link", "method": "POST",
|
||
"bodyTemplate": {"no": "{arg.contractNo}"}, "urlMode": "api", "urlPath": "data.url",
|
||
"viewUrlPath": "data.viewUrl", "urlOrigins": [f"http://127.0.0.1:{port}"],
|
||
"pageMode": "none",
|
||
})
|
||
return code if response.status_code < 400 else ""
|
||
|
||
|
||
def build_form(db) -> str:
|
||
"""两格嵌页面 + 一格普通文本:那两格嵌页面一格没被藏、一格在被藏的环节上试。"""
|
||
form = models.FormElement(name=f"只读只沿用校验表单 {STAMP}",
|
||
content={"fields": [
|
||
{"key": "contractNo", "label": "合同编号", "type": "text"},
|
||
{"key": FIELD_RO, "label": "外部合同页", "type": "embed"},
|
||
{"key": FIELD_HOLD, "label": "外部凭证页", "type": "embed"},
|
||
]})
|
||
db.add(form)
|
||
db.commit()
|
||
return str(form.id)
|
||
|
||
|
||
def build_process(db, approver_ref: str, starter_ref: str, form_id: str) -> str:
|
||
"""发起 → 部门审批(藏起 ``FIELD_HOLD``)→ 发起人复核 → 结束。
|
||
|
||
第二环的审批人**就是发起人**:这样他既有编辑页的资格(这张单是他起的),手上又真压着
|
||
一条待办,正好试出 ``view_only`` 只往严收、``reuse_only`` 不动可见性这两句。
|
||
"""
|
||
process = models.Process(name=f"只读只沿用校验流程 {STAMP}", category="check",
|
||
enabled=True, published=True, latest_form=form_id,
|
||
latest_form_name=f"只读只沿用校验表单 {STAMP}")
|
||
db.add(process)
|
||
db.flush()
|
||
begin = models.Activity(process=process.id, type="begin", name="发起申请",
|
||
order_number=0, form=form_id, config={})
|
||
first = models.Activity(process=process.id, type="manual", name="部门审批", order_number=1,
|
||
form=form_id,
|
||
config={"mode": "any",
|
||
"taskValues": [{"type": "person", "data": [approver_ref]}],
|
||
"formPerms": {FIELD_HOLD: "hidden"}})
|
||
second = models.Activity(process=process.id, type="manual", name="发起人复核", order_number=2,
|
||
form=form_id,
|
||
config={"mode": "any",
|
||
"taskValues": [{"type": "person", "data": [starter_ref]}]})
|
||
end = models.Activity(process=process.id, type="end", name="结束", order_number=3)
|
||
db.add_all([begin, first, second, end])
|
||
db.flush()
|
||
db.add_all([
|
||
models.Route(process=process.id, name="提交", from_activity=begin.id, to_activity=first.id),
|
||
models.Route(process=process.id, name="通过", from_activity=first.id, to_activity=second.id),
|
||
models.Route(process=process.id, name="通过", from_activity=second.id, to_activity=end.id),
|
||
])
|
||
db.commit()
|
||
return str(process.id)
|
||
|
||
|
||
def cfg_of(code: str, field: str) -> dict:
|
||
"""那一格的配置。``FIELD_RO`` 上故意点名一个认不出的 ``readonly`` 值:退回 auto。"""
|
||
cfg = {"source": code, "params": {"contractNo": "{form.contractNo}"}, "height": 480}
|
||
if field == FIELD_RO:
|
||
cfg["readonly"] = "Auti"
|
||
return cfg
|
||
|
||
|
||
def launch(client: TestClient, headers: dict, code: str, field: str, **over) -> dict:
|
||
body = {"code": code, "field": field, "embed": cfg_of(code, field)}
|
||
body.update(over)
|
||
response = client.post("/api/v1/embed/launch", headers=headers, json=body)
|
||
if response.status_code >= 400:
|
||
return {"_status": response.status_code, "_text": response.text[:300]}
|
||
return (response.json() or {}).get("data") or {}
|
||
|
||
|
||
def count_rows(db, model, code: str) -> int:
|
||
db.commit() # MySQL 默认可重复读:不先收掉自己的事务,看不见接口那边刚提交的行
|
||
return int(db.execute(select(func.count()).select_from(model)
|
||
.where(model.source == code)).scalar() or 0)
|
||
|
||
|
||
def task_for(db, job: str, activity_name: str):
|
||
db.commit()
|
||
return db.execute(
|
||
select(models.Task).where(models.Task.job == job, models.Task.status == "pending",
|
||
models.Task.activity_name == activity_name).order_by(models.Task.id)
|
||
).scalars().first()
|
||
|
||
|
||
def approve(db, task) -> None:
|
||
from app.engine import engine
|
||
|
||
person = db.get(models.User, int(task.person))
|
||
engine.execute_task(db, task_id=str(task.id),
|
||
actor=engine.Actor.from_ref(db, person, str(task.identity or "")),
|
||
route_name="通过", opinion="同意")
|
||
db.commit()
|
||
|
||
|
||
def purge(db, code: str, process_id: str, form_id: str, jobs: list[str]) -> None:
|
||
ids = list(jobs)
|
||
ids += [row[0] for row in db.execute(select(models.Work.id).where(
|
||
models.Work.job.in_(jobs or ["-1"]))).all()]
|
||
ids += [row[0] for row in db.execute(select(models.WorkCompleted.id).where(
|
||
models.WorkCompleted.job.in_(jobs or ["-1"]))).all()]
|
||
for model in (models.WorkComment, models.Attachment, models.Notification, models.NotifyDelivery,
|
||
models.OutboundMessage, models.OpenEvent, models.WorkLog, models.TaskCompleted,
|
||
models.Task, models.WorkCompleted, models.Work):
|
||
columns = [getattr(model, name) for name in ("job", "work", "work_completed")
|
||
if hasattr(model, name)]
|
||
if columns and ids:
|
||
db.execute(delete(model).where(or_(*[column.in_(ids) for column in columns])))
|
||
if process_id:
|
||
db.execute(delete(models.Activity).where(models.Activity.process == process_id))
|
||
db.execute(delete(models.Route).where(models.Route.process == process_id))
|
||
db.execute(delete(models.Process).where(models.Process.id == process_id))
|
||
if form_id:
|
||
db.execute(delete(models.FormElement).where(models.FormElement.id == form_id))
|
||
if code:
|
||
if hasattr(models, "EmbedPage"):
|
||
db.execute(delete(models.EmbedPage).where(models.EmbedPage.source == code))
|
||
db.execute(delete(models.EmbedSession).where(models.EmbedSession.source == code))
|
||
db.execute(delete(models.EmbedTicket).where(models.EmbedTicket.source == code))
|
||
db.execute(delete(models.DataSourceLog).where(models.DataSourceLog.source == code))
|
||
db.execute(delete(models.DataSource).where(models.DataSource.code == code))
|
||
db.commit()
|
||
|
||
|
||
def main() -> int:
|
||
models.EmbedPage.__table__.create(bind=db_engine, checkfirst=True)
|
||
|
||
db = SessionLocal()
|
||
starter = db.get(models.User, 1)
|
||
others = db.execute(
|
||
select(models.User).where(models.User.id != 1,
|
||
models.User.status == models.UserStatus.ACTIVE)
|
||
.order_by(models.User.id).limit(2)
|
||
).scalars().all()
|
||
if starter is None or len(others) < 2:
|
||
note("库里凑不齐「发起人 + 两个不同的人」,这一项校不了")
|
||
db.close()
|
||
return 0
|
||
outsider = others[1]
|
||
|
||
server = PageServer(Handler)
|
||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||
port = int(server.server_address[1])
|
||
client = TestClient(app, raise_server_exceptions=False)
|
||
mine = {"Authorization": f"Bearer {create_access_token(str(starter.id))[0]}"}
|
||
headers_of = {str(person.id): {"Authorization": f"Bearer {create_access_token(str(person.id))[0]}"}
|
||
for person in [starter, *others]}
|
||
code = process_id = form_id = ""
|
||
jobs: list[str] = []
|
||
try:
|
||
code = make_source(client, mine, port)
|
||
check("建成了这条「地址由建页接口现给」的源", bool(code), code)
|
||
if not code:
|
||
return 1
|
||
form_id = build_form(db)
|
||
process_id = build_process(db, personref.ref_of(others[0]), personref.ref_of(starter), form_id)
|
||
|
||
created = client.post("/api/v1/job", headers=mine, json={
|
||
"process": process_id, "data": {"contractNo": f"HT-RO-{STAMP}"},
|
||
"title": f"只读只沿用校验单 {STAMP}"})
|
||
if created.status_code >= 400:
|
||
note(f"发起这张流程没成功({created.status_code}):{created.text[:160]}")
|
||
return 0
|
||
body = (created.json() or {}).get("data") or {}
|
||
job = str(body.get("job") or "")
|
||
jobs.append(job)
|
||
check("发起了一张真单据", bool(job), created.text[:160])
|
||
|
||
# --- 1~3. 库里还没有那一页时的「只沿用」 ---
|
||
calls = server.calls
|
||
empty = launch(client, mine, code, FIELD_RO, job=job, reuseOnly=True, viewOnly=True)
|
||
check("库里没这一页时问「只沿用」:回 held:false,一次建页接口都没打",
|
||
empty.get("held") is False and server.calls == calls,
|
||
f"{empty} / 接口 {calls} → {server.calls}")
|
||
check("那一句也没留下会话与短码:没建页就不该多发一份凭据",
|
||
count_rows(db, models.EmbedSession, code) == 0
|
||
and count_rows(db, models.EmbedTicket, code) == 0,
|
||
f"会话 {count_rows(db, models.EmbedSession, code)} 条 / "
|
||
f"短码 {count_rows(db, models.EmbedTicket, code)} 条")
|
||
outsider_empty = launch(client, headers_of[str(outsider.id)], code, FIELD_RO, job=job,
|
||
reuseOnly=True, viewOnly=True)
|
||
check("「只沿用」没有把可见性放宽:与这张单没关系的人问同一句照样被挡",
|
||
outsider_empty.get("_status") == 403, outsider_empty)
|
||
|
||
# --- 4~5. 正常打开一次之后,「只沿用」回的就是对面第一次那一页 ---
|
||
built = launch(client, mine, code, FIELD_RO, job=job, viewOnly=True)
|
||
first_page = page_no(built.get("url"))
|
||
check("正常打开一次确实建了页,回看屏拿的是查看页那一条地址",
|
||
bool(first_page) and built.get("link") == "view" and "/view?" in str(built.get("url")),
|
||
built)
|
||
calls = server.calls
|
||
held = launch(client, mine, code, FIELD_RO, job=job, reuseOnly=True, viewOnly=True)
|
||
check("同一格再问「只沿用」:回对面第一次建的那一页,一次接口都不多打",
|
||
held.get("held") is True and page_no(held.get("url")) == first_page
|
||
and server.calls == calls,
|
||
f"页号 {page_no(held.get('url'))} vs {first_page},接口 {calls} → {server.calls}")
|
||
|
||
# --- 6~7. view_only 只往严收:同一个人、同一张单,只改给哪一条地址 ---
|
||
task_a = task_for(db, job, "部门审批")
|
||
check("单子走到了部门审批", task_a is not None, job)
|
||
if task_a is None:
|
||
return 1
|
||
approve(db, task_a)
|
||
task_b = task_for(db, job, "发起人复核")
|
||
check("单子走到了「发起人复核」,这一环的待办就在发起人手上", task_b is not None, job)
|
||
if task_b is None:
|
||
return 1
|
||
acting = launch(client, mine, code, FIELD_RO, job=job)
|
||
check("不给 view_only 时发起人还压着待办,照旧给编辑页:这一句只收窄不放行",
|
||
acting.get("link") == "edit" and page_no(acting.get("url")) == first_page, acting)
|
||
calls = server.calls
|
||
watching = launch(client, mine, code, FIELD_RO, job=job, viewOnly=True)
|
||
check("同一张单同一个人,带上 view_only 就换成交付配置的查看页,且还是对面那一页",
|
||
watching.get("link") == "view" and page_no(watching.get("url")) == first_page
|
||
and server.calls == calls,
|
||
f"{watching} / 接口 {calls} → {server.calls}")
|
||
|
||
# --- 8~10. 当前环节把这一格藏了:办理屏照旧挡,回看屏放 ---
|
||
approve(db, task_b)
|
||
# 那一环已经过去了,直接另开一张单试「被藏那一格」的两种屏
|
||
fresh = client.post("/api/v1/job", headers=mine, json={
|
||
"process": process_id, "data": {"contractNo": f"HT-RO-{STAMP}-B"},
|
||
"title": f"只读只沿用校验单 B {STAMP}"})
|
||
if fresh.status_code >= 400:
|
||
note(f"再发起一张没成功({fresh.status_code}):{fresh.text[:160]}")
|
||
return finish()
|
||
job_b = str(((fresh.json() or {}).get("data") or {}).get("job") or "")
|
||
jobs.append(job_b)
|
||
task_b_a = task_for(db, job_b, "部门审批")
|
||
if task_b_a is None:
|
||
check("第二张单也走到了部门审批", False, job_b)
|
||
return finish()
|
||
approver = str(task_b_a.person)
|
||
# 先问「只沿用」:那一格在这一张单上还没建过页。这一句同时钉两件事——
|
||
# 没有待办的发起人从「我的发起」点开被藏的那一格,既不该吃那句 403,
|
||
# 也不该因为问了这一句就在对面建出一页来。
|
||
starter_b = launch(client, mine, code, FIELD_HOLD, job=job_b,
|
||
reuseOnly=True, viewOnly=True)
|
||
check("没有待办的发起人从「我的发起」点开被藏的那一格:不再吃那句「当前环节是隐藏的」,"
|
||
"库里没货就安静退成卡片",
|
||
starter_b.get("held") is False and starter_b.get("_status") is None, starter_b)
|
||
built_b = launch(client, mine, code, FIELD_HOLD, job=job_b)
|
||
check("同一格由没有待办的人正常打开一次:确实建了页(这一路才该打那个接口)",
|
||
bool(page_no(built_b.get("url"))) and built_b.get("_status") is None, built_b)
|
||
on_duty = launch(client, headers_of[approver], code, FIELD_HOLD, job=job_b)
|
||
check("办这一环的人点开被藏的那一格:办理屏照旧 403,两边说同一句话",
|
||
on_duty.get("_status") == 403, on_duty)
|
||
glance = launch(client, headers_of[approver], code, FIELD_HOLD, job=job_b,
|
||
viewOnly=True, reuseOnly=True)
|
||
check("同一个人同一时刻换成回看屏(带 view_only):不再被那句「当前环节是隐藏的」挡在门外",
|
||
glance.get("_status") is None and glance.get("held") is True, glance)
|
||
|
||
# --- 11. 认不出的 readonly 退回 auto ---
|
||
check("认不出的 readonly 值退回 auto,不把人踢回「每张单都要亲手点一次」",
|
||
embed.readonly_of({"embed": {"readonly": "Auti"}}) == embed.READONLY_AUTO
|
||
and embed.readonly_of({"embed": {}}) == embed.READONLY_AUTO
|
||
and embed.readonly_of({"embed": {"readonly": "frame"}}) == embed.READONLY_FRAME,
|
||
embed.readonly_of({"embed": {"readonly": "Auti"}}))
|
||
|
||
return finish()
|
||
finally:
|
||
server.shutdown()
|
||
purge(db, code, process_id, form_id, jobs)
|
||
db.close()
|
||
|
||
|
||
def finish() -> int:
|
||
print(f"\n共 {PASSED + len(FAILS)} 项,失败 {len(FAILS)} 项")
|
||
if FAILS:
|
||
print("只读那一屏「只沿用对方已有那一页」这条路**不对**:\n " + "\n ".join(FAILS))
|
||
return 1
|
||
print("通过:只读屏只沿用已有那一页,没建过就退成卡片,一次接口都不打")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|