diff --git a/CHANGELOG.md b/CHANGELOG.md index 189d6da..6962d45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ All notable changes to this plugin are documented here. The format follows [Keep - 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. +### Fixed + +- A mapped kit on Inventoros 2.7 and newer is set to 0 at every mapped location that does not carry its count. Such a location kept whatever was pushed there before (the kit's own stock, or the count from when it was the primary location), so Shopify offered too many kits. The scheduled sync compares counts per location and sends only the locations that changed. These zeros are sent after every real count, and one Shopify refuses (the variant is not stocked at that location) is logged as a warning and skipped, so it never holds back other stock. +- A mapped kit changed to another product type is pushed its own stock once by the scheduled sync. It kept the kit count until its stock next moved. +- Variants of a kit are pushed as 0, because Inventoros never sells a kit by variant, and the scheduled sync sends the 0 once when their product becomes a kit. + ## [1.4.0] - Unreleased ### Added diff --git a/docs/configuration.md b/docs/configuration.md index 62bf655..eb567a9 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. 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. + - Kits (Inventoros 2.7+) are pushed as one total at the primary or "all stock" location and 0 at every other mapped location, because core counts kit availability across all warehouses. If Shopify refuses one of those zeros because the variant is not stocked at that location, the sync history shows a warning and the other quantities are still pushed. Variants of a kit are pushed as 0. 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, or turning a product into a kit or back) reach Shopify with the next scheduled sync, every 15 minutes, which sends only counts that 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/src/Kit/Exceptions/PermanentError.php b/src/Kit/Exceptions/PermanentError.php index 5ee2f6a..51a61f8 100644 --- a/src/Kit/Exceptions/PermanentError.php +++ b/src/Kit/Exceptions/PermanentError.php @@ -12,10 +12,13 @@ * * $authentication marks a credentials failure: the connection is put into * the error state and stops syncing until it is tested again. + * + * $refused marks a change the provider understood and refused for what it + * says, as opposed to a store or request it would not serve at all. */ final class PermanentError extends IntegrationException { - public function __construct(string $message, public readonly bool $authentication = false) + public function __construct(string $message, public readonly bool $authentication = false, public readonly bool $refused = false) { parent::__construct($message); } diff --git a/src/Kit/README.md b/src/Kit/README.md index 4791980..4f7f29b 100644 --- a/src/Kit/README.md +++ b/src/Kit/README.md @@ -21,7 +21,7 @@ Nothing in `src/Kit` knows about Shopify. The provider-specific code lives next | Sync history | `Models\SyncRun`, `Models\SyncLog`, `Sync\SyncRecorder` | `sync_runs`, `sync_logs` | A run per unit of work (type, resource, trigger, counters, status, error summary) and a log line per record. Every message is scrubbed of the connection's credential values. | | Jobs and retries | `Jobs\IntegrationJob`, `Jobs\RetryPolicy`, `Jobs\RetryDecision` | | Base job: rate limits re-queue after Retry-After without using an attempt; transient errors retry with backoff (15 s, 1 min, 4 min, 15 min); permanent errors and exhausted retries are dead-lettered. Retries are explicit re-dispatches, so they behave the same on every queue driver. | | Rate limits | `Support\CostBudget`, `Support\RetryAfter`, `Exceptions\RateLimited` | (cache) | A per-connection leaky bucket mirroring the provider's (Shopify query cost; set `maximum` and `restoreRate` for others). `reserve()` before a request throws `RateLimited` with the wait; `observe()` corrects it from the response. | -| Errors | `Exceptions\TransientError`, `PermanentError`, `RateLimited` | | What an adapter throws. `PermanentError(authentication: true)` puts the connection in the error state. | +| Errors | `Exceptions\TransientError`, `PermanentError`, `RateLimited` | | What an adapter throws. `PermanentError(authentication: true)` puts the connection in the error state; `PermanentError(refused: true)` marks one change the provider refused. | | Dead letters | `Jobs\DeadLetterQueue`, `Models\DeadLetter` | `dead_letters` | Failed work with the job class and arguments that rebuild it. Retry from the UI re-dispatches it from attempt 1; only job classes of the owning plugin are accepted. | | Webhook inbox | `Webhooks\WebhookInbox`, `Webhooks\HmacSignature`, `Models\WebhookInboxEntry` | `webhook_inbox` | Store a verified delivery once per provider event id and once per (topic, body hash); `claim()` succeeds once per delivery, so processing is exactly-once even with two workers. | | Mappings | `Mapping\MappingStore`, `Mapping\MappingConflict`, `Models\Mapping` | `mappings` | External id to core id per connection and entity, unique both ways. Statuses `mapped`, `suggested` (waiting for review), `unmatched`, `conflict`, `ignored`, `pending`. `isStale()` and `touch()` drop out-of-order deliveries. | diff --git a/src/Shopify/HttpShopifyClient.php b/src/Shopify/HttpShopifyClient.php index 21d2235..aa6baf5 100644 --- a/src/Shopify/HttpShopifyClient.php +++ b/src/Shopify/HttpShopifyClient.php @@ -477,7 +477,7 @@ private function assertNoUserErrors(array $userErrors): void $messages = array_map(fn (array $error) => (string) ($error['message'] ?? 'error'), $userErrors); - throw new PermanentError('Shopify rejected the change: '.$this->clean(implode('; ', array_slice($messages, 0, 3)))); + throw new PermanentError('Shopify rejected the change: '.$this->clean(implode('; ', array_slice($messages, 0, 3))), refused: true); } private function clean(string $message): string diff --git a/src/Sync/InventoryPush.php b/src/Sync/InventoryPush.php index dc6d8c3..b9aead1 100644 --- a/src/Sync/InventoryPush.php +++ b/src/Sync/InventoryPush.php @@ -5,14 +5,17 @@ namespace Inventoros\Plugins\Shopify\Sync; use Illuminate\Support\Collection; +use Inventoros\Plugins\Shopify\Kit\Exceptions\PermanentError; use Inventoros\Plugins\Shopify\Kit\Mapping\MappingStore; use Inventoros\Plugins\Shopify\Kit\Models\Connection; use Inventoros\Plugins\Shopify\Kit\Models\Mapping; use Inventoros\Plugins\Shopify\Kit\Models\OutboxEntry; +use Inventoros\Plugins\Shopify\Kit\Models\SyncLog; use Inventoros\Plugins\Shopify\Kit\Models\SyncRun; use Inventoros\Plugins\Shopify\Kit\Outbox\Outbox; use Inventoros\Plugins\Shopify\Kit\Sync\SyncRecorder; use Inventoros\Plugins\Shopify\Shopify\ClientFactory; +use Inventoros\Plugins\Shopify\Shopify\ShopifyClient; use Inventoros\Plugins\Shopify\Support\Core; /** @@ -31,8 +34,12 @@ * 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) + * primary or "all stock" location; 0 at + * every other mapped location, and 0 for a + * variant of a kit (see KitStock). The + * zeros that only clear another location + * go last, and one Shopify refuses (the + * item is not stocked there) is skipped * Reservations reduce availability. Negative stock is pushed as 0. */ final class InventoryPush @@ -78,32 +85,44 @@ public function push(Connection $connection, Collection $entries, SyncRun $run): { $locations = $this->locations->mapped($connection); $primary = $this->locations->primary($connection->id); - $quantities = []; $lines = []; + $clearing = []; $sent = []; foreach ($entries as $entry) { $rows = $this->quantitiesFor($connection, $entry->subject, $locations, $primary); - foreach ($rows as $row) { - $quantities[] = ['inventory_item_id' => $row['inventory_item_id'], 'location_id' => $row['location_id'], 'quantity' => $row['quantity']]; - $lines[] = $row; + foreach (KitStock::toSend($entry, $rows) as $row) { + if ($row['clears']) { + $clearing[] = $row; + } else { + $lines[] = $row; + } } 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')); + } else { + $sent[$entry->subject] = array_column($rows, 'quantity', 'location_id'); } } - $client = $quantities === [] ? null : $this->clients->make($connection); + $client = $lines === [] && $clearing === [] ? null : $this->clients->make($connection); $signature = $entries->map(fn (OutboxEntry $entry) => $entry->id.':'.$entry->coalesced)->sort()->implode(','); - foreach (array_chunk($quantities, self::BATCH) as $batch) { - $client->setInventoryQuantities($batch, $this->idempotencyKey($connection, $batch, $signature)); + foreach (array_chunk($lines, self::BATCH) as $batch) { + $this->send($client, $connection, $batch, $signature); + } + + $refused = []; + foreach (array_chunk($clearing, self::BATCH) as $batch) { + [$applied, $rejected] = $this->clear($client, $connection, $batch, $signature); + $lines = array_merge($lines, $applied); + $refused = array_merge($refused, $rejected); } + // A refused zero counts as sent, so the scheduled sync does not + // repeat it; the next push for another reason does. KitStock::rememberSent($connection, $sent); foreach ($lines as $line) { @@ -118,14 +137,64 @@ public function push(Connection $connection, Collection $entries, SyncRun $run): ]); } + foreach ($refused as $row) { + $this->recorder->count($run, 'processed'); + $this->recorder->count($run, 'skipped'); + $this->recorder->log($connection, $run, SyncLog::WARNING, "Shopify refused to set {$row['label']} to 0 at {$row['location_label']}; it may not be stocked there. {$row['error']}", [ + 'entity' => Catalog::ENTITY, + 'external_id' => $row['variant_id'], + 'internal_id' => $row['internal_id'], + 'action' => 'skip_push', + 'context' => ['location_id' => $row['location_id'], 'quantity' => 0], + ]); + } + foreach ($entries as $entry) { $this->outbox->done($entry); } } + /** + * @param array> $rows + */ + private function send(ShopifyClient $client, Connection $connection, array $rows, string $signature): void + { + $batch = array_map(fn (array $row) => ['inventory_item_id' => $row['inventory_item_id'], 'location_id' => $row['location_id'], 'quantity' => $row['quantity']], $rows); + + $client->setInventoryQuantities($batch, $this->idempotencyKey($connection, $batch, $signature)); + } + + /** + * Send zeros that only clear a location. Shopify refuses a whole call + * for one item it does not stock at the location, so a refused call is + * repeated row by row. Any other failure is thrown as usual. + * + * @param array> $rows + * @return array{0: array>, 1: array>} the rows applied, and those refused (with Shopify's error) + */ + private function clear(ShopifyClient $client, Connection $connection, array $rows, string $signature): array + { + try { + $this->send($client, $connection, $rows, $signature); + + return [$rows, []]; + } catch (PermanentError $error) { + if (! $error->refused) { + throw $error; + } + if (count($rows) === 1) { + return [[], [$rows[0] + ['error' => $error->getMessage()]]]; + } + } + + $results = array_map(fn (array $row) => $this->clear($client, $connection, [$row], $signature), $rows); + + return [array_merge(...array_column($results, 0)), array_merge(...array_column($results, 1))]; + } + /** * @param Collection $locations - * @return array + * @return array */ public function quantitiesFor(Connection $connection, string $subject, Collection $locations, ?Mapping $primary): array { @@ -152,30 +221,35 @@ public function quantitiesFor(Connection $connection, string $subject, Collectio return []; } $stock = app(InventoryStock::class); - // A kit sold from its components has no stock or bins of its own: - // its availability is placed like an unbinned product's. + // A kit sold from its components has no stock or bins of its own: its + // availability is placed like an unbinned product's, and every other + // location is set to 0, so none keeps a count pushed before. $kit = KitStock::isKit($target); + $sent = $kit ? (array) $mapping->meta(KitStock::SENT, []) : []; $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]]; + if ($type === 'variant' && ! $kit && ! InventoryStock::supportsVariantBins()) { + return $primary === null ? [] : [$base + ['location_id' => $primary->external_id, 'location_label' => (string) $primary->external_label, 'quantity' => $budget, 'sent' => null, 'clears' => false]]; } $free = $kit ? collect() : $stock->freeByWarehouse($target); // Unassigned stock retains the historic primary-location fallback. $unassigned = $kit || $stock->rows($target)->isEmpty(); foreach ($locations->sortBy(fn ($location) => [$location->id === $primary?->id ? 0 : 1, $location->id]) as $location) { + $clears = false; if ($location->internal_type === Locations::ALL_STOCK) { $quantity = $budget; } elseif ($unassigned) { - if ($primary === null || $location->id !== $primary->id) { + $isPrimary = $location->id === $primary?->id; + if (! $isPrimary && ! $kit) { continue; } - $quantity = $budget; + $quantity = $isPrimary ? $budget : 0; + $clears = ! $isPrimary; } else { $quantity = min($budget, max(0, (int) $free->get((int) $location->internal_id, 0))); } // A global hold cannot be advertised as available in several locations. $budget -= $quantity; - $rows[] = $base + ['location_id' => $location->external_id, 'location_label' => (string) $location->external_label, 'quantity' => $quantity]; + $rows[] = $base + ['location_id' => $location->external_id, 'location_label' => (string) $location->external_label, 'quantity' => $quantity, 'sent' => $sent[$location->external_id] ?? null, 'clears' => $clears]; } return $rows; diff --git a/src/Sync/KitStock.php b/src/Sync/KitStock.php index ea4ffb6..b48e051 100644 --- a/src/Sync/KitStock.php +++ b/src/Sync/KitStock.php @@ -6,10 +6,12 @@ use App\Models\Inventory\Product; use App\Models\Inventory\ProductComponent; +use App\Models\Inventory\ProductVariant; 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\Models\OutboxEntry; use Inventoros\Plugins\Shopify\Kit\Outbox\Outbox; use Inventoros\Plugins\Shopify\Support\Core; @@ -25,22 +27,35 @@ */ final class KitStock { + /** Mapping meta: what a kit was last sent, location id => quantity. Only kits and their variants have it. */ + public const SENT = 'sent_quantities'; + public static function supported(): bool { return class_exists(KitSaleService::class) && method_exists(KitSaleService::class, 'available'); } + /** + * Whether $target is a kit, or a variant of one. + */ public static function isKit(mixed $target): bool { - return $target instanceof Product && $target->type === 'kit' && self::supported(); + if (! self::supported()) { + return false; + } + + $product = $target instanceof ProductVariant ? $target->product()->withoutGlobalScopes()->first() : $target; + + return $product instanceof Product && $product->type === 'kit'; } /** - * Whole kits the components can make now; 0 for a kit core cannot sell. + * Whole kits the components can make now; 0 for a kit core cannot sell, + * and for a variant of a kit (core never sells a kit by variant). */ - public static function available(Product $kit): int + public static function available(Product|ProductVariant $kit): int { - return max(0, app(KitSaleService::class)->available($kit)); + return $kit instanceof Product ? max(0, app(KitSaleService::class)->available($kit)) : 0; } /** @@ -67,60 +82,103 @@ public static function kitsUsing(int $organizationId, array $productIds): array } /** - * 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). + * Queue a push for every mapped kit, or variant of one, whose count at + * any location differs from the last one sent, and for everything sent + * as a kit that no longer is one. The scheduled sync calls this for + * changes no hook reports (a component deleted or no longer sellable, a + * product turned into a kit or back, an upgrade to a core that sells + * kits from components, another primary location). * - * Unchanged kits are not sent again: that would put back on sale what - * Shopify has sold but Inventoros has not imported yet. + * Unchanged counts are not sent again (see toSend): 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); + $push = app(InventoryPush::class); + $locations = app(Locations::class)->mapped($connection); + $primary = app(Locations::class)->primary($connection->id); + + foreach ([true, false] as $kits) { + foreach (self::mappings($connection, $kits) as $mapping) { + $subject = InventoryPush::subject((string) $mapping->internal_type, (int) $mapping->internal_id); + $quantities = array_column($push->quantitiesFor($connection, $subject, $locations, $primary), 'quantity', 'location_id'); + + if ($quantities === [] || ($kits && $quantities == $mapping->meta(self::SENT))) { + continue; + } - if ($kit instanceof Product && self::available($kit) !== $mapping->meta('sent_quantity')) { - app(Outbox::class)->put($connection, InventoryPush::KIND, InventoryPush::subject('product', (int) $kit->id)); + // A row already waiting sends this change too. + if (! OutboxEntry::query()->where('connection_id', $connection->id)->where('kind', InventoryPush::KIND)->where('subject', $subject)->exists()) { + app(Outbox::class)->put($connection, InventoryPush::KIND, $subject, ['changed_only' => true]); + } } } } /** - * Remember the counts just sent for the kits among these products. + * The quantities an outbox row sends: all of them, or only the changed + * ones when nothing but the scheduled sync asked for the push. * - * @param array $sent product id => quantity over all locations + * @param array> $rows from InventoryPush::quantitiesFor + * @return array> + */ + public static function toSend(OutboxEntry $entry, array $rows): array + { + return ($entry->payload['changed_only'] ?? false) && $entry->coalesced === 0 + ? array_filter($rows, fn (array $row) => $row['quantity'] !== $row['sent']) + : $rows; + } + + /** + * Remember the counts just sent for the kits among these items, and + * forget those of items that are no longer kits. + * + * @param array> $sent outbox subject => location id => quantity */ public static function rememberSent(Connection $connection, array $sent): void { - if ($sent === []) { - return; - } + $ids = array_map(fn (string $subject) => (int) substr($subject, 1), array_keys($sent)); - foreach (self::mappedKits($connection, array_keys($sent)) as $mapping) { - $mapping->meta = array_merge($mapping->meta ?? [], ['sent_quantity' => $sent[(int) $mapping->internal_id]]); - $mapping->save(); + foreach ([true, false] as $kits) { + foreach (self::mappings($connection, $kits, $ids) as $mapping) { + $subject = InventoryPush::subject((string) $mapping->internal_type, (int) $mapping->internal_id); + + if (isset($sent[$subject])) { + $meta = $mapping->meta ?? []; + unset($meta[self::SENT]); + $mapping->meta = $kits ? $meta + [self::SENT => $sent[$subject]] : $meta; + $mapping->save(); + } + } } } /** - * @param list|null $ids Only these products; null for all. + * Mapped kits and variants of kits; or, with $kits false, what was last + * sent as one and is not one any more. + * + * @param list|null $ids Only these internal ids; null for all. * @return Collection */ - private static function mappedKits(Connection $connection, ?array $ids = null): Collection + private static function mappings(Connection $connection, bool $kits, ?array $ids = null): Collection { - if (! self::supported()) { + if (! self::supported() || $ids === []) { return collect(); } + $products = Core::products($connection->organization_id)->where('type', $kits ? '=' : '!=', 'kit')->select('products.id'); + $variants = Core::variants($connection->organization_id)->whereIn('product_id', clone $products)->select('product_variants.id'); + 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') + ->when(! $kits, fn ($query) => $query->whereNotNull('meta->'.self::SENT)) + ->where(fn ($query) => $query + ->where(fn ($query) => $query->where('internal_type', 'product')->whereIn('internal_id', $products)) + ->orWhere(fn ($query) => $query->where('internal_type', 'variant')->whereIn('internal_id', $variants))) + ->orderBy('id') ->get(); } } diff --git a/tests/Fakes/FakeShopifyClient.php b/tests/Fakes/FakeShopifyClient.php index 65f43a1..5dd0b34 100644 --- a/tests/Fakes/FakeShopifyClient.php +++ b/tests/Fakes/FakeShopifyClient.php @@ -26,6 +26,9 @@ final class FakeShopifyClient implements ShopifyClient /** @var array> */ private array $failures = []; + /** @var array "item@location" => thrown by any setInventoryQuantities call naming it */ + public array $refuseQuantities = []; + /** @var array */ public array $shop; @@ -183,6 +186,11 @@ public function transactions(string $orderId): array public function setInventoryQuantities(array $quantities, string $idempotencyKey): void { $this->record(__FUNCTION__, [$quantities, $idempotencyKey]); + foreach ($quantities as $row) { + if (isset($this->refuseQuantities[$row['inventory_item_id'].'@'.$row['location_id']])) { + throw $this->refuseQuantities[$row['inventory_item_id'].'@'.$row['location_id']]; + } + } $this->pushes[] = ['quantities' => $quantities, 'key' => $idempotencyKey]; } diff --git a/tests/Feature/KitAvailabilityTest.php b/tests/Feature/KitAvailabilityTest.php index 726486c..10b76c7 100644 --- a/tests/Feature/KitAvailabilityTest.php +++ b/tests/Feature/KitAvailabilityTest.php @@ -6,18 +6,30 @@ use App\Models\Inventory\Product; use App\Models\Inventory\ProductComponent; +use App\Models\Inventory\ProductLocationStock; use App\Models\Inventory\StockAdjustment; use App\Models\Order\Order; use App\Services\StockReservationService; use Illuminate\Support\Facades\Queue; use Inventoros\Plugins\Shopify\Jobs\PushInventory; +use Inventoros\Plugins\Shopify\Kit\Exceptions\PermanentError; +use Inventoros\Plugins\Shopify\Kit\Exceptions\RateLimited; +use Inventoros\Plugins\Shopify\Kit\Exceptions\TransientError; +use Inventoros\Plugins\Shopify\Kit\Mapping\MappingStore; +use Inventoros\Plugins\Shopify\Kit\Models\Connection; use Inventoros\Plugins\Shopify\Kit\Models\DeadLetter; use Inventoros\Plugins\Shopify\Kit\Models\Mapping; use Inventoros\Plugins\Shopify\Kit\Models\OutboxEntry; +use Inventoros\Plugins\Shopify\Kit\Models\SyncLog; +use Inventoros\Plugins\Shopify\Kit\Outbox\Outbox; use Inventoros\Plugins\Shopify\Sync\Catalog; +use Inventoros\Plugins\Shopify\Sync\InventoryPush; use Inventoros\Plugins\Shopify\Sync\KitStock; +use Inventoros\Plugins\Shopify\Sync\Locations; use Inventoros\Plugins\Shopify\Tests\Concerns\ShopifyWorld; use Inventoros\Plugins\Shopify\Tests\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use Throwable; /** * On cores that sell kits from their components, a kit mapped to a Shopify @@ -93,16 +105,16 @@ public function test_a_component_stock_change_pushes_how_many_kits_can_be_made_a { 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()); + // 6 of Part A make 3 kits; the kit has no bins, so they are all at + // the primary location, and none at the other mapped warehouse. + $this->assertSame(['4001@1001' => 3, '4001@1002' => 0], $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()); + $this->assertSame(['4001@1001' => 1, '4001@1002' => 0], $this->pushed()); } public function test_a_change_to_an_unrelated_product_does_not_push_the_kit(): void @@ -131,13 +143,13 @@ public function test_the_scheduled_sync_pushes_a_kit_whose_count_changed_without $this->scheduledSync(); - $this->assertSame(['4001@1001' => 7], $this->pushed()); + $this->assertSame(['4001@1001' => 7, '4001@1002' => 0], $this->pushed()); } public function test_the_scheduled_sync_does_not_send_an_unchanged_kit_again(): void { $this->scheduledSync(); - $this->assertSame(['4001@1001' => 3], $this->pushed()); + $this->assertSame(['4001@1001' => 3, '4001@1002' => 0], $this->pushed()); // Shopify may have sold some of those 3 since, in orders Inventoros // has not imported. Sending 3 again would put them back on sale. @@ -146,13 +158,296 @@ public function test_the_scheduled_sync_does_not_send_an_unchanged_kit_again(): $this->assertSame([], $this->pushed()); } + public function test_a_location_left_with_an_older_count_is_set_to_zero(): void + { + // Sold from its own stock, 5 of it at the Annex, until it became a kit. + $this->kit->forceFill(['type' => 'standard', 'stock' => 5])->saveQuietly(); + ProductLocationStock::create(['organization_id' => $this->organization->id, 'product_id' => $this->kit->id, 'location_id' => $this->annexBin->id, 'quantity' => 5]); + app(Outbox::class)->put($this->store, InventoryPush::KIND, InventoryPush::subject('product', (int) $this->kit->id)); + (new PushInventory($this->store->id))->handle(); + $this->assertSame(['4001@1001' => 0, '4001@1002' => 5], $this->pushed()); + + $this->kit->forceFill(['type' => 'kit'])->saveQuietly(); + $this->scheduledSync(); + + $this->assertSame(['4001@1001' => 3, '4001@1002' => 0], $this->pushed()); + } + + public function test_the_scheduled_sync_moves_the_count_when_the_primary_location_changes(): void + { + $this->scheduledSync(); + + app(Locations::class)->setPrimary($this->mapping(Locations::ENTITY, '1002')); + $this->scheduledSync(); + $this->assertEquals(['4001@1001' => 0, '4001@1002' => 3], $this->pushed()); + + $this->scheduledSync(); + $this->assertSame([], $this->pushed()); + } + + public function test_the_scheduled_sync_sends_only_the_locations_whose_count_changed(): void + { + $annex = $this->mapping(Locations::ENTITY, '1002'); + app(MappingStore::class)->unlink($annex); + $this->scheduledSync(); + $this->assertSame(['4001@1001' => 3], $this->pushed()); + + app(Locations::class)->map($annex, Locations::WAREHOUSE, (int) $this->annex->id, false); + $this->scheduledSync(); + $this->assertSame(['4001@1002' => 0], $this->pushed(), 'the 3 at the primary location are not put back on sale'); + + $this->scheduledSync(); + $this->assertSame([], $this->pushed()); + } + + public function test_a_scheduled_push_that_waits_stays_limited_to_what_changed(): void + { + $annex = $this->mapping(Locations::ENTITY, '1002'); + app(MappingStore::class)->unlink($annex); + $this->scheduledSync(); + + app(Locations::class)->map($annex, Locations::WAREHOUSE, (int) $this->annex->id, false); + $this->artisan('shopify:sync')->assertSuccessful(); + $this->scheduledSync(); + + $this->assertSame(['4001@1002' => 0], $this->pushed()); + } + + /** + * @return array + */ + public static function orders(): array + { + return ['before the scheduled sync' => [true], 'after the scheduled sync' => [false]]; + } + + #[DataProvider('orders')] + public function test_a_kit_queued_for_another_reason_is_sent_in_full(bool $before): void + { + $annex = $this->mapping(Locations::ENTITY, '1002'); + app(MappingStore::class)->unlink($annex); + $this->scheduledSync(); + app(Locations::class)->map($annex, Locations::WAREHOUSE, (int) $this->annex->id, false); + $this->shopify->pushes = []; + $resync = fn () => app(Outbox::class)->put($this->store, InventoryPush::KIND, InventoryPush::subject('product', (int) $this->kit->id)); + + if ($before) { + $resync(); + } + $this->artisan('shopify:sync')->assertSuccessful(); + if (! $before) { + $resync(); + } + (new PushInventory($this->store->id))->handle(); + + $this->assertSame(['4001@1001' => 3, '4001@1002' => 0], $this->pushed()); + } + + public function test_a_kit_turned_into_another_type_is_pushed_once_with_its_own_stock(): void + { + $this->scheduledSync(); + + $this->kit->forceFill(['type' => 'standard', 'stock' => 2])->saveQuietly(); + $this->scheduledSync(); + $this->assertSame(['4001@1001' => 2], $this->pushed()); + + $this->scheduledSync(); + $this->assertSame([], $this->pushed()); + + // A kit again, with the count sent before the change. + $this->kit->forceFill(['type' => 'kit'])->saveQuietly(); + $this->scheduledSync(); + $this->assertSame(['4001@1001' => 3, '4001@1002' => 0], $this->pushed()); + } + + public function test_the_variants_of_a_product_that_became_a_kit_are_pushed_once_as_zero(): void + { + $this->scheduledSync(); + + $this->tee->forceFill(['type' => 'kit'])->saveQuietly(); + $this->scheduledSync(); + $this->assertEquals(['4002@1001' => 0, '4002@1002' => 0, '4003@1001' => 0, '4003@1002' => 0], $this->pushed()); + + $this->scheduledSync(); + $this->assertSame([], $this->pushed()); + + $this->tee->forceFill(['type' => 'standard'])->saveQuietly(); + $this->scheduledSync(); + $this->assertEquals(['4002@1001' => 5, '4003@1001' => 4], $this->pushed()); + + $this->scheduledSync(); + $this->assertSame([], $this->pushed()); + } + + public function test_a_stock_change_of_a_kits_variant_pushes_zero(): void + { + $this->tee->forceFill(['type' => 'kit'])->saveQuietly(); + + StockAdjustment::adjustVariant($this->teeS->fresh(), 2, 'manual', 'test', null, null, true, $this->admin); + + $this->assertSame(['4002@1001' => 0, '4002@1002' => 0], $this->pushed(), 'core never sells a kit by variant'); + } + + public function test_the_scheduled_sync_leaves_products_that_never_were_kits_alone(): void + { + StockAdjustment::adjustVariant($this->teeS->fresh(), 2, 'manual', 'test', null, null, true, $this->admin); + $this->scheduledSync(); + + $this->scheduledSync(); + + $this->assertSame([], $this->pushed()); + } + + private function queuePush(string ...$subjects): void + { + foreach ($subjects as $subject) { + app(Outbox::class)->put($this->store, InventoryPush::KIND, $subject); + } + } + + private function refused(): PermanentError + { + return new PermanentError('Shopify rejected the change: not stocked at the location', refused: true); + } + + /** + * @return array + */ + private function idempotencyKeys(): array + { + return array_column(array_column(array_filter($this->shopify->calls, fn (array $call) => $call[0] === 'setInventoryQuantities'), 1), 1); + } + + public function test_a_refused_zero_at_another_location_holds_nothing_back(): void + { + Queue::fake(); + $this->tee->forceFill(['type' => 'kit'])->saveQuietly(); + $loose = $this->product('LOOSE-1', 'Loose part', 6, $this->binA); + Mapping::query()->where('connection_id', $this->store->id)->where('internal_type', 'variant')->where('internal_id', $this->teeM->id)->sole()->forceFill(['internal_type' => 'product', 'internal_id' => $loose->id])->save(); + $this->shopify->refuseQuantities['4001@1002'] = $this->refused(); + $this->queuePush(InventoryPush::subject('product', (int) $this->kit->id), InventoryPush::subject('product', (int) $loose->id), InventoryPush::subject('variant', (int) $this->teeS->id)); + + (new PushInventory($this->store->id))->handle(); + + $this->assertEquals([ + '4001@1001' => 3, + '4002@1001' => 0, '4002@1002' => 0, + '4003@1001' => 6, '4003@1002' => 0, + ], $this->pushed()); + $this->assertSame(0, OutboxEntry::query()->count()); + $this->assertSame(0, DeadLetter::query()->count()); + + $warning = SyncLog::query()->where('level', SyncLog::WARNING)->sole(); + $this->assertSame('1002', $warning->context['location_id']); + $this->assertSame((int) $this->kit->id, (int) $warning->internal_id); + $this->assertSame(0, SyncLog::query()->where('action', 'push_inventory')->where('internal_id', $this->kit->id)->where('message', 'like', 'Set % to 0%')->count()); + + $keys = $this->idempotencyKeys(); + $this->assertCount(4, $keys, 'the counts, the zeros, then each zero alone'); + $this->assertSame($keys, array_values(array_unique($keys))); + + $this->scheduledSync(); + $this->assertSame([], $this->pushed()); + } + + public function test_a_single_refused_zero_is_not_sent_twice(): void + { + Queue::fake(); + $this->shopify->refuseQuantities['4001@1002'] = $this->refused(); + + $this->scheduledSync(); + $this->assertSame(['4001@1001' => 3], $this->pushed()); + $this->assertCount(2, $this->idempotencyKeys()); + + $this->scheduledSync(); + $this->assertCount(2, $this->idempotencyKeys(), 'nothing is sent again'); + $this->assertSame(0, OutboxEntry::query()->count()); + } + + public function test_a_refused_count_still_fails_the_push(): void + { + Queue::fake(); + $this->shopify->refuseQuantities['4001@1001'] = $this->refused(); + $this->queuePush(InventoryPush::subject('product', (int) $this->kit->id)); + + (new PushInventory($this->store->id))->handle(); + + $this->assertSame([], $this->pushed(), 'the zero waits until the count is applied'); + $this->assertSame(1, OutboxEntry::query()->count()); + $this->assertSame(1, DeadLetter::query()->count()); + } + + public function test_a_refused_zero_at_the_primary_location_still_fails_the_push(): void + { + Queue::fake(); + $this->tee->forceFill(['type' => 'kit'])->saveQuietly(); + $this->shopify->refuseQuantities['4002@1001'] = $this->refused(); + $this->queuePush(InventoryPush::subject('variant', (int) $this->teeS->id)); + + (new PushInventory($this->store->id))->handle(); + + $this->assertSame(1, OutboxEntry::query()->count()); + $this->assertSame(1, DeadLetter::query()->count()); + } + + /** + * @return array + */ + public static function otherFailures(): array + { + return [ + 'rate limit' => [new RateLimited('Slow down', 5)], + 'network' => [new TransientError('Could not reach Shopify')], + 'credentials' => [new PermanentError('Token refused', authentication: true)], + 'frozen store' => [new PermanentError('The Shopify store is frozen or unpaid (HTTP 402).')], + ]; + } + + #[DataProvider('otherFailures')] + public function test_any_other_failure_of_a_zero_still_fails_the_push(Throwable $error): void + { + Queue::fake(); + $this->shopify->refuseQuantities['4001@1002'] = $error; + $this->queuePush(InventoryPush::subject('product', (int) $this->kit->id)); + + (new PushInventory($this->store->id))->handle(); + + $this->assertSame(['4001@1001' => 3], $this->pushed()); + $this->assertSame(1, OutboxEntry::query()->count()); + + // The retry repeats the same calls under the same keys. + $this->shopify->refuseQuantities = []; + $this->store->fresh()->forceFill(['status' => Connection::CONNECTED])->save(); + (new PushInventory($this->store->id))->handle(); + + $this->assertSame(['4001@1001' => 3, '4001@1002' => 0], $this->pushed()); + $this->assertSame(0, OutboxEntry::query()->count()); + $keys = $this->idempotencyKeys(); + $this->assertCount(4, $keys); + $this->assertSame(array_slice($keys, 0, 2), array_slice($keys, 2)); + } + + public function test_a_transient_failure_of_a_zero_sent_alone_still_fails_the_push(): void + { + Queue::fake(); + $this->tee->forceFill(['type' => 'kit'])->saveQuietly(); + $this->shopify->refuseQuantities['4001@1002'] = $this->refused(); + $this->shopify->refuseQuantities['4002@1002'] = new RateLimited('Slow down', 5); + $this->queuePush(InventoryPush::subject('product', (int) $this->kit->id), InventoryPush::subject('variant', (int) $this->teeS->id)); + + (new PushInventory($this->store->id))->handle(); + + $this->assertEquals(['4001@1001' => 3, '4002@1001' => 0], $this->pushed()); + $this->assertSame(2, OutboxEntry::query()->count()); + } + 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()); + $this->assertSame(['4001@1001' => 7, '4001@1002' => 0], $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()); + $this->assertSame(['4001@1001' => 20, '4001@1002' => 0], $this->pushed()); } public function test_a_kit_core_cannot_sell_is_pushed_as_zero(): void @@ -161,7 +456,7 @@ public function test_a_kit_core_cannot_sell_is_pushed_as_zero(): void $this->scheduledSync(); - $this->assertSame(['4001@1001' => 0], $this->pushed()); + $this->assertSame(['4001@1001' => 0, '4001@1002' => 0], $this->pushed()); } public function test_a_shopify_order_for_the_kit_takes_its_components(): void @@ -191,7 +486,7 @@ public function test_a_shopify_order_for_more_kits_than_can_be_made_is_held_back 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->store->forceFill(['settings' => array_merge($this->store->settings, ['stock_source' => 'shopify'])])->saveQuietly(); $this->webhook('inventory_levels/update', $this->payload('inventory_levels_update'))->assertOk(); diff --git a/tests/Feature/RetryAndRateLimitTest.php b/tests/Feature/RetryAndRateLimitTest.php index f3fa384..4a2354f 100644 --- a/tests/Feature/RetryAndRateLimitTest.php +++ b/tests/Feature/RetryAndRateLimitTest.php @@ -170,6 +170,25 @@ public function test_shopify_user_errors_are_permanent(): void $this->assertSame(Connection::CONNECTED, $this->store->fresh()->status); } + public function test_only_a_user_error_counts_as_a_refused_change(): void + { + $responses = [ + [Http::response(FakeShopifyClient::fixture('user_errors'), 200), true], + [Http::response('frozen', 402), false], + [Http::response(['errors' => [['message' => 'Invalid query']]], 200), false], + ]; + Http::fake([self::ENDPOINT => Http::sequence(array_column($responses, 0))]); + + foreach ($responses as [, $refused]) { + try { + app(ClientFactory::class)->make($this->store)->setInventoryQuantities([['inventory_item_id' => '4001', 'location_id' => '1001', 'quantity' => 1]], 'key'); + $this->fail('The change should have failed.'); + } catch (PermanentError $error) { + $this->assertSame($refused, $error->refused, $error->getMessage()); + } + } + } + public function test_five_failures_in_a_row_open_the_circuit_and_a_success_or_resume_closes_it(): void { $health = app(ConnectionHealth::class);