# Set a spending limit

The person approves an amount per month once; the SDK keeps the total and refuses what goes over.

| | |
|---|---|
| Level | 1: A person approves with a passkey. |
| Class | `write`: Something changes and can be undone. The approval can be reused. |

## What the test proves

- the person approves up to 100 EUR per month, and a first order of 60: 201
- 40.01 more is refused, 40.00 passes without asking, then not one cent more
- another currency is refused, with room left under the limit
- over the limit, the agent asks again: a new approval has its own total

## Python

```python
routes.append(route("POST", "/orders", "orders:place", cls="write", level=1, resource="order:new",
                    amount_field="/total", summary="Place an order",
                    body={"total": "a decimal string, e.g. 60.00", "currency": "e.g. EUR"}))
templates["orders:place"] = "Order for up to {amount.max} {amount.currency} per {amount.per}"


@app.post("/orders")
def place_order():
    # The SDK keeps the total of the period: an order over the limit the person approved never gets here.
    order = request.json
    return {"ordered": order["total"], "currency": order["currency"]}, 201
```

## JavaScript

```js
routes.push(route("POST", "/orders", "orders:place", {
  class: "write", level: 1, resource: "order:new", amountField: "/total", summary: "Place an order",
  body: { total: "a decimal string, e.g. 60.00", currency: "e.g. EUR" },
}));
templates["orders:place"] = "Order for up to {amount.max} {amount.currency} per {amount.per}";

api.post("/orders", (req, res) => {
  // The SDK keeps the total of the period: an order over the limit the person approved never gets here.
  const { total, currency } = req.body;
  res.status(201).json({ ordered: total, currency });
});
```

## Go

```go
routes = append(routes, allowedby.Route{Method: "POST", Path: "/orders", Capability: "orders:place",
	Class: allowedby.Write, Level: 1, Resource: "order:new", AmountField: "/total", Summary: "Place an order",
	Body: map[string]string{"total": "a decimal string, e.g. 60.00", "currency": "e.g. EUR"}})
templates["orders:place"] = allowedby.Text("Order for up to {amount.max} {amount.currency} per {amount.per}")

mux.HandleFunc("POST /orders", func(w http.ResponseWriter, r *http.Request) {
	// The SDK keeps the total of the period: an order over the limit the person approved never gets here.
	var order struct{ Total, Currency string }
	if err := json.NewDecoder(r.Body).Decode(&order); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "total, currency: strings"})
		return
	}
	writeJSON(w, http.StatusCreated, map[string]string{"ordered": order.Total, "currency": order.Currency})
})
```

## Java

```java
@Bean
AllowedByCustomizer spendLimit() {
    return aby -> aby
            .route(Route.post("/orders").capability("orders:place").actionClass(ActionClass.WRITE).level(1)
                    .resource("order:new").amountField("/total").summary("Place an order")
                    .body(Map.of("total", "a decimal string, e.g. 60.00", "currency", "e.g. EUR")))
            .template("orders:place", "Order for up to {amount.max} {amount.currency} per {amount.per}");
}

@PostMapping("/orders")
@ResponseStatus(HttpStatus.CREATED)
Map<String, String> placeOrder(@RequestBody Order order) {
    // The SDK keeps the total of the period: an order over the limit the person approved never gets here.
    return Map.of("ordered", order.total(), "currency", order.currency());
}
```

## C#

```dotnet
routes.Add(Route("POST", "/orders", "orders:place", cls: "write", level: 1, resource: "order:new",
    amountField: "/total", summary: "Place an order",
    body: new Dictionary<string, string> { ["total"] = "a decimal string, e.g. 60.00", ["currency"] = "e.g. EUR" }));
templates["orders:place"] = "Order for up to {amount.max} {amount.currency} per {amount.per}";

app.MapPost("/orders", (Order order) =>
    // The SDK keeps the total of the period: an order over the limit the person approved never gets here.
    Results.Json(new { ordered = order.Total, currency = order.Currency }, statusCode: 201));
```

## PHP

```php
$routes[] = route('POST', '/orders', 'orders:place', class: 'write', level: 1, resource: 'order:new',
    amountField: '/total', summary: 'Place an order',
    body: ['total' => 'a decimal string, e.g. 60.00', 'currency' => 'e.g. EUR']);
$templates['orders:place'] = 'Order for up to {amount.max} {amount.currency} per {amount.per}';

$app->post('/orders', function (Request $request, Response $response) use ($json) {
    // The SDK keeps the total of the period: an order over the limit the person approved never gets here.
    $order = json_decode((string) $request->getBody(), true);

    return $json($response, ['ordered' => $order['total'], 'currency' => $order['currency']], 201);
});
```

## Ruby

```ruby
ROUTES << AllowedBy.route(
  "POST", "/orders", "orders:place",
  class: "write", level: 1, resource: "order:new", amount_field: "/total", summary: "Place an order",
  body: { total: "a decimal string, e.g. 60.00", currency: "e.g. EUR" }
)
TEMPLATES["orders:place"] = "Order for up to {amount.max} {amount.currency} per {amount.per}"

post "/orders" do
  # The SDK keeps the total of the period: an order over the limit the person approved never gets here.
  order = JSON.parse(request.body.read)
  [201, { ordered: order["total"], currency: order["currency"] }.to_json]
end
```

## Rust

```rust
let aby = aby
    .route(
        Route::post("/orders")
            .capability("orders:place")
            .class(Class::Write)
            .level(1)
            .resource("order:new")
            .amount_field("/total")
            .summary("Place an order")
            .body_field("total", "a decimal string, e.g. 60.00")
            .body_field("currency", "e.g. EUR"),
    )
    .template("orders:place", "Order for up to {amount.max} {amount.currency} per {amount.per}");
let app = app.route("/orders", post(place_order));

async fn place_order(Json(order): Json<Order>) -> (StatusCode, Json<Value>) {
    // The SDK keeps the total of the period: an order over the limit the person approved never gets here.
    (StatusCode::CREATED, Json(json!({"ordered": order.total, "currency": order.currency})))
}
```
