# Prepaid API (TSHIRTORDER-1668)

A channel can pay in advance. Money is added to the channel's prepaid total, and each new order is deducted from it. This document covers how to read the balance, add money and list the deducted orders.

| Method | URL | Purpose |
|---|---|---|
| `GET` | `/api/v1/channels/{id}` | Read the balance, settings and history |
| `POST` | `/api/v1/channels/{id}` | Turn prepaid on or off |
| `POST` | `/api/v1/channels/{id}/get-prepaid-current-sum` | **Add money** and change settings |
| `GET` | `/api/v1/channels/{id}/prepaid-orders` | List the deducted orders |

| | |
|---|---|
| **Auth** | `Authorization: Bearer <access token>` (32 chars, `[0-9a-z]`) |
| **Content-Type** | `application/json` (form-data / x-www-form-urlencoded also accepted) |
| **Controller** | `ChannelController` → `OrderService` / `ChannelService` |

General channel fields: [channel-api.md](channel-api.md).

## Authentication and access

- Missing / malformed / unknown / expired token → `401 {"message": "Invalid token authorization"}`.
- A token flagged `lockForOnlyIntegration` is **rejected** by these endpoints.
- `GET /prepaid-orders`: a `ROLE_CHANNEL` guest account only gets channels linked to the account, and only when the channel has `guestLoginShowPrepaid = true`. Otherwise `403`. A removed link (`dateDeleted` set) does not count.
- `{id}` must be a number. Otherwise the server answers with a Symfony `404` "No route found" instead of a JSON body.
- `POST /get-prepaid-current-sum` and `POST /channels/{id}`: a `ROLE_CHANNEL` guest account gets `403 {"message": "Not allowed"}`.
- `GET /channels/{id}`: a guest account only gets channels linked to the account. See [channel-api.md](channel-api.md).

## How the balance is calculated

```
prepaidCurrentSum = prepaidSum − deducted orders + credits
```

All amounts include moms and are rounded to 2 decimals.

| Part | Rule |
|---|---|
| `prepaidSum` | Total money added |
| Deducted orders | `totalSum + totalTax` of orders in the channel that are not deleted, not cancelled, and have `dateOrder` **after the end of the `prepaidDate` day** (`prepaidDate` + 23:59:59). Other order statuses do not matter |
| Credits | Credits in the channel that are not deleted, where the credited order is after the same date. A credit with no order counts by its `dateCreated` |

Prepaid only applies when **both** are true: `prepaidActive = true` and `prepaidDate` is set. Otherwise nothing is deducted.

The balance can go **negative**. Orders are never blocked when the prepaid runs out.

---

## Read the balance, settings and history

`GET /api/v1/channels/{id}`

| Field | Type | Notes |
|---|---|---|
| `prepaidActive` | bool | Prepaid on or off |
| `prepaidDate` | datetime \| null | Orders after the end of this day are deducted. The time part is not used |
| `prepaidSum` | number \| null | Total money added |
| `prepaidWatcherLevel` | number \| null | Low balance limit |
| `prepaidCurrentSum` | number \| null | Current balance when prepaid applies. ⚠️ Otherwise the last saved value, which can be out of date |
| `prepaidLow` | bool | `prepaidCurrentSum` is below `prepaidWatcherLevel`. Always `false` when prepaid does not apply |
| `guestLoginShowPrepaid` | bool | Show prepaid to `ROLE_CHANNEL` guest accounts |
| `prepaidLogs` | array | History, newest first |

### `prepaidLogs[]`

| Field | Type | Notes |
|---|---|---|
| `id` | int | |
| `amount` | number \| null | Amount added. `0` = only the settings changed |
| `paymentId` | string \| null | |
| `prepaidSum` | number | Total **after** this change |
| `prepaidWatcherLevel` | number | |
| `prepaidCurrentSum` | number | Balance at that moment |
| `prepaidDate` | datetime \| null | |
| `dateCreated` | datetime \| null | Older rows can be `null` |

---

## Turn prepaid on or off

`POST /api/v1/channels/{id}`

```json
{ "prepaidActive": true }
```

Remember to also set `prepaidDate`, using the endpoint below. Without it nothing is deducted.

---

## Add money

`POST /api/v1/channels/{id}/get-prepaid-current-sum`

⚠️ Despite the name, this endpoint **changes data**. Each call with an `amount` adds to the total.

### Request body

All fields are optional.

| Field | Type | Notes |
|---|---|---|
| `amount` | number | Added to `prepaidSum`, incl. moms. Negative to correct a mistake. Empty or `0` adds nothing |
| `paymentId` | string | Free text such as a bank reference. Only saved when a log row is written |
| `prepaidWatcherLevel` | number | New low balance limit |
| `prepaidDateString` | string | Format `Y-m-d H:i:s`. An empty string clears the date, and prepaid then stops applying |

`prepaidSum` in the body is ignored: you send the amount to add, never the new total.

### Example

```http
POST /api/v1/channels/101/get-prepaid-current-sum
Authorization: Bearer 0123456789abcdef0123456789abcdef
Content-Type: application/json

{
  "amount": 5000,
  "paymentId": "BANK-2026-0042",
  "prepaidWatcherLevel": 1000,
  "prepaidDateString": "2026-07-03 00:00:00"
}
```

### 200 OK

```json
{
  "current_prepaid_sum": 13750,
  "channel_prepaid_sum": 15000,
  "order_sum": 1000,
  "order_tax": 250,
  "total_credited": 0,
  "prepaid_low": false
}
```

| Field | Notes |
|---|---|
| `current_prepaid_sum` | Balance now. Equals `channel_prepaid_sum` when prepaid does not apply |
| `channel_prepaid_sum` | Total money added |
| `order_sum`, `order_tax` | Deducted orders, excl. moms and moms. `0` when prepaid does not apply |
| `total_credited` | Credits added back. `0` when prepaid does not apply |
| `prepaid_low` | Balance is below the low balance limit |

A row is added to `prepaidLogs` only when `amount` is not 0, `prepaidWatcherLevel` changed, or the `prepaidDate` day changed.

### Errors

| Status | Body | Cause |
|---|---|---|
| 400 | `{"message": "prepaidDateString wrong format (Y-m-d H:i:s)"}` | Bad date. Nothing is saved, including `amount` |
| 401 | `{"message": "Invalid token authorization"}` | Bad token |
| 403 | `{"message": "Not allowed"}` | Guest account |
| 404 | `{"message": "Channel was not found"}` | Unknown channel |
| 500 | `{"message": "<exception message>"}` | Unexpected error |

---

## List the deducted orders

`GET /api/v1/channels/{id}/prepaid-orders`

Read only: writes nothing and sends no e-mail.

### Query parameters

| Param | Type | Notes |
|---|---|---|
| `limit` | int | Default `50`, from 1 to `500` |
| `offset` | int | Default `0` |

### 200 OK

Sorted by `dateOrder`, newest first.

```json
{
  "prepaidActive": true,
  "prepaidDate": "2026-07-03T02:30:00+02:00",
  "prepaidSum": 7000,
  "prepaidWatcherLevel": 0,
  "prepaidCurrentSum": -2745,
  "prepaidLow": true,
  "totalDeducted": 9745,
  "totalCredited": 0,
  "total": 35,
  "items": [
    {
      "orderId": 1001,
      "orderNr": "1001",
      "orderCountNr": 5001,
      "customerName": "ACME AB",
      "dateOrder": "2026-10-07T08:31:40+02:00",
      "totalSum": 117,
      "totalTax": 29.25,
      "deductedSum": 146.25
    }
  ]
}
```

- `total`, `totalDeducted` and `totalCredited` cover **all** matching orders, not only the current page.
- When prepaid does not apply: `items` is empty, the totals are `0` and `prepaidCurrentSum` equals `prepaidSum`.

### Errors

| Status | Body | Cause |
|---|---|---|
| 401 | `{"message": "Invalid token authorization"}` | Bad token |
| 403 | `{"message": "User not allow to view prepaid of channel <name>"}` | Guest account without access |
| 404 | `{"message": "Channel was not found"}` | Unknown channel |
| 500 | `{"message": "<exception message>"}` | Unexpected error |

---

## Related: prepaid on orders and invoices

Every order and invoice response also has these fields:

| Field | Type | Notes |
|---|---|---|
| `prepaidActive` | bool | Prepaid applies to the channel. ⚠️ Also `false` when the channel has it on but no `prepaidDate` |
| `prepaidCurrentSum` | number \| null | Balance of the **channel**, not the amount of this order or invoice. `null` when `prepaidActive = false` |
| `prepaidLow` | bool | Balance is below the low balance limit |
| `prepaidExcluded` | bool | Date is on or before the `prepaidDate` day, so it is not deducted. Uses `dateOrder` for orders and `dateInvoice` for invoices |
| `prepaidGuestVisible` | bool | Same as `guestLoginShowPrepaid` |

Effects on orders:

- An order deducted from prepaid gets the `Förskott` payment type (`uniqueKey = order_payment_type_prepaid`).
- Changing `paymentTypeId` on such an order returns `400 {"message": "Payment type cannot be changed on an order paid by prepaid"}`.

Prepaid is information only on invoices: it does not change the paid amount or the payment status.

## Low balance e-mail

No endpoint sends this e-mail. The cronjob `cronjob:channel-prepaid-watcher` runs once a day, saves the current balance on each channel with prepaid on, and e-mails the admin while the balance is below `prepaidWatcherLevel`.

## Gotchas

- **Adding money is not safe to retry.** There is no duplicate check on `paymentId`, so calling twice adds the amount twice. Check `prepaidLogs` before retrying after a timeout, and undo a mistake with a negative `amount`.
- **Use a dot for decimals.** The string `"1500,50"` is read as `1500`, and text such as `"abc"` is read as `0` and adds nothing. Neither returns an error. Compare `channel_prepaid_sum` with what you expected.
- **`amount` is added even when `prepaidActive = false`.**
- **`POST /channels/{id}` changes settings without a log row.** It also accepts `prepaidWatcherLevel` and `prepaidDateString`, and it does not report an invalid date. Use `get-prepaid-current-sum` for these so every change is traced.
- **Changing `prepaidDate` recalculates everything.** A new date changes which orders count, so the balance can jump.
- **A date change within the same day** is saved, but no log row is written.
- **`prepaidExcluded = false` does not always mean deducted.** A cancelled order after the date is not deducted, but still returns `false`.
- **Deleted channels:** unlike `GET /channels/{id}`, the two prepaid endpoints also accept a soft-deleted channel.
- **The two `404` messages differ:** `Channel not found` on channel endpoints and `Channel was not found` on the prepaid endpoints. Check the status code, not the text.

## Related files

| File | Purpose |
|---|---|
| `src/Application/ApiBundle/Resources/config/route/channel.yaml` | Route definitions |
| `src/Application/ApiBundle/Controller/ChannelController.php` | `getPrepaidCurrentSum()`, `getPrepaidOrders()` |
| `src/Service/OrderService.php` | `getChannelPrepaidCurrentSum()`, `getChannelPrepaidOrders()`, `calculatePrepaidBalance()`, `generatePrepaidFields()`, `isDeductedFromPrepaid()` |
| `src/Service/ChannelService.php` | `generateItem()`: prepaid fields on the channel |
| `src/Repository/OrderRepository.php` | `getPrepaidOrderSum()`, `getPrepaidOrders()`, `applyPrepaidOrderCriteria()` |
| `src/Repository/CreditRepository.php` | `getPrepaidCreditSum()` |
| `src/Entity/ChannelPrepaidLog.php` | History rows |
| `src/Command/Cronjob/ChannelPrepaidWatcherCommand.php` | Daily low balance e-mail |
