EnergyVenom commited on
Commit
bb808ef
·
verified ·
1 Parent(s): fd68ff8

Astra: Fusion 26D invoice lines, flows that find their document again, runner versioning (4dc9e04)

Browse files
automation/remote_runner/server.py CHANGED
@@ -1,373 +1,382 @@
1
- """Patchwise remote browser runner: runs one Playwright attempt at a time for a Patchwise server that cannot drive a
2
- browser itself (for example a host whose network Oracle's edge refuses). Standard library only; Python 3.10+.
3
-
4
- The Patchwise server posts an attempt (case ids, config, the run's environment, any AI-written or library specs),
5
- polls it, then downloads one zip: the Playwright JSON report (attachment paths relative to the run directory), the
6
- run directory (screenshots, videos, traces), the pod values tried and the ledger of created test records.
7
-
8
- Security: every call needs `Authorization: Bearer <RUNNER_TOKEN>` (compared in constant time). Only known environment
9
- keys and the Patchwise Playwright configs are accepted; spec names are plain file names. The Fusion password exists
10
- only in the Playwright process's environment, never on disk. Put it behind HTTPS (deploy/remote-runner/Caddyfile).
11
-
12
- Environment: RUNNER_TOKEN (required), RUNNER_PORT (default 8899), RUNNER_HOME (default ~/runner-data),
13
- AUTOMATION_DIR (default: ../ of this file), RUNNER_KEEP_HOURS (default 24)."""
14
- from __future__ import annotations
15
-
16
- import base64
17
- import hmac
18
- import io
19
- import json
20
- import os
21
- import re
22
- import secrets
23
- import shutil
24
- import signal
25
- import subprocess
26
- import threading
27
- import time
28
- import zipfile
29
- from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
30
- from pathlib import Path
31
-
32
- TOKEN = os.environ.get("RUNNER_TOKEN", "")
33
- PORT = int(os.environ.get("RUNNER_PORT", "8899"))
34
- HOME = Path(os.environ.get("RUNNER_HOME", str(Path.home() / "runner-data")))
35
- AUTOMATION = Path(os.environ.get("AUTOMATION_DIR", str(Path(__file__).resolve().parents[1])))
36
- KEEP_S = float(os.environ.get("RUNNER_KEEP_HOURS", "24")) * 3600
37
- CONFIGS = {"playwright.fusion.config.ts", "playwright.agent.config.ts"}
38
- ENV_KEYS = {"FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES",
39
- "FPT_FUSION_WORKERS", "PW_LOCATOR_OVERRIDES", "FPT_BROWSER_SLOWMO_MS"}
40
- SPEC = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.spec\.ts$")
41
- ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,80}$")
42
- MAX_BODY = 20_000_000
43
- # each attempt in its own process group, so a cancel stops it and every browser it started (Linux and Windows)
44
- GROUP = {"start_new_session": True} if os.name == "posix" else {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
45
- LOCK = threading.Lock() # one attempt at a time: the runner is sized for one browser
46
- JOBS: dict[str, dict] = {}
47
-
48
-
49
- def grep_for(ids: list[str]) -> str:
50
- return "|".join(re.escape(i) for i in ids)
51
-
52
-
53
- def _progress(log: Path) -> dict:
54
- try:
55
- b = log.read_bytes()[-20000:]
56
- except OSError:
57
- return {}
58
- m = list(re.finditer(rb"\[(\d+)/(\d+)\]", b))
59
- return {"done": int(m[-1].group(1)), "total": int(m[-1].group(2))} if m else {}
60
-
61
-
62
- def _relativize(report: Path, run_dir: Path) -> None:
63
- """Attachment paths in the report become relative to the run directory (the server maps them to its own)."""
64
- data = json.loads(report.read_text(encoding="utf-8"))
65
-
66
- def walk(suites):
67
- for s in suites or []:
68
- for sp in s.get("specs") or []:
69
- for t in sp.get("tests") or []:
70
- for r in t.get("results") or []:
71
- for a in r.get("attachments") or []:
72
- p = a.get("path")
73
- if p:
74
- try:
75
- a["path"] = str(Path(p).resolve().relative_to(run_dir.resolve())).replace("\\", "/")
76
- except ValueError:
77
- a["path"] = None # outside the run directory: not shipped
78
- walk(s.get("suites"))
79
- walk(data.get("suites"))
80
- report.write_text(json.dumps(data), encoding="utf-8")
81
-
82
-
83
- YAML_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,80}\.yaml$")
84
- _IMPORT_SRC = re.compile(r"""(from\s+)(["'])[^"'\n]*?/automation/src/""")
85
- _STEPS_DIR = re.compile(r"""(dir:\s*)"(?:[^"\\\n]|\\.)*\"""")
86
-
87
-
88
- def local_spec(text: str, steps_dir: Path) -> str:
89
- """A spec written on the Patchwise server, made runnable here: its imports of the server's automation/src point to
90
- this runner's, and a steps scenario reads its YAML from the job's steps folder."""
91
- text = _IMPORT_SRC.sub(lambda m: f"{m.group(1)}{m.group(2)}{(AUTOMATION / 'src').as_posix()}/", text)
92
- return _STEPS_DIR.sub(lambda m: m.group(1) + json.dumps(steps_dir.as_posix()), text)
93
-
94
-
95
- def start(body: dict) -> dict:
96
- ids = [str(i) for i in body.get("ids") or []]
97
- if not ids or not all(ID.match(i) for i in ids):
98
- raise ValueError("ids: case ids such as AP-FUS-001")
99
- pw_run_id = str(body.get("pw_run_id") or "")
100
- if not ID.match(pw_run_id):
101
- raise ValueError("pw_run_id is missing or not a plain id")
102
- config = str(body.get("config") or "playwright.fusion.config.ts")
103
- if config not in CONFIGS:
104
- raise ValueError(f"config is one of {sorted(CONFIGS)}")
105
- env_in = {k: str(v) for k, v in (body.get("env") or {}).items() if k in ENV_KEYS}
106
- if not LOCK.acquire(blocking=False):
107
- raise BlockingIOError("another attempt is running on this runner")
108
- try:
109
- jid = "job_" + secrets.token_hex(6)
110
- jd = HOME / jid
111
- (jd / "drafts").mkdir(parents=True)
112
- (jd / "library").mkdir()
113
- (jd / "steps").mkdir()
114
- for name, text in (body.get("steps") or {}).items(): # the steps scenarios' YAML (the server's copy is not here)
115
- if not YAML_NAME.match(name):
116
- raise ValueError(f"steps: {name!r} is not a scenario file name")
117
- (jd / "steps" / name).write_text(str(text), encoding="utf-8")
118
- for kind in ("drafts", "library"):
119
- for name, text in (body.get(kind) or {}).items():
120
- if not SPEC.match(name):
121
- raise ValueError(f"{kind}: {name!r} is not a spec file name")
122
- (jd / kind / name).write_text(local_spec(str(text), jd / "steps"), encoding="utf-8")
123
- report = jd / "report.json"
124
- env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN",)}
125
- env.update(env_in)
126
- env.update({"PLAYWRIGHT_MODE": "live", "PW_RETRIES": "0", "PW_RUN_ID": pw_run_id, "PLAYWRIGHT_JSON_OUTPUT_NAME": str(report),
127
- "FPT_TESTDATA_USED": str(jd / "testdata-used.jsonl"), "FPT_CREATED_FILE": str(jd / "created.jsonl")})
128
- live = body.get("live") or {}
129
- for k in ("FPT_LIVE_VIEW_DIR", "FPT_LIVE_VIEW_ATTEMPT", "FPT_LIVE_VIEW_CHUNK"):
130
- env.pop(k, None)
131
- if live and ID.match(str(live.get("attempt") or "")): # live view: the browser hook drops its latest frame here
132
- (jd / "live").mkdir()
133
- env.update({"FPT_LIVE_VIEW_DIR": str(jd / "live"), "FPT_LIVE_VIEW_ATTEMPT": str(live["attempt"]), "FPT_LIVE_VIEW_CHUNK": "0"})
134
- for kind in ("drafts", "library"):
135
- key = "FPT_DRAFTS_DIR" if kind == "drafts" else "FPT_LIBRARY_DIR"
136
- if any((jd / kind).glob("*.spec.ts")):
137
- env[key] = str(jd / kind)
138
- else:
139
- env.pop(key, None)
140
- cmd = ["node", str(AUTOMATION / "node_modules" / "@playwright" / "test" / "cli.js"), "test", "--config", config,
141
- "--retries=0", "--reporter=json", "--grep", grep_for(ids)]
142
- log = open(jd / "playwright.log", "wb")
143
- p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **GROUP)
144
- job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": pw_run_id, "started": time.time(),
145
- "deadline": time.time() + min(float(body.get("timeout_s") or 3600), 4 * 3600), "state": "running", "exit_code": None}
146
- JOBS[jid] = job
147
- threading.Thread(target=_watch, args=(job,), daemon=True).start()
148
- return {"id": jid, "state": "running"}
149
- except BaseException:
150
- LOCK.release()
151
- raise
152
-
153
-
154
- SCREEN_SCRIPTS = {"explore": "scripts/explore-fusion.ts", "capture": "scripts/capture-fusion.ts"}
155
- SCREEN_ENV = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA")
156
- TASK = re.compile(r"^[^\r\n<>]{5,250}$")
157
- OUT_FILE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,160}\.(json|values)$")
158
-
159
-
160
- def start_screens(body: dict) -> dict:
161
- """Read a pod's screens (labels only): "explore" with a plan of areas, or "capture" of one "Area > Page > Task".
162
- Same lock as the attempts (one browser); the files land in the job's out/ folder and come back in the bundle."""
163
- kind = str(body.get("kind") or "")
164
- if kind not in SCREEN_SCRIPTS:
165
- raise ValueError(f"kind is one of {sorted(SCREEN_SCRIPTS)}")
166
- env_in = {k: str(v) for k, v in (body.get("env") or {}).items() if k in SCREEN_ENV}
167
- if not all(env_in.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):
168
- raise ValueError("env needs FUSION_BASE_URL, FUSION_USERNAME and FUSION_PASSWORD")
169
- task = str(body.get("task") or "")
170
- if kind == "capture" and not TASK.match(task):
171
- raise ValueError('task is "Area > Page > Task"')
172
- if kind == "explore" and not isinstance(body.get("plan"), dict):
173
- raise ValueError("plan is the explorer's plan (an object)")
174
- if not LOCK.acquire(blocking=False):
175
- raise BlockingIOError("another attempt is running on this runner")
176
- try:
177
- jid = "job_" + secrets.token_hex(6)
178
- jd = HOME / jid
179
- (jd / "out").mkdir(parents=True)
180
- arg = task
181
- if kind == "explore":
182
- (jd / "plan.json").write_text(json.dumps(body["plan"]), encoding="utf-8")
183
- arg = str(jd / "plan.json")
184
- env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN",)}
185
- env.update(env_in)
186
- cmd = ["node", str(AUTOMATION / "node_modules" / "tsx" / "dist" / "cli.mjs"), SCREEN_SCRIPTS[kind], arg, "--out-dir", str(jd / "out")]
187
- log = open(jd / "playwright.log", "wb")
188
- p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **GROUP)
189
- job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": jid, "started": time.time(), "kind": kind,
190
- "deadline": time.time() + min(float(body.get("timeout_s") or 5400), 4 * 3600), "state": "running", "exit_code": None}
191
- JOBS[jid] = job
192
- threading.Thread(target=_watch, args=(job,), daemon=True).start()
193
- return {"id": jid, "state": "running"}
194
- except BaseException:
195
- LOCK.release()
196
- raise
197
-
198
-
199
- def live_now(job: dict) -> dict:
200
- """The live view of a running attempt: the latest frame and the failed scenario's last frame (JPEG, base64) and the
201
- hook's status. The hook never writes a sign-in screen (it masks pages with a password field)."""
202
- d = job["dir"] / "live"
203
- out: dict = {"status": None, "frame": None, "failed": None, "frame_at": None}
204
- if not d.is_dir():
205
- return out
206
- try:
207
- out["status"] = json.loads((d / "status.json").read_text(encoding="utf-8"))
208
- except (OSError, ValueError):
209
- pass
210
- for key, name in (("frame", "frame.jpg"), ("failed", "failed.jpg")):
211
- f = d / name
212
- try:
213
- if key == "frame":
214
- out["frame_at"] = f.stat().st_mtime
215
- out[key] = base64.b64encode(f.read_bytes()).decode()
216
- except OSError:
217
- pass
218
- return out
219
-
220
-
221
- def _lines(log: Path, since: int) -> tuple[list[str], int]:
222
- """The log's lines from `since` on (at most 200), and how many lines it has."""
223
- try:
224
- lines = log.read_text(encoding="utf-8", errors="replace").splitlines()
225
- except OSError:
226
- return [], 0
227
- return [ln[:500] for ln in lines[since:since + 200]], len(lines)
228
-
229
-
230
- def _kill_tree(p: subprocess.Popen) -> None:
231
- """Stop the attempt and every browser it started (a process group on Linux, a process tree on Windows)."""
232
- try:
233
- if os.name == "posix":
234
- os.killpg(p.pid, signal.SIGKILL)
235
- else:
236
- subprocess.run(["taskkill", "/PID", str(p.pid), "/T", "/F"], capture_output=True, timeout=30)
237
- except (OSError, subprocess.SubprocessError):
238
- pass
239
-
240
-
241
- def _watch(job: dict) -> None:
242
- p = job["proc"]
243
- try:
244
- while p.poll() is None:
245
- if time.time() > job["deadline"] or job.get("cancel"):
246
- job["timed_out"] = not job.get("cancel")
247
- _kill_tree(p)
248
- time.sleep(2)
249
- job["exit_code"] = p.returncode
250
- job["log"].close()
251
- run_dir = AUTOMATION / "results" / "runs" / job["pw_run_id"]
252
- report = job["dir"] / "report.json"
253
- if report.exists():
254
- _relativize(report, run_dir)
255
- if run_dir.exists(): # the run's evidence moves into the job (so the automation folder never piles up)
256
- shutil.move(str(run_dir), str(job["dir"] / "run"))
257
- job["state"] = "cancelled" if job.get("cancel") else "done"
258
- finally:
259
- LOCK.release()
260
-
261
-
262
- def bundle(job: dict) -> bytes:
263
- buf = io.BytesIO()
264
- with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
265
- for name in ("report.json", "testdata-used.jsonl", "created.jsonl", "playwright.log"):
266
- f = job["dir"] / name
267
- if f.exists():
268
- z.write(f, name)
269
- out = job["dir"] / "out" # a screen read: the inventories (labels) and the list choices it found
270
- if out.exists():
271
- for f in out.iterdir():
272
- if f.is_file() and OUT_FILE.match(f.name):
273
- z.write(f, "out/" + f.name)
274
- run = job["dir"] / "run"
275
- if run.exists():
276
- for f in run.rglob("*"):
277
- if f.is_file() and f.name != ".fusion-session.json": # never ship the session cookies
278
- z.write(f, "run/" + str(f.relative_to(run)).replace("\\", "/"))
279
- return buf.getvalue()
280
-
281
-
282
- def sweep() -> None:
283
- while True:
284
- cut = time.time() - KEEP_S
285
- for jid, job in list(JOBS.items()):
286
- if job["state"] != "running" and job["started"] < cut:
287
- shutil.rmtree(job["dir"], ignore_errors=True)
288
- JOBS.pop(jid, None)
289
- time.sleep(600)
290
-
291
-
292
- class H(BaseHTTPRequestHandler):
293
- server_version = "PatchwiseRunner/1"
294
-
295
- def log_message(self, fmt, *args): # one quiet line per call, never a header or a body
296
- print(time.strftime("%H:%M:%S"), self.command, self.path.split("?")[0], args[1] if len(args) > 1 else "", flush=True)
297
-
298
- def _send(self, code: int, obj=None, raw: bytes | None = None, ctype="application/json"):
299
- b = raw if raw is not None else json.dumps(obj).encode()
300
- self.send_response(code)
301
- self.send_header("Content-Type", ctype)
302
- self.send_header("Content-Length", str(len(b)))
303
- self.send_header("Cache-Control", "no-store")
304
- self.end_headers()
305
- self.wfile.write(b)
306
-
307
- def _auth(self) -> bool:
308
- h = self.headers.get("Authorization", "")
309
- ok = bool(TOKEN) and h.startswith("Bearer ") and hmac.compare_digest(h[7:].strip(), TOKEN)
310
- if not ok:
311
- self._send(401, {"error": "a valid runner token is needed"})
312
- return ok
313
-
314
- def _job(self, jid: str):
315
- job = JOBS.get(jid)
316
- if not job:
317
- self._send(404, {"error": "no such attempt"})
318
- return job
319
-
320
- def do_GET(self):
321
- if self.path == "/healthz":
322
- return self._send(200, {"ok": bool(TOKEN), "busy": LOCK.locked(), "automation": AUTOMATION.exists()})
323
- if not self._auth():
324
- return
325
- m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})(/bundle|/live)?(?:\?since=(\d{1,7}))?", self.path)
326
- if not m:
327
- return self._send(404, {"error": "not found"})
328
- job = self._job(m.group(1))
329
- if not job:
330
- return
331
- if m.group(2) == "/live":
332
- return self._send(200, live_now(job) if job["state"] == "running" else {"status": None, "frame": None, "failed": None, "frame_at": None})
333
- if m.group(2):
334
- if job["state"] == "running":
335
- return self._send(409, {"error": "the attempt is still running"})
336
- return self._send(200, raw=bundle(job), ctype="application/zip")
337
- st = {"id": job["id"], "state": job["state"], "exit_code": job["exit_code"], "timed_out": bool(job.get("timed_out")),
338
- "progress": _progress(job["dir"] / "playwright.log"), "report": (job["dir"] / "report.json").exists()}
339
- if m.group(3) is not None: # a screen read follows its log lines ("[explore] ...") for its progress
340
- st["lines"], st["line_count"] = _lines(job["dir"] / "playwright.log", int(m.group(3)))
341
- self._send(200, st)
342
-
343
- def do_POST(self):
344
- if not self._auth():
345
- return
346
- n = int(self.headers.get("Content-Length") or 0)
347
- if n > MAX_BODY:
348
- return self._send(413, {"error": "body too large"})
349
- if self.path in ("/v1/attempts", "/v1/screens"):
350
- try:
351
- body = json.loads(self.rfile.read(n) or b"{}")
352
- return self._send(202, start(body) if self.path == "/v1/attempts" else start_screens(body))
353
- except BlockingIOError as e:
354
- return self._send(409, {"error": str(e)})
355
- except (ValueError, TypeError) as e:
356
- return self._send(400, {"error": str(e)})
357
- m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})/cancel", self.path)
358
- if m:
359
- job = self._job(m.group(1))
360
- if job:
361
- job["cancel"] = True
362
- self._send(202, {"id": job["id"], "state": "cancelling"})
363
- return
364
- self._send(404, {"error": "not found"})
365
-
366
-
367
- if __name__ == "__main__":
368
- if not TOKEN or len(TOKEN) < 24:
369
- raise SystemExit("set RUNNER_TOKEN (at least 24 characters)")
370
- HOME.mkdir(parents=True, exist_ok=True)
371
- threading.Thread(target=sweep, daemon=True).start()
372
- print(f"Patchwise remote runner on 127.0.0.1:{PORT}, automation {AUTOMATION}", flush=True)
373
- ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
 
 
 
 
 
 
 
 
 
 
1
+ """Patchwise remote browser runner: runs one Playwright attempt at a time for a Patchwise server that cannot drive a
2
+ browser itself (for example a host whose network Oracle's edge refuses). Standard library only; Python 3.10+.
3
+
4
+ The Patchwise server posts an attempt (case ids, config, the run's environment, any AI-written or library specs),
5
+ polls it, then downloads one zip: the Playwright JSON report (attachment paths relative to the run directory), the
6
+ run directory (screenshots, videos, traces), the pod values tried and the ledger of created test records.
7
+
8
+ Security: every call needs `Authorization: Bearer <RUNNER_TOKEN>` (compared in constant time). Only known environment
9
+ keys and the Patchwise Playwright configs are accepted; spec names are plain file names. The Fusion password exists
10
+ only in the Playwright process's environment, never on disk. Put it behind HTTPS (deploy/remote-runner/Caddyfile).
11
+
12
+ Environment: RUNNER_TOKEN (required), RUNNER_PORT (default 8899), RUNNER_HOME (default ~/runner-data),
13
+ AUTOMATION_DIR (default: ../ of this file), RUNNER_KEEP_HOURS (default 24)."""
14
+ from __future__ import annotations
15
+
16
+ import base64
17
+ import hmac
18
+ import io
19
+ import json
20
+ import os
21
+ import re
22
+ import secrets
23
+ import shutil
24
+ import signal
25
+ import subprocess
26
+ import threading
27
+ import time
28
+ import zipfile
29
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
30
+ from pathlib import Path
31
+
32
+ TOKEN = os.environ.get("RUNNER_TOKEN", "")
33
+ PORT = int(os.environ.get("RUNNER_PORT", "8899"))
34
+ HOME = Path(os.environ.get("RUNNER_HOME", str(Path.home() / "runner-data")))
35
+ AUTOMATION = Path(os.environ.get("AUTOMATION_DIR", str(Path(__file__).resolve().parents[1])))
36
+ KEEP_S = float(os.environ.get("RUNNER_KEEP_HOURS", "24")) * 3600
37
+ # the scenario files the repo's own step specs read (../tests/cases), and the commit deploy/runner/sync.sh installed
38
+ CASES = AUTOMATION.parent / "tests" / "cases"
39
+ VERSION_FILE = AUTOMATION.parent / "VERSION"
40
+ CONFIGS = {"playwright.fusion.config.ts", "playwright.agent.config.ts"}
41
+ ENV_KEYS = {"FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES",
42
+ "FPT_FUSION_WORKERS", "PW_LOCATOR_OVERRIDES", "FPT_BROWSER_SLOWMO_MS"}
43
+ SPEC = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.spec\.ts$")
44
+ ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,80}$")
45
+ MAX_BODY = 20_000_000
46
+ # each attempt in its own process group, so a cancel stops it and every browser it started (Linux and Windows)
47
+ GROUP = {"start_new_session": True} if os.name == "posix" else {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
48
+ LOCK = threading.Lock() # one attempt at a time: the runner is sized for one browser
49
+ JOBS: dict[str, dict] = {}
50
+
51
+
52
+ def grep_for(ids: list[str]) -> str:
53
+ return "|".join(re.escape(i) for i in ids)
54
+
55
+
56
+ def _progress(log: Path) -> dict:
57
+ try:
58
+ b = log.read_bytes()[-20000:]
59
+ except OSError:
60
+ return {}
61
+ m = list(re.finditer(rb"\[(\d+)/(\d+)\]", b))
62
+ return {"done": int(m[-1].group(1)), "total": int(m[-1].group(2))} if m else {}
63
+
64
+
65
+ def _relativize(report: Path, run_dir: Path) -> None:
66
+ """Attachment paths in the report become relative to the run directory (the server maps them to its own)."""
67
+ data = json.loads(report.read_text(encoding="utf-8"))
68
+
69
+ def walk(suites):
70
+ for s in suites or []:
71
+ for sp in s.get("specs") or []:
72
+ for t in sp.get("tests") or []:
73
+ for r in t.get("results") or []:
74
+ for a in r.get("attachments") or []:
75
+ p = a.get("path")
76
+ if p:
77
+ try:
78
+ a["path"] = str(Path(p).resolve().relative_to(run_dir.resolve())).replace("\\", "/")
79
+ except ValueError:
80
+ a["path"] = None # outside the run directory: not shipped
81
+ walk(s.get("suites"))
82
+ walk(data.get("suites"))
83
+ report.write_text(json.dumps(data), encoding="utf-8")
84
+
85
+
86
+ YAML_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,80}\.yaml$")
87
+ _IMPORT_SRC = re.compile(r"""(from\s+)(["'])[^"'\n]*?/automation/src/""")
88
+ _STEPS_DIR = re.compile(r"""(dir:\s*)"(?:[^"\\\n]|\\.)*\"""")
89
+
90
+
91
+ def local_spec(text: str, steps_dir: Path) -> str:
92
+ """A spec written on the Patchwise server, made runnable here: its imports of the server's automation/src point to
93
+ this runner's, and a steps scenario reads its YAML from the job's steps folder."""
94
+ text = _IMPORT_SRC.sub(lambda m: f"{m.group(1)}{m.group(2)}{(AUTOMATION / 'src').as_posix()}/", text)
95
+ return _STEPS_DIR.sub(lambda m: m.group(1) + json.dumps(steps_dir.as_posix()), text)
96
+
97
+
98
+ def start(body: dict) -> dict:
99
+ ids = [str(i) for i in body.get("ids") or []]
100
+ if not ids or not all(ID.match(i) for i in ids):
101
+ raise ValueError("ids: case ids such as AP-FUS-001")
102
+ pw_run_id = str(body.get("pw_run_id") or "")
103
+ if not ID.match(pw_run_id):
104
+ raise ValueError("pw_run_id is missing or not a plain id")
105
+ config = str(body.get("config") or "playwright.fusion.config.ts")
106
+ if config not in CONFIGS:
107
+ raise ValueError(f"config is one of {sorted(CONFIGS)}")
108
+ env_in = {k: str(v) for k, v in (body.get("env") or {}).items() if k in ENV_KEYS}
109
+ if not LOCK.acquire(blocking=False):
110
+ raise BlockingIOError("another attempt is running on this runner")
111
+ try:
112
+ jid = "job_" + secrets.token_hex(6)
113
+ jd = HOME / jid
114
+ (jd / "drafts").mkdir(parents=True)
115
+ (jd / "library").mkdir()
116
+ (jd / "steps").mkdir()
117
+ for name, text in (body.get("steps") or {}).items(): # the steps scenarios' YAML (the server's copy is not here)
118
+ if not YAML_NAME.match(name):
119
+ raise ValueError(f"steps: {name!r} is not a scenario file name")
120
+ (jd / "steps" / name).write_text(str(text), encoding="utf-8")
121
+ for kind in ("drafts", "library"):
122
+ for name, text in (body.get(kind) or {}).items():
123
+ if not SPEC.match(name):
124
+ raise ValueError(f"{kind}: {name!r} is not a spec file name")
125
+ (jd / kind / name).write_text(local_spec(str(text), jd / "steps"), encoding="utf-8")
126
+ report = jd / "report.json"
127
+ env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN",)}
128
+ env.update(env_in)
129
+ env.update({"PLAYWRIGHT_MODE": "live", "PW_RETRIES": "0", "PW_RUN_ID": pw_run_id, "PLAYWRIGHT_JSON_OUTPUT_NAME": str(report),
130
+ "FPT_TESTDATA_USED": str(jd / "testdata-used.jsonl"), "FPT_CREATED_FILE": str(jd / "created.jsonl")})
131
+ live = body.get("live") or {}
132
+ for k in ("FPT_LIVE_VIEW_DIR", "FPT_LIVE_VIEW_ATTEMPT", "FPT_LIVE_VIEW_CHUNK"):
133
+ env.pop(k, None)
134
+ if live and ID.match(str(live.get("attempt") or "")): # live view: the browser hook drops its latest frame here
135
+ (jd / "live").mkdir()
136
+ env.update({"FPT_LIVE_VIEW_DIR": str(jd / "live"), "FPT_LIVE_VIEW_ATTEMPT": str(live["attempt"]), "FPT_LIVE_VIEW_CHUNK": "0"})
137
+ for kind in ("drafts", "library"):
138
+ key = "FPT_DRAFTS_DIR" if kind == "drafts" else "FPT_LIBRARY_DIR"
139
+ if any((jd / kind).glob("*.spec.ts")):
140
+ env[key] = str(jd / kind)
141
+ else:
142
+ env.pop(key, None)
143
+ cmd = ["node", str(AUTOMATION / "node_modules" / "@playwright" / "test" / "cli.js"), "test", "--config", config,
144
+ "--retries=0", "--reporter=json", "--grep", grep_for(ids)]
145
+ log = open(jd / "playwright.log", "wb")
146
+ p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **GROUP)
147
+ job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": pw_run_id, "started": time.time(),
148
+ "deadline": time.time() + min(float(body.get("timeout_s") or 3600), 4 * 3600), "state": "running", "exit_code": None}
149
+ JOBS[jid] = job
150
+ threading.Thread(target=_watch, args=(job,), daemon=True).start()
151
+ return {"id": jid, "state": "running"}
152
+ except BaseException:
153
+ LOCK.release()
154
+ raise
155
+
156
+
157
+ SCREEN_SCRIPTS = {"explore": "scripts/explore-fusion.ts", "capture": "scripts/capture-fusion.ts"}
158
+ SCREEN_ENV = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA")
159
+ TASK = re.compile(r"^[^\r\n<>]{5,250}$")
160
+ OUT_FILE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,160}\.(json|values)$")
161
+
162
+
163
+ def start_screens(body: dict) -> dict:
164
+ """Read a pod's screens (labels only): "explore" with a plan of areas, or "capture" of one "Area > Page > Task".
165
+ Same lock as the attempts (one browser); the files land in the job's out/ folder and come back in the bundle."""
166
+ kind = str(body.get("kind") or "")
167
+ if kind not in SCREEN_SCRIPTS:
168
+ raise ValueError(f"kind is one of {sorted(SCREEN_SCRIPTS)}")
169
+ env_in = {k: str(v) for k, v in (body.get("env") or {}).items() if k in SCREEN_ENV}
170
+ if not all(env_in.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):
171
+ raise ValueError("env needs FUSION_BASE_URL, FUSION_USERNAME and FUSION_PASSWORD")
172
+ task = str(body.get("task") or "")
173
+ if kind == "capture" and not TASK.match(task):
174
+ raise ValueError('task is "Area > Page > Task"')
175
+ if kind == "explore" and not isinstance(body.get("plan"), dict):
176
+ raise ValueError("plan is the explorer's plan (an object)")
177
+ if not LOCK.acquire(blocking=False):
178
+ raise BlockingIOError("another attempt is running on this runner")
179
+ try:
180
+ jid = "job_" + secrets.token_hex(6)
181
+ jd = HOME / jid
182
+ (jd / "out").mkdir(parents=True)
183
+ arg = task
184
+ if kind == "explore":
185
+ (jd / "plan.json").write_text(json.dumps(body["plan"]), encoding="utf-8")
186
+ arg = str(jd / "plan.json")
187
+ env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN",)}
188
+ env.update(env_in)
189
+ cmd = ["node", str(AUTOMATION / "node_modules" / "tsx" / "dist" / "cli.mjs"), SCREEN_SCRIPTS[kind], arg, "--out-dir", str(jd / "out")]
190
+ log = open(jd / "playwright.log", "wb")
191
+ p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **GROUP)
192
+ job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": jid, "started": time.time(), "kind": kind,
193
+ "deadline": time.time() + min(float(body.get("timeout_s") or 5400), 4 * 3600), "state": "running", "exit_code": None}
194
+ JOBS[jid] = job
195
+ threading.Thread(target=_watch, args=(job,), daemon=True).start()
196
+ return {"id": jid, "state": "running"}
197
+ except BaseException:
198
+ LOCK.release()
199
+ raise
200
+
201
+
202
+ def live_now(job: dict) -> dict:
203
+ """The live view of a running attempt: the latest frame and the failed scenario's last frame (JPEG, base64) and the
204
+ hook's status. The hook never writes a sign-in screen (it masks pages with a password field)."""
205
+ d = job["dir"] / "live"
206
+ out: dict = {"status": None, "frame": None, "failed": None, "frame_at": None}
207
+ if not d.is_dir():
208
+ return out
209
+ try:
210
+ out["status"] = json.loads((d / "status.json").read_text(encoding="utf-8"))
211
+ except (OSError, ValueError):
212
+ pass
213
+ for key, name in (("frame", "frame.jpg"), ("failed", "failed.jpg")):
214
+ f = d / name
215
+ try:
216
+ if key == "frame":
217
+ out["frame_at"] = f.stat().st_mtime
218
+ out[key] = base64.b64encode(f.read_bytes()).decode()
219
+ except OSError:
220
+ pass
221
+ return out
222
+
223
+
224
+ def _lines(log: Path, since: int) -> tuple[list[str], int]:
225
+ """The log's lines from `since` on (at most 200), and how many lines it has."""
226
+ try:
227
+ lines = log.read_text(encoding="utf-8", errors="replace").splitlines()
228
+ except OSError:
229
+ return [], 0
230
+ return [ln[:500] for ln in lines[since:since + 200]], len(lines)
231
+
232
+
233
+ def _kill_tree(p: subprocess.Popen) -> None:
234
+ """Stop the attempt and every browser it started (a process group on Linux, a process tree on Windows)."""
235
+ try:
236
+ if os.name == "posix":
237
+ os.killpg(p.pid, signal.SIGKILL)
238
+ else:
239
+ subprocess.run(["taskkill", "/PID", str(p.pid), "/T", "/F"], capture_output=True, timeout=30)
240
+ except (OSError, subprocess.SubprocessError):
241
+ pass
242
+
243
+
244
+ def _watch(job: dict) -> None:
245
+ p = job["proc"]
246
+ try:
247
+ while p.poll() is None:
248
+ if time.time() > job["deadline"] or job.get("cancel"):
249
+ job["timed_out"] = not job.get("cancel")
250
+ _kill_tree(p)
251
+ time.sleep(2)
252
+ job["exit_code"] = p.returncode
253
+ job["log"].close()
254
+ run_dir = AUTOMATION / "results" / "runs" / job["pw_run_id"]
255
+ report = job["dir"] / "report.json"
256
+ if report.exists():
257
+ _relativize(report, run_dir)
258
+ if run_dir.exists(): # the run's evidence moves into the job (so the automation folder never piles up)
259
+ shutil.move(str(run_dir), str(job["dir"] / "run"))
260
+ job["state"] = "cancelled" if job.get("cancel") else "done"
261
+ finally:
262
+ LOCK.release()
263
+
264
+
265
+ def bundle(job: dict) -> bytes:
266
+ buf = io.BytesIO()
267
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
268
+ for name in ("report.json", "testdata-used.jsonl", "created.jsonl", "playwright.log"):
269
+ f = job["dir"] / name
270
+ if f.exists():
271
+ z.write(f, name)
272
+ out = job["dir"] / "out" # a screen read: the inventories (labels) and the list choices it found
273
+ if out.exists():
274
+ for f in out.iterdir():
275
+ if f.is_file() and OUT_FILE.match(f.name):
276
+ z.write(f, "out/" + f.name)
277
+ run = job["dir"] / "run"
278
+ if run.exists():
279
+ for f in run.rglob("*"):
280
+ if f.is_file() and f.name != ".fusion-session.json": # never ship the session cookies
281
+ z.write(f, "run/" + str(f.relative_to(run)).replace("\\", "/"))
282
+ return buf.getvalue()
283
+
284
+
285
+ def sweep() -> None:
286
+ while True:
287
+ cut = time.time() - KEEP_S
288
+ for jid, job in list(JOBS.items()):
289
+ if job["state"] != "running" and job["started"] < cut:
290
+ shutil.rmtree(job["dir"], ignore_errors=True)
291
+ JOBS.pop(jid, None)
292
+ # folders of jobs from before a restart are not in JOBS: their age on disk decides
293
+ for d in HOME.glob("job_*"):
294
+ if d.is_dir() and d.name not in JOBS and d.stat().st_mtime < cut:
295
+ shutil.rmtree(d, ignore_errors=True)
296
+ time.sleep(600)
297
+
298
+
299
+ class H(BaseHTTPRequestHandler):
300
+ server_version = "PatchwiseRunner/1"
301
+
302
+ def log_message(self, fmt, *args): # one quiet line per call, never a header or a body
303
+ print(time.strftime("%H:%M:%S"), self.command, self.path.split("?")[0], args[1] if len(args) > 1 else "", flush=True)
304
+
305
+ def _send(self, code: int, obj=None, raw: bytes | None = None, ctype="application/json"):
306
+ b = raw if raw is not None else json.dumps(obj).encode()
307
+ self.send_response(code)
308
+ self.send_header("Content-Type", ctype)
309
+ self.send_header("Content-Length", str(len(b)))
310
+ self.send_header("Cache-Control", "no-store")
311
+ self.end_headers()
312
+ self.wfile.write(b)
313
+
314
+ def _auth(self) -> bool:
315
+ h = self.headers.get("Authorization", "")
316
+ ok = bool(TOKEN) and h.startswith("Bearer ") and hmac.compare_digest(h[7:].strip(), TOKEN)
317
+ if not ok:
318
+ self._send(401, {"error": "a valid runner token is needed"})
319
+ return ok
320
+
321
+ def _job(self, jid: str):
322
+ job = JOBS.get(jid)
323
+ if not job:
324
+ self._send(404, {"error": "no such attempt"})
325
+ return job
326
+
327
+ def do_GET(self):
328
+ if self.path == "/healthz":
329
+ version = VERSION_FILE.read_text(encoding="utf-8").strip()[:40] if VERSION_FILE.is_file() else "unknown"
330
+ return self._send(200, {"ok": bool(TOKEN), "busy": LOCK.locked(), "automation": AUTOMATION.exists(), "cases": CASES.is_dir(),
331
+ "version": version})
332
+ if not self._auth():
333
+ return
334
+ m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})(/bundle|/live)?(?:\?since=(\d{1,7}))?", self.path)
335
+ if not m:
336
+ return self._send(404, {"error": "not found"})
337
+ job = self._job(m.group(1))
338
+ if not job:
339
+ return
340
+ if m.group(2) == "/live":
341
+ return self._send(200, live_now(job) if job["state"] == "running" else {"status": None, "frame": None, "failed": None, "frame_at": None})
342
+ if m.group(2):
343
+ if job["state"] == "running":
344
+ return self._send(409, {"error": "the attempt is still running"})
345
+ return self._send(200, raw=bundle(job), ctype="application/zip")
346
+ st = {"id": job["id"], "state": job["state"], "exit_code": job["exit_code"], "timed_out": bool(job.get("timed_out")),
347
+ "progress": _progress(job["dir"] / "playwright.log"), "report": (job["dir"] / "report.json").exists()}
348
+ if m.group(3) is not None: # a screen read follows its log lines ("[explore] ...") for its progress
349
+ st["lines"], st["line_count"] = _lines(job["dir"] / "playwright.log", int(m.group(3)))
350
+ self._send(200, st)
351
+
352
+ def do_POST(self):
353
+ if not self._auth():
354
+ return
355
+ n = int(self.headers.get("Content-Length") or 0)
356
+ if n > MAX_BODY:
357
+ return self._send(413, {"error": "body too large"})
358
+ if self.path in ("/v1/attempts", "/v1/screens"):
359
+ try:
360
+ body = json.loads(self.rfile.read(n) or b"{}")
361
+ return self._send(202, start(body) if self.path == "/v1/attempts" else start_screens(body))
362
+ except BlockingIOError as e:
363
+ return self._send(409, {"error": str(e)})
364
+ except (ValueError, TypeError) as e:
365
+ return self._send(400, {"error": str(e)})
366
+ m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})/cancel", self.path)
367
+ if m:
368
+ job = self._job(m.group(1))
369
+ if job:
370
+ job["cancel"] = True
371
+ self._send(202, {"id": job["id"], "state": "cancelling"})
372
+ return
373
+ self._send(404, {"error": "not found"})
374
+
375
+
376
+ if __name__ == "__main__":
377
+ if not TOKEN or len(TOKEN) < 24:
378
+ raise SystemExit("set RUNNER_TOKEN (at least 24 characters)")
379
+ HOME.mkdir(parents=True, exist_ok=True)
380
+ threading.Thread(target=sweep, daemon=True).start()
381
+ print(f"Patchwise remote runner on 127.0.0.1:{PORT}, automation {AUTOMATION}", flush=True)
382
+ ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
automation/src/fusion/ui.ts CHANGED
@@ -1,800 +1,805 @@
1
- import { expect, type Locator, type Page } from '@playwright/test';
2
- import { dateFormat, FALLBACK_FORMATS, formatDate, formatFromHint, inferDateFormat, parseDate, reformat, setDateFormat } from './dates';
3
-
4
- /** A text as a literal inside a regular expression. */
5
- const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
6
-
7
- /** Where the tests run and as whom. Set by the co-worker from the pod registration and its vault (never in code). */
8
- export const fusionEnv = () => ({
9
- baseUrl: (process.env.FUSION_BASE_URL || '').replace(/\/$/, ''),
10
- username: process.env.FUSION_USERNAME || '',
11
- password: process.env.FUSION_PASSWORD || '',
12
- });
13
-
14
- /**
15
- * The pod's test data, by business area and key: what the scout discovered in the pod's own records, with the values an
16
- * admin set on the Test environments page on top. The co-worker passes it as FUSION_TESTDATA (JSON); nothing is built in,
17
- * so a value the pod does not offer fails the step with a message saying where to set it.
18
- */
19
- export function podData(): Record<string, Record<string, string>> {
20
- try {
21
- const d = JSON.parse(process.env.FUSION_TESTDATA || '{}');
22
- return d && typeof d === 'object' ? d : {};
23
- } catch {
24
- throw new Error('FUSION_TESTDATA is not valid JSON');
25
- }
26
- }
27
-
28
- /** One test data value ({{pod.<area>.<key>}}). FUSION_<AREA>_<KEY> in the environment wins (a one-off override). */
29
- export function podValue(area: string, key: string): string {
30
- const env = process.env[`FUSION_${area}_${key}`.toUpperCase()];
31
- if (env) return env;
32
- const v = podData()[area.toUpperCase()]?.[key];
33
- if (v) return v;
34
- throw new Error(`No test data "${key}" for ${area.toUpperCase()} on this pod: the scout found none in the pod's records. ` +
35
- `Set it on the Test environments page (Test data), then run again.`);
36
- }
37
-
38
- /** The values to try for one test data key, in order (FUSION_TESTDATA_CANDIDATES, set by the co-worker): the admin's
39
- * own, the one Fusion last accepted, the pod's records, then its screens' list choices. The single value otherwise. */
40
- export function podCandidates(area: string, key: string): string[] {
41
- const env = process.env[`FUSION_${area}_${key}`.toUpperCase()];
42
- if (env) return [env];
43
- try {
44
- const all = JSON.parse(process.env.FUSION_TESTDATA_CANDIDATES || '{}') as Record<string, Record<string, string[]>>;
45
- const list = all?.[area.toUpperCase()]?.[key];
46
- if (Array.isArray(list) && list.length) return list.map(String);
47
- } catch { /* fall back to the single value */ }
48
- return [podValue(area, key)];
49
- }
50
-
51
- /** Fusion did not take a value in a field (not in this user's list, or not valid there): another one may be. */
52
- export class ValueRefused extends Error {}
53
-
54
- /** Payables test data for this pod (discovered by the scout, overridable per pod). Read lazily: a test that never uses
55
- * a value does not need it. */
56
- export const apData = () => ({
57
- get businessUnit() { return podValue('AP', 'business_unit'); },
58
- get supplier() { return podValue('AP', 'supplier'); },
59
- get account() { return podValue('AP', 'account'); },
60
- });
61
-
62
- /** Today as the pod can never see as "in the future": the calendar day at UTC-12 (the earliest time zone on Earth).
63
- * Fusion refuses an invoice date after the pod's own today (AP-810244), and the tester's clock (e.g. India) is often
64
- * a day ahead of the pod's. */
65
- export const podToday = () => new Date(Date.now() - 12 * 3600_000);
66
-
67
- /** The UTC calendar day of `d` (default: podToday()) in the date format this run learned for the pod (dates.ts). */
68
- export const fusionDate = (d = podToday()) => formatDate(d);
69
-
70
- /** The invoice status Fusion shows next to the page title (a link opening the validation details). */
71
- export const INVOICE_STATUSES = ['Validated', 'Not validated', 'Needs revalidation', 'Canceled', 'Never validated'] as const;
72
-
73
- export interface InvoiceLine { amount: string; account: string; type?: 'Item' | 'Freight' | 'Miscellaneous' }
74
-
75
- /** A test document number nobody else will use: FPT-<tag>-<MMDDhhmmss>. */
76
- export const testNumber = (tag: string) => `FPT-${tag}-${new Date().toISOString().replace(/\D/g, '').slice(4, 14)}`;
77
-
78
- /**
79
- * The user-level steps on Oracle Fusion screens, proven on a real pod. Fusion pages are slow and recalculate defaults
80
- * after each field, so every step waits for the page to settle instead of a fixed short timeout.
81
- */
82
- export class FusionUi {
83
- constructor(readonly page: Page) {
84
- // Leaving a page with unsaved entries makes Fusion ask "leave this page?". Playwright's default answer is "stay",
85
- // which cancels the navigation and strands the test on that page. Nothing is saved by leaving, so leave.
86
- page.on('dialog', (d) => { if (d.type() === 'beforeunload') void d.accept().catch(() => {}); });
87
- }
88
-
89
- /** Wait until Fusion's page framework (Oracle ADF) has finished its round trip to the server. Fusion keeps
90
- * background requests going, so "network idle" never comes; ADF's own flag is the reliable signal. */
91
- async settle(extraMs = 800) {
92
- await this.page.waitForLoadState('domcontentloaded').catch(() => {});
93
- await this.page.waitForFunction(() => {
94
- const adf = (window as unknown as { AdfPage?: { PAGE?: { isSynchronizedWithServer?: () => boolean } } }).AdfPage;
95
- return !adf?.PAGE?.isSynchronizedWithServer || adf.PAGE.isSynchronizedWithServer();
96
- }, undefined, { timeout: 60_000, polling: 250 }).catch(() => {});
97
- await this.page.waitForTimeout(extraMs);
98
- }
99
-
100
- async signIn() {
101
- const { baseUrl, username, password } = fusionEnv();
102
- if (!baseUrl || !username || !password) throw new Error('FUSION_BASE_URL, FUSION_USERNAME and FUSION_PASSWORD must be set for a Fusion run');
103
- if (await this.signedIn(baseUrl)) return;
104
- await this.page.goto(`${baseUrl}/`, { waitUntil: 'domcontentloaded' });
105
- const user = this.page.locator('[id="idcs-signin-basic-signin-form-username|input"]');
106
- const pass = this.page.locator('[id="idcs-signin-basic-signin-form-password|input"]');
107
- await user.fill(username);
108
- await pass.waitFor();
109
- // The password must never reach a report, trace or log. Playwright records every action's arguments (so no
110
- // fill(password)), its trace snapshots record input values even of password fields, and its network log records
111
- // the sign-in request body. So the trace is stopped (and what it held discarded) until the user is signed in, then
112
- // started afresh; and the page fetches the password itself through a binding (no action argument carries it).
113
- const tracing = this.page.context().tracing;
114
- const paused = await tracing.stop().then(() => true, () => false);
115
- try {
116
- await this.page.exposeBinding('__fptSignInSecret', () => fusionEnv().password).catch(() => {});
117
- await pass.evaluate(async (el: HTMLInputElement) => {
118
- const v = await (window as unknown as { __fptSignInSecret: () => Promise<string> }).__fptSignInSecret();
119
- el.focus();
120
- Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(el, v);
121
- el.dispatchEvent(new Event('input', { bubbles: true }));
122
- el.dispatchEvent(new Event('change', { bubbles: true }));
123
- });
124
- await pass.press('Enter');
125
- // the address is the sign of arrival: the home page's "load" can hang on a slow background resource
126
- await this.page.waitForURL(/AtkHomePageWelcome|FuseWelcome/, { timeout: 120_000, waitUntil: 'commit' });
127
- await this.settle();
128
- } finally {
129
- if (paused) await tracing.start({ screenshots: true, snapshots: true, sources: true, title: 'after sign-in' }).catch(() => {});
130
- }
131
- }
132
-
133
- /** The browser already holds a good session: the run signed in once before its tests (playwright.fusion.config.ts,
134
- * src/fusion/session.ts), or an earlier step did. The home page then opens without the sign-in page, and signing in
135
- * again (20-60 s per test) is skipped. An expired session shows the sign-in page, and the caller signs in. */
136
- private async signedIn(baseUrl: string): Promise<boolean> {
137
- const host = new URL(baseUrl).hostname;
138
- if (!(await this.page.context().cookies(baseUrl).catch(() => [])).length) return false;
139
- await this.page.goto(`${baseUrl}/fscmUI/faces/AtkHomePageWelcome`, { waitUntil: 'domcontentloaded' }).catch(() => {});
140
- await this.settle(1000);
141
- const url = new URL(this.page.url());
142
- const signInPage = await this.page.locator('[id="idcs-signin-basic-signin-form-username|input"]').isVisible().catch(() => false);
143
- return url.hostname === host && /AtkHomePageWelcome|FuseWelcome/.test(url.pathname) && !signInPage;
144
- }
145
-
146
- /** The work area last opened ("Group > Page"): a task of the same work area is opened from its Tasks list without
147
- * going back through the home page. Cleared whenever the browser goes home. */
148
- private workArea: string | null = null;
149
-
150
- /** Navigator-style path: a work area link on the springboard, then a page, then a task from the Tasks panel.
151
- * Fusion occasionally serves a blank page mid-navigation; the whole path is then walked once more from the home page. */
152
- async openTask(area: string, page: string, task: string) {
153
- for (let attempt = 1; ; attempt++) {
154
- try {
155
- const here = attempt === 1 && this.workArea === `${area} > ${page}`
156
- && await this.page.locator('[id$="_FndTasksList::disAcr"], [id$="_FndTasksList"]').filter({ visible: true }).first().isVisible().catch(() => false);
157
- if (!here) await this.openWorkArea(area, page);
158
- const inList = await this.openTasksPanel().then(() => this.tasksRegion().getByRole('link', { name: task, exact: true }).first(), () => null);
159
- if (inList && await inList.isVisible().catch(() => false)) await inList.click({ timeout: attempt === 1 ? 45_000 : undefined });
160
- else await this.press(await this.target(task), attempt === 1 ? 45_000 : undefined); // an action on the page itself
161
- await this.settle(8000);
162
- await this.expectTitle(task);
163
- await this.answerOrganizationPrompt();
164
- return;
165
- } catch (e) {
166
- if (attempt >= 2) throw e;
167
- }
168
- }
169
- }
170
-
171
- /** Open a quick action of a home page group ("Group > Action", e.g. Receivables > Create Transaction): the entries
172
- * Fusion shows under a group on the springboard that open a task directly. */
173
- async openQuickAction(group: string, action: string) {
174
- for (let attempt = 1; ; attempt++) {
175
- try {
176
- await this.openGroup(group);
177
- await this.press(await this.target(action), attempt === 1 ? 45_000 : undefined);
178
- await this.settle(8000);
179
- await this.expectTitle(action);
180
- await this.answerOrganizationPrompt();
181
- return;
182
- } catch (e) {
183
- if (attempt >= 2) throw e;
184
- }
185
- }
186
- }
187
-
188
- /** Inventory tasks first ask which inventory organization to work in (one Organization field on an otherwise empty
189
- * page). The pod's own organization (test data {{pod.inv.organization}}, discovered by the scout) answers it, then
190
- * the task's real form opens. Nothing happens on any other page, or when the pod offers no organization. */
191
- async answerOrganizationPrompt() {
192
- const org = this.field('Organization');
193
- if (!(await org.isVisible().catch(() => false))) return;
194
- const inputs = await this.page.locator('input:visible, select:visible, textarea:visible').count().catch(() => 0);
195
- if (inputs > 3 || (await org.inputValue().catch(() => 'x')) !== '') return; // a real form that has an Organization field
196
- let code = '';
197
- try { code = podValue('INV', 'organization'); } catch { return; }
198
- await this.fill(org, code);
199
- // the pop-up's OK is not always a standard button: the same visible-target lookup as everywhere else
200
- for (const name of ['OK', 'Continue', 'Done']) {
201
- const go = await this.target(name);
202
- if (await go.isVisible().catch(() => false)) { await this.press(go); break; }
203
- }
204
- await this.settle(6000);
205
- if (await this.field('Organization').isVisible().catch(() => false)
206
- && (await this.page.locator('input:visible, select:visible, textarea:visible').count().catch(() => 0)) <= 3) {
207
- throw new Error(`the test user may not work in inventory organization "${code}" (Fusion keeps asking for it; its list is `
208
- + 'empty for this user): give the test user inventory organization access, or set another organization in Test data');
209
- }
210
- }
211
-
212
- /** Open a task by its path: "Group > Page > Task" (a work area's Tasks list) or "Group > Action" (a quick action). */
213
- async openPath(path: string) {
214
- const parts = path.split('>').map((x) => x.trim()).filter(Boolean);
215
- if (parts.length === 3) return this.openTask(parts[0], parts[1], parts[2]);
216
- if (parts.length === 2) return this.openQuickAction(parts[0], parts[1]);
217
- throw new Error(`a task is opened as "Group > Page > Task" or "Group > Action", got "${path}"`);
218
- }
219
-
220
- /** The task is open: the page title names it ("Create Invoice - Oracle Fusion ...", "Invoice Workbench - Create
221
- * Recurring Invoices - ..."), or a dialog named after it is showing (Create Order opens a dialog over the work area,
222
- * and the page title stays the work area's). */
223
- async expectTitle(task: string) {
224
- const title = new RegExp(`(^|[-–:|]\\s*)${esc(task)}\\b`, 'i');
225
- const dialog = this.page.getByRole('dialog').filter({ hasText: new RegExp(`^\\s*${esc(task)}\\b`, 'i') }).filter({ visible: true });
226
- await expect.poll(async () => title.test(await this.page.title()) || (await dialog.count()) > 0,
227
- { message: `"${task}" should open (its page or its dialog)`, timeout: 60_000 }).toBe(true);
228
- }
229
-
230
- /** The Tasks list of a work area: the panel region whose id ends "_FndTasksList" (its tab: "..._FndTasksList::disAcr").
231
- * The work area's own name sits in different places ("..._JournalEntryPage_itemNode_FndTasksList",
232
- * "..._itemNode_InvoiceWorkbench_FndTasksList"); the ending is Fusion's. */
233
- tasksRegion(): Locator {
234
- return this.page.locator('[id$="_FndTasksList"]').filter({ visible: true }).first();
235
- }
236
-
237
- /** Open the work area's Tasks list unless it is open already (Fusion keeps it open within a session, and clicking its
238
- * tab again would close it). */
239
- async openTasksPanel() {
240
- if (await this.tasksRegion().isVisible().catch(() => false)) return;
241
- await this.page.locator('[id$="_FndTasksList::disAcr"]').or(this.page.locator('div[title="Item: Tasks"]')).filter({ visible: true }).first().click();
242
- await this.settle(2500);
243
- await this.tasksRegion().waitFor({ timeout: 30_000 });
244
- }
245
-
246
- /** The task names in the open work area's Tasks list. */
247
- async taskNames(): Promise<string[]> {
248
- try {
249
- await this.openTasksPanel();
250
- const names = await this.tasksRegion().locator('a').evaluateAll((els) => els
251
- .filter((e) => (e as HTMLElement).getBoundingClientRect().width > 0)
252
- .map((e) => ((e as HTMLElement).innerText || '').replace(/\s+/g, ' ').trim()).filter((t) => t && t.length <= 80));
253
- if (names.length) return Array.from(new Set(names));
254
- } catch { /* no Tasks list on this work area: its actions are on the page */ }
255
- return this.pageActions();
256
- }
257
-
258
- /** The actions a work area shows on the page itself (Expenses: Create Expense Report; Inventory Management:
259
- * Create Miscellaneous Transaction; Redwood pages): visible links and buttons named like a task, outside the
260
- * global header. Used when the work area has no Tasks list. */
261
- async pageActions(): Promise<string[]> {
262
- const names = await this.page.locator('a, button, [role="button"], [role="link"], oj-button, oj-c-button').evaluateAll((els) => els
263
- .filter((e) => (e as HTMLElement).getBoundingClientRect().width > 0 && !e.closest('[role="banner"], header, [id^="pt1:_UIS"]'))
264
- .map((e) => ((e as HTMLElement).innerText || e.getAttribute('aria-label') || e.getAttribute('label') || '').replace(/\s+/g, ' ').trim())
265
- .filter((t) => t && t.length <= 60 && /^(create|manage|enter|submit|record|add|new|transfer|receive|review|view|search)\b/i.test(t)));
266
- return Array.from(new Set(names));
267
- }
268
-
269
- /** The groups of the home page springboard (Fusion's "groupNode_..." entries), by name. */
270
- async groupsOnHome(): Promise<string[]> {
271
- await this.goHome();
272
- const names = await this.page.locator('a[id^="groupNode_"]').evaluateAll((els) => els
273
- .filter((e) => (e as HTMLElement).getBoundingClientRect().width > 0)
274
- .map((e) => ((e as HTMLElement).innerText || e.getAttribute('title') || '').replace(/\s+/g, ' ').trim()).filter(Boolean));
275
- return Array.from(new Set(names));
276
- }
277
-
278
- /** Open a home page group; returns every name visible afterwards (its pages and quick actions among them). */
279
- async openGroup(group: string): Promise<string[]> {
280
- await this.goHome();
281
- // the springboard draws its groups after the page loads: wait for them before looking for this one
282
- await this.page.locator('a[id^="groupNode_"]').first().waitFor({ timeout: 60_000 }).catch(() => {});
283
- const g = this.page.locator('a[id^="groupNode_"]').filter({ hasText: new RegExp(`^\\s*${esc(group)}\\s*$`) })
284
- .filter({ visible: true }).first();
285
- await this.press((await g.count()) ? g : await this.target(group));
286
- await this.settle(3000);
287
- return this.visibleNames(250);
288
- }
289
-
290
- /** Click an element the way a user would. The springboard is a sideways strip of groups: one on another part of the
291
- * strip sits outside the window (x < 0), where a click at its position cannot land, so it gets the element's own
292
- * click instead (Fusion handles it the same way). */
293
- async press(el: Locator, timeout?: number) {
294
- const box = await el.boundingBox().catch(() => null);
295
- const vp = this.page.viewportSize() ?? { width: 1440, height: 900 };
296
- if (box && (box.x < 0 || box.y < 0 || box.x + box.width > vp.width || box.y + box.height > vp.height)) {
297
- await el.evaluate((e) => (e as HTMLElement).click());
298
- } else {
299
- await el.click(timeout ? { timeout } : undefined);
300
- }
301
- }
302
-
303
- /** Close what a previous task left open (its dialog), with the dialog's own Cancel / Close / OK. Nothing is saved. */
304
- async closeDialogs() {
305
- for (let i = 0; i < 3; i++) {
306
- const d = this.page.getByRole('dialog').filter({ visible: true }).first();
307
- if (!(await d.isVisible().catch(() => false))) return;
308
- const b = d.getByRole('button', { name: /^(Cancel|Close|OK|No)$/ }).filter({ visible: true }).first();
309
- if (await b.isVisible().catch(() => false)) await b.click().catch(() => {});
310
- else await this.page.keyboard.press('Escape').catch(() => {});
311
- await this.settle(1500);
312
- }
313
- }
314
-
315
- /** The home page with its springboard of groups. Work areas share the address "/faces/FuseWelcome" and reloading it
316
- * reopens the last work area, so home is "/faces/AtkHomePageWelcome" (where sign-in lands), else the Home link. */
317
- async goHome() {
318
- this.workArea = null;
319
- const base = fusionEnv().baseUrl;
320
- await this.page.goto(`${base}/fscmUI/faces/AtkHomePageWelcome`, { waitUntil: 'domcontentloaded' }).catch(() => {});
321
- await this.settle(4000);
322
- await this.closeDialogs(); // a dialog a previous task left open would cover the springboard
323
- const groups = this.page.locator('a[id^="groupNode_"]').filter({ visible: true });
324
- if (await groups.first().isVisible().catch(() => false)) return;
325
- const homeLink = this.page.getByRole('link', { name: 'Home', exact: true }).filter({ visible: true }).first();
326
- if (await homeLink.isVisible().catch(() => false)) {
327
- await homeLink.click();
328
- await this.settle(4000);
329
- } else {
330
- await this.page.goto(`${base}/fscmUI/faces/FuseWelcome`, { waitUntil: 'domcontentloaded' });
331
- await this.settle(4000);
332
- }
333
- }
334
-
335
- /** Open a work area ("Group > Page"): from the home page's springboard, as a user does; through Fusion's Navigator
336
- * menu when the springboard does not show the group (pods and roles differ in what the home page offers). */
337
- async openWorkArea(group: string, pageName: string) {
338
- const shown = await this.openGroup(group).catch(() => [] as string[]);
339
- if (shown.length) {
340
- // the group's work area entries are Fusion's "itemNode_..." elements; any visible target otherwise
341
- const item = this.page.locator('a[id^="itemNode_"]').filter({ hasText: new RegExp(`^\\s*${esc(pageName)}\\s*$`) }).filter({ visible: true }).first();
342
- const p = (await item.count().catch(() => 0)) ? item : await this.target(pageName);
343
- if (await p.isVisible().catch(() => false)) {
344
- await this.press(p);
345
- await this.settle(6000);
346
- this.workArea = `${group} > ${pageName}`;
347
- return;
348
- }
349
- }
350
- await this.goHome();
351
- await this.openNavigator();
352
- const g = await this.target(group);
353
- if (await g.isVisible().catch(() => false)) { await g.click(); await this.settle(1500); } // expand the group
354
- await (await this.target(pageName)).click({ timeout: 30_000 });
355
- await this.settle(6000);
356
- this.workArea = `${group} > ${pageName}`;
357
- }
358
-
359
- /** The VISIBLE element a user would click for `name`: a link with exactly that name, else a button or menu entry,
360
- * else that exact text. Fusion pages hold hidden copies of many links (collapsed menus, the Navigator, Favorites);
361
- * the first match is often one of those, and clicking it only waits until it times out. Links come first so a
362
- * heading with the same words is never clicked instead of the link. */
363
- async target(name: string): Promise<Locator> {
364
- const p = this.page;
365
- const kinds = [p.getByRole('link', { name, exact: true }), p.getByRole('button', { name, exact: true }),
366
- p.getByRole('menuitem', { name, exact: true }), p.getByText(name, { exact: true })];
367
- for (const k of kinds) {
368
- const v = k.filter({ visible: true });
369
- if (await v.count().catch(() => 0)) return v.first();
370
- }
371
- return kinds[0].filter({ visible: true }).first(); // none visible yet: wait for the link (the caller's timeout)
372
- }
373
-
374
- /** The names of the visible links and buttons of the page (labels only): what a pod offers where a name was not found. */
375
- async visibleNames(limit = 80): Promise<string[]> {
376
- const names = await this.page.locator('a, [role="link"], [role="button"], [role="menuitem"]').evaluateAll((els) => els
377
- .filter((e) => (e as HTMLElement).getBoundingClientRect().width > 0)
378
- .map((e) => ((e as HTMLElement).innerText || e.getAttribute('title') || e.getAttribute('aria-label') || '').replace(/\s+/g, ' ').trim())
379
- .filter((t) => t && t.length <= 60 && !/https?:|www\./i.test(t))).catch(() => [] as string[]);
380
- return Array.from(new Set(names)).slice(0, limit);
381
- }
382
-
383
- /** Fusion's Navigator: the menu of every work area the user may open. */
384
- async openNavigator() {
385
- await this.page.getByRole('link', { name: 'Navigator' }).or(this.page.getByRole('button', { name: 'Navigator' })).first().click({ timeout: 20_000 });
386
- await this.settle(2000);
387
- }
388
-
389
- /** A form field by its visible label; Fusion adds "(Required)" to the label of required fields. */
390
- field(label: string): Locator {
391
- // the visible one: Fusion pages keep hidden copies of many fields, and the first match is often one of those
392
- return this.page.getByLabel(new RegExp(`^\\s*${label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(\\s*\\(Required\\))?\\s*$`))
393
- .filter({ visible: true }).first();
394
- }
395
-
396
- /** Type a value (or choose it in a drop-down list) and leave the field, so Fusion runs its own logic (look-ups,
397
- * defaults) as it does for a user. */
398
- async put(label: string, value: string) {
399
- const was = dateFormat();
400
- try {
401
- await this.fill(this.field(label), value, label);
402
- } catch (e) {
403
- // a date Fusion refused: the user's date format comes from the field's hint, then from the dates Fusion shows on
404
- // this page, else the common formats are tried in turn; the first one Fusion takes is kept for the run
405
- if (!(e instanceof ValueRefused) || !parseDate(value, was)) throw e;
406
- const hint = await this.field(label).evaluate((el) => {
407
- const i = el as HTMLInputElement;
408
- const described = (i.getAttribute('aria-describedby') || '').split(/\s+/).filter(Boolean)
409
- .map((id) => document.getElementById(id)?.textContent || '');
410
- return [i.placeholder, i.title, ...described].filter(Boolean).join(' ');
411
- }).catch(() => '');
412
- const seen = await this.page.locator('input').evaluateAll((els) => els.map((el) => (el as HTMLInputElement).value || ''));
413
- const candidates = [formatFromHint(hint, podToday()), inferDateFormat(seen.filter((v) => v.trim() && v.trim() !== value.trim()), podToday()),
414
- ...FALLBACK_FORMATS].filter((f, i, all): f is string => !!f && f !== was && all.indexOf(f) === i);
415
- let last: unknown = e;
416
- for (const fmt of candidates.slice(0, 6)) {
417
- const typed = reformat(value, was, fmt);
418
- try {
419
- await this.fill(this.field(label), typed, label);
420
- setDateFormat(fmt);
421
- console.log(`[dates] this pod's user writes dates as ${fmt} (Fusion refused ${value}); typed ${typed}`);
422
- return;
423
- } catch (e2) {
424
- if (!(e2 instanceof ValueRefused)) throw e2;
425
- last = e2;
426
- }
427
- }
428
- throw last;
429
- }
430
- }
431
-
432
- async value(label: string): Promise<string> {
433
- return (await this.field(label).inputValue().catch(() => '')).trim();
434
- }
435
-
436
- async expectFilled(label: string) {
437
- await expect.poll(() => this.value(label), { message: `${label} should be filled in by Fusion`, timeout: 30_000 }).not.toBe('');
438
- }
439
-
440
- /** Invoice header as a Payables user types it: business unit, supplier (Fusion fills site, legal entity, terms),
441
- * then number, amount and date. The date goes in before any line exists, so Fusion does not ask about line dates. */
442
- async enterInvoiceHeader(h: { businessUnit: string; supplier: string; number: string; amount: string; date?: string }) {
443
- await this.put('Business Unit', h.businessUnit);
444
- await this.put('Supplier', h.supplier);
445
- await this.expectFilled('Supplier Site');
446
- await this.chooseCurrencyIfEmpty();
447
- await this.put('Number', h.number);
448
- await this.put('Amount', h.amount);
449
- await this.put('Date', h.date || fusionDate());
450
- }
451
-
452
- /** A business unit without a default currency leaves Invoice Currency empty, and Fusion then refuses the lines ("the
453
- * invoice header is incomplete"). Choose the pod's own invoice currency (its records' most used); nothing to do when
454
- * Fusion filled it, or when the screen has no such list. */
455
- async chooseCurrencyIfEmpty() {
456
- const list = this.page.getByLabel(/^\s*Invoice Currency(\s*\(Required\))?\s*$/).first();
457
- if (!(await list.count()) || (await list.evaluate((e) => e.tagName).catch(() => '')) !== 'SELECT') return;
458
- if (await list.evaluate((e) => (e as HTMLSelectElement).value !== '' && (e as HTMLSelectElement).selectedIndex > 0).catch(() => true)) return;
459
- const code = podCandidates('AP', 'currency')[0];
460
- if (!code) throw new Error('Invoice Currency is empty for this business unit and the pod has no currency in its records: set it on the Test environments page (Test data).');
461
- const label = await list.evaluate((e, c) => Array.from((e as HTMLSelectElement).options).map((o) => o.text).find((t) => t === c || t.startsWith(`${c} `)) ?? '', code);
462
- if (!label) throw new Error(`Invoice Currency is empty for this business unit and Fusion does not offer the pod's currency "${code}".`);
463
- await list.selectOption({ label });
464
- await this.settle(1500);
465
- }
466
-
467
- /** Open a collapsed region of the page (e.g. "Lines") if it is not open yet. */
468
- async expandSection(name: string) {
469
- const expand = this.page.locator(`a[title="Expand ${name}"]`);
470
- if (await expand.count()) { await expand.first().click(); await this.settle(3000); }
471
- await expect(this.page.locator(`a[title="Collapse ${name}"]`).first()).toBeVisible();
472
- }
473
-
474
- /** One row of the invoice Lines table; Fusion names each row "Select Row <n> <n> ...". */
475
- lineRow(n: number): Locator {
476
- return this.page.getByRole('row', { name: new RegExp(`^Select Row ${n} ${n} `) });
477
- }
478
-
479
- /** Fill invoice line n (1-based) in the Lines table: type, amount and the distribution combination. Fusion offers
480
- * empty rows; the next row only becomes editable after the previous one, so lines are added in order. */
481
- async addLine(n: number, line: InvoiceLine) {
482
- await this.expandSection('Lines');
483
- const row = this.lineRow(n);
484
- if (await row.getByRole('textbox', { name: `Amount: ${n}`, exact: true }).isDisabled()) {
485
- await this.page.getByRole('button', { name: 'Add Row' }).first().click();
486
- await this.settle(2000);
487
- }
488
- if (line.type && line.type !== 'Item') {
489
- await row.getByRole('combobox', { name: new RegExp(`^Type: ${n}`) }).selectOption({ label: line.type });
490
- await this.settle();
491
- }
492
- const amount = row.getByRole('textbox', { name: `Amount: ${n}`, exact: true });
493
- await amount.click(); await amount.fill(line.amount); await amount.press('Tab'); await this.settle(1500);
494
- const account = row.getByRole('textbox', { name: 'Distribution Combination ID' });
495
- await account.click(); await account.fill(line.account); await account.press('Tab'); await this.settle(2500);
496
- await expect(account).toHaveValue(line.account);
497
- }
498
-
499
- /** Texts of the message windows Fusion shows (warnings, errors, confirmations), whitespace collapsed. */
500
- async dialogs(): Promise<string[]> {
501
- const d = this.page.getByRole('dialog');
502
- const out: string[] = [];
503
- for (let i = 0; i < await d.count(); i++) {
504
- if (!(await d.nth(i).isVisible().catch(() => false))) continue;
505
- const t = (await d.nth(i).innerText().catch(() => '')).replace(/\s+/g, ' ').replace('Click here to exit this popup.', '').trim();
506
- if (t) out.push(t);
507
- }
508
- return out;
509
- }
510
-
511
- /** Answer the open Fusion message window with one of its buttons (OK by default). */
512
- async answerDialog(button = 'OK') {
513
- await this.page.getByRole('dialog').getByRole('button', { name: button, exact: true }).first().click();
514
- await this.settle(2000);
515
- }
516
-
517
- /** Press the page's Save button; returns what Fusion said in message windows (empty when it saved quietly). */
518
- async save(): Promise<string[]> {
519
- await this.page.getByRole('button', { name: 'Save', exact: true }).first().click();
520
- await this.settle(4000);
521
- return this.dialogs();
522
- }
523
-
524
- /** Run an entry of the Invoice Actions menu (Validate, Cancel Invoice, Manage Holds, ...). */
525
- async invoiceAction(name: string) {
526
- await this.menuAction('Invoice Actions', name);
527
- }
528
-
529
- /** Press a button, link or menu entry, failing at once (with the reason) when Fusion shows it disabled: an action
530
- * that needs a row selected or other fields filled first is greyed out, and waiting for it only times out. */
531
- async pressEnabled(el: Locator, what: string) {
532
- await el.waitFor({ state: 'visible', timeout: 30_000 });
533
- const off = (await el.getAttribute('aria-disabled').catch(() => null)) === 'true' || await el.isDisabled().catch(() => false);
534
- if (off) {
535
- throw new Error(`"${what}" is disabled on the screen at this point: Fusion enables it only once what it needs is done ` +
536
- '(a row selected, or the fields it depends on filled)');
537
- }
538
- await this.press(el);
539
- }
540
-
541
- /** The choices a list field offers this user (up to `max`), read the way a user sees them: a drop-down's entries, or
542
- * the rows a list of values shows on the down arrow. Read-only: the list is closed again and nothing is chosen. */
543
- async listChoices(label: string, max = 5): Promise<string[]> {
544
- const f = this.field(label);
545
- if (!(await f.isVisible().catch(() => false))) return [];
546
- const select = (await f.evaluate((e) => e.tagName).catch(() => '')) === 'SELECT' ? f
547
- : f.locator('select:visible').first();
548
- if (await select.count().catch(() => 0)) {
549
- return (await select.evaluate((e) => Array.from((e as HTMLSelectElement).options).map((o) => o.label.trim())).catch(() => [] as string[]))
550
- .filter((t) => t && !/^(-+|select|none)$/i.test(t)).slice(0, max);
551
- }
552
- // what the page shows before the list opens: the page's own tables (a transaction's lines) must not be mistaken
553
- // for the list. Each item: its text, and for a table row the first cell after Fusion's unseen "Select Row" cell
554
- const items = () => this.page.locator('tr:visible, [role="option"]:visible, li:visible').evaluateAll((els) => els.map((e) => {
555
- const text = ((e as HTMLElement).innerText || '').replace(/\s+/g, ' ').trim();
556
- // a list of values' row ("Select Row" + the value's columns), a search-select's row (role row: the value itself),
557
- // or an option; any other table row (a container of rows) is not a value
558
- const first = e.tagName === 'TR' && /^Select Row/.test(text)
559
- ? Array.from(e.querySelectorAll('td')).map((td) => ((td as HTMLElement).innerText || '').replace(/\s+/g, ' ').replace(/^\s*Select Row\s*/, '').trim())
560
- .find((t) => t) || ''
561
- : e.tagName === 'TR' ? (e.getAttribute('role') === 'row' ? text : '') : text;
562
- return { text, value: first };
563
- })).catch(() => [] as { text: string; value: string }[]);
564
- const before = new Set((await items()).map((i) => i.text));
565
- // a list of values (its input is the field) opens on the down arrow; a search-select (a box wrapping its input,
566
- // Ledger, Accounting Period) opens on a click on the box
567
- if ((await f.evaluate((e) => e.tagName).catch(() => '')) === 'INPUT') {
568
- if (!(await f.isEditable().catch(() => false))) return [];
569
- await f.click({ timeout: 5000 }).catch(() => {});
570
- await this.page.keyboard.press('ArrowDown').catch(() => {});
571
- } else {
572
- await f.click({ timeout: 5000 }).catch(() => {});
573
- }
574
- await this.settle(2500);
575
- // the user's recently used values come first, named "MRU Row <n> <value>" (an empty one: "... Empty Cell")
576
- const got = (await items()).filter((i) => !before.has(i.text) && i.value).map((i) => i.value.replace(/^MRU Row \d+\s*/i, ''))
577
- .filter((v) => v.length <= 120 && !/^(All|Empty Cell|Search\.*|More\.*|Previous|Next.*|No results.*)$/i.test(v) && !/\d+-\d+ of \d+/.test(v));
578
- await this.page.keyboard.press('Escape').catch(() => {});
579
- await this.settle(600);
580
- await this.page.locator('body').click({ position: { x: 5, y: 5 } }).catch(() => {}); // a list still open covers the page
581
- // a container entry repeats its entries' text: keep the single values
582
- const uniq = Array.from(new Set(got));
583
- return uniq.filter((v) => !uniq.some((o) => o !== v && v.includes(o) && v.length > o.length + 2)).slice(0, max);
584
- }
585
-
586
- /** Run an entry of any menu of the page (the screen inventory lists them: "Actions", "Invoice Actions", ...). */
587
- async menuAction(menu: string, entry: string) {
588
- const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
589
- const opener = this.page.getByRole('button', { name: menu, exact: true }).or(this.page.getByText(menu, { exact: true }));
590
- await opener.first().click();
591
- await this.settle(1500);
592
- await this.pressEnabled(this.page.getByRole('menuitem', { name: new RegExp(`^\\s*${esc(entry)}\\b`) }).first(), `${menu} > ${entry}`);
593
- await this.settle(5000);
594
- }
595
-
596
- /** Add a row to the table of a section ("Lines", "Distributions", ...): opens the section if collapsed, then presses
597
- * that table's Add Row (the only one on the page when the section cannot be told apart). */
598
- async addRow(section: string) {
599
- const expand = this.page.locator(`a[title="Expand ${section}"]`);
600
- if (await expand.count()) { await expand.first().click(); await this.settle(3000); }
601
- await this.refusedRow(section);
602
- const add = this.page.getByRole('button', { name: /^(Add Row|Add|Create)$/ });
603
- const region = this.page.locator('div, table, section').filter({ has: this.page.getByText(section, { exact: true }) }).filter({ has: add });
604
- const target = (await region.count()) ? region.last().getByRole('button', { name: /^(Add Row|Add|Create)$/ }).first() : add.first();
605
- await target.click({ timeout: 15_000 }).catch(async (e) => { await this.refusedRow(section); throw e; });
606
- await this.settle(2500);
607
- await this.refusedRow(section);
608
- }
609
-
610
- /** Fusion refuses a row in a message window when the header is not complete yet (opening the section is enough to
611
- * bring it up): say why, and clear the window. */
612
- private async refusedRow(section: string) {
613
- const said = await this.dialogs();
614
- if (!said.length) return;
615
- await this.closeDialogs();
616
- throw new Error(`Fusion would not add a row to ${section}: ${said[0].slice(0, 300)}`);
617
- }
618
-
619
- /** A field of a table row by its column label; Fusion names row cells "<Label>: <row>" or just "<Label>". The newest
620
- * editable one is the row just added. */
621
- rowField(label: string): Locator {
622
- const esc = label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
623
- // a table cell is named "<Label>: <row>": the newest editable one is the row just added (a header field with the
624
- // same label, e.g. the invoice's own Amount, has no row number)
625
- const inRow = this.page.getByLabel(new RegExp(`^\\s*${esc}(\\s*\\(Required\\))?:\\s*\\d+\\s*$`)).filter({ visible: true });
626
- const any = this.page.getByLabel(new RegExp(`^\\s*${esc}(\\s*\\(Required\\))?(:\\s*\\d+)?\\s*$`)).filter({ visible: true });
627
- // only a field that takes typing: a table's totals and display cells carry the same label (the lines' read-only
628
- // "Amount" total), and the last match on the page is often one of those
629
- const typable = this.page.locator('input:not([readonly]):not([disabled]):not([type="hidden"]), textarea:not([readonly]):not([disabled]), select:not([disabled])');
630
- const open = (l: Locator) => l.and(typable).or(l.filter({ has: typable }));
631
- return open(inRow).or(open(any)).last();
632
- }
633
-
634
- /** Type or choose a value in a table row's field, then leave it so Fusion runs its own logic. */
635
- async putInRow(label: string, value: string) {
636
- await this.fill(this.rowField(label), value, label);
637
- }
638
-
639
- /** Fill a field the way a user does: a drop-down list is chosen by its visible label, anything else is typed. */
640
- async fill(f: Locator, value: string, label?: string) {
641
- // a field the screen does not offer right now: say why it may be missing at once, not after a long timeout
642
- if (!(await f.waitFor({ state: 'visible', timeout: 20_000 }).then(() => true, () => false))) {
643
- const name = label || 'the field';
644
- const asText = label ? await this.page.getByText(new RegExp(`^\\s*${esc(label)}\\s*$`)).filter({ visible: true }).count().catch(() => 0) : 0;
645
- throw new Error(asText
646
- ? `"${name}" is shown as fixed text, not as a field to fill: Fusion set it already (often the only value this user has); leave it to Fusion`
647
- : `"${name}" is not on the screen at this point: it may be in a closed section, appear only after another field is filled, or not be offered to this user`);
648
- }
649
- // a label may name the control's container (a list of values): type into the field inside it
650
- const tag = await f.evaluate((e) => e.tagName).catch(() => '');
651
- if (tag && !['INPUT', 'SELECT', 'TEXTAREA'].includes(tag)) {
652
- const inner = f.locator('input:visible, select:visible, textarea:visible').first();
653
- if (await inner.count().catch(() => 0)) f = inner;
654
- }
655
- // a field Fusion keeps read-only until the fields it depends on are set (a transaction's dates wait for its
656
- // business unit): fail at once with the reason, not after a click timeout
657
- let editable = false;
658
- for (let i = 0; i < 20 && !(editable = await f.isEditable().catch(() => false)); i++) await this.page.waitForTimeout(500);
659
- if (!editable) {
660
- const name = (await f.getAttribute('aria-label').catch(() => null)) || (await f.getAttribute('title').catch(() => null)) || 'this field';
661
- throw new Error(`"${name.trim()}" is read-only on the screen at this point: Fusion opens it only once the fields it depends on are filled (fill those first, or leave it to Fusion)`);
662
- }
663
- if ((await f.evaluate((e) => e.tagName).catch(() => '')) === 'SELECT') {
664
- await f.selectOption({ index: await this.optionIndex(f, value) });
665
- await this.settle();
666
- return;
667
- }
668
- const before = new Set(await this.messages());
669
- await f.click();
670
- await f.fill(value);
671
- // a list field shows its matching entries as you type: pick the one that is exactly the value, as a user does
672
- // (a search-select takes nothing on Tab alone); a plain field, or a list showing no such entry, takes Tab
673
- if (await this.pickSuggestion(value)) await this.settle();
674
- else {
675
- await f.press('Tab');
676
- await this.settle();
677
- }
678
- // a list of values that has no such entry for this user marks the field invalid or says so in a message
679
- // ... or Fusion takes it and then says it cannot be used here (a business unit whose ledger has no open period)
680
- const said = (await this.messages()).filter((m) => !before.has(m)
681
- && (/not valid|isn.t valid|no match|invalid|does not exist|doesn.t exist|no results/i.test(m) || /^\s*Error\b/.test(m)
682
- // a list of values with no such entry opens its search window instead of taking the text
683
- || /^\s*Search and Select\b/.test(m)));
684
- // Fusion marks a value it does not know with an error style on the field and an "Error:<label>" icon beside it
685
- // (no message, no aria-invalid): looked for only within the field's own box, never a neighbour's
686
- const invalid = (await f.getAttribute('aria-invalid').catch(() => null)) === 'true' || await f.evaluate((e) => {
687
- if (e.closest('.p_AFError')) return true;
688
- let box: Element | null = e.parentElement;
689
- for (let i = 0; i < 6 && box && box.querySelectorAll('input, select, textarea').length < 2; i++) {
690
- if (box.querySelector('img[title^="Error"]')) return true;
691
- box = box.parentElement;
692
- }
693
- return false;
694
- }).catch(() => false);
695
- if (said.length || invalid) {
696
- // left as it is: emptying a required field only adds a "required" error; the next value is typed over it
697
- await this.page.keyboard.press('Escape').catch(() => {});
698
- await this.closeDialogs();
699
- await this.settle(800);
700
- throw new ValueRefused(`Fusion did not accept "${value}" in "${label || 'the field'}"${said.length ? `: ${said[0].slice(0, 200)}` : ''}`);
701
- }
702
- }
703
-
704
- /** Click the suggestion that is exactly `value` in the list a field opened while typing (a search-select's rows, or
705
- * a list of values' "Select Row" rows). False when no such entry shows within a few seconds. */
706
- private async pickSuggestion(value: string): Promise<boolean> {
707
- const exact = new RegExp(`^\\s*${esc(value)}\\s*$`, 'i');
708
- const row = this.page.locator('[role="row"], [role="option"]').filter({ hasText: exact }).filter({ visible: true })
709
- .or(this.page.locator('tr').filter({ hasText: /^\s*Select Row/ }).locator('td').filter({ hasText: exact }).filter({ visible: true }));
710
- for (let i = 0; i < 8; i++) {
711
- if (await row.first().isVisible().catch(() => false)) {
712
- await row.first().click().catch(() => {});
713
- return true;
714
- }
715
- await this.page.waitForTimeout(400);
716
- }
717
- return false;
718
- }
719
-
720
- /** Which entry of a drop-down list means `value`: the label exactly, else the option's value, else the one label
721
- * holding it as a whole word (a pod's records hold codes like "USD" where the list shows "US Dollar (USD)"). */
722
- async optionIndex(f: Locator, value: string): Promise<number> {
723
- const read = () => f.evaluate((e) => Array.from((e as HTMLSelectElement).options).map((o) => ({ label: o.label.trim(), value: o.value })));
724
- let opts = await read();
725
- if (!opts.some((o) => o.label)) { // some lists are filled only when opened
726
- await f.click().catch(() => {});
727
- await this.settle(1500);
728
- await this.page.keyboard.press('Escape').catch(() => {});
729
- opts = await read();
730
- }
731
- if (!opts.some((o) => o.label)) {
732
- throw new Error('the list is empty for this test user: Fusion offers no value here (the user may lack access to it, '
733
- + "for example as a buyer of a business unit); this needs the user's access set up on the pod");
734
- }
735
- const want = value.trim().toLowerCase();
736
- const word = new RegExp(`(^|[^a-z0-9])${want.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^a-z0-9]|$)`, 'i');
737
- const i = [(o: { label: string }) => o.label.toLowerCase() === want, (o: { value: string }) => o.value.toLowerCase() === want,
738
- (o: { label: string }) => word.test(o.label)].map((m) => opts.findIndex(m)).find((x) => x >= 0);
739
- if (i === undefined) {
740
- throw new ValueRefused(`"${value}" is not in the list (${opts.map((o) => o.label).filter(Boolean).slice(0, 12).join(', ')}): ` +
741
- 'set the right value on the Test environments page (Test data)');
742
- }
743
- return i;
744
- }
745
-
746
- /** Fusion's messages: its message windows, and inline error notes on the page. */
747
- async messages(): Promise<string[]> {
748
- const inline = await this.page.locator('.af_message, [class*="message-text"], [id*="msgDlg"]').evaluateAll((els) => els
749
- .filter((e) => (e as HTMLElement).getBoundingClientRect().width > 0)
750
- .map((e) => ((e as HTMLElement).innerText || '').replace(/\s+/g, ' ').trim()).filter(Boolean)).catch(() => [] as string[]);
751
- return [...await this.dialogs(), ...inline];
752
- }
753
-
754
- /** The page must not show an error (a message window or note naming an error). */
755
- async expectNoError() {
756
- const errs = (await this.messages()).filter((m) => /\berror\b/i.test(m));
757
- if (errs.length) throw new Error(`Fusion showed an error: ${errs[0].slice(0, 300)}`);
758
- }
759
-
760
- /** Fusion must show a message containing `text` (a confirmation, warning or error), within 30 s. */
761
- async expectMessage(text: string) {
762
- const want = text.toLowerCase();
763
- await expect.poll(async () => (await this.messages()).some((m) => m.toLowerCase().includes(want)),
764
- { message: `Fusion should show a message with "${text}"`, timeout: 30_000 }).toBe(true);
765
- }
766
-
767
- /** A search on a Manage page found something: no "No results" note and at least one result row. */
768
- async expectResults() {
769
- await expect.poll(async () => {
770
- const none = await this.page.getByText(/^(No results found\.?|No data to display\.?|No rows yet\.?)$/).filter({ visible: true }).count();
771
- const rows = await this.page.getByRole('row').filter({ visible: true }).count();
772
- return none === 0 && rows > 1;
773
- }, { message: 'the search should find at least one result', timeout: 60_000 }).toBe(true);
774
- }
775
-
776
- /** A status shown on the page: an invoice's status link, or the status text of any other document. */
777
- async expectStatusText(status: string) {
778
- if ((INVOICE_STATUSES as readonly string[]).includes(status)) return this.expectStatus(status as (typeof INVOICE_STATUSES)[number]);
779
- await expect(this.page.getByText(status, { exact: true }).filter({ visible: true }).first(),
780
- { message: `the page should show the status ${status}` }).toBeVisible({ timeout: 60_000 });
781
- }
782
-
783
- /** The invoice status Fusion shows beside the page title (Not validated, Validated, Needs revalidation, Canceled). */
784
- async statusOnPage(): Promise<string> {
785
- const link = this.page.getByRole('link', { name: new RegExp(`^(${INVOICE_STATUSES.join('|')})$`) }).first();
786
- return (await link.innerText({ timeout: 5_000 }).catch(() => '')).trim();
787
- }
788
-
789
- async expectStatus(status: (typeof INVOICE_STATUSES)[number]) {
790
- await expect.poll(() => this.statusOnPage(), { message: `invoice status on the page should be ${status}`, timeout: 60_000 }).toBe(status);
791
- }
792
-
793
- /** Leave the page with Cancel, discarding anything not saved. */
794
- async cancelPage() {
795
- await this.page.getByRole('button', { name: 'Cancel', exact: true }).first().click();
796
- await this.settle(3000);
797
- const yes = this.page.getByRole('dialog').getByRole('button', { name: /^(Yes|OK)$/ });
798
- if (await yes.count()) { await yes.first().click(); await this.settle(3000); }
799
- }
800
- }
 
 
 
 
 
 
1
+ import { expect, type Locator, type Page } from '@playwright/test';
2
+ import { dateFormat, FALLBACK_FORMATS, formatDate, formatFromHint, inferDateFormat, parseDate, reformat, setDateFormat } from './dates';
3
+
4
+ /** A text as a literal inside a regular expression. */
5
+ const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
6
+
7
+ /** Where the tests run and as whom. Set by the co-worker from the pod registration and its vault (never in code). */
8
+ export const fusionEnv = () => ({
9
+ baseUrl: (process.env.FUSION_BASE_URL || '').replace(/\/$/, ''),
10
+ username: process.env.FUSION_USERNAME || '',
11
+ password: process.env.FUSION_PASSWORD || '',
12
+ });
13
+
14
+ /**
15
+ * The pod's test data, by business area and key: what the scout discovered in the pod's own records, with the values an
16
+ * admin set on the Test environments page on top. The co-worker passes it as FUSION_TESTDATA (JSON); nothing is built in,
17
+ * so a value the pod does not offer fails the step with a message saying where to set it.
18
+ */
19
+ export function podData(): Record<string, Record<string, string>> {
20
+ try {
21
+ const d = JSON.parse(process.env.FUSION_TESTDATA || '{}');
22
+ return d && typeof d === 'object' ? d : {};
23
+ } catch {
24
+ throw new Error('FUSION_TESTDATA is not valid JSON');
25
+ }
26
+ }
27
+
28
+ /** One test data value ({{pod.<area>.<key>}}). FUSION_<AREA>_<KEY> in the environment wins (a one-off override). */
29
+ export function podValue(area: string, key: string): string {
30
+ const env = process.env[`FUSION_${area}_${key}`.toUpperCase()];
31
+ if (env) return env;
32
+ const v = podData()[area.toUpperCase()]?.[key];
33
+ if (v) return v;
34
+ throw new Error(`No test data "${key}" for ${area.toUpperCase()} on this pod: the scout found none in the pod's records. ` +
35
+ `Set it on the Test environments page (Test data), then run again.`);
36
+ }
37
+
38
+ /** The values to try for one test data key, in order (FUSION_TESTDATA_CANDIDATES, set by the co-worker): the admin's
39
+ * own, the one Fusion last accepted, the pod's records, then its screens' list choices. The single value otherwise. */
40
+ export function podCandidates(area: string, key: string): string[] {
41
+ const env = process.env[`FUSION_${area}_${key}`.toUpperCase()];
42
+ if (env) return [env];
43
+ try {
44
+ const all = JSON.parse(process.env.FUSION_TESTDATA_CANDIDATES || '{}') as Record<string, Record<string, string[]>>;
45
+ const list = all?.[area.toUpperCase()]?.[key];
46
+ if (Array.isArray(list) && list.length) return list.map(String);
47
+ } catch { /* fall back to the single value */ }
48
+ return [podValue(area, key)];
49
+ }
50
+
51
+ /** Fusion did not take a value in a field (not in this user's list, or not valid there): another one may be. */
52
+ export class ValueRefused extends Error {}
53
+
54
+ /** Payables test data for this pod (discovered by the scout, overridable per pod). Read lazily: a test that never uses
55
+ * a value does not need it. */
56
+ export const apData = () => ({
57
+ get businessUnit() { return podValue('AP', 'business_unit'); },
58
+ get supplier() { return podValue('AP', 'supplier'); },
59
+ get account() { return podValue('AP', 'account'); },
60
+ });
61
+
62
+ /** Today as the pod can never see as "in the future": the calendar day at UTC-12 (the earliest time zone on Earth).
63
+ * Fusion refuses an invoice date after the pod's own today (AP-810244), and the tester's clock (e.g. India) is often
64
+ * a day ahead of the pod's. */
65
+ export const podToday = () => new Date(Date.now() - 12 * 3600_000);
66
+
67
+ /** The UTC calendar day of `d` (default: podToday()) in the date format this run learned for the pod (dates.ts). */
68
+ export const fusionDate = (d = podToday()) => formatDate(d);
69
+
70
+ /** The invoice status Fusion shows next to the page title (a link opening the validation details). */
71
+ export const INVOICE_STATUSES = ['Validated', 'Not validated', 'Needs revalidation', 'Canceled', 'Never validated'] as const;
72
+
73
+ export interface InvoiceLine { amount: string; account: string; type?: 'Item' | 'Freight' | 'Miscellaneous' }
74
+
75
+ /** A test document number nobody else will use: FPT-<tag>-<MMDDhhmmss>. */
76
+ export const testNumber = (tag: string) => `FPT-${tag}-${new Date().toISOString().replace(/\D/g, '').slice(4, 14)}`;
77
+
78
+ /**
79
+ * The user-level steps on Oracle Fusion screens, proven on a real pod. Fusion pages are slow and recalculate defaults
80
+ * after each field, so every step waits for the page to settle instead of a fixed short timeout.
81
+ */
82
+ export class FusionUi {
83
+ constructor(readonly page: Page) {
84
+ // Leaving a page with unsaved entries makes Fusion ask "leave this page?". Playwright's default answer is "stay",
85
+ // which cancels the navigation and strands the test on that page. Nothing is saved by leaving, so leave.
86
+ page.on('dialog', (d) => { if (d.type() === 'beforeunload') void d.accept().catch(() => {}); });
87
+ }
88
+
89
+ /** Wait until Fusion's page framework (Oracle ADF) has finished its round trip to the server. Fusion keeps
90
+ * background requests going, so "network idle" never comes; ADF's own flag is the reliable signal. */
91
+ async settle(extraMs = 800) {
92
+ await this.page.waitForLoadState('domcontentloaded').catch(() => {});
93
+ await this.page.waitForFunction(() => {
94
+ const adf = (window as unknown as { AdfPage?: { PAGE?: { isSynchronizedWithServer?: () => boolean } } }).AdfPage;
95
+ return !adf?.PAGE?.isSynchronizedWithServer || adf.PAGE.isSynchronizedWithServer();
96
+ }, undefined, { timeout: 60_000, polling: 250 }).catch(() => {});
97
+ await this.page.waitForTimeout(extraMs);
98
+ }
99
+
100
+ async signIn() {
101
+ const { baseUrl, username, password } = fusionEnv();
102
+ if (!baseUrl || !username || !password) throw new Error('FUSION_BASE_URL, FUSION_USERNAME and FUSION_PASSWORD must be set for a Fusion run');
103
+ if (await this.signedIn(baseUrl)) return;
104
+ await this.page.goto(`${baseUrl}/`, { waitUntil: 'domcontentloaded' });
105
+ const user = this.page.locator('[id="idcs-signin-basic-signin-form-username|input"]');
106
+ const pass = this.page.locator('[id="idcs-signin-basic-signin-form-password|input"]');
107
+ await user.fill(username);
108
+ await pass.waitFor();
109
+ // The password must never reach a report, trace or log. Playwright records every action's arguments (so no
110
+ // fill(password)), its trace snapshots record input values even of password fields, and its network log records
111
+ // the sign-in request body. So the trace is stopped (and what it held discarded) until the user is signed in, then
112
+ // started afresh; and the page fetches the password itself through a binding (no action argument carries it).
113
+ const tracing = this.page.context().tracing;
114
+ const paused = await tracing.stop().then(() => true, () => false);
115
+ try {
116
+ await this.page.exposeBinding('__fptSignInSecret', () => fusionEnv().password).catch(() => {});
117
+ await pass.evaluate(async (el: HTMLInputElement) => {
118
+ const v = await (window as unknown as { __fptSignInSecret: () => Promise<string> }).__fptSignInSecret();
119
+ el.focus();
120
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(el, v);
121
+ el.dispatchEvent(new Event('input', { bubbles: true }));
122
+ el.dispatchEvent(new Event('change', { bubbles: true }));
123
+ });
124
+ await pass.press('Enter');
125
+ // the address is the sign of arrival: the home page's "load" can hang on a slow background resource
126
+ await this.page.waitForURL(/AtkHomePageWelcome|FuseWelcome/, { timeout: 120_000, waitUntil: 'commit' });
127
+ await this.settle();
128
+ } finally {
129
+ if (paused) await tracing.start({ screenshots: true, snapshots: true, sources: true, title: 'after sign-in' }).catch(() => {});
130
+ }
131
+ }
132
+
133
+ /** The browser already holds a good session: the run signed in once before its tests (playwright.fusion.config.ts,
134
+ * src/fusion/session.ts), or an earlier step did. The home page then opens without the sign-in page, and signing in
135
+ * again (20-60 s per test) is skipped. An expired session shows the sign-in page, and the caller signs in. */
136
+ private async signedIn(baseUrl: string): Promise<boolean> {
137
+ const host = new URL(baseUrl).hostname;
138
+ if (!(await this.page.context().cookies(baseUrl).catch(() => [])).length) return false;
139
+ await this.page.goto(`${baseUrl}/fscmUI/faces/AtkHomePageWelcome`, { waitUntil: 'domcontentloaded' }).catch(() => {});
140
+ await this.settle(1000);
141
+ const url = new URL(this.page.url());
142
+ const signInPage = await this.page.locator('[id="idcs-signin-basic-signin-form-username|input"]').isVisible().catch(() => false);
143
+ return url.hostname === host && /AtkHomePageWelcome|FuseWelcome/.test(url.pathname) && !signInPage;
144
+ }
145
+
146
+ /** The work area last opened ("Group > Page"): a task of the same work area is opened from its Tasks list without
147
+ * going back through the home page. Cleared whenever the browser goes home. */
148
+ private workArea: string | null = null;
149
+
150
+ /** Navigator-style path: a work area link on the springboard, then a page, then a task from the Tasks panel.
151
+ * Fusion occasionally serves a blank page mid-navigation; the whole path is then walked once more from the home page. */
152
+ async openTask(area: string, page: string, task: string) {
153
+ for (let attempt = 1; ; attempt++) {
154
+ try {
155
+ const here = attempt === 1 && this.workArea === `${area} > ${page}`
156
+ && await this.page.locator('[id$="_FndTasksList::disAcr"], [id$="_FndTasksList"]').filter({ visible: true }).first().isVisible().catch(() => false);
157
+ if (!here) await this.openWorkArea(area, page);
158
+ const inList = await this.openTasksPanel().then(() => this.tasksRegion().getByRole('link', { name: task, exact: true }).first(), () => null);
159
+ if (inList && await inList.isVisible().catch(() => false)) await inList.click({ timeout: attempt === 1 ? 45_000 : undefined });
160
+ else await this.press(await this.target(task), attempt === 1 ? 45_000 : undefined); // an action on the page itself
161
+ await this.settle(8000);
162
+ await this.expectTitle(task);
163
+ await this.answerOrganizationPrompt();
164
+ return;
165
+ } catch (e) {
166
+ if (attempt >= 2) throw e;
167
+ }
168
+ }
169
+ }
170
+
171
+ /** Open a quick action of a home page group ("Group > Action", e.g. Receivables > Create Transaction): the entries
172
+ * Fusion shows under a group on the springboard that open a task directly. */
173
+ async openQuickAction(group: string, action: string) {
174
+ for (let attempt = 1; ; attempt++) {
175
+ try {
176
+ await this.openGroup(group);
177
+ await this.press(await this.target(action), attempt === 1 ? 45_000 : undefined);
178
+ await this.settle(8000);
179
+ await this.expectTitle(action);
180
+ await this.answerOrganizationPrompt();
181
+ return;
182
+ } catch (e) {
183
+ if (attempt >= 2) throw e;
184
+ }
185
+ }
186
+ }
187
+
188
+ /** Inventory tasks first ask which inventory organization to work in (one Organization field on an otherwise empty
189
+ * page). The pod's own organization (test data {{pod.inv.organization}}, discovered by the scout) answers it, then
190
+ * the task's real form opens. Nothing happens on any other page, or when the pod offers no organization. */
191
+ async answerOrganizationPrompt() {
192
+ const org = this.field('Organization');
193
+ if (!(await org.isVisible().catch(() => false))) return;
194
+ const inputs = await this.page.locator('input:visible, select:visible, textarea:visible').count().catch(() => 0);
195
+ if (inputs > 3 || (await org.inputValue().catch(() => 'x')) !== '') return; // a real form that has an Organization field
196
+ let code = '';
197
+ try { code = podValue('INV', 'organization'); } catch { return; }
198
+ await this.fill(org, code);
199
+ // the pop-up's OK is not always a standard button: the same visible-target lookup as everywhere else
200
+ for (const name of ['OK', 'Continue', 'Done']) {
201
+ const go = await this.target(name);
202
+ if (await go.isVisible().catch(() => false)) { await this.press(go); break; }
203
+ }
204
+ await this.settle(6000);
205
+ if (await this.field('Organization').isVisible().catch(() => false)
206
+ && (await this.page.locator('input:visible, select:visible, textarea:visible').count().catch(() => 0)) <= 3) {
207
+ throw new Error(`the test user may not work in inventory organization "${code}" (Fusion keeps asking for it; its list is `
208
+ + 'empty for this user): give the test user inventory organization access, or set another organization in Test data');
209
+ }
210
+ }
211
+
212
+ /** Open a task by its path: "Group > Page > Task" (a work area's Tasks list) or "Group > Action" (a quick action). */
213
+ async openPath(path: string) {
214
+ const parts = path.split('>').map((x) => x.trim()).filter(Boolean);
215
+ if (parts.length === 3) return this.openTask(parts[0], parts[1], parts[2]);
216
+ if (parts.length === 2) return this.openQuickAction(parts[0], parts[1]);
217
+ throw new Error(`a task is opened as "Group > Page > Task" or "Group > Action", got "${path}"`);
218
+ }
219
+
220
+ /** The task is open: the page title names it ("Create Invoice - Oracle Fusion ...", "Invoice Workbench - Create
221
+ * Recurring Invoices - ..."), or a dialog named after it is showing (Create Order opens a dialog over the work area,
222
+ * and the page title stays the work area's). */
223
+ async expectTitle(task: string) {
224
+ const title = new RegExp(`(^|[-–:|]\\s*)${esc(task)}\\b`, 'i');
225
+ const dialog = this.page.getByRole('dialog').filter({ hasText: new RegExp(`^\\s*${esc(task)}\\b`, 'i') }).filter({ visible: true });
226
+ await expect.poll(async () => title.test(await this.page.title()) || (await dialog.count()) > 0,
227
+ { message: `"${task}" should open (its page or its dialog)`, timeout: 60_000 }).toBe(true);
228
+ }
229
+
230
+ /** The Tasks list of a work area: the panel region whose id ends "_FndTasksList" (its tab: "..._FndTasksList::disAcr").
231
+ * The work area's own name sits in different places ("..._JournalEntryPage_itemNode_FndTasksList",
232
+ * "..._itemNode_InvoiceWorkbench_FndTasksList"); the ending is Fusion's. */
233
+ tasksRegion(): Locator {
234
+ return this.page.locator('[id$="_FndTasksList"]').filter({ visible: true }).first();
235
+ }
236
+
237
+ /** Open the work area's Tasks list unless it is open already (Fusion keeps it open within a session, and clicking its
238
+ * tab again would close it). */
239
+ async openTasksPanel() {
240
+ if (await this.tasksRegion().isVisible().catch(() => false)) return;
241
+ await this.page.locator('[id$="_FndTasksList::disAcr"]').or(this.page.locator('div[title="Item: Tasks"]')).filter({ visible: true }).first().click();
242
+ await this.settle(2500);
243
+ await this.tasksRegion().waitFor({ timeout: 30_000 });
244
+ }
245
+
246
+ /** The task names in the open work area's Tasks list. */
247
+ async taskNames(): Promise<string[]> {
248
+ try {
249
+ await this.openTasksPanel();
250
+ const names = await this.tasksRegion().locator('a').evaluateAll((els) => els
251
+ .filter((e) => (e as HTMLElement).getBoundingClientRect().width > 0)
252
+ .map((e) => ((e as HTMLElement).innerText || '').replace(/\s+/g, ' ').trim()).filter((t) => t && t.length <= 80));
253
+ if (names.length) return Array.from(new Set(names));
254
+ } catch { /* no Tasks list on this work area: its actions are on the page */ }
255
+ return this.pageActions();
256
+ }
257
+
258
+ /** The actions a work area shows on the page itself (Expenses: Create Expense Report; Inventory Management:
259
+ * Create Miscellaneous Transaction; Redwood pages): visible links and buttons named like a task, outside the
260
+ * global header. Used when the work area has no Tasks list. */
261
+ async pageActions(): Promise<string[]> {
262
+ const names = await this.page.locator('a, button, [role="button"], [role="link"], oj-button, oj-c-button').evaluateAll((els) => els
263
+ .filter((e) => (e as HTMLElement).getBoundingClientRect().width > 0 && !e.closest('[role="banner"], header, [id^="pt1:_UIS"]'))
264
+ .map((e) => ((e as HTMLElement).innerText || e.getAttribute('aria-label') || e.getAttribute('label') || '').replace(/\s+/g, ' ').trim())
265
+ .filter((t) => t && t.length <= 60 && /^(create|manage|enter|submit|record|add|new|transfer|receive|review|view|search)\b/i.test(t)));
266
+ return Array.from(new Set(names));
267
+ }
268
+
269
+ /** The groups of the home page springboard (Fusion's "groupNode_..." entries), by name. */
270
+ async groupsOnHome(): Promise<string[]> {
271
+ await this.goHome();
272
+ const names = await this.page.locator('a[id^="groupNode_"]').evaluateAll((els) => els
273
+ .filter((e) => (e as HTMLElement).getBoundingClientRect().width > 0)
274
+ .map((e) => ((e as HTMLElement).innerText || e.getAttribute('title') || '').replace(/\s+/g, ' ').trim()).filter(Boolean));
275
+ return Array.from(new Set(names));
276
+ }
277
+
278
+ /** Open a home page group; returns every name visible afterwards (its pages and quick actions among them). */
279
+ async openGroup(group: string): Promise<string[]> {
280
+ await this.goHome();
281
+ // the springboard draws its groups after the page loads: wait for them before looking for this one
282
+ await this.page.locator('a[id^="groupNode_"]').first().waitFor({ timeout: 60_000 }).catch(() => {});
283
+ const g = this.page.locator('a[id^="groupNode_"]').filter({ hasText: new RegExp(`^\\s*${esc(group)}\\s*$`) })
284
+ .filter({ visible: true }).first();
285
+ await this.press((await g.count()) ? g : await this.target(group));
286
+ await this.settle(3000);
287
+ return this.visibleNames(250);
288
+ }
289
+
290
+ /** Click an element the way a user would. The springboard is a sideways strip of groups: one on another part of the
291
+ * strip sits outside the window (x < 0), where a click at its position cannot land, so it gets the element's own
292
+ * click instead (Fusion handles it the same way). */
293
+ async press(el: Locator, timeout?: number) {
294
+ const box = await el.boundingBox().catch(() => null);
295
+ const vp = this.page.viewportSize() ?? { width: 1440, height: 900 };
296
+ if (box && (box.x < 0 || box.y < 0 || box.x + box.width > vp.width || box.y + box.height > vp.height)) {
297
+ await el.evaluate((e) => (e as HTMLElement).click());
298
+ } else {
299
+ await el.click(timeout ? { timeout } : undefined);
300
+ }
301
+ }
302
+
303
+ /** Close what a previous task left open (its dialog), with the dialog's own Cancel / Close / OK. Nothing is saved. */
304
+ async closeDialogs() {
305
+ for (let i = 0; i < 3; i++) {
306
+ const d = this.page.getByRole('dialog').filter({ visible: true }).first();
307
+ if (!(await d.isVisible().catch(() => false))) return;
308
+ const b = d.getByRole('button', { name: /^(Cancel|Close|OK|No)$/ }).filter({ visible: true }).first();
309
+ if (await b.isVisible().catch(() => false)) await b.click().catch(() => {});
310
+ else await this.page.keyboard.press('Escape').catch(() => {});
311
+ await this.settle(1500);
312
+ }
313
+ }
314
+
315
+ /** The home page with its springboard of groups. Work areas share the address "/faces/FuseWelcome" and reloading it
316
+ * reopens the last work area, so home is "/faces/AtkHomePageWelcome" (where sign-in lands), else the Home link. */
317
+ async goHome() {
318
+ this.workArea = null;
319
+ const base = fusionEnv().baseUrl;
320
+ await this.page.goto(`${base}/fscmUI/faces/AtkHomePageWelcome`, { waitUntil: 'domcontentloaded' }).catch(() => {});
321
+ await this.settle(4000);
322
+ await this.closeDialogs(); // a dialog a previous task left open would cover the springboard
323
+ const groups = this.page.locator('a[id^="groupNode_"]').filter({ visible: true });
324
+ if (await groups.first().isVisible().catch(() => false)) return;
325
+ const homeLink = this.page.getByRole('link', { name: 'Home', exact: true }).filter({ visible: true }).first();
326
+ if (await homeLink.isVisible().catch(() => false)) {
327
+ await homeLink.click();
328
+ await this.settle(4000);
329
+ } else {
330
+ await this.page.goto(`${base}/fscmUI/faces/FuseWelcome`, { waitUntil: 'domcontentloaded' });
331
+ await this.settle(4000);
332
+ }
333
+ }
334
+
335
+ /** Open a work area ("Group > Page"): from the home page's springboard, as a user does; through Fusion's Navigator
336
+ * menu when the springboard does not show the group (pods and roles differ in what the home page offers). */
337
+ async openWorkArea(group: string, pageName: string) {
338
+ const shown = await this.openGroup(group).catch(() => [] as string[]);
339
+ if (shown.length) {
340
+ // the group's work area entries are Fusion's "itemNode_..." elements; any visible target otherwise
341
+ const item = this.page.locator('a[id^="itemNode_"]').filter({ hasText: new RegExp(`^\\s*${esc(pageName)}\\s*$`) }).filter({ visible: true }).first();
342
+ const p = (await item.count().catch(() => 0)) ? item : await this.target(pageName);
343
+ if (await p.isVisible().catch(() => false)) {
344
+ await this.press(p);
345
+ await this.settle(6000);
346
+ this.workArea = `${group} > ${pageName}`;
347
+ return;
348
+ }
349
+ }
350
+ await this.goHome();
351
+ await this.openNavigator();
352
+ const g = await this.target(group);
353
+ if (await g.isVisible().catch(() => false)) { await g.click(); await this.settle(1500); } // expand the group
354
+ await (await this.target(pageName)).click({ timeout: 30_000 });
355
+ await this.settle(6000);
356
+ this.workArea = `${group} > ${pageName}`;
357
+ }
358
+
359
+ /** The VISIBLE element a user would click for `name`: a link with exactly that name, else a button or menu entry,
360
+ * else that exact text. Fusion pages hold hidden copies of many links (collapsed menus, the Navigator, Favorites);
361
+ * the first match is often one of those, and clicking it only waits until it times out. Links come first so a
362
+ * heading with the same words is never clicked instead of the link. */
363
+ async target(name: string): Promise<Locator> {
364
+ const p = this.page;
365
+ const kinds = [p.getByRole('link', { name, exact: true }), p.getByRole('button', { name, exact: true }),
366
+ p.getByRole('menuitem', { name, exact: true }), p.getByText(name, { exact: true })];
367
+ for (const k of kinds) {
368
+ const v = k.filter({ visible: true });
369
+ if (await v.count().catch(() => 0)) return v.first();
370
+ }
371
+ return kinds[0].filter({ visible: true }).first(); // none visible yet: wait for the link (the caller's timeout)
372
+ }
373
+
374
+ /** The names of the visible links and buttons of the page (labels only): what a pod offers where a name was not found. */
375
+ async visibleNames(limit = 80): Promise<string[]> {
376
+ const names = await this.page.locator('a, [role="link"], [role="button"], [role="menuitem"]').evaluateAll((els) => els
377
+ .filter((e) => (e as HTMLElement).getBoundingClientRect().width > 0)
378
+ .map((e) => ((e as HTMLElement).innerText || e.getAttribute('title') || e.getAttribute('aria-label') || '').replace(/\s+/g, ' ').trim())
379
+ .filter((t) => t && t.length <= 60 && !/https?:|www\./i.test(t))).catch(() => [] as string[]);
380
+ return Array.from(new Set(names)).slice(0, limit);
381
+ }
382
+
383
+ /** Fusion's Navigator: the menu of every work area the user may open. */
384
+ async openNavigator() {
385
+ await this.page.getByRole('link', { name: 'Navigator' }).or(this.page.getByRole('button', { name: 'Navigator' })).first().click({ timeout: 20_000 });
386
+ await this.settle(2000);
387
+ }
388
+
389
+ /** A form field by its visible label; Fusion adds "(Required)" to the label of required fields. */
390
+ field(label: string): Locator {
391
+ // the visible one: Fusion pages keep hidden copies of many fields, and the first match is often one of those
392
+ return this.page.getByLabel(new RegExp(`^\\s*${label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(\\s*\\(Required\\))?\\s*$`))
393
+ .filter({ visible: true }).first();
394
+ }
395
+
396
+ /** Type a value (or choose it in a drop-down list) and leave the field, so Fusion runs its own logic (look-ups,
397
+ * defaults) as it does for a user. */
398
+ async put(label: string, value: string) {
399
+ const was = dateFormat();
400
+ try {
401
+ await this.fill(this.field(label), value, label);
402
+ } catch (e) {
403
+ // a date Fusion refused: the user's date format comes from the field's hint, then from the dates Fusion shows on
404
+ // this page, else the common formats are tried in turn; the first one Fusion takes is kept for the run
405
+ if (!(e instanceof ValueRefused) || !parseDate(value, was)) throw e;
406
+ const hint = await this.field(label).evaluate((el) => {
407
+ const i = el as HTMLInputElement;
408
+ const described = (i.getAttribute('aria-describedby') || '').split(/\s+/).filter(Boolean)
409
+ .map((id) => document.getElementById(id)?.textContent || '');
410
+ return [i.placeholder, i.title, ...described].filter(Boolean).join(' ');
411
+ }).catch(() => '');
412
+ const seen = await this.page.locator('input').evaluateAll((els) => els.map((el) => (el as HTMLInputElement).value || ''));
413
+ const candidates = [formatFromHint(hint, podToday()), inferDateFormat(seen.filter((v) => v.trim() && v.trim() !== value.trim()), podToday()),
414
+ ...FALLBACK_FORMATS].filter((f, i, all): f is string => !!f && f !== was && all.indexOf(f) === i);
415
+ let last: unknown = e;
416
+ for (const fmt of candidates.slice(0, 6)) {
417
+ const typed = reformat(value, was, fmt);
418
+ try {
419
+ await this.fill(this.field(label), typed, label);
420
+ setDateFormat(fmt);
421
+ console.log(`[dates] this pod's user writes dates as ${fmt} (Fusion refused ${value}); typed ${typed}`);
422
+ return;
423
+ } catch (e2) {
424
+ if (!(e2 instanceof ValueRefused)) throw e2;
425
+ last = e2;
426
+ }
427
+ }
428
+ throw last;
429
+ }
430
+ }
431
+
432
+ async value(label: string): Promise<string> {
433
+ return (await this.field(label).inputValue().catch(() => '')).trim();
434
+ }
435
+
436
+ async expectFilled(label: string) {
437
+ await expect.poll(() => this.value(label), { message: `${label} should be filled in by Fusion`, timeout: 30_000 }).not.toBe('');
438
+ }
439
+
440
+ /** Invoice header as a Payables user types it: business unit, supplier (Fusion fills site, legal entity, terms),
441
+ * then number, amount and date. The date goes in before any line exists, so Fusion does not ask about line dates. */
442
+ async enterInvoiceHeader(h: { businessUnit: string; supplier: string; number: string; amount: string; date?: string }) {
443
+ await this.put('Business Unit', h.businessUnit);
444
+ await this.put('Supplier', h.supplier);
445
+ await this.expectFilled('Supplier Site');
446
+ await this.chooseCurrencyIfEmpty();
447
+ await this.put('Number', h.number);
448
+ await this.put('Amount', h.amount);
449
+ await this.put('Date', h.date || fusionDate());
450
+ }
451
+
452
+ /** A business unit without a default currency leaves Invoice Currency empty, and Fusion then refuses the lines ("the
453
+ * invoice header is incomplete"). Choose the pod's own invoice currency (its records' most used); nothing to do when
454
+ * Fusion filled it, or when the screen has no such list. */
455
+ async chooseCurrencyIfEmpty() {
456
+ const list = this.page.getByLabel(/^\s*Invoice Currency(\s*\(Required\))?\s*$/).first();
457
+ if (!(await list.count()) || (await list.evaluate((e) => e.tagName).catch(() => '')) !== 'SELECT') return;
458
+ if (await list.evaluate((e) => (e as HTMLSelectElement).value !== '' && (e as HTMLSelectElement).selectedIndex > 0).catch(() => true)) return;
459
+ const code = podCandidates('AP', 'currency')[0];
460
+ if (!code) throw new Error('Invoice Currency is empty for this business unit and the pod has no currency in its records: set it on the Test environments page (Test data).');
461
+ const label = await list.evaluate((e, c) => Array.from((e as HTMLSelectElement).options).map((o) => o.text).find((t) => t === c || t.startsWith(`${c} `)) ?? '', code);
462
+ if (!label) throw new Error(`Invoice Currency is empty for this business unit and Fusion does not offer the pod's currency "${code}".`);
463
+ await list.selectOption({ label });
464
+ await this.settle(1500);
465
+ }
466
+
467
+ /** Open a collapsed region of the page (e.g. "Lines") if it is not open yet. */
468
+ async expandSection(name: string) {
469
+ const expand = this.page.locator(`a[title="Expand ${name}"]`);
470
+ if (await expand.count()) { await expand.first().click(); await this.settle(3000); }
471
+ await expect(this.page.locator(`a[title="Collapse ${name}"]`).first()).toBeVisible();
472
+ }
473
+
474
+ /** One row of the invoice Lines table. Up to 26C Fusion names each row "Select Row <n> <n> ..."; from 26D each line
475
+ * is a nested table in table "Invoice Lines" whose first cell is the line number. */
476
+ lineRow(n: number): Locator {
477
+ const named = this.page.getByRole('row', { name: new RegExp(`^Select Row ${n} ${n} `) });
478
+ const nested = this.page.getByRole('table', { name: 'Invoice Lines' }).getByRole('row')
479
+ .filter({ has: this.page.getByRole('cell', { name: String(n), exact: true }) });
480
+ return named.or(nested).first();
481
+ }
482
+
483
+ /** Fill invoice line n (1-based) in the Lines table: type, amount and the distribution combination. Fusion offers
484
+ * empty rows; the next row only becomes editable after the previous one (26D shows it read-only, without inputs),
485
+ * so lines are added in order. Input names: "Amount: <n>" up to 26C, "Amount" from 26D. */
486
+ async addLine(n: number, line: InvoiceLine) {
487
+ await this.expandSection('Lines');
488
+ const row = this.lineRow(n);
489
+ const amount = row.getByRole('textbox', { name: new RegExp(`^Amount(: ${n})?$`) }).first();
490
+ if (!(await amount.count()) || await amount.isDisabled()) {
491
+ await this.page.getByRole('button', { name: 'Add Row' }).or(this.page.getByRole('img', { name: 'Add Row', exact: true })).first().click();
492
+ await this.settle(2000);
493
+ }
494
+ if (line.type && line.type !== 'Item') {
495
+ await row.getByRole('combobox', { name: new RegExp(`^Type(: ${n})?$`) }).first().selectOption({ label: line.type });
496
+ await this.settle();
497
+ }
498
+ await amount.click(); await amount.fill(line.amount); await amount.press('Tab'); await this.settle(1500);
499
+ const account = row.getByRole('textbox', { name: 'Distribution Combination ID' });
500
+ await account.click(); await account.fill(line.account); await account.press('Tab'); await this.settle(2500);
501
+ await expect(account).toHaveValue(line.account);
502
+ }
503
+
504
+ /** Texts of the message windows Fusion shows (warnings, errors, confirmations), whitespace collapsed. */
505
+ async dialogs(): Promise<string[]> {
506
+ const d = this.page.getByRole('dialog');
507
+ const out: string[] = [];
508
+ for (let i = 0; i < await d.count(); i++) {
509
+ if (!(await d.nth(i).isVisible().catch(() => false))) continue;
510
+ const t = (await d.nth(i).innerText().catch(() => '')).replace(/\s+/g, ' ').replace('Click here to exit this popup.', '').trim();
511
+ if (t) out.push(t);
512
+ }
513
+ return out;
514
+ }
515
+
516
+ /** Answer the open Fusion message window with one of its buttons (OK by default). */
517
+ async answerDialog(button = 'OK') {
518
+ await this.page.getByRole('dialog').getByRole('button', { name: button, exact: true }).first().click();
519
+ await this.settle(2000);
520
+ }
521
+
522
+ /** Press the page's Save button; returns what Fusion said in message windows (empty when it saved quietly). */
523
+ async save(): Promise<string[]> {
524
+ await this.page.getByRole('button', { name: 'Save', exact: true }).first().click();
525
+ await this.settle(4000);
526
+ return this.dialogs();
527
+ }
528
+
529
+ /** Run an entry of the Invoice Actions menu (Validate, Cancel Invoice, Manage Holds, ...). */
530
+ async invoiceAction(name: string) {
531
+ await this.menuAction('Invoice Actions', name);
532
+ }
533
+
534
+ /** Press a button, link or menu entry, failing at once (with the reason) when Fusion shows it disabled: an action
535
+ * that needs a row selected or other fields filled first is greyed out, and waiting for it only times out. */
536
+ async pressEnabled(el: Locator, what: string) {
537
+ await el.waitFor({ state: 'visible', timeout: 30_000 });
538
+ const off = (await el.getAttribute('aria-disabled').catch(() => null)) === 'true' || await el.isDisabled().catch(() => false);
539
+ if (off) {
540
+ throw new Error(`"${what}" is disabled on the screen at this point: Fusion enables it only once what it needs is done ` +
541
+ '(a row selected, or the fields it depends on filled)');
542
+ }
543
+ await this.press(el);
544
+ }
545
+
546
+ /** The choices a list field offers this user (up to `max`), read the way a user sees them: a drop-down's entries, or
547
+ * the rows a list of values shows on the down arrow. Read-only: the list is closed again and nothing is chosen. */
548
+ async listChoices(label: string, max = 5): Promise<string[]> {
549
+ const f = this.field(label);
550
+ if (!(await f.isVisible().catch(() => false))) return [];
551
+ const select = (await f.evaluate((e) => e.tagName).catch(() => '')) === 'SELECT' ? f
552
+ : f.locator('select:visible').first();
553
+ if (await select.count().catch(() => 0)) {
554
+ return (await select.evaluate((e) => Array.from((e as HTMLSelectElement).options).map((o) => o.label.trim())).catch(() => [] as string[]))
555
+ .filter((t) => t && !/^(-+|select|none)$/i.test(t)).slice(0, max);
556
+ }
557
+ // what the page shows before the list opens: the page's own tables (a transaction's lines) must not be mistaken
558
+ // for the list. Each item: its text, and for a table row the first cell after Fusion's unseen "Select Row" cell
559
+ const items = () => this.page.locator('tr:visible, [role="option"]:visible, li:visible').evaluateAll((els) => els.map((e) => {
560
+ const text = ((e as HTMLElement).innerText || '').replace(/\s+/g, ' ').trim();
561
+ // a list of values' row ("Select Row" + the value's columns), a search-select's row (role row: the value itself),
562
+ // or an option; any other table row (a container of rows) is not a value
563
+ const first = e.tagName === 'TR' && /^Select Row/.test(text)
564
+ ? Array.from(e.querySelectorAll('td')).map((td) => ((td as HTMLElement).innerText || '').replace(/\s+/g, ' ').replace(/^\s*Select Row\s*/, '').trim())
565
+ .find((t) => t) || ''
566
+ : e.tagName === 'TR' ? (e.getAttribute('role') === 'row' ? text : '') : text;
567
+ return { text, value: first };
568
+ })).catch(() => [] as { text: string; value: string }[]);
569
+ const before = new Set((await items()).map((i) => i.text));
570
+ // a list of values (its input is the field) opens on the down arrow; a search-select (a box wrapping its input,
571
+ // Ledger, Accounting Period) opens on a click on the box
572
+ if ((await f.evaluate((e) => e.tagName).catch(() => '')) === 'INPUT') {
573
+ if (!(await f.isEditable().catch(() => false))) return [];
574
+ await f.click({ timeout: 5000 }).catch(() => {});
575
+ await this.page.keyboard.press('ArrowDown').catch(() => {});
576
+ } else {
577
+ await f.click({ timeout: 5000 }).catch(() => {});
578
+ }
579
+ await this.settle(2500);
580
+ // the user's recently used values come first, named "MRU Row <n> <value>" (an empty one: "... Empty Cell")
581
+ const got = (await items()).filter((i) => !before.has(i.text) && i.value).map((i) => i.value.replace(/^MRU Row \d+\s*/i, ''))
582
+ .filter((v) => v.length <= 120 && !/^(All|Empty Cell|Search\.*|More\.*|Previous|Next.*|No results.*)$/i.test(v) && !/\d+-\d+ of \d+/.test(v));
583
+ await this.page.keyboard.press('Escape').catch(() => {});
584
+ await this.settle(600);
585
+ await this.page.locator('body').click({ position: { x: 5, y: 5 } }).catch(() => {}); // a list still open covers the page
586
+ // a container entry repeats its entries' text: keep the single values
587
+ const uniq = Array.from(new Set(got));
588
+ return uniq.filter((v) => !uniq.some((o) => o !== v && v.includes(o) && v.length > o.length + 2)).slice(0, max);
589
+ }
590
+
591
+ /** Run an entry of any menu of the page (the screen inventory lists them: "Actions", "Invoice Actions", ...). */
592
+ async menuAction(menu: string, entry: string) {
593
+ const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
594
+ const opener = this.page.getByRole('button', { name: menu, exact: true }).or(this.page.getByText(menu, { exact: true }));
595
+ await opener.first().click();
596
+ await this.settle(1500);
597
+ await this.pressEnabled(this.page.getByRole('menuitem', { name: new RegExp(`^\\s*${esc(entry)}\\b`) }).first(), `${menu} > ${entry}`);
598
+ await this.settle(5000);
599
+ }
600
+
601
+ /** Add a row to the table of a section ("Lines", "Distributions", ...): opens the section if collapsed, then presses
602
+ * that table's Add Row (the only one on the page when the section cannot be told apart). */
603
+ async addRow(section: string) {
604
+ const expand = this.page.locator(`a[title="Expand ${section}"]`);
605
+ if (await expand.count()) { await expand.first().click(); await this.settle(3000); }
606
+ await this.refusedRow(section);
607
+ const add = this.page.getByRole('button', { name: /^(Add Row|Add|Create)$/ });
608
+ const region = this.page.locator('div, table, section').filter({ has: this.page.getByText(section, { exact: true }) }).filter({ has: add });
609
+ const target = (await region.count()) ? region.last().getByRole('button', { name: /^(Add Row|Add|Create)$/ }).first() : add.first();
610
+ await target.click({ timeout: 15_000 }).catch(async (e) => { await this.refusedRow(section); throw e; });
611
+ await this.settle(2500);
612
+ await this.refusedRow(section);
613
+ }
614
+
615
+ /** Fusion refuses a row in a message window when the header is not complete yet (opening the section is enough to
616
+ * bring it up): say why, and clear the window. */
617
+ private async refusedRow(section: string) {
618
+ const said = await this.dialogs();
619
+ if (!said.length) return;
620
+ await this.closeDialogs();
621
+ throw new Error(`Fusion would not add a row to ${section}: ${said[0].slice(0, 300)}`);
622
+ }
623
+
624
+ /** A field of a table row by its column label; Fusion names row cells "<Label>: <row>" or just "<Label>". The newest
625
+ * editable one is the row just added. */
626
+ rowField(label: string): Locator {
627
+ const esc = label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
628
+ // a table cell is named "<Label>: <row>": the newest editable one is the row just added (a header field with the
629
+ // same label, e.g. the invoice's own Amount, has no row number)
630
+ const inRow = this.page.getByLabel(new RegExp(`^\\s*${esc}(\\s*\\(Required\\))?:\\s*\\d+\\s*$`)).filter({ visible: true });
631
+ const any = this.page.getByLabel(new RegExp(`^\\s*${esc}(\\s*\\(Required\\))?(:\\s*\\d+)?\\s*$`)).filter({ visible: true });
632
+ // only a field that takes typing: a table's totals and display cells carry the same label (the lines' read-only
633
+ // "Amount" total), and the last match on the page is often one of those
634
+ const typable = this.page.locator('input:not([readonly]):not([disabled]):not([type="hidden"]), textarea:not([readonly]):not([disabled]), select:not([disabled])');
635
+ const open = (l: Locator) => l.and(typable).or(l.filter({ has: typable }));
636
+ return open(inRow).or(open(any)).last();
637
+ }
638
+
639
+ /** Type or choose a value in a table row's field, then leave it so Fusion runs its own logic. */
640
+ async putInRow(label: string, value: string) {
641
+ await this.fill(this.rowField(label), value, label);
642
+ }
643
+
644
+ /** Fill a field the way a user does: a drop-down list is chosen by its visible label, anything else is typed. */
645
+ async fill(f: Locator, value: string, label?: string) {
646
+ // a field the screen does not offer right now: say why it may be missing at once, not after a long timeout
647
+ if (!(await f.waitFor({ state: 'visible', timeout: 20_000 }).then(() => true, () => false))) {
648
+ const name = label || 'the field';
649
+ const asText = label ? await this.page.getByText(new RegExp(`^\\s*${esc(label)}\\s*$`)).filter({ visible: true }).count().catch(() => 0) : 0;
650
+ throw new Error(asText
651
+ ? `"${name}" is shown as fixed text, not as a field to fill: Fusion set it already (often the only value this user has); leave it to Fusion`
652
+ : `"${name}" is not on the screen at this point: it may be in a closed section, appear only after another field is filled, or not be offered to this user`);
653
+ }
654
+ // a label may name the control's container (a list of values): type into the field inside it
655
+ const tag = await f.evaluate((e) => e.tagName).catch(() => '');
656
+ if (tag && !['INPUT', 'SELECT', 'TEXTAREA'].includes(tag)) {
657
+ const inner = f.locator('input:visible, select:visible, textarea:visible').first();
658
+ if (await inner.count().catch(() => 0)) f = inner;
659
+ }
660
+ // a field Fusion keeps read-only until the fields it depends on are set (a transaction's dates wait for its
661
+ // business unit): fail at once with the reason, not after a click timeout
662
+ let editable = false;
663
+ for (let i = 0; i < 20 && !(editable = await f.isEditable().catch(() => false)); i++) await this.page.waitForTimeout(500);
664
+ if (!editable) {
665
+ const name = (await f.getAttribute('aria-label').catch(() => null)) || (await f.getAttribute('title').catch(() => null)) || 'this field';
666
+ throw new Error(`"${name.trim()}" is read-only on the screen at this point: Fusion opens it only once the fields it depends on are filled (fill those first, or leave it to Fusion)`);
667
+ }
668
+ if ((await f.evaluate((e) => e.tagName).catch(() => '')) === 'SELECT') {
669
+ await f.selectOption({ index: await this.optionIndex(f, value) });
670
+ await this.settle();
671
+ return;
672
+ }
673
+ const before = new Set(await this.messages());
674
+ await f.click();
675
+ await f.fill(value);
676
+ // a list field shows its matching entries as you type: pick the one that is exactly the value, as a user does
677
+ // (a search-select takes nothing on Tab alone); a plain field, or a list showing no such entry, takes Tab
678
+ if (await this.pickSuggestion(value)) await this.settle();
679
+ else {
680
+ await f.press('Tab');
681
+ await this.settle();
682
+ }
683
+ // a list of values that has no such entry for this user marks the field invalid or says so in a message
684
+ // ... or Fusion takes it and then says it cannot be used here (a business unit whose ledger has no open period)
685
+ const said = (await this.messages()).filter((m) => !before.has(m)
686
+ && (/not valid|isn.t valid|no match|invalid|does not exist|doesn.t exist|no results/i.test(m) || /^\s*Error\b/.test(m)
687
+ // a list of values with no such entry opens its search window instead of taking the text
688
+ || /^\s*Search and Select\b/.test(m)));
689
+ // Fusion marks a value it does not know with an error style on the field and an "Error:<label>" icon beside it
690
+ // (no message, no aria-invalid): looked for only within the field's own box, never a neighbour's
691
+ const invalid = (await f.getAttribute('aria-invalid').catch(() => null)) === 'true' || await f.evaluate((e) => {
692
+ if (e.closest('.p_AFError')) return true;
693
+ let box: Element | null = e.parentElement;
694
+ for (let i = 0; i < 6 && box && box.querySelectorAll('input, select, textarea').length < 2; i++) {
695
+ if (box.querySelector('img[title^="Error"]')) return true;
696
+ box = box.parentElement;
697
+ }
698
+ return false;
699
+ }).catch(() => false);
700
+ if (said.length || invalid) {
701
+ // left as it is: emptying a required field only adds a "required" error; the next value is typed over it
702
+ await this.page.keyboard.press('Escape').catch(() => {});
703
+ await this.closeDialogs();
704
+ await this.settle(800);
705
+ throw new ValueRefused(`Fusion did not accept "${value}" in "${label || 'the field'}"${said.length ? `: ${said[0].slice(0, 200)}` : ''}`);
706
+ }
707
+ }
708
+
709
+ /** Click the suggestion that is exactly `value` in the list a field opened while typing (a search-select's rows, or
710
+ * a list of values' "Select Row" rows). False when no such entry shows within a few seconds. */
711
+ private async pickSuggestion(value: string): Promise<boolean> {
712
+ const exact = new RegExp(`^\\s*${esc(value)}\\s*$`, 'i');
713
+ const row = this.page.locator('[role="row"], [role="option"]').filter({ hasText: exact }).filter({ visible: true })
714
+ .or(this.page.locator('tr').filter({ hasText: /^\s*Select Row/ }).locator('td').filter({ hasText: exact }).filter({ visible: true }));
715
+ for (let i = 0; i < 8; i++) {
716
+ if (await row.first().isVisible().catch(() => false)) {
717
+ await row.first().click().catch(() => {});
718
+ return true;
719
+ }
720
+ await this.page.waitForTimeout(400);
721
+ }
722
+ return false;
723
+ }
724
+
725
+ /** Which entry of a drop-down list means `value`: the label exactly, else the option's value, else the one label
726
+ * holding it as a whole word (a pod's records hold codes like "USD" where the list shows "US Dollar (USD)"). */
727
+ async optionIndex(f: Locator, value: string): Promise<number> {
728
+ const read = () => f.evaluate((e) => Array.from((e as HTMLSelectElement).options).map((o) => ({ label: o.label.trim(), value: o.value })));
729
+ let opts = await read();
730
+ if (!opts.some((o) => o.label)) { // some lists are filled only when opened
731
+ await f.click().catch(() => {});
732
+ await this.settle(1500);
733
+ await this.page.keyboard.press('Escape').catch(() => {});
734
+ opts = await read();
735
+ }
736
+ if (!opts.some((o) => o.label)) {
737
+ throw new Error('the list is empty for this test user: Fusion offers no value here (the user may lack access to it, '
738
+ + "for example as a buyer of a business unit); this needs the user's access set up on the pod");
739
+ }
740
+ const want = value.trim().toLowerCase();
741
+ const word = new RegExp(`(^|[^a-z0-9])${want.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^a-z0-9]|$)`, 'i');
742
+ const i = [(o: { label: string }) => o.label.toLowerCase() === want, (o: { value: string }) => o.value.toLowerCase() === want,
743
+ (o: { label: string }) => word.test(o.label)].map((m) => opts.findIndex(m)).find((x) => x >= 0);
744
+ if (i === undefined) {
745
+ throw new ValueRefused(`"${value}" is not in the list (${opts.map((o) => o.label).filter(Boolean).slice(0, 12).join(', ')}): ` +
746
+ 'set the right value on the Test environments page (Test data)');
747
+ }
748
+ return i;
749
+ }
750
+
751
+ /** Fusion's messages: its message windows, and inline error notes on the page. */
752
+ async messages(): Promise<string[]> {
753
+ const inline = await this.page.locator('.af_message, [class*="message-text"], [id*="msgDlg"]').evaluateAll((els) => els
754
+ .filter((e) => (e as HTMLElement).getBoundingClientRect().width > 0)
755
+ .map((e) => ((e as HTMLElement).innerText || '').replace(/\s+/g, ' ').trim()).filter(Boolean)).catch(() => [] as string[]);
756
+ return [...await this.dialogs(), ...inline];
757
+ }
758
+
759
+ /** The page must not show an error (a message window or note naming an error). */
760
+ async expectNoError() {
761
+ const errs = (await this.messages()).filter((m) => /\berror\b/i.test(m));
762
+ if (errs.length) throw new Error(`Fusion showed an error: ${errs[0].slice(0, 300)}`);
763
+ }
764
+
765
+ /** Fusion must show a message containing `text` (a confirmation, warning or error), within 30 s. */
766
+ async expectMessage(text: string) {
767
+ const want = text.toLowerCase();
768
+ await expect.poll(async () => (await this.messages()).some((m) => m.toLowerCase().includes(want)),
769
+ { message: `Fusion should show a message with "${text}"`, timeout: 30_000 }).toBe(true);
770
+ }
771
+
772
+ /** A search on a Manage page found something: no "No results" note and at least one result row. */
773
+ async expectResults() {
774
+ await expect.poll(async () => {
775
+ const none = await this.page.getByText(/^(No results found\.?|No data to display\.?|No rows yet\.?)$/).filter({ visible: true }).count();
776
+ const rows = await this.page.getByRole('row').filter({ visible: true }).count();
777
+ return none === 0 && rows > 1;
778
+ }, { message: 'the search should find at least one result', timeout: 60_000 }).toBe(true);
779
+ }
780
+
781
+ /** A status shown on the page: an invoice's status link, or the status text of any other document. */
782
+ async expectStatusText(status: string) {
783
+ if ((INVOICE_STATUSES as readonly string[]).includes(status)) return this.expectStatus(status as (typeof INVOICE_STATUSES)[number]);
784
+ await expect(this.page.getByText(status, { exact: true }).filter({ visible: true }).first(),
785
+ { message: `the page should show the status ${status}` }).toBeVisible({ timeout: 60_000 });
786
+ }
787
+
788
+ /** The invoice status Fusion shows beside the page title (Not validated, Validated, Needs revalidation, Canceled). */
789
+ async statusOnPage(): Promise<string> {
790
+ const link = this.page.getByRole('link', { name: new RegExp(`^(${INVOICE_STATUSES.join('|')})$`) }).first();
791
+ return (await link.innerText({ timeout: 5_000 }).catch(() => '')).trim();
792
+ }
793
+
794
+ async expectStatus(status: (typeof INVOICE_STATUSES)[number]) {
795
+ await expect.poll(() => this.statusOnPage(), { message: `invoice status on the page should be ${status}`, timeout: 60_000 }).toBe(status);
796
+ }
797
+
798
+ /** Leave the page with Cancel, discarding anything not saved. */
799
+ async cancelPage() {
800
+ await this.page.getByRole('button', { name: 'Cancel', exact: true }).first().click();
801
+ await this.settle(3000);
802
+ const yes = this.page.getByRole('dialog').getByRole('button', { name: /^(Yes|OK)$/ });
803
+ if (await yes.count()) { await yes.first().click(); await this.settle(3000); }
804
+ }
805
+ }
coworker/platform/step_writer.py CHANGED
@@ -240,7 +240,7 @@ def check_steps(draft: StepsDraft | dict, inv: dict, intent_type: str = "happy",
240
  if a == "menu_action":
241
  entries = sc.menus.get(norm_label(s.field or ""))
242
  if entries is None:
243
- problems.append(f"step {i}: menu_action needs a menu of the screen as field ({', '.join(sc.inv.get('sc.menus') or {}) or 'no sc.menus'})")
244
  elif (s.value or "").strip() not in entries:
245
  problems.append(f"step {i}: '{s.value}' is not in the {s.field} menu ({', '.join(entries)})")
246
  if a in ("enter", "open_task", "click", "add_line", "invoice_action", "expect_status", "enter_in_row", "menu_action",
@@ -273,9 +273,10 @@ def check_steps(draft: StepsDraft | dict, inv: dict, intent_type: str = "happy",
273
  if a == "invoice_action" and s.value and s.value not in sc.actions_menu:
274
  problems.append(f"step {i}: '{s.value}' is not in the Invoice Actions menu ({', '.join(sc.actions_menu) or 'no such menu on this screen'})")
275
  if a == "click" and s.value and norm_label(s.value) not in sc.buttons:
276
- problems.append(f"step {i}: button '{s.value}' is not on the screen ({', '.join(sc.inv.get('sc.buttons') or [])})")
277
  if a == "enter" and s.field and norm_label(s.field) == "number":
278
- if re.search(r"\{\{\s*unique:[A-Za-z0-9]+\s*\}\}", s.value or ""):
 
279
  number_entered = True
280
  else:
281
  problems.append(f"step {i}: enter Number must use a {{{{unique:TAG}}}} placeholder so every run creates a new document")
 
240
  if a == "menu_action":
241
  entries = sc.menus.get(norm_label(s.field or ""))
242
  if entries is None:
243
+ problems.append(f"step {i}: menu_action needs a menu of the screen as field ({', '.join(sc.inv.get('menus') or {}) or 'no menus'})")
244
  elif (s.value or "").strip() not in entries:
245
  problems.append(f"step {i}: '{s.value}' is not in the {s.field} menu ({', '.join(entries)})")
246
  if a in ("enter", "open_task", "click", "add_line", "invoice_action", "expect_status", "enter_in_row", "menu_action",
 
273
  if a == "invoice_action" and s.value and s.value not in sc.actions_menu:
274
  problems.append(f"step {i}: '{s.value}' is not in the Invoice Actions menu ({', '.join(sc.actions_menu) or 'no such menu on this screen'})")
275
  if a == "click" and s.value and norm_label(s.value) not in sc.buttons:
276
+ problems.append(f"step {i}: button '{s.value}' is not on the screen ({', '.join(sc.inv.get('buttons') or [])})")
277
  if a == "enter" and s.field and norm_label(s.field) == "number":
278
+ # a new number, or (in a flow) the number of the document an earlier screen created, to find it again
279
+ if re.search(r"\{\{\s*(?:unique:[A-Za-z0-9]+|saved\.[A-Za-z_]\w*)\s*\}\}", s.value or ""):
280
  number_entered = True
281
  else:
282
  problems.append(f"step {i}: enter Number must use a {{{{unique:TAG}}}} placeholder so every run creates a new document")
coworker/tests/test_end_to_end_flows.py CHANGED
@@ -62,6 +62,20 @@ class TestFlowChecks(unittest.TestCase):
62
  early["steps"].insert(3, {"action": "enter", "field": "Supplier", "value": "{{saved.order}}"})
63
  self.assertTrue(any("used before a remember step" in p for p in self.check(early)))
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  def test_one_screen_scenarios_are_checked_as_before(self):
66
  single = {**FLOW, "steps": FLOW["steps"][:8] + [{"action": "expect_no_error"}]}
67
  self.assertEqual(step_writer.check_steps(single, ORDER), [])
 
62
  early["steps"].insert(3, {"action": "enter", "field": "Supplier", "value": "{{saved.order}}"})
63
  self.assertTrue(any("used before a remember step" in p for p in self.check(early)))
64
 
65
+ def test_a_later_screen_finds_the_document_by_its_saved_number(self):
66
+ search = {"task": "Payables > Manage Invoices", "captured_at": "x", "source": "captured", "sections": [],
67
+ "fields": [{"label": "Number", "kind": "text", "required": False}], "line_fields": [], "buttons": ["Search"],
68
+ "menus": {}, "tables": {}}
69
+ steps = [dict(s) for s in FLOW["steps"]]
70
+ steps.insert(15, {"action": "remember", "field": "Number", "name": "invoice"})
71
+ steps += [{"action": "open_task", "value": search["task"]}, {"action": "enter", "field": "Number", "value": "{{saved.invoice}}"},
72
+ {"action": "click", "value": "Search"}, {"action": "expect_no_error"}]
73
+ flow = {**FLOW, "steps": steps}
74
+ self.assertEqual(step_writer.check_steps(flow, ORDER, flow=[ORDER, INVOICE, search]), [])
75
+ typed = {**flow, "steps": [dict(s) for s in steps]}
76
+ typed["steps"][-3] = {"action": "enter", "field": "Number", "value": "INV-1"} # a fixed number still is refused
77
+ self.assertTrue(any("must use a {{unique:TAG}}" in p for p in step_writer.check_steps(typed, ORDER, flow=[ORDER, INVOICE, search])))
78
+
79
  def test_one_screen_scenarios_are_checked_as_before(self):
80
  single = {**FLOW, "steps": FLOW["steps"][:8] + [{"action": "expect_no_error"}]}
81
  self.assertEqual(step_writer.check_steps(single, ORDER), [])
deploy/runner/sync.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Puts this repo's committed automation/ and tests/ on a browser runner, so the runner runs the same scenarios and
3
+ # step code as the Astra server. Run it after every Astra deploy, from the repo, on the commit that was deployed:
4
+ # deploy/runner/sync.sh ubuntu@runner-host ~/.ssh/runner_key [https://runner.example.com]
5
+ # It refuses while the runner is busy (a test run would lose its browsers), keeps the previous copy as astra.prev,
6
+ # reuses node_modules when package-lock.json is unchanged, and restarts the runner service only at the end.
7
+ set -euo pipefail
8
+ HOST=${1:?ssh target, e.g. ubuntu@runner-host}
9
+ KEY=${2:?ssh private key file}
10
+ URL=${3:-}
11
+ SERVICE=${RUNNER_SERVICE:-astra-runner}
12
+ REV=$(git rev-parse --short=12 HEAD)
13
+ git diff --quiet HEAD -- automation tests || { echo "automation/ or tests/ has uncommitted changes: commit first" >&2; exit 1; }
14
+ SSH=(ssh -i "$KEY" -o BatchMode=yes "$HOST")
15
+
16
+ if "${SSH[@]}" "curl -s --max-time 10 http://127.0.0.1:\${RUNNER_PORT:-8899}/healthz" | grep -q '"busy": true'; then
17
+ echo "the runner is busy with a test run: try again when it ends" >&2
18
+ exit 2
19
+ fi
20
+
21
+ PKG=$(mktemp -t astra-runner.XXXXXX.tgz)
22
+ trap 'rm -f "$PKG"' EXIT
23
+ git archive --format=tar.gz -o "$PKG" HEAD automation tests
24
+ scp -q -i "$KEY" -o BatchMode=yes "$PKG" "$HOST:astra-sync.tgz"
25
+
26
+ "${SSH[@]}" bash -s -- "$REV" "$SERVICE" <<'REMOTE'
27
+ set -euo pipefail
28
+ REV=$1 SERVICE=$2
29
+ rm -rf ~/astra.new && mkdir ~/astra.new
30
+ tar -xzf ~/astra-sync.tgz -C ~/astra.new && rm -f ~/astra-sync.tgz
31
+ echo "$REV" > ~/astra.new/VERSION
32
+ cd ~/astra.new/automation
33
+ if [ -d ~/astra/automation/node_modules ] && cmp -s package-lock.json ~/astra/automation/package-lock.json; then
34
+ cp -a ~/astra/automation/node_modules .
35
+ else
36
+ npm ci --no-audit --no-fund --loglevel=error
37
+ fi
38
+ npx playwright install chromium >/dev/null
39
+ rm -rf ~/astra.prev
40
+ [ -d ~/astra ] && mv ~/astra ~/astra.prev
41
+ mv ~/astra.new ~/astra
42
+ sudo systemctl restart "$SERVICE"
43
+ sleep 3
44
+ curl -s http://127.0.0.1:${RUNNER_PORT:-8899}/healthz; echo
45
+ REMOTE
46
+
47
+ if [ -n "$URL" ]; then
48
+ echo "from outside: $(curl -s --max-time 20 "$URL/healthz")"
49
+ fi
50
+ echo "runner now on $REV"