From 90cc7d0ddb1b96d8902a2ecf1a3c7a82fdbd13e0 Mon Sep 17 00:00:00 2001 From: Matt Gros Date: Thu, 22 Oct 2026 21:27:42 -0400 Subject: [PATCH 1/2] Import completed Shopify payments and refunds --- CHANGELOG.md | 7 + README.md | 35 ++++- docs/setup.md | 37 +++-- plugin.json | 2 +- src/Http/Controllers/ActionsController.php | 10 ++ src/Http/Controllers/PagesController.php | 2 + src/Shopify/HttpShopifyClient.php | 20 +++ src/Shopify/Queries.php | 12 ++ src/Shopify/ShopifyClient.php | 3 + src/Shopify/SyncPolicy.php | 8 +- src/Sync/OrderImporter.php | 72 +++++---- src/Sync/Payments.php | 112 +++++++++++++ src/Sync/WebhookProcessor.php | 15 ++ tests/Fakes/FakeShopifyClient.php | 9 ++ tests/Feature/ConnectionsTest.php | 2 +- tests/Feature/PaymentCompatibilityTest.php | 33 ++++ tests/Feature/PaymentRecordsTest.php | 175 +++++++++++++++++++++ tests/Feature/TransactionClientTest.php | 41 +++++ ui/src/components/ConnectionForm.vue | 8 + ui/src/locales/en.json | 3 + ui/src/pages/Overview.vue | 4 +- 21 files changed, 552 insertions(+), 58 deletions(-) create mode 100644 src/Sync/Payments.php create mode 100644 tests/Feature/PaymentCompatibilityTest.php create mode 100644 tests/Feature/PaymentRecordsTest.php create mode 100644 tests/Feature/TransactionClientTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ebf933..25303a0 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.3.0] - Unreleased + +### Added + +- Opt-in records of completed Shopify payments and refunds, using core imported-payment support. Provider IDs prevent duplicates; currencies, manual-entry conflicts, voids and refund limits are checked. +- Refund webhooks refresh transaction history; incomplete histories are refused. Historical financial imports stay silent and current order announcements wait for the complete aggregate to commit. + ## [1.2.0] - Unreleased ### Added diff --git a/README.md b/README.md index 2403258..81db62e 100644 --- a/README.md +++ b/README.md @@ -94,11 +94,11 @@ Admins hold both. On Inventoros versions without plugin permissions they fall ba - Routes follow the plugin route namespace: names `plg.shopify.*`, pages and actions under `/p/shopify/` (the overview moved from `/shopify` to `/p/shopify` in 1.0.1; update bookmarks). The webhook address, `/webhooks/plugins/shopify/{connection}`, is unchanged, so subscriptions registered by 1.0.0 keep delivering and nothing needs re-registering. - The sidebar item is translated on cores that translate plugin menu items (`label_key`). - Known limitations and SDK gaps: - - Core has no stock reservations (SDK gap G4): an order placed in Shopify takes stock when it is imported, not when it is placed. + - 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; refunds and order edits after import are not applied. - - No public OAuth app yet (custom app tokens only); see [docs/setup.md](docs/setup.md#7-future-a-public-app-with-oauth). + - 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. + - 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 @@ -182,3 +182,32 @@ 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. + +### Payment and refund records + +Enable **Record Shopify payments and refunds** after reconciling any manual +payment entries. This optional setting is off by default and requires core's +`OrderPaymentService::recordImported()` API (core PR Inventoros/Inventoros#305). +Older cores retain all existing sync features and show an upgrade hint instead +of enabling payment import. Enabling the setting retests the connection and +registers the refund webhook; scheduled order reconciliation also updates it. + +Only successful sales, captures and refunds create ledger records. Pending or +failed transactions and uncaptured authorizations create no receipts. Amounts +and dates come from Shopify transactions in shop currency; a currency mismatch +is refused. There are no calls to capture, charge or refund money in Shopify. +Payment status and balances are derived by core from the imported ledger, never +from a Shopify status label. Actual overpayments remain visible as overpayments. + +Provider transaction IDs map to core payment IDs, so repeated webhooks/resyncs +add nothing twice. Conflicting transaction changes and missing mapped payments +need review. Manual voids remain voided. Active manual/unrelated payment rows +block automatic import until reconciled or voided to prevent double counting. +Refunds cannot exceed recorded receipts. Historical imports use the same ledger +path silently, including cancelled orders; live imports announce core payment +hooks only after commit. Importing financial records does not restock returns. + +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. diff --git a/docs/setup.md b/docs/setup.md index 3138288..b00e4d7 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -1,6 +1,6 @@ # Setting up the Shopify connection -This guide connects one Shopify store to one Inventoros organization with a **custom app** and its Admin API access token. You need to be a Shopify store owner or a staff member allowed to develop apps, and an Inventoros user with **Manage Shopify sync** (or **Edit Settings** on cores without plugin permissions). +This guide connects one Shopify store to one Inventoros organization with an installed Shopify app, using client credentials for an app and store in the same Shopify organization or an existing Admin API token. You need to be a Shopify store owner or a staff member allowed to develop apps, and an Inventoros user with **Manage Shopify sync** (or **Edit Settings** on cores without plugin permissions). ## Contents @@ -14,24 +14,23 @@ This guide connects one Shopify store to one Inventoros organization with a **cu ## 1. Create the custom app in Shopify -1. In the Shopify admin, open **Settings > Apps and sales channels > Develop apps**. If app development is not enabled yet, choose **Allow custom app development** (store owners only). -2. Choose **Create an app**, name it (for example *Inventoros*) and pick yourself as the developer. -3. Open **Configuration > Admin API integration > Configure** and select these scopes: +1. Create an app in the Shopify Dev Dashboard and install it on the store. Client-credentials authentication requires the app and store to belong to the same Shopify organization. +2. Configure the scopes used by your sync directions: | Scope | Why | |-------|-----| - | `read_products` | Read products and variants to map them by SKU | - | `write_products` | Push titles and prices, only when Inventoros owns products | + | `read_products` | Read products and variants for mapping | + | `write_products` | Push titles/prices when Inventoros owns products | | `read_inventory` | Read inventory levels | - | `write_inventory` | Push stock levels, when Inventoros owns stock | - | `read_locations` | Read your locations to map them to warehouses | - | `read_orders` | Import orders (Shopify serves the last 60 days; add `read_all_orders` if you import older ones) | + | `write_inventory` | Push stock when Inventoros owns stock | + | `read_locations` | Map locations to warehouses | + | `read_orders` | Import orders and their transactions | + | `read_all_orders` | Approved access to orders older than 60 days | -4. Save, open **API credentials** and choose **Install app**. -5. Reveal and copy the **Admin API access token** (it starts with `shpat_` and is shown once). -6. On the same page, copy the **API secret key**. Shopify signs every webhook with it; Inventoros refuses any webhook it cannot verify. +3. Copy the app **Client ID** and **Client secret** from its settings. In Inventoros, the API secret key field holds that client secret and verifies incoming webhooks. Tokens are acquired and renewed automatically in client-credentials mode; the Dev Dashboard does not show a permanent token for this grant. +4. Existing manually obtained Admin API tokens remain supported with the app's API secret key. Select the saved-token authentication mode for these. A public multi-merchant OAuth installation flow is not provided here. -If your store no longer offers custom app development in the admin, create the app in the Shopify Dev Dashboard instead, give it the same scopes, install it on the store, and use its Admin API access token and client secret in the same two fields. +See [Shopify's client-credentials setup](https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant). ## 2. Connect it in Inventoros @@ -41,14 +40,18 @@ Open **Shopify** in the sidebar (`/p/shopify`) and fill in **Connect a store**: |-------|-------| | Name | Anything that tells your stores apart | | Shop domain | `your-store.myshopify.com` (the handle alone, `your-store`, also works). Custom storefront domains are not Admin API hosts and are refused. | -| Admin API access token | The `shpat_...` token | -| API secret key | The secret from step 1.6 | +| Authentication | App client credentials for stores in your own Shopify organization, or a saved Admin API token | +| App client ID | The app client ID in client-credentials mode | +| Admin API access token | Your existing token in saved-token mode | +| API secret key | The app client secret used to verify webhooks | | Who owns stock levels | **Inventoros** pushes Inventoros quantities to Shopify; **Shopify** applies Shopify's quantities to Inventoros. Pick one owner. | | Who owns product names and prices | **Shopify** copies Shopify edits into Inventoros; **Inventoros** pushes Inventoros edits to Shopify. | | Import Shopify orders | On by default | | Import orders placed on or after | Today by default, so old orders are not imported by accident | +| Import orders before this date as history | Optional cutoff (UTC); earlier orders do not change stock or announce new orders | +| Record Shopify payments and refunds | Optional, off by default; requires imported-payment support in core and reconciliation of manual entries | -**Save and test** stores the token and secret encrypted and queues a connection test. The page never waits on Shopify: refresh after a few seconds. When the test passes the store shows **Healthy**, the plugin registers its webhooks and reads your locations. If it fails, the card shows why (a wrong token, missing scopes, a token for another store). +**Save and test** stores credentials encrypted and queues a connection test. The page never waits on Shopify: refresh after a few seconds. When the test passes the store shows **Healthy**, the plugin registers its webhooks and reads your locations. If it fails, the card shows why (a wrong token, missing scopes, a token for another store). The background work needs the Inventoros queue worker and scheduler running (on cPanel the scheduler also drains the queue; see the core's CPANEL.md). @@ -91,4 +94,4 @@ Place a test order in Shopify (enable **Also import test orders** first, or use ## 7. Future: a public app with OAuth -Version 1 connects with a custom app's access token, one store at a time. 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. +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. diff --git a/plugin.json b/plugin.json index 4b1643f..ca0f5df 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.2.0", + "version": "1.3.0", "author": "Inventoros", "author_url": "https://inventoros.com", "license": "AGPL-3.0-or-later", diff --git a/src/Http/Controllers/ActionsController.php b/src/Http/Controllers/ActionsController.php index edca118..fafbdba 100644 --- a/src/Http/Controllers/ActionsController.php +++ b/src/Http/Controllers/ActionsController.php @@ -31,6 +31,7 @@ use Inventoros\Plugins\Shopify\Sync\InventoryPush; use Inventoros\Plugins\Shopify\Sync\Locations; use Inventoros\Plugins\Shopify\Sync\OrderImporter; +use Inventoros\Plugins\Shopify\Sync\Payments; use Inventoros\Plugins\Shopify\Sync\SkuMatcher; /** @@ -93,6 +94,10 @@ public function updateConnection(Request $request, int $connection): RedirectRes unset($credentials['client_id'], $credentials['token_expires_at']); } + if (($data['import_payments'] ?? false) && ! $record->setting('import_payments', false)) { + $retest = true; // Register the refund topic when payment imports are enabled. + } + $record->forceFill([ 'name' => $data['name'], 'acting_user_id' => $user->id, @@ -396,11 +401,16 @@ 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'], + '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['import_payments'] ?? false) && ! Payments::supported()) { + throw ValidationException::withMessages(['import_payments' => 'Update Inventoros core to enable imported-payment records.']); + } + if ($existing === null && ! ShopDomain::valid($data['shop_domain'])) { throw ValidationException::withMessages(['shop_domain' => __('shopify::messages.invalid_domain')]); } diff --git a/src/Http/Controllers/PagesController.php b/src/Http/Controllers/PagesController.php index a424696..cb0be64 100644 --- a/src/Http/Controllers/PagesController.php +++ b/src/Http/Controllers/PagesController.php @@ -25,6 +25,7 @@ use Inventoros\Plugins\Shopify\Sync\Catalog; use Inventoros\Plugins\Shopify\Sync\Locations; use Inventoros\Plugins\Shopify\Sync\OrderImporter; +use Inventoros\Plugins\Shopify\Sync\Payments; /** * Props of the plugin's three pages. register_page() calls these only for @@ -56,6 +57,7 @@ public static function overview(Request $request, User $user): array 'canManage' => Permissions::canManage($user), 'apiVersion' => ShopifyClient::API_VERSION, 'defaults' => SyncPolicy::DEFAULTS, + 'supportsPaymentImport' => Payments::supported(), 'urls' => self::urls(), ]; } diff --git a/src/Shopify/HttpShopifyClient.php b/src/Shopify/HttpShopifyClient.php index b57fd07..7e44ac5 100644 --- a/src/Shopify/HttpShopifyClient.php +++ b/src/Shopify/HttpShopifyClient.php @@ -152,6 +152,26 @@ public function order(string $id): ?array return is_array($data['order'] ?? null) ? Normalizer::order($this->complete($data['order'], 'lineItems', Queries::ORDER_LINES, 'order', 800)) : null; } + public function transactions(string $orderId): array + { + $data = $this->read(Queries::ORDER_TRANSACTIONS, ['id' => Gid::make('Order', $orderId)], 500); + $order = $data['order'] ?? []; + $rows = $order['transactions'] ?? null; + if (! is_array($rows) || ($order['transactionsCount']['precision'] ?? '') !== 'EXACT' + || ($order['transactionsCount']['count'] ?? -1) !== count($rows)) { + throw new PermanentError('Shopify did not return the complete transaction history (maximum 100 transactions per order). Review this order manually rather than importing partial payments.'); + } + + return array_map(fn ($row) => [ + 'id' => (string) Gid::id($row['id'] ?? null), 'kind' => strtolower((string) ($row['kind'] ?? '')), + 'status' => strtolower((string) ($row['status'] ?? '')), 'gateway' => $row['gateway'] ?? '', + 'amount' => (string) ($row['amountSet']['shopMoney']['amount'] ?? ''), + 'currency' => $row['amountSet']['shopMoney']['currencyCode'] ?? '', + 'processed_at' => $row['processedAt'] ?? $row['createdAt'] ?? null, + 'parent_id' => Gid::id($row['parentTransaction']['id'] ?? null), + ], $rows); + } + public function setInventoryQuantities(array $quantities, string $idempotencyKey): void { if ($quantities === []) { diff --git a/src/Shopify/Queries.php b/src/Shopify/Queries.php index d58dc77..a13d7ee 100644 --- a/src/Shopify/Queries.php +++ b/src/Shopify/Queries.php @@ -156,6 +156,18 @@ final class Queries } GQL; + public const ORDER_TRANSACTIONS = <<<'GQL' + query OrderTransactions($id: ID!) { + order(id: $id) { + transactionsCount { count precision } + transactions(first: 100) { + id kind status gateway processedAt createdAt parentTransaction { id } + amountSet { shopMoney { amount currencyCode } } + } + } + } + GQL; + public const SET_QUANTITIES = <<<'GQL' mutation SetQuantities($input: InventorySetQuantitiesInput!, $idempotencyKey: String!) { inventorySetQuantities(input: $input) @idempotent(key: $idempotencyKey) { diff --git a/src/Shopify/ShopifyClient.php b/src/Shopify/ShopifyClient.php index bcd1f79..17f671e 100644 --- a/src/Shopify/ShopifyClient.php +++ b/src/Shopify/ShopifyClient.php @@ -35,6 +35,9 @@ interface ShopifyClient */ public function shop(): array; + /** Successful and non-successful transactions, in shop currency; complete or refused. */ + public function transactions(string $orderId): array; + /** * @return Page */ diff --git a/src/Shopify/SyncPolicy.php b/src/Shopify/SyncPolicy.php index 18b781e..00394a1 100644 --- a/src/Shopify/SyncPolicy.php +++ b/src/Shopify/SyncPolicy.php @@ -33,6 +33,7 @@ final class SyncPolicy 'stock_source' => 'inventoros', 'product_source' => 'shopify', 'import_orders' => true, + 'import_payments' => false, 'import_test_orders' => false, 'orders_since' => null, 'history_before' => null, @@ -66,7 +67,7 @@ public static function sanitize(array $input, array $current = []): array $settings['product_source'] = $input['product_source']; } - foreach (['import_orders', 'import_test_orders'] as $flag) { + foreach (['import_orders', 'import_test_orders', 'import_payments'] as $flag) { if (array_key_exists($flag, $input)) { $settings[$flag] = (bool) $input[$flag]; } @@ -108,6 +109,11 @@ public function importsOrders(): bool return (bool) $this->settings['import_orders']; } + public function importsPayments(): bool + { + return (bool) $this->settings['import_payments']; + } + public function importsTestOrders(): bool { return (bool) $this->settings['import_test_orders']; diff --git a/src/Sync/OrderImporter.php b/src/Sync/OrderImporter.php index 7a37793..d163469 100644 --- a/src/Sync/OrderImporter.php +++ b/src/Sync/OrderImporter.php @@ -52,6 +52,7 @@ public function __construct( private readonly Locations $locations, private readonly SyncRecorder $recorder, private readonly OrderService $orders, + private readonly Payments $payments, ) {} public static function reference(Connection $connection, string $orderId): string @@ -129,11 +130,12 @@ private function create(Connection $connection, string $id, array $order, ?Carbo return $this->ignore($connection, $id, $label, $updatedAt, 'no line items that ship from stock', $run); } + $transactions = $this->payments->read($connection, $id); $reference = self::reference($connection, $id); $mapping = $this->mappings->remember($connection, self::ENTITY, $id, ['external_label' => $label]); try { - $created = DB::transaction(function () use ($connection, $mapping, $reference, $order, $items, $actor, $label, $historical) { + $created = DB::transaction(function () use ($connection, $mapping, $reference, $order, $items, $actor, $label, $historical, $transactions) { // Serialize concurrent imports of the same order on its mapping row. $locked = Mapping::query()->whereKey($mapping->id)->lockForUpdate()->first(); @@ -155,7 +157,13 @@ private function create(Connection $connection, string $id, array $order, ?Carbo $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); + $created = $this->orders->create($data, $actor, 'shopify', ! $historical, false); + if (! $historical) { + // Announce the complete aggregate only after order, payment + // records and mapping have all committed successfully. + DB::afterCommit(fn () => do_action('order_created', $created->refresh()->load('items'), $actor)); + } + $this->payments->sync($connection, $created, $transactions); $this->mappings->link($locked, 'order', (int) $created->id); return $created; @@ -173,7 +181,7 @@ private function create(Connection $connection, string $id, array $order, ?Carbo if ($created === null) { $this->log($connection, $run, 'info', "Order {$label} was already imported.", $id, $mapping->internal_id, 'duplicate'); - return 'unchanged'; + return $this->update($connection, $mapping->refresh(), $order, $updatedAt, $label, $run); } foreach ($skippedLines as $line) { @@ -203,39 +211,35 @@ 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'; + $transactions = $this->payments->read($connection, (string) $order['id']); - if (($order['cancelled_at'] ?? null) !== null && $core->status !== OrderStatus::CANCELLED) { - try { - Core::cancelOrder($this->orders, $core, Core::actor($connection)); - $outcome = 'cancelled'; - $this->log($connection, $run, 'info', "Cancelled order {$core->order_number} (Shopify {$label}) and restocked it.", (string) $order['id'], (int) $core->id, 'cancel_order'); - } catch (InvalidStateException $error) { - $this->log($connection, $run, 'warning', "Shopify cancelled {$label}, but Inventoros order {$core->order_number} cannot be cancelled: {$error->getMessage()}", (string) $order['id'], (int) $core->id, 'cancel_order'); + return DB::transaction(function () use ($connection, $mapping, $order, $updatedAt, $label, $run, $transactions) { + $lockedMapping = Mapping::whereKey($mapping->id)->lockForUpdate()->firstOrFail(); + if ($this->mappings->isStale($lockedMapping, $updatedAt)) { + return 'stale'; } - } - - $this->mappings->touch($mapping, $updatedAt); - - return $outcome; + $core = Core::orders((int) $connection->organization_id)->whereKey($lockedMapping->internal_id)->lockForUpdate()->firstOrFail(); + $this->payments->sync($connection, $core, $transactions); + $outcome = 'unchanged'; + if ($core->metadata['shopify']['historical'] ?? false) { + $core->forceFill(['status' => $this->historicalStatus($order)])->save(); + } elseif (($order['cancelled_at'] ?? null) !== null && $core->status !== OrderStatus::CANCELLED) { + try { + Core::cancelOrder($this->orders, $core, Core::actor($connection)); + $outcome = 'cancelled'; + $this->log($connection, $run, 'info', "Cancelled order {$core->order_number} (Shopify {$label}) and restocked it.", (string) $order['id'], (int) $core->id, 'cancel_order'); + } catch (InvalidStateException $error) { + $this->log($connection, $run, 'warning', "Shopify cancelled {$label}, but Inventoros order {$core->order_number} cannot be cancelled: {$error->getMessage()}", (string) $order['id'], (int) $core->id, 'cancel_order'); + } + } + $metadata = $core->metadata ?? []; + $metadata['shopify']['financial_status'] = $order['financial_status'] ?? null; + $metadata['shopify']['fulfillment_status'] = $order['fulfillment_status'] ?? null; + $core->forceFill(['metadata' => $metadata])->save(); + $this->mappings->touch($lockedMapping, $updatedAt); + + return $outcome; + }); } /** diff --git a/src/Sync/Payments.php b/src/Sync/Payments.php new file mode 100644 index 0000000..5dcd432 --- /dev/null +++ b/src/Sync/Payments.php @@ -0,0 +1,112 @@ +importsPayments() || ! $policy->importsOrders()) { + return null; + } + if (! self::supported()) { + throw new PermanentError('Update Inventoros to a core with imported-payment support before enabling Shopify payment imports.'); + } + + return app(ClientFactory::class)->make($connection)->transactions($orderId); + } + + public function sync(Connection $connection, Order $order, ?array $transactions): void + { + if ($transactions === null || $transactions === []) { + return; + } + $movements = []; + foreach ($transactions as $transaction) { + if (($transaction['status'] ?? '') !== 'success' || ! in_array($transaction['kind'] ?? '', ['sale', 'capture', 'refund'], true)) { + continue; // Authorizations, voided authorizations and failures do not move money. + } + if (! preg_match('/^[0-9]+(?:\.[0-9]{1,2})?$/', (string) ($transaction['amount'] ?? '')) + || ($transaction['id'] ?? '') === '' || empty($transaction['processed_at'])) { + throw new PermanentError('Shopify returned an invalid transaction amount, ID or date. Refusing to guess a payment.'); + } + if (($transaction['currency'] ?? '') !== $order->currency) { + throw new PermanentError('Shopify transaction currency differs from the Inventoros order. Reconcile it before retrying; no currency conversion is assumed.'); + } + if (! Money::isZero($transaction['amount'])) { + $movements[] = $transaction; + } + } + if ($movements === []) { + return; + } + // Receipts precede refunds even when the provider returns them reversed. + usort($movements, fn ($a, $b) => ($a['kind'] === 'refund') <=> ($b['kind'] === 'refund')); + + try { + DB::transaction(function () use ($connection, $order, $movements) { + $locked = Core::orders((int) $connection->organization_id)->whereKey($order->id)->lockForUpdate()->firstOrFail(); + $mapped = Mapping::forOrganization($connection->organization_id)->where('connection_id', $connection->id) + ->where('entity', self::ENTITY)->where('internal_type', 'order_payment')->whereNotNull('internal_id')->pluck('internal_id'); + if ($locked->payments()->withoutGlobalScopes()->active()->whereNotIn('id', $mapped)->exists()) { + throw new PermanentError('This order already has manually recorded or unrelated payments. Reconcile or void duplicate manual entries before retrying Shopify payment imports.'); + } + $mappings = app(MappingStore::class); + $service = app(OrderPaymentService::class); + $actor = Core::actor($connection); + foreach ($movements as $transaction) { + $mapping = $mappings->remember($connection, self::ENTITY, $transaction['id'], [ + 'external_label' => 'Transaction '.$transaction['id'], + 'meta' => ['order_id' => $locked->id, 'kind' => $transaction['kind'], 'parent_id' => $transaction['parent_id'] ?? null], + ]); + $type = $transaction['kind'] === 'refund' ? 'refund' : 'payment'; + if ($mapping->internal_id !== null) { + $payment = OrderPayment::withoutGlobalScopes()->where('organization_id', $connection->organization_id)->find($mapping->internal_id); + if ($payment === null || $payment->order_id !== $locked->id || $payment->type->value !== $type + || Money::compare($payment->amount, $transaction['amount']) !== 0) { + throw new PermanentError('A previously imported Shopify transaction changed or its payment is missing. Review the existing ledger before retrying.'); + } + + continue; // A manual void stays voided; never resurrect it. + } + $data = [ + 'source' => 'shopify', 'type' => $type, + 'amount' => $transaction['amount'], 'method' => 'other', + 'reference' => 'shopify:'.$connection->shop_domain.':'.$transaction['id'], + 'paid_at' => $transaction['processed_at'], + 'notes' => 'Imported Shopify '.$transaction['kind'].'; gateway: '.mb_substr((string) ($transaction['gateway'] ?? ''), 0, 120), + ]; + $payment = $service->recordImported($locked, $actor, $data, announce: ! ($locked->metadata['shopify']['historical'] ?? false)); + $mappings->link($mapping, 'order_payment', (int) $payment->id); + } + }); + } catch (ValidationException $error) { + throw new PermanentError('Shopify payments need review: '.implode(' ', $error->validator->errors()->all())); + } + } +} diff --git a/src/Sync/WebhookProcessor.php b/src/Sync/WebhookProcessor.php index fc29722..a86cc83 100644 --- a/src/Sync/WebhookProcessor.php +++ b/src/Sync/WebhookProcessor.php @@ -8,6 +8,7 @@ use Inventoros\Plugins\Shopify\Kit\Models\SyncRun; use Inventoros\Plugins\Shopify\Kit\Models\WebhookInboxEntry; use Inventoros\Plugins\Shopify\Kit\Sync\SyncRecorder; +use Inventoros\Plugins\Shopify\Shopify\ClientFactory; use Inventoros\Plugins\Shopify\Shopify\Normalizer; use Inventoros\Plugins\Shopify\Shopify\SyncPolicy; @@ -25,6 +26,7 @@ final class WebhookProcessor 'products/update' => 'PRODUCTS_UPDATE', 'inventory_levels/update' => 'INVENTORY_LEVELS_UPDATE', 'app/uninstalled' => 'APP_UNINSTALLED', + 'refunds/create' => 'REFUNDS_CREATE', ]; public const UNINSTALLED = 'app/uninstalled'; @@ -53,6 +55,19 @@ public function process(Connection $connection, WebhookInboxEntry $entry, SyncRu return in_array($outcome, ['stale', 'skipped'], true) ? "order {$outcome}" : null; + case 'refunds/create': + if (! $policy->importsPayments() || ! $policy->importsOrders() || empty($data['order_id'])) { + return 'Payment imports are disabled or the refund has no order'; + } + $order = app(ClientFactory::class)->make($connection)->order((string) $data['order_id']); + if ($order === null) { + return 'The refunded order is not available'; + } + $outcome = $this->orders->import($connection, $order, $run); + $this->count($run, $outcome); + + return in_array($outcome, ['stale', 'skipped'], true) ? "order {$outcome}" : null; + case 'products/create': case 'products/update': $this->catalog->ingest($connection, Normalizer::product($data), $run, applyChanges: true); diff --git a/tests/Fakes/FakeShopifyClient.php b/tests/Fakes/FakeShopifyClient.php index 0816054..c65e895 100644 --- a/tests/Fakes/FakeShopifyClient.php +++ b/tests/Fakes/FakeShopifyClient.php @@ -43,6 +43,8 @@ final class FakeShopifyClient implements ShopifyClient /** @var array */ public array $subscriptions = []; + public array $transactions = []; + public function __construct() { $shop = self::fixture('shop')['data']['shop']; @@ -170,6 +172,13 @@ public function order(string $id): ?array return null; } + public function transactions(string $orderId): array + { + $this->record(__FUNCTION__, [$orderId]); + + return $this->transactions[$orderId] ?? []; + } + public function setInventoryQuantities(array $quantities, string $idempotencyKey): void { $this->record(__FUNCTION__, [$quantities, $idempotencyKey]); diff --git a/tests/Feature/ConnectionsTest.php b/tests/Feature/ConnectionsTest.php index e67fa4c..13083b2 100644 --- a/tests/Feature/ConnectionsTest.php +++ b/tests/Feature/ConnectionsTest.php @@ -62,7 +62,7 @@ public function test_connecting_stores_encrypted_credentials_and_tests_them_in_t $this->assertStringNotContainsString(self::TOKEN, $raw, 'encrypted at rest'); $this->assertStringNotContainsString(self::SECRET, $raw); - $this->assertSame(['ORDERS_CREATE', 'ORDERS_UPDATED', 'ORDERS_CANCELLED', 'PRODUCTS_CREATE', 'PRODUCTS_UPDATE', 'INVENTORY_LEVELS_UPDATE', 'APP_UNINSTALLED'], $this->shopify->subscriptions); + $this->assertSame(['ORDERS_CREATE', 'ORDERS_UPDATED', 'ORDERS_CANCELLED', 'PRODUCTS_CREATE', 'PRODUCTS_UPDATE', 'INVENTORY_LEVELS_UPDATE', 'APP_UNINSTALLED', 'REFUNDS_CREATE'], $this->shopify->subscriptions); $callback = collect($this->shopify->calls)->firstWhere(0, 'subscribeWebhook')[1][1]; $this->assertSame('https://inventory.example.com/webhooks/plugins/shopify/'.$connection->id, $callback); $this->assertSame(2, Mapping::query()->where('entity', 'location')->count(), 'locations read after the test'); diff --git a/tests/Feature/PaymentCompatibilityTest.php b/tests/Feature/PaymentCompatibilityTest.php new file mode 100644 index 0000000..bfd745c --- /dev/null +++ b/tests/Feature/PaymentCompatibilityTest.php @@ -0,0 +1,33 @@ +setUpWorld(); + Queue::fake(); + $this->actingAs($this->admin)->get('/p/shopify')->assertOk()->assertInertia(fn ($page) => $page->where('supportsPaymentImport', Payments::supported())); + $response = $this->post(route('plg.shopify.actions.connections.update', $this->store->id), [ + 'name' => 'Payments', 'stock_source' => 'inventoros', 'product_source' => 'shopify', + 'import_orders' => true, 'import_payments' => true, + ]); + if (Payments::supported()) { + $response->assertRedirect()->assertSessionHasNoErrors(); + $this->assertTrue($this->store->fresh()->setting('import_payments')); + } else { + $response->assertRedirect()->assertSessionHasErrors('import_payments'); + $this->assertFalse((bool) $this->store->fresh()->setting('import_payments')); + } + } +} diff --git a/tests/Feature/PaymentRecordsTest.php b/tests/Feature/PaymentRecordsTest.php new file mode 100644 index 0000000..fe4f275 --- /dev/null +++ b/tests/Feature/PaymentRecordsTest.php @@ -0,0 +1,175 @@ +markTestSkipped('This core does not support imported-payment records. The feature remains disabled.'); + } + $this->setUpWorld(); + $this->mapLocations(); + $this->mapCatalog(); + $this->store->forceFill(['settings' => array_replace($this->store->settings, ['import_payments' => true])])->save(); + } + + private function transaction(string $id, string $kind = 'capture', string $amount = '10.00', array $overrides = []): array + { + return array_replace(['id' => $id, 'kind' => $kind, 'status' => 'success', 'amount' => $amount, + 'currency' => 'USD', 'processed_at' => '2026-10-02T10:00:00Z', 'gateway' => 'example', 'parent_id' => null], $overrides); + } + + private function coreOrder(): Order + { + return Order::withoutGlobalScopes()->where('organization_id', $this->store->organization_id)->where('external_id', '5001')->sole(); + } + + public function test_successful_receipts_and_refunds_are_recorded_once_and_authorizations_are_ignored(): void + { + $announcedBalances = []; + add_action('order_created', function ($order) use (&$announcedBalances) { + $announcedBalances[] = $order->amount_paid; + }); + $this->shopify->transactions['5001'] = [ + $this->transaction('2', 'refund', '2.00'), $this->transaction('1'), + $this->transaction('3', 'authorization', '100'), $this->transaction('4', overrides: ['status' => 'failure']), + ]; + $importer = app(OrderImporter::class); + $this->assertSame('created', $importer->import($this->store, $this->shopify->orders[0])); + $core = $this->coreOrder(); + $this->assertSame('8.00', $core->amount_paid); + $this->assertCount(2, $core->payments); + $this->assertSame(['payment', 'refund'], $core->payments->map(fn ($row) => $row->type->value)->all()); + $this->assertSame('shopify:acme-store.myshopify.com:1', $core->payments->first()->reference); + $this->assertSame('unchanged', $importer->import($this->store, $this->shopify->orders[0])); + $this->assertSame(2, $core->payments()->count()); + $this->assertSame(8, $this->bolt->fresh()->stock); + $this->assertSame(['8.00'], $announcedBalances); + } + + public function test_historical_cancelled_receipts_and_refunds_are_silent_and_do_not_move_stock(): void + { + $this->store->forceFill(['settings' => array_replace($this->store->settings, ['orders_since' => '2026-01-01', 'history_before' => '2026-10-10'])])->save(); + $announced = 0; + add_action('payment_recorded', function () use (&$announced) { + $announced++; + }); + $this->shopify->transactions['5001'] = [$this->transaction('1'), $this->transaction('2', 'refund', '10')]; + $order = array_replace($this->shopify->orders[0], ['cancelled_at' => '2026-10-03T10:00:00Z']); + app(OrderImporter::class)->import($this->store, $order); + $core = $this->coreOrder(); + $this->assertSame('cancelled', $core->status->value); + $this->assertSame(PaymentStatus::REFUNDED, $core->payment_status); + $this->assertSame('0.00', $core->amount_paid); + $this->assertFalse($core->stock_committed); + $this->assertSame(10, $this->bolt->fresh()->stock); + $this->assertSame(0, $announced); + } + + public function test_manual_payments_require_reconciliation_before_remote_records_are_added(): void + { + $this->store->forceFill(['settings' => array_replace($this->store->settings, ['import_payments' => false])])->save(); + app(OrderImporter::class)->import($this->store, $this->shopify->orders[0]); + $core = $this->coreOrder(); + app(OrderPaymentService::class)->record($core, $this->admin, ['amount' => '2', 'method' => 'cash']); + $this->store->forceFill(['settings' => array_replace($this->store->settings, ['import_payments' => true])])->save(); + $this->shopify->transactions['5001'] = [$this->transaction('1')]; + try { + app(OrderImporter::class)->import($this->store, $this->shopify->orders[0]); + $this->fail('Expected manual payment reconciliation.'); + } catch (PermanentError $error) { + $this->assertStringContainsString('manually recorded', $error->getMessage()); + } + $this->assertSame(1, $core->payments()->count()); + $this->assertSame('2.00', $core->fresh()->amount_paid); + } + + public function test_a_manually_voided_import_is_not_resurrected_and_actual_overpayments_are_preserved(): void + { + $this->shopify->transactions['5001'] = [$this->transaction('1', amount: '100')]; + $importer = app(OrderImporter::class); + $importer->import($this->store, $this->shopify->orders[0]); + $core = $this->coreOrder(); + $this->assertSame(PaymentStatus::OVERPAID, $core->payment_status); + app(OrderPaymentService::class)->void($core->payments()->first(), $this->admin, 'Manual correction'); + $importer->import($this->store, $this->shopify->orders[0]); + $this->assertSame('0.00', $core->fresh()->amount_paid); + $this->assertSame(1, $core->payments()->count()); + } + + public function test_currency_mismatches_and_excess_refunds_refuse_partial_ledgers(): void + { + $announced = 0; + add_action('order_created', function () use (&$announced) { + $announced++; + }); + $this->shopify->transactions['5001'] = [$this->transaction('1'), $this->transaction('2', overrides: ['currency' => 'EUR'])]; + try { + app(OrderImporter::class)->import($this->store, $this->shopify->orders[0]); + $this->fail('Expected currency refusal.'); + } catch (PermanentError $error) { + $this->assertStringContainsString('currency', $error->getMessage()); + } + $this->assertSame(0, Order::withoutGlobalScopes()->where('external_id', '5001')->count()); + $this->shopify->transactions['5001'] = [$this->transaction('1'), $this->transaction('2', 'refund', '11')]; + try { + app(OrderImporter::class)->import($this->store, $this->shopify->orders[0]); + $this->fail('Expected excess refund refusal.'); + } catch (PermanentError $error) { + $this->assertStringContainsString('refund', $error->getMessage()); + } + $this->assertSame(0, Order::withoutGlobalScopes()->where('external_id', '5001')->count()); + $this->assertSame(10, $this->bolt->fresh()->stock); + $this->assertSame(0, $announced); + } + + public function test_refund_webhooks_refresh_the_order_and_record_the_new_refund(): void + { + $this->shopify->transactions['5001'] = [$this->transaction('1')]; + app(OrderImporter::class)->import($this->store, $this->shopify->orders[0]); + $this->shopify->transactions['5001'][] = $this->transaction('2', 'refund', '3'); + $this->webhook('refunds/create', ['id' => 42, 'order_id' => 5001])->assertOk(); + $this->assertSame('7.00', $this->coreOrder()->amount_paid); + $this->assertSame(2, $this->coreOrder()->payments()->count()); + $this->assertSame(8, $this->bolt->fresh()->stock); + } + + public function test_disabled_payment_imports_make_no_transaction_requests(): void + { + $this->store->forceFill(['settings' => array_replace($this->store->settings, ['import_payments' => false])])->save(); + app(OrderImporter::class)->import($this->store, $this->shopify->orders[0]); + $this->assertSame(0, $this->shopify->callsTo('transactions')); + $this->assertSame(0, $this->coreOrder()->payments()->count()); + } + + public function test_a_receipt_recorded_after_local_cancellation_keeps_its_actual_amount_without_restocking(): void + { + $this->store->forceFill(['settings' => array_replace($this->store->settings, ['import_payments' => false])])->save(); + $importer = app(OrderImporter::class); + $importer->import($this->store, $this->shopify->orders[0]); + $cancelled = array_replace($this->shopify->orders[0], ['cancelled_at' => '2026-10-05T10:00:00Z', 'updated_at' => '2026-10-05T10:00:00Z']); + $importer->import($this->store, $cancelled); + $this->store->forceFill(['settings' => array_replace($this->store->settings, ['import_payments' => true])])->save(); + $this->shopify->transactions['5001'] = [$this->transaction('1')]; + $importer->import($this->store, $cancelled); + $this->assertSame('10.00', $this->coreOrder()->amount_paid); + $this->assertSame('cancelled', $this->coreOrder()->status->value); + $this->assertSame(10, $this->bolt->fresh()->stock); + } +} diff --git a/tests/Feature/TransactionClientTest.php b/tests/Feature/TransactionClientTest.php new file mode 100644 index 0000000..ad6af0b --- /dev/null +++ b/tests/Feature/TransactionClientTest.php @@ -0,0 +1,41 @@ + Http::response(['data' => ['order' => [ + 'transactionsCount' => ['count' => 1, 'precision' => 'EXACT'], + 'transactions' => [['id' => 'gid://shopify/OrderTransaction/123', 'kind' => 'REFUND', 'status' => 'SUCCESS', + 'gateway' => 'example', 'createdAt' => '2026-10-02T10:00:00Z', 'parentTransaction' => ['id' => 'gid://shopify/OrderTransaction/122'], + 'amountSet' => ['shopMoney' => ['amount' => '9007199254.12', 'currencyCode' => 'USD']]]], + ]]])]); + $client = new HttpShopifyClient('acme-store.myshopify.com', 'token', CostBudget::for(123)); + $row = $client->transactions('5001')[0]; + $this->assertSame('9007199254.12', $row['amount']); + $this->assertSame('USD', $row['currency']); + $this->assertSame('refund', $row['kind']); + $this->assertSame('122', $row['parent_id']); + $this->assertSame('2026-10-02T10:00:00Z', $row['processed_at']); + } + + public function test_incomplete_transaction_lists_are_refused(): void + { + Http::fake(['*' => Http::response(['data' => ['order' => [ + 'transactionsCount' => ['count' => 101, 'precision' => 'EXACT'], 'transactions' => [], + ]]])]); + $this->expectException(PermanentError::class); + $this->expectExceptionMessage('complete transaction history'); + (new HttpShopifyClient('acme-store.myshopify.com', 'token', CostBudget::for(123)))->transactions('5001'); + } +} diff --git a/ui/src/components/ConnectionForm.vue b/ui/src/components/ConnectionForm.vue index 65c9d88..1d7aff5 100644 --- a/ui/src/components/ConnectionForm.vue +++ b/ui/src/components/ConnectionForm.vue @@ -8,6 +8,7 @@ const { PrimaryButton, SecondaryButton } = window.Inventoros.ui; const props = defineProps({ action: { type: String, required: true }, + supportsPayments: { type: Boolean, default: false }, connection: { type: Object, default: null }, defaults: { type: Object, default: () => ({}) }, }); @@ -29,6 +30,7 @@ const form = useForm({ stock_source: settings.stock_source ?? 'inventoros', product_source: settings.product_source ?? 'shopify', import_orders: settings.import_orders ?? true, + import_payments: settings.import_payments ?? false, import_test_orders: settings.import_test_orders ?? false, orders_since: settings.orders_since ?? today, history_before: settings.history_before ?? '', @@ -124,6 +126,12 @@ const submit = () => { {{ t('form.importTestOrders') }} + +

{{ supportsPayments ? t('form.paymentsHint') : t('form.paymentsUpgrade') }}

+

{{ form.errors.import_payments }}

diff --git a/ui/src/locales/en.json b/ui/src/locales/en.json index 2bee7ad..59f02a9 100644 --- a/ui/src/locales/en.json +++ b/ui/src/locales/en.json @@ -16,6 +16,9 @@ "apiVersion": "Admin API {version}" }, "form": { + "paymentsUpgrade": "Update Inventoros core to enable imported-payment records.", + "importPayments": "Record Shopify payments and refunds", + "paymentsHint": "Imports completed transactions into the payment ledger. This does not charge or refund customers. Reconcile existing manual payment entries first to prevent duplicates.", "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", diff --git a/ui/src/pages/Overview.vue b/ui/src/pages/Overview.vue index 51f781d..8a4fac0 100644 --- a/ui/src/pages/Overview.vue +++ b/ui/src/pages/Overview.vue @@ -16,6 +16,7 @@ const props = defineProps({ title: { type: String, default: 'Shopify' }, connections: { type: Array, default: () => [] }, canManage: { type: Boolean, default: false }, + supportsPaymentImport: { type: Boolean, default: false }, apiVersion: { type: String, default: '' }, defaults: { type: Object, default: () => ({}) }, urls: { type: Object, required: true }, @@ -54,7 +55,7 @@ const disconnect = (connection) => {

{{ t('overview.connect') }}

{{ t('overview.setupHint') }}

- + @@ -147,6 +148,7 @@ const disconnect = (connection) => { v-if="editing === connection.id" :action="`${urls.actions}/connections/${connection.id}`" :connection="connection" + :supports-payments="supportsPaymentImport" @done="editing = null" /> From 05ab9cae71145414e239f1b94aca7c006aa05fd1 Mon Sep 17 00:00:00 2001 From: Matt Gros Date: Thu, 22 Oct 2026 21:42:56 -0400 Subject: [PATCH 2/2] Include the setup guide in release archives --- bin/package.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/package.php b/bin/package.php index a91fc95..469adf1 100644 --- a/bin/package.php +++ b/bin/package.php @@ -17,7 +17,7 @@ // The folder name inside the archive. bin/rename.php rewrites it. const SLUG = 'shopify'; -const PACKED = ['plugin.json', 'Plugin.php', 'bootstrap.php', 'assets', 'src', 'database', 'hooks', 'lang', 'dist', 'README.md', 'CHANGELOG.md', 'LICENSE']; +const PACKED = ['plugin.json', 'Plugin.php', 'bootstrap.php', 'assets', 'src', 'database', 'hooks', 'lang', 'dist', 'README.md', 'docs/setup.md', 'CHANGELOG.md', 'LICENSE']; $root = dirname(__DIR__); $manifest = json_decode((string) file_get_contents($root.'/plugin.json'), true);