@jinshuju/cli 0.23.0 → 0.24.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
@@ -227,6 +227,7 @@ issues exactly one request, and payload keys are field `api_code`s.
227
227
  ```bash
228
228
  jinshuju folder create Ledgers --kind table # folders are form or table; a table cannot go in a form folder
229
229
  jinshuju form edit Kp7mQ2 --json '{"name":"2026 signups"}'
230
+ jinshuju form edit Kp7mQ2 --json '{"setting":{"wording":{"submit":"立即报名"}}}' # the submit button; "" restores the default
230
231
  jinshuju form copy Kp7mQ2 --name Copy
231
232
  jinshuju form copy Kp7mQ2 --name 第二期 --with-notification-rules
232
233
  jinshuju form move Kp7mQ2 --folder Fd2xK8 # without --folder, moves it out of its folder
@@ -261,6 +262,8 @@ jinshuju entry update --form Kp7mQ2 12 --json '{"field_2":99}' #
261
262
  jinshuju entry update --form Kp7mQ2 12 --replace --json '{"field_1":"Bob"}' # replace; omitted fields are cleared
262
263
  jinshuju entry update --form Kp7mQ2 --batch @rows.json # [{serial_number, entry}]
263
264
  jinshuju entry delete --form Kp7mQ2 12 --yes
265
+ jinshuju entry state-flow get --form Kp7mQ2 12 --flow reservation_status # the state, and the events it can take now
266
+ jinshuju entry state-flow trigger --form Kp7mQ2 12 --flow reservation_status --event cancel_all --yes
264
267
 
265
268
  jinshuju view create --form Kp7mQ2 "High scores" --filter 'field_3 gte 80' --sort created_at:desc
266
269
  jinshuju comment create --form Kp7mQ2 --entry 12 "Contacted, awaiting reply"
@@ -272,7 +275,8 @@ jinshuju notification list --form Kp7mQ2 # each rule says whether it
272
275
  jinshuju notification log 6650b2 --form Kp7mQ2 --from 2026-10-01 # what the rule sent: how many succeeded, failed, and why
273
276
  ```
274
277
 
275
- Deletion always requires `--yes`. This CLI is non-interactive — stdin belongs to
278
+ Deletion always requires `--yes`, and so does a state flow event, which cannot
279
+ be undone either. This CLI is non-interactive — stdin belongs to
276
280
  `--json -` — so confirmation is a flag: without it nothing is deleted, rather
277
281
  than a prompt nobody is there to answer.
278
282
 
@@ -369,7 +373,7 @@ version has no such scope, and the routine commands answer it with 403 (exit
369
373
 
370
374
  ## Working with files
371
375
 
372
- Seven commands take a file. The CLI uploads with its own credential; there is no
376
+ Nine commands take a file. The CLI uploads with its own credential; there is no
373
377
  ticket to fetch first.
374
378
 
375
379
  ```bash
@@ -379,6 +383,8 @@ jinshuju entry import --table Vn4xR8 ./rows.csv --map field_1=1 --map field_2=2
379
383
  jinshuju entry create --form Kp7mQ2 --json '{"field_1":"Alice"}' --attach field_5=./id-card.jpg
380
384
  jinshuju form theme set Kp7mQ2 --wallpaper ./bg.png
381
385
  jinshuju opensearch edit Qy7nR3 --header ./banner.png
386
+ jinshuju form wheel-fortune edit Kp7mQ2 --json @wheel.json --prize-image 一等奖=./earbuds.png
387
+ jinshuju form quickpay edit Kp7mQ2 --json @quickpay.json --deliverable-file 电子书=./book.pdf
382
388
  jinshuju form image upload ./venue-map.png # answers with a url for an <img> in a form or field description
383
389
  jinshuju sms signature create 小金培训 --license ./license.jpg --company-name 小金培训有限公司 --company-id 91110000MA00000000 \
384
390
  --id-card-front ./front.jpg --id-card-back ./back.jpg --id-card-name 张三 --id-card-number 110101199001011234 --mobile 13800000000
@@ -462,6 +468,10 @@ the server answered with:
462
468
  }
463
469
  ```
464
470
 
471
+ A payload the CLI refuses before sending it (exit code 2, no `status`) carries
472
+ its reasons as `errors: [{ "pointers": ["/fields/0/required"], "message": … }]`,
473
+ the shape API v1 gives them in a 400's body.
474
+
465
475
  ## Timeouts and retries
466
476
 
467
477
  Every request has a deadline of one minute; `JINSHUJU_TIMEOUT_MS` changes it. A
@@ -1,9 +1,9 @@
1
1
  import { CONTAINER_LIST_OPTIONS, CONTAINER_OPTIONS, FILTER_OPTION, FILTERS_OPTION, JSON_OPTION, MINE_OPTION, PAGINATION_OPTIONS, SORT_OPTION, TIME_BUCKETS, UsageError, parseDimension, parseFilter, parseMetric, namedContainers, resolveContainer, resolveContainers } from '../options.js';
2
- import { LISTING, YES_OPTION, confirmed, filters, given, onContainer, paging, payload, refuseWithMine, requiredOption, sort } from './shared.js';
2
+ import { FORM_OPTION, LISTING, YES_OPTION, confirmed, filters, given, onContainer, paging, payload, refuseWithMine, requiredOption, sort } from './shared.js';
3
3
  import { RefusedError } from '../errors.js';
4
4
  import { progress } from '../progress.js';
5
5
  import { TransportError } from '../http.js';
6
- import { call, choices } from '../spec.js';
6
+ import { bodyChoices, call, choices } from '../spec.js';
7
7
  import { isRecord } from '../values.js';
8
8
  import { basename } from 'node:path';
9
9
  import { upload } from './upload.js';
@@ -26,6 +26,28 @@ const LABELS_OPTION = {
26
26
  type: 'boolean',
27
27
  description: "Pair each value with its field's label, saving a second read of the form"
28
28
  };
29
+ /** The flows an entry's state moves through, and the events that move it, as the API names them. */
30
+ const STATE_FLOWS = choices('getEntryStateFlow', 'flow');
31
+ const STATE_FLOW_EVENTS = bodyChoices('updateEntryStateFlow', 'event');
32
+ const STATE_FLOW_OPTION = {
33
+ name: '--flow',
34
+ type: 'string',
35
+ choices: STATE_FLOWS,
36
+ placeholder: '<flow>',
37
+ description: STATE_FLOWS ? `Which flow: ${STATE_FLOWS.join(', ')}` : 'Which flow'
38
+ };
39
+ const TRIGGER_OPTION = {
40
+ name: '--yes',
41
+ type: 'boolean',
42
+ description: 'Confirm the event, which cannot be undone'
43
+ };
44
+ function stateFlowPath(input) {
45
+ return {
46
+ form_token: requiredOption(input, 'form'),
47
+ serial_number: input.args.serial,
48
+ flow: requiredOption(input, 'flow')
49
+ };
50
+ }
29
51
  /**
30
52
  * `entry aggregate` answers a table taken apart: `columns` says what each
31
53
  * column is, `rows` holds one positional array per row and no names at all.
@@ -763,5 +785,61 @@ export const ENTRY = [
763
785
  path: { serial_number: input.args.serial },
764
786
  query: { fields: list(input.options.fields), include_labels: labels(input) }
765
787
  })
788
+ },
789
+ {
790
+ path: ['entry', 'state-flow', 'get'],
791
+ summary: "Show an entry's state in a flow, and the events it can take now",
792
+ description: "red_envelope_audit_state is the review of an entry's red envelope, reservation_status its " +
793
+ "reservation, and wheel_fortune_prize_audit_state the lucky wheel's winners, each with the id " +
794
+ '`entry state-flow trigger --target` takes. Forms only; takes the form creator, admin or data maintainer role.',
795
+ args: [{ name: 'serial', required: true, description: 'Entry serial number' }],
796
+ options: [FORM_OPTION, STATE_FLOW_OPTION],
797
+ request: (input) => call('getEntryStateFlow', { path: stateFlowPath(input) }),
798
+ examples: [
799
+ 'jinshuju entry state-flow get --form Kp7mQ2 12 --flow red_envelope_audit_state',
800
+ 'jinshuju entry state-flow get --form Kp7mQ2 12 --flow wheel_fortune_prize_audit_state'
801
+ ]
802
+ },
803
+ {
804
+ path: ['entry', 'state-flow', 'trigger'],
805
+ summary: 'Approve a red envelope, cancel a reservation or redeem a prize',
806
+ description: 'The event must be one `entry state-flow get` lists on the target now, and answers with the flow ' +
807
+ "afterwards. None can be undone: reda_confirm pays the red envelope out of the form's balance " +
808
+ 'and reda_refuse rejects it, cancel_all frees the reserved slots without refunding a paid entry, ' +
809
+ 'winner_confirm redeems a winner, and delete_winner removes one for good: its prize and voucher ' +
810
+ 'code do not go back to the pool. A winner is named by --target.',
811
+ args: [{ name: 'serial', required: true, description: 'Entry serial number' }],
812
+ options: [
813
+ FORM_OPTION,
814
+ STATE_FLOW_OPTION,
815
+ {
816
+ name: '--event',
817
+ type: 'string',
818
+ choices: STATE_FLOW_EVENTS,
819
+ placeholder: '<event>',
820
+ description: STATE_FLOW_EVENTS ? `Event to trigger: ${STATE_FLOW_EVENTS.join(', ')}` : 'Event to trigger'
821
+ },
822
+ {
823
+ name: '--target',
824
+ type: 'string',
825
+ placeholder: '<id>',
826
+ description: 'Winner id, from `entry state-flow get`; wheel_fortune_prize_audit_state only'
827
+ },
828
+ TRIGGER_OPTION
829
+ ],
830
+ request: (input) => {
831
+ const path = stateFlowPath(input);
832
+ const event = requiredOption(input, 'event');
833
+ confirmed(input, `Triggering ${event} on entry ${input.args.serial}`);
834
+ return call('updateEntryStateFlow', {
835
+ path,
836
+ body: given({ event, target_id: input.options.target })
837
+ });
838
+ },
839
+ examples: [
840
+ 'jinshuju entry state-flow trigger --form Kp7mQ2 12 --flow red_envelope_audit_state --event reda_confirm --yes',
841
+ 'jinshuju entry state-flow trigger --form Kp7mQ2 12 --flow reservation_status --event cancel_all --yes',
842
+ 'jinshuju entry state-flow trigger --form Kp7mQ2 12 --flow wheel_fortune_prize_audit_state --event winner_confirm --target 6af1381d114fae12e40e44eb --yes'
843
+ ]
766
844
  }
767
845
  ];
@@ -1,8 +1,9 @@
1
1
  import { FILTER_OPTION, FILTERS_OPTION, JSON_OPTION, MINE_OPTION, PAGINATION_OPTIONS, SORT_OPTION, UsageError } from '../options.js';
2
- import { FOLDER_OPTION, LISTING, filters, given, keywords, overriding, paging, payload, refuseWithMine, sort } from './shared.js';
2
+ import { FOLDER_OPTION, LISTING, filters, given, keywords, overriding, paging, payload, refuseWithMine, requiredOption, sort } from './shared.js';
3
3
  import { validateContainerPayload } from '../payload.js';
4
4
  import { bodyChoices, call } from '../spec.js';
5
- import { upload, uploadFormImage } from './upload.js';
5
+ import { readableSize, upload, uploadedId, uploadFormImage } from './upload.js';
6
+ import { isRecord } from '../values.js';
6
7
  /**
7
8
  * The shape behind `--json` on a form, shown rather than described: `fields` is
8
9
  * the part nothing else hints at, and one choice field carries more of the
@@ -41,6 +42,11 @@ const FORM_PAYLOAD = [
41
42
  'time-range, daily or entries rule. {"closed": false} reopens the form, and',
42
43
  'changing "closed" either way deletes the other three rules.',
43
44
  '',
45
+ 'setting.wording renames what the fill page says: "submit" is the submit',
46
+ "button's text, and its other keys the start button and the password, closed,",
47
+ 'not-open and fill-limit messages. A key left out keeps its text, and ""',
48
+ 'puts the default back.',
49
+ '',
44
50
  'Reading a form back does not give you something you can send again: a field',
45
51
  'written as "TextField" reads as "single_line_text". `field types` lists the',
46
52
  'names to write, and `field types <Type>` describes one.',
@@ -89,6 +95,154 @@ function includes(input) {
89
95
  }
90
96
  return query;
91
97
  }
98
+ /**
99
+ * What `form wheel-fortune edit --json` takes, shown rather than described: a
100
+ * gift and a voucher prize side by side carry most of what the shape asks.
101
+ */
102
+ const WHEEL_FORTUNE_PAYLOAD = [
103
+ '{',
104
+ ' "enabled": true,',
105
+ ' "prizes": [',
106
+ ' { "title": "一等奖", "prize_name": "蓝牙耳机", "probability": 5, "prize_amount": 10 },',
107
+ ' { "title": "二等奖", "prize_name": "咖啡券", "probability": 20, "prize_type": "voucher",',
108
+ ' "vouchers": [ { "code": "00123" }, { "code": "00124", "password": "p1" } ] }',
109
+ ' ],',
110
+ ' "lottery": { "limit_times": 1, "show_casher": false },',
111
+ ' "cash": { "cash_style": "code" },',
112
+ ' "text": { "win_text": "恭喜抽中 $(奖品名称)", "lose_text": "谢谢参与",',
113
+ ' "cash_text": "凭兑奖码到前台领取" }',
114
+ '}',
115
+ '',
116
+ 'Only the keys present are written, but "prizes" replaces the list as a whole:',
117
+ 'pass each prize to keep back with its "id" from `form wheel-fortune get`, or it',
118
+ 'goes with its winners. A voucher prize hands each winner one of its codes, and',
119
+ 'takes them only when it is added. "cash" cannot be changed once saved.',
120
+ '',
121
+ 'The lucky wheel is a paid add-on. "confirm_form_app_trial": true starts the',
122
+ "account's free trial, once per account, so ask its owner first. Turning the",
123
+ 'wheel on while the form ends with something else — a redirect, an exam score,',
124
+ 'a red envelope — is refused until "confirm_ending_conflicts": true, which',
125
+ 'switches the ending to a message as the editor does.',
126
+ '',
127
+ 'A "phone" cash and "send_sms" name a mobile field by its api_code:',
128
+ 'jinshuju field list --form <token>'
129
+ ];
130
+ const PRIZE_IMAGE_OPTION = {
131
+ name: '--prize-image',
132
+ type: 'string',
133
+ repeatable: true,
134
+ placeholder: '<title>=<file>',
135
+ description: 'Upload an image for the prize of this title in the payload, repeatable'
136
+ };
137
+ /**
138
+ * The files a flag ties to items of a payload list by one of their keys: a
139
+ * lucky wheel's prizes by title, a quick payment form's deliverables by name,
140
+ * which a caller can read off what they wrote. Every name is matched and every
141
+ * file found readable, and within `maxMegabytes` when given, before the first
142
+ * goes up: once one is uploaded, a failure on the next leaves it behind, and
143
+ * running the command again sends it a second time.
144
+ */
145
+ function namedFiles({ flag, values, items, key, noun, maxMegabytes }) {
146
+ const names = items.filter(isRecord).map((candidate) => candidate[key]);
147
+ const named = new Set();
148
+ return values.map((value) => {
149
+ const at = nameEnd(flag, value, names);
150
+ const name = value.slice(0, at);
151
+ const file = value.slice(at + 1);
152
+ if (at <= 0 || !file)
153
+ throw new UsageError(`${flag} must be '<${key}>=<file>', got ${JSON.stringify(value)}`);
154
+ if (named.has(name))
155
+ throw new UsageError(`${flag} names ${JSON.stringify(name)} twice`);
156
+ named.add(name);
157
+ const matching = items.filter((candidate) => isRecord(candidate) && candidate[key] === name);
158
+ if (matching.length === 0) {
159
+ throw new UsageError(`${flag} names ${JSON.stringify(name)}, but no ${noun} in the payload has that ${key}`);
160
+ }
161
+ if (matching.length > 1) {
162
+ throw new UsageError(`${flag} names ${JSON.stringify(name)}, which ${matching.length} ${noun}s share`);
163
+ }
164
+ const size = readableSize(file);
165
+ if (maxMegabytes !== undefined && size > maxMegabytes * 1024 * 1024) {
166
+ throw new UsageError(`${file} is over ${maxMegabytes} MB`);
167
+ }
168
+ return { item: matching[0], file };
169
+ });
170
+ }
171
+ /**
172
+ * Where `<name>=<file>` splits. A name and a path may each hold a `=`, so it is
173
+ * at the `=` whose left side is one of the names, or the first when none is.
174
+ */
175
+ function nameEnd(flag, value, names) {
176
+ const ends = [];
177
+ for (let at = value.indexOf('='); at !== -1; at = value.indexOf('=', at + 1)) {
178
+ if (names.includes(value.slice(0, at)))
179
+ ends.push(at);
180
+ }
181
+ if (ends.length > 1) {
182
+ const which = ends.map((at) => JSON.stringify(value.slice(0, at))).join(' or ');
183
+ throw new UsageError(`${flag} ${JSON.stringify(value)} could name ${which}`);
184
+ }
185
+ return ends[0] ?? value.indexOf('=');
186
+ }
187
+ /**
188
+ * Uploads each file and sets its id on its item, then saves. A failure after a
189
+ * file went up says which did and the id each went up as: an uploaded file
190
+ * stays, and a second run that puts its id in the payload need not upload it
191
+ * again.
192
+ */
193
+ async function uploadThenSave({ targets, key, upload, what, save }) {
194
+ const uploaded = [];
195
+ let step = '';
196
+ try {
197
+ for (const { item, file } of targets) {
198
+ step = `uploading ${file}`;
199
+ item[key] = await upload(file);
200
+ uploaded.push(`${file} as ${key} ${item[key]}`);
201
+ }
202
+ step = `saving ${what}`;
203
+ return await save();
204
+ }
205
+ catch (error) {
206
+ if (uploaded.length === 0)
207
+ throw error;
208
+ throw new Error(`uploaded ${uploaded.join(', ')}, but ${step} failed: ${error.message}. ` +
209
+ 'Put each id in the payload to run again without uploading its file again.', { cause: error });
210
+ }
211
+ }
212
+ /**
213
+ * What `form quickpay edit --json` takes, shown rather than described: a link
214
+ * and a file deliverable side by side carry most of what the shape asks.
215
+ */
216
+ const QUICKPAY_PAYLOAD = [
217
+ '{',
218
+ ' "mode": "choice",',
219
+ ' "auto_delivery_enabled": true,',
220
+ ' "deliverables": [',
221
+ ' { "kind": "link", "name": "下载地址", "url": "https://example.com/book",',
222
+ ' "goods_item_api_codes": ["early"] },',
223
+ ' { "kind": "file", "name": "电子书", "goods_item_api_codes": ["early", "full"] }',
224
+ ' ]',
225
+ '}',
226
+ '',
227
+ 'Only the keys present are written, but "deliverables" replaces those of the',
228
+ 'goods field buyers see under the mode as a whole: pass each one to keep back',
229
+ 'with its "token" from `form quickpay get`. A file or image deliverable takes',
230
+ 'an "attachment_id"; --deliverable-file uploads a file and sets it on the',
231
+ 'deliverable of that name. While auto_delivery_enabled is on, buyers get the',
232
+ 'deliverables of the tier they paid for once they pay.',
233
+ '',
234
+ 'mode is fixed for one price, choice for buyers to pick a tier, custom for them',
235
+ 'to enter the amount, and the goods field has to fit it. A tier is named by the',
236
+ '"value" of one of the goods field\'s goods_items:',
237
+ 'jinshuju field list --form <token>'
238
+ ];
239
+ const DELIVERABLE_FILE_OPTION = {
240
+ name: '--deliverable-file',
241
+ type: 'string',
242
+ repeatable: true,
243
+ placeholder: '<name>=<file>',
244
+ description: 'Upload a file for the deliverable of this name in the payload, repeatable'
245
+ };
92
246
  function themeBody(input) {
93
247
  const rest = input.options.json ?? {};
94
248
  return overriding(rest, {
@@ -304,6 +458,7 @@ export const FORM = [
304
458
  examples: [
305
459
  'jinshuju form edit Kp7mQ2 --json \'{"name":"2026 活动报名"}\'',
306
460
  'jinshuju form edit Kp7mQ2 --json \'{"setting":{"daily_repeat_close_rule":{"time_periods":[{"start_time":{"hour":11,"minute":0},"end_time":{"hour":12,"minute":40}}]}}}\'',
461
+ 'jinshuju form edit Kp7mQ2 --json \'{"setting":{"wording":{"submit":"立即报名"}}}\'',
307
462
  'jinshuju form edit Kp7mQ2 --json \'{"exam_setting":{"limited_time":30}}\''
308
463
  ]
309
464
  },
@@ -405,6 +560,135 @@ export const FORM = [
405
560
  options: [JSON_OPTION],
406
561
  request: (input) => call('updateForm', { path: { form_token: input.args.form }, body: { field_rules: payload(input) } })
407
562
  },
563
+ {
564
+ path: ['form', 'wheel-fortune', 'get'],
565
+ summary: "Show a form's lucky wheel: prizes, draws, how winners redeem",
566
+ description: 'The prize ids are what `form wheel-fortune edit` passes back to keep a prize and its ' +
567
+ 'winners, and what `form wheel-fortune export-vouchers --prize` takes. An account that has ' +
568
+ 'neither bought nor tried the lucky wheel is answered 402, saying how to start its trial.',
569
+ args: [{ name: 'form', required: true, description: 'Form token' }],
570
+ request: (input) => call('getWheelFortune', { path: { form_token: input.args.form } }),
571
+ examples: ['jinshuju form wheel-fortune get Kp7mQ2']
572
+ },
573
+ {
574
+ path: ['form', 'wheel-fortune', 'edit'],
575
+ summary: "Set up a form's lucky wheel and turn it on or off",
576
+ description: 'Respondents go to the wheel after submitting once it is on. --prize-image uploads an image ' +
577
+ "and sets it on the payload's prize of that title in one command.",
578
+ payload: WHEEL_FORTUNE_PAYLOAD,
579
+ args: [{ name: 'form', required: true, description: 'Form token' }],
580
+ options: [
581
+ JSON_OPTION,
582
+ { name: '--enable', type: 'boolean', description: 'Turn the lucky wheel on' },
583
+ { name: '--disable', type: 'boolean', description: 'Turn the lucky wheel off' },
584
+ PRIZE_IMAGE_OPTION
585
+ ],
586
+ run: async (input, client) => {
587
+ if (input.options.enable && input.options.disable) {
588
+ throw new UsageError('--enable and --disable are opposites, pass one');
589
+ }
590
+ const json = input.options.json;
591
+ if (json !== undefined && !isRecord(json))
592
+ throw new UsageError('--json must be a JSON object');
593
+ const path = { form_token: input.args.form };
594
+ const enabled = input.options.enable ? true : input.options.disable ? false : undefined;
595
+ const body = overriding(json ?? {}, { enabled });
596
+ const images = input.options.prize_image ?? [];
597
+ if (images.length === 0)
598
+ return client.request(call('updateWheelFortune', { path, body }));
599
+ const prizes = Array.isArray(body.prizes)
600
+ ? body.prizes.map((prize) => (isRecord(prize) ? { ...prize } : prize))
601
+ : [];
602
+ const targets = namedFiles({ flag: '--prize-image', values: images, items: prizes, key: 'title', noun: 'prize' });
603
+ // What the setup would be refused for is said before an image goes up for it.
604
+ client.check?.(call('updateWheelFortune', { path, body: { ...body, prizes } }));
605
+ return uploadThenSave({
606
+ targets,
607
+ key: 'prize_image_id',
608
+ upload: (file) => uploadFormImage(client, file, 'wheel_fortune_prize'),
609
+ what: 'the lucky wheel',
610
+ save: () => client.request(call('updateWheelFortune', { path, body: { ...body, prizes } }))
611
+ });
612
+ },
613
+ examples: [
614
+ 'jinshuju form wheel-fortune edit Kp7mQ2 --json @wheel.json --prize-image 一等奖=./earbuds.png',
615
+ 'jinshuju form wheel-fortune edit Kp7mQ2 --disable',
616
+ 'jinshuju form wheel-fortune edit Kp7mQ2 --json \'{"confirm_form_app_trial":true,"lottery":{"limit_times":3,"show_casher":false}}\''
617
+ ]
618
+ },
619
+ {
620
+ path: ['form', 'wheel-fortune', 'export-vouchers'],
621
+ summary: 'Export the vouchers a prize has not handed out yet',
622
+ description: 'Answers with a link to an Excel file of the codes, and how many there are.',
623
+ args: [{ name: 'form', required: true, description: 'Form token' }],
624
+ options: [
625
+ {
626
+ name: '--prize',
627
+ type: 'string',
628
+ placeholder: '<id>',
629
+ description: 'Voucher prize id, from `form wheel-fortune get`'
630
+ }
631
+ ],
632
+ request: (input) => call('exportRemainingVouchers', {
633
+ path: { form_token: input.args.form, prize_id: requiredOption(input, 'prize') }
634
+ }),
635
+ examples: ['jinshuju form wheel-fortune export-vouchers Kp7mQ2 --prize 6af1381d114fae12e40e44ea']
636
+ },
637
+ {
638
+ path: ['form', 'quickpay', 'get'],
639
+ summary: "Show a quick payment form's payment mode, and what buyers get once they pay",
640
+ description: 'goods_field_api_code is the goods field buyers see under the mode, and only its deliverables are ' +
641
+ "handed out. A deliverable's token is what `form quickpay edit` passes back to keep it. Quick " +
642
+ 'payment forms only.',
643
+ args: [{ name: 'form', required: true, description: 'Form token' }],
644
+ request: (input) => call('getQuickpaySetting', { path: { form_token: input.args.form } }),
645
+ examples: ['jinshuju form quickpay get Kp7mQ2']
646
+ },
647
+ {
648
+ path: ['form', 'quickpay', 'edit'],
649
+ summary: "Set a quick payment form's payment mode, and what buyers get once they pay",
650
+ description: "--deliverable-file uploads a file of up to 200 MB and sets it on the payload's deliverable of " +
651
+ 'that name in one command. An upload has the one-minute deadline of every request; give a large ' +
652
+ 'file on a slow line longer with JINSHUJU_TIMEOUT_MS.',
653
+ payload: QUICKPAY_PAYLOAD,
654
+ args: [{ name: 'form', required: true, description: 'Form token' }],
655
+ options: [JSON_OPTION, DELIVERABLE_FILE_OPTION],
656
+ run: async (input, client) => {
657
+ const json = payload(input);
658
+ if (!isRecord(json))
659
+ throw new UsageError('--json must be a JSON object');
660
+ const path = { form_token: input.args.form };
661
+ const body = { ...json };
662
+ const files = input.options.deliverable_file ?? [];
663
+ if (files.length === 0)
664
+ return client.request(call('updateQuickpaySetting', { path, body }));
665
+ const deliverables = Array.isArray(body.deliverables)
666
+ ? body.deliverables.map((deliverable) => (isRecord(deliverable) ? { ...deliverable } : deliverable))
667
+ : [];
668
+ const targets = namedFiles({
669
+ flag: '--deliverable-file',
670
+ values: files,
671
+ items: deliverables,
672
+ key: 'name',
673
+ noun: 'deliverable',
674
+ maxMegabytes: 200
675
+ });
676
+ // What the settings would be refused for is said before a file goes up for them.
677
+ client.check?.(call('updateQuickpaySetting', { path, body: { ...body, deliverables } }));
678
+ return uploadThenSave({
679
+ targets,
680
+ key: 'attachment_id',
681
+ upload: (file) => uploadedId(client, { id: 'uploadGoodsDeliverableAttachment', path, file, key: 'id' }),
682
+ what: 'the quick payment settings',
683
+ save: () => client.request(call('updateQuickpaySetting', { path, body: { ...body, deliverables } }))
684
+ });
685
+ },
686
+ examples: [
687
+ 'jinshuju form quickpay edit Kp7mQ2 --json @quickpay.json --deliverable-file 电子书=./book.pdf',
688
+ 'jinshuju form quickpay edit Kp7mQ2 --json \'{"auto_delivery_enabled":false}\'',
689
+ 'jinshuju form quickpay edit Kp7mQ2 --json \'{"mode":"fixed"}\''
690
+ ]
691
+ },
408
692
  {
409
693
  path: ['form', 'cooperator', 'list'],
410
694
  summary: 'List the cooperators of a form',
@@ -1,10 +1,8 @@
1
1
  import { PAGINATION_OPTIONS, UsageError } from '../options.js';
2
- import { progress } from '../progress.js';
3
2
  import { bodyChoices, call, choices } from '../spec.js';
4
3
  import { confirmed, DAY_RANGE_OPTIONS, dayRange, ESTIMATE_OPTION, estimating, FORM_OPTION, given, LISTING, NARROWING_OPTIONS, narrowingBody, narrowingQuery, paging, requiredOption as required, SELECT_ALL_OPTION, selectAll, SEND_OPTION, sendingConfirmed, YES_OPTION } from './shared.js';
5
- import { upload } from './upload.js';
6
- import { statSync } from 'node:fs';
7
- import { basename, extname } from 'node:path';
4
+ import { readableSize, uploadedId } from './upload.js';
5
+ import { extname } from 'node:path';
8
6
  /**
9
7
  * A signature is applied for with license images, which go up first as the
10
8
  * caller's own uploads and are then referred to by id. The review takes a
@@ -93,27 +91,12 @@ function checkLicenseFiles(files) {
93
91
  if (!LICENSE_EXTENSIONS.includes(extname(file).toLowerCase())) {
94
92
  throw new UsageError(`${file} is not a jpg, jpeg, png or bmp image`);
95
93
  }
96
- let size;
97
- try {
98
- size = statSync(file).size;
99
- }
100
- catch (error) {
101
- throw new UsageError(`could not read ${file}: ${error.message}`);
102
- }
103
- if (size > LICENSE_MAX_BYTES)
94
+ if (readableSize(file) > LICENSE_MAX_BYTES)
104
95
  throw new UsageError(`${file} is over 5 MB`);
105
96
  }
106
97
  }
107
- async function uploadLicense(client, file) {
108
- const watching = progress();
109
- watching.step(`uploading ${basename(file)}…`);
110
- try {
111
- const uploaded = await client.request(upload('uploadUserLicenseAttachment', {}, file));
112
- return uploaded.attachment_id;
113
- }
114
- finally {
115
- watching.done();
116
- }
98
+ function uploadLicense(client, file) {
99
+ return uploadedId(client, { id: 'uploadUserLicenseAttachment', file, key: 'attachment_id' });
117
100
  }
118
101
  /**
119
102
  * The materials the flags give, with their files uploaded. Only the flags that
@@ -4,7 +4,7 @@ import { type OperationId } from '../spec.js';
4
4
  * What the CLI uploads a form image as. A test holds the list to the spec's
5
5
  * `image_type`, which is where it would otherwise drift.
6
6
  */
7
- export declare const FORM_IMAGE_TYPES: readonly ["description", "header", "wallpaper", "opensearch_header"];
7
+ export declare const FORM_IMAGE_TYPES: readonly ["description", "header", "wallpaper", "opensearch_header", "wheel_fortune_prize"];
8
8
  export type FormImageType = (typeof FORM_IMAGE_TYPES)[number];
9
9
  /**
10
10
  * A file on disk, as multipart. The three endpoints that take one authenticate
@@ -13,7 +13,24 @@ export type FormImageType = (typeof FORM_IMAGE_TYPES)[number];
13
13
  */
14
14
  export declare function upload(id: OperationId, path: Record<string, string>, file: string, extra?: Record<string, string>): HttpRequest;
15
15
  /**
16
- * An image that a form's theme or one of its public queries refers to by id, uploaded
17
- * with `imageType` saying which (header, wallpaper, opensearch_header).
16
+ * The size of a file about to go up, once it is found to be a file this
17
+ * process may read. A bare stat passes a directory and an unreadable file, and
18
+ * a command uploading several would then fail only after the first went up.
19
+ */
20
+ export declare function readableSize(file: string): number;
21
+ /** One file to upload, and the key of the id the answer gives it. */
22
+ interface Upload {
23
+ id: OperationId;
24
+ path?: Record<string, string>;
25
+ file: string;
26
+ extra?: Record<string, string>;
27
+ key: string;
28
+ }
29
+ /** A file uploaded with a progress line while it goes, answered by its id. */
30
+ export declare function uploadedId(client: HttpClient, { id, path, file, extra, key }: Upload): Promise<string>;
31
+ /**
32
+ * An image that a form's theme, one of its public queries or a prize of its lucky wheel
33
+ * refers to by id, uploaded with `imageType` saying which.
18
34
  */
19
35
  export declare function uploadFormImage(client: HttpClient, file: string, imageType: FormImageType): Promise<string>;
36
+ export {};
@@ -1,7 +1,7 @@
1
1
  import { UsageError } from '../options.js';
2
2
  import { progress } from '../progress.js';
3
3
  import { call } from '../spec.js';
4
- import { readFileSync } from 'node:fs';
4
+ import { accessSync, constants, readFileSync, statSync } from 'node:fs';
5
5
  import { basename, extname } from 'node:path';
6
6
  /**
7
7
  * The media type of an upload, by extension. The server stores the type the
@@ -25,7 +25,13 @@ const UPLOAD_TYPES = {
25
25
  * What the CLI uploads a form image as. A test holds the list to the spec's
26
26
  * `image_type`, which is where it would otherwise drift.
27
27
  */
28
- export const FORM_IMAGE_TYPES = ['description', 'header', 'wallpaper', 'opensearch_header'];
28
+ export const FORM_IMAGE_TYPES = [
29
+ 'description',
30
+ 'header',
31
+ 'wallpaper',
32
+ 'opensearch_header',
33
+ 'wheel_fortune_prize'
34
+ ];
29
35
  /**
30
36
  * A file on disk, as multipart. The three endpoints that take one authenticate
31
37
  * like every other request, so there is no ticket to fetch first: the file goes
@@ -47,17 +53,38 @@ export function upload(id, path, file, extra = {}) {
47
53
  return call(id, { path, form });
48
54
  }
49
55
  /**
50
- * An image that a form's theme or one of its public queries refers to by id, uploaded
51
- * with `imageType` saying which (header, wallpaper, opensearch_header).
56
+ * The size of a file about to go up, once it is found to be a file this
57
+ * process may read. A bare stat passes a directory and an unreadable file, and
58
+ * a command uploading several would then fail only after the first went up.
52
59
  */
53
- export async function uploadFormImage(client, file, imageType) {
60
+ export function readableSize(file) {
61
+ try {
62
+ accessSync(file, constants.R_OK);
63
+ const stats = statSync(file);
64
+ if (stats.isFile())
65
+ return stats.size;
66
+ }
67
+ catch (error) {
68
+ throw new UsageError(`could not read ${file}: ${error.message}`);
69
+ }
70
+ throw new UsageError(`could not read ${file}: not a file`);
71
+ }
72
+ /** A file uploaded with a progress line while it goes, answered by its id. */
73
+ export async function uploadedId(client, { id, path = {}, file, extra, key }) {
54
74
  const watching = progress();
55
75
  watching.step(`uploading ${basename(file)}…`);
56
76
  try {
57
- const uploaded = await client.request(upload('uploadFormImage', {}, file, { image_type: imageType }));
58
- return uploaded.attachment_id;
77
+ const answer = await client.request(upload(id, path, file, extra));
78
+ return answer[key];
59
79
  }
60
80
  finally {
61
81
  watching.done();
62
82
  }
63
83
  }
84
+ /**
85
+ * An image that a form's theme, one of its public queries or a prize of its lucky wheel
86
+ * refers to by id, uploaded with `imageType` saying which.
87
+ */
88
+ export function uploadFormImage(client, file, imageType) {
89
+ return uploadedId(client, { id: 'uploadFormImage', file, extra: { image_type: imageType }, key: 'attachment_id' });
90
+ }
package/dist/errors.d.ts CHANGED
@@ -7,6 +7,11 @@ export interface Refusal {
7
7
  readonly pointer: string;
8
8
  readonly message: string;
9
9
  }
10
+ /** A reason as API v1's 400 gives it in errors[]: every place it occurs, as JSON Pointers. */
11
+ export interface Reason {
12
+ readonly pointers: readonly string[];
13
+ readonly message: string;
14
+ }
10
15
  /**
11
16
  * A body refused here, before it was sent, by the openapi.yaml this CLI
12
17
  * shipped with (src/preflight.ts). Usage, like any input the CLI could not
@@ -61,8 +66,11 @@ export type ClassifiedError = {
61
66
  body?: unknown;
62
67
  /** Seconds the server asked for before trying again, when it said. */
63
68
  retry_after?: number;
64
- /** What a body was refused for before it was sent, each at its pointer. */
65
- errors?: readonly Refusal[];
69
+ /**
70
+ * What a body was refused for before it was sent, in the shape of a server's
71
+ * 400 so a caller reads both the same way.
72
+ */
73
+ errors?: readonly Reason[];
66
74
  };
67
75
  /**
68
76
  * Sorts a failure into its kind. An error that wraps another — "the form was