ShopTRAINING/.codelf/architecture.md

10 KiB

药店销售预测系统 - 架构详情

🏗️ 系统架构图

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│    前端界面      │────│    API网关      │────│   数据存储层     │
│   (Vue3 UI)    │    │  (Flask API)   │    │  (SQLite + JSON)│
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
    ┌────────────┐         ┌─────────────┐        ┌─────────────┐
    │ ECharts图表│         │  模型引擎    │        │  文件系统   │
    │ Element UI │         │ (PyTorch)   │        │  (预测结果) │
    └────────────┘         └─────────────┘        └─────────────┘

🎯 核心API详细说明

📊 数据管理API

GET /api/products

功能: 获取所有产品列表 返回:

{
  "status": "success",
  "data": [
    {
      "product_id": "P001",
      "product_name": "阿莫西林胶囊",
      "category": "抗生素",
      "price": 12.5
    }
  ]
}

GET /api/products/{product_id}/sales

功能: 获取指定产品销售数据 参数:

  • product_id: 产品ID
  • start_date: 开始日期 (可选)
  • end_date: 结束日期 (可选)

POST /api/data/upload

功能: 上传Excel销售数据 请求体: multipart/form-data 文件格式:

日期        | 产品ID | 产品名称    | 销量 | 价格
2024-01-01 | P001   | 阿莫西林   | 120  | 12.5

🏋️ 模型训练API

POST /api/training

功能: 启动模型训练任务 请求体:

{
  "product_id": "P001",
  "model_type": "mlstm",
  "hyperparameters": {
    "epochs": 100,
    "batch_size": 32,
    "learning_rate": 0.001
  }
}

GET /api/training/{task_id}

功能: 查询训练任务状态 返回:

{
  "status": "success",
  "data": {
    "task_id": "train_123",
    "status": "running|completed|failed",
    "progress": 75,
    "current_epoch": 75,
    "total_epochs": 100,
    "loss": 0.0245,
    "model_path": "saved_models/P001_mlstm_model.pt"
  }
}

🔮 预测分析API

POST /api/prediction

功能: 执行销售预测 请求体:

{
  "product_id": "P001",
  "model_type": "mlstm",
  "model_id": "P001_mlstm_20241201",
  "start_date": "2024-12-15",
  "future_days": 7
}

响应:

{
  "status": "success",
  "meta": {
    "product_name": "阿莫西林胶囊",
    "model_type": "mLSTM",
    "start_date": "2024-12-15",
    "created_at": "2024-12-14T10:30:00"
  },
  "data": {
    "prediction_data": [
      {"date": "2024-12-15", "predicted_sales": 125, "type": "预测销量"},
      {"date": "2024-12-16", "predicted_sales": 118, "type": "预测销量"}
    ],
    "history_data": [
      {"date": "2024-12-13", "actual_sales": 120, "type": "历史销量"},
      {"date": "2024-12-14", "actual_sales": 115, "type": "历史销量"}
    ],
    "data": [
      {"date": "2024-12-13", "sales": 120, "type": "历史销量"},
      {"date": "2024-12-15", "sales": 125, "type": "预测销量"}
    ]
  },
  "analysis": {
    "total_predicted": 861,
    "average_daily": 123,
    "trend": "stable",
    "confidence": 0.85
  },
  "chart_data": {
    "dates": ["2024-12-13", "2024-12-14", "2024-12-15"],
    "history_sales": [120, 115, null],
    "predicted_sales": [null, null, 125]
  }
}

GET /api/prediction/history

功能: 获取历史预测记录 参数:

  • page: 页码 (默认1)
  • size: 每页数量 (默认10)
  • product_id: 产品ID过滤 (可选)
  • model_type: 模型类型过滤 (可选)

GET /api/prediction/history/{prediction_id}

功能: 获取预测详情 返回: 与POST /api/prediction相同格式

🎛️ 模型管理API

GET /api/models

功能: 获取模型列表 返回:

{
  "status": "success",
  "data": [
    {
      "model_id": "P001_mlstm_20241201",
      "product_id": "P001",
      "product_name": "阿莫西林胶囊",
      "model_type": "mLSTM",
      "created_at": "2024-12-01T15:30:00",
      "accuracy": 0.92,
      "file_size": "2.5MB",
      "training_epochs": 100
    }
  ]
}

DELETE /api/models/{model_id}

功能: 删除模型文件

🎨 前端组件详细架构

DataView.vue - 数据管理页面

核心功能:

  • Excel文件上传和解析
  • 数据预览和验证
  • 产品销售数据查看
  • 数据统计图表展示

关键组件:

<template>
  <div class="data-view">
    <el-upload :on-success="handleUploadSuccess" />
    <el-table :data="salesData" />
    <div ref="chartContainer" class="chart-container" />
  </div>
</template>

TrainingView.vue - 模型训练页面

核心功能:

  • 选择产品和模型类型
  • 配置训练超参数
  • 实时监控训练进度
  • 训练日志展示

状态管理:

const trainingState = reactive({
  isTraining: false,
  progress: 0,
  currentEpoch: 0,
  totalEpochs: 100,
  loss: 0
});

PredictionView.vue - 预测分析页面

核心功能:

  • 选择产品和已训练模型
  • 设置预测参数
  • 执行预测分析
  • 结果可视化展示

图表配置:

const chartOption = {
  title: { text: '销售预测分析' },
  xAxis: { data: dates },
  yAxis: { name: '销量' },
  series: [
    { name: '历史销量', type: 'line', data: historyData },
    { name: '预测销量', type: 'line', data: predictedData }
  ]
};

HistoryView.vue - 历史查看页面

核心功能:

  • 分页展示历史预测
  • 预测详情查看
  • 结果对比分析
  • 数据导出功能

数据处理:

const viewDetails = async (id) => {
  const response = await api.get(`/api/prediction/history/${id}`);
  currentPrediction.value = response.data;
  // 安全属性访问
  productName.value = response.data.meta?.product_name || '未知产品';
};

ManagementView.vue - 模型管理页面

核心功能:

  • 模型列表展示
  • 模型性能监控
  • 模型删除和备份
  • 存储空间管理

🗄️ 数据存储架构

SQLite数据库

表结构:

-- 产品信息表
CREATE TABLE products (
    product_id TEXT PRIMARY KEY,
    product_name TEXT NOT NULL,
    category TEXT,
    price REAL
);

-- 销售数据表
CREATE TABLE sales_data (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    product_id TEXT,
    date DATE,
    sales_volume INTEGER,
    revenue REAL,
    FOREIGN KEY (product_id) REFERENCES products(product_id)
);

-- 预测历史表
CREATE TABLE prediction_history (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    product_id TEXT,
    product_name TEXT,
    model_type TEXT,
    model_id TEXT,
    start_date DATE,
    future_days INTEGER,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    file_path TEXT,
    FOREIGN KEY (product_id) REFERENCES products(product_id)
);

文件存储结构

server/
├── static/
│   ├── csv/                    # CSV数据文件
│   ├── plots/                  # 生成的图表
│   └── predictions/            # 预测结果JSON
│       ├── compare/            # 对比分析
│       └── {model_type}/       # 按模型分类
├── saved_models/               # 训练好的模型
│   ├── {product_id}_{model_type}_{timestamp}.pt
└── predictions/                # 预测结果
    ├── history/                # 历史记录JSON
    └── {model_type}/           # 按模型分类
        └── {product_id}/       # 按产品分类

🔄 数据流程详解

1. 数据上传流程

Excel文件 → 后端解析 → 数据验证 → 存储到SQLite → 返回结果

2. 模型训练流程

选择参数 → 创建训练任务 → 异步训练 → 保存模型 → 更新状态

3. 预测执行流程

选择模型 → 加载数据 → 执行预测 → 生成图表 → 保存结果 → 返回JSON

4. 历史查看流程

查询数据库 → 读取JSON文件 → 合并数据 → 构建响应 → 前端展示

🛠️ 核心工具类

后端工具类

# server/utils/data_utils.py
class DataProcessor:
    def preprocess_sales_data(self, data: pd.DataFrame) -> pd.DataFrame
    def split_train_test(self, data: pd.DataFrame, test_size: float = 0.2)
    def normalize_data(self, data: np.ndarray) -> np.ndarray

# server/utils/visualization.py
class ChartGenerator:
    def create_prediction_chart(self, history_data, prediction_data)
    def save_chart_image(self, chart_data, file_path: str)

前端工具类

// UI/src/utils/chart.js
export const createPredictionChart = (historyData, predictedData) => {
  return {
    title: { text: '销售预测分析' },
    // ... 图表配置
  };
};

// UI/src/utils/api.js
export const api = {
  get: (url) => axios.get(url),
  post: (url, data) => axios.post(url, data),
  // ... API封装
};

🚨 错误处理机制

后端错误处理

@app.errorhandler(Exception)
def handle_error(error):
    return jsonify({
        'status': 'error',
        'message': str(error),
        'error_type': type(error).__name__
    }), 500

前端错误处理

// 全局错误处理
const handleApiError = (error) => {
  const message = error.response?.data?.message || '操作失败';
  ElMessage.error(message);
  console.error('API Error:', error);
};

🔧 性能优化策略

后端优化

  • 异步训练: 使用线程池执行训练任务
  • 模型缓存: 内存中缓存常用模型
  • 数据分页: 大数据集分页返回
  • 文件压缩: JSON结果gzip压缩

前端优化

  • 懒加载: 图表数据按需加载
  • 虚拟滚动: 大列表性能优化
  • 组件缓存: keep-alive缓存页面状态
  • 防抖节流: 频繁API调用优化

🏗️ 此文档提供系统架构的详细信息,帮助理解项目的整体设计和实现