@things-factory/marketplace-base 4.1.27 → 4.1.31

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