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

# Credit Consumption

> Understand how credits are consumed against invoices and usage

# Credit Consumption

Credits are automatically consumed when invoices are generated or usage events occur. This guide explains the consumption mechanics and how to track credit usage.

***

## How Credits Are Consumed

### Monetary Credits

Monetary credits are applied when an invoice is finalized:

1. Invoice is generated with line items
2. System calculates total amount due
3. Available credits are applied (by priority)
4. Remaining balance charged to payment method

```plaintext theme={null}
Invoice Total:     $500.00
Credits Applied:  -$300.00
Amount Due:        $200.00
```

### Unit Credits

Unit credits are consumed as usage events are ingested:

1. Usage event is received
2. Event is matched to a metric
3. Credits for that metric are decremented
4. If credits exhausted, usage is billed normally

```plaintext theme={null}
API Calls Made:    15,000
Credits Available: 10,000
Credits Used:     -10,000
Billable Usage:     5,000
```

***

## Consumption Priority

When multiple credit grants exist, consumption follows this order:

### Priority Rules

1. **Expiration date** - Earliest expiring first
2. **Priority value** - Lowest number first
3. **Creation date** - Oldest first

### Example

```plaintext theme={null}
Grant A: $200, Priority 10, Expires 2025-06-30
Grant B: $150, Priority 5,  Expires 2025-12-31
Grant C: $100, Priority 10, Expires 2025-03-31

Invoice: $350

Consumption order:
1. Grant B: $150 (lowest priority)
2. Grant C: $100 (same priority as A, but expires sooner)
3. Grant A: $100 (remaining needed)

Result: All grants partially/fully consumed
```

***

## Automatic vs Manual Application

### Automatic Application

By default, credits are automatically applied to invoices:

1. When invoice transitions to `pending` status
2. Before payment is attempted
3. Full available balance is applied

To disable automatic application for an account:

```bash theme={null}
curl -X PATCH https://api.alguna.io/accounts/acc_123 \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "creditSettings": {
      "autoApply": false
    }
  }'
```

### Manual Application

When auto-apply is disabled, apply credits manually:

```bash theme={null}
curl -X POST https://api.alguna.io/invoices/inv_456/apply-credits \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "amount": "250.00"
  }'
```

***

## Tracking Consumption

### Credit Ledger

Every credit transaction is recorded in the ledger:

```bash theme={null}
curl https://api.alguna.io/accounts/acc_123/credits/ledgers \
  -H "Authorization: Bearer YOUR_API_KEY"
```

**Response:**

```json theme={null}
{
  "entries": [
    {
      "id": "cle_001",
      "grantId": "cg_456",
      "type": "consumption",
      "amount": "-150.00",
      "balanceAfter": "350.00",
      "reference": {
        "type": "invoice",
        "id": "inv_789"
      },
      "createdAt": "2024-01-20T14:30:00Z"
    },
    {
      "id": "cle_002",
      "grantId": "cg_456",
      "type": "grant",
      "amount": "500.00",
      "balanceAfter": "500.00",
      "createdAt": "2024-01-15T10:00:00Z"
    }
  ]
}
```

### Ledger Entry Types

| Type          | Description                    |
| ------------- | ------------------------------ |
| `grant`       | Credit grant created           |
| `consumption` | Credits used for invoice/usage |
| `expiration`  | Credits expired                |
| `void`        | Grant voided                   |
| `adjustment`  | Manual adjustment              |

***

## Invoice Credit Display

When credits are applied to an invoice, they appear as a line item:

```json theme={null}
{
  "id": "inv_789",
  "total": "500.00",
  "creditsApplied": "300.00",
  "amountDue": "200.00",
  "lineItems": [
    {
      "description": "Platform subscription",
      "amount": "500.00"
    }
  ],
  "creditApplications": [
    {
      "grantId": "cg_456",
      "amount": "300.00",
      "description": "Q1 promotional credit"
    }
  ]
}
```

***

## Unit Credit Consumption

For usage-based products, unit credits are consumed in real-time:

### Configuration

Link credits to specific metrics:

```bash theme={null}
curl -X POST https://api.alguna.io/credit-grants \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "accountId": "acc_123",
    "type": "units",
    "amount": "100000",
    "metricId": "metric_api_calls"
  }'
```

### Consumption Flow

```mermaid theme={null}
graph LR
    A[Usage Event] --> B{Credits Available?}
    B -->|Yes| C[Consume Credit]
    C --> D[Update Ledger]
    B -->|No| E[Bill as Usage]
    D --> F[Remaining Balance]
```

### Checking Unit Balance

```bash theme={null}
curl https://api.alguna.io/accounts/acc_123/credits/balances \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "type": "units",
    "metricId": "metric_api_calls"
  }'
```

**Response:**

```json theme={null}
{
  "type": "units",
  "metricId": "metric_api_calls",
  "available": 45000,
  "consumed": 55000,
  "pending": 0
}
```

***

## Pending Consumption

Some consumption is recorded as "pending" before being confirmed:

### When Pending Occurs

* Pre-authorization for large transactions
* Usage aggregation periods
* Invoice draft state

### Confirming Pending

Pending consumption is automatically confirmed when:

* Invoice is finalized
* Billing period closes
* Manual confirmation via API

```bash theme={null}
curl -X POST https://api.alguna.io/credits/consumption/confirm \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "consumptionId": "cc_123"
  }'
```

### Rolling Back Pending

If an invoice is voided or usage is corrected:

```bash theme={null}
curl -X POST https://api.alguna.io/credits/consumption/rollback \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "consumptionId": "cc_123"
  }'
```

***

## Consumption Reports

### Dashboard

View consumption analytics at **Reports > Credits**:

* Consumption by period
* Top consumers
* Expiration forecasts
* Grant utilization rates

### API Export

```bash theme={null}
curl https://api.alguna.io/reports/credits/consumption \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "startDate": "2024-01-01",
    "endDate": "2024-03-31",
    "format": "csv"
  }'
```

***

## Webhooks

Monitor consumption with webhooks:

| Event                      | Description                      |
| -------------------------- | -------------------------------- |
| `credits.consumed`         | Credits applied to invoice/usage |
| `credits.balance_low`      | Balance below threshold          |
| `credits.balance_depleted` | Balance reached zero             |

### Balance Threshold Configuration

Set alerts when balance falls below a threshold:

```bash theme={null}
curl -X PATCH https://api.alguna.io/accounts/acc_123 \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "creditSettings": {
      "lowBalanceThreshold": "100.00",
      "lowBalanceNotification": true
    }
  }'
```

***

## Common Scenarios

### Partial Credit Application

Apply only part of available credits:

```bash theme={null}
curl -X POST https://api.alguna.io/invoices/inv_456/apply-credits \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "amount": "100.00",
    "grantId": "cg_789"
  }'
```

### Credit Refund

If an invoice is voided after credits were applied:

1. System automatically reverses the credit consumption
2. Credits are returned to the original grant
3. Ledger entry records the reversal

```json theme={null}
{
  "type": "reversal",
  "amount": "150.00",
  "reference": {
    "type": "invoice_void",
    "id": "inv_456"
  }
}
```

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Wallets" icon="wallet" href="/credits/wallets">
    Learn about prepaid wallets.
  </Card>

  <Card title="Credit Grants" icon="plus" href="/credits/credit-grants">
    Create and manage grants.
  </Card>
</CardGroup>
