# WeSmart 后端 API 规范 v1.0

**版本**: v1.0  
**日期**: 2026-03-03  
**状态**: 设计规范，待开发实现

---

## 1. 概述

### 1.1 设计目标
- 实现真正的服务器端数据持久化
- 支持文件的上传、删除、同步
- 支持贡献数据的实时同步
- 统一认证体系

### 1.2 技术栈建议
- **后端**: Node.js + Express / Python + FastAPI
- **数据库**: SQLite (轻量级) / PostgreSQL (企业级)
- **文件存储**: 本地文件系统 / OSS对象存储
- **认证**: JWT Token

---

## 2. 认证接口

### 2.1 用户登录
```http
POST /api/auth/login
Content-Type: application/json

{
    "phone": "13981734846",
    "password": "123456"
}
```

**响应**:
```json
{
    "success": true,
    "data": {
        "token": "eyJhbGciOiJIUzI1NiIs...",
        "user": {
            "phone": "13981734846",
            "name": "李茂林",
            "isAdmin": true,
            "folder": "limaolin"
        },
        "expire": 1709491200000
    }
}
```

### 2.2 验证Token
```http
GET /api/auth/verify
Authorization: Bearer {token}
```

### 2.3 修改密码
```http
POST /api/auth/change-password
Authorization: Bearer {token}
Content-Type: application/json

{
    "oldPassword": "123456",
    "newPassword": "newpass123"
}
```

---

## 3. 文件管理接口

### 3.1 获取文件列表
```http
GET /api/files/list?folder={my|common|temp}
Authorization: Bearer {token}
```

**响应**:
```json
{
    "success": true,
    "data": [
        {
            "id": "file_001",
            "name": "报告.html",
            "size": 15360,
            "sizeFormatted": "15KB",
            "type": "html",
            "url": "/files/users/limaolin/报告.html",
            "createdAt": "2026-03-03T00:00:00Z",
            "createdBy": "李茂林",
            "folder": "my"
        }
    ]
}
```

### 3.2 上传文件
```http
POST /api/files/upload
Authorization: Bearer {token}
Content-Type: multipart/form-data

file: [二进制文件]
folder: my
```

**响应**:
```json
{
    "success": true,
    "data": {
        "id": "file_002",
        "name": "上传的文件.html",
        "url": "/files/users/limaolin/上传的文件.html",
        "size": 20480
    }
}
```

### 3.3 删除文件
```http
DELETE /api/files/{fileId}
Authorization: Bearer {token}
```

**权限检查**:
- 自己的文件：可以删除
- 公共文件夹：仅管理员可删除
- 临时文件夹：所有人可删除

### 3.4 推送文件到其他文件夹
```http
POST /api/files/push
Authorization: Bearer {token}
Content-Type: application/json

{
    "fileId": "file_001",
    "targetFolder": "common"
}
```

---

## 4. 工具/项目接口（贡献系统）

### 4.1 贡献工具
```http
POST /api/tools/contribute
Authorization: Bearer {token}
Content-Type: application/json

{
    "name": "楼梯灯产品介绍",
    "desc": "详细介绍楼梯灯产品参数和优势",
    "url": "/internal/users/limaolin/楼梯灯产品介绍.html",
    "type": "html"
}
```

**响应**:
```json
{
    "success": true,
    "data": {
        "id": "tool_001",
        "name": "楼梯灯产品介绍",
        "status": "pending",
        "createdAt": "2026-03-03T00:00:00Z",
        "source": "李茂林"
    }
}
```

### 4.2 获取工具列表
```http
GET /api/tools/list?status={all|pending|approved|pinned}
Authorization: Bearer {token}
```

**响应**:
```json
{
    "success": true,
    "data": {
        "pinned": [
            {
                "id": "tool_001",
                "name": "楼梯灯招商政策",
                "desc": "2026年招商政策",
                "url": "...",
                "source": "系统",
                "likes": 15,
                "isPinned": true
            }
        ],
        "contrib": [
            {
                "id": "tool_002",
                "name": "楼梯灯产品介绍",
                "desc": "产品介绍页面",
                "url": "...",
                "source": "李茂林",
                "likes": 5,
                "isPinned": false
            }
        ]
    }
}
```

### 4.3 管理员置顶工具
```http
POST /api/tools/pin
Authorization: Bearer {token}
Content-Type: application/json

{
    "toolId": "tool_002",
    "action": "pin"  // or "unpin"
}
```

**权限**: 仅管理员

### 4.4 点赞工具
```http
POST /api/tools/like
Authorization: Bearer {token}
Content-Type: application/json

{
    "toolId": "tool_001"
}
```

**限制**: 每人每月10个点赞点

---

## 5. 用户管理接口（管理员）

### 5.1 获取用户列表
```http
GET /api/users/list
Authorization: Bearer {admin_token}
```

### 5.2 修改用户密码
```http
POST /api/users/reset-password
Authorization: Bearer {admin_token}
Content-Type: application/json

{
    "phone": "13760323136",
    "newPassword": "newpass123"
}
```

### 5.3 添加新用户
```http
POST /api/users/create
Authorization: Bearer {admin_token}
Content-Type: application/json

{
    "phone": "13800138000",
    "name": "新员工",
    "folder": "xin yuangong",
    "isAdmin": false
}
```

---

## 6. 数据库设计

### 6.1 用户表 (users)
```sql
CREATE TABLE users (
    phone VARCHAR(20) PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    folder VARCHAR(50) NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    is_admin BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

### 6.2 文件表 (files)
```sql
CREATE TABLE files (
    id VARCHAR(50) PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    original_name VARCHAR(255),
    path VARCHAR(500) NOT NULL,
    size BIGINT,
    type VARCHAR(50),
    owner_phone VARCHAR(20),
    folder ENUM('my', 'common', 'temp'),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (owner_phone) REFERENCES users(phone)
);
```

### 6.3 工具表 (tools)
```sql
CREATE TABLE tools (
    id VARCHAR(50) PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    url VARCHAR(500) NOT NULL,
    type VARCHAR(50),
    source_phone VARCHAR(20),
    status ENUM('pending', 'approved', 'rejected', 'pinned') DEFAULT 'pending',
    likes INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (source_phone) REFERENCES users(phone)
);
```

### 6.4 点赞记录表 (likes)
```sql
CREATE TABLE likes (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_phone VARCHAR(20),
    tool_id VARCHAR(50),
    month VARCHAR(7),  -- 格式: 2026-03
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_phone) REFERENCES users(phone),
    FOREIGN KEY (tool_id) REFERENCES tools(id),
    UNIQUE KEY unique_like (user_phone, tool_id, month)
);
```

---

## 7. 文件存储规范

### 7.1 目录结构
```
/var/www/html/files/
├── users/
│   ├── limaolin/
│   │   ├── 报告.html
│   │   └── 产品介绍.html
│   ├── xiezhongxiang/
│   └── ...
├── common/
│   └── 公共文件.html
└── temp/
    └── 临时文件.html
```

### 7.2 文件命名
- 原始文件名保留
- 存储时添加用户前缀避免冲突
- 支持中文文件名（URL编码）

---

## 8. 安全规范

### 8.1 认证
- 使用 JWT Token
- Token 24小时过期
- 密码使用 bcrypt 加密存储

### 8.2 文件上传
- 限制文件类型（白名单）
- 限制文件大小（如 50MB）
- 扫描恶意文件

### 8.3 CORS
```javascript
app.use(cors({
    origin: ['http://118.126.91.196', 'https://yourdomain.com'],
    credentials: true
}));
```

---

## 9. 部署建议

### 9.1 环境变量
```bash
# .env
DB_PATH=/data/wesmart.db
JWT_SECRET=your-secret-key
FILE_STORAGE_PATH=/var/www/html/files
MAX_FILE_SIZE=52428800  # 50MB
```

### 9.2 启动命令
```bash
# Node.js
npm install
npm start

# Python
pip install -r requirements.txt
python app.py
```

### 9.3 Nginx配置
```nginx
location /api/ {
    proxy_pass http://localhost:3000/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}
```

---

## 10. 实现优先级

### P0 - 核心功能（必须）
1. 用户登录/认证
2. 文件上传/下载
3. 贡献工具提交
4. 工具列表查询

### P1 - 重要功能（建议）
1. 文件删除
2. 管理员置顶
3. 点赞系统
4. 用户管理

### P2 - 优化功能（可选）
1. 文件预览
2. 搜索功能
3. 统计报表
4. 日志审计

---

## 附录：前端迁移指南

### 当前（浏览器存储）→ 目标（服务器API）

| 当前实现 | 目标API | 备注 |
|---------|---------|------|
| localStorage 保存文件列表 | GET /api/files/list | 实时同步 |
| FileReader 本地读取 | POST /api/files/upload | 服务器存储 |
| localStorage 删除记录 | DELETE /api/files/{id} | 真正删除文件 |
| IndexedDB 贡献数据 | POST /api/tools/contribute | 实时同步 |
| IndexedDB 用户数据 | 服务器Session | 统一认证 |

---

**编写**: AI Assistant  
**审核**: 待补充  
**实施**: 待开发团队评估
