Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/peLuis123/crypto-shop-backend/llms.txt

Use this file to discover all available pages before exploring further.

This guide covers the admin endpoints for monitoring platform statistics, viewing sales, managing customers, and analyzing business metrics.
All admin endpoints require authentication with a user account that has role: "admin".

Admin Statistics

Get comprehensive platform statistics including revenue, orders, users, and trends.

Endpoint

GET /api/admin/stats

Response

{
  "success": true,
  "stats": {
    "totals": {
      "totalRevenue": 15847.89,
      "totalOrders": 234,
      "activeUsers": 156,
      "totalUsers": 180,
      "networkFees": -2.34
    },
    "trends": {
      "revenueChange": "+23.5%",
      "ordersChange": "+18.2%",
      "usersChange": "+12.8%",
      "feesChange": "+22.1%"
    },
    "last30Days": {
      "totalRevenue": 4532.67,
      "totalOrders": 67,
      "networkFees": -0.67
    },
    "statusCounts": {
      "pending": 5,
      "completed": 198,
      "refunded": 12,
      "failed": 8,
      "cancelled": 11
    }
  },
  "recentSales": [
    {
      "_id": "507f1f77bcf86cd799439013",
      "orderId": "#TRX-1001",
      "userId": {
        "_id": "507f1f77bcf86cd799439010",
        "username": "johndoe",
        "email": "john@example.com"
      },
      "total": 59.97,
      "status": "completed",
      "transactionHash": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0",
      "products": [
        {
          "productId": "507f1f77bcf86cd799439011",
          "name": "Wireless Headphones",
          "price": 29.99,
          "quantity": 2
        }
      ],
      "createdAt": "2024-01-20T14:30:00.000Z"
    }
  ],
  "topProducts": [
    {
      "_id": "507f1f77bcf86cd799439011",
      "name": "Wireless Headphones",
      "quantitySold": 145,
      "revenue": 4348.55,
      "trend": "+28.3%"
    },
    {
      "_id": "507f1f77bcf86cd799439012",
      "name": "Phone Case",
      "quantitySold": 98,
      "revenue": 1469.02,
      "trend": "+15.7%"
    },
    {
      "_id": "507f1f77bcf86cd799439014",
      "name": "USB Cable",
      "quantitySold": 87,
      "revenue": 869.13,
      "trend": "+42.1%"
    }
  ],
  "chartData": [
    {
      "date": "2024-01-01",
      "revenue": 234.56
    },
    {
      "date": "2024-01-02",
      "revenue": 189.23
    }
  ]
}

Statistics Breakdown

All-time totals across the platform:
  • totalRevenue: Total revenue from completed orders (in TRX)
  • totalOrders: Total number of orders created
  • activeUsers: Number of active user accounts
  • totalUsers: Total registered users
  • networkFees: Total TRON network fees paid

Implementation Example

const response = await fetch('http://localhost:3000/api/admin/stats', {
  credentials: 'include'
});

const data = await response.json();

console.log('Total Revenue:', data.stats.totals.totalRevenue, 'TRX');
console.log('Revenue Trend:', data.stats.trends.revenueChange);
console.log('Top Product:', data.topProducts[0].name);

View All Sales

Retrieve a paginated list of all sales (orders) with filtering options.

Endpoint

GET /api/admin/sales

Query Parameters

  • status (optional): Filter by order status (pending, completed, refunded, failed, cancelled)
  • limit (optional): Number of results per page (default: 10)
  • page (optional): Page number (default: 1)

Response

{
  "success": true,
  "sales": [
    {
      "_id": "507f1f77bcf86cd799439013",
      "orderId": "#TRX-1001",
      "userId": {
        "_id": "507f1f77bcf86cd799439010",
        "username": "johndoe",
        "email": "john@example.com"
      },
      "products": [
        {
          "productId": "507f1f77bcf86cd799439011",
          "name": "Wireless Headphones",
          "price": 29.99,
          "quantity": 2,
          "color": "Black"
        }
      ],
      "subtotal": 59.98,
      "networkFee": -0.01,
      "discount": 0,
      "total": 59.97,
      "status": "completed",
      "paymentMethod": "TRC-20",
      "transactionHash": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0",
      "txHash": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0",
      "walletAddress": "TYwXGhKhqPTbLvRPFdvZnXqcqN4kVy7ABC",
      "merchantAddress": "TXYZMerchantAddressHere123456789",
      "createdAt": "2024-01-20T14:30:00.000Z",
      "updatedAt": "2024-01-20T14:35:00.000Z"
    }
  ],
  "pagination": {
    "total": 234,
    "page": 1,
    "pages": 24
  }
}

Implementation Example

const response = await fetch(
  'http://localhost:3000/api/admin/sales?limit=20&page=1',
  { credentials: 'include' }
);

const data = await response.json();
console.log('Total sales:', data.pagination.total);
console.log('Sales:', data.sales);

View Customers

Get a list of all customers with their spending statistics and trends.

Endpoint

GET /api/admin/customers

Query Parameters

  • search (optional): Search by username or email (case-insensitive)
  • limit (optional): Number of results per page (default: 10)
  • page (optional): Page number (default: 1)

Response

{
  "success": true,
  "users": [
    {
      "_id": "507f1f77bcf86cd799439010",
      "email": "john@example.com",
      "username": "johndoe",
      "role": "user",
      "wallet": {
        "address": "TYwXGhKhqPTbLvRPFdvZnXqcqN4kVy7ABC"
      },
      "phone": null,
      "country": null,
      "isActive": true,
      "lastLogin": "2024-01-20T14:22:00.000Z",
      "createdAt": "2024-01-15T10:30:00.000Z",
      "updatedAt": "2024-01-20T14:22:00.000Z",
      "totalSpent": 459.87
    }
  ],
  "stats": {
    "total": 180,
    "totalVolume": 15847.89,
    "totalChange": "+12.8%",
    "volumeChange": "+23.5%"
  },
  "pagination": {
    "total": 180,
    "page": 1,
    "pages": 18,
    "limit": 10
  }
}

Customer Statistics

From src/api/admin/getCustomers.js:29, each customer includes:
  • totalSpent: Net spending (completed orders minus refunded orders)
  • wallet.address: Customer’s TRON wallet address
  • isActive: Account status (active/inactive)
  • lastLogin: Last login timestamp
The stats object provides:
  • total: Total number of customers
  • totalVolume: Total spending across all customers
  • totalChange: New customer growth vs previous 30 days
  • volumeChange: Spending volume change vs previous 30 days

Implementation Example

const response = await fetch(
  'http://localhost:3000/api/admin/customers?limit=50',
  { credentials: 'include' }
);

const data = await response.json();
console.log('Total customers:', data.stats.total);
console.log('Total volume:', data.stats.totalVolume, 'TRX');
console.log('Customers:', data.users);

Customer Spending Calculation

From src/api/admin/getCustomers.js:41, the total spending is calculated using MongoDB aggregation:
{
  $lookup: {
    from: 'orders',
    let: { userId: '$_id' },
    pipeline: [
      { $match: { $expr: { $eq: ['$userId', '$$userId'] } } },
      { $match: { status: { $in: ['completed', 'refunded'] } } },
      {
        $group: {
          _id: null,
          completedTotal: {
            $sum: {
              $cond: [{ $eq: ['$status', 'completed'] }, '$total', 0]
            }
          },
          refundedTotal: {
            $sum: {
              $cond: [{ $eq: ['$status', 'refunded'] }, '$total', 0]
            }
          }
        }
      }
    ],
    as: 'orderStats'
  }
}

// totalSpent = completedTotal - refundedTotal

Trend Calculation

From src/api/admin/getStats.js:4, trends are calculated comparing 30-day periods:
const formatTrend = (current, previous) => {
  if (!previous) {
    if (!current) return '0.0%';
    return '+100.0%';
  }
  const change = ((current - previous) / previous) * 100;
  const sign = change >= 0 ? '+' : '';
  return `${sign}${change.toFixed(1)}%`;
};

Chart Data

The stats endpoint includes chartData for revenue visualization over 180 days from src/api/admin/getStats.js:125:
const chartTotals = await Order.aggregate([
  { $match: { status: 'completed', createdAt: { $gte: start180 } } },
  {
    $group: {
      _id: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt' } },
      revenue: { $sum: '$total' }
    }
  },
  { $sort: { _id: 1 } }
]);

const totalsByDate = new Map(chartTotals.map((item) => [item._id, item.revenue]));
const chartData = buildDailySeries(start180, 181, totalsByDate);

Building an Admin Dashboard

1

Fetch Statistics

Call /api/admin/stats to get overall metrics, recent sales, and top products.
2

Display Revenue Chart

Use the chartData array to render a revenue chart for the last 180 days.
3

Show Recent Sales

Display the recentSales array (last 8 orders) with user information.
4

List Top Products

Show topProducts with quantities sold, revenue, and growth trends.
5

Customer Management

Use /api/admin/customers to list and search customers with spending data.
6

Sales History

Use /api/admin/sales with pagination and filters to browse all orders.

Complete Dashboard Example

class AdminDashboard {
  async loadDashboard() {
    try {
      // Fetch all admin data in parallel
      const [statsRes, salesRes, customersRes] = await Promise.all([
        fetch('http://localhost:3000/api/admin/stats', {
          credentials: 'include'
        }),
        fetch('http://localhost:3000/api/admin/sales?limit=10', {
          credentials: 'include'
        }),
        fetch('http://localhost:3000/api/admin/customers?limit=10', {
          credentials: 'include'
        })
      ]);

      const stats = await statsRes.json();
      const sales = await salesRes.json();
      const customers = await customersRes.json();

      // Display statistics
      console.log('=== Platform Statistics ===');
      console.log('Total Revenue:', stats.stats.totals.totalRevenue, 'TRX');
      console.log('Revenue Trend:', stats.stats.trends.revenueChange);
      console.log('Total Orders:', stats.stats.totals.totalOrders);
      console.log('Active Users:', stats.stats.totals.activeUsers);

      // Display top products
      console.log('\n=== Top Products ===');
      stats.topProducts.forEach((product, index) => {
        console.log(
          `${index + 1}. ${product.name} - ${product.quantitySold} sold - ${product.revenue} TRX (${product.trend})`
        );
      });

      // Display recent sales
      console.log('\n=== Recent Sales ===');
      stats.recentSales.forEach((sale) => {
        console.log(
          `${sale.orderId} - ${sale.userId.username} - ${sale.total} TRX - ${sale.status}`
        );
      });

      // Display customer stats
      console.log('\n=== Customer Statistics ===');
      console.log('Total Customers:', customers.stats.total);
      console.log('Total Volume:', customers.stats.totalVolume, 'TRX');
      console.log('Customer Growth:', customers.stats.totalChange);
      console.log('Volume Growth:', customers.stats.volumeChange);

      return { stats, sales, customers };
    } catch (error) {
      console.error('Dashboard error:', error);
      throw error;
    }
  }
}

const dashboard = new AdminDashboard();
await dashboard.loadDashboard();

Next Steps

Real-time Notifications

Monitor transactions in real-time with Socket.io

Payment Processing

Understand how payments are processed and confirmed

Build docs developers (and LLMs) love