@pisell/pisellos 0.0.194 → 0.0.196

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.
@@ -292,6 +292,8 @@ export interface PaymentModuleAPI {
292
292
  getPartiallyPaidOrdersAsync: () => Promise<PaymentOrder[]>;
293
293
  /** 获取未同步到服务器的订单 */
294
294
  getUnsyncedOrdersAsync: () => Promise<PaymentOrder[]>;
295
+ /** 检测未同步的订单并重新加入任务队列 */
296
+ recheckAndRequeueUnsyncedOrders: () => Promise<number>;
295
297
  /** 手动执行支付同步队列 */
296
298
  runPaymentSyncQueue: () => Promise<void>;
297
299
  }
@@ -2,6 +2,13 @@ import { Module, PisellCore, ModuleOptions } from '../../types';
2
2
  import { BaseModule } from '../BaseModule';
3
3
  import { PaymentModuleAPI, PaymentMethod, PaymentOrder, PaymentItem, PaymentItemInput, PaymentUpdateFields, PushOrderParams, CashPayment, EftposPayment, WalletPayment } from './types';
4
4
  export * from './types';
5
+ export { generateRequestUniqueId };
6
+ /**
7
+ * 生成请求唯一ID
8
+ * 格式: 年月日时分秒毫秒+4位随机数
9
+ * 示例: 20241201143025123456
10
+ */
11
+ declare function generateRequestUniqueId(): string;
5
12
  /**
6
13
  * 支付模块实现
7
14
  *
@@ -174,9 +181,47 @@ export declare class PaymentModule extends BaseModule implements Module, Payment
174
181
  * 注意:只清理完全支付的订单,部分支付的订单保留以便继续支付
175
182
  */
176
183
  cleanupFinishedOrders(): Promise<void>;
184
+ /**
185
+ * 检测未同步的订单并重新加入任务队列
186
+ *
187
+ * 此方法专门用于处理因网络问题导致任务队列执行失败但队列被清空的情况。
188
+ * 它会检查本地 IndexDB 中所有未同步的订单(isSynced: false),
189
+ * 并将这些订单重新添加到任务队列中。
190
+ *
191
+ * 使用场景:
192
+ * - 网络恢复后重新检查未同步的订单
193
+ * - 应用启动时检查并重新排队未完成的支付
194
+ * - 用户手动重试前的预检查
195
+ *
196
+ * @returns Promise<number> 返回重新加入队列的订单数量
197
+ */
198
+ recheckAndRequeueUnsyncedOrders(): Promise<number>;
177
199
  /**
178
200
  * 手动执行支付同步队列
179
201
  * 外部可以调用此方法来触发支付同步任务的执行
202
+ *
203
+ * 注意:此方法只执行现有队列中的任务,不会检查未同步的订单。
204
+ * 如果需要检查未同步订单,请先调用 recheckAndRequeueUnsyncedOrders()
205
+ *
206
+ * 使用示例:
207
+ * ```typescript
208
+ * // 1. 先检查并重新排队未同步订单,然后执行队列
209
+ * const requeuedCount = await paymentModule.recheckAndRequeueUnsyncedOrders();
210
+ * if (requeuedCount > 0) {
211
+ * await paymentModule.runPaymentSyncQueue();
212
+ * }
213
+ *
214
+ * // 2. 或者直接执行现有队列(不检查未同步订单)
215
+ * await paymentModule.runPaymentSyncQueue();
216
+ * ```
180
217
  */
181
218
  runPaymentSyncQueue(): Promise<void>;
219
+ /**
220
+ * 重新将订单添加到同步队列
221
+ * 用于处理因网络问题导致任务队列清空但订单未同步的情况
222
+ *
223
+ * @param order 要重新添加的订单
224
+ * @returns Promise<boolean> 是否成功添加到队列
225
+ */
226
+ private reAddOrderToSyncQueue;
182
227
  }
@@ -20,7 +20,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/modules/Payment/index.ts
21
21
  var Payment_exports = {};
22
22
  __export(Payment_exports, {
23
- PaymentModule: () => PaymentModule
23
+ PaymentModule: () => PaymentModule,
24
+ generateRequestUniqueId: () => generateRequestUniqueId
24
25
  });
25
26
  module.exports = __toCommonJS(Payment_exports);
26
27
  var import_BaseModule = require("../BaseModule");
@@ -40,6 +41,18 @@ function formatAmount(amount) {
40
41
  return "0.00";
41
42
  }
42
43
  }
44
+ function generateRequestUniqueId() {
45
+ const now = /* @__PURE__ */ new Date();
46
+ const year = now.getFullYear();
47
+ const month = String(now.getMonth() + 1).padStart(2, "0");
48
+ const day = String(now.getDate()).padStart(2, "0");
49
+ const hour = String(now.getHours()).padStart(2, "0");
50
+ const minute = String(now.getMinutes()).padStart(2, "0");
51
+ const second = String(now.getSeconds()).padStart(2, "0");
52
+ const millisecond = String(now.getMilliseconds()).padStart(3, "0");
53
+ const randomDigits = Math.floor(Math.random() * 9e3) + 1e3;
54
+ return `${year}${month}${day}${hour}${minute}${second}${millisecond}${randomDigits}`;
55
+ }
43
56
  var PaymentModule = class extends import_BaseModule.BaseModule {
44
57
  constructor(name, version) {
45
58
  super(name, version);
@@ -130,9 +143,9 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
130
143
  *
131
144
  */
132
145
  registerNetworkHandlers() {
133
- const network = this.app.usePlugin("network");
146
+ const network = this.app.plugins.get("network");
134
147
  this.logInfo("Registering network status listener");
135
- network == null ? void 0 : network.addListener("networkStatusChange", (status) => {
148
+ network == null ? void 0 : network.addListener("networkStatusChange", async (status) => {
136
149
  console.log("网络状态:", status.connected);
137
150
  this.logInfo("Network status changed", {
138
151
  connected: status.connected,
@@ -140,7 +153,10 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
140
153
  });
141
154
  if (status.connected) {
142
155
  this.logInfo("Network reconnected - triggering payment sync queue");
143
- this.runPaymentSyncQueue();
156
+ const requeuedCount = await this.recheckAndRequeueUnsyncedOrders();
157
+ if (requeuedCount > 0) {
158
+ await this.runPaymentSyncQueue();
159
+ }
144
160
  }
145
161
  });
146
162
  }
@@ -738,13 +754,18 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
738
754
  var _a, _b, _c, _d, _e, _f;
739
755
  const { orderUuid, orderId, paymentData, core } = payload.task.payload;
740
756
  console.log(`[PaymentModule] 开始后台同步支付,订单ID: ${orderId}`);
757
+ paymentData.request_unique = generateRequestUniqueId();
741
758
  const app = window.app;
742
759
  const logger = app == null ? void 0 : app.logger;
743
760
  if (logger) {
744
761
  logger.addLog({
745
762
  type: "info",
746
763
  title: "[PaymentModule] Starting syncPaymentTask",
747
- metadata: { orderUuid, orderId, paymentDataKeys: Object.keys(paymentData) }
764
+ metadata: {
765
+ orderUuid,
766
+ orderId,
767
+ paymentDataKeys: Object.keys(paymentData)
768
+ }
748
769
  });
749
770
  }
750
771
  if (!app) {
@@ -878,7 +899,9 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
878
899
  payment.isSynced = true;
879
900
  });
880
901
  await dbManager.update("order", order);
881
- console.log(`[PaymentModule] 订单 ${orderUuid} 业务错误,已标记为已同步`);
902
+ console.log(
903
+ `[PaymentModule] 订单 ${orderUuid} 业务错误,已标记为已同步`
904
+ );
882
905
  }
883
906
  return {
884
907
  status: "completed_with_error",
@@ -959,9 +982,84 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
959
982
  console.error("[PaymentModule] 清理已完成订单失败", error);
960
983
  }
961
984
  }
985
+ /**
986
+ * 检测未同步的订单并重新加入任务队列
987
+ *
988
+ * 此方法专门用于处理因网络问题导致任务队列执行失败但队列被清空的情况。
989
+ * 它会检查本地 IndexDB 中所有未同步的订单(isSynced: false),
990
+ * 并将这些订单重新添加到任务队列中。
991
+ *
992
+ * 使用场景:
993
+ * - 网络恢复后重新检查未同步的订单
994
+ * - 应用启动时检查并重新排队未完成的支付
995
+ * - 用户手动重试前的预检查
996
+ *
997
+ * @returns Promise<number> 返回重新加入队列的订单数量
998
+ */
999
+ async recheckAndRequeueUnsyncedOrders() {
1000
+ this.logInfo("Starting recheckAndRequeueUnsyncedOrders");
1001
+ try {
1002
+ if (!this.app.tasksManager) {
1003
+ console.warn(
1004
+ "[PaymentModule] TasksManager 未初始化,无法重新排队未同步订单"
1005
+ );
1006
+ this.logWarning(
1007
+ "TasksManager not initialized, cannot requeue unsynced orders"
1008
+ );
1009
+ return 0;
1010
+ }
1011
+ const unsyncedOrders = await this.getUnsyncedOrdersAsync();
1012
+ if (unsyncedOrders.length === 0) {
1013
+ console.log("[PaymentModule] 没有发现未同步的订单");
1014
+ this.logInfo("No unsynced orders found");
1015
+ return 0;
1016
+ }
1017
+ console.log(
1018
+ `[PaymentModule] 发现 ${unsyncedOrders.length} 个未同步的订单,开始重新加入任务队列`
1019
+ );
1020
+ this.logInfo("Found unsynced orders, adding to sync queue", {
1021
+ unsyncedCount: unsyncedOrders.length,
1022
+ orderUuids: unsyncedOrders.map((o) => o.uuid)
1023
+ });
1024
+ let requeuedCount = 0;
1025
+ for (const order of unsyncedOrders) {
1026
+ const success = await this.reAddOrderToSyncQueue(order);
1027
+ if (success) {
1028
+ requeuedCount++;
1029
+ }
1030
+ }
1031
+ console.log(
1032
+ `[PaymentModule] 成功重新加入 ${requeuedCount} 个订单到任务队列`
1033
+ );
1034
+ this.logInfo("Successfully requeued unsynced orders", {
1035
+ requeuedCount,
1036
+ totalFound: unsyncedOrders.length
1037
+ });
1038
+ return requeuedCount;
1039
+ } catch (error) {
1040
+ console.error("[PaymentModule] 重新排队未同步订单失败", error);
1041
+ this.logError("recheckAndRequeueUnsyncedOrders failed", error);
1042
+ return 0;
1043
+ }
1044
+ }
962
1045
  /**
963
1046
  * 手动执行支付同步队列
964
1047
  * 外部可以调用此方法来触发支付同步任务的执行
1048
+ *
1049
+ * 注意:此方法只执行现有队列中的任务,不会检查未同步的订单。
1050
+ * 如果需要检查未同步订单,请先调用 recheckAndRequeueUnsyncedOrders()
1051
+ *
1052
+ * 使用示例:
1053
+ * ```typescript
1054
+ * // 1. 先检查并重新排队未同步订单,然后执行队列
1055
+ * const requeuedCount = await paymentModule.recheckAndRequeueUnsyncedOrders();
1056
+ * if (requeuedCount > 0) {
1057
+ * await paymentModule.runPaymentSyncQueue();
1058
+ * }
1059
+ *
1060
+ * // 2. 或者直接执行现有队列(不检查未同步订单)
1061
+ * await paymentModule.runPaymentSyncQueue();
1062
+ * ```
965
1063
  */
966
1064
  async runPaymentSyncQueue() {
967
1065
  this.logInfo("Starting runPaymentSyncQueue");
@@ -971,6 +1069,14 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
971
1069
  this.logWarning("TasksManager not initialized, cannot run sync queue");
972
1070
  return;
973
1071
  }
1072
+ const queue = this.app.tasksManager.getTaskQueue({
1073
+ module: "payment",
1074
+ queueId: "payment_sync"
1075
+ });
1076
+ if (!(queue == null ? void 0 : queue.length)) {
1077
+ console.log("[PaymentModule] 支付同步队列无内容,不执行");
1078
+ return;
1079
+ }
974
1080
  console.log("[PaymentModule] 开始执行支付同步队列");
975
1081
  await this.app.tasksManager.run({
976
1082
  module: "payment",
@@ -992,9 +1098,56 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
992
1098
  this.logError("runPaymentSyncQueue failed", error);
993
1099
  }
994
1100
  }
1101
+ /**
1102
+ * 重新将订单添加到同步队列
1103
+ * 用于处理因网络问题导致任务队列清空但订单未同步的情况
1104
+ *
1105
+ * @param order 要重新添加的订单
1106
+ * @returns Promise<boolean> 是否成功添加到队列
1107
+ */
1108
+ async reAddOrderToSyncQueue(order) {
1109
+ try {
1110
+ const paymentData = {
1111
+ payments: order.payment.map((payment) => payment),
1112
+ payment_status: order.payment_status === import_types.PaymentStatus.Finished ? "paid" : "partially_paid"
1113
+ };
1114
+ const existingQueue = this.app.tasksManager.getTaskQueue({
1115
+ module: "payment",
1116
+ queueId: "payment_sync"
1117
+ });
1118
+ const taskId = `payment_${order.uuid}`;
1119
+ const taskExists = existingQueue == null ? void 0 : existingQueue.some((task) => task.id === taskId);
1120
+ if (taskExists) {
1121
+ console.log(
1122
+ `[PaymentModule] 任务 ${taskId} 已存在于队列中,跳过重复添加`
1123
+ );
1124
+ return false;
1125
+ }
1126
+ await this.addToSyncQueue(order, paymentData);
1127
+ console.log(`[PaymentModule] 订单 ${order.uuid} 已重新添加到同步队列`);
1128
+ this.logInfo("Order re-added to sync queue", {
1129
+ orderUuid: order.uuid,
1130
+ orderId: order.order_info.order_id,
1131
+ paymentStatus: order.payment_status,
1132
+ unsyncedPayments: order.payment.filter((p) => !p.isSynced).length
1133
+ });
1134
+ return true;
1135
+ } catch (error) {
1136
+ console.error(
1137
+ `[PaymentModule] 重新添加订单 ${order.uuid} 到同步队列失败`,
1138
+ error
1139
+ );
1140
+ this.logError("Failed to re-add order to sync queue", error, {
1141
+ orderUuid: order.uuid,
1142
+ orderId: order.order_info.order_id
1143
+ });
1144
+ return false;
1145
+ }
1146
+ }
995
1147
  };
996
1148
  // Annotate the CommonJS export names for ESM import in node:
997
1149
  0 && (module.exports = {
998
1150
  PaymentModule,
1151
+ generateRequestUniqueId,
999
1152
  ...require("./types")
1000
1153
  });
@@ -292,6 +292,8 @@ export interface PaymentModuleAPI {
292
292
  getPartiallyPaidOrdersAsync: () => Promise<PaymentOrder[]>;
293
293
  /** 获取未同步到服务器的订单 */
294
294
  getUnsyncedOrdersAsync: () => Promise<PaymentOrder[]>;
295
+ /** 检测未同步的订单并重新加入任务队列 */
296
+ recheckAndRequeueUnsyncedOrders: () => Promise<number>;
295
297
  /** 手动执行支付同步队列 */
296
298
  runPaymentSyncQueue: () => Promise<void>;
297
299
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@pisell/pisellos",
4
- "version": "0.0.194",
4
+ "version": "0.0.196",
5
5
  "description": "一个可扩展的前端模块化SDK框架,支持插件系统",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",