From 7cf48d3869a86f3c88b217d0a4a75ba4ea5a642d Mon Sep 17 00:00:00 2001 From: Matt Gros Date: Thu, 22 Oct 2026 21:02:17 -0400 Subject: [PATCH 1/2] Backfill older Shopify orders without moving stock --- README.md | 21 +++++ src/Http/Controllers/ActionsController.php | 3 +- src/Shopify/ShopifyConnectionTester.php | 4 + src/Shopify/SyncPolicy.php | 10 ++ src/Sync/OrderImporter.php | 57 +++++++++-- tests/Fakes/FakeShopifyClient.php | 2 +- tests/Feature/HistoricalOrdersTest.php | 105 +++++++++++++++++++++ ui/src/components/ConnectionForm.vue | 8 ++ ui/src/locales/en.json | 2 + 9 files changed, 201 insertions(+), 11 deletions(-) create mode 100644 tests/Feature/HistoricalOrdersTest.php diff --git a/README.md b/README.md index 518da15..2403258 100644 --- a/README.md +++ b/README.md @@ -161,3 +161,24 @@ No OAuth redirect/authorization-code flow is provided by this option. See [Shopify client credentials](https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant) and [token lifetimes](https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens). + +### Historical order backfills + +An optional **Import orders before this date as history** cutoff separates past +sales from new stock-moving orders. Set the import start date to the earliest +order you want, select the history cutoff, test the connection, then run a full +sync. Dates use UTC. Shopify access beyond 60 days requires approved +`read_all_orders` access as well as order access; connection tests name it when +an older start date is configured. + +Orders before the cutoff use core's historical import path: no stock/bin/serial +allocation, reservations, approval requests or new-order announcements. Fulfilled +orders are recorded as shipped, cancelled orders as cancelled, and other orders +as pending; exact remote statuses remain in metadata. No shipments are created. +Subsequent updates and cancellations remain historical even if the cutoff changes, +and never restock the goods. Orders on/after the cutoff keep the normal stock path. + +Variant mappings are still required. Orders skipped by the start-date filter in +this version can be revisited as history after changing the range. Manually ignored +records and ignored records with no recorded reason stay ignored. Existing live +orders are never converted into history by changing a setting. diff --git a/src/Http/Controllers/ActionsController.php b/src/Http/Controllers/ActionsController.php index ee3a3f9..edca118 100644 --- a/src/Http/Controllers/ActionsController.php +++ b/src/Http/Controllers/ActionsController.php @@ -397,7 +397,8 @@ private function validateConnection(Request $request, ?Connection $existing): ar 'product_source' => ['required', Rule::in(SyncPolicy::PRODUCT_SOURCES)], 'import_orders' => ['required', 'boolean'], 'import_test_orders' => ['nullable', 'boolean'], - 'orders_since' => ['nullable', 'date'], + 'orders_since' => ['required_with:history_before', 'nullable', 'date'], + 'history_before' => ['nullable', 'date', 'after_or_equal:orders_since', 'before_or_equal:today'], ]); if ($existing === null && ! ShopDomain::valid($data['shop_domain'])) { diff --git a/src/Shopify/ShopifyConnectionTester.php b/src/Shopify/ShopifyConnectionTester.php index 7193d74..9de8815 100644 --- a/src/Shopify/ShopifyConnectionTester.php +++ b/src/Shopify/ShopifyConnectionTester.php @@ -4,6 +4,7 @@ namespace Inventoros\Plugins\Shopify\Shopify; +use Carbon\Carbon; use Inventoros\Plugins\Shopify\Kit\Connections\ConnectionTester; use Inventoros\Plugins\Shopify\Kit\Connections\TestResult; use Inventoros\Plugins\Shopify\Kit\Exceptions\IntegrationException; @@ -36,6 +37,9 @@ public function test(Connection $connection): TestResult } if ($policy->importsOrders()) { $required[] = 'read_orders'; + if ($policy->ordersSince() !== null && Carbon::parse($policy->ordersSince())->lt(now()->subDays(60))) { + $required[] = 'read_all_orders'; + } } $granted = $shop['scopes'] ?? []; $missing = array_values(array_filter($required, fn ($scope) => ! in_array($scope, $granted, true) diff --git a/src/Shopify/SyncPolicy.php b/src/Shopify/SyncPolicy.php index a5cecf9..18b781e 100644 --- a/src/Shopify/SyncPolicy.php +++ b/src/Shopify/SyncPolicy.php @@ -35,6 +35,7 @@ final class SyncPolicy 'import_orders' => true, 'import_test_orders' => false, 'orders_since' => null, + 'history_before' => null, 'push_delay_seconds' => 10, ]; @@ -75,6 +76,10 @@ public static function sanitize(array $input, array $current = []): array $settings['orders_since'] = $input['orders_since'] ?: null; } + if (array_key_exists('history_before', $input)) { + $settings['history_before'] = $input['history_before'] ?: null; + } + return $settings; } @@ -113,6 +118,11 @@ public function ordersSince(): ?string return $this->settings['orders_since']; } + public function historyBefore(): ?string + { + return $this->settings['history_before']; + } + public function pushDelay(): int { return max(0, (int) $this->settings['push_delay_seconds']); diff --git a/src/Sync/OrderImporter.php b/src/Sync/OrderImporter.php index 5b5da6c..7a37793 100644 --- a/src/Sync/OrderImporter.php +++ b/src/Sync/OrderImporter.php @@ -72,6 +72,9 @@ public function import(Connection $connection, array $order, ?SyncRun $run = nul $policy = SyncPolicy::for($connection); $updatedAt = $this->time($order['updated_at'] ?? null); + $createdAt = $this->time($order['created_at'] ?? null); + $historical = $policy->historyBefore() !== null && $createdAt !== null + && $createdAt->lt(Carbon::parse($policy->historyBefore())->startOfDay()); $label = $order['name'] !== '' ? $order['name'] : "#{$id}"; $existing = $this->mappings->find($connection, self::ENTITY, $id); @@ -85,7 +88,7 @@ public function import(Connection $connection, array $order, ?SyncRun $run = nul return $this->update($connection, $existing, $order, $updatedAt, $label, $run); } - if ($existing !== null && $existing->status === Mapping::IGNORED) { + if ($existing !== null && $existing->status === Mapping::IGNORED && ! ($historical && $existing->meta('ignored_before_start', false))) { $this->mappings->touch($existing, $updatedAt); return 'skipped'; @@ -100,22 +103,24 @@ public function import(Connection $connection, array $order, ?SyncRun $run = nul } $since = $policy->ordersSince(); - $createdAt = $this->time($order['created_at'] ?? null); + if ($policy->historyBefore() !== null && $createdAt === null) { + throw new PermanentError('This order has no creation date; refusing to guess whether it should affect current stock.'); + } if ($since !== null && $createdAt !== null && $createdAt->lt(Carbon::parse($since)->startOfDay())) { return $this->ignore($connection, $id, $label, $updatedAt, "placed before {$since}", $run); } - if (($order['cancelled_at'] ?? null) !== null) { + if (! $historical && ($order['cancelled_at'] ?? null) !== null) { return $this->ignore($connection, $id, $label, $updatedAt, 'cancelled before it was imported', $run); } - return $this->create($connection, $id, $order, $updatedAt, $label, $run); + return $this->create($connection, $id, $order, $updatedAt, $label, $run, $historical); } /** * @param array $order */ - private function create(Connection $connection, string $id, array $order, ?Carbon $updatedAt, string $label, ?SyncRun $run): string + private function create(Connection $connection, string $id, array $order, ?Carbon $updatedAt, string $label, ?SyncRun $run, bool $historical = false): string { $actor = Core::actor($connection); [$items, $skippedLines] = $this->items($connection, $order, $label); @@ -128,7 +133,7 @@ private function create(Connection $connection, string $id, array $order, ?Carbo $mapping = $this->mappings->remember($connection, self::ENTITY, $id, ['external_label' => $label]); try { - $created = DB::transaction(function () use ($connection, $mapping, $reference, $order, $items, $actor, $label) { + $created = DB::transaction(function () use ($connection, $mapping, $reference, $order, $items, $actor, $label, $historical) { // Serialize concurrent imports of the same order on its mapping row. $locked = Mapping::query()->whereKey($mapping->id)->lockForUpdate()->first(); @@ -143,7 +148,14 @@ private function create(Connection $connection, string $id, array $order, ?Carbo return null; } - $created = $this->orders->create($this->orderData($connection, $order, $items, $reference, $label), $actor, 'shopify'); + $data = $this->orderData($connection, $order, $items, $reference, $label); + if ($historical) { + $data['status'] = $this->historicalStatus($order)->value; + $data['approval_status'] = 'not_required'; + $data['metadata']['shopify']['historical'] = true; + $data['notes'] = 'Historical Shopify import: '.$label.'. No current stock was changed.'; + } + $created = $this->orders->create($data, $actor, 'shopify', ! $historical, ! $historical); $this->mappings->link($locked, 'order', (int) $created->id); return $created; @@ -170,7 +182,9 @@ private function create(Connection $connection, string $id, array $order, ?Carbo $this->log($connection, $run, 'info', "Imported order {$label} as {$created->order_number}.", $id, (int) $created->id, 'import_order'); - Events::orderImported($connection, $created, $id, $label); + if (! $historical) { + Events::orderImported($connection, $created, $id, $label); + } return 'created'; } @@ -189,6 +203,24 @@ private function update(Connection $connection, Mapping $mapping, array $order, return 'skipped'; } + if ($core->metadata['shopify']['historical'] ?? false) { + // History stays history even after the connection cutoff changes. + return DB::transaction(function () use ($core, $order, $mapping, $updatedAt) { + $lockedMapping = Mapping::whereKey($mapping->id)->lockForUpdate()->firstOrFail(); + if ($this->mappings->isStale($lockedMapping, $updatedAt)) { + return 'stale'; + } + $locked = Core::orders((int) $core->organization_id)->whereKey($core->id)->lockForUpdate()->firstOrFail(); + $metadata = $locked->metadata ?? []; + $metadata['shopify']['financial_status'] = $order['financial_status'] ?? null; + $metadata['shopify']['fulfillment_status'] = $order['fulfillment_status'] ?? null; + $locked->forceFill(['status' => $this->historicalStatus($order), 'metadata' => $metadata])->save(); + $this->mappings->touch($lockedMapping, $updatedAt); + + return 'unchanged'; + }); + } + $outcome = 'unchanged'; if (($order['cancelled_at'] ?? null) !== null && $core->status !== OrderStatus::CANCELLED) { @@ -282,6 +314,7 @@ private function orderData(Connection $connection, array $order, array $items, s 'external_id' => (string) $order['id'], 'external_reference' => $reference, 'metadata' => [ + 'channel_order_number' => $label, 'shopify' => [ 'connection_id' => $connection->id, 'shop' => $connection->shop_domain, @@ -296,9 +329,15 @@ private function orderData(Connection $connection, array $order, array $items, s ], fn ($value) => $value !== null); } + private function historicalStatus(array $order): OrderStatus + { + return ($order['cancelled_at'] ?? null) !== null ? OrderStatus::CANCELLED + : (($order['fulfillment_status'] ?? '') === 'fulfilled' ? OrderStatus::SHIPPED : OrderStatus::PENDING); + } + private function ignore(Connection $connection, string $id, string $label, ?Carbon $updatedAt, string $why, ?SyncRun $run): string { - $mapping = $this->mappings->remember($connection, self::ENTITY, $id, ['external_label' => $label, 'status' => Mapping::IGNORED]); + $mapping = $this->mappings->remember($connection, self::ENTITY, $id, ['external_label' => $label, 'status' => Mapping::IGNORED, 'meta' => ['ignored_before_start' => str_starts_with($why, 'placed before ')]]); if ($mapping->status !== Mapping::IGNORED && $mapping->internal_id === null) { $this->mappings->mark($mapping, Mapping::IGNORED); } diff --git a/tests/Fakes/FakeShopifyClient.php b/tests/Fakes/FakeShopifyClient.php index 7c33e03..0816054 100644 --- a/tests/Fakes/FakeShopifyClient.php +++ b/tests/Fakes/FakeShopifyClient.php @@ -46,7 +46,7 @@ final class FakeShopifyClient implements ShopifyClient public function __construct() { $shop = self::fixture('shop')['data']['shop']; - $this->shop = ['id' => '77001', 'name' => $shop['name'], 'domain' => $shop['myshopifyDomain'], 'currency' => $shop['currencyCode'], 'plan' => $shop['plan']['displayName'], 'scopes' => ['read_products', 'write_products', 'read_inventory', 'write_inventory', 'read_locations', 'read_orders']]; + $this->shop = ['id' => '77001', 'name' => $shop['name'], 'domain' => $shop['myshopifyDomain'], 'currency' => $shop['currencyCode'], 'plan' => $shop['plan']['displayName'], 'scopes' => ['read_products', 'write_products', 'read_inventory', 'write_inventory', 'read_locations', 'read_orders', 'read_all_orders']]; foreach (self::fixture('locations')['data']['locations']['nodes'] as $node) { $this->locations[] = ['id' => substr($node['id'], strrpos($node['id'], '/') + 1), 'name' => $node['name'], 'active' => $node['isActive']]; diff --git a/tests/Feature/HistoricalOrdersTest.php b/tests/Feature/HistoricalOrdersTest.php new file mode 100644 index 0000000..e0d72b6 --- /dev/null +++ b/tests/Feature/HistoricalOrdersTest.php @@ -0,0 +1,105 @@ +setUpWorld(); + $this->mapLocations(); + $this->mapCatalog(); + $this->store->forceFill(['settings' => array_replace($this->store->settings, ['orders_since' => '2026-08-01', 'history_before' => '2026-10-01'])])->save(); + } + + private function oldOrder(array $overrides = []): array + { + return array_replace($this->shopify->orders[0], ['created_at' => '2026-09-01T12:00:00Z', 'updated_at' => '2026-09-02T12:00:00Z'], $overrides); + } + + public function test_old_sales_are_imported_once_without_stock_ledger_or_new_order_hooks(): void + { + $announced = 0; + add_action('order_created', function () use (&$announced) { + $announced++; + }); + $ledger = StockAdjustment::count(); + $importer = app(OrderImporter::class); + $this->bolt->forceFill(['stock' => 0])->save(); + $this->assertSame('created', $importer->import($this->store, $this->oldOrder(['fulfillment_status' => 'fulfilled']))); + $core = Order::withoutGlobalScopes()->where('external_id', '5001')->sole(); + $this->assertFalse($core->stock_committed); + $this->assertSame('not_required', $core->approval_status->value); + $this->assertTrue($core->metadata['shopify']['historical']); + $this->assertSame(OrderStatus::SHIPPED, $core->status); + $this->assertSame(0, $this->bolt->fresh()->stock); + $this->assertSame(5, $this->teeS->fresh()->stock); + $this->assertSame($ledger, StockAdjustment::count()); + $this->assertSame(0, $announced); + $this->assertSame('unchanged', $importer->import($this->store, $this->oldOrder(['fulfillment_status' => 'fulfilled']))); + $this->assertSame(1, Order::withoutGlobalScopes()->where('external_id', '5001')->count()); + } + + public function test_historical_cancellations_never_restock_or_become_live_after_settings_change(): void + { + $importer = app(OrderImporter::class); + $importer->import($this->store, $this->oldOrder()); + $this->store->forceFill(['settings' => ['import_orders' => true]])->save(); + $cancelled = $this->oldOrder(['updated_at' => '2026-10-02T12:00:00Z', 'cancelled_at' => '2026-10-02T12:00:00Z']); + $this->assertSame('unchanged', $importer->import($this->store, $cancelled)); + $core = Order::withoutGlobalScopes()->where('external_id', '5001')->sole(); + $this->assertSame(OrderStatus::CANCELLED, $core->status); + $this->assertFalse($core->stock_committed); + $this->assertSame(10, $this->bolt->fresh()->stock); + $this->assertSame(5, $this->teeS->fresh()->stock); + $this->assertSame('stale', $importer->import($this->store, $this->oldOrder())); + $this->assertSame(OrderStatus::CANCELLED, $core->fresh()->status); + } + + public function test_already_cancelled_history_is_recorded_but_recent_orders_still_take_stock(): void + { + $importer = app(OrderImporter::class); + $this->assertSame('created', $importer->import($this->store, $this->oldOrder(['cancelled_at' => '2026-09-02T12:00:00Z']))); + $this->assertSame(OrderStatus::CANCELLED, Order::withoutGlobalScopes()->where('external_id', '5001')->sole()->status); + $recent = $this->oldOrder(['id' => '9001', 'created_at' => '2026-10-02T00:00:00Z', 'updated_at' => '2026-10-02T00:00:00Z']); + $this->assertSame('created', $importer->import($this->store, $recent)); + $this->assertTrue(Order::withoutGlobalScopes()->where('external_id', '9001')->sole()->stock_committed); + $this->assertSame(8, $this->bolt->fresh()->stock); + } + + public function test_only_records_ignored_by_the_start_date_can_be_revisited_as_history(): void + { + $importer = app(OrderImporter::class); + $this->store->forceFill(['settings' => ['orders_since' => '2026-10-01']])->save(); + $this->assertSame('skipped', $importer->import($this->store, $this->oldOrder())); + $this->assertTrue($this->mapping('order', '5001')->meta('ignored_before_start')); + $this->store->forceFill(['settings' => ['orders_since' => '2026-08-01', 'history_before' => '2026-10-01']])->save(); + $this->assertSame('created', $importer->import($this->store, $this->oldOrder())); + $this->assertSame(10, $this->bolt->fresh()->stock); + Mapping::create(['organization_id' => $this->store->organization_id, 'connection_id' => $this->store->id, + 'entity' => 'order', 'external_id' => '9002', 'status' => Mapping::IGNORED]); + $this->assertSame('skipped', $importer->import($this->store, $this->oldOrder(['id' => '9002']))); + } + + public function test_connection_tests_identify_the_older_order_access_scope(): void + { + $this->shopify->shop['scopes'] = array_values(array_diff($this->shopify->shop['scopes'], ['read_all_orders'])); + $result = app(ShopifyConnectionTester::class)->test($this->store); + $this->assertFalse($result->ok); + $this->assertStringContainsString('read_all_orders', $result->message); + } +} diff --git a/ui/src/components/ConnectionForm.vue b/ui/src/components/ConnectionForm.vue index 66a5c6a..65c9d88 100644 --- a/ui/src/components/ConnectionForm.vue +++ b/ui/src/components/ConnectionForm.vue @@ -31,6 +31,7 @@ const form = useForm({ import_orders: settings.import_orders ?? true, import_test_orders: settings.import_test_orders ?? false, orders_since: settings.orders_since ?? today, + history_before: settings.history_before ?? '', }); const submit = () => { @@ -131,6 +132,13 @@ const submit = () => {

{{ form.errors.orders_since }}

+
+ + +

{{ t('form.historyHint') }}

+

{{ form.errors.history_before }}

+
+
{{ editing ? t('form.save') : t('form.saveAndTest') }} diff --git a/ui/src/locales/en.json b/ui/src/locales/en.json index 3238aa4..2bee7ad 100644 --- a/ui/src/locales/en.json +++ b/ui/src/locales/en.json @@ -16,6 +16,8 @@ "apiVersion": "Admin API {version}" }, "form": { + "historyBefore": "Import orders before this date as history (optional)", + "historyHint": "History does not change current stock or announce new orders. Set the import start date far enough back and run a full sync. Older than 60 days requires approved read_all_orders access.", "authMode": "Authentication", "authToken": "Saved Admin API token", "authClient": "App client credentials (automatic renewal)", From aef34f1a81360faa40491d14c4784044894ea054 Mon Sep 17 00:00:00 2001 From: Matt Gros Date: Thu, 22 Oct 2026 21:21:47 -0400 Subject: [PATCH 2/2] Version historical order settings for release --- CHANGELOG.md | 7 +++++++ plugin.json | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b765a3f..4ebf933 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ All notable changes to this plugin are documented here. The format follows [Keep ## [Unreleased] +## [1.2.0] - Unreleased + +### Added + +- Optional historical order cutoff: backfill older sales without stock, reservations, approvals or new-order announcements. Historical updates and cancellations never restock goods. +- Identify the read_all_orders scope for older import start dates, and revisit start-date-filtered records safely as history. + ## [1.1.0] - Unreleased ### Added diff --git a/plugin.json b/plugin.json index e3d9939..4b1643f 100644 --- a/plugin.json +++ b/plugin.json @@ -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.1.0", + "version": "1.2.0", "author": "Inventoros", "author_url": "https://inventoros.com", "license": "AGPL-3.0-or-later",