dsh-uitest 2.1.1 → 2.1.3

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.
package/lib/ab.mjs ADDED
@@ -0,0 +1,760 @@
1
+ /**
2
+ * agent-browser 会话层(lib/ab.mjs)
3
+ * =====================================================================
4
+ * 把 `agent-browser` CLI 包成会话句柄:一个 `Ab` 对应一个命名 session,
5
+ * 页内读取/定位统一走 `eval`,动作统一走 CLI 的 click/fill/type/press。
6
+ *
7
+ * 为什么这样做:泛微 EBuilder 的子表是「Excel 表格渲染」,快照会爆炸,
8
+ * 而元素定位依赖表头列号 + 行内控件;用 eval 在页内精确取到元素、打上
9
+ * `data-ab-target` 标记,再交给 CLI 发真实鼠标/键盘事件,既保留原
10
+ * Playwright 脚本的定位精度,又不需要 Playwright 依赖。
11
+ */
12
+ import { spawn } from 'node:child_process';
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+ import { fileURLToPath } from 'node:url';
17
+
18
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
+ export const TEST_ROOT = path.resolve(__dirname, '../..');
20
+ export const AUTH_DIR = path.join(TEST_ROOT, '.auth');
21
+ export const SHOTS_DIR = path.join(TEST_ROOT, 'shots');
22
+ export const BASE_URL = process.env.OMS_BASE_URL || 'http://172.17.10.70:20600/';
23
+ export const LIST_URL =
24
+ 'http://172.17.10.70:20600/ebdapp/view/1248185764799545349/SEARCH/1273353070647500893-2037985215775852340' +
25
+ '?cusMenuId=2037985215775852340&appId_1273353070647500893=1248185764799545349';
26
+ export const TODO_URL =
27
+ 'http://172.17.10.70:20600/ebdapp/view/1248185764799545349/workflow/1248185764799545349_todo-2038270195886759042' +
28
+ '?cusMenuId=2038270195886759042';
29
+
30
+ const BIN = process.env.AGENT_BROWSER_BIN || 'agent-browser';
31
+
32
+ export const sleep = ms => new Promise(r => setTimeout(r, ms));
33
+ export const authFile = user => path.join(AUTH_DIR, `oms-${user}.json`);
34
+ export const DEFAULT_AUTH = path.join(AUTH_DIR, 'oms.json');
35
+
36
+ function run(args, { input, timeout = 180000 } = {}) {
37
+ // 泛微页面首屏和表单经常超过默认 25s,放宽到 60s
38
+ const env = {
39
+ ...process.env,
40
+ AGENT_BROWSER_DEFAULT_TIMEOUT: process.env.AGENT_BROWSER_DEFAULT_TIMEOUT || '60000',
41
+ AGENT_BROWSER_STREAM_QUALITY: process.env.AGENT_BROWSER_STREAM_QUALITY || '55',
42
+ AGENT_BROWSER_STREAM_MAX_WIDTH: process.env.AGENT_BROWSER_STREAM_MAX_WIDTH || '960',
43
+ AGENT_BROWSER_STREAM_MAX_HEIGHT: process.env.AGENT_BROWSER_STREAM_MAX_HEIGHT || '660',
44
+ // 用例结束后 daemon 闲置自动退出,避免整批用例累积大量 daemon/浏览器拖慢机器。
45
+ AGENT_BROWSER_IDLE_TIMEOUT_MS: process.env.AGENT_BROWSER_IDLE_TIMEOUT_MS || '600000',
46
+ };
47
+ // DSH 的 Windows 沙箱禁止受限子进程再用管道 stdio 启动孙子进程:libuv 用命名
48
+ // 管道实现 spawn 的 pipe stdio,其客户端请求的写权限不在 restricting SID 的
49
+ // 授权里,必现 spawn EPERM;继承 stdio 和文件重定向可用。Windows 上统一用
50
+ // 临时文件收集输出,Linux/macOS 保持管道(低延迟,且没有这个限制)。
51
+ if (process.platform === 'win32' || process.env.UITEST_AB_FILE_STDIO === '1') {
52
+ return runWithFiles(args, { input, timeout, env });
53
+ }
54
+ return runWithPipes(args, { input, timeout, env });
55
+ }
56
+
57
+ function timeoutMessage(args, timeout) {
58
+ return `agent-browser 超时(${timeout}ms): ${args.filter(a => !a.startsWith('--session')).slice(0, 4).join(' ')}`;
59
+ }
60
+
61
+ function runWithPipes(args, { input, timeout, env }) {
62
+ return new Promise((resolve, reject) => {
63
+ const p = spawn(BIN, args, { stdio: ['pipe', 'pipe', 'pipe'], env });
64
+ let out = '';
65
+ let err = '';
66
+ const timer = setTimeout(() => {
67
+ p.kill('SIGKILL');
68
+ reject(new Error(timeoutMessage(args, timeout)));
69
+ }, timeout);
70
+ p.stdout.on('data', d => { out += d; });
71
+ p.stderr.on('data', d => { err += d; });
72
+ p.on('error', e => { clearTimeout(timer); reject(e); });
73
+ // 子进程提前退出时 stdin 写入会抛 EPIPE;否则会变成未处理的 socket error 直接崩进程。
74
+ p.stdin.on('error', () => {});
75
+ p.on('close', code => {
76
+ clearTimeout(timer);
77
+ if (code !== 0) {
78
+ const detail = (err || out).replace(/\s+/g, ' ').trim().slice(0, 500);
79
+ reject(new Error(`agent-browser 退出 ${code}: ${detail}`));
80
+ } else resolve(out);
81
+ });
82
+ p.stdin.end(input === undefined ? '' : input);
83
+ });
84
+ }
85
+
86
+ /** 文件重定向版:子进程只继承文件句柄,不创建任何管道。行为与 runWithPipes 一致。 */
87
+ function runWithFiles(args, { input, timeout, env }) {
88
+ let dir;
89
+ try {
90
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'uitest-ab-'));
91
+ } catch (error) {
92
+ return Promise.reject(error);
93
+ }
94
+ const outPath = path.join(dir, 'stdout.log');
95
+ const errPath = path.join(dir, 'stderr.log');
96
+ const inPath = path.join(dir, 'stdin.txt');
97
+ const fds = [];
98
+ const cleanup = () => {
99
+ for (const fd of fds.splice(0)) {
100
+ try { fs.closeSync(fd); } catch { /* 已关闭 */ }
101
+ }
102
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* 可能仍被占用 */ }
103
+ };
104
+ const read = file => { try { return fs.readFileSync(file, 'utf8'); } catch { return ''; } };
105
+ try {
106
+ if (input !== undefined) fs.writeFileSync(inPath, String(input));
107
+ const stdin = input === undefined ? 'ignore' : fs.openSync(inPath, 'r');
108
+ if (stdin !== 'ignore') fds.push(stdin);
109
+ const stdout = fs.openSync(outPath, 'w');
110
+ const stderr = fs.openSync(errPath, 'w');
111
+ fds.push(stdout, stderr);
112
+ return new Promise((resolve, reject) => {
113
+ let settled = false;
114
+ let timer = null;
115
+ let p;
116
+ const finish = (fn, build) => {
117
+ if (settled) return;
118
+ settled = true;
119
+ if (timer) clearTimeout(timer);
120
+ const out = read(outPath);
121
+ const err = read(errPath);
122
+ cleanup();
123
+ fn(build(out, err));
124
+ };
125
+ try {
126
+ p = spawn(BIN, args, { stdio: [stdin, stdout, stderr], env, windowsHide: true });
127
+ } catch (error) {
128
+ finish(reject, () => error);
129
+ return;
130
+ }
131
+ timer = setTimeout(() => {
132
+ try { p.kill('SIGKILL'); } catch { /* 已退出 */ }
133
+ finish(reject, () => new Error(timeoutMessage(args, timeout)));
134
+ }, timeout);
135
+ p.on('error', error => finish(reject, () => error));
136
+ p.on('close', code => {
137
+ if (code !== 0) {
138
+ finish(reject, (out, err) => {
139
+ const detail = (err || out).replace(/\s+/g, ' ').trim().slice(0, 500);
140
+ return new Error(`agent-browser 退出 ${code}: ${detail}`);
141
+ });
142
+ } else {
143
+ finish(resolve, out => out);
144
+ }
145
+ });
146
+ });
147
+ } catch (error) {
148
+ cleanup();
149
+ return Promise.reject(error);
150
+ }
151
+ }
152
+
153
+ function parseJson(text) {
154
+ const s = String(text).trim();
155
+ const at = s.indexOf('{');
156
+ if (at < 0) throw new Error('agent-browser 没有返回 JSON: ' + s.slice(0, 200));
157
+ const j = JSON.parse(s.slice(at));
158
+ if (j.success === false) throw new Error(j.error || 'agent-browser 调用失败');
159
+ return j.data;
160
+ }
161
+
162
+ export class Ab {
163
+ constructor(session, { headed = false, state = null, profile = null } = {}) {
164
+ if (!/^[\p{L}\p{N}_-]+$/u.test(session)) throw new Error('非法 session 名:' + session);
165
+ this.session = session;
166
+ this.headed = headed;
167
+ this.state = state;
168
+ this.profile = profile;
169
+ this._launched = false;
170
+ this.closed = true;
171
+ }
172
+
173
+ async cmd(sub, { input, timeout = 180000, json = true } = {}) {
174
+ const args = ['--session', this.session];
175
+ if (json) args.push('--json');
176
+ args.push(...sub);
177
+ const out = await run(args, { input, timeout });
178
+ return json ? parseJson(out) : out.trim();
179
+ }
180
+
181
+ launchArgs() {
182
+ if (this._launched) return [];
183
+ const g = [];
184
+ if (this.state) g.push('--state', this.state);
185
+ if (this.headed) g.push('--headed');
186
+ if (this.profile) g.push('--profile', this.profile);
187
+ return g;
188
+ }
189
+
190
+ async open(url) {
191
+ const args = this.launchArgs();
192
+ this._launched = true;
193
+ this.closed = false;
194
+ try {
195
+ return await this.cmd([...args, 'open', url], { timeout: 120000 });
196
+ } catch (e) {
197
+ // 泛微首屏常超过 open 的 25s load 等待;导航已发出,交给调用方轮询 DOM
198
+ if (/waiting for load state|Timed out/i.test(e.message)) return null;
199
+ throw e;
200
+ }
201
+ }
202
+
203
+ async close() {
204
+ try { await this.cmd(['close'], { json: false, timeout: 30000 }); } catch { /* 已关闭 */ }
205
+ this._launched = false;
206
+ this.closed = true;
207
+ }
208
+
209
+ /** 在页面主文档执行函数;arg 会 JSON 序列化后传入。返回可序列化值。 */
210
+ async eval(fn, arg) {
211
+ const src = typeof fn === 'string'
212
+ ? fn
213
+ : `(${fn.toString()})(${JSON.stringify(arg === undefined ? null : arg)})`;
214
+ const d = await this.cmd(['eval', '--stdin'], { input: src, timeout: 120000 });
215
+ return d.result;
216
+ }
217
+
218
+ async url() { return (await this.cmd(['get', 'url'])).url; }
219
+ async title() { return (await this.cmd(['get', 'title'])).title; }
220
+
221
+ async click(sel) {
222
+ try { await this.cmd(['scrollintoview', sel], { timeout: 30000 }); } catch { /* 不可滚动 */ }
223
+ try {
224
+ await this.cmd(['click', sel], { timeout: 30000 });
225
+ } catch (e) {
226
+ const ok = await this.eval(s => {
227
+ const el = document.querySelector(s);
228
+ if (!el) return false;
229
+ el.click();
230
+ return true;
231
+ }, sel).catch(() => false);
232
+ if (!ok) throw e;
233
+ }
234
+ }
235
+
236
+ async fill(sel, text) {
237
+ await this.cmd(['fill', sel, '--', String(text)], { timeout: 60000 });
238
+ }
239
+
240
+ async type(sel, text, { clear = false, delay = 90 } = {}) {
241
+ const args = ['type', sel];
242
+ if (clear) args.push('--clear');
243
+ args.push('--delay', String(delay), '--', String(text));
244
+ await this.cmd(args, { timeout: 60000 });
245
+ }
246
+
247
+ async press(key) { await this.cmd(['press', key], { timeout: 30000 }); }
248
+
249
+ async waitFn(expr, timeout = 25000) {
250
+ await this.cmd(['wait', '--fn', expr, '--timeout', String(timeout)], { timeout: timeout + 10000 });
251
+ }
252
+
253
+ async waitText(text, timeout = 25000) {
254
+ await this.cmd(['wait', '--text', text, '--timeout', String(timeout)], { timeout: timeout + 10000 });
255
+ }
256
+
257
+ async screenshot(file) {
258
+ fs.mkdirSync(path.dirname(file), { recursive: true });
259
+ await this.cmd(['screenshot', file], { json: false, timeout: 60000 });
260
+ return path.relative(TEST_ROOT, file);
261
+ }
262
+
263
+ async stateSave(file) {
264
+ fs.mkdirSync(path.dirname(file), { recursive: true });
265
+ await this.cmd(['state', 'save', file], { json: false, timeout: 60000 });
266
+ }
267
+
268
+ async stateLoad(file) {
269
+ await this.cmd(['state', 'load', file], { json: false, timeout: 60000 });
270
+ }
271
+
272
+ async cookie(name, value, domain) {
273
+ await this.cmd(['cookies', 'set', name, value, '--domain', domain, '--path', '/'], { json: false, timeout: 30000 });
274
+ }
275
+
276
+ async tabs() { return (await this.cmd(['tab', 'list'])).tabs || []; }
277
+ async switchTab(ref) { await this.cmd(['tab', String(ref)], { json: false, timeout: 30000 }); }
278
+ async requests(filter) {
279
+ const args = ['network', 'requests'];
280
+ if (filter) args.push('--filter', filter);
281
+ return (await this.cmd(args)).requests || [];
282
+ }
283
+ }
284
+
285
+ /** 轮询页内条件,直到返回真值。 */
286
+ export async function until(ab, fn, { timeout = 120000, interval = 2000, arg, label = '' } = {}) {
287
+ const t0 = Date.now();
288
+ let last;
289
+ while (Date.now() - t0 < timeout) {
290
+ try {
291
+ last = await ab.eval(fn, arg);
292
+ if (last) return last;
293
+ } catch (e) {
294
+ last = 'eval-error: ' + e.message.slice(0, 120);
295
+ }
296
+ await sleep(interval);
297
+ }
298
+ throw new Error(`等待超时(${timeout}ms)${label ? ' [' + label + ']' : ''},最后状态: ${JSON.stringify(last)?.slice(0, 300)}`);
299
+ }
300
+
301
+ /** 登录并(可选)保存会话。返回存活的会话句柄,调用方负责 close。 */
302
+ export async function login({
303
+ user,
304
+ password = process.env.OMS_TEST_PW || process.env.OMS_PASSWORD || process.env.DSH_SECRET_OMS_PASSWORD,
305
+ session = `oms-login-${user}`,
306
+ out = null,
307
+ headed = false,
308
+ base = BASE_URL,
309
+ } = {}) {
310
+ if (!user) throw new Error('login 缺少 user');
311
+ if (!password) throw new Error('缺少密码:设置 OMS_TEST_PW 或 OMS_PASSWORD');
312
+ fs.mkdirSync(AUTH_DIR, { recursive: true });
313
+
314
+ const ab = new Ab(session, { headed });
315
+ await ab.close();
316
+ await ab.open(base);
317
+ await until(ab, () => document.querySelectorAll('input[type=password]').length > 0, {
318
+ timeout: 30000, label: '登录表单',
319
+ });
320
+
321
+ // 逐个定位并立即填写:每次打标都会清掉旧标记,所以不能先标记两个再填
322
+ const markInput = (selector, tag) => ab.eval(({ selector, tag }) => {
323
+ document.querySelectorAll('[data-ab-target]').forEach(e => e.removeAttribute('data-ab-target'));
324
+ const i = [...document.querySelectorAll(selector)].find(x => x.getBoundingClientRect().width > 0);
325
+ if (!i) return null;
326
+ i.setAttribute('data-ab-target', tag);
327
+ return `[data-ab-target="${tag}"]`;
328
+ }, { selector, tag });
329
+
330
+ const userSel = await markInput('input[type=text]', 'login-user');
331
+ if (!userSel) throw new Error('登录页找不到账号框');
332
+ await ab.fill(userSel, user);
333
+ await sleep(600);
334
+
335
+ const readForm = () => ab.eval(() => {
336
+ const u = [...document.querySelectorAll('input[type=text]')].find(x => x.getBoundingClientRect().width > 0);
337
+ const p = [...document.querySelectorAll('input[type=password]')].find(x => x.getBoundingClientRect().width > 0);
338
+ return { u: u?.value || '', p: p?.value.length || 0 };
339
+ });
340
+ let st = await readForm();
341
+ if (!st.u) {
342
+ const again = await markInput('input[type=text]', 'login-user');
343
+ if (again) await ab.fill(again, user);
344
+ await sleep(600);
345
+ st = await readForm();
346
+ }
347
+
348
+ const pwdSel = await markInput('input[type=password]', 'login-pwd');
349
+ if (!pwdSel) throw new Error('登录页找不到密码框');
350
+ await ab.fill(pwdSel, password);
351
+ await sleep(600);
352
+ const st2 = await readForm();
353
+ if (!st.u || !st2.p) throw new Error(`登录表单没吃进值:账号="${st.u}" 密码长度=${st2.p}`);
354
+
355
+ const btnSel = await ab.eval(() => {
356
+ const b = [...document.querySelectorAll('button')]
357
+ .find(x => x.getBoundingClientRect().width > 0 && /^\s*登录\s*$/.test((x.innerText || '').trim()));
358
+ if (!b) return null;
359
+ document.querySelectorAll('[data-ab-target]').forEach(e => e.removeAttribute('data-ab-target'));
360
+ b.setAttribute('data-ab-target', 'login-btn');
361
+ return '[data-ab-target="login-btn"]';
362
+ });
363
+ if (!btnSel) throw new Error('登录页找不到「登录」按钮');
364
+ await ab.click(btnSel);
365
+
366
+ await until(ab, () => !location.pathname.startsWith('/login') && (document.body.innerText || '').trim().length > 0, {
367
+ timeout: 45000, label: '登录成功',
368
+ });
369
+ // 语言状态由服务端 Cookie 决定,登录后强制回中文,避免半中半英传染
370
+ await ab.cookie('langType', 'zh_CN', new URL(base).hostname);
371
+
372
+ const info = await ab.eval(() => ({
373
+ url: location.href,
374
+ text: (document.body.innerText || '').replace(/\s+/g, ' ').slice(0, 200),
375
+ }));
376
+ if (out) await ab.stateSave(out);
377
+ return { ab, ...info };
378
+ }
379
+
380
+ /** 用已保存的会话打开页面。fresh=true 先关掉同名 session,确保 --state 真正被加载。 */
381
+ export async function openWithSession({
382
+ state = DEFAULT_AUTH,
383
+ session = `oms-${Date.now()}`,
384
+ headed = false,
385
+ url = LIST_URL,
386
+ fresh = true,
387
+ } = {}) {
388
+ if (!fs.existsSync(state)) throw new Error('未找到会话文件,请先登录:' + state);
389
+ const ab = new Ab(session, { headed, state });
390
+ if (fresh) await ab.close();
391
+ await ab.open(url);
392
+ return ab;
393
+ }
394
+
395
+ export const closePopovers = () => {
396
+ [...document.querySelectorAll('[class*=popover]')]
397
+ .filter(e => e.offsetParent && /工作消息/.test(e.innerText || ''))
398
+ .forEach(e => e.remove());
399
+ };
400
+
401
+ export async function gotoList(ab, { timeout = 180000 } = {}) {
402
+ await ab.open(LIST_URL);
403
+ if (/\/login/.test(await ab.url())) throw new Error('会话过期,先重新登录');
404
+ await until(ab, () =>
405
+ [...document.querySelectorAll('tbody tr')].filter(r => /SQ\d{10,}/.test(r.innerText || '')).length,
406
+ { timeout, interval: 2000, label: '报价单列表' });
407
+ await ab.eval(closePopovers);
408
+ await sleep(3000);
409
+ }
410
+
411
+ /** 列表默认只查最近 30 天;老源单会被时间筛选器挡掉。造数前先放宽到全年。 */
412
+ export async function widenDateRange(ab, {
413
+ start = '2026-01-01 00:00:00',
414
+ end = '2026-12-31 23:59:59',
415
+ } = {}) {
416
+ const markPh = ph => ab.eval((ph) => {
417
+ const e = [...document.querySelectorAll('input')]
418
+ .find(x => (x.placeholder || '') === ph && x.getBoundingClientRect().width > 0);
419
+ if (!e) return null;
420
+ document.querySelectorAll('[data-ab-target]').forEach(x => x.removeAttribute('data-ab-target'));
421
+ e.setAttribute('data-ab-target', 'date-' + ph);
422
+ return '[data-ab-target="date-' + ph + '"]';
423
+ }, ph);
424
+ const a = await markPh('开始日期');
425
+ if (a) { await ab.fill(a, start); await ab.press('Tab'); await sleep(500); }
426
+ const b = await markPh('结束日期');
427
+ if (b) { await ab.fill(b, end); await ab.press('Tab'); await sleep(500); }
428
+ const btn = await ab.eval(() => {
429
+ const e = [...document.querySelectorAll('button')]
430
+ .find(x => x.getBoundingClientRect().width > 0 && /^\s*搜索\s*$/.test((x.innerText || '').trim()));
431
+ if (!e) return null;
432
+ document.querySelectorAll('[data-ab-target]').forEach(x => x.removeAttribute('data-ab-target'));
433
+ e.setAttribute('data-ab-target', 'search-wide');
434
+ return '[data-ab-target="search-wide"]';
435
+ });
436
+ if (btn) { await ab.click(btn); await sleep(4000); }
437
+ return !!(a && b && btn);
438
+ }
439
+
440
+ export async function filterByNo(ab, no) {
441
+ const sel = await ab.eval(() => {
442
+ const i = [...document.querySelectorAll('input')]
443
+ .find(x => /报价单编号/.test(x.placeholder || '') && x.getBoundingClientRect().width > 0);
444
+ if (!i) return null;
445
+ document.querySelectorAll('[data-ab-target]').forEach(e => e.removeAttribute('data-ab-target'));
446
+ i.setAttribute('data-ab-target', 'filter-no');
447
+ return '[data-ab-target="filter-no"]';
448
+ });
449
+ if (!sel) return false;
450
+ await ab.fill(sel, no);
451
+ await ab.press('Enter');
452
+ // 只认目标行出现,别把上一次筛选残留的「暂无数据」当成完成
453
+ await until(ab, n => [...document.querySelectorAll('tbody tr')].some(r => (r.innerText || '').includes(n)),
454
+ { arg: no, timeout: 25000, interval: 1500, label: '筛选 ' + no }).catch(() => {});
455
+ await ab.eval(closePopovers);
456
+ await sleep(1500);
457
+ return true;
458
+ }
459
+
460
+ export function readRowsFn() {
461
+ const th = [...document.querySelectorAll('thead th')].map(e => (e.innerText || '').trim());
462
+ const cell = (cells, name) => {
463
+ const i = th.indexOf(name);
464
+ return i < 0 ? '' : (cells[i] || '');
465
+ };
466
+ return [...document.querySelectorAll('tbody tr')].map(tr => {
467
+ const cells = [...tr.children].map(x => (x.innerText || '').replace(/\s+/g, ' ').trim());
468
+ return {
469
+ no: (cells.join(' ').match(/SQ\d{10,}/) || [])[0] || '',
470
+ state: cell(cells, '报价单状态'),
471
+ approval: cell(cells, '审批状态'),
472
+ biz: cell(cells, '业务说明'),
473
+ svc: cell(cells, '服务名称'),
474
+ operate: cells[cells.length - 1] || '',
475
+ cells,
476
+ };
477
+ }).filter(r => r.no);
478
+ }
479
+
480
+ export async function listRows(ab) {
481
+ return ab.eval(readRowsFn);
482
+ }
483
+
484
+ export async function findRow(ab, no) {
485
+ const rows = await listRows(ab);
486
+ return rows.find(r => r.no === no) || null;
487
+ }
488
+
489
+ /** 在指定单号那一行里点操作文字(复制/编辑/删除/转订单…)。 */
490
+ export async function clickRowAction(ab, no, label) {
491
+ for (let attempt = 0; attempt < 3; attempt++) {
492
+ const sel = await markRowAction(ab, no, label);
493
+ if (sel) { await ab.click(sel); return true; }
494
+ await sleep(2000);
495
+ }
496
+ return false;
497
+ }
498
+
499
+ async function markRowAction(ab, no, label) {
500
+ return ab.eval(({ no, label }) => {
501
+ const row = [...document.querySelectorAll('tbody tr')]
502
+ .find(r => [...r.children].some(c => (c.innerText || '').includes(no)));
503
+ if (!row) return null;
504
+ const leaf = [...row.querySelectorAll('*')]
505
+ .find(e => e.children.length === 0 && (e.textContent || '').trim() === label && e.getBoundingClientRect().width > 0);
506
+ if (!leaf) return null;
507
+ document.querySelectorAll('[data-ab-target]').forEach(e => e.removeAttribute('data-ab-target'));
508
+ leaf.setAttribute('data-ab-target', 'row-action');
509
+ return '[data-ab-target="row-action"]';
510
+ }, { no, label });
511
+ }
512
+
513
+ /** 等右侧表单渲染到业务说明 + 至少两张子表。 */
514
+ export async function waitForForm(ab, { timeout = 180000 } = {}) {
515
+ await until(ab, () => {
516
+ const hasDesc = !!document.querySelector('.ui-dialog-content-right textarea[placeholder*="业务说明"]');
517
+ const tables = document.querySelectorAll('table.excelTableView-content-excel-table').length;
518
+ return hasDesc && tables >= 2;
519
+ }, { timeout, interval: 2000, label: '报价单表单' });
520
+ await sleep(6000);
521
+ }
522
+
523
+ /** 等可见下拉候选里出现目标文本并点中。 */
524
+ export async function pickOption(ab, text, { exact = true, timeout = 25000 } = {}) {
525
+ const t0 = Date.now();
526
+ while (Date.now() - t0 < timeout) {
527
+ const sel = await ab.eval(({ text, exact }) => {
528
+ const items = [...document.querySelectorAll(
529
+ '.ui-browser-associative-dropdown-list-item, .ui-select-dropdown li, .ui-select-option, [class*=select-dropdown] li'
530
+ )].filter(e => e.getBoundingClientRect().width > 0);
531
+ const hit = items.find(e => {
532
+ const t = (e.innerText || '').trim();
533
+ return exact ? t === text : t.includes(text);
534
+ });
535
+ if (!hit) return null;
536
+ document.querySelectorAll('[data-ab-target]').forEach(e => e.removeAttribute('data-ab-target'));
537
+ hit.setAttribute('data-ab-target', 'option');
538
+ return '[data-ab-target="option"]';
539
+ }, { text, exact });
540
+ if (sel) { await ab.click(sel); return true; }
541
+ await sleep(1000);
542
+ }
543
+ return false;
544
+ }
545
+
546
+ export async function visibleOptions(ab) {
547
+ return ab.eval(() => [...new Set([...document.querySelectorAll(
548
+ '.ui-browser-associative-dropdown-list-item, .ui-select-dropdown li, .ui-select-option, [class*=select-dropdown] li'
549
+ )].filter(e => e.getBoundingClientRect().width > 0).map(e => (e.innerText || '').trim()).filter(Boolean))]);
550
+ }
551
+
552
+ export async function activeTag(ab) {
553
+ return ab.eval(() => document.activeElement?.tagName || 'none');
554
+ }
555
+
556
+ /** 在「Excel 渲染表格」里按表头定位单元格,打标后返回 CSS 选择器。 */
557
+ export async function gridLocate(ab, { marker, colName, row }) {
558
+ return ab.eval(({ marker, colName, row }) => {
559
+ const tbl = [...document.querySelectorAll('table.excelTableView-content-excel-table')]
560
+ .find(t => [...t.querySelectorAll('td.excelTableView-th')].some(td => (td.innerText || '').trim() === marker));
561
+ if (!tbl) return { err: '找不到表格 ' + marker };
562
+ const th = [...tbl.querySelectorAll('td.excelTableView-th')]
563
+ .find(td => (td.innerText || '').trim() === colName);
564
+ const mm = (th?.className || '').match(/cell_[0-9a-f]+_\d+_(\d+)/);
565
+ if (!mm) return { err: '找不到列 ' + colName };
566
+ const col = Number(mm[1]);
567
+ const rows = [...tbl.querySelectorAll('tr')].filter(tr => {
568
+ const td = [...tr.children].find(x => String(x.className || '').trim().endsWith('_' + col));
569
+ return td && [...td.querySelectorAll('input')].some(i => i.getBoundingClientRect().width > 0);
570
+ });
571
+ if (row >= rows.length) return { err: `行 ${row} 超出 ${rows.length}` };
572
+ const td = [...rows[row].children].find(x => String(x.className || '').trim().endsWith('_' + col));
573
+ const inp = [...td.querySelectorAll('input')].find(i => i.getBoundingClientRect().width > 0);
574
+ if (!inp) return { err: '该单元格没有可见 input' };
575
+ document.querySelectorAll('[data-ab-target]').forEach(e => e.removeAttribute('data-ab-target'));
576
+ inp.setAttribute('data-ab-target', 'cell');
577
+ return { sel: '[data-ab-target="cell"]', before: inp.value, rows: rows.length };
578
+ }, { marker, colName, row });
579
+ }
580
+
581
+ export async function gridRowCount(ab, { marker, colName }) {
582
+ const r = await gridLocate(ab, { marker, colName, row: 0 });
583
+ return r.rows ?? -1;
584
+ }
585
+
586
+ export async function gridFill(ab, opt, value, what, log = () => {}) {
587
+ const loc = await gridLocate(ab, opt);
588
+ if (loc.err) { log(`${what} 定位失败`, loc.err); return null; }
589
+ try { await ab.fill(loc.sel, String(value)); } catch (e) { log(`${what} fill 失败`, e.message.slice(0, 120)); return null; }
590
+ await ab.press('Tab').catch(() => {});
591
+ await sleep(1200);
592
+ const back = (await gridLocate(ab, opt)).before ?? '?';
593
+ log(`${what} 写入 ${value} → 回读 ${back}`);
594
+ return back;
595
+ }
596
+
597
+ /** 在「Excel 渲染表格」里点一行单元格,用于下拉/关联选择控件。 */
598
+ export async function gridClick(ab, opt) {
599
+ const loc = await gridLocate(ab, opt);
600
+ if (loc.err) return false;
601
+ await ab.click(loc.sel);
602
+ return true;
603
+ }
604
+
605
+ export async function gridCols(ab, marker) {
606
+ return ab.eval(m => {
607
+ const tbl = [...document.querySelectorAll('table.excelTableView-content-excel-table')]
608
+ .find(t => [...t.querySelectorAll('td.excelTableView-th')].some(td => (td.innerText || '').trim() === m));
609
+ if (!tbl) return null;
610
+ const o = {};
611
+ [...tbl.querySelectorAll('td.excelTableView-th')].forEach(td => {
612
+ const t = (td.innerText || '').trim();
613
+ const mm = (td.className || '').match(/cell_[0-9a-f]+_\d+_(\d+)/);
614
+ if (t && mm) o[t] = Number(mm[1]);
615
+ });
616
+ return o;
617
+ }, marker);
618
+ }
619
+
620
+ export async function addGridRow(ab, sectionName) {
621
+ const sel = await ab.eval(sec => {
622
+ const headers = [...document.querySelectorAll('*')]
623
+ .filter(e => e.children.length === 0 && (e.textContent || '').trim() === sec && e.getBoundingClientRect().width > 0)
624
+ .map(e => e.getBoundingClientRect());
625
+ if (!headers.length) return null;
626
+ const btns = [...document.querySelectorAll('.weapp-form-detail-table__action-btn[title="添加"]')]
627
+ .filter(x => x.getBoundingClientRect().width > 0);
628
+ let best = null;
629
+ btns.forEach(x => {
630
+ const br = x.getBoundingClientRect();
631
+ headers.forEach(h => {
632
+ const d = Math.abs(br.y - h.y);
633
+ if (!best || d < best.d) best = { d, x };
634
+ });
635
+ });
636
+ if (!best) return null;
637
+ best.x.scrollIntoView({ block: 'center' });
638
+ document.querySelectorAll('[data-ab-target]').forEach(e => e.removeAttribute('data-ab-target'));
639
+ best.x.setAttribute('data-ab-target', 'add-row');
640
+ return '[data-ab-target="add-row"]';
641
+ }, sectionName);
642
+ if (!sel) return false;
643
+ await ab.click(sel);
644
+ return true;
645
+ }
646
+
647
+ /**
648
+ * 在待办流程里批准指定报价单。
649
+ * 判据与 lib/approve.mjs 一致:待办里出现任务 → 审批页「批准」可见且 body 含单号 →
650
+ * 点批准后等「确定」→ 点确定 → 审批页自动关闭才算成功。
651
+ */
652
+ export async function approveQuote(quoteNo, {
653
+ approver = 'qiujiahui',
654
+ state = authFile(approver),
655
+ session = `oms-approve-${Date.now()}`,
656
+ log = () => {},
657
+ timeout = 180000,
658
+ } = {}) {
659
+ if (!fs.existsSync(state)) {
660
+ throw new Error(`缺少审批人会话:${state}(先跑 node scripts/login-test-accounts.mjs ${approver})`);
661
+ }
662
+ const ab = new Ab(session, { state });
663
+ try {
664
+ await ab.close();
665
+ await ab.open(TODO_URL);
666
+ await until(ab, n => (document.body.innerText || '').includes(n), {
667
+ arg: quoteNo, timeout, label: '待办任务',
668
+ });
669
+ log('待办里找到审批任务');
670
+
671
+ const before = (await ab.tabs()).length;
672
+ const sel = await ab.eval(n => {
673
+ const el = [...document.querySelectorAll('*')]
674
+ .find(e => e.children.length === 0 && (e.innerText || '').trim() === `报价单审批 ${n}`);
675
+ if (!el) return null;
676
+ document.querySelectorAll('[data-ab-target]').forEach(e => e.removeAttribute('data-ab-target'));
677
+ el.setAttribute('data-ab-target', 'todo-open');
678
+ return '[data-ab-target="todo-open"]';
679
+ }, quoteNo);
680
+ if (!sel) return { approved: false, reason: '待办里找不到任务标题' };
681
+ await ab.click(sel);
682
+
683
+ let tabs = [];
684
+ const t1 = Date.now();
685
+ while (Date.now() - t1 < 60000) {
686
+ tabs = await ab.tabs();
687
+ if (tabs.length > before) break;
688
+ await sleep(1000);
689
+ }
690
+ if (tabs.length <= before) return { approved: false, reason: '点击审批任务后没有打开审批页' };
691
+ const tab = tabs.find(t => /workflow\/flowpage/.test(t.url || '')) || tabs[tabs.length - 1];
692
+ await ab.switchTab(tab.tabId || tab.targetId);
693
+ log('审批页已打开', String(tab.url || '').slice(-50));
694
+
695
+ await until(ab, n => {
696
+ const t = document.body.innerText || '';
697
+ const hasBtn = [...document.querySelectorAll('button')]
698
+ .some(b => b.offsetParent !== null && /^\s*批准\s*$/.test((b.innerText || '').trim()));
699
+ return hasBtn && t.includes(n) && window.frames.length >= 1 ? { len: t.length, frames: window.frames.length } : null;
700
+ }, { arg: quoteNo, timeout: 150000, interval: 1500, label: '审批页内容与 iframe' }).catch(() => null);
701
+ if (!await ab.eval(() => [...document.querySelectorAll('button')]
702
+ .some(b => b.offsetParent !== null && /^\s*批准\s*$/.test((b.innerText || '').trim())))) {
703
+ return { approved: false, reason: '审批页没有出现「批准」按钮' };
704
+ }
705
+ log('审批页内容已就绪');
706
+
707
+ const clicked = await ab.eval(() => {
708
+ const docs = [document, ...[...document.querySelectorAll('iframe')]
709
+ .map(f => { try { return f.contentDocument; } catch { return null; } })
710
+ .filter(Boolean)];
711
+ for (const d of docs) {
712
+ const b = [...d.querySelectorAll('button')]
713
+ .find(x => x.offsetParent !== null && (x.innerText || '').trim() === '批准');
714
+ if (b) { b.click(); return true; }
715
+ }
716
+ return false;
717
+ });
718
+ if (!clicked) return { approved: false, reason: '所有 frame 里都没点到「批准」' };
719
+ log('「批准」已点中');
720
+
721
+ let hasConfirm = false;
722
+ const t2 = Date.now();
723
+ while (Date.now() - t2 < 90000) {
724
+ hasConfirm = await ab.eval(() => [...document.querySelectorAll('button')]
725
+ .some(b => b.offsetParent !== null && /^(确定|确认|确认提交)$/.test((b.innerText || '').trim())));
726
+ if (hasConfirm) break;
727
+ await sleep(500);
728
+ }
729
+ if (!hasConfirm) return { approved: false, reason: '点「批准」后 90 秒内没等到「确定」二次确认按钮' };
730
+
731
+ const okClick = await ab.eval(() => {
732
+ const pool = [...document.querySelectorAll('.ui-dialog-footer button, .ui-dialog-footer a, button')]
733
+ .filter(x => x.getBoundingClientRect().width > 0 && /^\s*确定\s*$/.test((x.innerText || '').trim()));
734
+ const b = pool[pool.length - 1];
735
+ if (!b) return false;
736
+ b.click();
737
+ return true;
738
+ });
739
+ if (!okClick) return { approved: false, reason: '没点到弹窗底部「确定」' };
740
+ log('已点「确定」');
741
+
742
+ let closed = false;
743
+ const t3 = Date.now();
744
+ while (Date.now() - t3 < 45000) {
745
+ const now = await ab.tabs();
746
+ if (!now.some(t => (t.tabId || t.targetId) === (tab.tabId || tab.targetId))) { closed = true; break; }
747
+ await sleep(1000);
748
+ }
749
+ if (!closed) return { approved: false, reason: '点了「确定」但审批页 45 秒内没有关闭,流程可能未提交', uncertain: true };
750
+ log('审批页已自动关闭,审批完成');
751
+ return { approved: true };
752
+ } finally {
753
+ await ab.close().catch(() => {});
754
+ }
755
+ }
756
+
757
+ export function argv(k, d = null) {
758
+ const hit = process.argv.find(a => a.startsWith(`--${k}=`));
759
+ return hit ? hit.split('=').slice(1).join('=') : d;
760
+ }