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

# Admin Analytics — Dashboard Statistics and P&L Reports

> Access dashboard statistics, revenue analytics, and P&L reports. Dashboard stats require ADMIN role; P&L and expense management require SUPER_ADMIN.

The Admin Analytics group provides visibility into the financial health and operational performance of your store. Dashboard statistics give any admin a quick snapshot of revenue, orders, and customers over a recent time window. The P\&L overview and coupon analytics endpoints go deeper, covering profit and loss trends and discount impact — these require SUPER\_ADMIN access. The expense management endpoints let SUPER\_ADMINs record and track operating costs to complete the profit calculation.

<Note>
  The `GET /admin/stats` endpoint is available to **ADMIN** role and above. All other analytics endpoints — `/admin/analytics/overview`, `/admin/analytics/coupons`, and `/admin/analytics/expenses` — require **SUPER\_ADMIN** role.
</Note>

***

## Authentication

All analytics endpoints require:

* A valid `session` cookie (obtained via `POST /auth/login`)
* ADMIN role minimum; SUPER\_ADMIN for `/admin/analytics/*`
* `x-csrf-token` header on POST and PATCH requests

***

## Dashboard Statistics

Retrieve high-level KPIs for the platform over a selectable time window. The response summarises total revenue, order count, and total customer count for the selected period.

**`GET /admin/stats`**

<ParamField query="period" type="string" default="7d">
  Time window preset. One of `today`, `7d`, or `30d`.
</ParamField>

<CodeGroup>
  ```bash Last 7 Days theme={null}
  curl -X GET "https://api.example.com/api/v1/admin/stats?period=7d" \
    -H "Cookie: session=<your-session-token>"
  ```

  ```bash Today theme={null}
  curl -X GET "https://api.example.com/api/v1/admin/stats?period=today" \
    -H "Cookie: session=<your-session-token>"
  ```

  ```bash Last 30 Days theme={null}
  curl -X GET "https://api.example.com/api/v1/admin/stats?period=30d" \
    -H "Cookie: session=<your-session-token>"
  ```
</CodeGroup>

**Response `200 OK`**

<ResponseField name="success" type="boolean">
  Always `true` on a successful response.
</ResponseField>

<ResponseField name="data" type="object">
  <Expandable title="data fields">
    <ResponseField name="total_revenue" type="string">
      Total revenue collected in the selected period as a decimal string (e.g. `"14250.00"`). Money values are always strings, never floats.
    </ResponseField>

    <ResponseField name="total_orders" type="integer">
      Count of orders placed in the selected period.
    </ResponseField>

    <ResponseField name="total_customers" type="integer">
      Total customer accounts registered on the platform (cumulative, not period-scoped).
    </ResponseField>

    <ResponseField name="period" type="string">
      The period preset used in this request. One of `today`, `7d`, or `30d`.
    </ResponseField>
  </Expandable>
</ResponseField>

```json theme={null}
{
  "success": true,
  "data": {
    "total_revenue": "14250.00",
    "total_orders": 87,
    "total_customers": 1340,
    "period": "7d"
  }
}
```

| Status Code | Meaning                             |
| ----------- | ----------------------------------- |
| `200`       | Stats returned successfully.        |
| `400`       | Invalid `period` value.             |
| `401`       | Missing or expired session.         |
| `403`       | Insufficient role (requires ADMIN). |

***

## P\&L Overview

Retrieve a profit-and-loss overview including revenue, cost of goods, and profit trends over a custom date range. Use this to understand margin changes across periods and spot cost anomalies.

**`GET /admin/analytics/overview`**

<Tip>
  Use the `date_from` and `date_to` parameters to scope your revenue and P\&L reports to any arbitrary date range — for example, a fiscal quarter, a promotional campaign window, or a calendar month. Both parameters accept ISO 8601 datetime strings with offset (e.g. `2024-01-01T00:00:00.000Z`). Omit both to retrieve all-time aggregates.
</Tip>

<ParamField query="date_from" type="string">
  ISO 8601 datetime with UTC offset. Inclusive lower bound for the report window. Example: `2024-01-01T00:00:00.000Z`.
</ParamField>

<ParamField query="date_to" type="string">
  ISO 8601 datetime with UTC offset. Inclusive upper bound for the report window. Example: `2024-06-30T23:59:59.000Z`.
</ParamField>

<CodeGroup>
  ```bash Q1 P&L Overview theme={null}
  curl -X GET "https://api.example.com/api/v1/admin/analytics/overview?date_from=2024-01-01T00:00:00.000Z&date_to=2024-03-31T23:59:59.000Z" \
    -H "Cookie: session=<your-super-admin-session>"
  ```
</CodeGroup>

**Response `200 OK`**

```json theme={null}
{
  "success": true,
  "data": {
    "revenue": "128500.00",
    "cost": "74200.00",
    "profit": "54300.00",
    "date_from": "2024-01-01T00:00:00.000Z",
    "date_to": "2024-03-31T23:59:59.000Z"
  }
}
```

***

## Coupon Analytics

Retrieve coupon performance analytics including status breakdowns, usage trends over time, top-performing coupon codes, and the total revenue impact of discounts applied. Scoping by date range reports on coupons used within that window.

**`GET /admin/analytics/coupons`**

<ParamField query="date_from" type="string">
  ISO 8601 datetime with UTC offset. Inclusive lower bound.
</ParamField>

<ParamField query="date_to" type="string">
  ISO 8601 datetime with UTC offset. Inclusive upper bound.
</ParamField>

<CodeGroup>
  ```bash Coupon Analytics theme={null}
  curl -X GET "https://api.example.com/api/v1/admin/analytics/coupons?date_from=2024-01-01T00:00:00.000Z&date_to=2024-06-30T23:59:59.000Z" \
    -H "Cookie: session=<your-super-admin-session>"
  ```
</CodeGroup>

**Response `200 OK`**

```json theme={null}
{
  "success": true,
  "data": {
    "status_counts": {
      "ACTIVE": 8,
      "EXPIRED": 3,
      "USAGE_LIMIT_REACHED": 2,
      "INACTIVE": 1
    },
    "total_discount_applied": "3120.00",
    "total_uses": 214,
    "top_coupons": [
      {
        "code": "SAVE10",
        "usage_count": 98,
        "discount_applied": "980.00"
      }
    ]
  }
}
```

***

## List Expenses

Retrieve a paginated list of operating expenses, optionally filtered by category and date range. Use this to build a complete picture of outgoings for your P\&L calculation.

**`GET /admin/analytics/expenses`**

<ParamField query="page" type="integer" default="1">
  Page number (1-based).
</ParamField>

<ParamField query="limit" type="integer" default="20">
  Items per page. Minimum 1, maximum 100.
</ParamField>

<ParamField query="category" type="string">
  Filter by expense category. One of: `RENT`, `SALARIES`, `MARKETING`, `UTILITIES`, `SHIPPING`, `SOFTWARE`, `OTHER`.
</ParamField>

<ParamField query="date_from" type="string">
  ISO 8601 datetime. Filter expenses with `spent_at` on or after this date.
</ParamField>

<ParamField query="date_to" type="string">
  ISO 8601 datetime. Filter expenses with `spent_at` on or before this date.
</ParamField>

<CodeGroup>
  ```bash List All Expenses theme={null}
  curl -X GET "https://api.example.com/api/v1/admin/analytics/expenses" \
    -H "Cookie: session=<your-super-admin-session>"
  ```

  ```bash Filter by Category theme={null}
  curl -X GET "https://api.example.com/api/v1/admin/analytics/expenses?category=SALARIES&date_from=2024-01-01T00:00:00.000Z" \
    -H "Cookie: session=<your-super-admin-session>"
  ```
</CodeGroup>

**Response `200 OK`**

```json theme={null}
{
  "success": true,
  "data": [
    {
      "public_id": "exp_01H",
      "description": "Office rent - January",
      "category": "RENT",
      "amount": 1200.5,
      "spent_at": "2024-01-15T00:00:00.000Z",
      "created_at": "2024-01-15T10:00:00.000Z"
    }
  ],
  "meta": {
    "page": 1,
    "limit": 20,
    "total": 34,
    "totalPages": 2,
    "hasNext": true,
    "hasPrev": false
  }
}
```

***

## Create Expense

Record a new operating expense. Requires a description, category, amount, and the date the expense was incurred (`spent_at`). Use this endpoint to keep your P\&L data current by logging all platform-related costs.

**`POST /admin/analytics/expenses`**

<ParamField body="description" type="string" required>
  Human-readable description of the expense (1–255 characters). Example: `"Office rent - January"`.
</ParamField>

<ParamField body="category" type="string" required>
  Expense category. One of: `RENT`, `SALARIES`, `MARKETING`, `UTILITIES`, `SHIPPING`, `SOFTWARE`, `OTHER`.
</ParamField>

<ParamField body="amount" type="number" required>
  Expense amount as a number. Minimum `0.01`, maximum `99999999`. Example: `1200.50`.
</ParamField>

<ParamField body="spent_at" type="string" required>
  ISO 8601 datetime with UTC offset indicating when the expense was incurred. Example: `"2024-01-15T00:00:00.000Z"`.
</ParamField>

<CodeGroup>
  ```bash Create Expense theme={null}
  CSRF=$(curl -s -X GET https://api.example.com/api/v1/auth/csrf-token \
    -H "Cookie: session=<your-super-admin-session>" \
    | jq -r '.data.csrf_token')

  curl -X POST "https://api.example.com/api/v1/admin/analytics/expenses" \
    -H "Cookie: session=<your-super-admin-session>" \
    -H "x-csrf-token: $CSRF" \
    -H "Content-Type: application/json" \
    -d '{
      "description": "Office rent - January",
      "category": "RENT",
      "amount": 1200.50,
      "spent_at": "2024-01-15T00:00:00.000Z"
    }'
  ```
</CodeGroup>

**Response `201 Created`**

```json theme={null}
{
  "success": true,
  "data": {
    "public_id": "exp_01H",
    "description": "Office rent - January",
    "category": "RENT",
    "amount": 1200.5,
    "spent_at": "2024-01-15T00:00:00.000Z",
    "created_at": "2024-01-15T10:00:00.000Z"
  }
}
```

| Status Code | Meaning                                                          |
| ----------- | ---------------------------------------------------------------- |
| `201`       | Expense created successfully.                                    |
| `400`       | Validation failed (invalid category, amount out of range, etc.). |
| `401`       | Missing or expired session.                                      |
| `403`       | Insufficient role (requires SUPER\_ADMIN).                       |

***

## Update and Delete Expenses

Correct or remove an expense entry using its public ID.

**`PATCH /admin/analytics/expenses/{expense_public_id}`** — Update any combination of `description`, `category`, `amount`, or `spent_at`. At least one field required.

**`DELETE /admin/analytics/expenses/{expense_public_id}`** — Permanently remove the expense record. Returns `204 No Content`.

<CodeGroup>
  ```bash Update Expense theme={null}
  CSRF=$(curl -s -X GET https://api.example.com/api/v1/auth/csrf-token \
    -H "Cookie: session=<your-super-admin-session>" \
    | jq -r '.data.csrf_token')

  curl -X PATCH "https://api.example.com/api/v1/admin/analytics/expenses/exp_01H" \
    -H "Cookie: session=<your-super-admin-session>" \
    -H "x-csrf-token: $CSRF" \
    -H "Content-Type: application/json" \
    -d '{"amount": 1350.00, "description": "Office rent - January (corrected)"}'
  ```

  ```bash Delete Expense theme={null}
  CSRF=$(curl -s -X GET https://api.example.com/api/v1/auth/csrf-token \
    -H "Cookie: session=<your-super-admin-session>" \
    | jq -r '.data.csrf_token')

  curl -X DELETE "https://api.example.com/api/v1/admin/analytics/expenses/exp_01H" \
    -H "Cookie: session=<your-super-admin-session>" \
    -H "x-csrf-token: $CSRF"
  ```
</CodeGroup>

***

## Endpoint Summary

<CardGroup cols={2}>
  <Card title="GET /admin/stats" icon="chart-bar">
    Dashboard KPIs: revenue, order count, customer count. Requires ADMIN role.
  </Card>

  <Card title="GET /admin/analytics/overview" icon="chart-line">
    Full P\&L overview with revenue, cost, and profit. Requires SUPER\_ADMIN.
  </Card>

  <Card title="GET /admin/analytics/coupons" icon="tag">
    Coupon performance and discount impact analytics. Requires SUPER\_ADMIN.
  </Card>

  <Card title="GET /admin/analytics/expenses" icon="receipt">
    List operating expenses with category and date filters. Requires SUPER\_ADMIN.
  </Card>

  <Card title="POST /admin/analytics/expenses" icon="plus">
    Record a new operating expense for P\&L tracking. Requires SUPER\_ADMIN.
  </Card>

  <Card title="PATCH/DELETE /admin/analytics/expenses/:id" icon="pen-to-square">
    Correct or remove an existing expense record. Requires SUPER\_ADMIN.
  </Card>
</CardGroup>
