> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pcnaid.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Order Merge Pro architecture

> Runtime components, merge state machine, and data flow for Order Merge Pro.

# Order Merge Pro architecture

## Runtime

Order Merge Pro is an embedded Shopify Admin app built on React Router 7 running on Cloudflare Workers. A Durable Object drives an explicit merge state machine, D1 stores job state, KV holds OAuth sessions and rate-limit counters, R2 stores immutable audit logs and GDPR exports, and Cloudflare Queues handle Durable Object start retries and deferred business webhooks.

| Component | Role |
| - | - |
| React Router on Workers | Request routing, auth, SSR, and API endpoints |
| Worker Assets | Fingerprinted client bundles from `./build/client` |
| Durable Object | Stateful merge orchestration (12 statuses) |
| D1 | Jobs, B2B approvals, billing, rules, trials, and webhook receipts |
| KV | OAuth sessions, per-shop indexes, and portal rate limits |
| R2 | Immutable audit logs and GDPR request exports |
| Queue | Durable Object start retries and deferred business webhooks |

## Merge state machine

A merge validates orders, stages and commits Shopify order edits, cancels secondary orders, and refunds redundant shipping. `RECOVERY_REQUIRED` is a bounded operator state, not a terminal failure: the job-detail POST can resume the recorded commit or cancellation state after store-owner authorization.

```text theme={null}
PENDING -> VALIDATING -> STAGING_EDITS -> VERIFYING_INVENTORY ->
COMMITTING_MERGE -> CANCELLING_SECONDARIES -> WAITING_CANCELLATIONS ->
REFUNDING_SHIPPING -> FINALIZING -> COMPLETED

COMMITTING_MERGE -> RECOVERY_REQUIRED   (ambiguous result after bounded retries)
CANCELLING_SECONDARIES -> RECOVERY_REQUIRED
WAITING_CANCELLATIONS -> RECOVERY_REQUIRED
RECOVERY_REQUIRED -> COMMITTING_MERGE | CANCELLING_SECONDARIES | WAITING_CANCELLATIONS  (owner retry)

VALIDATING | STAGING_EDITS | VERIFYING_INVENTORY | REFUNDING_SHIPPING | FINALIZING -> FAILED
```

Key design decisions:

| Decision | Rationale |
| - | - |
| `orderEdit` workflow | Preserves order history, maintains the order number, supports partial edits |
| Commit before cancel | Source orders remain intact if inventory verification or the primary commit fails |
| Paid-value transfer | A 100% "paid on secondary" discount prevents duplicate charges; Basic and Pro carry the exact unpaid secondary total as a verified custom line before cancellation |
| Durable Object alarms | 5-minute alarms reconcile ambiguous commits and missed cancellation confirmations |
| Bounded recovery | Ambiguous commits or exhausted post-commit cancellation recovery stop at `RECOVERY_REQUIRED` for an owner retry |
| Queue fallback | If the Durable Object fails to start, a token-free compact message lets the consumer rebuild context from D1 and KV |
| Idempotent refunds | Refunded order IDs are tracked in the Durable Object context to prevent double-refunding on retry |

## Product data flow

1. Candidate discovery reads unfulfilled orders, groups them by customer, normalized shipping address, and currency, and filters with the shop's entitlements.
2. A merge stages line items onto the primary order edit, applies the paid-on-secondary discount and, on Basic and Pro, carries the secondary outstanding balance as a custom line, then verifies the staged total.
3. The job verifies tracked on-hand inventory at each fulfillment location, commits the primary edit, then cancels the secondary orders.
4. Cancellation confirmations arrive over the `orders/updated` webhook and are enqueued to the merge queue.
5. The job refunds redundant secondary shipping, tags the orders, and completes.

Queue configuration allows an initial delivery plus three retries. Exhausted merge-retry messages reach a dead-letter queue; exhausted webhook work marks its D1 receipt `FAILED` and is acknowledged.

## B2B approval flow

Only Shopify `PurchasingCompany` orders from one company can enter the B2B approval workflow. The server reloads every order instead of trusting dashboard form data. The account owner is derived from the online Shopify session; no merchant-entered shop or role value participates in authorization. A decision lease serializes concurrent approvals, and retrying after a lost lease is safe because merge-job creation uses the same deterministic order-set idempotency key. If merge creation fails, the request returns to `PENDING` with a merchant-visible error.

## Idempotency

Merge operations use a deterministic key: `{shop}:{primaryOrderId}:{sortedSecondaryIds joined by comma}`. This prevents duplicate merges from double-clicks, race conditions from concurrent requests, and reprocessing of completed merges.

## Security model

* Admin routes authenticate with `authenticate.admin()`.
* Webhooks use SDK HMAC verification, with unchanged raw-body HMAC-before-parse for the compliance topics.
* Job queries are scoped to the authenticated session shop.
* Server-side plan guards gate every premium action, and the Free monthly merge limit is enforced before job creation.
* The shop is derived from `session.shop`, the authenticated webhook shop, or signed app-proxy parameters, never merchant input.
* Shopify access and refresh tokens in KV and merge-job access tokens in the Durable Object context use AES-256-GCM envelopes with a rotatable encryption key.
* Audit metadata automatically redacts sensitive token, secret, password, and credential keys before the R2 write.

## Error handling

Pre-commit and non-recoverable errors transition to `FAILED`. Ambiguous commit outcomes and exhausted post-commit cancellation recovery transition to `RECOVERY_REQUIRED`, where only the store owner can retry. The queue consumer retries up to the configured maximum, and Durable Object alarms reconcile commit and cancellation work at 5-minute intervals before manual recovery is required.

See the [quickstart](https://docs.pcnaid.com/nodes/shopify/order-merge-pro/developer/quickstart.md) for scopes and integration entry points, the [API overview](https://docs.pcnaid.com/nodes/shopify/order-merge-pro/developer/api/index.md) for documented interfaces, and the [merchant setup guide](https://docs.pcnaid.com/nodes/shopify/order-merge-pro/merchant/guides/getting-started.md) for the store-facing workflow.

[Pcnaid Documentation](https://docs.pcnaid.com/namespace/index.md) › [Shopify Ecosystem](https://docs.pcnaid.com/hubs/shopify-ecosystem/index.md) › [Order Merge Pro](https://docs.pcnaid.com/nodes/shopify/order-merge-pro/index.md) › [Developer](https://docs.pcnaid.com/nodes/shopify/order-merge-pro/developer/index)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.