From 33f8e1fa2ccdd7d88446eeb604828d7dd6d2134f Mon Sep 17 00:00:00 2001 From: Matt Gros Date: Tue, 24 Nov 2026 14:48:29 -0500 Subject: [PATCH 1/2] Push kit availability to Shopify on cores that sell kits from components Inventoros 2.7 sells a kit by taking its components and never moves the kit's own stock, so a mapped kit was pushed a stale stored number and never updated. On those cores (KitStock::supported()): - a kit is pushed how many its components can make (KitSaleService, on hand less reservations) at the primary or "all stock" location; - a component's stock_changed (stock or reservations) also queues every mapped kit that uses it; - the scheduled sync re-pushes mapped kits, because editing a kit's component list fires no core hook; - a Shopify level for a kit is never pulled into Inventoros. Older cores push the kit's own stock as before. Orders for kits already import through OrderService, which takes the components or refuses the order naming the short component. --- CHANGELOG.md | 4 + docs/configuration.md | 1 + docs/features.md | 1 + src/Console/SyncCommand.php | 10 +- src/Support/Listeners.php | 36 +++++- src/Sync/InventoryPull.php | 4 +- src/Sync/InventoryPush.php | 12 +- src/Sync/KitStock.php | 97 ++++++++++++++ tests/Feature/KitAvailabilityTest.php | 178 ++++++++++++++++++++++++++ 9 files changed, 332 insertions(+), 11 deletions(-) create mode 100644 src/Sync/KitStock.php create mode 100644 tests/Feature/KitAvailabilityTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a57de5..cb8cc55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this plugin are documented here. The format follows [Keep ## [Unreleased] +### Added + +- Kits on Inventoros 2.7 and newer, which sell a kit from its components. A kit mapped to a Shopify variant is pushed how many kits its components can make (on hand less reservations, the number Inventoros sells against), at the primary or "all stock" location. It is pushed again whenever one of its components' stock or reservations changes, and the 15-minute scheduled sync re-pushes mapped kits, so a change to a kit's component list reaches Shopify within one interval. A Shopify order for a kit takes its components through core. One Inventoros cannot fill is held back with the short component named, like any short order. When Shopify owns stock, its level for a kit is never written back, because the kit keeps no stock of its own. Older cores push a kit's own stock as before. + ## [1.4.0] - Unreleased ### Added diff --git a/docs/configuration.md b/docs/configuration.md index affce8e..4716c07 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -31,6 +31,7 @@ Admins hold both. On Inventoros versions without plugin permissions they fall ba - The sidebar item is translated on cores that translate plugin menu items (`label_key`). - Known limitations and SDK gaps: - Orders take stock when imported. External Shopify checkout reservations are not created in Inventoros before the order webhook arrives. + - Kits (Inventoros 2.7+) are pushed as one total at the primary or "all stock" location, because core counts kit availability across all warehouses. Two kits that share a component each show the full count that component allows, so Shopify can sell more of them together than the shared component covers until the next push. Inventoros then holds back the order it cannot fill. Core reports no hook when a kit's component list is edited, so that change reaches Shopify with the next scheduled sync (every 15 minutes) or the next stock change of a component. - On cores with variant location stock, each variant syncs its own bins per mapped warehouse. Older cores retain primary-location variant sync. Local and global stock holds reduce pushed availability; warehouse quantities share a single SKU availability budget, allocated primary location first. - On cores before Inventoros#254, `OrderService::cancel()` takes its actor from the signed-in user, so the plugin signs in the connection's user for that one call when it cancels in a background job. Newer cores take the actor as a parameter and nobody is signed in. - Optional shipment fulfilment and tracking push is available on cores with shipment notification ownership; order edits after import are not applied. Completed payment/refund records can be imported with the optional ledger setting. diff --git a/docs/features.md b/docs/features.md index 18d31eb..fe82d89 100644 --- a/docs/features.md +++ b/docs/features.md @@ -4,6 +4,7 @@ - **Orders into Inventoros, exactly once**: through core's `OrderService` (ledger rows, bins, serials), with `external_reference` set, safe against duplicate, replayed and out-of-order webhooks. Shopify cancellations cancel and restock through core. - **Stock both ways, one owner**: Inventoros quantities pushed per mapped location, coalesced per item and queued; or Shopify levels applied as audited core adjustments. +- **Kits** (Inventoros 2.7+): a mapped kit shows Shopify how many its components can make, and is re-pushed when a component's stock or reservations change; Shopify orders for it take the components. - **Products both ways, one owner**: Shopify titles and prices copied into Inventoros, or Inventoros edits pushed to Shopify. - **Mapping review**: SKU matches are suggestions until you confirm them; conflicts and unmatched variants are listed, never guessed. Shopify locations map to warehouses. - **Webhooks** verified by HMAC, stored in an idempotent inbox and processed in the background, plus a 15-minute incremental sync as a safety net. diff --git a/src/Console/SyncCommand.php b/src/Console/SyncCommand.php index 6233363..ef91392 100644 --- a/src/Console/SyncCommand.php +++ b/src/Console/SyncCommand.php @@ -14,14 +14,18 @@ use Inventoros\Plugins\Shopify\Kit\Models\WebhookInboxEntry; use Inventoros\Plugins\Shopify\Kit\Outbox\Outbox; use Inventoros\Plugins\Shopify\Sync\FulfilmentPush; +use Inventoros\Plugins\Shopify\Shopify\SyncPolicy; use Inventoros\Plugins\Shopify\Sync\InventoryPush; +use Inventoros\Plugins\Shopify\Sync\KitStock; use Inventoros\Plugins\Shopify\Sync\ProductPush; /** * shopify:sync, every 15 minutes: for each connection that can sync, * queue an incremental sync (products and orders changed since the * cursor), re-queue inbox entries left unprocessed (a worker died, the - * connection was paused) and drain due outbox rows. Only queues work. + * connection was paused), re-push mapped kits when Inventoros owns stock + * (a kit's component list can change without any stock moving; see + * KitStock) and drain due outbox rows. Only queues work. */ final class SyncCommand extends Command { @@ -57,6 +61,10 @@ public function handle(Outbox $outbox): int ProcessWebhook::dispatch($connection->id, (int) $entryId); } + if (SyncPolicy::for($connection)->pushesStock()) { + KitStock::queueMapped($connection); + } + if ($outbox->hasDue($connection, InventoryPush::KIND)) { PushInventory::dispatch($connection->id); } diff --git a/src/Support/Listeners.php b/src/Support/Listeners.php index e9b096e..5279376 100644 --- a/src/Support/Listeners.php +++ b/src/Support/Listeners.php @@ -19,6 +19,7 @@ use Inventoros\Plugins\Shopify\Sync\Catalog; use Inventoros\Plugins\Shopify\Sync\FulfilmentPush; use Inventoros\Plugins\Shopify\Sync\InventoryPush; +use Inventoros\Plugins\Shopify\Sync\KitStock; use Inventoros\Plugins\Shopify\Sync\ProductPush; use Throwable; @@ -35,7 +36,9 @@ final class Listeners /** * stock_changed($product, $variant, $change): queue a stock push for - * every connection that owns stock in Inventoros and maps this item. + * every connection that owns stock in Inventoros and maps this item, + * and for every mapped kit that has this product as a component (how + * many kits can be made just changed; see KitStock). * * @param array $change */ @@ -46,17 +49,38 @@ public static function stockChanged(mixed $product, mixed $variant = null, mixed } self::guard(function () use ($product, $variant) { - [$type, $id] = $variant instanceof ProductVariant ? ['variant', (int) $variant->id] : ['product', (int) $product->id]; + $organizationId = (int) $product->organization_id; + $connections = self::connected($organizationId); + if ($connections->isEmpty()) { + return; + } + + $subjects = [$variant instanceof ProductVariant ? ['variant', (int) $variant->id] : ['product', (int) $product->id]]; + if (! $variant instanceof ProductVariant) { + foreach (KitStock::kitsUsing($organizationId, [(int) $product->id]) as $kitId) { + $subjects[] = ['product', $kitId]; + } + } - foreach (self::connected((int) $product->organization_id) as $connection) { + foreach ($connections as $connection) { $policy = SyncPolicy::for($connection); - if (! $policy->pushesStock() || ! self::isMapped($connection, $type, $id)) { + if (! $policy->pushesStock()) { continue; } - app(Outbox::class)->put($connection, InventoryPush::KIND, InventoryPush::subject($type, $id), [], $policy->pushDelay()); - PushInventory::dispatch($connection->id)->delay(now()->addSeconds($policy->pushDelay())); + $queued = false; + foreach ($subjects as [$type, $id]) { + if (! self::isMapped($connection, $type, $id)) { + continue; + } + app(Outbox::class)->put($connection, InventoryPush::KIND, InventoryPush::subject($type, $id), [], $policy->pushDelay()); + $queued = true; + } + + if ($queued) { + PushInventory::dispatch($connection->id)->delay(now()->addSeconds($policy->pushDelay())); + } } }); } diff --git a/src/Sync/InventoryPull.php b/src/Sync/InventoryPull.php index bb94735..bbba934 100644 --- a/src/Sync/InventoryPull.php +++ b/src/Sync/InventoryPull.php @@ -106,7 +106,9 @@ public function apply(Connection $connection, string $inventoryItemId, string $l } $product = Core::products($connection->organization_id)->lockForUpdate()->find($item->internal_id); - if (! $product instanceof Product) { + // A kit sold from its components keeps no stock of its own, so + // Shopify's count for it is never written back (see KitStock). + if (! $product instanceof Product || KitStock::isKit($product)) { return 'skipped'; } diff --git a/src/Sync/InventoryPush.php b/src/Sync/InventoryPush.php index 375819c..c7caa69 100644 --- a/src/Sync/InventoryPush.php +++ b/src/Sync/InventoryPush.php @@ -30,6 +30,9 @@ * product without any bins its total, at the primary location only * variant its own bins per warehouse on capable cores; * primary only on older releases + * kit (core 2.7+) how many its components can make, at the + * primary or "all stock" location only (see + * KitStock) * Reservations reduce availability. Negative stock is pushed as 0. */ final class InventoryPush @@ -144,13 +147,16 @@ public function quantitiesFor(Connection $connection, string $subject, Collectio return []; } $stock = app(InventoryStock::class); - $budget = max(0, (int) $target->stock - $stock->held($target)); + // A kit sold from its components has no stock or bins of its own: + // its availability is placed like an unbinned product's. + $kit = KitStock::isKit($target); + $budget = $kit ? KitStock::available($target) : max(0, (int) $target->stock - $stock->held($target)); if ($type === 'variant' && ! InventoryStock::supportsVariantBins()) { return $primary === null ? [] : [$base + ['location_id' => $primary->external_id, 'location_label' => (string) $primary->external_label, 'quantity' => $budget]]; } - $free = $stock->freeByWarehouse($target); + $free = $kit ? collect() : $stock->freeByWarehouse($target); // Unassigned stock retains the historic primary-location fallback. - $unassigned = $stock->rows($target)->isEmpty(); + $unassigned = $kit || $stock->rows($target)->isEmpty(); foreach ($locations->sortBy(fn ($location) => [$location->id === $primary?->id ? 0 : 1, $location->id]) as $location) { if ($location->internal_type === Locations::ALL_STOCK) { $quantity = $budget; diff --git a/src/Sync/KitStock.php b/src/Sync/KitStock.php new file mode 100644 index 0000000..1c9eb4e --- /dev/null +++ b/src/Sync/KitStock.php @@ -0,0 +1,97 @@ +type === 'kit' && self::supported(); + } + + /** + * Whole kits the components can make now; 0 for a kit core cannot sell. + */ + public static function available(Product $kit): int + { + return max(0, app(KitSaleService::class)->available($kit)); + } + + /** + * Ids of this organization's kits that have any of these products as a + * component, in ascending order. + * + * @param list $productIds + * @return list + */ + public static function kitsUsing(int $organizationId, array $productIds): array + { + if ($productIds === [] || ! self::supported()) { + return []; + } + + return ProductComponent::query() + ->whereIn('component_product_id', $productIds) + ->whereIn('parent_product_id', Core::products($organizationId)->where('type', 'kit')->select('products.id')) + ->distinct() + ->orderBy('parent_product_id') + ->pluck('parent_product_id') + ->map(fn ($id) => (int) $id) + ->all(); + } + + /** + * Queue a stock push for every mapped kit of the connection. + * + * Core reports no hook when a kit's component list is edited, so the + * scheduled sync calls this: a changed bill of materials reaches Shopify + * within one schedule interval. Pushes are absolute, so an unchanged kit + * is simply set to the same quantity again. + */ + public static function queueMapped(Connection $connection): int + { + if (! self::supported()) { + return 0; + } + + $ids = Mapping::query() + ->where('connection_id', $connection->id) + ->where('entity', Catalog::ENTITY) + ->where('status', Mapping::MAPPED) + ->where('internal_type', 'product') + ->whereIn('internal_id', Core::products($connection->organization_id)->where('type', 'kit')->select('products.id')) + ->orderBy('internal_id') + ->pluck('internal_id'); + + $outbox = app(Outbox::class); + foreach ($ids as $id) { + $outbox->put($connection, InventoryPush::KIND, InventoryPush::subject('product', (int) $id)); + } + + return $ids->count(); + } +} diff --git a/tests/Feature/KitAvailabilityTest.php b/tests/Feature/KitAvailabilityTest.php new file mode 100644 index 0000000..f3af2f5 --- /dev/null +++ b/tests/Feature/KitAvailabilityTest.php @@ -0,0 +1,178 @@ +markTestSkipped('This Inventoros release sells kits from their own stock.'); + } + + $this->setUpWorld(); + $this->mapLocations(); + $this->mapCatalog(); + + $this->partA = $this->product('PART-A', 'Part A', 7, $this->binA); + $this->partB = $this->product('PART-B', 'Part B', 20, $this->binA); + $this->kit = Product::create([ + 'organization_id' => $this->organization->id, + 'sku' => 'KIT-1', + 'name' => 'Bolt kit', + 'type' => 'kit', + 'price' => 12, + 'currency' => 'USD', + 'stock' => 0, + 'min_stock' => 0, + 'is_active' => true, + ]); + ProductComponent::create(['parent_product_id' => $this->kit->id, 'component_product_id' => $this->partA->id, 'quantity' => 2, 'sort_order' => 0]); + ProductComponent::create(['parent_product_id' => $this->kit->id, 'component_product_id' => $this->partB->id, 'quantity' => 1, 'sort_order' => 1]); + + Mapping::query() + ->where('connection_id', $this->store->id) + ->where('entity', Catalog::ENTITY) + ->where('internal_type', 'product') + ->where('internal_id', $this->bolt->id) + ->update(['internal_id' => $this->kit->id]); + + $this->shopify->pushes = []; + $this->shopify->calls = []; + } + + /** + * @return array "item@location" => quantity + */ + private function pushed(): array + { + $out = []; + foreach ($this->shopify->pushedQuantities() as $row) { + $out[$row['inventory_item_id'].'@'.$row['location_id']] = $row['quantity']; + } + + return $out; + } + + public function test_a_component_stock_change_pushes_how_many_kits_can_be_made_at_the_primary_location(): void + { + StockAdjustment::adjust($this->partA->fresh(), -1, 'manual', 'test', null, null, true, $this->admin, $this->binA->id); + + // 6 of Part A make 3 kits; the kit has no bins, so only the primary + // location is set, never the other mapped warehouse. + $this->assertSame(['4001@1001' => 3], $this->pushed()); + } + + public function test_reserving_a_component_lowers_the_pushed_kit_count(): void + { + app(StockReservationService::class)->reserve($this->partB->fresh(), null, 19, 'shop', 'CART-1'); + + $this->assertSame(['4001@1001' => 1], $this->pushed()); + } + + public function test_a_change_to_an_unrelated_product_does_not_push_the_kit(): void + { + Queue::fake(); + $loose = $this->product('LOOSE-1', 'Loose part', 5, $this->binA); + + StockAdjustment::adjust($loose->fresh(), 1, 'manual', 'test', null, null, true, $this->admin, $this->binA->id); + + $this->assertSame(0, OutboxEntry::query()->count()); + Queue::assertNotPushed(PushInventory::class); + } + + public function test_the_scheduled_sync_repushes_mapped_kits_so_a_component_list_edit_reaches_shopify(): void + { + Queue::fake(); + ProductComponent::query()->where('parent_product_id', $this->kit->id)->where('component_product_id', $this->partA->id)->update(['quantity' => 1]); + + $this->artisan('shopify:sync')->assertSuccessful(); + + $this->assertSame(['p'.$this->kit->id], OutboxEntry::query()->pluck('subject')->all()); + Queue::assertPushed(PushInventory::class); + + (new PushInventory($this->store->id))->handle(); + + $this->assertSame(['4001@1001' => 7], $this->pushed()); + } + + public function test_a_kit_core_cannot_sell_is_pushed_as_zero(): void + { + ProductComponent::query()->where('parent_product_id', $this->kit->id)->where('component_product_id', $this->partA->id)->update(['quantity' => 1.5]); + + KitStock::queueMapped($this->store); + (new PushInventory($this->store->id))->handle(); + + $this->assertSame(['4001@1001' => 0], $this->pushed()); + } + + public function test_a_shopify_order_for_the_kit_takes_its_components(): void + { + $this->webhook('orders/create', $this->payload('orders_create'))->assertOk(); + + $order = Order::withoutGlobalScopes()->where('organization_id', $this->organization->id)->where('source', 'shopify')->with('items')->sole(); + $this->assertSame(2, (int) $order->items->firstWhere('product_id', $this->kit->id)->quantity); + $this->assertSame(3, $this->partA->fresh()->stock, '2 kits take 4 of Part A'); + $this->assertSame(18, $this->partB->fresh()->stock, '2 kits take 2 of Part B'); + $this->assertSame(0, $this->kit->fresh()->stock, 'the kit itself holds no stock'); + } + + public function test_a_shopify_order_for_more_kits_than_can_be_made_is_held_back_naming_the_component(): void + { + StockAdjustment::adjust($this->partA->fresh(), -6, 'manual', 'test', null, null, true, $this->admin, $this->binA->id); + + $this->webhook('orders/create', $this->payload('orders_create'))->assertOk(); + + $this->assertSame(0, Order::withoutGlobalScopes()->where('organization_id', $this->organization->id)->where('source', 'shopify')->count()); + $this->assertSame(1, $this->partA->fresh()->stock); + $this->assertSame(20, $this->partB->fresh()->stock); + $error = DeadLetter::query()->sole()->error; + $this->assertStringContainsString('not enough stock', $error); + $this->assertStringContainsString('Part A', $error); + } + + public function test_a_shopify_level_for_the_kit_is_never_written_back_to_inventoros(): void + { + $this->store->forceFill(['settings' => array_merge($this->store->settings, ['stock_source' => 'shopify'])])->save(); + + $this->webhook('inventory_levels/update', $this->payload('inventory_levels_update'))->assertOk(); + + $this->assertSame(0, $this->kit->fresh()->stock); + $this->assertSame(0, StockAdjustment::query()->where('product_id', $this->kit->id)->count()); + } +} From 81ec63e083797c989c9a8e8c8c433dfb5edcf353 Mon Sep 17 00:00:00 2001 From: Matt Gros Date: Sun, 29 Nov 2026 21:23:09 -0500 Subject: [PATCH 2/2] Send a kit's count again only when it changed --- CHANGELOG.md | 2 +- docs/configuration.md | 2 +- docs/features.md | 2 +- src/Console/SyncCommand.php | 8 ++-- src/ShopifyPlugin.php | 5 ++ src/Support/Listeners.php | 67 ++++++++++++++++++++------- src/Sync/InventoryPush.php | 5 ++ src/Sync/KitStock.php | 65 +++++++++++++++++++------- tests/Feature/KitAvailabilityTest.php | 37 ++++++++++++--- 9 files changed, 145 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb8cc55..189d6da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this plugin are documented here. The format follows [Keep ### Added -- Kits on Inventoros 2.7 and newer, which sell a kit from its components. A kit mapped to a Shopify variant is pushed how many kits its components can make (on hand less reservations, the number Inventoros sells against), at the primary or "all stock" location. It is pushed again whenever one of its components' stock or reservations changes, and the 15-minute scheduled sync re-pushes mapped kits, so a change to a kit's component list reaches Shopify within one interval. A Shopify order for a kit takes its components through core. One Inventoros cannot fill is held back with the short component named, like any short order. When Shopify owns stock, its level for a kit is never written back, because the kit keeps no stock of its own. Older cores push a kit's own stock as before. +- Kits on Inventoros 2.7 and newer, which sell a kit from its components. A kit mapped to a Shopify variant is pushed how many kits its components can make (on hand less reservations, the number Inventoros sells against), at the primary or "all stock" location. It is pushed again whenever one of its components' stock or reservations, or its component list, changes. The 15-minute scheduled sync also pushes a mapped kit whose count differs from the last one sent; it never re-sends an unchanged count, which could put back on sale what Shopify has sold but Inventoros has not imported yet. A Shopify order for a kit takes its components through core. One Inventoros cannot fill is held back with the short component named, like any short order. When Shopify owns stock, its level for a kit is never written back, because the kit keeps no stock of its own. Older cores push a kit's own stock as before. ## [1.4.0] - Unreleased diff --git a/docs/configuration.md b/docs/configuration.md index 4716c07..62bf655 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -31,7 +31,7 @@ Admins hold both. On Inventoros versions without plugin permissions they fall ba - The sidebar item is translated on cores that translate plugin menu items (`label_key`). - Known limitations and SDK gaps: - Orders take stock when imported. External Shopify checkout reservations are not created in Inventoros before the order webhook arrives. - - Kits (Inventoros 2.7+) are pushed as one total at the primary or "all stock" location, because core counts kit availability across all warehouses. Two kits that share a component each show the full count that component allows, so Shopify can sell more of them together than the shared component covers until the next push. Inventoros then holds back the order it cannot fill. Core reports no hook when a kit's component list is edited, so that change reaches Shopify with the next scheduled sync (every 15 minutes) or the next stock change of a component. + - Kits (Inventoros 2.7+) are pushed as one total at the primary or "all stock" location, because core counts kit availability across all warehouses. Two kits that share a component each show the full count that component allows, so Shopify can sell more of them together than the shared component covers until the next push. Inventoros then holds back the order it cannot fill. Editing a kit's component list pushes it at once. Other changes that alter the count without moving stock (such as deleting a component product) reach Shopify with the next scheduled sync, every 15 minutes, which sends only kits whose count changed. - On cores with variant location stock, each variant syncs its own bins per mapped warehouse. Older cores retain primary-location variant sync. Local and global stock holds reduce pushed availability; warehouse quantities share a single SKU availability budget, allocated primary location first. - On cores before Inventoros#254, `OrderService::cancel()` takes its actor from the signed-in user, so the plugin signs in the connection's user for that one call when it cancels in a background job. Newer cores take the actor as a parameter and nobody is signed in. - Optional shipment fulfilment and tracking push is available on cores with shipment notification ownership; order edits after import are not applied. Completed payment/refund records can be imported with the optional ledger setting. diff --git a/docs/features.md b/docs/features.md index fe82d89..470fef2 100644 --- a/docs/features.md +++ b/docs/features.md @@ -4,7 +4,7 @@ - **Orders into Inventoros, exactly once**: through core's `OrderService` (ledger rows, bins, serials), with `external_reference` set, safe against duplicate, replayed and out-of-order webhooks. Shopify cancellations cancel and restock through core. - **Stock both ways, one owner**: Inventoros quantities pushed per mapped location, coalesced per item and queued; or Shopify levels applied as audited core adjustments. -- **Kits** (Inventoros 2.7+): a mapped kit shows Shopify how many its components can make, and is re-pushed when a component's stock or reservations change; Shopify orders for it take the components. +- **Kits** (Inventoros 2.7+): a mapped kit shows Shopify how many its components can make, and is re-pushed when a component's stock or reservations, or its component list, change; Shopify orders for it take the components. - **Products both ways, one owner**: Shopify titles and prices copied into Inventoros, or Inventoros edits pushed to Shopify. - **Mapping review**: SKU matches are suggestions until you confirm them; conflicts and unmatched variants are listed, never guessed. Shopify locations map to warehouses. - **Webhooks** verified by HMAC, stored in an idempotent inbox and processed in the background, plus a 15-minute incremental sync as a safety net. diff --git a/src/Console/SyncCommand.php b/src/Console/SyncCommand.php index ef91392..65d5fb0 100644 --- a/src/Console/SyncCommand.php +++ b/src/Console/SyncCommand.php @@ -23,9 +23,9 @@ * shopify:sync, every 15 minutes: for each connection that can sync, * queue an incremental sync (products and orders changed since the * cursor), re-queue inbox entries left unprocessed (a worker died, the - * connection was paused), re-push mapped kits when Inventoros owns stock - * (a kit's component list can change without any stock moving; see - * KitStock) and drain due outbox rows. Only queues work. + * connection was paused), queue mapped kits whose count changed without a + * hook when Inventoros owns stock (KitStock) and drain due outbox rows. + * Only queues work. */ final class SyncCommand extends Command { @@ -62,7 +62,7 @@ public function handle(Outbox $outbox): int } if (SyncPolicy::for($connection)->pushesStock()) { - KitStock::queueMapped($connection); + KitStock::queueChanged($connection); } if ($outbox->hasDue($connection, InventoryPush::KIND)) { diff --git a/src/ShopifyPlugin.php b/src/ShopifyPlugin.php index 63df1f4..eb8a641 100644 --- a/src/ShopifyPlugin.php +++ b/src/ShopifyPlugin.php @@ -4,9 +4,11 @@ namespace Inventoros\Plugins\Shopify; +use App\Models\Inventory\ProductComponent; use Illuminate\Console\Application as Artisan; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Contracts\Debug\ExceptionHandler; +use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Route; use Inventoros\Plugins\Shopify\Console\PruneCommand; use Inventoros\Plugins\Shopify\Console\SyncCommand; @@ -182,6 +184,9 @@ private function registerHooks(): void add_action('product_updated', [Listeners::class, 'catalogChanged']); add_action('variant_updated', [Listeners::class, 'catalogChanged']); + // Core fires no hook when a kit's component list changes. + Event::listen(['eloquent.saved: '.ProductComponent::class, 'eloquent.deleted: '.ProductComponent::class], [Listeners::class, 'componentChanged']); + add_action(Kit::HOOK_PREFIX.'connection_verified', static function (Connection $connection, ?int $userId = null): void { RegisterWebhooks::dispatch($connection->id); RunSync::dispatch($connection->id, ['locations'], 'initial', 'user', $userId); diff --git a/src/Support/Listeners.php b/src/Support/Listeners.php index 5279376..b5f7e0c 100644 --- a/src/Support/Listeners.php +++ b/src/Support/Listeners.php @@ -5,9 +5,11 @@ namespace Inventoros\Plugins\Shopify\Support; use App\Models\Inventory\Product; +use App\Models\Inventory\ProductComponent; use App\Models\Inventory\ProductVariant; use App\Models\Shipping\Shipment; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Inventoros\Plugins\Shopify\Jobs\PushFulfilments; use Inventoros\Plugins\Shopify\Jobs\PushInventory; @@ -62,26 +64,29 @@ public static function stockChanged(mixed $product, mixed $variant = null, mixed } } - foreach ($connections as $connection) { - $policy = SyncPolicy::for($connection); + self::queue($connections, $subjects); + }); + } - if (! $policy->pushesStock()) { - continue; - } + /** + * eloquent.saved / eloquent.deleted on a core ProductComponent: queue + * the kit whose component list changed, after the surrounding + * transaction commits (core fires no hook for it). + */ + public static function componentChanged(mixed $component): void + { + if (! $component instanceof ProductComponent || ! KitStock::supported()) { + return; + } - $queued = false; - foreach ($subjects as [$type, $id]) { - if (! self::isMapped($connection, $type, $id)) { - continue; - } - app(Outbox::class)->put($connection, InventoryPush::KIND, InventoryPush::subject($type, $id), [], $policy->pushDelay()); - $queued = true; - } + DB::afterCommit(static function () use ($component): void { + self::guard(function () use ($component) { + $kit = Product::withoutGlobalScopes()->find($component->parent_product_id); - if ($queued) { - PushInventory::dispatch($connection->id)->delay(now()->addSeconds($policy->pushDelay())); + if (KitStock::isKit($kit)) { + self::queue(self::connected((int) $kit->organization_id), [['product', (int) $kit->id]]); } - } + }); }); } @@ -171,6 +176,36 @@ private static function connected(int $organizationId): Collection return self::$connections[$organizationId]; } + /** + * Queue a stock push of the items each connection maps. + * + * @param Collection $connections + * @param array $subjects [internal type, internal id] + */ + private static function queue(Collection $connections, array $subjects): void + { + foreach ($connections as $connection) { + $policy = SyncPolicy::for($connection); + + if (! $policy->pushesStock()) { + continue; + } + + $queued = false; + foreach ($subjects as [$type, $id]) { + if (! self::isMapped($connection, $type, $id)) { + continue; + } + app(Outbox::class)->put($connection, InventoryPush::KIND, InventoryPush::subject($type, $id), [], $policy->pushDelay()); + $queued = true; + } + + if ($queued) { + PushInventory::dispatch($connection->id)->delay(now()->addSeconds($policy->pushDelay())); + } + } + } + private static function isMapped(Connection $connection, string $type, int $id): bool { return Mapping::query() diff --git a/src/Sync/InventoryPush.php b/src/Sync/InventoryPush.php index c7caa69..dc6d8c3 100644 --- a/src/Sync/InventoryPush.php +++ b/src/Sync/InventoryPush.php @@ -80,6 +80,7 @@ public function push(Connection $connection, Collection $entries, SyncRun $run): $primary = $this->locations->primary($connection->id); $quantities = []; $lines = []; + $sent = []; foreach ($entries as $entry) { $rows = $this->quantitiesFor($connection, $entry->subject, $locations, $primary); @@ -91,6 +92,8 @@ public function push(Connection $connection, Collection $entries, SyncRun $run): if ($rows === []) { $this->recorder->count($run, 'skipped'); + } elseif (str_starts_with($entry->subject, 'p')) { + $sent[$rows[0]['internal_id']] = array_sum(array_column($rows, 'quantity')); } } @@ -101,6 +104,8 @@ public function push(Connection $connection, Collection $entries, SyncRun $run): $client->setInventoryQuantities($batch, $this->idempotencyKey($connection, $batch, $signature)); } + KitStock::rememberSent($connection, $sent); + foreach ($lines as $line) { $this->recorder->count($run, 'processed'); $this->recorder->count($run, 'updated'); diff --git a/src/Sync/KitStock.php b/src/Sync/KitStock.php index 1c9eb4e..ea4ffb6 100644 --- a/src/Sync/KitStock.php +++ b/src/Sync/KitStock.php @@ -7,6 +7,7 @@ use App\Models\Inventory\Product; use App\Models\Inventory\ProductComponent; use App\Services\Inventory\KitSaleService; +use Illuminate\Support\Collection; use Inventoros\Plugins\Shopify\Kit\Models\Connection; use Inventoros\Plugins\Shopify\Kit\Models\Mapping; use Inventoros\Plugins\Shopify\Kit\Outbox\Outbox; @@ -18,8 +19,9 @@ * There a kit holds no stock of its own: selling one takes its components, * so Shopify is told how many kits the components can make (on hand less * reservations, the number core itself sells against), and a kit is pushed - * again whenever one of its components moves. Older cores sell a kit from - * its own stock, so it is pushed like any other product. + * again whenever one of its components moves or its component list changes. + * Older cores sell a kit from its own stock, so it is pushed like any other + * product. */ final class KitStock { @@ -65,33 +67,60 @@ public static function kitsUsing(int $organizationId, array $productIds): array } /** - * Queue a stock push for every mapped kit of the connection. + * Queue a push for every mapped kit whose count differs from the last + * one sent. The scheduled sync calls this for changes no hook reports + * (a component deleted or no longer sellable, a product turned into a + * kit, an upgrade to a core that sells kits from components). * - * Core reports no hook when a kit's component list is edited, so the - * scheduled sync calls this: a changed bill of materials reaches Shopify - * within one schedule interval. Pushes are absolute, so an unchanged kit - * is simply set to the same quantity again. + * Unchanged kits are not sent again: that would put back on sale what + * Shopify has sold but Inventoros has not imported yet. */ - public static function queueMapped(Connection $connection): int + public static function queueChanged(Connection $connection): void + { + foreach (self::mappedKits($connection) as $mapping) { + $kit = Core::products($connection->organization_id)->find($mapping->internal_id); + + if ($kit instanceof Product && self::available($kit) !== $mapping->meta('sent_quantity')) { + app(Outbox::class)->put($connection, InventoryPush::KIND, InventoryPush::subject('product', (int) $kit->id)); + } + } + } + + /** + * Remember the counts just sent for the kits among these products. + * + * @param array $sent product id => quantity over all locations + */ + public static function rememberSent(Connection $connection, array $sent): void + { + if ($sent === []) { + return; + } + + foreach (self::mappedKits($connection, array_keys($sent)) as $mapping) { + $mapping->meta = array_merge($mapping->meta ?? [], ['sent_quantity' => $sent[(int) $mapping->internal_id]]); + $mapping->save(); + } + } + + /** + * @param list|null $ids Only these products; null for all. + * @return Collection + */ + private static function mappedKits(Connection $connection, ?array $ids = null): Collection { if (! self::supported()) { - return 0; + return collect(); } - $ids = Mapping::query() + return Mapping::query() ->where('connection_id', $connection->id) ->where('entity', Catalog::ENTITY) ->where('status', Mapping::MAPPED) ->where('internal_type', 'product') + ->when($ids !== null, fn ($query) => $query->whereIn('internal_id', $ids)) ->whereIn('internal_id', Core::products($connection->organization_id)->where('type', 'kit')->select('products.id')) ->orderBy('internal_id') - ->pluck('internal_id'); - - $outbox = app(Outbox::class); - foreach ($ids as $id) { - $outbox->put($connection, InventoryPush::KIND, InventoryPush::subject('product', (int) $id)); - } - - return $ids->count(); + ->get(); } } diff --git a/tests/Feature/KitAvailabilityTest.php b/tests/Feature/KitAvailabilityTest.php index f3af2f5..726486c 100644 --- a/tests/Feature/KitAvailabilityTest.php +++ b/tests/Feature/KitAvailabilityTest.php @@ -116,27 +116,50 @@ public function test_a_change_to_an_unrelated_product_does_not_push_the_kit(): v Queue::assertNotPushed(PushInventory::class); } - public function test_the_scheduled_sync_repushes_mapped_kits_so_a_component_list_edit_reaches_shopify(): void + /** Run the scheduled sync, then whatever it queued. */ + private function scheduledSync(): void { Queue::fake(); + $this->shopify->pushes = []; + $this->artisan('shopify:sync')->assertSuccessful(); + (new PushInventory($this->store->id))->handle(); + } + + public function test_the_scheduled_sync_pushes_a_kit_whose_count_changed_without_a_hook(): void + { ProductComponent::query()->where('parent_product_id', $this->kit->id)->where('component_product_id', $this->partA->id)->update(['quantity' => 1]); - $this->artisan('shopify:sync')->assertSuccessful(); + $this->scheduledSync(); + + $this->assertSame(['4001@1001' => 7], $this->pushed()); + } - $this->assertSame(['p'.$this->kit->id], OutboxEntry::query()->pluck('subject')->all()); - Queue::assertPushed(PushInventory::class); + public function test_the_scheduled_sync_does_not_send_an_unchanged_kit_again(): void + { + $this->scheduledSync(); + $this->assertSame(['4001@1001' => 3], $this->pushed()); - (new PushInventory($this->store->id))->handle(); + // Shopify may have sold some of those 3 since, in orders Inventoros + // has not imported. Sending 3 again would put them back on sale. + $this->scheduledSync(); + $this->assertSame([], $this->pushed()); + } + + public function test_editing_the_component_list_pushes_the_kit_at_once(): void + { + ProductComponent::query()->where('parent_product_id', $this->kit->id)->where('component_product_id', $this->partA->id)->sole()->update(['quantity' => 1]); $this->assertSame(['4001@1001' => 7], $this->pushed()); + + ProductComponent::query()->where('parent_product_id', $this->kit->id)->where('component_product_id', $this->partA->id)->sole()->delete(); + $this->assertSame(['4001@1001' => 20], $this->pushed()); } public function test_a_kit_core_cannot_sell_is_pushed_as_zero(): void { ProductComponent::query()->where('parent_product_id', $this->kit->id)->where('component_product_id', $this->partA->id)->update(['quantity' => 1.5]); - KitStock::queueMapped($this->store); - (new PushInventory($this->store->id))->handle(); + $this->scheduledSync(); $this->assertSame(['4001@1001' => 0], $this->pushed()); }