priority-axi 0.1.0 → 0.2.1

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
@@ -4,9 +4,10 @@
4
4
  [![npm](https://img.shields.io/npm/v/priority-axi.svg)](https://www.npmjs.com/package/priority-axi)
5
5
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
6
 
7
- A command-line tool that lets AI agents read and create records in Priority ERP through its REST API (OData).
7
+ A command-line tool that lets AI agents read, create and update records in Priority ERP through its REST API (OData).
8
8
 
9
9
  priority-axi is an AXI, an agent experience interface. Every command:
10
+
10
11
  - prints compact [TOON](https://github.com/toon-format/toon) text on stdout, bounded in size;
11
12
  - checks its input against the server's own metadata, and says exactly what is wrong;
12
13
  - ends with hints for the next command;
@@ -31,19 +32,20 @@ Each release is published from GitHub Actions with [npm provenance](https://docs
31
32
 
32
33
  ## Configure
33
34
 
34
- | Variable | Flag | Meaning |
35
- | --- | --- | --- |
36
- | `PRIORITY_URL` | | `https://host`, or the full service root `https://host/odata/Priority/<ini>/<company>` |
37
- | `PRIORITY_USER` | `--user` | The API username |
38
- | `PRIORITY_PASSWORD` | | The password. Inside Comis it is a placeholder that the Gate replaces. |
39
- | `PRIORITY_COMPANY` | `--company` | The company code |
40
- | `PRIORITY_INI` | `--ini` | The ini file in the URL. The default is `tabula.ini`. |
35
+ | Variable | Flag | Meaning |
36
+ | ------------------- | ----------- | -------------------------------------------------------------------------------------- |
37
+ | `PRIORITY_URL` | | `https://host`, or the full service root `https://host/odata/Priority/<ini>/<company>` |
38
+ | `PRIORITY_USER` | `--user` | The API username |
39
+ | `PRIORITY_PASSWORD` | | The password. Inside Comis it is a placeholder that the Gate replaces. |
40
+ | `PRIORITY_COMPANY` | `--company` | The company code |
41
+ | `PRIORITY_INI` | `--ini` | The ini file in the URL. The default is `tabula.ini`. |
41
42
 
42
43
  A flag overrides its variable. Plain `http://` is accepted only for `localhost` and `127.0.0.1`.
43
44
 
44
45
  ### Priority administrator setup
45
46
 
46
47
  The REST API reads only the screens that the administrator has opened to it. Ask them to:
48
+
47
49
  1. Add the screens you need to **Limited Access / API Forms**, for example CUSTOMERS, LOGPART and ORDERS. Their sub-screens, such as ORDERITEMS, come with them.
48
50
  2. Give the API user an API license, and only the privileges it needs.
49
51
 
@@ -55,11 +57,14 @@ Until then, reads end with `code: screen_not_enabled`. The home view, `screens`,
55
57
  priority-axi home view: connection, version, company, next steps
56
58
  priority-axi screens [<text>] find screens by name or description
57
59
  priority-axi fields <SCREEN> [--sub <SUB>] a screen's fields, key and sub-screens
58
- priority-axi get <SCREEN> [--where F=V]... [--fields A,B] [--with <SUB>]... [--sort F[:desc]] [--limit N] [--page N]
60
+ priority-axi get <SCREEN> [--where F=V]... [--fields A,B] [--with <SUB>]... [--sort F[:desc]] [--limit N] [--page N | --offset N]
59
61
  priority-axi show <SCREEN> <key> [--with <SUB>]...
60
62
  priority-axi changes <SCREEN> --since 7d recent changes, on screens with a BPM status workflow
61
63
  priority-axi find <SCREEN> <words>... records by words in their name or description
62
64
  priority-axi create <SCREEN> --set F=V... [--line <SUB> F=V...]... [--dry-run]
65
+ priority-axi update <SCREEN> <key> --set F=V... [--dry-run] change a record
66
+ priority-axi add-line <SCREEN> <key> <SUB> F=V... [--dry-run] add a line to it
67
+ priority-axi update-line <SCREEN> <key> <SUB> <line-key> --set F=V... [--dry-run]
63
68
  priority-axi refresh rebuild the screen index
64
69
  priority-axi help [<command>] every flag of a command
65
70
  ```
@@ -98,12 +103,16 @@ priority-axi show ORDERS SO26000102 --with ORDERITEMS --with ORDERSTEXT
98
103
  priority-axi changes CUSTOMERS --since 7d
99
104
  priority-axi find LOGPART צינור ביוב 110
100
105
  priority-axi create ORDERS --set CUSTNAME=C1001 --line ORDERITEMS PARTNAME=P1 TQUANT=2 --dry-run
106
+ priority-axi add-line ORDERS SO26000102 ORDERITEMS PARTNAME=P1 TQUANT=2 --dry-run
107
+ priority-axi update-line ORDERS SO26000102 ORDERITEMS KLINE=1 --set TQUANT=3 --dry-run
101
108
  ```
102
109
 
103
110
  ### Filters
104
111
 
105
112
  `--where` takes `F=V`, `F!=V`, `F>V`, `F>=V`, `F<V` and `F<=V`. Values are typed from the screen's metadata, so you never write OData quotes. `--filter` passes raw OData for anything else the server supports.
106
113
 
114
+ **Dates and times are Priority's local (company) time,** in `--where`, `--set` and `--json-file`: write `2026-11-20` or `2026-11-20T08:00`. priority-axi sends the digits as written. Priority ignores an offset such as `+02:00`, so priority-axi drops it and never converts the time to UTC. `changes --since` is the exception: it takes UTC, such as `2026-11-01T06:00:00Z`, or `7d` and `24h`.
115
+
107
116
  Priority answers 501 to `contains` and `startswith`. For text that starts with `ABC`, use a range: `--where 'F>=ABC' --where 'F<ABD'`.
108
117
 
109
118
  Always filter large document screens such as orders and invoices. Without a filter, Priority goes through every record before it answers, even when you ask for one.
@@ -111,6 +120,7 @@ Always filter large document screens such as orders and invoices. Without a filt
111
120
  ### Finding records by words
112
121
 
113
122
  Priority cannot search inside text, so `find` keeps a local copy of a screen's catalog, refreshed daily: the key, description, unit, family and status. It matches as follows:
123
+
114
124
  - **Every word must appear.** A word matches the start of a word, after Hebrew prefix letters, so `ביוב` finds `לביוב`.
115
125
  - **Numbers match only as whole numbers.** `4` matches neither `4000` nor `SN4`.
116
126
  - **Spelling variants are ignored:** Hebrew points, final letter forms, and `״`/`׳` against `"`/`'`.
@@ -119,42 +129,50 @@ Records that are not in use are left out unless you pass `--all`. When no record
119
129
 
120
130
  ## Output and errors
121
131
 
122
- - **Lists** say how many records they show and whether more exist. Priority reports no totals.
132
+ - **Lists** say how many records they show and whether more exist. Priority reports no totals. When the size limit drops records, the summary says `N of M shown`, and the next-page hint continues with `--offset` at the first record not shown.
123
133
  - **Size:** long values are cut at 500 characters, and the whole output at about 4,000. `--full` lifts both limits, up to 256 KB.
124
134
  - **Text safety:** invisible and bidirectional control characters are shown as `\uXXXX`, and values that look like credentials are withheld. Remarks, which Priority stores as HTML, are shown as plain text.
125
135
  - **Errors** print `message`, `code` and `usage` on stdout.
126
136
  - **Exit codes:** 0 on success, 1 on an error, 2 on a usage error.
127
137
 
128
- | Code | Meaning |
129
- | --- | --- |
130
- | `usage` | The command line is wrong; `usage` shows the right form |
131
- | `not_connected`, `missing_setting` | A setting is missing |
132
- | `auth_failed` | Priority refused the username or password |
133
- | `company_not_found` | The API user cannot reach that company |
134
- | `screen_not_enabled` | The screen is not in Limited Access / API Forms |
135
- | `not_found` | No record has that key |
136
- | `already_exists` | A create clashed with an existing key |
137
- | `priority_rejected` | Priority refused the request; its own message is shown |
138
- | `unsupported_query` | Priority cannot run that query |
139
- | `rate_limited` | Too many requests; wait and try again |
140
- | `held_for_approval`, `reconnect_needed`, `refused` | Inside Comis: the owner must approve, the owner must reconnect, or the Gate refused |
141
- | `unreachable`, `priority_error` | The server could not be reached, or it failed |
142
- | `output_too_large` | Even `--full` would exceed 256 KB; narrow the query |
143
- | `internal_error` | A bug in priority-axi; please [report it](https://github.com/comisai/priority-axi/issues) |
138
+ | Code | Meaning |
139
+ | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
140
+ | `usage` | The command line is wrong; `usage` shows the right form |
141
+ | `not_connected`, `missing_setting` | A setting is missing |
142
+ | `auth_failed` | Priority refused the username or password |
143
+ | `company_not_found` | The API user cannot reach that company |
144
+ | `screen_not_enabled` | The screen is not in Limited Access / API Forms |
145
+ | `not_found` | No record has that key |
146
+ | `already_exists` | A create clashed with an existing key |
147
+ | `priority_rejected` | Priority refused the request; its own message is shown |
148
+ | `partly_saved` | Priority saved a new record but refused one of its lines; do not create it again |
149
+ | `unsupported_query` | Priority cannot run that query |
150
+ | `rate_limited` | Too many requests; wait and try again |
151
+ | `held_for_approval`, `reconnect_needed`, `refused` | Inside Comis: the owner must approve, the owner must reconnect, or the Gate refused |
152
+ | `unreachable`, `priority_error` | The server could not be reached, did not answer in time, or failed; after a write, it may have been saved |
153
+ | `output_too_large` | Even `--full` would exceed 256 KB; narrow the query |
154
+ | `internal_error` | A bug in priority-axi; please [report it](https://github.com/comisai/priority-axi/issues) |
144
155
 
145
156
  ## Writes
146
157
 
147
- `create` checks every field against the metadata before it sends anything: the field must exist and be writable, and its value must have the right type and length.
158
+ `create`, `update`, `add-line` and `update-line` check every field against the metadata before they send anything: the field must exist and be writable, and its value must have the right type and length.
159
+
148
160
  - **Dry run:** `--dry-run` shows the request and how many API transactions it will cost: one per record and one per line.
149
- - **Sent once:** a create is never retried. Inside Comis, the Gate holds it until the owner approves it.
161
+ - **Sent once:** a write is never retried. Inside Comis, the Gate holds it until the owner approves it.
162
+ - **When the answer is lost:** if the connection breaks or times out after a write was sent, or Priority answers with a server error, the message says Priority may have saved it. Check with `show` or `get`, and do not send it again blindly.
163
+ - **Partly saved creates:** Priority saves a new record and its lines one by one, with no rollback. When it refuses a line, the record is already saved without it. priority-axi reports `partly_saved`, names the saved record (or the `get` that finds it), and points to `add-line`. Never create it again.
164
+ - **Time limits:** inside Comis, `COMIS_DEADLINE` bounds every command. Reads stop one second before it and say to run the command from a worker. A write is refused without sending when fewer than 50 s remain, since the owner's approval can take 45 s. The first index build and a cold `find` catalog each take about 30 s.
165
+ - **Updates name the record in the path:** `PATCH ORDERS('SO26000102')`, `POST ORDERS('SO26000102')/ORDERITEMS_SUBFORM` and `PATCH ORDERS('SO26000102')/ORDERITEMS_SUBFORM(KLINE=1)`. A key value is a typed literal; it may not hold a slash, a percent sign, a backslash, a control character or two dots in a row, and the record's key fields cannot be changed. Deleting is not supported.
150
166
  - **Fields the metadata does not mark:** Priority may require them, and then refuses with `priority_rejected` and its own message.
151
167
 
152
168
  ## Comis
153
169
 
154
- [`comis/`](comis/README.md) holds the Comis connector bundle:
155
- - the catalog entry and the Gate template;
156
- - the wrapper;
157
- - the agent skills, including one that turns a plumber's Hebrew order message into a draft sales order.
170
+ Comis ships priority-axi in its optional apps pack:
171
+
172
+ - a read skill, and a write skill that turns a plumber's Hebrew order message into a draft sales order for the owner's approval;
173
+ - a Gate catalog entry that injects the password only on the routes priority-axi uses, with a template for a server on a public host.
174
+
175
+ That integration lives in the Comis repository.
158
176
 
159
177
  ## Development
160
178
 
package/dist/cli/parse.js CHANGED
@@ -4,7 +4,8 @@
4
4
  import { parseArgs } from 'node:util';
5
5
  import { usage } from '../errors.js';
6
6
  import { commandName, } from './table.js';
7
- const shownFlag = (raw) => /^--?[A-Za-z0-9][A-Za-z0-9-]{0,40}$/.test(raw) ? raw : 'that flag';
7
+ /** "flag --x", or just "flag" when the name is not safe to repeat back. */
8
+ const shownFlag = (raw) => /^--?[A-Za-z0-9][A-Za-z0-9_-]{0,40}$/.test(raw) ? `flag ${raw}` : 'flag';
8
9
  export function parseCommand(spec, argv) {
9
10
  const name = commandName(spec);
10
11
  const options = {};
@@ -33,7 +34,7 @@ export function parseCommand(spec, argv) {
33
34
  continue;
34
35
  const f = spec.flags[token.name];
35
36
  if (!f) {
36
- throw usage(`Unknown flag ${shownFlag(token.rawName)} for \`${name}\`. ${valid.length ? `Valid flags: ${valid.join(', ')}.` : 'It takes no flags.'}`);
37
+ throw usage(`Unknown ${shownFlag(token.rawName)} for \`${name}\`. ${valid.length ? `Valid flags: ${valid.join(', ')}.` : 'It takes no flags.'}`);
37
38
  }
38
39
  if (f.type === 'boolean' && token.inlineValue)
39
40
  throw usage(`--${token.name} takes no value.`);
package/dist/cli/run.js CHANGED
@@ -7,12 +7,13 @@ import { find as findRecords } from '../commands/find.js';
7
7
  import { home } from '../commands/home.js';
8
8
  import { changes, get, show } from '../commands/read.js';
9
9
  import { refresh } from '../commands/refresh.js';
10
+ import { addLine, update, updateLine } from '../commands/update.js';
10
11
  import { AxiError, usage } from '../errors.js';
11
12
  import { errorText } from '../output/toon.js';
12
13
  import { VERSION } from '../version.js';
13
14
  import { parseCommand } from './parse.js';
14
15
  import { BIN, CONNECTION_FLAGS, commandName, usageLine, } from './table.js';
15
- export const DESCRIPTION = 'Read and create Priority ERP records over its REST API';
16
+ export const DESCRIPTION = 'Read, create and update Priority ERP records over its REST API';
16
17
  export const COMMANDS = [
17
18
  {
18
19
  name: '',
@@ -63,7 +64,7 @@ export const COMMANDS = [
63
64
  type: 'string',
64
65
  multiple: true,
65
66
  value: '<F=V>',
66
- summary: 'Filter: F=V, F!=V, F>V, F>=V, F<V or F<=V',
67
+ summary: "Filter: F=V, F!=V, F>V, F>=V, F<V or F<=V. Dates and times are Priority's local (company) time",
67
68
  },
68
69
  filter: {
69
70
  type: 'string',
@@ -88,6 +89,11 @@ export const COMMANDS = [
88
89
  summary: 'Records per page, default 20, at most 500',
89
90
  },
90
91
  page: { type: 'string', value: '<n>', summary: 'Page number, default 1' },
92
+ offset: {
93
+ type: 'string',
94
+ value: '<n>',
95
+ summary: 'Records to skip first, instead of --page',
96
+ },
91
97
  full: {
92
98
  type: 'boolean',
93
99
  summary: 'Every non-empty field, no size limit',
@@ -131,13 +137,13 @@ export const COMMANDS = [
131
137
  type: 'string',
132
138
  required: true,
133
139
  value: '<time>',
134
- summary: 'From when: 7d, 24h, 2026-11-01 or a full UTC time',
140
+ summary: 'From when: 7d, 24h, 2026-11-01 or a full UTC time such as 2026-11-01T06:00:00Z',
135
141
  },
136
142
  where: {
137
143
  type: 'string',
138
144
  multiple: true,
139
145
  value: '<F=V>',
140
- summary: 'Filter, as for get',
146
+ summary: "Filter, as for get; times are Priority's local time",
141
147
  },
142
148
  fields: { type: 'string', value: '<A,B>', summary: 'Columns to show' },
143
149
  limit: {
@@ -146,6 +152,11 @@ export const COMMANDS = [
146
152
  summary: 'Records per page, default 20, at most 500',
147
153
  },
148
154
  page: { type: 'string', value: '<n>', summary: 'Page number, default 1' },
155
+ offset: {
156
+ type: 'string',
157
+ value: '<n>',
158
+ summary: 'Records to skip first, instead of --page',
159
+ },
149
160
  full: {
150
161
  type: 'boolean',
151
162
  summary: 'Every non-empty field, no size limit',
@@ -195,7 +206,7 @@ export const COMMANDS = [
195
206
  type: 'string',
196
207
  multiple: true,
197
208
  value: '<F=V>',
198
- summary: 'A field of the new record',
209
+ summary: "A field of the new record; times are Priority's local (company) time",
199
210
  },
200
211
  line: {
201
212
  type: 'string',
@@ -217,6 +228,70 @@ export const COMMANDS = [
217
228
  summary: 'Create a record; inside Comis the owner approves it first',
218
229
  run: create,
219
230
  },
231
+ {
232
+ name: 'update',
233
+ args: [
234
+ { name: '<SCREEN>', required: true },
235
+ { name: '<key>', required: true },
236
+ ],
237
+ flags: {
238
+ set: {
239
+ type: 'string',
240
+ multiple: true,
241
+ value: '<F=V>',
242
+ summary: "A field to change; times are Priority's local (company) time",
243
+ },
244
+ 'dry-run': {
245
+ type: 'boolean',
246
+ summary: 'Check and show the request without sending it',
247
+ },
248
+ ...CONNECTION_FLAGS,
249
+ },
250
+ summary: 'Change fields of one record; inside Comis the owner approves it first',
251
+ run: update,
252
+ },
253
+ {
254
+ name: 'add-line',
255
+ args: [
256
+ { name: '<SCREEN>', required: true },
257
+ { name: '<key>', required: true },
258
+ { name: '<SUB>', required: true },
259
+ { name: '<F=V>', required: true, variadic: true },
260
+ ],
261
+ flags: {
262
+ 'dry-run': {
263
+ type: 'boolean',
264
+ summary: 'Check and show the request without sending it',
265
+ },
266
+ ...CONNECTION_FLAGS,
267
+ },
268
+ summary: "Add one line to a record's sub-screen; inside Comis the owner approves it first",
269
+ run: addLine,
270
+ },
271
+ {
272
+ name: 'update-line',
273
+ args: [
274
+ { name: '<SCREEN>', required: true },
275
+ { name: '<key>', required: true },
276
+ { name: '<SUB>', required: true },
277
+ { name: '<line-key>', required: true },
278
+ ],
279
+ flags: {
280
+ set: {
281
+ type: 'string',
282
+ multiple: true,
283
+ value: '<F=V>',
284
+ summary: "A field of the line to change; times are Priority's local (company) time",
285
+ },
286
+ 'dry-run': {
287
+ type: 'boolean',
288
+ summary: 'Check and show the request without sending it',
289
+ },
290
+ ...CONNECTION_FLAGS,
291
+ },
292
+ summary: "Change one line of a record's sub-screen; inside Comis the owner approves it first",
293
+ run: updateLine,
294
+ },
220
295
  {
221
296
  name: 'refresh',
222
297
  args: [],
@@ -1,8 +1,8 @@
1
1
  // Shared steps for commands that talk to Priority.
2
2
  import { readSettings } from '../config.js';
3
3
  import { AxiError, usage } from '../errors.js';
4
- import { rowsOf, send, stringValue } from '../http.js';
5
- import { cacheDir, loadIndex, readCompany, readIndex, recordReach, staleReason, writeCompany, } from '../index/cache.js';
4
+ import { rowsOf, send, stringValue, timeLeft } from '../http.js';
5
+ import { cacheDir, LOCK_WAIT_MS, loadIndex, readCompany, readIndex, recordReach, staleReason, writeCompany, } from '../index/cache.js';
6
6
  import { screenSegment, utc } from '../odata.js';
7
7
  const text = (v) => (typeof v === 'string' ? v : undefined);
8
8
  export function open(input) {
@@ -67,7 +67,10 @@ export async function screenIndex(s) {
67
67
  if (cached && !staleReason(cached, { now }))
68
68
  return { index: cached };
69
69
  await checkCompany(s, false);
70
- return loadIndex(s.dir, indexSource(s), { now });
70
+ return loadIndex(s.dir, indexSource(s), {
71
+ now,
72
+ lockWaitMs: Math.min(LOCK_WAIT_MS, timeLeft(s.settings, s.input.io.http)),
73
+ });
71
74
  }
72
75
  /** A note for output when this command had to build the index first. */
73
76
  export function builtNote(loaded) {
@@ -3,13 +3,13 @@
3
3
  import { readFileSync } from 'node:fs';
4
4
  import { serviceRoot } from '../config.js';
5
5
  import { AxiError, usage } from '../errors.js';
6
- import { send } from '../http.js';
6
+ import { rowsOf, send } from '../http.js';
7
7
  import { resolveField, resolveScreen, resolveSub, } from '../index/build.js';
8
8
  import { recordReach } from '../index/cache.js';
9
- import { parseWhere, screenSegment, utc } from '../odata.js';
9
+ import { literal, localTime, parseWhere, queryString, screenSegment, } from '../odata.js';
10
10
  import { defaultColumns, tableRow } from '../output/shape.js';
11
11
  import { render } from '../output/toon.js';
12
- import { open, screenIndex, shellWord, str, strings, tokenLine, } from './common.js';
12
+ import { open, readScreen, screenIndex, shellWord, str, strings, tokenLine, } from './common.js';
13
13
  const INTEGER = new Set(['Int16', 'Int32', 'Int64', 'Byte', 'SByte']);
14
14
  const DECIMAL = new Set(['Decimal', 'Double', 'Single']);
15
15
  function writable(field, where) {
@@ -45,10 +45,10 @@ export function typedValue(field, raw, where) {
45
45
  return raw === 'true';
46
46
  }
47
47
  if (field.type === 'DateTimeOffset')
48
- return utc(raw, field.name);
48
+ return localTime(raw, field.name);
49
49
  throw usage(`${field.name} has type ${field.type}, which create cannot set.`);
50
50
  }
51
- function assign(type, where, target, term) {
51
+ export function assign(type, where, target, term) {
52
52
  const t = parseWhere(term);
53
53
  if (t.op !== '=')
54
54
  throw usage(`Set fields with FIELD=VALUE; ${t.field} uses ${t.op}.`);
@@ -150,6 +150,61 @@ function assemble(body, lines) {
150
150
  }
151
151
  return out;
152
152
  }
153
+ /**
154
+ * Priority saves a deep insert line by line and does not roll back: when it
155
+ * refuses line 2 or later (line 1 is the record itself), the record and any
156
+ * earlier lines are saved (live, 23.1), and its answer names no key. Report
157
+ * that as partly_saved, find the saved record with one read, and point to
158
+ * add-line, so the record is never created twice.
159
+ */
160
+ async function partlySaved(s, screen, header, lines, error) {
161
+ const line = error.formLine ?? 2;
162
+ const keys = screen.type.key.filter((k) => screen.type.fields.some((f) => f.name === k));
163
+ const terms = Object.entries(header).filter((entry) => ['string', 'number', 'boolean'].includes(typeof entry[1]));
164
+ const key = keys.length === 1 ? keys[0] : undefined;
165
+ const lookup = [
166
+ `priority-axi get ${screen.name}`,
167
+ ...terms.map(([f, v]) => `--where ${shellWord(`${f}=${String(v)}`)}`),
168
+ ...(key ? [`--sort ${key}:desc`] : []),
169
+ '--limit 3',
170
+ ].join(' ');
171
+ let found = [];
172
+ if (key && terms.length) {
173
+ try {
174
+ const filter = terms
175
+ .map(([f, v]) => {
176
+ const field = resolveField(screen.type, screen.name, f);
177
+ return `${field.name} eq ${literal(field, String(v))}`;
178
+ })
179
+ .join(' and ');
180
+ const answer = await readScreen(s, screen.name, queryString({
181
+ $filter: filter,
182
+ $select: key,
183
+ $orderby: `${key} desc`,
184
+ $top: 3,
185
+ }));
186
+ found = rowsOf(answer)
187
+ .map((r) => r[key])
188
+ .filter((v) => (typeof v === 'string' && v !== '') || typeof v === 'number')
189
+ .map(String);
190
+ }
191
+ catch {
192
+ found = [];
193
+ }
194
+ }
195
+ const subs = [...new Set(lines.map((l) => l.sub.name))];
196
+ const sub = subs.length === 1 ? subs[0] : '<SUB>';
197
+ const first = found[0];
198
+ const where = first
199
+ ? `The saved record is most likely ${first}, the newest ${screen.name} with these fields${found.length > 1 ? ` (older matches: ${found.slice(1).join(', ')})` : ''}; check it with \`priority-axi show ${screen.name} ${shellWord(first)}${sub === '<SUB>' ? '' : ` --with ${sub}`}\`. Add the corrected lines to it with \`priority-axi add-line ${screen.name} ${shellWord(first)} ${sub} F=V...\`.`
200
+ : `Find it with \`${lookup}\`, then add the corrected lines to it with \`priority-axi add-line ${screen.name} <key> ${sub} F=V...\`.`;
201
+ return new AxiError('partly_saved', `Priority saved the ${screen.name} record, and any lines before line ${line}, but refused line ${line} (line 1 is the record itself). Do not create it again. ${where}`, {
202
+ screen: screen.name,
203
+ line,
204
+ ...(first ? { saved: first } : { find: lookup }),
205
+ priority: error.message,
206
+ });
207
+ }
153
208
  export async function create(input) {
154
209
  const s = open(input);
155
210
  const { index } = await screenIndex(s);
@@ -187,6 +242,12 @@ export async function create(input) {
187
242
  catch (error) {
188
243
  if (error instanceof AxiError && error.code === 'screen_not_enabled')
189
244
  recordReach(s.dir, screen.name, 'no', now);
245
+ if (error instanceof AxiError &&
246
+ error.code === 'priority_rejected' &&
247
+ lines.length > 0 &&
248
+ (error.formLine ?? 0) >= 2) {
249
+ throw await partlySaved(s, screen, body, lines, error);
250
+ }
190
251
  throw error;
191
252
  }
192
253
  recordReach(s.dir, screen.name, 'yes', now);
@@ -7,9 +7,10 @@
7
7
  // word was in the record itself, or `parent` / `customer` when some were only
8
8
  // there.
9
9
  import { usage } from '../errors.js';
10
- import { rowsOf } from '../http.js';
10
+ import { rowsOf, timeLeft } from '../http.js';
11
11
  import { resolveScreen, resolveSub } from '../index/build.js';
12
- import { layout, pullCatalog, readCatalog, writeCatalog, } from '../index/catalog.js';
12
+ import { LOCK_WAIT_MS, withBuildLock } from '../index/cache.js';
13
+ import { catalogPath, layout, pullCatalog, readCatalog, writeCatalog, } from '../index/catalog.js';
13
14
  import { bounded, cut, render } from '../output/toon.js';
14
15
  import { haystack, missing, queryTerms, rank } from '../search.js';
15
16
  import { builtNote, commandLine, intFlag, open, readScreen, screenIndex, str, } from './common.js';
@@ -38,17 +39,21 @@ export async function find(input) {
38
39
  const lay = layout(screen, sub);
39
40
  const label = sub ? `${screen.name} > ${sub.name}` : screen.name;
40
41
  const now = input.io.now();
41
- let catalog = v.refresh === true
42
+ const cached = v.refresh === true
42
43
  ? undefined
43
44
  : readCatalog(s.dir, screen.name, sub?.name, lay.columns, now);
44
45
  let pulled;
45
- if (!catalog) {
46
- const started = performance.now();
47
- catalog = await pullCatalog(screen, sub, lay, async (query) => rowsOf(await readScreen(s, screen.name, query)), now);
48
- writeCatalog(s.dir, catalog);
49
- const seconds = Math.max(1, Math.round((performance.now() - started) / 1000));
50
- pulled = `built now: ${catalog.rows.length} ${sub ? 'lines' : 'records'} from Priority in ${seconds} s`;
51
- }
46
+ const catalog = cached ??
47
+ (await withBuildLock(`${catalogPath(s.dir, screen.name, sub?.name)}.lock`, () => v.refresh === true
48
+ ? undefined
49
+ : readCatalog(s.dir, screen.name, sub?.name, lay.columns, now), async () => {
50
+ const started = performance.now();
51
+ const built = await pullCatalog(screen, sub, lay, async (query) => rowsOf(await readScreen(s, screen.name, query)), now);
52
+ writeCatalog(s.dir, built);
53
+ const seconds = Math.max(1, Math.round((performance.now() - started) / 1000));
54
+ pulled = `built now: ${built.rows.length} ${sub ? 'lines' : 'records'} from Priority in ${seconds} s`;
55
+ return built;
56
+ }, Math.min(LOCK_WAIT_MS, timeLeft(s.settings, input.io.http))));
52
57
  const at = (name) => catalog.columns.indexOf(name);
53
58
  const statusAt = lay.status.map(at).filter((i) => i >= 0);
54
59
  const searchAt = lay.search.map(at).filter((i) => i >= 0);
@@ -18,20 +18,50 @@ function candidateSelect(type) {
18
18
  .map((f) => f.name);
19
19
  return [...keys, ...rest];
20
20
  }
21
+ /** The key fields of a sub-screen's lines that its type defines, to order them. */
22
+ function lineKey(sub) {
23
+ return sub.def.key.filter((k) => sub.def.fields.some((f) => f.name === k));
24
+ }
21
25
  /**
22
26
  * $expand for --with. Without --full, each line list is narrowed and capped on
23
27
  * the server: Priority 23.1 honours $select and $top inside $expand (live S9),
24
28
  * so a large order does not send every line. One extra line shows that more exist.
29
+ * Lines are ordered by their key, since Priority sends them in its own order.
25
30
  */
26
31
  function expandOf(subs, full) {
27
32
  if (!subs.length)
28
33
  return undefined;
29
34
  return subs
30
- .map((x) => !x.many || full
31
- ? x.nav
32
- : `${x.nav}($select=${candidateSelect(x.def).join(',')};$top=${LINES + 1})`)
35
+ .map((x) => {
36
+ if (!x.many)
37
+ return x.nav;
38
+ const key = lineKey(x);
39
+ const options = [
40
+ ...(full ? [] : [`$select=${candidateSelect(x.def).join(',')}`]),
41
+ ...(key.length ? [`$orderby=${key.join(',')}`] : []),
42
+ ...(full ? [] : [`$top=${LINES + 1}`]),
43
+ ];
44
+ return options.length ? `${x.nav}(${options.join(';')})` : x.nav;
45
+ })
33
46
  .join(',');
34
47
  }
48
+ /** Lines in key order, whatever order Priority sent them in. */
49
+ function byKey(sub, lines) {
50
+ const key = lineKey(sub);
51
+ if (!key.length)
52
+ return lines;
53
+ const cmp = (a, b) => typeof a === 'number' && typeof b === 'number'
54
+ ? a - b
55
+ : String(a ?? '').localeCompare(String(b ?? ''));
56
+ return [...lines].sort((a, b) => {
57
+ for (const k of key) {
58
+ const c = cmp(a[k], b[k]);
59
+ if (c)
60
+ return c;
61
+ }
62
+ return 0;
63
+ });
64
+ }
35
65
  function explicitFields(type, screen, raw) {
36
66
  if (raw === undefined)
37
67
  return undefined;
@@ -53,7 +83,7 @@ function subView(sub, value, fieldLimit, full) {
53
83
  : undefined;
54
84
  return { [sub.name]: one ? recordView(sub.def, one, fieldLimit) : null };
55
85
  }
56
- const lines = Array.isArray(value) ? value : [];
86
+ const lines = Array.isArray(value) ? byKey(sub, value) : [];
57
87
  const shown = full ? lines : lines.slice(0, LINES);
58
88
  const columns = defaultColumns(sub.def, shown);
59
89
  return {
@@ -75,6 +105,12 @@ async function list(input, mode) {
75
105
  const v = input.values;
76
106
  const limit = intFlag(v.limit, 'limit', 20, 1, 500);
77
107
  const page = intFlag(v.page, 'page', 1, 1, 1_000_000);
108
+ const byOffset = v.offset !== undefined;
109
+ if (byOffset && v.page !== undefined)
110
+ throw usage('Use --page or --offset, not both.');
111
+ const offset = intFlag(v.offset, 'offset', 0, 0, 500_000_000);
112
+ // The first record of this read, counted from 0.
113
+ const start = byOffset ? offset : (page - 1) * limit;
78
114
  const full = v.full === true;
79
115
  const since = mode === 'changes' ? sinceFlag(v.since, input.io.now()) : undefined;
80
116
  const filter = combineFilters(whereToFilter(strings(v.where), screen.type, screen.name), str(v.filter));
@@ -90,7 +126,7 @@ async function list(input, mode) {
90
126
  $select: select?.join(','),
91
127
  $orderby: order,
92
128
  $top: limit + 1,
93
- $skip: page > 1 ? (page - 1) * limit : undefined,
129
+ $skip: start || undefined,
94
130
  $expand: expandOf(subs, full),
95
131
  $since: since,
96
132
  }));
@@ -109,8 +145,13 @@ async function list(input, mode) {
109
145
  : defaultColumns(screen.type, rows));
110
146
  const noun = rows.length === 1 ? 'record' : 'records';
111
147
  const place = mode === 'changes' ? ` changed since ${since}` : '';
112
- const pageNote = page > 1 ? ` (page ${page})` : '';
113
- const summary = `${rows.length} ${noun} from ${screen.name}${place}${pageNote}${more ? ', more exist' : ''}`;
148
+ const pageNote = byOffset && offset > 0
149
+ ? ` (from record ${offset + 1})`
150
+ : page > 1
151
+ ? ` (page ${page})`
152
+ : '';
153
+ const summaryOf = (shown) => `${rows.length} ${noun} from ${screen.name}${place}${pageNote}${more ? ', more exist' : ''}${shown < rows.length ? `; ${shown} of ${rows.length} shown` : ''}`;
154
+ const summary = summaryOf(rows.length);
114
155
  if (!rows.length) {
115
156
  const help = filter || since
116
157
  ? [
@@ -134,19 +175,25 @@ async function list(input, mode) {
134
175
  return base;
135
176
  });
136
177
  const help = [];
137
- if (more) {
138
- help.push(`Run \`${commandLine(mode, [screen.name], v, { page: String(page + 1) })}\` for the next ${limit}`);
178
+ if (shown < rows.length) {
179
+ // Continue at the first record not shown, so none is skipped.
180
+ help.push(`Run \`${commandLine(mode, [screen.name], v, { page: null, offset: String(start + shown) })}\` for the records after the ${shown} shown`);
181
+ }
182
+ else if (more) {
183
+ help.push(byOffset
184
+ ? `Run \`${commandLine(mode, [screen.name], v, { offset: String(start + limit) })}\` for the next ${limit}`
185
+ : `Run \`${commandLine(mode, [screen.name], v, { page: String(page + 1) })}\` for the next ${limit}`);
139
186
  }
140
187
  if (keys.length === 1) {
141
188
  help.push(`Run \`priority-axi show ${screen.name} <${keys[0]}>\` for one record`);
142
189
  }
143
190
  return render({
144
- summary,
191
+ summary: summaryOf(shown),
145
192
  ...builtNote(loaded),
146
193
  records,
147
194
  ...(shown < rows.length
148
195
  ? {
149
- omitted: `${rows.length - shown} records not shown; use --limit ${Math.max(1, shown)} or --full`,
196
+ omitted: `${rows.length - shown} records not shown to keep the output small; the first help line continues after them, or use --full`,
150
197
  }
151
198
  : {}),
152
199
  }, help);
@@ -1,5 +1,6 @@
1
1
  // Rebuild the screen index now.
2
- import { loadIndex } from '../index/cache.js';
2
+ import { timeLeft } from '../http.js';
3
+ import { LOCK_WAIT_MS, loadIndex } from '../index/cache.js';
3
4
  import { render } from '../output/toon.js';
4
5
  import { checkCompany, indexSource, open, priorityVersion } from './common.js';
5
6
  export async function refresh(input) {
@@ -10,6 +11,7 @@ export async function refresh(input) {
10
11
  now: input.io.now(),
11
12
  refresh: true,
12
13
  liveVersion: version,
14
+ lockWaitMs: Math.min(LOCK_WAIT_MS, timeLeft(s.settings, input.io.http)),
13
15
  });
14
16
  const types = Object.values(index.types);
15
17
  const doc = {