@jacebenson/jsn 5.2.0 → 5.3.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 +72 -9
- package/package.json +1 -1
- package/skills/servicenow/SKILL.md +11 -1
- package/src/amb.js +370 -0
- package/src/app.js +8 -4
- package/src/cli.js +11 -1
- package/src/command-audience.js +1 -1
- package/src/commands/cases.js +218 -0
- package/src/commands/catalog/enrich.js +151 -56
- package/src/commands/catalog-order.js +99 -23
- package/src/commands/catalog.js +6 -5
- package/src/commands/records.js +110 -1
- package/src/commands/store.js +312 -0
- package/src/commands/updatesets.js +253 -11
- package/src/errors.js +10 -3
- package/src/output.js +28 -1
- package/src/record-command-profiles.js +1 -1
- package/src/record-watch.js +206 -0
- package/src/sdk.js +66 -1
- package/src/store.js +588 -0
- package/src/update-set-apply.js +287 -0
- package/src/welcome.js +324 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
// End-user case views: list/show/search over the case table the account can
|
|
2
|
+
// actually read. Which "case" a person means depends on the installed
|
|
3
|
+
// application, so the table is detected (or named explicitly) instead of
|
|
4
|
+
// assuming one product's schema. Reads only — every request goes through the
|
|
5
|
+
// normal authenticated Table API, so application roles and ACLs decide
|
|
6
|
+
// visibility; nothing here widens or bypasses them.
|
|
7
|
+
import { AppError, CodeForbidden, errUsage, errUsageHint } from '../errors.js';
|
|
8
|
+
import { buildQuerySuffix, formatCommandList, formatRecordForDisplay, getStringField, quoteShellArg, resolveFieldsParam } from '../helpers.js';
|
|
9
|
+
import { getRecord, listRecords, recordListParams } from '../records-engine.js';
|
|
10
|
+
import { declareCapabilities } from '../capabilities.js';
|
|
11
|
+
|
|
12
|
+
declareCapabilities('cases', {}); // read-only: no mutating subcommands
|
|
13
|
+
|
|
14
|
+
const TABLE = /^[a-z][a-z0-9_]*$/i;
|
|
15
|
+
const DEFAULT_COLUMNS = ['number', 'short_description', 'state', 'opened_by', 'sys_updated_on'];
|
|
16
|
+
|
|
17
|
+
// Detection order is presentation policy, not an access claim: each candidate
|
|
18
|
+
// is probed with the caller's own credentials.
|
|
19
|
+
const CASE_SOURCES = [
|
|
20
|
+
{ table: 'sn_customerservice_case', application: 'Customer Service Management', label: 'customer service case' },
|
|
21
|
+
{ table: 'sn_hr_core_case', application: 'HR Service Delivery', label: 'HR case' },
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
function sourceFor(table) { return CASE_SOURCES.find(source => source.table === table); }
|
|
25
|
+
function requireTableName(table) {
|
|
26
|
+
if (!TABLE.test(table || '')) throw errUsage('--table takes a table name such as sn_customerservice_case or sn_hr_core_case.');
|
|
27
|
+
return table;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Turn one failed case read into an honest error class. */
|
|
31
|
+
function caseReadError(table, error) {
|
|
32
|
+
const status = error?.status;
|
|
33
|
+
if (status === 401) return error; // already normalized by errAPI
|
|
34
|
+
if (status === 403) {
|
|
35
|
+
return new AppError(CodeForbidden, `Access to ${table} is denied for this account (HTTP 403).`,
|
|
36
|
+
'Case visibility follows the application roles and ACLs. Ask an administrator for access, or use a profile that has it.', 403);
|
|
37
|
+
}
|
|
38
|
+
if (status === 400 || status === 404) {
|
|
39
|
+
return errUsageHint(`Reading ${table} failed (HTTP ${status}).`,
|
|
40
|
+
'The case application may not be installed, or the query uses a field this table does not have. Try jsn cases tables, then --table with a supported table.');
|
|
41
|
+
}
|
|
42
|
+
return error;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** One read-only availability probe. Authentication failures are not a table fact. */
|
|
46
|
+
async function probe(app, table) {
|
|
47
|
+
const params = new URLSearchParams({ sysparm_limit: '1', sysparm_fields: 'sys_id', sysparm_display_value: 'false' });
|
|
48
|
+
try {
|
|
49
|
+
await app.sdk.list(table, params);
|
|
50
|
+
return { available: true };
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (error?.status === 401) throw error;
|
|
53
|
+
if (error?.status === 403) return { available: false, reason: 'denied (HTTP 403)', status: 403 };
|
|
54
|
+
if (error?.status === 400 || error?.status === 404) return { available: false, reason: `not installed (HTTP ${error.status})`, status: error.status };
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Pick the case table to read: --hr and --table are explicit, otherwise probe
|
|
61
|
+
* the known case applications in order and use the first readable one.
|
|
62
|
+
*/
|
|
63
|
+
async function resolveTable(app, argv) {
|
|
64
|
+
const explicit = argv.hr ? 'sn_hr_core_case' : argv.table === undefined ? undefined : requireTableName(argv.table);
|
|
65
|
+
if (argv.hr && argv.table !== undefined && argv.table !== 'sn_hr_core_case') throw errUsage('Choose --hr or --table, not both.');
|
|
66
|
+
if (explicit) {
|
|
67
|
+
const source = sourceFor(explicit);
|
|
68
|
+
return { table: explicit, application: source?.application ?? null, label: source?.label ?? 'case', source: 'explicit' };
|
|
69
|
+
}
|
|
70
|
+
const attempts = [];
|
|
71
|
+
for (const source of CASE_SOURCES) {
|
|
72
|
+
const probeResult = await probe(app, source.table);
|
|
73
|
+
attempts.push({ ...source, ...probeResult });
|
|
74
|
+
if (probeResult.available) return { ...source, source: 'detected', attempts };
|
|
75
|
+
}
|
|
76
|
+
const summary = attempts.map(a => `${a.table} ${a.reason}`).join('; ');
|
|
77
|
+
if (attempts.some(a => a.status === 403)) {
|
|
78
|
+
throw new AppError(CodeForbidden, `No readable case table for this account: ${summary}.`,
|
|
79
|
+
'Case visibility follows the application roles and ACLs. Ask an administrator for case access, or use a profile that has it.', 403);
|
|
80
|
+
}
|
|
81
|
+
throw errUsageHint(
|
|
82
|
+
`No readable case table on this instance: ${summary}.`,
|
|
83
|
+
'Install a case application (Customer Service Management or HR Service Delivery) and use an account with case access, or name a table explicitly with --table.',
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function listCases(app, argv, resolved, query) {
|
|
88
|
+
const columns = argv.columns ? argv.columns.split(',') : DEFAULT_COLUMNS;
|
|
89
|
+
const fields = resolveFieldsParam(columns);
|
|
90
|
+
const ordered = query ? `${query}^ORDERBYDESCsys_updated_on` : 'ORDERBYDESCsys_updated_on';
|
|
91
|
+
const params = recordListParams({ limit: argv.limit, offset: argv.offset, fields, query: ordered });
|
|
92
|
+
let records;
|
|
93
|
+
try {
|
|
94
|
+
records = await listRecords(app.sdk, { table: resolved.table, params, displayValues: argv.displayValues });
|
|
95
|
+
} catch (error) {
|
|
96
|
+
throw caseReadError(resolved.table, error);
|
|
97
|
+
}
|
|
98
|
+
const displayRecords = fields && !argv.displayValues ? records.map(r => formatRecordForDisplay(r, columns)) : records;
|
|
99
|
+
const breadcrumbs = [
|
|
100
|
+
{ action: 'search', cmd: `jsn cases search "<text>"${argv.hr ? ' --hr' : ''}`, description: 'Search cases' },
|
|
101
|
+
];
|
|
102
|
+
if (records.length === argv.limit) {
|
|
103
|
+
breadcrumbs.push({ action: 'next', cmd: `jsn cases list --limit ${argv.limit} --offset ${argv.offset + argv.limit}${buildQuerySuffix(argv.query)}`, description: 'Next page' });
|
|
104
|
+
}
|
|
105
|
+
if (argv.offset > 0) {
|
|
106
|
+
breadcrumbs.push({ action: 'prev', cmd: `jsn cases list --limit ${argv.limit} --offset ${Math.max(0, argv.offset - argv.limit)}${buildQuerySuffix(argv.query)}`, description: 'Previous page' });
|
|
107
|
+
}
|
|
108
|
+
app.ok({
|
|
109
|
+
table: resolved.table,
|
|
110
|
+
application: resolved.application,
|
|
111
|
+
table_source: resolved.source,
|
|
112
|
+
count: records.length,
|
|
113
|
+
columns,
|
|
114
|
+
records: displayRecords,
|
|
115
|
+
pagination: { limit: argv.limit, offset: argv.offset },
|
|
116
|
+
context: { instance_url: app.getEffectiveInstance() },
|
|
117
|
+
}, { summary: `${records.length} ${resolved.table}(s)`, breadcrumbs });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function listOptions(y) {
|
|
121
|
+
return y
|
|
122
|
+
.option('table', { type: 'string', describe: 'Case table to read (default: detected from installed case applications)' })
|
|
123
|
+
.option('hr', { type: 'boolean', default: false, describe: 'Read the HR case table (sn_hr_core_case)' })
|
|
124
|
+
.option('query', { type: 'string', describe: 'Encoded query (e.g. "active=true")' })
|
|
125
|
+
.option('columns', { alias: ['c', 'fields'], type: 'string', describe: 'Comma-separated columns' })
|
|
126
|
+
.option('limit', { alias: 'l', type: 'number', default: 20, describe: 'Max records' })
|
|
127
|
+
.option('offset', { alias: 'o', type: 'number', default: 0, describe: 'Offset' })
|
|
128
|
+
.option('display-values', { type: 'string', choices: ['raw', 'display', 'both'], describe: 'Reference values: raw, display or both' });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function showOptions(y) {
|
|
132
|
+
return y
|
|
133
|
+
.option('table', { type: 'string', describe: 'Case table to read (default: detected from installed case applications)' })
|
|
134
|
+
.option('hr', { type: 'boolean', default: false, describe: 'Read the HR case table (sn_hr_core_case)' })
|
|
135
|
+
.option('display-values', { type: 'string', choices: ['raw', 'display', 'both'], describe: 'Reference values: raw, display or both' });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function requireText(text) {
|
|
139
|
+
if (typeof text !== 'string' || !text.trim()) throw errUsage('Provide nonempty search text.');
|
|
140
|
+
if (text.includes('^')) throw errUsage('Search text cannot contain ^ (it separates encoded-query terms).');
|
|
141
|
+
return text.trim();
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function casesCmd(wrap) {
|
|
145
|
+
return {
|
|
146
|
+
command: 'cases [subcommand]',
|
|
147
|
+
aliases: ['case'],
|
|
148
|
+
describe: 'List, show or search service and HR cases visible to the connected account',
|
|
149
|
+
builder: (yargs) => yargs
|
|
150
|
+
.command({
|
|
151
|
+
command: 'list',
|
|
152
|
+
aliases: ['ls'],
|
|
153
|
+
describe: 'List cases the connected account can read',
|
|
154
|
+
builder: listOptions,
|
|
155
|
+
handler: wrap(async (argv, app) => {
|
|
156
|
+
const resolved = await resolveTable(app, argv);
|
|
157
|
+
await listCases(app, argv, resolved, argv.query || '');
|
|
158
|
+
}),
|
|
159
|
+
})
|
|
160
|
+
.command({
|
|
161
|
+
command: 'search <text>',
|
|
162
|
+
describe: 'Search case number and short description',
|
|
163
|
+
builder: y => listOptions(y).positional('text', { type: 'string' }),
|
|
164
|
+
handler: wrap(async (argv, app) => {
|
|
165
|
+
const text = requireText(argv.text);
|
|
166
|
+
const resolved = await resolveTable(app, argv);
|
|
167
|
+
await listCases(app, argv, resolved, `numberLIKE${text}^ORshort_descriptionLIKE${text}`);
|
|
168
|
+
}),
|
|
169
|
+
})
|
|
170
|
+
.command({
|
|
171
|
+
command: 'show <number>',
|
|
172
|
+
aliases: ['get'],
|
|
173
|
+
describe: 'Show one case by number',
|
|
174
|
+
builder: showOptions,
|
|
175
|
+
handler: wrap(async (argv, app) => {
|
|
176
|
+
const resolved = await resolveTable(app, argv);
|
|
177
|
+
let record;
|
|
178
|
+
try {
|
|
179
|
+
record = await getRecord(app.sdk, { table: resolved.table, identifier: argv.number, matchField: 'number', displayValues: argv.displayValues, resource: resolved.label });
|
|
180
|
+
} catch (error) {
|
|
181
|
+
throw caseReadError(resolved.table, error);
|
|
182
|
+
}
|
|
183
|
+
record._context = { instance_url: app.getEffectiveInstance(), table: resolved.table };
|
|
184
|
+
app.ok(record, {
|
|
185
|
+
summary: `${resolved.label.charAt(0).toUpperCase() + resolved.label.slice(1)} ${getStringField(record, 'number') || argv.number}`,
|
|
186
|
+
breadcrumbs: [
|
|
187
|
+
{ action: 'list', cmd: `jsn cases list${argv.hr ? ' --hr' : argv.table ? ` --table ${quoteShellArg(argv.table)}` : ''}`, description: 'Back to cases' },
|
|
188
|
+
],
|
|
189
|
+
});
|
|
190
|
+
}),
|
|
191
|
+
})
|
|
192
|
+
.command({
|
|
193
|
+
command: 'tables',
|
|
194
|
+
describe: 'Report which case applications this instance exposes to the account',
|
|
195
|
+
handler: wrap(async (argv, app) => {
|
|
196
|
+
const sources = [];
|
|
197
|
+
for (const source of CASE_SOURCES) {
|
|
198
|
+
const probeResult = await probe(app, source.table);
|
|
199
|
+
sources.push({ ...source, ...probeResult });
|
|
200
|
+
}
|
|
201
|
+
app.ok({ sources, available: sources.filter(s => s.available).map(s => s.table) },
|
|
202
|
+
{ summary: sources.filter(s => s.available).length ? `Case tables: ${sources.filter(s => s.available).map(s => s.table).join(', ')}` : 'No readable case table found',
|
|
203
|
+
breadcrumbs: [{ action: 'list', cmd: 'jsn cases list', description: 'List cases' }] });
|
|
204
|
+
}),
|
|
205
|
+
})
|
|
206
|
+
.epilogue([
|
|
207
|
+
'Default table: the first readable case application (Customer Service Management, then HR Service Delivery).',
|
|
208
|
+
'Use --hr for sn_hr_core_case or --table <name> for any case table you can read; jsn cases tables reports each one.',
|
|
209
|
+
'Reads use the caller\'s own credentials and ACLs. Self-service scoping is a query, not a bypass, and field names differ per application:',
|
|
210
|
+
' jsn cases list --query "opened_by=javascript:gs.getUserID()" --hr',
|
|
211
|
+
'Nothing here changes a case; use the application UI or records update for case work.',
|
|
212
|
+
].join('\n')),
|
|
213
|
+
handler: wrap(async (argv, app) => app.ok({ subcommands: argv.subcommands || [],
|
|
214
|
+
_formatted: formatCommandList({ title: 'Cases', commands: argv.subcommands || [] }) },
|
|
215
|
+
{ summary: 'Cases: list, show and search service or HR cases visible to the connected account',
|
|
216
|
+
breadcrumbs: [{ action: 'list', cmd: 'jsn cases list' + (argv.profile ? ` --profile ${quoteShellArg(argv.profile)}` : argv.instance ? ` --instance ${quoteShellArg(argv.instance)}` : ''), description: 'List visible cases' }] })),
|
|
217
|
+
};
|
|
218
|
+
}
|
|
@@ -1,24 +1,122 @@
|
|
|
1
|
-
// Catalog item enrichment —
|
|
1
|
+
// Catalog item enrichment — one place that reads a catalog item and shapes it
|
|
2
|
+
// for output. `catalogitems show` owns the user-facing view (and the
|
|
3
|
+
// describe/inputs aliases); `catalogitems order` reuses the same request-side
|
|
4
|
+
// read, so both agree on what a question is.
|
|
2
5
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
6
|
+
// Two calls, one answer:
|
|
7
|
+
// 1. the Table API (sc_cat_item + item_option_new) — the definition, always
|
|
8
|
+
// readable, and the fallback when the catalog API cannot answer;
|
|
9
|
+
// 2. /api/sn_sc/servicecatalog/items/{id} — what this account can actually
|
|
10
|
+
// request, with the variables a submission must answer.
|
|
11
|
+
// The catalog API wins when it answers; the definition list keeps the command
|
|
12
|
+
// useful when it does not (a producer whose server script throws, an item that
|
|
13
|
+
// is not in the catalog).
|
|
8
14
|
|
|
9
15
|
import { getStringField } from '../../helpers.js';
|
|
10
16
|
|
|
17
|
+
export const CATALOG_API = '/api/sn_sc/servicecatalog/items';
|
|
18
|
+
|
|
19
|
+
// Layout entries draw the form; they are not values a caller can send.
|
|
20
|
+
// Codes are item_option_new.type on a live instance (11 label, 14 macro,
|
|
21
|
+
// 17 macro with label, 19/20/24 containers, 23 html, 32 rich text label).
|
|
22
|
+
const LAYOUT_CODES = new Set([11, 14, 17, 19, 20, 23, 24, 32]);
|
|
23
|
+
const LAYOUT_TYPES = new Set([
|
|
24
|
+
'container_start', 'container_end', 'container_split',
|
|
25
|
+
'label', 'rich_text_label', 'html', 'break', 'formatter',
|
|
26
|
+
'macro', 'macro_with_abel', 'ui_macro',
|
|
27
|
+
]);
|
|
28
|
+
// "Requested for" (type 31) is mandatory in the API payload but is not a value
|
|
29
|
+
// the caller builds: the instance fills it from the session and --requested-for
|
|
30
|
+
// overrides it. It is reported separately so it never blocks an order.
|
|
31
|
+
export const REQUESTED_FOR = 31;
|
|
32
|
+
// item_option_new.type code → the same friendly word the catalog API uses, so
|
|
33
|
+
// the definition fallback and the API payload render identically. Codes taken
|
|
34
|
+
// from this instance's type choices; unknown codes fall back to null.
|
|
35
|
+
const TYPE_NAMES = {
|
|
36
|
+
1: 'yes_no', 2: 'multi_line_text', 3: 'multiple_choice', 4: 'numeric_scale',
|
|
37
|
+
5: 'select_box', 6: 'single_line_text', 7: 'check_box', 8: 'reference',
|
|
38
|
+
9: 'date', 10: 'date_time', 11: 'label', 14: 'macro', 16: 'wide_single_line_text',
|
|
39
|
+
17: 'macro_with_abel', 18: 'lookup_select_box', 19: 'container_start',
|
|
40
|
+
20: 'container_end', 21: 'list_collector', 23: 'html', 24: 'container_split',
|
|
41
|
+
25: 'masked', 26: 'email', 28: 'ip', 29: 'duration', 31: 'requested_for',
|
|
42
|
+
32: 'rich_text_label', 33: 'attachment', 40: 'table_name',
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** Raw value of a field: list rows come back as {value, display_value}. */
|
|
46
|
+
function rawValue(row, field) {
|
|
47
|
+
const v = row?.[field];
|
|
48
|
+
return v && typeof v === 'object' ? v.value : v;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const isInstanceSupplied = v => v?.friendly_type === 'requested_for' || Number(v?.type) === REQUESTED_FOR;
|
|
52
|
+
const object = v => v && typeof v === 'object' && !Array.isArray(v);
|
|
53
|
+
|
|
54
|
+
/** Read the item from the catalog API. Throws when the instance refuses. */
|
|
55
|
+
export async function readCatalogApiItem(sdk, sysID) {
|
|
56
|
+
const response = await sdk.request(`${sdk.baseURL}${CATALOG_API}/${sysID}`, { method: 'GET' });
|
|
57
|
+
if (!object(response?.result) || response.result.sys_id !== sysID) {
|
|
58
|
+
const error = new Error('Catalog API returned no readable item with the requested identity.');
|
|
59
|
+
error.code = 'api_error';
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
return response.result;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Flatten a catalog API `variables` tree into the questions a caller can
|
|
67
|
+
* answer. Containers are walked for their children; every other layout entry
|
|
68
|
+
* is dropped. A name is reported once — the API can repeat a variable inside a
|
|
69
|
+
* container.
|
|
70
|
+
*/
|
|
71
|
+
export function shapeVariables(list, out = [], seen = new Set()) {
|
|
72
|
+
if (!Array.isArray(list)) return out;
|
|
73
|
+
for (const entry of list) {
|
|
74
|
+
if (!object(entry)) continue;
|
|
75
|
+
const friendly = typeof entry.friendly_type === 'string' ? entry.friendly_type : '';
|
|
76
|
+
const name = typeof entry.name === 'string' ? entry.name : '';
|
|
77
|
+
if (name && !LAYOUT_TYPES.has(friendly) && !seen.has(name)) {
|
|
78
|
+
seen.add(name);
|
|
79
|
+
out.push({
|
|
80
|
+
name,
|
|
81
|
+
label: entry.label || entry.question_text || name,
|
|
82
|
+
type: entry.type ?? null,
|
|
83
|
+
friendly_type: friendly || null,
|
|
84
|
+
mandatory: entry.mandatory === true || entry.mandatory === 'true',
|
|
85
|
+
instance_supplied: isInstanceSupplied(entry),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
if (Array.isArray(entry.children)) shapeVariables(entry.children, out, seen);
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Shape one item_option_new row into the same question shape. */
|
|
94
|
+
function questionFromRow(row) {
|
|
95
|
+
const code = Number(rawValue(row, 'type'));
|
|
96
|
+
const name = getStringField(row, 'name');
|
|
97
|
+
if (!name || LAYOUT_CODES.has(code)) return null;
|
|
98
|
+
return {
|
|
99
|
+
name,
|
|
100
|
+
label: getStringField(row, 'question_text') || name,
|
|
101
|
+
type: Number.isFinite(code) ? code : null,
|
|
102
|
+
friendly_type: TYPE_NAMES[code] ?? null,
|
|
103
|
+
mandatory: String(rawValue(row, 'mandatory')) === 'true',
|
|
104
|
+
instance_supplied: code === REQUESTED_FOR,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Required / instance-supplied names for a question list. */
|
|
109
|
+
export function requestDetails(variables) {
|
|
110
|
+
return {
|
|
111
|
+
required: variables.filter(v => v.mandatory && !v.instance_supplied).map(v => v.name),
|
|
112
|
+
instanceSupplied: variables.filter(v => v.instance_supplied).map(v => v.name),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
11
116
|
/**
|
|
12
117
|
* Fetch a catalog item and assemble the full show envelope.
|
|
13
118
|
*
|
|
14
|
-
* @
|
|
15
|
-
* @param {object} deps.sdk - SDK handle (list/get).
|
|
16
|
-
* @param {string} deps.instanceUrl - Effective instance URL (for the item link).
|
|
17
|
-
* @param {string} deps.sysID - sc_cat_item sys_id.
|
|
18
|
-
* @returns {Promise<{data: object, standalone: Array, setVars: Array, totalVars: number}>}
|
|
19
|
-
* data is the envelope payload (no _formatted — the caller attaches it);
|
|
20
|
-
* standalone/setVars/totalVars are the raw groupings needed by
|
|
21
|
-
* buildCatalogFormatted.
|
|
119
|
+
* @returns {Promise<{data: object, variables: Array, totalVars: number, source: string}>}
|
|
22
120
|
*/
|
|
23
121
|
export async function enrichCatalogItem({ sdk, instanceUrl, sysID }) {
|
|
24
122
|
// Use list + display_value=all so reference fields (category, flow) resolve
|
|
@@ -32,30 +130,27 @@ export async function enrichCatalogItem({ sdk, instanceUrl, sysID }) {
|
|
|
32
130
|
if (!item) throw new Error(`Not found: ${sysID}`);
|
|
33
131
|
|
|
34
132
|
const vp = new URLSearchParams();
|
|
35
|
-
vp.set('sysparm_query', `cat_item=${sysID}^active=true`);
|
|
133
|
+
vp.set('sysparm_query', `cat_item=${sysID}^active=true^ORDERBYorder`);
|
|
36
134
|
vp.set('sysparm_limit', '100');
|
|
37
135
|
vp.set('sysparm_display_value', 'all');
|
|
38
136
|
vp.set('sysparm_fields', 'sys_id,name,question_text,type,order,mandatory,variable_set');
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
type: getStringField(v, 'type'),
|
|
49
|
-
mandatory: getStringField(v, 'mandatory'),
|
|
50
|
-
};
|
|
51
|
-
if (vs) {
|
|
52
|
-
if (!setVars.has(vs)) setVars.set(vs, { name: vs, variables: [] });
|
|
53
|
-
setVars.get(vs).variables.push(entry);
|
|
54
|
-
} else {
|
|
55
|
-
standalone.push(entry);
|
|
137
|
+
const rows = await sdk.list('item_option_new', vp);
|
|
138
|
+
|
|
139
|
+
let apiItem = null;
|
|
140
|
+
let apiError = '';
|
|
141
|
+
if (typeof sdk.request === 'function' && typeof sdk.baseURL === 'string') {
|
|
142
|
+
try {
|
|
143
|
+
apiItem = await readCatalogApiItem(sdk, sysID);
|
|
144
|
+
} catch (error) {
|
|
145
|
+
apiError = error?.message || 'catalog API read failed';
|
|
56
146
|
}
|
|
57
147
|
}
|
|
58
|
-
|
|
148
|
+
|
|
149
|
+
const fromApi = Array.isArray(apiItem?.variables);
|
|
150
|
+
const variables = fromApi
|
|
151
|
+
? shapeVariables(apiItem.variables)
|
|
152
|
+
: rows.map(questionFromRow).filter(Boolean);
|
|
153
|
+
const source = fromApi ? 'catalog_api' : 'item_option_new';
|
|
59
154
|
|
|
60
155
|
// Resolve flow name
|
|
61
156
|
let flowName = '', flowCmd = '';
|
|
@@ -69,6 +164,7 @@ export async function enrichCatalogItem({ sdk, instanceUrl, sysID }) {
|
|
|
69
164
|
}
|
|
70
165
|
const wfName = getStringField(item, 'workflow') || '';
|
|
71
166
|
const planName = getStringField(item, 'delivery_plan') || getStringField(item, 'execution_plan') || '';
|
|
167
|
+
const details = requestDetails(variables);
|
|
72
168
|
|
|
73
169
|
const data = {
|
|
74
170
|
name: getStringField(item, 'name'),
|
|
@@ -79,24 +175,22 @@ export async function enrichCatalogItem({ sdk, instanceUrl, sysID }) {
|
|
|
79
175
|
flow: flowName || undefined,
|
|
80
176
|
flow_cmd: flowCmd || undefined,
|
|
81
177
|
workflow: wfName || undefined,
|
|
82
|
-
|
|
83
178
|
execution_plan: planName || undefined,
|
|
84
|
-
variables
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
179
|
+
variables,
|
|
180
|
+
variables_source: source,
|
|
181
|
+
variables_reported: fromApi,
|
|
182
|
+
required_variables: details.required,
|
|
183
|
+
instance_supplied_variables: details.instanceSupplied,
|
|
184
|
+
...(apiError ? { variables_api_error: apiError } : {}),
|
|
89
185
|
};
|
|
90
186
|
|
|
91
|
-
return { data,
|
|
187
|
+
return { data, variables, totalVars: variables.length, source };
|
|
92
188
|
}
|
|
93
189
|
|
|
94
190
|
/**
|
|
95
|
-
* Styled-mode rendering of an enriched catalog item.
|
|
96
|
-
* original catalog.js — the output layer is being reworked elsewhere, so this
|
|
97
|
-
* stays byte-identical for now.
|
|
191
|
+
* Styled-mode rendering of an enriched catalog item.
|
|
98
192
|
*/
|
|
99
|
-
export function buildCatalogFormatted(data,
|
|
193
|
+
export function buildCatalogFormatted(data, variables = data.variables || [], source = data.variables_source) {
|
|
100
194
|
const lines = [];
|
|
101
195
|
lines.push(`${data.name} (sc_cat_item)`);
|
|
102
196
|
lines.push('');
|
|
@@ -118,19 +212,20 @@ export function buildCatalogFormatted(data, standalone, setVars, totalVars) {
|
|
|
118
212
|
lines.push(` ${data.workflow}`);
|
|
119
213
|
lines.push('');
|
|
120
214
|
}
|
|
121
|
-
if (
|
|
122
|
-
lines.push(
|
|
123
|
-
for (const v of
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
for (const s of setVars) {
|
|
128
|
-
lines.push(` [${s.name}]`);
|
|
129
|
-
for (const v of s.variables) {
|
|
130
|
-
const label = v.question_text || v.name;
|
|
131
|
-
lines.push(` ${label}: ${v.type}${String(v.mandatory) === 'true' ? ' (mandatory)' : ''}`);
|
|
132
|
-
}
|
|
215
|
+
if (variables.length) {
|
|
216
|
+
lines.push(`─ Catalog Questions (${source === 'catalog_api' ? 'catalog API' : 'item_option_new'}) ─`);
|
|
217
|
+
for (const v of variables) {
|
|
218
|
+
const type = v.friendly_type || (v.type === null ? '?' : String(v.type));
|
|
219
|
+
const flags = [v.mandatory ? 'required' : '', v.instance_supplied ? 'instance-supplied' : ''].filter(Boolean);
|
|
220
|
+
lines.push(` ${v.name} ${v.label} [${type}]${flags.length ? ` (${flags.join(', ')})` : ''}`);
|
|
133
221
|
}
|
|
222
|
+
if (data.required_variables?.length) lines.push(` required: ${data.required_variables.join(', ')}`);
|
|
223
|
+
if (data.instance_supplied_variables?.length) lines.push(` instance-supplied: ${data.instance_supplied_variables.join(', ')}`);
|
|
224
|
+
lines.push('');
|
|
225
|
+
}
|
|
226
|
+
if (data.variables_api_error) {
|
|
227
|
+
lines.push('─ Catalog API ─');
|
|
228
|
+
lines.push(` unavailable: ${data.variables_api_error}`);
|
|
134
229
|
lines.push('');
|
|
135
230
|
}
|
|
136
231
|
return lines.join('\n');
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { parseDataArg, confirmDelete, quoteShellArg } from '../helpers.js';
|
|
2
2
|
import { errAPI, errUsage } from '../errors.js';
|
|
3
|
+
import { CATALOG_API, readCatalogApiItem, shapeVariables } from './catalog/enrich.js';
|
|
3
4
|
|
|
4
5
|
const ID = /^[a-f0-9]{32}$/i;
|
|
5
|
-
const API =
|
|
6
|
+
const API = CATALOG_API;
|
|
7
|
+
const RITM = '/api/now/table/sc_req_item';
|
|
8
|
+
const MAX_REQUESTED_ITEMS = 10;
|
|
6
9
|
const object = v => v && typeof v === 'object' && !Array.isArray(v);
|
|
7
10
|
|
|
8
11
|
function emit(app, argv, data, summary, breadcrumbs = []) {
|
|
@@ -10,17 +13,67 @@ function emit(app, argv, data, summary, breadcrumbs = []) {
|
|
|
10
13
|
app.ok(data, { summary, breadcrumbs: breadcrumbs.map(h => ({ ...h, cmd: h.cmd + connection })) });
|
|
11
14
|
}
|
|
12
15
|
function requireId(id) { if (!ID.test(id || '')) throw errUsage('Use the full catalog item sys_id; find it with catalogitems search.'); }
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Item definition plus flattened question definitions.
|
|
19
|
+
*
|
|
20
|
+
* This is the request side of the catalog, not a second view command: the
|
|
21
|
+
* questions and the order come from the same payload, so `order` can never
|
|
22
|
+
* disagree with what `catalogitems show` printed. Items the catalog API cannot
|
|
23
|
+
* serve (record producers whose server scripts throw, non-catalog records)
|
|
24
|
+
* fail here rather than submitting against guessed definitions.
|
|
25
|
+
*/
|
|
26
|
+
async function inspect(app, id) {
|
|
27
|
+
const item = await readCatalogApiItem(app.sdk, id);
|
|
28
|
+
const variables = shapeVariables(item.variables);
|
|
29
|
+
return { item, variables, variablesReported: Array.isArray(item.variables) };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function isAnswered(value) {
|
|
33
|
+
if (value === undefined || value === null) return false;
|
|
34
|
+
if (typeof value === 'string') return value.trim() !== '';
|
|
35
|
+
if (Array.isArray(value)) return value.length > 0;
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Compare supplied variables against the item's own question definitions.
|
|
41
|
+
* The server remains the authority; this only refuses an obviously incomplete
|
|
42
|
+
* submission before a confirmation prompt or a POST.
|
|
43
|
+
*/
|
|
44
|
+
function reviewVariables(variables, supplied) {
|
|
45
|
+
const required = variables.filter(v => v.mandatory && !v.instance_supplied);
|
|
46
|
+
return {
|
|
47
|
+
requiredVariables: required.map(v => v.name),
|
|
48
|
+
missing: required.filter(v => !isAnswered(supplied[v.name])).map(v => v.name),
|
|
49
|
+
unknown: variables.length ? Object.keys(supplied).filter(name => !variables.some(v => v.name === name)) : [],
|
|
50
|
+
};
|
|
18
51
|
}
|
|
52
|
+
|
|
19
53
|
function itemHints(id) {
|
|
20
|
-
return [{ action: '
|
|
54
|
+
return [{ action: 'show', cmd: `jsn catalogitems show ${id}`, description: 'Read the item, its questions and required answers' },
|
|
21
55
|
{ action: 'preview', cmd: `jsn catalogitems order ${id} --dry-run --variables-file variables.json`, description: 'Preview an order without submitting' }];
|
|
22
56
|
}
|
|
23
57
|
|
|
58
|
+
/**
|
|
59
|
+
* Read the requested item(s) a submitted order produced. Failure here is
|
|
60
|
+
* reported, never retried, and never turns a placed order into an error.
|
|
61
|
+
*/
|
|
62
|
+
async function findRequestedItems(app, requestId) {
|
|
63
|
+
const params = new URLSearchParams({ sysparm_query: `request=${requestId}`, sysparm_fields: 'sys_id,number,cat_item', sysparm_limit: String(MAX_REQUESTED_ITEMS) });
|
|
64
|
+
try {
|
|
65
|
+
const response = await app.sdk.request(`${app.sdk.baseURL}${RITM}?${params}`, { method: 'GET' });
|
|
66
|
+
if (!Array.isArray(response?.result)) return { items: [], readable: false, error: 'unsupported response' };
|
|
67
|
+
return {
|
|
68
|
+
items: response.result.filter(r => object(r) && ID.test(r.sys_id || ''))
|
|
69
|
+
.map(r => ({ sys_id: r.sys_id, number: typeof r.number === 'string' ? r.number : null })),
|
|
70
|
+
readable: true,
|
|
71
|
+
};
|
|
72
|
+
} catch (error) {
|
|
73
|
+
return { items: [], readable: false, error: error?.status ? `HTTP ${error.status}` : 'read failed' };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
24
77
|
export function catalogOrderCommands(wrap) {
|
|
25
78
|
return [
|
|
26
79
|
{ command: 'search <text>', describe: 'Find requestable items through the Service Catalog API',
|
|
@@ -35,20 +88,14 @@ export function catalogOrderCommands(wrap) {
|
|
|
35
88
|
possibly_truncated: response.result.length === argv.limit }, `${response.result.length} catalog item(s)`,
|
|
36
89
|
response.result.flatMap(i => itemHints(i.sys_id).slice(0, 1)));
|
|
37
90
|
}) },
|
|
38
|
-
{ command: 'describe <id>', aliases: ['inputs'], describe: 'Read requestable item details, pricing and variable definitions',
|
|
39
|
-
builder: y => y.positional('id', { type: 'string' }),
|
|
40
|
-
handler: wrap(async (argv, app) => {
|
|
41
|
-
const item = await describe(app, argv.id);
|
|
42
|
-
emit(app, argv, item, item.name || item.short_description || argv.id, itemHints(argv.id));
|
|
43
|
-
}) },
|
|
44
91
|
{ command: 'order <id>', describe: 'Submit a catalog order with explicit confirmation',
|
|
45
92
|
builder: y => y.positional('id', { type: 'string' })
|
|
46
93
|
.option('variables', { type: 'string', describe: 'JSON object of catalog variable names/values' })
|
|
47
94
|
.option('variables-file', { type: 'string', describe: 'Read the variables object from a JSON file' })
|
|
48
95
|
.option('quantity', { type: 'number', default: 1, describe: 'Positive integer quantity (max 1000)' })
|
|
49
96
|
.option('requested-for', { type: 'string', describe: 'User sys_id; instance delegation rules still apply' })
|
|
50
|
-
.option('dry-run', { type: 'boolean', default: false, describe: 'Read item details and preview
|
|
51
|
-
.epilogue('Use describe to inspect variables first. Server-side rules validate the order
|
|
97
|
+
.option('dry-run', { type: 'boolean', default: false, describe: 'Read item details and preview variables; no order is submitted' })
|
|
98
|
+
.epilogue('Use describe to inspect variables and their types first. Requested for is supplied by the instance unless you pass --requested-for, so it is reported separately and never blocks an order. A preview only reads; submitting needs a write-enabled profile and an explicit confirmation (or --force). Server-side rules still validate the order, so a preview does not prove submission will succeed. Existing create/list/show commands manage definitions. Orders need no application/update-set selection.'),
|
|
52
99
|
handler: wrap(async (argv, app) => {
|
|
53
100
|
requireId(argv.id);
|
|
54
101
|
if (!Number.isInteger(argv.quantity) || argv.quantity < 1 || argv.quantity > 1000) throw errUsage('--quantity must be an integer from 1 to 1000.');
|
|
@@ -59,12 +106,26 @@ export function catalogOrderCommands(wrap) {
|
|
|
59
106
|
const variables = argv.variables !== undefined || file !== undefined
|
|
60
107
|
? parseDataArg({ data: argv.variables, 'data-file': file }) : {};
|
|
61
108
|
if (!object(variables)) throw errUsage('Catalog variables must be a JSON object.');
|
|
62
|
-
|
|
109
|
+
|
|
110
|
+
const { item, variables: definitions, variablesReported } = await inspect(app, argv.id);
|
|
63
111
|
if (item.sys_class_name && item.sys_class_name !== 'sc_cat_item') throw errUsage('order supports standard catalog items; record producers and order guides need their own submission workflows.');
|
|
64
112
|
if (item.active === false || item.active === 'false' || item.can_order === false) throw errUsage('This item is not currently orderable.');
|
|
65
|
-
|
|
66
|
-
|
|
113
|
+
|
|
114
|
+
// Only refuse on local evidence: an unreadable variable list is not
|
|
115
|
+
// proof that an item has no mandatory inputs.
|
|
116
|
+
const review = variablesReported ? reviewVariables(definitions, variables) : null;
|
|
117
|
+
if (review?.missing.length) {
|
|
118
|
+
throw errUsage(`Missing required catalog variable(s): ${review.missing.join(', ')}. Inspect them with: jsn catalogitems describe ${argv.id}`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const plan = {
|
|
122
|
+
item_id: argv.id, name: item.name || item.short_description, quantity: argv.quantity,
|
|
123
|
+
requested_for: requestedFor || null, variable_names: Object.keys(variables),
|
|
124
|
+
required_variables: review ? review.requiredVariables : [],
|
|
125
|
+
...(review?.unknown.length ? { unknown_variable_names: review.unknown } : {}),
|
|
126
|
+
};
|
|
67
127
|
if (argv.dryRun ?? argv['dry-run']) return emit(app, argv, { ...plan, submitted: false, server_validation: 'not performed' }, 'Catalog order preview; nothing submitted', itemHints(argv.id));
|
|
128
|
+
|
|
68
129
|
const rerun = ['catalogitems', 'order', argv.id, '--quantity', String(argv.quantity),
|
|
69
130
|
...(requestedFor ? ['--requested-for', requestedFor] : []),
|
|
70
131
|
...(file ? ['--variables-file', file] : Object.keys(variables).length ? ['--variables-file', '<variables.json>'] : [])];
|
|
@@ -83,11 +144,26 @@ export function catalogOrderCommands(wrap) {
|
|
|
83
144
|
throw errAPI(error.status || 0, 'Catalog submission did not return a confirmed order. Inspect your requests before retrying; the order may have been placed.');
|
|
84
145
|
}
|
|
85
146
|
const result = response?.result;
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
147
|
+
if (!object(result) || result.error || result.errMsg) throw errAPI(200, 'Catalog response did not confirm an order identity. Inspect your requests before retrying; do not resubmit automatically.');
|
|
148
|
+
// order_now answers with the request header (REQ); the requested item
|
|
149
|
+
// (RITM) identity is only knowable by reading the request's items.
|
|
150
|
+
const requestId = result.request_id || (result.table === 'sc_request' ? result.sys_id : undefined);
|
|
151
|
+
const requestNumber = result.request_number || (result.table === 'sc_request' ? result.number : undefined);
|
|
152
|
+
if (!ID.test(requestId || '') || typeof requestNumber !== 'string' || !requestNumber.trim()) throw errAPI(200, 'Catalog response did not confirm an order identity. Inspect your requests before retrying; do not resubmit automatically.');
|
|
153
|
+
|
|
154
|
+
const requested = await findRequestedItems(app, requestId);
|
|
155
|
+
emit(app, argv, {
|
|
156
|
+
item_id: argv.id, quantity: argv.quantity, request_id: requestId, request_number: requestNumber,
|
|
157
|
+
requested_items: requested.items,
|
|
158
|
+
requested_items_readable: requested.readable,
|
|
159
|
+
...(requested.error ? { requested_items_error: requested.error } : {}),
|
|
160
|
+
...(review?.unknown.length ? { unknown_variable_names: review.unknown } : {}),
|
|
161
|
+
submitted: true,
|
|
162
|
+
}, `Ordered: ${requestNumber}`, [
|
|
163
|
+
{ action: 'request', cmd: `jsn records get --table sc_request --sys-id ${requestId}`, description: 'Read the request header' },
|
|
164
|
+
...requested.items.filter(i => i.number).map(i => ({ action: 'item', cmd: `jsn requests show ${i.number}`, description: 'Read the requested item' })),
|
|
165
|
+
{ action: 'items', cmd: `jsn requests list --query ${quoteShellArg(`request=${requestId}`)}`, description: 'Track the request\'s items' },
|
|
166
|
+
]);
|
|
91
167
|
}) },
|
|
92
168
|
];
|
|
93
169
|
}
|