Files
jiebanke/docs/管理员后台系统API文档.md

16 KiB
Raw Blame History

管理员后台系统API文档

概述

管理员后台系统提供了完整的系统管理功能,包括用户管理、动物管理、数据统计、系统监控等功能,支持管理员对整个平台进行全面的管理和监控。

基础信息

  • 基础URL: /api/v1/admin
  • 认证方式: Bearer Token
  • 数据格式: JSON
  • 字符编码: UTF-8
  • 权限要求: 管理员权限admin 或 super_admin

权限说明

角色类型

  • super_admin: 超级管理员,拥有所有权限
  • admin: 普通管理员,拥有大部分管理权限
  • manager: 部门经理,拥有部分管理权限

权限控制

所有管理员接口都需要通过Bearer Token进行身份验证并根据用户角色进行权限控制。

用户管理模块

1. 获取用户列表

接口地址: GET /admin/users

请求参数:

{
  "page": 1,
  "limit": 10,
  "keyword": "搜索关键词",
  "user_type": "farmer",
  "status": "active",
  "start_date": "2024-01-01",
  "end_date": "2024-12-31",
  "sort_by": "created_at",
  "sort_order": "desc"
}

响应示例:

{
  "success": true,
  "message": "获取成功",
  "data": {
    "users": [
      {
        "id": 1,
        "username": "张三",
        "email": "zhangsan@example.com",
        "phone": "13800138001",
        "user_type": "farmer",
        "status": "active",
        "level": "bronze",
        "points": 1200,
        "travel_count": 5,
        "claim_count": 2,
        "last_login_at": "2024-12-01T10:30:00.000Z",
        "created_at": "2024-01-15T08:00:00.000Z"
      }
    ],
    "pagination": {
      "current_page": 1,
      "per_page": 10,
      "total": 1000,
      "total_pages": 100
    }
  }
}

2. 获取用户详情

接口地址: GET /admin/users/{user_id}

响应示例:

{
  "success": true,
  "message": "获取成功",
  "data": {
    "user": {
      "id": 1,
      "username": "张三",
      "email": "zhangsan@example.com",
      "phone": "13800138001",
      "user_type": "farmer",
      "status": "active",
      "level": "bronze",
      "points": 1200,
      "profile": {
        "real_name": "张三",
        "avatar": "/uploads/avatars/user1.jpg",
        "bio": "热爱农业的城市青年"
      }
    },
    "statistics": {
      "travel_count": 5,
      "claim_count": 2,
      "order_count": 8,
      "total_spent": 2500.00
    },
    "recentActivities": [
      {
        "type": "travel_created",
        "description": "创建了新的旅行计划",
        "created_at": "2024-12-01T10:00:00.000Z"
      }
    ]
  }
}

3. 更新用户状态

接口地址: PUT /admin/users/{user_id}/status

请求参数:

{
  "status": "suspended",
  "reason": "违反平台规定"
}

4. 批量更新用户状态

接口地址: PUT /admin/users/batch/status

请求参数:

{
  "user_ids": [1, 2, 3],
  "status": "suspended",
  "reason": "批量处理违规用户"
}

5. 获取用户统计信息

接口地址: GET /admin/users/statistics

响应示例:

{
  "success": true,
  "message": "获取成功",
  "data": {
    "totalStats": {
      "total_users": 10000,
      "active_users": 8500,
      "new_users_today": 50,
      "new_users_week": 300
    },
    "typeStats": [
      {
        "user_type": "farmer",
        "count": 6000,
        "percentage": 60.0
      },
      {
        "user_type": "merchant",
        "count": 4000,
        "percentage": 40.0
      }
    ],
    "levelStats": [
      {
        "level": "bronze",
        "count": 5000,
        "avg_points": 800
      }
    ]
  }
}

6. 导出用户数据

接口地址: GET /admin/users/export

请求参数:

{
  "format": "csv",
  "user_type": "farmer",
  "status": "active",
  "start_date": "2024-01-01",
  "end_date": "2024-12-31"
}

动物管理模块

1. 获取动物列表

接口地址: GET /admin/animals

请求参数:

{
  "page": 1,
  "limit": 10,
  "keyword": "小白",
  "species": "dog",
  "status": "available",
  "merchant_id": 1,
  "start_date": "2024-01-01",
  "end_date": "2024-12-31",
  "sort_by": "created_at",
  "sort_order": "desc"
}

响应示例:

{
  "success": true,
  "message": "获取成功",
  "data": {
    "animals": [
      {
        "id": 1,
        "name": "小白",
        "species": "dog",
        "breed": "金毛",
        "age": 12,
        "gender": "male",
        "price": 1200.00,
        "status": "available",
        "merchant_id": 1,
        "merchant_name": "阳光农场",
        "claim_count": 3,
        "created_at": "2024-01-15T08:00:00.000Z"
      }
    ],
    "pagination": {
      "current_page": 1,
      "per_page": 10,
      "total": 500,
      "total_pages": 50
    }
  }
}

2. 获取动物详情

接口地址: GET /admin/animals/{animal_id}

响应示例:

{
  "success": true,
  "message": "获取成功",
  "data": {
    "animal": {
      "id": 1,
      "name": "小白",
      "species": "dog",
      "breed": "金毛",
      "age": 12,
      "gender": "male",
      "price": 1200.00,
      "status": "available",
      "description": "温顺可爱的金毛犬",
      "images": ["/uploads/animals/dog1.jpg"],
      "merchant_name": "阳光农场"
    },
    "claimStats": {
      "total_claims": 5,
      "pending_claims": 1,
      "approved_claims": 3,
      "rejected_claims": 1
    },
    "recentClaims": [
      {
        "id": 1,
        "user_name": "张三",
        "status": "approved",
        "created_at": "2024-12-01T10:00:00.000Z"
      }
    ]
  }
}

3. 更新动物状态

接口地址: PUT /admin/animals/{animal_id}/status

请求参数:

{
  "status": "unavailable",
  "reason": "动物健康检查"
}

4. 获取动物统计信息

接口地址: GET /admin/animals/statistics

响应示例:

{
  "success": true,
  "message": "获取成功",
  "data": {
    "totalStats": {
      "total_animals": 500,
      "available_animals": 300,
      "claimed_animals": 150,
      "total_claims": 800,
      "avg_price": 1500.00
    },
    "speciesStats": [
      {
        "species": "dog",
        "count": 200,
        "avg_price": 1200.00
      }
    ],
    "monthlyTrend": [
      {
        "month": "2024-12",
        "new_animals": 20,
        "new_claims": 35
      }
    ]
  }
}

数据统计模块

1. 获取系统概览统计

接口地址: GET /admin/statistics/overview

响应示例:

{
  "success": true,
  "data": {
    "users": {
      "total_users": 10000,
      "active_users": 8500,
      "new_users_today": 50,
      "new_users_week": 300
    },
    "travels": {
      "total_travels": 2000,
      "published_travels": 1500,
      "new_travels_today": 10
    },
    "animals": {
      "total_animals": 500,
      "available_animals": 300,
      "claimed_animals": 150
    },
    "orders": {
      "total_orders": 5000,
      "completed_orders": 4500,
      "total_revenue": 500000.00
    }
  }
}

2. 获取用户增长趋势

接口地址: GET /admin/statistics/user-growth

请求参数:

{
  "period": "30d"
}

响应示例:

{
  "success": true,
  "data": {
    "period": "30d",
    "trendData": [
      {
        "date": "2024-12-01",
        "new_users": 25,
        "cumulative_users": 9975
      }
    ]
  }
}

3. 获取业务数据统计

接口地址: GET /admin/statistics/business

请求参数:

{
  "period": "30d"
}

响应示例:

{
  "success": true,
  "data": {
    "period": "30d",
    "travelStats": [
      {
        "date": "2024-12-01",
        "new_travels": 5,
        "published_travels": 4,
        "matched_travels": 3
      }
    ],
    "claimStats": [
      {
        "date": "2024-12-01",
        "new_claims": 8,
        "approved_claims": 6,
        "rejected_claims": 1
      }
    ],
    "orderStats": [
      {
        "date": "2024-12-01",
        "new_orders": 15,
        "completed_orders": 12,
        "daily_revenue": 2500.00
      }
    ]
  }
}

4. 获取地域分布统计

接口地址: GET /admin/statistics/geographic

响应示例:

{
  "success": true,
  "data": {
    "userDistribution": [
      {
        "province": "北京市",
        "city": "北京市",
        "user_count": 1500
      }
    ],
    "provinceStats": [
      {
        "province": "北京市",
        "user_count": 1500,
        "farmer_count": 900,
        "merchant_count": 600
      }
    ]
  }
}

5. 获取用户行为分析

接口地址: GET /admin/statistics/user-behavior

响应示例:

{
  "success": true,
  "data": {
    "activityStats": [
      {
        "activity_level": "high",
        "user_count": 2000
      }
    ],
    "levelDistribution": [
      {
        "level": "bronze",
        "user_count": 5000,
        "avg_points": 800,
        "avg_travel_count": 2.5,
        "avg_claim_count": 1.2
      }
    ]
  }
}

6. 获取收入统计

接口地址: GET /admin/statistics/revenue

请求参数:

{
  "period": "30d"
}

响应示例:

{
  "success": true,
  "data": {
    "period": "30d",
    "revenueTrend": [
      {
        "date": "2024-12-01",
        "daily_revenue": 2500.00,
        "completed_orders": 12,
        "total_orders": 15
      }
    ],
    "revenueSource": [
      {
        "order_type": "travel",
        "order_count": 800,
        "total_revenue": 120000.00,
        "avg_order_value": 150.00
      }
    ],
    "paymentMethodStats": [
      {
        "payment_method": "wechat",
        "order_count": 3000,
        "total_amount": 300000.00
      }
    ]
  }
}

7. 导出统计报告

接口地址: GET /admin/statistics/export

请求参数:

{
  "reportType": "overview",
  "period": "30d",
  "format": "csv"
}

错误码说明

错误码 说明
200 请求成功
400 参数错误
401 未授权,需要登录
403 权限不足
404 资源不存在
422 参数验证失败
500 服务器内部错误

状态说明

用户状态

  • active: 正常状态
  • suspended: 已暂停
  • banned: 已封禁
  • inactive: 未激活

动物状态

  • available: 可认领
  • claimed: 已认领
  • unavailable: 不可认领

认领状态

  • pending: 待审核
  • approved: 已通过
  • rejected: 已拒绝
  • cancelled: 已取消

业务规则

用户管理规则

  1. 只有超级管理员可以创建和删除管理员账户
  2. 普通管理员可以管理普通用户,但不能管理其他管理员
  3. 用户状态变更需要记录操作原因和操作人
  4. 批量操作有数量限制单次最多处理100个用户

动物管理规则

  1. 动物状态变更需要记录操作原因
  2. 已有认领申请的动物不能直接删除
  3. 动物价格修改需要管理员审核
  4. 动物图片上传有格式和大小限制

数据统计规则

  1. 统计数据每小时更新一次
  2. 导出功能有频率限制每个管理员每天最多导出10次
  3. 敏感数据需要特殊权限才能查看
  4. 历史数据保留期限为2年

注意事项

  1. 权限控制: 所有接口都需要管理员权限请确保在请求头中包含有效的Bearer Token
  2. 参数验证: 请求参数会进行严格验证,确保传入正确的数据类型和格式
  3. 频率限制: 部分接口有频率限制,请合理控制请求频率
  4. 数据安全: 敏感数据会进行脱敏处理,完整数据需要特殊权限
  5. 操作日志: 所有管理操作都会记录日志,便于审计和追踪

集成示例

JavaScript示例

// 获取用户列表
async function getUserList(page = 1, limit = 10) {
  try {
    const response = await fetch('/api/v1/admin/users?' + new URLSearchParams({
      page,
      limit,
      sort_by: 'created_at',
      sort_order: 'desc'
    }), {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    const result = await response.json();
    if (result.success) {
      console.log('用户列表:', result.data.users);
      return result.data;
    } else {
      throw new Error(result.message);
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    throw error;
  }
}

// 更新用户状态
async function updateUserStatus(userId, status, reason) {
  try {
    const response = await fetch(`/api/v1/admin/users/${userId}/status`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        status,
        reason
      })
    });
    
    const result = await response.json();
    if (result.success) {
      console.log('用户状态更新成功');
      return result;
    } else {
      throw new Error(result.message);
    }
  } catch (error) {
    console.error('更新用户状态失败:', error);
    throw error;
  }
}

// 获取系统统计数据
async function getSystemOverview() {
  try {
    const response = await fetch('/api/v1/admin/statistics/overview', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    const result = await response.json();
    if (result.success) {
      console.log('系统概览:', result.data);
      return result.data;
    } else {
      throw new Error(result.message);
    }
  } catch (error) {
    console.error('获取系统统计失败:', error);
    throw error;
  }
}

Python示例

import requests
import json

class AdminAPI:
    def __init__(self, base_url, token):
        self.base_url = base_url
        self.headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json'
        }
    
    def get_user_list(self, page=1, limit=10, **kwargs):
        """获取用户列表"""
        params = {'page': page, 'limit': limit, **kwargs}
        response = requests.get(
            f'{self.base_url}/admin/users',
            headers=self.headers,
            params=params
        )
        return response.json()
    
    def update_user_status(self, user_id, status, reason=None):
        """更新用户状态"""
        data = {'status': status}
        if reason:
            data['reason'] = reason
        
        response = requests.put(
            f'{self.base_url}/admin/users/{user_id}/status',
            headers=self.headers,
            json=data
        )
        return response.json()
    
    def get_system_overview(self):
        """获取系统概览"""
        response = requests.get(
            f'{self.base_url}/admin/statistics/overview',
            headers=self.headers
        )
        return response.json()

# 使用示例
api = AdminAPI('https://api.example.com/api/v1', 'your_token_here')

# 获取用户列表
users = api.get_user_list(page=1, limit=20, user_type='farmer')
print(f"获取到 {len(users['data']['users'])} 个用户")

# 更新用户状态
result = api.update_user_status(1, 'suspended', '违反平台规定')
if result['success']:
    print("用户状态更新成功")

# 获取系统统计
overview = api.get_system_overview()
print(f"系统用户总数: {overview['data']['users']['total_users']}")

更新日志

v1.0.0 (2024-12-01)

  • 初始版本发布
  • 实现用户管理基础功能
  • 实现动物管理基础功能
  • 实现数据统计基础功能

v1.1.0 (计划中)

  • 增加订单管理功能
  • 增加商家管理功能
  • 增加系统配置管理
  • 优化统计报表功能