# Payment Reconciliation

A `PaymentReconciliation` is a single payment recorded against an `Account`, and optionally allocated to one `Invoice`. It captures how much was paid, by what method, when, and by whom — mirroring the FHIR [`PaymentReconciliation`](https://build.fhir.org/paymentreconciliation.html) resource. Reach for it whenever you post a payment, refund, credit note, or adjustment to a patient or insurer account.

**Source:**

* Model: [`care/emr/models/payment_reconciliation.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/payment_reconciliation.py)
* Resource spec: [`care/emr/resources/payment_reconciliation/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/payment_reconciliation/spec.py)
* Viewset: [`care/emr/api/viewsets/payment_reconciliation.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/payment_reconciliation.py)

The model is thin storage: enum-constrained fields are plain `CharField`s and `extensions` is an opaque `JSONField`. The behaviour you integrate against — enum constraints, amount computation, validation, and the read/write schema split — lives in the Pydantic resource specs (`care/emr/resources/payment_reconciliation/spec.py`), built on `EMRResource`.

## Models

| Model | Purpose |
| - | - |
| `PaymentReconciliation` | A single payment (or credit note / adjustment) recorded against an account or invoice |

The model extends `EMRBaseModel`, the shared Care EMR base supplying `external_id`, audit fields, and soft-delete semantics — see [Base model](https://docs.ohc.network/references/foundation/base-model.md).

## `PaymentReconciliation` fields

### Relationships

| Field | Type | Notes |
| - | - | - |
| `facility` | `FK → Facility` (PROTECT) | Facility where the payment is recorded. Set server-side from the URL on create |
| `target_invoice` | `FK → Invoice` (PROTECT) | The invoice this payment is allocated to. Nullable (`default=None`); one allocation per record. On create, pass the invoice `external_id` (UUID); the invoice must belong to `account` and to the URL facility. Not writable on update |
| `account` | `FK → Account` (PROTECT) | The account being paid. Required even when `target_invoice` is set. On create, pass the account `external_id` (UUID); the account must belong to the URL facility. Not writable on update — use `change_account` |
| `location` | `FK → FacilityLocation` (PROTECT) | Physical location (e.g. the counter) where payment was taken. Nullable. On create, pass the location `external_id` (UUID); the location must belong to the URL facility, and the user needs `can_list_facility_location_obj` on it. Not writable on update |

### Classification

Six columns map to fixed enums defined in the resource spec. Each is stored as a free-form `CharField(100)`; the enum is enforced at the schema/API layer, not by the database. Full value lists are under [enum values](#enum-values).

| Field | Type | Spec enum | Notes |
| - | - | - | - |
| `reconciliation_type` | `CharField(100)` | `PaymentReconciliationTypeOptions` | Required. `payment` \| `adjustment` \| `advance` |
| `status` | `CharField(100)` | `PaymentReconciliationStatusOptions` | Required. `active` \| `cancelled` \| `draft` \| `entered_in_error` |
| `kind` | `CharField(100)` | `PaymentReconciliationKindOptions` | Required. `deposit` \| `periodic_payment` \| `online` \| `kiosk` |
| `issuer_type` | `CharField(100)` | `PaymentReconciliationIssuerTypeOptions` | Required. Who paid — `patient` \| `insurer` |
| `outcome` | `CharField(100)` | `PaymentReconciliationOutcomeOptions` | Required. `queued` \| `complete` \| `error` \| `partial` |
| `method` | `CharField(100)` | `PaymentReconciliationPaymentMethodOptions` | Required. HL7 [v2-0570](https://terminology.hl7.org/6.2.0/ValueSet-v2-0570.html) payment-method codes — `cash` \| `ccca` \| `cchk` \| `cdac` \| `chck` \| `ddpo` \| `debc` |

### Payment details

| Field | Type | Notes |
| - | - | - |
| `payment_datetime` | `DateTimeField` → `datetime \| None` | When the payment was issued. Optional (default `None`) |
| `reference_number` | `CharField(1024)` → `str \| None` | Cheque number or payment reference. Optional |
| `authorization` | `CharField(1024)` → `str \| None` | Authorization number. Optional |
| `disposition` | `TextField` → `str \| None` | Message describing the outcome. Optional |
| `note` | `TextField` → `str \| None` | Free-text note. Optional |

### Amounts

Every amount is a `DecimalField(max_digits=20, decimal_places=6)`. Six decimal places allow sub-currency precision.

| Field | Type | Notes |
| - | - | - |
| `tendered_amount` | `Decimal(20, 6)` | Required on create; not writable on update. Amount offered by the issuer |
| `returned_amount` | `Decimal(20, 6)` | Required on create; not writable on update. Amount returned to the issuer (e.g. change). Must be strictly less than `tendered_amount`, or the create is rejected |
| `amount` | `Decimal(20, 6)` | Net payment, computed server-side on create as `tendered_amount - returned_amount`. A client-supplied value is always overwritten |

### Flags & extensions

| Field | Type | Notes |
| - | - | - |
| `is_credit_note` | `BooleanField` → `bool` | Default `False`. Create only. Marks the record as a credit note rather than an inbound payment. Account sync subtracts credit notes from `total_paid` |
| `extensions` | `JSONField` → `dict` | Default `{}`. Open extension bag, writable on create only. Each key is validated against the registered handler for resource type `payment_reconciliation` — unknown keys are currently dropped. Retrieve returns the stored dict as-is |

## Enum values

All enums are `str, Enum` classes in [`spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/payment_reconciliation/spec.py).

### `PaymentReconciliationTypeOptions` (`reconciliation_type`)

| Value |
| - |
| `payment` |
| `adjustment` |
| `advance` |

### `PaymentReconciliationStatusOptions` (`status`)

| Value |
| - |
| `active` |
| `cancelled` |
| `draft` |
| `entered_in_error` |

Only records with `status = active` and `outcome = complete` count toward the account's `total_paid`. Move a record to `cancelled` or `entered_in_error` only through the `cancel_payment_reconciliation` action.

### `PaymentReconciliationKindOptions` (`kind`)

| Value |
| - |
| `deposit` |
| `periodic_payment` |
| `online` |
| `kiosk` |

### `PaymentReconciliationIssuerTypeOptions` (`issuer_type`)

| Value |
| - |
| `patient` |
| `insurer` |

### `PaymentReconciliationOutcomeOptions` (`outcome`)

| Value |
| - |
| `queued` |
| `complete` |
| `error` |
| `partial` |

### `PaymentReconciliationPaymentMethodOptions` (`method`)

HL7 v2-0570 payment-method codes.

| Value | HL7 meaning |
| - | - |
| `cash` | Cash |
| `ccca` | Credit card |
| `cchk` | Cashier's check |
| `cdac` | Credit/debit account |
| `chck` | Check |
| `ddpo` | Direct deposit |
| `debc` | Debit card |

## Resource specs (API schema)

Defined in [`care/emr/resources/payment_reconciliation/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/payment_reconciliation/spec.py). All extend `EMRResource` (`serialize` / `de_serialize`, with `perform_extra_serialization` / `perform_extra_deserialization` hooks). See [Base model](https://docs.ohc.network/references/foundation/base-model.md).

| Spec class | Role | Notes |
| - | - | - |
| `BasePaymentReconciliationSpec` | shared base · write · update | Holds `id`, the six enum fields, `disposition`, `payment_datetime`, `method`, `reference_number`, `authorization`, `note`. `__exclude__ = ["target_invoice", "account"]` (FKs handled in hooks). `___extension_resource_type__ = payment_reconciliation`. The viewset uses it as the update schema, so an update changes only these fields |
| `PaymentReconciliationWriteSpec` | write · create | Adds `target_invoice` (UUID, optional), `account` (UUID, required), `tendered_amount`, `returned_amount`, `amount` (optional), `is_credit_note` (default `False`), `location` (UUID, optional). Mixes in `ExtensionValidator` |
| `PaymentReconciliationMinimalReadSpec` | read · base | Adds `amount`, `tendered_amount`, `returned_amount`, `is_credit_note`, `created_date`, `modified_date`. Base class of the read specs; the viewset does not return it directly |
| `PaymentReconciliationReadSpec` | read · list | Extends minimal read; adds `account: dict` (serialized via `AccountReadSpec`) and `target_invoice: dict \| None` (serialized via `InvoiceReadSpec`). Also the response of `cancel_payment_reconciliation` |
| `PaymentReconciliationRetrieveSpec` | read · detail | Extends read; adds `location: dict \| None` (via `FacilityLocationListSpec`), `extensions: dict`, `created_by` / `updated_by`. Also injects `account.patient` via `PatientRetrieveSpec`. The response of retrieve, create, and update |

### Write validation & side effects

`PaymentReconciliationWriteSpec` is the create schema. It runs three steps:

* The amount validator (`model_validator(mode="after")`, `check_amount_or_factor`) raises `"Returned amount cannot be greater than tendered amount"` when `returned_amount >= tendered_amount`, then sets `amount = tendered_amount - returned_amount`. The spec's `amount` field is advisory and always recomputed.

* `perform_extra_deserialization(is_update, obj)` resolves the FK UUIDs to model instances:

  <!-- -->

  * `target_invoice` (if provided) → `Invoice.objects.get(external_id=...)`
  * `account` (required) → `Account.objects.get(external_id=...)`
  * `location` (if provided) → `FacilityLocation.objects.get(external_id=...)`

* `ExtensionValidator.validate_extensions` checks `extensions` against the `payment_reconciliation` extension registry before save.

### Read serialization side effects

* `PaymentReconciliationMinimalReadSpec.perform_extra_serialization` maps `id` ← `obj.external_id`.
* `PaymentReconciliationReadSpec` serializes the related `account` (`AccountReadSpec`) and, when present, `target_invoice` (`InvoiceReadSpec`) into nested objects.
* `PaymentReconciliationRetrieveSpec` additionally nests the account's `patient` (`PatientRetrieveSpec`, scoped to the account's facility), the `location` (`FacilityLocationListSpec`), the raw `extensions`, and audit users (`created_by` / `updated_by` via `serialize_audit_users`).

## Related models

`PaymentReconciliation` is self-contained; its foreign keys reach into the billing and facility domains:

```
facility       → FK Facility (PROTECT)

target_invoice → FK Invoice (PROTECT, nullable)

account        → FK Account (PROTECT)

location       → FK FacilityLocation (PROTECT, nullable)
```

Each foreign key uses `on_delete=PROTECT`, so a payment record blocks deletion of the facility, invoice, account, or location it references.

## Methods & save behaviour

`PaymentReconciliation` defines no custom `save()`; it inherits `EMRBaseModel` behaviour (audit fields, `external_id`, soft delete). The write spec and the viewset hold the behaviour:

* `amount` is derived, not stored as sent. On create the write spec computes `amount = tendered_amount - returned_amount` and rejects `returned_amount >= tendered_amount`. Update cannot change any amount.
* FK resolution happens in `perform_extra_deserialization`: `external_id` UUIDs for `account`, `target_invoice`, and `location` resolve to instances at de-serialization time.
* `extensions` are validated against the `payment_reconciliation` registry on create. Retrieve returns the stored value without handler rendering.
* **Account rebalance**: create, update, `cancel_payment_reconciliation`, and `change_account` each run `rebalance_account_task` inline for the affected accounts (see [Account balance sync](https://docs.ohc.network/references/billing/account.md#balance-sync)).
* **Update guards** (`validate_data`): an update cannot move `status` into `cancelled` or `entered_in_error` (`"Cannot update payment reconciliation, use the cancel endpoint instead"`). A record already in either status cannot change status.
* **Update locking** (`handle_update`): every update runs inside `AccountLock` on the record's account and re-reads the record. If the record moved to another account meanwhile, the update fails with `ObjectLocked` (HTTP 423).
* **Cancel (`POST cancel_payment_reconciliation`, detail route)**: the body is `{ "reason": "cancelled" | "entered_in_error" }`. Within `PAYMENT_RECONCILIATION_FREE_CANCEL_PERIOD_MINUTES` of creation (default `0`), write permission is enough. After that the user needs `can_destroy_payment_reconciliation_in_facility`. The action sets `status` to the reason under `AccountLock` and rebalances the account.
* **Change account (`POST change_account`, list route)**: moves 1 to 100 records to a target account in the facility. Each record must be `active` or `draft` and have no `target_invoice`. It locks every affected account, saves the records, and rebalances each account. It returns HTTP 201.

## API integration notes

* Create uses `PaymentReconciliationWriteSpec`; update uses `BasePaymentReconciliationSpec`. List responses use `PaymentReconciliationReadSpec`; retrieve, create, and update responses use `PaymentReconciliationRetrieveSpec`.
* The viewset scopes every query to the facility in the URL. It checks `can_read_payment_reconciliation_in_facility` for reads and `can_write_payment_reconciliation_in_facility` for create, update, and `change_account`.
* `account` is always required on create; `target_invoice` is optional and allocates the payment to one invoice. Pass `account`, `target_invoice`, and `location` as `external_id` UUIDs.
* The Pydantic schema constrains the six classification fields (`reconciliation_type`, `status`, `kind`, `issuer_type`, `outcome`, `method`) to the enums above and rejects invalid values, even though each column is a plain `CharField`.
* On create, send `tendered_amount` and `returned_amount` (both required); the server derives `amount`, so any value you send for it is ignored.
* `extensions` holds custom key-value data without a schema migration, validated against registered handlers on create.

## Related

* Reference: [Account](https://docs.ohc.network/references/billing/account.md)
* Reference: [Invoice](https://docs.ohc.network/references/billing/invoice.md)
* Reference: [Charge item](https://docs.ohc.network/references/billing/charge-item.md)
* Reference: [Base model](https://docs.ohc.network/references/foundation/base-model.md)
* Source (model): [payment\_reconciliation.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/payment_reconciliation.py)
* Source (spec): [payment\_reconciliation/spec.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/payment_reconciliation/spec.py)
