zt-oawf-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
zt_oawf_cli/api.py ADDED
@@ -0,0 +1,226 @@
1
+ """OAWF API 请求封装"""
2
+ import time
3
+ from urllib.parse import urlparse
4
+
5
+ import requests
6
+
7
+ from .auth import get_auth_cookies, get_auth_headers
8
+ from .config import config
9
+ from .detail import parse_review_detail, review_detail_url
10
+
11
+
12
+ class OawfApiError(RuntimeError):
13
+ """API 或登录态错误。"""
14
+
15
+
16
+ def _is_sso_url(url: str) -> bool:
17
+ parsed = urlparse(url or "")
18
+ hostname = (parsed.hostname or "").lower()
19
+ path = parsed.path.lower()
20
+ return (
21
+ hostname.startswith("sso.")
22
+ or "/cas/login" in path
23
+ or path.rstrip("/").endswith("/login")
24
+ )
25
+
26
+
27
+ def _is_html_response(response: requests.Response) -> bool:
28
+ content_type = response.headers.get("Content-Type", "").lower()
29
+ text = (response.text or "").lstrip().lower()
30
+ return "text/html" in content_type or text.startswith(("<!doctype html", "<html"))
31
+
32
+
33
+ def _is_auth_error(
34
+ response: requests.Response,
35
+ expected_url: str | None = None,
36
+ ) -> bool:
37
+ if response.status_code in (401, 403):
38
+ return True
39
+
40
+ actual_url = getattr(response, "url", "") or ""
41
+ expected_host = (urlparse(expected_url or "").hostname or "").lower()
42
+ actual_host = (urlparse(actual_url).hostname or "").lower()
43
+ if expected_host and actual_host and actual_host != expected_host:
44
+ return True
45
+
46
+ if _is_sso_url(actual_url):
47
+ return True
48
+ for previous in getattr(response, "history", []):
49
+ if _is_sso_url(previous.headers.get("Location", "")):
50
+ return True
51
+
52
+ if _is_html_response(response):
53
+ text = (response.text or "").lower()
54
+ if any(keyword in text for keyword in ("login", "sso", "sign in", "登录")):
55
+ return True
56
+
57
+ content_type = response.headers.get("Content-Type", "").lower()
58
+ if "application/json" in content_type:
59
+ try:
60
+ data = response.json()
61
+ except ValueError:
62
+ return False
63
+ if isinstance(data, dict):
64
+ msg = str(data.get("msg") or data.get("message") or "").lower()
65
+ if any(
66
+ keyword in msg
67
+ for keyword in ("login", "登录", "未授权", "认证", "session")
68
+ ):
69
+ return True
70
+
71
+ return False
72
+
73
+
74
+ def _response_excerpt(response: requests.Response, limit: int = 500) -> str:
75
+ text = " ".join((response.text or "").split())
76
+ return text[:limit]
77
+
78
+
79
+ class OawfApi:
80
+ """OAWF API 客户端"""
81
+
82
+ def __init__(self):
83
+ self.base_url = config.BASE_URL
84
+
85
+ def list_reviews(
86
+ self,
87
+ *,
88
+ mydoc: str = "all",
89
+ j_path: str = "/listAll",
90
+ orderby: str = "docCreateTime",
91
+ ordertype: str = "down",
92
+ paging_setting: str = "",
93
+ ):
94
+ """查询流程列表(对应 kmReviewIndex.do?method=list)。"""
95
+ return self.request(
96
+ "GET",
97
+ "/km/review/km_review_index/kmReviewIndex.do",
98
+ params={
99
+ "method": "list",
100
+ "pagingSetting": paging_setting,
101
+ "q.mydoc": mydoc,
102
+ "q.j_path": j_path,
103
+ "orderby": orderby,
104
+ "ordertype": ordertype,
105
+ "__seq": str(int(time.time() * 1000)),
106
+ "s_ajax": "true",
107
+ },
108
+ )
109
+
110
+ def get_review_detail(self, fd_id: str, *, _retried: bool = False) -> dict:
111
+ """获取流程详情(kmReviewMain.do?method=view,解析 HTML 表单)。"""
112
+ if not fd_id or not str(fd_id).strip():
113
+ raise OawfApiError("fdId 不能为空")
114
+
115
+ fd_id = str(fd_id).strip()
116
+ url = review_detail_url(self.base_url, fd_id)
117
+ cookies = get_auth_cookies()
118
+ headers = get_auth_headers(cookies)
119
+ headers = {
120
+ **headers,
121
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
122
+ }
123
+
124
+ try:
125
+ response = requests.get(
126
+ url,
127
+ headers=headers,
128
+ cookies=cookies,
129
+ timeout=60,
130
+ allow_redirects=True,
131
+ )
132
+ except requests.RequestException as exc:
133
+ raise OawfApiError(f"请求流程详情失败: {exc}") from exc
134
+
135
+ actual_url = getattr(response, "url", "") or url
136
+ if _is_sso_url(actual_url) or any(
137
+ _is_sso_url(prev.headers.get("Location", ""))
138
+ for prev in getattr(response, "history", [])
139
+ ):
140
+ if _retried:
141
+ raise OawfApiError(
142
+ "登录态已失效,请执行 `zt-oawf-cli login --headed` 后重试。"
143
+ )
144
+ try:
145
+ get_auth_cookies(force_refresh=True)
146
+ except Exception as exc:
147
+ raise OawfApiError(
148
+ f"登录态已失效,自动重新登录失败: {exc}。"
149
+ "请先执行 `zt-oawf-cli login --headed`。"
150
+ ) from exc
151
+ return self.get_review_detail(fd_id, _retried=True)
152
+
153
+ if response.status_code >= 400:
154
+ raise OawfApiError(
155
+ f"流程详情错误: {response.status_code} {_response_excerpt(response)}"
156
+ )
157
+
158
+ html = response.text or ""
159
+ # 登录页误判:无表单且明显是登录
160
+ if "kmReviewMainForm" not in html:
161
+ lower = html.lower()
162
+ if any(k in lower for k in ("/cas/login", "sso.", "请登录", "用户登录")):
163
+ if _retried:
164
+ raise OawfApiError(
165
+ "登录态已失效,请执行 `zt-oawf-cli login --headed` 后重试。"
166
+ )
167
+ get_auth_cookies(force_refresh=True)
168
+ return self.get_review_detail(fd_id, _retried=True)
169
+ raise OawfApiError(
170
+ f"未获取到流程详情,请确认 fdId 是否有效: {fd_id}"
171
+ )
172
+
173
+ try:
174
+ return parse_review_detail(html, fd_id=fd_id, url=url)
175
+ except ValueError as exc:
176
+ raise OawfApiError(str(exc)) from exc
177
+
178
+ def request(self, method: str, path: str, *, _retried: bool = False, **kwargs):
179
+ cookies = get_auth_cookies()
180
+ headers = get_auth_headers(cookies)
181
+ url = f"{self.base_url}/{path.lstrip('/')}"
182
+
183
+ try:
184
+ response = requests.request(
185
+ method=method,
186
+ url=url,
187
+ headers=headers,
188
+ cookies=cookies,
189
+ **kwargs,
190
+ )
191
+ except requests.RequestException as exc:
192
+ raise OawfApiError(f"请求失败: {exc}") from exc
193
+
194
+ if _is_auth_error(response, expected_url=url):
195
+ if _retried:
196
+ raise OawfApiError(
197
+ "登录态已失效,自动重新登录后仍未通过认证。"
198
+ "请执行 `zt-oawf-cli login --headed` 检查登录流程。"
199
+ )
200
+
201
+ try:
202
+ get_auth_cookies(force_refresh=True)
203
+ except Exception as exc:
204
+ raise OawfApiError(
205
+ f"登录态已失效,自动重新登录失败: {exc}。"
206
+ "请先执行 `zt-oawf-cli login --headed` 完成登录。"
207
+ ) from exc
208
+ return self.request(method, path, _retried=True, **kwargs)
209
+
210
+ if response.status_code >= 400:
211
+ raise OawfApiError(
212
+ f"API 错误: {response.status_code} {_response_excerpt(response)}"
213
+ )
214
+
215
+ if _is_html_response(response):
216
+ raise OawfApiError(
217
+ "API 返回了 HTML 页面,已拒绝将其作为数据输出。"
218
+ "请检查登录态或站点网关配置。"
219
+ )
220
+
221
+ try:
222
+ return response.json()
223
+ except ValueError as exc:
224
+ raise OawfApiError(
225
+ f"API 返回了非 JSON 响应: {_response_excerpt(response)}"
226
+ ) from exc
zt_oawf_cli/auth.py ADDED
@@ -0,0 +1,281 @@
1
+ """认证模块 - 通过 Playwright 获取 OAWF 浏览器 cookie"""
2
+ import json
3
+ import os
4
+ import sys
5
+ import tempfile
6
+ import time
7
+
8
+ from playwright.sync_api import sync_playwright
9
+
10
+ from .config import config
11
+
12
+
13
+ LOGIN_HOST = "oawf.ztn.cn"
14
+ LOGIN_URL = "https://oawf.ztn.cn/km/review/"
15
+ REVIEW_REFERER = "https://oawf.ztn.cn/km/review/"
16
+
17
+ REQUIRED_COOKIES = ("JSESSIONID", "OaToken")
18
+ AUTO_LOGIN_TIMEOUT_SECONDS = 60
19
+ MANUAL_LOGIN_TIMEOUT_SECONDS = 300
20
+ LOGIN_POLL_INTERVAL_MS = 1000
21
+
22
+
23
+ def _is_login_cookie_domain(domain: str) -> bool:
24
+ normalized = (domain or "").lstrip(".").lower()
25
+ return bool(normalized) and (
26
+ normalized == LOGIN_HOST or LOGIN_HOST.endswith(f".{normalized}")
27
+ )
28
+
29
+
30
+ def _extract_cookie_dict(cookies: list[dict]) -> dict:
31
+ matching = [
32
+ cookie
33
+ for cookie in cookies
34
+ if _is_login_cookie_domain(cookie.get("domain", ""))
35
+ ]
36
+ matching.sort(key=lambda cookie: len(cookie.get("domain", "").lstrip(".")))
37
+ return {cookie["name"]: cookie["value"] for cookie in matching}
38
+
39
+
40
+ def _has_required_cookies(cookies: dict) -> bool:
41
+ return all(cookies.get(name) for name in REQUIRED_COOKIES)
42
+
43
+
44
+ def save_cookies(cookies: dict):
45
+ config.CONFIG_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
46
+ os.chmod(config.CONFIG_DIR, 0o700)
47
+
48
+ fd, temp_name = tempfile.mkstemp(
49
+ prefix=f".{config.COOKIE_FILE.name}.",
50
+ dir=config.CONFIG_DIR,
51
+ text=True,
52
+ )
53
+ try:
54
+ with os.fdopen(fd, "w", encoding="utf-8") as file:
55
+ json.dump(cookies, file)
56
+ file.flush()
57
+ os.fsync(file.fileno())
58
+
59
+ os.chmod(temp_name, 0o600)
60
+ os.replace(temp_name, config.COOKIE_FILE)
61
+ os.chmod(config.COOKIE_FILE, 0o600)
62
+ except Exception:
63
+ try:
64
+ os.unlink(temp_name)
65
+ except FileNotFoundError:
66
+ pass
67
+ raise
68
+
69
+
70
+ def load_cookies() -> dict:
71
+ if config.COOKIE_FILE.exists():
72
+ with open(config.COOKIE_FILE, encoding="utf-8") as file:
73
+ return json.load(file)
74
+ return {}
75
+
76
+
77
+ def get_auth_headers(cookies: dict) -> dict:
78
+ return {
79
+ "Accept": "text/plain, */*; q=0.01",
80
+ "Accept-Language": "zh-CN,zh;q=0.9",
81
+ "Origin": f"https://{LOGIN_HOST}",
82
+ "Referer": REVIEW_REFERER,
83
+ "User-Agent": (
84
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
85
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
86
+ "Chrome/157.0.0.0 Safari/537.36"
87
+ ),
88
+ "X-Requested-With": "XMLHttpRequest",
89
+ }
90
+
91
+
92
+ def has_cached_cookies() -> bool:
93
+ return _has_required_cookies(load_cookies())
94
+
95
+
96
+ def clear_cookies():
97
+ if config.COOKIE_FILE.exists():
98
+ config.COOKIE_FILE.unlink()
99
+
100
+
101
+ def get_auth_cookies(*, force_refresh: bool = False) -> dict:
102
+ if not force_refresh and has_cached_cookies():
103
+ return load_cookies()
104
+
105
+ if force_refresh:
106
+ print("登录态已失效,正在重新登录...", file=sys.stderr)
107
+ else:
108
+ print("未检测到有效登录态,正在自动登录...", file=sys.stderr)
109
+
110
+ cookies = get_cookies_from_browser(headless=True)
111
+ save_cookies(cookies)
112
+ print("登录成功,cookie 已缓存", file=sys.stderr)
113
+ return cookies
114
+
115
+
116
+ def open_login_page(page) -> bool:
117
+ username = os.environ.get("ZT_SSO_USERNAME")
118
+ password = os.environ.get("ZT_SSO_PASSWORD")
119
+
120
+ if not username or not password:
121
+ return False
122
+
123
+ print("检测到环境变量,自动登录中...", file=sys.stderr)
124
+
125
+ try:
126
+ page.wait_for_selector("#username", timeout=15000)
127
+ page.fill("#username", username)
128
+ print("已填写用户名", file=sys.stderr)
129
+
130
+ page.fill("#password2", password)
131
+ print("已填写密码", file=sys.stderr)
132
+
133
+ page.click(".login_in")
134
+ print("已点击登录按钮", file=sys.stderr)
135
+ return True
136
+ except Exception as exc:
137
+ print(f"自动登录失败: {exc}", file=sys.stderr)
138
+ return False
139
+
140
+
141
+ def _detect_login_issue(page) -> str:
142
+ try:
143
+ if page.locator("#code").is_visible():
144
+ return "页面要求输入验证码"
145
+ except Exception:
146
+ pass
147
+
148
+ try:
149
+ text = page.locator("body").inner_text(timeout=2000)
150
+ except Exception:
151
+ text = ""
152
+
153
+ error_markers = (
154
+ "用户名或密码错误",
155
+ "账号或密码错误",
156
+ "密码错误",
157
+ "登录失败",
158
+ "已连续登录失败",
159
+ )
160
+ for marker in error_markers:
161
+ if marker in text:
162
+ return marker
163
+ return ""
164
+
165
+
166
+ def _wait_for_login(context, page, timeout_seconds: int, allow_manual: bool) -> None:
167
+ deadline = time.monotonic() + timeout_seconds
168
+ last_issue = ""
169
+
170
+ while time.monotonic() < deadline:
171
+ if _has_required_cookies(_extract_cookie_dict(context.cookies())):
172
+ return
173
+
174
+ issue = _detect_login_issue(page)
175
+ if issue and issue != last_issue:
176
+ last_issue = issue
177
+ if not allow_manual:
178
+ raise RuntimeError(f"自动登录未完成:{issue}")
179
+ if "验证码" in issue:
180
+ print(
181
+ "检测到验证码,请在浏览器窗口中完成验证并继续登录。",
182
+ file=sys.stderr,
183
+ )
184
+ else:
185
+ print(
186
+ f"检测到登录页提示:{issue}。请在浏览器窗口中完成登录。",
187
+ file=sys.stderr,
188
+ )
189
+
190
+ try:
191
+ page.wait_for_timeout(LOGIN_POLL_INTERVAL_MS)
192
+ except Exception as exc:
193
+ raise RuntimeError("浏览器页面已关闭,登录未完成。") from exc
194
+
195
+ action = "完成登录" if allow_manual else "完成自动登录"
196
+ raise RuntimeError(
197
+ f"登录超时({timeout_seconds} 秒),未能{action}。"
198
+ "可能原因:验证码、扫码登录、账号密码错误或网络异常。"
199
+ )
200
+
201
+
202
+ def _launch_browser(playwright, headless: bool):
203
+ channel = (config.browser_channel or "").strip().lower()
204
+ if not channel or channel == "chromium":
205
+ return playwright.chromium.launch(headless=headless)
206
+ return playwright.chromium.launch(headless=headless, channel=channel)
207
+
208
+
209
+ def get_cookies_from_browser(headless: bool = True) -> dict:
210
+ username = os.environ.get("ZT_SSO_USERNAME")
211
+ password = os.environ.get("ZT_SSO_PASSWORD")
212
+ if headless and (not username or not password):
213
+ raise RuntimeError(
214
+ "无头模式需要 ZT_SSO_USERNAME / ZT_SSO_PASSWORD 环境变量以完成自动登录;"
215
+ "如需手动登录,请使用 zt-oawf-cli login --headed。"
216
+ )
217
+
218
+ mode_text = "无头模式" if headless else "浏览器窗口"
219
+ print(f"正在启动浏览器({mode_text}),请登录...", file=sys.stderr)
220
+
221
+ with sync_playwright() as playwright:
222
+ try:
223
+ browser = _launch_browser(playwright, headless)
224
+ except Exception as exc:
225
+ raise RuntimeError(
226
+ "启动浏览器失败。请确认已执行 `python -m playwright install chromium`,"
227
+ f"或检查 config.yaml 中的 browser_channel 配置。原始错误: {exc}"
228
+ ) from exc
229
+
230
+ try:
231
+ context = browser.new_context()
232
+ page = context.new_page()
233
+
234
+ try:
235
+ page.goto(LOGIN_URL, wait_until="domcontentloaded")
236
+ except Exception as exc:
237
+ raise RuntimeError(f"无法打开 OAWF 登录页: {exc}") from exc
238
+
239
+ auto_login_started = False
240
+ if username and password:
241
+ auto_login_started = open_login_page(page)
242
+ if not auto_login_started:
243
+ if headless:
244
+ raise RuntimeError(
245
+ "自动填写登录表单失败,请检查登录页是否发生变化。"
246
+ )
247
+ print(
248
+ "自动登录未完成,请在已打开的浏览器窗口中手动登录。",
249
+ file=sys.stderr,
250
+ )
251
+ elif not headless:
252
+ print("浏览器窗口已打开,请在窗口中完成登录。", file=sys.stderr)
253
+
254
+ print("等待登录完成...", file=sys.stderr)
255
+ timeout = (
256
+ AUTO_LOGIN_TIMEOUT_SECONDS
257
+ if headless and auto_login_started
258
+ else MANUAL_LOGIN_TIMEOUT_SECONDS
259
+ )
260
+ _wait_for_login(
261
+ context,
262
+ page,
263
+ timeout_seconds=timeout,
264
+ allow_manual=not headless,
265
+ )
266
+
267
+ cookies = _extract_cookie_dict(context.cookies())
268
+ if not _has_required_cookies(cookies):
269
+ raise RuntimeError("登录已返回,但未获取完整的认证 cookie。")
270
+
271
+ print("登录成功,已获取关键 cookie", file=sys.stderr)
272
+ return cookies
273
+ finally:
274
+ browser.close()
275
+
276
+
277
+ def login(headless: bool = True) -> dict:
278
+ cookies = get_cookies_from_browser(headless=headless)
279
+ save_cookies(cookies)
280
+ print("登录成功,cookie 已缓存!", file=sys.stderr)
281
+ return cookies
zt_oawf_cli/cli.py ADDED
@@ -0,0 +1,322 @@
1
+ """CLI 入口"""
2
+ import json
3
+ import re
4
+
5
+ import click
6
+
7
+ from . import __version__
8
+ from .api import OawfApi, OawfApiError
9
+ from .auth import login
10
+
11
+ _HTML_TAG_RE = re.compile(r"<[^>]+>")
12
+ _WHITESPACE_RE = re.compile(r"\s+")
13
+
14
+
15
+ class OawfGroup(click.Group):
16
+ """将运行期错误转换为 Click 友好错误和非零退出码。"""
17
+
18
+ def invoke(self, ctx):
19
+ try:
20
+ return super().invoke(ctx)
21
+ except (click.exceptions.Exit, click.exceptions.Abort):
22
+ raise
23
+ except (OawfApiError, RuntimeError) as exc:
24
+ raise click.ClickException(str(exc)) from exc
25
+
26
+
27
+ def _strip_html(value) -> str:
28
+ raw = str(value or "")
29
+ # 优先取 title="..." 文本(Landray 常把可读名放在 title)
30
+ title_match = re.search(r'\btitle="([^"]*)"', raw)
31
+ if title_match and title_match.group(1).strip():
32
+ raw = title_match.group(1)
33
+ text = _HTML_TAG_RE.sub("", raw)
34
+ text = (
35
+ text.replace("&lt;", "<")
36
+ .replace("&gt;", ">")
37
+ .replace("&amp;", "&")
38
+ .replace("&nbsp;", " ")
39
+ .replace("&quot;", '"')
40
+ )
41
+ return _WHITESPACE_RE.sub(" ", text).strip(" \t\r\n\"'>")
42
+
43
+
44
+ def _normalize_landray_row(row):
45
+ """将 Landray datas 行([{col,value}, ...])转为普通 dict。"""
46
+ if isinstance(row, dict):
47
+ return row
48
+ if isinstance(row, list) and row and isinstance(row[0], dict) and "col" in row[0]:
49
+ return {cell.get("col"): cell.get("value") for cell in row if isinstance(cell, dict)}
50
+ return {"value": row}
51
+
52
+
53
+ def _extract_rows(result):
54
+ if isinstance(result, list):
55
+ return [_normalize_landray_row(row) for row in result]
56
+ if isinstance(result, dict):
57
+ for key in ("datas", "data", "rows", "list", "result", "results"):
58
+ value = result.get(key)
59
+ if isinstance(value, list):
60
+ return [_normalize_landray_row(row) for row in value]
61
+ return []
62
+
63
+
64
+ def _print_result(ctx, result, preferred_headers=None):
65
+ output_format = ctx.obj["output_format"]
66
+ if output_format == "json":
67
+ click.echo(json.dumps(result, ensure_ascii=False, indent=2))
68
+ return
69
+
70
+ rows = _extract_rows(result)
71
+ if not rows:
72
+ if result in (None, {}, []):
73
+ click.echo("暂无数据")
74
+ elif isinstance(result, dict):
75
+ page = result.get("page")
76
+ if page:
77
+ click.echo(
78
+ f"暂无数据(page={page.get('currentPage')}/"
79
+ f"size={page.get('pageSize')}/total={page.get('totalSize')})"
80
+ )
81
+ else:
82
+ click.echo("暂无数据")
83
+ else:
84
+ click.echo(str(result))
85
+ return
86
+
87
+ if isinstance(result, dict) and isinstance(result.get("page"), dict):
88
+ page = result["page"]
89
+ click.echo(
90
+ f"page={page.get('currentPage')} pageSize={page.get('pageSize')} "
91
+ f"totalSize={page.get('totalSize')}",
92
+ err=True,
93
+ )
94
+
95
+ if isinstance(rows[0], dict):
96
+ headers = preferred_headers or list(rows[0].keys())
97
+ available = [h for h in headers if any(h in row for row in rows)]
98
+ if not available:
99
+ available = list(rows[0].keys())
100
+ click.echo("\t".join(available))
101
+ for row in rows:
102
+ click.echo("\t".join(_strip_html(row.get(h, "-")) for h in available))
103
+ return
104
+
105
+ for row in rows:
106
+ click.echo(str(row))
107
+
108
+
109
+ @click.group(cls=OawfGroup)
110
+ @click.version_option(version=__version__, prog_name="zt-oawf-cli")
111
+ @click.option(
112
+ "--output",
113
+ "-o",
114
+ "output_format",
115
+ type=click.Choice(["human", "json"], case_sensitive=False),
116
+ default="json",
117
+ show_default=True,
118
+ help="输出格式: human / json",
119
+ )
120
+ @click.pass_context
121
+ def cli(ctx, output_format):
122
+ """ZT OAWF 命令行工具"""
123
+ ctx.ensure_object(dict)
124
+ ctx.obj["output_format"] = output_format.lower()
125
+
126
+
127
+ @cli.command("login")
128
+ @click.option(
129
+ "--headed",
130
+ is_flag=True,
131
+ help="显示浏览器窗口,用于无环境变量时的手动登录",
132
+ )
133
+ def cmd_login(headed):
134
+ """登录 - 打开浏览器获取 OAWF cookie(默认无头;需手动登录时请传 --headed)"""
135
+ login(headless=not headed)
136
+
137
+
138
+ @cli.group()
139
+ def wf():
140
+ """工作流 / 流程相关命令"""
141
+ pass
142
+
143
+
144
+ @wf.command("ping")
145
+ @click.pass_context
146
+ def wf_ping(ctx):
147
+ """脚手架连通性占位命令(不发起业务请求)"""
148
+ payload = {"ok": True, "message": "zt-oawf-cli scaffold ready"}
149
+ if ctx.obj["output_format"] == "json":
150
+ click.echo(json.dumps(payload, ensure_ascii=False, indent=2))
151
+ else:
152
+ click.echo(payload["message"])
153
+
154
+
155
+ _LIST_HEADERS = [
156
+ "fdNumber",
157
+ "docSubject",
158
+ "docCreator.fdName",
159
+ "docCreateTime",
160
+ "workitemStartDate",
161
+ "docStatus",
162
+ "nodeName",
163
+ "handlerName",
164
+ "fdId",
165
+ ]
166
+
167
+
168
+ def _run_review_list(ctx, *, mydoc, j_path, orderby, ordertype="down"):
169
+ api = OawfApi()
170
+ result = api.list_reviews(
171
+ mydoc=mydoc,
172
+ j_path=j_path,
173
+ orderby=orderby,
174
+ ordertype=ordertype.lower(),
175
+ )
176
+ _print_result(ctx, result, preferred_headers=_LIST_HEADERS)
177
+
178
+
179
+ @wf.command("list")
180
+ @click.option(
181
+ "--mydoc",
182
+ default="all",
183
+ show_default=True,
184
+ help="文档范围(对应 q.mydoc,如 all/approval/create)",
185
+ )
186
+ @click.option(
187
+ "--path",
188
+ "j_path",
189
+ default="/listAll",
190
+ show_default=True,
191
+ help="列表路径(对应 q.j_path)",
192
+ )
193
+ @click.option(
194
+ "--orderby",
195
+ default="docCreateTime",
196
+ show_default=True,
197
+ help="排序字段",
198
+ )
199
+ @click.option(
200
+ "--ordertype",
201
+ type=click.Choice(["down", "up"], case_sensitive=False),
202
+ default="down",
203
+ show_default=True,
204
+ help="排序方向:down=降序,up=升序",
205
+ )
206
+ @click.pass_context
207
+ def wf_list(ctx, mydoc, j_path, orderby, ordertype):
208
+ """查询流程列表(全部;kmReviewIndex method=list)"""
209
+ _run_review_list(
210
+ ctx,
211
+ mydoc=mydoc,
212
+ j_path=j_path,
213
+ orderby=orderby,
214
+ ordertype=ordertype,
215
+ )
216
+
217
+
218
+ @wf.command("approval")
219
+ @click.option(
220
+ "--ordertype",
221
+ type=click.Choice(["down", "up"], case_sensitive=False),
222
+ default="down",
223
+ show_default=True,
224
+ help="排序方向:down=降序,up=升序",
225
+ )
226
+ @click.pass_context
227
+ def wf_approval(ctx, ordertype):
228
+ """待我审批的工单(q.mydoc=approval, /listApproval)"""
229
+ _run_review_list(
230
+ ctx,
231
+ mydoc="approval",
232
+ j_path="/listApproval",
233
+ orderby="workitemStartDate",
234
+ ordertype=ordertype,
235
+ )
236
+
237
+
238
+ @wf.command("created")
239
+ @click.option(
240
+ "--ordertype",
241
+ type=click.Choice(["down", "up"], case_sensitive=False),
242
+ default="down",
243
+ show_default=True,
244
+ help="排序方向:down=降序,up=升序",
245
+ )
246
+ @click.pass_context
247
+ def wf_created(ctx, ordertype):
248
+ """我发起的工单(q.mydoc=create, /listCreate)"""
249
+ _run_review_list(
250
+ ctx,
251
+ mydoc="create",
252
+ j_path="/listCreate",
253
+ orderby="docCreateTime",
254
+ ordertype=ordertype,
255
+ )
256
+
257
+
258
+ @wf.command("approved")
259
+ @click.option(
260
+ "--ordertype",
261
+ type=click.Choice(["down", "up"], case_sensitive=False),
262
+ default="down",
263
+ show_default=True,
264
+ help="排序方向:down=降序,up=升序",
265
+ )
266
+ @click.pass_context
267
+ def wf_approved(ctx, ordertype):
268
+ """我已审核的工单(q.mydoc=approved, /listApproved)"""
269
+ _run_review_list(
270
+ ctx,
271
+ mydoc="approved",
272
+ j_path="/listApproved",
273
+ orderby="docCreateTime",
274
+ ordertype=ordertype,
275
+ )
276
+
277
+
278
+ @wf.command("detail")
279
+ @click.argument("fd_id")
280
+ @click.pass_context
281
+ def wf_detail(ctx, fd_id):
282
+ """查看流程详情(kmReviewMain method=view,按 fdId)"""
283
+ api = OawfApi()
284
+ result = api.get_review_detail(fd_id)
285
+ if ctx.obj["output_format"] == "json":
286
+ click.echo(json.dumps(result, ensure_ascii=False, indent=2))
287
+ return
288
+
289
+ summary = result.get("summary") or {}
290
+ click.echo(f"url\t{result.get('url')}")
291
+ for key in (
292
+ "fdNumber",
293
+ "docSubject",
294
+ "docStatus",
295
+ "docStatusLabel",
296
+ "docCreatorId",
297
+ "fdId",
298
+ ):
299
+ if summary.get(key) not in (None, ""):
300
+ click.echo(f"{key}\t{summary.get(key)}")
301
+
302
+ form_fields = result.get("form_fields") or []
303
+ if not form_fields:
304
+ click.echo("(无表单扩展字段)")
305
+ return
306
+
307
+ click.echo("--- form_fields ---")
308
+ click.echo("label\tname\tvalue")
309
+ for field in form_fields:
310
+ click.echo(
311
+ f"{_strip_html(field.get('label'))}\t"
312
+ f"{field.get('name')}\t"
313
+ f"{_strip_html(field.get('value'))}"
314
+ )
315
+
316
+
317
+ def main():
318
+ cli(prog_name="zt-oawf-cli")
319
+
320
+
321
+ if __name__ == "__main__":
322
+ main()
zt_oawf_cli/config.py ADDED
@@ -0,0 +1,28 @@
1
+ """配置管理模块"""
2
+ from pathlib import Path
3
+
4
+ import yaml
5
+
6
+
7
+ class Config:
8
+ CONFIG_DIR = Path.home() / ".zt-oawf-cli"
9
+ COOKIE_FILE = CONFIG_DIR / "cookies.json"
10
+ CONFIG_FILE = CONFIG_DIR / "config.yaml"
11
+
12
+ BASE_URL = "https://oawf.ztn.cn"
13
+
14
+ def __init__(self):
15
+ self._config = self._load_config()
16
+
17
+ def _load_config(self) -> dict:
18
+ if self.CONFIG_FILE.exists():
19
+ with open(self.CONFIG_FILE, encoding="utf-8") as f:
20
+ return yaml.safe_load(f) or {}
21
+ return {}
22
+
23
+ @property
24
+ def browser_channel(self) -> str:
25
+ return self._config.get("browser_channel", "chromium")
26
+
27
+
28
+ config = Config()
zt_oawf_cli/detail.py ADDED
@@ -0,0 +1,123 @@
1
+ """流程详情页 HTML 解析"""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from html import unescape
6
+
7
+ _INPUT_RE = re.compile(r"<input\b([^>]*)>", re.I)
8
+ _TEXTAREA_RE = re.compile(r"<textarea\b([^>]*)>(.*?)</textarea>", re.I | re.S)
9
+ _TITLE_RE = re.compile(r"<title>(.*?)</title>", re.I | re.S)
10
+ _ATTR_RE = {
11
+ "name": re.compile(r'\bname="([^"]+)"', re.I),
12
+ "value": re.compile(r'\bvalue="([^"]*)"', re.I),
13
+ "subject": re.compile(r'\bsubject="([^"]*)"', re.I),
14
+ }
15
+
16
+ DOC_STATUS_LABELS = {
17
+ "00": "废弃",
18
+ "10": "草稿",
19
+ "11": "驳回",
20
+ "20": "待审",
21
+ "30": "结束",
22
+ }
23
+
24
+
25
+ def review_detail_url(base_url: str, fd_id: str) -> str:
26
+ return (
27
+ f"{base_url.rstrip('/')}/km/review/km_review_main/kmReviewMain.do"
28
+ f"?method=view&fdId={fd_id}"
29
+ )
30
+
31
+
32
+ def _attr(attrs: str, key: str) -> str:
33
+ match = _ATTR_RE[key].search(attrs or "")
34
+ return unescape(match.group(1)) if match else ""
35
+
36
+
37
+ def _collect_fields(html: str) -> list[dict]:
38
+ fields: list[dict] = []
39
+ seen: set[tuple[str, str]] = set()
40
+
41
+ for match in _INPUT_RE.finditer(html):
42
+ attrs = match.group(1)
43
+ name = _attr(attrs, "name")
44
+ if not name:
45
+ continue
46
+ value = _attr(attrs, "value")
47
+ label = _attr(attrs, "subject")
48
+ key = (name, value)
49
+ if key in seen:
50
+ continue
51
+ seen.add(key)
52
+ fields.append({"name": name, "label": label, "value": value})
53
+
54
+ for match in _TEXTAREA_RE.finditer(html):
55
+ attrs, body = match.group(1), match.group(2)
56
+ name = _attr(attrs, "name")
57
+ if not name:
58
+ continue
59
+ label = _attr(attrs, "subject")
60
+ value = unescape(re.sub(r"<[^>]+>", "", body or "")).strip()
61
+ key = (name, value)
62
+ if key in seen:
63
+ continue
64
+ seen.add(key)
65
+ fields.append({"name": name, "label": label, "value": value})
66
+
67
+ return fields
68
+
69
+
70
+ def _first_value(fields: list[dict], name: str) -> str | None:
71
+ for field in fields:
72
+ if field["name"] == name and field["value"] != "":
73
+ return field["value"]
74
+ return None
75
+
76
+
77
+ def parse_review_detail(html: str, *, fd_id: str, url: str) -> dict:
78
+ """从 kmReviewMain view HTML 提取结构化详情。"""
79
+ if "kmReviewMainForm" not in html and 'name="fdId"' not in html:
80
+ raise ValueError("页面不是有效的流程详情(可能未登录或 fdId 无效)")
81
+
82
+ fields = _collect_fields(html)
83
+ values = {f["name"]: f["value"] for f in fields if f["value"] != ""}
84
+
85
+ title_match = _TITLE_RE.search(html or "")
86
+ title = ""
87
+ if title_match:
88
+ title = re.sub(r"\s+", " ", unescape(title_match.group(1))).strip()
89
+
90
+ doc_status = _first_value(fields, "docStatus")
91
+ summary = {
92
+ "fdId": _first_value(fields, "fdId") or fd_id,
93
+ "docSubject": _first_value(fields, "docSubject"),
94
+ "fdNumber": _first_value(fields, "fdNumber"),
95
+ "docStatus": doc_status,
96
+ "docStatusLabel": DOC_STATUS_LABELS.get(doc_status or "", doc_status),
97
+ "docCreatorId": _first_value(fields, "docCreatorId"),
98
+ "title": title,
99
+ }
100
+
101
+ def _pretty_label(name: str, label: str) -> str:
102
+ if label:
103
+ return label
104
+ match = re.fullmatch(r"extendDataFormInfo\.value\((.+)\)", name)
105
+ return match.group(1) if match else name
106
+
107
+ # 业务扩展字段(表单内容),去掉纯框架字段噪音
108
+ form_fields = [
109
+ {
110
+ "name": f["name"],
111
+ "label": _pretty_label(f["name"], f["label"]),
112
+ "value": f["value"],
113
+ }
114
+ for f in fields
115
+ if f["name"].startswith("extendDataFormInfo.value(") and f["value"] != ""
116
+ ]
117
+
118
+ return {
119
+ "url": url,
120
+ "summary": summary,
121
+ "form_fields": form_fields,
122
+ "values": values,
123
+ }
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: zt-oawf-cli
3
+ Version: 0.1.0
4
+ Summary: ZT OAWF CLI scaffold
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: playwright>=1.40.0
8
+ Requires-Dist: requests>=2.31.0
9
+ Requires-Dist: click>=8.1.0
10
+ Requires-Dist: pyyaml>=6.0
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=7.0; extra == "dev"
13
+
14
+ # zt-oawf-cli
15
+
16
+ ZT OAWF(`oawf.ztn.cn`)命令行工具:登录缓存 Cookie,查询流程列表。
17
+
18
+ ## 环境要求
19
+
20
+ - Python `>=3.10`
21
+ - 可用浏览器(首次登录会打开)
22
+
23
+ ## 安装
24
+
25
+ ### 开发安装(源码)
26
+
27
+ ```bash
28
+ pip install -e ".[dev]"
29
+ python -m playwright install chromium
30
+ ```
31
+
32
+ ### 打包发布
33
+
34
+ ```bash
35
+ python -m pip install --upgrade build twine
36
+ python -m build
37
+ twine upload dist/*
38
+ ```
39
+
40
+ ## 快速开始
41
+
42
+ ### 1) 登录并缓存 Cookie
43
+
44
+ 推荐有头登录(SSO / 验证码更稳):
45
+
46
+ ```bash
47
+ zt-oawf-cli login --headed
48
+ ```
49
+
50
+ 已设置 SSO 环境变量时也可无头:
51
+
52
+ ```bash
53
+ zt-oawf-cli login
54
+ ```
55
+
56
+ 登录成功后 Cookie 写入 `~/.zt-oawf-cli/cookies.json`(需含 `JSESSIONID`、`OaToken`)。
57
+
58
+ ### 2) 查询流程列表
59
+
60
+ 对应 `kmReviewIndex.do?method=list`:
61
+
62
+ ```bash
63
+ # 全部
64
+ zt-oawf-cli wf list
65
+ zt-oawf-cli -o human wf list
66
+
67
+ # 待我审批
68
+ zt-oawf-cli wf approval
69
+ zt-oawf-cli -o human wf approval
70
+
71
+ # 我发起的
72
+ zt-oawf-cli wf created
73
+ zt-oawf-cli -o human wf created
74
+
75
+ # 我已审核
76
+ zt-oawf-cli wf approved
77
+ zt-oawf-cli -o human wf approved
78
+
79
+ # 流程详情(fdId)
80
+ zt-oawf-cli wf detail 1a1f8e767ae0b5854254ddb42acb763d
81
+ zt-oawf-cli -o human wf detail 1a1f8e767ae0b5854254ddb42acb763d
82
+ ```
83
+
84
+ ### 3) 脚手架占位
85
+
86
+ ```bash
87
+ zt-oawf-cli wf ping
88
+ ```
89
+
90
+ ## 全局参数
91
+
92
+ - `-o, --output`:`json`(默认)/ `human`
93
+ - `--version`:查看版本
94
+
95
+ ## 配置说明
96
+
97
+ 默认配置目录:`~/.zt-oawf-cli`
98
+
99
+ - Cookie 缓存:`~/.zt-oawf-cli/cookies.json`
100
+ - 配置文件:`~/.zt-oawf-cli/config.yaml`
101
+
102
+ 可选:
103
+
104
+ ```yaml
105
+ browser_channel: chromium
106
+ ```
107
+
108
+ ## 环境变量(可选)
109
+
110
+ - `ZT_SSO_USERNAME`
111
+ - `ZT_SSO_PASSWORD`
112
+
113
+ 未设置时请执行 `zt-oawf-cli login --headed`。
114
+
115
+ ## 命令一览
116
+
117
+ - `zt-oawf-cli login [--headed]`
118
+ - `zt-oawf-cli wf list [--mydoc] [--path] [--orderby] [--ordertype]` — 全部
119
+ - `zt-oawf-cli wf approval` — 待我审批
120
+ - `zt-oawf-cli wf created` — 我发起的
121
+ - `zt-oawf-cli wf approved` — 我已审核
122
+ - `zt-oawf-cli wf detail <fdId>` — 流程详情
123
+ - `zt-oawf-cli wf ping`
@@ -0,0 +1,11 @@
1
+ zt_oawf_cli/__init__.py,sha256=Pru0BlFBASFCFo7McHdohtKkUtgMPDwbGfyUZlE2_Vw,21
2
+ zt_oawf_cli/api.py,sha256=0C7N_CoIR5YlNrRW2Ku09mucqMR2BYwWTjR0iXnzXZY,7866
3
+ zt_oawf_cli/auth.py,sha256=6iBs4cqbvOlEUs_g_-2rGJE2XkCJBtkBn1rJ8-I7POQ,9156
4
+ zt_oawf_cli/cli.py,sha256=gQnvqH1h7DOANt50dbNIvj8KH7EdQS7z-bOmFSDUKJY,8710
5
+ zt_oawf_cli/config.py,sha256=hpNtQ4iycVCWq4lvsOWSm7Ez83JhNnnmfHst5NbJ0-g,661
6
+ zt_oawf_cli/detail.py,sha256=xHndyKXHERVFHMLTrKOFa2PP1RdVgaBmgO4l1UgsRl4,3815
7
+ zt_oawf_cli-0.1.0.dist-info/METADATA,sha256=jLrlcSkzF40QyVlxTd-QfltGQr_5szYFST3VYX9d2SY,2379
8
+ zt_oawf_cli-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ zt_oawf_cli-0.1.0.dist-info/entry_points.txt,sha256=32wDpHGTrFougfTXsJs1v3cxEKBeVNJTTdpPqRkOWlA,53
10
+ zt_oawf_cli-0.1.0.dist-info/top_level.txt,sha256=Xcvi5VNFxjoTTlntZtKcu196di7rbigdK1DL4-U9LY8,12
11
+ zt_oawf_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ zt-oawf-cli = zt_oawf_cli.cli:main
@@ -0,0 +1 @@
1
+ zt_oawf_cli