@jinshuju/cli 0.22.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
@@ -571,9 +581,14 @@ SMS go to each `--to`, at most 50. `--mention` @s group members by mobile number
571
581
  or everyone with `@all`; WeCom sends a message that mentions anyone as plain
572
582
  text, so leave Markdown out of it. SMS sends the channel's template: it takes
573
583
  no `--title` or `--content`, and each of the template's variables comes as
574
- `--variable <name>=<value>`. A sent message cannot be recalled, so it
575
- takes `--yes`. After a timeout, send again with the same `--idempotency-key`:
576
- the API answers the first records instead of sending twice.
584
+ `--variable <name>=<value>`. From Jiri, a webhook can push entries of a form or
585
+ table instead of a title and content: `--form` names it and each `--entry` a
586
+ serial number, at most 50, each entry in a request of its own shaped as a form
587
+ webhook notification pushes it. A webhook can also push JSON of your own
588
+ instead: `--body` is the whole request body, the text of a JSON object or
589
+ array, posted as it is. A sent message cannot be recalled, so it takes
590
+ `--yes`. After a timeout, send again with the same `--idempotency-key`: the
591
+ API answers the first records instead of sending twice.
577
592
 
578
593
  `message channel list` gives the ids `--channel` takes, `--type` narrowing
579
594
  them, and `message channel get <id>` shows one. Email needs no channel: without
@@ -585,6 +600,7 @@ jinshuju message channel list --type wxwork
585
600
  jinshuju message send --type wxwork --channel 6729f1c2a1b2c3d4e5f60718 --content '今天是星期三,该吃午饭啦!' --mention 13800000000 --yes
586
601
  jinshuju message send --type email --to someone@example.com --title 上课提醒 --content '明天上午 9 点开课' --yes
587
602
  jinshuju message send --type sms --channel 6729f1c2a1b2c3d4e5f60719 --to 13800000000 --variable var_1=张三 --variable var_2=9:00 --yes
603
+ jinshuju message send --type webhook --channel 6729f1c2a1b2c3d4e5f6071a --body '{"report":"orders","order_count":1}' --yes
588
604
  ```
589
605
 
590
606
  ## Artifacts
@@ -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',
@@ -16,7 +16,10 @@ export const MESSAGE = [
16
16
  description: 'Queues the message and answers at once with one record per recipient; a group robot or webhook is the ' +
17
17
  'recipient itself. --mention is for DingTalk and WeCom robots only, at most 50; WeCom sends a message that ' +
18
18
  "mentions anyone as plain text, so leave Markdown out of it. SMS sends the channel's template, so it takes no " +
19
- '--title or --content: give each of its variables with --variable. Sent messages cannot be recalled: after a timeout ' +
19
+ '--title or --content: give each of its variables with --variable. From Jiri, a webhook can push entries of a ' +
20
+ 'form or table instead of --title and --content: --form names it and --entry each serial number, each entry in a ' +
21
+ 'request of its own, shaped as a form webhook notification pushes it. A webhook can also push JSON of your own ' +
22
+ 'instead: --body is the whole request body, posted as it is. Sent messages cannot be recalled: after a timeout ' +
20
23
  'or a dropped connection, send again with the same --idempotency-key, which answers the first records instead ' +
21
24
  'of sending twice. --yes sends.',
22
25
  options: [
@@ -63,6 +66,26 @@ export const MESSAGE = [
63
66
  description: "Every variable the SMS channel's template declares, as it is named there (var_1...), each 1 to 100 " +
64
67
  'characters; repeatable'
65
68
  },
69
+ {
70
+ name: '--body',
71
+ type: 'string',
72
+ placeholder: '<json>',
73
+ description: 'For a webhook, in place of --title and --content: the whole request body, the text of a JSON object or ' +
74
+ 'array, at most 65536 bytes, posted as it is'
75
+ },
76
+ {
77
+ name: '--form',
78
+ type: 'string',
79
+ placeholder: '<token>',
80
+ description: 'Only from Jiri, for a webhook: the form or table whose entries --entry names'
81
+ },
82
+ {
83
+ name: '--entry',
84
+ type: 'integer',
85
+ repeatable: true,
86
+ placeholder: '<serial_number>',
87
+ description: 'Only from Jiri, for a webhook with --form: the serial number of an entry to push, repeatable, at most 50'
88
+ },
66
89
  {
67
90
  name: '--mention',
68
91
  type: 'string',
@@ -80,6 +103,17 @@ export const MESSAGE = [
80
103
  ],
81
104
  request: (input) => {
82
105
  const type = requiredOption(input, 'type');
106
+ const body = input.options.body;
107
+ if (body !== undefined) {
108
+ if (type !== 'webhook')
109
+ throw new UsageError(`--body is for --type webhook only, not ${type}`);
110
+ for (const flag of ['title', 'content', 'form', 'entry']) {
111
+ const value = input.options[flag];
112
+ if (Array.isArray(value) ? value.length > 0 : value !== undefined) {
113
+ throw new UsageError(`--${flag} cannot be combined with --body: the body is the whole request`);
114
+ }
115
+ }
116
+ }
83
117
  if (!input.options.yes)
84
118
  throw new UsageError('A sent message cannot be recalled; pass --yes to send');
85
119
  const variables = input.options.variable;
@@ -92,6 +126,9 @@ export const MESSAGE = [
92
126
  content: input.options.content,
93
127
  variables: variables && Object.fromEntries(variables.map(parseVariable)),
94
128
  mentioned_mobile_list: input.options.mention,
129
+ body,
130
+ form_token: input.options.form,
131
+ entries: input.options.entry,
95
132
  idempotency_key: input.options.idempotency_key
96
133
  })
97
134
  });
@@ -101,7 +138,10 @@ export const MESSAGE = [
101
138
  '--mention 13800000000 --yes',
102
139
  "jinshuju message send --type email --to someone@example.com --title 上课提醒 --content '明天上午 9 点开课' --yes",
103
140
  'jinshuju message send --type sms --channel 6729f1c2a1b2c3d4e5f60719 --to 13800000000 --variable var_1=张三 ' +
104
- '--variable var_2=9:00 --yes'
141
+ '--variable var_2=9:00 --yes',
142
+ 'jinshuju message send --type webhook --channel 6729f1c2a1b2c3d4e5f6071a --form Kp7mQ2 --entry 1282 --entry 1283 --yes',
143
+ 'jinshuju message send --type webhook --channel 6729f1c2a1b2c3d4e5f6071a ' +
144
+ '--body \'{"report":"orders","order_count":1}\' --yes'
105
145
  ]
106
146
  },
107
147
  {
@@ -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