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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 4 additions & 1 deletion src/Kit/Exceptions/PermanentError.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Kit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
2 changes: 1 addition & 1 deletion src/Shopify/HttpShopifyClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
112 changes: 93 additions & 19 deletions src/Sync/InventoryPush.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand All @@ -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
Expand Down Expand Up @@ -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) {
Expand All @@ -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<int, array<string, mixed>> $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<int, array<string, mixed>> $rows
* @return array{0: array<int, array<string, mixed>>, 1: array<int, array<string, mixed>>} 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<int, Mapping> $locations
* @return array<int, array{inventory_item_id: string, location_id: string, quantity: int, label: string, location_label: string, variant_id: string, internal_id: int}>
* @return array<int, array{inventory_item_id: string, location_id: string, quantity: int, label: string, location_label: string, variant_id: string, internal_id: int, sent: int|null, clears: bool}>
*/
public function quantitiesFor(Connection $connection, string $subject, Collection $locations, ?Mapping $primary): array
{
Expand All @@ -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;
Expand Down
Loading
Loading