koishi-plugin-prism 0.1.33 → 0.1.34

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
@@ -25,7 +25,7 @@
25
25
  | `autoRegister` | `boolean` | `true` | 当玩家未注册时,是否在首次操作(如入场/查钱包)时自动在 PRiSM 中创建新玩家。 |
26
26
  | `loginPricingConfigIds` | `string[]` | `[]` | 默认入场计费规则 ID 列表。 |
27
27
  | `loginSessionLabel` | `string` | `"音游区间"` | 默认入场会话的标签文本。后端会按该标签对同一玩家的活跃会话去重,重复入场会被拒绝并提示。留空则不启用去重。 |
28
- | `defaultDoorDeviceId` | `string` | - | 默认门锁设备的 ID,用于开门指令。 |
28
+ | `defaultDoorDeviceId` | `string` | - | 默认门锁设备的名称或别名,用于开门指令;配置项名称仅为兼容旧配置而保留。 |
29
29
  | `defaultScanProvider` | `string` | `"aime"` | 默认模拟刷卡时的读卡器协议提供商(如 `"aime"`)。 |
30
30
  | `currencyName` | `string` | `"金币"` | 账户货币在显示时的自定义单位名称。 |
31
31
  | `resolveDisplayName` | `function` | - | 可选。自定义用于获取群内昵称作为玩家注册名的异步逻辑。 |
@@ -33,7 +33,6 @@
33
33
  | `staffUserIds` | `string[]` | `[]` | 允许执行管理员快捷指令的平台用户 ID(如 QQ 号)白名单。空列表不授予目标用户操作权限。 |
34
34
  | `logoutNotifyUserIds` | `string[]` | `[]` | 结账成功后额外私聊完整账单的平台用户 ID。通知收件人为该列表与 `staffUserIds` 的去重并集。 |
35
35
  | `mahjongTableConfigs` | `object[]` | `[]` | 推荐的结构化麻将桌列表。每项填写显示名称、命令别名列表与计费方案 ID 列表。显示名称同时作为内部桌位锚点与 session 标签。 |
36
- | `mahjongTables` | `string` | - | 旧版文本配置,仅在 `mahjongTableConfigs` 为空时读取;建议迁移到结构化列表。 |
37
36
 
38
37
  ### 麻将桌配置
39
38
 
@@ -45,7 +44,7 @@ aliases: [a, 四麻A, 比赛机]
45
44
  pricingConfigIds: [pricing-mahjong-a]
46
45
  ```
47
46
 
48
- `displayName` 是该桌的稳定锚点和 session 标签;玩家输入的桌号、简称等均写入 `aliases`(至少一个)。结构化配置有内容时优先于旧 `mahjongTables` 文本;已有旧配置不会失效,可逐桌迁移。
47
+ `displayName` 是该桌的稳定锚点和 session 标签;玩家输入的桌号、简称等均写入 `aliases`(至少一个)。麻将桌只读取这个结构化列表。
49
48
 
50
49
  管理员快捷指令必须同时配置 `enableStaffCommands: true` 与 `staffUserIds`。它们使用现有 `integrationToken` 调用受限的余额调整和立即结账接口;目标用户参数使用 Koishi 的 `user` 选择器,只有白名单内的管理员可以操作其他用户。
51
50
 
@@ -55,9 +54,9 @@ pricingConfigIds: [pricing-mahjong-a]
55
54
  * `register` - 绑定或注册当前平台账号到 PRiSM 账户。
56
55
  * `login` / `入场` - 开启当前玩家的计费场次。
57
56
  * `logout` - 结算当前玩家的计费场次。
58
- 玩家在未产生任何费用时退场,机器人会简洁显示“本次未产生费用”和当前余额;存在收费或优惠明细时仍显示完整结算账单。
57
+ 玩家在未产生任何费用时退场,机器人会简洁显示“本次未产生费用”和当前余额;存在收费或优惠明细时仍显示完整结算账单。负单价 session 会在区间明细中保留真实的负数计费贡献,只有后端汇总全部 session 后的最终应付金额会限制为不低于 `0`。
59
58
  结账成功回执中的余额为后端已经完成扣款后的余额;只有 `/billing` 预览会显示当前余额与预计结账后余额。
60
- 方案内区间封顶直接计入对应计时费用;全局封顶按日期和时段逐条列出,不合并、不截断,并直接形成计费总价,不作为优惠。若旧后端未返回结构化封顶窗口,插件会用封顶历史恢复原价与计入金额,不会显示内部 adjustment 差额。只作用于整次结账的资产优惠直接列在计费总价下方,不显示额外标题或 emoji,也不会误归属到最后一个 session。
59
+ 方案内区间封顶直接计入对应计时费用;全局封顶按后端返回的结构化日期和时段逐条列出,不合并、不截断,并直接形成计费总价,不作为优惠。只作用于整次结账的资产优惠直接列在计费总价下方,不显示额外标题或 emoji,也不会误归属到最后一个 session。
61
60
  在玩家退场或管理员覆盖结账成功后,机器人会向 `staffUserIds` 与 `logoutNotifyUserIds` 中的用户私聊同一份账单,账单会明确显示结账玩家身份。
62
61
  同一玩家在前一次退场结账尚未完成时重复发送 `/logout` 或 `/退场`,机器人会复用同一次结账请求与账单,避免重复扣款。
63
62
  账单和管理员代操作回执均使用“平台昵称(QQ:号码)”称呼玩家;平台暂时无法提供昵称时显示“未知昵称(QQ:号码)”,不会显示内部玩家 ID。
@@ -69,8 +68,8 @@ pricingConfigIds: [pricing-mahjong-a]
69
68
  * `show [deviceId]` - 查看设备电源与连接状态。
70
69
  * `history` - 查看自己的历史游玩记录。
71
70
  * `lock` - 发送开门指令。
72
- * `on <deviceId>` - 请求启动指定设备电源。
73
- * `off <deviceId>` - 请求关闭指定设备电源。
71
+ * `on <deviceRef>` - 使用后台设备名称、别名或 `all` 请求启动电源;不接受 Home Assistant entity ID,成功回复使用后端返回的设备名称。
72
+ * `off <deviceRef>` - 使用后台设备名称、别名或 `all` 请求关闭电源;不接受 Home Assistant entity ID,`all` 显示为“所有设备”。
74
73
  * `coin <deviceId> [count]` - 请求向指定设备投币指定枚数。
75
74
  * `scan <deviceId> <subject>` - 请求向设备发送模拟刷卡。
76
75
  * `redeem <code>` - 兑换礼物码。
@@ -78,6 +77,9 @@ pricingConfigIds: [pricing-mahjong-a]
78
77
  * `下桌` - 自动离开当前所在麻将桌,下桌后会停止计费,并显示该麻将桌的剩余游玩人数。
79
78
  * `麻将列表` - 查看已配置机器的桌名、命令别名,以及空闲、等位或游玩中状态。
80
79
  * `api测速 [次数]` - 连续查询自己的钱包,显示 Bot 到 PRiSM API 的最小、平均与最大延迟(默认 3 次,最多 10 次)。
80
+ * `versions` - 显示当前 Bot npm 包版本和后端发布版本;后端不可达时仍会显示 Bot 版本。
81
+
82
+ Bot 版本直接读取本 npm 包的 `package.json`,后端版本读取无需认证的 `GET /version`。插件发布遵循 SemVer;修复使用 patch、兼容新增功能使用 minor、不兼容改动使用 major,发布前通过 `npm version <patch|minor|major>` 自动更新包版本。
81
83
 
82
84
  ### 管理员快捷指令
83
85
  启用 `enableStaffCommands`、配置 `staffUserIds` 白名单与 `staffSessionToken` 后可使用:
package/lib/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Schema } from "koishi";
2
2
  export declare const name = "prism";
3
+ export declare const version: string;
3
4
  export declare const Config: Schema<PrismKoishiPluginConfig>;
4
5
  export declare function apply(ctx: any, config: PrismKoishiPluginConfig): void;
5
6
  export declare class PrismBotClientError extends Error {
@@ -27,9 +28,7 @@ export type PrismKoishiPluginConfig = {
27
28
  staffUserIds?: string[];
28
29
  logoutNotifyUserIds?: string[];
29
30
  mahjongTableConfigs?: MahjongTableConfigInput[];
30
- mahjongTables?: string;
31
31
  mahjongTableSize?: number;
32
- mahjongLabelPrefix?: string;
33
32
  powerOffInterval?: number;
34
33
  /**
35
34
  * Used by /list to resolve player display names from the chat platform.
@@ -76,8 +75,7 @@ export type Sender = {
76
75
  name: string;
77
76
  };
78
77
  export declare function humanReadableBotError(error: PrismBotClientError): string;
79
- export declare function parseMahjongTables(value: string, labelPrefix: string): Map<string, MahjongTableConfig>;
80
- export declare function resolveMahjongTableConfigs(structured: readonly MahjongTableConfigInput[], legacyValue: string, labelPrefix: string): Map<string, MahjongTableConfig>;
78
+ export declare function resolveMahjongTableConfigs(structured: readonly MahjongTableConfigInput[]): Map<string, MahjongTableConfig>;
81
79
  declare const _default: {
82
80
  name: string;
83
81
  Config: Schema<PrismKoishiPluginConfig>;
package/lib/index.js CHANGED
@@ -1,20 +1,24 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PrismBotClientError = exports.Config = exports.name = void 0;
6
+ exports.PrismBotClientError = exports.Config = exports.version = exports.name = void 0;
4
7
  exports.apply = apply;
5
8
  exports.applyPrismKoishiPlugin = applyPrismKoishiPlugin;
6
9
  exports.humanReadableBotError = humanReadableBotError;
7
- exports.parseMahjongTables = parseMahjongTables;
8
10
  exports.resolveMahjongTableConfigs = resolveMahjongTableConfigs;
9
11
  const koishi_1 = require("koishi");
12
+ const package_json_1 = __importDefault(require("../package.json"));
10
13
  exports.name = "prism";
14
+ exports.version = package_json_1.default.version;
11
15
  exports.Config = koishi_1.Schema.object({
12
16
  provider: koishi_1.Schema.string().required().description("平台提供商 (如 qq)"),
13
17
  autoRegister: koishi_1.Schema.boolean().default(true).description("是否自动注册"),
14
18
  baseUrl: koishi_1.Schema.string().description("PRiSM 后端 API Base URL"),
15
19
  integrationToken: koishi_1.Schema.string().role("secret").description("集成 API Token"),
16
20
  currencyName: koishi_1.Schema.string().default("猫粮").description("代币名称"),
17
- defaultDoorDeviceId: koishi_1.Schema.string().default("front-door").description("默认开门设备ID"),
21
+ defaultDoorDeviceId: koishi_1.Schema.string().default("front-door").description("默认开门设备名或别名"),
18
22
  defaultScanProvider: koishi_1.Schema.string().default("aime").description("默认刷卡提供商"),
19
23
  loginPricingConfigIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("默认入场绑定的计费策略ID"),
20
24
  loginSessionLabel: koishi_1.Schema.string().default("音游区间").description("默认入场场次标签 (防重复入场)"),
@@ -27,9 +31,7 @@ exports.Config = koishi_1.Schema.object({
27
31
  aliases: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("命令别名(至少一个),例如 a、四麻A"),
28
32
  pricingConfigIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("开局时绑定的计费方案 ID"),
29
33
  })).default([]).description("麻将桌配置"),
30
- mahjongTables: koishi_1.Schema.string().description("旧版麻将桌文本配置(已废弃;仅在结构化配置为空时使用)"),
31
34
  mahjongTableSize: koishi_1.Schema.number().default(4).description("麻将桌人数限制"),
32
- mahjongLabelPrefix: koishi_1.Schema.string().default("麻将桌").description("麻将账单前缀"),
33
35
  });
34
36
  function apply(ctx, config) {
35
37
  applyPrismKoishiPlugin(ctx, config);
@@ -53,8 +55,8 @@ const USAGE = {
53
55
  mahjong_leave: "/下桌",
54
56
  mahjong_list: "/麻将列表",
55
57
  api_benchmark: "/api测速 [次数]",
56
- prism_on: "/prism on <设备ID>",
57
- prism_off: "/prism off <设备ID|all>",
58
+ prism_on: "/prism on <设备名|别名|all>",
59
+ prism_off: "/prism off <设备名|别名|all>",
58
60
  prism_coin: "/prism coin <设备ID> [数量]",
59
61
  prism_scan: "/prism scan <设备ID> <卡号>",
60
62
  prism_redeem: "/prism redeem <兑换码>",
@@ -84,13 +86,14 @@ function applyPrismKoishiPlugin(ctx, config) {
84
86
  ctx.command("billing [target:user]", "预览玩家结账费用").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.billing(sender), context.session?.bot)));
85
87
  ctx.command("wallet [target:user]", "查看玩家钱包").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.wallet(sender), context.session?.bot)));
86
88
  ctx.command("api测速 [count:number]", "测试 Bot 到 PRiSM API 的钱包查询延迟").action(wrap(async (context, count) => service.benchmarkApi(await service.sender(context), count)));
89
+ ctx.command("versions", "查看 Bot 与 PRiSM 后端版本").action(wrap(async () => service.versions()));
87
90
  ctx.command("items [target:user]", "查看玩家资产").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.items(sender), context.session?.bot)));
88
91
  ctx.command("list", "查看当前在线玩家列表").action(wrap(async (context) => service.listActiveSessions(await service.sender(context))));
89
92
  ctx.command("show [deviceId]", "查看设备电源状态").action(wrap(async (context, deviceId) => service.listDeviceStates(deviceId)));
90
93
  ctx.command("history [target:user]", "查看玩家历史").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.history(sender), context.session?.bot)));
91
94
  ctx.command("lock", "向默认门锁设备发送开门指令").action(wrap(async (context) => service.lock(await service.sender(context))));
92
- ctx.command("on <deviceId>", "请求启动指定设备电源").action(wrap(async (context, deviceId) => service.powerOn(await service.sender(context), deviceId)));
93
- ctx.command("off <deviceId>", "请求关闭指定设备电源").action(wrap(async (context, deviceId) => service.powerOff(await service.sender(context), deviceId)));
95
+ ctx.command("on <deviceRef>", "请求启动指定设备电源").action(wrap(async (context, deviceRef) => service.powerOn(await service.sender(context), deviceRef)));
96
+ ctx.command("off <deviceRef>", "请求关闭指定设备电源").action(wrap(async (context, deviceRef) => service.powerOff(await service.sender(context), deviceRef)));
94
97
  ctx.command("coin <deviceId> [count]", "请求向指定设备投币").action(wrap(async (context, deviceId, count) => service.coin(await service.sender(context), deviceId, count)));
95
98
  ctx.command("scan <deviceId> <subject>", "请求指定设备模拟刷卡").action(wrap(async (context, deviceId, subject) => service.scan(await service.sender(context), deviceId, subject)));
96
99
  ctx.command("redeem <code>", "兑换 PRiSM 礼物码").action(wrap(async (context, code) => service.redeem(await service.sender(context), code)));
@@ -179,6 +182,9 @@ class PrismApiClient {
179
182
  });
180
183
  return result.player;
181
184
  }
185
+ async getVersion() {
186
+ return this.request("GET", "/version", {});
187
+ }
182
188
  async startSessionByIdentity(identity, body) {
183
189
  return this.request("POST", "/rpc/integration/players/by-identity/session/start", {
184
190
  token: this.config.integrationToken,
@@ -390,7 +396,7 @@ class PrismKoishiService {
390
396
  return "金额必须为非负数";
391
397
  const reason = cleanText(rawReason) || "管理员调价";
392
398
  const result = (await this.client.checkoutWithOverrideByIdentity(this.identity(sender), total, reason));
393
- const playerId = String(result?.playerSettlement?.playerId ?? result?.settlement?.playerId ?? "");
399
+ const playerId = String(result.playerSettlement.playerId);
394
400
  if (playerId)
395
401
  this.removeMahjongPlayer(playerId);
396
402
  return this.formatAndNotifyCheckout(result, sender, "✅ 覆盖结账成功 · 结算账单", bot);
@@ -424,7 +430,7 @@ class PrismKoishiService {
424
430
  return `「${tableSubject}」正在游玩中(${activeCount}/${tableSize}),请等待本局结束后再上桌。`;
425
431
  }
426
432
  if (activeCount > 0) {
427
- const label = tableConfig.displayName || `${this.config.mahjongLabelPrefix ?? "麻将桌"} ${tableKey}`;
433
+ const label = tableConfig.displayName;
428
434
  const result = (await this.client.startSessionByIdentity(this.identity(sender), {
429
435
  pricingConfigIds: tableConfig.pricingConfigIds,
430
436
  label,
@@ -447,7 +453,7 @@ class PrismKoishiService {
447
453
  }
448
454
  const seats = state.waiting.slice(0, tableSize);
449
455
  state.waiting = state.waiting.slice(tableSize);
450
- const label = tableConfig.displayName || `${this.config.mahjongLabelPrefix ?? "麻将桌"} ${tableKey}`;
456
+ const label = tableConfig.displayName;
451
457
  for (const seat of seats) {
452
458
  const result = (await this.client.startSessionByIdentity(seat.identity, {
453
459
  pricingConfigIds: tableConfig.pricingConfigIds,
@@ -509,7 +515,7 @@ class PrismKoishiService {
509
515
  }
510
516
  async billing(sender) {
511
517
  const result = (await this.client.previewCheckoutByIdentity(this.identity(sender)));
512
- return this.formatCheckoutPreview(result, sender);
518
+ return this.formatCheckoutPreview(result, sender, "【结算账单】", true);
513
519
  }
514
520
  async logout(sender, bot) {
515
521
  const existing = this.logoutInFlight.get(sender.id);
@@ -527,54 +533,53 @@ class PrismKoishiService {
527
533
  }
528
534
  async performLogout(sender, bot) {
529
535
  const result = (await this.client.confirmCheckoutByIdentity(this.identity(sender), false));
530
- const playerId = String(result?.playerSettlement?.playerId ?? result?.settlement?.playerId ?? "");
536
+ const playerId = String(result.playerSettlement.playerId);
531
537
  if (playerId)
532
538
  this.removeMahjongPlayer(playerId);
533
539
  return this.formatAndNotifyCheckout(result, sender, "✅ 退场成功 · 结算账单", bot);
534
540
  }
535
541
  async formatAndNotifyCheckout(result, sender, title, bot) {
536
- const settlement = result?.playerSettlement ?? result?.settlement ?? {};
537
- const records = result?.settlements ?? [];
538
- const checkoutAdjustments = (result?.checkoutAdjustments ?? []);
539
- const pricingCapAdjustments = (result?.pricingCapAdjustments ?? []);
542
+ const settlement = result.playerSettlement;
543
+ const records = result.settlements;
544
+ const checkoutAdjustments = result.checkoutAdjustments;
545
+ const pricingCapAdjustments = result.pricingCapAdjustments;
540
546
  const checkoutAdjustmentKeys = new Set(checkoutAdjustments.map(adjustmentKey));
541
547
  const pricingCapAdjustmentKeys = new Set(pricingCapAdjustments.map(adjustmentKey));
542
548
  const sessionPreviews = records.map((rec) => {
543
- const s = rec?.settlement ?? {};
544
- const sessionAdjustments = (rec?.adjustments ?? []).filter((adjustment) => {
549
+ const s = rec.settlement;
550
+ const sessionAdjustments = rec.adjustments.filter((adjustment) => {
545
551
  const key = adjustmentKey(adjustment);
546
552
  return !checkoutAdjustmentKeys.has(key) &&
547
553
  !pricingCapAdjustmentKeys.has(key) &&
548
554
  !isPricingCapAdjustment(adjustment);
549
555
  });
550
- const sessionSubtotal = toNumber(s.subtotal ?? 0);
556
+ const sessionSubtotal = toNumber(s.subtotal);
551
557
  return {
552
558
  sessionId: s.sessionId,
553
559
  label: s.label,
554
560
  startedAt: s.startedAt,
555
- endedAt: s.endedAt ?? s.settledAt,
561
+ endedAt: s.endedAt,
556
562
  status: "closed",
557
563
  subtotal: sessionSubtotal,
558
- total: Math.max(0, sessionSubtotal + sessionAdjustments.reduce((sum, adjustment) => sum + toNumber(adjustment?.amount ?? 0), 0)),
559
- chargeItems: rec?.chargeItems ?? [],
564
+ total: sessionSubtotal + sessionAdjustments.reduce((sum, adjustment) => sum + toNumber(adjustment?.amount ?? 0), 0),
565
+ chargeItems: rec.chargeItems,
560
566
  adjustments: sessionAdjustments,
561
567
  };
562
568
  });
563
569
  const synthetic = {
564
- settlement: {
570
+ settlementPreview: {
565
571
  playerId: settlement.playerId,
566
- subtotal: settlement.subtotal ?? 0,
567
- total: settlement.total ?? 0,
572
+ subtotal: settlement.subtotal,
573
+ total: settlement.total,
568
574
  },
569
575
  sessionPreviews,
570
- chargeItems: result?.chargeItems ?? [],
571
- adjustments: result?.adjustments ?? [],
576
+ chargeItems: result.chargeItems,
572
577
  checkoutAdjustments,
573
578
  pricingCapAdjustments,
574
- globalCapWindows: result?.globalCapWindows ?? [],
575
- assetHoldings: result?.assetHoldings ?? [],
579
+ globalCapWindows: result.globalCapWindows,
580
+ assetHoldings: result.assetHoldings,
576
581
  };
577
- const receipt = await this.formatCheckoutPreview(synthetic, sender, title);
582
+ const receipt = await this.formatCheckoutPreview(synthetic, sender, title, false);
578
583
  const recipients = [...new Set([...(this.config.staffUserIds ?? []), ...(this.config.logoutNotifyUserIds ?? [])])];
579
584
  if (recipients.length > 0 && bot?.broadcast) {
580
585
  const channelIds = recipients.map((id) => (id.includes(":") ? id : `private:${id}`));
@@ -584,7 +589,7 @@ class PrismKoishiService {
584
589
  }
585
590
  async wallet(sender) {
586
591
  const result = (await this.client.getWalletByIdentity(this.identity(sender)));
587
- return formatWallet(result, this.config.currencyName);
592
+ return formatWallet(result.wallet, this.config.currencyName);
588
593
  }
589
594
  async benchmarkApi(sender, rawCount) {
590
595
  const count = rawCount == null || rawCount === "" ? 3 : Number(rawCount);
@@ -606,33 +611,49 @@ class PrismKoishiService {
606
611
  `最大:${formatNumber(max)} ms`,
607
612
  ].join("\n");
608
613
  }
614
+ async versions() {
615
+ let backendVersion = "不可用";
616
+ try {
617
+ backendVersion = formatReleaseVersion(await this.client.getVersion());
618
+ }
619
+ catch {
620
+ // The Bot version remains useful when the backend is offline or too old.
621
+ }
622
+ return [
623
+ "PRiSM 版本信息",
624
+ `Bot:${exports.version}`,
625
+ `后端:${backendVersion}`,
626
+ ].join("\n");
627
+ }
609
628
  async items(sender) {
610
- const holdings = extractRows((await this.client.getAssetsByIdentity(this.identity(sender))));
629
+ const result = (await this.client.getAssetsByIdentity(this.identity(sender)));
630
+ const holdings = result.holdings;
611
631
  if (holdings.length === 0)
612
632
  return "您当前没有任何物品。";
613
633
  return ["🎒 --- 您拥有的物品 ---", ...holdings.map(formatInventoryItem)].join("\n");
614
634
  }
615
635
  async history(sender) {
616
- return formatHistory((await this.client.getSessionHistoryByIdentity(this.identity(sender))), this.config.currencyName);
636
+ const result = (await this.client.getSessionHistoryByIdentity(this.identity(sender)));
637
+ return formatHistory(result.sessions, this.config.currencyName);
617
638
  }
618
639
  async lock(sender) {
619
640
  await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
620
641
  type: "door.open",
621
- target: { kind: "facility", id: this.config.defaultDoorDeviceId },
642
+ target: { kind: "facility", ref: this.config.defaultDoorDeviceId },
622
643
  });
623
644
  return "🔑 门锁指令已发送";
624
645
  }
625
- async powerOn(sender, rawDeviceId) {
626
- const deviceId = cleanText(rawDeviceId);
627
- if (!deviceId)
646
+ async powerOn(sender, rawDeviceRef) {
647
+ const deviceRef = cleanText(rawDeviceRef);
648
+ if (!deviceRef)
628
649
  return commandUsage("prism_on");
629
- return this.power(sender, deviceId, "on");
650
+ return this.power(sender, deviceRef, "on");
630
651
  }
631
- async powerOff(sender, rawDeviceId) {
632
- const deviceId = cleanText(rawDeviceId);
633
- if (!deviceId)
652
+ async powerOff(sender, rawDeviceRef) {
653
+ const deviceRef = cleanText(rawDeviceRef);
654
+ if (!deviceRef)
634
655
  return commandUsage("prism_off");
635
- return this.power(sender, deviceId, "off");
656
+ return this.power(sender, deviceRef, "off");
636
657
  }
637
658
  async coin(sender, rawDeviceId, rawCount) {
638
659
  const deviceId = cleanText(rawDeviceId);
@@ -671,45 +692,23 @@ class PrismKoishiService {
671
692
  if (!code)
672
693
  return commandUsage("prism_redeem");
673
694
  const result = (await this.client.redeemCodeByIdentity(this.identity(sender), code));
674
- const holdings = extractRows(result);
675
- if (holdings.length === 0)
695
+ const grantedAssets = result.grantedAssets;
696
+ if (grantedAssets.length === 0)
676
697
  return "兑换成功,但没有获得任何物品。";
677
- return ["✅ 兑换成功!您获得了以下物品:", ...holdings.map(formatRedeemedItem)].join("\n");
698
+ return ["✅ 兑换成功!您获得了以下物品:", ...grantedAssets.map(formatRedeemedItem)].join("\n");
678
699
  }
679
700
  async listActiveSessions(sender) {
680
701
  const result = (await this.client.listActiveSessions());
681
702
  const sessions = (result?.sessions ?? []);
682
703
  this.syncMahjongTableStates(sessions);
683
704
  const tableByLabel = new Map(uniqueMahjongConfigs(this.mahjongTableConfigs()).map((table) => [
684
- mahjongSessionLabel(table, this.config.mahjongLabelPrefix ?? "麻将桌"),
705
+ mahjongSessionLabel(table),
685
706
  table,
686
707
  ]));
687
708
  const players = groupSessionsByPlayer(sessions);
688
709
  const groups = await this.buildPlayerGroups(players, tableByLabel);
689
710
  this.mergeWaitingSeats(groups);
690
- return formatPlayerGroups(groups, this.config.mahjongTableSize ?? 4, this.config.mahjongLabelPrefix ?? "麻将桌");
691
- }
692
- parseDeviceStateValue(stateVal) {
693
- if (!stateVal)
694
- return "unknown";
695
- if (typeof stateVal === "string") {
696
- try {
697
- const decoded = JSON.parse(stateVal);
698
- if (typeof decoded === "string") {
699
- return decoded;
700
- }
701
- if (decoded && typeof decoded.state === "string") {
702
- return decoded.state;
703
- }
704
- }
705
- catch {
706
- return stateVal;
707
- }
708
- }
709
- if (typeof stateVal === "object" && stateVal !== null) {
710
- return stateVal.state ?? "unknown";
711
- }
712
- return "unknown";
711
+ return formatPlayerGroups(groups, this.config.mahjongTableSize ?? 4);
713
712
  }
714
713
  async listDeviceStates(rawAlias) {
715
714
  const alias = cleanText(rawAlias);
@@ -721,11 +720,11 @@ class PrismKoishiService {
721
720
  const matched = states.find((d) => d.deviceId === alias || d.label === alias);
722
721
  if (!matched)
723
722
  return `找不到设备: ${alias}`;
724
- const stateVal = this.parseDeviceStateValue(matched.state);
723
+ const stateVal = matched.state?.state ?? "unknown";
725
724
  return `${matched.label || matched.deviceId}: ${stateVal}`;
726
725
  }
727
726
  return states
728
- .map((d) => `${d.label || d.deviceId}: ${this.parseDeviceStateValue(d.state)}`)
727
+ .map((d) => `${d.label || d.deviceId}: ${d.state?.state ?? "unknown"}`)
729
728
  .join("\n");
730
729
  }
731
730
  async autoPowerOffLoop() {
@@ -738,28 +737,24 @@ class PrismKoishiService {
738
737
  return;
739
738
  const statesResult = (await this.client.listDeviceStates());
740
739
  const states = (statesResult?.deviceStates ?? []);
741
- const anyOn = states.some((d) => this.parseDeviceStateValue(d.state) !== "off");
740
+ const anyOn = states.some((d) => d.state?.state !== "off");
742
741
  if (!anyOn)
743
742
  return;
744
743
  const dummySender = { id: "system", name: "system" };
745
744
  await this.powerOff(dummySender, "all");
746
745
  }
747
746
  /* ---------------------------- helpers ---------------------------------- */
748
- async power(sender, deviceId, state) {
747
+ async power(sender, deviceRef, state) {
749
748
  const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
750
749
  type: state === "on" ? "power.on" : "power.off",
751
- target: { kind: "facility", id: deviceId },
750
+ target: { kind: "facility", ref: deviceRef },
752
751
  payload: { state },
753
752
  });
754
753
  const failure = this.getCommandFailureMessage(result);
755
754
  if (failure)
756
755
  return `❌ 执行失败:${failure}`;
757
- const displayName = result?.action?.payload?.deviceLabel || deviceId;
758
- if (state === "on")
759
- return `✅ ${displayName} 启动成功`;
760
- if (deviceId === "all")
761
- return `🛑 全部机器关闭成功`;
762
- return `🛑 ${displayName} 关闭成功`;
756
+ const deviceLabel = result.action.payload.deviceLabel;
757
+ return state === "on" ? `✅ ${deviceLabel} 启动成功` : `🛑 ${deviceLabel} 关闭成功`;
763
758
  }
764
759
  getCommandFailureMessage(result) {
765
760
  const action = result?.action;
@@ -820,7 +815,7 @@ class PrismKoishiService {
820
815
  const table = uniqueMahjongConfigs(this.mahjongTableConfigs()).find((candidate) => candidate.tableId === tableId);
821
816
  if (!table)
822
817
  continue;
823
- const label = mahjongSessionLabel(table, this.config.mahjongLabelPrefix ?? "麻将桌");
818
+ const label = mahjongSessionLabel(table);
824
819
  let group = groups.groups.find((candidate) => candidate.label === label);
825
820
  if (!group) {
826
821
  group = { label, table, players: [] };
@@ -864,12 +859,12 @@ class PrismKoishiService {
864
859
  }
865
860
  }
866
861
  mahjongTableConfigs() {
867
- return resolveMahjongTableConfigs(this.config.mahjongTableConfigs ?? [], this.config.mahjongTables ?? "", this.config.mahjongLabelPrefix ?? "麻将桌");
862
+ return resolveMahjongTableConfigs(this.config.mahjongTableConfigs ?? []);
868
863
  }
869
864
  syncMahjongTableStates(sessions) {
870
865
  const tables = uniqueMahjongConfigs(this.mahjongTableConfigs());
871
866
  const tableByLabel = new Map(tables.map((table) => [
872
- mahjongSessionLabel(table, this.config.mahjongLabelPrefix ?? "麻将桌"),
867
+ mahjongSessionLabel(table),
873
868
  table,
874
869
  ]));
875
870
  // All playerIds that still have at least one active session in the backend.
@@ -955,38 +950,17 @@ class PrismKoishiService {
955
950
  return "权限不足";
956
951
  return null;
957
952
  }
958
- async formatCheckoutPreview(result, sender, title = "【结算账单】") {
959
- if (result?.billing && result?.session) {
960
- return formatLegacyBilling(result, this.config.currencyName);
961
- }
953
+ async formatCheckoutPreview(result, sender, title = "【结算账单】", isPreview) {
962
954
  const currency = this.config.currencyName;
963
- const preview = result?.settlementPreview ?? result?.settlement ?? {};
964
- const playerId = preview?.playerId ?? "";
965
- const subtotal = firstDefined(preview, "subtotal", "originalCost", 0);
966
- const total = firstDefined(preview, "total", "finalCost", "amount", subtotal);
967
- const previewedAt = parseDateTime(preview?.previewedAt);
968
- let sessionPreviews = (result?.sessionPreviews ?? []);
969
- if (sessionPreviews.length === 0 && (result?.chargeItems || result?.session)) {
970
- const session = result?.session ?? {};
971
- sessionPreviews = [
972
- {
973
- sessionId: session?.id ?? session?.sessionId,
974
- label: session?.label ?? "计时区间",
975
- startedAt: firstDefined(session, "startedAt", "createdAt"),
976
- endedAt: firstDefined(preview, "endedAt", "settledAt", "endTime"),
977
- status: session?.status ?? "active",
978
- subtotal,
979
- total,
980
- chargeItems: result?.chargeItems ?? [],
981
- adjustments: [],
982
- },
983
- ];
984
- }
985
- const adjustments = (result?.adjustments ?? []);
986
- const pricingCapAdjustments = (result?.pricingCapAdjustments ?? adjustments.filter(isPricingCapAdjustment));
987
- const sessionAdjustmentKeys = new Set(sessionPreviews.flatMap((session) => (session?.adjustments ?? []).map(adjustmentKey)));
988
- const checkoutAdjustments = (result?.checkoutAdjustments ?? adjustments.filter((adjustment) => !isPricingCapAdjustment(adjustment) && !sessionAdjustmentKeys.has(adjustmentKey(adjustment))));
989
- const assetHoldings = result?.assetHoldings ?? [];
955
+ const preview = result.settlementPreview;
956
+ const playerId = preview.playerId;
957
+ const subtotal = preview.subtotal;
958
+ const total = preview.total;
959
+ const previewedAt = parseDateTime(preview.previewedAt);
960
+ const sessionPreviews = result.sessionPreviews;
961
+ const pricingCapAdjustments = result.pricingCapAdjustments;
962
+ const checkoutAdjustments = result.checkoutAdjustments;
963
+ const assetHoldings = result.assetHoldings;
990
964
  const lines = [];
991
965
  lines.push(title);
992
966
  lines.push(await this.resolvePlayerDisplay(sender, playerId));
@@ -1033,49 +1007,33 @@ class PrismKoishiService {
1033
1007
  }
1034
1008
  const sessionAdjustments = (sPrev?.adjustments ?? []);
1035
1009
  for (const adj of sessionAdjustments) {
1036
- const amount = toNumber(firstDefined(adj ?? {}, "amount", "saved", 0));
1010
+ const amount = toNumber(adj.amount);
1037
1011
  if (amount === 0)
1038
1012
  continue;
1039
- const adjLabel = firstDefined(adj ?? {}, "label", "name", "source") ?? "优惠";
1013
+ const adjLabel = adj.label || adj.source || "优惠";
1040
1014
  lines.push(` └ ${adjLabel}:${formatNumber(amount)}${currency}`);
1041
1015
  }
1042
1016
  }
1043
- const cappedWindows = (result?.globalCapWindows ?? []).filter((window) => toNumber(window?.currentAmount) !== toNumber(window?.amountApplied));
1044
- const appliedCapAdjustments = pricingCapAdjustments.filter((adjustment) => toNumber(adjustment?.amount ?? 0) !== 0);
1045
- if (cappedWindows.length > 0 || appliedCapAdjustments.length > 0) {
1017
+ const cappedWindows = result.globalCapWindows.filter((window) => toNumber(window?.currentAmount) !== toNumber(window?.amountApplied));
1018
+ if (cappedWindows.length > 0) {
1046
1019
  lines.push("");
1047
1020
  lines.push("封顶:");
1048
- if (cappedWindows.length > 0) {
1049
- for (const window of cappedWindows) {
1050
- const label = firstDefined(window, "ruleLabel", "label", "name") ?? "封顶时段";
1051
- const startedAt = parseDateTime(window?.windowStartedAt);
1052
- const datedLabel = startedAt ? `${formatMD(startedAt)} ${label}` : label;
1053
- const currentAmount = toNumber(window?.currentAmount);
1054
- const amountApplied = toNumber(window?.amountApplied);
1055
- const priceCap = toNumber(window?.priceCap);
1056
- const paidBefore = toNumber(window?.paidBefore);
1057
- const details = [`上限${formatNumber(priceCap)}`];
1058
- if (paidBefore > 0)
1059
- details.push(`已计${formatNumber(paidBefore)}`);
1060
- lines.push(`- ${datedLabel}:${formatNumber(currentAmount)} → ${formatNumber(amountApplied)}${currency}(${details.join(",")})`);
1061
- }
1062
- }
1063
- else {
1064
- for (const adjustment of appliedCapAdjustments) {
1065
- const label = firstDefined(adjustment, "label", "name", "source") ?? "封顶时段";
1066
- const history = adjustment?.pricingCapHistory ?? {};
1067
- const amountApplied = toNumber(history?.amount);
1068
- const currentAmount = amountApplied - toNumber(adjustment?.amount ?? 0);
1069
- const anchorAt = parseDateTime(history?.capAnchorAt);
1070
- const datedLabel = anchorAt ? `${formatMD(anchorAt)} ${label}` : label;
1071
- lines.push(amountApplied > 0
1072
- ? `- ${datedLabel}:${formatNumber(currentAmount)} → ${formatNumber(amountApplied)}${currency}`
1073
- : `- ${datedLabel}:${formatNumber(adjustment?.amount ?? 0)}${currency}`);
1074
- }
1021
+ for (const window of cappedWindows) {
1022
+ const label = window.ruleLabel || "封顶时段";
1023
+ const startedAt = parseDateTime(window.windowStartedAt);
1024
+ const datedLabel = startedAt ? `${formatMD(startedAt)} ${label}` : label;
1025
+ const currentAmount = toNumber(window.currentAmount);
1026
+ const amountApplied = toNumber(window.amountApplied);
1027
+ const priceCap = toNumber(window.priceCap);
1028
+ const paidBefore = toNumber(window.paidBefore);
1029
+ const details = [`上限${formatNumber(priceCap)}`];
1030
+ if (paidBefore > 0)
1031
+ details.push(`已计${formatNumber(paidBefore)}`);
1032
+ lines.push(`- ${datedLabel}:${formatNumber(currentAmount)} → ${formatNumber(amountApplied)}${currency}(${details.join(",")})`);
1075
1033
  }
1076
1034
  }
1077
1035
  const visibleCheckoutAdjustments = checkoutAdjustments.filter((adjustment) => {
1078
- const amount = toNumber(firstDefined(adjustment ?? {}, "amount", "saved", 0));
1036
+ const amount = toNumber(adjustment.amount);
1079
1037
  const isOverride = cleanText(adjustment?.source).startsWith("staff.override:");
1080
1038
  return amount !== 0 && !isOverride;
1081
1039
  });
@@ -1086,8 +1044,8 @@ class PrismKoishiService {
1086
1044
  if (visibleCheckoutAdjustments.length > 0) {
1087
1045
  lines.push("");
1088
1046
  for (const adjustment of visibleCheckoutAdjustments) {
1089
- const amount = toNumber(firstDefined(adjustment ?? {}, "amount", "saved", 0));
1090
- const label = firstDefined(adjustment ?? {}, "label", "name", "source") ?? "优惠";
1047
+ const amount = toNumber(adjustment.amount);
1048
+ const label = adjustment.label || adjustment.source || "优惠";
1091
1049
  lines.push(`${label}:${formatNumber(amount)}${currency}`);
1092
1050
  }
1093
1051
  }
@@ -1097,7 +1055,6 @@ class PrismKoishiService {
1097
1055
  lines.push(`${hasManualAdjustment ? "调整后价格" : "优惠后价格"}:${formatNumber(total)}${currency}`);
1098
1056
  }
1099
1057
  if (hasBalance) {
1100
- const isPreview = result?.settlementPreview != null && result?.settlement == null;
1101
1058
  if (isPreview) {
1102
1059
  const projectedBalance = balance - toNumber(total);
1103
1060
  lines.push(`当前余额:${formatNumber(balance)}${currency}`);
@@ -1151,46 +1108,7 @@ function humanReadableBotError(error) {
1151
1108
  }
1152
1109
  return String(error?.message ?? error);
1153
1110
  }
1154
- function parseMahjongTables(value, labelPrefix) {
1155
- const tables = new Map();
1156
- for (const item of value.replace(/\n/g, ";").split(";")) {
1157
- const text = item.trim();
1158
- if (!text)
1159
- continue;
1160
- let aliasPart;
1161
- let rest;
1162
- let displayName = "";
1163
- if (text.includes(":")) {
1164
- [aliasPart, rest] = splitOnce(text, ":");
1165
- if (!rest.includes("="))
1166
- continue;
1167
- [displayName, rest] = splitOnce(rest, "=");
1168
- displayName = displayName.trim();
1169
- }
1170
- else {
1171
- if (!text.includes("="))
1172
- continue;
1173
- [aliasPart, rest] = splitOnce(text, "=");
1174
- }
1175
- const aliases = aliasPart.split(",").map((a) => a.trim()).filter(Boolean);
1176
- const pricingConfigIds = rest.split("+").map((p) => p.trim()).filter(Boolean);
1177
- if (aliases.length === 0 || pricingConfigIds.length === 0)
1178
- continue;
1179
- const tableId = aliases[0];
1180
- const config = {
1181
- tableId,
1182
- displayName,
1183
- aliases,
1184
- pricingConfigIds,
1185
- };
1186
- for (const alias of aliases)
1187
- tables.set(alias, config);
1188
- }
1189
- return tables;
1190
- }
1191
- function resolveMahjongTableConfigs(structured, legacyValue, labelPrefix) {
1192
- if (structured.length === 0)
1193
- return parseMahjongTables(legacyValue, labelPrefix);
1111
+ function resolveMahjongTableConfigs(structured) {
1194
1112
  const tables = new Map();
1195
1113
  for (const input of structured) {
1196
1114
  const displayName = cleanText(input.displayName);
@@ -1208,8 +1126,8 @@ function resolveMahjongTableConfigs(structured, legacyValue, labelPrefix) {
1208
1126
  function uniqueMahjongConfigs(tables) {
1209
1127
  return [...new Map([...tables.values()].map((table) => [table.tableId, table])).values()];
1210
1128
  }
1211
- function mahjongSessionLabel(table, labelPrefix) {
1212
- return table.displayName || `${labelPrefix} ${table.tableId}`;
1129
+ function mahjongSessionLabel(table) {
1130
+ return table.displayName;
1213
1131
  }
1214
1132
  function groupSessionsByPlayer(sessions) {
1215
1133
  const players = new Map();
@@ -1227,7 +1145,7 @@ function sessionStartedAt(session) {
1227
1145
  const value = Date.parse(session.startedAt ?? "");
1228
1146
  return Number.isFinite(value) ? value : 0;
1229
1147
  }
1230
- function formatPlayerGroups(groups, tableSize, mahjongLabelPrefix) {
1148
+ function formatPlayerGroups(groups, tableSize) {
1231
1149
  const populatedGroups = groups.groups.filter((group) => group.players.length > 0);
1232
1150
  const total = new Set(populatedGroups.flatMap((group) => group.players.map((player) => player.playerId))).size;
1233
1151
  if (total === 0)
@@ -1235,25 +1153,15 @@ function formatPlayerGroups(groups, tableSize, mahjongLabelPrefix) {
1235
1153
  const lines = [`[总计 ${total} 人]`];
1236
1154
  for (const group of populatedGroups) {
1237
1155
  const heading = group.table
1238
- ? `${formatMahjongTableLabel(group.table, mahjongLabelPrefix)} ( ${group.players.length}/${tableSize} )`
1156
+ ? `${group.table.displayName} ( ${group.players.length}/${tableSize} )`
1239
1157
  : `${group.label} ( ${group.players.length}人 )`;
1240
1158
  lines.push(`\n${heading}:\n${formatPlayerNames(group.players)}`);
1241
1159
  }
1242
1160
  return lines.join("\n");
1243
1161
  }
1244
- function formatMahjongTableLabel(table, labelPrefix) {
1245
- const label = mahjongSessionLabel(table, labelPrefix);
1246
- return table.displayName ? label : `🀄️ ${label}`;
1247
- }
1248
1162
  function formatPlayerNames(players) {
1249
1163
  return players.map((player) => `- ${player.displayName || player.playerId || "未知玩家"}`).join(", ");
1250
1164
  }
1251
- function splitOnce(text, sep) {
1252
- const idx = text.indexOf(sep);
1253
- if (idx === -1)
1254
- return [text, ""];
1255
- return [text.slice(0, idx), text.slice(idx + sep.length)];
1256
- }
1257
1165
  function commandUsage(command) {
1258
1166
  return `用法: ${USAGE[command] ?? command}`;
1259
1167
  }
@@ -1273,6 +1181,12 @@ function parsePositiveInt(value, command, label, fallback) {
1273
1181
  function cleanText(value) {
1274
1182
  return value == null ? "" : String(value).trim();
1275
1183
  }
1184
+ function formatReleaseVersion(value) {
1185
+ const record = value && typeof value === "object" ? value : {};
1186
+ const release = cleanText(record.version) || "unknown";
1187
+ const revision = cleanText(record.revision);
1188
+ return !revision || revision === "unknown" ? release : `${release} (${revision})`;
1189
+ }
1276
1190
  function normalizeTargetSubject(value) {
1277
1191
  const subject = cleanText(value);
1278
1192
  const separator = subject.indexOf(":");
@@ -1316,7 +1230,7 @@ function toNumber(value) {
1316
1230
  return 0;
1317
1231
  }
1318
1232
  function hasAdjustmentEntries(adjustments, sessionPreviews) {
1319
- return adjustments.some((adjustment) => toNumber(firstDefined(adjustment ?? {}, "amount", "saved", 0)) !== 0) || sessionPreviews.some((session) => (session?.adjustments ?? []).some((adjustment) => toNumber(firstDefined(adjustment ?? {}, "amount", "saved", 0)) !== 0));
1233
+ return adjustments.some((adjustment) => toNumber(adjustment.amount) !== 0) || sessionPreviews.some((session) => session.adjustments.some((adjustment) => toNumber(adjustment.amount) !== 0));
1320
1234
  }
1321
1235
  function formatNumber(value) {
1322
1236
  if (typeof value === "boolean")
@@ -1413,86 +1327,28 @@ function minDate(dates) {
1413
1327
  function maxDate(dates) {
1414
1328
  return dates.reduce((acc, d) => (d.getTime() > acc.getTime() ? d : acc), dates[0]);
1415
1329
  }
1416
- function extractRows(value) {
1417
- if (Array.isArray(value))
1418
- return value.filter((row) => row && typeof row === "object");
1419
- if (!value || typeof value !== "object")
1420
- return [];
1421
- for (const key of ["holdings", "assets", "items", "wallet", "sessions"]) {
1422
- const rows = value[key];
1423
- if (Array.isArray(rows))
1424
- return rows.filter((row) => row && typeof row === "object");
1425
- }
1426
- return [];
1427
- }
1428
- function rowQuantity(row) {
1429
- return toNumber(firstDefined(row, "quantity", "amount", "count", 0));
1430
- }
1431
- function holdingName(row) {
1432
- return (row.name ||
1433
- row.assetName ||
1434
- assetName(row) ||
1435
- row.assetCode ||
1436
- row.type ||
1437
- "资产");
1438
- }
1439
- function assetName(row) {
1440
- const asset = row?.asset;
1441
- if (asset && typeof asset === "object") {
1442
- return asset.name || asset.code || "";
1443
- }
1444
- return row.assetName || row.name || row.assetCode || "资产";
1445
- }
1446
- function isPaidBalance(row) {
1447
- const value = `${row?.assetCode ?? ""} ${row?.assetName ?? ""} ${row?.type ?? ""}`.toLowerCase();
1448
- return value.includes("paid") || value.includes("充值");
1449
- }
1450
- function isFreeBalance(row) {
1451
- const value = `${row?.assetCode ?? ""} ${row?.assetName ?? ""} ${row?.type ?? ""}`.toLowerCase();
1452
- return value.includes("free") || value.includes("免费") || value.includes("赠送");
1453
- }
1454
- function firstDefined(mapping, ...keys) {
1455
- const last = keys[keys.length - 1];
1456
- let keyList = keys;
1457
- let fallback = undefined;
1458
- if (typeof last !== "string") {
1459
- fallback = last;
1460
- keyList = keys.slice(0, -1);
1461
- }
1462
- for (const key of keyList) {
1463
- if (mapping && typeof mapping === "object" && key in mapping && mapping[key] != null)
1464
- return mapping[key];
1465
- }
1466
- return fallback;
1467
- }
1468
1330
  function formatInventoryItem(row) {
1469
- let line = `- ${holdingName(row)} (x${formatNumber(rowQuantity(row))})`;
1470
- const expiresAt = row?.expireAt ?? row?.expiresAt;
1471
- if (expiresAt)
1472
- line += `\n 到期: ${formatDateTime(expiresAt)}`;
1331
+ let line = `- ${row.assetName || row.assetCode || "资产"} (x${formatNumber(row.quantity)})`;
1332
+ if (row.expiresAt)
1333
+ line += `\n 到期: ${formatDateTime(row.expiresAt)}`;
1473
1334
  return line;
1474
1335
  }
1475
1336
  function formatRedeemedItem(row) {
1476
- let name = holdingName(row);
1477
- const assetType = row?.assetType ?? row?.asset?.type;
1478
- const durationMs = row?.durationMs;
1479
- if (assetType === "PASS" && durationMs) {
1480
- const days = Math.floor(toNumber(durationMs) / (1000 * 60 * 60 * 24));
1481
- if (days > 0)
1482
- name += ` (${days}天)`;
1483
- }
1484
- return `- ${name} x${formatNumber(rowQuantity(row))}`;
1337
+ return `- ${row.assetName || row.assetCode || "资产"} x${formatNumber(row.quantity)}`;
1485
1338
  }
1486
- function formatWallet(result, currency) {
1487
- if (result && typeof result.total === "object") {
1488
- return formatLegacyWallet(result, currency);
1489
- }
1490
- const rows = extractRows(result?.wallet ?? result);
1491
- const paid = rows.filter(isPaidBalance).reduce((acc, row) => acc + rowQuantity(row), 0);
1492
- const free = rows.filter(isFreeBalance).reduce((acc, row) => acc + rowQuantity(row), 0);
1339
+ function formatWallet(rows, currency) {
1340
+ const paid = rows
1341
+ .filter((row) => String(row.assetCode).toLowerCase().includes("paid"))
1342
+ .reduce((sum, row) => sum + toNumber(row.quantity), 0);
1343
+ const free = rows
1344
+ .filter((row) => String(row.assetCode).toLowerCase().includes("free"))
1345
+ .reduce((sum, row) => sum + toNumber(row.quantity), 0);
1493
1346
  const other = rows
1494
- .filter((row) => !isPaidBalance(row) && !isFreeBalance(row))
1495
- .reduce((acc, row) => acc + rowQuantity(row), 0);
1347
+ .filter((row) => {
1348
+ const code = String(row.assetCode).toLowerCase();
1349
+ return !code.includes("paid") && !code.includes("free");
1350
+ })
1351
+ .reduce((sum, row) => sum + toNumber(row.quantity), 0);
1496
1352
  const total = paid + free + other;
1497
1353
  return [
1498
1354
  "💰 --- 钱包余额 ---",
@@ -1501,120 +1357,14 @@ function formatWallet(result, currency) {
1501
1357
  ` - 免费: ${formatNumber(free)}`,
1502
1358
  ].join("\n");
1503
1359
  }
1504
- function formatLegacyWallet(result, currency) {
1505
- const totalInfo = result?.total ?? {};
1506
- const paidInfo = result?.paid ?? {};
1507
- const freeInfo = result?.free ?? {};
1508
- const available = firstDefined(totalInfo, "available", 0);
1509
- const allBalance = firstDefined(totalInfo, "all", available);
1510
- const paid = firstDefined(paidInfo, "available", 0);
1511
- const free = firstDefined(freeInfo, "available", 0);
1512
- const lines = [
1513
- "💰 --- 钱包余额 ---",
1514
- `可用: ${formatNumber(available)} ${currency} (共 ${formatNumber(allBalance)})`,
1515
- ` - 付费: ${formatNumber(paid)}`,
1516
- ` - 免费: ${formatNumber(free)}`,
1517
- ];
1518
- const unavailable = toNumber(allBalance) - toNumber(available);
1519
- if (unavailable > 0) {
1520
- lines.push(`\n您还有 ${formatNumber(unavailable)} ${currency}未到可用时间。`);
1521
- }
1522
- const expiringFree = availableDetails(freeInfo).filter((item) => item.expireAt);
1523
- expiringFree.sort((a, b) => (parseDateTime(a.expireAt)?.getTime() ?? 0) - (parseDateTime(b.expireAt)?.getTime() ?? 0));
1524
- if (expiringFree.length > 0) {
1525
- const soonest = expiringFree[0];
1526
- lines.push(`\n注意:您有 ${formatNumber(soonest.count ?? 0)} 免费${currency}将于 ${formatDateTime(soonest.expireAt)} 过期。`);
1527
- }
1528
- const passes = availableDetails(result?.passes);
1529
- if (passes.length > 0) {
1530
- lines.push(`\n--- 可用月卡 (${passes.length}) ---`);
1531
- for (const item of passes) {
1532
- lines.push(`- ${assetName(item)}`);
1533
- lines.push(` 到期: ${formatDateTime(item?.expireAt ?? item?.expiresAt)}`);
1534
- }
1535
- }
1536
- const tickets = availableDetails(result?.tickets);
1537
- if (tickets.length > 0) {
1538
- lines.push(`\n--- 可用优惠券 (${tickets.length}) ---`);
1539
- for (const item of tickets) {
1540
- lines.push(`- ${assetName(item)} (x${formatNumber(item?.count ?? rowQuantity(item))})`);
1541
- lines.push(` 到期: ${formatDateTime(item?.expireAt ?? item?.expiresAt)}`);
1542
- }
1543
- }
1544
- return lines.join("\n");
1545
- }
1546
- function availableDetails(value) {
1547
- const details = value?.details ?? {};
1548
- const rows = details?.available ?? [];
1549
- return Array.isArray(rows) ? rows.filter((row) => row && typeof row === "object") : [];
1550
- }
1551
- function formatHistory(result, currency) {
1552
- const sessions = extractRows(result?.sessions ?? result);
1360
+ function formatHistory(sessions, currency) {
1553
1361
  if (sessions.length === 0)
1554
1362
  return "暂无历史记录";
1555
1363
  const lines = [`📜 最近 ${sessions.length} 条记录:`];
1556
1364
  for (const session of sessions) {
1557
- const sessionId = firstDefined(session, "id", "sessionId", "");
1558
- const start = formatDateTime(firstDefined(session, "createdAt", "startedAt", "startTime"));
1559
- const endRaw = firstDefined(session, "closedAt", "endedAt", "endTime");
1560
- const end = endRaw ? formatDateTime(endRaw) : "进行中";
1561
- const finalCost = firstDefined(session, "finalCost", "total");
1562
- const cost = finalCost == null ? "未结算" : `${formatNumber(finalCost)} ${currency}`;
1563
- lines.push(`- [${sessionId}] ${start} -> ${end} (${cost})`);
1564
- }
1565
- return lines.join("\n");
1566
- }
1567
- function formatLegacyBilling(result, currency) {
1568
- const billing = result?.billing ?? {};
1569
- const session = result?.session ?? {};
1570
- const discount = result?.discount;
1571
- const wallet = result?.wallet ?? {};
1572
- const lines = ["--- 账单详情 ---"];
1573
- const start = session.createdAt;
1574
- const end = billing.endTime;
1575
- lines.push(`入场: ${formatDateTime(start)}`);
1576
- lines.push(`结算: ${formatDateTime(end)}`);
1577
- lines.push(`时长: ${formatDurationMinutes(start, end)}`);
1578
- lines.push("---");
1579
- const originalCost = discount ? discount.originalCost : billing.totalCost ?? 0;
1580
- let finalCost = discount ? discount.finalCost : billing.totalCost ?? 0;
1581
- if (session.costOverwrite)
1582
- finalCost = session.costOverwrite;
1583
- lines.push(`计费价: ${formatNumber(originalCost)} ${currency}`);
1584
- if (discount) {
1585
- for (const log of discount.appliedLogs ?? []) {
1586
- lines.push(` -「${log?.asset ?? ""}」: -${formatNumber(log?.saved ?? 0)} ${currency}`);
1587
- }
1588
- }
1589
- lines.push(`结算价: ${formatNumber(finalCost)} ${currency}`);
1590
- const walletTotal = wallet?.total ?? {};
1591
- if (walletTotal.available != null) {
1592
- const currentBalance = walletTotal.available ?? 0;
1593
- lines.push("---");
1594
- lines.push(`当前余额: ${formatNumber(currentBalance)} ${currency}`);
1595
- lines.push(`扣款后: ${formatNumber(toNumber(currentBalance) - toNumber(finalCost))} ${currency}`);
1596
- }
1597
- lines.push("---");
1598
- lines.push("计费区间:");
1599
- const segments = billing.segments ?? [];
1600
- if (segments.length === 0) {
1601
- lines.push(" (无)");
1602
- }
1603
- for (const segment of segments) {
1604
- if (toNumber(segment?.cost ?? 0) < 0)
1605
- continue;
1606
- lines.push(`- ${segment?.ruleName ?? ""}`);
1607
- if (segment?.startTime && segment?.endTime) {
1608
- lines.push(` 时段: ${formatTimeRange(segment.startTime, segment.endTime)}`);
1609
- }
1610
- lines.push(` 时长: ${formatDurationValue(segment?.durationMinutes ?? 0)}`);
1611
- const capped = segment?.isCapped ? " (已封顶)" : "";
1612
- lines.push(` 费用: ${formatNumber(segment?.cost ?? 0)} ${currency}${capped}`.trim());
1613
- }
1614
- const monthlyPass = (wallet?.passes?.details?.available ?? [null])[0];
1615
- if (monthlyPass && monthlyPass?.expireAt) {
1616
- lines.push("---");
1617
- lines.push(`您的月卡将于 ${formatDateTime(monthlyPass.expireAt)} 到期。`);
1365
+ const end = session.endedAt ? formatDateTime(session.endedAt) : "进行中";
1366
+ const cost = session.total == null ? "未结算" : `${formatNumber(session.total)} ${currency}`;
1367
+ lines.push(`- [${session.sessionId}] ${formatDateTime(session.startedAt)} -> ${end} (${cost})`);
1618
1368
  }
1619
1369
  return lines.join("\n");
1620
1370
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koishi-plugin-prism",
3
- "version": "0.1.33",
3
+ "version": "0.1.34",
4
4
  "description": "PRiSM Next 计费与设备管理系统的 Koishi 机器人集成插件",
5
5
  "main": "./lib/index.js",
6
6
  "exports": {
@@ -45,7 +45,8 @@
45
45
  "scripts": {
46
46
  "build": "tsc",
47
47
  "prepare": "tsc",
48
+ "prepublishOnly": "bun run typecheck && bun test && bun run build",
48
49
  "test": "bun test test",
49
50
  "typecheck": "tsc -p tsconfig.json"
50
51
  }
51
- }
52
+ }