@things-factory/marketplace-base 4.1.27 → 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,544 +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: 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 });
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: marketplaceStore.eTrax
262
- ? existingOrderShipping.trackingNo
263
- : (marketplaceOrderShipping === null || marketplaceOrderShipping === void 0 ? void 0 : marketplaceOrderShipping.trackingNo)
264
- ? marketplaceOrderShipping.trackingNo
265
- : (existingOrderShipping === null || existingOrderShipping === void 0 ? void 0 : existingOrderShipping.trackingNo)
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
266
271
  ? existingOrderShipping.trackingNo
267
- : marketplaceOrderShipping.trackingNo, updater: user });
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;
268
286
  savedMarketplaceOrderShipping = await tx
269
287
  .getRepository(entities_1.MarketplaceOrderShipping)
270
288
  .save(marketplaceOrderShipping);
271
289
  }
272
290
  }
273
- }
274
- else {
275
- if (marketplaceStore.eTrax)
276
- delete marketplaceOrderShipping.trackingNo;
277
- savedMarketplaceOrderShipping = await tx
278
- .getRepository(entities_1.MarketplaceOrderShipping)
279
- .save(marketplaceOrderShipping);
280
- }
281
- }
282
- let orderTotalWeight = 0;
283
- let foundVariations = [];
284
- for (var j = 0; j < order.orderItems.length; j++) {
285
- var item = order.orderItems[j];
286
- let foundVariationsQuery = await tx.getRepository(entities_1.MarketplaceProductVariation).find({
287
- where: { domain: marketplaceStore.domain, variationId: item.variationId },
288
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
289
- });
290
- let foundVariation = foundVariationsQuery.filter(fv => fv.marketplaceProduct.marketplaceStore.id == marketplaceStore.id)[0];
291
- if (foundVariation) {
292
- foundVariations.push(foundVariation);
293
- }
294
- if (!foundVariation) {
295
- let newVariation = {
296
- variationId: item.variationId,
297
- name: item.variationName,
298
- variationSku: item.variationSku,
299
- channelSku: item.sku,
300
- status: 'INACTIVE',
301
- domain: marketplaceStore.domain
302
- };
303
- await tx.getRepository(entities_1.MarketplaceProductVariation).save(newVariation);
304
- foundVariation = newVariation;
305
- }
306
- let marketplaceOrderItem = new entities_1.MarketplaceOrderItem();
307
- marketplaceOrderItem.domain = marketplaceStore.domain;
308
- marketplaceOrderItem.name = item.name;
309
- marketplaceOrderItem.qty = item.qty;
310
- marketplaceOrderItem.paidPrice = item.paidPrice;
311
- marketplaceOrderItem.status = marketplaceOrder.status;
312
- marketplaceOrderItem.docRefNo = item.docRefNo;
313
- marketplaceOrderItem.marketplaceProductVariation = foundVariation;
314
- marketplaceOrderItem.trackingCode = order.trackingNo;
315
- marketplaceOrderItem.marketplaceOrder = marketplaceOrder;
316
- marketplaceOrderItem.originalPrice = item.originalPrice;
317
- marketplaceOrderItem.discount = item.discount;
318
- marketplaceOrderItem.promotionId = item.promotionId;
319
- marketplaceOrderItem.creator = user;
320
- marketplaceOrderItem.paymentFee = item.paymentFee || null;
321
- marketplaceOrderItem.commissionFee = item.commissionFee || null;
322
- marketplaceOrderItem.shippingFeePaidByCustomer = item.shippingFeePaidByCustomer || null;
323
- marketplaceOrderItem.itemPriceCredit = item.itemPriceCredit || null;
324
- marketplaceOrderItem.promotionalCharges = item.promotionalCharges || null;
325
- marketplaceOrderItem.ordersMarketplaceFeesTotal = item.ordersMarketplaceFeesTotal || null;
326
- marketplaceOrderItem.ordersSalesTotal = item.ordersSalesTotal || null;
327
- marketplaceOrderItem.ordersMarketingFeesTotal = item.ordersMarketingFeesTotal || null;
328
- marketplaceOrderItem.ordersLogisticsTotal = item.ordersLogisticsTotal || null;
329
- marketplaceOrderItem.marketplaceBonus = item.marketplaceBonus;
330
- marketplaceOrderItem.marketplaceBonusSeller = item.marketplaceBonusSeller;
331
- marketplaceOrderItem.shippingFeeDiscountMarketplace = item.shippingFeeDiscountMarketplace;
332
- marketplaceOrderItem.shippingFeeDiscountSeller = item.shippingFeeDiscountSeller;
333
- marketplaceOrderItem.promotionalChargesFlexiCombo = item.promotionalChargesFlexiCombo;
334
- marketplaceOrderItem.autoShippingSubsidyMarketplace = item.autoShippingSubsidyMarketplace;
335
- marketplaceOrderItem.originalShippingFee = item.originalShippingFee;
336
- marketplaceOrderItem.taxAmount = item.taxAmount;
337
- marketplaceOrderItems.push(Object.assign({}, marketplaceOrderItem));
338
- if (foundVariation === null || foundVariation === void 0 ? void 0 : foundVariation.primaryUnitValue)
339
- orderTotalWeight += parseFloat(foundVariation.primaryUnitValue.toFixed(3)) * item.qty || 0;
340
- }
341
- if (existingMarketplaceOrder) {
342
- let existingOrderItems = [];
343
- existingOrderItems = existingMarketplaceOrder.marketplaceOrderItems;
344
- existingOrderItems = await checkUpdateItemId(existingOrderItems, marketplaceOrderItems);
345
- if (existingMarketplaceOrder.isSplitted) {
346
- marketplaceOrderItems = existingOrderItems.filter(itm => itm.name == item.name && itm.marketplaceProductVariation.variationId == item.variationId);
347
- marketplaceOrderItems = marketplaceOrderItems.map(marketplaceOrderitem => {
348
- return Object.assign(Object.assign({}, marketplaceOrderitem), { status: order.status, trackingCode: order.trackingNo });
349
- });
350
- }
351
- else {
352
- if (existingOrderItems.length > marketplaceOrderItems.length) {
353
- let nonMatchedOrderItems = [];
354
- existingOrderItems.map(item => {
355
- const matchedOrderItem = marketplaceOrderItems.find(itm => itm.name === item.name &&
356
- itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId);
357
- if (!matchedOrderItem) {
358
- nonMatchedOrderItems.push(Object.assign({}, item));
359
- }
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']
360
298
  });
361
- if (nonMatchedOrderItems.length > 0 && !cancelStatuses.includes(marketplaceOrder.status)) {
362
- await Promise.all(nonMatchedOrderItems.map(async (item) => {
363
- for (var foundVariation of foundVariations) {
364
- if (foundVariation.sku) {
365
- let allVariations = await tx
366
- .getRepository(entities_1.MarketplaceProductVariation)
367
- .find({
368
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
369
- relations: [
370
- 'domain',
371
- 'marketplaceProduct',
372
- 'marketplaceProduct.marketplaceStore',
373
- 'marketplaceProduct.marketplaceStore.marketplaceDistributors'
374
- ]
375
- });
376
- let activeVariations = allVariations.filter(variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED');
377
- await Promise.all(activeVariations.map(async (variation) => {
378
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty, '-');
379
- variation.reserveQty -= item.qty;
380
- variation.qty += item.qty;
381
- variation = await tx.getRepository(entities_1.MarketplaceProductVariation).save(variation);
382
- }));
383
- }
384
- }
385
- }));
386
- 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);
387
302
  }
388
- if (!cancelStatuses.includes(marketplaceOrder.status)) {
389
- existingOrderItems = await Promise.all(marketplaceOrderItems.map(async (item) => {
390
- const matchedOrderItem = existingOrderItems.find(itm => itm.name == item.name &&
391
- itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId);
392
- if (matchedOrderItem) {
393
- 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);
394
373
  if (foundVariation.sku) {
395
- let allVariations = await tx
396
- .getRepository(entities_1.MarketplaceProductVariation)
397
- .find({
398
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
399
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
400
- });
401
- let activeVariations = allVariations.filter(variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED');
402
- await Promise.all(activeVariations.map(async (variation) => {
403
- if (!(existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.releaseOrderId) && matchedOrderItem.qty - item.qty != 0) {
404
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, matchedOrderItem.qty - item.qty);
405
- }
406
- variation.reserveQty = (existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.releaseOrderId)
407
- ? variation.reserveQty
408
- : variation.reserveQty - item.qty + matchedOrderItem.qty;
409
- variation.qty = (existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.releaseOrderId)
410
- ? variation.qty
411
- : variation.qty + item.qty - matchedOrderItem.qty;
412
- variation = await tx.getRepository(entities_1.MarketplaceProductVariation).save(variation);
413
- }));
374
+ await updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, item.qty * -1);
414
375
  }
415
- }
416
- 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
+ }));
417
391
  }
418
- }));
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
+ }
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
+ }
419
424
  }
420
425
  }
421
426
  else {
422
427
  if (!cancelStatuses.includes(marketplaceOrder.status)) {
423
- existingOrderItems = await Promise.all(marketplaceOrderItems.map(async (item) => {
424
- const matchedOrderItem = existingOrderItems.find(itm => itm.name == item.name &&
425
- itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId);
426
- if (matchedOrderItem) {
427
- for (var foundVariation of foundVariations) {
428
- if (foundVariation.sku) {
429
- let allVariations = await tx
430
- .getRepository(entities_1.MarketplaceProductVariation)
431
- .find({
432
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
433
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
434
- });
435
- let activeVariations = allVariations.filter(variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED');
436
- await Promise.all(activeVariations.map(async (variation) => {
437
- if (!(existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.releaseOrderId) && matchedOrderItem.qty - item.qty != 0) {
438
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, matchedOrderItem.qty - item.qty);
439
- }
440
- variation.reserveQty = (existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.releaseOrderId)
441
- ? variation.reserveQty
442
- : variation.reserveQty - item.qty + matchedOrderItem.qty;
443
- variation.qty = (existingMarketplaceOrder === null || existingMarketplaceOrder === void 0 ? void 0 : existingMarketplaceOrder.releaseOrderId)
444
- ? variation.qty
445
- : variation.qty + item.qty - matchedOrderItem.qty;
446
- variation = await tx.getRepository(entities_1.MarketplaceProductVariation).save(variation);
447
- }));
448
- }
449
- }
450
- 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);
451
432
  }
452
- else {
453
- for (var foundVariation of foundVariations) {
454
- if (foundVariation.sku) {
455
- let allVariations = await tx
456
- .getRepository(entities_1.MarketplaceProductVariation)
457
- .find({
458
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
459
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
460
- });
461
- let activeVariations = allVariations.filter(variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED');
462
- await Promise.all(activeVariations.map(async (variation) => {
463
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty);
464
- variation.reserveQty += item.qty;
465
- if (variation.qty - item.qty >= 0) {
466
- variation.qty -= item.qty;
467
- }
468
- variation = await tx.getRepository(entities_1.MarketplaceProductVariation).save(variation);
469
- }));
470
- }
471
- }
472
- 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);
473
440
  }
474
- }));
441
+ }
475
442
  }
476
443
  }
477
- marketplaceOrderItems = existingOrderItems;
478
- if (order === null || order === void 0 ? void 0 : order.orderShipping) {
479
- savedMarketplaceOrderShipping.totalWeight = orderTotalWeight;
480
- if (marketplaceStore.eTrax)
481
- delete savedMarketplaceOrderShipping.trackingNo;
482
- savedMarketplaceOrderShipping = await tx
483
- .getRepository(entities_1.MarketplaceOrderShipping)
484
- .save(savedMarketplaceOrderShipping);
485
- }
486
- }
487
- }
488
- else {
489
- if (!cancelStatuses.includes(marketplaceOrder.status)) {
490
- for (var foundVariation of foundVariations) {
491
- if (foundVariation.sku) {
492
- let allVariations = await tx
493
- .getRepository(entities_1.MarketplaceProductVariation)
494
- .find({
495
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
496
- 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']
497
463
  });
498
- let activeVariations = allVariations.filter(variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED');
499
- let item = order.orderItems.find(e => e.variationId == foundVariation.variationId);
500
- await Promise.all(activeVariations.map(async (variation) => {
501
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty);
502
- variation.reserveQty += item.qty;
503
- if (variation.qty - item.qty >= 0) {
504
- variation.qty -= item.qty;
505
- }
506
- variation = await tx.getRepository(entities_1.MarketplaceProductVariation).save(variation);
507
- }));
508
464
  }
509
- if (order === null || order === void 0 ? void 0 : order.orderShipping) {
510
- savedMarketplaceOrderShipping.totalWeight = orderTotalWeight;
511
- if (marketplaceStore.eTrax)
512
- delete savedMarketplaceOrderShipping.trackingNo;
513
- savedMarketplaceOrderShipping = await tx
514
- .getRepository(entities_1.MarketplaceOrderShipping)
515
- .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
+ }
516
493
  }
517
494
  }
518
- }
519
- }
520
- await tx.getRepository(entities_1.MarketplaceOrder).save(marketplaceOrder);
521
- await tx.getRepository(entities_1.MarketplaceOrderItem).save(marketplaceOrderItems);
522
- for (let i = 0; i < marketplaceOrderItems.length; i++) {
523
- const marketplaceOrderItem = marketplaceOrderItems[i];
524
- const marketplaceProductVariation = marketplaceOrderItem.marketplaceProductVariation;
525
- let existingMarketplaceOrderShippingItems = await tx
526
- .getRepository(entities_1.MarketplaceOrderShippingItem)
527
- .find({
528
- where: { domain: marketplaceStore.domain, marketplaceOrderItem }
529
- });
530
- let product = await tx.getRepository(product_base_1.Product).findOne({
531
- where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku, deletedAt: (0, typeorm_1.IsNull)() },
532
- relations: ['productDetails']
533
- });
534
- let productBundle;
535
- if (!product) {
536
- productBundle = await tx.getRepository(product_base_1.ProductBundle).findOne({
537
- where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku },
538
- relations: ['productBundleSettings', 'productBundleSettings.product']
539
- });
540
- }
541
- if (existingMarketplaceOrderShippingItems && (existingMarketplaceOrderShippingItems === null || existingMarketplaceOrderShippingItems === void 0 ? void 0 : existingMarketplaceOrderShippingItems.length)) {
542
- }
543
- else {
544
- if (productBundle) {
545
- const productBundleSettings = productBundle.productBundleSettings;
546
- let marketplaceOrderShippingItems = [];
547
- productBundleSettings.map(productBundleSetting => {
548
- let marketplaceOrderShippingItem = new entities_1.MarketplaceOrderShippingItem();
549
- marketplaceOrderShippingItem.name = (0, v4_1.default)();
550
- marketplaceOrderShippingItem.qty = marketplaceOrderItem.qty * productBundleSetting.bundleQty;
551
- marketplaceOrderShippingItem.domain = marketplaceStore.domain;
552
- marketplaceOrderShippingItem.marketplaceOrderItem = marketplaceOrderItem;
553
- marketplaceOrderShippingItem.marketplaceOrderShipping = savedMarketplaceOrderShipping;
554
- marketplaceOrderShippingItem.product = productBundleSetting.product;
555
- marketplaceOrderShippingItems.push(marketplaceOrderShippingItem);
556
- });
557
- await tx.getRepository(entities_1.MarketplaceOrderShippingItem).save(marketplaceOrderShippingItems);
558
- }
559
- else {
560
- let marketplaceOrderShippingItem = new entities_1.MarketplaceOrderShippingItem();
561
- marketplaceOrderShippingItem.name = (0, v4_1.default)();
562
- marketplaceOrderShippingItem.qty = marketplaceOrderItem.qty;
563
- marketplaceOrderShippingItem.domain = marketplaceStore.domain;
564
- marketplaceOrderShippingItem.marketplaceOrderItem = marketplaceOrderItem;
565
- marketplaceOrderShippingItem.marketplaceOrderShipping = savedMarketplaceOrderShipping;
566
- marketplaceOrderShippingItem.product = product ? product : null;
567
- await tx.getRepository(entities_1.MarketplaceOrderShippingItem).save(marketplaceOrderShippingItem);
495
+ if (i == marketplaceOrders.length - 1) {
496
+ lastOrderId = order.name;
568
497
  }
569
498
  }
570
- }
571
- if (i == marketplaceOrders.length - 1) {
572
- lastOrderId = order.name;
573
- }
499
+ catch (e) {
500
+ env_1.logger.error(`Order no: ${marketplaceOrders[i]}: ${e}`);
501
+ }
502
+ });
574
503
  }
575
504
  if (more)
576
505
  page++;
@@ -592,46 +521,61 @@ exports.syncMarketplaceOrder = {
592
521
  pageNo++;
593
522
  hasMore = more;
594
523
  }
595
- await Promise.all(payoutDateList.map(async (item) => {
596
- await tx.getRepository(entities_1.MarketplaceOrder).update({
597
- orderNo: item.orderNo
598
- }, {
599
- payoutDate: item.payoutDate
600
- });
601
- }));
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
+ });
602
533
  }
603
534
  return true;
604
535
  }
605
536
  };
606
- 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;
607
542
  const productBundle = await tx.getRepository(product_base_1.ProductBundle).findOne({
608
- where: { sku: variation.sku, domain }
543
+ where: { sku: variation.sku, domain },
544
+ relations: ['productBundleSettings', 'productBundleSettings.product']
609
545
  });
610
546
  if (productBundle) {
611
- const productBundleSettings = await tx.getRepository(product_base_1.ProductBundleSetting).find({
612
- where: { productBundle },
613
- relations: ['productBundle', 'product']
614
- });
615
- for (let setting of productBundleSettings) {
616
- const product = await tx.getRepository(product_base_1.Product).findOne({
617
- where: { id: setting.product.id }
618
- });
547
+ for (let setting of productBundle.productBundleSettings) {
619
548
  const mpvs = await tx.getRepository(entities_1.MarketplaceProductVariation).find({
620
- where: { domain, sku: product.sku },
549
+ where: { domain, sku: setting.product.sku },
621
550
  relations: ['domain']
622
551
  });
623
552
  for (let mpv of mpvs) {
624
- if (operator === '+') {
625
- mpv.reserveQty += setting.bundleQty * qty;
626
- if (mpv.qty - setting.bundleQty * qty >= 0) {
627
- 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;
628
559
  }
560
+ updatedQty += setting.bundleQty * qty - matchedOrderItemQty * setting.bundleQty;
629
561
  }
630
- if (operator === '-') {
631
- mpv.reserveQty -= setting.bundleQty * qty;
632
- 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
+ }
633
569
  }
634
- 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();
635
579
  }
636
580
  }
637
581
  }
@@ -641,11 +585,60 @@ function checkUpdateItemId(existingOrderItems, marketplaceOrderItems) {
641
585
  let existingItem = existingOrderItems.find(i => i.name == item.name);
642
586
  if (!existingItem) {
643
587
  let existingItemByVariation = existingOrderItems.find(i => i.marketplaceProductVariation.id == item.marketplaceProductVariation.id);
644
- existingOrderItems = existingOrderItems.filter(i => i != existingItemByVariation);
645
- existingItemByVariation.name = item.name;
646
- existingOrderItems.push(existingItemByVariation);
588
+ if (existingItemByVariation) {
589
+ existingOrderItems = existingOrderItems.filter(i => i != existingItemByVariation);
590
+ existingItemByVariation.name = item.name;
591
+ existingOrderItems.push(existingItemByVariation);
592
+ }
647
593
  }
648
594
  }
649
595
  return existingOrderItems;
650
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
+ }
651
644
  //# sourceMappingURL=sync-marketplace-order.js.map