@things-factory/marketplace-base 4.1.27 → 4.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,724 +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:
180
- foundMarketplaceOrderShipping?.trackingNo == '[]'
181
- ? foundMarketplaceOrderShipping.ownTrackingNo
182
- : foundMarketplaceOrderShipping?.trackingNo
183
- ? foundMarketplaceOrderShipping.trackingNo
184
- : foundMarketplaceOrderShipping.ownTrackingNo,
185
- transporter: dropPickProvider ? dropPickProvider : marketplaceOrder.shippingProvider
186
- }
125
+ if (existingMarketplaceOrder) {
126
+ let otherInfoJSON: any = {}
187
127
 
188
- await FulfillmentAPI.updateReleaseGoodDetails(fulfillmentCenter, {
189
- customerBizplaceId,
190
- releaseOrder: { ...patch },
191
- shippingOrder: null
192
- })
193
- }
194
- } else {
195
- let releaseOrder = Object.assign({}, releaseOrders[0])
196
- const foundMarketplaceOrderShipping: MarketplaceOrderShipping = await tx
197
- .getRepository(MarketplaceOrderShipping)
198
- .findOne({
199
- where: { domain: marketplaceStore.domain, orderNoRef: releaseOrder.refNo }
200
- })
201
- let patch = {
202
- id: releaseOrder.id,
203
- marketplaceOrderStatus: marketplaceOrder.status,
204
- trackingNo:
205
- foundMarketplaceOrderShipping?.trackingNo == '[]'
206
- ? foundMarketplaceOrderShipping.ownTrackingNo
207
- : foundMarketplaceOrderShipping?.trackingNo
208
- ? foundMarketplaceOrderShipping.trackingNo
209
- : foundMarketplaceOrderShipping.ownTrackingNo,
210
- transporter: dropPickProvider ? dropPickProvider : marketplaceOrder.shippingProvider
128
+ if (existingMarketplaceOrder?.otherInfoJSON && deliveryProvider) {
129
+ otherInfoJSON = JSON.parse(existingMarketplaceOrder.otherInfoJSON)
130
+ otherInfoJSON.shippingProvider = deliveryProvider
211
131
  }
212
132
 
213
- await FulfillmentAPI.updateReleaseGoodDetails(fulfillmentCenter, {
214
- customerBizplaceId,
215
- releaseOrder: { ...patch },
216
- shippingOrder: null
217
- })
218
- }
219
-
220
- if (cancelStatuses.includes(marketplaceOrder.status)) {
221
- if (existingMarketplaceOrder.isSplitted) {
222
- releaseOrders = releaseOrders.filter(function (order) {
223
- return !disallowCancelStatuses.includes(order.status)
224
- })
133
+ marketplaceOrder = {
134
+ ...existingMarketplaceOrder,
135
+ ...marketplaceOrder,
136
+ otherInfoJSON: otherInfoJSON ? JSON.stringify(otherInfoJSON) : null,
137
+ updater: user
138
+ }
225
139
 
226
- if (releaseOrders?.length) {
227
- for (let a = 0; a < releaseOrders.length; a++) {
228
- const releaseOrderId: string = releaseOrders[a].id
229
- await FulfillmentAPI.cancelReleaseOrder(fulfillmentCenter, { customerBizplaceId, releaseOrderId })
230
- }
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
+ )
231
156
  }
232
- } else {
157
+ }
158
+
159
+ if (marketplaceOrder?.releaseOrderId) {
233
160
  const fulfillmentCenter: FulfillmentCenter = marketplaceOrder.fulfillmentCenter
234
161
  const centerId: string = fulfillmentCenter.centerId
235
-
236
162
  const warehouseDomain: Domain = await tx
237
163
  .getRepository(Domain)
238
164
  .findOne({ where: { subdomain: centerId } })
239
165
  const customerBizplaces: Bizplace[] = await getCustomerBizplaces(warehouseDomain)
240
- const customerBizplaceId: string = customerBizplaces[0].id
166
+ const customerBizplaceId: string = customerBizplaces.find(
167
+ customerBizplace => customerBizplace.company.domain.id == domain.id
168
+ ).id
241
169
 
242
- const { items: releaseOrders }: any = await FulfillmentAPI.getOutboundOrders(fulfillmentCenter, {
170
+ let { items: releaseOrders }: any = await FulfillmentAPI.getOutboundOrders(fulfillmentCenter, {
243
171
  customerBizplaceId,
244
172
  refNo: marketplaceOrder.orderNo
245
173
  })
246
174
 
247
- 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
+ }
248
219
 
249
- if (!disallowCancelStatuses.includes(releaseOrderStatus)) {
250
- await FulfillmentAPI.cancelReleaseOrder(fulfillmentCenter, {
220
+ await FulfillmentAPI.updateReleaseGoodDetails(fulfillmentCenter, {
251
221
  customerBizplaceId,
252
- releaseOrderId: releaseOrders[0].id
222
+ releaseOrder: { ...patch },
223
+ shippingOrder: null
253
224
  })
254
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
+ }
255
267
  }
256
268
  }
257
- }
258
- }
259
269
 
260
- let savedMarketplaceOrderShipping: MarketplaceOrderShipping = new MarketplaceOrderShipping()
261
- let savedMarketplaceOrderShippings: MarketplaceOrderShipping[] = []
262
-
263
- if (order?.orderShipping) {
264
- const orderShipping: any = order.orderShipping
265
-
266
- let marketplaceOrderShipping: MarketplaceOrderShipping = new MarketplaceOrderShipping()
267
- marketplaceOrderShipping.name = NoGenerator.orderShipping()
268
- marketplaceOrderShipping.address1 = orderShipping.address1
269
- marketplaceOrderShipping.address2 = orderShipping.address2
270
- marketplaceOrderShipping.address3 = orderShipping.address3
271
- marketplaceOrderShipping.address4 = orderShipping.address4
272
- marketplaceOrderShipping.address5 = orderShipping.address5
273
- marketplaceOrderShipping.attentionTo = orderShipping.attentionTo
274
- marketplaceOrderShipping.city = orderShipping.city
275
- marketplaceOrderShipping.country = orderShipping.country
276
- marketplaceOrderShipping.state = orderShipping?.state || null
277
- marketplaceOrderShipping.postCode = orderShipping.postCode
278
- marketplaceOrderShipping.phone1 = orderShipping.phone1
279
- marketplaceOrderShipping.phone2 = orderShipping.phone2
280
- marketplaceOrderShipping.trackingNo = order?.trackingNo || null
281
- marketplaceOrderShipping.orderNoRef = marketplaceOrder.orderNo
282
- marketplaceOrderShipping.subOrderNoRef = marketplaceOrder.orderNo
283
- marketplaceOrderShipping.marketplaceStore = marketplaceStore
284
- marketplaceOrderShipping.creator = user
285
- marketplaceOrderShipping.domain = marketplaceStore.domain
286
- marketplaceOrderShipping.shippingFee = orderShipping.shippingFee
287
- marketplaceOrderShipping.actualShippingFee = orderShipping.actualShippingFee
288
- marketplaceOrderShipping.marketplaceShippingFeeVoucher = orderShipping.marketplaceShippingFeeVoucher
289
- marketplaceOrderShipping.sellerShippingFeeVoucher = orderShipping.sellerShippingFeeVoucher
290
-
291
- if (existingMarketplaceOrder) {
292
- if (existingMarketplaceOrder.isSplitted) {
293
- let existingOrderShippings: MarketplaceOrderShipping[] = await tx
294
- .getRepository(MarketplaceOrderShipping)
295
- .find({
296
- where: { domain, marketplaceStore, orderNoRef: marketplaceOrder.orderNo }
297
- })
270
+ let savedMarketplaceOrderShipping: MarketplaceOrderShipping = new MarketplaceOrderShipping()
271
+ let savedMarketplaceOrderShippings: MarketplaceOrderShipping[] = []
298
272
 
299
- existingOrderShippings = existingOrderShippings.map(item => {
300
- return {
301
- ...item,
302
- address1: orderShipping.address1,
303
- address2: orderShipping.address2,
304
- address3: orderShipping.address3,
305
- address4: orderShipping.address4,
306
- address5: orderShipping.address5,
307
- attentionTo: orderShipping.attentionTo,
308
- city: orderShipping.city,
309
- country: orderShipping.country,
310
- state: orderShipping?.state,
311
- postCode: orderShipping.postCode,
312
- phone1: orderShipping.phone1,
313
- phone2: orderShipping.phone2,
314
- email: orderShipping?.email,
315
- trackingNo: marketplaceStore.eTrax ? item.trackingNo : order?.trackingNo,
316
- shippingFee: orderShipping.shippingFee,
317
- actualShippingFee: orderShipping.actualShippingFee,
318
- marketplaceShippingFeeVoucher: orderShipping.marketplaceShippingFeeVoucher,
319
- sellerShippingFeeVoucher: orderShipping.sellerShippingFeeVoucher
320
- }
321
- })
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
+ })
322
332
 
323
- savedMarketplaceOrderShippings = await tx
324
- .getRepository(MarketplaceOrderShipping)
325
- .save(existingOrderShippings)
326
- } else {
327
- if (existingMarketplaceOrder?.marketplaceOrderItems) {
328
- let existingOrderShipping: MarketplaceOrderShipping
329
- existingOrderShipping =
330
- existingMarketplaceOrder.marketplaceOrderItems[0].marketplaceOrderShippingItems[0]
331
- .marketplaceOrderShipping
332
-
333
- marketplaceOrderShipping = {
334
- ...existingOrderShipping,
335
- ...marketplaceOrderShipping,
336
- trackingNo: marketplaceStore.eTrax
337
- ? existingOrderShipping.trackingNo
338
- : marketplaceOrderShipping?.trackingNo
339
- ? marketplaceOrderShipping.trackingNo
340
- : existingOrderShipping?.trackingNo
341
- ? existingOrderShipping.trackingNo
342
- : marketplaceOrderShipping.trackingNo,
343
- 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
+ }
344
360
  }
361
+ } else {
362
+ if (marketplaceStore.eTrax) delete marketplaceOrderShipping.trackingNo
345
363
 
346
364
  savedMarketplaceOrderShipping = await tx
347
365
  .getRepository(MarketplaceOrderShipping)
348
366
  .save(marketplaceOrderShipping)
349
367
  }
350
368
  }
351
- } else {
352
- if (marketplaceStore.eTrax) delete marketplaceOrderShipping.trackingNo
353
369
 
354
- savedMarketplaceOrderShipping = await tx
355
- .getRepository(MarketplaceOrderShipping)
356
- .save(marketplaceOrderShipping)
357
- }
358
- }
359
-
360
- let orderTotalWeight: number = 0
361
- let foundVariations = []
362
- for (var j = 0; j < order.orderItems.length; j++) {
363
- var item = order.orderItems[j]
364
- let foundVariationsQuery = await tx.getRepository(MarketplaceProductVariation).find({
365
- where: { domain: marketplaceStore.domain, variationId: item.variationId },
366
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
367
- })
368
-
369
- let foundVariation = foundVariationsQuery.filter(
370
- fv => fv.marketplaceProduct.marketplaceStore.id == marketplaceStore.id
371
- )[0]
372
-
373
- if (foundVariation) {
374
- foundVariations.push(foundVariation)
375
- }
376
-
377
- if (!foundVariation) {
378
- let newVariation: any = {
379
- variationId: item.variationId,
380
- name: item.variationName,
381
- variationSku: item.variationSku,
382
- channelSku: item.sku,
383
- status: 'INACTIVE',
384
- domain: marketplaceStore.domain
385
- }
386
-
387
- await tx.getRepository(MarketplaceProductVariation).save(newVariation)
388
- foundVariation = newVariation
389
- }
390
-
391
- let marketplaceOrderItem: MarketplaceOrderItem = new MarketplaceOrderItem()
392
- marketplaceOrderItem.domain = marketplaceStore.domain
393
- marketplaceOrderItem.name = item.name
394
- marketplaceOrderItem.qty = item.qty
395
- marketplaceOrderItem.paidPrice = item.paidPrice
396
- marketplaceOrderItem.status = marketplaceOrder.status
397
- marketplaceOrderItem.docRefNo = item.docRefNo
398
- marketplaceOrderItem.marketplaceProductVariation = foundVariation
399
- marketplaceOrderItem.trackingCode = order.trackingNo
400
- marketplaceOrderItem.marketplaceOrder = marketplaceOrder
401
- marketplaceOrderItem.originalPrice = item.originalPrice
402
- marketplaceOrderItem.discount = item.discount
403
- marketplaceOrderItem.promotionId = item.promotionId
404
- marketplaceOrderItem.creator = user
405
- marketplaceOrderItem.paymentFee = item.paymentFee || null
406
- marketplaceOrderItem.commissionFee = item.commissionFee || null
407
- marketplaceOrderItem.shippingFeePaidByCustomer = item.shippingFeePaidByCustomer || null
408
- marketplaceOrderItem.itemPriceCredit = item.itemPriceCredit || null
409
- marketplaceOrderItem.promotionalCharges = item.promotionalCharges || null
410
- marketplaceOrderItem.ordersMarketplaceFeesTotal = item.ordersMarketplaceFeesTotal || null
411
- marketplaceOrderItem.ordersSalesTotal = item.ordersSalesTotal || null
412
- marketplaceOrderItem.ordersMarketingFeesTotal = item.ordersMarketingFeesTotal || null
413
- marketplaceOrderItem.ordersLogisticsTotal = item.ordersLogisticsTotal || null
414
- marketplaceOrderItem.marketplaceBonus = item.marketplaceBonus
415
- marketplaceOrderItem.marketplaceBonusSeller = item.marketplaceBonusSeller
416
- marketplaceOrderItem.shippingFeeDiscountMarketplace = item.shippingFeeDiscountMarketplace
417
- marketplaceOrderItem.shippingFeeDiscountSeller = item.shippingFeeDiscountSeller
418
- marketplaceOrderItem.promotionalChargesFlexiCombo = item.promotionalChargesFlexiCombo
419
- marketplaceOrderItem.autoShippingSubsidyMarketplace = item.autoShippingSubsidyMarketplace
420
- marketplaceOrderItem.originalShippingFee = item.originalShippingFee
421
- marketplaceOrderItem.taxAmount = item.taxAmount
422
-
423
- marketplaceOrderItems.push({ ...marketplaceOrderItem })
424
-
425
- if (foundVariation?.primaryUnitValue)
426
- orderTotalWeight += parseFloat(foundVariation.primaryUnitValue.toFixed(3)) * item.qty || 0
427
- }
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
+ })
428
378
 
429
- if (existingMarketplaceOrder) {
430
- let existingOrderItems: MarketplaceOrderItem[] = []
431
- existingOrderItems = existingMarketplaceOrder.marketplaceOrderItems
379
+ let foundVariation = foundVariationsQuery.filter(
380
+ fv => fv.marketplaceProduct.marketplaceStore.id == marketplaceStore.id
381
+ )[0]
432
382
 
433
- existingOrderItems = await checkUpdateItemId(existingOrderItems, marketplaceOrderItems)
383
+ if (foundVariation) {
384
+ foundVariations.push(foundVariation)
385
+ }
434
386
 
435
- if (existingMarketplaceOrder.isSplitted) {
436
- marketplaceOrderItems = existingOrderItems.filter(
437
- itm => itm.name == item.name && itm.marketplaceProductVariation.variationId == item.variationId
438
- )
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
+ }
439
396
 
440
- marketplaceOrderItems = marketplaceOrderItems.map(marketplaceOrderitem => {
441
- return {
442
- ...marketplaceOrderitem,
443
- status: order.status,
444
- trackingCode: order.trackingNo
397
+ await tx.getRepository(MarketplaceProductVariation).save(newVariation)
398
+ foundVariation = newVariation
445
399
  }
446
- })
447
- } else {
448
- if (existingOrderItems.length > marketplaceOrderItems.length) {
449
- let nonMatchedOrderItems = []
450
- existingOrderItems.map(item => {
451
- const matchedOrderItem = marketplaceOrderItems.find(
452
- itm =>
453
- itm.name === item.name &&
454
- itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId
455
- )
456
- if (!matchedOrderItem) {
457
- nonMatchedOrderItems.push({ ...item })
458
- }
459
- })
460
- if (nonMatchedOrderItems.length > 0 && !cancelStatuses.includes(marketplaceOrder.status)) {
461
- await Promise.all(
462
- nonMatchedOrderItems.map(async item => {
463
- for (var foundVariation of foundVariations) {
464
- if (foundVariation.sku) {
465
- let allVariations: MarketplaceProductVariation[] = await tx
466
- .getRepository(MarketplaceProductVariation)
467
- .find({
468
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
469
- relations: [
470
- 'domain',
471
- 'marketplaceProduct',
472
- 'marketplaceProduct.marketplaceStore',
473
- 'marketplaceProduct.marketplaceStore.marketplaceDistributors'
474
- ]
475
- })
476
-
477
- let activeVariations: MarketplaceProductVariation[] = allVariations.filter(
478
- variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED'
479
- )
480
400
 
481
- await Promise.all(
482
- activeVariations.map(async variation => {
483
- 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
+ }
484
438
 
485
- variation.reserveQty -= item.qty
486
- variation.qty += item.qty
439
+ if (existingMarketplaceOrder) {
440
+ let existingOrderItems: MarketplaceOrderItem[] = []
441
+ existingOrderItems = existingMarketplaceOrder.marketplaceOrderItems
487
442
 
488
- variation = await tx.getRepository(MarketplaceProductVariation).save(variation)
489
- })
490
- )
491
- }
492
- }
493
- })
494
- )
443
+ existingOrderItems = await checkUpdateItemId(existingOrderItems, marketplaceOrderItems)
495
444
 
496
- await tx.getRepository(MarketplaceOrderItem).delete(nonMatchedOrderItems)
497
- }
445
+ if (existingMarketplaceOrder.isSplitted) {
446
+ marketplaceOrderItems = existingOrderItems.filter(
447
+ itm => itm.name == item.name && itm.marketplaceProductVariation.variationId == item.variationId
448
+ )
498
449
 
499
- if (!cancelStatuses.includes(marketplaceOrder.status)) {
500
- existingOrderItems = await Promise.all(
501
- marketplaceOrderItems.map(async item => {
502
- 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(
503
462
  itm =>
504
- itm.name == item.name &&
463
+ itm.name === item.name &&
505
464
  itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId
506
465
  )
507
- if (matchedOrderItem) {
508
- 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)
509
474
  if (foundVariation.sku) {
510
- let allVariations: MarketplaceProductVariation[] = await tx
511
- .getRepository(MarketplaceProductVariation)
512
- .find({
513
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
514
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
515
- })
516
-
517
- let activeVariations: MarketplaceProductVariation[] = allVariations.filter(
518
- variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED'
519
- )
475
+ await updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, item.qty * -1)
476
+ }
477
+ })
478
+ )
479
+
480
+ await tx.getRepository(MarketplaceOrderItem).delete(nonMatchedOrderItems)
481
+ }
520
482
 
521
- await Promise.all(
522
- activeVariations.map(async variation => {
523
- if (!existingMarketplaceOrder?.releaseOrderId && matchedOrderItem.qty - item.qty != 0) {
524
- await calculateReserveQtyForBundle(
525
- tx,
526
- variation,
527
- marketplaceOrder.domain,
528
- matchedOrderItem.qty - item.qty
529
- )
530
- }
531
-
532
- variation.reserveQty = existingMarketplaceOrder?.releaseOrderId
533
- ? variation.reserveQty
534
- : variation.reserveQty - item.qty + matchedOrderItem.qty
535
-
536
- variation.qty = existingMarketplaceOrder?.releaseOrderId
537
- ? variation.qty
538
- : variation.qty + item.qty - matchedOrderItem.qty
539
-
540
- variation = await tx.getRepository(MarketplaceProductVariation).save(variation)
541
- })
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
542
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
+ }
543
510
  }
544
- }
545
- return {
546
- ...matchedOrderItem,
547
- ...item,
548
- updater: user
549
- }
550
- }
551
- })
552
- )
553
- }
554
- } else {
555
- if (!cancelStatuses.includes(marketplaceOrder.status)) {
556
- existingOrderItems = await Promise.all(
557
- marketplaceOrderItems.map(async item => {
558
- const matchedOrderItem = existingOrderItems.find(
559
- itm =>
560
- itm.name == item.name &&
561
- itm.marketplaceProductVariation.variationId == item.marketplaceProductVariation.variationId
511
+ })
562
512
  )
563
- if (matchedOrderItem) {
564
- for (var foundVariation of foundVariations) {
565
- if (foundVariation.sku) {
566
- let allVariations: MarketplaceProductVariation[] = await tx
567
- .getRepository(MarketplaceProductVariation)
568
- .find({
569
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
570
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
571
- })
572
-
573
- let activeVariations: MarketplaceProductVariation[] = allVariations.filter(
574
- 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
575
526
  )
576
-
577
- await Promise.all(
578
- activeVariations.map(async variation => {
579
- if (!existingMarketplaceOrder?.releaseOrderId && matchedOrderItem.qty - item.qty != 0) {
580
- await calculateReserveQtyForBundle(
581
- tx,
582
- variation,
583
- marketplaceOrder.domain,
584
- matchedOrderItem.qty - item.qty
585
- )
586
- }
587
-
588
- variation.reserveQty = existingMarketplaceOrder?.releaseOrderId
589
- ? variation.reserveQty
590
- : variation.reserveQty - item.qty + matchedOrderItem.qty
591
-
592
- variation.qty = existingMarketplaceOrder?.releaseOrderId
593
- ? variation.qty
594
- : variation.qty + item.qty - matchedOrderItem.qty
595
-
596
- variation = await tx.getRepository(MarketplaceProductVariation).save(variation)
597
- })
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)
598
545
  )
546
+ if (foundVariation.sku) {
547
+ await updateQtyAndReserveQty(tx, foundVariation, marketplaceOrder, item.qty)
548
+ }
549
+ return {
550
+ ...item,
551
+ updater: user
552
+ }
599
553
  }
600
- }
601
- return {
602
- ...matchedOrderItem,
603
- ...item,
604
- updater: user
605
- }
606
- } else {
607
- for (var foundVariation of foundVariations) {
608
- if (foundVariation.sku) {
609
- let allVariations: MarketplaceProductVariation[] = await tx
610
- .getRepository(MarketplaceProductVariation)
611
- .find({
612
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
613
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
614
- })
615
-
616
- let activeVariations: MarketplaceProductVariation[] = allVariations.filter(
617
- variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED'
618
- )
554
+ })
555
+ )
556
+ }
557
+ }
619
558
 
620
- await Promise.all(
621
- activeVariations.map(async variation => {
622
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty)
559
+ marketplaceOrderItems = existingOrderItems
623
560
 
624
- variation.reserveQty += item.qty
561
+ if (order?.orderShipping) {
562
+ savedMarketplaceOrderShipping.totalWeight = orderTotalWeight
625
563
 
626
- if (variation.qty - item.qty >= 0) {
627
- variation.qty -= item.qty
628
- }
564
+ if (marketplaceStore.eTrax) delete savedMarketplaceOrderShipping.trackingNo
629
565
 
630
- variation = await tx.getRepository(MarketplaceProductVariation).save(variation)
631
- })
632
- )
633
- }
634
- }
635
- return {
636
- ...item,
637
- updater: user
638
- }
639
- }
640
- })
641
- )
566
+ savedMarketplaceOrderShipping = await tx
567
+ .getRepository(MarketplaceOrderShipping)
568
+ .save(savedMarketplaceOrderShipping)
569
+ }
642
570
  }
643
- }
644
-
645
- marketplaceOrderItems = existingOrderItems
646
-
647
- if (order?.orderShipping) {
648
- savedMarketplaceOrderShipping.totalWeight = orderTotalWeight
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
+ }
649
578
 
650
- if (marketplaceStore.eTrax) delete savedMarketplaceOrderShipping.trackingNo
579
+ if (order?.orderShipping) {
580
+ savedMarketplaceOrderShipping.totalWeight = orderTotalWeight
581
+ if (marketplaceStore.eTrax) delete savedMarketplaceOrderShipping.trackingNo
651
582
 
652
- savedMarketplaceOrderShipping = await tx
653
- .getRepository(MarketplaceOrderShipping)
654
- .save(savedMarketplaceOrderShipping)
583
+ savedMarketplaceOrderShipping = await tx
584
+ .getRepository(MarketplaceOrderShipping)
585
+ .save(savedMarketplaceOrderShipping)
586
+ }
587
+ }
588
+ }
655
589
  }
656
- }
657
- } else {
658
- if (!cancelStatuses.includes(marketplaceOrder.status)) {
659
- for (var foundVariation of foundVariations) {
660
- if (foundVariation.sku) {
661
- let allVariations: MarketplaceProductVariation[] = await tx
662
- .getRepository(MarketplaceProductVariation)
663
- .find({
664
- where: { domain: foundVariation.domain, sku: foundVariation.sku },
665
- relations: ['domain', 'marketplaceProduct', 'marketplaceProduct.marketplaceStore']
666
- })
667
590
 
668
- let activeVariations: MarketplaceProductVariation[] = allVariations.filter(
669
- variation => variation.marketplaceProduct.marketplaceStore.status != 'TERMINATED'
670
- )
671
- let item = order.orderItems.find(e => e.variationId == foundVariation.variationId)
672
- await Promise.all(
673
- activeVariations.map(async variation => {
674
- await calculateReserveQtyForBundle(tx, variation, marketplaceOrder.domain, item.qty)
591
+ await tx.getRepository(MarketplaceOrder).save(marketplaceOrder)
592
+ await tx.getRepository(MarketplaceOrderItem).save(marketplaceOrderItems)
675
593
 
676
- 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
+ })
677
603
 
678
- if (variation.qty - item.qty >= 0) {
679
- variation.qty -= item.qty
680
- }
604
+ let product: Product = await tx.getRepository(Product).findOne({
605
+ where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku, deletedAt: IsNull() },
606
+ relations: ['productDetails']
607
+ })
681
608
 
682
- variation = await tx.getRepository(MarketplaceProductVariation).save(variation)
683
- })
684
- )
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
+ })
685
615
  }
686
616
 
687
- if (order?.orderShipping) {
688
- savedMarketplaceOrderShipping.totalWeight = orderTotalWeight
689
- if (marketplaceStore.eTrax) delete savedMarketplaceOrderShipping.trackingNo
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
+ })
690
633
 
691
- savedMarketplaceOrderShipping = await tx
692
- .getRepository(MarketplaceOrderShipping)
693
- .save(savedMarketplaceOrderShipping)
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
+ }
694
646
  }
695
647
  }
696
- }
697
- }
698
-
699
- await tx.getRepository(MarketplaceOrder).save(marketplaceOrder)
700
- await tx.getRepository(MarketplaceOrderItem).save(marketplaceOrderItems)
701
-
702
- for (let i = 0; i < marketplaceOrderItems.length; i++) {
703
- const marketplaceOrderItem: MarketplaceOrderItem = marketplaceOrderItems[i]
704
- const marketplaceProductVariation: MarketplaceProductVariation =
705
- marketplaceOrderItem.marketplaceProductVariation
706
- let existingMarketplaceOrderShippingItems: MarketplaceOrderShippingItem[] = await tx
707
- .getRepository(MarketplaceOrderShippingItem)
708
- .find({
709
- where: { domain: marketplaceStore.domain, marketplaceOrderItem }
710
- })
711
-
712
- let product: Product = await tx.getRepository(Product).findOne({
713
- where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku, deletedAt: IsNull() },
714
- relations: ['productDetails']
715
- })
716
-
717
- let productBundle: ProductBundle
718
- if (!product) {
719
- productBundle = await tx.getRepository(ProductBundle).findOne({
720
- where: { domain: marketplaceStore.domain, sku: marketplaceProductVariation.sku },
721
- relations: ['productBundleSettings', 'productBundleSettings.product']
722
- })
723
- }
724
648
 
725
- if (existingMarketplaceOrderShippingItems && existingMarketplaceOrderShippingItems?.length) {
726
- } else {
727
- if (productBundle) {
728
- const productBundleSettings: ProductBundleSetting[] = productBundle.productBundleSettings
729
- let marketplaceOrderShippingItems: MarketplaceOrderShippingItem[] = []
730
- productBundleSettings.map(productBundleSetting => {
731
- let marketplaceOrderShippingItem: MarketplaceOrderShippingItem = new MarketplaceOrderShippingItem()
732
- marketplaceOrderShippingItem.name = uuid()
733
- marketplaceOrderShippingItem.qty = marketplaceOrderItem.qty * productBundleSetting.bundleQty
734
- marketplaceOrderShippingItem.domain = marketplaceStore.domain
735
- marketplaceOrderShippingItem.marketplaceOrderItem = marketplaceOrderItem
736
- marketplaceOrderShippingItem.marketplaceOrderShipping = savedMarketplaceOrderShipping
737
- marketplaceOrderShippingItem.product = productBundleSetting.product
738
-
739
- marketplaceOrderShippingItems.push(marketplaceOrderShippingItem)
740
- })
741
-
742
- await tx.getRepository(MarketplaceOrderShippingItem).save(marketplaceOrderShippingItems)
743
- } else {
744
- let marketplaceOrderShippingItem: MarketplaceOrderShippingItem = new MarketplaceOrderShippingItem()
745
- marketplaceOrderShippingItem.name = uuid()
746
- marketplaceOrderShippingItem.qty = marketplaceOrderItem.qty
747
- marketplaceOrderShippingItem.domain = marketplaceStore.domain
748
- marketplaceOrderShippingItem.marketplaceOrderItem = marketplaceOrderItem
749
- marketplaceOrderShippingItem.marketplaceOrderShipping = savedMarketplaceOrderShipping
750
- marketplaceOrderShippingItem.product = product ? product : null
751
-
752
- await tx.getRepository(MarketplaceOrderShippingItem).save(marketplaceOrderShippingItem)
649
+ if (i == marketplaceOrders.length - 1) {
650
+ lastOrderId = order.name
753
651
  }
652
+ } catch (e) {
653
+ logger.error(`Order no: ${marketplaceOrders[i]}: ${e}`)
754
654
  }
755
- }
756
-
757
- if (i == marketplaceOrders.length - 1) {
758
- lastOrderId = order.name
759
- }
655
+ })
760
656
  }
761
657
 
762
658
  if (more) page++
@@ -781,56 +677,85 @@ export const syncMarketplaceOrder = {
781
677
  hasMore = more
782
678
  }
783
679
 
784
- await Promise.all(
785
- payoutDateList.map(async item => {
786
- await tx.getRepository(MarketplaceOrder).update(
787
- {
788
- orderNo: item.orderNo
789
- },
790
- {
791
- payoutDate: item.payoutDate
792
- }
793
- )
794
- })
795
- )
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
+ })
796
694
  }
797
695
  return true
798
696
  }
799
697
  }
800
698
 
801
- 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
802
716
  const productBundle: ProductBundle = await tx.getRepository(ProductBundle).findOne({
803
- where: { sku: variation.sku, domain }
717
+ where: { sku: variation.sku, domain },
718
+ relations: ['productBundleSettings', 'productBundleSettings.product']
804
719
  })
805
720
 
806
721
  if (productBundle) {
807
- const productBundleSettings: ProductBundleSetting[] = await tx.getRepository(ProductBundleSetting).find({
808
- where: { productBundle },
809
- relations: ['productBundle', 'product']
810
- })
811
-
812
- for (let setting of productBundleSettings) {
813
- const product: Product = await tx.getRepository(Product).findOne({
814
- where: { id: setting.product.id }
815
- })
816
-
722
+ for (let setting of productBundle.productBundleSettings) {
817
723
  const mpvs: MarketplaceProductVariation[] = await tx.getRepository(MarketplaceProductVariation).find({
818
- where: { domain, sku: product.sku },
724
+ where: { domain, sku: setting.product.sku },
819
725
  relations: ['domain']
820
726
  })
821
727
 
822
728
  for (let mpv of mpvs) {
823
- if (operator === '+') {
824
- 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
+
825
746
  if (mpv.qty - setting.bundleQty * qty >= 0) {
826
- mpv.qty -= setting.bundleQty * qty
747
+ updatedQty += setting.bundleQty * qty
827
748
  }
828
749
  }
829
- if (operator === '-') {
830
- mpv.reserveQty -= setting.bundleQty * qty
831
- mpv.qty += setting.bundleQty * qty
832
- }
833
- 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()
834
759
  }
835
760
  }
836
761
  }
@@ -844,10 +769,81 @@ function checkUpdateItemId(existingOrderItems, marketplaceOrderItems) {
844
769
  let existingItemByVariation = existingOrderItems.find(
845
770
  i => i.marketplaceProductVariation.id == item.marketplaceProductVariation.id
846
771
  )
847
- existingOrderItems = existingOrderItems.filter(i => i != existingItemByVariation)
848
- existingItemByVariation.name = item.name
849
- existingOrderItems.push(existingItemByVariation)
772
+ if (existingItemByVariation) {
773
+ existingOrderItems = existingOrderItems.filter(i => i != existingItemByVariation)
774
+ existingItemByVariation.name = item.name
775
+ existingOrderItems.push(existingItemByVariation)
776
+ }
850
777
  }
851
778
  }
852
779
  return existingOrderItems
853
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
+ }