diff --git a/packages/medusa-plugin-brightpearl/src/loaders/inventory.js b/packages/medusa-plugin-brightpearl/src/loaders/inventory.js index f60a6423a1..fc76a4fdf0 100644 --- a/packages/medusa-plugin-brightpearl/src/loaders/inventory.js +++ b/packages/medusa-plugin-brightpearl/src/loaders/inventory.js @@ -5,13 +5,9 @@ const inventorySync = async (container, options) => { const brightpearlService = container.resolve("brightpearlService") const eventBus = container.resolve("eventBusService") try { - const client = await brightpearlService.getClient() const pattern = options.inventory_sync_cron - eventBus.createCronJob( - "inventory-sync", - {}, - pattern, - brightpearlService.syncInventory + eventBus.createCronJob("inventory-sync", {}, pattern, () => + brightpearlService.syncInventory() ) } catch (err) { if (err.name === "not_allowed") { diff --git a/packages/medusa-plugin-brightpearl/src/services/brightpearl.js b/packages/medusa-plugin-brightpearl/src/services/brightpearl.js index a2b5d5d12f..8d4c197bcb 100644 --- a/packages/medusa-plugin-brightpearl/src/services/brightpearl.js +++ b/packages/medusa-plugin-brightpearl/src/services/brightpearl.js @@ -126,7 +126,6 @@ class BrightpearlService extends BaseService { async syncInventory() { const client = await this.getClient() - const variants = await this.productVariantService_.list() let search = true let bpProducts = [] @@ -141,31 +140,39 @@ class BrightpearlService extends BaseService { } if (bpProducts.length) { - const productRange = `${bpProducts[0].productId}-${ - bpProducts[bpProducts.length - 1].productId - }` + const productRange = bpProducts + .map(({ productId }) => productId) + .join(",") 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 + bpProducts.map(async (bpProduct) => { + const { SKU: sku, productId } = bpProduct + + const variant = await this.productVariantService_ + .retrieveBySKU(sku, { + select: ["id", "manage_inventory", "inventory_quantity"], + }) + .catch((_) => undefined) + + const prodAvail = availabilities[productId] + + let onHand = 0 + if ( + prodAvail && + prodAvail.warehouses && + prodAvail.warehouses[`${this.options.warehouse}`] + ) { + onHand = prodAvail.warehouses[`${this.options.warehouse}`].onHand } - 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, + if (variant && variant.manage_inventory) { + if (parseInt(variant.inventory_quantity) !== parseInt(onHand)) { + return this.productVariantService_.update(variant.id, { + inventory_quantity: parseInt(onHand), }) } }