@things-factory/marketplace-base 4.1.27 → 4.1.31

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,544 +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: 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)
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
266
275
  ? existingOrderShipping.trackingNo
267
- : marketplaceOrderShipping.trackingNo, updater: user });
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;
268
290
  savedMarketplaceOrderShipping = await tx
269
291
  .getRepository(entities_1.MarketplaceOrderShipping)
270
292
  .save(marketplaceOrderShipping);
271
293
  }
272
294
  }
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
- }
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']
360
302
  });
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);
303
+ let foundVariation = foundVariationsQuery.filter(fv => fv.marketplaceProduct.marketplaceStore.id == marketplaceStore.id)[0];
304
+ if (foundVariation) {
305
+ foundVariations.push(foundVariation);
387
306
  }
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) {
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);
394
377
  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
- }));
378
+ await updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, item.qty * -1);
414
379
  }
415
- }
416
- 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
+ }));
417
417
  }
418
- }));
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
+ }
419
428
  }
420
429
  }
421
430
  else {
422
431
  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 });
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);
451
436
  }
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 });
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);
473
444
  }
474
- }));
445
+ }
475
446
  }
476
447
  }
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']
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']
497
467
  });
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
468
  }
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);
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
+ }
516
497
  }
517
498
  }
499
+ if (i == marketplaceOrders.length - 1) {
500
+ lastOrderId = order.name;
501
+ }
518
502
  }
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);
503
+ catch (e) {
504
+ if (scheduler) {
505
+ env_1.logger.error(`Order no: ${marketplaceOrders[i].name}: ${e}`);
558
506
  }
559
507
  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);
508
+ throw new Error(e);
568
509
  }
569
510
  }
570
- }
571
- if (i == marketplaceOrders.length - 1) {
572
- lastOrderId = order.name;
573
- }
511
+ });
574
512
  }
575
513
  if (more)
576
514
  page++;
@@ -592,46 +530,61 @@ exports.syncMarketplaceOrder = {
592
530
  pageNo++;
593
531
  hasMore = more;
594
532
  }
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
- }));
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
+ });
602
542
  }
603
543
  return true;
604
544
  }
605
545
  };
606
- 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;
607
551
  const productBundle = await tx.getRepository(product_base_1.ProductBundle).findOne({
608
- where: { sku: variation.sku, domain }
552
+ where: { sku: variation.sku, domain },
553
+ relations: ['productBundleSettings', 'productBundleSettings.product']
609
554
  });
610
555
  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
- });
556
+ for (let setting of productBundle.productBundleSettings) {
619
557
  const mpvs = await tx.getRepository(entities_1.MarketplaceProductVariation).find({
620
- where: { domain, sku: product.sku },
558
+ where: { domain, sku: setting.product.sku },
621
559
  relations: ['domain']
622
560
  });
623
561
  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;
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;
628
568
  }
569
+ updatedQty += setting.bundleQty * qty - matchedOrderItemQty * setting.bundleQty;
629
570
  }
630
- if (operator === '-') {
631
- mpv.reserveQty -= setting.bundleQty * qty;
632
- 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
+ }
633
578
  }
634
- 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();
635
588
  }
636
589
  }
637
590
  }
@@ -641,11 +594,60 @@ function checkUpdateItemId(existingOrderItems, marketplaceOrderItems) {
641
594
  let existingItem = existingOrderItems.find(i => i.name == item.name);
642
595
  if (!existingItem) {
643
596
  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);
597
+ if (existingItemByVariation) {
598
+ existingOrderItems = existingOrderItems.filter(i => i != existingItemByVariation);
599
+ existingItemByVariation.name = item.name;
600
+ existingOrderItems.push(existingItemByVariation);
601
+ }
647
602
  }
648
603
  }
649
604
  return existingOrderItems;
650
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
+ }
651
653
  //# sourceMappingURL=sync-marketplace-order.js.map