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 @@ -4,6 +4,12 @@ All notable changes to this plugin are documented here. The format follows [Keep

## [Unreleased]

## [1.4.0] - Unreleased

### Added

- Optional shipment fulfilment and tracking push, destination inventory activation and Shopify-owned shipping notifications. Exact line mappings and persisted send claims prevent duplicate fulfilments. Historical/non-stock orders are excluded.

## [1.3.0] - Unreleased

### Added
Expand Down
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ Admins hold both. On Inventoros versions without plugin permissions they fall ba
- Orders take stock when imported. External Shopify checkout reservations are not created in Inventoros before the order webhook arrives.
- 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.
- Fulfillments and tracking are not pushed to Shopify yet; order edits after import are not applied. Completed payment/refund records can be imported with the optional ledger setting.
- 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.
- Public multi-merchant OAuth installation is not implemented; see [docs/setup.md](docs/setup.md#7-future-a-public-app-with-oauth).

## Develop and test
Expand Down Expand Up @@ -211,3 +211,15 @@ The API reader checks the exact transaction count and refuses incomplete lists
or orders with more than 100 transactions for manual review. It does not
silently import a subset. Financial records and new-order creation are atomic;
an invalid transaction leaves no partial order/payment ledger.

## Shipment fulfilment and tracking

After upgrading the core with shipment notification ownership, grant the custom app `read_merchant_managed_fulfillment_orders` and `write_merchant_managed_fulfillment_orders`, plus `write_inventory` for destination activation, then enable **Push shipments and tracking to Shopify** in the connection settings. This is off by default. Map each ship-from warehouse to exactly one Shopify location.

Newly imported order lines retain their exact Shopify line ids. When an Inventoros shipment is marked shipped, queued work fulfils only those shipped quantities, includes tracking, and lets Shopify send the shipping email if the customer notification option is enabled. The core email is suppressed for those shipments. Older imported orders without exact line mappings must be fulfilled in Shopify. Shipping never deducts Inventoros stock a second time.

If routing differs, the plugin activates previously unstocked inventory items at the destination, without resetting existing quantities, before moving only the shipment’s fulfilment-order lines. Moves re-read Shopify because order and line ids may change. Fulfilment holds and unsupported service requests stop the push for review. Read pages and definite throttles use the existing delayed retries.

Shopify’s [fulfillmentCreate](https://shopify.dev/docs/api/admin-graphql/2026-07/mutations/fulfillmentCreate) does not document a creation idempotency key. The plugin commits a send claim before creation, persists the returned id, and refuses to blindly replay an uncertain response or a killed worker’s claim. Check the failed operation in Sync activity and verify or finish that shipment in Shopify; repeated retries cannot create another fulfilment. This conservative stop also applies to rejected creation responses. [Destination activation](https://shopify.dev/docs/api/admin-graphql/2026-07/mutations/inventoryActivate) uses its required idempotency key; [fulfilment-order moves](https://shopify.dev/docs/api/admin-graphql/2026-07/mutations/fulfillmentOrderMove) require the items to be stocked at the destination.

Historical orders and orders that never committed stock are excluded from shipment push. Fulfilment orders and their lines use bounded, complete read pages; missing/repeated cursors stop partial data before any shipment mutation.
4 changes: 4 additions & 0 deletions docs/setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,7 @@ Place a test order in Shopify (enable **Also import test orders** first, or use
## 7. Future: a public app with OAuth

The plugin connects one store at a time with app client credentials or an existing Admin API token. A public Shopify app installed through OAuth (an install link, offline access tokens, Shopify's mandatory privacy webhooks) is planned; the connection model already keeps credentials as an encrypted set so an OAuth token can replace the custom app token without a data migration.

### Optional shipment sync

To push shipped parcels and tracking, upgrade Inventoros with shipment notification ownership, add `read_merchant_managed_fulfillment_orders` and `write_merchant_managed_fulfillment_orders` to the Shopify custom app, and enable shipment push in the connection settings. Keep one Shopify location per ship-from warehouse. Shopify owns customer shipping emails while this option is enabled, including while sync is paused. Resume sync to process queued shipments. Orders imported before exact line mappings were stored require manual fulfilment in Shopify. See the README for uncertain-response recovery.
2 changes: 1 addition & 1 deletion plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "Shopify",
"description": "Connect Inventoros with Shopify for asynchronous two-way product, inventory and order sync, with webhooks, retries, mappings and sync health checks.",
"version": "1.3.0",
"version": "1.4.0",
"author": "Inventoros",
"author_url": "https://inventoros.com",
"license": "AGPL-3.0-or-later",
Expand Down
6 changes: 6 additions & 0 deletions src/Console/SyncCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@

use Illuminate\Console\Command;
use Inventoros\Plugins\Shopify\Jobs\ProcessWebhook;
use Inventoros\Plugins\Shopify\Jobs\PushFulfilments;
use Inventoros\Plugins\Shopify\Jobs\PushInventory;
use Inventoros\Plugins\Shopify\Jobs\PushProducts;
use Inventoros\Plugins\Shopify\Jobs\RunSync;
use Inventoros\Plugins\Shopify\Kit\Models\Connection;
use Inventoros\Plugins\Shopify\Kit\Models\WebhookInboxEntry;
use Inventoros\Plugins\Shopify\Kit\Outbox\Outbox;
use Inventoros\Plugins\Shopify\Sync\FulfilmentPush;
use Inventoros\Plugins\Shopify\Sync\InventoryPush;
use Inventoros\Plugins\Shopify\Sync\ProductPush;

Expand Down Expand Up @@ -59,6 +61,10 @@ public function handle(Outbox $outbox): int
PushInventory::dispatch($connection->id);
}

if ($outbox->hasDue($connection, FulfilmentPush::KIND)) {
PushFulfilments::dispatch($connection->id);
}

if ($outbox->hasDue($connection, ProductPush::KIND)) {
PushProducts::dispatch($connection->id);
}
Expand Down
10 changes: 10 additions & 0 deletions src/Http/Controllers/ActionsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use Inventoros\Plugins\Shopify\Support\Core;
use Inventoros\Plugins\Shopify\Support\Permissions;
use Inventoros\Plugins\Shopify\Sync\Catalog;
use Inventoros\Plugins\Shopify\Sync\FulfilmentPush;
use Inventoros\Plugins\Shopify\Sync\InventoryPush;
use Inventoros\Plugins\Shopify\Sync\Locations;
use Inventoros\Plugins\Shopify\Sync\OrderImporter;
Expand Down Expand Up @@ -94,6 +95,9 @@ public function updateConnection(Request $request, int $connection): RedirectRes
unset($credentials['client_id'], $credentials['token_expires_at']);
}

if (($data['push_fulfilments'] ?? false) && ! $record->setting('push_fulfilments', false)) {
$retest = true;
}
if (($data['import_payments'] ?? false) && ! $record->setting('import_payments', false)) {
$retest = true; // Register the refund topic when payment imports are enabled.
}
Expand Down Expand Up @@ -401,12 +405,18 @@ private function validateConnection(Request $request, ?Connection $existing): ar
'stock_source' => ['required', Rule::in(SyncPolicy::STOCK_SOURCES)],
'product_source' => ['required', Rule::in(SyncPolicy::PRODUCT_SOURCES)],
'import_orders' => ['required', 'boolean'],
'push_fulfilments' => ['nullable', 'boolean'],
'import_payments' => ['nullable', 'boolean'],

'import_test_orders' => ['nullable', 'boolean'],
'orders_since' => ['required_with:history_before', 'nullable', 'date'],
'history_before' => ['nullable', 'date', 'after_or_equal:orders_since', 'before_or_equal:today'],
]);

if (($data['push_fulfilments'] ?? false) && ! FulfilmentPush::supported()) {
throw ValidationException::withMessages(['push_fulfilments' => 'Update Inventoros to a version with shipment notification ownership before enabling this option.']);
}

if (($data['import_payments'] ?? false) && ! Payments::supported()) {
throw ValidationException::withMessages(['import_payments' => 'Update Inventoros core to enable imported-payment records.']);
}
Expand Down
27 changes: 27 additions & 0 deletions src/Jobs/PushFulfilments.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace Inventoros\Plugins\Shopify\Jobs;

use Inventoros\Plugins\Shopify\Kit\Models\Connection;
use Inventoros\Plugins\Shopify\Shopify\SyncPolicy;
use Inventoros\Plugins\Shopify\Sync\FulfilmentPush;

class PushFulfilments extends PushInventory
{
protected function kindOfWork(): string
{
return FulfilmentPush::KIND;
}

protected function allowed(Connection $connection): bool
{
return SyncPolicy::for($connection)->pushesFulfilments();
}

protected function pushBatch(Connection $connection, $entries, $run): void
{
app(FulfilmentPush::class)->push($connection, $entries, $run);
}
}
71 changes: 71 additions & 0 deletions src/Shopify/FulfilmentQueries.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

declare(strict_types=1);

namespace Inventoros\Plugins\Shopify\Shopify;

final class FulfilmentQueries
{
public const ORDERS = <<<'GQL'
query FulfilmentOrders($id: ID!, $location: ID!, $after: String) {
order(id: $id) {
fulfillmentOrders(first: 2, after: $after) {
nodes {
id status requestStatus assignedLocation { location { id } }
lineItems(first: 50) {
nodes {
id remainingQuantity inventoryItemId
lineItem { id }
variant { inventoryItem { inventoryLevel(locationId: $location) { id } } }
}
pageInfo { hasNextPage endCursor }
}
}
pageInfo { hasNextPage endCursor }
}
}
}
GQL;

public const LINES = <<<'GQL'
query FulfilmentLines($id: ID!, $location: ID!, $after: String) {
fulfillmentOrder(id: $id) {
id
lineItems(first: 100, after: $after) {
nodes {
id remainingQuantity inventoryItemId lineItem { id }
variant { inventoryItem { inventoryLevel(locationId: $location) { id } } }
}
pageInfo { hasNextPage endCursor }
}
}
}
GQL;

public const ACTIVATE = <<<'GQL'
mutation ActivateForShipment($item: ID!, $location: ID!, $key: String!) {
inventoryActivate(inventoryItemId: $item, locationId: $location) @idempotent(key: $key) {
inventoryLevel { id }
userErrors { field message }
}
}
GQL;

public const MOVE = <<<'GQL'
mutation MoveShipmentLines($id: ID!, $location: ID!, $lines: [FulfillmentOrderLineItemInput!]!) {
fulfillmentOrderMove(id: $id, newLocationId: $location, fulfillmentOrderLineItems: $lines) {
movedFulfillmentOrder { id }
userErrors { field message }
}
}
GQL;

public const CREATE = <<<'GQL'
mutation FulfilShipment($fulfillment: FulfillmentInput!, $message: String) {
fulfillmentCreate(fulfillment: $fulfillment, message: $message) {
fulfillment { id }
userErrors { field message }
}
}
GQL;
}
70 changes: 68 additions & 2 deletions src/Shopify/HttpShopifyClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,72 @@ public function setInventoryQuantities(array $quantities, string $idempotencyKey
$this->assertNoUserErrors($data['inventorySetQuantities']['userErrors'] ?? []);
}

public function fulfilmentOrders(string $orderId, string $locationId): array
{
$result = [];
$after = null;
$seen = [];
do {
$data = $this->read(FulfilmentQueries::ORDERS, ['id' => Gid::make('Order', $orderId), 'location' => Gid::make('Location', $locationId), 'after' => $after], 600);
if (! is_array($data['order'] ?? null)) {
throw new PermanentError('The Shopify order no longer exists or is not accessible.');
}
$page = $data['order']['fulfillmentOrders'] ?? [];
foreach ($page['nodes'] ?? [] as $order) {
$order = $this->complete($order, 'lineItems', FulfilmentQueries::LINES, 'fulfillmentOrder', 600, ['location' => Gid::make('Location', $locationId)]);
$result[] = [
'id' => Gid::id($order['id']), 'status' => $order['status'], 'request_status' => $order['requestStatus'],
'location_id' => Gid::id($order['assignedLocation']['location']['id'] ?? null),
'lines' => array_map(fn ($line) => [
'id' => Gid::id($line['id']), 'line_id' => Gid::id($line['lineItem']['id']),
'inventory_item_id' => Gid::id($line['inventoryItemId'] ?? null), 'remaining' => (int) $line['remainingQuantity'],
'stocked' => ($line['variant']['inventoryItem']['inventoryLevel'] ?? null) !== null,
], $order['lineItems']['nodes'] ?? []),
];
}
$more = (bool) ($page['pageInfo']['hasNextPage'] ?? false);
$after = $page['pageInfo']['endCursor'] ?? null;
if ($more && (! is_string($after) || $after === '' || isset($seen[$after]))) {
throw new PermanentError('Shopify returned a missing or repeated fulfilment order cursor; refusing partial data.');
}
if ($more) {
$seen[$after] = true;
}
} while ($more);

return $result;
}

public function activateInventory(string $inventoryItemId, string $locationId, string $key): void
{
$data = $this->query(FulfilmentQueries::ACTIVATE, ['item' => Gid::make('InventoryItem', $inventoryItemId), 'location' => Gid::make('Location', $locationId), 'key' => $key], 10);
$this->assertNoUserErrors($data['inventoryActivate']['userErrors'] ?? []);
}

public function moveFulfilmentOrder(string $id, string $locationId, array $lines): void
{
if ($lines === []) {
throw new PermanentError('A shipment move must name its line quantities.');
}
$data = $this->query(FulfilmentQueries::MOVE, [
'id' => Gid::make('FulfillmentOrder', $id), 'location' => Gid::make('Location', $locationId),
'lines' => array_map(fn ($line) => ['id' => Gid::make('FulfillmentOrderLineItem', $line['id']), 'quantity' => $line['quantity']], $lines),
], 10);
$this->assertNoUserErrors($data['fulfillmentOrderMove']['userErrors'] ?? []);
}

public function createFulfilment(array $fulfilment, string $message): string
{
$data = $this->query(FulfilmentQueries::CREATE, ['fulfillment' => $fulfilment, 'message' => $message], 10);
$this->assertNoUserErrors($data['fulfillmentCreate']['userErrors'] ?? []);
$id = Gid::id($data['fulfillmentCreate']['fulfillment']['id'] ?? null);
if ($id === null) {
throw new TransientError('Shopify did not return a fulfilment id.');
}

return $id;
}

public function updateProductTitle(string $productId, string $title): void
{
$data = $this->query(Queries::UPDATE_PRODUCT, [
Expand Down Expand Up @@ -280,7 +346,7 @@ private function query(string $query, array $variables, int $expectedCost): arra
}

/** Finish a nested connection before returning a record to an importer. */
private function complete(array $node, string $field, string $query, string $root, int $cost): array
private function complete(array $node, string $field, string $query, string $root, int $cost, array $variables = []): array
{
$connection = $node[$field] ?? [];
$seen = [];
Expand All @@ -290,7 +356,7 @@ private function complete(array $node, string $field, string $query, string $roo
throw new PermanentError('Shopify returned a missing or repeated pagination cursor; refusing a partial record.');
}
$seen[$cursor] = true;
$data = $this->read($query, ['id' => $node['id'], 'after' => $cursor], $cost);
$data = $this->read($query, ['id' => $node['id'], 'after' => $cursor] + $variables, $cost);
if (! is_array($data[$root][$field] ?? null)) {
throw new TransientError('Shopify omitted a nested page; refusing a partial record. Retry the sync.');
}
Expand Down
11 changes: 11 additions & 0 deletions src/Shopify/ShopifyClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,17 @@ public function order(string $id): ?array;
*/
public function setInventoryQuantities(array $quantities, string $idempotencyKey): void;

/** Unfulfilled line ids and quantities, with destination stock activation state. */
public function fulfilmentOrders(string $orderId, string $locationId): array;

public function activateInventory(string $inventoryItemId, string $locationId, string $key): void;

/** Move only these explicit line ids/quantities; callers re-read afterwards. */
public function moveFulfilmentOrder(string $id, string $locationId, array $lines): void;

/** Returns the created fulfilment id. Not safe to replay after an ambiguous response. */
public function createFulfilment(array $fulfilment, string $message): string;

public function updateProductTitle(string $productId, string $title): void;

/**
Expand Down
4 changes: 4 additions & 0 deletions src/Shopify/ShopifyConnectionTester.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ public function test(Connection $connection): TestResult
$required[] = 'read_all_orders';
}
}
if ($policy->pushesFulfilments()) {
$required = array_merge($required, ['read_orders', 'read_merchant_managed_fulfillment_orders', 'write_merchant_managed_fulfillment_orders', 'write_inventory']);
}
$required = array_values(array_unique($required));
$granted = $shop['scopes'] ?? [];
$missing = array_values(array_filter($required, fn ($scope) => ! in_array($scope, $granted, true)
&& ! (str_starts_with($scope, 'read_') && in_array('write_'.substr($scope, 5), $granted, true))));
Expand Down
8 changes: 7 additions & 1 deletion src/Shopify/SyncPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ final class SyncPolicy
'stock_source' => 'inventoros',
'product_source' => 'shopify',
'import_orders' => true,
'push_fulfilments' => false,
'import_payments' => false,
'import_test_orders' => false,
'orders_since' => null,
Expand Down Expand Up @@ -67,7 +68,7 @@ public static function sanitize(array $input, array $current = []): array
$settings['product_source'] = $input['product_source'];
}

foreach (['import_orders', 'import_test_orders', 'import_payments'] as $flag) {
foreach (['import_orders', 'import_test_orders', 'push_fulfilments', 'import_payments'] as $flag) {
if (array_key_exists($flag, $input)) {
$settings[$flag] = (bool) $input[$flag];
}
Expand All @@ -84,6 +85,11 @@ public static function sanitize(array $input, array $current = []): array
return $settings;
}

public function pushesFulfilments(): bool
{
return (bool) $this->settings['push_fulfilments'];
}

public function pushesStock(): bool
{
return $this->settings['stock_source'] === 'inventoros';
Expand Down
Loading
Loading