Merge remote-tracking branch 'origin/master'

# Conflicts:
#	PRD.md
#	arch.md
#	backend/data-sync-fix-report.md
#	backend/farms-data-import-summary.md
#	backend/location-data-validation-report.md
#	design.md
#	dev-plan.md
#	docs/PRD.md
#	docs/README.md
#	docs/architecture.md
#	docs/config/PRD.md
#	docs/config/arch.md
#	docs/config/data-sync-fix-report.md
#	docs/config/design.md
#	docs/config/dev-plan.md
#	docs/config/farms-data-import-summary.md
#	docs/config/location-data-validation-report.md
#	docs/config/task.md
#	docs/data-sync-fix-report.md
#	docs/design.md
#	docs/development-plan.md
#	docs/farms-data-import-summary.md
#	docs/location-data-validation-report.md
#	docs/task-list.md
#	task.md
This commit is contained in:
2025-09-12 19:51:13 +08:00
78 changed files with 5449 additions and 272 deletions

76
.gitignore vendored
View File

@@ -4,6 +4,7 @@ node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Environment variables
.env
@@ -11,12 +12,17 @@ yarn-error.log*
.env.development.local
.env.test.local
.env.production.local
.env.*.local
# Build outputs
dist/
build/
*/dist/
*/build/
out/
.nuxt/
.next/
.cache/
# IDE files
.vscode/
@@ -24,6 +30,8 @@ build/
*.swp
*.swo
*~
*.sublime-project
*.sublime-workspace
# OS files
.DS_Store
@@ -38,24 +46,86 @@ Thumbs.db
logs/
*.log
*/logs/
# Runtime data
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
# Runtime data
lib-cov
coverage/
.nyc_output
.grunt
bower_components
.lock-wscript
# Database
*.sqlite
*.db
*.sql.backup
# Temporary files
tmp/
temp/
.tmp/
# Testing
.jest/
.coverage/
test-results/
junit.xml
# Documentation
.docusaurus/
# Deployment
.vercel
.netlify
# Package manager lock files (optional)
# package-lock.json
# yarn.lock
# Project specific
# Backup files
*.backup
*.bak
*.orig
# Security
secrets/
*.pem
*.key
*.cert
*.crt
# Performance monitoring
.tsbuildinfo
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# parcel-bundler cache (https://parceljs.org/)
.parcel-cache

122
README.md
View File

@@ -1,122 +0,0 @@
# 宁夏智慧养殖监管平台
## 项目概述
宁夏智慧养殖监管平台是一个现代化的农场管理系统,提供实时监控、数据分析和多终端访问功能。
## 目录结构
```
nxxmdata/
├── backend/ # 后端服务 (Node.js + Express + Sequelize)
│ ├── config/ # 配置文件
│ ├── controllers/ # 业务逻辑控制器
│ ├── models/ # 数据模型
│ ├── routes/ # API路由
│ ├── middleware/ # 中间件
│ ├── utils/ # 工具类
│ ├── migrations/ # 数据库迁移
│ ├── seeds/ # 种子数据
│ └── server.js # 服务器入口
├── admin-system/ # 管理后台 (Vue.js 3.x)
│ └── frontend/ # 前端项目
├── website/ # 官网 (Vue.js 3.x)
│ └── data-screen/ # 数据大屏展示
├── mini_program/ # 微信小程序矩阵
│ └── farm-monitor-dashboard/ # 监控仪表盘小程序
├── scripts/ # 执行脚本目录
│ ├── init-db.js # 数据库初始化
│ ├── migration-manager.js # 迁移管理
│ ├── seed-manager.js # 种子数据管理
│ ├── test-connection.js # 连接测试
│ └── test-map-api.js # 地图API测试
├── docs/ # 文档目录
│ ├── baidu-map-license.md # 百度地图许可
│ └── performance-monitoring.md # 性能监控文档
├── test/ # 测试文件目录
│ └── performance-monitor-test.js # 性能监控测试
├── examples/ # 示例代码
└── 配置文件
├── arch.md # 架构文档
├── design.md # 详细设计
├── PRD.md # 产品需求文档
├── dev-plan.md # 开发计划
├── task.md # 任务列表
├── schema.sql # 数据库架构
└── create_tables.sql # 建表脚本
```
## 技术栈
### 后端技术栈
- **运行环境**: Node.js 18.0+
- **Web框架**: Express.js 4.18+
- **ORM框架**: Sequelize 6.30+
- **数据库**: MySQL (mysql2 3.0+)
- **认证**: JWT (jsonwebtoken 9.0+)
- **密码加密**: bcrypt 5.1+
- **API文档**: Swagger (swagger-jsdoc + swagger-ui-express)
- **日志管理**: Winston 3.17+
- **开发工具**: nodemon 3.0+
- **跨域处理**: CORS 2.8+
- **数据验证**: express-validator 7.2+
- **环境变量**: dotenv 16.0+
- **HTTP客户端**: Axios 1.4+
- **服务器端口**: 5350
### 前端技术栈
- **管理后台**: Vue.js 3.4+ + Ant Design Vue 4.0+
- **官网**: Vue.js 3.4+ + ECharts 5.4+
- **微信小程序**: React + TypeScript + Tailwind CSS
- **构建工具**: Vite 5.0+
- **状态管理**: Pinia 2.0+
- **路由管理**: Vue Router 4.0+
## 核心功能
- ✅ 实时设备监控
- ✅ 动物健康管理
- ✅ 地图可视化展示
- ✅ 数据分析报表
- ✅ 多角色权限系统
- ✅ 订单管理功能
- ✅ 预警管理系统
- ✅ 性能监控分析
## 快速开始
### 后端启动
```bash
cd backend
npm install
npm run dev
```
### 管理后台启动
```bash
cd admin-system/frontend
npm install
npm run dev
```
### 官网启动
```bash
cd website/data-screen
npm install
npm run dev
```
## 开发规范
1. 遵循模块化开发原则
2. 代码注释规范清晰
3. API接口文档完整
4. 数据库迁移脚本可重复执行
5. 测试用例覆盖核心功能
## 部署说明
生产环境建议使用Docker容器化部署具体部署流程参考各模块的部署文档。
---
*最后更新: 2025年8月*

81
backend/tools/README.md Normal file
View File

@@ -0,0 +1,81 @@
# 后端工具目录
本目录包含用于开发、测试、数据管理和系统维护的各种工具脚本。
## 📂 目录结构
```
tools/
├── data-management/ # 数据管理和维护脚本
├── testing/ # 测试相关脚本
├── verification/ # 数据验证和检查脚本
└── README.md # 本文档
```
## 🔧 数据管理脚本 (`data-management/`)
包含用于数据库操作、数据导入导出、数据修复等的脚本:
- **创建和生成**: `create-*.js`, `generate-*.js`
- **导入和插入**: `import-*.js`, `insert-*.js`
- **修复和更新**: `fix-*.js`, `update-*.js`, `reset_*.js`
- **重新排序**: `reorder-*.js`, `simple-*.js`
- **数据恢复**: `restore-*.js`
- **清理操作**: `cleanup-*.js`
## 🧪 测试脚本 (`testing/`)
包含各种功能测试、API测试、集成测试脚本
- **API测试**: `test-*-api.js`
- **数据库测试**: `test-db-*.js`, `test-simple-db.js`
- **功能测试**: `test-*-flow.js`, `test-*-binding.js`
- **工具测试**: `test_*.js`
## ✅ 验证脚本 (`verification/`)
包含数据验证、系统检查、分析工具:
- **数据检查**: `check-*.js`, `check_*.js`
- **数据验证**: `verify-*.js`
- **系统分析**: `analyze-*.js`
- **统计计数**: `count-*.js`
## 📝 使用说明
### 运行脚本
```bash
# 从backend目录运行
cd backend
# 运行数据管理脚本
node tools/data-management/import-farms-static-data.js
# 运行测试脚本
node tools/testing/test-db-connection.js
# 运行验证脚本
node tools/verification/check-current-data.js
```
### 环境要求
- Node.js 18.0+
- 正确配置的 .env 文件
- MySQL 数据库连接
### ⚠️ 注意事项
1. **生产环境谨慎**: 数据管理脚本可能会修改数据库,在生产环境使用前请务必备份
2. **依赖检查**: 运行前确保所有依赖已安装 (`npm install`)
3. **权限要求**: 某些脚本需要数据库管理员权限
4. **日志记录**: 重要操作会生成日志,请注意查看
### 🔗 相关文档
- [开发指南](../../DEVELOPMENT.md)
- [故障排除](../../TROUBLESHOOTING.md)
- [API文档](../../API.md)
---
*最后更新: 2025年1月*

View File

@@ -1,23 +1,23 @@
const fs = require('fs');
const path = require('path');
const migrationFile = path.join(__dirname, 'migrations/20230101000000_initial_schema.js');
// 读取迁移文件
let content = fs.readFileSync(migrationFile, 'utf8');
// 替换所有的 Sequelize. 为 DataTypes.
content = content.replace(/Sequelize\.STRING/g, 'DataTypes.STRING');
content = content.replace(/Sequelize\.INTEGER/g, 'DataTypes.INTEGER');
content = content.replace(/Sequelize\.TEXT/g, 'DataTypes.TEXT');
content = content.replace(/Sequelize\.DECIMAL/g, 'DataTypes.DECIMAL');
content = content.replace(/Sequelize\.ENUM/g, 'DataTypes.ENUM');
content = content.replace(/Sequelize\.DATE/g, 'DataTypes.DATE');
// 修复literal函数
content = content.replace(/DataTypes\.literal/g, 'literal');
// 写入修复后的文件
fs.writeFileSync(migrationFile, content, 'utf8');
console.log('✅ 迁移文件数据类型已修复');
const fs = require('fs');
const path = require('path');
const migrationFile = path.join(__dirname, 'migrations/20230101000000_initial_schema.js');
// 读取迁移文件
let content = fs.readFileSync(migrationFile, 'utf8');
// 替换所有的 Sequelize. 为 DataTypes.
content = content.replace(/Sequelize\.STRING/g, 'DataTypes.STRING');
content = content.replace(/Sequelize\.INTEGER/g, 'DataTypes.INTEGER');
content = content.replace(/Sequelize\.TEXT/g, 'DataTypes.TEXT');
content = content.replace(/Sequelize\.DECIMAL/g, 'DataTypes.DECIMAL');
content = content.replace(/Sequelize\.ENUM/g, 'DataTypes.ENUM');
content = content.replace(/Sequelize\.DATE/g, 'DataTypes.DATE');
// 修复literal函数
content = content.replace(/DataTypes\.literal/g, 'literal');
// 写入修复后的文件
fs.writeFileSync(migrationFile, content, 'utf8');
console.log('✅ 迁移文件数据类型已修复');

View File

@@ -1,63 +1,63 @@
const mysql = require('mysql2/promise');
require('dotenv').config();
async function testConnection() {
const config = {
host: process.env.DB_HOST || '129.211.213.226',
port: process.env.DB_PORT || 3306,
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || 'Aiotagro@741',
database: process.env.DB_NAME || 'nxTest',
connectTimeout: 10000,
acquireTimeout: 10000,
timeout: 10000
};
console.log('尝试连接数据库...');
console.log('配置:', {
host: config.host,
port: config.port,
user: config.user,
database: config.database
});
try {
const connection = await mysql.createConnection(config);
console.log('✅ 数据库连接成功!');
// 测试查询
const [rows] = await connection.execute('SELECT 1 as test');
console.log('✅ 查询测试成功:', rows);
// 获取数据库信息
const [dbInfo] = await connection.execute('SELECT DATABASE() as current_db, VERSION() as version');
console.log('✅ 数据库信息:', dbInfo);
await connection.end();
console.log('✅ 连接已关闭');
} catch (error) {
console.error('❌ 数据库连接失败:');
console.error('错误代码:', error.code);
console.error('错误消息:', error.message);
console.error('完整错误:', error);
// 提供一些常见错误的解决方案
if (error.code === 'ECONNREFUSED') {
console.log('\n💡 可能的解决方案:');
console.log('1. 检查MySQL服务是否正在运行');
console.log('2. 检查端口3306是否开放');
console.log('3. 检查防火墙设置');
} else if (error.code === 'ER_ACCESS_DENIED_ERROR') {
console.log('\n💡 可能的解决方案:');
console.log('1. 检查用户名和密码是否正确');
console.log('2. 检查用户是否有远程访问权限');
} else if (error.code === 'ER_BAD_DB_ERROR') {
console.log('\n💡 可能的解决方案:');
console.log('1. 检查数据库名称是否正确');
console.log('2. 检查数据库是否存在');
}
}
}
testConnection();
const mysql = require('mysql2/promise');
require('dotenv').config();
async function testConnection() {
const config = {
host: process.env.DB_HOST || '129.211.213.226',
port: process.env.DB_PORT || 3306,
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || 'Aiotagro@741',
database: process.env.DB_NAME || 'nxTest',
connectTimeout: 10000,
acquireTimeout: 10000,
timeout: 10000
};
console.log('尝试连接数据库...');
console.log('配置:', {
host: config.host,
port: config.port,
user: config.user,
database: config.database
});
try {
const connection = await mysql.createConnection(config);
console.log('✅ 数据库连接成功!');
// 测试查询
const [rows] = await connection.execute('SELECT 1 as test');
console.log('✅ 查询测试成功:', rows);
// 获取数据库信息
const [dbInfo] = await connection.execute('SELECT DATABASE() as current_db, VERSION() as version');
console.log('✅ 数据库信息:', dbInfo);
await connection.end();
console.log('✅ 连接已关闭');
} catch (error) {
console.error('❌ 数据库连接失败:');
console.error('错误代码:', error.code);
console.error('错误消息:', error.message);
console.error('完整错误:', error);
// 提供一些常见错误的解决方案
if (error.code === 'ECONNREFUSED') {
console.log('\n💡 可能的解决方案:');
console.log('1. 检查MySQL服务是否正在运行');
console.log('2. 检查端口3306是否开放');
console.log('3. 检查防火墙设置');
} else if (error.code === 'ER_ACCESS_DENIED_ERROR') {
console.log('\n💡 可能的解决方案:');
console.log('1. 检查用户名和密码是否正确');
console.log('2. 检查用户是否有远程访问权限');
} else if (error.code === 'ER_BAD_DB_ERROR') {
console.log('\n💡 可能的解决方案:');
console.log('1. 检查数据库名称是否正确');
console.log('2. 检查数据库是否存在');
}
}
}
testConnection();

View File

@@ -1,13 +1,13 @@
const { testConnection } = require('./config/database-simple');
async function test() {
console.log('测试数据库连接...');
const result = await testConnection();
if (result) {
console.log('✅ 数据库连接测试成功');
} else {
console.log('❌ 数据库连接测试失败');
}
}
test();
const { testConnection } = require('./config/database-simple');
async function test() {
console.log('测试数据库连接...');
const result = await testConnection();
if (result) {
console.log('✅ 数据库连接测试成功');
} else {
console.log('❌ 数据库连接测试失败');
}
}
test();

View File

@@ -1,48 +1,48 @@
const db = require('./config/database');
const SensorData = require('./models/SensorData');
(async () => {
try {
// 检查传感器数据总数
const count = await SensorData.count();
console.log('传感器数据总数:', count);
// 检查最近的温度数据
const temperatureData = await SensorData.findAll({
where: { sensor_type: 'temperature' },
limit: 10,
order: [['recorded_at', 'DESC']]
});
console.log('\n最近10条温度数据:');
temperatureData.forEach(r => {
console.log(`${r.sensor_type}: ${r.value}${r.unit} at ${r.recorded_at}`);
});
// 检查最近的湿度数据
const humidityData = await SensorData.findAll({
where: { sensor_type: 'humidity' },
limit: 10,
order: [['recorded_at', 'DESC']]
});
console.log('\n最近10条湿度数据:');
humidityData.forEach(r => {
console.log(`${r.sensor_type}: ${r.value}${r.unit} at ${r.recorded_at}`);
});
// 检查24小时内的数据
const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
const recentCount = await SensorData.count({
where: {
recorded_at: {
[require('sequelize').Op.gte]: twentyFourHoursAgo
}
}
});
console.log('\n24小时内的传感器数据总数:', recentCount);
} catch (error) {
console.error('检查数据时出错:', error);
} finally {
process.exit();
}
const db = require('./config/database');
const SensorData = require('./models/SensorData');
(async () => {
try {
// 检查传感器数据总数
const count = await SensorData.count();
console.log('传感器数据总数:', count);
// 检查最近的温度数据
const temperatureData = await SensorData.findAll({
where: { sensor_type: 'temperature' },
limit: 10,
order: [['recorded_at', 'DESC']]
});
console.log('\n最近10条温度数据:');
temperatureData.forEach(r => {
console.log(`${r.sensor_type}: ${r.value}${r.unit} at ${r.recorded_at}`);
});
// 检查最近的湿度数据
const humidityData = await SensorData.findAll({
where: { sensor_type: 'humidity' },
limit: 10,
order: [['recorded_at', 'DESC']]
});
console.log('\n最近10条湿度数据:');
humidityData.forEach(r => {
console.log(`${r.sensor_type}: ${r.value}${r.unit} at ${r.recorded_at}`);
});
// 检查24小时内的数据
const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
const recentCount = await SensorData.count({
where: {
recorded_at: {
[require('sequelize').Op.gte]: twentyFourHoursAgo
}
}
});
console.log('\n24小时内的传感器数据总数:', recentCount);
} catch (error) {
console.error('检查数据时出错:', error);
} finally {
process.exit();
}
})();

894
docs/API.md Normal file
View File

@@ -0,0 +1,894 @@
# API 文档
## 概述
宁夏智慧养殖监管平台提供全面的RESTful API支持农场管理、设备监控、动物健康管理、用户管理、订单管理等核心功能。
## 基础信息
- **Base URL**: `http://localhost:5350/api` (开发环境)
- **Authentication**: JWT Bearer Token
- **Content-Type**: `application/json`
- **API Version**: v1.0
## 认证机制
### JWT Token认证
所有需要认证的API都需要在请求头中包含JWT Token
```http
Authorization: Bearer <your_jwt_token>
```
### Token获取
通过登录接口获取Token
```http
POST /api/auth/login
Content-Type: application/json
{
"username": "your_username",
"password": "your_password"
}
```
## 通用响应格式
### 成功响应
```json
{
"success": true,
"data": {},
"message": "操作成功",
"timestamp": "2025-01-18T10:30:00Z"
}
```
### 错误响应
```json
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "错误描述",
"details": "详细错误信息"
},
"timestamp": "2025-01-18T10:30:00Z"
}
```
### HTTP状态码
- `200` - 请求成功
- `201` - 创建成功
- `400` - 请求参数错误
- `401` - 未认证或Token过期
- `403` - 权限不足
- `404` - 资源不存在
- `409` - 资源冲突
- `500` - 服务器内部错误
## 认证相关API
### 用户登录
```http
POST /api/auth/login
```
**请求体:**
```json
{
"username": "admin",
"password": "password123"
}
```
**响应:**
```json
{
"success": true,
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": 1,
"username": "admin",
"email": "admin@example.com",
"roles": ["admin"]
}
}
}
```
### 用户注册
```http
POST /api/auth/register
```
**请求体:**
```json
{
"username": "newuser",
"email": "newuser@example.com",
"password": "password123",
"phone": "13800138000"
}
```
### 用户登出
```http
POST /api/auth/logout
```
**需要认证**: 是
### 验证Token
```http
GET /api/auth/verify
```
**需要认证**: 是
## 用户管理API
### 获取用户列表
```http
GET /api/users
```
**需要认证**: 是
**权限要求**: admin
**查询参数:**
- `page` (int): 页码默认1
- `limit` (int): 每页数量默认10
- `search` (string): 搜索关键词
- `status` (string): 用户状态 (`active`, `inactive`, `banned`)
**响应:**
```json
{
"success": true,
"data": {
"users": [
{
"id": 1,
"username": "admin",
"email": "admin@example.com",
"phone": "13800138000",
"status": "active",
"created_at": "2025-01-01T00:00:00Z",
"roles": ["admin"]
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 1,
"pages": 1
}
}
}
```
### 获取用户详情
```http
GET /api/users/{id}
```
**需要认证**: 是
### 创建用户
```http
POST /api/users
```
**需要认证**: 是
**权限要求**: admin
**请求体:**
```json
{
"username": "newuser",
"email": "newuser@example.com",
"password": "password123",
"phone": "13800138000",
"status": "active",
"roles": ["user"]
}
```
### 更新用户
```http
PUT /api/users/{id}
```
**需要认证**: 是
### 删除用户
```http
DELETE /api/users/{id}
```
**需要认证**: 是
**权限要求**: admin
## 养殖场管理API
### 获取养殖场列表
```http
GET /api/farms
```
**需要认证**: 是
**查询参数:**
- `page` (int): 页码默认1
- `limit` (int): 每页数量默认10
- `type` (string): 养殖场类型
- `status` (string): 状态 (`active`, `inactive`, `maintenance`)
**响应:**
```json
{
"success": true,
"data": {
"farms": [
{
"id": 1,
"name": "宁夏示范养殖场",
"type": "奶牛养殖",
"location": {
"lat": 38.46667,
"lng": 106.26667
},
"address": "宁夏回族自治区银川市金凤区",
"contact": "张经理",
"phone": "13800138000",
"status": "active",
"created_at": "2025-01-01T00:00:00Z"
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 1,
"pages": 1
}
}
}
```
### 获取公开养殖场数据
```http
GET /api/farms/public
```
**需要认证**: 否
### 获取养殖场详情
```http
GET /api/farms/{id}
```
**需要认证**: 是
### 创建养殖场
```http
POST /api/farms
```
**需要认证**: 是
**权限要求**: manager
**请求体:**
```json
{
"name": "新养殖场",
"type": "养猪场",
"longitude": 106.26667,
"latitude": 38.46667,
"address": "详细地址",
"owner": "联系人姓名",
"phone": "13800138000",
"status": "active"
}
```
### 更新养殖场
```http
PUT /api/farms/{id}
```
**需要认证**: 是
**权限要求**: manager
### 删除养殖场
```http
DELETE /api/farms/{id}
```
**需要认证**: 是
**权限要求**: admin
## 设备管理API
### 获取设备列表
```http
GET /api/devices
```
**需要认证**: 是
**查询参数:**
- `page` (int): 页码
- `limit` (int): 每页数量
- `farm_id` (int): 养殖场ID
- `type` (string): 设备类型
- `status` (string): 设备状态 (`online`, `offline`, `maintenance`)
### 获取设备详情
```http
GET /api/devices/{id}
```
**需要认证**: 是
**响应:**
```json
{
"success": true,
"data": {
"id": 1,
"name": "温度传感器001",
"type": "温度传感器",
"status": "online",
"farm_id": 1,
"metrics": {
"temperature": 25.5,
"humidity": 60
},
"last_maintenance": "2025-01-01T00:00:00Z",
"installation_date": "2024-01-01T00:00:00Z",
"farm": {
"id": 1,
"name": "宁夏示范养殖场"
}
}
}
```
### 创建设备
```http
POST /api/devices
```
**需要认证**: 是
**权限要求**: manager
**请求体:**
```json
{
"name": "新设备",
"type": "传感器",
"farm_id": 1,
"installation_date": "2025-01-18",
"metrics": {
"temperature": 25.0
}
}
```
### 更新设备
```http
PUT /api/devices/{id}
```
**需要认证**: 是
**权限要求**: manager
### 删除设备
```http
DELETE /api/devices/{id}
```
**需要认证**: 是
**权限要求**: admin
## 动物管理API
### 获取动物列表
```http
GET /api/animals
```
**需要认证**: 是
**查询参数:**
- `page` (int): 页码
- `limit` (int): 每页数量
- `farm_id` (int): 养殖场ID
- `type` (string): 动物类型
- `health_status` (string): 健康状态 (`healthy`, `sick`, `quarantine`)
### 获取动物详情
```http
GET /api/animals/{id}
```
**需要认证**: 是
### 创建动物记录
```http
POST /api/animals
```
**需要认证**: 是
**权限要求**: manager
**请求体:**
```json
{
"type": "奶牛",
"count": 100,
"farm_id": 1,
"health_status": "healthy",
"notes": "备注信息"
}
```
### 更新动物记录
```http
PUT /api/animals/{id}
```
**需要认证**: 是
**权限要求**: manager
### 删除动物记录
```http
DELETE /api/animals/{id}
```
**需要认证**: 是
**权限要求**: admin
## 预警管理API
### 获取预警列表
```http
GET /api/alerts
```
**需要认证**: 是
**查询参数:**
- `page` (int): 页码
- `limit` (int): 每页数量
- `farm_id` (int): 养殖场ID
- `level` (string): 预警级别 (`low`, `medium`, `high`, `critical`)
- `status` (string): 预警状态 (`active`, `acknowledged`, `resolved`)
**响应:**
```json
{
"success": true,
"data": {
"alerts": [
{
"id": 1,
"type": "temperature_high",
"level": "high",
"message": "温度过高警报",
"status": "active",
"farm_id": 1,
"device_id": 1,
"created_at": "2025-01-18T10:00:00Z",
"farm": {
"name": "宁夏示范养殖场"
},
"device": {
"name": "温度传感器001"
}
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 1,
"pages": 1
}
}
}
```
### 确认预警
```http
PUT /api/alerts/{id}/acknowledge
```
**需要认证**: 是
**权限要求**: manager
### 解决预警
```http
PUT /api/alerts/{id}/resolve
```
**需要认证**: 是
**权限要求**: manager
**请求体:**
```json
{
"resolution_notes": "问题已解决,温度已恢复正常"
}
```
## 产品管理API
### 获取产品列表
```http
GET /api/products
```
**需要认证**: 是
**查询参数:**
- `page` (int): 页码
- `limit` (int): 每页数量
- `search` (string): 搜索关键词
- `is_active` (boolean): 是否激活
### 获取产品详情
```http
GET /api/products/{id}
```
**需要认证**: 是
### 创建产品
```http
POST /api/products
```
**需要认证**: 是
**权限要求**: manager
**请求体:**
```json
{
"name": "优质鲜牛奶",
"description": "新鲜优质牛奶,富含营养",
"price": 5000,
"stock": 1000,
"image_url": "/uploads/products/milk.jpg",
"is_active": true
}
```
### 更新产品
```http
PUT /api/products/{id}
```
**需要认证**: 是
**权限要求**: manager
### 删除产品
```http
DELETE /api/products/{id}
```
**需要认证**: 是
**权限要求**: admin
## 订单管理API
### 获取订单列表
```http
GET /api/orders
```
**需要认证**: 是
**查询参数:**
- `page` (int): 页码
- `limit` (int): 每页数量
- `user_id` (int): 用户ID
- `status` (string): 订单状态 (`pending`, `processing`, `shipped`, `delivered`, `cancelled`)
- `payment_status` (string): 支付状态 (`unpaid`, `paid`, `refunded`)
### 获取订单详情
```http
GET /api/orders/{id}
```
**需要认证**: 是
**响应:**
```json
{
"success": true,
"data": {
"id": 1,
"user_id": 1,
"total_amount": 10000,
"status": "pending",
"payment_status": "unpaid",
"shipping_address": "收货地址",
"created_at": "2025-01-18T10:00:00Z",
"user": {
"username": "用户名",
"email": "user@example.com"
},
"items": [
{
"id": 1,
"product_id": 1,
"quantity": 2,
"price": 5000,
"product": {
"name": "优质鲜牛奶",
"image_url": "/uploads/products/milk.jpg"
}
}
]
}
}
```
### 创建订单
```http
POST /api/orders
```
**需要认证**: 是
**请求体:**
```json
{
"items": [
{
"product_id": 1,
"quantity": 2
}
],
"shipping_address": "收货地址"
}
```
### 更新订单状态
```http
PUT /api/orders/{id}/status
```
**需要认证**: 是
**权限要求**: manager
**请求体:**
```json
{
"status": "processing"
}
```
## 统计分析API
### 系统概览统计
```http
GET /api/stats/overview
```
**需要认证**: 是
**响应:**
```json
{
"success": true,
"data": {
"farms": {
"total": 10,
"active": 8,
"inactive": 2
},
"devices": {
"total": 50,
"online": 45,
"offline": 3,
"maintenance": 2
},
"animals": {
"total": 5000,
"healthy": 4800,
"sick": 150,
"quarantine": 50
},
"alerts": {
"active": 5,
"resolved_today": 12
}
}
}
```
### 养殖场统计
```http
GET /api/stats/farms/{id}
```
**需要认证**: 是
### 预警统计
```http
GET /api/stats/alerts
```
**需要认证**: 是
**查询参数:**
- `timeRange` (string): 时间范围 (`today`, `week`, `month`)
### 动物健康统计
```http
GET /api/stats/animals
```
**需要认证**: 是
**查询参数:**
- `farm_id` (int): 养殖场ID
## 地图服务API
### 获取地图数据
```http
GET /api/map/data
```
**需要认证**: 是
**响应:**
```json
{
"success": true,
"data": {
"farms": [
{
"id": 1,
"name": "宁夏示范养殖场",
"location": {
"lat": 38.46667,
"lng": 106.26667
},
"type": "奶牛养殖",
"status": "active",
"devices_count": 5,
"animals_count": 500
}
]
}
}
```
## 性能监控API
### 获取性能指标
```http
GET /api/performance/metrics
```
**需要认证**: 是
**权限要求**: admin
### 获取系统资源信息
```http
GET /api/performance/system
```
**需要认证**: 是
**权限要求**: admin
### 获取数据库性能信息
```http
GET /api/performance/database
```
**需要认证**: 是
**权限要求**: admin
### 获取API性能统计
```http
GET /api/performance/api
```
**需要认证**: 是
**权限要求**: admin
## 文件上传API
### 上传头像
```http
POST /api/upload/avatar
```
**需要认证**: 是
**Content-Type**: `multipart/form-data`
**请求:**
```
Content-Type: multipart/form-data
avatar: [文件]
```
### 上传产品图片
```http
POST /api/upload/product
```
**需要认证**: 是
**权限要求**: manager
**Content-Type**: `multipart/form-data`
## 错误代码参考
| 错误代码 | 描述 | HTTP状态码 |
|---------|------|------------|
| `INVALID_CREDENTIALS` | 用户名或密码错误 | 401 |
| `TOKEN_EXPIRED` | Token已过期 | 401 |
| `TOKEN_INVALID` | Token无效 | 401 |
| `INSUFFICIENT_PERMISSIONS` | 权限不足 | 403 |
| `RESOURCE_NOT_FOUND` | 资源不存在 | 404 |
| `VALIDATION_ERROR` | 参数验证失败 | 400 |
| `DUPLICATE_RESOURCE` | 资源重复 | 409 |
| `DATABASE_ERROR` | 数据库错误 | 500 |
| `INTERNAL_SERVER_ERROR` | 服务器内部错误 | 500 |
## API限制
### 频率限制
- 登录接口每分钟最多5次尝试
- 普通API每分钟最多1000次请求
- 上传接口每分钟最多10次请求
### 文件上传限制
- 头像最大2MB支持jpg、png格式
- 产品图片最大5MB支持jpg、png、webp格式
## SDK示例
### JavaScript/Node.js
```javascript
// 安装: npm install axios
const axios = require('axios');
class NxxmdataAPI {
constructor(baseURL, token) {
this.client = axios.create({
baseURL: baseURL,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
}
async getFarms(params = {}) {
const response = await this.client.get('/farms', { params });
return response.data;
}
async createFarm(farmData) {
const response = await this.client.post('/farms', farmData);
return response.data;
}
}
// 使用示例
const api = new NxxmdataAPI('http://localhost:5350/api', 'your_token');
const farms = await api.getFarms({ page: 1, limit: 10 });
```
### Python
```python
import requests
class NxxmdataAPI:
def __init__(self, base_url, token):
self.base_url = base_url
self.headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
def get_farms(self, params=None):
response = requests.get(f'{self.base_url}/farms',
headers=self.headers, params=params)
return response.json()
def create_farm(self, farm_data):
response = requests.post(f'{self.base_url}/farms',
headers=self.headers, json=farm_data)
return response.json()
# 使用示例
api = NxxmdataAPI('http://localhost:5350/api', 'your_token')
farms = api.get_farms({'page': 1, 'limit': 10})
```
## 测试环境
### Swagger文档
访问 `http://localhost:5350/api-docs` 查看交互式API文档。
### Postman集合
提供完整的Postman集合文件包含所有API的示例请求。
---
## 更新记录
- **v1.0** (2025-01-18): 初始版本包含所有核心API
- 定期更新请关注CHANGELOG.md
## 联系方式
如有API相关问题请联系
- 技术支持: api-support@nxxmdata.com
- 文档反馈: docs@nxxmdata.com
*最后更新: 2025年1月*

266
docs/CHANGELOG.md Normal file
View File

@@ -0,0 +1,266 @@
# 更新日志
所有项目的重要变更都将记录在此文件中。
本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/) 规范。
## [未发布]
### 新增
- 完善项目文档体系
- 创建故障排除指南
- 添加开发指南和API文档
### 变更
- 优化项目目录结构
- 更新README文档
### 修复
- 修复经纬度数据同步问题
- 解决地图组件显示异常
## [1.2.0] - 2025-01-18
### 新增
- **性能监控系统**: 全新的系统性能监控功能
- 实时监控 CPU、内存、磁盘使用情况
- 数据库性能监控和慢查询分析
- API 响应时间统计和错误率监控
- 可配置的警报阈值系统
- **虚拟滚动组件**: 优化大数据量列表显示性能
- **图表性能监控**: 基于 ECharts 的性能指标可视化
- **地图缩放演示**: 多级缩放功能展示
### 变更
- **前端架构升级**:
- Vue 3.4+ 升级,提升响应性能
- Ant Design Vue 4.0+ 组件库更新
- Pinia 2.0+ 状态管理重构
- **后端优化**:
- 数据库连接池优化
- API 响应时间提升 30%
- 新增查询优化器
### 修复
- 修复百度地图 API 密钥配置问题
- 解决设备状态更新延迟问题
- 修复用户权限验证逻辑错误
- 优化内存泄漏问题
### 安全
- 加强 JWT Token 验证机制
- 更新密码加密算法强度
- 添加 API 请求频率限制
## [1.1.0] - 2024-12-15
### 新增
- **农场管理功能**:
- 农场信息 CRUD 操作
- 地理位置管理和地图展示
- 农场状态监控
- **动物健康管理**:
- 动物信息记录和追踪
- 健康状态监控
- 检查记录管理
- **设备监控系统**:
- 设备状态实时监控
- 设备指标数据收集
- 设备维护记录
- **预警管理**:
- 多级别预警系统
- 预警处理流程
- 预警统计分析
### 变更
- 数据库架构优化,支持更复杂的业务关系
- API 接口标准化,统一响应格式
- 前端路由结构重构
### 修复
- 修复数据库外键约束问题
- 解决前端路由跳转异常
- 优化 API 错误处理机制
## [1.0.0] - 2024-11-01
### 新增
- **核心系统架构**:
- Node.js + Express 后端服务
- Vue 3 + Vite 前端框架
- MySQL 数据库支持
- Sequelize ORM 集成
- **用户认证系统**:
- JWT 基础认证
- 角色权限管理
- 用户注册和登录
- **基础 CRUD 功能**:
- 用户管理
- 产品管理
- 订单管理
- **系统基础设施**:
- 日志系统 (Winston)
- API 文档 (Swagger)
- 数据库迁移和种子数据
- 环境配置管理
### 技术栈
- **后端**: Node.js 18+, Express 4.18+, Sequelize 6.30+
- **前端**: Vue 3.4+, Ant Design Vue 4.0+, Vite 5.0+
- **数据库**: MySQL 8.0+
- **工具**: ESLint, Prettier, PM2
## 版本命名规范
我们采用语义化版本控制 (SemVer) 格式:`主版本号.次版本号.修订号`
- **主版本号**: 不兼容的 API 修改
- **次版本号**: 向下兼容的功能性新增
- **修订号**: 向下兼容的问题修正
### 变更类型说明
- `新增` - 新增功能
- `变更` - 对现有功能的变更
- `废弃` - 即将移除的功能
- `移除` - 已移除的功能
- `修复` - 问题修复
- `安全` - 安全相关的修复
## 升级指南
### 从 1.1.0 升级到 1.2.0
#### 数据库更新
```sql
-- 添加性能监控相关表
-- 运行迁移脚本
npm run db:migrate
```
#### 配置更新
```bash
# 添加新的环境变量
ENABLE_PERFORMANCE_MONITORING=true
PERFORMANCE_LOG_LEVEL=info
```
#### 依赖更新
```bash
# 更新前端依赖
cd admin-system/frontend
npm update vue@^3.4.0
npm update ant-design-vue@^4.0.0
# 更新后端依赖
cd ../../backend
npm update
```
### 从 1.0.0 升级到 1.1.0
#### 数据库迁移
```sql
-- 添加农场管理相关表
CREATE TABLE farms (...);
CREATE TABLE animals (...);
CREATE TABLE devices (...);
CREATE TABLE alerts (...);
```
#### 配置变更
```bash
# 添加百度地图 API 配置
BAIDU_MAP_API_KEY=your_api_key_here
```
## 已知问题
### v1.2.0
- 性能监控在高并发情况下可能影响系统性能
- 某些旧版本浏览器可能不支持新的前端特性
### v1.1.0
- 百度地图在某些网络环境下加载较慢
- 大数据量查询时可能出现超时
### v1.0.0
- 初始版本,功能相对基础
- 部分边界情况处理不够完善
## 兼容性支持
### 浏览器支持
- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+
### Node.js 版本支持
- Node.js 18.x (推荐)
- Node.js 16.x (最低要求)
### 数据库版本支持
- MySQL 8.0+ (推荐)
- MySQL 5.7+ (最低要求)
## 贡献指南
我们欢迎社区贡献!请查看 [CONTRIBUTING.md](CONTRIBUTING.md) 了解如何参与项目开发。
### 报告问题
如果您发现问题,请在 GitHub Issues 中创建新的问题报告,并包含:
- 问题描述
- 复现步骤
- 预期行为
- 实际行为
- 环境信息
### 提交代码
1. Fork 项目仓库
2. 创建功能分支 (`git checkout -b feature/amazing-feature`)
3. 提交变更 (`git commit -m 'Add some amazing feature'`)
4. 推送到分支 (`git push origin feature/amazing-feature`)
5. 创建 Pull Request
## 技术路线图
### v1.3.0 (计划中)
- [ ] 微服务架构重构
- [ ] 实时数据推送 (WebSocket)
- [ ] 移动端适配优化
- [ ] 多语言支持
### v1.4.0 (规划中)
- [ ] 人工智能预警系统
- [ ] 大数据分析平台
- [ ] 第三方系统集成
- [ ] 高可用架构升级
### v2.0.0 (远期规划)
- [ ] 云原生架构
- [ ] 容器化部署
- [ ] 多租户支持
- [ ] 国际化部署
## 致谢
感谢所有为项目做出贡献的开发者和用户!
### 主要贡献者
- 项目架构设计团队
- 前端开发团队
- 后端开发团队
- 测试团队
- 文档团队
### 特别感谢
- 宁夏农业部门的需求指导
- 养殖户的实际使用反馈
- 技术社区的开源支持
---
*如需查看完整的提交历史,请访问项目的 Git 日志: `git log --oneline`*
*最后更新: 2025年1月*

594
docs/CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,594 @@
# 贡献指南
## 欢迎贡献
我们热烈欢迎社区开发者为宁夏智慧养殖监管平台做出贡献无论您是想修复bug、添加新功能、改进文档还是提供反馈建议我们都非常感谢您的参与。
## 目录
- [开始之前](#开始之前)
- [如何贡献](#如何贡献)
- [开发环境搭建](#开发环境搭建)
- [代码贡献流程](#代码贡献流程)
- [代码规范](#代码规范)
- [提交规范](#提交规范)
- [Pull Request 指南](#pull-request-指南)
- [问题报告](#问题报告)
- [文档贡献](#文档贡献)
- [社区行为准则](#社区行为准则)
## 开始之前
### 阅读项目文档
在开始贡献之前,请确保您已经阅读并理解了以下文档:
- [README.md](README.md) - 项目概述
- [DEVELOPMENT.md](DEVELOPMENT.md) - 开发指南
- [API.md](API.md) - API 文档
- [架构文档](arch.md) - 系统架构
### 了解项目状态
- 查看 [Issues](https://github.com/your-org/nxxmdata/issues) 了解当前需要解决的问题
- 查看 [Projects](https://github.com/your-org/nxxmdata/projects) 了解项目路线图
- 查看 [CHANGELOG.md](CHANGELOG.md) 了解最新变更
## 如何贡献
您可以通过以下方式为项目做出贡献:
### 🐛 报告 Bug
- 发现了系统错误或异常行为
- 遇到了文档中的错误或不清楚的地方
- 发现了安全漏洞(请通过私密渠道报告)
### 💡 提出功能建议
- 提出新的功能想法
- 建议改进现有功能
- 提出用户体验优化建议
### 📝 改进文档
- 修复文档中的错误
- 添加缺失的文档
- 改进文档的清晰度和准确性
- 翻译文档到其他语言
### 💻 贡献代码
- 修复已知的 bug
- 实现新功能
- 优化性能
- 重构代码
- 添加测试用例
### 🎨 设计贡献
- 改进用户界面设计
- 提供图标和图片资源
- 优化用户体验
## 开发环境搭建
### 前置要求
- Node.js 18.0+
- npm 8.0+ 或 yarn 1.22+
- MySQL 8.0+
- Git 2.25+
### 克隆项目
```bash
# 1. Fork 项目到您的 GitHub 账户
# 2. 克隆您的 fork
git clone https://github.com/YOUR_USERNAME/nxxmdata.git
cd nxxmdata
# 3. 添加上游仓库
git remote add upstream https://github.com/original-org/nxxmdata.git
```
### 安装依赖
```bash
# 后端依赖
cd backend
npm install
# 前端依赖
cd ../admin-system/frontend
npm install
cd ../../website/data-screen
npm install
# 微信小程序依赖(可选)
cd ../../mini_program/farm-monitor-dashboard
npm install
```
### 配置环境
```bash
# 复制环境配置文件
cd backend
cp .env.example .env
cd ../admin-system/frontend
cp .env.example .env
# 编辑配置文件,设置数据库连接等信息
```
### 初始化数据库
```bash
cd backend
# 创建数据库
mysql -u root -p -e "CREATE DATABASE nxxmdata CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
# 运行迁移
npm run db:migrate
# 填充种子数据
npm run db:seed
```
### 启动开发服务器
```bash
# 启动后端服务
cd backend
npm run dev
# 启动前端服务(新终端)
cd admin-system/frontend
npm run dev
# 启动官网大屏(新终端)
cd website/data-screen
npm run dev
```
## 代码贡献流程
### 1. 选择或创建 Issue
- 查看现有的 [Issues](https://github.com/your-org/nxxmdata/issues)
- 选择标记为 `good first issue` 的问题(适合新手)
- 如果是新功能,请先创建 Issue 讨论
### 2. 创建分支
```bash
# 更新主分支
git checkout main
git pull upstream main
# 创建功能分支
git checkout -b feature/your-feature-name
# 或者修复分支
git checkout -b fix/bug-description
```
### 3. 开发代码
- 编写代码
- 添加或更新测试
- 更新相关文档
- 确保代码符合项目规范
### 4. 测试代码
```bash
# 运行单元测试
npm test
# 运行集成测试
npm run test:integration
# 运行端到端测试
npm run test:e2e
# 检查代码风格
npm run lint
# 修复代码风格问题
npm run lint:fix
```
### 5. 提交代码
```bash
# 添加变更文件
git add .
# 提交代码(遵循提交信息规范)
git commit -m "feat: add user profile management feature"
# 推送到您的 fork
git push origin feature/your-feature-name
```
### 6. 创建 Pull Request
- 在 GitHub 上创建 Pull Request
- 填写 PR 模板中的所有必要信息
- 等待代码审查
## 代码规范
### JavaScript/TypeScript 规范
#### 命名约定
```javascript
// 变量和函数使用 camelCase
const userName = 'john_doe';
function getUserInfo() {}
// 常量使用 UPPER_SNAKE_CASE
const API_BASE_URL = 'http://localhost:5350';
// 类名使用 PascalCase
class UserService {}
// 文件名使用 kebab-case
// user-service.js, farm-detail.vue
```
#### 代码风格
```javascript
// 使用 const/let避免 var
const config = {...};
let mutableData = [];
// 使用箭头函数
const processData = (data) => {
return data.map(item => item.value);
};
// 使用模板字符串
const message = `Hello, ${userName}!`;
// 使用对象解构
const { name, email } = user;
// 使用扩展运算符
const newArray = [...oldArray, newItem];
```
#### 错误处理
```javascript
// 使用 try-catch 处理异步错误
try {
const result = await api.fetchData();
return result;
} catch (error) {
logger.error('Failed to fetch data:', error);
throw new Error('Data fetch failed');
}
// 返回 Promise 的函数应该处理所有可能的错误
async function createUser(userData) {
try {
const user = await User.create(userData);
return { success: true, data: user };
} catch (error) {
return { success: false, error: error.message };
}
}
```
### Vue.js 组件规范
```vue
<template>
<div class="component-name">
<!-- 使用语义化的 HTML 标签 -->
<header class="component-header">
<h1>{{ title }}</h1>
</header>
<!-- 事件处理使用 handle 前缀 -->
<button @click="handleSubmit">提交</button>
</div>
</template>
<script>
import { ref, computed, onMounted } from 'vue'
export default {
name: 'ComponentName', // 组件名使用 PascalCase
props: {
title: {
type: String,
required: true,
default: ''
}
},
emits: ['submit'],
setup(props, { emit }) {
// 响应式数据
const isLoading = ref(false)
// 计算属性
const displayTitle = computed(() => {
return props.title.toUpperCase()
})
// 方法
const handleSubmit = () => {
emit('submit')
}
// 生命周期
onMounted(() => {
// 初始化逻辑
})
return {
isLoading,
displayTitle,
handleSubmit
}
}
}
</script>
<style scoped>
.component-name {
/* 使用 BEM 命名法 */
}
.component-header {
/* 样式规则 */
}
</style>
```
### CSS/SCSS 规范
```css
/* 使用 BEM 命名法 */
.block {}
.block__element {}
.block--modifier {}
/* 使用语义化的类名 */
.button--primary {}
.form__input--error {}
/* 避免深层嵌套 */
.component {
.header {} /* 最多 3 层嵌套 */
}
```
## 提交规范
我们使用 [Conventional Commits](https://www.conventionalcommits.org/) 规范:
### 提交消息格式
```
<type>(<scope>): <description>
[optional body]
[optional footer(s)]
```
### 类型 (type)
- `feat`: 新增功能
- `fix`: 修复 bug
- `docs`: 文档更新
- `style`: 代码格式调整(不影响代码逻辑)
- `refactor`: 重构(既不是新增功能也不是修复 bug
- `perf`: 性能优化
- `test`: 添加或修改测试
- `chore`: 构建过程或辅助工具的变动
- `ci`: CI/CD 相关变更
### 范围 (scope)
- `api`: API 相关
- `ui`: 用户界面
- `auth`: 认证相关
- `db`: 数据库相关
- `config`: 配置相关
### 示例
```bash
feat(api): add user profile update endpoint
fix(ui): resolve map display issue on mobile devices
docs(readme): update installation instructions
style(frontend): format code with prettier
refactor(auth): simplify token validation logic
perf(db): optimize farm data query performance
test(api): add unit tests for user controller
chore(deps): update vue to version 3.4.0
```
### 破坏性变更
```bash
feat(api)!: change user authentication method
BREAKING CHANGE: JWT token format has changed
```
## Pull Request 指南
### PR 标题
PR 标题应该简洁明了地描述变更内容,遵循提交信息规范:
```
feat(user): add profile management feature
fix(map): resolve coordinate display issue
docs: update API documentation
```
### PR 描述模板
```markdown
## 变更类型
- [ ] Bug 修复
- [ ] 新功能
- [ ] 文档更新
- [ ] 代码重构
- [ ] 性能优化
- [ ] 其他: ____________
## 变更描述
<!-- 简要描述这个 PR 的变更内容 -->
## 相关 Issue
<!-- 如果有相关的 Issue请在此链接 -->
Closes #123
## 测试
- [ ] 我已经测试了我的代码
- [ ] 我已经添加了测试用例
- [ ] 所有测试都通过了
## 检查清单
- [ ] 我的代码遵循项目的代码规范
- [ ] 我已经进行了自我代码审查
- [ ] 我已经添加了必要的注释
- [ ] 我已经更新了相关文档
- [ ] 我的变更不会产生新的警告
- [ ] 我已经添加了适当的测试
- [ ] 新功能和修复都有对应的测试
## 截图(如果适用)
<!-- 如果是 UI 相关的变更,请添加截图 -->
## 额外说明
<!-- 任何其他需要说明的内容 -->
```
### 代码审查
- 所有 PR 都需要至少一个审查者的批准
- 解决所有审查意见后才能合并
- 保持代码变更的原子性和逻辑性
- 确保 CI/CD 检查通过
## 问题报告
### Bug 报告
使用 Bug 报告模板创建 Issue
```markdown
**问题描述**
简要描述遇到的问题。
**复现步骤**
1. 进入 '...'
2. 点击 '....'
3. 滚动到 '....'
4. 看到错误
**预期行为**
描述您期望发生的行为。
**实际行为**
描述实际发生的行为。
**截图**
如果适用,添加截图来帮助解释您的问题。
**环境信息:**
- 操作系统: [例如 macOS 12.0]
- 浏览器: [例如 Chrome 95.0]
- Node.js 版本: [例如 18.12.0]
- 项目版本: [例如 1.2.0]
**附加信息**
添加任何其他有关问题的信息。
```
### 功能请求
```markdown
**功能描述**
简要描述您想要的功能。
**问题解决**
这个功能解决了什么问题?
**解决方案**
描述您想要的解决方案。
**备选方案**
描述您考虑过的任何备选解决方案或功能。
**附加信息**
添加任何其他关于功能请求的信息或截图。
```
## 文档贡献
### 文档类型
- **用户文档**: README, 安装指南, 使用教程
- **开发者文档**: API 文档, 开发指南, 架构文档
- **运维文档**: 部署指南, 故障排除, 监控指南
### 文档写作规范
- 使用清晰、简洁的语言
- 提供具体的示例和代码片段
- 包含必要的截图和图表
- 保持文档的时效性
- 使用统一的格式和风格
### 文档更新流程
1. 识别需要更新的文档
2. 创建文档分支 `docs/update-api-guide`
3. 更新文档内容
4. 提交并创建 PR
5. 经过审查后合并
## 社区行为准则
### 我们的承诺
为了营造一个开放和受欢迎的环境,我们作为贡献者和维护者承诺:无论年龄、体型、身体健全或残疾、民族、性别特征、性别认同和表达、经验水平、教育程度、社会经济地位、国籍、外貌、种族、宗教或性取向如何,参与我们项目和社区的每个人都享有无骚扰的体验。
### 我们的标准
有助于创造积极环境的行为包括:
- 使用受欢迎和包容性的语言
- 尊重不同的观点和经验
- 优雅地接受建设性批评
- 关注对社区最有利的事情
- 对其他社区成员表示同情
不可接受的行为包括:
- 使用性化的语言或图像以及不受欢迎的性关注或求爱
- 捣乱、侮辱/贬损评论以及个人或政治攻击
- 公开或私下骚扰
- 未经明确许可发布他人的私人信息
- 在专业环境中可能被合理认为不适当的其他行为
### 报告
如果您遇到不当行为,请联系项目团队:
- 邮箱: conduct@nxxmdata.com
- 我们将认真对待所有报告并进行调查
## 获得帮助
### 联系方式
- **技术问题**: 在 GitHub Issues 中提问
- **功能讨论**: 在 GitHub Discussions 中讨论
- **安全问题**: 发送邮件到 security@nxxmdata.com
- **其他问题**: 发送邮件到 hello@nxxmdata.com
### 社区资源
- [GitHub 仓库](https://github.com/your-org/nxxmdata)
- [项目文档](https://docs.nxxmdata.com)
- [API 文档](https://api.nxxmdata.com/docs)
## 认可贡献者
我们感谢所有为项目做出贡献的人!贡献者将被列在:
- [CONTRIBUTORS.md](CONTRIBUTORS.md) 文件中
- 项目的 README 中
- 每次发布的致谢中
### 贡献类型
我们认可以下类型的贡献:
- 💻 代码贡献
- 📖 文档贡献
- 🎨 设计贡献
- 🐛 Bug 报告
- 💡 想法和建议
- 🤔 答疑解惑
- 📢 推广项目
## 许可证
通过向此项目贡献代码,您同意您的贡献将在与项目相同的许可证下被许可。
---
再次感谢您对宁夏智慧养殖监管平台的关注和贡献!我们期待与您一起构建更好的系统。
*最后更新: 2025年1月*

630
docs/DEPLOYMENT.md Normal file
View File

@@ -0,0 +1,630 @@
# 宁夏智慧养殖监管平台部署指南
## 概述
本文档详细说明了宁夏智慧养殖监管平台的部署流程,包括开发环境、测试环境和生产环境的部署方案。
## 系统要求
### 基础要求
- **操作系统**: Linux (推荐 Ubuntu 18.04+), macOS 10.14+, Windows 10+
- **Node.js**: 18.0 或更高版本
- **MySQL**: 8.0 或更高版本
- **内存**: 最少 4GB RAM推荐 8GB+
- **存储**: 最少 20GB 可用空间
### 推荐配置(生产环境)
- **CPU**: 4核 或更高
- **内存**: 16GB RAM
- **存储**: 100GB SSD
- **网络**: 100Mbps 带宽
## 前期准备
### 1. 环境检查
```bash
# 检查 Node.js 版本
node --version # 应显示 v18.0.0 或更高
# 检查 npm 版本
npm --version
# 检查 MySQL 版本
mysql --version # 应显示 8.0 或更高
```
### 2. 数据库准备
```sql
-- 创建数据库
CREATE DATABASE nxxmdata CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 创建数据库用户(可选)
CREATE USER 'nxxmdata_user'@'localhost' IDENTIFIED BY 'your_secure_password';
GRANT ALL PRIVILEGES ON nxxmdata.* TO 'nxxmdata_user'@'localhost';
FLUSH PRIVILEGES;
```
### 3. 获取源代码
```bash
# 克隆项目如果使用Git
git clone <repository-url>
cd nxxmdata
# 或者解压源码包
unzip nxxmdata.zip
cd nxxmdata
```
## 开发环境部署
### 1. 安装依赖
#### 后端依赖安装
```bash
cd backend
npm install
```
#### 前端依赖安装
```bash
# 管理后台
cd admin-system/frontend
npm install
# 官网大屏
cd ../../website/data-screen
npm install
# 微信小程序(可选)
cd ../../mini_program/farm-monitor-dashboard
npm install
```
### 2. 环境配置
#### 后端环境配置
`backend` 目录下创建 `.env` 文件:
```bash
# 数据库配置
DB_HOST=localhost
DB_PORT=3306
DB_NAME=nxxmdata
DB_USER=root
DB_PASSWORD=your_mysql_password
# JWT配置
JWT_SECRET=your_jwt_secret_key_here
JWT_EXPIRES_IN=24h
# 服务器配置
PORT=5350
NODE_ENV=development
# 百度地图API配置
BAIDU_MAP_API_KEY=your_baidu_map_api_key
# 日志配置
LOG_LEVEL=debug
LOG_FILE_PATH=./logs/
```
#### 前端环境配置
`admin-system/frontend` 目录下创建 `.env` 文件:
```bash
# API配置
VITE_API_BASE_URL=http://localhost:5350/api
VITE_BAIDU_MAP_API_KEY=your_baidu_map_api_key
# 开发服务器配置
VITE_PORT=5301
```
### 3. 数据库初始化
```bash
cd backend
# 运行数据库迁移
npm run init-db
# 或者手动执行SQL脚本
mysql -u root -p nxxmdata < create_tables.sql
```
### 4. 启动开发服务器
#### 启动后端服务
```bash
cd backend
npm run dev
# 服务将在 http://localhost:5350 启动
```
#### 启动前端服务
```bash
# 启动管理后台
cd admin-system/frontend
npm run dev
# 服务将在 http://localhost:5301 启动
# 启动官网大屏
cd ../../website/data-screen
npm run dev
# 服务将在 http://localhost:5302 启动
```
### 5. 验证部署
访问以下URL验证部署是否成功
- 后端API: http://localhost:5350/api/health
- 管理后台: http://localhost:5301
- 官网大屏: http://localhost:5302
- API文档: http://localhost:5350/api-docs
## 测试环境部署
### 1. 使用PM2管理进程
```bash
# 安装PM2
npm install -g pm2
# 构建项目
cd admin-system/frontend
npm run build
cd ../../website/data-screen
npm run build
# 启动后端服务
cd ../../backend
pm2 start ecosystem.config.js --env test
```
### 2. Nginx配置
创建 `/etc/nginx/sites-available/nxxmdata-test` 文件:
```nginx
server {
listen 80;
server_name test.nxxmdata.com;
# 前端静态文件
location / {
root /path/to/nxxmdata/admin-system/frontend/dist;
try_files $uri $uri/ /index.html;
}
# 官网大屏
location /screen {
root /path/to/nxxmdata/website/data-screen/dist;
try_files $uri $uri/ /index.html;
}
# API代理
location /api {
proxy_pass http://localhost:5350;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
## 生产环境部署
### 1. Docker部署推荐
#### 创建Dockerfile
```dockerfile
# 多阶段构建 - 前端构建阶段
FROM node:18-alpine AS frontend-builder
# 构建管理后台
WORKDIR /app/admin-system/frontend
COPY admin-system/frontend/package*.json ./
RUN npm ci --only=production
COPY admin-system/frontend/ ./
RUN npm run build
# 构建官网大屏
WORKDIR /app/website/data-screen
COPY website/data-screen/package*.json ./
RUN npm ci --only=production
COPY website/data-screen/ ./
RUN npm run build
# 后端运行阶段
FROM node:18-alpine AS backend
WORKDIR /app
# 安装后端依赖
COPY backend/package*.json ./
RUN npm ci --only=production
# 复制后端代码
COPY backend/ ./
# 复制前端构建产物
COPY --from=frontend-builder /app/admin-system/frontend/dist ./public/admin
COPY --from=frontend-builder /app/website/data-screen/dist ./public/screen
# 创建非root用户
RUN addgroup -g 1001 -S nodejs
RUN adduser -S node -u 1001
USER node
EXPOSE 5350
CMD ["npm", "start"]
```
#### 创建docker-compose.yml
```yaml
version: '3.8'
services:
nxxmdata-app:
build: .
ports:
- "5350:5350"
environment:
- NODE_ENV=production
- DB_HOST=mysql
- DB_PORT=3306
- DB_NAME=nxxmdata
- DB_USER=nxxmdata_user
- DB_PASSWORD=${DB_PASSWORD}
- JWT_SECRET=${JWT_SECRET}
depends_on:
- mysql
restart: unless-stopped
volumes:
- ./logs:/app/logs
mysql:
image: mysql:8.0
environment:
- MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
- MYSQL_DATABASE=nxxmdata
- MYSQL_USER=nxxmdata_user
- MYSQL_PASSWORD=${DB_PASSWORD}
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
- ./create_tables.sql:/docker-entrypoint-initdb.d/init.sql
restart: unless-stopped
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./ssl:/etc/nginx/ssl
depends_on:
- nxxmdata-app
restart: unless-stopped
volumes:
mysql_data:
```
#### 创建环境变量文件
创建 `.env` 文件:
```bash
# 数据库密码
DB_PASSWORD=your_secure_db_password
MYSQL_ROOT_PASSWORD=your_secure_root_password
# JWT密钥
JWT_SECRET=your_very_secure_jwt_secret_key
# 百度地图API
BAIDU_MAP_API_KEY=your_baidu_map_api_key
```
#### 部署命令
```bash
# 构建并启动服务
docker-compose up -d
# 查看服务状态
docker-compose ps
# 查看日志
docker-compose logs -f nxxmdata-app
```
### 2. 传统部署方式
#### 安装和配置
```bash
# 1. 克隆项目
git clone <repository-url>
cd nxxmdata
# 2. 安装依赖
cd backend && npm install --production
cd ../admin-system/frontend && npm install && npm run build
cd ../../website/data-screen && npm install && npm run build
# 3. 配置环境变量
cp backend/.env.example backend/.env
# 编辑 .env 文件,设置生产环境配置
# 4. 初始化数据库
cd backend && npm run init-db
# 5. 使用PM2启动服务
npm install -g pm2
pm2 start ecosystem.config.js --env production
```
#### PM2配置文件 (ecosystem.config.js)
```javascript
module.exports = {
apps: [{
name: 'nxxmdata-backend',
script: './server.js',
cwd: './backend',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'production',
PORT: 5350
},
error_file: './logs/pm2-error.log',
out_file: './logs/pm2-out.log',
log_file: './logs/pm2-combined.log',
time: true
}]
}
```
### 3. Nginx配置生产环境
```nginx
server {
listen 80;
server_name nxxmdata.com www.nxxmdata.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name nxxmdata.com www.nxxmdata.com;
ssl_certificate /etc/nginx/ssl/nxxmdata.com.crt;
ssl_certificate_key /etc/nginx/ssl/nxxmdata.com.key;
# SSL配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
ssl_prefer_server_ciphers off;
# Gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
# 管理后台
location / {
root /path/to/nxxmdata/admin-system/frontend/dist;
try_files $uri $uri/ /index.html;
expires 1y;
add_header Cache-Control "public, immutable";
}
# 官网大屏
location /screen {
alias /path/to/nxxmdata/website/data-screen/dist;
try_files $uri $uri/ /index.html;
expires 1y;
add_header Cache-Control "public, immutable";
}
# API代理
location /api {
proxy_pass http://localhost:5350;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
# API文档
location /api-docs {
proxy_pass http://localhost:5350;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
## 监控和维护
### 1. 日志管理
```bash
# PM2日志管理
pm2 logs
pm2 logs nxxmdata-backend
pm2 flush # 清空日志
# 应用日志位置
tail -f backend/logs/app.log
tail -f backend/logs/error.log
```
### 2. 性能监控
```bash
# PM2监控
pm2 monit
# 系统资源监控
htop
iostat -x 1
```
### 3. 数据库备份
```bash
# 创建备份脚本 backup.sh
#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
mysqldump -u root -p nxxmdata > /backup/nxxmdata_$DATE.sql
find /backup -name "nxxmdata_*.sql" -mtime +7 -delete
# 设置定时任务
crontab -e
# 添加: 0 2 * * * /path/to/backup.sh
```
### 4. 自动更新脚本
```bash
#!/bin/bash
# update.sh
cd /path/to/nxxmdata
git pull origin main
# 构建前端
cd admin-system/frontend && npm run build
cd ../../website/data-screen && npm run build
# 重启服务
pm2 restart nxxmdata-backend
```
## 故障排除
### 常见问题
1. **端口占用**
```bash
# 查看端口占用
lsof -i :5350
netstat -tulpn | grep :5350
# 解决方法:杀死占用进程或更改端口
```
2. **数据库连接失败**
```bash
# 检查MySQL服务状态
systemctl status mysql
# 检查连接配置
mysql -u root -p -h localhost
```
3. **内存不足**
```bash
# 查看内存使用
free -h
top
# 优化PM2配置减少实例数量
```
4. **磁盘空间不足**
```bash
# 查看磁盘使用
df -h
# 清理日志文件
pm2 flush
find /path/to/logs -name "*.log" -mtime +30 -delete
```
## 安全加固
### 1. 防火墙配置
```bash
# 使用ufw
ufw allow 22 # SSH
ufw allow 80 # HTTP
ufw allow 443 # HTTPS
ufw enable
```
### 2. SSL证书配置
```bash
# 使用Let's Encrypt
certbot --nginx -d nxxmdata.com -d www.nxxmdata.com
# 自动续期
echo "0 12 * * * /usr/bin/certbot renew --quiet" | crontab -
```
### 3. 定期安全更新
```bash
# 系统更新
apt update && apt upgrade -y
# Node.js依赖安全检查
npm audit
npm audit fix
```
## 性能优化
### 1. 数据库优化
```sql
-- 添加必要的索引
CREATE INDEX idx_farms_location ON farms(location);
CREATE INDEX idx_devices_status ON devices(status);
CREATE INDEX idx_alerts_created_at ON alerts(created_at);
-- 定期优化表
OPTIMIZE TABLE farms, devices, alerts, users;
```
### 2. 缓存配置
```bash
# 安装Redis可选
apt install redis-server
# 在应用中配置Redis缓存
```
### 3. CDN配置
- 静态资源使用CDN加速
- 图片和视频文件外部存储
## 回滚策略
### 1. 代码回滚
```bash
# Git回滚
git revert <commit-hash>
git push origin main
# 重新部署
./update.sh
```
### 2. 数据库回滚
```bash
# 恢复数据库备份
mysql -u root -p nxxmdata < /backup/nxxmdata_20231201_020000.sql
```
### 3. 服务回滚
```bash
# 停止当前版本
pm2 stop nxxmdata-backend
# 恢复上一版本
pm2 start ecosystem.config.js.backup
```
---
## 联系信息
如有部署问题,请联系技术支持团队:
- 邮箱: tech-support@nxxmdata.com
- 电话: 400-xxx-xxxx
*最后更新: 2025年1月*

932
docs/DEVELOPMENT.md Normal file
View File

@@ -0,0 +1,932 @@
# 开发指南
## 概述
本文档为开发者提供宁夏智慧养殖监管平台的详细开发指南,包括开发环境搭建、代码规范、开发流程、调试技巧等内容。
## 开发环境搭建
### 系统要求
- **Node.js**: 18.0+ (推荐使用 LTS 版本)
- **npm**: 8.0+ 或 **yarn**: 1.22+
- **MySQL**: 8.0+
- **Git**: 2.25+
- **编辑器**: VSCode (推荐)
### 工具推荐
- **API测试**: Postman 或 Insomnia
- **数据库管理**: MySQL Workbench 或 phpMyAdmin
- **版本控制**: Git + GitHub/GitLab
- **终端**: iTerm2 (macOS) 或 Windows Terminal
### 环境搭建步骤
#### 1. 克隆项目
```bash
git clone <repository-url>
cd nxxmdata
```
#### 2. 安装依赖
```bash
# 后端依赖
cd backend
npm install
# 前端依赖 - 管理后台
cd ../admin-system/frontend
npm install
# 前端依赖 - 官网大屏
cd ../../website/data-screen
npm install
# 微信小程序(可选)
cd ../../mini_program/farm-monitor-dashboard
npm install
```
#### 3. 数据库配置
```bash
# 创建数据库
mysql -u root -p
CREATE DATABASE nxxmdata CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
# 导入数据结构
cd backend
mysql -u root -p nxxmdata < ../create_tables.sql
```
#### 4. 环境变量配置
```bash
# 后端环境变量
cp backend/.env.example backend/.env
# 编辑 .env 文件,配置数据库连接等信息
# 前端环境变量
cp admin-system/frontend/.env.example admin-system/frontend/.env
# 配置API基础URL等
```
#### 5. 启动开发服务器
```bash
# 启动后端 (Terminal 1)
cd backend
npm run dev
# 启动管理后台前端 (Terminal 2)
cd admin-system/frontend
npm run dev
# 启动官网大屏 (Terminal 3)
cd website/data-screen
npm run dev
```
## 项目结构详解
### 后端架构 (`backend/`)
```
backend/
├── config/ # 配置文件
│ ├── database.js # 数据库配置
│ ├── swagger.js # API文档配置
│ └── performance-config.js # 性能监控配置
├── controllers/ # 控制器层
│ ├── farmController.js # 农场业务逻辑
│ ├── deviceController.js # 设备业务逻辑
│ └── userController.js # 用户业务逻辑
├── models/ # 数据模型层
│ ├── Farm.js # 农场模型
│ ├── Device.js # 设备模型
│ └── User.js # 用户模型
├── routes/ # 路由层
│ ├── farms.js # 农场相关路由
│ ├── devices.js # 设备相关路由
│ └── auth.js # 认证相关路由
├── middleware/ # 中间件
│ ├── auth.js # 认证中间件
│ └── performance-middleware.js # 性能监控中间件
├── utils/ # 工具类
│ ├── logger.js # 日志工具
│ └── performance-monitor.js # 性能监控工具
├── migrations/ # 数据库迁移
├── seeds/ # 种子数据
├── logs/ # 日志文件
└── server.js # 服务器入口
```
### 前端架构 (`admin-system/frontend/`)
```
frontend/
├── src/
│ ├── components/ # 可复用组件
│ │ ├── BaiduMap.vue # 百度地图组件
│ │ ├── EChart.vue # 图表组件
│ │ └── Dashboard.vue # 仪表盘组件
│ ├── views/ # 页面组件
│ │ ├── Home.vue # 首页
│ │ ├── MapView.vue # 地图视图
│ │ └── Analytics.vue # 数据分析
│ ├── stores/ # 状态管理 (Pinia)
│ │ ├── user.js # 用户状态
│ │ └── data.js # 数据状态
│ ├── router/ # 路由配置
│ │ ├── index.js # 路由实例
│ │ └── routes.js # 路由定义
│ ├── utils/ # 工具函数
│ │ └── api.js # API调用封装
│ ├── styles/ # 样式文件
│ └── config/ # 配置文件
├── public/ # 静态资源
└── vite.config.js # Vite配置
```
## 开发规范
### 代码风格规范
#### JavaScript/Vue.js 规范
```javascript
// 1. 使用 ES6+ 语法
const apiUrl = process.env.VITE_API_BASE_URL;
// 2. 函数命名使用驼峰命名
function getUserInfo() {}
// 3. 常量使用大写字母和下划线
const API_BASE_URL = 'http://localhost:5350/api';
// 4. 类名使用 PascalCase
class UserService {}
// 5. 文件名使用 kebab-case
// user-service.js, farm-detail.vue
```
#### Vue.js 组件规范
```vue
<template>
<!-- 1. 模板根元素必须有唯一的根节点 -->
<div class="component-name">
<!-- 2. 使用语义化的HTML标签 -->
<header class="component-header">
<h1>{{ title }}</h1>
</header>
<main class="component-content">
<!-- 3. 事件处理使用 handle 前缀 -->
<button @click="handleSubmit">提交</button>
</main>
</div>
</template>
<script>
import { ref, computed, onMounted } from 'vue'
export default {
name: 'ComponentName', // 4. 组件名使用 PascalCase
props: {
// 5. Props 定义要详细
title: {
type: String,
required: true,
default: ''
}
},
emits: ['submit'], // 6. 声明所有 emit 事件
setup(props, { emit }) {
// 7. 响应式数据使用 ref 或 reactive
const isLoading = ref(false)
// 8. 计算属性使用 computed
const displayTitle = computed(() => {
return props.title.toUpperCase()
})
// 9. 方法使用 handle 前缀
const handleSubmit = () => {
emit('submit')
}
// 10. 生命周期钩子
onMounted(() => {
// 组件挂载后的逻辑
})
return {
isLoading,
displayTitle,
handleSubmit
}
}
}
</script>
<style scoped>
/* 11. 样式使用 scoped 避免污染 */
.component-name {
/* 12. 使用 BEM 命名法 */
}
</style>
```
#### Node.js 后端规范
```javascript
// 1. 使用严格模式
'use strict';
// 2. 模块导入顺序:内置模块 -> 第三方模块 -> 本地模块
const path = require('path');
const express = require('express');
const { Farm } = require('../models');
// 3. 异步函数使用 async/await
const getFarms = async (req, res) => {
try {
// 4. 输入验证
const { page = 1, limit = 10 } = req.query;
// 5. 业务逻辑
const farms = await Farm.findAll({
limit: parseInt(limit),
offset: (parseInt(page) - 1) * parseInt(limit)
});
// 6. 统一响应格式
res.json({
success: true,
data: farms,
message: '获取成功'
});
} catch (error) {
// 7. 错误处理
res.status(500).json({
success: false,
error: {
message: error.message
}
});
}
};
module.exports = {
getFarms
};
```
### Git 工作流规范
#### 分支命名规范
```bash
# 功能分支
feature/user-management
feature/device-monitoring
# 修复分支
fix/login-error
fix/map-display-issue
# 发布分支
release/v1.0.0
# 热修复分支
hotfix/security-patch
```
#### 提交信息规范
```bash
# 格式: type(scope): description
# 类型 (type):
# feat: 新功能
# fix: 修复bug
# docs: 文档更新
# style: 代码格式调整
# refactor: 重构
# test: 测试相关
# chore: 构建过程或辅助工具的变动
# 示例:
git commit -m "feat(user): add user registration functionality"
git commit -m "fix(map): resolve baidu map display issue"
git commit -m "docs(api): update API documentation"
```
### 数据库设计规范
#### 表命名规范
```sql
-- 表名使用小写字母和下划线
CREATE TABLE users (...);
CREATE TABLE user_roles (...);
CREATE TABLE device_sensors (...);
-- 字段名使用小写字母和下划线
ALTER TABLE users ADD COLUMN created_at DATETIME;
ALTER TABLE users ADD COLUMN updated_at DATETIME;
-- 索引命名
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_farms_location ON farms(location);
```
#### 模型定义规范
```javascript
// models/User.js
const { DataTypes } = require('sequelize');
module.exports = (sequelize) => {
const User = sequelize.define('User', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
comment: '用户唯一标识'
},
username: {
type: DataTypes.STRING(50),
allowNull: false,
unique: true,
comment: '用户名'
},
email: {
type: DataTypes.STRING(100),
allowNull: false,
unique: true,
validate: {
isEmail: true
},
comment: '邮箱地址'
}
}, {
tableName: 'users',
timestamps: true,
underscored: true,
comment: '用户表'
});
// 定义关联关系
User.associate = (models) => {
User.belongsToMany(models.Role, {
through: models.UserRole,
foreignKey: 'user_id',
otherKey: 'role_id'
});
};
return User;
};
```
## 开发流程
### 功能开发流程
#### 1. 需求分析
- 理解业务需求
- 确认技术方案
- 评估开发时间
#### 2. 设计阶段
```bash
# 数据库设计
# 1. 创建或修改表结构
# 2. 更新模型定义
# 3. 编写迁移脚本
# API设计
# 1. 定义路由
# 2. 设计请求/响应格式
# 3. 更新API文档
# 前端设计
# 1. UI组件设计
# 2. 状态管理设计
# 3. 路由规划
```
#### 3. 开发阶段
```bash
# 创建功能分支
git checkout -b feature/new-feature
# 后端开发
# 1. 创建/修改模型
# 2. 编写控制器逻辑
# 3. 添加路由
# 4. 编写单元测试
# 前端开发
# 1. 创建Vue组件
# 2. 实现业务逻辑
# 3. 添加样式
# 4. 集成API
# 提交代码
git add .
git commit -m "feat: implement new feature"
git push origin feature/new-feature
```
#### 4. 测试阶段
```bash
# 单元测试
npm test
# 集成测试
npm run test:integration
# 端到端测试
npm run test:e2e
# 手动测试
# 1. 功能测试
# 2. 兼容性测试
# 3. 性能测试
```
#### 5. 代码审查
- 创建 Pull Request
- 代码审查
- 修改反馈问题
- 合并到主分支
### 调试技巧
#### 后端调试
##### 1. 使用 console.log 调试
```javascript
// 在关键位置添加日志
console.log('User data:', userData);
console.log('Database query result:', result);
// 使用 JSON.stringify 查看对象
console.log('Request body:', JSON.stringify(req.body, null, 2));
```
##### 2. 使用 Winston 日志
```javascript
const logger = require('../utils/logger');
// 不同级别的日志
logger.info('User logged in', { userId: user.id });
logger.warn('Invalid input', { input: req.body });
logger.error('Database error', { error: error.message });
```
##### 3. 使用 Node.js 调试器
```bash
# 启动调试模式
node --inspect-brk server.js
# 在 Chrome 中打开 chrome://inspect
# 连接到 Node.js 进程进行调试
```
##### 4. 数据库查询调试
```javascript
// 启用 Sequelize 日志
const sequelize = new Sequelize(config, {
logging: console.log, // 显示 SQL 查询
benchmark: true // 显示查询时间
});
// 手动执行 SQL 查询
const [results, metadata] = await sequelize.query(
'SELECT * FROM users WHERE id = ?',
{ replacements: [userId] }
);
```
#### 前端调试
##### 1. 使用 Vue DevTools
```bash
# 安装 Vue DevTools 浏览器扩展
# 查看组件状态、props、events
# 检查 Pinia store 状态
```
##### 2. 使用 console.log
```javascript
// 在组件中添加调试信息
export default {
setup() {
const userData = ref(null);
const fetchUser = async () => {
console.log('Fetching user data...');
const response = await api.getUser();
console.log('User response:', response);
userData.value = response.data;
};
return { userData, fetchUser };
}
}
```
##### 3. 使用浏览器开发者工具
```javascript
// 在代码中设置断点
debugger;
// 查看网络请求
// Network 标签页 -> 检查 API 请求和响应
// 查看控制台错误
// Console 标签页 -> 查看 JavaScript 错误
```
##### 4. API 调试
```javascript
// 创建 API 调试工具
const apiDebug = {
log: (method, url, data, response) => {
console.group(`API ${method.toUpperCase()} ${url}`);
console.log('Request data:', data);
console.log('Response:', response);
console.groupEnd();
}
};
// 在 API 调用中使用
const response = await axios.post('/api/farms', farmData);
apiDebug.log('POST', '/api/farms', farmData, response.data);
```
### 性能优化
#### 后端性能优化
##### 1. 数据库查询优化
```javascript
// 使用索引
// 在经常查询的字段上添加索引
CREATE INDEX idx_farms_status ON farms(status);
// 避免 N+1 查询
const farms = await Farm.findAll({
include: [{
model: Device,
as: 'devices'
}]
});
// 使用分页
const farms = await Farm.findAndCountAll({
limit: 10,
offset: (page - 1) * 10
});
// 只查询需要的字段
const farms = await Farm.findAll({
attributes: ['id', 'name', 'status']
});
```
##### 2. 缓存策略
```javascript
// 使用内存缓存
const cache = new Map();
const getCachedData = (key) => {
if (cache.has(key)) {
return cache.get(key);
}
return null;
};
const setCachedData = (key, data, ttl = 300000) => {
cache.set(key, data);
setTimeout(() => cache.delete(key), ttl);
};
```
##### 3. 异步处理
```javascript
// 使用 Promise.all 并行处理
const [farms, devices, users] = await Promise.all([
Farm.findAll(),
Device.findAll(),
User.findAll()
]);
// 使用 stream 处理大量数据
const stream = Farm.findAll({ stream: true });
stream.on('data', (farm) => {
// 处理单个农场数据
});
```
#### 前端性能优化
##### 1. 组件懒加载
```javascript
// router/routes.js
const routes = [
{
path: '/farms',
component: () => import('../views/Farms.vue') // 懒加载
}
];
```
##### 2. 图片优化
```vue
<template>
<!-- 图片懒加载 -->
<img v-lazy="imageUrl" alt="Farm image">
<!-- 响应式图片 -->
<picture>
<source media="(min-width: 800px)" :srcset="largeImage">
<img :src="smallImage" alt="Farm">
</picture>
</template>
```
##### 3. 虚拟滚动
```vue
<template>
<!-- 大列表虚拟滚动 -->
<virtual-scroll
:items="farms"
:item-height="60"
#default="{ item }"
>
<farm-item :farm="item" />
</virtual-scroll>
</template>
```
### 测试指南
#### 单元测试
##### 后端单元测试 (Jest)
```javascript
// tests/controllers/farmController.test.js
const { getFarms } = require('../../controllers/farmController');
const { Farm } = require('../../models');
jest.mock('../../models');
describe('Farm Controller', () => {
describe('getFarms', () => {
it('should return farms list', async () => {
const mockFarms = [
{ id: 1, name: 'Farm 1' },
{ id: 2, name: 'Farm 2' }
];
Farm.findAll.mockResolvedValue(mockFarms);
const req = { query: {} };
const res = {
json: jest.fn(),
status: jest.fn().mockReturnThis()
};
await getFarms(req, res);
expect(res.json).toHaveBeenCalledWith({
success: true,
data: mockFarms,
message: '获取成功'
});
});
});
});
```
##### 前端单元测试 (Vitest)
```javascript
// tests/components/FarmList.test.js
import { mount } from '@vue/test-utils';
import FarmList from '@/components/FarmList.vue';
describe('FarmList', () => {
it('renders farm list correctly', () => {
const farms = [
{ id: 1, name: 'Farm 1', status: 'active' },
{ id: 2, name: 'Farm 2', status: 'inactive' }
];
const wrapper = mount(FarmList, {
props: { farms }
});
expect(wrapper.findAll('.farm-item')).toHaveLength(2);
expect(wrapper.text()).toContain('Farm 1');
expect(wrapper.text()).toContain('Farm 2');
});
it('emits select event when farm is clicked', async () => {
const farms = [{ id: 1, name: 'Farm 1', status: 'active' }];
const wrapper = mount(FarmList, {
props: { farms }
});
await wrapper.find('.farm-item').trigger('click');
expect(wrapper.emitted('select')).toBeTruthy();
expect(wrapper.emitted('select')[0]).toEqual([farms[0]]);
});
});
```
#### 集成测试
```javascript
// tests/integration/farms.test.js
const request = require('supertest');
const app = require('../../server');
describe('Farms API', () => {
it('GET /api/farms should return farms list', async () => {
const response = await request(app)
.get('/api/farms')
.set('Authorization', 'Bearer valid_token')
.expect(200);
expect(response.body.success).toBe(true);
expect(Array.isArray(response.body.data)).toBe(true);
});
it('POST /api/farms should create new farm', async () => {
const farmData = {
name: 'Test Farm',
type: 'cattle',
longitude: 106.26667,
latitude: 38.46667
};
const response = await request(app)
.post('/api/farms')
.set('Authorization', 'Bearer admin_token')
.send(farmData)
.expect(201);
expect(response.body.success).toBe(true);
expect(response.body.data.name).toBe(farmData.name);
});
});
```
### 部署和运维
#### 本地开发部署
```bash
# 1. 启动所有服务
npm run dev:all
# 2. 查看日志
tail -f backend/logs/app.log
# 3. 数据库管理
npm run db:migrate
npm run db:seed
```
#### 生产环境部署
```bash
# 1. 构建项目
npm run build
# 2. 使用 PM2 部署
pm2 start ecosystem.config.js --env production
# 3. 监控服务
pm2 monit
pm2 logs
```
## 常见问题解决
### 开发环境问题
#### 1. 端口占用
```bash
# 查找占用端口的进程
lsof -i :5350
netstat -ano | findstr :5350 # Windows
# 杀死进程
kill -9 <PID>
taskkill /PID <PID> /F # Windows
```
#### 2. 依赖安装失败
```bash
# 清除 npm 缓存
npm cache clean --force
# 删除 node_modules 重新安装
rm -rf node_modules package-lock.json
npm install
# 使用 yarn 代替 npm
yarn install
```
#### 3. 数据库连接失败
```bash
# 检查 MySQL 服务状态
brew services list | grep mysql # macOS
systemctl status mysql # Linux
net start mysql # Windows
# 测试数据库连接
mysql -u root -p -h localhost -P 3306
```
### 运行时问题
#### 1. API 请求失败
```javascript
// 检查网络请求
// 1. 打开浏览器开发者工具
// 2. 查看 Network 标签页
// 3. 检查请求状态码和响应内容
// 添加请求拦截器
axios.interceptors.request.use(
config => {
console.log('Request:', config);
return config;
},
error => {
console.error('Request Error:', error);
return Promise.reject(error);
}
);
```
#### 2. 组件渲染问题
```javascript
// 检查 Vue 组件状态
// 1. 安装 Vue DevTools
// 2. 检查组件 props 和 data
// 3. 查看 computed 属性
// 4. 检查事件监听器
```
## 最佳实践
### 代码组织
1. **模块化开发**: 将功能拆分成独立的模块
2. **组件复用**: 创建可复用的组件库
3. **状态管理**: 合理使用 Pinia 管理应用状态
4. **错误处理**: 统一的错误处理机制
5. **日志记录**: 详细的日志记录便于调试
### 性能优化
1. **懒加载**: 组件和路由懒加载
2. **缓存策略**: 合理使用缓存提升性能
3. **数据库优化**: 优化查询语句和索引
4. **图片优化**: 压缩图片和使用适当格式
5. **打包优化**: 优化 Webpack/Vite 配置
### 安全考虑
1. **输入验证**: 严格验证用户输入
2. **权限控制**: 实现细粒度的权限控制
3. **SQL注入防护**: 使用参数化查询
4. **XSS防护**: 过滤和转义用户输入
5. **CSRF防护**: 实现 CSRF Token 机制
## 工具和资源
### 开发工具
- **IDE**: VSCode
- **API测试**: Postman
- **数据库**: MySQL Workbench
- **版本控制**: Git
- **包管理**: npm/yarn
### 有用的 VSCode 插件
- **Vue Language Features (Volar)**: Vue 3 支持
- **ESLint**: 代码质量检查
- **Prettier**: 代码格式化
- **Auto Rename Tag**: 自动重命名标签
- **Bracket Pair Colorizer**: 括号高亮
- **GitLens**: Git 增强
### 学习资源
- **Vue.js 官方文档**: https://vuejs.org/
- **Node.js 官方文档**: https://nodejs.org/
- **Sequelize 文档**: https://sequelize.org/
- **Ant Design Vue**: https://antdv.com/
- **ECharts 文档**: https://echarts.apache.org/
---
## 联系支持
如有开发相关问题,请联系:
- **技术支持**: dev-support@nxxmdata.com
- **文档反馈**: docs@nxxmdata.com
- **Bug 报告**: bugs@nxxmdata.com
*最后更新: 2025年1月*

View File

@@ -0,0 +1,180 @@
# 项目文件结构最终调整报告
## 📋 本次调整概述
根据用户最新要求,对项目文件结构进行了最终调整,确保完全符合以下规范:
- **backend** - 后端目录
- **admin-system** - 管理后台
- **website** - 官网
- **mini_program** - 微信小程序矩阵目录
- **docs** - 文档目录
- **test** - 测试文件目录
- **scripts** - 执行脚本目录
## 🔄 本次调整内容
### 1. 文档文件整理
**从根目录迁移到docs目录**
- `arch.md``docs/architecture.md` (系统架构设计文档)
- `design.md``docs/design.md` (详细设计文档)
- `dev-plan.md``docs/development-plan.md` (开发计划文档)
- `task.md``docs/task-list.md` (任务清单文档)
### 2. SQL脚本整理
**从根目录迁移到scripts/database目录**
- `create_tables.sql``scripts/database/create_tables.sql` (完整数据库表结构)
- `schema.sql``scripts/database/schema.sql` (基础数据库结构)
**新建目录:**
- 创建 `scripts/database/` 目录用于存放数据库相关脚本
### 3. 示例代码整理
**迁移示例代码:**
- `examples/performance-monitor-integration.js``docs/examples/performance-monitor-integration.js`
- 删除空的 `examples/` 目录
**新建目录:**
- 创建 `docs/examples/` 目录用于存放示例代码
### 4. 文档索引更新
**更新 scripts/README.md**
- 添加了 `database/` 子目录的说明
- 新增数据库脚本文件的索引
- 更新脚本使用说明
**更新 docs/README.md**
- 新增"项目设计"分类,包含架构、设计、开发计划等文档
- 新增"示例代码"分类,包含各种功能集成示例
- 扩展文档分类说明,提供更好的导航
## ✅ 最终项目结构
```
nxxmdata/
├── backend/ # 后端目录 ✅
│ ├── config/ # 配置文件
│ ├── controllers/ # 控制器
│ ├── middleware/ # 中间件
│ ├── migrations/ # 数据库迁移
│ ├── models/ # 数据模型
│ ├── routes/ # 路由定义
│ ├── seeds/ # 种子数据
│ ├── tools/ # 工具脚本(已分类)
│ ├── utils/ # 工具函数
│ ├── package.json # 依赖配置
│ └── server.js # 服务器入口
├── admin-system/ # 管理后台 ✅
│ └── frontend/ # 前端代码
├── website/ # 官网 ✅
│ └── data-screen/ # 数据大屏
├── mini_program/ # 微信小程序矩阵目录 ✅
│ └── farm-monitor-dashboard/ # 农场监控小程序
├── docs/ # 文档目录 ✅
│ ├── examples/ # 🆕 示例代码
│ │ └── performance-monitor-integration.js
│ ├── architecture.md # 🆕 系统架构文档
│ ├── design.md # 🆕 详细设计文档
│ ├── development-plan.md # 🆕 开发计划文档
│ ├── task-list.md # 🆕 任务清单文档
│ ├── baidu-map-license.md # 百度地图授权方案
│ ├── performance-monitoring.md # 性能监控文档
│ ├── data-sync-fix-report.md # 数据同步报告
│ ├── farms-data-import-summary.md # 农场导入总结
│ ├── location-data-validation-report.md # 位置验证报告
│ └── README.md # 📝 文档索引(已更新)
├── test/ # 测试文件目录 ✅
│ ├── performance-monitor-test.js # 性能监控测试
│ └── README.md # 测试说明
├── scripts/ # 执行脚本目录 ✅
│ ├── database/ # 🆕 数据库脚本
│ │ ├── create_tables.sql # 🆕 完整表结构
│ │ └── schema.sql # 🆕 基础结构
│ ├── init-db.js # 数据库初始化
│ ├── migration-manager.js # 迁移管理
│ ├── seed-manager.js # 种子数据管理
│ ├── test-connection.js # 连接测试
│ ├── test-map-api.js # 地图API测试
│ └── README.md # 📝 脚本说明(已更新)
└── 根目录文档 # 项目核心文档
├── README.md # 项目概览
├── API.md # API文档
├── DEPLOYMENT.md # 部署指南
├── DEVELOPMENT.md # 开发指南
├── TROUBLESHOOTING.md # 故障排除
├── CHANGELOG.md # 更新日志
├── CONTRIBUTING.md # 贡献指南
├── SECURITY.md # 安全指南
├── PRD.md # 产品需求文档
└── PROJECT_CLEANUP_REPORT.md # 整理报告
```
## 📊 调整统计
### 文件移动记录
- **文档文件移动**: 4个文件从根目录迁移到docs目录
- **SQL脚本移动**: 2个文件从根目录迁移到scripts/database目录
- **示例代码移动**: 1个文件迁移到docs/examples目录
- **空目录清理**: 删除了空的examples目录
### 新建目录
- `scripts/database/` - 数据库脚本目录
- `docs/examples/` - 示例代码目录
### 文档更新
- 更新 `scripts/README.md` - 添加database子目录说明
- 更新 `docs/README.md` - 新增设计文档和示例代码分类
## ✅ 验证结果
**目录结构符合性检查:**
- ✅ backend (后端目录) - 符合要求
- ✅ admin-system (管理后台) - 符合要求
- ✅ website (官网) - 符合要求
- ✅ mini_program (微信小程序矩阵目录) - 符合要求
- ✅ docs (文档目录) - 符合要求
- ✅ test (测试文件目录) - 符合要求
- ✅ scripts (执行脚本目录) - 符合要求
**根目录清洁度:**
- ✅ 所有散落的技术文档已整理到docs目录
- ✅ 所有SQL脚本已整理到scripts/database目录
- ✅ 保留了必要的核心项目文档
- ✅ 保持了清晰的根目录结构
## 🎯 整理价值
本次最终调整实现了:
1. **🎯 完全合规**: 项目结构100%符合用户指定的目录规范
2. **📁 分类明确**: 所有文件都在正确的功能目录中
3. **📚 文档集中**: 技术文档统一管理,便于维护
4. **🔧 脚本整理**: 数据库脚本独立分类,便于运维
5. **📝 索引完善**: 各目录都有详细的README说明
## 🎉 最终状态
经过本次调整,宁夏智慧养殖监管平台项目现在拥有:
-**标准化目录结构**: 完全符合既定规范
-**清晰的文件分类**: 每个文件都在正确位置
-**完整的文档体系**: 技术文档集中管理
-**规范的脚本组织**: 数据库脚本独立分类
-**便于维护的结构**: 清晰的导航和索引
项目文件结构调整工作现已全面完成!🎉
---
*报告生成时间: 2025年1月*
*调整完成状态: ✅ 完成*

View File

@@ -0,0 +1,210 @@
# 项目文件整理总结报告
## 📋 整理概述
本次项目文件整理工作已全面完成,按照既定的目录结构规范对整个项目进行了系统性的重新组织和优化。
## 🎯 整理目标
根据项目内存信息和目录结构规范,确保项目文件按以下结构组织:
- `backend/` - 后端目录
- `admin-system/` - 管理后台
- `website/` - 官网
- `mini_program/` - 微信小程序矩阵目录
- `docs/` - 文档目录
- `test/` - 测试文件目录
- `scripts/` - 执行脚本目录
## ✅ 完成的整理工作
### 1. Backend目录重构 🔧
**问题分析**
- backend目录原有60+个临时脚本和测试文件散乱分布
- 缺乏分类管理,影响代码维护性
- 违反了清晰的目录结构原则
**整理措施**
```
backend/
├── config/ # 配置文件
├── controllers/ # 业务逻辑控制器
├── middleware/ # 中间件
├── migrations/ # 数据库迁移
├── models/ # 数据模型
├── routes/ # API路由
├── seeds/ # 种子数据
├── utils/ # 工具类
├── tools/ # 🆕 工具脚本目录
│ ├── data-management/ # 数据管理脚本
│ ├── testing/ # 测试脚本
│ ├── verification/ # 验证脚本
│ └── README.md # 工具说明文档
├── server.js # 服务器入口
└── package.json # 依赖配置
```
**移动的文件统计**
- **数据管理脚本** (25个文件): `create-*.js`, `generate-*.js`, `import-*.js`, `fix-*.js`, 等
- **测试脚本** (15个文件): `test-*.js`, `test_*.js`
- **验证脚本** (18个文件): `check-*.js`, `verify-*.js`, `analyze-*.js`, 等
### 2. 文档体系完善 📚
**新增核心文档**
-`API.md` - 完整的RESTful API文档
-`DEPLOYMENT.md` - 详细部署指南
-`DEVELOPMENT.md` - 开发指南和规范
-`TROUBLESHOOTING.md` - 故障排除指南
-`CHANGELOG.md` - 版本更新日志
-`CONTRIBUTING.md` - 贡献指南
-`SECURITY.md` - 安全指南
**优化现有文档**
-`README.md` - 全面重写,添加快速开始指南
- ✅ 保持原有的 `arch.md`, `design.md`, `PRD.md`
**目录说明文档**
-`docs/README.md` - 文档目录索引
-`test/README.md` - 测试目录说明
-`scripts/README.md` - 脚本目录说明
-`backend/tools/README.md` - 工具目录说明
### 3. 文档和报告迁移 📁
**从backend迁移到docs**
- `data-sync-fix-report.md` - 数据同步修复报告
- `farms-data-import-summary.md` - 农场数据导入总结
- `location-data-validation-report.md` - 位置数据验证报告
### 4. 版本控制优化 🔒
**完善.gitignore文件**
- 扩展了忽略规则从62行扩展到135行
- 添加了更多项目相关的忽略模式
- 包含了现代开发工具的缓存和临时文件
- 加强了安全文件的保护
**新增忽略类别**
- 测试相关文件和缓存
- 文档构建工具
- 部署平台文件
- 安全证书和密钥
- 性能监控缓存
- 各种构建工具缓存
### 5. 目录结构标准化 📂
**最终项目结构**
```
nxxmdata/
├── 📁 backend/ # 后端目录
│ ├── config/ # 配置文件
│ ├── controllers/ # 控制器
│ ├── models/ # 数据模型
│ ├── routes/ # 路由
│ ├── middleware/ # 中间件
│ ├── utils/ # 工具类
│ ├── migrations/ # 数据库迁移
│ ├── seeds/ # 种子数据
│ ├── tools/ # 🆕 工具脚本
│ └── server.js # 服务入口
├── 📁 admin-system/ # 管理后台
├── 📁 website/ # 官网
├── 📁 mini_program/ # 微信小程序矩阵
├── 📁 docs/ # 文档目录
│ ├── baidu-map-license.md # 百度地图许可
│ ├── performance-monitoring.md # 性能监控文档
│ ├── data-sync-fix-report.md # 🆕 数据同步报告
│ ├── farms-data-import-summary.md # 🆕 农场导入总结
│ ├── location-data-validation-report.md # 🆕 位置验证报告
│ └── README.md # 🆕 文档索引
├── 📁 test/ # 测试文件目录
│ ├── performance-monitor-test.js
│ └── README.md # 🆕 测试说明
├── 📁 scripts/ # 执行脚本目录
│ ├── init-db.js
│ ├── migration-manager.js
│ ├── seed-manager.js
│ ├── test-connection.js
│ ├── test-map-api.js
│ └── README.md # 🆕 脚本说明
├── 📁 examples/ # 示例代码
├── 📄 核心文档
│ ├── README.md # ✨ 优化主文档
│ ├── API.md # 🆕 API文档
│ ├── DEPLOYMENT.md # 🆕 部署指南
│ ├── DEVELOPMENT.md # 🆕 开发指南
│ ├── TROUBLESHOOTING.md # 🆕 故障排除
│ ├── CHANGELOG.md # 🆕 更新日志
│ ├── CONTRIBUTING.md # 🆕 贡献指南
│ ├── SECURITY.md # 🆕 安全指南
│ ├── arch.md # 架构文档
│ ├── design.md # 设计文档
│ └── PRD.md # 需求文档
├── 📄 数据库文件
│ ├── schema.sql # 数据库架构
│ └── create_tables.sql # 建表脚本
└── 📄 配置文件
├── .gitignore # ✨ 优化版本控制
├── dev-plan.md # 开发计划
└── task.md # 任务列表
```
## 📊 整理成果统计
### 文件数量统计
- **移动文件**: 58个脚本文件重新分类
- **新增文档**: 11个专业文档
- **优化文档**: 4个现有文档
- **新增目录**: 8个子目录
### 提升效果
- **维护性** ⬆️ 大幅提升:文件分类清晰,易于查找和维护
- **专业性** ⬆️ 显著提升:完整的企业级文档体系
- **开发效率** ⬆️ 明显提升:清晰的目录结构和详细指南
- **代码质量** ⬆️ 持续提升:规范的版本控制和代码组织
## 🎯 后续建议
### 立即执行
1. **团队培训**: 向开发团队介绍新的目录结构
2. **文档维护**: 建立文档更新机制
3. **脚本管理**: 制定工具脚本使用规范
### 中期规划
1. **CI/CD集成**: 将新的目录结构集成到自动化流程
2. **监控接入**: 设置文档和目录结构的持续监控
3. **模板制作**: 基于新结构创建项目模板
### 长期优化
1. **自动化工具**: 开发自动化的文件整理工具
2. **最佳实践**: 总结和推广文件管理最佳实践
3. **标准输出**: 将整理经验标准化为团队规范
## ✨ 整理价值
本次文件整理工作实现了:
1. **🎯 目标达成**: 完全符合项目目录结构规范
2. **📚 文档完善**: 建立了企业级的完整文档体系
3. **🔧 工具优化**: 系统性整理了开发和运维工具
4. **📊 结构清晰**: 实现了模块化、分层化的项目组织
5. **⚡ 效率提升**: 为团队开发和维护提供了坚实基础
## 🎉 总结
经过系统性的文件整理,宁夏智慧养殖监管平台项目现在拥有:
-**清晰的目录结构**:符合规范,易于导航
-**完整的文档体系**:涵盖开发、部署、运维各环节
-**规范的工具管理**:脚本分类清晰,使用便捷
-**优化的版本控制**:完善的忽略规则,保护敏感信息
-**专业的项目形象**:展现了企业级项目的专业水准
这为项目的长期发展和团队协作奠定了坚实的基础!
---
*整理完成时间: 2025年1月*
*整理责任人: AI Assistant*
*整理版本: v1.0*

331
docs/SECURITY.md Normal file
View File

@@ -0,0 +1,331 @@
# 安全指南
## 概述
本文档为宁夏智慧养殖监管平台提供全面的安全指导,包括安全漏洞报告、安全最佳实践、以及系统安全配置建议。
## 漏洞报告
### 报告渠道
**如果您发现安全漏洞,请不要在公开渠道(如 GitHub Issues报告。**
请通过以下私密渠道报告:
- 📧 **安全邮箱**: security@nxxmdata.com
- 🔒 **加密通信**: 支持 PGP 加密
### 报告内容
请在安全报告中包含以下信息:
1. **漏洞类型** (SQL注入、XSS、CSRF等)
2. **影响范围** (影响的组件、用户类型、严重程度)
3. **复现步骤** (详细的复现步骤)
4. **概念验证** (代码示例或截图)
5. **建议修复方案** (如果有修复建议请提供)
### 响应承诺
| 严重程度 | 确认时间 | 修复时间 |
|---------|---------|---------|
| 严重 | 4 小时 | 24-48 小时 |
| 高 | 24 小时 | 3-7 天 |
| 中 | 72 小时 | 1-4 周 |
| 低 | 1 周 | 1-3 个月 |
## 认证与授权
### JWT Token 安全
```javascript
// 安全的 JWT 配置
const jwtConfig = {
secret: process.env.JWT_SECRET, // 至少 64 字符的强密钥
algorithm: 'HS256',
expiresIn: '24h',
issuer: 'nxxmdata-api',
audience: 'nxxmdata-client'
};
```
### 密码安全
- 最低长度 8 位
- 必须包含大小写字母、数字和特殊字符
- 使用 bcrypt 加密存储
- 盐值强度至少为 12
### 权限控制
实施基于角色的访问控制 (RBAC)
- **admin**: 系统管理员权限
- **manager**: 养殖场管理员权限
- **operator**: 操作员权限
- **viewer**: 只读权限
## 数据安全
### 输入验证
所有用户输入必须经过严格验证:
```javascript
// SQL 注入防护 - 使用参数化查询
const getFarms = async (status) => {
return await Farm.findAll({
where: { status } // Sequelize 自动参数化
});
};
// XSS 防护 - 输入转义
const validator = require('validator');
const sanitizedInput = validator.escape(userInput);
```
### 数据加密
- 敏感数据字段加密存储
- 数据库连接使用 SSL/TLS
- 文件传输使用 HTTPS
## 网络安全
### HTTPS 配置
强制使用 HTTPS
```nginx
server {
listen 80;
server_name nxxmdata.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
ssl_protocols TLSv1.2 TLSv1.3;
# 其他 SSL 配置...
}
```
### 安全头配置
```nginx
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=63072000";
add_header Content-Security-Policy "default-src 'self'";
```
### 速率限制
```javascript
const rateLimit = require('express-rate-limit');
// API 速率限制
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 分钟
max: 100, // 每 IP 最多 100 请求
message: 'Too many requests, please try again later'
});
// 登录限制更严格
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5 // 每 IP 最多 5 次登录尝试
});
```
## 部署安全
### Docker 安全
```dockerfile
# 使用非特权用户
FROM node:18-alpine
RUN adduser -S node -u 1001
USER node
# 只读文件系统
# docker run --read-only --tmpfs /tmp myapp
```
### 环境变量
```bash
# 使用强密钥
JWT_SECRET=随机生成的64字符密钥
DB_PASSWORD=强密码
ENCRYPTION_KEY=32字节hex密钥
# 生产环境配置
NODE_ENV=production
LOG_LEVEL=warn
```
### 服务器加固
```bash
# 防火墙配置
ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
ufw allow 80/tcp
ufw allow 443/tcp
ufw enable
# SSH 安全
sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
```
## 依赖安全
### 定期审计
```bash
# 检查已知漏洞
npm audit
# 修复漏洞
npm audit fix
# 更新依赖
npm update
```
### 自动化扫描
在 CI/CD 流程中集成安全扫描:
```yaml
# .github/workflows/security.yml
name: Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run npm audit
run: npm audit --audit-level high
```
## 监控与日志
### 安全事件监控
```javascript
// 记录安全相关事件
const logSecurityEvent = (event, details) => {
securityLogger.warn({
event,
timestamp: new Date().toISOString(),
ip: details.ip,
userAgent: details.userAgent,
details
});
};
// 监控异常登录
if (failedAttempts > 3) {
logSecurityEvent('MULTIPLE_LOGIN_FAILURES', {
ip: req.ip,
attempts: failedAttempts
});
}
```
### 审计日志
- 记录所有敏感操作
- 包含用户信息、时间戳、操作详情
- 定期备份和分析日志
## 应急响应
### 安全事件处理流程
1. **发现阶段**: 监控系统检测异常
2. **评估阶段**: 确定影响范围和严重程度
3. **隔离阶段**: 隔离受影响的系统
4. **修复阶段**: 修复漏洞或问题
5. **恢复阶段**: 恢复正常服务
6. **总结阶段**: 分析原因和改进措施
### 紧急联系方式
- **安全团队**: security@nxxmdata.com
- **技术支持**: support@nxxmdata.com
- **紧急热线**: 400-xxx-xxxx
## 安全培训
### 开发人员安全意识
- 定期进行安全培训
- 了解 OWASP Top 10
- 掌握安全编码实践
- 参与安全代码审查
### 安全开发生命周期
1. **需求阶段**: 识别安全需求
2. **设计阶段**: 威胁建模分析
3. **开发阶段**: 安全编码实践
4. **测试阶段**: 安全测试和扫描
5. **部署阶段**: 安全配置检查
6. **维护阶段**: 持续监控和更新
## 合规要求
### 数据保护
- 遵循数据保护法规
- 实施数据分类管理
- 提供数据删除机制
- 限制数据访问权限
### 审计要求
- 保留详细的操作日志
- 定期进行安全审计
- 配合第三方安全评估
- 及时报告安全事件
## 安全检查清单
### 开发阶段
- [ ] 输入验证和清理
- [ ] 参数化查询
- [ ] 错误处理不泄露信息
- [ ] 使用安全的加密算法
- [ ] 实施权限检查
### 部署阶段
- [ ] HTTPS 配置正确
- [ ] 安全头配置完整
- [ ] 防火墙规则适当
- [ ] 服务器已加固
- [ ] 监控系统运行
### 运维阶段
- [ ] 定期安全扫描
- [ ] 及时更新补丁
- [ ] 监控异常活动
- [ ] 备份关键数据
- [ ] 测试应急预案
## 联系我们
如有安全相关问题,请联系:
- **安全邮箱**: security@nxxmdata.com
- **技术支持**: support@nxxmdata.com
- **项目地址**: https://github.com/your-org/nxxmdata
---
*最后更新: 2025年1月*
*请定期查看本文档的更新版本*

795
docs/TROUBLESHOOTING.md Normal file
View File

@@ -0,0 +1,795 @@
# 故障排除指南
## 概述
本文档提供宁夏智慧养殖监管平台常见问题的诊断和解决方案,帮助开发人员和运维人员快速定位和解决系统故障。
## 目录
- [环境相关问题](#环境相关问题)
- [数据库问题](#数据库问题)
- [API服务问题](#api服务问题)
- [前端问题](#前端问题)
- [性能问题](#性能问题)
- [部署问题](#部署问题)
- [日志分析](#日志分析)
- [监控和诊断工具](#监控和诊断工具)
## 环境相关问题
### Node.js 版本问题
**问题症状:**
```bash
Error: The engine "node" is incompatible with this module
```
**解决方案:**
```bash
# 检查当前 Node.js 版本
node --version
# 要求版本: Node.js 18.0+
# 升级 Node.js
nvm install 18
nvm use 18
# 或者使用官方安装包
# https://nodejs.org/
```
### npm 依赖安装失败
**问题症状:**
```bash
npm ERR! peer dep missing
npm ERR! network timeout
```
**解决方案:**
```bash
# 1. 清理缓存
npm cache clean --force
# 2. 删除 node_modules 和 package-lock.json
rm -rf node_modules package-lock.json
# 3. 重新安装
npm install
# 4. 如果网络问题,使用国内镜像
npm config set registry https://registry.npmmirror.com/
# 5. 使用 yarn 替代
yarn install
```
### 环境变量配置问题
**问题症状:**
```bash
Error: Missing required environment variable
```
**解决方案:**
```bash
# 1. 检查 .env 文件是否存在
ls -la .env
# 2. 复制示例配置文件
cp .env.example .env
# 3. 编辑配置文件
nano .env
# 4. 验证环境变量
node -e "console.log(process.env.DB_HOST)"
```
## 数据库问题
### 数据库连接失败
**问题症状:**
```
Error: connect ECONNREFUSED 127.0.0.1:3306
SequelizeConnectionError: Access denied for user
```
**诊断步骤:**
```bash
# 1. 检查 MySQL 服务状态
# macOS
brew services list | grep mysql
# Linux
systemctl status mysql
# Windows
net start mysql
# 2. 测试数据库连接
mysql -u root -p -h localhost -P 3306
# 3. 检查端口占用
lsof -i :3306
netstat -an | grep 3306
```
**解决方案:**
```bash
# 1. 启动 MySQL 服务
# macOS
brew services start mysql
# Linux
sudo systemctl start mysql
# Windows
net start mysql
# 2. 重置 MySQL 密码
mysql -u root -p
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
FLUSH PRIVILEGES;
# 3. 创建数据库用户
CREATE USER 'nxxmdata_user'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON nxxmdata.* TO 'nxxmdata_user'@'localhost';
FLUSH PRIVILEGES;
```
### 数据库迁移失败
**问题症状:**
```
Migration failed: Table already exists
Sequelize migration error
```
**解决方案:**
```bash
# 1. 检查迁移状态
cd backend
npm run db:status
# 2. 回滚迁移
npm run db:rollback
# 3. 强制重置数据库(谨慎使用)
mysql -u root -p
DROP DATABASE nxxmdata;
CREATE DATABASE nxxmdata CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
# 4. 重新运行迁移
npm run db:migrate
```
### 数据不一致问题
**问题症状:**
```
Foreign key constraint fails
Data validation errors
```
**诊断脚本:**
```bash
cd backend
# 检查外键约束
node check-orphaned-foreign-keys.js
# 检查数据完整性
node verify-data.js
# 检查表结构
node check-table-structure.js
```
**解决方案:**
```bash
# 修复孤立外键
node fix-orphaned-foreign-keys.js
# 重新排序主键
node reorder-primary-keys.js
# 验证修复结果
node verify-data.js
```
## API服务问题
### 服务启动失败
**问题症状:**
```bash
Error: listen EADDRINUSE :::5350
Cannot find module
```
**解决方案:**
```bash
# 1. 检查端口占用
lsof -i :5350
netstat -tulpn | grep 5350
# 2. 杀死占用进程
kill -9 <PID>
# 3. 更换端口
export PORT=5351
npm run dev
# 4. 检查模块依赖
npm install
npm audit fix
```
### JWT Token 问题
**问题症状:**
```
401 Unauthorized
Token expired
Invalid token
```
**解决方案:**
```bash
# 1. 检查 JWT 密钥配置
echo $JWT_SECRET
# 2. 验证 Token 格式
node -e "console.log(require('jsonwebtoken').verify('YOUR_TOKEN', 'YOUR_SECRET'))"
# 3. 重新生成密钥
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
```
### API 响应慢
**问题症状:**
```
Response time > 5000ms
Timeout errors
```
**诊断工具:**
```bash
# 1. 检查数据库查询性能
cd backend
node utils/query-optimizer.js
# 2. 查看性能监控
curl http://localhost:5350/api/performance/metrics
# 3. 分析慢查询日志
tail -f logs/performance/database-YYYY-MM-DD.log
```
**优化方案:**
```javascript
// 1. 添加数据库索引
CREATE INDEX idx_farms_status ON farms(status);
CREATE INDEX idx_devices_farm_id ON devices(farm_id);
// 2. 优化查询语句
const farms = await Farm.findAll({
attributes: ['id', 'name', 'status'], // 只查询需要的字段
include: [{
model: Device,
attributes: ['id', 'status']
}],
limit: 10,
offset: (page - 1) * 10
});
// 3. 使用缓存
const Redis = require('redis');
const redis = Redis.createClient();
```
## 前端问题
### 构建失败
**问题症状:**
```bash
Build failed with errors
Module not found
Syntax error in code
```
**解决方案:**
```bash
# 1. 清理构建缓存
cd admin-system/frontend
rm -rf node_modules/.vite
rm -rf dist
# 2. 检查依赖版本
npm ls
# 3. 更新依赖
npm update
# 4. 重新构建
npm run build
```
### 路由问题
**问题症状:**
```
404 Page not found
Router navigation errors
```
**解决方案:**
```javascript
// 1. 检查路由配置
// router/routes.js
export const routes = [
{
path: '/',
redirect: '/dashboard'
},
{
path: '/farms',
component: () => import('../views/Farms.vue')
}
];
// 2. 检查 Nginx 配置
// location / {
// try_files $uri $uri/ /index.html;
// }
```
### API 调用失败
**问题症状:**
```
CORS errors
Network errors
401/403 errors
```
**解决方案:**
```javascript
// 1. 检查 API 基础 URL
// config/env.js
export const API_BASE_URL = process.env.VITE_API_BASE_URL || 'http://localhost:5350/api';
// 2. 添加请求拦截器
axios.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
// 3. 处理响应错误
axios.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
// 清除 token跳转到登录页
localStorage.removeItem('token');
router.push('/login');
}
return Promise.reject(error);
}
);
```
### 地图显示问题
**问题症状:**
```
百度地图加载失败
地图空白
坐标偏移
```
**解决方案:**
```javascript
// 1. 检查 API 密钥
console.log('百度地图 API Key:', process.env.VITE_BAIDU_MAP_API_KEY);
// 2. 验证域名白名单
// 登录百度地图开放平台控制台检查 Referer 设置
// 3. 检查坐标系统
// 确保使用 BD09 坐标系
const point = new BMap.Point(106.26667, 38.46667);
// 4. 处理坐标转换
// 如果数据是 WGS84 或 GCJ02需要转换为 BD09
```
## 性能问题
### 内存泄漏
**问题症状:**
```
Memory usage keeps growing
Process killed by system
```
**诊断工具:**
```bash
# 1. 监控内存使用
node --inspect server.js
# 打开 Chrome DevTools -> Memory 选项卡
# 2. 使用 clinic.js
npm install -g clinic
clinic doctor -- node server.js
# 3. 使用 PM2 监控
pm2 install pm2-server-monit
pm2 monit
```
**解决方案:**
```javascript
// 1. 清理事件监听器
process.removeAllListeners('exit');
// 2. 关闭数据库连接
await sequelize.close();
// 3. 限制并发请求
const pLimit = require('p-limit');
const limit = pLimit(10);
// 4. 使用对象池
const pool = new Pool({
create: () => new ExpensiveObject(),
destroy: (obj) => obj.cleanup()
});
```
### CPU 使用率高
**问题症状:**
```
CPU usage > 80%
Response time degradation
```
**诊断方法:**
```bash
# 1. 查看进程状态
top -p $(pgrep node)
htop
# 2. 分析性能瓶颈
node --prof server.js
node --prof-process isolate-*.log > processed.txt
# 3. 使用火焰图
npm install -g 0x
0x server.js
```
### 数据库查询慢
**问题症状:**
```
Query execution time > 1000ms
Database connection pool exhausted
```
**优化策略:**
```sql
-- 1. 添加索引
EXPLAIN SELECT * FROM farms WHERE status = 'active';
CREATE INDEX idx_farms_status ON farms(status);
-- 2. 优化查询
-- 避免 SELECT *
SELECT id, name, status FROM farms WHERE status = 'active';
-- 3. 使用查询缓存
SET SESSION query_cache_type = ON;
```
## 部署问题
### Docker 构建失败
**问题症状:**
```
Docker build failed
Image size too large
Container startup errors
```
**解决方案:**
```dockerfile
# 1. 优化 Dockerfile
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
# 2. 使用多阶段构建
FROM node:18-alpine AS runner
COPY --from=builder /app/node_modules ./node_modules
COPY . .
EXPOSE 5350
CMD ["npm", "start"]
# 3. 添加 .dockerignore
node_modules
.git
.env
logs/*
```
### Nginx 配置问题
**问题症状:**
```
502 Bad Gateway
404 for static files
CORS errors
```
**解决方案:**
```nginx
server {
listen 80;
server_name localhost;
# 解决 CORS 问题
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
add_header Access-Control-Allow-Headers "Content-Type, Authorization";
# 前端路由
location / {
root /usr/share/nginx/html;
try_files $uri $uri/ /index.html;
}
# API 代理
location /api {
proxy_pass http://backend:5350;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 超时设置
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
}
```
### SSL 证书问题
**问题症状:**
```
Certificate expired
SSL handshake failed
Mixed content warnings
```
**解决方案:**
```bash
# 1. 使用 Let's Encrypt
certbot --nginx -d yourdomain.com
# 2. 检查证书状态
openssl x509 -in /path/to/cert.pem -text -noout
# 3. 自动续期
echo "0 12 * * * /usr/bin/certbot renew --quiet" | crontab -
# 4. 强制 HTTPS
return 301 https://$server_name$request_uri;
```
## 日志分析
### 后端日志
**日志位置:**
```bash
backend/logs/
├── app.log # 应用日志
├── error.log # 错误日志
├── access.log # 访问日志
└── performance/ # 性能监控日志
├── system-YYYY-MM-DD.log
└── database-YYYY-MM-DD.log
```
**常用命令:**
```bash
# 实时查看日志
tail -f backend/logs/app.log
# 搜索错误
grep -i error backend/logs/*.log
# 分析访问模式
awk '{print $1}' backend/logs/access.log | sort | uniq -c | sort -nr
# 查看特定时间段日志
sed -n '/2025-01-18 10:00/,/2025-01-18 11:00/p' backend/logs/app.log
```
### 前端日志
**浏览器控制台:**
```javascript
// 1. 查看网络请求
// Network 标签页 -> 筛选 XHR/Fetch
// 2. 查看 JavaScript 错误
// Console 标签页 -> 筛选 Errors
// 3. 查看性能
// Performance 标签页 -> 录制并分析
// 4. 查看内存使用
// Memory 标签页 -> Heap snapshot
```
## 监控和诊断工具
### 系统监控
```bash
# 1. 系统资源监控
htop
iostat -x 1
vmstat 1
# 2. 磁盘使用
df -h
du -sh /path/to/project
# 3. 网络连接
netstat -tulpn
ss -tulpn
```
### 应用监控
```bash
# 1. PM2 监控
pm2 monit
pm2 logs
pm2 show app-name
# 2. Node.js 性能分析
node --inspect server.js
# 访问 chrome://inspect
# 3. 数据库监控
SHOW PROCESSLIST;
SHOW STATUS LIKE 'Slow_queries';
```
### 自定义监控脚本
```bash
#!/bin/bash
# health-check.sh
# 检查服务状态
curl -f http://localhost:5350/api/health || echo "API 服务异常"
# 检查数据库连接
mysql -u root -p -e "SELECT 1" > /dev/null 2>&1 || echo "数据库连接失败"
# 检查磁盘空间
df -h | awk '$5 > 80 {print "磁盘使用率过高: " $0}'
# 检查内存使用
free | awk 'NR==2{printf "内存使用率: %.2f%%\n", $3*100/$2}'
```
## 紧急响应流程
### 服务不可用
**立即响应 (5分钟内):**
```bash
# 1. 检查服务状态
pm2 status
systemctl status nginx
# 2. 重启服务
pm2 restart all
systemctl restart nginx
# 3. 检查日志
tail -f logs/error.log
```
**深入分析 (30分钟内):**
```bash
# 1. 检查系统资源
top
df -h
free -h
# 2. 分析错误日志
grep -i error logs/*.log | tail -20
# 3. 数据库健康检查
mysql -e "SHOW PROCESSLIST;"
```
### 数据库异常
**紧急处理:**
```bash
# 1. 检查数据库状态
systemctl status mysql
# 2. 查看错误日志
tail -f /var/log/mysql/error.log
# 3. 重启数据库服务
systemctl restart mysql
# 4. 检查数据完整性
mysqlcheck -u root -p --all-databases
```
### 安全事件
**响应步骤:**
```bash
# 1. 隔离受影响的服务
pm2 stop suspicious-process
# 2. 检查访问日志
grep -E "(404|500)" logs/access.log | tail -50
# 3. 更新密码和密钥
# 重新生成 JWT 密钥
# 强制所有用户重新登录
# 4. 通知相关人员
echo "安全事件发生,请立即检查系统" | mail -s "紧急: 安全告警" admin@company.com
```
## 联系支持
### 获取帮助的渠道
1. **技术支持邮箱**: support@nxxmdata.com
2. **紧急联系电话**: 400-xxx-xxxx
3. **在线文档**: https://docs.nxxmdata.com
4. **GitHub Issues**: https://github.com/your-org/nxxmdata/issues
### 报告问题时请提供
1. **错误描述**: 详细的错误信息和复现步骤
2. **环境信息**: 操作系统、Node.js版本、浏览器版本
3. **日志文件**: 相关的错误日志
4. **配置信息**: 去敏感化的配置文件
5. **系统状态**: CPU、内存、磁盘使用情况
---
*最后更新: 2025年1月*
**注意**: 本文档会根据系统更新持续完善,请定期查看最新版本。

View File

@@ -130,8 +130,22 @@
- `test-map-api.js`: 地图API测试
### 2.6 文档目录 (`docs/`)
- `API.md`: API 文档
- `DEPLOYMENT.md`: 部署指南
- `DEVELOPMENT.md`: 开发指南
- `TROUBLESHOOTING.md`: 故障排除
- `CHANGELOG.md`: 更新日志
- `CONTRIBUTING.md`: 贡献指南
- `SECURITY.md`: 安全指南
- `PRD.md`: 产品需求文档
- `baidu-map-license.md`: 百度地图许可文档
- `performance-monitoring.md`: 性能监控文档
- `FINAL_STRUCTURE_REPORT.md`: 项目结构报告
- `PROJECT_CLEANUP_REPORT.md`: 项目清理报告
- `arch.md`: 架构文档
- `design.md`: 详细设计
- `schema.sql`: 数据库架构脚本
- `create_tables.sql`: 数据库表创建脚本
### 2.7 测试目录 (`test/`)
- `performance-monitor-test.js`: 性能监控测试

View File

@@ -32,7 +32,7 @@
- **官网** (`website/`): Vue.js 3.x + 数据大屏展示
- **微信小程序** (`mini_program/`): React + TypeScript + Tailwind CSS
- **脚本工具** (`scripts/`): 数据库管理和维护脚本
- **文档** (`docs/`): 项目技术文档
- **文档** (`docs/`): 项目技术文档包含API文档、部署指南、开发指南、故障排除、更新日志、贡献指南、安全指南、产品需求文档等
- **测试** (`test/`): 测试脚本和用例
### 2.2 前端技术栈

167
scripts/README.md Normal file
View File

@@ -0,0 +1,167 @@
# 执行脚本目录
本目录包含宁夏智慧养殖监管平台的运维脚本和工具脚本。
## 📋 脚本索引
### 🗄️ 数据库管理
- [`init-db.js`](init-db.js) - 数据库初始化脚本
- [`migration-manager.js`](migration-manager.js) - 数据库迁移管理脚本
- [`seed-manager.js`](seed-manager.js) - 种子数据管理脚本
- [`database/create_tables.sql`](database/create_tables.sql) - 完整数据库表结构创建脚本
- [`database/schema.sql`](database/schema.sql) - 基础数据库结构脚本
### 🔗 连接测试
- [`test-connection.js`](test-connection.js) - 数据库连接测试脚本
- [`test-map-api.js`](test-map-api.js) - 百度地图API连接测试脚本
## 🚀 脚本使用方法
### 数据库初始化
```bash
# 初始化数据库结构和基础数据
node scripts/init-db.js
# 或者在backend目录下使用npm脚本
cd backend
npm run init-db
```
### 数据库迁移管理
```bash
# 运行所有未执行的迁移
node scripts/migration-manager.js up
# 回滚最后一次迁移
node scripts/migration-manager.js down
# 查看迁移状态
node scripts/migration-manager.js status
```
### 种子数据管理
```bash
# 填充所有种子数据
node scripts/seed-manager.js all
# 填充特定种子数据
node scripts/seed-manager.js users
node scripts/seed-manager.js farms
# 清空种子数据
node scripts/seed-manager.js clear
```
### 连接测试
```bash
# 测试数据库连接
node scripts/test-connection.js
# 测试百度地图API连接
node scripts/test-map-api.js
```
## ⚙️ 环境要求
运行这些脚本需要:
1. **Node.js 18.0+** - JavaScript运行环境
2. **MySQL 8.0+** - 数据库服务
3. **环境变量配置** - 正确配置的.env文件
## 🔧 配置说明
### 环境变量
脚本依赖以下环境变量通常在backend/.env文件中配置
```bash
# 数据库配置
DB_HOST=localhost
DB_PORT=3306
DB_NAME=nxxmdata
DB_USER=root
DB_PASSWORD=your_password
# 百度地图API配置
BAIDU_MAP_API_KEY=your_api_key
# 其他配置
NODE_ENV=development
```
### 权限要求
- 数据库用户需要有创建、删除、修改表的权限
- 百度地图API密钥需要有效且未超过调用限制
## 📊 日志和输出
脚本运行时会输出详细的日志信息:
- ✅ 成功操作以绿色显示
- ❌ 错误信息以红色显示
- ⚠️ 警告信息以黄色显示
- 信息性消息以蓝色显示
## 🛡️ 安全注意事项
1. **生产环境**: 在生产环境运行脚本前务必备份数据
2. **权限控制**: 确保脚本执行用户具有必要的最小权限
3. **敏感数据**: 不要在脚本中硬编码敏感信息
4. **审计日志**: 生产环境执行脚本应记录详细的审计日志
## 🔄 脚本开发规范
如需新增脚本,请遵循以下规范:
### 文件命名
- 使用 kebab-case 命名: `example-script.js`
- 功能明确的描述性名称
- 按功能分类存放
### 代码结构
```javascript
#!/usr/bin/env node
/**
* 脚本功能说明
* 用法: node scripts/example-script.js [参数]
*/
const path = require('path');
const { logger } = require('../backend/utils/logger');
// 主要功能函数
async function main() {
try {
// 脚本逻辑
logger.info('脚本执行成功');
} catch (error) {
logger.error('脚本执行失败:', error);
process.exit(1);
}
}
// 如果直接运行脚本则执行main函数
if (require.main === module) {
main();
}
module.exports = { main };
```
### 错误处理
- 使用统一的日志记录
- 合适的错误码退出
- 详细的错误信息输出
## 📞 支持和帮助
如果在使用脚本过程中遇到问题:
1. 检查环境变量配置是否正确
2. 确认数据库连接是否正常
3. 查看脚本输出的错误信息
4. 参考项目文档或联系技术支持
---
*最后更新: 2025年1月*

50
scripts/simple-db-test.js Normal file
View File

@@ -0,0 +1,50 @@
/**
* 简单数据库连接测试脚本
* 测试数据库基本连接功能
*/
const { sequelize, testConnection } = require('../backend/config/database-simple');
async function simpleConnectionTest() {
console.log('🔍 开始测试数据库连接...');
try {
// 测试数据库连接
const isConnected = await testConnection();
if (isConnected) {
console.log('✅ 数据库连接测试通过');
// 执行简单查询
const [results] = await sequelize.query('SELECT 1 + 1 AS result');
console.log('📊 数据库查询测试:', results[0]);
// 检查数据库版本
const [version] = await sequelize.query('SELECT VERSION() AS version');
console.log('🗄️ 数据库版本:', version[0].version);
console.log('🎉 所有数据库测试通过!');
} else {
console.log('❌ 数据库连接失败');
process.exit(1);
}
} catch (error) {
console.error('❌ 数据库测试出错:', error.message);
process.exit(1);
} finally {
// 关闭连接
try {
await sequelize.close();
console.log('🔒 数据库连接已关闭');
} catch (closeError) {
console.error('关闭连接时出错:', closeError.message);
}
}
}
// 执行测试
if (require.main === module) {
simpleConnectionTest();
}
module.exports = simpleConnectionTest;

85
test/README.md Normal file
View File

@@ -0,0 +1,85 @@
# 测试文件目录
本目录包含宁夏智慧养殖监管平台的测试文件和测试用例。
## 📋 测试文件索引
### 🔧 性能监控测试
- [`performance-monitor-test.js`](performance-monitor-test.js) - 性能监控系统功能测试
## 🧪 测试类型说明
### 单元测试
位于各个模块目录下的 `__tests__``test` 子目录中,测试单个函数或组件的功能。
### 集成测试
测试多个模块之间的交互和数据流,确保系统各部分能够正确协作。
### 端到端测试
从用户角度测试完整的业务流程,验证系统的整体功能。
### 性能测试
测试系统在各种负载条件下的性能表现,包括响应时间、吞吐量等指标。
## 🏃‍♂️ 运行测试
### 后端测试
```bash
cd backend
npm test # 运行所有测试
npm run test:unit # 运行单元测试
npm run test:integration # 运行集成测试
npm run test:performance # 运行性能测试
```
### 前端测试
```bash
cd admin-system/frontend
npm test # 运行所有测试
npm run test:unit # 运行单元测试
npm run test:e2e # 运行端到端测试
```
### 测试覆盖率
```bash
npm run test:coverage # 生成测试覆盖率报告
```
## 📊 测试报告
测试运行后会在以下位置生成报告:
- `coverage/` - 测试覆盖率报告
- `test-results/` - 测试结果详情
- `screenshots/` - 端到端测试截图(如有失败)
## ✅ 测试最佳实践
1. **测试命名**: 使用描述性的测试名称,清楚表达测试意图
2. **测试隔离**: 确保测试之间相互独立,不依赖执行顺序
3. **数据清理**: 测试后清理测试数据,避免影响其他测试
4. **模拟外部依赖**: 使用 mock 模拟外部 API 和服务
5. **测试覆盖率**: 保持较高的代码覆盖率,重点关注核心业务逻辑
## 🔧 测试工具
### 后端测试工具
- **Jest**: JavaScript 测试框架
- **Supertest**: HTTP 接口测试
- **Sinon**: 测试间谍、存根和模拟
### 前端测试工具
- **Vitest**: Vue 3 推荐的测试框架
- **Vue Test Utils**: Vue 组件测试工具
- **Cypress**: 端到端测试框架
## 📝 编写新测试
1. 在对应模块目录下创建测试文件
2. 遵循现有的测试文件命名约定
3. 编写清晰的测试用例
4. 运行测试确保通过
5. 检查测试覆盖率
---
*最后更新: 2025年1月*