@things-factory/marketplace-base 4.1.22 → 4.1.29

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