-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathofflineOrderFallback.js
More file actions
421 lines (375 loc) · 18 KB
/
Copy pathofflineOrderFallback.js
File metadata and controls
421 lines (375 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// ============================================================
// OFFLINE ORDER FALLBACK WRAPPER - Sprint 6 disabled/dry-run layer
// XE KHÔ POS
//
// Purpose:
// Build and verify POS order fallback action payloads before enabling any
// live fallback. By default this module auto-installs in disabled mode only:
// it does NOT wrap DB.Orders, does NOT write Firestore, and does NOT enqueue
// live POS actions unless explicitly installed with mode='enabled'.
// ============================================================
(function initOfflineOrderFallback(globalScope) {
'use strict';
const VERSION = 'sprint-6-disabled-dry-run';
const VALID_MODES = new Set(['disabled', 'dry-run', 'enabled']);
const WRAPPED_FLAG = '__xekhoOfflineOrderFallbackWrapped';
const ORIGINALS_KEY = '__xekhoOfflineOrderFallbackOriginals';
const DEVICE_ID_STORAGE_KEY = 'xekho_pos_device_id';
let memoryDeviceId = '';
function nowIso() {
return new Date().toISOString();
}
function defaultLogger() {
const consoleRef = globalScope.console || {};
return {
info: typeof consoleRef.info === 'function' ? consoleRef.info.bind(consoleRef) : function noop() {},
warn: typeof consoleRef.warn === 'function' ? consoleRef.warn.bind(consoleRef) : function noop() {},
error: typeof consoleRef.error === 'function' ? consoleRef.error.bind(consoleRef) : function noop() {},
};
}
function isPlainObject(value) {
return !!value && typeof value === 'object' && !Array.isArray(value);
}
function cloneJson(value) {
if (value === undefined) return undefined;
return JSON.parse(JSON.stringify(value));
}
function cleanText(value, fallback = '') {
const text = String(value == null ? fallback : value).trim();
return text || fallback;
}
function cleanMode(mode) {
const next = String(mode || 'disabled').trim().toLowerCase();
return VALID_MODES.has(next) ? next : 'disabled';
}
function getRuntime(options = {}) {
return options.runtime || globalScope.XekhoOfflineBackupRuntime || null;
}
function getBackupLib(options = {}) {
return options.backupLib || globalScope.XekhoOfflineBackup || null;
}
function makeClientOrderId(options = {}) {
const backupLib = getBackupLib(options);
if (backupLib && typeof backupLib.makeClientOrderId === 'function') {
return backupLib.makeClientOrderId('offline_order');
}
return `offline_order_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
}
function randomToken() {
if (globalScope.crypto && typeof globalScope.crypto.getRandomValues === 'function') {
const bytes = new Uint8Array(8);
globalScope.crypto.getRandomValues(bytes);
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}
return Math.random().toString(36).slice(2, 10);
}
function makeDeviceId() {
return `device_${Date.now()}_${randomToken()}`;
}
function getDeviceId(options = {}) {
const explicit = cleanText(options.deviceId || globalScope.XEKHO_DEVICE_ID || '', '');
if (explicit) return explicit;
const storageKey = cleanText(options.deviceIdStorageKey || DEVICE_ID_STORAGE_KEY, DEVICE_ID_STORAGE_KEY);
try {
const storage = globalScope.localStorage;
if (storage && typeof storage.getItem === 'function' && typeof storage.setItem === 'function') {
const existing = cleanText(storage.getItem(storageKey) || '', '');
if (existing) return existing;
const next = makeDeviceId();
storage.setItem(storageKey, next);
return next;
}
} catch (_) {}
if (!memoryDeviceId) memoryDeviceId = makeDeviceId();
return memoryDeviceId;
}
function shouldFallback(error, options = {}) {
const backupLib = getBackupLib(options);
if (backupLib && typeof backupLib.isOfflineOrServerError === 'function') {
return backupLib.isOfflineOrServerError(error);
}
if (typeof navigator !== 'undefined' && navigator && navigator.onLine === false) return true;
const text = String((error && (error.message || error.code || error.name)) || error || '').toLowerCase();
return text.includes('offline') || text.includes('network') || text.includes('unavailable') || text.includes('timeout') || text.includes('failed to fetch') || text.includes('503') || text.includes('504');
}
function basePayload(type, input = {}, options = {}) {
const createdAt = input.createdAt || nowIso();
const clientOrderId = cleanText(input.clientOrderId || input.orderId || '', '') || makeClientOrderId(options);
return {
clientOrderId,
source: 'pos_offline_fallback',
fallbackVersion: VERSION,
method: cleanText(input.method || type, type),
deviceId: getDeviceId(options),
offlineCreatedAt: createdAt,
createdAtLocal: createdAt,
};
}
function normalizeItem(item) {
const clean = isPlainObject(item) ? cloneJson(item) : {};
if (clean.qty != null) clean.qty = Number(clean.qty || 0) || 1;
if (clean.price != null) clean.price = Number(clean.price || 0);
if (clean.cost != null) clean.cost = Number(clean.cost || 0);
return clean;
}
function buildOpenOrderAction(input = {}, options = {}) {
const tableId = cleanText(input.tableId || input.table || '', '');
const tableName = cleanText(input.tableName || (tableId ? `Ban ${tableId}` : ''), '');
const payload = {
...basePayload('open_order', { ...input, method: 'Orders.open' }, options),
tableId,
tableName,
staffUid: input.staffUid || null,
createdBy: isPlainObject(input.createdBy) ? cloneJson(input.createdBy) : (input.createdBy || null),
};
return { type: 'open_order', clientOrderId: payload.clientOrderId, payload };
}
function buildAddItemAction(input = {}, options = {}) {
const orderId = cleanText(input.orderId || '', '');
const payload = {
...basePayload('add_item', { ...input, method: 'Orders.addItem' }, options),
orderId,
tableId: cleanText(input.tableId || '', ''),
item: normalizeItem(input.item),
};
return { type: 'add_item', clientOrderId: payload.clientOrderId, payload };
}
function buildChangeQtyAction(input = {}, options = {}) {
const payload = {
...basePayload('change_qty', { ...input, method: 'Orders.changeQty' }, options),
orderId: cleanText(input.orderId || '', ''),
tableId: cleanText(input.tableId || '', ''),
itemId: cleanText(input.itemId || '', ''),
itemNote: input.itemNote || '',
delta: Number(input.delta || 0),
lineItemId: cleanText(input.lineItemId || '', ''),
};
return { type: 'change_qty', clientOrderId: payload.clientOrderId, payload };
}
function buildRemoveItemAction(input = {}, options = {}) {
const payload = {
...basePayload('remove_item', { ...input, method: 'Orders.removeItem' }, options),
orderId: cleanText(input.orderId || '', ''),
tableId: cleanText(input.tableId || '', ''),
itemId: cleanText(input.itemId || '', ''),
itemNote: input.itemNote || '',
lineItemId: cleanText(input.lineItemId || '', ''),
removeMode: 'line_item',
};
return { type: 'remove_item', clientOrderId: payload.clientOrderId, payload };
}
function buildUpdateItemAction(input = {}, options = {}) {
const payload = {
...basePayload('update_item', { ...input, method: 'Orders.updateItemNote' }, options),
orderId: cleanText(input.orderId || '', ''),
tableId: cleanText(input.tableId || '', ''),
itemId: cleanText(input.itemId || '', ''),
note: input.note || input.itemNote || '',
lineItemId: cleanText(input.lineItemId || '', ''),
};
return { type: 'update_item', clientOrderId: payload.clientOrderId, payload };
}
function buildUpdateMetaAction(input = {}, options = {}) {
const meta = isPlainObject(input.meta) ? cloneJson(input.meta) : {};
const payload = {
...basePayload('update_meta', { ...input, method: 'Orders.updateMeta' }, options),
orderId: cleanText(input.orderId || '', ''),
tableId: cleanText(input.tableId || meta.tableId || '', ''),
meta,
};
return { type: 'update_meta', clientOrderId: payload.clientOrderId, payload };
}
function buildCloseOrderAction(input = {}, options = {}) {
const payInfo = isPlainObject(input.payInfo) ? cloneJson(input.payInfo) : {};
const rawItems = Array.isArray(input.items) ? input.items : (Array.isArray(payInfo.items) ? payInfo.items : []);
const items = rawItems.map(normalizeItem);
const paidAtLocal = input.paidAtLocal || nowIso();
const payload = {
...basePayload('close_order', { ...input, method: 'Orders.close', createdAt: paidAtLocal }, options),
orderId: cleanText(input.orderId || '', ''),
tableId: cleanText(input.tableId || payInfo.tableId || '', ''),
tableName: cleanText(input.tableName || payInfo.tableName || '', ''),
items,
total: Number(input.total != null ? input.total : payInfo.total || 0),
cost: Number(input.cost != null ? input.cost : payInfo.cost || 0),
payMethod: input.payMethod || payInfo.payMethod || payInfo.paymentMethod || 'cash',
discount: Number(input.discount != null ? input.discount : payInfo.discount || 0),
discountNote: input.discountNote || payInfo.discountNote || '',
discountType: input.discountType || payInfo.discountType || 'vnd',
shipping: Number(input.shipping != null ? input.shipping : payInfo.shipping || 0),
vatAmount: Number(input.vatAmount != null ? input.vatAmount : payInfo.vatAmount || 0),
taxRate: Number(input.taxRate != null ? input.taxRate : payInfo.taxRate || 0),
billNo: input.billNo || payInfo.billNo || '',
historyId: input.historyId || payInfo.historyId || '',
paidAtLocal,
};
return { type: 'close_order', clientOrderId: payload.clientOrderId, payload };
}
function buildCancelOrderAction(input = {}, options = {}) {
const cancelledAtLocal = input.cancelledAtLocal || nowIso();
const payload = {
...basePayload('cancel_order', { ...input, method: 'Orders.cancel', createdAt: cancelledAtLocal }, options),
orderId: cleanText(input.orderId || '', ''),
tableId: cleanText(input.tableId || '', ''),
cancelReason: cleanText(input.cancelReason || '', 'Hủy đơn hàng offline'),
cancelledAtLocal,
};
return { type: 'cancel_order', clientOrderId: payload.clientOrderId, payload };
}
function actionFromMethod(methodName, args, options = {}) {
const list = Array.from(args || []);
const tableIdResolver = typeof options.tableIdResolver === 'function' ? options.tableIdResolver : null;
const tableIdFromOrder = orderId => tableIdResolver ? tableIdResolver(orderId) : '';
switch (methodName) {
case 'open':
return buildOpenOrderAction({ tableId: list[0], tableName: list[1], staffUid: list[2], createdBy: list[3] }, options);
case 'addItem':
return buildAddItemAction({ orderId: list[0], tableId: tableIdFromOrder(list[0]), item: list[1] }, options);
case 'changeQty':
return buildChangeQtyAction({ orderId: list[0], tableId: tableIdFromOrder(list[0]), itemId: list[1], itemNote: list[2], delta: list[3], lineItemId: list[4] }, options);
case 'removeItem':
return buildRemoveItemAction({ orderId: list[0], tableId: tableIdFromOrder(list[0]), itemId: list[1], itemNote: list[2], lineItemId: list[3] }, options);
case 'updateItemNote':
return buildUpdateItemAction({ orderId: list[0], tableId: tableIdFromOrder(list[0]), itemId: list[1], note: list[2], lineItemId: list[3] }, options);
case 'updateMeta':
return buildUpdateMetaAction({ orderId: list[0], tableId: tableIdFromOrder(list[0]), meta: list[1] }, options);
case 'close':
return buildCloseOrderAction({ orderId: list[0], tableId: tableIdFromOrder(list[0]), payInfo: list[1] }, options);
case 'cancel':
return buildCancelOrderAction({ orderId: list[0], tableId: tableIdFromOrder(list[0]), cancelReason: list[1] }, options);
default:
throw new Error(`[OfflineOrderFallback] unsupported Orders method: ${methodName}`);
}
}
async function enqueueAction(action, options = {}) {
const runtime = getRuntime(options);
if (!runtime || typeof runtime.savePendingOrderAction !== 'function') {
throw new Error('[OfflineOrderFallback] offline runtime is not available');
}
return runtime.savePendingOrderAction(action);
}
function createOfflineOrderFallback(options = {}) {
const logger = options.logger || defaultLogger();
let mode = cleanMode(options.mode);
const dryRunActions = [];
async function handleFailedOrderMethod(methodName, args, error) {
const action = actionFromMethod(methodName, args, options);
action.payload.fallbackReason = String((error && (error.message || error.code || error.name)) || error || 'unknown');
if (mode === 'dry-run') {
dryRunActions.push(cloneJson(action));
logger.warn('[OfflineOrderFallback] dry-run captured action', action.type, action.payload.orderId || action.payload.tableId || action.clientOrderId);
return { dryRun: true, action };
}
if (mode === 'enabled') {
const saved = await enqueueAction(action, options);
logger.warn('[OfflineOrderFallback] saved offline action', saved.type, saved.id);
return { saved: true, action: saved };
}
return { skipped: true, reason: 'disabled', action };
}
function wrapOrders(orders) {
if (!orders || typeof orders !== 'object') return { wrapped: false, reason: 'orders-unavailable' };
if (orders[WRAPPED_FLAG]) return { wrapped: false, reason: 'already-wrapped' };
const methodNames = ['open', 'addItem', 'changeQty', 'removeItem', 'updateItemNote', 'updateMeta', 'close', 'cancel'];
const originals = {};
methodNames.forEach(methodName => {
if (typeof orders[methodName] !== 'function') return;
originals[methodName] = orders[methodName];
orders[methodName] = async function wrappedOrderMethod(...args) {
try {
return await originals[methodName].apply(this, args);
} catch (error) {
if (!shouldFallback(error, options)) throw error;
const result = await handleFailedOrderMethod(methodName, args, error);
if (mode === 'enabled' && methodName === 'open') {
return result.action && result.action.clientOrderId;
}
throw error;
}
};
});
Object.defineProperty(orders, WRAPPED_FLAG, { value: true, enumerable: false, configurable: true });
Object.defineProperty(orders, ORIGINALS_KEY, { value: originals, enumerable: false, configurable: true });
return { wrapped: Object.keys(originals).length > 0, methods: Object.keys(originals) };
}
function unwrapOrders(orders) {
if (!orders || !orders[WRAPPED_FLAG] || !orders[ORIGINALS_KEY]) return { unwrapped: false };
Object.keys(orders[ORIGINALS_KEY]).forEach(methodName => {
orders[methodName] = orders[ORIGINALS_KEY][methodName];
});
delete orders[WRAPPED_FLAG];
delete orders[ORIGINALS_KEY];
return { unwrapped: true };
}
function install(targetDb = options.db || globalScope.DB || null) {
if (mode === 'disabled') {
return { installed: true, wrapped: false, mode, reason: 'disabled-safe-default' };
}
const orders = targetDb && targetDb.Orders;
return { installed: true, mode, ...wrapOrders(orders) };
}
return {
version: VERSION,
get mode() { return mode; },
setMode(nextMode) { mode = cleanMode(nextMode); return mode; },
install,
unwrapOrders,
handleFailedOrderMethod,
actionFromMethod: (methodName, args) => actionFromMethod(methodName, args, options),
buildOpenOrderAction: input => buildOpenOrderAction(input, options),
buildAddItemAction: input => buildAddItemAction(input, options),
buildChangeQtyAction: input => buildChangeQtyAction(input, options),
buildRemoveItemAction: input => buildRemoveItemAction(input, options),
buildUpdateItemAction: input => buildUpdateItemAction(input, options),
buildUpdateMetaAction: input => buildUpdateMetaAction(input, options),
buildCloseOrderAction: input => buildCloseOrderAction(input, options),
buildCancelOrderAction: input => buildCancelOrderAction(input, options),
getDryRunActions: () => dryRunActions.map(cloneJson),
clearDryRunActions: () => { dryRunActions.length = 0; },
};
}
function installOfflineOrderFallback(options = {}) {
const target = options.target || globalScope;
if (target.XekhoOfflineOrderFallbackController && options.force !== true) {
return target.XekhoOfflineOrderFallbackController;
}
const controller = createOfflineOrderFallback({ mode: 'disabled', ...options });
controller.install(options.db || target.DB || null);
target.XekhoOfflineOrderFallbackController = controller;
return controller;
}
function autoInstall() {
try {
if (globalScope.__XEKHO_OFFLINE_ORDER_FALLBACK_NO_AUTO_INSTALL__) return;
const controller = installOfflineOrderFallback({ mode: 'disabled' });
defaultLogger().info('[OfflineOrderFallback] Ready', { version: VERSION, mode: controller.mode });
} catch (error) {
defaultLogger().warn('[OfflineOrderFallback] Auto install failed', error && error.message ? error.message : error);
}
}
const api = {
version: VERSION,
createOfflineOrderFallback,
installOfflineOrderFallback,
shouldFallback,
buildOpenOrderAction,
buildAddItemAction,
buildChangeQtyAction,
buildRemoveItemAction,
buildUpdateItemAction,
buildUpdateMetaAction,
buildCloseOrderAction,
buildCancelOrderAction,
};
globalScope.XekhoOfflineOrderFallback = api;
if (typeof module !== 'undefined' && module.exports) {
module.exports = api;
}
if (typeof document !== 'undefined') {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', autoInstall, { once: true });
} else {
autoInstall();
}
}
})(typeof globalThis !== 'undefined' ? globalThis : window);