@xeplr/ui-jobs 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -84,11 +84,11 @@ There is no embedded / standalone switch: `registerJobsUI()` returns `<Route>` e
84
84
  | `optionSources` | `{}` | where a kind of thing is listed, for action inputs with `optionsFrom` — see below |
85
85
  | `breadcrumb` | — | a component, rendered as `<Breadcrumb items={[{ label: 'Jobs' }]} />` above the page |
86
86
  | `uploadLink` | — | element or string, shown in the page footnote ("Loading a file into a table is recorded separately — see …"); without it the footnote says "the upload screen" |
87
- | `connectLink` | — | element shown in the header before **+ New job** — a link to a workflow canvas for chaining jobs. Passed in rather than imported, so this package does not depend on workflow (which already calls jobs over HTTP) |
87
+ | `chainsApiBase` | `null` | where the **workflow** API is mounted (e.g. `'/workflow'`). It keeps each job's "After this job" rules (`/job-chains/:jobId`), because jobs never start each other: the workflow engine does every hand-off. `null` (no workflow on the install) leaves the editor's **After this job** step out. HTTP only; this package does not import workflow |
88
88
 
89
89
  Returns `{ routes, path }`: one `<Route>` at `path`, and the path itself so your navigation does not retype it.
90
90
 
91
- `apiBase` and `optionSources` are module-level settings — the last `registerJobsUI()` call wins.
91
+ `apiBase`, `optionSources` and `chainsApiBase` are module-level settings — the last `registerJobsUI()` call wins.
92
92
 
93
93
  ## Requests
94
94
 
@@ -107,6 +107,7 @@ Every call goes through `authFetch`, which prefixes the base URL `@xeplr/ui-acco
107
107
  | pause / resume | `POST /jobs/:id/pause`, `POST /jobs/:id/resume` |
108
108
  | a run's log lines | `GET /logs?referenceId=<occurrenceId>` — **not** under `apiBase` |
109
109
  | an option list | `GET <source.url>?limit=0` — under `apiBase` |
110
+ | a job's "After this job" rules | `GET` / `PUT <chainsApiBase>/job-chains/:jobId` with `{ rules, jobName }` — **not** under `apiBase` |
110
111
 
111
112
  `/logs` is the platform's generic log route, not part of `@xeplr/jobs`. A host without it answers 404 and the panel shows an error in place of the log. Log lines are keyed by occurrence id because an action writes under the `referenceId` it is handed.
112
113
 
@@ -121,11 +122,19 @@ State shows **Running** over **Paused**: a pause takes effect at the next pick,
121
122
 
122
123
  ### The editor
123
124
 
124
- Three steps, all reachable at any time, with **Save job** on each:
125
+ Three steps (four with `chainsApiBase`), all reachable at any time, with **Save job** on each:
125
126
 
126
127
  1. **Job** — name, description, action.
127
128
  2. **Inputs** — a control per field of the action's `inputSchema`: a select for `options`, true/false for `boolean`, a number input, a JSON textarea for `object` / `array` (invalid JSON blocks the save), text otherwise. Fields marked `system: true` are never shown — the server fills them, and rendering them would ask for a credential. Optional fields with a `default` are under **Advanced**, whose summary lists their values. Values are converted to the declared types on save, since `@xeplr/schema-handler` rejects `"1000"` for a number.
128
129
  3. **Schedule** — cron (`CronScheduleField`), status, **Start from** (`startAt`), **Retry on failure** (0–3, default 0), **Give up after** (`timeoutMinutes`, blank = server default of 30).
130
+ 4. **After this job** (`JobChainSection`, `useJobChainController`, `lib/jobChainModel.js`) — "Run another job when this one finishes", then rules checked top to bottom, first match wins. Each rule has:
131
+ - **If**: a JSON condition, e.g. `{ "field": "status", "op": "=", "value": "success" }`, or `{ "all": [ … ] }` / `{ "any": [ … ] }`. Empty means "otherwise" and must come last.
132
+ - **Run**: another job.
133
+ - Optional **inputs** for the next job and **carry** for later ones, binding `{output.x}`, `{carry.x}`, `{window.to}`.
134
+
135
+ The period this job ran for passes to the next job by itself. Text that is not JSON, a missing job, or an "otherwise" that is not last is refused before anything is saved; the server checks the meaning and names the rule. An existing job's rules are saved before the job, and a new job's right after it (it needs its id).
136
+
137
+ With `chainsApiBase`, **Inputs** also has **From the job before**: tickboxes for the inputs another job may fill when it runs this one (the job's `acceptsInputs`). No field is ticked by default, and a field naming a connection is never offered.
129
138
 
130
139
  A new job with a schedule defaults to **Paused**, so it can be written now and started later. A job with no schedule is saved as `ready` and runs only when triggered.
131
140
 
@@ -181,7 +190,7 @@ Styles read `--accent`, `--surface`, `--ink`, `--muted`, `--hair`, `--plane` and
181
190
  npm test
182
191
  ```
183
192
 
184
- Plain Node scripts, no framework (`test/run.mjs` runs each `*.test.*` file): job state, `describeCron`, next-run and duration labels, latest run per job, search and sort.
193
+ Plain Node scripts, no framework (`test/run.mjs` runs each `*.test.*` file): job state, `describeCron`, next-run and duration labels, latest run per job, search and sort; and the "After this job" form's rules: text to rules and back, what is refused, what the job before may fill (`jobChainModel.test.mjs`).
185
194
 
186
195
  ## License
187
196
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/ui-jobs",
3
- "version": "1.0.3",
3
+ "version": "1.1.0",
4
4
  "description": "The screens for @xeplr/jobs — schedule, run, pause and watch jobs — as routes a host app registers, or a standalone app",
5
5
  "type": "module",
6
6
  "main": "src/index.jsx",
@@ -0,0 +1,36 @@
1
+ import { authFetch } from '@xeplr/ui-account'
2
+
3
+ // "AFTER THIS JOB" RULES — served by the WORKFLOW API, not by jobs.
4
+ //
5
+ // Jobs never start each other; the workflow engine does every hand-off, and a
6
+ // job's rules are a workflow it keeps (GET/PUT <workflow>/job-chains/:jobId).
7
+ // So this is where that API is mounted, set by the host — and null when there
8
+ // is no workflow on the install, which hides the section rather than showing
9
+ // one that cannot save.
10
+ //
11
+ // Over HTTP only: this package does not import workflow's code, so each can be
12
+ // installed on its own.
13
+ let CHAINS_BASE = null
14
+
15
+ export function configureChainsApi(base) {
16
+ CHAINS_BASE = typeof base === 'string' ? base.replace(/\/+$/, '') : null
17
+ }
18
+
19
+ export function chainsEnabled() {
20
+ return CHAINS_BASE !== null
21
+ }
22
+
23
+ const url = (jobId) => `${CHAINS_BASE}/job-chains/${encodeURIComponent(jobId)}`
24
+
25
+ /** { jobId, workflowId, rules } — an empty list for a job with none. */
26
+ export async function getChain(jobId) {
27
+ return authFetch(url(jobId))
28
+ }
29
+
30
+ /** Replace a job's rules. An empty list removes them. */
31
+ export async function putChain(jobId, rules, jobName) {
32
+ return authFetch(url(jobId), {
33
+ method: 'PUT',
34
+ body: JSON.stringify({ rules: rules, jobName: jobName })
35
+ })
36
+ }
@@ -0,0 +1,19 @@
1
+ /* "After this job" — the rules list in the job editor. */
2
+ .jb-chain { display: grid; gap: 10px; }
3
+ .jb-chain-toggle { display: flex; align-items: center; gap: 8px; font-size: 14px; color: var(--ink, #1a1a19); cursor: pointer; }
4
+ .jb-chain-rules { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; }
5
+ .jb-chain-rule {
6
+ padding: 12px 14px; background: var(--plane, #f7f7f5);
7
+ border: 1px solid var(--hair, #e2e1d9); border-radius: 11px;
8
+ }
9
+ .jb-chain-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
10
+ .jb-chain-n { font-size: 12px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--muted, #6b6a63); }
11
+ .jb-chain-tools { display: flex; gap: 6px; }
12
+ .jb-chain-tools button, .jb-chain-add {
13
+ padding: 4px 10px; font: inherit; font-size: 12px; color: var(--ink, #1a1a19);
14
+ background: var(--surface, #ffffff); border: 1px solid var(--hair, #e2e1d9); border-radius: 7px; cursor: pointer;
15
+ }
16
+ .jb-chain-tools button:disabled { opacity: .45; cursor: default; }
17
+ .jb-chain-add { justify-self: start; font-size: 13px; padding: 6px 12px; }
18
+ .jb-chain-json { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; resize: vertical; }
19
+ .jb-chain-fields { margin: 6px 0 8px; padding-left: 18px; font-size: 13px; color: var(--muted, #6b6a63); display: grid; gap: 3px; }
@@ -0,0 +1,115 @@
1
+ import { CHAIN_FIELDS, EXAMPLE_WHEN } from '../lib/jobChainModel.js'
2
+ import './JobChainSection.css'
3
+
4
+ /**
5
+ * "After this job" — which job runs next, depending on how this one ended.
6
+ *
7
+ * Presentation only: everything comes from useJobChainController. Conditions
8
+ * and values are JSON on purpose (the free product has no workflow designer);
9
+ * the server checks what they mean and names the rule when one is wrong.
10
+ *
11
+ * @param {object} props.chain useJobChainController()
12
+ * @param {object[]} props.jobs every job, for the "run" picker
13
+ * @param {string} [props.jobId] this job, left out of the picker
14
+ */
15
+ export default function JobChainSection({ chain, jobs, jobId }) {
16
+ if (chain.loading) return <p className="muted">Loading the rules…</p>
17
+ if (chain.loadError) {
18
+ return <p className="jb-help jb-warn">Could not load this job's rules, so they cannot be changed here: {chain.loadError}</p>
19
+ }
20
+
21
+ const others = (jobs || []).filter((j) => j.id !== jobId)
22
+
23
+ return (
24
+ <div className="jb-chain">
25
+ <label className="jb-chain-toggle">
26
+ <input type="checkbox" checked={chain.on} onChange={(e) => chain.setOn(e.target.checked)} />
27
+ Run another job when this one finishes
28
+ </label>
29
+
30
+ {!chain.on && (
31
+ <p className="jb-help">Nothing runs after this job. Tick the box to choose what should, and when.</p>
32
+ )}
33
+
34
+ {chain.on && (
35
+ <>
36
+ <p className="jb-help">
37
+ Rules are checked top to bottom and the first that matches runs its job. A rule with no
38
+ condition means “otherwise”. The period this job ran for passes to the next job by itself.
39
+ </p>
40
+
41
+ <ol className="jb-chain-rules">
42
+ {chain.rows.map((row, i) => (
43
+ <li key={i} className="jb-chain-rule">
44
+ <div className="jb-chain-head">
45
+ <span className="jb-chain-n">Rule {i + 1}</span>
46
+ <span className="jb-chain-tools">
47
+ <button type="button" onClick={() => chain.moveUp(i)} disabled={i === 0} title="Check this rule earlier">↑</button>
48
+ <button type="button" className="jb-danger" onClick={() => chain.removeRow(i)}>Remove</button>
49
+ </span>
50
+ </div>
51
+
52
+ <div className="jb-field">
53
+ <label htmlFor={`jb-chain-when-${i}`}>If <span className="jb-type">· JSON, empty = otherwise</span></label>
54
+ <textarea id={`jb-chain-when-${i}`} className="jb-chain-json" rows={3}
55
+ placeholder={EXAMPLE_WHEN} value={row.when}
56
+ onChange={(e) => chain.updateRow(i, { when: e.target.value })} />
57
+ </div>
58
+
59
+ <div className="jb-field">
60
+ <label htmlFor={`jb-chain-run-${i}`}>Run</label>
61
+ <select id={`jb-chain-run-${i}`} value={row.run}
62
+ onChange={(e) => chain.updateRow(i, { run: e.target.value })}>
63
+ <option value="">Choose a job…</option>
64
+ {others.map((j) => <option key={j.id} value={j.id}>{j.name}</option>)}
65
+ </select>
66
+ </div>
67
+
68
+ <details className="jb-advanced" open={Boolean(row.inputs || row.carry)}>
69
+ <summary>Pass values on <span className="jb-dim">— optional</span></summary>
70
+ <div className="jb-field">
71
+ <label htmlFor={`jb-chain-inputs-${i}`}>Inputs of the next job <span className="jb-type">· JSON</span></label>
72
+ <textarea id={`jb-chain-inputs-${i}`} className="jb-chain-json" rows={3}
73
+ placeholder={'{ "region": "{output.region}" }'} value={row.inputs}
74
+ onChange={(e) => chain.updateRow(i, { inputs: e.target.value })} />
75
+ <span className="jb-help">
76
+ Only inputs the next job accepts (its Inputs step lists them). Leave out
77
+ <code className="jb-code">window</code> to pass this job's period on unchanged.
78
+ </span>
79
+ </div>
80
+ <div className="jb-field">
81
+ <label htmlFor={`jb-chain-carry-${i}`}>Carry for later jobs <span className="jb-type">· JSON</span></label>
82
+ <textarea id={`jb-chain-carry-${i}`} className="jb-chain-json" rows={3}
83
+ placeholder={'{ "loadedRows": "{output.totalRows}" }'} value={row.carry}
84
+ onChange={(e) => chain.updateRow(i, { carry: e.target.value })} />
85
+ <span className="jb-help">Read later as <code className="jb-code">carry.loadedRows</code>, in a condition or a value.</span>
86
+ </div>
87
+ </details>
88
+ </li>
89
+ ))}
90
+ </ol>
91
+
92
+ <button type="button" className="jb-chain-add" onClick={chain.addRow}>+ Add rule</button>
93
+
94
+ <details className="jb-advanced">
95
+ <summary>What a condition can read</summary>
96
+ <ul className="jb-chain-fields">
97
+ {CHAIN_FIELDS.map((f) => (
98
+ <li key={f.field}><code className="jb-code">{f.field}</code> — {f.about}</li>
99
+ ))}
100
+ </ul>
101
+ <p className="jb-help">
102
+ Comparisons: <code className="jb-code">=</code> <code className="jb-code">!=</code>{' '}
103
+ <code className="jb-code">&gt;</code> <code className="jb-code">&gt;=</code>{' '}
104
+ <code className="jb-code">&lt;</code> <code className="jb-code">&lt;=</code>{' '}
105
+ <code className="jb-code">in</code> <code className="jb-code">contains</code>{' '}
106
+ <code className="jb-code">isEmpty</code> and more. Combine with
107
+ <code className="jb-code">{'{ "all": [ … ] }'}</code> or <code className="jb-code">{'{ "any": [ … ] }'}</code>.
108
+ Values bind with <code className="jb-code">{'{output.name}'}</code>, <code className="jb-code">{'{carry.name}'}</code>, <code className="jb-code">{'{window.to}'}</code>.
109
+ </p>
110
+ </details>
111
+ </>
112
+ )}
113
+ </div>
114
+ )
115
+ }
package/src/index.jsx CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Route } from 'react-router-dom';
2
2
  import JobsPage from './pages/Jobs.jsx';
3
3
  import { configureJobsApi, configureOptionSources } from './api/jobs.js';
4
+ import { configureChainsApi } from './api/jobChains.js';
4
5
  import { ROUTES } from './routes.js';
5
6
 
6
7
  /**
@@ -57,18 +58,18 @@ import { ROUTES } from './routes.js';
57
58
  * navigate back up to.
58
59
  * @param {JSX.Element|string} [config.uploadLink] - a link to wherever the host
59
60
  * loads files, named in the empty state.
60
- * @param {JSX.Element} [config.connectLink] - a link to the workflow canvas,
61
- * for connecting jobs so one starts when another finishes. Supplied by the
62
- * host because this package must not import @xeplr/workflow — workflow
63
- * already calls jobs over HTTP at run time, and importing its UI here would
64
- * close that into a circular dependency between two packages that are
65
- * deliberately installable on their own.
61
+ * @param {string|null} [config.chainsApiBase=null] - where the WORKFLOW API
62
+ * is mounted (e.g. '/workflow'), which keeps each job's "After this job"
63
+ * rules. Jobs never start each other — the workflow engine does every
64
+ * hand-off — so without it the editor shows no "After this job" step.
65
+ * Talked to over HTTP only: this package does not import workflow.
66
66
  * @returns {{ routes: JSX.Element[], path: string }}
67
67
  */
68
68
  export function registerJobsUI(config) {
69
69
  config = config || {};
70
70
  if (config.apiBase !== undefined) configureJobsApi({ base: config.apiBase });
71
71
  configureOptionSources(config.optionSources);
72
+ configureChainsApi(config.chainsApiBase);
72
73
 
73
74
  var path = ROUTES.jobs(config.basePath);
74
75
 
@@ -0,0 +1,122 @@
1
+ // "AFTER THIS JOB" — the rules a job's screen writes, as pure logic.
2
+ //
3
+ // The rules are kept by the workflow engine, not by jobs: each becomes a branch
4
+ // of one hidden workflow that runs when the job finishes (see
5
+ // @xeplr-workflow/engine's lib/jobChains.js). This file is only the form's
6
+ // half — the text a person types, turned into the rules the server takes,
7
+ // and back — so it can be tested with plain node.
8
+ //
9
+ // A rule as the server takes it:
10
+ //
11
+ // { when: { field, op, value } | { all: [...] } | { any: [...] } | null,
12
+ // run: '<jobId>', inputs: { … }, carry: { … } }
13
+ //
14
+ // `when` null is "otherwise". The window the job ran for passes to the next
15
+ // job by itself; `inputs` and `carry` are only for anything more.
16
+
17
+ /** The fields a condition can read, for the help text. */
18
+ export const CHAIN_FIELDS = [
19
+ { field: 'status', about: '"success" or "failed" — did this job\'s work happen' },
20
+ { field: 'output.<name>', about: 'what this job\'s action returned, e.g. output.totalRows' },
21
+ { field: 'window.from / window.to', about: 'the period this job ran for' },
22
+ { field: 'carry.<name>', about: 'values carried from earlier jobs in the chain' },
23
+ { field: 'error.message', about: 'why it failed' }
24
+ ]
25
+
26
+ export const EXAMPLE_WHEN = '{ "field": "status", "op": "=", "value": "success" }'
27
+
28
+ function pretty(value) {
29
+ if (value === null || value === undefined) return ''
30
+ if (typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) return ''
31
+ return JSON.stringify(value, null, 2)
32
+ }
33
+
34
+ /** Server rules → the rows the form edits (JSON as text). */
35
+ export function rulesToRows(rules) {
36
+ return (Array.isArray(rules) ? rules : []).map((r) => ({
37
+ when: pretty(r.when),
38
+ run: r.run || '',
39
+ inputs: pretty(r.inputs),
40
+ carry: pretty(r.carry)
41
+ }))
42
+ }
43
+
44
+ export function blankRow() {
45
+ return { when: '', run: '', inputs: '', carry: '' }
46
+ }
47
+
48
+ function parseObject(text, label, problems) {
49
+ const raw = String(text || '').trim()
50
+ if (!raw) return null
51
+ try {
52
+ const value = JSON.parse(raw)
53
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
54
+ problems.push(`${label} must be a JSON object, in { }.`)
55
+ return null
56
+ }
57
+ return value
58
+ } catch (err) {
59
+ problems.push(`${label} is not valid JSON: ${err.message}`)
60
+ return null
61
+ }
62
+ }
63
+
64
+ /**
65
+ * The form's rows → { rules, problems }. Every problem names its rule, so the
66
+ * form can say all of them at once rather than one per save.
67
+ *
68
+ * The meaning of a condition (which fields, which comparisons) is the
69
+ * server's to check — it answers with the rule and the reason. This only
70
+ * catches what would never reach it: text that is not JSON, a rule with no job.
71
+ */
72
+ export function rowsToRules(rows, ownJobId) {
73
+ const problems = []
74
+ const rules = (rows || []).map((row, i) => {
75
+ const n = i + 1
76
+ if (!row.run) problems.push(`Rule ${n}: choose the job to run.`)
77
+ else if (ownJobId && row.run === ownJobId) problems.push(`Rule ${n}: a job cannot run itself when it finishes.`)
78
+ const when = parseObject(row.when, `Rule ${n}'s condition`, problems)
79
+ const inputs = parseObject(row.inputs, `Rule ${n}'s inputs`, problems)
80
+ const carry = parseObject(row.carry, `Rule ${n}'s carry`, problems)
81
+ return { when: when, run: row.run, inputs: inputs || {}, carry: carry || {} }
82
+ })
83
+ // First match wins, so nothing can follow an "otherwise".
84
+ const otherwiseAt = rules.findIndex((r) => !r.when)
85
+ if (otherwiseAt > -1 && otherwiseAt < rules.length - 1) {
86
+ problems.push(`Rule ${otherwiseAt + 1} has no condition, so it always matches — move it last, or give it one.`)
87
+ }
88
+ return { rules: rules, problems: problems }
89
+ }
90
+
91
+ /** Whether two sets of server rules say the same thing. */
92
+ export function sameRules(a, b) {
93
+ return JSON.stringify(a || []) === JSON.stringify(b || [])
94
+ }
95
+
96
+ /** One line describing a rule, for a summary. */
97
+ export function describeRule(rule, jobName) {
98
+ const target = jobName(rule.run) || rule.run || 'a job'
99
+ const w = rule.when
100
+ if (!w) return `Otherwise, run ${target}`
101
+ if (w.field) return `If ${w.field} ${w.op} ${JSON.stringify(w.value ?? '')}, run ${target}`
102
+ return `If ${w.all ? 'all' : 'any'} of ${(w.all || w.any || []).length} conditions match, run ${target}`
103
+ }
104
+
105
+ // ── what a job accepts from the job before it ───────────────────────────
106
+ //
107
+ // @xeplr/jobs lets a trigger fill only `window` and the inputs a job lists in
108
+ // acceptsInputs. A connection is never offered: it decides where the job
109
+ // reads and writes, and only whoever saves the job chooses that.
110
+ const NEVER_ACCEPTED = /connection/i
111
+
112
+ /** The action's fields another job could fill, by name. */
113
+ export function acceptableFields(fields) {
114
+ return (fields || []).filter((f) => f && f.name && f.name !== 'window' && !NEVER_ACCEPTED.test(f.name))
115
+ }
116
+
117
+ export function toggleAccepted(list, name, on) {
118
+ const set = new Set(Array.isArray(list) ? list : [])
119
+ if (on) set.add(name)
120
+ else set.delete(name)
121
+ return Array.from(set)
122
+ }
@@ -11,6 +11,9 @@ import {
11
11
  latestByJob, prepareJobs, progressLabel, progressStale, lastSeenLabel
12
12
  } from './jobsList.js'
13
13
  import CronScheduleField from '../components/CronScheduleField.jsx'
14
+ import JobChainSection from '../components/JobChainSection.jsx'
15
+ import { useJobChainController } from '../useJobChainController.js'
16
+ import { acceptableFields, toggleAccepted } from '../lib/jobChainModel.js'
14
17
  import './Jobs.css'
15
18
 
16
19
  // SCHEDULED JOBS — @xeplr/jobs, in this product's chrome.
@@ -254,12 +257,15 @@ function JobRuns({ jobId, refreshKey }) {
254
257
  // always available — someone editing a live job to change its cron should not
255
258
  // have to walk past its name and its inputs to get there. The steps are for
256
259
  // grouping, not for gatekeeping.
257
- const STEPS = [
260
+ const BASE_STEPS = [
258
261
  { key: 'job', label: 'Job', hint: 'What it is, and what it runs' },
259
262
  { key: 'inputs', label: 'Inputs', hint: 'What that action needs' },
260
263
  { key: 'schedule', label: 'Schedule', hint: 'When, and what if it goes wrong' }
261
264
  ]
262
265
 
266
+ // Shown only when the host has a workflow API — the rules are kept there.
267
+ const AFTER_STEP = { key: 'after', label: 'After this job', hint: 'What runs when this one finishes' }
268
+
263
269
  /**
264
270
  * Fields a PERSON fills in.
265
271
  *
@@ -489,7 +495,7 @@ function ActionInput({ field, value, onChange, inputs }) {
489
495
 
490
496
  // The editor. A panel rather than a route: a job is a handful of fields, and a
491
497
  // page you navigate to and back from for those is three navigations too many.
492
- function JobEditor({ job, actions, onCancel, onSaved }) {
498
+ function JobEditor({ job, jobs, actions, onCancel, onSaved }) {
493
499
  const [draft, setDraft] = useState(() => ({
494
500
  name: job?.name || '',
495
501
  description: job?.description || '',
@@ -515,10 +521,15 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
515
521
  // at save — see fromFieldValues.
516
522
  inputs: Object.fromEntries(
517
523
  Object.entries(job?.inputs || {}).map(([k, v]) => [k, toFieldValue(v)])
518
- )
524
+ ),
525
+ // Inputs the job BEFORE this one in a chain may fill (@xeplr/jobs'
526
+ // acceptsInputs). `window` always may, so it is not listed.
527
+ acceptsInputs: Array.isArray(job?.acceptsInputs) ? job.acceptsInputs : []
519
528
  }))
520
529
  const [saving, setSaving] = useState(false)
521
530
  const [step, setStep] = useState(0)
531
+ const chain = useJobChainController(job?.id || null)
532
+ const STEPS = chain.enabled ? [...BASE_STEPS, AFTER_STEP] : BASE_STEPS
522
533
 
523
534
  const action = actions.find((a) => a.name === draft.actionName) || null
524
535
  const patch = (p) => setDraft((d) => ({ ...d, ...p }))
@@ -534,12 +545,26 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
534
545
  raiseSnackbar(`Not valid JSON: ${broken.join(', ')}`, { design: 'error' })
535
546
  return
536
547
  }
548
+ // The rules are checked BEFORE anything is saved, so a typo in one does
549
+ // not leave a job saved and its chain not.
550
+ const chainCheck = chain.check(job?.id)
551
+ if (chainCheck.problems.length) {
552
+ setStep(STEPS.length - 1)
553
+ raiseSnackbar(chainCheck.problems.join(' '), { design: 'error' })
554
+ return
555
+ }
537
556
 
538
557
  setSaving(true)
539
558
  try {
540
- await saveJob({
559
+ const name = draft.name.trim() || 'Untitled job'
560
+ // AN EXISTING JOB'S RULES GO FIRST: the server is the one that checks
561
+ // what a condition means, and a refusal there should leave the job as
562
+ // it was rather than half-saved. A new job has no id to hang rules on
563
+ // until it is saved, so its rules follow it.
564
+ if (job?.id) await chain.save(job.id, name)
565
+ const res = await saveJob({
541
566
  ...(job?.id ? { id: job.id } : {}),
542
- name: draft.name.trim() || 'Untitled job',
567
+ name: name,
543
568
  description: draft.description || '',
544
569
  actionName: draft.actionName,
545
570
  // Trimmed to null rather than '': the model treats an absent schedule
@@ -558,8 +583,19 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
558
583
  timeoutMinutes: draft.timeoutMinutes === '' ? null : Number(draft.timeoutMinutes),
559
584
  // Converted back to the types the action declared. Sending the raw
560
585
  // strings is what made every number/boolean field fail validation.
561
- inputs: fromFieldValues(action, draft.inputs)
586
+ inputs: fromFieldValues(action, draft.inputs),
587
+ // Only names that are still fields of the chosen action.
588
+ acceptsInputs: draft.acceptsInputs.filter((n) => acceptableFields(fields).some((f) => f.name === n))
562
589
  })
590
+ if (!job?.id) {
591
+ const newId = res && Array.isArray(res.updatedIds) ? res.updatedIds[0] : null
592
+ try {
593
+ await chain.save(newId, name)
594
+ } catch (err) {
595
+ // The job exists now; reopening it shows the rules to fix.
596
+ raiseSnackbar(`The job was saved, but its "After this job" rules were not: ${err.message}`, { design: 'error' })
597
+ }
598
+ }
563
599
  onSaved()
564
600
  } catch (err) {
565
601
  raiseSnackbar(err.message || 'Could not save the job', { design: 'error' })
@@ -646,9 +682,35 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
646
682
  onChange={(v) => patch({ inputs: { ...draft.inputs, [f.name]: v } })}
647
683
  />
648
684
  )
685
+ const acceptable = acceptableFields(fields)
649
686
  return (
650
687
  <>
651
688
  <div className="jb-grid">{primary.map(render)}</div>
689
+ {chain.enabled && acceptable.length > 0 && (
690
+ /* WHAT THE JOB BEFORE THIS ONE MAY FILL. Off for every
691
+ field until ticked: a chain may otherwise only pass the
692
+ period (window), never this job's SQL or connection. */
693
+ <details className="jb-advanced" open={draft.acceptsInputs.length > 0}>
694
+ <summary>
695
+ From the job before
696
+ <span className="jb-dim">
697
+ {' — '}
698
+ {draft.acceptsInputs.length ? draft.acceptsInputs.map((n) => fieldLabel(acceptable.find((f) => f.name === n) || { name: n })).join(' · ') : 'only the period'}
699
+ </span>
700
+ </summary>
701
+ <p className="jb-help">
702
+ When another job runs this one, it always passes the period it ran for. Tick the inputs
703
+ it may also fill; everything else stays as saved here.
704
+ </p>
705
+ {acceptable.map((f) => (
706
+ <label key={f.name} className="jb-chain-toggle">
707
+ <input type="checkbox" checked={draft.acceptsInputs.includes(f.name)}
708
+ onChange={(e) => patch({ acceptsInputs: toggleAccepted(draft.acceptsInputs, f.name, e.target.checked) })} />
709
+ {fieldLabel(f)}
710
+ </label>
711
+ ))}
712
+ </details>
713
+ )}
652
714
  {advanced.length > 0 && (
653
715
  /* COLLAPSED, NOT HIDDEN. The summary names every field in
654
716
  here and its current value, so closing it never conceals
@@ -770,6 +832,11 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
770
832
  </>
771
833
  )}
772
834
 
835
+ {/* ── 4. What runs next ────────────────────────────────────────────── */}
836
+ {chain.enabled && step === STEPS.length - 1 && STEPS[step].key === 'after' && (
837
+ <JobChainSection chain={chain} jobs={jobs} jobId={job?.id} />
838
+ )}
839
+
773
840
  <div className="jb-editor-actions">
774
841
  <button type="button" onClick={onCancel}>Cancel</button>
775
842
  <span className="jb-editor-nav">
@@ -802,8 +869,6 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
802
869
  * @param {Function} [props.breadcrumb] - the host's breadcrumb component
803
870
  * @param {JSX.Element|string} [props.uploadLink] - a link to wherever the host
804
871
  * loads files, if it has such a screen
805
- * @param {JSX.Element} [props.connectLink] - a link to the workflow canvas,
806
- * for connecting jobs to each other so one starts when another finishes.
807
872
  *
808
873
  * SUPPLIED BY THE HOST, not imported. This package must not depend on
809
874
  * @xeplr/workflow: workflow already calls jobs — over HTTP, at run time, to
@@ -817,7 +882,7 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
817
882
  * the link. Omitted, nothing is rendered — the screen is complete without
818
883
  * it, exactly as uploadLink is.
819
884
  */
820
- export default function Jobs({ breadcrumb: Breadcrumb, uploadLink, connectLink } = {}) {
885
+ export default function Jobs({ breadcrumb: Breadcrumb, uploadLink } = {}) {
821
886
  const [jobs, setJobs] = useState(null)
822
887
  const [runs, setRuns] = useState([])
823
888
  const [actions, setActions] = useState([])
@@ -988,10 +1053,6 @@ export default function Jobs({ breadcrumb: Breadcrumb, uploadLink, connectLink }
988
1053
  <span className="jb-live-count">{active.length} running</span>
989
1054
  )}
990
1055
  </label>
991
- {/* Before "+ New job", because connecting jobs is something you do
992
- to the ones already listed — a secondary action ON this screen's
993
- content, where the primary one creates more of it. */}
994
- {connectLink}
995
1056
  <button type="button" className="jb-primary" onClick={() => setEditing({})}>+ New job</button>
996
1057
  </div>
997
1058
  </header>
@@ -1002,6 +1063,7 @@ export default function Jobs({ breadcrumb: Breadcrumb, uploadLink, connectLink }
1002
1063
  {editing && (
1003
1064
  <JobEditor
1004
1065
  job={editing.id ? editing : null}
1066
+ jobs={jobs || []}
1005
1067
  actions={actions}
1006
1068
  onCancel={() => setEditing(null)}
1007
1069
  onSaved={() => { setEditing(null); load() }}
@@ -0,0 +1,83 @@
1
+ import { useEffect, useState } from 'react'
2
+ import { chainsEnabled, getChain, putChain } from './api/jobChains.js'
3
+ import { blankRow, rowsToRules, rulesToRows, sameRules } from './lib/jobChainModel.js'
4
+
5
+ /**
6
+ * State and handlers for a job's "After this job" rules — no JSX.
7
+ *
8
+ * Loaded when an existing job is opened; saved by the editor's own Save,
9
+ * after the job itself (a new job has no id to hang rules on until then).
10
+ * `enabled` is false when the host has no workflow API, and the section is
11
+ * then not shown at all.
12
+ */
13
+ export function useJobChainController(jobId) {
14
+ const enabled = chainsEnabled()
15
+ const [rows, setRows] = useState([])
16
+ const [saved, setSaved] = useState([])
17
+ const [on, setOn] = useState(false)
18
+ const [loading, setLoading] = useState(Boolean(enabled && jobId))
19
+ const [loadError, setLoadError] = useState(null)
20
+
21
+ useEffect(() => {
22
+ if (!enabled || !jobId) return
23
+ let live = true
24
+ setLoading(true)
25
+ getChain(jobId)
26
+ .then((res) => {
27
+ if (!live) return
28
+ const rules = (res && res.rules) || []
29
+ setSaved(rules)
30
+ setRows(rulesToRows(rules))
31
+ setOn(rules.length > 0)
32
+ setLoadError(null)
33
+ })
34
+ .catch((err) => { if (live) setLoadError(err.message || 'Could not load the rules') })
35
+ .finally(() => { if (live) setLoading(false) })
36
+ return () => { live = false }
37
+ }, [enabled, jobId])
38
+
39
+ function setTurnedOn(value) {
40
+ setOn(value)
41
+ if (value && !rows.length) setRows([blankRow()])
42
+ }
43
+
44
+ function updateRow(index, patch) {
45
+ setRows((rs) => rs.map((r, i) => (i === index ? { ...r, ...patch } : r)))
46
+ }
47
+
48
+ function addRow() { setRows((rs) => [...rs, blankRow()]) }
49
+
50
+ function removeRow(index) { setRows((rs) => rs.filter((_, i) => i !== index)) }
51
+
52
+ // First match wins, so order is meaning.
53
+ function moveUp(index) {
54
+ if (index < 1) return
55
+ setRows((rs) => {
56
+ const next = rs.slice()
57
+ const [row] = next.splice(index, 1)
58
+ next.splice(index - 1, 0, row)
59
+ return next
60
+ })
61
+ }
62
+
63
+ /** The rules this form would save, and anything wrong with them. */
64
+ function check(ownJobId) {
65
+ if (!on) return { rules: [], problems: [] }
66
+ return rowsToRules(rows, ownJobId)
67
+ }
68
+
69
+ /**
70
+ * Save the rules for a job that now has an id. Skipped when nothing
71
+ * changed, so saving a job's schedule does not rewrite its chain.
72
+ */
73
+ async function save(savedJobId, jobName) {
74
+ if (!enabled || !savedJobId || loadError) return
75
+ const { rules, problems } = check(savedJobId)
76
+ if (problems.length) throw new Error(problems.join(' '))
77
+ if (sameRules(rules, saved)) return
78
+ const res = await putChain(savedJobId, rules, jobName)
79
+ setSaved((res && res.rules) || rules)
80
+ }
81
+
82
+ return { enabled, on, setOn: setTurnedOn, rows, updateRow, addRow, removeRow, moveUp, loading, loadError, check, save }
83
+ }