@things-factory/marketplace-base 4.1.19 → 4.1.28

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