### Save PM2 Configuration and Setup Autostart (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Saves the current list of PM2-managed processes to ensure they are restored after a system reboot. It also initiates the setup for PM2 to automatically start applications on system boot by running 'pm2 startup' and following the on-screen instructions.
```bash
# 保存当前进程列表
pm2 save
# 设置开机自启
pm2 startup
# 按照提示执行返回的命令
```
--------------------------------
### Start Development Server (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/README.md
Command to start the development server for the application. This allows for local testing and development.
```bash
npm run dev
```
--------------------------------
### Install Git (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Installs the Git version control system on Debian-based Linux distributions using apt. This is necessary for cloning and managing the project's codebase. It first updates the package list and then installs Git.
```bash
sudo apt update
sudo apt install git -y
```
--------------------------------
### Start Next.js Application with PM2 (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Starts the Next.js application using PM2. It demonstrates two methods: directly using 'npm start' via PM2, and a more robust approach using an 'ecosystem.config.js' file for detailed configuration of the application process.
```bash
# 方式1:直接启动
pm2 start npm --name "stock-toolbox" -- start
# 方式2:使用配置文件(推荐)
# 创建 ecosystem.config.js
cat > ecosystem.config.js << EOF
module.exports = {
apps: [{
name: 'stock-toolbox',
script: 'npm',
args: 'start',
cwd: '$(pwd)',
instances: 1,
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'production',
PORT: 3000
}
}]
}
EOF
# 使用配置文件启动
pm2 start ecosystem.config.js
```
--------------------------------
### Install Node.js 20 using NVM (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Installs Node.js version 20 using Node Version Manager (NVM). This is a prerequisite for running the Next.js application. It downloads and executes the NVM installation script, sources the bash profile, and then installs, uses, and sets Node.js 20 as the default.
```bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 20
nvm use 20
nvm alias default 20
```
--------------------------------
### Configure Environment Variables (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/README.md
Commands to copy the example environment file and set up database connection details. This step is crucial for the application to connect to the database.
```bash
cp .env.example .env
# 配置数据库连接
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=123456
DB_NAME=stock_lab
```
--------------------------------
### Install Project Dependencies (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/README.md
Command to install project dependencies using npm. This command should be run after cloning the repository and navigating into the project directory.
```bash
npm install
```
--------------------------------
### Configure Environment Variables (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Sets up environment variables for the application. It copies an example environment file to '.env.local' or prompts the user to create and edit it manually using 'nano'. This file contains crucial configuration like database credentials and API URLs.
```bash
# 创建或更新环境配置文件
cp .env.example .env.local # 如果有示例文件
# 或者直接创建
nano .env.local
```
--------------------------------
### Install PM2 Globally (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Installs PM2, a production process manager for Node.js applications, globally on the system using npm. This command is required before using PM2 to manage application services.
```bash
npm install -g pm2
```
--------------------------------
### Get Platform and Service Data API
Source: https://github.com/lijianye521/my-app/blob/main/API-Documentation.md
Retrieves data for platforms, services, and agents. Requires user login for access. The response includes arrays for platforms, services, and agents, with detailed properties for each item like ID, name, description, status, and URL. Requires GET request to /platforms.
```JSON
{
"platforms": [
{
"id": "platform_code",
"name": "平台名称",
"description": "平台描述",
"iconName": "icon_name",
"status": "运行中",
"url": "http://example.com",
"color": "blue",
"urlType": "internal",
"otherInformation": "其他信息"
}
],
"services": [...],
"agents": [...]
}
```
--------------------------------
### Platform Services - Get Platforms and Services
Source: https://github.com/lijianye521/my-app/blob/main/API-Documentation.md
Retrieves data for platforms, services, and agents. Requires user login.
```APIDOC
## GET /platforms
### Description
Retrieves data for platforms, services, and agents. Requires user login.
### Method
GET
### Endpoint
/api/platforms
### Parameters
#### Query Parameters
- **Requires Login**
### Response
#### Success Response
- **platforms** (array) - Array of platform objects.
- **id** (string) - Platform code.
- **name** (string) - Platform name.
- **description** (string) - Platform description.
- **iconName** (string) - Icon name.
- **status** (string) - Current status (e.g., '运行中').
- **url** (string) - URL of the platform.
- **color** (string) - Display color.
- **urlType** (string) - Type of URL ('internal' or 'terminal').
- **otherInformation** (string) - Other relevant information.
- **services** (array) - Array of service objects.
- **agents** (array) - Array of agent objects.
### Response Example
```json
{
"platforms": [
{
"id": "platform_code",
"name": "平台名称",
"description": "平台描述",
"iconName": "icon_name",
"status": "运行中",
"url": "http://example.com",
"color": "blue",
"urlType": "internal",
"otherInformation": "其他信息"
}
],
"services": [],
"agents": []
}
```
```
--------------------------------
### Install/Update Node.js Dependencies (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Installs or updates the project's Node.js dependencies. It includes an optional step to clean up old 'node_modules' and 'package-lock.json' files to resolve potential dependency conflicts before running 'npm install'.
```bash
# 清理旧的node_modules和锁文件(可选,解决依赖冲突)
rm -rf node_modules package-lock.json
# 安装依赖
npm install
# 或者使用 yarn
# yarn install
```
--------------------------------
### Development Environment Commands (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Lists common commands for developing the Next.js application. These include starting the development server, running linters for code quality, executing tests, and performing type checking.
```bash
# 启动开发服务器
npm run dev
# 代码检查
npm run lint
# 运行测试
npm test
# 类型检查
npm run type-check
```
--------------------------------
### GET /api/platforms
Source: https://context7.com/lijianye521/my-app/llms.txt
Retrieves all platform services grouped by type. Requires valid session authentication.
```APIDOC
## GET /api/platforms
### Description
Retrieves all platform services grouped by type with authentication.
### Method
GET
### Endpoint
/api/platforms
### Parameters
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
- **platforms** (array) - List of platform objects.
- **services** (array) - List of service objects.
- **agents** (array) - List of agent objects.
#### Response Example
```json
{
"platforms": [
{
"id": "ainews-admin",
"name": "AINEWS运营管理",
"description": "AI新闻运营管理平台",
"iconName": "Newspaper",
"status": "运行中",
"url": "http://10.106.19.29:8080/admin",
"color": "bg-blue-500",
"urlType": "internal",
"otherInformation": null
}
],
"services": [
{
"id": "ocean-service",
"name": "Ocean数据处理服务",
"description": "大规模数据处理平台",
"iconName": "Waves",
"url": "http://10.106.19.30:9000/ocean",
"color": "bg-cyan-500",
"urlType": "internal",
"otherInformation": null
}
],
"agents": [
{
"id": "ai-assistant",
"name": "AI助手",
"description": "智能助理服务",
"iconName": "Bot",
"url": "http://10.106.19.31:8000/ai",
"color": "bg-purple-500",
"urlType": "internal",
"otherInformation": null
}
]
}
```
```
--------------------------------
### Get All Platform Services (TypeScript)
Source: https://context7.com/lijianye521/my-app/llms.txt
Retrieves all platform services grouped by type. Requires valid session authentication. The response includes lists of platforms, services, and agents, each with detailed properties.
```typescript
// GET /api/platforms
// Requires: Valid session authentication
// Response
{
"platforms": [
{
"id": "ainews-admin",
"name": "AINEWS运营管理",
"description": "AI新闻运营管理平台",
"iconName": "Newspaper",
"status": "运行中",
"url": "http://10.106.19.29:8080/admin",
"color": "bg-blue-500",
"urlType": "internal",
"otherInformation": null
}
],
"services": [
{
"id": "ocean-service",
"name": "Ocean数据处理服务",
"description": "大规模数据处理平台",
"iconName": "Waves",
"url": "http://10.106.19.30:9000/ocean",
"color": "bg-cyan-500",
"urlType": "internal",
"otherInformation": null
}
],
"agents": [
{
"id": "ai-assistant",
"name": "AI助手",
"description": "智能助理服务",
"iconName": "Bot",
"url": "http://10.106.19.31:8000/ai",
"color": "bg-purple-500",
"urlType": "internal",
"otherInformation": null
}
]
}
// Implementation usage
import { getServerSession } from "next-auth";
async function fetchPlatforms() {
const response = await fetch('/api/platforms', {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
});
if (response.status === 401) {
throw new Error("未授权访问");
}
const data = await response.json();
return data;
}
```
--------------------------------
### User Management - Get User List
Source: https://github.com/lijianye521/my-app/blob/main/API-Documentation.md
Retrieves a list of all users. Requires administrator privileges.
```APIDOC
## GET /users
### Description
Retrieves a list of all users. Requires administrator privileges.
### Method
GET
### Endpoint
/api/users
### Parameters
#### Query Parameters
- **Requires Administrator Privileges**
### Response
#### Success Response
- **success** (boolean) - Indicates if the operation was successful.
- **data** (array) - An array of user objects.
- **id** (integer) - User ID.
- **username** (string) - Username.
- **nickname** (string) - Nickname.
- **email** (string) - Email address.
- **role** (string) - User role ('admin' or 'user').
- **is_active** (integer) - Activation status (1 for active, 0 for inactive).
- **created_at** (string) - Timestamp of creation.
- **updated_at** (string) - Timestamp of last update.
### Response Example
```json
{
"success": true,
"data": [
{
"id": 1,
"username": "admin",
"nickname": "管理员",
"email": "admin@example.com",
"role": "admin",
"is_active": 1,
"created_at": "2024-01-01T12:00:00.000Z",
"updated_at": "2024-01-01T12:00:00.000Z"
}
]
}
```
```
--------------------------------
### Get User List API (Admin)
Source: https://github.com/lijianye521/my-app/blob/main/API-Documentation.md
Retrieves a list of all users on the platform. This API requires administrator privileges. The response includes a success flag and an array of user objects, each containing details like id, username, email, role, and timestamps. Requires GET request to /users.
```JSON
{
"success": true,
"data": [
{
"id": 1,
"username": "admin",
"nickname": "管理员",
"email": "admin@example.com",
"role": "admin",
"is_active": 1,
"created_at": "2024-01-01T12:00:00.000Z",
"updated_at": "2024-01-01T12:00:00.000Z"
}
]
}
```
--------------------------------
### Create Users Table SQL
Source: https://context7.com/lijianye521/my-app/llms.txt
Defines the 'users' table structure for storing user credentials, roles, and account status. Includes primary key, unique username constraint, and default values for common fields. Also includes an example INSERT statement for a default admin user.
```sql
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`username` varchar(50) NOT NULL COMMENT '用户名',
`password` varchar(255) NOT NULL COMMENT '用户密码(加密存储)',
`nickname` varchar(100) DEFAULT NULL COMMENT '用户昵称',
`email` varchar(100) DEFAULT NULL COMMENT '邮箱地址',
`role` enum('admin','user') NOT NULL DEFAULT 'user' COMMENT '用户角色',
`is_active` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否激活',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Default admin user (password: "password")
INSERT INTO `users` (`username`, `password`, `nickname`, `email`, `role`)
VALUES ('admin', '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', '系统管理员', 'admin@company.com', 'admin')
ON DUPLICATE KEY UPDATE username=username;
```
--------------------------------
### Code Update Workflow (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Outlines the steps for updating the project's codebase in a production environment. It involves stopping the running service, pulling the latest code, installing new dependencies, running database migrations, rebuilding the application, and finally restarting the service.
```bash
# 1. 停止服务
pm2 stop stock-toolbox
# 2. 更新代码
git pull origin main
# 3. 安装新依赖
npm install
# 4. 运行数据库迁移
node database/migrate.js up
# 5. 重新构建
npm run build
# 6. 重启服务
pm2 restart stock-toolbox
```
--------------------------------
### MySQL Database Connection Management (TypeScript)
Source: https://context7.com/lijianye521/my-app/llms.txt
Manages a MySQL connection pool using 'mysql2/promise'. It supports automatic database initialization, retry logic, and configuration via environment variables. Includes functions to get a database connection and check its status.
```typescript
// lib/db.ts
import mysql from 'mysql2/promise';
// Configuration from environment variables
const dbConfig = {
host: process.env.DB_HOST || 'localhost',
port: Number(process.env.DB_PORT) || 3306,
user: process.env.DB_USER || 'root2',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || 'stock_lab',
};
// Get database connection with auto-initialization
export async function getDb() {
await initializeDatabase();
return mysql.createPool({
...dbConfig,
waitForConnections: true,
connectionLimit: 10,
multipleStatements: true,
connectTimeout: 30000,
});
}
// Usage in API routes
import { getDb } from '@/lib/db';
export async function GET() {
try {
const db = await getDb();
const [rows] = await db.query('SELECT * FROM platform_services');
return NextResponse.json({ data: rows });
} catch (error) {
console.error('Database error:', error);
return NextResponse.json(
{ error: 'Database query failed' },
{ status: 500 }
);
}
}
// Check database connection status
export async function checkDatabaseConnection() {
let connection;
try {
const pool = mysql.createPool({
host: dbConfig.host,
port: dbConfig.port,
user: dbConfig.user,
password: dbConfig.password,
});
connection = await pool.getConnection();
const [version] = await connection.query('SELECT VERSION() as version');
const [status] = await connection.query('SHOW STATUS LIKE "Threads_connected"');
return {
success: true,
message: '数据库连接正常',
version: (version as any)[0].version,
connections: (status as any)[0].Value
};
} catch (error) {
return {
success: false,
error: (error as Error).message
};
} finally {
if (connection) connection.release();
}
}
```
--------------------------------
### Wind Terminal Integration with URL Routing (TypeScript)
Source: https://context7.com/lijianye521/my-app/llms.txt
Provides a URL routing system that handles internal browser navigation and integration with the Wind Terminal protocol. It defines URL types and includes a handler function to route based on these types. Usage examples show how to integrate this into a platform card component. Dependencies include browser APIs like `window.open` and `window.location.href`.
```typescript
// URL Type definitions
export type UrlType = 'internal' | 'terminal' | 'internal_terminal';
// URL routing handler
function handleServiceAccess(
url: string,
urlType: UrlType,
serviceName: string
) {
// Log access operation
logAccessOperation(serviceName);
// Route based on URL type
if (urlType === 'internal') {
// Open in new browser tab
window.open(url, '_blank');
} else if (urlType === 'terminal') {
// Open via Wind Terminal protocol
const windUrl = `windlocal://open?${encodeURIComponent(url)}`;
window.location.href = windUrl;
} else if (urlType === 'internal_terminal') {
// Deprecated: Previously used for same-domain routing
console.warn('internal_terminal is deprecated');
window.open(window.location.origin + url, '_blank');
}
}
// Usage in platform card component
function PlatformCard({ platform }: { platform: PlatformItem }) {
const handleClick = () => {
handleServiceAccess(
platform.url,
platform.urlType || 'internal',
platform.name
);
};
return (
{platform.name}
{platform.description}
{platform.urlType === 'internal' ? '浏览器打开' : 'Wind终端打开'}
);
}
```
--------------------------------
### Insert User Operation Log Entry (SQL)
Source: https://github.com/lijianye521/my-app/blob/main/README.md
SQL statement to insert a new record into the 'user_operation_logs' table. This example demonstrates logging an 'update' operation for a specific service, including old and new values, and the IP address.
```sql
INSERT INTO user_operation_logs (user_id, operation_type, service_code, operation_detail, ip_address)
VALUES (1, 'update', 'ainews', '{"field": "service_url", "old_value": "/old-path", "new_value": "/new-path"}', '192.168.1.100');
```
--------------------------------
### Query Operation Logs API
Source: https://github.com/lijianye521/my-app/blob/main/API-Documentation.md
Retrieves operation logs for the system. Requires user login. Supports filtering by user ID, operation type, service code, and date range. Includes pagination parameters like limit and offset. Returns a success flag, log data, and total count. Requires GET request to /operation-logs.
```JSON
{
"success": true,
"data": {
"logs": [...],
"total": 100
}
}
```
--------------------------------
### Initialize Database and Run Migrations (Bash & SQL)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Initializes the database with a schema script and then applies pending database migrations. It first runs an initialization SQL script and then uses Sequelize CLI or a custom Node.js script to check migration status and apply them.
```bash
# 首次部署:运行初始化脚本
mysql -u root2 -p123456 stock_lab < database/init.sql
# 检查迁移状态
npx sequelize-cli db:migrate:status
# 运行所有待执行的迁移
npx sequelize-cli db:migrate
# 或者使用项目自带的迁移工具
node database/migrate.js status
node database/migrate.js up
```
--------------------------------
### Initialize Database with SQL Script (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/README.md
Command to initialize the MySQL database by executing an SQL script. This sets up the necessary tables and initial data. Replace 'username' and 'database_name' with your actual credentials and database name.
```bash
mysql -u username -p database_name < database/init.sql
```
--------------------------------
### Update User Role to Admin API
Source: https://github.com/lijianye521/my-app/blob/main/API-Documentation.md
A temporary GET endpoint to update the current logged-in user's role to administrator. Returns a success status, a message confirming the role update, and the updated session information. Requires GET request to /auth/update-role.
```JSON
{
"success": true,
"message": "用户 admin (ID: 1) 已更新为管理员权限",
"session": {}
}
```
--------------------------------
### Clone Project Repository (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/README.md
Command to clone the project repository from a given URL. This is the first step in setting up the project locally.
```bash
git clone http://10.106.18.36:8082/stock/web/stock.product.lab
cd stock.product.lab
```
--------------------------------
### Configure MySQL Database (SQL)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Sets up a new MySQL/MariaDB database named 'stock_lab' with specific character set and collation. It also creates a dedicated user 'root2' with the password '123456' and grants all privileges on the newly created database to this user.
```sql
CREATE DATABASE stock_lab CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'root2'@'localhost' IDENTIFIED BY '123456';
GRANT ALL PRIVILEGES ON stock_lab.* TO 'root2'@'localhost';
FLUSH PRIVILEGES;
```
--------------------------------
### Get All Users (TypeScript)
Source: https://context7.com/lijianye521/my-app/llms.txt
Retrieves a list of all users via a GET request to '/api/users'. This endpoint is restricted to administrators only. The response includes user details such as ID, username, role, and timestamps. Client-side implementation uses 'next-auth/react' for session management and includes a permission check for the admin role.
```typescript
// GET /api/users
// Requires: Admin role
// Response
{
"success": true,
"data": [
{
"id": 1,
"username": "admin",
"password": "$2a$10$...".
"nickname": "系统管理员",
"email": "admin@company.com",
"role": "admin",
"is_active": 1,
"created_at": "2025-01-01T00:00:00.000Z",
"updated_at": "2025-01-15T10:30:00.000Z"
},
{
"id": 2,
"username": "user1",
"password": "$2a$10$...".
"nickname": "普通用户",
"email": "user1@company.com",
"role": "user",
"is_active": 1,
"created_at": "2025-01-02T00:00:00.000Z",
"updated_at": "2025-01-10T14:20:00.000Z"
}
]
}
// Client usage with permission check
import { useSession } from "next-auth/react";
function UserManagement() {
const { data: session } = useSession();
const [users, setUsers] = useState([]);
useEffect(() => {
if (session?.user?.role === 'admin') {
fetchUsers();
}
}, [session]);
async function fetchUsers() {
const response = await fetch('/api/users');
if (response.ok) {
const result = await response.json();
setUsers(result.data);
} else if (response.status === 403) {
console.error("没有管理员权限");
}
}
return (
{session?.user?.role === 'admin' ? (
) : (
需要管理员权限
)}
);
}
```
--------------------------------
### POST /api/platforms
Source: https://context7.com/lijianye521/my-app/llms.txt
Creates a new platform/service or updates an existing one. Includes audit logging.
```APIDOC
## POST /api/platforms
### Description
Adds new platform/service or updates existing configuration with audit logging.
### Method
POST
### Endpoint
/api/platforms
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **id** (string) - Required - Unique identifier for the platform or service.
- **name** (string) - Required - Display name of the platform or service.
- **description** (string) - Optional - A detailed description.
- **iconName** (string) - Optional - Name of the icon to be used.
- **color** (string) - Optional - Color associated with the platform/service.
- **url** (string) - Required - The URL for the platform or service.
- **type** (string) - Required - Type of the entry (e.g., 'platform', 'service').
- **urlType** (string) - Required - Type of URL ('internal' or 'terminal').
- **otherInformation** (any) - Optional - Additional miscellaneous information.
- **isNew** (boolean) - Required - Flag indicating if it's a new creation (true) or an update (false).
### Request Example
**Create new platform:**
```json
{
"id": "new-platform",
"name": "新平台",
"description": "这是一个新平台",
"iconName": "Settings",
"color": "bg-green-500",
"url": "http://example.com",
"type": "platform",
"urlType": "internal",
"otherInformation": "额外信息",
"isNew": true
}
```
**Update existing platform:**
```json
{
"id": "ainews-admin",
"name": "AINEWS运营管理(更新)",
"description": "更新后的描述",
"iconName": "Newspaper",
"color": "bg-blue-600",
"url": "http://10.106.19.29:8080/admin/v2",
"type": "platform",
"urlType": "terminal",
"otherInformation": null,
"isNew": false
}
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the operation was successful.
- **message** (string) - Optional error message if success is false.
#### Response Example
```json
{
"success": true
}
```
```
--------------------------------
### Troubleshoot Database and Migration Issues (Bash & SQL)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Offers steps for troubleshooting database connection and migration failures. It includes checking the database service status, verifying connection details in the configuration, examining the database table structure, and safely resetting migrations if necessary.
```bash
# 检查数据库表结构
mysql -u root2 -p123456 stock_lab -e "SHOW TABLES;"
# 重置迁移(谨慎使用)
node database/migrate.js reset
```
--------------------------------
### Create Platform Services Table SQL
Source: https://context7.com/lijianye521/my-app/llms.txt
Defines the 'platform_services' table for managing information about available platform services. Includes fields for service code, name, description, type, icon, color, URL, visibility, and sorting. Features unique constraints and indexes for efficient querying.
```sql
CREATE TABLE IF NOT EXISTS `platform_services` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`service_code` varchar(50) NOT NULL COMMENT '服务代码,唯一标识',
`service_name` varchar(100) NOT NULL COMMENT '服务名称',
`service_description` text COMMENT '服务描述信息',
`service_type` enum('platform','service','agent') NOT NULL DEFAULT 'platform',
`icon_name` varchar(50) NOT NULL DEFAULT 'Settings' COMMENT '图标名称(lucide-react)',
`color_class` varchar(50) NOT NULL DEFAULT 'bg-blue-500' COMMENT '颜色CSS类名',
`service_url` varchar(500) NOT NULL COMMENT '服务访问地址',
`url_type` enum('internal','terminal','internal_terminal') DEFAULT 'internal',
`sort_order` int(11) NOT NULL DEFAULT 0 COMMENT '排序权重',
`is_visible` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否可见',
`other_information` text COMMENT '其他信息',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_service_code` (`service_code`),
KEY `idx_service_type` (`service_type`),
KEY `idx_sort_order` (`sort_order`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```
--------------------------------
### Add User API (Admin)
Source: https://github.com/lijianye521/my-app/blob/main/API-Documentation.md
Adds a new user to the system. Requires administrator privileges. Accepts username, password, and optional nickname, email, and role. Returns a success message and the new user's ID. Requires POST request to /users/add.
```JSON
{
"username": "string",
"password": "string",
"nickname": "string",
"email": "string",
"role": "user|admin"
}
```
--------------------------------
### User Management - Add User
Source: https://github.com/lijianye521/my-app/blob/main/API-Documentation.md
Adds a new user to the system. Requires administrator privileges.
```APIDOC
## POST /users/add
### Description
Adds a new user to the system. Requires administrator privileges.
### Method
POST
### Endpoint
/api/users/add
### Parameters
#### Query Parameters
- **Requires Administrator Privileges**
#### Request Body
- **username** (string) - Required - Username
- **password** (string) - Required - Password
- **nickname** (string) - Optional - Nickname
- **email** (string) - Optional - Email
- **role** (string) - Optional - Role ('user' or 'admin', defaults to 'user')
### Response
#### Success Response
- **success** (boolean) - Indicates if the operation was successful.
- **message** (string) - Confirmation message.
- **userId** (integer) - The ID of the newly added user.
### Request Example
```json
{
"username": "string",
"password": "string",
"nickname": "string",
"email": "string",
"role": "user|admin"
}
```
### Response Example
```json
{
"success": true,
"message": "用户添加成功",
"userId": 123
}
```
```
--------------------------------
### User Management - Get All Users
Source: https://context7.com/lijianye521/my-app/llms.txt
Retrieves a complete list of all users. This operation is restricted to users with administrator roles.
```APIDOC
## GET /api/users
### Description
Retrieves a complete list of all users. This operation is restricted to administrators only.
### Method
GET
### Endpoint
/api/users
### Parameters
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the operation was successful.
- **data** (array) - An array of user objects.
- **id** (integer) - The unique identifier for the user.
- **username** (string) - The user's login name.
- **password** (string) - The user's hashed password.
- **nickname** (string) - The user's display name.
- **email** (string) - The user's email address.
- **role** (string) - The user's role ('admin' or 'user').
- **is_active** (integer) - Indicates if the user account is active (1 for active, 0 for inactive).
- **created_at** (string) - The timestamp when the user was created.
- **updated_at** (string) - The timestamp when the user was last updated.
#### Response Example
```json
{
"success": true,
"data": [
{
"id": 1,
"username": "admin",
"password": "$2a$10$...",
"nickname": "系统管理员",
"email": "admin@company.com",
"role": "admin",
"is_active": 1,
"created_at": "2025-01-01T00:00:00.000Z",
"updated_at": "2025-01-15T10:30:00.000Z"
}
]
}
```
#### Error Response (403)
- **Error**: Forbidden. Requires admin role.
```
--------------------------------
### GET /api/operation-logs/stats
Source: https://context7.com/lijianye521/my-app/llms.txt
Retrieves operation statistics, allowing filtering by a specified number of past days. The response includes a list of operations grouped by type and date.
```APIDOC
## GET /api/operation-logs/stats
### Description
Retrieves operation statistics grouped by type and date. You can specify the number of past days to include in the statistics.
### Method
GET
### Endpoint
/api/operation-logs/stats
### Parameters
#### Query Parameters
- **days** (integer) - Optional - The number of past days to retrieve statistics for. Defaults to 7.
### Request Example
```json
{
"days": 7
}
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **stats** (array) - An array of objects, where each object contains:
- **operation_type** (string) - The type of operation (e.g., 'add', 'update', 'delete', 'access').
- **count** (integer) - The number of occurrences for the operation type on the given date.
- **date** (string) - The date in 'YYYY-MM-DD' format.
#### Response Example
```json
{
"success": true,
"stats": [
{ "operation_type": "add", "count": 15, "date": "2025-01-15" },
{ "operation_type": "update", "count": 42, "date": "2025-01-15" },
{ "operation_type": "delete", "count": 3, "date": "2025-01-15" },
{ "operation_type": "access", "count": 156, "date": "2025-01-15" },
{ "operation_type": "add", "count": 12, "date": "2025-01-14" },
{ "operation_type": "update", "count": 38, "date": "2025-01-14" }
]
}
```
```
--------------------------------
### User Authentication - Register
Source: https://github.com/lijianye521/my-app/blob/main/API-Documentation.md
Allows new users to register on the platform.
```APIDOC
## POST /auth/register
### Description
Allows new users to register on the platform.
### Method
POST
### Endpoint
/api/auth/register
### Parameters
#### Request Body
- **username** (string) - Required - Username
- **password** (string) - Required - Password
- **nickname** (string) - Optional - Nickname
- **email** (string) - Optional - Email
### Response
#### Success Response (201)
- **message** (string) - Success message
#### Error Responses
- **400**: Bad Request (Parameter error)
- **409**: Conflict (Username already exists)
- **500**: Internal Server Error
### Request Example
```json
{
"username": "string",
"password": "string",
"nickname": "string",
"email": "string"
}
```
### Response Example
```json
{
"message": "注册成功"
}
```
```
--------------------------------
### User Management - Add User
Source: https://context7.com/lijianye521/my-app/llms.txt
Creates a new user account. This is an administrator-only operation and includes automatic logging.
```APIDOC
## POST /api/users/add
### Description
Creates a new user account. This is an administrator-only operation with automatic logging.
### Method
POST
### Endpoint
/api/users/add
### Parameters
#### Request Body
- **username** (string) - Required - The desired username for the new user.
- **password** (string) - Required - The password for the new user.
- **nickname** (string) - Optional - The display name for the new user.
- **email** (string) - Optional - The email address for the new user.
- **role** (string) - Optional - The role for the new user. Defaults to 'user'. Can be 'admin' or 'user'.
### Request Example
```json
{
"username": "newemployee",
"password": "TempPass123!",
"nickname": "张三",
"email": "zhangsan@company.com",
"role": "user"
}
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the operation was successful.
- **message** (string) - A confirmation message.
- **userId** (integer) - The ID of the newly created user.
#### Response Example
```json
{
"success": true,
"message": "用户添加成功",
"userId": 15
}
```
#### Error Response (e.g., Username exists)
- **success** (boolean) - Indicates if the operation failed.
- **message** (string) - An error message explaining the failure.
#### Response Example
```json
{
"success": false,
"message": "用户名已存在"
}
```
```
--------------------------------
### Create or Update Platform/Service (TypeScript)
Source: https://context7.com/lijianye521/my-app/llms.txt
Adds new platform/service configurations or updates existing ones. Supports creating new entries or modifying existing ones using POST request. Includes client-side implementation with operation logging and error handling.
```typescript
// POST /api/platforms
// Request - Create new platform
{
"id": "new-platform",
"name": "新平台",
"description": "这是一个新平台",
"iconName": "Settings",
"color": "bg-green-500",
"url": "http://example.com",
"type": "platform",
"urlType": "internal",
"otherInformation": "额外信息",
"isNew": true
}
// Request - Update existing platform
{
"id": "ainews-admin",
"name": "AINEWS运营管理(更新)",
"description": "更新后的描述",
"iconName": "Newspaper",
"color": "bg-blue-600",
"url": "http://10.106.19.29:8080/admin/v2",
"type": "platform",
"urlType": "terminal",
"otherInformation": null,
"isNew": false
}
// Response
{
"success": true
}
// Client implementation with operation logging
async function savePlatformService(data: any) {
try {
const response = await fetch('/api/platforms', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await response.json();
if (result.success) {
console.log(data.isNew ? "平台创建成功" : "平台更新成功");
// Operation is automatically logged on server side
} else {
throw new Error(result.message || "操作失败");
}
return result;
} catch (error) {
console.error("保存失败:", error);
throw error;
}
}
```
--------------------------------
### Build Production Version (Bash)
Source: https://github.com/lijianye521/my-app/blob/main/部署.md
Builds the Next.js application for production deployment. This command compiles the application, optimizes assets, and prepares it for serving. It also includes a step to verify the build output by listing the contents of the '.next' directory.
```bash
# 构建项目
npm run build
# 检查构建是否成功
ls -la .next/
```
--------------------------------
### Database Status Check API
Source: https://github.com/lijianye521/my-app/blob/main/API-Documentation.md
Checks the connectivity status of the database. Returns a timestamp, the current status (e.g., 'online'), and detailed information about the connection's success and status. Requires GET request to /db-status.
```JSON
{
"timestamp": "2024-01-01T12:00:00.000Z",
"status": "online",
"details": {
"success": true,
"connection": "正常"
}
}
```
--------------------------------
### Create User Operation Logs Table SQL
Source: https://context7.com/lijianye521/my-app/llms.txt
Defines the 'user_operation_logs' table for recording user activities within the platform. Tracks user ID, operation type, service code, details, IP address, and user agent. Includes indexes for performance.
```sql
CREATE TABLE IF NOT EXISTS `user_operation_logs` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
`operation_type` varchar(50) NOT NULL COMMENT '操作类型',
`service_code` varchar(50) DEFAULT NULL COMMENT '操作的服务代码',
`operation_detail` text COMMENT '操作详情JSON',
`ip_address` varchar(45) DEFAULT NULL COMMENT '操作IP地址',
`user_agent` varchar(500) DEFAULT NULL COMMENT '用户代理信息',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_operation_type` (`operation_type`),
KEY `idx_service_code` (`service_code`),
KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```
--------------------------------
### User Registration API Endpoint - TypeScript
Source: https://context7.com/lijianye521/my-app/llms.txt
Provides a public API endpoint (/api/auth/register) for creating new users. It accepts user details, hashes the password using bcryptjs, and stores the new user in the MySQL database. Includes checks for existing usernames to prevent duplicates.
```typescript
import { hash } from "bcryptjs";
import { getDb } from "@/lib/db";
export async function POST(req: Request) {
const { username, password, nickname, email } = await req.json();
if (!username || !password) {
return NextResponse.json(
{ message: "用户名和密码是必填项" },
{ status: 400 }
);
}
const db = await getDb();
const [existingUsers] = await db.query(
"SELECT * FROM users WHERE username = ?",
[username]
);
if ((existingUsers as any[]).length > 0) {
return NextResponse.json(
{ message: "用户名已存在" },
{ status: 409 }
);
}
const hashedPassword = await hash(password, 10);
await db.query(
"INSERT INTO users (username, password, nickname, email) VALUES (?, ?, ?, ?)",
[username, hashedPassword, nickname || null, email || null]
);
return NextResponse.json({ message: "注册成功" }, { status: 201 });
}
```