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

# Reconcile payments

> Build a procedure that compares a day's payments in your policy system with the processor's settlement report, fixes a failed webhook, asks a person only about what it can't explain, and pays out the balance under a key built from the date.

In this tutorial you build a daily payment reconciliation. The procedure compares the payments
your policy system recorded for one day with your payment processor's settlement report for that
day. For each mismatch it checks whether the processor's webhook to your policy system failed. If
it did, the procedure resends the event once, waits until the payment is recorded and checks the
recorded amount. Mismatches it can't explain go to a person. When nothing is on hold, it pays out
the day's balance.

## What this does for your team

Every day, the payments your processor settled should match the payments your policy system
recorded. The procedure does that comparison for one day. When a payment is missing because the
processor's notification never reached your policy system, it resends that notification and checks
the amount that arrives. Finance operations sees only the mismatches the procedure can't explain,
with both amounts in front of them. The day's payout goes out only when nothing is on hold, under a
key built from the date, so reconciling the same day twice doesn't pay it out twice with a
processor that honours the key. The run records each mismatch, what was done about it, and who
explained it.

The example carrier is Northwind Mutual. Its hosts, policy numbers, payments and amounts are made
up; replace them with your own.

## Before you start

You need:

* An API key for a member who is not read-only, and `curl` and `jq`. See
  [Run procedures from your system](https://docs.canary.effectiveai.app/guides/procedures.md), which also covers
  publishing and starting runs. A draft also needs permission to create procedures, or to publish
  this one once it exists. Resource-scoped and app API keys can't start drafts.
* A group in Effective for the people who look into payment mismatches. The procedure assigns its
  task to `group:finance-operations`; replace that with your group.
* HTTPS APIs for your payment processor and policy system. The procedure's code calls these
  endpoints; change the hosts, paths and field names to match yours:

| Step | Request | Returns |
| - | - | - |
| Read the settlement report | `GET https://api.payments.example/v1/settlements/{date}` | `netCents`, and `payments` with `id`, `policyNumber`, `amountCents`, `eventId` |
| Read recorded payments | `GET https://policy.northwind.example/v1/payments?date={date}` | `payments` with `paymentId`, `policyNumber`, `amountCents` |
| Read webhook deliveries | `GET https://api.payments.example/v1/events/{eventId}/deliveries` | `deliveries`, oldest first, each with `succeeded` and `responseStatus` |
| Resend an event | `POST https://api.payments.example/v1/events/{eventId}/resend` | — |
| Read one payment | `GET https://policy.northwind.example/v1/payments/{paymentId}` | `amountCents`, or `404` |
| Pay out | `POST https://api.payments.example/v1/payouts` | `id` |

Two behaviors keep a repeated write from applying twice. Your policy system must record at most
one payment per webhook event ID, however many times the event arrives. Your processor's payout
endpoint must accept an `Idempotency-Key` header and answer a repeated key with its first payout.

## The procedure

Save this as `reconcile-payments.procedure.md`. The sections after it walk through each part.

````markdown reconcile-payments.procedure.md theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
---
kind: procedure@v0
id: reconcile-payments

inputs:
  settlement_date: { type: string }
outputs:
  reconciliation: { schema: reconciliation-result }
run:
  title: 'Reconcile payments for {{ $inputs.settlement_date }}'
---

# Reconcile payments

Compare the payments the policy system recorded for one day with the payment
processor's settlement report for that day. Fix the mismatches the procedure
can explain, ask finance operations about the rest, and release the day's
payout once every mismatch is resolved.

## Read both sides

Read the processor's settlement report for the day.

```yaml call id=read-settlement
function: '@local.get-settlement-report'
input:
  date: $inputs.settlement_date
output: settlement
```

Read the payments the policy system recorded for the same day.

```yaml call id=read-recorded-payments
function: '@local.get-recorded-payments'
input:
  date: $inputs.settlement_date
output: recorded
```

## Compare them

Match the two lists by payment ID. A payment is a mismatch when only one side
has it, or when the amounts differ.

```yaml call id=compare-payments
function: '@local.match-payments'
input:
  settled: $settlement.payments
  recorded: $recorded.payments
output: comparison
```

## Investigate each mismatch

Work through the mismatches one at a time and collect one outcome for each.

```yaml for-each id=investigate-mismatches
items: $comparison.mismatches
item:
  name: mismatch
  schema: mismatch
body: '#investigate-mismatch'
collect:
  outcomes:
    schema: mismatch-outcomes
    from: $mismatch_outcome
```

### Investigate one mismatch {#investigate-mismatch}

Ask the processor whether it delivered the payment's webhook event to the
policy system.

```yaml call id=check-webhook
function: '@local.get-webhook-delivery'
input:
  kind: $mismatch.kind
  eventId: $mismatch.eventId
output: diagnosis
```

```yaml choice id=route-cause
on: $diagnosis.cause
cases:
  'webhook-failed': '#resend-event'
  'unexplained': '#ask-finance'
outputs:
  mismatch_outcome:
    schema: mismatch-outcome
```

#### Resend the event {#resend-event}

The processor settled the payment but its webhook never reached the policy
system. Resend the event, wait until the policy system has recorded the
payment, then check that it recorded the amount the processor settled.

```yaml call id=resend-event
function: '@local.resend-webhook-event'
input:
  eventId: $mismatch.eventId
output: resend
```

```yaml wait id=confirm-recorded
poll:
  function: '@local.get-payment'
  input:
    paymentId: $mismatch.paymentId
until:
  path: status
  equals: recorded
  schema: payment-recorded
every: 1m
timeout: 30m
output: recorded_payment
on_timeout:
  fail: resent-payment-not-recorded
```

```yaml call id=check-resent-amount
function: '@local.compare-resent-amount'
input:
  settledCents: $mismatch.settledCents
  recordedCents: $recorded_payment.amountCents
output: resent_amount
```

```yaml choice id=route-resent-amount
on: $resent_amount.matches
cases:
  'true': '#resent-matches'
  'false': '#resent-differs'
outputs:
  mismatch_outcome:
    schema: mismatch-outcome
```

##### The amounts match {#resent-matches}

```yaml value id=record-resend
schema: mismatch-outcome
output: mismatch_outcome
value:
  paymentId: $mismatch.paymentId
  resolution: resent
  note: 'Resent webhook event {{ $resend.eventId }}'
```

##### The amounts differ {#resent-differs}

The policy system recorded the resent payment with a different amount. Put
the mismatch on hold, so the day's payout is held.

```yaml value id=record-resent-hold
schema: mismatch-outcome
output: mismatch_outcome
value:
  paymentId: $mismatch.paymentId
  resolution: hold
  note: 'Resent webhook event {{ $resend.eventId }}: {{ $resent_amount.detail }}'
```

#### Ask finance operations {#ask-finance}

The procedure can't explain this one. A person looks at both records and
says whether the day's payout can go ahead.

```yaml task id=explain-mismatch
assignees:
  - group:finance-operations
title: Explain the {{ $inputs.settlement_date }} mismatch on payment {{ $mismatch.paymentId }}
instructions: |
  Payment {{ $mismatch.paymentId }} on policy {{ $mismatch.policyNumber }}
  doesn't match.

  - Settled by the payment processor: ${{ $mismatch.settledAmount }}
  - Recorded in the policy system: ${{ $mismatch.recordedAmount }}
  - What the procedure found: {{ $diagnosis.detail }}

  Choose **explained** if you have fixed or accounted for it, or **hold** to
  hold the day's payout. Say what you found in the note.
result:
  schema: mismatch-decision
output: explanation
```

```yaml value id=record-explanation
schema: mismatch-outcome
output: mismatch_outcome
value:
  paymentId: $mismatch.paymentId
  resolution: $explanation.value.resolution
  note: $explanation.value.note
```

## Pay out the balance

Total the outcomes. The payout goes ahead only when no mismatch is on hold.

```yaml call id=summarize
function: '@local.summarize-reconciliation'
input:
  netCents: $settlement.netCents
  matchedCount: $comparison.matchedCount
  outcomes: $outcomes
output: summary
```

```yaml choice id=route-payout
on: $summary.releasePayout
cases:
  'true': '#release-payout'
  'false': '#hold-payout'
```

### Release the payout {#release-payout}

Ask the processor to pay out the day's balance. The key is built from the
settlement date, so a processor that honours it pays the day out once, even if
reconciliation runs again.

```yaml call id=pay-out
function: '@local.create-payout'
input:
  date: $inputs.settlement_date
  amountCents: $summary.payoutCents
output: payout
```

```yaml complete id=reconciled
output: reconciliation
value:
  date: $inputs.settlement_date
  status: paid-out
  matchedCount: $comparison.matchedCount
  payoutCents: $summary.payoutCents
  payoutId: $payout.payoutId
  outcomes: $outcomes
```

### Hold the payout {#hold-payout}

At least one mismatch is on hold. Nothing is paid out.

```yaml complete id=held
output: reconciliation
value:
  date: $inputs.settlement_date
  status: held
  matchedCount: $comparison.matchedCount
  payoutCents: $summary.payoutCents
  outcomes: $outcomes
```

## Resources

### Contracts

```yaml schema id=reconciliation-result
type: object
additionalProperties: false
required: [date, status, matchedCount, payoutCents, outcomes]
properties:
  date: { type: string }
  status: { enum: [paid-out, held] }
  matchedCount: { type: integer }
  payoutCents: { type: integer }
  payoutId: { type: string }
  outcomes:
    type: array
    items:
      type: object
      additionalProperties: false
      required: [paymentId, resolution, note]
      properties:
        paymentId: { type: string }
        resolution: { enum: [resent, explained, hold] }
        note: { type: string }
```

```yaml schema id=date-request
type: object
additionalProperties: false
required: [date]
properties:
  date: { type: string }
```

```yaml schema id=settlement-report
type: object
additionalProperties: false
required: [netCents, payments]
properties:
  netCents: { type: integer }
  payments:
    type: array
    items:
      type: object
      additionalProperties: false
      required: [paymentId, policyNumber, amountCents, eventId]
      properties:
        paymentId: { type: string }
        policyNumber: { type: string }
        amountCents: { type: integer }
        eventId: { type: string }
```

```yaml schema id=recorded-payments
type: object
additionalProperties: false
required: [payments]
properties:
  payments:
    type: array
    items:
      type: object
      additionalProperties: false
      required: [paymentId, policyNumber, amountCents]
      properties:
        paymentId: { type: string }
        policyNumber: { type: string }
        amountCents: { type: integer }
```

```yaml schema id=comparison-input
type: object
additionalProperties: false
required: [settled, recorded]
properties:
  settled:
    type: array
    items:
      type: object
      additionalProperties: false
      required: [paymentId, policyNumber, amountCents, eventId]
      properties:
        paymentId: { type: string }
        policyNumber: { type: string }
        amountCents: { type: integer }
        eventId: { type: string }
  recorded:
    type: array
    items:
      type: object
      additionalProperties: false
      required: [paymentId, policyNumber, amountCents]
      properties:
        paymentId: { type: string }
        policyNumber: { type: string }
        amountCents: { type: integer }
```

```yaml schema id=comparison
type: object
additionalProperties: false
required: [matchedCount, mismatches]
properties:
  matchedCount: { type: integer }
  mismatches:
    type: array
    items:
      $ref: '#/schemas/mismatch'
```

```yaml schema id=mismatch
type: object
additionalProperties: false
required: [paymentId, policyNumber, kind, eventId, settledCents, settledAmount, recordedAmount]
properties:
  paymentId: { type: string }
  policyNumber: { type: string }
  kind: { enum: [not-recorded, not-settled, amount-differs] }
  eventId: { type: [string, 'null'] }
  settledCents: { type: [integer, 'null'] }
  settledAmount: { type: string }
  recordedAmount: { type: string }
```

```yaml schema id=webhook-request
type: object
additionalProperties: false
required: [kind, eventId]
properties:
  kind: { enum: [not-recorded, not-settled, amount-differs] }
  eventId: { type: [string, 'null'] }
```

```yaml schema id=webhook-diagnosis
type: object
additionalProperties: false
required: [cause, detail]
properties:
  cause: { enum: [webhook-failed, unexplained] }
  detail: { type: string }
```

```yaml schema id=resend-request
type: object
additionalProperties: false
required: [eventId]
properties:
  eventId: { type: [string, 'null'] }
```

```yaml schema id=resend-result
type: object
additionalProperties: false
required: [eventId]
properties:
  eventId: { type: string }
```

```yaml schema id=payment-request
type: object
additionalProperties: false
required: [paymentId]
properties:
  paymentId: { type: string }
```

```yaml schema id=payment-status
type: object
additionalProperties: false
required: [status]
properties:
  status: { enum: [recorded, not-found] }
  amountCents: { type: integer }
```

```yaml schema id=payment-recorded
type: object
additionalProperties: false
required: [status, amountCents]
properties:
  status: { const: recorded }
  amountCents: { type: integer }
```

```yaml schema id=resent-amount-input
type: object
additionalProperties: false
required: [settledCents, recordedCents]
properties:
  settledCents: { type: [integer, 'null'] }
  recordedCents: { type: integer }
```

```yaml schema id=resent-amount-check
type: object
additionalProperties: false
required: [matches, detail]
properties:
  matches: { type: boolean }
  detail: { type: string }
```

```yaml schema id=mismatch-decision
type: object
additionalProperties: false
required: [resolution, note]
properties:
  resolution: { enum: [explained, hold] }
  note: { type: string, minLength: 1 }
```

```yaml schema id=mismatch-outcome
type: object
additionalProperties: false
required: [paymentId, resolution, note]
properties:
  paymentId: { type: string }
  resolution: { enum: [resent, explained, hold] }
  note: { type: string }
```

```yaml schema id=mismatch-outcomes
type: array
items:
  $ref: '#/schemas/mismatch-outcome'
```

```yaml schema id=summary-input
type: object
additionalProperties: false
required: [netCents, matchedCount, outcomes]
properties:
  netCents: { type: integer }
  matchedCount: { type: integer }
  outcomes:
    $ref: '#/schemas/mismatch-outcomes'
```

```yaml schema id=summary
type: object
additionalProperties: false
required: [releasePayout, payoutCents]
properties:
  releasePayout: { type: boolean }
  payoutCents: { type: integer }
```

```yaml schema id=payout-request
type: object
additionalProperties: false
required: [date, amountCents]
properties:
  date: { type: string }
  amountCents: { type: integer }
```

```yaml schema id=payout-result
type: object
additionalProperties: false
required: [payoutId]
properties:
  payoutId: { type: string }
```

### Secrets

```yaml secret id=policy-system-token
format: text
description: API token for the Northwind Mutual policy system
```

```yaml secret id=payments-token
format: text
description: API key for the payment processor
```

### Code

Match settled and recorded payments by payment ID.

```ts function id=match-payments input=comparison-input result=comparison
({ settled, recorded }) => {
  const dollars = (cents: number): string =>
    `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, '0')}`;
  let matchedCount = 0;
  const mismatches: Array<{
    paymentId: string;
    policyNumber: string;
    kind: 'not-recorded' | 'not-settled' | 'amount-differs';
    eventId: string | null;
    settledCents: number | null;
    settledAmount: string;
    recordedAmount: string;
  }> = [];
  for (let index = 0; index < settled.length; index += 1) {
    const payment = settled[index];
    const match = recorded.find((entry) => entry.paymentId === payment.paymentId);
    if (match !== undefined && match.amountCents === payment.amountCents) {
      matchedCount += 1;
      continue;
    }
    mismatches.push({
      paymentId: payment.paymentId,
      policyNumber: payment.policyNumber,
      kind: match === undefined ? 'not-recorded' : 'amount-differs',
      eventId: payment.eventId,
      settledCents: payment.amountCents,
      settledAmount: dollars(payment.amountCents),
      recordedAmount: match === undefined ? 'none' : dollars(match.amountCents),
    });
  }
  for (let index = 0; index < recorded.length; index += 1) {
    const entry = recorded[index];
    if (!settled.some((payment) => payment.paymentId === entry.paymentId)) {
      mismatches.push({
        paymentId: entry.paymentId,
        policyNumber: entry.policyNumber,
        kind: 'not-settled',
        eventId: null,
        settledCents: null,
        settledAmount: 'none',
        recordedAmount: dollars(entry.amountCents),
      });
    }
  }
  return { matchedCount, mismatches };
};
```

A resent payment is resolved only when the policy system recorded the amount
the processor settled.

```ts function id=compare-resent-amount input=resent-amount-input result=resent-amount-check
({ settledCents, recordedCents }) => {
  const dollars = (cents: number): string =>
    `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, '0')}`;
  if (settledCents === recordedCents) {
    return { matches: true, detail: `Recorded $${dollars(recordedCents)} as settled.` };
  }
  const recorded = `$${dollars(recordedCents)}`;
  const settled = settledCents === null ? 'nothing' : `$${dollars(settledCents)}`;
  return {
    matches: false,
    detail: `The policy system recorded ${recorded}, but the processor settled ${settled}.`,
  };
};
```

Pay out only when no mismatch is on hold.

```ts function id=summarize-reconciliation input=summary-input result=summary
({ netCents, outcomes }) => ({
  releasePayout: outcomes.every((outcome) => outcome.resolution !== 'hold'),
  payoutCents: netCents,
});
```

```ts effect id=get-settlement-report input=date-request result=settlement-report uses=fetch,secrets secrets=payments-token
async ({ date }, { fetch, secrets, signal, FatalError }) => {
  const key = await secrets.getText('payments-token');
  const response = await fetch(`https://api.payments.example/v1/settlements/${date}`, {
    headers: { Authorization: `Bearer ${key}` },
    signal,
  });
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`No settlement report for ${date} (${response.status}).`);
  }
  if (!response.ok) throw new Error(`Payment processor answered ${response.status}.`);
  const body = await response.json();
  if (
    typeof body !== 'object' ||
    body === null ||
    !('netCents' in body) ||
    typeof body.netCents !== 'number' ||
    !('payments' in body) ||
    !Array.isArray(body.payments)
  ) {
    throw new FatalError('The settlement report has an unexpected shape.');
  }
  const payments = [];
  for (let index = 0; index < body.payments.length; index += 1) {
    const line = body.payments[index];
    if (
      typeof line !== 'object' ||
      line === null ||
      !('id' in line) ||
      typeof line.id !== 'string' ||
      !('policyNumber' in line) ||
      typeof line.policyNumber !== 'string' ||
      !('amountCents' in line) ||
      typeof line.amountCents !== 'number' ||
      !('eventId' in line) ||
      typeof line.eventId !== 'string'
    ) {
      throw new FatalError('A settlement line has an unexpected shape.');
    }
    payments.push({
      paymentId: line.id,
      policyNumber: line.policyNumber,
      amountCents: line.amountCents,
      eventId: line.eventId,
    });
  }
  return { netCents: body.netCents, payments };
};
```

```ts effect id=get-recorded-payments input=date-request result=recorded-payments uses=fetch,secrets secrets=policy-system-token
async ({ date }, { fetch, secrets, signal, FatalError }) => {
  const token = await secrets.getText('policy-system-token');
  const response = await fetch(`https://policy.northwind.example/v1/payments?date=${date}`, {
    headers: { Authorization: `Bearer ${token}` },
    signal,
  });
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`The policy system refused the payments read (${response.status}).`);
  }
  if (!response.ok) throw new Error(`Policy system answered ${response.status}.`);
  const body = await response.json();
  if (
    typeof body !== 'object' ||
    body === null ||
    !('payments' in body) ||
    !Array.isArray(body.payments)
  ) {
    throw new FatalError('The payments list has an unexpected shape.');
  }
  const payments = [];
  for (let index = 0; index < body.payments.length; index += 1) {
    const entry = body.payments[index];
    if (
      typeof entry !== 'object' ||
      entry === null ||
      !('paymentId' in entry) ||
      typeof entry.paymentId !== 'string' ||
      !('policyNumber' in entry) ||
      typeof entry.policyNumber !== 'string' ||
      !('amountCents' in entry) ||
      typeof entry.amountCents !== 'number'
    ) {
      throw new FatalError('A recorded payment has an unexpected shape.');
    }
    payments.push({
      paymentId: entry.paymentId,
      policyNumber: entry.policyNumber,
      amountCents: entry.amountCents,
    });
  }
  return { payments };
};
```

A payment the policy system never recorded is explained when the processor's
last attempt to deliver its event failed. Anything else goes to a person.

```ts effect id=get-webhook-delivery input=webhook-request result=webhook-diagnosis uses=fetch,secrets secrets=payments-token
async ({ kind, eventId }, { fetch, secrets, signal, FatalError }) => {
  if (kind !== 'not-recorded' || eventId === null) {
    return { cause: 'unexplained', detail: `The two records disagree (${kind}).` };
  }
  const key = await secrets.getText('payments-token');
  const response = await fetch(`https://api.payments.example/v1/events/${eventId}/deliveries`, {
    headers: { Authorization: `Bearer ${key}` },
    signal,
  });
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`Event ${eventId} could not be read (${response.status}).`);
  }
  if (!response.ok) throw new Error(`Payment processor answered ${response.status}.`);
  const body = await response.json();
  if (
    typeof body !== 'object' ||
    body === null ||
    !('deliveries' in body) ||
    !Array.isArray(body.deliveries)
  ) {
    throw new FatalError('The delivery list has an unexpected shape.');
  }
  const last = body.deliveries[body.deliveries.length - 1];
  if (
    typeof last === 'object' &&
    last !== null &&
    'succeeded' in last &&
    last.succeeded === false &&
    'responseStatus' in last
  ) {
    return {
      cause: 'webhook-failed',
      detail: `Delivery of event ${eventId} failed with ${String(last.responseStatus)}.`,
    };
  }
  return {
    cause: 'unexplained',
    detail: `Event ${eventId} was delivered, but the policy system has no payment for it.`,
  };
};
```

Resending an event is safe to repeat: the policy system records a payment
once per event ID, however many times the event arrives.

```ts effect id=resend-webhook-event input=resend-request result=resend-result uses=fetch,secrets secrets=payments-token
async ({ eventId }, { fetch, secrets, signal, operation, FatalError }) => {
  if (eventId === null) throw new FatalError('There is no event to resend.');
  const key = await secrets.getText('payments-token');
  const response = await fetch(`https://api.payments.example/v1/events/${eventId}/resend`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${key}`, 'Idempotency-Key': operation.idempotencyKey },
    signal,
  });
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`The processor refused to resend ${eventId} (${response.status}).`);
  }
  if (!response.ok) throw new Error(`Payment processor answered ${response.status}.`);
  return { eventId };
};
```

```ts effect id=get-payment input=payment-request result=payment-status uses=fetch,secrets secrets=policy-system-token
async ({ paymentId }, { fetch, secrets, signal, FatalError }) => {
  const token = await secrets.getText('policy-system-token');
  const response = await fetch(`https://policy.northwind.example/v1/payments/${paymentId}`, {
    headers: { Authorization: `Bearer ${token}` },
    signal,
  });
  if (response.status === 404) return { status: 'not-found' };
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`The policy system refused the payment read (${response.status}).`);
  }
  if (!response.ok) throw new Error(`Policy system answered ${response.status}.`);
  const body = await response.json();
  if (
    typeof body !== 'object' ||
    body === null ||
    !('amountCents' in body) ||
    typeof body.amountCents !== 'number'
  ) {
    throw new FatalError('The payment has an unexpected shape.');
  }
  return { status: 'recorded', amountCents: body.amountCents };
};
```

```ts effect id=create-payout input=payout-request result=payout-result uses=fetch,secrets secrets=payments-token
async ({ date, amountCents }, { fetch, secrets, signal, FatalError }) => {
  const key = await secrets.getText('payments-token');
  const response = await fetch('https://api.payments.example/v1/payouts', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${key}`,
      'Content-Type': 'application/json',
      'Idempotency-Key': `payout-${date}`,
    },
    body: JSON.stringify({ amount: amountCents, currency: 'usd', settlementDate: date }),
    signal,
  });
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`The processor refused the payout (${response.status}).`);
  }
  if (!response.ok) throw new Error(`Payment processor answered ${response.status}.`);
  const body = await response.json();
  if (typeof body !== 'object' || body === null || !('id' in body) || typeof body.id !== 'string') {
    throw new FatalError('The processor did not return a payout ID.');
  }
  return { payoutId: body.id };
};
```
````

## How it works

### Input and output

The procedure takes one input, `settlement_date`, a `YYYY-MM-DD` date. Its output,
`reconciliation`, says whether the day was `paid-out` or `held`, how many payments matched, the
day's balance in `payoutCents`, and one outcome for each mismatch.

### Read both sides

`read-settlement` and `read-recorded-payments` are [`call`](https://docs.canary.effectiveai.app/procedures/reference/nodes/call)
nodes. Each runs a local effect, a `ts effect` you write and publish with the procedure. Each
effect declares the one secret it uses, `payments-token` or `policy-system-token`; the values are
never in the source. Both effects check the shape of what they read and return it in a fixed
shape, so the rest of the procedure works on typed data. See
[Functions and effects](https://docs.canary.effectiveai.app/procedures/reference/nodes/function-and-effect.md).

A 4xx answer other than `429` throws `FatalError` and fails the run at once, because another
attempt can't change it. A `429`, a 5xx answer or a network error throws an ordinary error, which
is retried. Reads change nothing, so retrying them is always safe.

When an effect fails the run, the run's `failure` names the step and its code, but not the
message the effect threw: Effective doesn't show thrown messages, because they could hold secret
values. Look in the system that answered for why it refused. Anything the procedure has to act on
belongs in a typed result instead, as `get-webhook-delivery` returns `cause`.

### Compare them

`compare-payments` calls `match-payments`, a pure `ts function`. It gets only its input, with no
network, secrets or clock, so the same two lists always give the same comparison. It matches
payments by ID and returns the count that matched, plus one entry for each mismatch:

* `not-recorded`: the processor settled the payment, but your policy system has no record of it.
* `amount-differs`: both have it, with different amounts.
* `not-settled`: your policy system recorded it, but it isn't in the settlement report.

Amounts stay in whole cents. Each mismatch carries the settled amount as `settledCents`, or
`null` when the processor didn't settle the payment. It also carries the two amounts as text, such
as `412.50`, for the person who may have to read them.

For the illustrative day, 2026-11-27, the processor settled four payments for \$922.75 in all. Your
policy system recorded three of them:

| Payment | Policy | Settled | Recorded |
| - | - | - | - |
| `pay_1001` | NW-100234 | \$184.00 | \$184.00 |
| `pay_1002` | NW-100517 | \$96.25 | \$96.25 |
| `pay_1003` | NW-100871 | \$412.50 | none |
| `pay_1004` | NW-101102 | \$230.00 | \$230.00 |

The comparison finds three matches and one mismatch: `pay_1003`, `not-recorded`, a \$412.50 gap.

### Investigate each mismatch

`investigate-mismatches` is a [`for-each`](https://docs.canary.effectiveai.app/procedures/reference/nodes/for-each). It runs the
nodes under **Investigate one mismatch** once for each entry in `comparison.mismatches`, with the
entry as `$mismatch`. Each item has its own names: a value one item binds is invisible to the
others.

`collect` gathers each item's `mismatch_outcome` into `outcomes`, in the order of the mismatches,
whatever order they finish in. Items run one at a time, because `concurrency` defaults to `1`.
With no mismatches, `outcomes` is empty and the run goes straight on.

A run that stops partway resumes at the item it was on. Items that already finished keep their
recorded results.

### Find the cause

For each mismatch, `check-webhook` asks the processor how it delivered the payment's event. The
`get-webhook-delivery` effect returns `webhook-failed` only for a `not-recorded` payment whose last
delivery to your policy system failed. Every other case is `unexplained`, with a `detail` line
saying what it found.

`route-cause` is a [`choice`](https://docs.canary.effectiveai.app/procedures/reference/nodes/choice) on `diagnosis.cause`, with a case
for each value. Its `outputs` declare `mismatch_outcome`, and each case's heading binds it, so the
item always ends with an outcome whichever way it went. That is what `collect` reads.

### Resend the event once

For `pay_1003`, the processor's delivery log shows that the event `evt_503` failed with a 503, so
the run takes **Resend the event**.

`resend-event` asks the processor to deliver the event again. The run records that the call
finished. If the run is interrupted and resumes later, it doesn't resend: it uses the recorded
result. That is the sense in which the event is resent once.

A retry is different. If the resend's reply is lost, the effect's default retry may send the
request again. That's safe here for two reasons: the effect passes `operation.idempotencyKey`,
which is the same on every attempt of this call, and your policy system records a payment once
per event ID. A second delivery of `evt_503` changes nothing. If your processor has no idempotency
key for resends, the event ID still protects you, as long as your policy system deduplicates on
it.

`confirm-recorded` is a polling [`wait`](https://docs.canary.effectiveai.app/procedures/reference/nodes/wait). It reads the payment
from your policy system every minute until `status` is `recorded`, for up to 30 minutes. If it's
still not recorded by then, the run fails before any payout. Its `failure.code` is `poll_timeout`,
and its message is `resent-payment-not-recorded`.
Someone then looks at why your policy system rejected the event.

A recorded payment isn't yet a resolved one: the policy system could record the resent event with
the wrong amount. `check-resent-amount` calls the pure function `compare-resent-amount`, which
compares the amount the policy system recorded, `recorded_payment.amountCents`, with the
mismatch's `settledCents`. It returns `matches`, and a `detail` line that gives both amounts when
they differ.

`route-resent-amount` is a choice on `resent_amount.matches`, nested in **Resend the event**. Its
cases claim the two headings under it, and it declares `mismatch_outcome` as its own output. When
it finishes, that output is the outcome the enclosing `route-cause` reads, so every path through
**Resend the event** still ends with an outcome:

* `'true'` runs `record-resend`, which binds `resolution: resent`.
* `'false'` runs `record-resent-hold`, which binds `resolution: hold`, with the two amounts in the
  note. The day's payout is held, as when finance answers `hold`.

A nested choice can only claim headings under its own section, so this path can't send the
mismatch to **Ask finance operations**. It holds the payout instead, and the run's outcomes show
which payment to look at.

### Ask a person about the rest

Suppose your policy system had recorded `pay_1004` as $220.00 instead of $230.00. That mismatch is
`amount-differs`, which the procedure can't explain, so the run takes **Ask finance operations**.

`explain-mismatch` is a [`task`](https://docs.canary.effectiveai.app/procedures/reference/nodes/task) for the `finance-operations`
group. Its instructions show both amounts and the procedure's finding. The person answers with a
`resolution`, `explained` or `hold`, and a note; the `mismatch-decision` schema requires both.
The run waits for the answer without holding anything. `record-explanation` binds the outcome from
the answer.

Only unexplained mismatches create a task. A day with nothing but failed webhooks needs no person.

### Pay out the balance

`summarize` calls the pure function `summarize-reconciliation`. It releases the payout only if no
outcome is `hold`. The payout is the settlement report's `netCents`: once every mismatch is
resent with the settled amount or explained, the two sides agree, and the processor's balance for
the day is the amount to pay out.

`route-payout` is a choice on `summary.releasePayout`:

* `'true'` runs **Release the payout**. `pay-out` asks the processor for the payout and the run
  completes with `status: paid-out` and the `payoutId`.
* `'false'` runs **Hold the payout**. The run completes with `status: held`. Nothing is paid out:
  `payoutCents` is the balance held back, not an amount paid. The outcomes show which mismatch is
  on hold and why.

The payout's key is built from the settlement date:

```ts theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
'Idempotency-Key': `payout-${date}`,
```

If the reply is lost and the effect runs again, the processor sees `payout-2026-11-27` again and
returns the payout it already made. The same is true across runs: if someone reconciles
2026-11-27 a second time, the second payout request gets the first payout back. A processor that
honours the key pays a day out once; one that ignores it can pay twice, which is why you check
this before you go live. If the second run asks for a different amount under the same key, a
processor that checks the payload refuses it, and the effect's `FatalError` fails the run instead
of paying. One that doesn't check returns the first payout, for the first amount, so if your
processor returns the payout's amount, compare it with `amountCents` and throw `FatalError` when
they differ.

## Try it as a draft

A draft runs source without publishing it. See
[Try a draft](https://docs.canary.effectiveai.app/guides/procedures.md#try-a-draft). A draft can't declare secrets, and
this procedure declares two, so sending `reconcile-payments.procedure.md` as a draft is refused
with `422 invalid_procedure` and no run starts.

To try the flow before you connect your systems, make a stand-in copy that runs without secrets.
Save it as `reconcile-payments.draft.procedure.md` and change three things:

1. Delete the two `yaml secret` blocks under **Secrets**.

2. Replace each `ts effect` with one that returns sample data and declares no `uses=` or
   `secrets=`. These two give the day from the table above, with `pay_1004` recorded as \$220.00
   so that you see both paths:

   ```ts effect id=get-settlement-report input=date-request result=settlement-report theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
   async (_input, _context) => ({
     netCents: 92275,
     payments: [
       { paymentId: 'pay_1001', policyNumber: 'NW-100234', amountCents: 18400, eventId: 'evt_501' },
       { paymentId: 'pay_1002', policyNumber: 'NW-100517', amountCents: 9625, eventId: 'evt_502' },
       { paymentId: 'pay_1003', policyNumber: 'NW-100871', amountCents: 41250, eventId: 'evt_503' },
       { paymentId: 'pay_1004', policyNumber: 'NW-101102', amountCents: 23000, eventId: 'evt_504' },
     ],
   });
   ```

   ```ts effect id=get-recorded-payments input=date-request result=recorded-payments theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
   async (_input, _context) => ({
     payments: [
       { paymentId: 'pay_1001', policyNumber: 'NW-100234', amountCents: 18400 },
       { paymentId: 'pay_1002', policyNumber: 'NW-100517', amountCents: 9625 },
       { paymentId: 'pay_1004', policyNumber: 'NW-101102', amountCents: 22000 },
     ],
   });
   ```

   For the others: `get-webhook-delivery` returns `webhook-failed` when `kind` is `not-recorded`
   and `unexplained` otherwise; `resend-webhook-event` returns `{ eventId: eventId ?? '' }`;
   `get-payment` returns `{ status: 'recorded', amountCents: 41250 }`; and `create-payout` returns
   `{ payoutId: 'po_test_1' }`.

3. Assign the task to yourself, so you can answer it:

   ```yaml theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
   assignees:
     - 'user:{{ $run.principal.id }}'
   ```

Keep the three functions and everything else as they are. Then start the draft:

```bash theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
curl --request POST \
  --url "https://api.canary.effectiveai.app/api/v2/procedures/runs" \
  --header "Authorization: Bearer $EFFECTIVE_API_KEY" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: reconcile-payments-draft-1" \
  --data "$(jq --null-input --rawfile source reconcile-payments.draft.procedure.md '{
    sourceName: "reconcile-payments.draft.procedure.md",
    source: $source,
    inputs: { settlement_date: "2026-11-27" }
  }')"
```

An illustrative response, abbreviated; your IDs differ:

```json theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
{
  "outcome": "started",
  "run": {
    "id": "2d9b7e14-6a3c-4f81-b5d2-8e0f1a2b3c4d",
    "procedureId": "reconcile-payments",
    "version": null,
    "draft": true,
    "status": "starting",
    "visibility": "private"
  }
}
```

The run resends `evt_503` for `pay_1003`, then stops at the task for `pay_1004`. Find the task with
`GET /procedures/tasks?status=open&assignedToMe=true` and answer it as in
[Answer a task](https://docs.canary.effectiveai.app/guides/procedures.md#answer-a-task), using the task ID from your own
list:

```bash theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
curl --request POST \
  --url "https://api.canary.effectiveai.app/api/v2/procedures/tasks/9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d/submissions" \
  --header "Authorization: Bearer $EFFECTIVE_API_KEY" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: explain-pay_1004-draft-1" \
  --data '{ "answer": { "resolution": "explained", "note": "Endorsement refund netted against the payment." } }'
```

Each edit to the draft needs a new `Idempotency-Key`.

## Check the result

Read the run with `GET /procedures/runs/{runId}` until `status` is `completed`. With the answer
above, `output` looks like this (illustrative):

```json theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
{
  "status": "completed",
  "output": {
    "reconciliation": {
      "date": "2026-11-27",
      "status": "paid-out",
      "matchedCount": 2,
      "payoutCents": 92275,
      "payoutId": "po_test_1",
      "outcomes": [
        { "paymentId": "pay_1003", "resolution": "resent", "note": "Resent webhook event evt_503" },
        {
          "paymentId": "pay_1004",
          "resolution": "explained",
          "note": "Endorsement refund netted against the payment."
        }
      ]
    }
  },
  "failure": null
}
```

Check that:

* `matchedCount` is `2` and `outcomes` has one entry per mismatch, in the order of the
  comparison: `pay_1003` first, then `pay_1004`.
* `pay_1003` was resent without a task. `tasks` lists only the task for `pay_1004`.
* Answering `hold` instead completes the run with `status: "held"` and no `payoutId`.
* With `pay_1004` recorded as \$230.00 in the stand-in, there is one mismatch, no task, and the run
  pays out on its own.
* With `get-payment` returning `amountCents: 40000` instead, the resent `pay_1003` doesn't match
  its settled \$412.50. Its outcome is `hold`, with both amounts in the note, and the run completes
  with `status: "held"` and no `payoutId`, whatever you answer for `pay_1004`.

## Run it against your systems

When the flow does what you want, publish the real `reconcile-payments.procedure.md`, as in
[Publish a version](https://docs.canary.effectiveai.app/guides/procedures.md#publish-a-version). Reading the version lists
the two secrets it needs under `secrets`. Before the first run, set their values on the
procedure's page in the Effective app, under **Secrets**: a shared default for every run, or a
personal override for the runs that run as you. See
[Give a secret a value](https://docs.canary.effectiveai.app/procedures/reference/nodes/secret.md#give-a-secret-a-value).

Try it on a test day first. If your processor and policy system have test environments, publish a
copy with its own `id`, such as `reconcile-payments-test`, whose effects call your test hosts, and
give that copy test credentials. Secrets are set for each procedure, so the copy's values don't
affect the real procedure's.

Then check what only your systems can show:

* After a resend, your policy system holds the missing payment once, with the settled amount.
* Run the same day again. The comparison should find no mismatch for the resent payment, and the
  processor should return the first payout's ID. If it makes a second payout, its payout endpoint
  isn't honoring the key; fix that before you go live.

Start the daily run from your own system after the processor publishes the day's report. Use a
run `Idempotency-Key` derived from the date, such as `reconcile-2026-11-27`, as in
[Start a run](https://docs.canary.effectiveai.app/guides/procedures.md#start-a-run).

## Next steps

* [Cancel a policy](https://docs.canary.effectiveai.app/procedures/tutorials/cancel-a-policy.md): an approval before three keyed writes,
  and a run that is safe to start again.
* [Writes to your systems](https://docs.canary.effectiveai.app/procedures/concepts/writes-to-your-systems.md): retries, idempotency keys
  and what to do when an endpoint has no key.
* [`for-each`](https://docs.canary.effectiveai.app/procedures/reference/nodes/for-each) and [`wait`](https://docs.canary.effectiveai.app/procedures/reference/nodes/wait):
  concurrency, collections, polling and timeouts.


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