Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, 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

### Added
Expand Down
1 change: 1 addition & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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.
Expand Down
1 change: 1 addition & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, 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.
Expand Down
10 changes: 9 additions & 1 deletion src/Console/SyncCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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), 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
{
Expand Down Expand Up @@ -57,6 +61,10 @@ public function handle(Outbox $outbox): int
ProcessWebhook::dispatch($connection->id, (int) $entryId);
}

if (SyncPolicy::for($connection)->pushesStock()) {
KitStock::queueChanged($connection);
}

if ($outbox->hasDue($connection, InventoryPush::KIND)) {
PushInventory::dispatch($connection->id);
}
Expand Down
5 changes: 5 additions & 0 deletions src/ShopifyPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
79 changes: 69 additions & 10 deletions src/Support/Listeners.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -19,6 +21,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;

Expand All @@ -35,7 +38,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<string, mixed> $change
*/
Expand All @@ -46,18 +51,42 @@ 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];

foreach (self::connected((int) $product->organization_id) as $connection) {
$policy = SyncPolicy::for($connection);
$organizationId = (int) $product->organization_id;
$connections = self::connected($organizationId);
if ($connections->isEmpty()) {
return;
}

if (! $policy->pushesStock() || ! self::isMapped($connection, $type, $id)) {
continue;
$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];
}

app(Outbox::class)->put($connection, InventoryPush::KIND, InventoryPush::subject($type, $id), [], $policy->pushDelay());
PushInventory::dispatch($connection->id)->delay(now()->addSeconds($policy->pushDelay()));
}

self::queue($connections, $subjects);
});
}

/**
* 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;
}

DB::afterCommit(static function () use ($component): void {
self::guard(function () use ($component) {
$kit = Product::withoutGlobalScopes()->find($component->parent_product_id);

if (KitStock::isKit($kit)) {
self::queue(self::connected((int) $kit->organization_id), [['product', (int) $kit->id]]);
}
});
});
}

Expand Down Expand Up @@ -147,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<int, Connection> $connections
* @param array<int, array{0: string, 1: int}> $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()
Expand Down
4 changes: 3 additions & 1 deletion src/Sync/InventoryPull.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
}

Expand Down
17 changes: 14 additions & 3 deletions src/Sync/InventoryPush.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -77,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);
Expand All @@ -88,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'));
}
}

Expand All @@ -98,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');
Expand Down Expand Up @@ -144,13 +152,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;
Expand Down
126 changes: 126 additions & 0 deletions src/Sync/KitStock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
<?php

declare(strict_types=1);

namespace Inventoros\Plugins\Shopify\Sync;

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;
use Inventoros\Plugins\Shopify\Support\Core;

/**
* Kits on cores that sell them from their components (Inventoros 2.7+).
*
* 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 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
{
public static function supported(): bool
{
return class_exists(KitSaleService::class) && method_exists(KitSaleService::class, 'available');
}

public static function isKit(mixed $target): bool
{
return $target instanceof Product && $target->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<int> $productIds
* @return list<int>
*/
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 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).
*
* 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 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<int, int> $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<int>|null $ids Only these products; null for all.
* @return Collection<int, Mapping>
*/
private static function mappedKits(Connection $connection, ?array $ids = null): Collection
{
if (! self::supported()) {
return collect();
}

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')
->get();
}
}
Loading
Loading