Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
## Summary

<!-- What changed and why? Link the issue or contract. -->

## 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

<!-- List exact commands, CI checks and any manual Network/worker evidence. -->

## Rollout and rollback

<!-- Note configuration, static asset, cache and rollback considerations. -->
104 changes: 104 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -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
16 changes: 16 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -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
25 changes: 25 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -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.
7 changes: 3 additions & 4 deletions Model/OrderLifecycleTracker.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
4 changes: 2 additions & 2 deletions Model/VersionInformation.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {}

Expand Down
34 changes: 19 additions & 15 deletions Plugin/CartData.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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;
}
Expand Down
15 changes: 14 additions & 1 deletion Test/README.md
Original file line number Diff line number Diff line change
@@ -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:

Expand All @@ -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
Expand Down
36 changes: 33 additions & 3 deletions Test/Unit/Js/bridge.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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: {
Expand Down Expand Up @@ -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;
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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);
Expand Down
17 changes: 17 additions & 0 deletions Test/Unit/Plugin/CartDataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
}
}
Loading
Loading