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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
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.1.0",
"version": "1.2.0",
"author": "Inventoros",
"author_url": "https://inventoros.com",
"license": "AGPL-3.0-or-later",
Expand Down
3 changes: 2 additions & 1 deletion src/Http/Controllers/ActionsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'])) {
Expand Down
4 changes: 4 additions & 0 deletions src/Shopify/ShopifyConnectionTester.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down
10 changes: 10 additions & 0 deletions src/Shopify/SyncPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ final class SyncPolicy
'import_orders' => true,
'import_test_orders' => false,
'orders_since' => null,
'history_before' => null,
'push_delay_seconds' => 10,
];

Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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']);
Expand Down
57 changes: 48 additions & 9 deletions src/Sync/OrderImporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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';
Expand All @@ -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<string, mixed> $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);
Expand All @@ -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();

Expand All @@ -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;
Expand All @@ -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';
}
Expand All @@ -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) {
Expand Down Expand Up @@ -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,
Expand All @@ -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);
}
Expand Down
2 changes: 1 addition & 1 deletion tests/Fakes/FakeShopifyClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']];
Expand Down
105 changes: 105 additions & 0 deletions tests/Feature/HistoricalOrdersTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php

declare(strict_types=1);

namespace Inventoros\Plugins\Shopify\Tests\Feature;

use App\Enums\OrderStatus;
use App\Models\Inventory\StockAdjustment;
use App\Models\Order\Order;
use Inventoros\Plugins\Shopify\Kit\Models\Mapping;
use Inventoros\Plugins\Shopify\Shopify\ShopifyConnectionTester;
use Inventoros\Plugins\Shopify\Sync\OrderImporter;
use Inventoros\Plugins\Shopify\Tests\Concerns\ShopifyWorld;
use Inventoros\Plugins\Shopify\Tests\TestCase;

final class HistoricalOrdersTest extends TestCase
{
use ShopifyWorld;

protected function setUp(): void
{
parent::setUp();
$this->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);
}
}
Loading
Loading