bdip-office-assistant-cli 0.0.0-stage → 1.0.0

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.
Files changed (58) hide show
  1. package/README.md +37 -2
  2. package/dist/accounts.js +30 -0
  3. package/dist/args.js +36 -0
  4. package/dist/auth-token.js +778 -0
  5. package/dist/auth.js +290 -0
  6. package/dist/blog.js +562 -0
  7. package/dist/browser-links.js +223 -0
  8. package/dist/captcha-display.js +30 -0
  9. package/dist/cli.js +5479 -0
  10. package/dist/client.js +254 -0
  11. package/dist/config.js +170 -0
  12. package/dist/createcontext.js +41 -0
  13. package/dist/crypto.js +139 -0
  14. package/dist/cube.js +1771 -0
  15. package/dist/email.js +841 -0
  16. package/dist/field-preparation.js +185 -0
  17. package/dist/fileutil.js +20 -0
  18. package/dist/hrm.js +478 -0
  19. package/dist/keepalive.js +99 -0
  20. package/dist/kq.js +280 -0
  21. package/dist/links.js +34 -0
  22. package/dist/nodemap.js +242 -0
  23. package/dist/odoc.js +199 -0
  24. package/dist/office-tools.js +138 -0
  25. package/dist/pageopen.js +29 -0
  26. package/dist/parse.js +177 -0
  27. package/dist/password-input.js +84 -0
  28. package/dist/password-login.js +208 -0
  29. package/dist/querystate.js +38 -0
  30. package/dist/render.js +21 -0
  31. package/dist/report.js +50 -0
  32. package/dist/session-worker.js +54 -0
  33. package/dist/session.js +280 -0
  34. package/dist/submissionplan.js +45 -0
  35. package/dist/submissionstate.js +81 -0
  36. package/dist/subordinate.js +458 -0
  37. package/dist/supervise.js +152 -0
  38. package/dist/todoaskidea.js +54 -0
  39. package/dist/todobatch.js +172 -0
  40. package/dist/todocc.js +128 -0
  41. package/dist/todoforward.js +66 -0
  42. package/dist/todoreject.js +215 -0
  43. package/dist/todosubmit.js +325 -0
  44. package/dist/todotransfer.js +54 -0
  45. package/dist/util.js +25 -0
  46. package/dist/wfagent.js +538 -0
  47. package/dist/wfcreate.js +102 -0
  48. package/dist/wfform.js +169 -0
  49. package/dist/wfops.js +40 -0
  50. package/dist/wfreceiver.js +43 -0
  51. package/dist/wfstart.js +558 -0
  52. package/dist/wfsummary.js +89 -0
  53. package/dist/wfupload.js +78 -0
  54. package/dist/wfuser.js +96 -0
  55. package/dist/workflow-runtime.js +151 -0
  56. package/dist/workflow.js +570 -0
  57. package/dist/workplan.js +431 -0
  58. package/package.json +28 -6
@@ -0,0 +1,458 @@
1
+ /**
2
+ * 我的下属:查询直接/全部层级下属 + 越权防护(fail-closed)。
3
+ *
4
+ * 链路(用户抓包确认,POST 均表单编码):
5
+ * 1) /api/hrm/subordinateinfo/getSearchResult body { id, lastname, showAllLevel } → dataKey
6
+ * 2) /api/ec/dev/table/datas body { dataKey, current, sortParams } → 行 + columns(不带 pageSize,跟随服务端默认)
7
+ * 3) /api/ec/dev/table/counts body { dataKey } → 总数 {count:N,status:true}
8
+ *
9
+ * 越权边界(用户明确要求,fail-closed):
10
+ * 查询数据只能查「当前登录用户 + 全部层级下属」,目标人员不在授权集合 → 拒绝。
11
+ * 授权集合加载失败/不可靠时,非本人查询一律拒绝;本人永远允许。
12
+ *
13
+ * 安全设计要点:
14
+ * - 授权集合按环境隔离缓存 ~/.bdip/subordinate_scope_<envkey>.json,TTL 12h(E9_SCOPE_TTL_HOURS 可调)。
15
+ * - 缓存必须 selfId 匹配才可用(错用户/过期/不可靠一律不用,防离职下属仍被放行)。
16
+ * - 姓名→userid 解析唯一入口是 blog at-list(SKILL.md 硬规则),候选按 精确>前缀>拼音 排序后过滤到范围。
17
+ * - 下属表找不到 id 列 → scope 标记 reliable:false → 非本人查询拒绝(安全但功能受限,实跑校准回填规则)。
18
+ */
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import os from 'node:os';
22
+ import { createApiFromProfile } from './client.js';
23
+ import { extractDataKey, extractRows, extractColumns, extractTotal, pickByPaths, stripHtml } from './parse.js';
24
+ import { getCurrentUser } from './wfuser.js';
25
+ import { getAtAllList } from './blog.js';
26
+ import { profileNameFromBaseUrl } from './config.js';
27
+
28
+ /** 全层级下属翻页上限(超限仍未收全 → reliable:false)。 */
29
+ export const MAX_SCOPE_PAGES = 20;
30
+ /** 授权集合缓存 TTL(默认 12h,比台账目录的 7 天短——越权集合同理会随组织变动,宁短勿长)。 */
31
+ export const SCOPE_TTL_MS = (Number(process.env.E9_SCOPE_TTL_HOURS ?? '12') || 12) * 3600 * 1000;
32
+ /** 缓存目录(测试可用 E9_SCOPE_CACHE_DIR 覆盖,避免污染真实 ~/.e9)。 */
33
+ function scopeCacheDir() {
34
+ return process.env.E9_SCOPE_CACHE_DIR || path.join(os.homedir(), '.bdip');
35
+ }
36
+ function scopeCachePath(cfg) {
37
+ const envkey = profileNameFromBaseUrl(cfg.baseUrl);
38
+ return path.join(scopeCacheDir(), `subordinate_scope_${envkey}.json`);
39
+ }
40
+
41
+ // ─── 链路函数 ────────────────────────────────────────────
42
+
43
+ /** 拿下属列表 dataKey。token no-op 逃生:200 但无 dataKey 且配了 cookie → 强制 cookie 重试一次。 */
44
+ export async function fetchSubordinateDataKey(cfg, { lastname = '', showAllLevel = false } = {}) {
45
+ const api = await createApiFromProfile(cfg);
46
+ const body = { id: '', lastname: String(lastname ?? ''), showAllLevel: showAllLevel ? 'true' : 'false' };
47
+ let r = await api.post('/api/hrm/subordinateinfo/getSearchResult', body);
48
+ let dataKey = extractDataKey(r?.json);
49
+ if (!dataKey && cfg.cookie) {
50
+ r = await api.post('/api/hrm/subordinateinfo/getSearchResult', body, { forceCookie: true });
51
+ dataKey = extractDataKey(r?.json);
52
+ }
53
+ if (!dataKey) {
54
+ throw new Error('未能从 getSearchResult 响应中提取 dataKey。\n' + `响应(前300字): ${truncate(r?.text)}`);
55
+ }
56
+ return { dataKey, raw: r?.json ?? null };
57
+ }
58
+
59
+ /** 取下属表一页数据(不带 pageSize,跟随服务端默认每页条数)。 */
60
+ export async function fetchSubordinateDataPage(cfg, dataKey, page) {
61
+ const api = await createApiFromProfile(cfg);
62
+ const r = await api.post('/api/ec/dev/table/datas', { dataKey, current: String(page), sortParams: '[]' });
63
+ const json = r?.json ?? {};
64
+ return {
65
+ rows: extractRows(json),
66
+ columns: extractColumns(json),
67
+ pageSize: pickNum(json, ['pageSize', 'data.pageSize', 'rootMap.pagesize', 'data.rootMap.pagesize']),
68
+ raw: json,
69
+ };
70
+ }
71
+
72
+ /** 下属表总数。 */
73
+ export async function fetchSubordinateCount(cfg, dataKey) {
74
+ const api = await createApiFromProfile(cfg);
75
+ const r = await api.post('/api/ec/dev/table/counts', { dataKey });
76
+ return { total: extractTotal(r?.json), raw: r?.json ?? null };
77
+ }
78
+
79
+ // ─── 列检测(校准锚点,fail-closed 关键) ────────────────
80
+
81
+ /** 找下属表的 id 列(拿不到 → scope 不可靠 → 非本人查询拒绝)。 */
82
+ export function detectSubordinateIdColumn(columns) {
83
+ if (!Array.isArray(columns))
84
+ return null;
85
+ return columns.find((c) => {
86
+ const di = String(c?.dataIndex ?? '').toLowerCase();
87
+ const db = String(c?.dbField ?? '').toLowerCase();
88
+ return /^(id|userid|hrmid|randomfieldid)$/i.test(di) || /^(id|userid|hrmid)$/i.test(db);
89
+ }) ?? null;
90
+ }
91
+
92
+ /** 找下属表的姓名列(取不到 → userName 匹配失效,但 userId 匹配仍生效)。 */
93
+ export function detectSubordinateNameColumn(columns) {
94
+ if (!Array.isArray(columns))
95
+ return null;
96
+ return columns.find((c) => {
97
+ const di = String(c?.dataIndex ?? '').toLowerCase();
98
+ const title = String(c?.title ?? '');
99
+ return /^(lastname|name)$/i.test(di) || /姓名|人员|名字/.test(title);
100
+ }) ?? null;
101
+ }
102
+
103
+ // ─── 列表命令后端 ────────────────────────────────────────
104
+
105
+ /** 规范化一行下属:id/name + 全部列(<field>span 优先去 HTML)。人员无独立页面 → 纯文本。 */
106
+ export function normalizeSubordinateRow(row, columns) {
107
+ if (!row || typeof row !== 'object')
108
+ return {};
109
+ const idCol = detectSubordinateIdColumn(columns);
110
+ const nameCol = detectSubordinateNameColumn(columns);
111
+ const get = (k) => pickByPaths(row, [k]);
112
+ const id = idCol ? stripHtml(get(idCol.dataIndex)) : '';
113
+ const name = nameCol ? stripHtml(get(`${nameCol.dataIndex}span`) ?? get(nameCol.dataIndex)) : '';
114
+ const fields = (columns || []).map((c) => ({
115
+ dataIndex: c.dataIndex,
116
+ title: c.title,
117
+ value: stripHtml(get(`${c.dataIndex}span`) ?? get(c.dataIndex)),
118
+ }));
119
+ return { id, name, fields, idCol: idCol?.dataIndex, nameCol: nameCol?.dataIndex, raw: row };
120
+ }
121
+
122
+ /**
123
+ * 查询我的下属列表。showAllLevel=false=直接下属(抓包默认)/true=全部层级。
124
+ * 返回 { lastname, allLevel, page, pageSize, total, count, dataKey, columns, items, raw }。
125
+ */
126
+ export async function getSubordinates(cfg, opts = {}) {
127
+ const lastname = opts.lastname ?? '';
128
+ const allLevel = !!opts.allLevel;
129
+ const page = Number(opts.page ?? '1') || 1;
130
+ const { dataKey, raw: searchRaw } = await fetchSubordinateDataKey(cfg, { lastname, showAllLevel: allLevel });
131
+ const data = await fetchSubordinateDataPage(cfg, dataKey, page);
132
+ const count = await fetchSubordinateCount(cfg, dataKey);
133
+ const total = count.total ?? null;
134
+ const items = data.rows.map((r) => normalizeSubordinateRow(r, data.columns));
135
+ return {
136
+ lastname,
137
+ allLevel,
138
+ page,
139
+ pageSize: data.pageSize ?? (data.rows.length || null),
140
+ total,
141
+ count: items.length,
142
+ dataKey,
143
+ columns: data.columns,
144
+ items,
145
+ raw: { getSearchResult: searchRaw, datas: data.raw, counts: count.raw },
146
+ };
147
+ }
148
+
149
+ // ─── 授权集合加载 + 缓存(严格 fail-closed) ─────────────
150
+
151
+ /**
152
+ * 加载授权集合 { 当前用户 } ∪ { 全部层级下属 }。
153
+ * 返回 { reliable, error?, selfId, selfName, userIds:Set, userNames:Set, fromCache, fetchedAt }。
154
+ * reliable:false 表示集合不可靠(身份未确认/拉取失败/未收全/id 列缺失)→ 调用方只允许放行本人。
155
+ */
156
+ export async function loadScope(cfg, opts = {}) {
157
+ // 1. 自证身份:getCurrentUser → cookie 兜底 → 仍空则连本人都无法确认,一切带人查询拒绝
158
+ let selfId = '';
159
+ let selfName = '';
160
+ try {
161
+ const u = await getCurrentUser(cfg);
162
+ selfId = String(u?.userid ?? '');
163
+ selfName = String(u?.username ?? '');
164
+ }
165
+ catch { /* 走 cookie 兜底 */ }
166
+ if (!selfId)
167
+ selfId = parseUserIdFromCookie(cfg?.cookie);
168
+ if (!selfId) {
169
+ return { reliable: false, error: 'no-self', selfId: '', selfName: '', userIds: new Set(), userNames: new Set() };
170
+ }
171
+ // 2. 缓存命中:selfId 匹配 + 未过期 + reliable 才可用(错用户/过期/不可靠一律弃)
172
+ if (!opts.refresh && !opts.noCache) {
173
+ const cached = readScopeCache(cfg, selfId);
174
+ if (cached) {
175
+ return { ...cached, selfId, selfName, userIds: new Set(cached.userIds), userNames: new Set(cached.userNames), fromCache: true };
176
+ }
177
+ }
178
+ // 3. 拉全层级下属,逐页收行
179
+ const userIds = new Set([selfId]);
180
+ const userNames = new Set([selfName].filter(Boolean));
181
+ let reliable = false;
182
+ let idCol = null;
183
+ let nameCol = null;
184
+ let rows = [];
185
+ let total = null;
186
+ try {
187
+ const { dataKey } = await fetchSubordinateDataKey(cfg, { lastname: '', showAllLevel: true });
188
+ let page = 1;
189
+ let hitEnd = false;
190
+ while (page <= MAX_SCOPE_PAGES) {
191
+ const d = await fetchSubordinateDataPage(cfg, dataKey, page);
192
+ if (page === 1) {
193
+ idCol = detectSubordinateIdColumn(d.columns);
194
+ nameCol = detectSubordinateNameColumn(d.columns);
195
+ }
196
+ const pageRows = d.rows;
197
+ rows = rows.concat(pageRows);
198
+ if (pageRows.length === 0) {
199
+ hitEnd = true;
200
+ break;
201
+ }
202
+ // 短页 = 末尾(响应给了 pageSize 时能判;不给就靠 counts total 判完整)
203
+ if (d.pageSize && pageRows.length < d.pageSize) {
204
+ hitEnd = true;
205
+ break;
206
+ }
207
+ page++;
208
+ }
209
+ const count = await fetchSubordinateCount(cfg, dataKey);
210
+ total = count.total;
211
+ // 完整性判定:有 total 时收行数必须 >= total;无 total 时必须见到空页/短页才算到底
212
+ reliable = idCol != null && (total != null ? rows.length >= total : hitEnd);
213
+ if (reliable) {
214
+ for (const row of rows) {
215
+ const uid = stripHtml(pickByPaths(row, [idCol.dataIndex]));
216
+ if (/^\d+$/.test(uid))
217
+ userIds.add(uid);
218
+ if (nameCol) {
219
+ const nm = stripHtml(pickByPaths(row, [`${nameCol.dataIndex}span`, nameCol.dataIndex]));
220
+ if (nm)
221
+ userNames.add(nm);
222
+ }
223
+ }
224
+ }
225
+ }
226
+ catch { reliable = false; }
227
+ const scope = { reliable, error: reliable ? undefined : 'scope-unreliable', selfId, selfName, userIds, userNames, fetchedAt: Date.now() };
228
+ // 仅 reliable 才写缓存(写失败不阻断)
229
+ if (reliable)
230
+ writeScopeCache(cfg, scope);
231
+ return scope;
232
+ }
233
+
234
+ /** 读缓存;selfId 不匹配 / 过期 / 不可靠 → null。 */
235
+ function readScopeCache(cfg, selfId) {
236
+ try {
237
+ const raw = JSON.parse(fs.readFileSync(scopeCachePath(cfg), 'utf8'));
238
+ if (!raw || raw.selfId !== selfId || raw.reliable !== true)
239
+ return null;
240
+ if (Date.now() - (raw.fetchedAt || 0) > SCOPE_TTL_MS)
241
+ return null;
242
+ return raw;
243
+ }
244
+ catch {
245
+ return null;
246
+ }
247
+ }
248
+
249
+ /** 写缓存(失败不阻断)。 */
250
+ function writeScopeCache(cfg, scope) {
251
+ try {
252
+ fs.mkdirSync(scopeCacheDir(), { recursive: true });
253
+ fs.writeFileSync(scopeCachePath(cfg), JSON.stringify({
254
+ envkey: profileNameFromBaseUrl(cfg.baseUrl),
255
+ baseUrl: cfg.baseUrl,
256
+ selfId: scope.selfId,
257
+ selfName: scope.selfName,
258
+ userIds: [...scope.userIds],
259
+ userNames: [...scope.userNames],
260
+ reliable: scope.reliable,
261
+ fetchedAt: scope.fetchedAt,
262
+ }, null, 2) + '\n', 'utf8');
263
+ }
264
+ catch { /* 缓存写失败不阻断查询 */ }
265
+ }
266
+
267
+ /** 是否在授权集合内(纯函数,便于单测)。 */
268
+ export function isInScope(scope, { userId, userName } = {}) {
269
+ if (!scope || !scope.userIds)
270
+ return false;
271
+ if (userId != null && scope.userIds.has(String(userId).trim()))
272
+ return true;
273
+ if (userName != null && String(userName).trim() && scope.userNames?.has(String(userName).trim()))
274
+ return true;
275
+ return false;
276
+ }
277
+
278
+ // ─── 校验/拒绝 ───────────────────────────────────────────
279
+
280
+ /**
281
+ * 「只能查本人 + 全部层级下属」策略开关(当前默认**不生效**)。
282
+ * 设 BDIP_SCOPE_ENFORCE=1 可恢复强制校验;后台 OA 权限仍是最终兜底。
283
+ */
284
+ export function isScopeEnforced() {
285
+ return process.env.BDIP_SCOPE_ENFORCE === '1';
286
+ }
287
+
288
+ /**
289
+ * 按数字 userid 校验:目标必须 == 本人 或 ∈ 下属集合,否则 throw。
290
+ * ids 里的每个目标都校验;scope 不可靠时本人放行、他人一律拒绝。
291
+ * 策略未启用(默认)时直接放行——不做任何拦截。
292
+ */
293
+ export async function assertUserIdsInScope(cfg, ids, opts = {}) {
294
+ if (!isScopeEnforced())
295
+ return;
296
+ const scope = await loadScope(cfg, opts);
297
+ for (const id of ids) {
298
+ const s = String(id ?? '').trim();
299
+ if (!s)
300
+ continue;
301
+ // 本人恒允许(即使 scope 不可靠)——越权边界定义:本人 + 全部层级下属;
302
+ // no-self 时 selfId 为空,非空 id 自然落空走拒绝。
303
+ if (s === scope.selfId)
304
+ continue;
305
+ if (scope.reliable && scope.userIds.has(s))
306
+ continue;
307
+ throw new Error(outOfScopeMessage(s, { reason: scope.reliable ? 'not-subordinate' : (scope.error === 'no-self' ? 'no-self' : 'scope-unreliable') }));
308
+ }
309
+ }
310
+
311
+ /**
312
+ * 按姓名校验:纯数字走 assertUserIdsInScope;否则 blog at-list 解析(SKILL.md 硬规则唯一入口),
313
+ * 候选按 精确>前缀>拼音 排序后过滤到授权集合:
314
+ * - 恰 1 个在范围 → 放行,返回其 uid;
315
+ * - 全部越界 / 多个在范围 → throw(拒绝,附范围内候选清单)。
316
+ * 返回单个 uid(names 长度 1)或 uid 数组。调用方可忽略返回值(如 cube 仅校验、值保持原样)。
317
+ */
318
+ export async function assertNamesInScope(cfg, names, opts = {}) {
319
+ const scope = await loadScope(cfg, opts);
320
+ const resolved = [];
321
+ for (const name of names) {
322
+ const n = String(name ?? '').trim();
323
+ if (!n)
324
+ continue;
325
+ if (/^\d+$/.test(n)) {
326
+ await assertUserIdsInScope(cfg, [n], opts);
327
+ resolved.push(n);
328
+ continue;
329
+ }
330
+ const r = await getAtAllList(cfg, { name: n });
331
+ const candidates = sortPersonCandidates(r.items, n);
332
+ const { inScope, outCount } = filterCandidatesToScope(scope, candidates);
333
+ if (inScope.length === 0) {
334
+ throw new Error(outOfScopeMessage(n, { reason: 'none-in-scope', candidates: candidates.slice(0, 5), outCount }));
335
+ }
336
+ if (inScope.length === 1) {
337
+ resolved.push(String(inScope[0].uid ?? ''));
338
+ continue;
339
+ }
340
+ throw new Error(outOfScopeMessage(n, { reason: 'multiple-in-scope', candidates: inScope }));
341
+ }
342
+ return resolved.length === 1 ? resolved[0] : resolved;
343
+ }
344
+
345
+ /**
346
+ * 仅把姓名解析成 uid,**不做任何范围过滤**。
347
+ *
348
+ * 与 assertNamesInScope 的区别:后者用于「查询他人」类筛选,越界要拦;
349
+ * 而本函数用于**给他人派活**的场景(如流程代理把待办委托给谁——委托对象不限于下属),
350
+ * 只需遵守「人员搜索必须走 blog at-list」这条硬规则,不施加授权集合限制。
351
+ * 恰 1 个候选才返回;0 个 / 多个一律抛错并**列全候选**(不自动取首条)。
352
+ */
353
+ export async function resolveNameToUid(cfg, name) {
354
+ const n = String(name ?? '').trim();
355
+ if (!n)
356
+ throw new Error('人员姓名为空。');
357
+ if (/^\d+$/.test(n))
358
+ return n;
359
+ const r = await getAtAllList(cfg, { name: n });
360
+ const candidates = sortPersonCandidates(r.items, n);
361
+ if (candidates.length === 0)
362
+ throw new Error(`未找到「${n}」对应的人员(at-list 无候选)。`);
363
+ if (candidates.length > 1) {
364
+ const list = candidates.slice(0, 10).map((c) => `${stripHtml(String(c.name ?? ''))}(${c.uid})`).join('、');
365
+ throw new Error(`「${n}」匹配到 ${candidates.length} 个人员,请确认后用 --agent <用户id> 指定:${list}${candidates.length > 10 ? ' …' : ''}`);
366
+ }
367
+ return String(candidates[0].uid ?? '');
368
+ }
369
+
370
+ /** 候选过滤到授权集合(纯函数)。策略未启用(默认)时不过滤,全部视为在范围内。 */
371
+ export function filterCandidatesToScope(scope, candidates) {
372
+ if (!isScopeEnforced()) {
373
+ return { inScope: (candidates || []).map((c) => ({ ...c, name: stripHtml(String(c?.name ?? '')).trim() })), outCount: 0 };
374
+ }
375
+ const inScope = [];
376
+ let outCount = 0;
377
+ for (const c of candidates) {
378
+ const uid = String(c.uid ?? '');
379
+ const name = stripHtml(String(c.name ?? '')).trim();
380
+ if (uid && isInScope(scope, { userId: uid })) {
381
+ inScope.push({ ...c, name });
382
+ }
383
+ else if (name && isInScope(scope, { userName: name })) {
384
+ inScope.push({ ...c, name });
385
+ }
386
+ else {
387
+ outCount++;
388
+ }
389
+ }
390
+ return { inScope, outCount };
391
+ }
392
+
393
+ /** 人员候选排序:精确 > 前缀 > 其它(复刻 cli.js at-list 逻辑)。 */
394
+ function sortPersonCandidates(items, query) {
395
+ const q = String(query ?? '').trim().toLowerCase();
396
+ return (items || [])
397
+ .map((it) => {
398
+ const name = String(it.name ?? '').trim();
399
+ const nameLow = name.toLowerCase();
400
+ let matchType = 'other';
401
+ if (q && nameLow === q)
402
+ matchType = 'exact';
403
+ else if (q && nameLow.startsWith(q))
404
+ matchType = 'prefix';
405
+ return { ...it, name, matchType, _sort: matchType === 'exact' ? 0 : matchType === 'prefix' ? 1 : 2 };
406
+ })
407
+ .sort((a, b) => a._sort - b._sort)
408
+ .map(({ _sort, ...rest }) => rest);
409
+ }
410
+
411
+ /** 越权拒绝文案(fail-closed 显式归因)。 */
412
+ export function outOfScopeMessage(target, { reason = 'not-subordinate', candidates = [], outCount = 0 } = {}) {
413
+ let cause;
414
+ if (reason === 'no-self')
415
+ cause = '无法确认当前登录用户身份,为安全起见拒绝所有按人查询';
416
+ else if (reason === 'scope-unreliable')
417
+ cause = '下属范围加载失败,为安全起见仅允许查询您本人的数据';
418
+ else if (reason === 'none-in-scope')
419
+ cause = `匹配到 ${outCount} 位人员,均不在您的下属名单中`;
420
+ else if (reason === 'multiple-in-scope')
421
+ cause = '匹配到多位在您授权范围内的人员,请指定唯一目标';
422
+ else
423
+ cause = '目标不在您的下属名单中';
424
+ const lines = [`拒绝越权查询:目标“${target}”不在您的授权范围(您本人 + 您的全部层级下属)内。`, `原因:${cause}。`];
425
+ if (candidates.length) {
426
+ lines.push('在您授权范围内匹配到以下人员:');
427
+ candidates.forEach((c, i) => {
428
+ lines.push(`${i + 1}. ${c.name} [uid=${c.uid}]${c.matchType === 'exact' ? ' ★精确匹配' : c.matchType === 'prefix' ? ' ·前缀' : ''}`);
429
+ });
430
+ lines.push('如需继续,请指定其中一人的 ID 作为目标。');
431
+ }
432
+ lines.push('如需查询其本人数据,请在 OA 中由其本人或对其有权限的上级办理。');
433
+ return lines.join('\n');
434
+ }
435
+
436
+ // ─── 工具 ────────────────────────────────────────────────
437
+
438
+ function parseUserIdFromCookie(cookie) {
439
+ if (!cookie)
440
+ return '';
441
+ const m = String(cookie).match(/loginuuids=([^;]+)/);
442
+ return m ? m[1].trim() : '';
443
+ }
444
+
445
+ function pickNum(obj, paths) {
446
+ const v = pickByPaths(obj, paths);
447
+ if (typeof v === 'number')
448
+ return v;
449
+ if (typeof v === 'string' && /^\d+$/.test(v))
450
+ return parseInt(v, 10);
451
+ return null;
452
+ }
453
+
454
+ function truncate(s, n = 300) {
455
+ if (s == null)
456
+ return '(空)';
457
+ return String(s).length > n ? String(s).slice(0, n) + '…(已截断)' : String(s);
458
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * BDIP5 流程督办(supervise)模块。
3
+ *
4
+ * 链路(HAR 抓包实证 + 前端 bundle 逆向):
5
+ * 1) POST /api/workflow/supervise/getTree body{menuIds,menuPathIds} → topTab[](页签)+ treedata(流程类型树)
6
+ * 2) POST /api/workflow/supervise/getTreeCount body 同上 → {flowAllCounts, flowOverCounts, treecount{}} 各类型计数
7
+ * 3) POST /api/workflow/supervise/getConditionInfo body 空 → conditioninfo(搜索条件定义,结构与待办同构)
8
+ * 4) POST /api/workflow/supervise/getSessionkey body{同待办过滤项 + tabKey} → sessionkey(**恒顶层**)
9
+ * tabKey:0=全部 / 1=未督办 / 2=已督办 / 3=我的关注
10
+ * 5) POST /api/ec/dev/table/datas body{dataKey=sessionkey,current,sortParams} → columns + datas 行
11
+ * 6) POST /api/ec/dev/table/counts body{dataKey} → {count}
12
+ * 7) POST /api/workflow/supervise/doSupervise body{requestids,remark} → 发起督办(勾选多条用逗号分隔)
13
+ *
14
+ * 列表行 `ops` 含 4 个操作(前端 href 实证):督办(handle) / 短信催办(smsHandle) / 邮件催办(emailHandle) / 关注(doAttention)。
15
+ * ⚠️ 短信/邮件催办的**实际发送接口未抓到**(前端 getSendEmailInfo 取信息后要打开弹窗填写再发),故本模块只做「督办」。
16
+ */
17
+ import { endpointFor } from './config.js';
18
+ import { createApiFromProfile } from './client.js';
19
+ import { extractRows, extractColumns, extractTotal, pickByPaths, stripHtml } from './parse.js';
20
+
21
+ /** 督办菜单 id(抓包实证:menuIds=1,235)。 */
22
+ const SUPERVISE_MENU = { menuIds: '1,235', menuPathIds: '1,235' };
23
+
24
+ /** 督办页签:tabKey ↔ 中文名(getTree.topTab 实证)。 */
25
+ export const SUPERVISE_TABS = {
26
+ '全部': '0', '未督办': '1', '已督办': '2', '我的关注': '3',
27
+ };
28
+
29
+ /** 页签名/别名 → tabKey(数字直传)。 */
30
+ export function resolveSuperviseTab(spec) {
31
+ const s = String(spec ?? '').trim();
32
+ if (!s)
33
+ return '0';
34
+ if (/^[0-3]$/.test(s))
35
+ return s;
36
+ const key = Object.keys(SUPERVISE_TABS).find((k) => k === s || k.includes(s));
37
+ return key ? SUPERVISE_TABS[key] : undefined;
38
+ }
39
+
40
+ /** 督办页签 + 流程类型树。POST /api/workflow/supervise/getTree */
41
+ export async function getSuperviseTree(cfg) {
42
+ const api = await createApiFromProfile(cfg);
43
+ const r = await api.post('/api/workflow/supervise/getTree', SUPERVISE_MENU);
44
+ const j = r.json ?? {};
45
+ return {
46
+ tabs: (j.topTab ?? []).map((t) => ({ key: String(t.key ?? ''), title: String(t.title ?? '') })),
47
+ tree: j.treedata ?? [],
48
+ raw: j,
49
+ };
50
+ }
51
+
52
+ /** 督办计数。POST /api/workflow/supervise/getTreeCount(flowAllCounts=总数、flowOverCounts=未督办)。 */
53
+ export async function getSuperviseCount(cfg) {
54
+ const api = await createApiFromProfile(cfg);
55
+ const r = await api.post('/api/workflow/supervise/getTreeCount', SUPERVISE_MENU);
56
+ const j = r.json ?? {};
57
+ return {
58
+ total: j.flowAllCounts ?? null,
59
+ pending: j.flowOverCounts ?? null,
60
+ treeCount: j.treecount ?? {},
61
+ raw: j,
62
+ };
63
+ }
64
+
65
+ /** 督办搜索条件(结构与待办同构)。POST /api/workflow/supervise/getConditionInfo */
66
+ export async function getSuperviseConditions(cfg) {
67
+ const api = await createApiFromProfile(cfg);
68
+ const r = await api.post('/api/workflow/supervise/getConditionInfo', {});
69
+ const j = r.json ?? {};
70
+ const groups = (j.conditioninfo ?? []).map((g) => ({
71
+ title: String(g.title ?? ''),
72
+ items: (g.items ?? []).map((it) => ({
73
+ label: String(it.label ?? ''),
74
+ domkey: Array.isArray(it.domkey) ? it.domkey.join(',') : String(it.domkey ?? ''),
75
+ type: String(it.conditionType ?? ''),
76
+ })),
77
+ }));
78
+ return { groups, raw: j };
79
+ }
80
+
81
+ /**
82
+ * 督办列表。getSessionkey → table/datas → table/counts(同待办 table 链路)。
83
+ * opts: { tabKey, keyword, page, pageSize, ...过滤项 }
84
+ */
85
+ export async function listSupervise(cfg, opts = {}) {
86
+ const api = await createApiFromProfile(cfg);
87
+ const tabKey = String(opts.tabKey ?? '0');
88
+ const body = {
89
+ requestname: opts.keyword ?? '',
90
+ workcode: '', requestlevel: '', creatertype: '0',
91
+ ownerdepartmentid: opts.creatorDept ?? '', creatersubcompanyid: opts.creatorSubcom ?? '',
92
+ receivedateselect: '0', receivedatefrom: '', receivedateto: '',
93
+ createdateselect: '0', createdatefrom: '', createdateto: '',
94
+ wfstatu: '1', currentnodetype: '', unophrmid: '', docids: '',
95
+ hrmcreaterid: opts.creator ?? '', crmids: '', proids: '',
96
+ ...SUPERVISE_MENU, tabKey,
97
+ };
98
+ const r1 = await api.post('/api/workflow/supervise/getSessionkey', body);
99
+ const sessionkey = pickByPaths(r1.json, ['sessionkey', 'data.sessionkey']);
100
+ if (!sessionkey)
101
+ throw new Error(`未拿到督办 sessionkey(getSessionkey 响应:${(r1.text ?? '').slice(0, 200)})`);
102
+ const page = Number(opts.page ?? '1') || 1;
103
+ const r2 = await api.post('/api/ec/dev/table/datas', { dataKey: sessionkey, current: String(page), sortParams: '[]', pageSize: String(opts.pageSize ?? '10') });
104
+ const columns = extractColumns(r2.json);
105
+ const rows = extractRows(r2.json);
106
+ const items = rows.map((row) => normalizeSuperviseRow(row, columns));
107
+ let total = null;
108
+ let countsRaw = null;
109
+ try {
110
+ const r3 = await api.post('/api/ec/dev/table/counts', { dataKey: sessionkey });
111
+ countsRaw = r3.json;
112
+ total = extractTotal(r3.json);
113
+ }
114
+ catch { /* counts 失败不阻断 */ }
115
+ let pageSize = pickByPaths(r2.json, ['pageSize', 'data.pageSize']);
116
+ if (typeof pageSize !== 'number' && /^\d+$/.test(String(pageSize ?? '')))
117
+ pageSize = parseInt(String(pageSize), 10);
118
+ return { tabKey, page, total, pageSize: pageSize ?? null, items, sessionkey, columns, raw: { getSessionkey: r1.json, datas: r2.json, counts: countsRaw } };
119
+ }
120
+
121
+ /** 规范化一行督办(可读值优先取 `<field>span`,回退原值)。 */
122
+ export function normalizeSuperviseRow(row, columns) {
123
+ if (!row || typeof row !== 'object')
124
+ return {};
125
+ void columns;
126
+ const get = (keys) => pickByPaths(row, keys);
127
+ const spanOr = (k, extra = []) => stripHtml(get([`${k}span`, k, ...extra]));
128
+ return {
129
+ requestId: String(pickByPaths(row, ['requestid', 'randomField2', 'randomFieldId']) ?? ''),
130
+ title: stripHtml(get(['requestnamespan'])) || String(get(['requestname', 'requestName']) ?? ''),
131
+ creator: spanOr('creater', ['createrName']),
132
+ createTime: spanOr('createtime', ['createdate']),
133
+ node: stripHtml(get(['currentnodeidspan', 'currentnodespan'])) || String(get(['currentnodeid', 'currentnodename']) ?? ''),
134
+ unoperators: stripHtml(get(['unoperatorsspan', 'unoperators'])),
135
+ workflowId: String(get(['workflowid', 'randomField0']) ?? ''),
136
+ raw: row,
137
+ };
138
+ }
139
+
140
+ /** 发起督办。POST /api/workflow/supervise/doSupervise(body: requestids + remark)。 */
141
+ export async function doSupervise(cfg, opts = {}) {
142
+ const ep = endpointFor(cfg);
143
+ const requestIds = String(opts.requestIds ?? '').split(',').map((s) => s.trim()).filter(Boolean);
144
+ const remark = String(opts.remark ?? '');
145
+ if (!requestIds.length)
146
+ throw new Error('doSupervise 需要 requestIds(逗号分隔多个)。');
147
+ if (!opts.send)
148
+ return { sent: false, endpoint: { baseUrl: ep.baseUrl }, requestIds, remark };
149
+ const api = await createApiFromProfile(cfg);
150
+ const r = await api.post('/api/workflow/supervise/doSupervise', { requestids: requestIds.join(','), remark });
151
+ return { sent: true, endpoint: { baseUrl: ep.baseUrl }, requestIds, remark, response: r };
152
+ }
@@ -0,0 +1,54 @@
1
+ import { createApiFromProfile } from './client.js';
2
+ import { resolveReceivers } from './wfreceiver.js';
3
+ /**
4
+ * 意见征询(向某人征询意见,不改审批人)。实跑确认链路(2026-09-02 真机 .27):
5
+ * loadForm(取 workflowid/nodeid/操作人 userid) → signInput(forwardflag=2 预载) →
6
+ * remarkOperate(operate=save, forwardflag=2, field5=征询对象 userId) → {"success":true,"message":"流程意见征询成功"}。
7
+ *
8
+ * 与转发(forwardflag=1)/传阅(forwardflag=4)/转办(forwardflag=3)同款链路:均走 signInput → remarkOperate
9
+ * (0.5.1 起转发/传阅/转办不再走 requestOperation——会被服务端当"批准")。
10
+ * forward_token_<requestid>_<操作人userid> 由客户端生成(Date.now()),signInput 与 remarkOperate 须用同一值。
11
+ */
12
+ async function buildCommon(cfg, opts) {
13
+ const { requestId } = opts;
14
+ const api = await createApiFromProfile(cfg);
15
+ const r0 = await api.post('/api/workflow/reqform/loadForm', { iscreate: '0', requestid: String(requestId) });
16
+ const p = (r0.json ?? {}).params ?? {};
17
+ const userId = String(p.f_weaver_belongto_userid ?? '1');
18
+ const userType = String(p.f_weaver_belongto_usertype ?? '0');
19
+ const workflowid = String(p.workflowid ?? '');
20
+ const nodeid = String(p.nodeid ?? '');
21
+ const field5 = await resolveReceivers(cfg, opts);
22
+ if (!field5)
23
+ throw new Error('意见征询需要征询对象:传 --receiver <userId> 或 --receiver-name <姓名>');
24
+ const remarkText = opts.remark ?? '';
25
+ const remarkHtml = remarkText.split(/\r?\n/).map((l) => `<p>${l}</p>`).join('');
26
+ const tokenKey = `forward_token_${requestId}_${userId}`;
27
+ const token = String(Date.now());
28
+ const common = {
29
+ isShowReplyNotice: '0', takOverMins: '30', remark: remarkHtml,
30
+ workflowRequestLogId: '', forwardflag: '2', requestid: String(requestId),
31
+ nodeid, workflowid, 'f_weaver_belongto_userid': userId, 'f_weaver_belongto_usertype': userType,
32
+ agentType: '0', agentorByAgentId: '-1', secLevelInfo: '[object Object]',
33
+ [tokenKey]: token,
34
+ };
35
+ return { api, common, field5 };
36
+ }
37
+ export async function askIdeaTodo(cfg, opts) {
38
+ const { api, common, field5 } = await buildCommon(cfg, opts);
39
+ // ① signInput 预载(forwardflag=2,field5 空)
40
+ await api.post('/api/workflow/reqform/signInput', {
41
+ ...common, field5: '', IsSubmitedOpinion: '1', IsBeForwardTodo: '1',
42
+ });
43
+ // ② remarkOperate 提交(operate=save,field5=征询对象)
44
+ return api.post('/api/workflow/reqform/remarkOperate', {
45
+ ...common, field5,
46
+ operate: 'save',
47
+ openByDefaultBrowser: '', IsBeForwardSubmitAlready: '', IsBeForwardAlready: '',
48
+ IsSubmitedOpinion: '', IsBeForwardTodo: '',
49
+ isSubmitSign: '0', isChuanyue: '0', isRemind: '0',
50
+ signworkflowids: '', signdocids: '', remarkLocation: '',
51
+ 'field-annexupload': '', 'field-annexupload-request': String(opts.requestId),
52
+ handWrittenSign: '0', remindTypes: '',
53
+ });
54
+ }