# Independent Emacron Store example

This is an actual framework-independent browser client using `/emacron-store.js` and documented public/customer endpoints. It contains no CRM employee token/key, mocked products, invented prices, provider responses or customer records. All business facts come from the connected native Store API. It is a developer example, not a claim that every ecommerce/admin feature is available.

Read the [step-by-step dashboard-to-frontend connection guide](CONNECT_FRONTEND.md), including the supported API boundaries and optional carrier-price integration.

## Run against your Store

1. Create/configure a native Emacron Store, publish real products/options and enable the supported payment/fulfillment methods you intend to use. Customer OTP needs the selected connected sender and its required channel package.
2. In Store → Storefront → Connect your own website, approve the **exact origin** hosting these files. HTTPS is required except localhost/127.0.0.1 development. Approving an origin is not authentication.
3. Serve this folder and `/emacron-store.js` from your website. Keep `storefront.js`, `returns.js`, `storefront.css`, `money.js`, `owned.js`, and `index.html` together. The frontend can be any framework; these files intentionally use none.
4. Open `index.html`, enter the API origin and public Store slug, then connect. Optional `?api=...&slug=...` supplies these two public values only; never put customer/checkout/staff credentials in a URL.
5. Use a merchant-authorised disposable/test Store for test orders. Production connection means real Store actions: submitting checkout creates a real order, and requesting OTP uses the configured channel/allowance.

## What this client covers

- Actual published catalog search/pagination, exact option choice, cart identity/quantity, public product reviews.
- Email/WhatsApp sign-in according to actual advertised methods; captured fixture codes are never part of this production example.
- Current verified profile, private wishlist, account-cart replace using its current version, owned-order history.
- Digital delivery and server-validated zero-total checkout, without COD, parcel service selection or invented free eligibility. Nonzero digital totals require a currently enabled payment method.
- Guest or authenticated COD/manual checkout, pickup/delivery destination, server-reviewed items/amounts/policies, explicit placement, saved order status, release of an unused review and fresh cart after a saved order.
- Return/refund-review eligibility, exact eligible returned lines/condition, saved policy, current customer-visible history and explicit withdrawal. Reviews never submit a refund or book a carrier.
- Cancellation eligibility/request/status/withdraw with explicit confirmation; private photo metadata/upload/on-demand Blob preview when the backend reports storage ready.
- Native form labels/validation, keyboard focus, live status/error messages, desktop/mobile composition and reduced-motion styling.

Raw credentials stay in memory. Reload clears the customer session and prepared checkout; do not build an automatic retry on reload. Existing holds expire on the server. Preserve a real application's pending identities securely before adding cross-reload recovery; do not store employee keys in a browser or infer a successful payment from a UI result.

Writes are never automatically replayed. Unknown review/placement outcomes retain the original prepared identity; use Retry same review request or Check saved order status. Cart/request/photo/withdraw prepared identities are retained in memory on uncertainty. Explicitly closing a pending form does not undo saved server records. Re-read current facts before another operation. Server responses are authoritative for eligibility, prices, stock, source and ownership.

The example supports merchant-enabled COD/manual/online Razorpay choices; online requests retain one attempt identity and expose saved status/reconciliation without treating the browser callback as payment proof. Profile/address read/save/remove, explicit account-cart restore/merge, owned reorder, review submission/history, whole-order exchange and private complaint threads are in Account & order tools. It does not implement carrier booking, provider refunds, arbitrary attachments or offline persistence. Real provider capture/refund and channel delivery acceptance remain separate. Never advertise unsupported operations by copying generic ecommerce buttons.

## Isolated local acceptance

The test API is in `api-server/tests/fixtures/storeCustomerServer.cjs`. It refuses any database except the disposable `127.0.0.1:55482/store_batch30` fixture. Establish that schema using the existing Store database setup first; never change its guard to target a production DB.

From `api-server`:

```sh
STORE_TEST_DATABASE_URL=postgresql://harsh@127.0.0.1:55482/store_batch30 STORE_CORS_HTTP_FIXTURE=1 node --import tsx tests/fixtures/storeCustomerServer.cjs
```

The API listens at `http://127.0.0.1:55517`; its printed context slug is also readable at `/__qa/context` **only in this isolated fixture**. The fixture captures OTP locally and stores evidence in an explicit memory adapter. These helpers are never deployed and are not shopper SDK endpoints.

From `frontend`:

```sh
node tests/storeIndependentServer.cjs
STORE_CORS_HTTP_ORIGIN=http://127.0.0.1:55517 node --test tests/storeIndependentHttp.test.cjs
node --test tests/storeIndependentMoney.test.cjs
```

Open `http://127.0.0.1:55518/?api=http%3A%2F%2F127.0.0.1%3A55517&slug=THE_PRINTED_FIXTURE_SLUG&qa=isolated`. A local-only banner identifies the isolated run. For sign-in in this fixture, retrieve its captured code from `/__qa/code?method=email&destination=YOUR_TEST_ADDRESS`; a real website must obtain the code from the customer's selected delivery channel, never add that helper to its frontend or production API.

The browser example itself never uses `/__qa`, merchant routes, SQL shortcuts or a staff key. The QA operator obtains only the captured test code separately. All shopper interactions run through normal SDK/public/customer endpoints.

## Cross-origin contract

Allowed sites must match the saved canonical origin exactly. API preflight validates the requested method as well as exact supported public/customer paths. No staff path, wildcard, credentials/cookies, JWT Authorization or X-API-Key is admitted by merchant website CORS. The API still enforces publication, packages, proof, limits and resource ownership; CORS does not replace any of these checks. Server-to-server consumers have no browser CORS and still require the appropriate endpoint authentication.

Tests derive the route inventory from the registered native public/customer routers. Adding an endpoint requires updating the explicit allowlist and its actual preflight/ownership tests, rather than opening a broad `/customer/*` wildcard.


Delivery rules: when the Store enables its own service rules, the example explicitly loads actual `deliveryChoices`, requires a selected eligible payment method and uses offered `pickupSlots` when needed. The prepared review retains service/window and postal destination across uncertain retries. These merchant rules do not quote or book a carrier; capacity is held only by the actual checkout review. Changing cart/destination requires checking choices again.


## Recurring product profiles

The merchant chooses digital/service access or physical renewal eligibility per native Store product. These are separate from the merchant's CRM subscription package and from connected WooCommerce/Shopify products. An active offer cannot use both classifications at once. Pausing an offer does not cancel an existing customer mandate or order.

Digital/service plans: read `recurringPlans()`, retain `prepareSubscriptionConsent(plan)` privately, then call `startSubscription(customerToken, draft, true)` only after explicit customer consent to the exact finite terms. Hosted authorization is not proof of paid access. Use `customerSubscriptions()` and `customerSubscription()` for owned history and original-merchant verified status. Cancellation uses a retained `prepareSubscriptionCancellation()` draft and explicit confirmation.

Physical products: `preparePhysicalSchedule(ownedOrderId, {period, totalCount})` and `startPhysicalSchedule(customerToken, draft, true)` create a finite review-and-pay schedule from the customer's own eligible order. This profile does **not** authorize automatic debits. Each cycle requires current stock, tax/delivery pricing and customer checkout confirmation. Unavailable stock skips the cycle without requesting a payment. Existing placed orders remain subject to normal order cancellation, payment, delivery and return controls.

At a due cycle, retain `preparePhysicalCheckout(scheduleId)` on the same private device. Call `physicalCycle(customerToken, draft)` deliberately. For a `prepared` response with `charged:false`, create `physicalReviewDraft(draft, cycle, checkoutInput)` and use the existing `review`, `place`, payment and receipt methods. The cycle's exact products/options/quantities and original proof are enforced server-side. Never merge the ordinary cart into a renewal. `skipped` and `not_due` results must not open a payment flow.

All writes require explicit user actions and retain the same request identity after uncertain outcomes. The SDK never automatically retries writes. Keep customer/checkout proofs out of URLs, logs and analytics. Independent frontend origins must be approved by the merchant; browser CORS is not authentication. New recurring provider writes and new physical renewal checkout have separate deployment switches and remain off until their acceptance checks pass.

Access-only recurring plans are for memberships/services. They do not replace per-order private-file download allowances, bundles or future-supply fulfillment. Those products retain their normal checkout; the server rejects classifying them as access-only subscriptions.

## Carrier-priced checkout integration

The SDK preserves a selected `carrier_quote_id` in the prepared delivery review. A custom frontend must show the selected service’s actual `carrier_quotes`, exact charge, permitted payment methods and expiry, then pass the chosen quote ID alongside `service_id`. Server review remains authoritative. The framework-free example offers merchant delivery rules, pickup slots and an estimate picker for enabled carrier-priced services. It forwards the selected quote with checkout review. Merchant carrier acceptance is tested separately. See CONNECT_FRONTEND.md.
