@wkgeo/cli 1.1.5 → 2.0.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.
@@ -1,985 +1,936 @@
1
- /**
2
- * 会员自助面(task-197 / 2026-11-02):把「线上会员中心早有、CLI 还没有」的 8 组动作补上。
3
- *
4
- * 为什么单独一个模块:这 8 条的共同点是**对象都是"我自己"**——
5
- * 我的账单 / 我的欠费 / 我的券 / 我的消息 / 我的开票 / 套餐目录 / 回收站 / 改站名。
6
- * 后端动作在 `wkgeo-user` 里早就写好了,`wkgeo-cli-fc` 也已经把它们**自持重建**并挂在 `/cli`
7
- * 的动作面里(`SELF_HOSTED_ACTIONS`,`src/user-core.js` 是代码副本)—— 所以本文件**只写命令层**:
8
- * 解析参数 → `ctx.callData(action)` → 表格 / `--json`。**一行云函数代码都不碰。**
9
- *
10
- * 四条约定(与既有命令逐条对齐):
11
- * 1. 只读命令直接发;写命令(`notify read` / `sites recycle restore` / `sites update`)
12
- * **默认 dry-run**,加 `--confirm` 才真发 —— 与 `lang save` / `member remove` 同一把闸。
13
- * 2. 服务端回什么,`--json` 就原样给什么(**不裁剪**):会员端以后加字段,agent 不用升级 CLI。
14
- * 3. 单位:金额一律"分",flag 名带 `-cents` 后缀(与 `wallet recharge --amount-cents` 一致),
15
- * 表格里才换成 `¥x.xx`。
16
- * 4. **故意没有**的动作:`purgeSite`(彻底删站,不可逆,线上只给管理员:
17
- * 「彻底删除只能由管理员操作;你可以把它还原回站点列表」)、开票、券核销。
18
- * 缺口写清在命令的 notes 里,不造"看起来能跑"的假命令。
19
- */
20
-
21
- import { UsageError, CliError } from '../errors.mjs';
22
- import { formatMoney, formatTime } from '../format.mjs';
23
-
24
- /* ══════════════════════════════ 公共小件 ══════════════════════════════ */
25
-
26
- /** 写动作的确认闸:不加就 dry-run(与 config-auth.mjs 的 CONFIRM_FLAG 同义) */
27
- const CONFIRM_FLAG = {
28
- confirm: {
29
- type: 'boolean',
30
- desc: '真发(不加只打印将要发什么,一个写请求都不发)',
31
- },
32
- };
33
-
34
- const LIMIT_FLAG = { type: 'string', desc: '返回条数上限' };
35
- const OFFSET_FLAG = { type: 'string', desc: '跳过前 N 条(翻页用,默认 0)' };
36
-
37
- /** 正整数 flag;非法直接给人话(带收到的原值,别让人猜) */
38
- function positiveInt(raw, flag, { min = 1, max } = {}) {
39
- const text = String(raw).trim();
40
- const n = Number(text);
41
- if (!Number.isInteger(n) || n < min || (max !== undefined && n > max)) {
42
- const range = max === undefined ? `不小于 ${min}` : `${min}~${max}`;
43
- throw new UsageError(`${flag} 必须是${range}的整数,收到:${raw}`);
44
- }
45
- return n;
46
- }
47
-
48
- /** 可选正整数:没传就不进请求体(服务端有默认值,别用 0 覆盖它) */
49
- function optionalInt(raw, flag, opts) {
50
- if (raw === undefined || raw === null || raw === '') return undefined;
51
- return positiveInt(raw, flag, opts);
52
- }
53
-
54
- /** 配额值:`null` = 不限量(服务端就是这么表达的,别显示成 0) */
55
- function quotaText(v) {
56
- return v === null || v === undefined ? '不限' : String(v);
57
- }
58
-
59
- /** `undefined` / `null` / 空串 → `-`,其余原样(表格里不留空白) */
60
- function dash(v) {
61
- return v === undefined || v === null || v === '' ? '-' : v;
62
- }
63
-
64
- /** 时间列:统一走 formatTime(服务端给的是 UTC ISO,本地时区展示) */
65
- const TIME = (v) => formatTime(v);
66
-
67
- /** dry-run 回执:把"将要发什么"结构化打印,**一个请求都不发** */
68
- function dryRun(ctx, action, request, lines) {
69
- const data = {
70
- dry_run: true,
71
- action,
72
- request,
73
- confirm_hint: '确认无误后加 --confirm 真发',
74
- };
75
- const { out } = ctx;
76
- if (!out.json) {
77
- out.head(`dry-run:${action}(没有发送任何写请求)`);
78
- for (const l of lines || []) out.line(` ${l}`);
79
- out.line('');
80
- out.line(' 确认无误后加 --confirm 真发。');
81
- }
82
- ctx.done(data);
83
- return data;
84
- }
85
-
86
- /* ══════════════════════════ ① wallet billing ══════════════════════════ */
87
-
88
- /**
89
- * `getMyBilling`:当前订阅 + 生效配额(套餐配额 + 加量包)+ 钱包余额。
90
- *
91
- * 与 `wkgeo wallet` 的分工:那条只给余额 / `wallet txns` 给流水;这条回答"我这个账号现在
92
- * **有哪些额度、到什么时候**"。三块配额分开列(套餐内 / 加量包 / 生效合计),因为用户最常问的
93
- * 就是"我买了加量包,额度到底加没加上"。
94
- */
95
- export const walletBillingCommand = {
96
- name: 'wallet billing',
97
- summary: '我的账单:当前订阅 / 生效配额(含加量包)/ 钱包余额',
98
- usage: 'wkgeo wallet billing',
99
- args: [],
100
- flags: {},
101
- examples: ['wkgeo wallet billing', 'wkgeo wallet billing --json'],
102
- notes: [
103
- '只读(`billing:self`),不发任何写请求。',
104
- '配额值是 `null` = **不限量**(不是 0,也不是"没有")。',
105
- '只看余额用 `wkgeo wallet`,看流水用 `wkgeo wallet txns`。',
106
- ],
107
- async run(ctx) {
108
- const { out } = ctx;
109
- const data = await ctx.callData('getMyBilling', {});
110
- const res = data && typeof data === 'object' ? data : {};
111
- const sub = res.subscription && typeof res.subscription === 'object' ? res.subscription : null;
112
- const quotas = res.quotas && typeof res.quotas === 'object' ? res.quotas : {};
113
- const planQuotas = res.plan_quotas && typeof res.plan_quotas === 'object' ? res.plan_quotas : {};
114
- const addons = res.addons && typeof res.addons === 'object' ? res.addons : {};
115
-
116
- if (!out.json) {
117
- out.head('我的账单');
118
- if (sub) {
119
- const planName = sub.plan_name || sub.plan_code || '-';
120
- out.line(` 订阅套餐:${planName}${sub.expired ? '(已过期)' : ''}`);
121
- out.line(` 订阅期间:${TIME(sub.started_at)} → ${TIME(sub.expires_at)}`);
122
- } else {
123
- out.line(' 订阅套餐:(未订阅)');
124
- }
125
- out.line(` 钱包余额:${formatMoney(res.balance_cents)}`);
126
-
127
- const keys = Array.from(
128
- new Set([...Object.keys(quotas), ...Object.keys(planQuotas), ...Object.keys(addons)]),
129
- );
130
- if (keys.length) {
131
- out.line('');
132
- out.table(
133
- [
134
- { title: '配额', key: 'key', width: 28 },
135
- { title: '套餐内', key: 'plan', width: 10, format: (v) => quotaText(v) },
136
- { title: '加量包', key: 'addon', width: 10, format: (v) => quotaText(v) },
137
- { title: '生效合计', key: 'total', width: 10, format: (v) => quotaText(v) },
138
- ],
139
- keys.map((k) => ({
140
- key: k,
141
- plan: planQuotas[k] === undefined ? null : planQuotas[k],
142
- addon: addons[k] === undefined ? null : addons[k],
143
- total: quotas[k] === undefined ? null : quotas[k],
144
- })),
145
- );
146
- }
147
- }
148
-
149
- ctx.done(res);
150
- return res;
151
- },
152
- };
153
-
154
- /* ═══════════════════════════ ② wallet debt ═══════════════════════════ */
155
-
156
- const DEBT_STATUS_TEXT = {
157
- none: '没有欠费',
158
- open: '待结清',
159
- overdue: '已逾期',
160
- };
161
-
162
- /** `getMyDebt`:欠费金额 / 到期日 / 宽限期 / 明细(自助还款在会员端,CLI 只读) */
163
- export const walletDebtCommand = {
164
- name: 'wallet debt',
165
- summary: '我的欠费(金额 / 应缴日期 / 宽限期 / 明细)',
166
- usage: 'wkgeo wallet debt',
167
- args: [],
168
- flags: {},
169
- examples: ['wkgeo wallet debt', 'wkgeo wallet debt --json'],
170
- notes: [
171
- '只读(`billing:self`)。**不含还款动作**:结清走会员端收银台。',
172
- '`debt_cents` 为 0 时 `status` 是 `none`,此时 `items` 一定是空数组。',
173
- ],
174
- async run(ctx) {
175
- const { out } = ctx;
176
- const data = await ctx.callData('getMyDebt', {});
177
- const res = data && typeof data === 'object' ? data : {};
178
- const debt = Number(res.debt_cents) || 0;
179
- const items = Array.isArray(res.items) ? res.items : [];
180
-
181
- if (!out.json) {
182
- out.head('我的欠费');
183
- if (!debt) {
184
- out.ok('没有欠费');
185
- } else {
186
- const statusText = DEBT_STATUS_TEXT[res.status] || dash(res.status);
187
- out.line(` 欠费金额:${formatMoney(debt)}(${statusText})`);
188
- out.line(` 应缴日期:${TIME(res.due_at)} 宽限期:${dash(res.grace_days)} 天`);
189
- if (items.length) {
190
- out.line('');
191
- out.table(
192
- [
193
- { title: '来源', key: 'source', width: 16 },
194
- { title: '金额', key: 'amount_cents', width: 12, format: (v) => formatMoney(v) },
195
- { title: '应缴日期', key: 'due_at', width: 20, format: TIME },
196
- { title: '状态', key: 'status', width: 10 },
197
- { title: '说明', key: 'remark', width: 30 },
198
- ],
199
- items,
200
- );
201
- }
202
- }
203
- }
204
-
205
- ctx.done(res);
206
- return res;
207
- },
208
- };
209
-
210
- /* ════════════════════════════ ③ coupons ════════════════════════════ */
211
-
212
- const COUPON_STATUSES = ['unused', 'used', 'expired'];
213
- const ORDER_KINDS = ['subscribe', 'site_renew', 'quota'];
214
- const COUPON_STATUS_TEXT = {
215
- unused: '未使用',
216
- locked: '已锁定',
217
- used: '已使用',
218
- expired: '已过期',
219
- canceled: '已作废',
220
- };
221
-
222
- /**
223
- * 我的优惠券:不带 `--usable` 看**全部券**;带 `--usable` 看**这笔单能用的券**(带抵扣预览)。
224
- *
225
- * 为什么拆成两条后端动作:`listUsableCoupons` 必须带 `order_kind` + `amount_cents`
226
- * (服务端按订单类型和金额挑券并算预览),缺一个就 400 —— 所以 CLI 也必须把这两个参数
227
- * 做成 `--usable` 的**前置条件**,而不是让它自己去猜。
228
- *
229
- * ⚠️ `amount_cents` **只影响"给你看哪些券"**,不参与定价:真正抵扣由下单接口按它自己算的
230
- * 订单金额重算(前端传的钱一律不采信)。CLI 这边更不可能用预览值去下单。
231
- */
232
- export const couponsCommand = {
233
- name: 'coupons',
234
- summary: '我的优惠券(默认全部;`--usable` 看某个订单能用的券与抵扣预览)',
235
- usage:
236
- 'wkgeo coupons [--status unused|used|expired] [--page 1] [--page-size 20]\n' +
237
- 'wkgeo coupons --usable --kind subscribe --amount-cents 2990',
238
- args: [],
239
- flags: {
240
- usable: {
241
- type: 'boolean',
242
- desc: '只看**这笔订单**能用的券(需同时给 --kind 与 --amount-cents)',
243
- },
244
- kind: {
245
- type: 'string',
246
- desc: `订单类型,仅 --usable 时用:${ORDER_KINDS.join(' / ')}(充值单不能用券)`,
247
- },
248
- 'amount-cents': {
249
- type: 'string',
250
- desc: '订单金额,**单位分**,仅 --usable 时用(只影响筛券与预览,不参与定价)',
251
- },
252
- status: { type: 'string', desc: `按状态筛:${COUPON_STATUSES.join(' / ')}(仅不带 --usable 时用)` },
253
- page: { type: 'string', desc: '页码(默认 1)' },
254
- 'page-size': { type: 'string', desc: '每页条数(默认 20)' },
255
- },
256
- examples: [
257
- 'wkgeo coupons',
258
- 'wkgeo coupons --status unused',
259
- 'wkgeo coupons --usable --kind subscribe --amount-cents 2990',
260
- ],
261
- notes: [
262
- '只读(`billing:self`)。**不含核销**:用券发生在下单时,由订单接口按它自己算的金额重算抵扣。',
263
- '`--status` 只认 `unused` / `used` / `expired`(服务端白名单,其它值直接 400)。',
264
- '`display_status` 是服务端算好的状态:券本身 `unused` 但已过期 → 显示 `expired`。',
265
- ],
266
- async run(ctx) {
267
- const { out, flags } = ctx;
268
-
269
- /* —— ① 这笔单能用的券 —— */
270
- if (flags.usable) {
271
- if (flags.status !== undefined) {
272
- throw new UsageError(
273
- '`--usable` 不接受 `--status`:可用券列表由 `--kind` + `--amount-cents` 决定(服务端没有第二个筛选项)',
274
- );
275
- }
276
- const kind = String(flags.kind === undefined ? '' : flags.kind).trim();
277
- if (!kind) {
278
- throw new UsageError(
279
- `\`--usable\` 需要 --kind(${ORDER_KINDS.join(' / ')}):服务端要按订单类型挑券`,
280
- );
281
- }
282
- if (!ORDER_KINDS.includes(kind)) {
283
- throw new UsageError(
284
- `--kind 只能是 ${ORDER_KINDS.join(' / ')},收到:${kind}\n(充值单不能用券:recharge 会被服务端 400 拒绝)`,
285
- );
286
- }
287
- if (flags.amountCents === undefined) {
288
- throw new UsageError('`--usable` 需要 --amount-cents(单位分):服务端要按订单金额挑券');
289
- }
290
- const amountCents = positiveInt(flags.amountCents, '--amount-cents', { min: 1 });
291
-
292
- const data = await ctx.callData('listUsableCoupons', {
293
- order_kind: kind,
294
- amount_cents: amountCents,
295
- });
296
- const res = data && typeof data === 'object' ? data : {};
297
- const rows = Array.isArray(res.rows) ? res.rows : [];
298
-
299
- if (!out.json) {
300
- out.head(
301
- `这笔单能用的券:${kind} · 订单金额 ${formatMoney(amountCents)}(共 ${rows.length} 张)`,
302
- );
303
- out.table(
304
- [
305
- { title: '券', key: 'template_name', width: 24 },
306
- { title: '面额', key: 'amount_cents', width: 10, format: (v) => formatMoney(v) },
307
- { title: '门槛', key: 'threshold_cents', width: 10, format: (v) => formatMoney(v) },
308
- {
309
- title: '抵扣预览',
310
- key: 'discount_preview_cents',
311
- width: 12,
312
- format: (v) => formatMoney(v),
313
- },
314
- {
315
- title: '应付预览',
316
- key: 'payable_preview_cents',
317
- width: 12,
318
- format: (v) => formatMoney(v),
319
- },
320
- { title: '到期', key: 'expires_at', width: 20, format: TIME },
321
- { title: '券 ID', key: 'user_coupon_id', width: 36 },
322
- ],
323
- rows,
324
- );
325
- out.info(' 预览值只用于挑券;真正抵扣由下单接口按它自己算的订单金额重算。');
326
- }
327
-
328
- ctx.done(res);
329
- return res;
330
- }
331
-
332
- /* —— ② 全部券 —— */
333
- let status;
334
- if (flags.status !== undefined && flags.status !== '') {
335
- status = String(flags.status).trim();
336
- if (!COUPON_STATUSES.includes(status)) {
337
- throw new UsageError(
338
- `--status 只能是 ${COUPON_STATUSES.join(' / ')},收到:${flags.status}`,
339
- );
340
- }
341
- }
342
- const body = {};
343
- if (status) body.status = status;
344
- const page = optionalInt(flags.page, '--page', { min: 1 });
345
- if (page !== undefined) body.page = page;
346
- const pageSize = optionalInt(flags.pageSize, '--page-size', { min: 1, max: 200 });
347
- if (pageSize !== undefined) body.pageSize = pageSize;
348
-
349
- const data = await ctx.callData('listMyCoupons', body);
350
- const res = data && typeof data === 'object' ? data : {};
351
- const rows = Array.isArray(res.rows) ? res.rows : [];
352
- const counts = res.counts && typeof res.counts === 'object' ? res.counts : {};
353
-
354
- if (!out.json) {
355
- out.head(
356
- `我的优惠券${status ? `(${status})` : ''} · 共 ${dash(res.total)} 张` +
357
- `(未用 ${counts.unused || 0} / 已锁 ${counts.locked || 0} / 已用 ${counts.used || 0} / 过期 ${counts.expired || 0})`,
358
- );
359
- out.table(
360
- [
361
- { title: '券', key: 'template_name', width: 24 },
362
- { title: '面额', key: 'amount_cents', width: 10, format: (v) => formatMoney(v) },
363
- { title: '门槛', key: 'threshold_cents', width: 10, format: (v) => formatMoney(v) },
364
- {
365
- title: '状态',
366
- key: 'display_status',
367
- width: 10,
368
- format: (v) => COUPON_STATUS_TEXT[v] || dash(v),
369
- },
370
- { title: '到期', key: 'expires_at', width: 20, format: TIME },
371
- { title: '券 ID', key: 'user_coupon_id', width: 36 },
372
- ],
373
- rows,
374
- );
375
- }
376
-
377
- ctx.done(res);
378
- return res;
379
- },
380
- };
381
-
382
- /* ════════════════════════════ ④ notify ════════════════════════════ */
383
-
384
- /** `listMyNotifications`:站内消息(未读数 + 列表) */
385
- export const notifyListCommand = {
386
- name: 'notify list',
387
- summary: '我的消息(未读数 + 列表,最新在前)',
388
- usage: 'wkgeo notify list [--limit 20] [--offset 0]',
389
- args: [],
390
- flags: {
391
- limit: { ...LIMIT_FLAG, desc: '返回条数上限(1~50,默认 20)' },
392
- offset: OFFSET_FLAG,
393
- },
394
- examples: ['wkgeo notify list', 'wkgeo notify list --limit 5'],
395
- notes: [
396
- '只读(`billing:self`)。',
397
- '服务端把未读**置顶**在同一排序里,未读数单独回 `unread`。',
398
- '标已读:`wkgeo notify read <id> --confirm`。',
399
- ],
400
- async run(ctx) {
401
- const { out, flags } = ctx;
402
- const body = {};
403
- const limit = optionalInt(flags.limit, '--limit', { min: 1, max: 50 });
404
- if (limit !== undefined) body.limit = limit;
405
- const offset = optionalInt(flags.offset, '--offset', { min: 0 });
406
- if (offset !== undefined) body.offset = offset;
407
-
408
- const data = await ctx.callData('listMyNotifications', body);
409
- const res = data && typeof data === 'object' ? data : {};
410
- const rows = Array.isArray(res.rows) ? res.rows : [];
411
-
412
- if (!out.json) {
413
- out.head(
414
- `我的消息 · 未读 ${res.unread === undefined || res.unread === null ? '?' : res.unread} 条` +
415
- `(共 ${res.total === undefined || res.total === null ? '?' : res.total} 条)`,
416
- );
417
- out.table(
418
- [
419
- {
420
- title: '状态',
421
- key: 'read_at',
422
- width: 6,
423
- format: (v) => (v ? '已读' : '未读'),
424
- },
425
- { title: '类型', key: 'kind', width: 12 },
426
- { title: '标题', key: 'title', width: 40 },
427
- { title: '时间', key: 'created_at', width: 20, format: TIME },
428
- { title: 'ID', key: 'id', width: 10 },
429
- ],
430
- rows,
431
- );
432
- if (res.has_more === true) out.info(' 还有更多:用 --offset 翻页。');
433
- }
434
-
435
- ctx.done(res);
436
- return res;
437
- },
438
- };
439
-
440
- /**
441
- * `markMyNotificationRead`:把一条消息标已读(**写操作 → 默认 dry-run**)。
442
- *
443
- * 幂等:服务端只更新 `read_at is null` 的行,重复点不会报错、`updated` 会是 0。
444
- * 别人的 id 同样回 `updated: 0`(不报错,防信息泄漏)—— CLI 照实说"可能是别人的或已读过"。
445
- */
446
- export const notifyReadCommand = {
447
- name: 'notify read',
448
- summary: '把一条消息标为已读(默认 dry-run,`--confirm` 才真发)',
449
- usage: 'wkgeo notify read <消息ID> [--confirm]',
450
- args: [{ name: 'id', required: true, desc: '消息 ID(纯数字,来自 `wkgeo notify list`)' }],
451
- flags: { ...CONFIRM_FLAG },
452
- examples: ['wkgeo notify read 12345', 'wkgeo notify read 12345 --confirm'],
453
- notes: [
454
- '需要 `billing:self`。**默认 dry-run**,加 `--confirm` 才真发。',
455
- '幂等:已经读过的再标一次不会报错,回 `updated: 0`。',
456
- '别人的消息 id 同样回 `updated: 0`(服务端不回"不存在",防信息泄漏)。',
457
- ],
458
- async run(ctx) {
459
- const { out } = ctx;
460
- const id = String(ctx.positional.id === undefined ? '' : ctx.positional.id).trim();
461
- if (!/^\d+$/.test(id)) {
462
- throw new UsageError(
463
- `消息 ID 必须是纯数字,收到:${ctx.positional.id}\n(用 \`wkgeo notify list\` 看每条消息的 ID)`,
464
- );
465
- }
466
-
467
- if (!ctx.flags.confirm) {
468
- return dryRun(ctx, 'markMyNotificationRead', { id }, [`消息 ID:${id}`, '效果:只把这一条标为已读']);
469
- }
470
-
471
- const res = await ctx.callData('markMyNotificationRead', { id });
472
- const updated = Number(res && res.updated) || 0;
473
- const data = { id, updated, all: Boolean(res && res.all) };
474
- if (!out.json) {
475
- if (updated > 0) out.ok(`已把消息 ${id} 标为已读`);
476
- else out.warn(`消息 ${id} 没有被更新(可能已经读过、或不属于你)`);
477
- }
478
- ctx.done(data);
479
- return data;
480
- },
481
- };
482
-
483
- /* ════════════════════════════ ⑤ sites recycle ════════════════════════════ */
484
-
485
- /** 回收站行 → 域名文本(服务端 `domains` 是数组,`domain` 是主域名副本) */
486
- function domainsText(row) {
487
- const list = Array.isArray(row && row.domains) ? row.domains.filter(Boolean) : [];
488
- if (list.length) return list.join(', ');
489
- return (row && row.domain) || '-';
490
- }
491
-
492
- /** `listDeletedSites`:回收站(软删的站,可还原) */
493
- export const sitesRecycleCommand = {
494
- name: 'sites recycle',
495
- summary: '回收站:我删掉的站点(软删除,可还原)',
496
- usage: 'wkgeo sites recycle [--limit 50] [--offset 0]',
497
- args: [],
498
- flags: {
499
- limit: { ...LIMIT_FLAG, desc: '返回条数上限(1~200,默认 50)' },
500
- offset: OFFSET_FLAG,
501
- },
502
- examples: ['wkgeo sites recycle', 'wkgeo sites recycle --limit 10'],
503
- notes: [
504
- '只读(`site:read`)。非平台管理员只能看到**自己**删的站。',
505
- '还原:`wkgeo sites recycle restore <站点ID> --confirm`。',
506
- '**彻底删除没有 CLI 命令**(`purgeSite` 不可逆,线上只给管理员)。',
507
- ],
508
- async run(ctx) {
509
- const { out, flags } = ctx;
510
- const body = {};
511
- const limit = optionalInt(flags.limit, '--limit', { min: 1, max: 200 });
512
- if (limit !== undefined) body.limit = limit;
513
- const offset = optionalInt(flags.offset, '--offset', { min: 0 });
514
- if (offset !== undefined) body.offset = offset;
515
-
516
- const data = await ctx.callData('listDeletedSites', body);
517
- const res = data && typeof data === 'object' ? data : {};
518
- const rows = Array.isArray(res.rows) ? res.rows : [];
519
-
520
- if (!out.json) {
521
- out.head(`回收站 · 共 ${dash(res.total)} 个站点`);
522
- out.table(
523
- [
524
- { title: '站点', key: 'name', width: 24 },
525
- { title: '域名', key: 'domains', width: 30, format: (v, row) => domainsText(row) },
526
- { title: '删除时间', key: 'offline_at', width: 20, format: TIME },
527
- { title: '到期时间', key: 'expires_at', width: 20, format: TIME },
528
- { title: '站点 ID', key: 'id', width: 36 },
529
- ],
530
- rows,
531
- );
532
- if (rows.length) out.info(' 还原:wkgeo sites recycle restore <站点ID> --confirm');
533
- }
534
-
535
- ctx.done(res);
536
- return res;
537
- },
538
- };
539
-
540
- /**
541
- * `restoreSite`:把回收站里的站还原回站点列表(**写操作 → 默认 dry-run**)。
542
- *
543
- * 服务端还会校验"资源池":退役 / 名额满会回 409(`POOL_RETIRED` / `POOL_EXHAUSTED`),
544
- * 这类失败 CLI 原样透传错误文案 —— 不自己编一套。
545
- */
546
- export const sitesRecycleRestoreCommand = {
547
- name: 'sites recycle restore',
548
- summary: '把回收站里的站点还原回站点列表(默认 dry-run,`--confirm` 才真发)',
549
- usage: 'wkgeo sites recycle restore <站点ID> [--confirm]',
550
- args: [{ name: 'id', required: true, desc: '站点 ID(来自 `wkgeo sites recycle`)' }],
551
- flags: { ...CONFIRM_FLAG },
552
- examples: ['wkgeo sites recycle restore 0f2c…', 'wkgeo sites recycle restore 0f2c… --confirm'],
553
- notes: [
554
- '需要 `site:write`。**默认 dry-run**,加 `--confirm` 才真发。',
555
- '只在回收站里的站能还原;不在回收站 ⇒ 服务端 400「这个站点不在回收站里」。',
556
- '资源池退役 / 名额已满 ⇒ 服务端 409(`POOL_RETIRED` / `POOL_EXHAUSTED`),CLI 原样回错误。',
557
- '**不是自己的站** ⇒ 403,CLI 不隐瞒也不重试。',
558
- ],
559
- async run(ctx) {
560
- const { out } = ctx;
561
- const id = String(ctx.positional.id === undefined ? '' : ctx.positional.id).trim();
562
- if (!id) throw new UsageError('缺少 <站点ID>(用 `wkgeo sites recycle` 看回收站里的站点)');
563
-
564
- if (!ctx.flags.confirm) {
565
- return dryRun(ctx, 'restoreSite', { id }, [
566
- `站点 ID:${id}`,
567
- '效果:从回收站还原回站点列表(会重新占用一个资源池名额)',
568
- ]);
569
- }
570
-
571
- const res = await ctx.callData('restoreSite', { id });
572
- const src = res && typeof res === 'object' ? res : {};
573
- const data = {
574
- id: src.id || id,
575
- restored: src.restored !== false,
576
- };
577
- if (!out.json) {
578
- out.ok(`站点已还原:${data.id}`);
579
- }
580
- ctx.done(data);
581
- return data;
582
- },
583
- };
584
-
585
- /* ════════════════════════════ ⑥ invoices ════════════════════════════ */
586
-
587
- /**
588
- * 我的开票:① 可开票订单(还没被开票消耗掉的已支付单)② 我的开票申请(含状态)。
589
- *
590
- * 两块**必须分两张表**:`listInvoiceableOrders` 回的是 `orders` + `total_cents`,
591
- * `listMyInvoiceRequests` 回的是 `rows` + `total` —— 形状不同、语义也不同(一个是"能开什么",
592
- * 一个是"申请到哪一步了")。合成一张表只会让人看不懂。
593
- *
594
- * ⚠️ **本命令不做开票**(`createInvoiceRequest` / `cancelInvoiceRequest` 刻意没有):
595
- * 开票要填抬头 / 税号 / 收件信息,CLI 里交互式拼这些字段很容易出错又难撤销。
596
- */
597
- export const invoicesListCommand = {
598
- name: 'invoices list',
599
- summary: '我的开票:可开票订单 + 我的开票申请(只读,不含开票动作)',
600
- usage: 'wkgeo invoices list [--limit 20]',
601
- args: [],
602
- flags: {
603
- limit: { ...LIMIT_FLAG, desc: '两块各取多少条(1~100,默认 20;可开票订单服务端默认 100)' },
604
- },
605
- examples: ['wkgeo invoices list', 'wkgeo invoices list --limit 50'],
606
- notes: [
607
- '只读(`billing:self`)。',
608
- '**不含开票 / 取消开票**:这两个动作要填抬头、税号等字段,留在会员端做(CLI 不造半成品入口)。',
609
- '可开票订单只算**已支付且未被开票占用**的单,金额合计见 `total_cents`。',
610
- ],
611
- async run(ctx) {
612
- const { out, flags } = ctx;
613
- const limit = optionalInt(flags.limit, '--limit', { min: 1, max: 100 });
614
-
615
- const invoiceableBody = {};
616
- if (limit !== undefined) invoiceableBody.limit = limit;
617
- const requestsBody = {};
618
- if (limit !== undefined) requestsBody.limit = limit;
619
-
620
- const invoiceable = await ctx.callData('listInvoiceableOrders', invoiceableBody);
621
- const requests = await ctx.callData('listMyInvoiceRequests', requestsBody);
622
-
623
- const orders =
624
- invoiceable && Array.isArray(invoiceable.orders) ? invoiceable.orders : [];
625
- const totalCents = Number(invoiceable && invoiceable.total_cents) || 0;
626
- const reqRows = requests && Array.isArray(requests.rows) ? requests.rows : [];
627
-
628
- const data = {
629
- invoiceable_orders: invoiceable && typeof invoiceable === 'object' ? invoiceable : {},
630
- invoice_requests: requests && typeof requests === 'object' ? requests : {},
631
- };
632
-
633
- if (!out.json) {
634
- out.head(`可开票订单 · ${orders.length} 笔,合计 ${formatMoney(totalCents)}`);
635
- out.table(
636
- [
637
- { title: '订单号', key: 'out_trade_no', width: 28 },
638
- { title: '类型', key: 'kind', width: 14 },
639
- { title: '金额', key: 'amount_cents', width: 12, format: (v) => formatMoney(v) },
640
- { title: '支付时间', key: 'paid_at', width: 20, format: TIME },
641
- { title: '标题', key: 'title', width: 30 },
642
- ],
643
- orders,
644
- );
645
-
646
- out.head(`我的开票申请 · 共 ${dash(requests && requests.total)} 条`);
647
- out.table(
648
- [
649
- { title: '状态', key: 'status', width: 12 },
650
- {
651
- title: '类型',
652
- key: 'invoice_type',
653
- width: 10,
654
- format: (v) => (v === 'special' ? '专票' : v === 'normal' ? '普票' : dash(v)),
655
- },
656
- { title: '公司', key: 'company_name', width: 24 },
657
- { title: '税号', key: 'tax_no', width: 20 },
658
- { title: '金额', key: 'amount_cents', width: 12, format: (v) => formatMoney(v) },
659
- { title: '申请时间', key: 'created_at', width: 20, format: TIME },
660
- { title: '开票时间', key: 'issued_at', width: 20, format: TIME },
661
- ],
662
- reqRows,
663
- );
664
- out.info(' 开票 / 取消开票请在会员端操作(CLI 不提供这两个写动作)。');
665
- }
666
-
667
- ctx.done(data);
668
- return data;
669
- },
670
- };
671
-
672
- /* ════════════════════════════ ⑦ plans list ════════════════════════════ */
673
-
674
- /** 像「时长」的档位标签(`1 年` / `7 天` / `2 年(24 个月)`);不像就**不**拿它当时长用 */
675
- const DURATION_LABEL_RE = /^\d+\s*(?:天|日|个月|月|年)/;
676
-
677
- /**
678
- * ★ 2026-11-16 task-528:时长文案统一入口。
679
- *
680
- * 为什么不能一律写「N 个月」:`bundle_price.months` 是**时长档里的数量**,单位在
681
- * `unit`(`day` / `month` / `year`)—— `basic` 的三档是 **1 / 2 / 3 年**,按「个月」读
682
- * 会说成「1 / 2 / 3 个月」,客户看到的档位就是错的。
683
- * 取值顺序:① 服务端下发的 `duration_text`(「7 天」「1 年」,与下单计价同一份实现
684
- * `_shared/bundle-term-policy.js`)→ ② 档位标签 `label`(管理员填的展示文案,且必须**长得像时长**)
685
- * → ③ 按 `unit + months` 拼 → ④ 最后才按 `month` 降级。纯展示,不参与任何计价。
686
- */
687
- function termTextOf(t) {
688
- const row = t && typeof t === 'object' ? t : {};
689
- const text = String(row.duration_text === null || row.duration_text === undefined ? '' : row.duration_text).trim();
690
- if (text) return text;
691
- const label = String(row.label === null || row.label === undefined ? '' : row.label).trim();
692
- if (DURATION_LABEL_RE.test(label)) return label;
693
- const months = Number(row.months);
694
- if (!Number.isFinite(months) || months <= 0) return dash(row.months);
695
- const unit = String(row.unit === null || row.unit === undefined ? '' : row.unit).trim().toLowerCase();
696
- if (unit === 'year') return `${months} 年`;
697
- if (unit === 'day') return `${months} 天`;
698
- return `${months} 个月`;
699
- }
700
-
701
- /**
702
- * 档价文案:**生效价**(`price_cents`,后端按 `bundle_price` 算出)优先,
703
- * 其次老的 `price_cents_month`,两者都没有才是「面议」。
704
- *
705
- * 为什么不再固定读 `price_cents_month`:那列是**每等价月的价**,按年 / 按天卖的档位
706
- * 上恒为 NULL ⇒ 以前一律读它,`basic`(年档)全档显示成「面议」。
707
- */
708
- function termPriceTextOf(t) {
709
- const row = t && typeof t === 'object' ? t : {};
710
- const cents = Number(row.price_cents);
711
- if (Number.isFinite(cents) && cents > 0) return formatMoney(cents);
712
- const monthCents = Number(row.price_cents_month);
713
- if (Number.isFinite(monthCents) && monthCents > 0) return formatMoney(monthCents);
714
- return '面议';
715
- }
716
-
717
- /** 各周期价格数组 → 一行文本:`1 年 ¥368.00 / 2 年 ¥577.00` */
718
- function priceListText(prices) {
719
- const list = Array.isArray(prices) ? prices : [];
720
- if (!list.length) return '-';
721
- return list.map((p) => `${termTextOf(p)} ${termPriceTextOf(p)}`).join(' / ');
722
- }
723
-
724
- /**
725
- * 套餐目录(三块一起看,**默认全取**):
726
- * ① `listPlans` —— 订阅套餐 + 各周期价格(active)
727
- * ② `listBundlePlans` —— 加量包套餐(含/加量项 + 各周期单价)
728
- * ③ `listBundles` —— 我已买的加量包(旧 plan 模型,含下架件)
729
- *
730
- * 为什么三块都用**独立小表**:`plan` / `bundle` / `bundle_plan` 是三张表、
731
- * 三套字段(价格字段名都不一样:`price_cents` / `base_price_cents` / `price_cents_month`),
732
- * 硬合成一张宽表只会满屏 `-`。`--no-bundles` 可以只取第一块。
733
- */
734
- export const plansListCommand = {
735
- name: 'plans list',
736
- summary: '套餐目录:订阅套餐 / 加量包套餐 / 我已买的加量包',
737
- usage: 'wkgeo plans list [--no-bundles]',
738
- args: [],
739
- flags: {
740
- bundles: {
741
- type: 'boolean',
742
- desc: '取加量包那两块(默认取;`--no-bundles` 只取套餐)',
743
- },
744
- },
745
- examples: ['wkgeo plans list', 'wkgeo plans list --no-bundles', 'wkgeo plans list --json'],
746
- notes: [
747
- '只读(`billing:self` / `site:read`),三块分别是三次查询;`--no-bundles` 省掉后两次。',
748
- '只列**在售**(`status=active`):下架的套餐 / 加量包不会出现。`listBundles` 例外 —— 管理员能看到自己名下的下架件。',
749
- '下单不在这条命令里:订阅 `wkgeo orders create`、加量包走报价单接口(CLI 暂未开放)。',
750
- ],
751
- async run(ctx) {
752
- const { out, flags } = ctx;
753
- const withBundles = flags.bundles !== false;
754
-
755
- const plans = await ctx.callData('listPlans', {});
756
- const bundlePlans = withBundles ? await ctx.callData('listBundlePlans', {}) : null;
757
- const bundles = withBundles ? await ctx.callData('listBundles', {}) : null;
758
-
759
- const planRows = plans && Array.isArray(plans.rows) ? plans.rows : [];
760
- const bundlePlanRows = bundlePlans && Array.isArray(bundlePlans.rows) ? bundlePlans.rows : [];
761
- const bundleRows = bundles && Array.isArray(bundles.rows) ? bundles.rows : [];
762
-
763
- const data = {
764
- plans: plans && typeof plans === 'object' ? plans : {},
765
- };
766
- if (withBundles) {
767
- data.bundle_plans = bundlePlans && typeof bundlePlans === 'object' ? bundlePlans : {};
768
- data.bundles = bundles && typeof bundles === 'object' ? bundles : {};
769
- }
770
-
771
- if (!out.json) {
772
- const current =
773
- plans && plans.current_subscription && typeof plans.current_subscription === 'object'
774
- ? plans.current_subscription
775
- : null;
776
-
777
- out.head(`订阅套餐 · ${planRows.length} 个`);
778
- if (current) {
779
- out.line(
780
- ` 我当前:${current.plan_name || current.plan_code || '-'}` +
781
- `${current.expired ? '(已过期)' : ''} 到期:${TIME(current.expires_at)}`,
782
- );
783
- }
784
- out.table(
785
- [
786
- { title: '套餐', key: 'name', width: 22 },
787
- { title: '代码', key: 'code', width: 14 },
788
- { title: '各周期价格', key: 'prices', width: 40, format: (v) => priceListText(v) },
789
- {
790
- title: '特性',
791
- key: 'features',
792
- width: 30,
793
- format: (v) => (Array.isArray(v) && v.length ? v.join('、') : '-'),
794
- },
795
- ],
796
- planRows,
797
- );
798
-
799
- if (withBundles) {
800
- out.head(`加量包套餐 · ${bundlePlanRows.length} 个`);
801
- /**
802
- * ⚠️ ★ 2026-11-16 task-528(老板 2026-11-16 拍板「删一列比显示错的好」):
803
- * **不再列「基础价」(`bundle.base_price_cents`)**。
804
- *
805
- * 那一列是旧「月价」模型的基础月价(`basic` = ¥180.60/月),与在售档价
806
- * (`basic` ¥368/年 ≈ ¥30.7/月)差一个量级,既不是客户能买的价格,也不参与本次任何计价;
807
- * 「各周期」列已经把**真实生效价**按档列全了 ⇒ 显示它只会误导。
808
- * 基础月价要不要与在售档价对齐(改数据)属定价口径,由老板定;在那之前**不展示**。
809
- */
810
- out.table(
811
- [
812
- { title: '套餐', key: 'name', width: 22 },
813
- { title: '代码', key: 'code', width: 16 },
814
- {
815
- title: '含项',
816
- key: 'included',
817
- width: 34,
818
- format: (v) =>
819
- Array.isArray(v) && v.length
820
- ? v.map((it) => `${it.product_name || it.product_code}×${it.qty}`).join('、')
821
- : '-',
822
- },
823
- {
824
- title: '各周期',
825
- key: 'terms',
826
- width: 40,
827
- format: (v) =>
828
- Array.isArray(v) && v.length
829
- ? v.map((t) => `${termTextOf(t)} ${termPriceTextOf(t)}`).join(' / ')
830
- : '-',
831
- },
832
- ],
833
- bundlePlanRows,
834
- );
835
-
836
- out.head(`我已买的加量包 · ${bundleRows.length} 个`);
837
- /**
838
- * ★ 2026-11-16 task-528:**不再读 `bundle.price_cents` / `bundle.period_months`**。
839
- *
840
- * 那两列是旧「月价」模型的遗留值(`basic` / `trial_7d` 都停在 ¥180.60、`period_months`
841
- * 为 null),既不是在售档价也不对应任何能买的东西。
842
- * 档价按「目录价优先、本行 prices 兜底」展示:
843
- * · 目录(`listBundlePlans`)按商品档价**实时算**出各档生效价(`basic` = ¥368 / ¥577 / ¥786);
844
- * · `bundle_price.price_cents` 只是**手填快照**(`basic` 停在 ¥400.10,与生效价不同)
845
- * ⇒ 只在下架件(不在目录里)时兜底,免得给"买不到的东西"假装报一个现价。
846
- * ⚠️ 只改展示:不碰库、不碰计价(金额仍由服务端 `bundle-pricing` 算)。
847
- */
848
- const catalogTermsByCode = new Map();
849
- for (const r of bundlePlanRows) {
850
- const code = String((r && r.code) || '').trim();
851
- if (code && Array.isArray(r.terms) && r.terms.length) catalogTermsByCode.set(code, r.terms);
852
- }
853
- const bundleDisplayRows = bundleRows.map((r) => {
854
- const code = String((r && r.code) || '').trim();
855
- const catalogTerms = catalogTermsByCode.get(code);
856
- return {
857
- ...r,
858
- terms_display: Array.isArray(catalogTerms)
859
- ? catalogTerms
860
- : Array.isArray(r && r.prices)
861
- ? r.prices
862
- : [],
863
- };
864
- });
865
- out.table(
866
- [
867
- { title: '名称', key: 'name', width: 22 },
868
- { title: '代码', key: 'code', width: 16 },
869
- { title: '状态', key: 'status', width: 10 },
870
- {
871
- title: '各周期',
872
- key: 'terms_display',
873
- width: 40,
874
- format: (v) => priceListText(v),
875
- },
876
- ],
877
- bundleDisplayRows,
878
- );
879
- }
880
- }
881
-
882
- ctx.done(data);
883
- return data;
884
- },
885
- };
886
-
887
- /* ════════════════════════════ ⑧ sites update ════════════════════════════ */
888
-
889
- /**
890
- * `updateSite`:改站点信息(**写操作 → 默认 dry-run**)。
891
- *
892
- * ⚠️ 只开放 `--name`(改站名)。**`--remark` 目前发不通,CLI 必须如实报缺口**:
893
- * 服务端 `updateSite` 的字段白名单是
894
- * `name / template_id / settings / domain / domains / expires_at / asset_storage_mode`
895
- * (★ 2026-11-11 task-85:`status` 已移出白名单,显式传会回 400 `STATUS_NOT_EDITABLE`,
896
- * 上下架走 `siteOffline` / `siteOnline`)
897
- * —— 没有 remark;`public.site` 表里也没有这一列(remark 只存在于 customer / wallet_txn /
898
- * 白名单外的 key 会被**静默忽略**,所以"传了就返回成功"是假成功。与其假装能改备注,
899
- * 不如明确报错 —— 要支持它得后端先加列 + 加白名单,那是另一个任务。
900
- * (也**不**用 `settings.remark` 变通:`settings` 是整块覆盖,读-改-写会吞掉原有设置。)
901
- */
902
- export const sitesUpdateCommand = {
903
- name: 'sites update',
904
- summary: '改站点信息(目前支持改站名;默认 dry-run,`--confirm` 才真发)',
905
- usage: 'wkgeo sites update <站点ID> [--name <新站名>] [--confirm]',
906
- args: [{ name: 'id', required: true, desc: '站点 ID' }],
907
- flags: {
908
- name: { type: 'string', desc: '新的站点名称(1~60 字)' },
909
- remark: { type: 'string', desc: '站点备注(**服务端暂不支持**,传了会明确报缺口)' },
910
- ...CONFIRM_FLAG,
911
- },
912
- examples: [
913
- 'wkgeo sites update 0f2c… --name 新站名',
914
- 'wkgeo sites update 0f2c… --name 新站名 --confirm',
915
- ],
916
- notes: [
917
- '需要 `site:write`。**默认 dry-run**,加 `--confirm` 才真发。',
918
- '**`--remark` 暂时发不通**(服务端 `updateSite` 白名单与站点表都没有备注字段),传了会明确报缺口而不是假装成功。',
919
- '回收站里的站不能编辑:要么先 `wkgeo sites recycle restore`,要么彻底删(只有管理员能做)。',
920
- '要改域名/模板/有效期不在这条命令里(域名走 `wkgeo domain bind`、有效期只有管理员能改)。',
921
- ],
922
- async run(ctx) {
923
- const { out } = ctx;
924
- const id = String(ctx.positional.id === undefined ? '' : ctx.positional.id).trim();
925
- if (!id) throw new UsageError('缺少 <站点ID>(用 `wkgeo sites list` 看站点 ID)');
926
-
927
- if (ctx.flags.remark !== undefined) {
928
- throw new CliError(
929
- '站点备注暂时改不了:服务端 updateSite 的字段白名单里没有 remark,站点表也没有这一列',
930
- {
931
- kind: 'unsupported',
932
- hint:
933
- '这不是参数写错了。要支持它需要后端先给站点表加 remark 列并加入 updateSite 白名单;' +
934
- '在那之前 CLI 不会假装写入成功。别的字段(站名)照常可用:--name <新站名>',
935
- },
936
- );
937
- }
938
-
939
- const nameRaw = ctx.flags.name;
940
- const name = nameRaw === undefined ? '' : String(nameRaw).trim();
941
- if (!name) {
942
- throw new UsageError(
943
- '至少要给一个要改的字段:`--name <新站名>`\n用法:wkgeo sites update <站点ID> --name <新站名> [--confirm]',
944
- );
945
- }
946
- if (name.length > 60) {
947
- throw new UsageError(`--name 最长 60 字,收到 ${name.length} 字`);
948
- }
949
-
950
- const request = { id, name };
951
-
952
- if (!ctx.flags.confirm) {
953
- return dryRun(ctx, 'updateSite', request, [
954
- `站点 ID:${id}`,
955
- `新站名:${name}`,
956
- '效果:只改站点名称,域名/模板/有效期不动',
957
- ]);
958
- }
959
-
960
- const res = await ctx.callData('updateSite', request);
961
- const src = res && typeof res === 'object' ? res : {};
962
- const data = {
963
- id: src.id || id,
964
- name: src.name || name,
965
- updated: true,
966
- };
967
- if (!out.json) out.ok(`站点已更新:${data.name}(${data.id})`);
968
- ctx.done(data);
969
- return data;
970
- },
971
- };
972
-
973
- /** 本模块的 8 组命令(10 条 spec),由 `commands/index.mjs` 展开进 COMMANDS */
974
- export const MEMBER_COMMANDS = [
975
- walletBillingCommand,
976
- walletDebtCommand,
977
- couponsCommand,
978
- notifyListCommand,
979
- notifyReadCommand,
980
- sitesRecycleCommand,
981
- sitesRecycleRestoreCommand,
982
- invoicesListCommand,
983
- plansListCommand,
984
- sitesUpdateCommand,
985
- ];
1
+ /**
2
+ * 会员自助面(task-197 / 2026-11-02):把「线上会员中心早有、CLI 还没有」的 8 组动作补上。
3
+ *
4
+ * 为什么单独一个模块:这 8 条的共同点是**对象都是"我自己"**——
5
+ * 我的账单 / 我的欠费 / 我的券 / 我的消息 / 我的开票 / 套餐目录 / 回收站 / 改站名。
6
+ * 后端动作在 `wkgeo-user` 里早就写好了,`wkgeo-cli-fc` 也已经把它们**自持重建**并挂在 `/cli`
7
+ * 的动作面里(`SELF_HOSTED_ACTIONS`,`src/user-core.js` 是代码副本)—— 所以本文件**只写命令层**:
8
+ * 解析参数 → `ctx.callData(action)` → 表格 / `--json`。**一行云函数代码都不碰。**
9
+ *
10
+ * 四条约定(与既有命令逐条对齐):
11
+ * 1. 只读命令直接发;写命令(`notify read` / `sites recycle restore` / `sites update`)
12
+ * **默认 dry-run**,加 `--confirm` 才真发 —— 与 `lang save` / `member remove` 同一把闸。
13
+ * 2. 服务端回什么,`--json` 就原样给什么(**不裁剪**):会员端以后加字段,agent 不用升级 CLI。
14
+ * 3. 单位:金额一律"分",flag 名带 `-cents` 后缀(与 `wallet recharge --amount-cents` 一致),
15
+ * 表格里才换成 `¥x.xx`。
16
+ * 4. **故意没有**的动作:`purgeSite`(彻底删站,不可逆,线上只给管理员:
17
+ * 「彻底删除只能由管理员操作;你可以把它还原回站点列表」)、开票、券核销。
18
+ * 缺口写清在命令的 notes 里,不造"看起来能跑"的假命令。
19
+ */
20
+
21
+ import { UsageError, CliError } from '../errors.mjs';
22
+ import { formatMoney, formatTime } from '../format.mjs';
23
+
24
+ /* ══════════════════════════════ 公共小件 ══════════════════════════════ */
25
+
26
+ /** 写动作的确认闸:不加就 dry-run(与 config-auth.mjs 的 CONFIRM_FLAG 同义) */
27
+ const CONFIRM_FLAG = {
28
+ confirm: {
29
+ type: 'boolean',
30
+ desc: '真发(不加只打印将要发什么,一个写请求都不发)',
31
+ },
32
+ };
33
+
34
+ const LIMIT_FLAG = { type: 'string', desc: '返回条数上限' };
35
+ const OFFSET_FLAG = { type: 'string', desc: '跳过前 N 条(翻页用,默认 0)' };
36
+
37
+ /** 正整数 flag;非法直接给人话(带收到的原值,别让人猜) */
38
+ function positiveInt(raw, flag, { min = 1, max } = {}) {
39
+ const text = String(raw).trim();
40
+ const n = Number(text);
41
+ if (!Number.isInteger(n) || n < min || (max !== undefined && n > max)) {
42
+ const range = max === undefined ? `不小于 ${min}` : `${min}~${max}`;
43
+ throw new UsageError(`${flag} 必须是${range}的整数,收到:${raw}`);
44
+ }
45
+ return n;
46
+ }
47
+
48
+ /** 可选正整数:没传就不进请求体(服务端有默认值,别用 0 覆盖它) */
49
+ function optionalInt(raw, flag, opts) {
50
+ if (raw === undefined || raw === null || raw === '') return undefined;
51
+ return positiveInt(raw, flag, opts);
52
+ }
53
+
54
+ /** 配额值:`null` = 不限量(服务端就是这么表达的,别显示成 0) */
55
+ function quotaText(v) {
56
+ return v === null || v === undefined ? '不限' : String(v);
57
+ }
58
+
59
+ /** `undefined` / `null` / 空串 → `-`,其余原样(表格里不留空白) */
60
+ function dash(v) {
61
+ return v === undefined || v === null || v === '' ? '-' : v;
62
+ }
63
+
64
+ /** 时间列:统一走 formatTime(服务端给的是 UTC ISO,本地时区展示) */
65
+ const TIME = (v) => formatTime(v);
66
+
67
+ /** dry-run 回执:把"将要发什么"结构化打印,**一个请求都不发** */
68
+ function dryRun(ctx, action, request, lines) {
69
+ const data = {
70
+ dry_run: true,
71
+ action,
72
+ request,
73
+ confirm_hint: '确认无误后加 --confirm 真发',
74
+ };
75
+ const { out } = ctx;
76
+ if (!out.json) {
77
+ out.head(`dry-run:${action}(没有发送任何写请求)`);
78
+ for (const l of lines || []) out.line(` ${l}`);
79
+ out.line('');
80
+ out.line(' 确认无误后加 --confirm 真发。');
81
+ }
82
+ ctx.done(data);
83
+ return data;
84
+ }
85
+
86
+ /* ══════════════════════════ ① wallet billing ══════════════════════════ */
87
+
88
+ /**
89
+ * `getMyBilling`:当前订阅 + 生效配额(套餐配额 + 加量包)+ 钱包余额。
90
+ *
91
+ * 与 `wkgeo wallet` 的分工:那条只给余额 / `wallet txns` 给流水;这条回答"我这个账号现在
92
+ * **有哪些额度、到什么时候**"。三块配额分开列(套餐内 / 加量包 / 生效合计),因为用户最常问的
93
+ * 就是"我买了加量包,额度到底加没加上"。
94
+ */
95
+ export const walletBillingCommand = {
96
+ name: 'wallet billing',
97
+ summary: '我的账单:生效配额(含加量包)/ 钱包余额',
98
+ usage: 'wkgeo wallet billing',
99
+ args: [],
100
+ flags: {},
101
+ examples: ['wkgeo wallet billing', 'wkgeo wallet billing --json'],
102
+ notes: [
103
+ '只读(`billing:self`),不发任何写请求。',
104
+ '配额值是 `null` = **不限量**(不是 0,也不是"没有")。',
105
+ '只看余额用 `wkgeo wallet`,看流水用 `wkgeo wallet txns`。',
106
+ ],
107
+ async run(ctx) {
108
+ const { out } = ctx;
109
+ const data = await ctx.callData('getMyBilling', {});
110
+ const res = data && typeof data === 'object' ? data : {};
111
+ const quotas = res.quotas && typeof res.quotas === 'object' ? res.quotas : {};
112
+ const planQuotas = res.plan_quotas && typeof res.plan_quotas === 'object' ? res.plan_quotas : {};
113
+ const addons = res.addons && typeof res.addons === 'object' ? res.addons : {};
114
+
115
+ if (!out.json) {
116
+ out.head('我的账单');
117
+ out.line(` 钱包余额:${formatMoney(res.balance_cents)}`);
118
+
119
+ const keys = Array.from(
120
+ new Set([...Object.keys(quotas), ...Object.keys(planQuotas), ...Object.keys(addons)]),
121
+ );
122
+ if (keys.length) {
123
+ out.line('');
124
+ out.table(
125
+ [
126
+ { title: '配额', key: 'key', width: 28 },
127
+ { title: '套餐内', key: 'plan', width: 10, format: (v) => quotaText(v) },
128
+ { title: '加量包', key: 'addon', width: 10, format: (v) => quotaText(v) },
129
+ { title: '生效合计', key: 'total', width: 10, format: (v) => quotaText(v) },
130
+ ],
131
+ keys.map((k) => ({
132
+ key: k,
133
+ plan: planQuotas[k] === undefined ? null : planQuotas[k],
134
+ addon: addons[k] === undefined ? null : addons[k],
135
+ total: quotas[k] === undefined ? null : quotas[k],
136
+ })),
137
+ );
138
+ }
139
+ }
140
+
141
+ ctx.done(res);
142
+ return res;
143
+ },
144
+ };
145
+
146
+ /* ═══════════════════════════ ② wallet debt ═══════════════════════════ */
147
+
148
+ const DEBT_STATUS_TEXT = {
149
+ none: '没有欠费',
150
+ open: '待结清',
151
+ overdue: '已逾期',
152
+ };
153
+
154
+ /** `getMyDebt`:欠费金额 / 到期日 / 宽限期 / 明细(自助还款在会员端,CLI 只读) */
155
+ export const walletDebtCommand = {
156
+ name: 'wallet debt',
157
+ summary: '我的欠费(金额 / 应缴日期 / 宽限期 / 明细)',
158
+ usage: 'wkgeo wallet debt',
159
+ args: [],
160
+ flags: {},
161
+ examples: ['wkgeo wallet debt', 'wkgeo wallet debt --json'],
162
+ notes: [
163
+ '只读(`billing:self`)。**不含还款动作**:结清走会员端收银台。',
164
+ '`debt_cents` 为 0 时 `status` 是 `none`,此时 `items` 一定是空数组。',
165
+ ],
166
+ async run(ctx) {
167
+ const { out } = ctx;
168
+ const data = await ctx.callData('getMyDebt', {});
169
+ const res = data && typeof data === 'object' ? data : {};
170
+ const debt = Number(res.debt_cents) || 0;
171
+ const items = Array.isArray(res.items) ? res.items : [];
172
+
173
+ if (!out.json) {
174
+ out.head('我的欠费');
175
+ if (!debt) {
176
+ out.ok('没有欠费');
177
+ } else {
178
+ const statusText = DEBT_STATUS_TEXT[res.status] || dash(res.status);
179
+ out.line(` 欠费金额:${formatMoney(debt)}(${statusText})`);
180
+ out.line(` 应缴日期:${TIME(res.due_at)} 宽限期:${dash(res.grace_days)} 天`);
181
+ if (items.length) {
182
+ out.line('');
183
+ out.table(
184
+ [
185
+ { title: '来源', key: 'source', width: 16 },
186
+ { title: '金额', key: 'amount_cents', width: 12, format: (v) => formatMoney(v) },
187
+ { title: '应缴日期', key: 'due_at', width: 20, format: TIME },
188
+ { title: '状态', key: 'status', width: 10 },
189
+ { title: '说明', key: 'remark', width: 30 },
190
+ ],
191
+ items,
192
+ );
193
+ }
194
+ }
195
+ }
196
+
197
+ ctx.done(res);
198
+ return res;
199
+ },
200
+ };
201
+
202
+ /* ════════════════════════════ ③ coupons ════════════════════════════ */
203
+
204
+ const COUPON_STATUSES = ['unused', 'used', 'expired'];
205
+ const ORDER_KINDS = ['subscribe', 'site_renew', 'quota'];
206
+ const COUPON_STATUS_TEXT = {
207
+ unused: '未使用',
208
+ locked: '已锁定',
209
+ used: '已使用',
210
+ expired: '已过期',
211
+ canceled: '已作废',
212
+ };
213
+
214
+ /**
215
+ * 我的优惠券:不带 `--usable` 看**全部券**;带 `--usable` 看**这笔单能用的券**(带抵扣预览)。
216
+ *
217
+ * 为什么拆成两条后端动作:`listUsableCoupons` 必须带 `order_kind` + `amount_cents`
218
+ * (服务端按订单类型和金额挑券并算预览),缺一个就 400 —— 所以 CLI 也必须把这两个参数
219
+ * 做成 `--usable` 的**前置条件**,而不是让它自己去猜。
220
+ *
221
+ * ⚠️ `amount_cents` **只影响"给你看哪些券"**,不参与定价:真正抵扣由下单接口按它自己算的
222
+ * 订单金额重算(前端传的钱一律不采信)。CLI 这边更不可能用预览值去下单。
223
+ */
224
+ export const couponsCommand = {
225
+ name: 'coupons',
226
+ summary: '我的优惠券(默认全部;`--usable` 看某个订单能用的券与抵扣预览)',
227
+ usage:
228
+ 'wkgeo coupons [--status unused|used|expired] [--page 1] [--page-size 20]\n' +
229
+ 'wkgeo coupons --usable --kind subscribe --amount-cents 2990',
230
+ args: [],
231
+ flags: {
232
+ usable: {
233
+ type: 'boolean',
234
+ desc: '只看**这笔订单**能用的券(需同时给 --kind 与 --amount-cents)',
235
+ },
236
+ kind: {
237
+ type: 'string',
238
+ desc: `订单类型,仅 --usable 时用:${ORDER_KINDS.join(' / ')}(充值单不能用券)`,
239
+ },
240
+ 'amount-cents': {
241
+ type: 'string',
242
+ desc: '订单金额,**单位分**,仅 --usable 时用(只影响筛券与预览,不参与定价)',
243
+ },
244
+ status: { type: 'string', desc: `按状态筛:${COUPON_STATUSES.join(' / ')}(仅不带 --usable 时用)` },
245
+ page: { type: 'string', desc: '页码(默认 1)' },
246
+ 'page-size': { type: 'string', desc: '每页条数(默认 20)' },
247
+ },
248
+ examples: [
249
+ 'wkgeo coupons',
250
+ 'wkgeo coupons --status unused',
251
+ 'wkgeo coupons --usable --kind subscribe --amount-cents 2990',
252
+ ],
253
+ notes: [
254
+ '只读(`billing:self`)。**不含核销**:用券发生在下单时,由订单接口按它自己算的金额重算抵扣。',
255
+ '`--status` 只认 `unused` / `used` / `expired`(服务端白名单,其它值直接 400)。',
256
+ '`display_status` 是服务端算好的状态:券本身 `unused` 但已过期 → 显示 `expired`。',
257
+ ],
258
+ async run(ctx) {
259
+ const { out, flags } = ctx;
260
+
261
+ /* —— ① 这笔单能用的券 —— */
262
+ if (flags.usable) {
263
+ if (flags.status !== undefined) {
264
+ throw new UsageError(
265
+ '`--usable` 不接受 `--status`:可用券列表由 `--kind` + `--amount-cents` 决定(服务端没有第二个筛选项)',
266
+ );
267
+ }
268
+ const kind = String(flags.kind === undefined ? '' : flags.kind).trim();
269
+ if (!kind) {
270
+ throw new UsageError(
271
+ `\`--usable\` 需要 --kind(${ORDER_KINDS.join(' / ')}):服务端要按订单类型挑券`,
272
+ );
273
+ }
274
+ if (!ORDER_KINDS.includes(kind)) {
275
+ throw new UsageError(
276
+ `--kind 只能是 ${ORDER_KINDS.join(' / ')},收到:${kind}\n(充值单不能用券:recharge 会被服务端 400 拒绝)`,
277
+ );
278
+ }
279
+ if (flags.amountCents === undefined) {
280
+ throw new UsageError('`--usable` 需要 --amount-cents(单位分):服务端要按订单金额挑券');
281
+ }
282
+ const amountCents = positiveInt(flags.amountCents, '--amount-cents', { min: 1 });
283
+
284
+ const data = await ctx.callData('listUsableCoupons', {
285
+ order_kind: kind,
286
+ amount_cents: amountCents,
287
+ });
288
+ const res = data && typeof data === 'object' ? data : {};
289
+ const rows = Array.isArray(res.rows) ? res.rows : [];
290
+
291
+ if (!out.json) {
292
+ out.head(
293
+ `这笔单能用的券:${kind} · 订单金额 ${formatMoney(amountCents)}(共 ${rows.length} 张)`,
294
+ );
295
+ out.table(
296
+ [
297
+ { title: '券', key: 'template_name', width: 24 },
298
+ { title: '面额', key: 'amount_cents', width: 10, format: (v) => formatMoney(v) },
299
+ { title: '门槛', key: 'threshold_cents', width: 10, format: (v) => formatMoney(v) },
300
+ {
301
+ title: '抵扣预览',
302
+ key: 'discount_preview_cents',
303
+ width: 12,
304
+ format: (v) => formatMoney(v),
305
+ },
306
+ {
307
+ title: '应付预览',
308
+ key: 'payable_preview_cents',
309
+ width: 12,
310
+ format: (v) => formatMoney(v),
311
+ },
312
+ { title: '到期', key: 'expires_at', width: 20, format: TIME },
313
+ { title: '券 ID', key: 'user_coupon_id', width: 36 },
314
+ ],
315
+ rows,
316
+ );
317
+ out.info(' 预览值只用于挑券;真正抵扣由下单接口按它自己算的订单金额重算。');
318
+ }
319
+
320
+ ctx.done(res);
321
+ return res;
322
+ }
323
+
324
+ /* —— ② 全部券 —— */
325
+ let status;
326
+ if (flags.status !== undefined && flags.status !== '') {
327
+ status = String(flags.status).trim();
328
+ if (!COUPON_STATUSES.includes(status)) {
329
+ throw new UsageError(
330
+ `--status 只能是 ${COUPON_STATUSES.join(' / ')},收到:${flags.status}`,
331
+ );
332
+ }
333
+ }
334
+ const body = {};
335
+ if (status) body.status = status;
336
+ const page = optionalInt(flags.page, '--page', { min: 1 });
337
+ if (page !== undefined) body.page = page;
338
+ const pageSize = optionalInt(flags.pageSize, '--page-size', { min: 1, max: 200 });
339
+ if (pageSize !== undefined) body.pageSize = pageSize;
340
+
341
+ const data = await ctx.callData('listMyCoupons', body);
342
+ const res = data && typeof data === 'object' ? data : {};
343
+ const rows = Array.isArray(res.rows) ? res.rows : [];
344
+ const counts = res.counts && typeof res.counts === 'object' ? res.counts : {};
345
+
346
+ if (!out.json) {
347
+ out.head(
348
+ `我的优惠券${status ? `(${status})` : ''} · 共 ${dash(res.total)} 张` +
349
+ `(未用 ${counts.unused || 0} / 已锁 ${counts.locked || 0} / 已用 ${counts.used || 0} / 过期 ${counts.expired || 0})`,
350
+ );
351
+ out.table(
352
+ [
353
+ { title: '券', key: 'template_name', width: 24 },
354
+ { title: '面额', key: 'amount_cents', width: 10, format: (v) => formatMoney(v) },
355
+ { title: '门槛', key: 'threshold_cents', width: 10, format: (v) => formatMoney(v) },
356
+ {
357
+ title: '状态',
358
+ key: 'display_status',
359
+ width: 10,
360
+ format: (v) => COUPON_STATUS_TEXT[v] || dash(v),
361
+ },
362
+ { title: '到期', key: 'expires_at', width: 20, format: TIME },
363
+ { title: '券 ID', key: 'user_coupon_id', width: 36 },
364
+ ],
365
+ rows,
366
+ );
367
+ }
368
+
369
+ ctx.done(res);
370
+ return res;
371
+ },
372
+ };
373
+
374
+ /* ════════════════════════════ ④ notify ════════════════════════════ */
375
+
376
+ /** `listMyNotifications`:站内消息(未读数 + 列表) */
377
+ export const notifyListCommand = {
378
+ name: 'notify list',
379
+ summary: '我的消息(未读数 + 列表,最新在前)',
380
+ usage: 'wkgeo notify list [--limit 20] [--offset 0]',
381
+ args: [],
382
+ flags: {
383
+ limit: { ...LIMIT_FLAG, desc: '返回条数上限(1~50,默认 20)' },
384
+ offset: OFFSET_FLAG,
385
+ },
386
+ examples: ['wkgeo notify list', 'wkgeo notify list --limit 5'],
387
+ notes: [
388
+ '只读(`billing:self`)。',
389
+ '服务端把未读**置顶**在同一排序里,未读数单独回 `unread`。',
390
+ '标已读:`wkgeo notify read <id> --confirm`。',
391
+ ],
392
+ async run(ctx) {
393
+ const { out, flags } = ctx;
394
+ const body = {};
395
+ const limit = optionalInt(flags.limit, '--limit', { min: 1, max: 50 });
396
+ if (limit !== undefined) body.limit = limit;
397
+ const offset = optionalInt(flags.offset, '--offset', { min: 0 });
398
+ if (offset !== undefined) body.offset = offset;
399
+
400
+ const data = await ctx.callData('listMyNotifications', body);
401
+ const res = data && typeof data === 'object' ? data : {};
402
+ const rows = Array.isArray(res.rows) ? res.rows : [];
403
+
404
+ if (!out.json) {
405
+ out.head(
406
+ `我的消息 · 未读 ${res.unread === undefined || res.unread === null ? '?' : res.unread} 条` +
407
+ `(共 ${res.total === undefined || res.total === null ? '?' : res.total} 条)`,
408
+ );
409
+ out.table(
410
+ [
411
+ {
412
+ title: '状态',
413
+ key: 'read_at',
414
+ width: 6,
415
+ format: (v) => (v ? '已读' : '未读'),
416
+ },
417
+ { title: '类型', key: 'kind', width: 12 },
418
+ { title: '标题', key: 'title', width: 40 },
419
+ { title: '时间', key: 'created_at', width: 20, format: TIME },
420
+ { title: 'ID', key: 'id', width: 10 },
421
+ ],
422
+ rows,
423
+ );
424
+ if (res.has_more === true) out.info(' 还有更多:用 --offset 翻页。');
425
+ }
426
+
427
+ ctx.done(res);
428
+ return res;
429
+ },
430
+ };
431
+
432
+ /**
433
+ * `markMyNotificationRead`:把一条消息标已读(**写操作 → 默认 dry-run**)。
434
+ *
435
+ * 幂等:服务端只更新 `read_at is null` 的行,重复点不会报错、`updated` 会是 0。
436
+ * 别人的 id 同样回 `updated: 0`(不报错,防信息泄漏)—— CLI 照实说"可能是别人的或已读过"。
437
+ */
438
+ export const notifyReadCommand = {
439
+ name: 'notify read',
440
+ summary: '把一条消息标为已读(默认 dry-run,`--confirm` 才真发)',
441
+ usage: 'wkgeo notify read <消息ID> [--confirm]',
442
+ args: [{ name: 'id', required: true, desc: '消息 ID(纯数字,来自 `wkgeo notify list`)' }],
443
+ flags: { ...CONFIRM_FLAG },
444
+ examples: ['wkgeo notify read 12345', 'wkgeo notify read 12345 --confirm'],
445
+ notes: [
446
+ '需要 `billing:self`。**默认 dry-run**,加 `--confirm` 才真发。',
447
+ '幂等:已经读过的再标一次不会报错,回 `updated: 0`。',
448
+ '别人的消息 id 同样回 `updated: 0`(服务端不回"不存在",防信息泄漏)。',
449
+ ],
450
+ async run(ctx) {
451
+ const { out } = ctx;
452
+ const id = String(ctx.positional.id === undefined ? '' : ctx.positional.id).trim();
453
+ if (!/^\d+$/.test(id)) {
454
+ throw new UsageError(
455
+ `消息 ID 必须是纯数字,收到:${ctx.positional.id}\n(用 \`wkgeo notify list\` 看每条消息的 ID)`,
456
+ );
457
+ }
458
+
459
+ if (!ctx.flags.confirm) {
460
+ return dryRun(ctx, 'markMyNotificationRead', { id }, [`消息 ID:${id}`, '效果:只把这一条标为已读']);
461
+ }
462
+
463
+ const res = await ctx.callData('markMyNotificationRead', { id });
464
+ const updated = Number(res && res.updated) || 0;
465
+ const data = { id, updated, all: Boolean(res && res.all) };
466
+ if (!out.json) {
467
+ if (updated > 0) out.ok(`已把消息 ${id} 标为已读`);
468
+ else out.warn(`消息 ${id} 没有被更新(可能已经读过、或不属于你)`);
469
+ }
470
+ ctx.done(data);
471
+ return data;
472
+ },
473
+ };
474
+
475
+ /* ════════════════════════════ ⑤ sites recycle ════════════════════════════ */
476
+
477
+ /** 回收站行 → 域名文本(服务端 `domains` 是数组,`domain` 是主域名副本) */
478
+ function domainsText(row) {
479
+ const list = Array.isArray(row && row.domains) ? row.domains.filter(Boolean) : [];
480
+ if (list.length) return list.join(', ');
481
+ return (row && row.domain) || '-';
482
+ }
483
+
484
+ /** `listDeletedSites`:回收站(软删的站,可还原) */
485
+ export const sitesRecycleCommand = {
486
+ name: 'sites recycle',
487
+ summary: '回收站:我删掉的站点(软删除,可还原)',
488
+ usage: 'wkgeo sites recycle [--limit 50] [--offset 0]',
489
+ args: [],
490
+ flags: {
491
+ limit: { ...LIMIT_FLAG, desc: '返回条数上限(1~200,默认 50)' },
492
+ offset: OFFSET_FLAG,
493
+ },
494
+ examples: ['wkgeo sites recycle', 'wkgeo sites recycle --limit 10'],
495
+ notes: [
496
+ '只读(`site:read`)。非平台管理员只能看到**自己**删的站。',
497
+ '还原:`wkgeo sites recycle restore <站点ID> --confirm`。',
498
+ '**彻底删除没有 CLI 命令**(`purgeSite` 不可逆,线上只给管理员)。',
499
+ ],
500
+ async run(ctx) {
501
+ const { out, flags } = ctx;
502
+ const body = {};
503
+ const limit = optionalInt(flags.limit, '--limit', { min: 1, max: 200 });
504
+ if (limit !== undefined) body.limit = limit;
505
+ const offset = optionalInt(flags.offset, '--offset', { min: 0 });
506
+ if (offset !== undefined) body.offset = offset;
507
+
508
+ const data = await ctx.callData('listDeletedSites', body);
509
+ const res = data && typeof data === 'object' ? data : {};
510
+ const rows = Array.isArray(res.rows) ? res.rows : [];
511
+
512
+ if (!out.json) {
513
+ out.head(`回收站 · 共 ${dash(res.total)} 个站点`);
514
+ out.table(
515
+ [
516
+ { title: '站点', key: 'name', width: 24 },
517
+ { title: '域名', key: 'domains', width: 30, format: (v, row) => domainsText(row) },
518
+ { title: '删除时间', key: 'offline_at', width: 20, format: TIME },
519
+ { title: '到期时间', key: 'expires_at', width: 20, format: TIME },
520
+ { title: '站点 ID', key: 'id', width: 36 },
521
+ ],
522
+ rows,
523
+ );
524
+ if (rows.length) out.info(' 还原:wkgeo sites recycle restore <站点ID> --confirm');
525
+ }
526
+
527
+ ctx.done(res);
528
+ return res;
529
+ },
530
+ };
531
+
532
+ /**
533
+ * `restoreSite`:把回收站里的站还原回站点列表(**写操作 → 默认 dry-run**)。
534
+ *
535
+ * 服务端还会校验"资源池":退役 / 名额满会回 409(`POOL_RETIRED` / `POOL_EXHAUSTED`),
536
+ * 这类失败 CLI 原样透传错误文案 —— 不自己编一套。
537
+ */
538
+ export const sitesRecycleRestoreCommand = {
539
+ name: 'sites recycle restore',
540
+ summary: '把回收站里的站点还原回站点列表(默认 dry-run,`--confirm` 才真发)',
541
+ usage: 'wkgeo sites recycle restore <站点ID> [--confirm]',
542
+ args: [{ name: 'id', required: true, desc: '站点 ID(来自 `wkgeo sites recycle`)' }],
543
+ flags: { ...CONFIRM_FLAG },
544
+ examples: ['wkgeo sites recycle restore 0f2c…', 'wkgeo sites recycle restore 0f2c… --confirm'],
545
+ notes: [
546
+ '需要 `site:write`。**默认 dry-run**,加 `--confirm` 才真发。',
547
+ '只在回收站里的站能还原;不在回收站 ⇒ 服务端 400「这个站点不在回收站里」。',
548
+ '资源池退役 / 名额已满 ⇒ 服务端 409(`POOL_RETIRED` / `POOL_EXHAUSTED`),CLI 原样回错误。',
549
+ '**不是自己的站** ⇒ 403,CLI 不隐瞒也不重试。',
550
+ ],
551
+ async run(ctx) {
552
+ const { out } = ctx;
553
+ const id = String(ctx.positional.id === undefined ? '' : ctx.positional.id).trim();
554
+ if (!id) throw new UsageError('缺少 <站点ID>(用 `wkgeo sites recycle` 看回收站里的站点)');
555
+
556
+ if (!ctx.flags.confirm) {
557
+ return dryRun(ctx, 'restoreSite', { id }, [
558
+ `站点 ID:${id}`,
559
+ '效果:从回收站还原回站点列表(会重新占用一个资源池名额)',
560
+ ]);
561
+ }
562
+
563
+ const res = await ctx.callData('restoreSite', { id });
564
+ const src = res && typeof res === 'object' ? res : {};
565
+ const data = {
566
+ id: src.id || id,
567
+ restored: src.restored !== false,
568
+ };
569
+ if (!out.json) {
570
+ out.ok(`站点已还原:${data.id}`);
571
+ }
572
+ ctx.done(data);
573
+ return data;
574
+ },
575
+ };
576
+
577
+ /* ════════════════════════════ ⑥ invoices ════════════════════════════ */
578
+
579
+ /**
580
+ * 我的开票:① 可开票订单(还没被开票消耗掉的已支付单)② 我的开票申请(含状态)。
581
+ *
582
+ * 两块**必须分两张表**:`listInvoiceableOrders` 回的是 `orders` + `total_cents`,
583
+ * `listMyInvoiceRequests` 回的是 `rows` + `total` —— 形状不同、语义也不同(一个是"能开什么",
584
+ * 一个是"申请到哪一步了")。合成一张表只会让人看不懂。
585
+ *
586
+ * ⚠️ **本命令不做开票**(`createInvoiceRequest` / `cancelInvoiceRequest` 刻意没有):
587
+ * 开票要填抬头 / 税号 / 收件信息,CLI 里交互式拼这些字段很容易出错又难撤销。
588
+ */
589
+ export const invoicesListCommand = {
590
+ name: 'invoices list',
591
+ summary: '我的开票:可开票订单 + 我的开票申请(只读,不含开票动作)',
592
+ usage: 'wkgeo invoices list [--limit 20]',
593
+ args: [],
594
+ flags: {
595
+ limit: { ...LIMIT_FLAG, desc: '两块各取多少条(1~100,默认 20;可开票订单服务端默认 100)' },
596
+ },
597
+ examples: ['wkgeo invoices list', 'wkgeo invoices list --limit 50'],
598
+ notes: [
599
+ '只读(`billing:self`)。',
600
+ '**不含开票 / 取消开票**:这两个动作要填抬头、税号等字段,留在会员端做(CLI 不造半成品入口)。',
601
+ '可开票订单只算**已支付且未被开票占用**的单,金额合计见 `total_cents`。',
602
+ ],
603
+ async run(ctx) {
604
+ const { out, flags } = ctx;
605
+ const limit = optionalInt(flags.limit, '--limit', { min: 1, max: 100 });
606
+
607
+ const invoiceableBody = {};
608
+ if (limit !== undefined) invoiceableBody.limit = limit;
609
+ const requestsBody = {};
610
+ if (limit !== undefined) requestsBody.limit = limit;
611
+
612
+ const invoiceable = await ctx.callData('listInvoiceableOrders', invoiceableBody);
613
+ const requests = await ctx.callData('listMyInvoiceRequests', requestsBody);
614
+
615
+ const orders =
616
+ invoiceable && Array.isArray(invoiceable.orders) ? invoiceable.orders : [];
617
+ const totalCents = Number(invoiceable && invoiceable.total_cents) || 0;
618
+ const reqRows = requests && Array.isArray(requests.rows) ? requests.rows : [];
619
+
620
+ const data = {
621
+ invoiceable_orders: invoiceable && typeof invoiceable === 'object' ? invoiceable : {},
622
+ invoice_requests: requests && typeof requests === 'object' ? requests : {},
623
+ };
624
+
625
+ if (!out.json) {
626
+ out.head(`可开票订单 · ${orders.length} 笔,合计 ${formatMoney(totalCents)}`);
627
+ out.table(
628
+ [
629
+ { title: '订单号', key: 'out_trade_no', width: 28 },
630
+ { title: '类型', key: 'kind', width: 14 },
631
+ { title: '金额', key: 'amount_cents', width: 12, format: (v) => formatMoney(v) },
632
+ { title: '支付时间', key: 'paid_at', width: 20, format: TIME },
633
+ { title: '标题', key: 'title', width: 30 },
634
+ ],
635
+ orders,
636
+ );
637
+
638
+ out.head(`我的开票申请 · 共 ${dash(requests && requests.total)} 条`);
639
+ out.table(
640
+ [
641
+ { title: '状态', key: 'status', width: 12 },
642
+ {
643
+ title: '类型',
644
+ key: 'invoice_type',
645
+ width: 10,
646
+ format: (v) => (v === 'special' ? '专票' : v === 'normal' ? '普票' : dash(v)),
647
+ },
648
+ { title: '公司', key: 'company_name', width: 24 },
649
+ { title: '税号', key: 'tax_no', width: 20 },
650
+ { title: '金额', key: 'amount_cents', width: 12, format: (v) => formatMoney(v) },
651
+ { title: '申请时间', key: 'created_at', width: 20, format: TIME },
652
+ { title: '开票时间', key: 'issued_at', width: 20, format: TIME },
653
+ ],
654
+ reqRows,
655
+ );
656
+ out.info(' 开票 / 取消开票请在会员端操作(CLI 不提供这两个写动作)。');
657
+ }
658
+
659
+ ctx.done(data);
660
+ return data;
661
+ },
662
+ };
663
+
664
+ /* ════════════════════════════ ⑦ plans list ════════════════════════════ */
665
+
666
+ /** 像「时长」的档位标签(`1 年` / `7 天` / `2 年(24 个月)`);不像就**不**拿它当时长用 */
667
+ const DURATION_LABEL_RE = /^\d+\s*(?:天|日|个月|月|年)/;
668
+
669
+ /**
670
+ * ★ 2026-11-16 task-528:时长文案统一入口。
671
+ *
672
+ * 为什么不能一律写「N 个月」:`bundle_price.months` 是**时长档里的数量**,单位在
673
+ * `unit`(`day` / `month` / `year`)—— `basic` 的三档是 **1 / 2 / 3 年**,按「个月」读
674
+ * 会说成「1 / 2 / 3 个月」,客户看到的档位就是错的。
675
+ * 取值顺序:① 服务端下发的 `duration_text`(「7 天」「1 年」,与下单计价同一份实现
676
+ * `_shared/bundle-term-policy.js`)→ ② 档位标签 `label`(管理员填的展示文案,且必须**长得像时长**)
677
+ * → ③ 按 `unit + months` 拼 → ④ 最后才按 `month` 降级。纯展示,不参与任何计价。
678
+ */
679
+ function termTextOf(t) {
680
+ const row = t && typeof t === 'object' ? t : {};
681
+ const text = String(row.duration_text === null || row.duration_text === undefined ? '' : row.duration_text).trim();
682
+ if (text) return text;
683
+ const label = String(row.label === null || row.label === undefined ? '' : row.label).trim();
684
+ if (DURATION_LABEL_RE.test(label)) return label;
685
+ const months = Number(row.months);
686
+ if (!Number.isFinite(months) || months <= 0) return dash(row.months);
687
+ const unit = String(row.unit === null || row.unit === undefined ? '' : row.unit).trim().toLowerCase();
688
+ if (unit === 'year') return `${months} 年`;
689
+ if (unit === 'day') return `${months} 天`;
690
+ return `${months} 个月`;
691
+ }
692
+
693
+ /**
694
+ * 档价文案:**生效价**(`price_cents`,后端按 `bundle_price` 算出)优先,
695
+ * 其次老的 `price_cents_month`,两者都没有才是「面议」。
696
+ *
697
+ * 为什么不再固定读 `price_cents_month`:那列是**每等价月的价**,按年 / 按天卖的档位
698
+ * 上恒为 NULL ⇒ 以前一律读它,`basic`(年档)全档显示成「面议」。
699
+ */
700
+ function termPriceTextOf(t) {
701
+ const row = t && typeof t === 'object' ? t : {};
702
+ const cents = Number(row.price_cents);
703
+ if (Number.isFinite(cents) && cents > 0) return formatMoney(cents);
704
+ const monthCents = Number(row.price_cents_month);
705
+ if (Number.isFinite(monthCents) && monthCents > 0) return formatMoney(monthCents);
706
+ return '面议';
707
+ }
708
+
709
+ /** 各周期价格数组 → 一行文本:`1 年 ¥368.00 / 2 年 ¥577.00` */
710
+ function priceListText(prices) {
711
+ const list = Array.isArray(prices) ? prices : [];
712
+ if (!list.length) return '-';
713
+ return list.map((p) => `${termTextOf(p)} ${termPriceTextOf(p)}`).join(' / ');
714
+ }
715
+
716
+ /**
717
+ * 套餐目录(**唯一真源 = `bundle` 家族**):
718
+ * ① `listBundlePlans` —— 在售套餐(包含项 + 后台配置的各时长档 + 实时算出的档价)
719
+ * ② `listBundles` —— 我已买的套餐 / 加量包(含下架件)
720
+ *
721
+ * ★ 2026-11-17 task-681:旧的订阅套餐线(`listPlans` 读 `public.plan` / `plan_price`)
722
+ * 已整条下线 ⇒ 三块变两块,`--no-bundles` 一并取消(少一个能取到空集的开关)。
723
+ * 金额仍由服务端按商品档价实时算(`basic` = ¥368 / ¥577 / ¥786),前端只展示。
724
+ */
725
+ export const plansListCommand = {
726
+ name: 'plans list',
727
+ summary: '套餐目录:在售套餐 / 我已买的套餐与加量包',
728
+ usage: 'wkgeo plans list',
729
+ args: [],
730
+ flags: {},
731
+ examples: ['wkgeo plans list', 'wkgeo plans list --json'],
732
+ notes: [
733
+ '只读(illing:self / site:read),两块分别是两次查询。',
734
+ '只列**在售**(status=active):下架的套餐 / 加量包不会出现。listBundles 例外 —— 管理员能看到自己名下的下架件。',
735
+ '下单不在这条命令里:买套餐走 wkgeo orders create(kind=bundle),加量包走报价单接口(CLI 暂未开放)。',
736
+ ],
737
+ async run(ctx) {
738
+ const { out } = ctx;
739
+
740
+ const bundlePlans = await ctx.callData('listBundlePlans', {});
741
+ const bundles = await ctx.callData('listBundles', {});
742
+
743
+ const bundlePlanRows = bundlePlans && Array.isArray(bundlePlans.rows) ? bundlePlans.rows : [];
744
+ const bundleRows = bundles && Array.isArray(bundles.rows) ? bundles.rows : [];
745
+
746
+ const data = {
747
+ bundle_plans: bundlePlans && typeof bundlePlans === 'object' ? bundlePlans : {},
748
+ bundles: bundles && typeof bundles === 'object' ? bundles : {},
749
+ };
750
+
751
+ if (!out.json) {
752
+ out.head(`加量包套餐 · ${bundlePlanRows.length} 个`);
753
+ /**
754
+ * ⚠️ ★ 2026-11-16 task-528(老板 2026-11-16 拍板「删一列比显示错的好」):
755
+ * **不再列「基础价」(`bundle.base_price_cents`)**。
756
+ *
757
+ * 那一列是旧「月价」模型的基础月价(`basic` = ¥180.60/月),与在售档价
758
+ * (`basic` ¥368/年 ≈ ¥30.7/月)差一个量级,既不是客户能买的价格,也不参与本次任何计价;
759
+ * 「各周期」列已经把**真实生效价**按档列全了 ⇒ 显示它只会误导。
760
+ * 基础月价要不要与在售档价对齐(改数据)属定价口径,由老板定;在那之前**不展示**。
761
+ */
762
+ out.table(
763
+ [
764
+ { title: '套餐', key: 'name', width: 22 },
765
+ { title: '代码', key: 'code', width: 16 },
766
+ {
767
+ title: '含项',
768
+ key: 'included',
769
+ width: 34,
770
+ format: (v) =>
771
+ Array.isArray(v) && v.length
772
+ ? v.map((it) => `${it.product_name || it.product_code}×${it.qty}`).join('、')
773
+ : '-',
774
+ },
775
+ {
776
+ title: '各周期',
777
+ key: 'terms',
778
+ width: 40,
779
+ format: (v) =>
780
+ Array.isArray(v) && v.length
781
+ ? v.map((t) => `${termTextOf(t)} ${termPriceTextOf(t)}`).join(' / ')
782
+ : '-',
783
+ },
784
+ ],
785
+ bundlePlanRows,
786
+ );
787
+
788
+ out.head(`我已买的加量包 · ${bundleRows.length} 个`);
789
+ /**
790
+ * ★ 2026-11-16 task-528:**不再读 `bundle.price_cents` / `bundle.period_months`**。
791
+ *
792
+ * 那两列是旧「月价」模型的遗留值(`basic` / `trial_7d` 都停在 ¥180.60、`period_months`
793
+ * 为 null),既不是在售档价也不对应任何能买的东西。
794
+ * 档价按「目录价优先、本行 prices 兜底」展示:
795
+ * · 目录(`listBundlePlans`)按商品档价**实时算**出各档生效价(`basic` = ¥368 / ¥577 / ¥786);
796
+ * · `bundle_price.price_cents` 只是**手填快照**(`basic` 停在 ¥400.10,与生效价不同)
797
+ * ⇒ 只在下架件(不在目录里)时兜底,免得给"买不到的东西"假装报一个现价。
798
+ * ⚠️ 只改展示:不碰库、不碰计价(金额仍由服务端 `bundle-pricing` 算)。
799
+ */
800
+ const catalogTermsByCode = new Map();
801
+ for (const r of bundlePlanRows) {
802
+ const code = String((r && r.code) || '').trim();
803
+ if (code && Array.isArray(r.terms) && r.terms.length) catalogTermsByCode.set(code, r.terms);
804
+ }
805
+ const bundleDisplayRows = bundleRows.map((r) => {
806
+ const code = String((r && r.code) || '').trim();
807
+ const catalogTerms = catalogTermsByCode.get(code);
808
+ return {
809
+ ...r,
810
+ terms_display: Array.isArray(catalogTerms)
811
+ ? catalogTerms
812
+ : Array.isArray(r && r.prices)
813
+ ? r.prices
814
+ : [],
815
+ };
816
+ });
817
+ out.table(
818
+ [
819
+ { title: '名称', key: 'name', width: 22 },
820
+ { title: '代码', key: 'code', width: 16 },
821
+ { title: '状态', key: 'status', width: 10 },
822
+ {
823
+ title: '各周期',
824
+ key: 'terms_display',
825
+ width: 40,
826
+ format: (v) => priceListText(v),
827
+ },
828
+ ],
829
+ bundleDisplayRows,
830
+ );
831
+ }
832
+
833
+ ctx.done(data);
834
+ return data;
835
+ },
836
+ };
837
+
838
+ /* ════════════════════════════ ⑧ sites update ════════════════════════════ */
839
+
840
+ /**
841
+ * `updateSite`:改站点信息(**写操作 → 默认 dry-run**)。
842
+ *
843
+ * ⚠️ 只开放 `--name`(改站名)。**`--remark` 目前发不通,CLI 必须如实报缺口**:
844
+ * 服务端 `updateSite` 的字段白名单是
845
+ * `name / template_id / settings / domain / domains / expires_at / asset_storage_mode`
846
+ * (★ 2026-11-11 task-85:`status` 已移出白名单,显式传会回 400 `STATUS_NOT_EDITABLE`,
847
+ * 上下架走 `siteOffline` / `siteOnline`)
848
+ * —— 没有 remark;`public.site` 表里也没有这一列(remark 只存在于 customer / wallet_txn /
849
+ * 白名单外的 key 会被**静默忽略**,所以"传了就返回成功"是假成功。与其假装能改备注,
850
+ * 不如明确报错 —— 要支持它得后端先加列 + 加白名单,那是另一个任务。
851
+ * (也**不**用 `settings.remark` 变通:`settings` 是整块覆盖,读-改-写会吞掉原有设置。)
852
+ */
853
+ export const sitesUpdateCommand = {
854
+ name: 'sites update',
855
+ summary: '改站点信息(目前支持改站名;默认 dry-run,`--confirm` 才真发)',
856
+ usage: 'wkgeo sites update <站点ID> [--name <新站名>] [--confirm]',
857
+ args: [{ name: 'id', required: true, desc: '站点 ID' }],
858
+ flags: {
859
+ name: { type: 'string', desc: '新的站点名称(1~60 字)' },
860
+ remark: { type: 'string', desc: '站点备注(**服务端暂不支持**,传了会明确报缺口)' },
861
+ ...CONFIRM_FLAG,
862
+ },
863
+ examples: [
864
+ 'wkgeo sites update 0f2c… --name 新站名',
865
+ 'wkgeo sites update 0f2c… --name 新站名 --confirm',
866
+ ],
867
+ notes: [
868
+ '需要 `site:write`。**默认 dry-run**,加 `--confirm` 才真发。',
869
+ '**`--remark` 暂时发不通**(服务端 `updateSite` 白名单与站点表都没有备注字段),传了会明确报缺口而不是假装成功。',
870
+ '回收站里的站不能编辑:要么先 `wkgeo sites recycle restore`,要么彻底删(只有管理员能做)。',
871
+ '要改域名/模板/有效期不在这条命令里(域名走 `wkgeo domain bind`、有效期只有管理员能改)。',
872
+ ],
873
+ async run(ctx) {
874
+ const { out } = ctx;
875
+ const id = String(ctx.positional.id === undefined ? '' : ctx.positional.id).trim();
876
+ if (!id) throw new UsageError('缺少 <站点ID>(用 `wkgeo sites list` 看站点 ID)');
877
+
878
+ if (ctx.flags.remark !== undefined) {
879
+ throw new CliError(
880
+ '站点备注暂时改不了:服务端 updateSite 的字段白名单里没有 remark,站点表也没有这一列',
881
+ {
882
+ kind: 'unsupported',
883
+ hint:
884
+ '这不是参数写错了。要支持它需要后端先给站点表加 remark 列并加入 updateSite 白名单;' +
885
+ '在那之前 CLI 不会假装写入成功。别的字段(站名)照常可用:--name <新站名>',
886
+ },
887
+ );
888
+ }
889
+
890
+ const nameRaw = ctx.flags.name;
891
+ const name = nameRaw === undefined ? '' : String(nameRaw).trim();
892
+ if (!name) {
893
+ throw new UsageError(
894
+ '至少要给一个要改的字段:`--name <新站名>`\n用法:wkgeo sites update <站点ID> --name <新站名> [--confirm]',
895
+ );
896
+ }
897
+ if (name.length > 60) {
898
+ throw new UsageError(`--name 最长 60 字,收到 ${name.length} 字`);
899
+ }
900
+
901
+ const request = { id, name };
902
+
903
+ if (!ctx.flags.confirm) {
904
+ return dryRun(ctx, 'updateSite', request, [
905
+ `站点 ID:${id}`,
906
+ `新站名:${name}`,
907
+ '效果:只改站点名称,域名/模板/有效期不动',
908
+ ]);
909
+ }
910
+
911
+ const res = await ctx.callData('updateSite', request);
912
+ const src = res && typeof res === 'object' ? res : {};
913
+ const data = {
914
+ id: src.id || id,
915
+ name: src.name || name,
916
+ updated: true,
917
+ };
918
+ if (!out.json) out.ok(`站点已更新:${data.name}(${data.id})`);
919
+ ctx.done(data);
920
+ return data;
921
+ },
922
+ };
923
+
924
+ /** 本模块的 8 组命令(10 条 spec),由 `commands/index.mjs` 展开进 COMMANDS */
925
+ export const MEMBER_COMMANDS = [
926
+ walletBillingCommand,
927
+ walletDebtCommand,
928
+ couponsCommand,
929
+ notifyListCommand,
930
+ notifyReadCommand,
931
+ sitesRecycleCommand,
932
+ sitesRecycleRestoreCommand,
933
+ invoicesListCommand,
934
+ plansListCommand,
935
+ sitesUpdateCommand,
936
+ ];