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

# Operations

> How digital contracting runs in production: the contract workers and what enqueues each one, the manual review, recovery tools, monitoring and how to run the flow locally.

## The asynchronous pipeline

Long work runs in five workers on the contract queue. In deployed
environments the transport is Upstash QStash; every message is also recorded
in the queue ledger (`queue_event`), so a failed job is retried, traced and
never lost.

```mermaid theme={null}
flowchart LR
    confirm["PATCH …/payment/confirm,<br/>…/signature/send or<br/>POST …/signature"] --> A["Worker A<br/>contract-pdf-generation"]
    A --> B["Worker B<br/>contract-send-to-signer"]
    B -->|"company_phase = first"| ENT["Enterprise worker<br/>contract-enterprise-sign"]
    sign["Last signature<br/>seals the group"] --> C
    approve["PATCH …/review<br/>(approve)"] --> ENT
    retry["Enterprise retry<br/>(back office)"] --> ENT
    ENT -->|sealed| C["Worker C<br/>contract-activated"]
    C --> EMAIL["Email worker<br/>contract-email"]
```

| Worker | Enqueued by | Does | Guard against duplicates |
| - | - | - | - |
| A — `contract-pdf-generation` | Payment confirm, `POST …/signature/send` and the back-office `POST …/signature` (all through the pipeline start); `PATCH …/payment` and `…/payment/period` run a warm-up that only pre-renders the PDFs | Renders the contract and annex PDFs and stores the originals; then enqueues Worker B | A run carries the send epoch (the payment confirmation time and the live annex); a run from an older confirmation does nothing |
| B — `contract-send-to-signer` | Worker A | Opens the signature group from `contract_signer` and the business-unit workflow; with `company_phase = first` it also enqueues the enterprise worker | Same send epoch; a stale run cancels the group it would replace |
| Enterprise — `contract-enterprise-sign` | Review approval, Worker B (`first`), or the back-office retry | Signs Maihue's representatives; when that completes the group it seals the PDFs and enqueues Worker C; with `first` it opens the customer phase instead | Skips activation when the contract is already `signed` or `active` |
| C — `contract-activated` | Enterprise worker, or the customer signature that seals the group | Records the sealed PDFs (already uploaded when sealing) as version 2, activates the contract and the subscription; then enqueues the email | Does not insert version 2 twice |
| Email — `contract-email` | Worker C | Sends the signed-contract confirmation to the primary signer | The notification id (contract, purpose and signer) is unique, so a redelivery does not send twice |

Handlers live in `backend/horizon-api/lib/queue/contract/handlers/`. A
platform cron (`/api/v3/cron/queue/event/reconcile`, every 10 minutes)
requeues open jobs (`received`, `enqueued` or `processing`) that have
stalled.

## Manual review

With `company_phase = last` (used by the seeded workflows), every contract
signed by its customers waits in `pending_review` until Maihue operations
decide. The customer is already in the customer portal by then.

```http theme={null}
PATCH /api/v3/contract/{id}/review
Authorization: Bearer <back-office token with contract:review>

{ "state": "approve", "user": "<reviewer user id>" }
```

* `approve` is accepted only from `pending_review`. It moves the contract to
  `awaiting_enterprise_signature` and enqueues the enterprise worker.
* `reject` needs a `reason` and is accepted from `pending_review` or
  `awaiting_enterprise_signature`. It cancels the signature group and the
  contract.

## Recovery tools

| Situation | Tool | Permission |
| - | - | - |
| Countersignature did not finish | `GET /api/v3/signature/enterprise-signer/stuck` lists signatures stuck in the enterprise phase; `POST /api/v3/signature/enterprise-signer/retry` with `contract_id` and `signature_id` enqueues the enterprise worker again | `signature-enterprise-signer:stuck`, `signature-enterprise-signer:retry` |
| A customer lost the link | `POST /api/v3/contract/{id}/resend-portal-magic-link` (rate-limited per contract) | `contract:resend-portal-magic-link` |
| A contract must be stopped | `POST /api/v3/contract/{id}/cancel` with `actor: "admin"` | `contract:cancel-admin` |
| A status must be set by hand | `POST /api/v3/admin/contract/{id}/force-status` with `target_status_internal` and a mandatory `reason`; it skips the transition guards and logs who did it | `contract:force-status-admin` |

A signature counts as stuck when it has waited more than 30 minutes on the
enterprise phase: a signature group in `awaiting_enterprise_signature` (with
`company_phase = last` the group reaches that status as soon as the customers
sign, so a contract still waiting for review also shows up), a
`company_phase = first` group whose enterprise turn is incomplete, or a
sealed group whose contract is still in `pending_signature`, `in_signature`,
`partially_signed` or `awaiting_enterprise_signature`.

## Monitoring

Better Stack watches the flow; its configuration lives in
`infra/betterstack/` and is described in
[Monitoring — Terraform](https://docs.bbrands.io/monitoring/terraform.md).

| Signal | What it covers |
| - | - |
| **Digital Contract** status-page component | A journey monitor across registration, the one-time link, the contract routes and the signer routes, folded with a probe of the flow's external dependencies |
| **Signature Engine / Enterprise unattended failure** alert | An enterprise countersignature job failed |
| **Signature Engine / Enterprise stuck scan** alert | The scan found signatures stuck in the enterprise phase |

The stuck scan runs as a cron (`/api/v3/cron/signature/enterprise-stuck`,
every 10 minutes in production). It reports; the retry above is a manual
decision. Incident handling follows the
[Monitoring runbook](https://docs.bbrands.io/monitoring/runbook.md).

## Running the flow locally

Start the apps with Turbo:

```bash theme={null}
pnpm turbo dev --filter=@bbrandslab/horizon-api --filter=@bbrandslab/portal-customer
```

| Setting | App | Effect |
| - | - | - |
| `NEXT_PUBLIC_CONTRACT_API_MODE=mock` | portal-customer | The wizard runs against mock routes inside the portal; no backend needed (local only) |
| `NEXT_PUBLIC_CONTRACT_API_MODE` unset (`real`, the default) | portal-customer | The wizard calls the local horizon-api |
| `QUEUE_PROVIDER=inline` | horizon-api | Workers run in-process, because hosted queues cannot reach `next dev` |
| `INTEGRATION_FLOID_STUB=true` | horizon-api | Fakes Floid success; refused when the API points to the production host |

Notes for an end-to-end run:

* **Mock mode** seals for Maihue a few seconds after the customer signs, so
  the wizard can be walked to the password. To rehearse the review, open the
  wizard with `?mock_enterprise_seal=pending` (also `slow` or `never`) once
  the magic link was exchanged; `auto` is the default. After the mock
  checkout the portal calls the mock `POST …/payment/enrollment-notify`
  until the card is attached.
* **Real mode** needs the platform signing certificates configured locally
  (see `backend/horizon-api/.env.example`) for the countersignature to seal.
  Approve the review with a back-office token as shown above.
* **Fintoc** webhooks cannot reach `localhost`. Against a local API, the
  portal calls `POST …/payment/enrollment-notify` after returning from Fintoc
  so other open tabs still see the new method; deployed environments answer
  `404` to that route.

## Internal runbooks

Step-by-step runbooks live in the repository under `docs/operations/`:

| Runbook | Use |
| - | - |
| `digital-contract-manual-review-local.md` | Local demo of the review and the countersignature |
| `digital-contract-identity-audit.md` | Read-only checks for email and RUT mismatches |
| `signature-enterprise-representative-replacement.md` | Replace a Maihue representative used for the countersignature |
| `signature-certificate-rotation.md` | Rotate the signing certificates |
| `cron-inventory.md` | Every cron and its schedule |

## Code

| Concern | Path |
| - | - |
| Topics, dispatch and ledger | `backend/horizon-api/lib/queue/contract/` |
| Worker handlers | `backend/horizon-api/lib/queue/contract/handlers/` |
| Review | `backend/horizon-api/lib/endpoint/contract-review/` |
| Enterprise recovery | `backend/horizon-api/app/api/v3/signature/enterprise-signer/`, `lib/integration/signature-provider/internal-signer/enterprise-signing.observability.ts` |
| Cron routes | `backend/horizon-api/app/api/v3/cron/` |
| Better Stack | `infra/betterstack/` |


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