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

# Client integration

> How the customer portal drives the contract wizard: the orchestrator, the ContractState it renders, the screens, how it applies realtime events, and the mock and real API modes.

The wizard lives in `frontend/portal-customer`. It is a thin client: the
backend decides the step, and the portal renders it and sends the customer's
input.

## Route and orchestrator

There is a single route, `/{locale}/contract/{contractId}`, for the five
portal locales (`es`, `en`, `fr`, `it`, `pt`).

| File | Role |
| - | - |
| `app/[locale]/(public)/contract/[contractId]/page.tsx` | Server entry; resolves the params and renders the orchestrator |
| `app/[locale]/(public)/contract/[contractId]/contract-orchestrator.tsx` | Client orchestrator: boot, session, screen choice, realtime, rewind |
| `app/components/digital-contract/steps/` | One component per step |
| `app/lib/services/v3/contract/service.ts` | Calls to the contract backend |
| `app/lib/realtime/use-contract-channel.ts` | Subscription to `private-contract-{id}` |

### Boot

```mermaid theme={null}
flowchart TD
    open["Open /{locale}/contract/{id}"] --> link{"?action_link<br/>in the URL?"}
    link -->|yes| exchange["POST /contract/{id}/sessions"]
    exchange --> seed["Seed the cache with { jwt, state }"]
    link -->|no| stored{"Stored session<br/>for this contract?"}
    stored -->|yes| read["GET /contract/{id}/state"]
    stored -->|no| recovery["Access recovery screen"]
    read --> render["Render the step for state.stage"]
    seed --> render
    exchange -->|401, 410, or 409 with no stored session| recovery
    read -->|401, 403| recovery
```

The session is kept in the browser tab, bound to its contract id, so a reload
lands on the same step without a new link.

### What the orchestrator renders

In order:

1. An invalid contract id or a server error → **Redirecting** out of the
   wizard.

2. A session that cannot start → **Access recovery**, which offers to resend
   the link. The screen names the reason:

   | Reason | Cause |
   | - | - |
   | `linkUsed` | The one-time link was already redeemed (`409`) and no session for this contract is stored; if one is, the portal keeps it |
   | `linkExpired` | The link expired (`410`) |
   | `linkInvalid` | The link is not valid (`401`) |
   | `sessionExpired` | The stored session expired or was refused (`403`) |
   | `missingAccess` | No link and no stored session |

3. While booting or waiting for the first state → **Validating**.

4. Otherwise, the screen for `state.stage`.

## The ContractState

Every screen reads one object, `ContractState`, returned by
`GET /api/v3/contract/{id}/state`, by `POST …/sessions` and inside the
realtime snapshots. The portal never computes the stage itself.

| Field | Content |
| - | - |
| `contract_id`, `user_id`, `email` | The contract and its primary signer (the account holder) |
| `stage` | The step to render (see below) |
| `flags` | Progress flags (see below) |
| `summary` | Contract terms for the summary step: duration, fee, services, renewal, cancellation penalty and the frozen contract text |
| `plans` | Billing options (`monthly`, `annual`) with prices |
| `payment` | Enrolled cards and bank-account mandates (always masked) and the chosen method and period |
| `documents` | The documents to sign and their status |
| `signing` | Signature group id, signer seats (masked emails) and the pipeline status |

**Stages.** The account holder goes
`NOT_STARTED → IDENTITY → SUMMARY → PAYMENT → SIGNATURE → COMPLETED`. A later
company administrator goes `IDENTITY → SUMMARY → SIGNATURE`. The stage stays
`SIGNATURE` while the contract is in signature, review and countersignature,
and becomes `COMPLETED` only once the documents are sealed and the session
user has a portal password.

**Password screen.** The portal, not the stage, decides when to show it: as
soon as the session user's own seat is signed and they press **Create
password** on the success ticket, whatever the review status. A signer who
already has a password goes straight to the customer portal through the
handoff.

**Flags.**

| Flag | True when |
| - | - |
| `is_identity_validated` | The signer's identity is verified for this contract |
| `summary_accepted` | The account holder accepted the summary |
| `has_payment_method` | The account has a usable enrolled method |
| `payment_method_confirmed` | The method and period were confirmed |
| `are_documents_signed` | The documents are sealed |
| `pending_review` | Every customer signed and the contract waits for Maihue operations |
| `has_password` | The session user already has a portal password |
| `require_signer_document_number` | A re-entry session must prove the card serial before signing |
| `has_other_contracted_unit` | The account has another signed or active contract |

**Signing status.** `signing.status` tells the portal where the pipeline is
without exposing internal statuses: `NOT_REQUESTED`, `PREPARING`,
`IN_PROGRESS`, `COMPLETED` or `FAILED`.

## Screens

| Stage | Screen | Component | Backend calls |
| - | - | - | - |
| `NOT_STARTED` | Welcome | `welcome-step.tsx` | `POST …/start` |
| `IDENTITY` | Identity | `identity-step.tsx` | `PATCH …/identity` |
| `SUMMARY` | Summary | `summary-step.tsx` | `PATCH …/summary`; later administrators `PATCH …/signer-summary` |
| `PAYMENT` | Payment (account holder only) | `payment-step.tsx`, `payment-period-selector.tsx` | `PATCH …/payment`, `…/payment/period`, `…/payment/confirm` |
| `SIGNATURE` | Documents and signers | `signature-step.tsx` | `POST …/signature/send` (fallback only) |
| `SIGNATURE` | Signing modal | `signature-signing-modal.tsx` | `POST /signature/{id}/signer/{signer}/otp`, `…/sign` |
| `SIGNATURE` (own seat signed, no password) | Password | `password-step.tsx` | `PATCH …/password` |

Overlays available on several steps:

* **Exit**, labelled **Reject** (`contract-abandon-modal.tsx`): cancels this
  registration as the customer. It is shown from Identity until Signature,
  not on Welcome or Password.
* **Back** (`use-contract-rewind.ts`): shows Payment or Summary again from
  Signature, before anyone signs, and Summary from Payment (account holder).
  It is a local view: the backend keeps its stage, and only a confirm with a
  different method or period changes the contract.

The Welcome step also asks the browser for its location when the customer
continues. The prompt never blocks the wizard and the result is not stored.

## Realtime

The orchestrator subscribes to `private-contract-{id}`. In real mode the
channel is authorized by horizon-api
(`POST /api/v3/realtime/pusher/auth`); the events and their payloads are in
[Realtime — Channels & Events](https://docs.bbrands.io/realtime/channels-and-events.md).

| Category | Events | Payload |
| - | - | - |
| Wizard steps | `contract.state_updated` | A patch (`stage`, `flags`; payment confirm adds `signing`; the later administrator's summary publishes only `{ stage }`); rewind and the holder's password publish a full `ContractState` |
| Payment enrollment | `contract.payment_method.enrollment.success`, `contract.payment_method_failed` | A full `ContractState` |
| Signing lifecycle | `contract.signature_requested` | A patch (`documents`, `signing`, `stage`; Worker B adds `flags`) |
| Signing lifecycle | `contract.status_changed`, `contract.signed` | A full `ContractState` |
| Signing lifecycle | `contract.cancelled`, `contract.rejected` | The portal also listens to them |

How the portal applies them:

* A **full state** replaces the cached state, keeping the visitor's own
  fields (password, re-entry, own seat, contract text); a **patch** is merged
  into it. The portal never re-reads the state just because an event arrived.
* With Pusher configured, a successful step does not move the wizard on its
  own: the button stays loading until the event arrives. If the event does
  not come within about 10 seconds, the portal applies the response it
  already received. A later company administrator's identity and summary
  results, and a re-entry identity result, are applied right away; their
  summary patch is broadcast but not awaited. Without a Pusher key every step
  is applied right away.
* After the socket reconnects, the portal reads `GET …/state` **once** to
  catch up on missed events. It does not poll while realtime is configured;
  without a Pusher key it polls `GET …/state` on the signature step.
* While documents are `PREPARING` and no signature group shows up, the portal
  calls `POST …/signature/send` (it is idempotent) and offers a retry if the
  pipeline still does not start.
* Back from Fintoc (`?resumed=payment&enrollment=…`), the payment screen stays
  open and waits for the enrollment event.

## Mock and real modes

`NEXT_PUBLIC_CONTRACT_API_MODE` switches the whole wizard between two
backends without touching the service layer:

| Mode | Backend | Realtime auth |
| - | - | - |
| `mock` | Route handlers inside the portal (`app/api/v3/contract/[contractId]/` and, for the code and signing calls, `app/api/v3/signature/[signatureId]/signer/[signerId]/`) | A local stub |
| `real` | horizon-api | horizon-api `POST /api/v3/realtime/pusher/auth` |

`real` is the default since 2026.11.2 and the only mode of the hosted
environments, which no longer set the variable; `mock` is a switch for local
development only. The document preview (`preview.pdf`) is always served by
the portal itself, in both modes; mock mode does not implement
`signer-summary`.

## Code

| Concern | Path |
| - | - |
| Route and orchestrator | `frontend/portal-customer/app/[locale]/(public)/contract/[contractId]/`, `frontend/portal-customer/app/[locale]/(public)/contract/[contractId]/use-contract-rewind.ts` |
| Steps and overlays | `frontend/portal-customer/app/components/digital-contract/` |
| Service layer and API mode | `frontend/portal-customer/app/lib/services/v3/contract/`, `frontend/portal-customer/app/lib/services/config.ts` |
| Realtime | `frontend/portal-customer/app/lib/realtime/` |
| Mock routes | `frontend/portal-customer/app/api/v3/contract/`, `frontend/portal-customer/app/api/v3/signature/` |
| Fintoc bridge for callers without `locale` | `frontend/portal-customer/app/gateway/fintoc/enrollment/finish/` |
| `ContractState` and stages (backend) | `backend/horizon-api/lib/endpoint/contract-state/` |


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