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

# Customers Admin

> Administrative customer management, statistics, and bulk operations

## Overview

Customers Admin API provides tools for platform administrators to view customer statistics, list and search customers, inspect detailed customer profiles, manage account status, and perform bulk deletions. All functions require admin authorization.

**Location:** `convex/admins/customersAdmin.ts`

***

## Get Customer Statistics

Returns aggregate customer statistics for the admin dashboard. Includes total counts, activity breakdowns, growth metrics, and high-value customer count.

*No arguments required.*

<CodeGroup>
  ```typescript TypeScript theme={null}
  const stats = await convex.query(api.admins.customersAdmin.getCustomerStatistics, {});
  ```
</CodeGroup>

<ResponseExample>
  ```json Response theme={null}
  {
    "totalCustomers": 5200,
    "activeCustomers": 4850,
    "inactiveCustomers": 350,
    "newCustomersToday": 12,
    "newCustomersThisWeek": 85,
    "newCustomersThisMonth": 340,
    "highValueCustomers": 48,
    "verifiedCustomers": 4100
  }
  ```
</ResponseExample>

<Note>
  High-value customers are defined as the top 10% by total spending. Verified customers are those with either a verified phone number or verified email. Growth metrics use rolling time windows (24h, 7d, 30d).
</Note>

***

## Get All Customers

Fetches a paginated list of customers with optional filtering. Returns enriched customer data including avatar URLs, order statistics, and verification status.

<ParamField path="status" type="string">
  Filter by account status: `active` or `inactive`
</ParamField>

<ParamField path="searchQuery" type="string">
  Text search across name, username, email, and phone number (case-insensitive)
</ParamField>

<ParamField path="highValueOnly" type="boolean">
  When `true`, filters to only the top 10% of customers by total spending
</ParamField>

<ParamField path="paginationOpts" type="PaginationOptions" required>
  Pagination options (numItems, cursor)
</ParamField>

<CodeGroup>
  ```typescript TypeScript theme={null}
  const customers = await convex.query(api.admins.customersAdmin.getAllCustomers, {
    paginationOpts: { numItems: 20, cursor: null },
    status: "active",
    searchQuery: "ahmed"
  });
  ```
</CodeGroup>

<ResponseExample>
  ```json Response theme={null}
  {
    "page": [
      {
        "_id": "c111",
        "_creationTime": 1700000000000,
        "userId": "user_abc123",
        "name": "Ahmed Ali",
        "username": "ahmed_ali",
        "avatarId": "stor_xyz",
        "avatarUrl": "https://storage.convex.cloud/...",
        "phoneNumber": "+971501234567",
        "phoneNumberVerified": true,
        "email": "ahmed@example.com",
        "emailVerified": true,
        "isActive": true,
        "followersCount": 25,
        "followingCustomersCount": 12,
        "followingStoresCount": 8,
        "totalOrders": 45,
        "totalSpent": 5620.50,
        "lastOrderDate": 1700000000000,
        "isVerified": true
      }
    ],
    "continueCursor": "abc123",
    "isDone": false
  }
  ```
</ResponseExample>

***

## Get Customer Details

Fetches detailed information about a specific customer, including their profile, recent orders (last 10), and saved addresses with resolved city and area names.

<ParamField path="customerId" type="Id<'customers'>" required>
  Customer ID to retrieve
</ParamField>

<CodeGroup>
  ```typescript TypeScript theme={null}
  const details = await convex.query(api.admins.customersAdmin.getCustomerDetails, {
    customerId: "c111"
  });
  ```
</CodeGroup>

<ResponseExample>
  ```json Response theme={null}
  {
    "customer": {
      "_id": "c111",
      "_creationTime": 1700000000000,
      "userId": "user_abc123",
      "name": "Ahmed Ali",
      "username": "ahmed_ali",
      "avatarUrl": "https://storage.convex.cloud/...",
      "phoneNumber": "+971501234567",
      "phoneNumberVerified": true,
      "email": "ahmed@example.com",
      "emailVerified": true,
      "isActive": true,
      "isPrivate": false,
      "followersCount": 25,
      "followingCustomersCount": 12,
      "followingStoresCount": 8,
      "preferences": {
        "preferredLanguage": "en",
        "pushNotifications": true,
        "emailNotifications": true,
        "smsNotifications": false
      },
      "totalOrders": 45,
      "totalSpent": 5620.50,
      "lastOrderDate": 1700000000000
    },
    "recentOrders": [
      {
        "_id": "o123456789",
        "_creationTime": 1700000000000,
        "orderNumber": "o123456789",
        "status": "delivered",
        "totalAmount": 125.50,
        "storeName": "Pizza Palace",
        "itemCount": 3
      }
    ],
    "addresses": [
      {
        "_id": "a111",
        "_creationTime": 1700000000000,
        "label": "Home",
        "fullAddress": "Villa 12, Al Nahda Street",
        "cityName": "Dubai",
        "areaName": "Al Nahda",
        "buildingNumber": "12",
        "isDefault": true
      }
    ]
  }
  ```
</ResponseExample>

<Note>
  The `orderNumber` field uses the order's `_id`. Customer stats (`totalOrders`, `totalSpent`, `lastOrderDate`) are flattened from the nested `stats` object for easier access. City and area names are resolved from their respective reference tables.
</Note>

***

## Update Customer Status

Activates or deactivates a customer account. Sets the `isActive` flag on the customer record.

<ParamField path="customerId" type="Id<'customers'>" required>
  Customer ID to update
</ParamField>

<ParamField path="isActive" type="boolean" required>
  Set to `true` to activate or `false` to deactivate the account
</ParamField>

<ParamField path="reason" type="string">
  Optional reason for the status change (for audit purposes)
</ParamField>

<CodeGroup>
  ```typescript TypeScript theme={null}
  const result = await convex.mutation(api.admins.customersAdmin.updateCustomerStatus, {
    customerId: "c111",
    isActive: false,
    reason: "Repeated policy violations"
  });
  ```
</CodeGroup>

<ResponseExample>
  ```json Response theme={null}
  {
    "success": true
  }
  ```
</ResponseExample>

***

## Bulk Delete Customers

Permanently deletes multiple customers and all their related data. Processes in batches of 10 using internal mutations. Related data deleted includes: addresses, store follows, customer follows, followers, product likes, carts, search history, and avatar storage files.

<ParamField path="customerIds" type="Id<'customers'>[]" required>
  Array of customer IDs to delete
</ParamField>

<CodeGroup>
  ```typescript TypeScript theme={null}
  const result = await convex.action(api.admins.customersAdmin.bulkDeleteCustomers, {
    customerIds: ["c111", "c222", "c333"]
  });
  ```
</CodeGroup>

<ResponseExample>
  ```json Response theme={null}
  {
    "customersDeleted": 3,
    "relatedDeleted": 47
  }
  ```
</ResponseExample>

<Note>
  This is a Convex action that delegates to internal mutations in batches of 10 (smaller than other bulk operations because each customer has many related records). The `relatedDeleted` count includes all associated records: addresses, follows, likes, carts, search history, and avatar files. Returns zero counts if an empty array is passed.
</Note>
