ts-glitter 20.5.7 → 20.5.9

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.
Files changed (33) hide show
  1. package/lowcode/Entry.js +1 -1
  2. package/lowcode/Entry.ts +1 -1
  3. package/lowcode/cms-plugin/shopping-setting-basic.js +1 -1
  4. package/lowcode/cms-plugin/shopping-setting-basic.ts +1 -1
  5. package/lowcode/public-components/checkout/index.js +1 -0
  6. package/lowcode/public-components/checkout/index.ts +1 -0
  7. package/lowcode/public-components/user-manager/um-login.js +6 -1
  8. package/lowcode/public-components/user-manager/um-login.ts +7 -1
  9. package/package.json +1 -1
  10. package/src/api-public/controllers/shop.js +6 -5
  11. package/src/api-public/controllers/shop.js.map +1 -1
  12. package/src/api-public/controllers/shop.ts +6 -5
  13. package/src/api-public/models/glitter-finance.d.ts +1 -1
  14. package/src/api-public/models/glitter-finance.js +14 -11
  15. package/src/api-public/models/glitter-finance.js.map +1 -1
  16. package/src/api-public/models/glitter-finance.ts +12 -10
  17. package/src/api-public/services/checkout-event.d.ts +92 -0
  18. package/src/api-public/services/checkout-event.js +1103 -0
  19. package/src/api-public/services/checkout-event.js.map +1 -0
  20. package/src/api-public/services/checkout-event.ts +1460 -0
  21. package/src/api-public/services/checkout-service.d.ts +83 -0
  22. package/src/api-public/services/checkout-service.js +1074 -0
  23. package/src/api-public/services/checkout-service.js.map +1 -0
  24. package/src/api-public/services/data-analyze.d.ts +1 -1
  25. package/src/api-public/services/shopping.d.ts +1 -71
  26. package/src/api-public/services/shopping.js +3 -1044
  27. package/src/api-public/services/shopping.js.map +1 -1
  28. package/src/api-public/services/shopping.ts +3 -1391
  29. package/src/api-public/services/updated-table-checked.js +2 -2
  30. package/src/api-public/services/updated-table-checked.js.map +1 -1
  31. package/src/services/private_config.js +1 -1
  32. package/src/services/private_config.js.map +1 -1
  33. package/src/services/private_config.ts +1 -1
@@ -0,0 +1,1103 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.CheckoutEvent = void 0;
30
+ const ut_timer_js_1 = require("../utils/ut-timer.js");
31
+ const user_js_1 = require("./user.js");
32
+ const rebate_js_1 = require("./rebate.js");
33
+ const database_js_1 = __importDefault(require("../../modules/database.js"));
34
+ const exception_js_1 = __importDefault(require("../../modules/exception.js"));
35
+ const private_config_js_1 = require("../../services/private_config.js");
36
+ const shipment_config_js_1 = require("../config/shipment-config.js");
37
+ const stock_js_1 = require("./stock.js");
38
+ const shopee_js_1 = require("./shopee.js");
39
+ const recommend_js_1 = require("./recommend.js");
40
+ const glitter_finance_js_1 = require("../models/glitter-finance.js");
41
+ const tool_js_1 = __importDefault(require("../../modules/tool.js"));
42
+ const order_event_js_1 = require("./order-event.js");
43
+ const notify_js_1 = require("./notify.js");
44
+ const auto_fcm_js_1 = require("../../public-config-initial/auto-fcm.js");
45
+ const auto_send_email_js_1 = require("./auto-send-email.js");
46
+ const invoice_js_1 = require("./invoice.js");
47
+ const redis_js_1 = __importDefault(require("../../modules/redis.js"));
48
+ const financial_service_js_1 = __importStar(require("./financial-service.js"));
49
+ const sms_js_1 = require("./sms.js");
50
+ const line_message_js_1 = require("./line-message.js");
51
+ const shopping_js_1 = require("./shopping.js");
52
+ class CheckoutEvent {
53
+ constructor(app, token) {
54
+ this.app = app;
55
+ this.token = token;
56
+ this.shopping = new shopping_js_1.Shopping(this.app, this.token);
57
+ }
58
+ getPaymentSetting() {
59
+ return JSON.parse(JSON.stringify((0, glitter_finance_js_1.onlinePayArray)()));
60
+ }
61
+ async toCheckout(data, type = 'add', replace_order_id) {
62
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9;
63
+ try {
64
+ const utTimer = new ut_timer_js_1.UtTimer('TO-CHECKOUT');
65
+ const checkPoint = utTimer.checkPoint;
66
+ const userClass = new user_js_1.User(this.app);
67
+ const rebateClass = new rebate_js_1.Rebate(this.app);
68
+ let checkoutPayment = (_a = data.user_info) === null || _a === void 0 ? void 0 : _a.payment;
69
+ let scheduledData;
70
+ data.line_items = (_b = (data.line_items || data.lineItems)) !== null && _b !== void 0 ? _b : [];
71
+ data.isExhibition = data.checkOutType === 'POS' && ((_d = (_c = data.pos_store) === null || _c === void 0 ? void 0 : _c.includes('exhibition_')) !== null && _d !== void 0 ? _d : false);
72
+ if (replace_order_id) {
73
+ const orderData = (await database_js_1.default.query(`SELECT *
74
+ FROM \`${this.app}\`.t_checkout
75
+ WHERE cart_token = ?
76
+ AND status = 0;
77
+ `, [replace_order_id]))[0];
78
+ if (!orderData) {
79
+ throw exception_js_1.default.BadRequestError('BAD_REQUEST', 'ToCheckout Error: Cannot find this orderID', null);
80
+ }
81
+ await database_js_1.default.query(`DELETE
82
+ FROM \`${this.app}\`.t_checkout
83
+ WHERE cart_token = ?
84
+ AND status = 0;
85
+ `, [replace_order_id]);
86
+ const { lineItems, user_info, code, customer_info, use_rebate } = orderData.orderData;
87
+ data.line_items = lineItems;
88
+ data.email = orderData.email;
89
+ data.user_info = user_info;
90
+ data.code = code;
91
+ data.customer_info = customer_info;
92
+ data.use_rebate = use_rebate;
93
+ }
94
+ if (data.order_id && type === 'POS') {
95
+ const order = (await database_js_1.default.query(`SELECT *
96
+ FROM \`${this.app}\`.t_checkout
97
+ WHERE cart_token = ?
98
+ `, [data.order_id]))[0];
99
+ if (order) {
100
+ for (const b of order.orderData.lineItems) {
101
+ const pdDqlData = (await this.shopping.getProduct({
102
+ page: 0,
103
+ limit: 50,
104
+ id: b.id,
105
+ status: 'inRange',
106
+ channel: data.checkOutType === 'POS' ? (data.isExhibition ? 'exhibition' : 'pos') : undefined,
107
+ whereStore: data.checkOutType === 'POS' ? data.pos_store : undefined,
108
+ })).data;
109
+ const pd = pdDqlData.content;
110
+ const variant = pd.variants.find((dd) => dd.spec.join('-') === b.spec.join('-'));
111
+ await updateStock(variant, b.deduction_log);
112
+ await this.shopping.updateVariantsWithSpec(variant, b.id, b.spec);
113
+ await database_js_1.default.query(`UPDATE \`${this.app}\`.t_manager_post
114
+ SET content = ?
115
+ WHERE id = ?
116
+ `, [JSON.stringify(pd), pdDqlData.id]);
117
+ }
118
+ }
119
+ }
120
+ async function updateStock(variant, deductionLog) {
121
+ Object.keys(deductionLog).forEach(key => {
122
+ try {
123
+ variant.stockList[key].count += deductionLog[key];
124
+ }
125
+ catch (e) {
126
+ console.error(`Error updating stock for variant ${variant.id}:`, e);
127
+ }
128
+ });
129
+ }
130
+ if (data.checkOutType === 'POS') {
131
+ this.token = undefined;
132
+ }
133
+ const hasAuthentication = (data) => {
134
+ return ((this.token && this.token.userID) ||
135
+ data.email ||
136
+ (data.user_info && data.user_info.email) ||
137
+ (data.user_info && data.user_info.phone));
138
+ };
139
+ if (type !== 'preview' && !hasAuthentication(data)) {
140
+ throw exception_js_1.default.BadRequestError('BAD_REQUEST', 'ToCheckout Error: No email and phone', null);
141
+ }
142
+ const checkOutType = (_e = data.checkOutType) !== null && _e !== void 0 ? _e : 'manual';
143
+ const getUserDataAsync = async (type, token, data) => {
144
+ if (type === 'preview' &&
145
+ !((token === null || token === void 0 ? void 0 : token.userID) || (data.user_info && data.user_info.email) || (data.user_info && data.user_info.phone))) {
146
+ return {};
147
+ }
148
+ if ((token === null || token === void 0 ? void 0 : token.userID) && type !== 'POS' && checkOutType !== 'POS') {
149
+ return await userClass.getUserData(`${token.userID}`, 'userID');
150
+ }
151
+ return ((data.user_info.email && (await userClass.getUserData(data.user_info.email, 'email_or_phone'))) ||
152
+ (data.user_info.phone && (await userClass.getUserData(data.user_info.phone, 'email_or_phone'))) ||
153
+ {});
154
+ };
155
+ checkPoint('check user auth');
156
+ const userData = await getUserDataAsync(type, this.token, data);
157
+ data.email = ((_f = userData === null || userData === void 0 ? void 0 : userData.userData) === null || _f === void 0 ? void 0 : _f.email) || ((_g = userData === null || userData === void 0 ? void 0 : userData.userData) === null || _g === void 0 ? void 0 : _g.phone) || '';
158
+ if (!data.email || data.email === 'no-email') {
159
+ data.email =
160
+ ((_h = data.user_info) === null || _h === void 0 ? void 0 : _h.email) && data.user_info.email !== 'no-email'
161
+ ? data.user_info.email
162
+ : ((_j = data.user_info) === null || _j === void 0 ? void 0 : _j.phone) || '';
163
+ }
164
+ if (!data.email && type !== 'preview') {
165
+ data.email = 'no-email';
166
+ }
167
+ const appStatus = await rebateClass.mainStatus();
168
+ if (appStatus && userData && data.use_rebate && data.use_rebate > 0) {
169
+ const userRebate = await rebateClass.getOneRebate({ user_id: userData.userID });
170
+ const sum = userRebate ? userRebate.point : 0;
171
+ if (sum < data.use_rebate) {
172
+ data.use_rebate = 0;
173
+ }
174
+ }
175
+ else {
176
+ data.use_rebate = 0;
177
+ }
178
+ checkPoint('check rebate');
179
+ const shipment = await this.shopping.getShipmentRefer(data.user_info);
180
+ const shipment_setting = await (async () => {
181
+ try {
182
+ const config = await private_config_js_1.Private_config.getConfig({
183
+ appName: this.app,
184
+ key: 'logistics_setting',
185
+ });
186
+ if (!config) {
187
+ return {
188
+ support: [],
189
+ shipmentSupport: [],
190
+ };
191
+ }
192
+ return config[0].value;
193
+ }
194
+ catch (e) {
195
+ return [];
196
+ }
197
+ })();
198
+ checkPoint('set shipment');
199
+ shipment_setting.custom_delivery = shipment_setting.custom_delivery
200
+ ? await Promise.all(shipment_setting.custom_delivery.map(async (form) => {
201
+ const config = await new user_js_1.User(this.app).getConfigV2({
202
+ user_id: 'manager',
203
+ key: `form_delivery_${form.id}`,
204
+ });
205
+ form.form = config.list || [];
206
+ return form;
207
+ })).then(dataArray => dataArray)
208
+ : [];
209
+ shipment_setting.support = (_k = shipment_setting.support) !== null && _k !== void 0 ? _k : [];
210
+ const languageInfo = (_m = (_l = shipment_setting.language_data) === null || _l === void 0 ? void 0 : _l[data.language]) === null || _m === void 0 ? void 0 : _m.info;
211
+ shipment_setting.info = languageInfo !== null && languageInfo !== void 0 ? languageInfo : shipment_setting.info;
212
+ const carData = {
213
+ customer_info: data.customer_info || {},
214
+ lineItems: [],
215
+ total: 0,
216
+ email: (_q = (_o = data.email) !== null && _o !== void 0 ? _o : (_p = data.user_info) === null || _p === void 0 ? void 0 : _p.email) !== null && _q !== void 0 ? _q : '',
217
+ user_info: data.user_info,
218
+ shipment_fee: 0,
219
+ rebate: 0,
220
+ goodsWeight: 0,
221
+ use_rebate: data.use_rebate || 0,
222
+ orderID: data.order_id || `${Date.now()}`,
223
+ shipment_support: shipment_setting.support,
224
+ shipment_info: shipment_setting.info,
225
+ shipment_selector: [
226
+ ...shipment_config_js_1.ShipmentConfig.list.map(dd => ({
227
+ name: dd.title,
228
+ value: dd.value,
229
+ })),
230
+ ...((_r = shipment_setting.custom_delivery) !== null && _r !== void 0 ? _r : []).map((dd) => ({
231
+ form: dd.form,
232
+ name: dd.name,
233
+ value: dd.id,
234
+ system_form: dd.system_form,
235
+ })),
236
+ ].filter(option => shipment_setting.support.includes(option.value)),
237
+ use_wallet: 0,
238
+ method: (_s = data.user_info) === null || _s === void 0 ? void 0 : _s.method,
239
+ user_email: (_w = (_u = (_t = userData === null || userData === void 0 ? void 0 : userData.account) !== null && _t !== void 0 ? _t : data.email) !== null && _u !== void 0 ? _u : (_v = data.user_info) === null || _v === void 0 ? void 0 : _v.email) !== null && _w !== void 0 ? _w : '',
240
+ useRebateInfo: { point: 0 },
241
+ custom_form_format: data.custom_form_format,
242
+ custom_form_data: data.custom_form_data,
243
+ custom_receipt_form: data.custom_receipt_form,
244
+ orderSource: checkOutType === 'POS' ? 'POS' : '',
245
+ code_array: data.code_array,
246
+ give_away: data.give_away,
247
+ user_rebate_sum: 0,
248
+ language: data.language,
249
+ pos_info: data.pos_info,
250
+ client_ip_address: data.client_ip_address,
251
+ fbc: data.fbc,
252
+ fbp: data.fbp,
253
+ editRecord: [],
254
+ };
255
+ if (!((_x = data.user_info) === null || _x === void 0 ? void 0 : _x.name) && userData && userData.userData) {
256
+ const { name, phone } = userData.userData;
257
+ carData.user_info = Object.assign(Object.assign({}, carData.user_info), { name,
258
+ phone });
259
+ }
260
+ const add_on_items = [];
261
+ const gift_product = [];
262
+ const saveStockArray = [];
263
+ function getVariant(prod, item) {
264
+ var _a;
265
+ if (prod.product_category === 'kitchen') {
266
+ let price = 0;
267
+ let show_understocking = false;
268
+ let stock = Infinity;
269
+ if (prod.specs.length) {
270
+ price = item.spec.reduce((total, spec, index) => {
271
+ const dpe = prod.specs[index].option.find((dd) => dd.title === spec);
272
+ if (dpe) {
273
+ const currentStock = Number(dpe.stock) || Infinity;
274
+ stock = Math.min(stock, currentStock);
275
+ if (dpe.stock !== undefined) {
276
+ show_understocking = true;
277
+ }
278
+ return total + (Number(dpe.price) || 0);
279
+ }
280
+ return total;
281
+ }, 0);
282
+ }
283
+ else {
284
+ price = Number(prod.price) || 0;
285
+ show_understocking = Boolean((_a = prod.stock) !== null && _a !== void 0 ? _a : '');
286
+ stock = Number(prod.stock) || 0;
287
+ }
288
+ if (stock === Infinity) {
289
+ show_understocking = false;
290
+ }
291
+ return {
292
+ sku: '',
293
+ spec: [],
294
+ type: 'variants',
295
+ stock,
296
+ v_width: 0,
297
+ product_id: prod.id,
298
+ sale_price: price,
299
+ origin_price: 0,
300
+ compare_price: 0,
301
+ preview_image: prod.preview_image && prod.preview_image[0],
302
+ shipment_type: 'none',
303
+ show_understocking: String(show_understocking),
304
+ };
305
+ }
306
+ else {
307
+ return prod.variants.find((dd) => dd.spec.join('-') === item.spec.join('-'));
308
+ }
309
+ }
310
+ data.line_items = await Promise.all(data.line_items.map(async (item) => {
311
+ var _a, _b, _c, _d, _e;
312
+ const getProductData = (await this.shopping.getProduct({
313
+ page: 0,
314
+ limit: 1,
315
+ id: `${item.id}`,
316
+ status: 'inRange',
317
+ channel: checkOutType === 'POS' ? (data.isExhibition ? 'exhibition' : 'pos') : undefined,
318
+ whereStore: checkOutType === 'POS' ? data.pos_store : undefined,
319
+ setUserID: `${(userData === null || userData === void 0 ? void 0 : userData.userID) || ''}`,
320
+ })).data;
321
+ if (getProductData) {
322
+ const content = getProductData.content;
323
+ const variant = getVariant(content, item);
324
+ const count = Number(item.count);
325
+ if ((Number.isInteger(variant.stock) || variant.show_understocking === 'false') &&
326
+ !isNaN(count) &&
327
+ count > 0) {
328
+ const isPOS = checkOutType === 'POS';
329
+ const isUnderstockingVisible = variant.show_understocking !== 'false';
330
+ const isManualType = type === 'manual' || type === 'manual-preview';
331
+ if (isPOS && isUnderstockingVisible && !data.isExhibition) {
332
+ variant.stock = ((_b = (_a = variant.stockList) === null || _a === void 0 ? void 0 : _a[data.pos_store]) === null || _b === void 0 ? void 0 : _b.count) || 0;
333
+ }
334
+ if (variant.stock < item.count && isUnderstockingVisible && !isManualType) {
335
+ if (isPOS) {
336
+ item.pre_order = true;
337
+ }
338
+ else {
339
+ item.count = variant.stock;
340
+ }
341
+ }
342
+ if (variant && item.count > 0) {
343
+ Object.assign(item, {
344
+ specs: content.specs,
345
+ language_data: content.language_data,
346
+ product_category: content.product_category,
347
+ preview_image: variant.preview_image || content.preview_image[0],
348
+ title: content.title,
349
+ sale_price: variant.sale_price,
350
+ origin_price: variant.origin_price,
351
+ collection: content.collection,
352
+ sku: variant.sku,
353
+ stock: variant.stock,
354
+ show_understocking: variant.show_understocking,
355
+ stockList: variant.stockList,
356
+ weight: parseInt(variant.weight || '0', 10),
357
+ designated_logistics: (_c = content.designated_logistics) !== null && _c !== void 0 ? _c : { type: 'all', list: [] },
358
+ });
359
+ const shipmentValue = (() => {
360
+ if (!variant.shipment_type || variant.shipment_type === 'none')
361
+ return 0;
362
+ if (variant.shipment_type === 'weight') {
363
+ return item.count * variant.weight;
364
+ }
365
+ if (variant.shipment_type === 'volume') {
366
+ return item.count * variant.v_length * variant.v_width * variant.v_height;
367
+ }
368
+ return 0;
369
+ })();
370
+ item.shipment_obj = {
371
+ type: variant.shipment_type,
372
+ value: shipmentValue,
373
+ };
374
+ variant.shipment_weight = parseInt(variant.shipment_weight || '0', 10);
375
+ carData.lineItems.push(item);
376
+ if (checkOutType == 'group_buy') {
377
+ if (!scheduledData) {
378
+ const sql = `WHERE JSON_CONTAINS(content->'$.pending_order', '"${data.temp_cart_id}"'`;
379
+ const scheduledDataQuery = `
380
+ SELECT *
381
+ FROM \`${this.app}\`.\`t_live_purchase_interactions\` ${sql});
382
+ `;
383
+ scheduledData = (await database_js_1.default.query(scheduledDataQuery, []))[0];
384
+ if (scheduledData) {
385
+ const { content } = scheduledData;
386
+ const productData = content.item_list.find((pb) => pb.id === item.id);
387
+ if (productData) {
388
+ const variantData = productData.content.variants.find((dd) => dd.spec.join('-') === item.spec.join('-'));
389
+ if (variantData) {
390
+ item.sale_price = variantData.live_model.live_price;
391
+ carData.total += item.sale_price * item.count;
392
+ }
393
+ }
394
+ }
395
+ }
396
+ }
397
+ else if (type !== 'manual') {
398
+ if (content.productType.giveaway) {
399
+ variant.sale_price = 0;
400
+ }
401
+ else {
402
+ carData.total += variant.sale_price * item.count;
403
+ }
404
+ }
405
+ }
406
+ if (!['preview', 'manual', 'manual-preview'].includes(type) && variant.show_understocking !== 'false') {
407
+ const remainingStock = Math.max(variant.stock - item.count, 0);
408
+ variant.stock = remainingStock;
409
+ if (type === 'POS') {
410
+ if (data.isExhibition) {
411
+ if (data.pos_store) {
412
+ await this.shopping.updateExhibitionActiveStock(data.pos_store, variant.variant_id, item.count);
413
+ }
414
+ }
415
+ else {
416
+ variant.deduction_log = { [data.pos_store]: item.count };
417
+ variant.stockList[data.pos_store].count -= item.count;
418
+ item.deduction_log = variant.deduction_log;
419
+ }
420
+ }
421
+ else {
422
+ const returnData = new stock_js_1.Stock(this.app, this.token).allocateStock(variant.stockList, item.count);
423
+ variant.deduction_log = returnData.deductionLog;
424
+ item.deduction_log = returnData.deductionLog;
425
+ }
426
+ saveStockArray.push(() => new Promise(async (resolve, reject) => {
427
+ var _a;
428
+ try {
429
+ if (data.checkOutType == 'group_buy') {
430
+ if (!scheduledData) {
431
+ const sql = `WHERE JSON_CONTAINS(content->'$.pending_order', '"${data.temp_cart_id}"'`;
432
+ const scheduledDataQuery = `
433
+ SELECT *
434
+ FROM \`${this.app}\`.\`t_live_purchase_interactions\` ${sql});
435
+ `;
436
+ scheduledData = (await database_js_1.default.query(scheduledDataQuery, []))[0];
437
+ }
438
+ if (scheduledData) {
439
+ const { content } = scheduledData;
440
+ const productData = content.item_list.find((pb) => pb.id === item.id);
441
+ if (productData) {
442
+ const variantData = productData.content.variants.find((dd) => dd.spec.join('-') === item.spec.join('-'));
443
+ if (variantData) {
444
+ const stockService = new stock_js_1.Stock(this.app, this.token);
445
+ const { stockList, deductionLog } = stockService.allocateStock(variantData.stockList, item.count);
446
+ variantData.stockList = stockList;
447
+ item.deduction_log = deductionLog;
448
+ carData.scheduled_id = scheduledData.id;
449
+ await this.shopping.updateVariantsForScheduled(content, scheduledData.id);
450
+ }
451
+ }
452
+ }
453
+ }
454
+ else {
455
+ if (content.shopee_id) {
456
+ await new shopee_js_1.Shopee(this.app, this.token).asyncStockToShopee({
457
+ product: getProductData,
458
+ callback: () => { },
459
+ });
460
+ }
461
+ if (content.product_category === 'kitchen' && ((_a = variant.spec) === null || _a === void 0 ? void 0 : _a.length)) {
462
+ variant.spec.forEach((d1, index) => {
463
+ const option = content.specs[index].option.find((d2) => d2.title === d1);
464
+ if ((option === null || option === void 0 ? void 0 : option.stock) !== undefined) {
465
+ option.stock = parseInt(option.stock, 10) - item.count;
466
+ }
467
+ });
468
+ const store_config = await userClass.getConfigV2({
469
+ key: 'store_manager',
470
+ user_id: 'manager',
471
+ });
472
+ item.deduction_log = { [store_config.list[0].id]: item.count };
473
+ }
474
+ else {
475
+ await this.shopping.updateVariantsWithSpec(variant, item.id, item.spec);
476
+ }
477
+ await database_js_1.default.query(`UPDATE \`${this.app}\`.\`t_manager_post\`
478
+ SET ?
479
+ WHERE id = ${getProductData.id}`, [{ content: JSON.stringify(content) }]);
480
+ }
481
+ resolve(true);
482
+ }
483
+ catch (error) {
484
+ reject(error);
485
+ }
486
+ }));
487
+ }
488
+ }
489
+ Object.assign(item, {
490
+ is_add_on_items: content.productType.addProduct && !content.productType.product,
491
+ is_hidden: content.visible === 'false',
492
+ is_gift: content.productType.giveaway,
493
+ sale_price: content.productType.giveaway ? 0 : item.sale_price,
494
+ min_qty: (_d = content.min_qty) !== null && _d !== void 0 ? _d : item.min_qty,
495
+ max_qty: (_e = content.max_qty) !== null && _e !== void 0 ? _e : item.max_qty,
496
+ });
497
+ item.is_add_on_items && add_on_items.push(item);
498
+ item.is_gift && gift_product.push(item);
499
+ }
500
+ return item;
501
+ })).then(dataArray => dataArray);
502
+ checkPoint('get product info');
503
+ const maxProductMap = new Map();
504
+ let hasMaxProduct = false;
505
+ for (const product of data.line_items) {
506
+ if (product.max_qty && product.max_qty > 0) {
507
+ maxProductMap.set(product.id, true);
508
+ hasMaxProduct = true;
509
+ }
510
+ }
511
+ if (hasMaxProduct && data.email !== 'no-email') {
512
+ const cartTokenSQL = `
513
+ SELECT cart_token
514
+ FROM \`${this.app}\`.t_checkout
515
+ WHERE email IN (${[-99, (_y = userData === null || userData === void 0 ? void 0 : userData.userData) === null || _y === void 0 ? void 0 : _y.email, (_z = userData === null || userData === void 0 ? void 0 : userData.userData) === null || _z === void 0 ? void 0 : _z.phone]
516
+ .filter(Boolean)
517
+ .map(item => database_js_1.default.escape(item))
518
+ .join(',')})
519
+ AND order_status <> '-1'
520
+ `;
521
+ const soldHistory = await database_js_1.default.query(`
522
+ SELECT *
523
+ FROM \`${this.app}\`.t_products_sold_history
524
+ WHERE product_id IN (${[...maxProductMap.keys()].join(',')})
525
+ AND order_id IN (${cartTokenSQL})
526
+ `, []);
527
+ const purchaseHistory = new Map();
528
+ for (const history of soldHistory) {
529
+ const pid = Number(history.product_id);
530
+ purchaseHistory.set(pid, ((_0 = purchaseHistory.get(pid)) !== null && _0 !== void 0 ? _0 : 0) + history.count);
531
+ }
532
+ for (const item of data.line_items) {
533
+ if (maxProductMap.has(item.id)) {
534
+ item.buy_history_count = purchaseHistory.get(item.id) || 0;
535
+ }
536
+ }
537
+ }
538
+ checkPoint('set max product');
539
+ carData.shipment_fee = this.shopping.getShipmentFee(data.user_info, carData.lineItems, shipment);
540
+ carData.total += carData.shipment_fee;
541
+ const f_rebate = await this.shopping.formatUseRebate(carData.total, carData.use_rebate);
542
+ carData.useRebateInfo = f_rebate;
543
+ carData.use_rebate = f_rebate.point;
544
+ carData.total -= carData.use_rebate;
545
+ carData.code = data.code;
546
+ carData.voucherList = [];
547
+ checkPoint('set carData');
548
+ if (userData && userData.account) {
549
+ const userRebate = await rebateClass.getOneRebate({ user_id: userData.userID });
550
+ carData.user_rebate_sum = (userRebate === null || userRebate === void 0 ? void 0 : userRebate.point) || 0;
551
+ }
552
+ if (data.distribution_code) {
553
+ const linkList = await new recommend_js_1.Recommend(this.app, this.token).getLinkList({
554
+ page: 0,
555
+ limit: 99999,
556
+ code: data.distribution_code,
557
+ status: true,
558
+ no_detail: true,
559
+ });
560
+ if (linkList.data.length > 0) {
561
+ const content = linkList.data[0].content;
562
+ if (this.shopping.checkDuring(content)) {
563
+ carData.distribution_info = content;
564
+ }
565
+ }
566
+ }
567
+ checkPoint('distribution code');
568
+ if (type !== 'manual' && type !== 'manual-preview') {
569
+ carData.lineItems = carData.lineItems.filter(dd => {
570
+ return !add_on_items.includes(dd) && !gift_product.includes(dd);
571
+ });
572
+ const c_carData = await this.shopping.checkVoucher(structuredClone(carData));
573
+ add_on_items.forEach(dd => {
574
+ var _a;
575
+ try {
576
+ const isAddOnItem = (_a = c_carData.voucherList) === null || _a === void 0 ? void 0 : _a.some(voucher => {
577
+ return (voucher.reBackType === 'add_on_items' &&
578
+ voucher.add_on_products.find(d2 => {
579
+ return `${dd.id}` === `${d2}`;
580
+ }));
581
+ });
582
+ if (isAddOnItem) {
583
+ carData.lineItems.push(dd);
584
+ }
585
+ }
586
+ catch (e) {
587
+ console.error('Error processing add-on items:', e);
588
+ }
589
+ });
590
+ await this.shopping.checkVoucher(carData);
591
+ checkPoint('check voucher');
592
+ let can_add_gift = [];
593
+ (_1 = carData.voucherList) === null || _1 === void 0 ? void 0 : _1.filter(dd => dd.reBackType === 'giveaway').forEach(dd => can_add_gift.push(dd.add_on_products));
594
+ gift_product.forEach(dd => {
595
+ const max_count = can_add_gift.filter(d1 => d1.includes(dd.id)).length;
596
+ if (dd.count <= max_count) {
597
+ for (let a = 0; a < dd.count; a++) {
598
+ can_add_gift = can_add_gift.filter(d1 => !d1.includes(dd.id));
599
+ }
600
+ carData.lineItems.push(dd);
601
+ }
602
+ });
603
+ for (const giveawayData of carData.voucherList.filter(dd => dd.reBackType === 'giveaway')) {
604
+ if (!((_2 = giveawayData.add_on_products) === null || _2 === void 0 ? void 0 : _2.length))
605
+ continue;
606
+ const productPromises = giveawayData.add_on_products.map(async (id) => {
607
+ const getGiveawayData = (await this.shopping.getProduct({
608
+ page: 0,
609
+ limit: 1,
610
+ id: `${id}`,
611
+ status: 'inRange',
612
+ channel: checkOutType === 'POS' ? (data.isExhibition ? 'exhibition' : 'pos') : undefined,
613
+ whereStore: checkOutType === 'POS' ? data.pos_store : undefined,
614
+ })).data.content;
615
+ getGiveawayData.voucher_id = giveawayData.id;
616
+ return getGiveawayData;
617
+ });
618
+ giveawayData.add_on_products = await Promise.all(productPromises);
619
+ }
620
+ }
621
+ const configData = await private_config_js_1.Private_config.getConfig({
622
+ appName: this.app,
623
+ key: 'glitter_finance',
624
+ });
625
+ const keyData = (_3 = configData[0]) === null || _3 === void 0 ? void 0 : _3.value;
626
+ if (keyData) {
627
+ carData.payment_info_custom = keyData.payment_info_custom;
628
+ }
629
+ await new Promise(resolve => {
630
+ var _a;
631
+ let n = 0;
632
+ carData.payment_customer_form = (_a = carData.payment_customer_form) !== null && _a !== void 0 ? _a : [];
633
+ keyData.payment_info_custom.map((item, index) => {
634
+ userClass
635
+ .getConfigV2({
636
+ user_id: 'manager',
637
+ key: `form_finance_${item.id}`,
638
+ })
639
+ .then(data => {
640
+ carData.payment_customer_form[index] = {
641
+ id: item.id,
642
+ list: data.list,
643
+ };
644
+ n++;
645
+ if (keyData.payment_info_custom.length === n) {
646
+ resolve();
647
+ }
648
+ });
649
+ });
650
+ if (n === 0) {
651
+ resolve();
652
+ }
653
+ });
654
+ checkPoint('set payment');
655
+ keyData.cash_on_delivery = (_4 = keyData.cash_on_delivery) !== null && _4 !== void 0 ? _4 : { shipmentSupport: [] };
656
+ carData.payment_info_line_pay = keyData.payment_info_line_pay;
657
+ carData.payment_info_atm = keyData.payment_info_atm;
658
+ keyData.cash_on_delivery.shipmentSupport = (_5 = keyData.cash_on_delivery.shipmentSupport) !== null && _5 !== void 0 ? _5 : [];
659
+ await this.setPaymentSetting({ carData: carData, checkoutPayment: checkoutPayment, keyData: keyData });
660
+ let subtotal = 0;
661
+ carData.lineItems.map(item => {
662
+ var _a;
663
+ if (item.is_gift) {
664
+ item.sale_price = 0;
665
+ }
666
+ if (!item.is_gift) {
667
+ subtotal += item.count * (item.sale_price - ((_a = item.discount_price) !== null && _a !== void 0 ? _a : 0));
668
+ }
669
+ });
670
+ if (carData.total < 0 || carData.use_rebate > subtotal) {
671
+ carData.use_rebate = 0;
672
+ carData.total = subtotal + carData.shipment_fee;
673
+ }
674
+ carData.lineItems.map(item => {
675
+ carData.goodsWeight += item.weight * item.count;
676
+ });
677
+ const excludedValuesByTotal = new Set(['UNIMARTC2C', 'FAMIC2C', 'HILIFEC2C', 'OKMARTC2C']);
678
+ const excludedValuesByWeight = new Set(['normal', 'black_cat']);
679
+ const isExcludedByTotal = (dd) => {
680
+ return carData.total > 20000 && excludedValuesByTotal.has(dd.value);
681
+ };
682
+ const isExcludedByWeight = (dd) => {
683
+ return carData.goodsWeight > 20 && excludedValuesByWeight.has(dd.value);
684
+ };
685
+ const isIncludedInDesignatedLogistics = (dd) => {
686
+ return carData.lineItems.every(item => {
687
+ return (item.designated_logistics === undefined ||
688
+ item.designated_logistics.type === 'all' ||
689
+ item.designated_logistics.list.includes(dd.value));
690
+ });
691
+ };
692
+ carData.shipment_selector = carData.shipment_selector
693
+ .filter((dd) => {
694
+ return isIncludedInDesignatedLogistics(dd);
695
+ })
696
+ .map(dd => {
697
+ dd.isExcludedByTotal = isExcludedByTotal(dd);
698
+ dd.isExcludedByWeight = isExcludedByWeight(dd);
699
+ return dd;
700
+ });
701
+ carData.code_array = (carData.code_array || []).filter(code => {
702
+ return (carData.voucherList || []).find(dd => dd.code === code);
703
+ });
704
+ if (Array.isArray(carData.shipment_support)) {
705
+ await Promise.all(carData.shipment_support.map(async (sup) => {
706
+ return await userClass
707
+ .getConfigV2({ key: 'shipment_config_' + sup, user_id: 'manager' })
708
+ .then(r => {
709
+ return this.getCartFormulaPass(carData, r);
710
+ })
711
+ .catch(() => {
712
+ return true;
713
+ });
714
+ })).then(dataArray => {
715
+ var _a;
716
+ carData.shipment_support = (_a = carData.shipment_support) === null || _a === void 0 ? void 0 : _a.filter((_, index) => dataArray[index]);
717
+ });
718
+ }
719
+ checkPoint('return preview');
720
+ if (type === 'preview' || type === 'manual-preview')
721
+ return { data: carData };
722
+ if (userData && userData.userID) {
723
+ await rebateClass.insertRebate(userData.userID, carData.use_rebate * -1, '使用折抵', {
724
+ order_id: carData.orderID,
725
+ });
726
+ if (carData.voucherList && carData.voucherList.length > 0) {
727
+ for (const voucher of carData.voucherList) {
728
+ await this.shopping.insertVoucherHistory(userData.userID, carData.orderID, voucher.id);
729
+ }
730
+ }
731
+ const sum = (await database_js_1.default.query(`SELECT sum(money)
732
+ FROM \`${this.app}\`.t_wallet
733
+ WHERE status in (1, 2)
734
+ and userID = ?`, [userData.userID]))[0]['sum(money)'] || 0;
735
+ carData.use_wallet = sum < carData.total ? sum : carData.total;
736
+ }
737
+ checkPoint('check user rebate');
738
+ if (type === 'manual' || type === 'split') {
739
+ carData.orderSource = type;
740
+ let tempVoucher = {
741
+ discount_total: data.voucher.discount_total,
742
+ end_ISO_Date: '',
743
+ for: 'all',
744
+ forKey: [],
745
+ method: data.voucher.method,
746
+ overlay: false,
747
+ rebate_total: data.voucher.rebate_total,
748
+ reBackType: data.voucher.reBackType,
749
+ rule: 'min_price',
750
+ ruleValue: 0,
751
+ startDate: '',
752
+ startTime: '',
753
+ start_ISO_Date: '',
754
+ status: 1,
755
+ target: '',
756
+ targetList: [],
757
+ title: data.voucher.title,
758
+ trigger: 'auto',
759
+ type: 'voucher',
760
+ value: data.voucher.value,
761
+ id: data.voucher.id,
762
+ bind: [],
763
+ bind_subtotal: 0,
764
+ times: 1,
765
+ counting: 'single',
766
+ conditionType: 'item',
767
+ includeDiscount: 'before',
768
+ device: ['normal'],
769
+ productOffStart: 'price_all',
770
+ };
771
+ carData.discount = data.discount;
772
+ carData.voucherList = [tempVoucher];
773
+ carData.customer_info = data.customer_info;
774
+ carData.total = (_6 = data.total) !== null && _6 !== void 0 ? _6 : 0;
775
+ carData.rebate = tempVoucher.rebate_total;
776
+ if (tempVoucher.reBackType == 'shipment_free' || type == 'split') {
777
+ carData.shipment_fee = 0;
778
+ }
779
+ if (tempVoucher.reBackType == 'rebate') {
780
+ let customerData = await userClass.getUserData(data.email || data.user_info.email, 'account');
781
+ if (!customerData) {
782
+ await userClass.createUser(data.email, tool_js_1.default.randomString(8), {
783
+ email: data.email,
784
+ name: data.customer_info.name,
785
+ phone: data.customer_info.phone,
786
+ }, {}, true);
787
+ customerData = await userClass.getUserData(data.email || data.user_info.email, 'account');
788
+ }
789
+ }
790
+ await order_event_js_1.OrderEvent.insertOrder({
791
+ cartData: carData,
792
+ status: data.pay_status,
793
+ app: this.app,
794
+ });
795
+ new notify_js_1.ManagerNotify(this.app).checkout({ orderData: carData, status: 0 });
796
+ const emailList = new Set([carData.customer_info, carData.user_info].map(dd => dd && dd.email));
797
+ for (const email of emailList) {
798
+ if (email) {
799
+ await auto_fcm_js_1.AutoFcm.orderChangeInfo({
800
+ app: this.app,
801
+ tag: 'order-create',
802
+ order_id: carData.orderID,
803
+ phone_email: email,
804
+ });
805
+ auto_send_email_js_1.AutoSendEmail.customerOrder(this.app, 'auto-email-order-create', carData.orderID, email, carData.language);
806
+ }
807
+ }
808
+ checkPoint('manual order done');
809
+ return {
810
+ data: carData,
811
+ };
812
+ }
813
+ else if (type === 'POS') {
814
+ carData.orderSource = 'POS';
815
+ if (checkOutType === 'POS' && Array.isArray(data.voucherList)) {
816
+ const manualVoucher = data.voucherList.find((item) => item.id === 0);
817
+ if (manualVoucher) {
818
+ manualVoucher.discount = (_7 = manualVoucher.discount_total) !== null && _7 !== void 0 ? _7 : 0;
819
+ carData.total -= manualVoucher.discount;
820
+ carData.discount += manualVoucher.discount;
821
+ carData.voucherList.push(manualVoucher);
822
+ }
823
+ }
824
+ const trans = await database_js_1.default.Transaction.build();
825
+ if (data.pre_order) {
826
+ carData.progress = 'pre_order';
827
+ carData.orderStatus = '0';
828
+ const payTotal = data.pos_info.payment
829
+ .map((dd) => dd.total)
830
+ .reduce((acc, val) => acc + val, 0);
831
+ if (carData.total <= payTotal) {
832
+ data.pay_status = 1;
833
+ }
834
+ else {
835
+ data.pay_status = 3;
836
+ }
837
+ }
838
+ else if (carData.user_info.shipment === 'now') {
839
+ carData.orderStatus = '1';
840
+ carData.progress = 'finish';
841
+ }
842
+ await order_event_js_1.OrderEvent.insertOrder({
843
+ cartData: carData,
844
+ status: data.pay_status,
845
+ app: this.app,
846
+ });
847
+ if (data.invoice_select !== 'nouse') {
848
+ carData.invoice = await new invoice_js_1.Invoice(this.app).postCheckoutInvoice(carData, carData.user_info.send_type !== 'carrier');
849
+ }
850
+ await trans.commit();
851
+ await trans.release();
852
+ await Promise.all(saveStockArray.map(dd => dd()));
853
+ await this.shopping.releaseCheckout((_8 = data.pay_status) !== null && _8 !== void 0 ? _8 : 0, carData.orderID);
854
+ checkPoint('release pos checkout');
855
+ for (const email of new Set([carData.customer_info, carData.user_info].map(dd => {
856
+ return dd && dd.email;
857
+ }))) {
858
+ if (email) {
859
+ await auto_fcm_js_1.AutoFcm.orderChangeInfo({
860
+ app: this.app,
861
+ tag: 'order-create',
862
+ order_id: carData.orderID,
863
+ phone_email: email,
864
+ });
865
+ auto_send_email_js_1.AutoSendEmail.customerOrder(this.app, 'auto-email-order-create', carData.orderID, email, carData.language);
866
+ }
867
+ }
868
+ return { result: 'SUCCESS', message: 'POS訂單新增成功', data: carData };
869
+ }
870
+ const id = 'redirect_' + tool_js_1.default.randomString(6);
871
+ const redirect_url = new URL(data.return_url);
872
+ redirect_url.searchParams.set('cart_token', carData.orderID);
873
+ await redis_js_1.default.setValue(id, redirect_url.href);
874
+ if (carData.use_wallet === carData.total) {
875
+ await database_js_1.default.query(`INSERT INTO \`${this.app}\`.t_wallet (orderID, userID, money, status, note)
876
+ values (?, ?, ?, ?, ?);`, [
877
+ carData.orderID,
878
+ userData.userID,
879
+ carData.use_wallet * -1,
880
+ 1,
881
+ JSON.stringify({
882
+ note: '使用錢包購物',
883
+ orderData: carData,
884
+ }),
885
+ ]);
886
+ carData.method = 'off_line';
887
+ await order_event_js_1.OrderEvent.insertOrder({
888
+ cartData: carData,
889
+ status: 1,
890
+ app: this.app,
891
+ });
892
+ if (carData.use_wallet > 0) {
893
+ new invoice_js_1.Invoice(this.app).postCheckoutInvoice(carData.orderID, false);
894
+ }
895
+ await Promise.all(saveStockArray.map(dd => dd()));
896
+ checkPoint('insert order & create invoice');
897
+ return {
898
+ is_free: true,
899
+ return_url: `${process.env.DOMAIN}/api-public/v1/ec/redirect?g-app=${this.app}&return=${id}`,
900
+ };
901
+ }
902
+ else {
903
+ const keyData = (await private_config_js_1.Private_config.getConfig({
904
+ appName: this.app,
905
+ key: 'glitter_finance',
906
+ }))[0].value;
907
+ let kd = (_9 = keyData[carData.customer_info.payment_select]) !== null && _9 !== void 0 ? _9 : {
908
+ ReturnURL: '',
909
+ NotifyURL: '',
910
+ };
911
+ switch (carData.customer_info.payment_select) {
912
+ case 'ecPay':
913
+ case 'newWebPay':
914
+ const subMitData = await new financial_service_js_1.default(this.app, {
915
+ HASH_IV: kd.HASH_IV,
916
+ HASH_KEY: kd.HASH_KEY,
917
+ ActionURL: kd.ActionURL,
918
+ NotifyURL: `${process.env.DOMAIN}/api-public/v1/ec/notify?g-app=${this.app}&type=${carData.customer_info.payment_select}`,
919
+ ReturnURL: `${process.env.DOMAIN}/api-public/v1/ec/redirect?g-app=${this.app}&return=${id}`,
920
+ MERCHANT_ID: kd.MERCHANT_ID,
921
+ TYPE: carData.customer_info.payment_select,
922
+ }).createOrderPage(carData);
923
+ await Promise.all(saveStockArray.map(dd => {
924
+ return dd();
925
+ }));
926
+ checkPoint('select newWebPay');
927
+ return {
928
+ form: subMitData,
929
+ };
930
+ case 'paypal':
931
+ kd.ReturnURL = `${process.env.DOMAIN}/api-public/v1/ec/redirect?g-app=${this.app}&return=${id}`;
932
+ kd.NotifyURL = `${process.env.DOMAIN}/api-public/v1/ec/notify?g-app=${this.app}&type=${carData.customer_info.payment_select}`;
933
+ await Promise.all(saveStockArray.map(dd => {
934
+ return dd();
935
+ }));
936
+ checkPoint('select paypal');
937
+ return await new financial_service_js_1.PayPal(this.app, kd).checkout(carData);
938
+ case 'line_pay':
939
+ kd.ReturnURL = `${process.env.DOMAIN}/api-public/v1/ec/redirect?g-app=${this.app}&return=${id}&type=${carData.customer_info.payment_select}`;
940
+ kd.NotifyURL = `${process.env.DOMAIN}/api-public/v1/ec/notify?g-app=${this.app}&type=${carData.customer_info.payment_select}`;
941
+ await Promise.all(saveStockArray.map(dd => {
942
+ return dd();
943
+ }));
944
+ checkPoint('select linepay');
945
+ return await new financial_service_js_1.LinePay(this.app, kd).createOrder(carData);
946
+ case 'paynow': {
947
+ kd.ReturnURL = `${process.env.DOMAIN}/api-public/v1/ec/redirect?g-app=${this.app}&return=${id}&type=${carData.customer_info.payment_select}`;
948
+ kd.NotifyURL = `${process.env.DOMAIN}/api-public/v1/ec/notify?g-app=${this.app}&paynow=true&type=${carData.customer_info.payment_select}`;
949
+ await Promise.all(saveStockArray.map(dd => {
950
+ return dd();
951
+ }));
952
+ checkPoint('select paynow');
953
+ return await new financial_service_js_1.PayNow(this.app, kd).createOrder(carData);
954
+ }
955
+ case 'jkopay': {
956
+ kd.ReturnURL = `${process.env.DOMAIN}/api-public/v1/ec/redirect?g-app=${this.app}&jkopay=true&return=${id}`;
957
+ kd.NotifyURL = `${process.env.DOMAIN}/api-public/v1/ec/notify?g-app=${this.app}&type=jkopay&return=${id}`;
958
+ checkPoint('select jkopay');
959
+ return await new financial_service_js_1.JKO(this.app, kd).createOrder(carData);
960
+ }
961
+ default:
962
+ carData.method = 'off_line';
963
+ await order_event_js_1.OrderEvent.insertOrder({
964
+ cartData: carData,
965
+ status: 0,
966
+ app: this.app,
967
+ });
968
+ await Promise.all(saveStockArray.map(dd => {
969
+ return dd();
970
+ }));
971
+ new notify_js_1.ManagerNotify(this.app).checkout({
972
+ orderData: carData,
973
+ status: 0,
974
+ });
975
+ for (const phone of new Set([carData.customer_info, carData.user_info].map(dd => {
976
+ return dd && dd.phone;
977
+ }))) {
978
+ let sns = new sms_js_1.SMS(this.app);
979
+ await sns.sendCustomerSns('auto-sns-order-create', carData.orderID, phone);
980
+ console.info('訂單簡訊寄送成功');
981
+ }
982
+ if (carData.customer_info.lineID) {
983
+ let line = new line_message_js_1.LineMessage(this.app);
984
+ await line.sendCustomerLine('auto-line-order-create', carData.orderID, carData.customer_info.lineID);
985
+ console.info('訂單line訊息寄送成功');
986
+ }
987
+ for (const email of new Set([carData.customer_info, carData.user_info].map(dd => {
988
+ return dd && dd.email;
989
+ }))) {
990
+ if (email) {
991
+ await auto_fcm_js_1.AutoFcm.orderChangeInfo({
992
+ app: this.app,
993
+ tag: 'order-create',
994
+ order_id: carData.orderID,
995
+ phone_email: email,
996
+ });
997
+ auto_send_email_js_1.AutoSendEmail.customerOrder(this.app, 'auto-email-order-create', carData.orderID, email, carData.language);
998
+ }
999
+ }
1000
+ await this.shopping.releaseVoucherHistory(carData.orderID, 1);
1001
+ checkPoint('default release checkout');
1002
+ return {
1003
+ off_line: true,
1004
+ return_url: `${process.env.DOMAIN}/api-public/v1/ec/redirect?g-app=${this.app}&return=${id}`,
1005
+ };
1006
+ }
1007
+ }
1008
+ }
1009
+ catch (e) {
1010
+ console.error(e);
1011
+ throw exception_js_1.default.BadRequestError('BAD_REQUEST', 'ToCheckout Func Error:' + e, null);
1012
+ }
1013
+ }
1014
+ async setPaymentSetting(obj) {
1015
+ var _a, _b;
1016
+ let { carData, keyData, checkoutPayment } = obj;
1017
+ let payment_setting = this.getPaymentSetting();
1018
+ payment_setting.filter((dd) => {
1019
+ const k = keyData[dd.key];
1020
+ if (!k || !k.toggle || !this.getCartFormulaPass(carData, k))
1021
+ return false;
1022
+ dd.custome_name = k.custome_name;
1023
+ if (carData.orderSource === 'POS') {
1024
+ if (dd.key === 'ut_credit_card') {
1025
+ dd.pwd = k['pwd'];
1026
+ }
1027
+ return dd.type === 'pos';
1028
+ }
1029
+ return dd.type !== 'pos';
1030
+ });
1031
+ carData.off_line_support = (_a = keyData.off_line_support) !== null && _a !== void 0 ? _a : {};
1032
+ Object.entries(carData.off_line_support).map(([key, value]) => {
1033
+ if (!value)
1034
+ return;
1035
+ if (key === 'cash_on_delivery') {
1036
+ carData.off_line_support[key] = this.getCartFormulaPass(carData, keyData[key]);
1037
+ if (carData.off_line_support[key]) {
1038
+ payment_setting.push({ key: 'cash_on_delivery', name: '貨到付款' });
1039
+ }
1040
+ }
1041
+ else if (key === 'atm') {
1042
+ carData.off_line_support[key] = this.getCartFormulaPass(carData, keyData.payment_info_atm);
1043
+ if (carData.off_line_support[key]) {
1044
+ payment_setting.push({ key: 'atm', name: 'atm轉帳' });
1045
+ }
1046
+ }
1047
+ else if (key === 'line') {
1048
+ carData.off_line_support[key] = this.getCartFormulaPass(carData, keyData.payment_info_line_pay);
1049
+ if (carData.off_line_support[key]) {
1050
+ payment_setting.push({ key: 'line', name: 'line轉帳' });
1051
+ }
1052
+ }
1053
+ else {
1054
+ const customPay = keyData.payment_info_custom.find((c) => c.id === key);
1055
+ carData.off_line_support[key] = this.getCartFormulaPass(carData, customPay !== null && customPay !== void 0 ? customPay : {});
1056
+ if (carData.off_line_support[key]) {
1057
+ payment_setting.push({ key: key, name: customPay.name });
1058
+ }
1059
+ }
1060
+ });
1061
+ carData.payment_setting = payment_setting;
1062
+ checkoutPayment = checkoutPayment || (carData.payment_setting[0] && carData.payment_setting[0].key);
1063
+ console.log('checkoutPayment', checkoutPayment);
1064
+ console.log('onlinePayArray', glitter_finance_js_1.onlinePayArray);
1065
+ carData.shipment_support =
1066
+ (_b = (() => {
1067
+ if (checkoutPayment === 'cash_on_delivery') {
1068
+ console.log(`shipment_support-cash-delivery`);
1069
+ return keyData.cash_on_delivery;
1070
+ }
1071
+ else if (this.getPaymentSetting().map((item) => item.key).includes(checkoutPayment)) {
1072
+ console.log(`shipment_support-online-pay-${checkoutPayment}`);
1073
+ return keyData[checkoutPayment];
1074
+ }
1075
+ else if (checkoutPayment === 'atm') {
1076
+ console.log(`shipment_support-atm`);
1077
+ return keyData.payment_info_atm;
1078
+ }
1079
+ else if (checkoutPayment === 'line') {
1080
+ console.log(`shipment_support-line`);
1081
+ return keyData.payment_info_line_pay;
1082
+ }
1083
+ else {
1084
+ console.log(`shipment_support-custom`);
1085
+ const customPay = keyData.payment_info_custom.find((c) => c.id === checkoutPayment);
1086
+ return customPay !== null && customPay !== void 0 ? customPay : {};
1087
+ }
1088
+ })().shipmentSupport) !== null && _b !== void 0 ? _b : [];
1089
+ }
1090
+ getCartFormulaPass(carData, keyData) {
1091
+ const data = keyData.cartSetting;
1092
+ if (!data || data.orderFormula === undefined)
1093
+ return true;
1094
+ const formulaSet = new Set(data.orderFormula);
1095
+ const total = carData.total -
1096
+ (formulaSet.has('shipment_fee') ? 0 : carData.shipment_fee) +
1097
+ (formulaSet.has('discount') || !carData.discount ? 0 : carData.discount) +
1098
+ (formulaSet.has('use_rebate') ? 0 : carData.use_rebate);
1099
+ return (!data.minimumTotal || total >= data.minimumTotal) && (!data.maximumTotal || total <= data.maximumTotal);
1100
+ }
1101
+ }
1102
+ exports.CheckoutEvent = CheckoutEvent;
1103
+ //# sourceMappingURL=checkout-event.js.map