@things-factory/marketplace-base 4.1.19 → 4.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { EntityManager, IsNull } from 'typeorm'
1
+ import { EntityManager, IsNull, getConnection, SelectQueryBuilder } from 'typeorm'
2
2
  import uuid from 'uuid/v4'
3
3
 
4
4
  import { User } from '@things-factory/auth-base'
@@ -7,6 +7,7 @@ import { FulfillmentAPI, FulfillmentCenter } from '@things-factory/integration-f
7
7
  import { MarketplaceStore, StoreAPI } from '@things-factory/integration-marketplace'
8
8
  import { Product, ProductBundle, ProductBundleSetting } from '@things-factory/product-base'
9
9
  import { Domain } from '@things-factory/shell'
10
+ import { logger } from '@things-factory/env'
10
11
 
11
12
  import {
12
13
  MarketplaceOrder,
@@ -16,10 +17,22 @@ import {
16
17
  MarketplaceProductVariation
17
18
  } from '../../../entities'
18
19
  import { NoGenerator } from '../../../utils'
20
+ import { RESERVE_QTY_ORDER_STATUSES } from '../../../constants/reserve-qty-order-statuses'
21
+
22
+ const cancelStatuses: string[] = [
23
+ 'cancelled',
24
+ 'canceled',
25
+ 'failed',
26
+ 'shipped_back_success',
27
+ 'shipped_back',
28
+ 'returned',
29
+ 'to_return',
30
+ 'refunded'
31
+ ]
19
32
 
20
33
  export const syncMarketplaceOrder = {
21
34
  async syncMarketplaceOrder(_: any, { storeId, fromDate, toDate }, context: any) {
22
- const { domain, user, tx }: { domain: Domain; user: User; tx: EntityManager } = context.state
35
+ const { domain, user }: { domain: Domain; user: User; tx: EntityManager } = context.state
23
36
 
24
37
  const marketplaceStore: MarketplaceStore = await StoreAPI.getMarketplaceStore(storeId)
25
38
 
@@ -27,7 +40,6 @@ export const syncMarketplaceOrder = {
27
40
  let hasMorePage: boolean = true
28
41
  let lastOrderId: string
29
42
  var limit: number = 100
30
- const cancelStatuses: string[] = ['cancelled', 'canceled']
31
43
  const disallowCancelStatuses: string[] = ['CANCELLED', 'PENDING_CANCEL']
32
44
 
33
45
  while (hasMorePage) {
@@ -39,713 +51,608 @@ export const syncMarketplaceOrder = {
39
51
  })
40
52
 
41
53
  if (marketplaceOrders?.length == 0) throw new Error('There is no order available to sync')
42
-
43
54
  for (var i = 0; i < marketplaceOrders.length; i++) {
44
- var order = marketplaceOrders[i]
45
-
46
- let marketplaceOrderItems = []
47
- let tracking_code = ''
48
- let deliveryProvider: string
49
- let dropPickProvider: string
50
-
51
- if (marketplaceStore.platform == 'lazada') {
52
- if (order.trackingNo != '') {
53
- tracking_code = JSON.parse(order.trackingNo)
54
- .reduce((newItem, item) => {
55
- if (newItem.indexOf(item.tracking_code) < 0) {
56
- newItem.push(item.tracking_code)
57
- }
58
- return newItem
59
- }, [])
60
- .join(',')
61
- }
62
-
63
- const shippingProviderInfo: any = {}
64
- order.shippingProvider.split(', ').forEach(s => {
65
- var [key, value] = s.split(': ')
66
- shippingProviderInfo[key] = value
67
- })
68
-
69
- dropPickProvider = shippingProviderInfo?.Pickup
70
- ? shippingProviderInfo['Pickup']
71
- : shippingProviderInfo['Drop-off']
72
- deliveryProvider = shippingProviderInfo['Delivery']
73
- }
74
-
75
- let marketplaceOrder: MarketplaceOrder = new MarketplaceOrder()
76
- marketplaceOrder.name = order.name
77
- marketplaceOrder.orderNo = order.orderNo
78
- marketplaceOrder.itemCount = order.itemCount
79
- marketplaceOrder.totalAmount = order.totalAmount
80
- marketplaceOrder.status = order.status
81
- marketplaceOrder.remark = order?.remark
82
- marketplaceOrder.trackingNo = tracking_code ? tracking_code : order.trackingNo
83
- marketplaceOrder.shippingProvider = order.shippingProvider
84
- marketplaceOrder.orderCreatedAt = order.orderCreatedAt
85
- marketplaceOrder.orderUpdatedAt = order.orderUpdatedAt
86
- marketplaceOrder.marketplaceStore = marketplaceStore
87
- marketplaceOrder.domain = marketplaceStore.domain
88
- marketplaceOrder.buyerUsername = order.buyerUsername
89
- marketplaceOrder.payTime = order.payTime
90
- marketplaceOrder.serviceFee = order.serviceFee
91
- marketplaceOrder.commissionFee = order.commissionFee
92
- marketplaceOrder.transactionFee = order.transactionFee
93
- marketplaceOrder.shippingMode = order.shippingMode
94
- marketplaceOrder.voucherAmount = order.voucherAmount
95
- marketplaceOrder.totalRealeasedAmount = order.totalRealeasedAmount
96
- marketplaceOrder.voucherCode = order.voucherCode
97
- marketplaceOrder.shippingRebate = order.shippingRebate
98
-
99
- const existingMarketplaceOrder: MarketplaceOrder = await tx.getRepository(MarketplaceOrder).findOne({
100
- where: { domain: marketplaceStore.domain, name: order.name },
101
- relations: [
102
- 'domain',
103
- 'fulfillmentCenter',
104
- 'marketplaceOrderItems',
105
- 'marketplaceOrderItems.marketplaceOrderShippingItems',
106
- 'marketplaceOrderItems.marketplaceOrderShippingItems.marketplaceOrderShipping',
107
- 'marketplaceOrderItems.marketplaceProductVariation'
108
- ]
109
- })
110
-
111
- if (existingMarketplaceOrder) {
112
- let otherInfoJSON: any = {}
113
-
114
- if (existingMarketplaceOrder?.otherInfoJSON && deliveryProvider) {
115
- otherInfoJSON = JSON.parse(existingMarketplaceOrder.otherInfoJSON)
116
- otherInfoJSON.shippingProvider = deliveryProvider
117
- }
118
-
119
- marketplaceOrder = {
120
- ...existingMarketplaceOrder,
121
- ...marketplaceOrder,
122
- otherInfoJSON: otherInfoJSON ? JSON.stringify(otherInfoJSON) : null,
123
- updater: user
124
- }
55
+ await getConnection().transaction(async tx => {
56
+ try {
57
+ var order = marketplaceOrders[i]
58
+
59
+ let marketplaceOrderItems = []
60
+ let tracking_code = ''
61
+ let deliveryProvider: string
62
+ let dropPickProvider: string
63
+
64
+ if (marketplaceStore.platform == 'lazada') {
65
+ if (order.trackingNo != '') {
66
+ tracking_code = JSON.parse(order.trackingNo)
67
+ .reduce((newItem, item) => {
68
+ if (newItem.indexOf(item.tracking_code) < 0) {
69
+ newItem.push(item.tracking_code)
70
+ }
71
+ return newItem
72
+ }, [])
73
+ .join(',')
74
+ }
125
75
 
126
- if (
127
- !marketplaceOrder?.releaseOrderId &&
128
- cancelStatuses.includes(marketplaceOrder.status) &&
129
- !cancelStatuses.includes(existingMarketplaceOrder.status)
130
- ) {
131
- for (let item of marketplaceOrder.marketplaceOrderItems) {
132
- let foundVariations = await tx.getRepository(MarketplaceProductVariation).find({
133
- where: { domain: marketplaceOrder.domain, sku: item.marketplaceProductVariation.sku },
134
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
76
+ const shippingProviderInfo: any = {}
77
+ order.shippingProvider.split(', ').forEach(s => {
78
+ var [key, value] = s.split(': ')
79
+ shippingProviderInfo[key] = value
135
80
  })
136
81
 
137
- let activeVariations: MarketplaceProductVariation[] = foundVariations.filter(
138
- variation =>
139
- variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED' && variation.sku != null
140
- )
141
-
142
- await Promise.all(
143
- activeVariations.map(async variation => {
144
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty, '-')
145
-
146
- variation.reserveQty -= item.qty
147
- variation.qty += item.qty
148
- await tx.getRepository(MarketplaceProductVariation).save(variation)
149
- })
150
- )
82
+ dropPickProvider = shippingProviderInfo?.Pickup
83
+ ? shippingProviderInfo['Pickup']
84
+ : shippingProviderInfo['Drop-off']
85
+ deliveryProvider = shippingProviderInfo['Delivery']
151
86
  }
152
- }
153
87
 
154
- if (marketplaceOrder?.releaseOrderId) {
155
- const fulfillmentCenter: FulfillmentCenter = marketplaceOrder.fulfillmentCenter
156
- const centerId: string = fulfillmentCenter.centerId
157
- const warehouseDomain: Domain = await tx.getRepository(Domain).findOne({ where: { subdomain: centerId } })
158
- const customerBizplaces: Bizplace[] = await getCustomerBizplaces(warehouseDomain)
159
- const customerBizplaceId: string = customerBizplaces.find(
160
- customerBizplace => customerBizplace.company.domain.id == domain.id
161
- ).id
162
-
163
- let { items: releaseOrders }: any = await FulfillmentAPI.getOutboundOrders(fulfillmentCenter, {
164
- customerBizplaceId,
165
- refNo: marketplaceOrder.orderNo
88
+ let marketplaceOrder: MarketplaceOrder = new MarketplaceOrder()
89
+ marketplaceOrder.name = order.name
90
+ marketplaceOrder.orderNo = order.orderNo
91
+ marketplaceOrder.itemCount = order.itemCount
92
+ marketplaceOrder.totalAmount = order.totalAmount
93
+ marketplaceOrder.status = order.status
94
+ marketplaceOrder.remark = order?.remark
95
+ marketplaceOrder.trackingNo = tracking_code ? tracking_code : order.trackingNo
96
+ marketplaceOrder.shippingProvider = order.shippingProvider
97
+ marketplaceOrder.orderCreatedAt = order.orderCreatedAt
98
+ marketplaceOrder.orderUpdatedAt = order.orderUpdatedAt
99
+ marketplaceOrder.marketplaceStore = marketplaceStore
100
+ marketplaceOrder.domain = marketplaceStore.domain
101
+ marketplaceOrder.buyerUsername = order.buyerUsername
102
+ marketplaceOrder.payTime = order.payTime
103
+ marketplaceOrder.serviceFee = order.serviceFee
104
+ marketplaceOrder.commissionFee = order.commissionFee
105
+ marketplaceOrder.transactionFee = order.transactionFee
106
+ marketplaceOrder.shippingMode = order.shippingMode
107
+ marketplaceOrder.voucherAmount = order.voucherAmount
108
+ marketplaceOrder.totalRealeasedAmount = order.totalRealeasedAmount
109
+ marketplaceOrder.voucherCode = order.voucherCode
110
+ marketplaceOrder.shippingRebate = order.shippingRebate
111
+
112
+ const existingMarketplaceOrder: MarketplaceOrder = await tx.getRepository(MarketplaceOrder).findOne({
113
+ where: { domain: marketplaceStore.domain, name: order.name },
114
+ relations: [
115
+ 'domain',
116
+ 'fulfillmentCenter',
117
+ 'marketplaceOrderItems',
118
+ 'marketplaceOrderItems.marketplaceOrderShippingItems',
119
+ 'marketplaceOrderItems.marketplaceOrderShippingItems.marketplaceOrderShipping',
120
+ 'marketplaceOrderItems.marketplaceProductVariation',
121
+ 'marketplaceStore'
122
+ ]
166
123
  })
167
124
 
168
- if (existingMarketplaceOrder.isSplitted) {
169
- for (let a = 0; a < releaseOrders.length; a++) {
170
- const releaseOrder: any = releaseOrders[a]
171
- const foundMarketplaceOrderShipping: MarketplaceOrderShipping = await tx
172
- .getRepository(MarketplaceOrderShipping)
173
- .findOne({
174
- where: { domain: marketplaceStore.domain, subOrderNoRef: releaseOrder.refNo2 }
175
- })
176
- let patch = {
177
- id: releaseOrder.id,
178
- marketplaceOrderStatus: marketplaceOrder.status,
179
- trackingNo: foundMarketplaceOrderShipping?.trackingNo == '[]'
180
- ? foundMarketplaceOrderShipping.ownTrackingNo :
181
- foundMarketplaceOrderShipping?.trackingNo
182
- ? foundMarketplaceOrderShipping.trackingNo
183
- : foundMarketplaceOrderShipping.ownTrackingNo,
184
- transporter: dropPickProvider ? dropPickProvider : marketplaceOrder.shippingProvider
185
- }
125
+ if (existingMarketplaceOrder) {
126
+ let otherInfoJSON: any = {}
186
127
 
187
- await FulfillmentAPI.updateReleaseGoodDetails(fulfillmentCenter, {
188
- customerBizplaceId,
189
- releaseOrder: { ...patch },
190
- shippingOrder: null
191
- })
192
- }
193
- } else {
194
- let releaseOrder = Object.assign({}, releaseOrders[0])
195
- const foundMarketplaceOrderShipping: MarketplaceOrderShipping = await tx
196
- .getRepository(MarketplaceOrderShipping)
197
- .findOne({
198
- where: { domain: marketplaceStore.domain, orderNoRef: releaseOrder.refNo }
199
- })
200
- let patch = {
201
- id: releaseOrder.id,
202
- marketplaceOrderStatus: marketplaceOrder.status,
203
- trackingNo: foundMarketplaceOrderShipping?.trackingNo == '[]'
204
- ? foundMarketplaceOrderShipping.ownTrackingNo :
205
- foundMarketplaceOrderShipping?.trackingNo
206
- ? foundMarketplaceOrderShipping.trackingNo
207
- : foundMarketplaceOrderShipping.ownTrackingNo,
208
- transporter: dropPickProvider ? dropPickProvider : marketplaceOrder.shippingProvider
128
+ if (existingMarketplaceOrder?.otherInfoJSON && deliveryProvider) {
129
+ otherInfoJSON = JSON.parse(existingMarketplaceOrder.otherInfoJSON)
130
+ otherInfoJSON.shippingProvider = deliveryProvider
209
131
  }
210
132
 
211
- await FulfillmentAPI.updateReleaseGoodDetails(fulfillmentCenter, {
212
- customerBizplaceId,
213
- releaseOrder: { ...patch },
214
- shippingOrder: null
215
- })
216
- }
217
-
218
- if (cancelStatuses.includes(marketplaceOrder.status)) {
219
- if (existingMarketplaceOrder.isSplitted) {
220
- releaseOrders = releaseOrders.filter(function (order) {
221
- return !disallowCancelStatuses.includes(order.status)
222
- })
133
+ marketplaceOrder = {
134
+ ...existingMarketplaceOrder,
135
+ ...marketplaceOrder,
136
+ otherInfoJSON: otherInfoJSON ? JSON.stringify(otherInfoJSON) : null,
137
+ updater: user
138
+ }
223
139
 
224
- if (releaseOrders?.length) {
225
- for (let a = 0; a < releaseOrders.length; a++) {
226
- const releaseOrderId: string = releaseOrders[a].id
227
- await FulfillmentAPI.cancelReleaseOrder(fulfillmentCenter, { customerBizplaceId, releaseOrderId })
228
- }
140
+ if (
141
+ !marketplaceOrder?.releaseOrderId &&
142
+ RESERVE_QTY_ORDER_STATUSES[marketplaceOrder.marketplaceStore.platform.toUpperCase()].includes(
143
+ existingMarketplaceOrder.status
144
+ ) &&
145
+ cancelStatuses.includes(marketplaceOrder.status)
146
+ ) {
147
+ for (let item of marketplaceOrder.marketplaceOrderItems) {
148
+ await updateQtyAndReserveQty(
149
+ tx,
150
+ item.marketplaceProductVariation,
151
+ marketplaceOrder,
152
+ item.qty * -1,
153
+ null,
154
+ existingMarketplaceOrder
155
+ )
229
156
  }
230
- } else {
157
+ }
158
+
159
+ if (marketplaceOrder?.releaseOrderId) {
231
160
  const fulfillmentCenter: FulfillmentCenter = marketplaceOrder.fulfillmentCenter
232
161
  const centerId: string = fulfillmentCenter.centerId
233
-
234
162
  const warehouseDomain: Domain = await tx
235
163
  .getRepository(Domain)
236
164
  .findOne({ where: { subdomain: centerId } })
237
165
  const customerBizplaces: Bizplace[] = await getCustomerBizplaces(warehouseDomain)
238
- const customerBizplaceId: string = customerBizplaces[0].id
166
+ const customerBizplaceId: string = customerBizplaces.find(
167
+ customerBizplace => customerBizplace.company.domain.id == domain.id
168
+ ).id
239
169
 
240
- const { items: releaseOrders }: any = await FulfillmentAPI.getOutboundOrders(fulfillmentCenter, {
170
+ let { items: releaseOrders }: any = await FulfillmentAPI.getOutboundOrders(fulfillmentCenter, {
241
171
  customerBizplaceId,
242
172
  refNo: marketplaceOrder.orderNo
243
173
  })
244
174
 
245
- const releaseOrderStatus = releaseOrders[0].status
175
+ if (existingMarketplaceOrder.isSplitted) {
176
+ for (let a = 0; a < releaseOrders.length; a++) {
177
+ const releaseOrder: any = releaseOrders[a]
178
+ const foundMarketplaceOrderShipping: MarketplaceOrderShipping = await tx
179
+ .getRepository(MarketplaceOrderShipping)
180
+ .findOne({
181
+ where: { domain: marketplaceStore.domain, subOrderNoRef: releaseOrder.refNo2 }
182
+ })
183
+ let patch = {
184
+ id: releaseOrder.id,
185
+ marketplaceOrderStatus: marketplaceOrder.status,
186
+ trackingNo:
187
+ foundMarketplaceOrderShipping?.trackingNo == '[]'
188
+ ? foundMarketplaceOrderShipping.ownTrackingNo
189
+ : foundMarketplaceOrderShipping?.trackingNo
190
+ ? foundMarketplaceOrderShipping.trackingNo
191
+ : foundMarketplaceOrderShipping.ownTrackingNo,
192
+ transporter: dropPickProvider ? dropPickProvider : marketplaceOrder.shippingProvider
193
+ }
194
+
195
+ await FulfillmentAPI.updateReleaseGoodDetails(fulfillmentCenter, {
196
+ customerBizplaceId,
197
+ releaseOrder: { ...patch },
198
+ shippingOrder: null
199
+ })
200
+ }
201
+ } else {
202
+ let releaseOrder = Object.assign({}, releaseOrders[0])
203
+ const foundMarketplaceOrderShipping: MarketplaceOrderShipping = await tx
204
+ .getRepository(MarketplaceOrderShipping)
205
+ .findOne({
206
+ where: { domain: marketplaceStore.domain, orderNoRef: releaseOrder.refNo }
207
+ })
208
+ let patch = {
209
+ id: releaseOrder.id,
210
+ marketplaceOrderStatus: marketplaceOrder.status,
211
+ trackingNo:
212
+ foundMarketplaceOrderShipping?.trackingNo == '[]'
213
+ ? foundMarketplaceOrderShipping.ownTrackingNo
214
+ : foundMarketplaceOrderShipping?.trackingNo
215
+ ? foundMarketplaceOrderShipping.trackingNo
216
+ : foundMarketplaceOrderShipping.ownTrackingNo,
217
+ transporter: dropPickProvider ? dropPickProvider : marketplaceOrder.shippingProvider
218
+ }
246
219
 
247
- if (!disallowCancelStatuses.includes(releaseOrderStatus)) {
248
- await FulfillmentAPI.cancelReleaseOrder(fulfillmentCenter, {
220
+ await FulfillmentAPI.updateReleaseGoodDetails(fulfillmentCenter, {
249
221
  customerBizplaceId,
250
- releaseOrderId: releaseOrders[0].id
222
+ releaseOrder: { ...patch },
223
+ shippingOrder: null
251
224
  })
252
225
  }
226
+
227
+ if (cancelStatuses.includes(marketplaceOrder.status)) {
228
+ if (existingMarketplaceOrder.isSplitted) {
229
+ releaseOrders = releaseOrders.filter(function (order) {
230
+ return !disallowCancelStatuses.includes(order.status)
231
+ })
232
+
233
+ if (releaseOrders?.length) {
234
+ for (let a = 0; a < releaseOrders.length; a++) {
235
+ const releaseOrderId: string = releaseOrders[a].id
236
+ await FulfillmentAPI.cancelReleaseOrder(fulfillmentCenter, {
237
+ customerBizplaceId,
238
+ releaseOrderId
239
+ })
240
+ }
241
+ }
242
+ } else {
243
+ const fulfillmentCenter: FulfillmentCenter = marketplaceOrder.fulfillmentCenter
244
+ const centerId: string = fulfillmentCenter.centerId
245
+
246
+ const warehouseDomain: Domain = await tx
247
+ .getRepository(Domain)
248
+ .findOne({ where: { subdomain: centerId } })
249
+ const customerBizplaces: Bizplace[] = await getCustomerBizplaces(warehouseDomain)
250
+ const customerBizplaceId: string = customerBizplaces[0].id
251
+
252
+ const { items: releaseOrders }: any = await FulfillmentAPI.getOutboundOrders(fulfillmentCenter, {
253
+ customerBizplaceId,
254
+ refNo: marketplaceOrder.orderNo
255
+ })
256
+
257
+ const releaseOrderStatus = releaseOrders[0].status
258
+
259
+ if (!disallowCancelStatuses.includes(releaseOrderStatus)) {
260
+ await FulfillmentAPI.cancelReleaseOrder(fulfillmentCenter, {
261
+ customerBizplaceId,
262
+ releaseOrderId: releaseOrders[0].id
263
+ })
264
+ }
265
+ }
266
+ }
253
267
  }
254
268
  }
255
- }
256
- }
257
269
 
258
- let savedMarketplaceOrderShipping: MarketplaceOrderShipping = new MarketplaceOrderShipping()
259
- let savedMarketplaceOrderShippings: MarketplaceOrderShipping[] = []
260
-
261
- if (order?.orderShipping) {
262
- const orderShipping: any = order.orderShipping
263
-
264
- let marketplaceOrderShipping: MarketplaceOrderShipping = new MarketplaceOrderShipping()
265
- marketplaceOrderShipping.name = NoGenerator.orderShipping()
266
- marketplaceOrderShipping.address1 = orderShipping.address1
267
- marketplaceOrderShipping.address2 = orderShipping.address2
268
- marketplaceOrderShipping.address3 = orderShipping.address3
269
- marketplaceOrderShipping.address4 = orderShipping.address4
270
- marketplaceOrderShipping.address5 = orderShipping.address5
271
- marketplaceOrderShipping.attentionTo = orderShipping.attentionTo
272
- marketplaceOrderShipping.city = orderShipping.city
273
- marketplaceOrderShipping.country = orderShipping.country
274
- marketplaceOrderShipping.state = orderShipping?.state || null
275
- marketplaceOrderShipping.postCode = orderShipping.postCode
276
- marketplaceOrderShipping.phone1 = orderShipping.phone1
277
- marketplaceOrderShipping.phone2 = orderShipping.phone2
278
- marketplaceOrderShipping.trackingNo = order?.trackingNo || null
279
- marketplaceOrderShipping.orderNoRef = marketplaceOrder.orderNo
280
- marketplaceOrderShipping.subOrderNoRef = marketplaceOrder.orderNo
281
- marketplaceOrderShipping.marketplaceStore = marketplaceStore
282
- marketplaceOrderShipping.creator = user
283
- marketplaceOrderShipping.domain = marketplaceStore.domain
284
- marketplaceOrderShipping.shippingFee = orderShipping.shippingFee
285
- marketplaceOrderShipping.actualShippingFee = orderShipping.actualShippingFee
286
- marketplaceOrderShipping.marketplaceShippingFeeVoucher = orderShipping.marketplaceShippingFeeVoucher
287
- marketplaceOrderShipping.sellerShippingFeeVoucher = orderShipping.sellerShippingFeeVoucher
288
-
289
- if (existingMarketplaceOrder) {
290
- if (existingMarketplaceOrder.isSplitted) {
291
- let existingOrderShippings: MarketplaceOrderShipping[] = await tx
292
- .getRepository(MarketplaceOrderShipping)
293
- .find({
294
- where: { domain, marketplaceStore, orderNoRef: marketplaceOrder.orderNo }
295
- })
270
+ let savedMarketplaceOrderShipping: MarketplaceOrderShipping = new MarketplaceOrderShipping()
271
+ let savedMarketplaceOrderShippings: MarketplaceOrderShipping[] = []
296
272
 
297
- existingOrderShippings = existingOrderShippings.map(item => {
298
- return {
299
- ...item,
300
- address1: orderShipping.address1,
301
- address2: orderShipping.address2,
302
- address3: orderShipping.address3,
303
- address4: orderShipping.address4,
304
- address5: orderShipping.address5,
305
- attentionTo: orderShipping.attentionTo,
306
- city: orderShipping.city,
307
- country: orderShipping.country,
308
- state: orderShipping?.state,
309
- postCode: orderShipping.postCode,
310
- phone1: orderShipping.phone1,
311
- phone2: orderShipping.phone2,
312
- email: orderShipping?.email,
313
- trackingNo: order?.trackingNo,
314
- shippingFee: orderShipping.shippingFee,
315
- actualShippingFee: orderShipping.actualShippingFee,
316
- marketplaceShippingFeeVoucher: orderShipping.marketplaceShippingFeeVoucher,
317
- sellerShippingFeeVoucher: orderShipping.sellerShippingFeeVoucher
318
- }
319
- })
273
+ if (order?.orderShipping) {
274
+ const orderShipping: any = order.orderShipping
275
+
276
+ let marketplaceOrderShipping: MarketplaceOrderShipping = new MarketplaceOrderShipping()
277
+ marketplaceOrderShipping.name = NoGenerator.orderShipping()
278
+ marketplaceOrderShipping.address1 = orderShipping.address1
279
+ marketplaceOrderShipping.address2 = orderShipping.address2
280
+ marketplaceOrderShipping.address3 = orderShipping.address3
281
+ marketplaceOrderShipping.address4 = orderShipping.address4
282
+ marketplaceOrderShipping.address5 = orderShipping.address5
283
+ marketplaceOrderShipping.attentionTo = orderShipping.attentionTo
284
+ marketplaceOrderShipping.city = orderShipping.city
285
+ marketplaceOrderShipping.country = orderShipping.country
286
+ marketplaceOrderShipping.state = orderShipping?.state || null
287
+ marketplaceOrderShipping.postCode = orderShipping.postCode
288
+ marketplaceOrderShipping.phone1 = orderShipping.phone1
289
+ marketplaceOrderShipping.phone2 = orderShipping.phone2
290
+ marketplaceOrderShipping.trackingNo = order?.trackingNo || null
291
+ marketplaceOrderShipping.orderNoRef = marketplaceOrder.orderNo
292
+ marketplaceOrderShipping.subOrderNoRef = marketplaceOrder.orderNo
293
+ marketplaceOrderShipping.marketplaceStore = marketplaceStore
294
+ marketplaceOrderShipping.creator = user
295
+ marketplaceOrderShipping.domain = marketplaceStore.domain
296
+ marketplaceOrderShipping.shippingFee = orderShipping.shippingFee
297
+ marketplaceOrderShipping.actualShippingFee = orderShipping.actualShippingFee
298
+ marketplaceOrderShipping.marketplaceShippingFeeVoucher = orderShipping.marketplaceShippingFeeVoucher
299
+ marketplaceOrderShipping.sellerShippingFeeVoucher = orderShipping.sellerShippingFeeVoucher
300
+
301
+ if (existingMarketplaceOrder) {
302
+ if (existingMarketplaceOrder.isSplitted) {
303
+ let existingOrderShippings: MarketplaceOrderShipping[] = await tx
304
+ .getRepository(MarketplaceOrderShipping)
305
+ .find({
306
+ where: { domain, marketplaceStore, orderNoRef: marketplaceOrder.orderNo }
307
+ })
308
+
309
+ existingOrderShippings = existingOrderShippings.map(item => {
310
+ return {
311
+ ...item,
312
+ address1: orderShipping.address1,
313
+ address2: orderShipping.address2,
314
+ address3: orderShipping.address3,
315
+ address4: orderShipping.address4,
316
+ address5: orderShipping.address5,
317
+ attentionTo: orderShipping.attentionTo,
318
+ city: orderShipping.city,
319
+ country: orderShipping.country,
320
+ state: orderShipping?.state,
321
+ postCode: orderShipping.postCode,
322
+ phone1: orderShipping.phone1,
323
+ phone2: orderShipping.phone2,
324
+ email: orderShipping?.email,
325
+ trackingNo: marketplaceStore.eTrax ? item.trackingNo : order?.trackingNo,
326
+ shippingFee: orderShipping.shippingFee,
327
+ actualShippingFee: orderShipping.actualShippingFee,
328
+ marketplaceShippingFeeVoucher: orderShipping.marketplaceShippingFeeVoucher,
329
+ sellerShippingFeeVoucher: orderShipping.sellerShippingFeeVoucher
330
+ }
331
+ })
320
332
 
321
- savedMarketplaceOrderShippings = await tx
322
- .getRepository(MarketplaceOrderShipping)
323
- .save(existingOrderShippings)
324
- } else {
325
- if (existingMarketplaceOrder?.marketplaceOrderItems) {
326
- let existingOrderShipping: MarketplaceOrderShipping
327
- existingOrderShipping =
328
- existingMarketplaceOrder.marketplaceOrderItems[0].marketplaceOrderShippingItems[0]
329
- .marketplaceOrderShipping
330
-
331
- marketplaceOrderShipping = {
332
- ...existingOrderShipping,
333
- ...marketplaceOrderShipping,
334
- trackingNo: marketplaceOrderShipping?.trackingNo
335
- ? marketplaceOrderShipping.trackingNo
336
- : existingOrderShipping?.trackingNo
337
- ? existingOrderShipping.trackingNo
338
- : marketplaceOrderShipping.trackingNo,
339
- updater: user
333
+ savedMarketplaceOrderShippings = await tx
334
+ .getRepository(MarketplaceOrderShipping)
335
+ .save(existingOrderShippings)
336
+ } else {
337
+ if (existingMarketplaceOrder?.marketplaceOrderItems) {
338
+ let existingOrderShipping: MarketplaceOrderShipping
339
+ existingOrderShipping =
340
+ existingMarketplaceOrder.marketplaceOrderItems[0].marketplaceOrderShippingItems[0]
341
+ .marketplaceOrderShipping
342
+
343
+ marketplaceOrderShipping = {
344
+ ...existingOrderShipping,
345
+ ...marketplaceOrderShipping,
346
+ trackingNo: marketplaceStore.eTrax
347
+ ? existingOrderShipping.trackingNo
348
+ : marketplaceOrderShipping?.trackingNo
349
+ ? marketplaceOrderShipping.trackingNo
350
+ : existingOrderShipping?.trackingNo
351
+ ? existingOrderShipping.trackingNo
352
+ : marketplaceOrderShipping.trackingNo,
353
+ updater: user
354
+ }
355
+
356
+ savedMarketplaceOrderShipping = await tx
357
+ .getRepository(MarketplaceOrderShipping)
358
+ .save(marketplaceOrderShipping)
359
+ }
340
360
  }
361
+ } else {
362
+ if (marketplaceStore.eTrax) delete marketplaceOrderShipping.trackingNo
341
363
 
342
364
  savedMarketplaceOrderShipping = await tx
343
365
  .getRepository(MarketplaceOrderShipping)
344
366
  .save(marketplaceOrderShipping)
345
367
  }
346
368
  }
347
- } else {
348
- savedMarketplaceOrderShipping = await tx
349
- .getRepository(MarketplaceOrderShipping)
350
- .save(marketplaceOrderShipping)
351
- }
352
- }
353
-
354
- let orderTotalWeight: number = 0
355
- let foundVariations = []
356
- for (var j = 0; j < order.orderItems.length; j++) {
357
- var item = order.orderItems[j]
358
- let foundVariationsQuery = await tx.getRepository(MarketplaceProductVariation).find({
359
- where: { domain: marketplaceStore.domain, variationId: item.variationId },
360
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
361
- })
362
-
363
- let foundVariation = foundVariationsQuery.filter(
364
- fv => fv.marketplaceProduct.marketplaceStore.id == marketplaceStore.id
365
- )[0]
366
-
367
- if (foundVariation) {
368
- foundVariations.push(foundVariation)
369
- }
370
369
 
371
- if (!foundVariation) {
372
- let newVariation: any = {
373
- variationId: item.variationId,
374
- name: item.variationName,
375
- variationSku: item.variationSku,
376
- channelSku: item.sku,
377
- status: 'INACTIVE',
378
- domain: marketplaceStore.domain
379
- }
380
-
381
- await tx.getRepository(MarketplaceProductVariation).save(newVariation)
382
- foundVariation = newVariation
383
- }
384
-
385
- let marketplaceOrderItem: MarketplaceOrderItem = new MarketplaceOrderItem()
386
- marketplaceOrderItem.domain = marketplaceStore.domain
387
- marketplaceOrderItem.name = item.name
388
- marketplaceOrderItem.qty = item.qty
389
- marketplaceOrderItem.paidPrice = item.paidPrice
390
- marketplaceOrderItem.status = marketplaceOrder.status
391
- marketplaceOrderItem.docRefNo = item.docRefNo
392
- marketplaceOrderItem.marketplaceProductVariation = foundVariation
393
- marketplaceOrderItem.trackingCode = order.trackingNo
394
- marketplaceOrderItem.marketplaceOrder = marketplaceOrder
395
- marketplaceOrderItem.originalPrice = item.originalPrice
396
- marketplaceOrderItem.discount = item.discount
397
- marketplaceOrderItem.promotionId = item.promotionId
398
- marketplaceOrderItem.creator = user
399
- marketplaceOrderItem.paymentFee = item.paymentFee || null
400
- marketplaceOrderItem.commissionFee = item.commissionFee || null
401
- marketplaceOrderItem.shippingFeePaidByCustomer = item.shippingFeePaidByCustomer || null
402
- marketplaceOrderItem.itemPriceCredit = item.itemPriceCredit || null
403
- marketplaceOrderItem.promotionalCharges = item.promotionalCharges || null
404
- marketplaceOrderItem.ordersMarketplaceFeesTotal = item.ordersMarketplaceFeesTotal || null
405
- marketplaceOrderItem.ordersSalesTotal = item.ordersSalesTotal || null
406
- marketplaceOrderItem.ordersMarketingFeesTotal = item.ordersMarketingFeesTotal || null
407
- marketplaceOrderItem.ordersLogisticsTotal = item.ordersLogisticsTotal || null
408
- marketplaceOrderItem.marketplaceBonus = item.marketplaceBonus
409
- marketplaceOrderItem.marketplaceBonusSeller = item.marketplaceBonusSeller
410
- marketplaceOrderItem.shippingFeeDiscountMarketplace = item.shippingFeeDiscountMarketplace
411
- marketplaceOrderItem.shippingFeeDiscountSeller = item.shippingFeeDiscountSeller
412
- marketplaceOrderItem.promotionalChargesFlexiCombo = item.promotionalChargesFlexiCombo
413
- marketplaceOrderItem.autoShippingSubsidyMarketplace = item.autoShippingSubsidyMarketplace
414
- marketplaceOrderItem.originalShippingFee = item.originalShippingFee
415
- marketplaceOrderItem.taxAmount = item.taxAmount
416
-
417
- marketplaceOrderItems.push({ ...marketplaceOrderItem })
418
-
419
- if (foundVariation?.primaryUnitValue)
420
- orderTotalWeight += parseFloat(foundVariation.primaryUnitValue.toFixed(3)) * item.qty || 0
421
- }
370
+ let orderTotalWeight: number = 0
371
+ let foundVariations = []
372
+ for (var j = 0; j < order.orderItems.length; j++) {
373
+ var item = order.orderItems[j]
374
+ let foundVariationsQuery = await tx.getRepository(MarketplaceProductVariation).find({
375
+ where: { domain: marketplaceStore.domain, variationId: item.variationId },
376
+ relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
377
+ })
422
378
 
423
- if (existingMarketplaceOrder) {
424
- let existingOrderItems: MarketplaceOrderItem[] = []
425
- existingOrderItems = existingMarketplaceOrder.marketplaceOrderItems
379
+ let foundVariation = foundVariationsQuery.filter(
380
+ fv => fv.marketplaceProduct.marketplaceStore.id == marketplaceStore.id
381
+ )[0]
426
382
 
427
- existingOrderItems = await checkUpdateItemId(existingOrderItems, marketplaceOrderItems)
383
+ if (foundVariation) {
384
+ foundVariations.push(foundVariation)
385
+ }
428
386
 
429
- if (existingMarketplaceOrder.isSplitted) {
430
- marketplaceOrderItems = existingOrderItems.filter(
431
- itm => itm.name == item.name && itm.marketplaceProductVariation.variationId == item.variationId
432
- )
387
+ if (!foundVariation) {
388
+ let newVariation: any = {
389
+ variationId: item.variationId,
390
+ name: item.variationName,
391
+ variationSku: item.variationSku,
392
+ channelSku: item.sku,
393
+ status: 'INACTIVE',
394
+ domain: marketplaceStore.domain
395
+ }
433
396
 
434
- marketplaceOrderItems = marketplaceOrderItems.map(marketplaceOrderitem => {
435
- return {
436
- ...marketplaceOrderitem,
437
- status: order.status,
438
- trackingCode: order.trackingNo
397
+ await tx.getRepository(MarketplaceProductVariation).save(newVariation)
398
+ foundVariation = newVariation
439
399
  }
440
- })
441
- } else {
442
- if (existingOrderItems.length > marketplaceOrderItems.length) {
443
- let nonMatchedOrderItems = []
444
- existingOrderItems.map(item => {
445
- const matchedOrderItem = marketplaceOrderItems.find(
446
- itm =>
447
- itm.name === item.name &&
448
- itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId
449
- )
450
- if (!matchedOrderItem) {
451
- nonMatchedOrderItems.push({ ...item })
452
- }
453
- })
454
- if (nonMatchedOrderItems.length > 0 && !cancelStatuses.includes(marketplaceOrder.status)) {
455
- await Promise.all(
456
- nonMatchedOrderItems.map(async item => {
457
- for (var foundVariation of foundVariations) {
458
- if (foundVariation.sku) {
459
- let allVariations: MarketplaceProductVariation[] = await tx
460
- .getRepository(MarketplaceProductVariation)
461
- .find({
462
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
463
- relations: [
464
- 'domain',
465
- 'marketplaceProduct',
466
- 'marketplaceProduct.marketplaceStore',
467
- 'marketplaceProduct.marketplaceStore.marketplaceDistributors'
468
- ]
469
- })
470
-
471
- let activeVariations: MarketplaceProductVariation[] = allVariations.filter(
472
- variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED'
473
- )
474
400
 
475
- await Promise.all(
476
- activeVariations.map(async variation => {
477
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty, '-')
401
+ let marketplaceOrderItem: MarketplaceOrderItem = new MarketplaceOrderItem()
402
+ marketplaceOrderItem.domain = marketplaceStore.domain
403
+ marketplaceOrderItem.name = item.name
404
+ marketplaceOrderItem.qty = item.qty
405
+ marketplaceOrderItem.paidPrice = item.paidPrice
406
+ marketplaceOrderItem.status = marketplaceOrder.status
407
+ marketplaceOrderItem.docRefNo = item.docRefNo
408
+ marketplaceOrderItem.marketplaceProductVariation = foundVariation
409
+ marketplaceOrderItem.trackingCode = order.trackingNo
410
+ marketplaceOrderItem.marketplaceOrder = marketplaceOrder
411
+ marketplaceOrderItem.originalPrice = item.originalPrice
412
+ marketplaceOrderItem.discount = item.discount
413
+ marketplaceOrderItem.promotionId = item.promotionId
414
+ marketplaceOrderItem.creator = user
415
+ marketplaceOrderItem.paymentFee = item.paymentFee || null
416
+ marketplaceOrderItem.commissionFee = item.commissionFee || null
417
+ marketplaceOrderItem.shippingFeePaidByCustomer = item.shippingFeePaidByCustomer || null
418
+ marketplaceOrderItem.itemPriceCredit = item.itemPriceCredit || null
419
+ marketplaceOrderItem.promotionalCharges = item.promotionalCharges || null
420
+ marketplaceOrderItem.ordersMarketplaceFeesTotal = item.ordersMarketplaceFeesTotal || null
421
+ marketplaceOrderItem.ordersSalesTotal = item.ordersSalesTotal || null
422
+ marketplaceOrderItem.ordersMarketingFeesTotal = item.ordersMarketingFeesTotal || null
423
+ marketplaceOrderItem.ordersLogisticsTotal = item.ordersLogisticsTotal || null
424
+ marketplaceOrderItem.marketplaceBonus = item.marketplaceBonus
425
+ marketplaceOrderItem.marketplaceBonusSeller = item.marketplaceBonusSeller
426
+ marketplaceOrderItem.shippingFeeDiscountMarketplace = item.shippingFeeDiscountMarketplace
427
+ marketplaceOrderItem.shippingFeeDiscountSeller = item.shippingFeeDiscountSeller
428
+ marketplaceOrderItem.promotionalChargesFlexiCombo = item.promotionalChargesFlexiCombo
429
+ marketplaceOrderItem.autoShippingSubsidyMarketplace = item.autoShippingSubsidyMarketplace
430
+ marketplaceOrderItem.originalShippingFee = item.originalShippingFee
431
+ marketplaceOrderItem.taxAmount = item.taxAmount
432
+
433
+ marketplaceOrderItems.push({ ...marketplaceOrderItem })
434
+
435
+ if (foundVariation?.primaryUnitValue)
436
+ orderTotalWeight += parseFloat(foundVariation.primaryUnitValue.toFixed(3)) * item.qty || 0
437
+ }
478
438
 
479
- variation.reserveQty -= item.qty
480
- variation.qty += item.qty
439
+ if (existingMarketplaceOrder) {
440
+ let existingOrderItems: MarketplaceOrderItem[] = []
441
+ existingOrderItems = existingMarketplaceOrder.marketplaceOrderItems
481
442
 
482
- variation = await tx.getRepository(MarketplaceProductVariation).save(variation)
483
- })
484
- )
485
- }
486
- }
487
- })
488
- )
443
+ existingOrderItems = await checkUpdateItemId(existingOrderItems, marketplaceOrderItems)
489
444
 
490
- await tx.getRepository(MarketplaceOrderItem).delete(nonMatchedOrderItems)
491
- }
445
+ if (existingMarketplaceOrder.isSplitted) {
446
+ marketplaceOrderItems = existingOrderItems.filter(
447
+ itm => itm.name == item.name && itm.marketplaceProductVariation.variationId == item.variationId
448
+ )
492
449
 
493
- if (!cancelStatuses.includes(marketplaceOrder.status)) {
494
- existingOrderItems = await Promise.all(
495
- marketplaceOrderItems.map(async item => {
496
- const matchedOrderItem = existingOrderItems.find(
450
+ marketplaceOrderItems = marketplaceOrderItems.map(marketplaceOrderitem => {
451
+ return {
452
+ ...marketplaceOrderitem,
453
+ status: order.status,
454
+ trackingCode: order.trackingNo
455
+ }
456
+ })
457
+ } else {
458
+ if (existingOrderItems.length > marketplaceOrderItems.length) {
459
+ let nonMatchedOrderItems = []
460
+ existingOrderItems.map(item => {
461
+ const matchedOrderItem = marketplaceOrderItems.find(
497
462
  itm =>
498
- itm.name == item.name &&
463
+ itm.name === item.name &&
499
464
  itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId
500
465
  )
501
- if (matchedOrderItem) {
502
- for (var foundVariation of foundVariations) {
466
+ if (!matchedOrderItem) {
467
+ nonMatchedOrderItems.push({ ...item })
468
+ }
469
+ })
470
+ if (nonMatchedOrderItems.length > 0 && !cancelStatuses.includes(marketplaceOrder.status)) {
471
+ await Promise.all(
472
+ nonMatchedOrderItems.map(async item => {
473
+ let foundVariation = foundVariations.find(fv => fv.sku == item.marketplaceProductVariation.sku)
503
474
  if (foundVariation.sku) {
504
- let allVariations: MarketplaceProductVariation[] = await tx
505
- .getRepository(MarketplaceProductVariation)
506
- .find({
507
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
508
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
509
- })
510
-
511
- let activeVariations: MarketplaceProductVariation[] = allVariations.filter(
512
- variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED'
513
- )
475
+ await updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, item.qty * -1)
476
+ }
477
+ })
478
+ )
479
+
480
+ await tx.getRepository(MarketplaceOrderItem).delete(nonMatchedOrderItems)
481
+ }
514
482
 
515
- await Promise.all(
516
- activeVariations.map(async variation => {
517
- if (!existingMarketplaceOrder?.releaseOrderId && matchedOrderItem.qty - item.qty != 0) {
518
- await calculateReserveQtyForBundle(
519
- tx,
520
- variation,
521
- marketplaceOrder.domain,
522
- matchedOrderItem.qty - item.qty
523
- )
524
- }
525
-
526
- variation.reserveQty = existingMarketplaceOrder?.releaseOrderId
527
- ? variation.reserveQty
528
- : variation.reserveQty - item.qty + matchedOrderItem.qty
529
-
530
- variation.qty = existingMarketplaceOrder?.releaseOrderId
531
- ? variation.qty
532
- : variation.qty + item.qty - matchedOrderItem.qty
533
-
534
- variation = await tx.getRepository(MarketplaceProductVariation).save(variation)
535
- })
483
+ if (!cancelStatuses.includes(marketplaceOrder.status)) {
484
+ existingOrderItems = await Promise.all(
485
+ marketplaceOrderItems.map(async item => {
486
+ const matchedOrderItem = existingOrderItems.find(
487
+ itm =>
488
+ itm.name == item.name &&
489
+ itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId
490
+ )
491
+ if (matchedOrderItem) {
492
+ foundVariation = foundVariations.find(
493
+ fv => fv.variationId == matchedOrderItem.marketplaceProductVariation.variationId
536
494
  )
495
+ if (foundVariation.sku) {
496
+ await updateQtyAndReserveQty(
497
+ tx,
498
+ foundVariation,
499
+ marketplaceOrder,
500
+ item.qty,
501
+ matchedOrderItem.qty,
502
+ existingMarketplaceOrder
503
+ )
504
+ }
505
+ return {
506
+ ...matchedOrderItem,
507
+ ...item,
508
+ updater: user
509
+ }
537
510
  }
538
- }
539
- return {
540
- ...matchedOrderItem,
541
- ...item,
542
- updater: user
543
- }
544
- }
545
- })
546
- )
547
- }
548
- } else {
549
- if (!cancelStatuses.includes(marketplaceOrder.status)) {
550
- existingOrderItems = await Promise.all(
551
- marketplaceOrderItems.map(async item => {
552
- const matchedOrderItem = existingOrderItems.find(
553
- itm =>
554
- itm.name == item.name &&
555
- itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId
511
+ })
556
512
  )
557
- if (matchedOrderItem) {
558
- for (var foundVariation of foundVariations) {
559
- if (foundVariation.sku) {
560
- let allVariations: MarketplaceProductVariation[] = await tx
561
- .getRepository(MarketplaceProductVariation)
562
- .find({
563
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
564
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
565
- })
566
-
567
- let activeVariations: MarketplaceProductVariation[] = allVariations.filter(
568
- variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED'
513
+ }
514
+ } else {
515
+ if (!cancelStatuses.includes(marketplaceOrder.status)) {
516
+ existingOrderItems = await Promise.all(
517
+ marketplaceOrderItems.map(async item => {
518
+ const matchedOrderItem = existingOrderItems.find(
519
+ itm =>
520
+ itm.name == item.name &&
521
+ itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId
522
+ )
523
+ if (matchedOrderItem) {
524
+ foundVariation = foundVariations.find(
525
+ fv => fv.variationId == matchedOrderItem.marketplaceProductVariation.variationId
569
526
  )
570
-
571
- await Promise.all(
572
- activeVariations.map(async variation => {
573
- if (!existingMarketplaceOrder?.releaseOrderId && matchedOrderItem.qty - item.qty != 0) {
574
- await calculateReserveQtyForBundle(
575
- tx,
576
- variation,
577
- marketplaceOrder.domain,
578
- matchedOrderItem.qty - item.qty
579
- )
580
- }
581
-
582
- variation.reserveQty = existingMarketplaceOrder?.releaseOrderId
583
- ? variation.reserveQty
584
- : variation.reserveQty - item.qty + matchedOrderItem.qty
585
-
586
- variation.qty = existingMarketplaceOrder?.releaseOrderId
587
- ? variation.qty
588
- : variation.qty + item.qty - matchedOrderItem.qty
589
-
590
- variation = await tx.getRepository(MarketplaceProductVariation).save(variation)
591
- })
527
+ if (foundVariation.sku) {
528
+ await updateQtyAndReserveQty(
529
+ tx,
530
+ foundVariation,
531
+ marketplaceOrder,
532
+ item.qty,
533
+ matchedOrderItem.qty,
534
+ existingMarketplaceOrder
535
+ )
536
+ }
537
+ return {
538
+ ...matchedOrderItem,
539
+ ...item,
540
+ updater: user
541
+ }
542
+ } else {
543
+ let foundVariation = foundVariations.find(
544
+ fv => (fv.sku = item.marketplaceProductVariation.sku)
592
545
  )
546
+ if (foundVariation.sku) {
547
+ await updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, item.qty)
548
+ }
549
+ return {
550
+ ...item,
551
+ updater: user
552
+ }
593
553
  }
594
- }
595
- return {
596
- ...matchedOrderItem,
597
- ...item,
598
- updater: user
599
- }
600
- } else {
601
- for (var foundVariation of foundVariations) {
602
- if (foundVariation.sku) {
603
- let allVariations: MarketplaceProductVariation[] = await tx
604
- .getRepository(MarketplaceProductVariation)
605
- .find({
606
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
607
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
608
- })
609
-
610
- let activeVariations: MarketplaceProductVariation[] = allVariations.filter(
611
- variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED'
612
- )
554
+ })
555
+ )
556
+ }
557
+ }
613
558
 
614
- await Promise.all(
615
- activeVariations.map(async variation => {
616
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty)
559
+ marketplaceOrderItems = existingOrderItems
617
560
 
618
- variation.reserveQty += item.qty
561
+ if (order?.orderShipping) {
562
+ savedMarketplaceOrderShipping.totalWeight = orderTotalWeight
619
563
 
620
- if (variation.qty - item.qty >= 0) {
621
- variation.qty -= item.qty
622
- }
564
+ if (marketplaceStore.eTrax) delete savedMarketplaceOrderShipping.trackingNo
623
565
 
624
- variation = await tx.getRepository(MarketplaceProductVariation).save(variation)
625
- })
626
- )
627
- }
628
- }
629
- return {
630
- ...item,
631
- updater: user
632
- }
633
- }
634
- })
635
- )
566
+ savedMarketplaceOrderShipping = await tx
567
+ .getRepository(MarketplaceOrderShipping)
568
+ .save(savedMarketplaceOrderShipping)
569
+ }
636
570
  }
637
- }
571
+ } else {
572
+ if (!cancelStatuses.includes(marketplaceOrder.status)) {
573
+ for (var foundVariation of foundVariations) {
574
+ if (foundVariation.sku) {
575
+ let item = order.orderItems.find(e => e.variationId == foundVariation.variationId)
576
+ await updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, item.qty)
577
+ }
638
578
 
639
- marketplaceOrderItems = existingOrderItems
579
+ if (order?.orderShipping) {
580
+ savedMarketplaceOrderShipping.totalWeight = orderTotalWeight
581
+ if (marketplaceStore.eTrax) delete savedMarketplaceOrderShipping.trackingNo
640
582
 
641
- if (order?.orderShipping) {
642
- savedMarketplaceOrderShipping.totalWeight = orderTotalWeight
643
- savedMarketplaceOrderShipping = await tx
644
- .getRepository(MarketplaceOrderShipping)
645
- .save(savedMarketplaceOrderShipping)
583
+ savedMarketplaceOrderShipping = await tx
584
+ .getRepository(MarketplaceOrderShipping)
585
+ .save(savedMarketplaceOrderShipping)
586
+ }
587
+ }
588
+ }
646
589
  }
647
- }
648
- } else {
649
- if (!cancelStatuses.includes(marketplaceOrder.status)) {
650
- for (var foundVariation of foundVariations) {
651
- if (foundVariation.sku) {
652
- let allVariations: MarketplaceProductVariation[] = await tx
653
- .getRepository(MarketplaceProductVariation)
654
- .find({
655
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
656
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
657
- })
658
590
 
659
- let activeVariations: MarketplaceProductVariation[] = allVariations.filter(
660
- variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED'
661
- )
662
- let item = order.orderItems.find(e => e.variationId == foundVariation.variationId)
663
- await Promise.all(
664
- activeVariations.map(async variation => {
665
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty)
591
+ await tx.getRepository(MarketplaceOrder).save(marketplaceOrder)
592
+ await tx.getRepository(MarketplaceOrderItem).save(marketplaceOrderItems)
666
593
 
667
- variation.reserveQty += item.qty
594
+ for (let i = 0; i < marketplaceOrderItems.length; i++) {
595
+ const marketplaceOrderItem: MarketplaceOrderItem = marketplaceOrderItems[i]
596
+ const marketplaceProductVariation: MarketplaceProductVariation =
597
+ marketplaceOrderItem.marketplaceProductVariation
598
+ let existingMarketplaceOrderShippingItems: MarketplaceOrderShippingItem[] = await tx
599
+ .getRepository(MarketplaceOrderShippingItem)
600
+ .find({
601
+ where: { domain: marketplaceStore.domain, marketplaceOrderItem }
602
+ })
668
603
 
669
- if (variation.qty - item.qty >= 0) {
670
- variation.qty -= item.qty
671
- }
604
+ let product: Product = await tx.getRepository(Product).findOne({
605
+ where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku, deletedAt: IsNull() },
606
+ relations: ['productDetails']
607
+ })
672
608
 
673
- variation = await tx.getRepository(MarketplaceProductVariation).save(variation)
674
- })
675
- )
609
+ let productBundle: ProductBundle
610
+ if (!product) {
611
+ productBundle = await tx.getRepository(ProductBundle).findOne({
612
+ where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku },
613
+ relations: ['productBundleSettings', 'productBundleSettings.product']
614
+ })
676
615
  }
677
616
 
678
- if (order?.orderShipping) {
679
- savedMarketplaceOrderShipping.totalWeight = orderTotalWeight
680
- savedMarketplaceOrderShipping = await tx
681
- .getRepository(MarketplaceOrderShipping)
682
- .save(savedMarketplaceOrderShipping)
617
+ if (existingMarketplaceOrderShippingItems && existingMarketplaceOrderShippingItems?.length) {
618
+ } else {
619
+ if (productBundle) {
620
+ const productBundleSettings: ProductBundleSetting[] = productBundle.productBundleSettings
621
+ let marketplaceOrderShippingItems: MarketplaceOrderShippingItem[] = []
622
+ productBundleSettings.map(productBundleSetting => {
623
+ let marketplaceOrderShippingItem: MarketplaceOrderShippingItem = new MarketplaceOrderShippingItem()
624
+ marketplaceOrderShippingItem.name = uuid()
625
+ marketplaceOrderShippingItem.qty = marketplaceOrderItem.qty * productBundleSetting.bundleQty
626
+ marketplaceOrderShippingItem.domain = marketplaceStore.domain
627
+ marketplaceOrderShippingItem.marketplaceOrderItem = marketplaceOrderItem
628
+ marketplaceOrderShippingItem.marketplaceOrderShipping = savedMarketplaceOrderShipping
629
+ marketplaceOrderShippingItem.product = productBundleSetting.product
630
+
631
+ marketplaceOrderShippingItems.push(marketplaceOrderShippingItem)
632
+ })
633
+
634
+ await tx.getRepository(MarketplaceOrderShippingItem).save(marketplaceOrderShippingItems)
635
+ } else {
636
+ let marketplaceOrderShippingItem: MarketplaceOrderShippingItem = new MarketplaceOrderShippingItem()
637
+ marketplaceOrderShippingItem.name = uuid()
638
+ marketplaceOrderShippingItem.qty = marketplaceOrderItem.qty
639
+ marketplaceOrderShippingItem.domain = marketplaceStore.domain
640
+ marketplaceOrderShippingItem.marketplaceOrderItem = marketplaceOrderItem
641
+ marketplaceOrderShippingItem.marketplaceOrderShipping = savedMarketplaceOrderShipping
642
+ marketplaceOrderShippingItem.product = product ? product : null
643
+
644
+ await tx.getRepository(MarketplaceOrderShippingItem).save(marketplaceOrderShippingItem)
645
+ }
683
646
  }
684
647
  }
685
- }
686
- }
687
-
688
- await tx.getRepository(MarketplaceOrder).save(marketplaceOrder)
689
- await tx.getRepository(MarketplaceOrderItem).save(marketplaceOrderItems)
690
-
691
- for (let i = 0; i < marketplaceOrderItems.length; i++) {
692
- const marketplaceOrderItem: MarketplaceOrderItem = marketplaceOrderItems[i]
693
- const marketplaceProductVariation: MarketplaceProductVariation =
694
- marketplaceOrderItem.marketplaceProductVariation
695
- let existingMarketplaceOrderShippingItems: MarketplaceOrderShippingItem[] = await tx
696
- .getRepository(MarketplaceOrderShippingItem)
697
- .find({
698
- where: { domain: marketplaceStore.domain, marketplaceOrderItem }
699
- })
700
-
701
- let product: Product = await tx.getRepository(Product).findOne({
702
- where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku, deletedAt: IsNull() },
703
- relations: ['productDetails']
704
- })
705
-
706
- let productBundle: ProductBundle
707
- if (!product) {
708
- productBundle = await tx.getRepository(ProductBundle).findOne({
709
- where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku },
710
- relations: ['productBundleSettings', 'productBundleSettings.product']
711
- })
712
- }
713
-
714
- if (existingMarketplaceOrderShippingItems && existingMarketplaceOrderShippingItems?.length) {
715
- } else {
716
- if (productBundle) {
717
- const productBundleSettings: ProductBundleSetting[] = productBundle.productBundleSettings
718
- let marketplaceOrderShippingItems: MarketplaceOrderShippingItem[] = []
719
- productBundleSettings.map(productBundleSetting => {
720
- let marketplaceOrderShippingItem: MarketplaceOrderShippingItem = new MarketplaceOrderShippingItem()
721
- marketplaceOrderShippingItem.name = uuid()
722
- marketplaceOrderShippingItem.qty = marketplaceOrderItem.qty * productBundleSetting.bundleQty
723
- marketplaceOrderShippingItem.domain = marketplaceStore.domain
724
- marketplaceOrderShippingItem.marketplaceOrderItem = marketplaceOrderItem
725
- marketplaceOrderShippingItem.marketplaceOrderShipping = savedMarketplaceOrderShipping
726
- marketplaceOrderShippingItem.product = productBundleSetting.product
727
-
728
- marketplaceOrderShippingItems.push(marketplaceOrderShippingItem)
729
- })
730
648
 
731
- await tx.getRepository(MarketplaceOrderShippingItem).save(marketplaceOrderShippingItems)
732
- } else {
733
- let marketplaceOrderShippingItem: MarketplaceOrderShippingItem = new MarketplaceOrderShippingItem()
734
- marketplaceOrderShippingItem.name = uuid()
735
- marketplaceOrderShippingItem.qty = marketplaceOrderItem.qty
736
- marketplaceOrderShippingItem.domain = marketplaceStore.domain
737
- marketplaceOrderShippingItem.marketplaceOrderItem = marketplaceOrderItem
738
- marketplaceOrderShippingItem.marketplaceOrderShipping = savedMarketplaceOrderShipping
739
- marketplaceOrderShippingItem.product = product ? product : null
740
-
741
- await tx.getRepository(MarketplaceOrderShippingItem).save(marketplaceOrderShippingItem)
649
+ if (i == marketplaceOrders.length - 1) {
650
+ lastOrderId = order.name
742
651
  }
652
+ } catch (e) {
653
+ logger.error(`Order no: ${marketplaceOrders[i]}: ${e}`)
743
654
  }
744
- }
745
-
746
- if (i == marketplaceOrders.length - 1) {
747
- lastOrderId = order.name
748
- }
655
+ })
749
656
  }
750
657
 
751
658
  if (more) page++
@@ -770,56 +677,85 @@ export const syncMarketplaceOrder = {
770
677
  hasMore = more
771
678
  }
772
679
 
773
- await Promise.all(
774
- payoutDateList.map(async item => {
775
- await tx.getRepository(MarketplaceOrder).update(
776
- {
777
- orderNo: item.orderNo
778
- },
779
- {
780
- payoutDate: item.payoutDate
781
- }
782
- )
783
- })
784
- )
680
+ await getConnection().transaction(async tx => {
681
+ await Promise.all(
682
+ payoutDateList.map(async item => {
683
+ await tx.getRepository(MarketplaceOrder).update(
684
+ {
685
+ orderNo: item.orderNo
686
+ },
687
+ {
688
+ payoutDate: item.payoutDate
689
+ }
690
+ )
691
+ })
692
+ )
693
+ })
785
694
  }
786
695
  return true
787
696
  }
788
697
  }
789
698
 
790
- async function calculateReserveQtyForBundle(tx, variation, domain, qty, operator = '+') {
699
+ async function updateQtyAndReserveQtyBundle(
700
+ tx,
701
+ variation,
702
+ domain,
703
+ qty,
704
+ marketplaceOrder,
705
+ existingMarketplaceOrder = null,
706
+ matchedOrderItemQty = null
707
+ ) {
708
+ let statusAllowed = RESERVE_QTY_ORDER_STATUSES[marketplaceOrder.marketplaceStore.platform.toUpperCase()].includes(
709
+ marketplaceOrder.status
710
+ )
711
+ let existingStatusNotAllowed = existingMarketplaceOrder
712
+ ? !RESERVE_QTY_ORDER_STATUSES[existingMarketplaceOrder.marketplaceStore.platform.toUpperCase()].includes(
713
+ existingMarketplaceOrder.status
714
+ )
715
+ : false
791
716
  const productBundle: ProductBundle = await tx.getRepository(ProductBundle).findOne({
792
- where: { sku: variation.sku, domain }
717
+ where: { sku: variation.sku, domain },
718
+ relations: ['productBundleSettings', 'productBundleSettings.product']
793
719
  })
794
720
 
795
721
  if (productBundle) {
796
- const productBundleSettings: ProductBundleSetting[] = await tx.getRepository(ProductBundleSetting).find({
797
- where: { productBundle },
798
- relations: ['productBundle', 'product']
799
- })
800
-
801
- for (let setting of productBundleSettings) {
802
- const product: Product = await tx.getRepository(Product).findOne({
803
- where: { id: setting.product.id }
804
- })
805
-
722
+ for (let setting of productBundle.productBundleSettings) {
806
723
  const mpvs: MarketplaceProductVariation[] = await tx.getRepository(MarketplaceProductVariation).find({
807
- where: { domain, sku: product.sku },
724
+ where: { domain, sku: setting.product.sku },
808
725
  relations: ['domain']
809
726
  })
810
727
 
811
728
  for (let mpv of mpvs) {
812
- if (operator === '+') {
813
- mpv.reserveQty += setting.bundleQty * qty
729
+ let updatedReserveQty = 0
730
+ let updatedQty = 0
731
+
732
+ if (existingMarketplaceOrder) {
733
+ if (
734
+ (statusAllowed && existingStatusNotAllowed) ||
735
+ (cancelStatuses.includes(marketplaceOrder.status) && !existingStatusNotAllowed)
736
+ ) {
737
+ updatedReserveQty += setting.bundleQty * qty
738
+ }
739
+
740
+ updatedQty += setting.bundleQty * qty - matchedOrderItemQty * setting.bundleQty
741
+ } else {
742
+ if (statusAllowed && qty > 0) {
743
+ updatedReserveQty += setting.bundleQty * qty
744
+ }
745
+
814
746
  if (mpv.qty - setting.bundleQty * qty >= 0) {
815
- mpv.qty -= setting.bundleQty * qty
747
+ updatedQty += setting.bundleQty * qty
816
748
  }
817
749
  }
818
- if (operator === '-') {
819
- mpv.reserveQty -= setting.bundleQty * qty
820
- mpv.qty += setting.bundleQty * qty
821
- }
822
- await tx.getRepository(MarketplaceProductVariation).save(mpv)
750
+ await tx
751
+ .createQueryBuilder()
752
+ .update(MarketplaceProductVariation)
753
+ .set({
754
+ qty: () => `COALESCE("qty", 0) - ${updatedQty}`,
755
+ reserveQty: () => `COALESCE("reserve_qty", 0) + ${updatedReserveQty}`
756
+ })
757
+ .where('id = :id', { id: mpv.id })
758
+ .execute()
823
759
  }
824
760
  }
825
761
  }
@@ -827,14 +763,87 @@ async function calculateReserveQtyForBundle(tx, variation, domain, qty, operator
827
763
 
828
764
  function checkUpdateItemId(existingOrderItems, marketplaceOrderItems) {
829
765
  for (let item of marketplaceOrderItems) {
830
- let existingItem = existingOrderItems.find(i => i.name == item.name)
766
+ let existingItem = existingOrderItems.find(i => i.name == item.name)
831
767
 
832
768
  if (!existingItem) {
833
- let existingItemByVariation = existingOrderItems.find(i => i.marketplaceProductVariation.id == item.marketplaceProductVariation.id)
834
- existingOrderItems = existingOrderItems.filter(i => i != existingItemByVariation)
835
- existingItemByVariation.name = item.name
836
- existingOrderItems.push(existingItemByVariation)
769
+ let existingItemByVariation = existingOrderItems.find(
770
+ i => i.marketplaceProductVariation.id == item.marketplaceProductVariation.id
771
+ )
772
+ if (existingItemByVariation) {
773
+ existingOrderItems = existingOrderItems.filter(i => i != existingItemByVariation)
774
+ existingItemByVariation.name = item.name
775
+ existingOrderItems.push(existingItemByVariation)
776
+ }
837
777
  }
838
778
  }
839
779
  return existingOrderItems
840
- }
780
+ }
781
+
782
+ async function updateQtyAndReserveQty(
783
+ tx,
784
+ foundVariation,
785
+ marketplaceOrder,
786
+ qty,
787
+ matchedOrderItemQty = null,
788
+ existingMarketplaceOrder = null
789
+ ) {
790
+ let roCreated = existingMarketplaceOrder ? existingMarketplaceOrder?.realaseOrderId : false
791
+ let existingStatusNotAllowed = existingMarketplaceOrder
792
+ ? !RESERVE_QTY_ORDER_STATUSES[existingMarketplaceOrder.marketplaceStore.platform.toUpperCase()].includes(
793
+ existingMarketplaceOrder.status
794
+ )
795
+ : false
796
+ let activeVariations: MarketplaceProductVariation[] = await tx
797
+ .getRepository(MarketplaceProductVariation)
798
+ .createQueryBuilder('mpv')
799
+ .innerJoin('mpv.marketplaceProduct', 'marketplaceProduct')
800
+ .innerJoin('marketplaceProduct.marketplaceStore', 'marketplaceStore')
801
+ .where('mpv.domain_id = :domainId', { domainId: marketplaceOrder.domain.id })
802
+ .andWhere('mpv.sku = :sku', { sku: foundVariation.sku })
803
+ .andWhere(`marketplaceStore.status != 'TERMINATED'`)
804
+ .getMany()
805
+
806
+ let statusAllowed = RESERVE_QTY_ORDER_STATUSES[marketplaceOrder.marketplaceStore.platform.toUpperCase()].includes(
807
+ marketplaceOrder.status
808
+ )
809
+
810
+ if (existingMarketplaceOrder && !roCreated) {
811
+ await updateQtyAndReserveQtyBundle(
812
+ tx,
813
+ foundVariation,
814
+ marketplaceOrder.domain,
815
+ qty,
816
+ marketplaceOrder,
817
+ existingMarketplaceOrder,
818
+ matchedOrderItemQty
819
+ )
820
+ } else {
821
+ await updateQtyAndReserveQtyBundle(tx, foundVariation, marketplaceOrder.domain, qty, marketplaceOrder)
822
+ }
823
+ await Promise.all(
824
+ activeVariations.map(async variation => {
825
+ let updatedReserveQty = 0
826
+ let updatedQty = 0
827
+ if (matchedOrderItemQty) {
828
+ updatedReserveQty = roCreated ? 0 : statusAllowed && existingStatusNotAllowed ? qty : qty - matchedOrderItemQty
829
+ updatedQty = roCreated ? 0 : qty - matchedOrderItemQty
830
+ } else {
831
+ if ((statusAllowed && qty > 0) || qty < 0) {
832
+ updatedReserveQty = qty
833
+ }
834
+ if (variation.qty - qty >= 0) {
835
+ updatedQty = qty
836
+ }
837
+ }
838
+ await tx
839
+ .createQueryBuilder()
840
+ .update(MarketplaceProductVariation)
841
+ .set({
842
+ qty: () => `COALESCE("qty", 0) - ${updatedQty}`,
843
+ reserveQty: () => `COALESCE("reserve_qty", 0) + ${updatedReserveQty}`
844
+ })
845
+ .where('id = :id', { id: variation.id })
846
+ .execute()
847
+ })
848
+ )
849
+ }