diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..4cf0df0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +# Only the Magento module is distributed (Packagist/Composer dist archives and Marketplace zips built with +# `git archive`). Tests, CI and contributor files stay in the repository. +/.github export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/CONTRIBUTING.md export-ignore +/Test export-ignore diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..18de437 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,21 @@ +## Summary + + + +## Supported-scope checklist + +- [ ] The change is within the documented storefront tracking and signed API scope. +- [ ] Public product data and private cart data remain separated. +- [ ] API-root validation, CSP and browser checks were updated together when relevant. +- [ ] Magento native checkout remains fail-open and no synchronous remote call was added. +- [ ] Tests cover the changed behavior and important negative cases. +- [ ] Documentation and the changelog match the shipped behavior. +- [ ] Manual validation was run for storefront, cart and cache behavior when relevant. + +## Verification + + + +## Rollout and rollback + + diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..765c412 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,104 @@ +name: Magento module checks + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + javascript: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: node --test Test/*.test.js Test/*.test.mjs Test/Unit/Js/*.test.cjs + - name: Check committed whitespace + env: + DIFF_BASE: ${{ github.event.pull_request.base.sha || github.event.before }} + run: | + if [[ "$DIFF_BASE" == "0000000000000000000000000000000000000000" ]]; then + DIFF_BASE=$(git hash-object -t tree -w /dev/null) + fi + git diff --check "$DIFF_BASE" HEAD + - name: Parse Magento XML files + shell: bash + run: | + set -euo pipefail + python3 - <<'PY' + import glob + import xml.etree.ElementTree as ET + + files = glob.glob('etc/**/*.xml', recursive=True) + glob.glob('view/**/*.xml', recursive=True) + for filename in files: + ET.parse(filename) + print(f'parsed {filename}') + PY + + php: + runs-on: ubuntu-latest + defaults: + run: + working-directory: module + strategy: + fail-fast: false + matrix: + php-version: ['8.2', '8.3'] + steps: + - uses: actions/checkout@v4 + with: + path: module + - uses: actions/checkout@v4 + with: + repository: magento/magento2 + ref: 2.4.7-p10 + path: magento + - uses: actions/checkout@v4 + with: + repository: magento/inventory + ref: 1.2.7-p10 + path: inventory + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php-version }} + extensions: bcmath, curl, dom, gd, intl, mbstring, pdo_mysql, soap, sodium, xsl, zip + tools: composer:v2 + - name: Lint PHP sources and isolated checks + shell: bash + run: | + set -euo pipefail + composer validate --no-check-publish + find Api Block Console Controller Model Observer Plugin Setup Test view registration.php \( -name '*.php' -o -name '*.phtml' \) -print0 | xargs -0 -n1 php -l + for test in Test/*.test.php; do php "$test"; done + - name: Install Magento unit test dependencies + run: | + cp -R ../inventory/InventoryApi ../inventory/InventorySalesApi ../magento/app/code/Magento/ + mkdir -p ../magento/app/code/Hellotext + ln -s "$GITHUB_WORKSPACE/module" ../magento/app/code/Hellotext/Tracking + composer --working-dir=../magento install --no-interaction --prefer-dist --no-progress + - name: Run PHPUnit against Magento 2.4.7-p10 + working-directory: magento + run: vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist app/code/Hellotext/Tracking/Test/Unit + + coding-standard: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + tools: composer:v2 + # Adobe's Marketplace technical review rejects severity-10 violations; warnings are reported only. + - name: Magento coding standard (errors) + shell: bash + run: | + set -euo pipefail + composer create-project --no-interaction --quiet magento/magento-coding-standard "$RUNNER_TEMP/mcs" + "$RUNNER_TEMP/mcs/vendor/bin/phpcs" --standard=Magento2 --severity=10 --extensions=php,phtml,xml \ + Api Block Console Controller Model Observer Plugin Setup etc view registration.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..855c883 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +.DS_Store +node_modules/ +vendor/ +tmp/ +generated/ +var/ +auth.json +auth.json.* +.env +.env.* +!.env.example +*.log +*.key +*.csr +*.crt +*.pem diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..ac82fb7 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,25 @@ +# Contributing + +This repository is the Magento module of the Hellotext integration. Keep changes small, explicit and reviewable. + +## Pull requests + +Every PR should state the user-visible behavior, the security and cache implications, the tests run and any manual check that remains. Do not add production credentials, local certificates, customer data, quote IDs or generated Magento assets. + +## Local checks + +```bash +node --test Test/*.test.js Test/*.test.mjs Test/Unit/Js/*.test.cjs +for test in Test/*.test.php; do php "$test"; done +composer validate --no-check-publish +``` + +The standalone PHP checks use small Magento stubs for mapping and guard logic. Also run the PHPUnit suite against Magento's real classes as described in [Test/README.md](Test/README.md). CI runs both suites on PHP 8.2 and 8.3, plus all JavaScript tests. These checks do not replace an installation smoke test on a real Magento store. + +## Commit and review expectations + +- Use the repository convention: `magento-integration: ...`. +- Regenerate Magento static assets after JavaScript or template changes. +- Do not weaken privacy, SSRF, CSRF, cache or session guards to make a local check pass. +- Do not introduce synchronous network calls into checkout. +- Changes that affect tracking payloads, identity or orders need a matching review on the Hellotext side. diff --git a/Model/OrderLifecycleTracker.php b/Model/OrderLifecycleTracker.php index db63c89..e10623c 100644 --- a/Model/OrderLifecycleTracker.php +++ b/Model/OrderLifecycleTracker.php @@ -96,16 +96,15 @@ private function post(string $apiRoot, string $business, string $action, string } } - // Magento sets an order's original data only when it loads one, so an order without it was created in - // this request. Storefront checkout must not wait on Hellotext: its success page reports the order. - // An Admin order has no success page, so it is reported here. + // An order without original data was created in this request. Only the frontend area relies on + // the success page to report placement; API and Admin requests are reported here. private function placedInCheckout(object $order): bool { if (!method_exists($order, 'getOrigData') || $order->getOrigData('entity_id') !== null) { return false; } try { - return $this->appState->getAreaCode() !== Area::AREA_ADMINHTML; + return $this->appState->getAreaCode() === Area::AREA_FRONTEND; } catch (\Throwable) { return true; } diff --git a/Model/VersionInformation.php b/Model/VersionInformation.php index 51f99a4..267f276 100644 --- a/Model/VersionInformation.php +++ b/Model/VersionInformation.php @@ -7,8 +7,8 @@ class VersionInformation { - // The storefront follows the latest 2.x release; the exact version is whatever jsDelivr serves. - public const SDK_VERSION = '2.x'; + // The storefront follows the latest release; the exact version is whatever jsDelivr serves. + public const SDK_VERSION = 'latest'; public function __construct(private ProductMetadataInterface $magento) {} diff --git a/Plugin/CartData.php b/Plugin/CartData.php index 9c78595..fe53c51 100644 --- a/Plugin/CartData.php +++ b/Plugin/CartData.php @@ -42,13 +42,24 @@ public function afterGetSectionData(Cart $subject, array $result): array if ($business === '' || !Configuration::isSafeApiRoot($api)) { return $result; } + $currency = (string) $store->getCurrentCurrencyCode(); + $result['hellotext'] = [ + 'enabled' => true, + 'context' => ['businessId' => $business, 'apiRoot' => $api, 'installationId' => $installation, 'storeId' => $storeId, 'currency' => $currency], + 'items' => [], + 'cart_ready' => false, + 'checkout_reference' => null, + 'identity' => $customerId > 0 && $this->config->isSetFlag('hellotext/tracking/identity_enabled', ScopeInterface::SCOPE_STORE, $storeId) + ? ['customer_id' => (string) $customerId] + : null, + ]; $quote = $this->checkout->getQuote(); // A quote of another customer (or store) must never be reported for this visitor. if ((string) $quote->getStoreId() !== $storeId || ($quote->getCustomerId() && (int) $quote->getCustomerId() !== $customerId)) { return $result; } - $currency = (string) ($quote->getQuoteCurrencyCode() ?: $store->getCurrentCurrencyCode()); + $currency = (string) ($quote->getQuoteCurrencyCode() ?: $currency); $rows = []; foreach ($quote->getAllVisibleItems() as $item) { $row = $this->product($item); @@ -68,21 +79,14 @@ public function afterGetSectionData(Cart $subject, array $result): array $rows[] = $row; } $items = CartPayload::items($rows, $installation, $storeId, $currency); - $result['hellotext'] = [ - 'enabled' => true, - 'context' => ['businessId' => $business, 'apiRoot' => $api, 'installationId' => $installation, 'storeId' => $storeId, 'currency' => $currency], - 'items' => $items, - 'cart_ready' => true, - 'checkout_reference' => $quote->getId() - ? Reference::build($installation, 'checkout', (int) $quote->getId()) - : null, - 'identity' => $customerId > 0 && $this->config->isSetFlag('hellotext/tracking/identity_enabled', ScopeInterface::SCOPE_STORE, $storeId) - ? ['customer_id' => (string) $customerId] - : null, - ]; + $reference = $quote->getId() + ? Reference::build($installation, 'checkout', (int) $quote->getId()) + : null; + $result['hellotext']['items'] = $items; + $result['hellotext']['cart_ready'] = true; + $result['hellotext']['checkout_reference'] = $reference; } catch (\Throwable $error) { - // Optional analytics must not break Magento cart/checkout or expose private error data. - $result['hellotext'] = ['enabled' => false]; + // Keep tracking enabled when only the cart could not be serialized. } return $result; } diff --git a/Test/README.md b/Test/README.md index c299c8f..2429515 100644 --- a/Test/README.md +++ b/Test/README.md @@ -1,4 +1,15 @@ -# Module unit tests +# Module tests + +Run all JavaScript tests and the standalone PHP checks from this module's directory: + +```sh +node --test Test/*.test.js Test/*.test.mjs Test/Unit/Js/*.test.cjs +for test in Test/*.test.php; do php "$test" || exit; done +``` + +The JavaScript suite requires Node.js 22. Standalone PHP checks use small Magento stubs and run in separate processes to avoid conflicts between their definitions. The PHPUnit suite below uses Magento's real classes. + +## PHPUnit Run these tests from a Magento Open Source 2.4.7-p10 development installation with its Composer development dependencies installed: @@ -10,6 +21,8 @@ For an installation under `app/code`, use `app/code/Hellotext/Tracking/Test/Unit The PHP tests cover session handoff, delegation to Magento's customer-cart merge, rejected links, failed persistence, redirects, browser-cache invalidation and attribution from the SDK cookie through order lifecycle events. Stock tests cover store/website scoping, native bulk salability, exact child IDs, unavailable products, batch bounds and incomplete/failed inventory responses. They use Magento's real class and interface definitions with mocked persistence and sessions; Inventory Sales API must be installed for the stock tests. +CI checks out Magento `2.4.7-p10` and the `InventoryApi` and `InventorySalesApi` modules from Inventory `1.2.7-p10`, installs Magento's Composer development dependencies, and runs this suite on PHP 8.2 and 8.3. It uses Magento's unit bootstrap, including generated factory classes, without a database or a running storefront. + Run the bridge behavior tests from this module's directory with Node.js 18 or newer: ```sh diff --git a/Test/Unit/Js/bridge.test.cjs b/Test/Unit/Js/bridge.test.cjs index 083bd4a..de839d8 100644 --- a/Test/Unit/Js/bridge.test.cjs +++ b/Test/Unit/Js/bridge.test.cjs @@ -9,7 +9,7 @@ const source = resolve(__dirname, '../../../view/frontend/web/js'); const linked = 'AbC123xyAbC123xyAbC123xyAbC123xy'; const flush = () => new Promise(resolve => setImmediate(resolve)); -async function storefront({ urlSession, cookieSession, identity = null, enabled = true, order = null } = {}) { +async function storefront({ urlSession, cookieSession, identity = null, enabled = true, order = null, offline = false, invalidItems = false } = {}) { const config = { businessId: 'business-one', installationId: 'store-one', storeId: '1', currency: 'USD', apiRoot: 'https://api.hellotext.com/v1', checkoutStarted: true @@ -28,6 +28,7 @@ async function storefront({ urlSession, cookieSession, identity = null, enabled quantity: 1, price: { amount: '25.00', currency: 'USD' } }] }; + if (invalidItems) { data.items = [{}]; } const window = { location: { href: 'https://shop.example/checkout/' + (urlSession ? '?hello_session=' + urlSession : '') }, sessionStorage: { @@ -57,7 +58,7 @@ async function storefront({ urlSession, cookieSession, identity = null, enabled }; const customerData = { getInitCustomerData: () => Promise.resolve(), - reload: () => Promise.resolve({ cart: { hellotext: data } }), + reload: () => offline ? Promise.reject(new Error('cart unavailable')) : Promise.resolve({ cart: { hellotext: data } }), get: () => ({ subscribe(callback) { subscription = callback; } }) }; let createCartTracker; @@ -70,7 +71,9 @@ async function storefront({ urlSession, cookieSession, identity = null, enabled console: { warn: (...args) => warnings.push(args) } }); await flush(); - return { sdk, data, cookies, storage, events, initializations, warnings, refresh: async () => { subscription(); await flush(); } }; + return { sdk, data, cookies, storage, events, initializations, warnings, + setOffline: value => { offline = value; }, + refresh: async () => { subscription(); await flush(); } }; } test('the URL session overrides an existing cookie and reaches checkout/cart tracking', async () => { @@ -140,6 +143,33 @@ test('the success-page event uses the SDK cookie', async () => { assert.deepEqual(page.events.find(event => event.action === 'order.placed'), { action: 'order.placed', session: linked }); }); +for (const failure of [{ offline: true }, { invalidItems: true }]) { + test(`tracks the success-page order despite ${Object.keys(failure)[0]}`, async () => { + const page = await storefront({ cookieSession: linked, order: 'magento:store-one:order:99', ...failure }); + assert.deepEqual(page.events.map(event => event.action).sort(), ['order.placed', 'page.viewed']); + assert.ok(page.events.every(event => event.session === linked)); + }); +} + +test('cart failures preserve the last snapshot and allow later cart updates', async () => { + const page = await storefront({ cookieSession: linked }); + const before = page.events.length; + page.setOffline(true); + await page.refresh(); + assert.equal(page.events.length, before); + + page.setOffline(false); + const items = page.data.items; + page.data.items = [{}]; + await page.refresh(); + assert.equal(page.events.length, before); + + page.data.items = items; + page.data.items[0].quantity = 2; + await page.refresh(); + assert.deepEqual(page.events.slice(before), [{ action: 'cart.added', session: linked }]); +}); + test('a disabled private section still prevents SDK initialization', async () => { const page = await storefront({ urlSession: linked, enabled: false }); assert.equal(page.initializations.length, 0); diff --git a/Test/Unit/Plugin/CartDataTest.php b/Test/Unit/Plugin/CartDataTest.php index 59ff1bf..52afb58 100644 --- a/Test/Unit/Plugin/CartDataTest.php +++ b/Test/Unit/Plugin/CartDataTest.php @@ -82,4 +82,21 @@ public function testCookieRestrictionsStillDisableTracking(): void self::assertSame(['enabled' => false], $result['hellotext']); } + + /** @dataProvider customers */ + public function testUnavailableCartKeepsTrackingAndCustomerIdentity(int $customerId): void + { + $this->customer->method('isLoggedIn')->willReturn($customerId > 0); + $this->customer->method('getCustomerId')->willReturn($customerId); + $this->checkout->method('getQuote')->willThrowException(new \RuntimeException('Cart unavailable')); + + $result = $this->subject->afterGetSectionData($this->createMock(Cart::class), ['summary_count' => 0]); + + self::assertSame(0, $result['summary_count']); + self::assertTrue($result['hellotext']['enabled']); + self::assertFalse($result['hellotext']['cart_ready']); + self::assertSame([], $result['hellotext']['items']); + self::assertNull($result['hellotext']['checkout_reference']); + self::assertSame($customerId > 0 ? ['customer_id' => (string) $customerId] : null, $result['hellotext']['identity']); + } } diff --git a/Test/bridge.test.js b/Test/bridge.test.js new file mode 100644 index 0000000..a40cda9 --- /dev/null +++ b/Test/bridge.test.js @@ -0,0 +1,491 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); +const vm = require('node:vm'); + +const source = fs.readFileSync( + path.join(__dirname, '../view/frontend/web/js/bridge.js'), + 'utf8' +); + +const anonymousSession = 'ae25b1d4-8000-4000-8000-123456789abc'; +const emptyTracker = () => () => Promise.resolve(); +emptyTracker.validItems = Array.isArray; + +function runBridge(context, identity = null, tracking = {}) { + let configuration; + context.window.location ||= { href: 'http://localhost/product.html' }; + context.document.cookie ||= ''; + const define = context.define; + const require = context.require; + context.require = (deps, callback) => require(deps, (sdk) => { + sdk.session = anonymousSession; + callback(sdk); + }); + context.define = (deps, factory) => define(deps, () => (value) => { + configuration = { installationId: 'store-one', storeId: '1', currency: 'USD', ...value }; + return factory({ + getInitCustomerData: () => Promise.resolve(), + reload: async () => ({ cart: { hellotext: { enabled: true, cart_ready: true, context: configuration, identity, items: [], ...tracking } }, customer: {} }), + get: () => ({ subscribe: () => {} }) + }, emptyTracker)(configuration); + }); + vm.runInNewContext(source, context); +} + +function productElement(payload, variants = {}) { + return { + getAttribute: (attribute) => JSON.stringify( + attribute === 'data-hellotext-product' ? payload : variants + ) + }; +} + +test('initializes once and sends the canonical product view payload', async () => { + const calls = []; + let initialize; + const sdk = { + initialize: async (id, options) => { calls.push(['initialize', id, options]); }, + track: async (action, params) => { + calls.push(['track', action, params]); + return { failed: false }; + } + }; + const context = { + window: {}, + document: { + querySelector: () => productElement({ + name: 'Test shirt', reference: 'magento:store-one:product:42', sku: 'TS-42', source: 'magento' + }), + querySelectorAll: () => [], + addEventListener: () => {} + }, + console, + Promise, + URL, + setTimeout, + require: (deps, callback) => { + calls.push(['require', deps[0]]); + callback(sdk); + }, + define: (_deps, factory) => { initialize = factory(); } + }; + runBridge(context); + + initialize({ businessId: 'public-business', apiRoot: 'http://api.lvh.me:3200/v1' }); + initialize({ businessId: 'public-business', apiRoot: 'http://api.lvh.me:3200/v1' }); + await new Promise(setImmediate); + + assert.equal(calls.filter(([name]) => name === 'require').length, 1); + assert.equal(calls[1][1], 'public-business'); + assert.equal(calls[1][2].apiRoot, 'http://api.lvh.me:3200/v1'); + assert.equal(calls[1][2].push, false); + assert.equal('session' in calls[1][2], false); + assert.equal('autoGenerateSession' in calls[1][2], false); + ['popup', 'webchat', 'whatsappWidget'].forEach((widget) => assert.equal(widget in calls[1][2], false)); + assert.equal(calls.find(([name, action]) => name === 'track' && action === 'page.viewed')[2].object_parameters.source, 'magento'); + assert.equal(calls.filter(([name, action]) => name === 'track' && action === 'page.viewed').length, 1); + const productCall = calls.find(([name, action]) => name === 'track' && action === 'product.viewed'); + assert.deepEqual(JSON.parse(JSON.stringify(productCall[2])), { + url: 'http://localhost/product.html', + object_parameters: { + name: 'Test shirt', reference: 'magento:store-one:product:42', sku: 'TS-42', source: 'magento' + } + }); +}); + +test('identifies an authenticated customer before storefront events and keeps tracking active', async () => { + const calls = []; + let initialize; + const identity = { customer_id: '42' }; + const sdk = { + initialize: async () => {}, + identify: async (id, options) => { calls.push(['identify', id, options]); return { failed: false }; }, + track: async (action) => { calls.push(['track', action]); return { failed: false }; } + }; + const context = { + window: {}, + document: { + querySelector: () => productElement({ name: 'Shirt', reference: 'magento:store-one:product:42', sku: 'TS-42', source: 'magento' }), + querySelectorAll: () => [], + addEventListener: () => {} + }, + console, Promise, URL, setTimeout, + require: (_deps, callback) => callback(sdk), + define: (_deps, factory) => { initialize = factory(); } + }; + runBridge(context, identity); + initialize({ businessId: 'public-business', apiRoot: 'http://api.lvh.me:3200/v1' }); + await new Promise(setImmediate); + + assert.equal(calls[0][0], 'identify'); + assert.deepEqual(JSON.parse(JSON.stringify(calls[0])), ['identify', '42', { source: 'magento' }]); + assert.deepEqual(calls.filter(([name]) => name === 'track').map(([, action]) => action), ['page.viewed', 'product.viewed']); +}); + +test('product observation URL excludes query parameters and fragments', async () => { + const calls = []; + let initialize; + runBridge({ + window: { location: { href: 'http://localhost/product.html?email=private@example.com#secret' } }, + document: { + querySelector: () => productElement({ + name: 'Shirt', reference: 'magento:store-one:product:42', sku: 'TS-42', source: 'magento' + }), + querySelectorAll: () => [], + addEventListener: () => {} + }, + console, Promise, URL, setTimeout, + require: (_deps, callback) => callback({ initialize: async () => {}, + track: async (action, params) => { calls.push([action, params]); return { failed: false }; } }), + define: (_deps, factory) => { initialize = factory(); } + }); + + initialize({ businessId: 'public-business', apiRoot: 'http://api.lvh.me:3200/v1' }); + await new Promise(setImmediate); + const productCall = calls.find(([action]) => action === 'product.viewed'); + assert.equal(productCall[1].url, 'http://localhost/product.html'); +}); + +test('accepts the explicit production API root', async () => { + let initialize; + let loaded = false; + runBridge({ + window: {}, + document: { + querySelector: () => productElement({ + name: 'Production shirt', reference: 'magento:store-one:product:42', sku: 'PROD-42', source: 'magento' + }), + querySelectorAll: () => [], + addEventListener: () => {} + }, + console, + Promise, + URL, + setTimeout, + require: (_deps, callback) => { + loaded = true; + callback({ initialize: async () => {}, track: async () => ({ failed: false }) }); + }, + define: (_deps, factory) => { initialize = factory(); } + }); + + initialize({ businessId: 'public-business', apiRoot: 'https://api.hellotext.com/v1' }); + await new Promise(setImmediate); + assert.equal(loaded, true); +}); + +test('rejects the host-only Rails URL because API routes require the api subdomain', async () => { + let initialize; + let loaded = false; + runBridge({ + window: {}, + document: { querySelector: () => null, querySelectorAll: () => [], addEventListener: () => {} }, + console, + Promise, + URL, + setTimeout, + require: (_deps, callback) => { loaded = true; callback({ initialize: async () => {}, track: async () => ({ failed: false }) }); }, + define: (_deps, factory) => { initialize = factory(); } + }); + + initialize({ businessId: 'public-business', apiRoot: 'http://localhost:3200/v1' }); + await new Promise(setImmediate); + assert.equal(loaded, false); +}); + +test('tracks a selected configurable child once after Magento updates its hidden input', async () => { + const calls = []; + let initialize; + let selected = ''; + let onChange; + let onDirectChange; + const sdk = { + initialize: async () => {}, + track: async (action, params) => { if (action === 'product.viewed') { calls.push(params.object_parameters); } return { failed: false }; } + }; + runBridge({ + window: {}, + document: { + querySelector: (selector) => selector === '[data-hellotext-product]' + ? productElement( + { name: 'Parent', reference: 'magento:store-one:product:4', sku: 'PARENT', source: 'magento' }, + { '93:4': { name: 'Red', reference: 'magento:store-one:product:2', sku: 'CHILD-RED', source: 'magento' } } + ) + : null, + querySelectorAll: () => [{ + name: 'super_attribute[93]', + value: selected, + addEventListener: (_event, callback) => { onDirectChange = callback; } + }], + addEventListener: (_event, callback) => { onChange = callback; } + }, + console, + Promise, + URL, + setTimeout, + require: (_deps, callback) => callback(sdk), + define: (_deps, factory) => { initialize = factory(); } + }); + + initialize({ businessId: 'public-business', apiRoot: 'http://api.lvh.me:3100/v1' }); + await new Promise(setImmediate); + selected = '4'; + onDirectChange(); + await new Promise((resolve) => setTimeout(resolve, 1)); + onChange(); + await new Promise((resolve) => setTimeout(resolve, 1)); + + assert.deepEqual(JSON.parse(JSON.stringify(calls)), [ + { name: 'Parent', reference: 'magento:store-one:product:4', sku: 'PARENT', source: 'magento' }, + { name: 'Red', reference: 'magento:store-one:product:2', sku: 'CHILD-RED', source: 'magento' } + ]); +}); + +test('does not load the SDK for an unsupported API root', async () => { + let initialize; + let loaded = false; + runBridge({ + window: {}, + document: { + querySelector: () => { throw new Error('Must not read product'); }, + querySelectorAll: () => [] + }, + console, + Promise, + URL, + setTimeout, + require: () => { loaded = true; }, + define: (_deps, factory) => { initialize = factory(); } + }); + + for (const apiRoot of [ + 'https://api.hellotext.com./v1', + 'http://user@api.lvh.me:3200/v1', + 'http://user:pass@api.lvh.me:3200/v1', + 'http://api.lvh.me:3200/v1?redirect=production', + 'http://api.lvh.me:3200/v1#fragment', + 'http://api.lvh.me:3201/v1', + 'http://api.lvh.me.:3200/v1', + 'http://api.lvh.me:3200/v1//' + ]) { + initialize({ businessId: 'public-business', apiRoot }); + } + await new Promise(setImmediate); + assert.equal(loaded, false); +}); + +test('allows a later change to retry an SDK-rejected product event', async () => { + const calls = []; + let initialize; + let onChange; + runBridge({ + window: {}, + document: { + querySelector: () => productElement({ + name: 'Test shirt', reference: 'magento:store-one:product:42', sku: 'TS-42', source: 'magento' + }), + querySelectorAll: () => [], + addEventListener: (_event, callback) => { onChange = callback; } + }, + console: { warn: () => {} }, + Promise, + URL, + setTimeout, + require: (_deps, callback) => callback({ + initialize: async () => {}, + track: async (action) => { + if (action === 'page.viewed') { return { failed: false }; } + calls.push('track'); + return { failed: calls.length === 1, data: 'temporary failure' }; + } + }), + define: (_deps, factory) => { initialize = factory(); } + }); + + initialize({ businessId: 'public-business', apiRoot: 'http://api.lvh.me:3100/v1' }); + await new Promise(setImmediate); + onChange(); + await new Promise((resolve) => setTimeout(resolve, 1)); + assert.deepEqual(calls, ['track', 'track']); +}); + +test('contains a synchronous SDK initialization failure and releases the page lock', async () => { + let initialize; + const warnings = []; + const window = {}; + runBridge({ + window, + document: { + querySelector: () => { throw new Error('Must not read product'); }, + querySelectorAll: () => [] + }, + console: { warn: (_message, error) => { warnings.push(error.message); } }, + Promise, + URL, + setTimeout, + require: (_deps, callback) => callback({ + initialize: () => { throw new Error('offline'); } + }), + define: (_deps, factory) => { initialize = factory(); } + }); + + initialize({ businessId: 'public-business', apiRoot: 'http://api.lvh.me:3100/v1' }); + await new Promise(setImmediate); + assert.deepEqual(warnings, ['offline']); + assert.equal(window.hellotextMagentoStarted, false); +}); + +for (const businessId of [undefined, 'public-business', 'other-business']) { + test(`reuses a global SDK with the store configuration after ${businessId || 'no'} initialization`, async () => { + const calls = []; + let initialize; + const sdk = { + business: businessId ? { id: businessId } : undefined, + initialize: async (id, options) => { + calls.push(['initialize', id, options]); + sdk.session = anonymousSession; + }, + track: async (action) => { calls.push(['track', action]); } + }; + runBridge({ + window: { Hellotext: sdk }, + document: { querySelector: () => null, querySelectorAll: () => [] }, + console: { warn: () => { calls.push(['warn']); } }, + Promise, + URL, + setTimeout, + require: () => { throw new Error('Must not load a duplicate SDK'); }, + define: (_deps, factory) => { initialize = factory(); } + }); + + initialize({ businessId: 'public-business', apiRoot: 'http://api.lvh.me:3100/v1' }); + await new Promise(setImmediate); + assert.equal(calls[0][0], 'initialize'); + assert.equal(calls[0][1], 'public-business'); + assert.equal(calls[0][2].apiRoot, 'http://api.lvh.me:3100/v1'); + assert.deepEqual(calls.slice(1), [['track', 'page.viewed']]); + }); +} + +test('tracks through an already initialized AMD SDK using the store configuration', async () => { + let initialize; + const calls = []; + runBridge({ + window: {}, + document: { querySelector: () => null, querySelectorAll: () => [] }, + console: { warn: () => { calls.push(['warn']); } }, + Promise, + URL, + setTimeout, + require: (_deps, callback) => callback({ + business: { id: 'public-business' }, + initialize: async (id, options) => { calls.push(['initialize', id, options]); }, + track: async (action) => { calls.push(['track', action]); } + }), + define: (_deps, factory) => { initialize = factory(); } + }); + + initialize({ businessId: 'public-business', apiRoot: 'http://api.lvh.me:3100/v1' }); + await new Promise(setImmediate); + assert.equal(calls[0][0], 'initialize'); + assert.equal(calls[0][1], 'public-business'); + assert.equal(calls[0][2].apiRoot, 'http://api.lvh.me:3100/v1'); + assert.deepEqual(calls.slice(1), [['track', 'page.viewed']]); +}); + +test('reports a success-page order by its canonical reference only, once per order', async () => { + const run = async (reference, storage) => { + const calls = []; + let initialize; + runBridge({ + window: { sessionStorage: storage }, + document: { + querySelector: (selector) => selector === '[data-hellotext-order]' + ? { getAttribute: () => reference } + : null, + querySelectorAll: () => [], + addEventListener: () => {} + }, + console, Promise, URL, setTimeout, + require: (_deps, callback) => callback({ + initialize: async () => {}, + identify: async () => ({ failed: false }), + track: async (action, payload) => { calls.push([action, payload]); return { failed: false }; } + }), + define: (_deps, factory) => { initialize = factory(); } + }); + initialize({ businessId: 'public-business', apiRoot: 'http://api.lvh.me:3200/v1' }); + await new Promise(setImmediate); + return calls.filter(([action]) => action === 'order.placed'); + }; + const values = { [`hellotext-magento-cart:public-business:${anonymousSession}`]: '[]' }; + const storage = { + getItem: (key) => values[key] || null, + setItem: (key, value) => { values[key] = value; }, + removeItem: (key) => { delete values[key]; } + }; + + const first = await run('magento:store-one:order:99', storage); + assert.deepEqual(JSON.parse(JSON.stringify(first)), + [['order.placed', { object_parameters: { reference: 'magento:store-one:order:99', source: 'magento' } }]]); + // The purchased cart's baseline is dropped instead of reporting its lines as removed. + assert.equal(values[`hellotext-magento-cart:public-business:${anonymousSession}`], undefined); + assert.equal((await run('magento:store-one:order:99', storage)).length, 0); + assert.equal((await run('magento:another-store:order:99', storage)).length, 0); + assert.equal((await run('magento:store-one:order:0', storage)).length, 0); +}); + +test('reports checkout started once for a non-empty valid quote and retries rejected events', async () => { + const values = {}; + const storage = { + getItem: (key) => values[key] || null, + setItem: (key, value) => { values[key] = value; } + }; + const item = { + quantity: 1, + price: { amount: 25, currency: 'USD' }, + product: { name: 'Shirt', reference: 'magento:store-one:product:42', sku: 'TS-42', source: 'magento' } + }; + const run = async (failed) => { + const calls = []; + let initialize; + runBridge({ + window: { sessionStorage: storage }, + document: { querySelector: () => null, querySelectorAll: () => [], addEventListener: () => {} }, + console, Promise, URL, setTimeout, + require: (_deps, callback) => callback({ + initialize: async () => {}, + track: async (action, payload) => { calls.push([action, payload]); return { failed: action === 'checkout.started' && failed }; } + }), + define: (_deps, factory) => { initialize = factory(); } + }, null, { checkout_reference: 'magento:store-one:checkout:17', items: [item] }); + initialize({ businessId: 'public-business', apiRoot: 'http://api.lvh.me:3200/v1', checkoutStarted: true }); + await new Promise(setImmediate); + return calls.filter(([action]) => action === 'checkout.started'); + }; + + assert.equal((await run(true)).length, 1); + assert.equal((await run(false)).length, 1); + assert.equal((await run(false)).length, 0); + assert.equal(values[`hellotext-magento-checkout:${anonymousSession}:magento:store-one:checkout:17`], '1'); +}); + +test('does not report checkout started for an empty cart', async () => { + const calls = []; + let initialize; + runBridge({ + window: {}, + document: { querySelector: () => null, querySelectorAll: () => [], addEventListener: () => {} }, + console, Promise, URL, setTimeout, + require: (_deps, callback) => callback({ + initialize: async () => {}, + track: async (action) => { calls.push(action); return { failed: false }; } + }), + define: (_deps, factory) => { initialize = factory(); } + }, null, { checkout_reference: 'magento:store-one:checkout:17', items: [] }); + initialize({ businessId: 'public-business', apiRoot: 'http://api.lvh.me:3200/v1', checkoutStarted: true }); + await new Promise(setImmediate); + assert.equal(calls.includes('checkout.started'), false); +}); diff --git a/Test/cart-tracker.test.js b/Test/cart-tracker.test.js new file mode 100644 index 0000000..f113e08 --- /dev/null +++ b/Test/cart-tracker.test.js @@ -0,0 +1,147 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); +const vm = require('node:vm'); + +let createTracker; +vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../view/frontend/web/js/cart-tracker.js'), 'utf8'), { + define: (_deps, factory) => { createTracker = factory(); }, + console: { warn() {} }, Promise +}); +const item = (id, quantity = 1) => ({ + quantity, price: { amount: '24.99', currency: 'USD' }, + product: { reference: `magento:store-one:product:${id}`, sku: `SKU-${id}`, name: `Product ${id}`, source: 'magento' } +}); +const plain = (value) => JSON.parse(JSON.stringify(value)); + +test('initial cart is viewed, absolute increases added, decreases viewed, removals explicit', async () => { + const events = []; + const track = createTracker({ track: async (action, payload) => { + events.push([action, plain(payload)]); return { failed: false }; + } }, () => true); + await track([item(1)]); + await track([item(1)]); + await track([item(1, 3), item(2)]); + await track([item(1, 2)]); + await track([]); + await track([]); + await track([item(1)]); + assert.deepEqual(events.map(([action, params]) => [action, params.object_parameters.items.map((row) => row.quantity)]), [ + ['cart.viewed', [1]], ['cart.added', [3, 1]], ['cart.removed', [1]], + ['cart.viewed', [2]], ['cart.removed', [2]], ['cart.added', [1]] + ]); + assert.ok(events.every(([, params]) => params.object_parameters.source === 'magento')); + assert.ok(events.every(([, params]) => !('reference' in params.object_parameters))); +}); + +test('empty initial snapshots do not create empty carts', async () => { + const events = []; + const track = createTracker({ track: async (action) => { events.push(action); return { failed: false }; } }, () => true); + await track([]); + await track([item(1)]); + assert.deepEqual(events, ['cart.added']); +}); + +test('price-only changes update the cart without claiming a new addition', async () => { + const events = []; + const track = createTracker({ track: async (action, params) => { + events.push([action, params.object_parameters.items[0].price.amount]); return { failed: false }; + } }, () => true); + await track([item(1)]); + await track([{ ...item(1), price: { amount: '19.99', currency: 'USD' } }]); + await track([{ ...item(1), price: { amount: '19.9900', currency: 'USD' } }]); + await track([{ ...item(1), price: { amount: '29.99', currency: 'USD' } }]); + assert.deepEqual(events, [['cart.viewed', '24.99'], ['cart.viewed', '19.99'], ['cart.viewed', '29.99']]); +}); + +test('serializes rapid snapshots without incrementing or dropping the final quantity', async () => { + const quantities = []; + let inFlight = 0; + const track = createTracker({ track: async (_action, payload) => { + assert.equal(++inFlight, 1); + await new Promise(setImmediate); + quantities.push(payload.object_parameters.items[0].quantity); + inFlight--; + return { failed: false }; + } }, () => true); + await Promise.all([track([]), track([item(1)]), track([item(1, 4)]), track([item(1, 2)])]); + assert.deepEqual(quantities, [1, 4, 2]); +}); + +for (const fail of [() => ({ failed: true }), () => { throw new Error('offline'); }]) { + test('retains accepted baseline after network/rejection failure for a fresh retry', async () => { + const events = []; + const track = createTracker({ track: async (action, params) => { + events.push([action, plain(params)]); + if (events.length === 1) { return fail(); } + return { failed: false }; + } }, () => true); + await track([]); + await track([item(1)]); + await track([item(1)]); + await track([item(1)]); + assert.equal(events.length, 2); + assert.deepEqual(events[0], events[1]); + }); +} + +test('does not replay an accepted event after a later event fails', async () => { + const actions = []; + let attempts = 0; + const tracker = createTracker({ track: async (action) => { + actions.push(action); + attempts++; + return attempts === 3 ? { failed: true } : { failed: false }; + } }, () => true); + + await tracker([item(1)]); + await tracker([item(2, 2)]); + await tracker([item(2, 2)]); + + assert.deepEqual(actions, ['cart.viewed', 'cart.removed', 'cart.added', 'cart.added']); +}); + +test('does not send queued events after an authentication/session boundary', async () => { + let active = true; + const events = []; + const track = createTracker({ track: async (action) => { + events.push(action); active = false; return { failed: false }; + } }, () => active); + await Promise.all([track([item(1)]), track([item(1, 2)])]); + assert.deepEqual(events, ['cart.viewed']); +}); + +test('restores the accepted per-tab baseline after navigation and removes the last item', async () => { + const values = new Map(); + const storage = { getItem: (key) => values.get(key) || null, setItem: (key, value) => values.set(key, value) }; + const actions = []; + const sdk = { track: async (action) => { actions.push(action); return { failed: false }; } }; + await createTracker(sdk, () => true, storage, 'session-one')([item(1)]); + await createTracker(sdk, () => true, storage, 'session-one')([]); + await createTracker(sdk, () => true, storage, 'session-one')([]); + await createTracker(sdk, () => true, storage, 'session-two')([]); + assert.deepEqual(actions, ['cart.viewed', 'cart.removed']); +}); + +test('rejects malformed or duplicate items without throwing or sending partial carts', async () => { + const actions = []; + const tracker = createTracker({ track: async (action) => { actions.push(action); return { failed: false }; } }, () => true); + for (const invalid of [[{}], [item(1), item(1)], [{ ...item(1), quantity: 1.5 }], [{ ...item(1), price: { amount: 'NaN', currency: 'USD' } }]]) { + assert.equal(createTracker.validItems(invalid), false); + await tracker(invalid); + } + assert.deepEqual(actions, []); +}); + +test('corrupt or blocked optional browser storage does not break native cart tracking', async () => { + for (const storage of [ + { getItem: () => '{broken', setItem() { throw new Error('quota'); } }, + { getItem: () => '[{}]', setItem() {} } + ]) { + const actions = []; + const tracker = createTracker({ track: async (action) => { actions.push(action); return { failed: false }; } }, () => true, storage, 'key'); + await tracker([item(1)]); + assert.deepEqual(actions, ['cart.viewed']); + } +}); diff --git a/Test/cart_data.test.php b/Test/cart_data.test.php new file mode 100644 index 0000000..513c84b --- /dev/null +++ b/Test/cart_data.test.php @@ -0,0 +1,128 @@ +data[$key] ?? null; } + public function setData($key, $value) { $this->data[$key] = $value; } + public function unsetData($key) { unset($this->data[$key]); } + public function getQuote() { return $this->quote; } + } +} +namespace Magento\Customer\Model { class Session { + public bool $loggedIn = false; + public int $customerId = 42; + public function isLoggedIn() { return $this->loggedIn; } + public function getCustomerId() { return $this->customerId; } +} } +namespace Magento\Cookie\Helper { class Cookie { + public bool $denied = false; + public function isUserNotAllowSaveCookie() { return $this->denied; } +} } +namespace Magento\Framework\App\Config { interface ScopeConfigInterface { public function getValue($path, $scope = null, $id = null); public function isSetFlag($path, $scope = null, $id = null); } } +namespace Magento\Store\Model { + class ScopeInterface { public const SCOPE_STORE = 'store'; } + interface StoreManagerInterface { public function getStore(); } +} +namespace { + foreach (['Reference', 'Configuration', 'CartPayload'] as $file) { require __DIR__ . "/../Model/$file.php"; } + require __DIR__ . '/../Plugin/CartData.php'; + $checkout = new \Magento\Checkout\Model\Session(); + $customer = new \Magento\Customer\Model\Session(); + $config = new class implements \Magento\Framework\App\Config\ScopeConfigInterface { + public string $api = 'http://api.lvh.me:3200/v1'; + public bool $identity = true; + public function isSetFlag($path, $scope = null, $id = null) { return $path === 'hellotext/tracking/identity_enabled' && $this->identity; } + public function getValue($path, $scope = null, $id = null) { return match ($path) { + 'hellotext/tracking/installation_id' => 'magento-local', + 'hellotext/tracking/business_id' => 'public-business', + default => $this->api + }; } + }; + $stores = new class implements \Magento\Store\Model\StoreManagerInterface { + public function getStore() { return $this; } + public function getId() { return 1; } + public function getCurrentCurrencyCode() { return 'USD'; } + }; + $quote = new class { + public int $store = 1; + public ?int $customer = null; + public ?int $id = null; + public array $items = []; + public function getId() { return $this->id; } + public function getStoreId() { return $this->store; } + public function getCustomerId() { return $this->customer; } + public function getQuoteCurrencyCode() { return 'USD'; } + public function getAllVisibleItems() { return $this->items; } + }; + $checkout->quote = $quote; + $cookies = new \Magento\Cookie\Helper\Cookie(); + $plugin = new \Hellotext\Tracking\Plugin\CartData($checkout, $customer, $config, $stores, $cookies); + $read = fn() => $plugin->afterGetSectionData(new \Magento\Checkout\CustomerData\Cart(), ['items' => ['native-preserved']]); + $assert = function ($value) { if (!$value) { throw new \RuntimeException('Private cart assertion failed.'); } }; + $assertUnavailableCart = function () use ($read, $assert) { + $data = $read()['hellotext']; + $assert($data['enabled'] === true && $data['cart_ready'] === false); + $assert($data['items'] === [] && $data['checkout_reference'] === null); + }; + $data = $read(); + $assert($data['items'] === ['native-preserved'] && $data['hellotext']['items'] === [] && $data['hellotext']['enabled']); + $assert(!array_key_exists('session', $data['hellotext']) && !array_key_exists('anonymous', $data['hellotext'])); + $quote->id = 17; + $assert($read()['hellotext']['checkout_reference'] === 'magento:magento-local:checkout:17'); + $assert($read()['hellotext']['context']['currency'] === 'USD'); + $assert(!array_key_exists('quote_id', $read()['hellotext']) && !array_key_exists('quoteId', $read()['hellotext']['context'])); + // Cookie Restriction Mode disables tracking until consent is granted. + $cookies->denied = true; + $assert($read()['hellotext'] === ['enabled' => false]); + $cookies->denied = false; + $resumed = $read()['hellotext']; + $assert($resumed['enabled'] === true && !array_key_exists('session', $resumed)); + $quote->id = null; + $assert($read()['hellotext']['checkout_reference'] === null); + // A signed-in shopper keeps being tracked and is identified by their ID only, with their own quote. + $customer->loggedIn = true; + $signedIn = $read()['hellotext']; + $assert($signedIn['enabled'] === true && $signedIn['identity'] === ['customer_id' => '42']); + $quote->customer = 42; + $assert($read()['hellotext']['identity'] === ['customer_id' => '42']); + $config->identity = false; + $assert($read()['hellotext']['identity'] === null); + $config->identity = true; + // Another customer's quote is never reported for this visitor. + $quote->customer = 7; + $assertUnavailableCart(); + $customer->loggedIn = false; + $quote->customer = 42; + $assertUnavailableCart(); + $quote->customer = null; + $assert($read()['hellotext']['identity'] === null); + $quote->store = 2; + $assertUnavailableCart(); + $quote->store = 1; + $config->api = 'https://api.hellotext.com/v1'; + $assert($read()['hellotext']['enabled'] === true); + $config->api = 'http://api.lvh.me:3200/v1'; + $item = new class { + public bool $additional = false; + public function getProductType() { return 'simple'; } + public function getProductId() { return 7; } + public function getName() { return 'Native product'; } + public function getSku() { return 'NATIVE'; } + public function getQty() { return 2; } + public function getCalculationPrice() { return 24.99; } + public function getBuyRequest() { return $this; } + public function getData($key) { return null; } + public function getOptionByCode($code) { return $code === 'additional_options' && $this->additional; } + }; + $quote->items = [$item]; + $assert($read()['hellotext']['items'][0]['product']['reference'] === 'magento:magento-local:product:7'); + $item->additional = true; + $assertUnavailableCart(); + $quote->items = []; + $assert($checkout->data === []); + $assert(array_keys($read()['hellotext']) === ['enabled', 'context', 'items', 'cart_ready', 'checkout_reference', 'identity']); + $assert($read()['hellotext']['context'] === ['businessId' => 'public-business', 'apiRoot' => 'http://api.lvh.me:3200/v1', 'installationId' => 'magento-local', 'storeId' => '1', 'currency' => 'USD']); + echo "Private cart configuration, authentication and scope checks passed.\n"; +} diff --git a/Test/cart_payload.test.php b/Test/cart_payload.test.php new file mode 100644 index 0000000..30c44b1 --- /dev/null +++ b/Test/cart_payload.test.php @@ -0,0 +1,37 @@ + '1', 'type' => 'simple', 'name' => 'Shirt', 'sku' => 'SHIRT', 'quantity' => '2.0000', 'price' => '24.9900']; +$items = CartPayload::items([$simple], 'magento-local', '1', 'USD'); +check($items[0]['quantity'] === 2); +check($items[0]['product']['reference'] === 'magento:magento-local:product:1'); +check($items[0]['price'] === ['amount' => '24.9900', 'currency' => 'USD']); +$configurable = array_replace($simple, ['type' => 'configurable', 'id' => '4', 'quantity' => 3, 'price' => 29.99, 'child' => array_replace($simple, ['id' => '2', 'sku' => 'RED'])]); +$items = CartPayload::items([$configurable], 'magento-local', '1', 'USD'); +check($items[0]['quantity'] === 3 && $items[0]['product']['sku'] === 'RED'); +check($items[0]['product']['reference'] === 'magento:magento-local:product:2'); +check($items[0]['price']['amount'] === '29.99'); +check(CartPayload::items([], 'magento-local', '1', 'USD') === []); +$many = array_map(static fn(int $id): array => array_replace($simple, ['id' => (string) $id, 'sku' => "SKU-$id"]), range(1, 15)); +check(count(CartPayload::items($many, 'magento-local', '1', 'USD')) === 15); +foreach (['virtual', 'bundle', 'grouped', 'downloadable', 'unknown'] as $type) { rejected([array_replace($simple, ['type' => $type])]); } +foreach ([0, -1, '1.5', 'NaN', '2147483648', '1e3'] as $quantity) { rejected([array_replace($simple, ['quantity' => $quantity])]); } +foreach (['-1', 'NaN', '1e3', INF] as $price) { rejected([array_replace($simple, ['price' => $price])]); } +rejected([$simple, $simple]); +rejected([array_replace($simple, ['custom_options' => true])]); +rejected([array_replace($simple, ['type' => 'configurable'])]); +rejected([array_replace($simple, ['sku' => ''])]); +rejected([$simple], 'usd'); +check(!str_contains(json_encode($items), 'customer')); +echo "Cart mapping checks passed.\n"; diff --git a/Test/catalog-contract.test.mjs b/Test/catalog-contract.test.mjs new file mode 100644 index 0000000..751275e --- /dev/null +++ b/Test/catalog-contract.test.mjs @@ -0,0 +1,52 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import test from 'node:test' + +const root = path.resolve(import.meta.dirname, '..') +const read = (name) => fs.readFileSync(path.join(root, name), 'utf8') + +test('catalog permission is separate from delivery and never grants Magento product writes', () => { + const routes = read('etc/webapi.xml') + const acl = read('etc/acl.xml') + const catalog = routes.match(/([\s\S]*?)<\/route>/) + + assert.ok(catalog) + assert.equal(catalog[1], 'GET') + assert.match(catalog[2], /Hellotext_Tracking::catalog_read/) + assert.doesNotMatch(catalog[2], /Magento_Catalog::products|Hellotext_Tracking::delivery/) + assert.match(acl, /id="Hellotext_Tracking::catalog_read"/) + assert.doesNotMatch(routes, /Magento_Catalog::products/) + assert.doesNotMatch(routes, / { + const service = read('Api/CatalogManagementInterface.php') + const page = read('Api/Data/CatalogPageInterface.php') + const item = read('Api/Data/CatalogItemInterface.php') + + assert.match(service, /@return \\Hellotext\\Tracking\\Api\\Data\\CatalogPageInterface/) + assert.match(page, /@return \\Hellotext\\Tracking\\Api\\Data\\CatalogItemInterface\[\]/) + assert.doesNotMatch(page + item, /getCustomAttributes|getExtensionAttributes|getCost|getDescription/) +}) + +test('customer import uses a separate bounded read-only permission and narrow response fields', () => { + const routes = read('etc/webapi.xml') + const acl = read('etc/acl.xml') + const route = routes.match(/([\s\S]*?)<\/route>/) + const service = read('Model/CustomerManagement.php') + const item = read('Api/Data/CustomerItemInterface.php') + + assert.ok(route) + assert.equal(route[1], 'GET') + assert.match(route[2], /Hellotext_Tracking::customer_read/) + assert.doesNotMatch(route[2], /Magento_Customer::customer|Hellotext_Tracking::delivery|catalog_read/) + assert.match(acl, /id="Hellotext_Tracking::customer_read"/) + assert.match(service, /website_id/) + assert.match(service, /Subscriber::STATUS_SUBSCRIBED/) + assert.match(service, /Subscriber::STATUS_UNSUBSCRIBED/) + assert.match(service, /default => 'unconfirmed'/) + assert.match(service, /setPageSize\(\$limit \+ 1\)/) + assert.match(item, /getNewsletterStatus\(\): string/) + assert.doesNotMatch(item, /getPhone|getAddress|getCustomAttributes|getExtensionAttributes/) +}) diff --git a/Test/configuration.test.php b/Test/configuration.test.php new file mode 100644 index 0000000..dc1a707 --- /dev/null +++ b/Test/configuration.test.php @@ -0,0 +1,42 @@ +saved[] = [$path, $value, $scope, $scopeId]; } + public function delete($path, $scope = 'default', $scopeId = 0) { $this->deleted[] = [$path, $scope, $scopeId]; } + }; + $config = new class implements \Magento\Framework\App\Config\ReinitableConfigInterface { + public int $reinits = 0; + public function reinit() { $this->reinits++; } + }; + $cache = new class implements \Magento\Framework\App\Cache\TypeListInterface { + public array $cleaned = []; + public function cleanType($typeCode) { $this->cleaned[] = $typeCode; } + }; + $stores = new class($storeId) implements \Magento\Store\Model\StoreManagerInterface { + public function __construct(private int $id) {} + public function getStore($storeId = null) { return new class($this->id) { public function __construct(private int $id) {} public function getId() { return $this->id; } public function getWebsiteId() { return 9; } }; } + public function getStores() { return array_map(static fn (int $id) => new class($id) { public function __construct(private int $id) {} public function getId() { return $this->id; } public function getWebsiteId() { return 9; } }, [3, 4]); } + }; + $status = new class implements \Hellotext\Tracking\Api\StatusManagementInterface { + public function getStatus(): \Hellotext\Tracking\Api\Data\StatusInterface + { + return new class implements \Hellotext\Tracking\Api\Data\StatusInterface { + public function getSchemaVersion(): int { return 1; } + public function getInstallationId(): string { return ''; } + public function getStoreId(): int { return 1; } + public function getWebsiteId(): int { return 9; } + public function getStoreCodes(): array { return ['default']; } + public function getBusinessId(): string { return ''; } + public function getConfigurationValid(): bool { return true; } + public function getModuleVersion() { return null; } + public function getSdkVersion(): string { return ''; } + public function getMagentoVersion(): string { return ''; } + public function getMagentoEdition(): string { return ''; } + public function getPhpVersion(): string { return ''; } + }; + } + }; + return [new ConfigurationManagement($writer, $config, $cache, $stores, $status), $writer, $config, $cache]; + } + + function expectInput(callable $call, string $label): void + { + try { $call(); } catch (InputException) { return; } + throw new RuntimeException("Expected input rejection: $label"); + } + + $key = '2b89d85a-739c-4b5b-a644-1bdfbe36467a'; + + [$management, $writer, $config, $cache] = fixture(3); + $management->save($key, '4EPvZP3w', true); + if ($writer->saved !== [ + ['hellotext/tracking/installation_id', $key, 'websites', 9], + ['hellotext/tracking/business_id', '4EPvZP3w', 'websites', 9], + ['hellotext/tracking/identity_enabled', '1', 'websites', 9], + ]) throw new RuntimeException('Expected the full connection configuration at website scope: ' . json_encode($writer->saved)); + if (count($writer->deleted) !== 6 || $writer->deleted[0] !== ['hellotext/tracking/installation_id', 'stores', 3] || + $writer->deleted[5] !== ['hellotext/tracking/identity_enabled', 'stores', 4]) throw new RuntimeException('Expected old store-view overrides to be cleared for every website view'); + if ($config->reinits !== 1 || $cache->cleaned !== ['config', 'full_page']) throw new RuntimeException('Expected config reinit and config + FPC cleaning'); + + [$management, $writer] = fixture(3); + $management->save($key, '', false); + if ($writer->saved[1] !== ['hellotext/tracking/business_id', '', 'websites', 9]) throw new RuntimeException('Expected disconnect to clear the website business ID'); + + [$management, $writer, , $cache] = fixture(0); + expectInput(fn () => $management->save($key, '4EPvZP3w', false), 'admin/all store scope'); + if ($writer->saved !== [] || $cache->cleaned !== []) throw new RuntimeException('Rejected requests must not write'); + + [$management, $writer] = fixture(1); + expectInput(fn () => $management->save('Not A Key', '4EPvZP3w', false), 'installation format'); + expectInput(fn () => $management->save($key, 'bad id!', false), 'business format'); + expectInput(fn () => $management->save($key, '', true), 'identity without business'); + if ($writer->saved !== []) throw new RuntimeException('Rejected requests must not write'); + + echo "configuration management: ok\n"; +} diff --git a/Test/connect_link.test.php b/Test/connect_link.test.php new file mode 100644 index 0000000..79e88dc --- /dev/null +++ b/Test/connect_link.test.php @@ -0,0 +1,27 @@ + 'https://shop.example/', 'connect_code' => $code]) { + throw new RuntimeException('Expected the code check to carry no credentials'); +} + +foreach ([200 => 'linked', 204 => 'linked', 409 => 'refused', 429 => 'rate_limited', 500 => 'unreachable', 0 => 'unreachable', 302 => 'unreachable'] as $status => $outcome) { + if (ConnectLink::outcome($status) !== $outcome) throw new RuntimeException("Unexpected outcome for HTTP $status"); +} + +echo "connect link: ok\n"; diff --git a/Test/customer_management.test.php b/Test/customer_management.test.php new file mode 100644 index 0000000..b601a5f --- /dev/null +++ b/Test/customer_management.test.php @@ -0,0 +1,121 @@ +headers[$name] = $value; } + } +} +namespace Magento\Store\Model { + interface StoreManagerInterface { public function getStore($storeId = null); public function getStores(); } + class ScopeInterface { public const SCOPE_STORE = 'store'; } +} +namespace Magento\Newsletter\Model { + class Subscriber { public const STATUS_SUBSCRIBED = 1; public const STATUS_UNSUBSCRIBED = 3; } +} +namespace Magento\Customer\Model\ResourceModel\Customer { + class CollectionFactory { + public function __construct(private array $records) {} + public function create(): object { + return new class($this->records) { + private array $filters = []; + private int $limit = 0; + public function __construct(private array $records) {} + public function addFieldToSelect($fields): self { return $this; } + public function addFieldToFilter($field, $filter): self { $this->filters[$field] = $filter; return $this; } + public function setOrder($field, $direction): self { return $this; } + public function setPageSize($limit): self { $this->limit = $limit; return $this; } + public function setCurPage($page): self { return $this; } + public function getItems(): array { + $rows = array_values(array_filter($this->records, function ($row): bool { + foreach ($this->filters as $field => $filter) { + if ($field === 'website_id' && $row['website_id'] !== $filter['eq'] || + $field === 'entity_id' && $row['entity_id'] <= $filter['gt']) return false; + } + return true; + })); + usort($rows, static fn ($a, $b) => $a['entity_id'] <=> $b['entity_id']); + return array_map(static fn ($row) => new class($row) { + public function __construct(private array $row) {} + public function getId(): int { return $this->row['entity_id']; } + public function getEmail(): string { return $this->row['email']; } + public function getFirstname(): string { return $this->row['firstname']; } + public function getLastname(): string { return $this->row['lastname']; } + }, array_slice($rows, 0, $this->limit)); + } + }; + } + } +} +namespace Magento\Newsletter\Model\ResourceModel\Subscriber { + class CollectionFactory { + public array $filters = []; + public function __construct(private array $records) {} + public function create(): object { + $factory = $this; + return new class($this->records, $factory) implements \IteratorAggregate { + private array $filters = []; + public function __construct(private array $records, private CollectionFactory $factory) {} + public function addFieldToFilter($field, $filter): self { $this->filters[$field] = $filter; $this->factory->filters = $this->filters; return $this; } + public function getIterator(): \Traversable { + foreach ($this->records as $row) { + if (isset($this->filters['customer_id']) && !in_array($row['customer_id'], $this->filters['customer_id']['in'], true)) continue; + if (isset($this->filters['store_id']) && !in_array($row['store_id'], $this->filters['store_id']['in'], true)) continue; + yield new class($row) { + public function __construct(private array $row) {} + public function getCustomerId(): int { return $this->row['customer_id']; } + public function getSubscriberStatus(): int { return $this->row['status']; } + }; + } + } + }; + } + } +} +namespace { + function __($text) { return $text; } + spl_autoload_register(function (string $class): void { + $prefix = 'Hellotext\\Tracking\\'; + if (str_starts_with($class, $prefix)) require __DIR__ . '/../' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php'; + }); + + $customers = new \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory([ + ['entity_id' => 1, 'website_id' => 3, 'email' => 'one@example.com', 'firstname' => 'One', 'lastname' => 'Customer'], + ['entity_id' => 2, 'website_id' => 3, 'email' => 'two@example.com', 'firstname' => 'Two', 'lastname' => 'Customer'], + ['entity_id' => 3, 'website_id' => 3, 'email' => 'three@example.com', 'firstname' => 'Three', 'lastname' => 'Customer'], + ['entity_id' => 4, 'website_id' => 4, 'email' => 'other@example.com', 'firstname' => 'Other', 'lastname' => 'Website'], + ]); + $subscribers = new \Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory([ + ['customer_id' => 1, 'store_id' => 1, 'status' => 1], ['customer_id' => 1, 'store_id' => 2, 'status' => 3], + ['customer_id' => 2, 'store_id' => 1, 'status' => 1], ['customer_id' => 2, 'store_id' => 2, 'status' => 4], + ['customer_id' => 3, 'store_id' => 2, 'status' => 4], ['customer_id' => 4, 'store_id' => 3, 'status' => 3], + ]); + $config = new class implements \Magento\Framework\App\Config\ScopeConfigInterface { + public function getValue($path, $scopeType = 'default', $scopeCode = null) { + return str_ends_with($path, 'installation_id') ? 'magento-local' : 'Business1'; + } + }; + $stores = new class implements \Magento\Store\Model\StoreManagerInterface { + public function getStore($storeId = null) { return new class { public function getId(): int { return 1; } public function getWebsiteId(): int { return 3; } }; } + public function getStores() { return array_map(static fn (int $id) => new class($id) { public function __construct(private int $id) {} public function getId(): int { return $this->id; } public function getWebsiteId(): int { return $this->id === 3 ? 4 : 3; } }, [1, 2, 3]); } + }; + $response = new \Magento\Framework\Webapi\Rest\Response(); + $management = new \Hellotext\Tracking\Model\CustomerManagement($customers, $subscribers, $config, $stores, $response); + $page = $management->getCustomers(100); + $items = $page->getItems(); + if ($page->getStoreId() !== 1 || $page->getWebsiteId() !== 3 || count($items) !== 3 || + $items[0]->getNewsletterStatus() !== 'unsubscribed' || $items[1]->getNewsletterStatus() !== 'subscribed' || + $items[2]->getNewsletterStatus() !== 'unconfirmed' || $subscribers->filters['store_id'] !== ['in' => [1, 2]] || + !str_contains($response->headers['Cache-Control'], 'no-store')) { + throw new \RuntimeException('Website-wide customer import or newsletter precedence failed.'); + } + try { $management->getCustomers(101); } catch (\Magento\Framework\Exception\LocalizedException) { echo "Website customer scope and consent checks passed.\n"; return; } + throw new \RuntimeException('Invalid customer page limit was accepted.'); +} diff --git a/Test/docs-links.test.mjs b/Test/docs-links.test.mjs new file mode 100644 index 0000000..5dabaf9 --- /dev/null +++ b/Test/docs-links.test.mjs @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import test from 'node:test'; + +const root = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..'); + +function markdownFiles(directory) { + return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const target = path.join(directory, entry.name); + if (entry.isDirectory()) return markdownFiles(target); + return entry.isFile() && entry.name.endsWith('.md') ? [target] : []; + }); +} + +test('all local Markdown links resolve', () => { + const broken = []; + for (const file of markdownFiles(root)) { + const source = fs.readFileSync(file, 'utf8'); + for (const match of source.matchAll(/\[[^\]]+\]\(([^)]+)\)/g)) { + const target = match[1].trim().replace(/^<|>$/g, ''); + if (!target || target.startsWith('#') || /^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith('//')) continue; + const [relative] = target.split('#', 1); + const resolved = path.resolve(path.dirname(file), relative); + if (!fs.existsSync(resolved)) broken.push(`${path.relative(root, file)} -> ${target}`); + } + } + assert.deepEqual(broken, []); +}); diff --git a/Test/i18n.test.php b/Test/i18n.test.php new file mode 100644 index 0000000..7681380 --- /dev/null +++ b/Test/i18n.test.php @@ -0,0 +1,28 @@ +([^<]+)getPathname(); + if (!str_ends_with($path, '.php') || preg_match('#/(Test|dev|tmp|vendor)/#', substr($path, strlen($root)))) continue; + preg_match_all("/__\\('((?:[^'\\\\]|\\\\.)+)'/", file_get_contents($path), $m); + array_push($strings, ...$m[1]); +} + +$missing = array_values(array_diff(array_unique($strings), array_keys($translations))); +if ($missing) throw new RuntimeException("Missing es_ES translations:\n" . implode("\n", $missing)); + +echo "i18n: ok (" . count(array_unique($strings)) . " strings)\n"; diff --git a/Test/init.test.php b/Test/init.test.php new file mode 100644 index 0000000..678de99 --- /dev/null +++ b/Test/init.test.php @@ -0,0 +1,37 @@ +route; } + public function getControllerName() { return $this->controller; } + public function getActionName() { return $this->action; } +} } +namespace Magento\Framework\View\Element { class Template { + public function __construct(private \Magento\Framework\View\Element\Template\Context $context, array $data = []) {} + public function getRequest() { return $this->context; } +} } +namespace Magento\Store\Model { class ScopeInterface { public const SCOPE_STORE = 'store'; } } +namespace { + foreach (['Reference', 'Configuration'] as $name) { require __DIR__ . "/../Model/$name.php"; } + require __DIR__ . '/../Block/Init.php'; + $context = new \Magento\Framework\View\Element\Template\Context(); + $config = new class implements \Magento\Framework\App\Config\ScopeConfigInterface { + public function getValue($path, $scope = null) { return match ($path) { + 'hellotext/tracking/installation_id' => 'magento-local', + 'hellotext/tracking/business_id' => 'public-business', + default => 'http://api.lvh.me:3200/v1' + }; } + }; + $block = new \Hellotext\Tracking\Block\Init($context, $config); + foreach ([['catalog', 'product', 'view', true], ['checkout', 'cart', 'index', true], ['checkout', 'index', 'index', true], + ['checkout', 'onepage', 'saveOrder', false], ['checkout', 'onepage', 'success', true], ['multishipping', 'checkout', 'success', false]] + as [$route, $controller, $action, $expected]) { + $context->route = $route; + $context->controller = $controller; + $context->action = $action; + if ($block->hasSafeConfig() !== $expected) { throw new \RuntimeException('Checkout route guard failed.'); } + } + echo "Storefront checkout-route guards passed.\n"; +} diff --git a/Test/integration_endpoints.test.php b/Test/integration_endpoints.test.php new file mode 100644 index 0000000..c3795c2 --- /dev/null +++ b/Test/integration_endpoints.test.php @@ -0,0 +1,45 @@ + [ + 'email' => 'info@hellotext.com', + 'endpoint_url' => 'https://www.hellotext.com/oauth/magento/callback', + 'identity_link_url' => 'https://www.hellotext.com/magento/connect', + 'resource' => ['Magento_Backend::admin'], +], 'Other' => ['endpoint_url' => 'https://other.example/callback']]; + +if (IntegrationEndpoints::apply($declared, null) !== $declared) throw new RuntimeException('No override must keep production URLs'); + +$local = IntegrationEndpoints::apply($declared, [ + 'endpoint_url' => 'https://callback.magento.lvh.me:3443/oauth/magento/callback', + 'identity_link_url' => 'http://localhost:3200/magento/connect', +]); +if ($local['Hellotext']['endpoint_url'] !== 'https://callback.magento.lvh.me:3443/oauth/magento/callback' || + $local['Hellotext']['identity_link_url'] !== 'http://localhost:3200/magento/connect' || + $local['Hellotext']['resource'] !== ['Magento_Backend::admin'] || $local['Other'] !== $declared['Other']) { + throw new RuntimeException('Expected only the Hellotext URLs to be overridden'); +} + +foreach ([ + 'http://staging.example.com/oauth/magento/callback', // secrets over plain HTTP + 'https://user:pass@example.com/callback', + 'https://example.com/callback?next=https://evil.test', + 'https://example.com/callback#fragment', + 'javascript:alert(1)', + '/relative/callback', +] as $url) { + $result = IntegrationEndpoints::apply($declared, ['endpoint_url' => $url]); + if ($result['Hellotext']['endpoint_url'] !== $declared['Hellotext']['endpoint_url']) { + throw new RuntimeException("Expected unsafe override to be ignored: $url"); + } +} + +if (IntegrationEndpoints::apply(['Other' => []], ['endpoint_url' => 'https://x.test/cb']) !== ['Other' => []]) { + throw new RuntimeException('Expected no change when the Hellotext integration is not declared'); +} + +echo "integration endpoints: ok\n"; diff --git a/Test/order-history-contract.test.mjs b/Test/order-history-contract.test.mjs new file mode 100644 index 0000000..331eaf6 --- /dev/null +++ b/Test/order-history-contract.test.mjs @@ -0,0 +1,24 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import test from 'node:test' + +const root = path.resolve(import.meta.dirname, '..') +const read = (name) => fs.readFileSync(path.join(root, name), 'utf8') + +test('order reads reuse the signed delivery permission without native Sales access', () => { + const routes = read('etc/webapi.xml') + + for (const url of ['/V1/hellotext/orders', '/V1/hellotext/orders/:orderId']) { + const matches = [...routes.matchAll(/([\s\S]*?)<\/route>/g)] + .filter((match) => match[1] === url) + + assert.equal(matches.length, 1) + assert.equal(matches[0][2], 'GET') + assert.match(matches[0][3], /Hellotext_Tracking::delivery/) + assert.match(matches[0][3], /Hellotext\\Tracking\\Api\\OrderManagementInterface/) + } + + assert.doesNotMatch(routes + read('etc/integration.xml'), /Magento_Sales::/) + assert.match(read('etc/di.xml'), /for="Hellotext\\Tracking\\Api\\OrderManagementInterface" type="Hellotext\\Tracking\\Model\\OrderManagement"/) +}) diff --git a/Test/order_lifecycle_tracker.test.php b/Test/order_lifecycle_tracker.test.php new file mode 100644 index 0000000..6bfaf60 --- /dev/null +++ b/Test/order_lifecycle_tracker.test.php @@ -0,0 +1,196 @@ +headers[$name] = $value; } + public function setOption(int $option, int $value): void { $this->options[$option] = $value; } + public function setTimeout(int $timeout): void { $this->timeout = $timeout; } + public function post(string $url, string $body): void { + if ($this->fail) throw new \RuntimeException('network unavailable'); + $this->url = $url; + $this->body = $body; + } + } + class CurlFactory { + public array $clients = []; + public bool $fail = false; + public function create(): Curl { + $client = new Curl(); + $client->fail = $this->fail; + return $this->clients[] = $client; + } + } +} + +namespace Magento\Store\Model { interface ScopeInterface { public const SCOPE_STORE = 'store'; } } + +namespace Magento\Framework\App { + class Area { + public const AREA_ADMINHTML = 'adminhtml'; + public const AREA_FRONTEND = 'frontend'; + } + class State { + public ?string $area = 'adminhtml'; + public function getAreaCode(): string { + if ($this->area === null) throw new \RuntimeException('Area code is not set'); + return $this->area; + } + } +} + +namespace Magento\Framework\Event { + class Observer { public function __construct(private object $event) {} public function getEvent(): object { return $this->event; } } + interface ObserverInterface { public function execute(Observer $observer): void; } +} + +namespace { + require __DIR__ . '/../Model/Configuration.php'; + require __DIR__ . '/../Model/Reference.php'; + require __DIR__ . '/../Model/OrderLifecycleTracker.php'; + require __DIR__ . '/../Observer/TrackOrderLifecycle.php'; + + $assert = static function (bool $condition, string $message): void { + if (!$condition) throw new \RuntimeException($message); + }; + $config = new class implements \Magento\Framework\App\Config\ScopeConfigInterface { + public bool $enabled = true; + public string $api = 'http://api.lvh.me:3200/v1/'; + public string $business = 'public-business'; + public function isSetFlag(string $path, string $scope, int $scopeId): bool { return $this->enabled; } + public function getValue(string $path, ?string $scope = null, ?int $scopeId = null): string { + return match ($path) { + 'hellotext/tracking/installation_id' => 'magento-local', + 'hellotext/tracking/business_id' => $this->business, + default => $this->api, + }; + } + }; + $curls = new \Magento\Framework\HTTP\Client\CurlFactory(); + $appState = new \Magento\Framework\App\State(); + $tracker = new \Hellotext\Tracking\Model\OrderLifecycleTracker($curls, $config, $appState); + $order = new class { + public string $state = 'new'; + public int $store = 1; + public int $id = 21; + public bool $stateChanged = true; + public bool $refundChanged = false; + public float $refunded = 0; + public function getState(): string { return $this->state; } + public function getStoreId(): int { return $this->store; } + public function getEntityId(): int { return $this->id; } + public function dataHasChangedFor(string $field): bool { + return $field === 'state' ? $this->stateChanged : ($field === 'total_refunded' && $this->refundChanged); + } + public function getTotalRefunded(): float { return $this->refunded; } + public ?string $session = null; + public bool $loaded = true; + public function getData(string $key) { return $key === 'hellotext_session' ? $this->session : null; } + public function getOrigData(string $key) { return $this->loaded && $key === 'entity_id' ? $this->id : null; } + }; + + $sessions = []; + foreach ([ + 'new' => 'order.placed', 'pending_payment' => 'order.placed', 'payment_review' => 'order.placed', + 'holded' => 'order.placed', 'processing' => 'order.confirmed', 'complete' => 'order.shipped', + 'canceled' => 'order.cancelled', + ] as $state => $action) { + $order->state = $state; + $tracker->track($order); + $curl = $curls->clients[array_key_last($curls->clients)]; + $payload = json_decode((string) $curl->body, true, flags: JSON_THROW_ON_ERROR); + $assert($payload['action'] === $action, "Unexpected action for {$state}"); + $assert($payload['object_parameters'] === ['reference' => 'magento:magento-local:order:21', 'source' => 'magento'], "Unexpected payload for {$state}"); + $assert(preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $payload['session']) === 1, 'Lifecycle tracking session must be a deterministic UUID v5.'); + $sessions[] = $payload['session']; + $assert($curl->url === 'http://api.lvh.me:3200/v1/track/events', 'Tracking endpoint was unsafe or malformed.'); + $assert($curl->headers === ['Authorization' => 'Bearer public-business', 'Content-Type' => 'application/json'], 'Tracking headers changed.'); + $assert($curl->timeout === 2, 'Tracking request must have a short total timeout.'); + } + $assert(count(array_unique($sessions)) === 1, 'One order must reuse one server tracking session across lifecycle changes.'); + $order->session = '123e4567-e89b-42d3-a456-426614174000'; + $tracker->track($order); + $placed = json_decode((string) $curls->clients[array_key_last($curls->clients)]->body, true, flags: JSON_THROW_ON_ERROR); + $assert($placed['session'] === $order->session, 'An order placed from the storefront must reuse its placing session.'); + $order->session = null; + + $before = count($curls->clients); + foreach (['closed', 'pending', 'fraud'] as $state) { + $order->state = $state; + $tracker->track($order); + } + $assert(count($curls->clients) === $before, 'Unsupported states, including closed, must not emit lifecycle events.'); + + $config->business = ''; + $order->state = 'processing'; + $tracker->track($order); + $assert(count($curls->clients) === $before, 'A store without a connected business must not call the API.'); + $config->business = 'public-business'; + $config->api = 'https://example.test/v1'; + $tracker->track($order); + $assert(count($curls->clients) === $before, 'An unsafe API root must not be called.'); + $config->api = 'http://api.lvh.me:3200/v1'; + $curls->fail = true; + $tracker->track($order); + $assert(count($curls->clients) === $before + 1, 'A network failure must be contained after one best-effort request.'); + + $curls->fail = false; + $event = new class($order) { public function __construct(private object $order) {} public function getOrder(): object { return $this->order; } }; + (new \Hellotext\Tracking\Observer\TrackOrderLifecycle($tracker))->execute(new \Magento\Framework\Event\Observer($event)); + $assert(count($curls->clients) === $before + 2, 'The commit observer did not delegate to lifecycle tracking.'); + $order->stateChanged = false; + (new \Hellotext\Tracking\Observer\TrackOrderLifecycle($tracker))->execute(new \Magento\Framework\Event\Observer($event)); + $assert(count($curls->clients) === $before + 2, 'An unchanged order state must not call the tracking API again.'); + $order->refunded = 10; + $order->refundChanged = true; + (new \Hellotext\Tracking\Observer\TrackOrderLifecycle($tracker))->execute(new \Magento\Framework\Event\Observer($event)); + $refund = json_decode((string) $curls->clients[array_key_last($curls->clients)]->body, true, flags: JSON_THROW_ON_ERROR); + $assert($refund['action'] === 'refund.received', 'A native refund must use the shared refund action.'); + $assert($refund['object_parameters'] === ['reference' => 'magento:magento-local:refund:21', 'source' => 'magento'], 'A native refund must use its canonical reference only.'); + $assert($refund['session'] === $sessions[0], 'A refund must reuse its order session.'); + $assert(count($curls->clients) === $before + 3, 'A changed refunded total must call the tracking API.'); + // Frontend placement relies on the success page; API and Admin requests report through the observer. + $order->refundChanged = false; + $order->stateChanged = true; + $order->loaded = false; + $count = count($curls->clients); + foreach (['frontend', null] as $area) { + $appState->area = $area; + $tracker->track($order); + } + $assert(count($curls->clients) === $count, 'Frontend placement and an unset area must remain suppressed.'); + foreach (['webapi_rest', 'webapi_soap', 'graphql', 'adminhtml'] as $area) { + $appState->area = $area; + foreach (['new' => 'order.placed', 'processing' => 'order.confirmed'] as $state => $action) { + $order->state = $state; + $tracker->track($order); + $assert(count($curls->clients) === ++$count, "A new {$area} order in {$state} must report exactly one event."); + $payload = json_decode((string) $curls->clients[array_key_last($curls->clients)]->body, true, flags: JSON_THROW_ON_ERROR); + $assert($payload['action'] === $action, "Unexpected action for a new {$area} order in {$state}."); + $assert($payload['session'] === $sessions[0], "Session handling changed for a new {$area} order."); + } + } + $order->loaded = true; + $appState->area = 'frontend'; + $tracker->track($order); + $assert(count($curls->clients) === $count + 1, 'A later change in any area must be reported.'); + + $globalEvents = file_get_contents(__DIR__ . '/../etc/events.xml'); + $frontendEvents = file_get_contents(__DIR__ . '/../etc/frontend/events.xml'); + $assert(str_contains($globalEvents, 'sales_order_save_commit_after'), 'Order lifecycle observer must be registered globally for Admin and API changes.'); + $assert(!str_contains($frontendEvents, 'sales_order_save_commit_after'), 'Order lifecycle observer must not be limited to storefront requests.'); + echo "Order lifecycle observer checks passed.\n"; +} diff --git a/Test/order_management.test.php b/Test/order_management.test.php new file mode 100644 index 0000000..e168595 --- /dev/null +++ b/Test/order_management.test.php @@ -0,0 +1,256 @@ +headers[$name] = $value; } + } +} +namespace Magento\Store\Model { + interface StoreManagerInterface { public function getStore($storeId = null); public function getStores(); } + class ScopeInterface { public const SCOPE_STORE = 'store'; } +} +namespace Psr\Log { + interface LoggerInterface { public function warning($message, array $context = []); } +} +namespace Magento\Sales\Model\ResourceModel\Order { + class CollectionFactory { + public array $queries = []; + public function __construct(public array $records) {} + public function create(): object { + $collection = new class($this->records) { + public array $filters = []; + public int $size = 0; + private string $field = 'entity_id'; + private string $direction = 'ASC'; + public function __construct(private array $records) {} + public function addFieldToFilter($field, $filter): self { $this->filters[$field] = $filter; return $this; } + public function setOrder($field, $direction): self { $this->field = $field; $this->direction = $direction; return $this; } + public function setPageSize($size): self { $this->size = $size; return $this; } + public function setCurPage($page): self { if ($page !== 1) throw new \RuntimeException('Expected cursor paging'); return $this; } + public function getItems(): array { + $result = array_filter($this->records, function ($order): bool { + foreach ($this->filters as $field => $filter) { + $value = $order->data[$field]; + foreach ($filter as $operator => $expected) { + if ($operator === 'eq' && $value !== $expected || $operator === 'in' && !in_array($value, $expected, true) || $operator === 'gt' && $value <= $expected || $operator === 'lt' && $value >= $expected ) return false; + } + } + return true; + }); + usort($result, fn ($left, $right) => $this->direction === 'ASC' ? $left->data[$this->field] <=> $right->data[$this->field] : $right->data[$this->field] <=> $left->data[$this->field]); + return array_slice($result, 0, $this->size); + } + }; + $this->queries[] = $collection; + return $collection; + } + } +} +namespace { + function __($text) { return $text; } + spl_autoload_register(function (string $class): void { + $prefix = 'Hellotext\\Tracking\\'; + if (str_starts_with($class, $prefix)) require __DIR__ . '/../' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php'; + }); + + use Hellotext\Tracking\Model\OrderManagement; + use Magento\Framework\Exception\LocalizedException; + use Magento\Framework\Exception\NoSuchEntityException; + + final class HistoryOrder { + public function __construct(public array $data, private bool $virtual = false) {} + public function getStoreId(): int { return $this->data['store_id']; } + public function getEntityId(): int { return $this->data['entity_id']; } + public function getCreatedAt(): string { return $this->data['created_at']; } + public function getUpdatedAt(): string { return $this->data['updated_at'] ?? $this->data['created_at']; } + public function getState(): string { return $this->data['state'] ?? 'processing'; } + public function getStatus(): string { return $this->data['status'] ?? 'custom_processing'; } + public function getTotalRefunded(): ?string { return $this->data['refunded_total'] ?? null; } + public function getIsVirtual(): bool { return $this->virtual; } + public function getOrderCurrencyCode(): string { return 'USD'; } + public function getAllVisibleItems(): array { + if (isset($this->data['items'])) return $this->data['items']; + return [new class { + public function getProductType(): string { return 'simple'; } + public function getIsVirtual(): bool { return false; } + public function getProductId(): int { return 307; } + public function getName(): string { return 'Shirt'; } + public function getSku(): string { return 'SHIRT-1'; } + public function getQtyOrdered(): string { return '2.000'; } + public function getPrice(): string { return '29.990000'; } + }]; + } + public function getIncrementId(): string { return $this->data['increment_id'] ?? '000' . $this->getEntityId(); } + public function getCustomerId(): int { return 42; } + public function getCustomerFirstname(): string { return 'PrivateFirstName'; } + public function getCustomerLastname(): string { return 'PrivateLastName'; } + public function getGrandTotal(): string { return '65.00'; } + public function getShippingMethod(): string { return 'flatrate_flatrate'; } + public function getPayment(): ?object { return null; } + public function getData($key) { return $this->data[$key] ?? null; } + } + + function order(int $id, int $store = 1, string $created = '2020-01-01 00:00:00', bool $virtual = false, array $extra = []): HistoryOrder { + return new HistoryOrder(array_merge(['entity_id' => $id, 'store_id' => $store, 'created_at' => $created], $extra), $virtual); + } + + function largeItems(string $text): array { + $item = new class($text) { + public function __construct(private string $text) {} + public function getProductType(): string { return 'simple'; } + public function getIsVirtual(): bool { return false; } + public function getProductId(): int { return 307; } + public function getName(): string { return $this->text; } + public function getSku(): string { return $this->text; } + public function getQtyOrdered(): string { return '1'; } + public function getPrice(): string { return '1.00'; } + }; + return array_fill(0, 500, $item); + } + + function fixture(array $records, int $store = 1, string $installation = 'magento-local', string $business = 'Business1'): array { + $factory = new \Magento\Sales\Model\ResourceModel\Order\CollectionFactory($records); + $config = new class($installation, $business) implements \Magento\Framework\App\Config\ScopeConfigInterface { + public array $reads = []; + public function __construct(private string $installation, private string $business) {} + public function getValue($path, $scopeType = 'default', $scopeCode = null) { + $this->reads[] = [$path, $scopeType, $scopeCode]; + return str_ends_with($path, 'installation_id') ? $this->installation : $this->business; + } + }; + $stores = new class($store) implements \Magento\Store\Model\StoreManagerInterface { + public function __construct(private int $id) {} + public function getStore($storeId = null) { return new class($this->id) { public function __construct(private int $id) {} public function getId() { return $this->id; } public function getWebsiteId() { return 3; } }; } + public function getStores() { return array_map(static fn (int $id) => new class($id) { public function __construct(private int $id) {} public function getId() { return $this->id; } public function getWebsiteId() { return $this->id === 3 ? 4 : 3; } }, [1, 2, 3]); } + }; + $response = new \Magento\Framework\Webapi\Rest\Response(); + $logger = new class implements \Psr\Log\LoggerInterface { + public array $messages = []; + public function warning($message, array $context = []) { $this->messages[] = [$message, $context]; } + }; + return [new OrderManagement($factory, $config, $stores, $response, $logger), $factory, $response, $logger, $config]; + } + + function expectException(callable $operation, string $type): void { + try { $operation(); } catch (\Throwable $error) { + if ($error instanceof $type) return; + throw $error; + } + throw new \RuntimeException('Expected exception: ' . $type); + } + + // Assert the explicit DTO contract, including nested objects and required + // nullable descriptors. Real Magento REST serialization remains its own gate. + function wire(object $object, string $interface): array { + $result = []; + foreach ((new \ReflectionClass($interface))->getMethods() as $method) { + $doc = $method->getDocComment(); + if (!preg_match('/@return\s+(\S+)/', $doc, $match)) throw new \RuntimeException('Missing serializer return descriptor'); + $type = $match[1]; + $value = $object->{$method->name}(); + if ($value === null && str_contains($type, 'null')) continue; + if (is_object($value)) $value = wire($value, $type); + if (is_array($value)) $value = array_map(fn ($item) => is_object($item) ? wire($item, substr($type, 0, -2)) : $item, $value); + $key = strtolower(preg_replace('/(?name, 3))); + $result[$key] = $value; + } + return $result; + } + + $cutoff = '2026-10-03 00:00:00'; + [$manager, $factory, $response, , $config] = fixture([ + order(4, 1, $cutoff), order(2, 2), order(3), order(1), order(5, 1, '2026-10-04 00:00:00'), + ]); + $page = $manager->getOrders($cutoff, 1); + $data = wire($page, \Hellotext\Tracking\Api\Data\OrderPageInterface::class); + if ($data['schema_version'] !== 1 || $data['store_id'] !== 1 || $data['website_id'] !== 3 || $data['business_id'] !== 'Business1' || + $data['installation_id'] !== 'magento-local' || $data['next_cursor'] !== 1 || $data['has_more'] !== true || count($data['items']) !== 1) throw new \RuntimeException('Invalid scoped history envelope'); + $snapshot = $data['items'][0]; + if ($snapshot['order_id'] !== 1 || $snapshot['reference'] !== 'magento:magento-local:order:1' || $snapshot['state'] !== 'processing' || + $snapshot['status'] !== 'custom_processing' || $snapshot['created_at'] !== '2020-01-01 00:00:00' || $snapshot['session'] !== null || + $snapshot['payment_method'] !== null || $snapshot['refunded_total'] !== '0' || isset($snapshot['customer_email']) || + $snapshot['items'][0]['price']['amount'] !== '29.990000' || $snapshot['items'][0]['product']['reference'] !== 'magento:magento-local:product:307') throw new \RuntimeException('Snapshot DTO lost canonical mapping or nullable fields'); + if ($factory->queries[0]->size !== 2 || $factory->queries[0]->filters['store_id'] !== ['in' => [1, 2]] || + !in_array(['hellotext/tracking/business_id', 'store', 1], $config->reads, true) || !str_contains($response->headers['Cache-Control'], 'no-store')) throw new \RuntimeException('Scope, lookahead or cache boundary failed'); + + $page = $manager->getOrders($cutoff, 1, 1); + if (!$page->getHasMore() || $page->getNextCursor() !== 2 || $page->getItems()[0]->getOrderId() !== 2) throw new \RuntimeException('Website-wide history cursor failed'); + $page = $manager->getOrders($cutoff, 1, 2); + if ($page->getHasMore() || $page->getNextCursor() !== 3 || $page->getItems()[0]->getOrderId() !== 3) throw new \RuntimeException('Cursor or exclusive cutoff failed'); + $page = $manager->getOrders($cutoff, 100, 3); + if ($page->getItems() !== [] || $page->getHasMore() || $page->getNextCursor() !== 3) throw new \RuntimeException('Empty terminal cursor failed'); + + [$manager, , , $logger] = fixture([order(1, virtual: true), order(2, virtual: true), order(3)]); + $page = $manager->getOrders($cutoff, 2); + if ($page->getItems() !== [] || !$page->getHasMore() || $page->getNextCursor() !== 2 || count($logger->messages) !== 2) throw new \RuntimeException('Unsupported page did not advance'); + $page = $manager->getOrders($cutoff, 2, $page->getNextCursor()); + if ($page->getItems()[0]->getOrderId() !== 3 || $page->getHasMore()) throw new \RuntimeException('Unsupported orders trapped later history'); + if (str_contains(json_encode($logger->messages), 'Private') || $logger->messages[0][1] !== ['order_id' => 1, 'reason' => 'unsupported_virtual_order']) throw new \RuntimeException('Unsupported diagnostics contain private data'); + + [$unsupported] = fixture([order(7, virtual: true)]); + $page = $unsupported->getOrders($cutoff); + if ($page->getItems() !== [] || $page->getHasMore() || $page->getNextCursor() !== 7) throw new \RuntimeException('Unsupported terminal page lost scanned cursor'); + + foreach ([['2026-02-30 00:00:00', 50, 0], ['2026-10-03T00:00:00Z', 50, 0], ['', 50, 0], [$cutoff, 0, 0], [$cutoff, 101, 0], [$cutoff, 50, -1]] as $arguments) { + expectException(fn () => $manager->getOrders(...$arguments), LocalizedException::class); + } + foreach ([[0, 'magento-local', 'Business1'], [1, 'Invalid Key', 'Business1'], [1, 'magento-local', '']] as $scope) { + [$invalid, $queries, $response] = fixture([], ...$scope); + expectException(fn () => $invalid->getOrders($cutoff), LocalizedException::class); + if ($queries->queries !== [] || !str_contains($response->headers['Cache-Control'], 'no-store')) throw new \RuntimeException('Invalid configuration queried orders or became cacheable'); + } + + [$manager] = fixture([order(1), order(2, 2), order(99, 3), order(3, virtual: true), order(4, extra: ['updated_at' => '2026-02-30 00:00:00']), + order(5, extra: ['state' => 'closed', 'status' => 'closed', 'refunded_total' => '65.00']), + order(6, extra: ['increment_id' => "invalid\xFF"])]); + $page = $manager->getOrder(1); + if ($page->getHasMore() || $page->getNextCursor() !== 1 || count($page->getItems()) !== 1) throw new \RuntimeException('Single order envelope failed'); + expectException(fn () => $manager->getOrder(0), LocalizedException::class); + if ($manager->getOrder(2)->getItems()[0]->getOrderId() !== 2) throw new \RuntimeException('Single lookup excluded a sibling store-view order'); + expectException(fn () => $manager->getOrder(99), NoSuchEntityException::class); + expectException(fn () => $manager->getOrder(99), NoSuchEntityException::class); + expectException(fn () => $manager->getOrder(3), LocalizedException::class); + expectException(fn () => $manager->getOrder(4), LocalizedException::class); + expectException(fn () => $manager->getOrder(6), LocalizedException::class); + $closed = $manager->getOrder(5)->getItems()[0]; + if ($closed->getState() !== 'closed' || $closed->getRefundedTotal() !== '65.00') throw new \RuntimeException('Refunded order snapshot lost native evidence'); + + // A full native page can exceed the consumer's response cap even though + // every order fits independently. Preserve each supported order on replay. + $large = largeItems(str_repeat('界', 85)); // 255 UTF-8 bytes, 510 escaped JSON bytes per field. + [$manager] = fixture([order(1, extra: ['items' => $large]), order(2, virtual: true), + order(3, extra: ['items' => $large]), order(4)]); + $page = $manager->getOrders($cutoff, 100); + $encoded = json_encode(wire($page, \Hellotext\Tracking\Api\Data\OrderPageInterface::class), JSON_THROW_ON_ERROR); + if (count($page->getItems()) !== 1 || !$page->getHasMore() || $page->getNextCursor() !== 2 || strlen($encoded) > 768 * 1024) throw new \RuntimeException('Large Unicode page did not split safely after its last consumed ID'); + $next = $manager->getOrders($cutoff, 100, $page->getNextCursor()); + if ($next->getHasMore() || $next->getNextCursor() !== 4 || array_map(fn ($item) => $item->getOrderId(), $next->getItems()) !== [3, 4]) throw new \RuntimeException('Byte limit dropped the next supported order'); + if (strlen(json_encode(wire($next, \Hellotext\Tracking\Api\Data\OrderPageInterface::class), JSON_THROW_ON_ERROR)) > 768 * 1024) throw new \RuntimeException('Continuation exceeded the JSON byte budget'); + + // One pathological order cannot fit even alone. Skip it with a fixed safe + // diagnostic and advance, rather than retrying an impossible response. + [$manager, , , $logger] = fixture([order(9, extra: ['items' => largeItems(str_repeat('é', 127))]), order(10)]); + $page = $manager->getOrders($cutoff, 1); + if ($page->getItems() !== [] || !$page->getHasMore() || $page->getNextCursor() !== 9 || + $logger->messages[0][1] !== ['order_id' => 9, 'reason' => 'unsupported_snapshot_size']) throw new \RuntimeException('An oversized single snapshot trapped the cursor'); + if ($manager->getOrders($cutoff, 1, 9)->getItems()[0]->getOrderId() !== 10) throw new \RuntimeException('Oversized snapshot blocked the next supported order'); + expectException(fn () => $manager->getOrder(9), LocalizedException::class); + if (strlen(json_encode(wire($manager->getOrder(10), \Hellotext\Tracking\Api\Data\OrderPageInterface::class), JSON_THROW_ON_ERROR)) > 768 * 1024) throw new \RuntimeException('Single lookup exceeded the JSON byte budget'); + + // Both SDK-generated UUIDs and tracked-link sessions travel with the snapshot. + $session = '123e4567-e89b-42d3-a456-426614174000'; + [$manager] = fixture([order(1, extra: ['hellotext_session' => $session]), order(2, extra: ['hellotext_session' => 'AbC123xy']), order(3)]); + $items = $manager->getOrders($cutoff)->getItems(); + if ($items[0]->toArray()['session'] !== $session || $items[1]->toArray()['session'] !== 'AbC123xy' || $items[2]->toArray()['session'] !== null) throw new \RuntimeException('Placement session was not preserved'); + + echo "Order history management checks passed.\n"; +} diff --git a/Test/order_payload.test.php b/Test/order_payload.test.php new file mode 100644 index 0000000..f57bd44 --- /dev/null +++ b/Test/order_payload.test.php @@ -0,0 +1,129 @@ +getMessage() !== $message) { + throw new RuntimeException("Expected '{$message}', got '{$exception->getMessage()}'."); + } + return; + } + throw new RuntimeException('Expected InvalidArgumentException.'); +} + +function orderFixture(array $changes = []): array +{ + return array_replace_recursive([ + 'entity_id' => 101, + 'increment_id' => '000000101', + 'quote_id' => 77, + 'store_id' => 2, + 'customer_email' => 'ada@example.test', + 'customer_firstname' => 'Ada', + 'customer_lastname' => 'Lovelace', + 'created_at' => '2026-09-22 10:30:00', + 'order_currency_code' => 'USD', + 'grand_total' => '25.00', + 'subtotal' => '20.00', + 'discount_amount' => '-2.00', + 'shipping_amount' => '3.00', + 'shipping_method' => 'flatrate_flatrate', + 'tax_amount' => '4.00', + 'is_virtual' => false, + 'payment' => ['method' => 'checkmo'], + 'items' => [[ + 'item_id' => 1, + 'product_id' => 11, + 'name' => 'Simple tee', + 'sku' => 'TEE-1', + 'product_type' => 'simple', + 'qty_ordered' => '2', + 'price' => '10.00', + ]], + ], $changes); +} + +$simple = OrderPayload::fromArray(orderFixture(), 'local_store'); +assertSameValue('order.placed', $simple['event']['action']); +assertSameValue('2026-09-22T10:30:00Z', $simple['event']['tracked_at']); +assertSameValue('25.00', $simple['event']['amount']); +assertSameValue('magento:local_store:order:101', $simple['event']['object_parameters']['reference']); +assertSameValue(2, $simple['event']['object_parameters']['items'][0]['quantity']); +assertSameValue('10.00', $simple['event']['object_parameters']['items'][0]['price']['amount']); +assertSameValue('magento:local_store:product:11', $simple['event']['object_parameters']['items'][0]['product']['reference']); +assertSameValue(false, array_key_exists('subscribe', $simple['profile'])); +assertSameValue('ada@example.test', OrderPayload::fromArray(orderFixture(['customer_email' => 'Ada@Example.TEST']), 'local_store')['profile']['email']); + +$configurable = OrderPayload::fromArray(orderFixture(['items' => [ + ['item_id' => 1, 'product_id' => 20, 'name' => 'Parent', 'sku' => 'PARENT', 'product_type' => 'configurable', 'qty_ordered' => '2', 'price' => '12.50'], + ['item_id' => 2, 'parent_item_id' => 1, 'product_id' => 21, 'name' => 'Red', 'sku' => 'PARENT-RED', 'product_type' => 'simple', 'qty_ordered' => '2', 'price' => '12.50'], +]]), 'local_store'); +assertSameValue(1, count($configurable['event']['object_parameters']['items'])); +assertSameValue('magento:local_store:product:21', $configurable['event']['object_parameters']['items'][0]['product']['reference']); +assertSameValue(2, $configurable['event']['object_parameters']['items'][0]['quantity']); +assertSameValue('12.50', $configurable['event']['object_parameters']['items'][0]['price']['amount']); + +$decimalQuantity = OrderPayload::fromArray(orderFixture(['items' => [[ + 'item_id' => 1, 'product_id' => 11, 'name' => 'Simple tee', 'sku' => 'TEE-1', 'product_type' => 'simple', 'qty_ordered' => '2.0000', 'price' => '10.00', +]]]), 'local_store'); +assertSameValue(2, $decimalQuantity['event']['object_parameters']['items'][0]['quantity']); + +$emptyParent = OrderPayload::fromArray(orderFixture(['quote_id' => null, 'items' => [[ + 'item_id' => 1, 'parent_item_id' => '', 'product_id' => 11, 'name' => 'Simple tee', 'sku' => 'TEE-1', 'product_type' => 'simple', 'qty_ordered' => '1.0000', 'price' => '10.00', +]]]), 'local_store'); +assertSameValue(null, $emptyParent['event']['object_parameters']['metadata']['magento']['quote_id']); +assertSameValue(1, count($emptyParent['event']['object_parameters']['items'])); + +assertSameValue('magento:shop_one:product:1', Reference::build('shop_one', 'product', 1)); +assertSameValue('magento:shop_two:product:1', Reference::build('shop_two', 'product', 1)); + +$free = OrderPayload::fromArray(orderFixture(['grand_total' => '0.00', 'subtotal' => '0.00', 'shipping_amount' => '0.00', 'tax_amount' => '0.00', 'discount_amount' => '0.00']), 'local_store'); +assertSameValue('0.00', $free['event']['object_parameters']['total']['amount']); +assertSameValue('deliver', $free['event']['object_parameters']['delivery']); + +assertInvalid(fn() => Reference::build('Bad', 'product', 1)); +assertInvalid(fn() => Reference::build('local_store', 'product', 0)); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['customer_email' => '']), 'local_store')); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['entity_id' => 0]), 'local_store')); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['grand_total' => '-1.00']), 'local_store')); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['grand_total' => INF]), 'local_store')); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['order_currency_code' => 'US']), 'local_store')); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['items' => [['item_id' => 1, 'product_id' => 11, 'name' => 'Simple', 'sku' => 'S', 'product_type' => 'simple', 'qty_ordered' => '1.5', 'price' => '10.00']]]), 'local_store')); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['items' => [['item_id' => 1, 'product_id' => 11, 'name' => 'Simple', 'sku' => 'S', 'product_type' => 'simple', 'qty_ordered' => ((string) PHP_INT_MAX) . '0', 'price' => '10.00']]]), 'local_store')); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['items' => [['item_id' => 1, 'product_id' => 11, 'name' => 'Bundle', 'sku' => 'B', 'product_type' => 'bundle', 'qty_ordered' => '1', 'price' => '10.00']]]), 'local_store')); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['is_virtual' => true]), 'local_store'), 'Virtual orders are unsupported until a fulfillment mapping is agreed.'); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['shipping_method' => 'pickup_in_store']), 'local_store'), 'Only the flatrate_flatrate shipping method is supported by this development order adapter.'); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['shipping_method' => 'freeshipping_freeshipping']), 'local_store'), 'Only the flatrate_flatrate shipping method is supported by this development order adapter.'); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['shipping_method' => '']), 'local_store'), 'Only the flatrate_flatrate shipping method is supported by this development order adapter.'); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['items' => [ + ['item_id' => 1, 'product_id' => 11, 'name' => 'Physical', 'sku' => 'PHYSICAL', 'product_type' => 'simple', 'qty_ordered' => '1', 'price' => '10.00'], + ['item_id' => 2, 'product_id' => 12, 'name' => 'Virtual', 'sku' => 'VIRTUAL', 'product_type' => 'virtual', 'qty_ordered' => '1', 'price' => '10.00'], +]]), 'local_store'), 'Virtual order items are unsupported until a fulfillment mapping is agreed.'); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['created_at' => '2026-02-30 10:30:00']), 'local_store')); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['items' => [['item_id' => 2, 'parent_item_id' => 1, 'product_id' => 11, 'name' => 'Orphan', 'sku' => 'O', 'product_type' => 'simple', 'qty_ordered' => '1.0000', 'price' => '10.00']]]), 'local_store')); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['items' => [ + ['item_id' => 1, 'product_id' => 20, 'name' => 'Parent', 'sku' => 'PARENT', 'product_type' => 'configurable', 'qty_ordered' => '1', 'price' => '10.00'], + ['item_id' => 2, 'parent_item_id' => 1, 'product_id' => 21, 'name' => 'Red', 'sku' => 'PARENT-RED', 'product_type' => 'simple', 'qty_ordered' => '1', 'price' => '10.00'], + ['item_id' => 3, 'parent_item_id' => 1, 'product_id' => 22, 'name' => 'Blue', 'sku' => 'PARENT-BLUE', 'product_type' => 'simple', 'qty_ordered' => '1', 'price' => '10.00'], +]]), 'local_store')); +assertInvalid(fn() => OrderPayload::fromArray(orderFixture(['items' => [ + ['item_id' => 1, 'product_id' => 11, 'name' => 'One', 'sku' => 'ONE', 'product_type' => 'simple', 'qty_ordered' => '1', 'price' => '10.00'], + ['item_id' => 2, 'product_id' => 11, 'name' => 'One', 'sku' => 'ONE', 'product_type' => 'simple', 'qty_ordered' => '1', 'price' => '10.00'], +]]), 'local_store'), 'Multiple order lines for the same canonical product are unsupported because Hellotext merges them.'); + +echo "order_payload.test.php: ok\n"; diff --git a/Test/order_snapshot_payload.test.php b/Test/order_snapshot_payload.test.php new file mode 100644 index 0000000..4f7509c --- /dev/null +++ b/Test/order_snapshot_payload.test.php @@ -0,0 +1,57 @@ +type; } + public function getIsVirtual(): bool { return $this->virtual; } + public function getProductId(): int { return 11; } + public function getName(): string { return 'Tee'; } + public function getSku(): string { return 'TEE'; } + public function getQtyOrdered(): string { return '2.000'; } + public function getPrice(): string { return '10.00'; } +} + +final class FixtureOrder +{ + public function __construct(private array $items, private bool $virtual = false) {} + public function getStoreId(): int { return 1; } + public function getEntityId(): int { return 21; } + public function getIsVirtual(): bool { return $this->virtual; } + public function getOrderCurrencyCode(): string { return 'USD'; } + public function getAllVisibleItems(): array { return $this->items; } + public function getIncrementId(): string { return '000021'; } + public function getCustomerId(): int { return 0; } + public function getCustomerFirstname(): string { return 'Guest'; } + public function getCustomerLastname(): string { return 'Customer'; } + public function getGrandTotal(): string { return '20.00'; } + public function getShippingMethod(): string { return 'flatrate_flatrate'; } + public function getPayment(): ?object { return null; } +} + +function expectMappingFailure(FixtureOrder $order, string $reason): void +{ + try { + OrderSnapshotPayload::fromOrder($order, 'magento-local', null); + } catch (InvalidArgumentException $error) { + if ($error->getMessage() === $reason) return; + throw $error; + } + throw new RuntimeException('Expected mapping failure: ' . $reason); +} + +$payload = OrderSnapshotPayload::fromOrder(new FixtureOrder([new FixtureItem()]), 'magento-local', '123e4567-e89b-42d3-a456-426614174000'); +if ($payload['reference'] !== 'magento:magento-local:order:21' || $payload['session'] === null || $payload['delivery'] !== 'deliver' || + $payload['items'][0]['product']['reference'] !== 'magento:magento-local:product:11' || $payload['customer_id'] !== null || isset($payload['customer_email'])) { + throw new RuntimeException('Order snapshot payload mapping failed.'); +} +expectMappingFailure(new FixtureOrder([new FixtureItem(false, 'bundle')]), 'unsupported_item_type:bundle'); +expectMappingFailure(new FixtureOrder([new FixtureItem()], true), 'unsupported_virtual_order'); +expectMappingFailure(new FixtureOrder([new FixtureItem(), new FixtureItem(true)]), 'unsupported_virtual_item'); +echo "Order snapshot payload checks passed.\n"; diff --git a/Test/product.test.php b/Test/product.test.php new file mode 100644 index 0000000..4d46f5d --- /dev/null +++ b/Test/product.test.php @@ -0,0 +1,47 @@ +id; } + public function getStatus() { return $this->status; } + public function getData($key) { return $this->id; } + } + $attribute = new class { + public function getProductAttribute() { return $this; } + public function getAttributeId() { return 93; } + public function getAttributeCode() { return 'color'; } + }; + $product = new class($attribute) { + public function __construct(private object $attribute) {} + public function getTypeId() { return 'configurable'; } + public function getTypeInstance() { return $this; } + public function getConfigurableAttributes($product) { return [$this->attribute]; } + public function getUsedProducts($product) { return [new Variant(1, 1), new Variant(2, 2)]; } + }; + $block = new class($product) extends \Hellotext\Tracking\Block\Product { + public function __construct(private object $product) {} + public function getProduct() { return $this->product; } + public function getProductPayload($product = null): ?array { return ['reference' => $product->getId()]; } + }; + if ($block->getVariantPayloads() !== ['93:1' => ['reference' => 1]]) { + throw new \RuntimeException('Only enabled configurable children may be rendered.'); + } + $bundle = new class { public function getTypeId() { return 'bundle'; } }; + $real = new class extends \Hellotext\Tracking\Block\Product { public function __construct() {} }; + if ($real->getProductPayload($bundle) !== null) { + throw new \RuntimeException('Product types outside the catalog import must not be tracked.'); + } + echo "Product variant visibility checks passed.\n"; +} diff --git a/Test/reference.test.php b/Test/reference.test.php new file mode 100644 index 0000000..7aca1af --- /dev/null +++ b/Test/reference.test.php @@ -0,0 +1,26 @@ +denied; } + } +} +namespace Magento\Framework\Event { + class Observer { + public function __construct(private ?object $order) {} + public function getEvent(): object { return new class($this->order) { public function __construct(private ?object $order) {} public function getOrder() { return $this->order; } }; } + } + interface ObserverInterface { public function execute(Observer $observer); } +} +namespace { + require __DIR__ . '/../Observer/RememberOrderSession.php'; + + $cookies = new class implements \Magento\Framework\Stdlib\CookieManagerInterface { + public ?string $session = null; + public function getCookie($name) { + if ($name !== 'hello_session') throw new \RuntimeException('Unexpected cookie'); + return $this->session; + } + }; + $consent = new \Magento\Cookie\Helper\Cookie(); + $observer = new \Hellotext\Tracking\Observer\RememberOrderSession($cookies, $consent); + + foreach ([null, '', str_repeat('a', 37), 'AbC123xy', '123e4567-e89b-42d3-a456-426614174000'] as $session) { + $cookies->session = $session; + $order = new class { public array $data = []; public function setData($key, $value) { $this->data[$key] = $value; } }; + $observer->execute(new \Magento\Framework\Event\Observer($order)); + $expected = $session !== null && $session !== '' && strlen($session) <= 36 ? ['hellotext_session' => $session] : []; + if ($order->data !== $expected) throw new \RuntimeException('The SDK cookie was not kept on the order.'); + } + + $order->data = []; + $consent->denied = true; + $observer->execute(new \Magento\Framework\Event\Observer($order)); + if ($order->data !== []) throw new \RuntimeException('Cookie restrictions must prevent attribution.'); + + $consent->denied = false; + $failing = new class { public function setData($key, $value) { throw new \RuntimeException('save failed'); } }; + $observer->execute(new \Magento\Framework\Event\Observer($failing)); + $observer->execute(new \Magento\Framework\Event\Observer(null)); + + echo "Order placement session checks passed.\n"; +} diff --git a/Test/status-contract.test.mjs b/Test/status-contract.test.mjs new file mode 100644 index 0000000..6db7168 --- /dev/null +++ b/Test/status-contract.test.mjs @@ -0,0 +1,36 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import test from 'node:test'; + +const root = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..'); +const read = (file) => fs.readFileSync(path.join(root, file), 'utf8'); + +test('status is a signed, store-scoped, safe version handshake', () => { + const routes = read('etc/webapi.xml'); + const service = read('Model/StatusManagement.php'); + const data = read('Api/Data/StatusInterface.php'); + const version = read('Model/VersionInformation.php'); + const bridge = read('view/frontend/web/js/bridge.js'); + const route = routes.match(/([\s\S]*?)<\/route>/); + + assert.ok(route); + assert.equal(route[1], 'GET'); + assert.match(route[2], /Magento_Backend::store/); + assert.doesNotMatch(route[2], /Hellotext_Tracking::(?:delivery|catalog_read)|Magento_Catalog::products/); + assert.match(service, /Cache-Control.*no-store/); + assert.match(service, /Reference::build\(\$installation, 'product', 1\)/); + assert.match(service, /Configuration::isSafeApiRoot/); + for (const field of [ + 'SchemaVersion', 'InstallationId', 'StoreId', 'WebsiteId', 'StoreCodes', 'BusinessId', 'ConfigurationValid', + 'ModuleVersion', 'SdkVersion', 'MagentoVersion', 'MagentoEdition', 'PhpVersion' + ]) { + assert.match(data, new RegExp(`get${field}`)); + } + assert.match(data, /concrete DTO deliberately returns \?string/); + assert.doesNotMatch(data, /get(?:ApiRoot|Token|Secret|Customer|Order|Session)/); + const sdkVersion = version.match(/SDK_VERSION = '([^']+)'/)[1]; + // The reported SDK channel matches the unversioned CDN URL used by the bridge. + assert.equal(sdkVersion, 'latest'); + assert.match(bridge, /https:\/\/cdn\.jsdelivr\.net\/npm\/@hellotext\/hellotext\/dist\/hellotext\.min\.js/); +}); diff --git a/Test/storefront-boundary.test.js b/Test/storefront-boundary.test.js new file mode 100644 index 0000000..f1cc535 --- /dev/null +++ b/Test/storefront-boundary.test.js @@ -0,0 +1,273 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); +const vm = require('node:vm'); +const source = fs.readFileSync(path.join(__dirname, '../view/frontend/web/js/bridge.js'), 'utf8'); +const generatedSession = 'ae25b1d4-8000-4000-8000-123456789abc'; +const context = { businessId: 'public-business', apiRoot: 'http://api.lvh.me:3200/v1', installationId: 'local', storeId: '1', currency: 'USD' }; +const settle = () => new Promise(setImmediate); +let realCartTracker; +vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../view/frontend/web/js/cart-tracker.js'), 'utf8'), { + define: (_deps, factory) => { realCartTracker = factory(); }, console, Promise +}); + +function harness({ cookie = '', query = '', sections, offline = false, rejectReinitialize = false, rejectInitialData = false, productReference = 'magento:local:product:1' } = {}) { + const events = []; + const carts = []; + const subscriptions = {}; + let initialize; + let reloads = 0; + let loads = 0; + let initializations = 0; + let fresh = sections || { cart: { hellotext: { enabled: true, cart_ready: true, context, identity: null, items: [] } }, customer: {} }; + const cookies = new Map(cookie ? cookie.split('; ').map(value => value.split('=')) : []); + const document = { + get cookie() { return [...cookies].map(([name, value]) => `${name}=${value}`).join('; '); }, + set cookie(value) { const [name, content] = value.split('='); cookies.set(name, content); }, + querySelector: () => ({ getAttribute: (attribute) => JSON.stringify(attribute === 'data-hellotext-product' + ? { reference: productReference, name: 'Item', sku: 'ITEM', source: 'magento' } : {}) }), + querySelectorAll: () => [], addEventListener() {} + }; + const sdk = { + initialize: async (_business, config) => { + initializations++; + if (rejectReinitialize && initializations > 1) { throw new Error('SDK refresh unavailable'); } + assert.equal('session' in config, false); + assert.equal('autoGenerateSession' in config, false); + sdk.session = new URLSearchParams(query).get('hello_session') || cookies.get('hello_session') || generatedSession; + document.cookie = `hello_session=${sdk.session}`; + }, + identify: async (id, options) => { + cookies.set('hello_user_id', id); + cookies.set('hello_user_source', options.source); + events.push(['identify', id, options]); + return { failed: false }; + }, + forget: () => { cookies.delete('hello_user_id'); cookies.delete('hello_user_source'); }, + track: async (action) => { events.push(action); return { failed: false }; } + }; + const customerData = { + getInitCustomerData: () => rejectInitialData ? Promise.reject(new Error('initial cart unavailable')) : Promise.resolve(), + get: (name) => ({ subscribe: (fn) => { subscriptions[name] = fn; } }), + reload: async (names, force) => { + reloads++; + assert.deepEqual(Array.from(names), ['cart']); + assert.equal(force, true); + if (offline) { throw new Error('private server unavailable'); } + const data = JSON.parse(JSON.stringify(fresh)); + // Magento updates observables before resolving reload's deferred. + subscriptions.cart?.(data.cart); + return data; + } + }; + const cartTracker = () => (items) => { carts.push(items); }; + cartTracker.validItems = realCartTracker.validItems; + vm.runInNewContext(source, { + window: { location: { href: `http://localhost/product.html${query}` } }, document, + Promise, URL, setTimeout, console: { warn() {} }, + define: (_deps, factory) => { initialize = factory(customerData, cartTracker); }, + require: (_deps, callback) => { loads++; callback(sdk); } + }); + initialize(context); + return { + events, carts, document, sdk, + reloads: () => reloads, loads: () => loads, + fresh: (value) => { fresh = value; }, + setOffline: (value) => { offline = value; }, + notify: (name, value) => subscriptions[name]?.(value) + }; +} + +test('waits for fresh native private content before initialization and product/cart tracking', async () => { + const h = harness(); + assert.equal(h.loads(), 0); + await settle(); + assert.equal(h.sdk.session, generatedSession); + assert.deepEqual(h.events, ['page.viewed', 'product.viewed']); + assert.equal(h.carts.length, 1); + assert.ok(h.reloads() >= 2); + const before = h.reloads(); + h.notify('cart', { hellotext: { enabled: true, session: 'forged-cached-value' } }); + await settle(); + assert.equal(h.reloads(), before + 1); + assert.equal(h.carts.length, 2); +}); + +for (const cookie of ['hello_user_id=123', 'x=y; hello_user_source=shopify', 'hello_user_identification_hash=abc', 'hello_user_id=123; hello_user_source=shopify']) { + test(`tracks without changing existing identity cookies: ${cookie}`, async () => { + const h = harness({ cookie }); + await settle(); + assert.equal(h.loads(), 1); + assert.deepEqual(h.events, ['page.viewed', 'product.viewed']); + assert.equal(h.carts.length, 1); + assert.ok(cookie.split('; ').every(value => h.document.cookie.split('; ').includes(value))); + }); +} +for (const query of ['?hello_session=other', '?hello_session=', '?hello%5fsession=other']) { + test(`lets the SDK select the URL session ${query}`, async () => { + const h = harness({ query }); + await settle(); + assert.equal(h.loads(), 1); + assert.equal(h.sdk.session, new URLSearchParams(query).get('hello_session') || generatedSession); + assert.deepEqual(h.events, ['page.viewed', 'product.viewed']); + }); +} +for (const [name, data] of Object.entries({ + disabled: { enabled: false }, + 'missing context': { enabled: true, cart_ready: true, identity: null, items: [] }, + 'invalid identity': { enabled: true, cart_ready: true, context, identity: { customer_id: '0' }, items: [] } +})) { + test(`does not load SDK for ${name} private state`, async () => { + const h = harness({ sections: { cart: { hellotext: data } } }); + await settle(); + assert.equal(h.loads(), 0); + }); +} +for (const [name, data] of Object.entries({ + missing: null, + 'invalid items': { enabled: true, cart_ready: true, context, identity: null, items: [{}] }, + 'invalid cart readiness': { enabled: true, cart_ready: 'unknown', context, identity: null, items: [] }, + 'invalid checkout reference': { enabled: true, cart_ready: true, context, identity: null, items: [], checkout_reference: 'invalid' } +})) { + test(`keeps page and product tracking when the cart has ${name}`, async () => { + const h = harness({ sections: { cart: { hellotext: data } } }); + await settle(); + assert.equal(h.loads(), 1); + assert.deepEqual(h.events, ['page.viewed', 'product.viewed']); + assert.equal(h.carts.length, 0); + }); +} +test('a failed cart reload does not stop tracking or prevent a later refresh', async () => { + const h = harness({ offline: true }); + await settle(); + assert.equal(h.loads(), 1); + assert.deepEqual(h.events, ['page.viewed', 'product.viewed']); + assert.equal(h.carts.length, 0); + + h.setOffline(false); + h.notify('cart', {}); + await settle(); + assert.equal(h.carts.length, 1); + assert.equal(h.sdk.session, generatedSession); +}); +test('continues tracking when initial customer-data loading fails', async () => { + const h = harness({ rejectInitialData: true }); + await settle(); + assert.deepEqual(h.events, ['page.viewed', 'product.viewed']); + assert.equal(h.carts.length, 1); +}); +test('an unavailable cart does not clear the existing identity', async () => { + const h = harness({ offline: true, cookie: 'hello_user_id=42; hello_user_source=magento' }); + await settle(); + assert.deepEqual(h.events, ['page.viewed', 'product.viewed']); + assert.ok(h.document.cookie.includes('hello_user_id=42')); + assert.ok(h.document.cookie.includes('hello_user_source=magento')); +}); +test('refreshes Magento identity after login while preserving the SDK session', async () => { + const h = harness(); + await settle(); + h.fresh({ cart: { hellotext: { + enabled: true, cart_ready: true, context, + identity: { customer_id: '42' }, items: [] + } } }); + h.notify('cart', {}); + await settle(); + + assert.equal(h.sdk.session, generatedSession); + assert.ok(h.events.some((event) => Array.isArray(event) && event[0] === 'identify' && event[1] === '42')); + assert.ok(h.events.includes('page.viewed')); + assert.equal(h.events.filter((event) => event === 'product.viewed').length, 1); + assert.ok(h.carts.length >= 2); +}); +test('does not turn a temporary unbound quote during login into cart removals', async () => { + const item = { quantity: 1, price: { amount: '12.00', currency: 'USD' }, product: { + reference: 'magento:local:product:1', source: 'magento', name: 'Item', sku: 'ITEM' + } }; + const h = harness({ sections: { cart: { hellotext: { + enabled: true, cart_ready: true, context, identity: null, items: [item] + } } } }); + await settle(); + assert.equal(h.carts.length, 1); + + h.fresh({ cart: { hellotext: { + enabled: true, cart_ready: false, context, + identity: { customer_id: '42' }, items: [] + } } }); + h.notify('cart', {}); + await settle(); + + assert.equal(h.carts.length, 1); + assert.deepEqual(h.carts[0], [item]); +}); +test('contains SDK reinitialization failure after its cookie changes', async () => { + const h = harness({ rejectReinitialize: true }); + await settle(); + h.document.cookie = 'hello_session=AbC123xy'; + h.fresh({ cart: { hellotext: { + enabled: true, cart_ready: true, + context, + identity: { customer_id: '42' }, items: [] + } } }); + h.notify('cart', {}); + await settle(); + + assert.equal(h.carts.length, 1); +}); +test('keeps tracking cart snapshots when identity cookies change', async () => { + const h = harness(); + await settle(); + h.document.cookie = 'hello_user_id=other'; + h.document.cookie = 'hello_user_source=shopify'; + h.notify('cart', {}); + await settle(); + assert.equal(h.carts.length, 2); + assert.equal(h.sdk.session, generatedSession); +}); + +for (const field of ['businessId', 'apiRoot', 'installationId', 'storeId', 'currency']) { + test(`rejects stale public/private ${field} bindings before SDK load`, async () => { + const h = harness({ sections: { cart: { hellotext: { + enabled: true, cart_ready: true, identity: null, items: [], context: { ...context, [field]: 'different' } + } }, customer: {} } }); + await settle(); + assert.equal(h.loads(), 0); + assert.deepEqual(h.events, []); + }); +} + +test('lets the SDK reuse an existing session cookie', async () => { + const cookie = 'hello_session=be25b1d4-8000-4000-8000-123456789abc'; + const h = harness({ cookie }); + await settle(); + assert.equal(h.loads(), 1); + assert.equal(h.sdk.session, cookie.split('=')[1]); + assert.equal(h.document.cookie, cookie); + assert.deepEqual(h.events, ['page.viewed', 'product.viewed']); +}); + +test('allows its matching session cookie across navigation', async () => { + const h = harness({ cookie: `hello_session=${generatedSession}` }); + await settle(); + assert.equal(h.loads(), 1); + assert.deepEqual(h.events, ['page.viewed', 'product.viewed']); +}); + +for (const [reference, currency] of [ + ['magento:other:product:1', 'USD'], ['magento:local:product:1', 'EUR'] +]) { + test('skips a cart outside the product namespace or currency while tracking the page and product', async () => { + const items = [{ quantity: 1, price: { amount: '19.99', currency }, product: { reference, source: 'magento', sku: 'ITEM', name: 'Item' } }]; + const h = harness({ sections: { cart: { hellotext: { enabled: true, cart_ready: true, context, identity: null, items } }, customer: {} } }); + await settle(); + assert.equal(h.loads(), 1); + assert.deepEqual(h.events, ['page.viewed', 'product.viewed']); + assert.equal(h.carts.length, 0); + }); +} + +test('does not send a stale PDP reference belonging to another store', async () => { + const h = harness({ productReference: 'magento:other:product:1' }); + await settle(); + assert.equal(h.events.includes('product.viewed'), false); +}); diff --git a/Test/uninstall.test.php b/Test/uninstall.test.php new file mode 100644 index 0000000..a2143ff --- /dev/null +++ b/Test/uninstall.test.php @@ -0,0 +1,53 @@ +calls[] = "find:$name"; return new class { public function getId() { return 7; } }; } + public function delete($id) { $this->calls[] = "delete:$id"; return ['consumer_id' => 9]; } + }; + $oauth = new class($calls) implements \Magento\Integration\Api\OauthServiceInterface { + public function __construct(private array &$calls) {} + public function deleteConsumer($id) { $this->calls[] = "consumer:$id"; } + }; + $connection = new class($calls) { + public function __construct(private array &$calls) {} + public function delete($table, $where) { $this->calls[] = "config:$table:" . json_encode($where); } + public function dropTable($table) { $this->calls[] = "drop:$table"; } + }; + $setup = new class($connection) implements \Magento\Framework\Setup\SchemaSetupInterface { + public function __construct(private $connection) {} + public function startSetup() {} + public function endSetup() {} + public function getConnection() { return $this->connection; } + public function getTable($name) { return $name; } + }; + + (new \Hellotext\Tracking\Setup\Uninstall($integrations, $oauth)) + ->uninstall($setup, new class implements \Magento\Framework\Setup\ModuleContextInterface {}); + + $expected = ['find:Hellotext', 'delete:7', 'consumer:9', 'config:core_config_data:{"path LIKE ?":"hellotext\/%"}']; + if ($calls !== $expected) throw new RuntimeException('Unexpected uninstall steps: ' . json_encode($calls)); + + echo "uninstall: ok\n"; +} diff --git a/docs/compatibility.md b/docs/compatibility.md index 7386dd4..2d03898 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -10,7 +10,7 @@ Compatibility is a tested contract, not an assumption from a successful module i | PHP | 8.2–8.3 | | Theme | Luma | | Browser runtime | Secure context with RequireJS/AMD support | -| Hellotext.js | Latest 2.x, followed through jsDelivr | +| Hellotext.js | Latest release, followed through jsDelivr | | API root | `https://api.hellotext.com/v1` | This is the production support baseline for page, product and anonymous cart events. It does not claim support for Adobe Commerce, other Magento versions, custom themes, Varnish or alternate proxy topologies. @@ -18,7 +18,7 @@ This is the production support baseline for page, product and anonymous cart eve ## Known constraints - Hellotext.js requires a secure browser context; plain `lvh.me` HTTP is not a representative storefront runtime. -- The bridge loads the latest 2.x SDK from jsDelivr at runtime, so SDK releases reach stores without a module release. The public API the bridge uses (`business`, `session`, `identify`, `track`) must stay stable within 2.x, and jsDelivr and browsers cache the resolved file (a rollback of a bad release may need a purge). CDN availability and merchant CSP/network policy are release gates: verify the asset loads in browser Network. An approved owned asset is an alternative only after changing the bridge/CSP and revalidating it; this package does not provide one. +- The bridge loads the latest SDK from the unversioned jsDelivr URL at runtime, so SDK releases, including new major versions, reach stores without a module release. The status endpoint reports `latest` rather than a fixed SDK version. The public API the bridge uses (`business`, `session`, `identify`, `track`) must remain compatible, and jsDelivr and browsers cache the resolved file (a rollback of a bad release may need a purge). CDN availability and merchant CSP/network policy are release gates: verify the asset loads in browser Network. An approved owned asset is an alternative only after changing the bridge/CSP and revalidating it; this package does not provide one. - Generated Magento static assets must be rebuilt after changing module JavaScript. - Product and order references include the Magento installation and entity ID, not store-view IDs; one connection covers every view in its website. - FPC must be checked at the backend/cache-key level; response headers alone do not prove a HIT. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index acdbee6..2261f80 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -24,12 +24,12 @@ Check, in order: 1. the page is a secure context; 2. the API root passed validation and matches the CSP/CORS configuration; -3. no other Hellotext SDK initialized first; -4. the page is not checkout, payment or success; -5. the browser can load the SDK asset from jsDelivr; -6. the private cart/customer-data request completed successfully. +3. the page is not checkout, payment or success; +4. the browser can load the SDK asset from jsDelivr when it is not already loaded. -The bridge should warn and stop optional tracking rather than break Magento. +The bridge reuses an existing `window.Hellotext` and initializes it with the store's configured business and API root. + +Unavailable or invalid cart data skips cart tracking without stopping page, product or success-page order events. Later cart refreshes can recover without reloading the page. An explicitly disabled section still stops tracking, including when Magento's Cookie Restriction Mode denies consent. ## No cart event is persisted diff --git a/i18n/es_ES.csv b/i18n/es_ES.csv index 9736f60..a19fafd 100644 --- a/i18n/es_ES.csv +++ b/i18n/es_ES.csv @@ -30,3 +30,5 @@ "Order snapshot is unsupported or invalid.","Los datos del pedido no son compatibles o no son válidos." "Hellotext order configuration is invalid for this store.","La configuración de pedidos de Hellotext no es válida para esta tienda." "Hellotext order configuration is invalid for this website.","La configuración de pedidos de Hellotext no es válida para este sitio web." +"Request at most 100 positive product IDs.","Solicita como máximo 100 ID de producto positivos." +"Inventory did not return a result for every product.","El inventario no devolvió un resultado para cada producto." diff --git a/view/frontend/web/js/bridge.js b/view/frontend/web/js/bridge.js index 3f56c3f..aca8915 100644 --- a/view/frontend/web/js/bridge.js +++ b/view/frontend/web/js/bridge.js @@ -1,7 +1,7 @@ define(['Magento_Customer/js/customer-data', 'Hellotext_Tracking/js/cart-tracker'], function (customerData, createCartTracker) { 'use strict'; - var sdkUrl = 'https://cdn.jsdelivr.net/npm/@hellotext/hellotext@2/dist/hellotext.min.js'; + var sdkUrl = 'https://cdn.jsdelivr.net/npm/@hellotext/hellotext/dist/hellotext.min.js'; return function (config) { if (!hasSafeConfig(config) || window.hellotextMagentoStarted) { @@ -19,28 +19,12 @@ define(['Magento_Customer/js/customer-data', 'Hellotext_Tracking/js/cart-tracker stopped = true; } - function safeBrowser() { - if (stopped) { return false; } - if (hasForeignIdentityCookie()) { - stop(); - return false; - } - return true; - } - function cookieValue(name) { var match = document.cookie.match(new RegExp('(?:^|;\\s*)' + name + '=([^;]*)')); if (!match) { return null; } try { return decodeURIComponent(match[1]); } catch (error) { return null; } } - function hasForeignIdentityCookie() { - var id = cookieValue('hello_user_id'); - var source = cookieValue('hello_user_source'); - var fingerprint = cookieValue('hello_user_identification_hash'); - return Boolean((id || source || fingerprint) && source !== 'magento'); - } - // Only the signed-in customer's ID: Hellotext verifies it against the store and reads the profile there. function validIdentity(identity) { return identity === null || Boolean(identity @@ -51,20 +35,23 @@ define(['Magento_Customer/js/customer-data', 'Hellotext_Tracking/js/cart-tracker function safeSection(sections) { var data = sections && sections.cart && sections.cart.hellotext; - if (!safeBrowser() || !data || data.enabled !== true + if (!data) { return null; } + if (stopped || data.enabled !== true || !data.context || !['businessId', 'apiRoot', 'installationId', 'storeId', 'currency'].every(function (key) { return typeof data.context[key] === 'string' && data.context[key] === config[key]; }) - || typeof data.cart_ready !== 'boolean' + || !validIdentity(data.identity)) { + stop(); + return null; + } + if (typeof data.cart_ready !== 'boolean' || !createCartTracker.validItems(data.items) || !data.items.every(function (item) { return matchesProductContext(item.product) && item.price.currency === config.currency; }) - || !validIdentity(data.identity) || !(data.checkout_reference == null || (typeof data.checkout_reference === 'string' && new RegExp('^magento:' + config.installationId + ':checkout:[1-9]\\d*$').test(data.checkout_reference)))) { - stop(); - return null; + return Object.assign({}, data, { cart_ready: false }); } return data; } @@ -81,7 +68,7 @@ define(['Magento_Customer/js/customer-data', 'Hellotext_Tracking/js/cart-tracker function isActive() { if (sdk && (sdk.session !== session || !hasExpectedSessionCookie(session))) { stop(); } - return safeBrowser() && sdk && sdk.session === session; + return !stopped && sdk && sdk.session === session; } function initializeSession(Hellotext) { @@ -118,8 +105,7 @@ define(['Magento_Customer/js/customer-data', 'Hellotext_Tracking/js/cart-tracker }).then(function (sections) { return safeSection(sections); }).catch(function () { - stop(); - console.warn('Hellotext Magento: private cart unavailable; tracking stopped'); + console.warn('Hellotext Magento: private cart unavailable; skipping cart tracking'); return null; }).finally(function () { refresh = null; }); return refresh; @@ -171,7 +157,7 @@ define(['Magento_Customer/js/customer-data', 'Hellotext_Tracking/js/cart-tracker } function trackCheckoutStarted(Hellotext, data) { - if (!config.checkoutStarted || !data.cart_ready || !data.items.length || !data.checkout_reference) { + if (!config.checkoutStarted || !data || !data.cart_ready || !data.items.length || !data.checkout_reference) { return false; } var storage; @@ -193,26 +179,21 @@ define(['Magento_Customer/js/customer-data', 'Hellotext_Tracking/js/cart-tracker function start(Hellotext) { var trackedReferences = {}; - if (!safeBrowser()) { stop(); return; } - if (Hellotext.business) { - console.warn('Hellotext Magento: existing SDK API root cannot be verified'); - return; - } + if (stopped) { return; } sdk = Hellotext; var ready = Promise.resolve().then(function () { - if (!safeBrowser()) { stop(); return; } + if (stopped) { return; } return initializeSession(Hellotext); }); ready.then(readCurrentCart).then(function (current) { - if (!current) { return; } + if (stopped) { return; } return synchronizeSession(Hellotext).then(function () { return current; }); }).then(function (current) { - if (!current) { return; } return identifyCurrent(Hellotext, current).then(function () { return current; }); }).then(function (current) { - if (!current || !isActive()) { return; } + if (!isActive()) { return; } // The SDK does not automatically emit page.viewed. Promise.resolve().then(function () { if (isActive()) { @@ -230,11 +211,11 @@ define(['Magento_Customer/js/customer-data', 'Hellotext_Tracking/js/cart-tracker } trackCheckoutStarted(Hellotext, current); cartTracker = createCartTracker(Hellotext, isActive, storage, 'hellotext-magento-cart:' + config.businessId + ':' + session); - if (current.cart_ready) { cartTracker(current.items); } + if (current && current.cart_ready) { cartTracker(current.items); } customerData.get('cart').subscribe(function () { if (!refresh) { readCurrentCart().then(function (data) { - if (!data) { return; } + if (stopped) { return; } var sessionChanged; return synchronizeSession(Hellotext).then(function (changed) { sessionChanged = changed; @@ -244,7 +225,7 @@ define(['Magento_Customer/js/customer-data', 'Hellotext_Tracking/js/cart-tracker return Hellotext.track('page.viewed', { object_parameters: { source: 'magento' } }); } }).then(function () { - if (isActive() && data.cart_ready) { cartTracker(data.items); } + if (isActive() && data && data.cart_ready) { cartTracker(data.items); } if (sessionChanged && refreshProductTracking) { refreshProductTracking(); } }).catch(function () { console.warn('Hellotext Magento: private cart refresh failed'); @@ -298,7 +279,7 @@ define(['Magento_Customer/js/customer-data', 'Hellotext_Tracking/js/cart-tracker return Promise.resolve().then(function () { return readCurrentCart(); }).then(function (data) { - if (!data) { return; } + if (stopped) { return; } var sessionChanged; return synchronizeSession(Hellotext).then(function (changed) { sessionChanged = changed; @@ -350,6 +331,7 @@ define(['Magento_Customer/js/customer-data', 'Hellotext_Tracking/js/cart-tracker } function identifyCurrent(Hellotext, current) { + if (!current) { return Promise.resolve(); } var identity = current.identity; var currentId = cookieValue('hello_user_id'); var currentSource = cookieValue('hello_user_source'); @@ -363,18 +345,16 @@ define(['Magento_Customer/js/customer-data', 'Hellotext_Tracking/js/cart-tracker }).catch(function () { console.warn('Hellotext Magento: customer identification failed'); }); } - if (window.Hellotext) { - console.warn('Hellotext Magento: existing SDK API root cannot be verified'); - return; - } - - if (!safeBrowser()) { return; } - Promise.resolve(customerData.getInitCustomerData()).then(readCurrentCart).then(function (data) { - if (!data) { return; } - require([sdkUrl], function (Hellotext) { start(Hellotext); }, function () { - window.hellotextMagentoStarted = false; - console.warn('Hellotext Magento could not load the SDK'); - }); + Promise.resolve(customerData.getInitCustomerData()).then(readCurrentCart, readCurrentCart).then(function () { + if (stopped) { return; } + if (window.Hellotext) { + start(window.Hellotext); + } else { + require([sdkUrl], function (Hellotext) { start(Hellotext); }, function () { + window.hellotextMagentoStarted = false; + console.warn('Hellotext Magento could not load the SDK'); + }); + } }); }; });