@things-factory/marketplace-base 4.1.27 → 4.1.28

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