@things-factory/marketplace-base 4.1.22 → 4.1.29

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