fix(medusa-plugin-brightpearl): more gentle inventory syncs

This commit is contained in:
Sebastian Rindom committed 2020-08-28 11:19:20 +02:00
1 parent 70e8fcde41
commit e25478034b
4 files changed
+86 -38

No files matched your search

@@ -125,27 +125,51 @@ class BrightpearlService extends BaseService {
async syncInventory() {
const client = await this.getClient()
const variants = await this.productVariantService_.list()
return Promise.all(
variants.map(async (v) => {
const brightpearlProduct = await this.retrieveProductBySKU(v.sku)
if (!brightpearlProduct) {
return
}
const { productId } = brightpearlProduct
const availability = await client.products.retrieveAvailability(
productId
)
const onHand = availability[productId].total.onHand
let search = true
let bpProducts = []
while (search) {
const { products, metadata } = await client.products.search(search)
bpProducts = [...bpProducts, ...products]
if (metadata.morePagesAvailable) {
search = `firstResult=${metadata.lastResult + 1}`
} else {
search = false
}
}
// Only update if the inventory levels have changed
if (parseInt(v.inventory_quantity) !== parseInt(onHand)) {
return this.productVariantService_.update(v._id, {
inventory_quantity: onHand,
})
}
})
)
if (bpProducts.length) {
const productRange = `${bpProducts[0].productId}-${
bpProducts[bpProducts.length - 1].productId
}`
const availabilities = await client.products.retrieveAvailability(
productRange
)
return Promise.all(
variants.map(async (v) => {
const brightpearlProduct = bpProducts.find(
(prod) => prod.SKU === v.sku
)
if (!brightpearlProduct) {
return
}
const { productId } = brightpearlProduct
const availability = availabilities[productId]
if (availability) {
const onHand = availability.total.onHand
// Only update if the inventory levels have changed
if (parseInt(v.inventory_quantity) !== parseInt(onHand)) {
return this.productVariantService_.update(v._id, {
inventory_quantity: onHand,
})
}
}
})
)
}
}
async updateInventory(productId) {
@@ -289,6 +289,18 @@ class BrightpearlClient {
})
.then(({ data }) => data.response && data.response[0])
},
search: (search) => {
return this.client_
.request({
url: `/product-service/product-search?${search}`,
})
.then(({ data }) => {
return {
products: this.buildSearchResults_(data.response),
metadata: data.response.metaData,
}
})
},
retrieveBySKU: (sku) => {
return this.client_
.request({