@things-factory/marketplace-base 4.1.19 → 4.1.28

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.
@@ -11,17 +11,28 @@ const integration_fulfillment_1 = require("@things-factory/integration-fulfillme
11
11
  const integration_marketplace_1 = require("@things-factory/integration-marketplace");
12
12
  const product_base_1 = require("@things-factory/product-base");
13
13
  const shell_1 = require("@things-factory/shell");
14
+ const env_1 = require("@things-factory/env");
14
15
  const entities_1 = require("../../../entities");
15
16
  const utils_1 = require("../../../utils");
17
+ const reserve_qty_order_statuses_1 = require("../../../constants/reserve-qty-order-statuses");
18
+ const cancelStatuses = [
19
+ 'cancelled',
20
+ 'canceled',
21
+ 'failed',
22
+ 'shipped_back_success',
23
+ 'shipped_back',
24
+ 'returned',
25
+ 'to_return',
26
+ 'refunded'
27
+ ];
16
28
  exports.syncMarketplaceOrder = {
17
29
  async syncMarketplaceOrder(_, { storeId, fromDate, toDate }, context) {
18
- const { domain, user, tx } = context.state;
30
+ const { domain, user } = context.state;
19
31
  const marketplaceStore = await integration_marketplace_1.StoreAPI.getMarketplaceStore(storeId);
20
32
  let page = 0;
21
33
  let hasMorePage = true;
22
34
  let lastOrderId;
23
35
  var limit = 100;
24
- const cancelStatuses = ['cancelled', 'canceled'];
25
36
  const disallowCancelStatuses = ['CANCELLED', 'PENDING_CANCEL'];
26
37
  while (hasMorePage) {
27
38
  const { results: marketplaceOrders, more } = await integration_marketplace_1.StoreAPI.getStoreOrders(marketplaceStore, {
@@ -33,536 +44,462 @@ exports.syncMarketplaceOrder = {
33
44
  if ((marketplaceOrders === null || marketplaceOrders === void 0 ? void 0 : marketplaceOrders.length) == 0)
34
45
  throw new Error('There is no order available to sync');
35
46
  for (var i = 0; i < marketplaceOrders.length; i++) {
36
- var order = marketplaceOrders[i];
37
- let marketplaceOrderItems = [];
38
- let tracking_code = '';
39
- let deliveryProvider;
40
- let dropPickProvider;
41
- if (marketplaceStore.platform == 'lazada') {
42
- if (order.trackingNo != '') {
43
- tracking_code = JSON.parse(order.trackingNo)
44
- .reduce((newItem, item) => {
45
- if (newItem.indexOf(item.tracking_code) < 0) {
46
- newItem.push(item.tracking_code);
47
+ await (0, typeorm_1.getConnection)().transaction(async (tx) => {
48
+ try {
49
+ var order = marketplaceOrders[i];
50
+ let marketplaceOrderItems = [];
51
+ let tracking_code = '';
52
+ let deliveryProvider;
53
+ let dropPickProvider;
54
+ if (marketplaceStore.platform == 'lazada') {
55
+ if (order.trackingNo != '') {
56
+ tracking_code = JSON.parse(order.trackingNo)
57
+ .reduce((newItem, item) => {
58
+ if (newItem.indexOf(item.tracking_code) < 0) {
59
+ newItem.push(item.tracking_code);
60
+ }
61
+ return newItem;
62
+ }, [])
63
+ .join(',');
47
64
  }
48
- return newItem;
49
- }, [])
50
- .join(',');
51
- }
52
- const shippingProviderInfo = {};
53
- order.shippingProvider.split(', ').forEach(s => {
54
- var [key, value] = s.split(': ');
55
- shippingProviderInfo[key] = value;
56
- });
57
- dropPickProvider = (shippingProviderInfo === null || shippingProviderInfo === void 0 ? void 0 : shippingProviderInfo.Pickup)
58
- ? shippingProviderInfo['Pickup']
59
- : shippingProviderInfo['Drop-off'];
60
- deliveryProvider = shippingProviderInfo['Delivery'];
61
- }
62
- let marketplaceOrder = new entities_1.MarketplaceOrder();
63
- marketplaceOrder.name = order.name;
64
- marketplaceOrder.orderNo = order.orderNo;
65
- marketplaceOrder.itemCount = order.itemCount;
66
- marketplaceOrder.totalAmount = order.totalAmount;
67
- marketplaceOrder.status = order.status;
68
- marketplaceOrder.remark = order === null || order === void 0 ? void 0 : order.remark;
69
- marketplaceOrder.trackingNo = tracking_code ? tracking_code : order.trackingNo;
70
- marketplaceOrder.shippingProvider = order.shippingProvider;
71
- marketplaceOrder.orderCreatedAt = order.orderCreatedAt;
72
- marketplaceOrder.orderUpdatedAt = order.orderUpdatedAt;
73
- marketplaceOrder.marketplaceStore = marketplaceStore;
74
- marketplaceOrder.domain = marketplaceStore.domain;
75
- marketplaceOrder.buyerUsername = order.buyerUsername;
76
- marketplaceOrder.payTime = order.payTime;
77
- marketplaceOrder.serviceFee = order.serviceFee;
78
- marketplaceOrder.commissionFee = order.commissionFee;
79
- marketplaceOrder.transactionFee = order.transactionFee;
80
- marketplaceOrder.shippingMode = order.shippingMode;
81
- marketplaceOrder.voucherAmount = order.voucherAmount;
82
- marketplaceOrder.totalRealeasedAmount = order.totalRealeasedAmount;
83
- marketplaceOrder.voucherCode = order.voucherCode;
84
- marketplaceOrder.shippingRebate = order.shippingRebate;
85
- const existingMarketplaceOrder = await tx.getRepository(entities_1.MarketplaceOrder).findOne({
86
- where: { domain: marketplaceStore.domain, name: order.name },
87
- relations: [
88
- 'domain',
89
- 'fulfillmentCenter',
90
- 'marketplaceOrderItems',
91
- 'marketplaceOrderItems.marketplaceOrderShippingItems',
92
- 'marketplaceOrderItems.marketplaceOrderShippingItems.marketplaceOrderShipping',
93
- 'marketplaceOrderItems.marketplaceProductVariation'
94
- ]
95
- });
96
- if (existingMarketplaceOrder) {
97
- let otherInfoJSON = {};
98
- if ((existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.otherInfoJSON) && deliveryProvider) {
99
- otherInfoJSON = JSON.parse(existingMarketplaceOrder.otherInfoJSON);
100
- otherInfoJSON.shippingProvider = deliveryProvider;
101
- }
102
- marketplaceOrder = Object.assign(Object.assign(Object.assign({}, existingMarketplaceOrder), marketplaceOrder), { otherInfoJSON: otherInfoJSON ? JSON.stringify(otherInfoJSON) : null, updater: user });
103
- if (!(marketplaceOrder === null || marketplaceOrder === void 0 ? void 0 : marketplaceOrder.releaseOrderId) &&
104
- cancelStatuses.includes(marketplaceOrder.status) &&
105
- !cancelStatuses.includes(existingMarketplaceOrder.status)) {
106
- for (let item of marketplaceOrder.marketplaceOrderItems) {
107
- let foundVariations = await tx.getRepository(entities_1.MarketplaceProductVariation).find({
108
- where: { domain: marketplaceOrder.domain, sku: item.marketplaceProductVariation.sku },
109
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
65
+ const shippingProviderInfo = {};
66
+ order.shippingProvider.split(', ').forEach(s => {
67
+ var [key, value] = s.split(': ');
68
+ shippingProviderInfo[key] = value;
110
69
  });
111
- let activeVariations = foundVariations.filter(variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED' && variation.sku != null);
112
- await Promise.all(activeVariations.map(async (variation) => {
113
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty, '-');
114
- variation.reserveQty -= item.qty;
115
- variation.qty += item.qty;
116
- await tx.getRepository(entities_1.MarketplaceProductVariation).save(variation);
117
- }));
70
+ dropPickProvider = (shippingProviderInfo === null || shippingProviderInfo === void 0 ? void 0 : shippingProviderInfo.Pickup)
71
+ ? shippingProviderInfo['Pickup']
72
+ : shippingProviderInfo['Drop-off'];
73
+ deliveryProvider = shippingProviderInfo['Delivery'];
118
74
  }
119
- }
120
- if (marketplaceOrder === null || marketplaceOrder === void 0 ? void 0 : marketplaceOrder.releaseOrderId) {
121
- const fulfillmentCenter = marketplaceOrder.fulfillmentCenter;
122
- const centerId = fulfillmentCenter.centerId;
123
- const warehouseDomain = await tx.getRepository(shell_1.Domain).findOne({ where: { subdomain: centerId } });
124
- const customerBizplaces = await (0, biz_base_1.getCustomerBizplaces)(warehouseDomain);
125
- const customerBizplaceId = customerBizplaces.find(customerBizplace => customerBizplace.company.domain.id == domain.id).id;
126
- let { items: releaseOrders } = await integration_fulfillment_1.FulfillmentAPI.getOutboundOrders(fulfillmentCenter, {
127
- customerBizplaceId,
128
- refNo: marketplaceOrder.orderNo
75
+ let marketplaceOrder = new entities_1.MarketplaceOrder();
76
+ marketplaceOrder.name = order.name;
77
+ marketplaceOrder.orderNo = order.orderNo;
78
+ marketplaceOrder.itemCount = order.itemCount;
79
+ marketplaceOrder.totalAmount = order.totalAmount;
80
+ marketplaceOrder.status = order.status;
81
+ marketplaceOrder.remark = order === null || order === void 0 ? void 0 : order.remark;
82
+ marketplaceOrder.trackingNo = tracking_code ? tracking_code : order.trackingNo;
83
+ marketplaceOrder.shippingProvider = order.shippingProvider;
84
+ marketplaceOrder.orderCreatedAt = order.orderCreatedAt;
85
+ marketplaceOrder.orderUpdatedAt = order.orderUpdatedAt;
86
+ marketplaceOrder.marketplaceStore = marketplaceStore;
87
+ marketplaceOrder.domain = marketplaceStore.domain;
88
+ marketplaceOrder.buyerUsername = order.buyerUsername;
89
+ marketplaceOrder.payTime = order.payTime;
90
+ marketplaceOrder.serviceFee = order.serviceFee;
91
+ marketplaceOrder.commissionFee = order.commissionFee;
92
+ marketplaceOrder.transactionFee = order.transactionFee;
93
+ marketplaceOrder.shippingMode = order.shippingMode;
94
+ marketplaceOrder.voucherAmount = order.voucherAmount;
95
+ marketplaceOrder.totalRealeasedAmount = order.totalRealeasedAmount;
96
+ marketplaceOrder.voucherCode = order.voucherCode;
97
+ marketplaceOrder.shippingRebate = order.shippingRebate;
98
+ const existingMarketplaceOrder = await tx.getRepository(entities_1.MarketplaceOrder).findOne({
99
+ where: { domain: marketplaceStore.domain, name: order.name },
100
+ relations: [
101
+ 'domain',
102
+ 'fulfillmentCenter',
103
+ 'marketplaceOrderItems',
104
+ 'marketplaceOrderItems.marketplaceOrderShippingItems',
105
+ 'marketplaceOrderItems.marketplaceOrderShippingItems.marketplaceOrderShipping',
106
+ 'marketplaceOrderItems.marketplaceProductVariation',
107
+ 'marketplaceStore'
108
+ ]
129
109
  });
130
- if (existingMarketplaceOrder.isSplitted) {
131
- for (let a = 0; a < releaseOrders.length; a++) {
132
- const releaseOrder = releaseOrders[a];
133
- const foundMarketplaceOrderShipping = await tx
134
- .getRepository(entities_1.MarketplaceOrderShipping)
135
- .findOne({
136
- where: { domain: marketplaceStore.domain, subOrderNoRef: releaseOrder.refNo2 }
137
- });
138
- let patch = {
139
- id: releaseOrder.id,
140
- marketplaceOrderStatus: marketplaceOrder.status,
141
- trackingNo: (foundMarketplaceOrderShipping === null || foundMarketplaceOrderShipping === void 0 ? void 0 : foundMarketplaceOrderShipping.trackingNo) == '[]'
142
- ? foundMarketplaceOrderShipping.ownTrackingNo :
143
- (foundMarketplaceOrderShipping === null || foundMarketplaceOrderShipping === void 0 ? void 0 : foundMarketplaceOrderShipping.trackingNo)
144
- ? foundMarketplaceOrderShipping.trackingNo
145
- : foundMarketplaceOrderShipping.ownTrackingNo,
146
- transporter: dropPickProvider ? dropPickProvider : marketplaceOrder.shippingProvider
147
- };
148
- await integration_fulfillment_1.FulfillmentAPI.updateReleaseGoodDetails(fulfillmentCenter, {
149
- customerBizplaceId,
150
- releaseOrder: Object.assign({}, patch),
151
- shippingOrder: null
152
- });
110
+ if (existingMarketplaceOrder) {
111
+ let otherInfoJSON = {};
112
+ if ((existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.otherInfoJSON) && deliveryProvider) {
113
+ otherInfoJSON = JSON.parse(existingMarketplaceOrder.otherInfoJSON);
114
+ otherInfoJSON.shippingProvider = deliveryProvider;
153
115
  }
154
- }
155
- else {
156
- let releaseOrder = Object.assign({}, releaseOrders[0]);
157
- const foundMarketplaceOrderShipping = await tx
158
- .getRepository(entities_1.MarketplaceOrderShipping)
159
- .findOne({
160
- where: { domain: marketplaceStore.domain, orderNoRef: releaseOrder.refNo }
161
- });
162
- let patch = {
163
- id: releaseOrder.id,
164
- marketplaceOrderStatus: marketplaceOrder.status,
165
- trackingNo: (foundMarketplaceOrderShipping === null || foundMarketplaceOrderShipping === void 0 ? void 0 : foundMarketplaceOrderShipping.trackingNo) == '[]'
166
- ? foundMarketplaceOrderShipping.ownTrackingNo :
167
- (foundMarketplaceOrderShipping === null || foundMarketplaceOrderShipping === void 0 ? void 0 : foundMarketplaceOrderShipping.trackingNo)
168
- ? foundMarketplaceOrderShipping.trackingNo
169
- : foundMarketplaceOrderShipping.ownTrackingNo,
170
- transporter: dropPickProvider ? dropPickProvider : marketplaceOrder.shippingProvider
171
- };
172
- await integration_fulfillment_1.FulfillmentAPI.updateReleaseGoodDetails(fulfillmentCenter, {
173
- customerBizplaceId,
174
- releaseOrder: Object.assign({}, patch),
175
- shippingOrder: null
176
- });
177
- }
178
- if (cancelStatuses.includes(marketplaceOrder.status)) {
179
- if (existingMarketplaceOrder.isSplitted) {
180
- releaseOrders = releaseOrders.filter(function (order) {
181
- return !disallowCancelStatuses.includes(order.status);
182
- });
183
- if (releaseOrders === null || releaseOrders === void 0 ? void 0 : releaseOrders.length) {
184
- for (let a = 0; a < releaseOrders.length; a++) {
185
- const releaseOrderId = releaseOrders[a].id;
186
- await integration_fulfillment_1.FulfillmentAPI.cancelReleaseOrder(fulfillmentCenter, { customerBizplaceId, releaseOrderId });
187
- }
116
+ marketplaceOrder = Object.assign(Object.assign(Object.assign({}, existingMarketplaceOrder), marketplaceOrder), { otherInfoJSON: otherInfoJSON ? JSON.stringify(otherInfoJSON) : null, updater: user });
117
+ if (!(marketplaceOrder === null || marketplaceOrder === void 0 ? void 0 : marketplaceOrder.releaseOrderId) &&
118
+ reserve_qty_order_statuses_1.RESERVE_QTY_ORDER_STATUSES[marketplaceOrder.marketplaceStore.platform.toUpperCase()].includes(existingMarketplaceOrder.status) &&
119
+ cancelStatuses.includes(marketplaceOrder.status)) {
120
+ for (let item of marketplaceOrder.marketplaceOrderItems) {
121
+ await updateQtyAndReserveQty(tx, item.marketplaceProductVariation, marketplaceOrder, item.qty * -1, null, existingMarketplaceOrder);
188
122
  }
189
123
  }
190
- else {
124
+ if (marketplaceOrder === null || marketplaceOrder === void 0 ? void 0 : marketplaceOrder.releaseOrderId) {
191
125
  const fulfillmentCenter = marketplaceOrder.fulfillmentCenter;
192
126
  const centerId = fulfillmentCenter.centerId;
193
127
  const warehouseDomain = await tx
194
128
  .getRepository(shell_1.Domain)
195
129
  .findOne({ where: { subdomain: centerId } });
196
130
  const customerBizplaces = await (0, biz_base_1.getCustomerBizplaces)(warehouseDomain);
197
- const customerBizplaceId = customerBizplaces[0].id;
198
- const { items: releaseOrders } = await integration_fulfillment_1.FulfillmentAPI.getOutboundOrders(fulfillmentCenter, {
131
+ const customerBizplaceId = customerBizplaces.find(customerBizplace => customerBizplace.company.domain.id == domain.id).id;
132
+ let { items: releaseOrders } = await integration_fulfillment_1.FulfillmentAPI.getOutboundOrders(fulfillmentCenter, {
199
133
  customerBizplaceId,
200
134
  refNo: marketplaceOrder.orderNo
201
135
  });
202
- const releaseOrderStatus = releaseOrders[0].status;
203
- if (!disallowCancelStatuses.includes(releaseOrderStatus)) {
204
- await integration_fulfillment_1.FulfillmentAPI.cancelReleaseOrder(fulfillmentCenter, {
136
+ if (existingMarketplaceOrder.isSplitted) {
137
+ for (let a = 0; a < releaseOrders.length; a++) {
138
+ const releaseOrder = releaseOrders[a];
139
+ const foundMarketplaceOrderShipping = await tx
140
+ .getRepository(entities_1.MarketplaceOrderShipping)
141
+ .findOne({
142
+ where: { domain: marketplaceStore.domain, subOrderNoRef: releaseOrder.refNo2 }
143
+ });
144
+ let patch = {
145
+ id: releaseOrder.id,
146
+ marketplaceOrderStatus: marketplaceOrder.status,
147
+ trackingNo: (foundMarketplaceOrderShipping === null || foundMarketplaceOrderShipping === void 0 ? void 0 : foundMarketplaceOrderShipping.trackingNo) == '[]'
148
+ ? foundMarketplaceOrderShipping.ownTrackingNo
149
+ : (foundMarketplaceOrderShipping === null || foundMarketplaceOrderShipping === void 0 ? void 0 : foundMarketplaceOrderShipping.trackingNo)
150
+ ? foundMarketplaceOrderShipping.trackingNo
151
+ : foundMarketplaceOrderShipping.ownTrackingNo,
152
+ transporter: dropPickProvider ? dropPickProvider : marketplaceOrder.shippingProvider
153
+ };
154
+ await integration_fulfillment_1.FulfillmentAPI.updateReleaseGoodDetails(fulfillmentCenter, {
155
+ customerBizplaceId,
156
+ releaseOrder: Object.assign({}, patch),
157
+ shippingOrder: null
158
+ });
159
+ }
160
+ }
161
+ else {
162
+ let releaseOrder = Object.assign({}, releaseOrders[0]);
163
+ const foundMarketplaceOrderShipping = await tx
164
+ .getRepository(entities_1.MarketplaceOrderShipping)
165
+ .findOne({
166
+ where: { domain: marketplaceStore.domain, orderNoRef: releaseOrder.refNo }
167
+ });
168
+ let patch = {
169
+ id: releaseOrder.id,
170
+ marketplaceOrderStatus: marketplaceOrder.status,
171
+ trackingNo: (foundMarketplaceOrderShipping === null || foundMarketplaceOrderShipping === void 0 ? void 0 : foundMarketplaceOrderShipping.trackingNo) == '[]'
172
+ ? foundMarketplaceOrderShipping.ownTrackingNo
173
+ : (foundMarketplaceOrderShipping === null || foundMarketplaceOrderShipping === void 0 ? void 0 : foundMarketplaceOrderShipping.trackingNo)
174
+ ? foundMarketplaceOrderShipping.trackingNo
175
+ : foundMarketplaceOrderShipping.ownTrackingNo,
176
+ transporter: dropPickProvider ? dropPickProvider : marketplaceOrder.shippingProvider
177
+ };
178
+ await integration_fulfillment_1.FulfillmentAPI.updateReleaseGoodDetails(fulfillmentCenter, {
205
179
  customerBizplaceId,
206
- releaseOrderId: releaseOrders[0].id
180
+ releaseOrder: Object.assign({}, patch),
181
+ shippingOrder: null
207
182
  });
208
183
  }
184
+ if (cancelStatuses.includes(marketplaceOrder.status)) {
185
+ if (existingMarketplaceOrder.isSplitted) {
186
+ releaseOrders = releaseOrders.filter(function (order) {
187
+ return !disallowCancelStatuses.includes(order.status);
188
+ });
189
+ if (releaseOrders === null || releaseOrders === void 0 ? void 0 : releaseOrders.length) {
190
+ for (let a = 0; a < releaseOrders.length; a++) {
191
+ const releaseOrderId = releaseOrders[a].id;
192
+ await integration_fulfillment_1.FulfillmentAPI.cancelReleaseOrder(fulfillmentCenter, {
193
+ customerBizplaceId,
194
+ releaseOrderId
195
+ });
196
+ }
197
+ }
198
+ }
199
+ else {
200
+ const fulfillmentCenter = marketplaceOrder.fulfillmentCenter;
201
+ const centerId = fulfillmentCenter.centerId;
202
+ const warehouseDomain = await tx
203
+ .getRepository(shell_1.Domain)
204
+ .findOne({ where: { subdomain: centerId } });
205
+ const customerBizplaces = await (0, biz_base_1.getCustomerBizplaces)(warehouseDomain);
206
+ const customerBizplaceId = customerBizplaces[0].id;
207
+ const { items: releaseOrders } = await integration_fulfillment_1.FulfillmentAPI.getOutboundOrders(fulfillmentCenter, {
208
+ customerBizplaceId,
209
+ refNo: marketplaceOrder.orderNo
210
+ });
211
+ const releaseOrderStatus = releaseOrders[0].status;
212
+ if (!disallowCancelStatuses.includes(releaseOrderStatus)) {
213
+ await integration_fulfillment_1.FulfillmentAPI.cancelReleaseOrder(fulfillmentCenter, {
214
+ customerBizplaceId,
215
+ releaseOrderId: releaseOrders[0].id
216
+ });
217
+ }
218
+ }
219
+ }
209
220
  }
210
221
  }
211
- }
212
- }
213
- let savedMarketplaceOrderShipping = new entities_1.MarketplaceOrderShipping();
214
- let savedMarketplaceOrderShippings = [];
215
- if (order === null || order === void 0 ? void 0 : order.orderShipping) {
216
- const orderShipping = order.orderShipping;
217
- let marketplaceOrderShipping = new entities_1.MarketplaceOrderShipping();
218
- marketplaceOrderShipping.name = utils_1.NoGenerator.orderShipping();
219
- marketplaceOrderShipping.address1 = orderShipping.address1;
220
- marketplaceOrderShipping.address2 = orderShipping.address2;
221
- marketplaceOrderShipping.address3 = orderShipping.address3;
222
- marketplaceOrderShipping.address4 = orderShipping.address4;
223
- marketplaceOrderShipping.address5 = orderShipping.address5;
224
- marketplaceOrderShipping.attentionTo = orderShipping.attentionTo;
225
- marketplaceOrderShipping.city = orderShipping.city;
226
- marketplaceOrderShipping.country = orderShipping.country;
227
- marketplaceOrderShipping.state = (orderShipping === null || orderShipping === void 0 ? void 0 : orderShipping.state) || null;
228
- marketplaceOrderShipping.postCode = orderShipping.postCode;
229
- marketplaceOrderShipping.phone1 = orderShipping.phone1;
230
- marketplaceOrderShipping.phone2 = orderShipping.phone2;
231
- marketplaceOrderShipping.trackingNo = (order === null || order === void 0 ? void 0 : order.trackingNo) || null;
232
- marketplaceOrderShipping.orderNoRef = marketplaceOrder.orderNo;
233
- marketplaceOrderShipping.subOrderNoRef = marketplaceOrder.orderNo;
234
- marketplaceOrderShipping.marketplaceStore = marketplaceStore;
235
- marketplaceOrderShipping.creator = user;
236
- marketplaceOrderShipping.domain = marketplaceStore.domain;
237
- marketplaceOrderShipping.shippingFee = orderShipping.shippingFee;
238
- marketplaceOrderShipping.actualShippingFee = orderShipping.actualShippingFee;
239
- marketplaceOrderShipping.marketplaceShippingFeeVoucher = orderShipping.marketplaceShippingFeeVoucher;
240
- marketplaceOrderShipping.sellerShippingFeeVoucher = orderShipping.sellerShippingFeeVoucher;
241
- if (existingMarketplaceOrder) {
242
- if (existingMarketplaceOrder.isSplitted) {
243
- let existingOrderShippings = await tx
244
- .getRepository(entities_1.MarketplaceOrderShipping)
245
- .find({
246
- where: { domain, marketplaceStore, orderNoRef: marketplaceOrder.orderNo }
247
- });
248
- existingOrderShippings = existingOrderShippings.map(item => {
249
- return Object.assign(Object.assign({}, item), { address1: orderShipping.address1, address2: orderShipping.address2, address3: orderShipping.address3, address4: orderShipping.address4, address5: orderShipping.address5, attentionTo: orderShipping.attentionTo, city: orderShipping.city, country: orderShipping.country, state: orderShipping === null || orderShipping === void 0 ? void 0 : orderShipping.state, postCode: orderShipping.postCode, phone1: orderShipping.phone1, phone2: orderShipping.phone2, email: orderShipping === null || orderShipping === void 0 ? void 0 : orderShipping.email, trackingNo: order === null || order === void 0 ? void 0 : order.trackingNo, shippingFee: orderShipping.shippingFee, actualShippingFee: orderShipping.actualShippingFee, marketplaceShippingFeeVoucher: orderShipping.marketplaceShippingFeeVoucher, sellerShippingFeeVoucher: orderShipping.sellerShippingFeeVoucher });
250
- });
251
- savedMarketplaceOrderShippings = await tx
252
- .getRepository(entities_1.MarketplaceOrderShipping)
253
- .save(existingOrderShippings);
254
- }
255
- else {
256
- if (existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.marketplaceOrderItems) {
257
- let existingOrderShipping;
258
- existingOrderShipping =
259
- existingMarketplaceOrder.marketplaceOrderItems[0].marketplaceOrderShippingItems[0]
260
- .marketplaceOrderShipping;
261
- marketplaceOrderShipping = Object.assign(Object.assign(Object.assign({}, existingOrderShipping), marketplaceOrderShipping), { trackingNo: (marketplaceOrderShipping === null || marketplaceOrderShipping === void 0 ? void 0 : marketplaceOrderShipping.trackingNo)
262
- ? marketplaceOrderShipping.trackingNo
263
- : (existingOrderShipping === null || existingOrderShipping === void 0 ? void 0 : existingOrderShipping.trackingNo)
264
- ? existingOrderShipping.trackingNo
265
- : marketplaceOrderShipping.trackingNo, updater: user });
222
+ let savedMarketplaceOrderShipping = new entities_1.MarketplaceOrderShipping();
223
+ let savedMarketplaceOrderShippings = [];
224
+ if (order === null || order === void 0 ? void 0 : order.orderShipping) {
225
+ const orderShipping = order.orderShipping;
226
+ let marketplaceOrderShipping = new entities_1.MarketplaceOrderShipping();
227
+ marketplaceOrderShipping.name = utils_1.NoGenerator.orderShipping();
228
+ marketplaceOrderShipping.address1 = orderShipping.address1;
229
+ marketplaceOrderShipping.address2 = orderShipping.address2;
230
+ marketplaceOrderShipping.address3 = orderShipping.address3;
231
+ marketplaceOrderShipping.address4 = orderShipping.address4;
232
+ marketplaceOrderShipping.address5 = orderShipping.address5;
233
+ marketplaceOrderShipping.attentionTo = orderShipping.attentionTo;
234
+ marketplaceOrderShipping.city = orderShipping.city;
235
+ marketplaceOrderShipping.country = orderShipping.country;
236
+ marketplaceOrderShipping.state = (orderShipping === null || orderShipping === void 0 ? void 0 : orderShipping.state) || null;
237
+ marketplaceOrderShipping.postCode = orderShipping.postCode;
238
+ marketplaceOrderShipping.phone1 = orderShipping.phone1;
239
+ marketplaceOrderShipping.phone2 = orderShipping.phone2;
240
+ marketplaceOrderShipping.trackingNo = (order === null || order === void 0 ? void 0 : order.trackingNo) || null;
241
+ marketplaceOrderShipping.orderNoRef = marketplaceOrder.orderNo;
242
+ marketplaceOrderShipping.subOrderNoRef = marketplaceOrder.orderNo;
243
+ marketplaceOrderShipping.marketplaceStore = marketplaceStore;
244
+ marketplaceOrderShipping.creator = user;
245
+ marketplaceOrderShipping.domain = marketplaceStore.domain;
246
+ marketplaceOrderShipping.shippingFee = orderShipping.shippingFee;
247
+ marketplaceOrderShipping.actualShippingFee = orderShipping.actualShippingFee;
248
+ marketplaceOrderShipping.marketplaceShippingFeeVoucher = orderShipping.marketplaceShippingFeeVoucher;
249
+ marketplaceOrderShipping.sellerShippingFeeVoucher = orderShipping.sellerShippingFeeVoucher;
250
+ if (existingMarketplaceOrder) {
251
+ if (existingMarketplaceOrder.isSplitted) {
252
+ let existingOrderShippings = await tx
253
+ .getRepository(entities_1.MarketplaceOrderShipping)
254
+ .find({
255
+ where: { domain, marketplaceStore, orderNoRef: marketplaceOrder.orderNo }
256
+ });
257
+ existingOrderShippings = existingOrderShippings.map(item => {
258
+ return Object.assign(Object.assign({}, item), { address1: orderShipping.address1, address2: orderShipping.address2, address3: orderShipping.address3, address4: orderShipping.address4, address5: orderShipping.address5, attentionTo: orderShipping.attentionTo, city: orderShipping.city, country: orderShipping.country, state: orderShipping === null || orderShipping === void 0 ? void 0 : orderShipping.state, postCode: orderShipping.postCode, phone1: orderShipping.phone1, phone2: orderShipping.phone2, email: orderShipping === null || orderShipping === void 0 ? void 0 : orderShipping.email, trackingNo: marketplaceStore.eTrax ? item.trackingNo : order === null || order === void 0 ? void 0 : order.trackingNo, shippingFee: orderShipping.shippingFee, actualShippingFee: orderShipping.actualShippingFee, marketplaceShippingFeeVoucher: orderShipping.marketplaceShippingFeeVoucher, sellerShippingFeeVoucher: orderShipping.sellerShippingFeeVoucher });
259
+ });
260
+ savedMarketplaceOrderShippings = await tx
261
+ .getRepository(entities_1.MarketplaceOrderShipping)
262
+ .save(existingOrderShippings);
263
+ }
264
+ else {
265
+ if (existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.marketplaceOrderItems) {
266
+ let existingOrderShipping;
267
+ existingOrderShipping =
268
+ existingMarketplaceOrder.marketplaceOrderItems[0].marketplaceOrderShippingItems[0]
269
+ .marketplaceOrderShipping;
270
+ marketplaceOrderShipping = Object.assign(Object.assign(Object.assign({}, existingOrderShipping), marketplaceOrderShipping), { trackingNo: marketplaceStore.eTrax
271
+ ? existingOrderShipping.trackingNo
272
+ : (marketplaceOrderShipping === null || marketplaceOrderShipping === void 0 ? void 0 : marketplaceOrderShipping.trackingNo)
273
+ ? marketplaceOrderShipping.trackingNo
274
+ : (existingOrderShipping === null || existingOrderShipping === void 0 ? void 0 : existingOrderShipping.trackingNo)
275
+ ? existingOrderShipping.trackingNo
276
+ : marketplaceOrderShipping.trackingNo, updater: user });
277
+ savedMarketplaceOrderShipping = await tx
278
+ .getRepository(entities_1.MarketplaceOrderShipping)
279
+ .save(marketplaceOrderShipping);
280
+ }
281
+ }
282
+ }
283
+ else {
284
+ if (marketplaceStore.eTrax)
285
+ delete marketplaceOrderShipping.trackingNo;
266
286
  savedMarketplaceOrderShipping = await tx
267
287
  .getRepository(entities_1.MarketplaceOrderShipping)
268
288
  .save(marketplaceOrderShipping);
269
289
  }
270
290
  }
271
- }
272
- else {
273
- savedMarketplaceOrderShipping = await tx
274
- .getRepository(entities_1.MarketplaceOrderShipping)
275
- .save(marketplaceOrderShipping);
276
- }
277
- }
278
- let orderTotalWeight = 0;
279
- let foundVariations = [];
280
- for (var j = 0; j < order.orderItems.length; j++) {
281
- var item = order.orderItems[j];
282
- let foundVariationsQuery = await tx.getRepository(entities_1.MarketplaceProductVariation).find({
283
- where: { domain: marketplaceStore.domain, variationId: item.variationId },
284
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
285
- });
286
- let foundVariation = foundVariationsQuery.filter(fv => fv.marketplaceProduct.marketplaceStore.id == marketplaceStore.id)[0];
287
- if (foundVariation) {
288
- foundVariations.push(foundVariation);
289
- }
290
- if (!foundVariation) {
291
- let newVariation = {
292
- variationId: item.variationId,
293
- name: item.variationName,
294
- variationSku: item.variationSku,
295
- channelSku: item.sku,
296
- status: 'INACTIVE',
297
- domain: marketplaceStore.domain
298
- };
299
- await tx.getRepository(entities_1.MarketplaceProductVariation).save(newVariation);
300
- foundVariation = newVariation;
301
- }
302
- let marketplaceOrderItem = new entities_1.MarketplaceOrderItem();
303
- marketplaceOrderItem.domain = marketplaceStore.domain;
304
- marketplaceOrderItem.name = item.name;
305
- marketplaceOrderItem.qty = item.qty;
306
- marketplaceOrderItem.paidPrice = item.paidPrice;
307
- marketplaceOrderItem.status = marketplaceOrder.status;
308
- marketplaceOrderItem.docRefNo = item.docRefNo;
309
- marketplaceOrderItem.marketplaceProductVariation = foundVariation;
310
- marketplaceOrderItem.trackingCode = order.trackingNo;
311
- marketplaceOrderItem.marketplaceOrder = marketplaceOrder;
312
- marketplaceOrderItem.originalPrice = item.originalPrice;
313
- marketplaceOrderItem.discount = item.discount;
314
- marketplaceOrderItem.promotionId = item.promotionId;
315
- marketplaceOrderItem.creator = user;
316
- marketplaceOrderItem.paymentFee = item.paymentFee || null;
317
- marketplaceOrderItem.commissionFee = item.commissionFee || null;
318
- marketplaceOrderItem.shippingFeePaidByCustomer = item.shippingFeePaidByCustomer || null;
319
- marketplaceOrderItem.itemPriceCredit = item.itemPriceCredit || null;
320
- marketplaceOrderItem.promotionalCharges = item.promotionalCharges || null;
321
- marketplaceOrderItem.ordersMarketplaceFeesTotal = item.ordersMarketplaceFeesTotal || null;
322
- marketplaceOrderItem.ordersSalesTotal = item.ordersSalesTotal || null;
323
- marketplaceOrderItem.ordersMarketingFeesTotal = item.ordersMarketingFeesTotal || null;
324
- marketplaceOrderItem.ordersLogisticsTotal = item.ordersLogisticsTotal || null;
325
- marketplaceOrderItem.marketplaceBonus = item.marketplaceBonus;
326
- marketplaceOrderItem.marketplaceBonusSeller = item.marketplaceBonusSeller;
327
- marketplaceOrderItem.shippingFeeDiscountMarketplace = item.shippingFeeDiscountMarketplace;
328
- marketplaceOrderItem.shippingFeeDiscountSeller = item.shippingFeeDiscountSeller;
329
- marketplaceOrderItem.promotionalChargesFlexiCombo = item.promotionalChargesFlexiCombo;
330
- marketplaceOrderItem.autoShippingSubsidyMarketplace = item.autoShippingSubsidyMarketplace;
331
- marketplaceOrderItem.originalShippingFee = item.originalShippingFee;
332
- marketplaceOrderItem.taxAmount = item.taxAmount;
333
- marketplaceOrderItems.push(Object.assign({}, marketplaceOrderItem));
334
- if (foundVariation === null || foundVariation === void 0 ? void 0 : foundVariation.primaryUnitValue)
335
- orderTotalWeight += parseFloat(foundVariation.primaryUnitValue.toFixed(3)) * item.qty || 0;
336
- }
337
- if (existingMarketplaceOrder) {
338
- let existingOrderItems = [];
339
- existingOrderItems = existingMarketplaceOrder.marketplaceOrderItems;
340
- existingOrderItems = await checkUpdateItemId(existingOrderItems, marketplaceOrderItems);
341
- if (existingMarketplaceOrder.isSplitted) {
342
- marketplaceOrderItems = existingOrderItems.filter(itm => itm.name == item.name && itm.marketplaceProductVariation.variationId == item.variationId);
343
- marketplaceOrderItems = marketplaceOrderItems.map(marketplaceOrderitem => {
344
- return Object.assign(Object.assign({}, marketplaceOrderitem), { status: order.status, trackingCode: order.trackingNo });
345
- });
346
- }
347
- else {
348
- if (existingOrderItems.length > marketplaceOrderItems.length) {
349
- let nonMatchedOrderItems = [];
350
- existingOrderItems.map(item => {
351
- const matchedOrderItem = marketplaceOrderItems.find(itm => itm.name === item.name &&
352
- itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId);
353
- if (!matchedOrderItem) {
354
- nonMatchedOrderItems.push(Object.assign({}, item));
355
- }
291
+ let orderTotalWeight = 0;
292
+ let foundVariations = [];
293
+ for (var j = 0; j < order.orderItems.length; j++) {
294
+ var item = order.orderItems[j];
295
+ let foundVariationsQuery = await tx.getRepository(entities_1.MarketplaceProductVariation).find({
296
+ where: { domain: marketplaceStore.domain, variationId: item.variationId },
297
+ relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
356
298
  });
357
- if (nonMatchedOrderItems.length > 0 && !cancelStatuses.includes(marketplaceOrder.status)) {
358
- await Promise.all(nonMatchedOrderItems.map(async (item) => {
359
- for (var foundVariation of foundVariations) {
360
- if (foundVariation.sku) {
361
- let allVariations = await tx
362
- .getRepository(entities_1.MarketplaceProductVariation)
363
- .find({
364
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
365
- relations: [
366
- 'domain',
367
- 'marketplaceProduct',
368
- 'marketplaceProduct.marketplaceStore',
369
- 'marketplaceProduct.marketplaceStore.marketplaceDistributors'
370
- ]
371
- });
372
- let activeVariations = allVariations.filter(variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED');
373
- await Promise.all(activeVariations.map(async (variation) => {
374
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty, '-');
375
- variation.reserveQty -= item.qty;
376
- variation.qty += item.qty;
377
- variation = await tx.getRepository(entities_1.MarketplaceProductVariation).save(variation);
378
- }));
379
- }
380
- }
381
- }));
382
- await tx.getRepository(entities_1.MarketplaceOrderItem).delete(nonMatchedOrderItems);
299
+ let foundVariation = foundVariationsQuery.filter(fv => fv.marketplaceProduct.marketplaceStore.id == marketplaceStore.id)[0];
300
+ if (foundVariation) {
301
+ foundVariations.push(foundVariation);
383
302
  }
384
- if (!cancelStatuses.includes(marketplaceOrder.status)) {
385
- existingOrderItems = await Promise.all(marketplaceOrderItems.map(async (item) => {
386
- const matchedOrderItem = existingOrderItems.find(itm => itm.name == item.name &&
387
- itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId);
388
- if (matchedOrderItem) {
389
- for (var foundVariation of foundVariations) {
303
+ if (!foundVariation) {
304
+ let newVariation = {
305
+ variationId: item.variationId,
306
+ name: item.variationName,
307
+ variationSku: item.variationSku,
308
+ channelSku: item.sku,
309
+ status: 'INACTIVE',
310
+ domain: marketplaceStore.domain
311
+ };
312
+ await tx.getRepository(entities_1.MarketplaceProductVariation).save(newVariation);
313
+ foundVariation = newVariation;
314
+ }
315
+ let marketplaceOrderItem = new entities_1.MarketplaceOrderItem();
316
+ marketplaceOrderItem.domain = marketplaceStore.domain;
317
+ marketplaceOrderItem.name = item.name;
318
+ marketplaceOrderItem.qty = item.qty;
319
+ marketplaceOrderItem.paidPrice = item.paidPrice;
320
+ marketplaceOrderItem.status = marketplaceOrder.status;
321
+ marketplaceOrderItem.docRefNo = item.docRefNo;
322
+ marketplaceOrderItem.marketplaceProductVariation = foundVariation;
323
+ marketplaceOrderItem.trackingCode = order.trackingNo;
324
+ marketplaceOrderItem.marketplaceOrder = marketplaceOrder;
325
+ marketplaceOrderItem.originalPrice = item.originalPrice;
326
+ marketplaceOrderItem.discount = item.discount;
327
+ marketplaceOrderItem.promotionId = item.promotionId;
328
+ marketplaceOrderItem.creator = user;
329
+ marketplaceOrderItem.paymentFee = item.paymentFee || null;
330
+ marketplaceOrderItem.commissionFee = item.commissionFee || null;
331
+ marketplaceOrderItem.shippingFeePaidByCustomer = item.shippingFeePaidByCustomer || null;
332
+ marketplaceOrderItem.itemPriceCredit = item.itemPriceCredit || null;
333
+ marketplaceOrderItem.promotionalCharges = item.promotionalCharges || null;
334
+ marketplaceOrderItem.ordersMarketplaceFeesTotal = item.ordersMarketplaceFeesTotal || null;
335
+ marketplaceOrderItem.ordersSalesTotal = item.ordersSalesTotal || null;
336
+ marketplaceOrderItem.ordersMarketingFeesTotal = item.ordersMarketingFeesTotal || null;
337
+ marketplaceOrderItem.ordersLogisticsTotal = item.ordersLogisticsTotal || null;
338
+ marketplaceOrderItem.marketplaceBonus = item.marketplaceBonus;
339
+ marketplaceOrderItem.marketplaceBonusSeller = item.marketplaceBonusSeller;
340
+ marketplaceOrderItem.shippingFeeDiscountMarketplace = item.shippingFeeDiscountMarketplace;
341
+ marketplaceOrderItem.shippingFeeDiscountSeller = item.shippingFeeDiscountSeller;
342
+ marketplaceOrderItem.promotionalChargesFlexiCombo = item.promotionalChargesFlexiCombo;
343
+ marketplaceOrderItem.autoShippingSubsidyMarketplace = item.autoShippingSubsidyMarketplace;
344
+ marketplaceOrderItem.originalShippingFee = item.originalShippingFee;
345
+ marketplaceOrderItem.taxAmount = item.taxAmount;
346
+ marketplaceOrderItems.push(Object.assign({}, marketplaceOrderItem));
347
+ if (foundVariation === null || foundVariation === void 0 ? void 0 : foundVariation.primaryUnitValue)
348
+ orderTotalWeight += parseFloat(foundVariation.primaryUnitValue.toFixed(3)) * item.qty || 0;
349
+ }
350
+ if (existingMarketplaceOrder) {
351
+ let existingOrderItems = [];
352
+ existingOrderItems = existingMarketplaceOrder.marketplaceOrderItems;
353
+ existingOrderItems = await checkUpdateItemId(existingOrderItems, marketplaceOrderItems);
354
+ if (existingMarketplaceOrder.isSplitted) {
355
+ marketplaceOrderItems = existingOrderItems.filter(itm => itm.name == item.name && itm.marketplaceProductVariation.variationId == item.variationId);
356
+ marketplaceOrderItems = marketplaceOrderItems.map(marketplaceOrderitem => {
357
+ return Object.assign(Object.assign({}, marketplaceOrderitem), { status: order.status, trackingCode: order.trackingNo });
358
+ });
359
+ }
360
+ else {
361
+ if (existingOrderItems.length > marketplaceOrderItems.length) {
362
+ let nonMatchedOrderItems = [];
363
+ existingOrderItems.map(item => {
364
+ const matchedOrderItem = marketplaceOrderItems.find(itm => itm.name === item.name &&
365
+ itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId);
366
+ if (!matchedOrderItem) {
367
+ nonMatchedOrderItems.push(Object.assign({}, item));
368
+ }
369
+ });
370
+ if (nonMatchedOrderItems.length > 0 && !cancelStatuses.includes(marketplaceOrder.status)) {
371
+ await Promise.all(nonMatchedOrderItems.map(async (item) => {
372
+ let foundVariation = foundVariations.find(fv => fv.sku == item.marketplaceProductVariation.sku);
390
373
  if (foundVariation.sku) {
391
- let allVariations = await tx
392
- .getRepository(entities_1.MarketplaceProductVariation)
393
- .find({
394
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
395
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
396
- });
397
- let activeVariations = allVariations.filter(variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED');
398
- await Promise.all(activeVariations.map(async (variation) => {
399
- if (!(existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.releaseOrderId) && matchedOrderItem.qty - item.qty != 0) {
400
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, matchedOrderItem.qty - item.qty);
401
- }
402
- variation.reserveQty = (existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.releaseOrderId)
403
- ? variation.reserveQty
404
- : variation.reserveQty - item.qty + matchedOrderItem.qty;
405
- variation.qty = (existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.releaseOrderId)
406
- ? variation.qty
407
- : variation.qty + item.qty - matchedOrderItem.qty;
408
- variation = await tx.getRepository(entities_1.MarketplaceProductVariation).save(variation);
409
- }));
374
+ await updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, item.qty * -1);
410
375
  }
411
- }
412
- return Object.assign(Object.assign(Object.assign({}, matchedOrderItem), item), { updater: user });
376
+ }));
377
+ await tx.getRepository(entities_1.MarketplaceOrderItem).delete(nonMatchedOrderItems);
378
+ }
379
+ if (!cancelStatuses.includes(marketplaceOrder.status)) {
380
+ existingOrderItems = await Promise.all(marketplaceOrderItems.map(async (item) => {
381
+ const matchedOrderItem = existingOrderItems.find(itm => itm.name == item.name &&
382
+ itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId);
383
+ if (matchedOrderItem) {
384
+ foundVariation = foundVariations.find(fv => fv.variationId == matchedOrderItem.marketplaceProductVariation.variationId);
385
+ if (foundVariation.sku) {
386
+ await updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, item.qty, matchedOrderItem.qty, existingMarketplaceOrder);
387
+ }
388
+ return Object.assign(Object.assign(Object.assign({}, matchedOrderItem), item), { updater: user });
389
+ }
390
+ }));
391
+ }
392
+ }
393
+ else {
394
+ if (!cancelStatuses.includes(marketplaceOrder.status)) {
395
+ existingOrderItems = await Promise.all(marketplaceOrderItems.map(async (item) => {
396
+ const matchedOrderItem = existingOrderItems.find(itm => itm.name == item.name &&
397
+ itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId);
398
+ if (matchedOrderItem) {
399
+ foundVariation = foundVariations.find(fv => fv.variationId == matchedOrderItem.marketplaceProductVariation.variationId);
400
+ if (foundVariation.sku) {
401
+ await updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, item.qty, matchedOrderItem.qty, existingMarketplaceOrder);
402
+ }
403
+ return Object.assign(Object.assign(Object.assign({}, matchedOrderItem), item), { updater: user });
404
+ }
405
+ else {
406
+ let foundVariation = foundVariations.find(fv => (fv.sku = item.marketplaceProductVariation.sku));
407
+ if (foundVariation.sku) {
408
+ await updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, item.qty);
409
+ }
410
+ return Object.assign(Object.assign({}, item), { updater: user });
411
+ }
412
+ }));
413
413
  }
414
- }));
414
+ }
415
+ marketplaceOrderItems = existingOrderItems;
416
+ if (order === null || order === void 0 ? void 0 : order.orderShipping) {
417
+ savedMarketplaceOrderShipping.totalWeight = orderTotalWeight;
418
+ if (marketplaceStore.eTrax)
419
+ delete savedMarketplaceOrderShipping.trackingNo;
420
+ savedMarketplaceOrderShipping = await tx
421
+ .getRepository(entities_1.MarketplaceOrderShipping)
422
+ .save(savedMarketplaceOrderShipping);
423
+ }
415
424
  }
416
425
  }
417
426
  else {
418
427
  if (!cancelStatuses.includes(marketplaceOrder.status)) {
419
- existingOrderItems = await Promise.all(marketplaceOrderItems.map(async (item) => {
420
- const matchedOrderItem = existingOrderItems.find(itm => itm.name == item.name &&
421
- itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId);
422
- if (matchedOrderItem) {
423
- for (var foundVariation of foundVariations) {
424
- if (foundVariation.sku) {
425
- let allVariations = await tx
426
- .getRepository(entities_1.MarketplaceProductVariation)
427
- .find({
428
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
429
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
430
- });
431
- let activeVariations = allVariations.filter(variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED');
432
- await Promise.all(activeVariations.map(async (variation) => {
433
- if (!(existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.releaseOrderId) && matchedOrderItem.qty - item.qty != 0) {
434
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, matchedOrderItem.qty - item.qty);
435
- }
436
- variation.reserveQty = (existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.releaseOrderId)
437
- ? variation.reserveQty
438
- : variation.reserveQty - item.qty + matchedOrderItem.qty;
439
- variation.qty = (existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.releaseOrderId)
440
- ? variation.qty
441
- : variation.qty + item.qty - matchedOrderItem.qty;
442
- variation = await tx.getRepository(entities_1.MarketplaceProductVariation).save(variation);
443
- }));
444
- }
445
- }
446
- return Object.assign(Object.assign(Object.assign({}, matchedOrderItem), item), { updater: user });
428
+ for (var foundVariation of foundVariations) {
429
+ if (foundVariation.sku) {
430
+ let item = order.orderItems.find(e => e.variationId == foundVariation.variationId);
431
+ await updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, item.qty);
447
432
  }
448
- else {
449
- for (var foundVariation of foundVariations) {
450
- if (foundVariation.sku) {
451
- let allVariations = await tx
452
- .getRepository(entities_1.MarketplaceProductVariation)
453
- .find({
454
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
455
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
456
- });
457
- let activeVariations = allVariations.filter(variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED');
458
- await Promise.all(activeVariations.map(async (variation) => {
459
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty);
460
- variation.reserveQty += item.qty;
461
- if (variation.qty - item.qty >= 0) {
462
- variation.qty -= item.qty;
463
- }
464
- variation = await tx.getRepository(entities_1.MarketplaceProductVariation).save(variation);
465
- }));
466
- }
467
- }
468
- return Object.assign(Object.assign({}, item), { updater: user });
433
+ if (order === null || order === void 0 ? void 0 : order.orderShipping) {
434
+ savedMarketplaceOrderShipping.totalWeight = orderTotalWeight;
435
+ if (marketplaceStore.eTrax)
436
+ delete savedMarketplaceOrderShipping.trackingNo;
437
+ savedMarketplaceOrderShipping = await tx
438
+ .getRepository(entities_1.MarketplaceOrderShipping)
439
+ .save(savedMarketplaceOrderShipping);
469
440
  }
470
- }));
441
+ }
471
442
  }
472
443
  }
473
- marketplaceOrderItems = existingOrderItems;
474
- if (order === null || order === void 0 ? void 0 : order.orderShipping) {
475
- savedMarketplaceOrderShipping.totalWeight = orderTotalWeight;
476
- savedMarketplaceOrderShipping = await tx
477
- .getRepository(entities_1.MarketplaceOrderShipping)
478
- .save(savedMarketplaceOrderShipping);
479
- }
480
- }
481
- }
482
- else {
483
- if (!cancelStatuses.includes(marketplaceOrder.status)) {
484
- for (var foundVariation of foundVariations) {
485
- if (foundVariation.sku) {
486
- let allVariations = await tx
487
- .getRepository(entities_1.MarketplaceProductVariation)
488
- .find({
489
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
490
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
444
+ await tx.getRepository(entities_1.MarketplaceOrder).save(marketplaceOrder);
445
+ await tx.getRepository(entities_1.MarketplaceOrderItem).save(marketplaceOrderItems);
446
+ for (let i = 0; i < marketplaceOrderItems.length; i++) {
447
+ const marketplaceOrderItem = marketplaceOrderItems[i];
448
+ const marketplaceProductVariation = marketplaceOrderItem.marketplaceProductVariation;
449
+ let existingMarketplaceOrderShippingItems = await tx
450
+ .getRepository(entities_1.MarketplaceOrderShippingItem)
451
+ .find({
452
+ where: { domain: marketplaceStore.domain, marketplaceOrderItem }
453
+ });
454
+ let product = await tx.getRepository(product_base_1.Product).findOne({
455
+ where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku, deletedAt: (0, typeorm_1.IsNull)() },
456
+ relations: ['productDetails']
457
+ });
458
+ let productBundle;
459
+ if (!product) {
460
+ productBundle = await tx.getRepository(product_base_1.ProductBundle).findOne({
461
+ where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku },
462
+ relations: ['productBundleSettings', 'productBundleSettings.product']
491
463
  });
492
- let activeVariations = allVariations.filter(variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED');
493
- let item = order.orderItems.find(e => e.variationId == foundVariation.variationId);
494
- await Promise.all(activeVariations.map(async (variation) => {
495
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty);
496
- variation.reserveQty += item.qty;
497
- if (variation.qty - item.qty >= 0) {
498
- variation.qty -= item.qty;
499
- }
500
- variation = await tx.getRepository(entities_1.MarketplaceProductVariation).save(variation);
501
- }));
502
464
  }
503
- if (order === null || order === void 0 ? void 0 : order.orderShipping) {
504
- savedMarketplaceOrderShipping.totalWeight = orderTotalWeight;
505
- savedMarketplaceOrderShipping = await tx
506
- .getRepository(entities_1.MarketplaceOrderShipping)
507
- .save(savedMarketplaceOrderShipping);
465
+ if (existingMarketplaceOrderShippingItems && (existingMarketplaceOrderShippingItems === null || existingMarketplaceOrderShippingItems === void 0 ? void 0 : existingMarketplaceOrderShippingItems.length)) {
466
+ }
467
+ else {
468
+ if (productBundle) {
469
+ const productBundleSettings = productBundle.productBundleSettings;
470
+ let marketplaceOrderShippingItems = [];
471
+ productBundleSettings.map(productBundleSetting => {
472
+ let marketplaceOrderShippingItem = new entities_1.MarketplaceOrderShippingItem();
473
+ marketplaceOrderShippingItem.name = (0, v4_1.default)();
474
+ marketplaceOrderShippingItem.qty = marketplaceOrderItem.qty * productBundleSetting.bundleQty;
475
+ marketplaceOrderShippingItem.domain = marketplaceStore.domain;
476
+ marketplaceOrderShippingItem.marketplaceOrderItem = marketplaceOrderItem;
477
+ marketplaceOrderShippingItem.marketplaceOrderShipping = savedMarketplaceOrderShipping;
478
+ marketplaceOrderShippingItem.product = productBundleSetting.product;
479
+ marketplaceOrderShippingItems.push(marketplaceOrderShippingItem);
480
+ });
481
+ await tx.getRepository(entities_1.MarketplaceOrderShippingItem).save(marketplaceOrderShippingItems);
482
+ }
483
+ else {
484
+ let marketplaceOrderShippingItem = new entities_1.MarketplaceOrderShippingItem();
485
+ marketplaceOrderShippingItem.name = (0, v4_1.default)();
486
+ marketplaceOrderShippingItem.qty = marketplaceOrderItem.qty;
487
+ marketplaceOrderShippingItem.domain = marketplaceStore.domain;
488
+ marketplaceOrderShippingItem.marketplaceOrderItem = marketplaceOrderItem;
489
+ marketplaceOrderShippingItem.marketplaceOrderShipping = savedMarketplaceOrderShipping;
490
+ marketplaceOrderShippingItem.product = product ? product : null;
491
+ await tx.getRepository(entities_1.MarketplaceOrderShippingItem).save(marketplaceOrderShippingItem);
492
+ }
508
493
  }
509
494
  }
510
- }
511
- }
512
- await tx.getRepository(entities_1.MarketplaceOrder).save(marketplaceOrder);
513
- await tx.getRepository(entities_1.MarketplaceOrderItem).save(marketplaceOrderItems);
514
- for (let i = 0; i < marketplaceOrderItems.length; i++) {
515
- const marketplaceOrderItem = marketplaceOrderItems[i];
516
- const marketplaceProductVariation = marketplaceOrderItem.marketplaceProductVariation;
517
- let existingMarketplaceOrderShippingItems = await tx
518
- .getRepository(entities_1.MarketplaceOrderShippingItem)
519
- .find({
520
- where: { domain: marketplaceStore.domain, marketplaceOrderItem }
521
- });
522
- let product = await tx.getRepository(product_base_1.Product).findOne({
523
- where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku, deletedAt: (0, typeorm_1.IsNull)() },
524
- relations: ['productDetails']
525
- });
526
- let productBundle;
527
- if (!product) {
528
- productBundle = await tx.getRepository(product_base_1.ProductBundle).findOne({
529
- where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku },
530
- relations: ['productBundleSettings', 'productBundleSettings.product']
531
- });
532
- }
533
- if (existingMarketplaceOrderShippingItems && (existingMarketplaceOrderShippingItems === null || existingMarketplaceOrderShippingItems === void 0 ? void 0 : existingMarketplaceOrderShippingItems.length)) {
534
- }
535
- else {
536
- if (productBundle) {
537
- const productBundleSettings = productBundle.productBundleSettings;
538
- let marketplaceOrderShippingItems = [];
539
- productBundleSettings.map(productBundleSetting => {
540
- let marketplaceOrderShippingItem = new entities_1.MarketplaceOrderShippingItem();
541
- marketplaceOrderShippingItem.name = (0, v4_1.default)();
542
- marketplaceOrderShippingItem.qty = marketplaceOrderItem.qty * productBundleSetting.bundleQty;
543
- marketplaceOrderShippingItem.domain = marketplaceStore.domain;
544
- marketplaceOrderShippingItem.marketplaceOrderItem = marketplaceOrderItem;
545
- marketplaceOrderShippingItem.marketplaceOrderShipping = savedMarketplaceOrderShipping;
546
- marketplaceOrderShippingItem.product = productBundleSetting.product;
547
- marketplaceOrderShippingItems.push(marketplaceOrderShippingItem);
548
- });
549
- await tx.getRepository(entities_1.MarketplaceOrderShippingItem).save(marketplaceOrderShippingItems);
550
- }
551
- else {
552
- let marketplaceOrderShippingItem = new entities_1.MarketplaceOrderShippingItem();
553
- marketplaceOrderShippingItem.name = (0, v4_1.default)();
554
- marketplaceOrderShippingItem.qty = marketplaceOrderItem.qty;
555
- marketplaceOrderShippingItem.domain = marketplaceStore.domain;
556
- marketplaceOrderShippingItem.marketplaceOrderItem = marketplaceOrderItem;
557
- marketplaceOrderShippingItem.marketplaceOrderShipping = savedMarketplaceOrderShipping;
558
- marketplaceOrderShippingItem.product = product ? product : null;
559
- await tx.getRepository(entities_1.MarketplaceOrderShippingItem).save(marketplaceOrderShippingItem);
495
+ if (i == marketplaceOrders.length - 1) {
496
+ lastOrderId = order.name;
560
497
  }
561
498
  }
562
- }
563
- if (i == marketplaceOrders.length - 1) {
564
- lastOrderId = order.name;
565
- }
499
+ catch (e) {
500
+ env_1.logger.error(`Order no: ${marketplaceOrders[i]}: ${e}`);
501
+ }
502
+ });
566
503
  }
567
504
  if (more)
568
505
  page++;
@@ -584,46 +521,61 @@ exports.syncMarketplaceOrder = {
584
521
  pageNo++;
585
522
  hasMore = more;
586
523
  }
587
- await Promise.all(payoutDateList.map(async (item) => {
588
- await tx.getRepository(entities_1.MarketplaceOrder).update({
589
- orderNo: item.orderNo
590
- }, {
591
- payoutDate: item.payoutDate
592
- });
593
- }));
524
+ await (0, typeorm_1.getConnection)().transaction(async (tx) => {
525
+ await Promise.all(payoutDateList.map(async (item) => {
526
+ await tx.getRepository(entities_1.MarketplaceOrder).update({
527
+ orderNo: item.orderNo
528
+ }, {
529
+ payoutDate: item.payoutDate
530
+ });
531
+ }));
532
+ });
594
533
  }
595
534
  return true;
596
535
  }
597
536
  };
598
- async function calculateReserveQtyForBundle(tx, variation, domain, qty, operator = '+') {
537
+ async function updateQtyAndReserveQtyBundle(tx, variation, domain, qty, marketplaceOrder, existingMarketplaceOrder = null, matchedOrderItemQty = null) {
538
+ let statusAllowed = reserve_qty_order_statuses_1.RESERVE_QTY_ORDER_STATUSES[marketplaceOrder.marketplaceStore.platform.toUpperCase()].includes(marketplaceOrder.status);
539
+ let existingStatusNotAllowed = existingMarketplaceOrder
540
+ ? !reserve_qty_order_statuses_1.RESERVE_QTY_ORDER_STATUSES[existingMarketplaceOrder.marketplaceStore.platform.toUpperCase()].includes(existingMarketplaceOrder.status)
541
+ : false;
599
542
  const productBundle = await tx.getRepository(product_base_1.ProductBundle).findOne({
600
- where: { sku: variation.sku, domain }
543
+ where: { sku: variation.sku, domain },
544
+ relations: ['productBundleSettings', 'productBundleSettings.product']
601
545
  });
602
546
  if (productBundle) {
603
- const productBundleSettings = await tx.getRepository(product_base_1.ProductBundleSetting).find({
604
- where: { productBundle },
605
- relations: ['productBundle', 'product']
606
- });
607
- for (let setting of productBundleSettings) {
608
- const product = await tx.getRepository(product_base_1.Product).findOne({
609
- where: { id: setting.product.id }
610
- });
547
+ for (let setting of productBundle.productBundleSettings) {
611
548
  const mpvs = await tx.getRepository(entities_1.MarketplaceProductVariation).find({
612
- where: { domain, sku: product.sku },
549
+ where: { domain, sku: setting.product.sku },
613
550
  relations: ['domain']
614
551
  });
615
552
  for (let mpv of mpvs) {
616
- if (operator === '+') {
617
- mpv.reserveQty += setting.bundleQty * qty;
618
- if (mpv.qty - setting.bundleQty * qty >= 0) {
619
- mpv.qty -= setting.bundleQty * qty;
553
+ let updatedReserveQty = 0;
554
+ let updatedQty = 0;
555
+ if (existingMarketplaceOrder) {
556
+ if ((statusAllowed && existingStatusNotAllowed) ||
557
+ (cancelStatuses.includes(marketplaceOrder.status) && !existingStatusNotAllowed)) {
558
+ updatedReserveQty += setting.bundleQty * qty;
620
559
  }
560
+ updatedQty += setting.bundleQty * qty - matchedOrderItemQty * setting.bundleQty;
621
561
  }
622
- if (operator === '-') {
623
- mpv.reserveQty -= setting.bundleQty * qty;
624
- mpv.qty += setting.bundleQty * qty;
562
+ else {
563
+ if (statusAllowed && qty > 0) {
564
+ updatedReserveQty += setting.bundleQty * qty;
565
+ }
566
+ if (mpv.qty - setting.bundleQty * qty >= 0) {
567
+ updatedQty += setting.bundleQty * qty;
568
+ }
625
569
  }
626
- await tx.getRepository(entities_1.MarketplaceProductVariation).save(mpv);
570
+ await tx
571
+ .createQueryBuilder()
572
+ .update(entities_1.MarketplaceProductVariation)
573
+ .set({
574
+ qty: () => `COALESCE("qty", 0) - ${updatedQty}`,
575
+ reserveQty: () => `COALESCE("reserve_qty", 0) + ${updatedReserveQty}`
576
+ })
577
+ .where('id = :id', { id: mpv.id })
578
+ .execute();
627
579
  }
628
580
  }
629
581
  }
@@ -633,11 +585,60 @@ function checkUpdateItemId(existingOrderItems, marketplaceOrderItems) {
633
585
  let existingItem = existingOrderItems.find(i => i.name == item.name);
634
586
  if (!existingItem) {
635
587
  let existingItemByVariation = existingOrderItems.find(i => i.marketplaceProductVariation.id == item.marketplaceProductVariation.id);
636
- existingOrderItems = existingOrderItems.filter(i => i != existingItemByVariation);
637
- existingItemByVariation.name = item.name;
638
- existingOrderItems.push(existingItemByVariation);
588
+ if (existingItemByVariation) {
589
+ existingOrderItems = existingOrderItems.filter(i => i != existingItemByVariation);
590
+ existingItemByVariation.name = item.name;
591
+ existingOrderItems.push(existingItemByVariation);
592
+ }
639
593
  }
640
594
  }
641
595
  return existingOrderItems;
642
596
  }
597
+ async function updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, qty, matchedOrderItemQty = null, existingMarketplaceOrder = null) {
598
+ let roCreated = existingMarketplaceOrder ? existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.realaseOrderId : false;
599
+ let existingStatusNotAllowed = existingMarketplaceOrder
600
+ ? !reserve_qty_order_statuses_1.RESERVE_QTY_ORDER_STATUSES[existingMarketplaceOrder.marketplaceStore.platform.toUpperCase()].includes(existingMarketplaceOrder.status)
601
+ : false;
602
+ let activeVariations = await tx
603
+ .getRepository(entities_1.MarketplaceProductVariation)
604
+ .createQueryBuilder('mpv')
605
+ .innerJoin('mpv.marketplaceProduct', 'marketplaceProduct')
606
+ .innerJoin('marketplaceProduct.marketplaceStore', 'marketplaceStore')
607
+ .where('mpv.domain_id = :domainId', { domainId: marketplaceOrder.domain.id })
608
+ .andWhere('mpv.sku = :sku', { sku: foundVariation.sku })
609
+ .andWhere(`marketplaceStore.status != 'TERMINATED'`)
610
+ .getMany();
611
+ let statusAllowed = reserve_qty_order_statuses_1.RESERVE_QTY_ORDER_STATUSES[marketplaceOrder.marketplaceStore.platform.toUpperCase()].includes(marketplaceOrder.status);
612
+ if (existingMarketplaceOrder && !roCreated) {
613
+ await updateQtyAndReserveQtyBundle(tx, foundVariation, marketplaceOrder.domain, qty, marketplaceOrder, existingMarketplaceOrder, matchedOrderItemQty);
614
+ }
615
+ else {
616
+ await updateQtyAndReserveQtyBundle(tx, foundVariation, marketplaceOrder.domain, qty, marketplaceOrder);
617
+ }
618
+ await Promise.all(activeVariations.map(async (variation) => {
619
+ let updatedReserveQty = 0;
620
+ let updatedQty = 0;
621
+ if (matchedOrderItemQty) {
622
+ updatedReserveQty = roCreated ? 0 : statusAllowed && existingStatusNotAllowed ? qty : qty - matchedOrderItemQty;
623
+ updatedQty = roCreated ? 0 : qty - matchedOrderItemQty;
624
+ }
625
+ else {
626
+ if ((statusAllowed && qty > 0) || qty < 0) {
627
+ updatedReserveQty = qty;
628
+ }
629
+ if (variation.qty - qty >= 0) {
630
+ updatedQty = qty;
631
+ }
632
+ }
633
+ await tx
634
+ .createQueryBuilder()
635
+ .update(entities_1.MarketplaceProductVariation)
636
+ .set({
637
+ qty: () => `COALESCE("qty", 0) - ${updatedQty}`,
638
+ reserveQty: () => `COALESCE("reserve_qty", 0) + ${updatedReserveQty}`
639
+ })
640
+ .where('id = :id', { id: variation.id })
641
+ .execute();
642
+ }));
643
+ }
643
644
  //# sourceMappingURL=sync-marketplace-order.js.map