# `Discount`

An amount off a price or a percentage off it, a choice: `money.apply_discount` takes one off a `Price`. An amount off is never below 0, and a percentage off is from 0% to 100%.

[Money and banking](types.md#money-and-banking); not ordered; since Jadpo 0.1.0.

## Make one

Pick one of its variants and give its fields, `Discount.amount_off { amount: ... }`.

## Variants

| Variant | Fields |
|---|---|
| `amount_off` | `amount`: [`Money`](type-money.md) |
| `percentage_off` | `percentage`: [`Percentage`](type-percentage.md) |

## Text, JSON and storage

It has no single text form, so `text.from` and `text.parse` don't take it. JSON sends an object of its variant's name, as `tag`, and the variant's fields.

| JSON |
|---|
| `{"tag":"amount_off","amount":{"amount":500,"currency":"GBP"}}` |
| `{"tag":"percentage_off","percentage":"20%"}` |
| `{"tag":"percentage_off","percentage":"12.5%"}` |

It is stored in 4 columns, each named for the field, `_` and its suffix. This is `{"tag":"percentage_off","percentage":"20%"}`:

| Column | Type | Holds |
|---|---|---|
| `<field>_kind` | `text` | `'percentage_off'` |
| `<field>_amount` | `bigint` | `NULL::bigint` |
| `<field>_currency` | `char(3)` | `NULL::text` |
| `<field>_percentage` | `numeric` | `0.20` |

## Shown to people

`text.format(value, locale:)` shows it to people in their locale.

With `locale: Locale.en_gb`:

| Value | Shown |
|---|---|
| `{"tag":"amount_off","amount":{"amount":500,"currency":"GBP"}}` | `£5.00` |
| `{"tag":"percentage_off","percentage":"20%"}` | `20%` |
| `{"tag":"percentage_off","percentage":"12.5%"}` | `12.5%` |

## Operations

- `money.apply_discount(price: Price, discount: Discount) -> Price`: `price` with `discount` taken off its amount, keeping whether it includes tax: an amount off in the price's currency, or that percentage of the amount, rounded half to even to a minor unit, so 15% off £10.05 is £1.51 off. More off than the price leaves nothing. It fails with `currency_mismatch` for an amount off in another currency.

Like every standard type, it also has the contract's own operations: `text.format`, `json.read`, `json.write` and `==`. It isn't ordered, so `<` and sorting don't take it. [Every standard type meets one contract](../topics/every-standard-type-meets-one-contract.md) says how they work.
