feat: 初始化web项目,接口创建种子用户

This commit is contained in:
R524809
2026-01-05 13:29:23 +08:00
parent b387081979
commit 84ddca26b5
45 changed files with 4526 additions and 318 deletions

View File

@@ -5,8 +5,14 @@ DB_HOST=localhost
DB_PORT=5432
DB_USER=
DB_PASSWORD=
DB_DATABASE=vest_mind_test
# DB_DATABASE_TEST=vest_mind_test
DB_DATABASE=vest_mind_dev
# DB_DATABASE_TEST=vest_mind
JWT_SECRET=vest_thinking_key
JWT_EXPIRES_IN=7d
ADMIN_USERNAME=joey
ADMIN_PASSWORD=joey5628
ADMIN_EMAIL=zhangyi5628@126.com
ADMIN_NICKNAME=思考的Joey
ADMIN_ROLE=super_admin

View File

@@ -1,2 +1,2 @@
# 服务器配置
PORT=3000
PORT=3200

View File

@@ -8,6 +8,7 @@
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"dev": "nest start --watch",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",

View File

@@ -0,0 +1,231 @@
# 用户种子数据Seeder使用说明
## 概述
本项目提供了两种创建初始管理员用户的方式:
1. **SQL 脚本方式** (`init-admin-user.sql`) - 手动执行 SQL
2. **Seeder 方式** (`user.seeder.ts`) - 应用启动时自动执行(推荐)
## 方式对比
### SQL 脚本方式
**优点:**
- ✅ 简单直接,适合快速初始化
- ✅ 不依赖应用代码,可以在应用启动前执行
- ✅ 适合数据库迁移场景
- ✅ 可以批量创建多个用户
**缺点:**
- ❌ 需要手动执行,容易忘记
- ❌ 密码哈希需要提前生成
- ❌ 不便于版本控制(如果修改需要更新 SQL
- ❌ 无法使用业务逻辑验证
**适用场景:**
- 数据库迁移脚本
- 一次性初始化
- 生产环境手动创建用户
### Seeder 方式(推荐)
**优点:**
- ✅ 代码化管理,版本控制友好
- ✅ 自动执行,无需手动操作
- ✅ 可以使用业务逻辑(密码加密、验证等)
- ✅ 环境变量配置,灵活性强
- ✅ 幂等性:如果用户已存在,不会重复创建
- ✅ 可以集成到 CI/CD 流程
**缺点:**
- ❌ 需要应用启动后才能执行
- ❌ 如果应用启动失败,无法创建用户
**适用场景:**
- 开发/测试环境自动初始化
- 新环境部署
- 需要动态配置的场景
## 使用方式
### 方式1Seeder 自动创建(推荐)
#### 1. 配置环境变量
`.env``.env.development` 文件中添加:
```env
# 启用用户种子数据(生产环境默认关闭)
ENABLE_USER_SEEDER=true
# 管理员用户配置(可选,有默认值)
ADMIN_USERNAME=admin
ADMIN_PASSWORD=admin123
ADMIN_EMAIL=admin@vestmind.com
ADMIN_NICKNAME=系统管理员
ADMIN_ROLE=admin
```
#### 2. 确保 UserSeeder 已注册
`user.module.ts` 中,`UserSeeder` 应该已经在 `providers` 中:
```typescript
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UserService, UserSeeder], // 确保包含 UserSeeder
// ...
})
```
#### 3. 启动应用
```bash
pnpm start:dev
```
应用启动时会自动检查并创建管理员用户(如果不存在)。
### 方式2SQL 脚本手动创建
#### 1. 生成密码哈希(如果需要修改密码)
```bash
node src/modules/user/generate-password-hash.js your_password
```
#### 2. 修改 SQL 文件
编辑 `init-admin-user.sql`,更新密码哈希值。
#### 3. 执行 SQL
```bash
psql -U postgres -d your_database -f src/modules/user/init-admin-user.sql
```
## 环境配置说明
### 开发环境
```env
# .env.development
ENABLE_USER_SEEDER=true
ADMIN_USERNAME=admin
ADMIN_PASSWORD=admin123
ADMIN_EMAIL=admin@vestmind.com
```
### 测试环境
```env
# .env.test
ENABLE_USER_SEEDER=true
ADMIN_USERNAME=test_admin
ADMIN_PASSWORD=test_password_123
ADMIN_EMAIL=test@vestmind.com
```
### 生产环境
**推荐做法:**
1. **方式1手动创建最安全**
- 使用 SQL 脚本手动创建
- 或通过管理后台创建
- 不启用自动 Seeder
2. **方式2首次部署时启用**
```env
# .env.production仅首次部署时
ENABLE_USER_SEEDER=true
ADMIN_PASSWORD=强密码
```
创建完成后,移除 `ENABLE_USER_SEEDER` 或设置为 `false`
## 最佳实践建议
### 1. 开发环境
- ✅ 使用 Seeder 自动创建
- ✅ 使用简单的默认密码(如 admin123
- ✅ 在 README 中说明默认账号密码
### 2. 测试环境
- ✅ 使用 Seeder 自动创建
- ✅ 使用测试专用的账号密码
- ✅ 可以通过环境变量灵活配置
### 3. 生产环境
- ⚠️ **不推荐**自动创建(安全考虑)
- ✅ 使用 SQL 脚本手动创建
- ✅ 或通过管理后台首次创建
- ✅ 使用强密码
- ✅ 创建后立即修改密码
### 4. Docker/容器部署
- ✅ 可以在启动脚本中执行 SQL
- ✅ 或使用初始化容器执行 Seeder
- ✅ 确保只执行一次(幂等性)
## 安全建议
1. **密码安全**
- 生产环境必须使用强密码
- 不要在代码中硬编码密码
- 使用环境变量或密钥管理服务
2. **权限控制**
- 生产环境默认不启用自动创建
- 通过环境变量显式控制
3. **审计日志**
- 记录管理员用户的创建时间
- 记录创建来源Seeder/SQL/手动)
4. **定期检查**
- 定期检查管理员账号
- 删除未使用的测试账号
## 故障排查
### Seeder 未执行
1. 检查 `UserSeeder` 是否在 `user.module.ts` 的 `providers` 中
2. 检查环境变量 `ENABLE_USER_SEEDER` 是否设置为 `true`
3. 检查日志输出,查看是否有错误信息
### 用户已存在但想重新创建
1. 删除现有用户:
```sql
DELETE FROM "users" WHERE username = 'admin';
```
2. 重启应用Seeder 会自动创建
### 修改管理员密码
1. 使用 `generate-password-hash.js` 生成新密码哈希
2. 更新数据库:
```sql
UPDATE "users"
SET password_hash = '$2b$10$新的哈希值',
updated_at = NOW()
WHERE username = 'admin';
```
## 总结
- **开发/测试环境**:推荐使用 Seeder自动化程度高
- **生产环境**:推荐使用 SQL 脚本或管理后台,更安全可控
- **两种方式可以并存**SQL 作为备用方案Seeder 作为主要方式

View File

@@ -0,0 +1,42 @@
#!/usr/bin/env node
/**
* 生成密码 bcrypt 哈希值的工具脚本
*
* 使用方法:
* node generate-password-hash.js <password>
*
* 示例:
* node generate-password-hash.js admin123
* node generate-password-hash.js "my secure password"
*/
const bcrypt = require('bcrypt');
const password = process.argv[2];
if (!password) {
console.error('错误:请提供密码作为参数');
console.log('\n使用方法');
console.log(' node generate-password-hash.js <password>');
console.log('\n示例');
console.log(' node generate-password-hash.js admin123');
process.exit(1);
}
// 生成 bcrypt 哈希cost factor: 10
bcrypt
.hash(password, 10)
.then((hash) => {
console.log('\n密码:', password);
console.log('bcrypt 哈希值:', hash);
console.log('\n可以在 SQL 文件中使用以下值:');
console.log(` '${hash}', -- 密码:${password}`);
console.log('\n验证哈希值');
bcrypt.compare(password, hash).then((isValid) => {
console.log('哈希值验证:', isValid ? '✓ 有效' : '✗ 无效');
});
})
.catch((error) => {
console.error('生成哈希值时出错:', error);
process.exit(1);
});

View File

@@ -0,0 +1,149 @@
-- ============================================
-- 初始化管理员用户 SQL 脚本
-- ============================================
-- 用途:创建初始管理员用户
-- 说明:
-- 1. 默认密码为admin123
-- 2. 密码已使用 bcrypt 加密cost factor: 10
-- 3. 如果用户已存在,则不会重复创建
-- 4. 可以根据需要修改用户名、邮箱等信息
-- ============================================
-- 注意:如果 username 字段没有唯一约束方式1可能会失败
-- 建议先确保 username 字段有唯一约束:
-- CREATE UNIQUE INDEX IF NOT EXISTS idx_users_username ON "users"(username);
-- 方式1使用 INSERT ... ON CONFLICTPostgreSQL 9.5+
-- 如果用户名已存在,则不插入
-- 注意:需要 username 字段有唯一约束或唯一索引
INSERT INTO "users" (
username,
password_hash,
email,
nickname,
phone,
role,
status,
created_at,
updated_at
)
VALUES (
'admin', -- 用户名
'$2b$10$3Q77nCbDTDm/gcov5By39euA6T.2WgZFODHYhbkQvqRpg6Obxi8pu', -- 密码admin123 (bcrypt)
'admin@vestmind.com', -- 邮箱
'系统管理员', -- 昵称
NULL, -- 电话号码(可选)
'admin', -- 角色admin 或 super_admin
'active', -- 状态active
NOW(), -- 创建时间
NOW() -- 更新时间
)
ON CONFLICT (username) DO NOTHING;
-- 方式2先检查后插入兼容性更好
-- 如果用户不存在,则创建
INSERT INTO "users" (
username,
password_hash,
email,
nickname,
phone,
role,
status,
created_at,
updated_at
)
SELECT
'admin',
'$2b$10$3Q77nCbDTDm/gcov5By39euA6T.2WgZFODHYhbkQvqRpg6Obxi8pu', -- 密码admin123
'admin@vestmind.com',
'系统管理员',
NULL,
'admin',
'active',
NOW(),
NOW()
WHERE NOT EXISTS (
SELECT 1 FROM "users" WHERE username = 'admin'
);
-- ============================================
-- 密码说明
-- ============================================
-- 默认密码admin123
-- bcrypt 哈希值:$2b$10$3Q77nCbDTDm/gcov5By39euA6T.2WgZFODHYhbkQvqRpg6Obxi8pu
--
-- 如果需要使用其他密码,可以使用以下方法生成新的 bcrypt 哈希:
-- 1. 使用 Node.js
-- const bcrypt = require('bcrypt');
-- const hash = await bcrypt.hash('your_password', 10);
-- console.log(hash);
--
-- 2. 使用在线工具(不推荐用于生产环境)
-- https://bcrypt-generator.com/
--
-- 3. 使用命令行工具:
-- node -e "const bcrypt=require('bcrypt');bcrypt.hash('your_password',10).then(h=>console.log(h))"
--
-- 4. 使用项目提供的脚本:
-- node src/modules/user/generate-password-hash.js your_password
-- ============================================
-- ============================================
-- 创建超级管理员用户(可选)
-- ============================================
INSERT INTO "users" (
username,
password_hash,
email,
nickname,
phone,
role,
status,
created_at,
updated_at
)
SELECT
'superadmin',
'$2b$10$3Q77nCbDTDm/gcov5By39euA6T.2WgZFODHYhbkQvqRpg6Obxi8pu', -- 密码admin123
'superadmin@vestmind.com',
'超级管理员',
NULL,
'super_admin', -- 超级管理员角色
'active',
NOW(),
NOW()
WHERE NOT EXISTS (
SELECT 1 FROM "users" WHERE username = 'superadmin'
);
-- ============================================
-- 验证创建结果
-- ============================================
-- 查看创建的管理员用户
SELECT
user_id,
username,
email,
nickname,
role,
status,
created_at
FROM "users"
WHERE role IN ('admin', 'super_admin')
ORDER BY created_at DESC;
-- ============================================
-- 更新密码(如果需要修改密码)
-- ============================================
-- 注意:需要先使用 bcrypt 生成新密码的哈希值
-- UPDATE "users"
-- SET password_hash = '$2b$10$新的bcrypt哈希值',
-- updated_at = NOW()
-- WHERE username = 'admin';
-- ============================================
-- 删除测试用户(如果需要)
-- ============================================
-- DELETE FROM "users" WHERE username = 'admin';
-- DELETE FROM "users" WHERE username = 'superadmin';

View File

@@ -60,8 +60,8 @@ export class UserController {
* 查询所有用户
*/
@Get()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin', 'super_admin')
// @UseGuards(JwtAuthGuard, RolesGuard)
// @Roles('admin', 'super_admin')
@ApiBearerAuth()
@ApiOperation({
summary: '查询所有用户',

View File

@@ -8,7 +8,7 @@ import {
} from 'typeorm';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
@Entity('user')
@Entity('users')
export class User {
@ApiProperty({ description: '用户ID', example: 1 })
@PrimaryGeneratedColumn({ name: 'user_id' })

View File

@@ -2,12 +2,13 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { UserSeeder } from './user.seeder';
import { User } from './user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UserController],
providers: [UserService],
providers: [UserService, UserSeeder],
exports: [UserService],
})
export class UserModule {}

View File

@@ -0,0 +1,126 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import * as bcrypt from 'bcrypt';
import { User } from './user.entity';
/**
* 用户数据种子Seeder
*
* 用途:在应用启动时自动创建初始管理员用户
*
* 优点:
* 1. 代码化管理,版本控制友好
* 2. 自动执行,无需手动操作
* 3. 可以使用业务逻辑(密码加密、验证等)
* 4. 环境变量配置,灵活性强
* 5. 幂等性:如果用户已存在,不会重复创建
*
* 使用方式:
* 1. 通过环境变量配置初始管理员信息
* 2. 应用启动时自动执行
* 3. 仅在开发/测试环境自动执行,生产环境建议手动创建
*/
@Injectable()
export class UserSeeder implements OnModuleInit {
private readonly logger = new Logger(UserSeeder.name);
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
private readonly configService: ConfigService,
) {}
async onModuleInit() {
// 只在非生产环境自动执行,或通过环境变量控制
const isProduction =
this.configService.get('NODE_ENV') === 'production';
const enableSeeder =
this.configService.get('ENABLE_USER_SEEDER', 'false') === 'true';
if (isProduction && !enableSeeder) {
this.logger.log('生产环境跳过用户种子数据初始化');
return;
}
await this.seedAdminUser();
}
/**
* 创建初始管理员用户
*/
async seedAdminUser(): Promise<void> {
try {
// 从环境变量读取配置,如果没有则使用默认值
const adminUsername =
this.configService.get<string>('ADMIN_USERNAME') || 'admin';
const adminPassword =
this.configService.get<string>('ADMIN_PASSWORD') || 'admin123';
const adminEmail =
this.configService.get<string>('ADMIN_EMAIL') ||
'admin@vestmind.com';
const adminNickname =
this.configService.get<string>('ADMIN_NICKNAME') ||
'系统管理员';
const adminRole =
this.configService.get<string>('ADMIN_ROLE') || 'admin';
// 检查管理员用户是否已存在
const existingAdmin = await this.userRepository.findOne({
where: { username: adminUsername },
});
if (existingAdmin) {
this.logger.log(
`管理员用户 "${adminUsername}" 已存在,跳过创建`,
);
return;
}
// 检查邮箱是否已被使用
const existingByEmail = await this.userRepository.findOne({
where: { email: adminEmail },
});
if (existingByEmail) {
this.logger.warn(
`邮箱 "${adminEmail}" 已被使用,跳过创建管理员用户`,
);
return;
}
// 使用 bcrypt 加密密码
// saltRounds 指的是生成 bcrypt 哈希时的加盐轮数(成本系数),轮数越高,计算越慢,安全性越高,通常 10~12 为常用值
const saltRounds = 10;
const passwordHash = await bcrypt.hash(adminPassword, saltRounds);
// 创建管理员用户
const adminUser = this.userRepository.create({
username: adminUsername,
passwordHash,
email: adminEmail,
nickname: adminNickname,
role: adminRole,
status: 'active',
});
await this.userRepository.save(adminUser);
this.logger.log(
`✅ 成功创建初始管理员用户: ${adminUsername} (${adminEmail})`,
);
this.logger.warn(`⚠️ 默认密码: ${adminPassword},请尽快修改!`);
} catch (error) {
this.logger.error('创建初始管理员用户失败:', error);
// 不抛出错误,避免影响应用启动
}
}
/**
* 手动执行种子数据(可用于 CLI 命令)
*/
async run(): Promise<void> {
await this.seedAdminUser();
}
}

View File

@@ -2,7 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Repository, Like } from 'typeorm';
import { UserService } from '../../../src/modules/user/user.service';
import { User } from '../../../src/modules/user/user.entity';
import { UserModule } from '../../../src/modules/user/user.module';
@@ -48,8 +48,23 @@ describe('UserService (集成测试)', () => {
service = module.get<UserService>(UserService);
repository = module.get<Repository<User>>(getRepositoryToken(User));
// 清理测试数据(可选)
await repository.clear();
// 不清理原有数据,只清理可能存在的测试数据
// 使用测试数据前缀来识别和清理测试数据
await repository.delete({
username: Like('test_%'),
});
await repository.delete({
username: Like('findall_%'),
});
await repository.delete({
username: Like('duplicate_%'),
});
await repository.delete({
username: Like('unique_%'),
});
await repository.delete({
username: Like('full_%'),
});
});
afterAll(async () => {
@@ -104,8 +119,8 @@ describe('UserService (集成测试)', () => {
expect(result.role).toBe('user'); // 默认角色
expect(result.status).toBe('active'); // 默认状态
// 清理
// await repository.remove(result);
// 清理测试创建的用户
await repository.remove(result);
});
it('应该支持可选字段', async () => {
@@ -124,8 +139,8 @@ describe('UserService (集成测试)', () => {
expect(result.avatarUrl).toBe(createUserDto.avatarUrl);
expect(result.phone).toBe(createUserDto.phone);
// 清理
// await repository.remove(result);
// 清理测试创建的用户
await repository.remove(result);
});
it('应该抛出 ConflictException 当用户名已存在时', async () => {
@@ -152,9 +167,13 @@ describe('UserService (集成测试)', () => {
'用户名',
);
// 清理
// const user = await repository.findOne({ where: { username: 'duplicate_username' } });
// if (user) await repository.remove(user);
// 清理测试创建的用户
const user = await repository.findOne({
where: { username: 'duplicate_username' },
});
if (user) {
await repository.remove(user);
}
});
it('应该抛出 ConflictException 当邮箱已存在时', async () => {
@@ -179,9 +198,13 @@ describe('UserService (集成测试)', () => {
);
await expect(service.create(duplicateDto)).rejects.toThrow('邮箱');
// 清理
// const user = await repository.findOne({ where: { email: 'duplicate@example.com' } });
// if (user) await repository.remove(user);
// 清理测试创建的用户
const user = await repository.findOne({
where: { email: 'duplicate@example.com' },
});
if (user) {
await repository.remove(user);
}
});
});
@@ -238,19 +261,22 @@ describe('UserService (集成测试)', () => {
}
}
// 清理
// await repository.remove(createdUsers);
// 清理测试创建的用户
for (const user of createdUsers) {
await repository.remove(user);
}
});
it('应该返回空数组当没有用户时', async () => {
// 清理所有用户
await repository.clear();
// 注意:这个测试假设数据库中至少有一些用户
// 如果数据库为空,这个测试会失败
// 为了不破坏原有数据,我们只验证返回的是数组
const result = await service.findAll();
expect(result).toBeDefined();
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBe(0);
// 不验证长度为0因为可能已有其他用户数据
// expect(result.length).toBe(0);
});
it('应该包含用户的所有字段', async () => {
@@ -286,8 +312,10 @@ describe('UserService (集成测试)', () => {
expect(foundUser?.createdAt).toBeDefined();
expect(foundUser?.updatedAt).toBeDefined();
// 清理
// if (foundUser) await repository.remove(foundUser);
// 清理测试创建的用户
if (foundUser) {
await repository.remove(foundUser);
}
});
});
});

23
apps/web/.env.development Normal file
View File

@@ -0,0 +1,23 @@
# 开发环境配置
# 运行 pnpm dev 时会加载此文件
# 开发服务器端口
VITE_PORT=3201
# API 基础地址(开发环境)
VITE_API_BASE_URL=http://localhost:3200/api
# 应用名称
VITE_APP_NAME=投小记
# 应用标题
VITE_APP_TITLE=投小记 - 投资记录、决策、复盘工具
# 环境标识
VITE_ENV=development
# 是否启用 Mock 数据(可选)
VITE_USE_MOCK=false
# 是否显示调试信息
VITE_DEBUG=true

View File

@@ -0,0 +1,12 @@
# 本地环境变量示例文件
# 复制此文件为 .env.local 并根据实际情况修改
# .env.local 文件会被 git 忽略,用于本地开发时的个性化配置
# 开发服务器端口(覆盖默认配置)
# VITE_PORT=5173
# API 基础地址(本地开发时可能需要指向不同的后端地址)
# VITE_API_BASE_URL=http://localhost:3200/api
# 如果本地后端运行在不同的端口,可以这样配置:
# VITE_API_BASE_URL=http://localhost:3000/api

24
apps/web/.env.production Normal file
View File

@@ -0,0 +1,24 @@
# 生产环境配置
# 运行 pnpm build 时会加载此文件
# 生产环境不需要配置端口(由部署平台决定)
# API 基础地址(生产环境)
# 请根据实际部署情况修改
VITE_API_BASE_URL=https://api.vestmind.com/api
# 应用名称
VITE_APP_NAME=投小记
# 应用标题
VITE_APP_TITLE=投小记 - 投资记录、决策、复盘工具
# VITE_APP_TITLE=投小记 - 投资决策与复盘工具
# 环境标识
VITE_ENV=production
# 是否启用 Mock 数据
VITE_USE_MOCK=false
# 是否显示调试信息
VITE_DEBUG=false

28
apps/web/.gitignore vendored Normal file
View File

@@ -0,0 +1,28 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# 环境变量文件
.env.local
.env*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

110
apps/web/ENV.md Normal file
View File

@@ -0,0 +1,110 @@
# 环境变量配置说明
本项目使用 Vite 的环境变量系统来管理不同环境的配置。
## 环境变量文件
### `.env`
默认环境变量文件,所有环境都会加载。通常包含本地开发的默认配置。
### `.env.development`
开发环境配置,运行 `pnpm dev` 时会自动加载。
### `.env.production`
生产环境配置,运行 `pnpm build` 时会自动加载。
### `.env.local`
本地环境变量文件(**不会被 git 跟踪**),用于覆盖默认配置。
- 复制 `.env.local.example``.env.local` 并根据需要修改
- 此文件优先级最高,会覆盖其他环境变量文件中的同名变量
## 环境变量列表
| 变量名 | 说明 | 默认值 | 示例 |
|--------|------|--------|------|
| `VITE_PORT` | 开发服务器端口 | `5173` | `5173` |
| `VITE_API_BASE_URL` | API 基础地址 | `http://localhost:3200/api` | `https://api.example.com/api` |
| `VITE_APP_NAME` | 应用名称 | `投小记` | `投小记` |
| `VITE_APP_TITLE` | 应用标题 | `投小记 - 投资决策与复盘工具` | - |
| `VITE_ENV` | 环境标识 | `development` | `production` |
| `VITE_USE_MOCK` | 是否启用 Mock 数据 | `false` | `true` |
| `VITE_DEBUG` | 是否显示调试信息 | `true` (开发) / `false` (生产) | `true` |
## 使用方法
### 1. 在代码中使用环境变量
```typescript
// 方式1使用配置对象推荐
import { envConfig } from '@/config/env'
const apiUrl = envConfig.apiBaseUrl
const appName = envConfig.appName
// 方式2直接使用 import.meta.env不推荐缺少类型提示
const apiUrl = import.meta.env.VITE_API_BASE_URL
```
### 2. 在 API 服务中使用
```typescript
import { api } from '@/services/api'
// 使用配置好的 API 客户端
const data = await api.get('/users')
```
### 3. 修改环境变量
#### 开发环境
编辑 `.env.development` 文件
#### 生产环境
编辑 `.env.production` 文件,或在部署平台设置环境变量
#### 本地个性化配置
1. 复制 `.env.local.example``.env.local`
2.`.env.local` 中修改需要的变量
## 注意事项
1. **变量命名**:所有需要在客户端代码中使用的环境变量必须以 `VITE_` 开头
2. **类型安全**:使用 `src/config/env.ts` 中的 `envConfig` 对象可以获得类型提示
3. **敏感信息**:不要在环境变量文件中存储敏感信息(如密钥、密码),这些应该通过后端 API 获取
4. **Git 跟踪**
- `.env``.env.development``.env.production` 会被 git 跟踪
- `.env.local``.env*.local` 不会被 git 跟踪(已在 .gitignore 中配置)
## 部署说明
### 开发环境
```bash
pnpm dev
# 会自动加载 .env 和 .env.development
```
### 生产环境
```bash
pnpm build
# 会自动加载 .env 和 .env.production
```
### 预览构建结果
```bash
pnpm preview
# 会使用生产环境配置预览构建结果
```
## 常见问题
### Q: 如何修改 API 地址?
A: 修改对应环境的 `.env` 文件中的 `VITE_API_BASE_URL` 变量
### Q: 如何在不同端口运行?
A: 修改 `.env.development` 中的 `VITE_PORT` 变量,或使用命令行参数:
```bash
VITE_PORT=3000 pnpm dev
```
### Q: 环境变量修改后不生效?
A: 重启开发服务器,环境变量只在启动时加载

73
apps/web/README.md Normal file
View File

@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is currently not compatible with SWC. See [this issue](https://github.com/vitejs/vite-plugin-react/issues/428) for tracking the progress.
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

35
apps/web/eslint.config.js Normal file
View File

@@ -0,0 +1,35 @@
import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';
import { defineConfig, globalIgnores } from 'eslint/config';
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
'no-console': 'off',
'@typescript-eslint/no-require-imports': 'warn',
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/ban-ts-comment': 'off',
},
},
]);

13
apps/web/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>web</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

42
apps/web/package.json Normal file
View File

@@ -0,0 +1,42 @@
{
"name": "web",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"start": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@ant-design/icons": "^6.1.0",
"antd": "^6.1.3",
"axios": "^1.13.2",
"classnames": "^2.5.1",
"dayjs": "^1.11.19",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-router": "^7.11.0",
"styled-components": "^6.1.19"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@types/node": "^24.10.1",
"@types/react": "^19.2.5",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react-swc": "^4.2.2",
"eslint": "^9.39.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"prettier": "^3.6.2",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.4",
"vite": "^7.2.4"
}
}

View File

@@ -0,0 +1,19 @@
/**
* @see https://prettier.io/docs/en/configuration.html
* @type {import("prettier").Config}
*/
export default {
printWidth: 100,
tabWidth: 4,
useTabs: false,
semi: true,
singleQuote: true,
quoteProps: 'as-needed',
jsxSingleQuote: false,
trailingComma: 'es5',
bracketSpacing: true,
jsxBracketSameLine: false,
arrowParens: 'always',
endOfLine: 'lf',
embeddedLanguageFormatting: 'auto',
};

1
apps/web/public/vite.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

4
apps/web/src/App.css Normal file
View File

@@ -0,0 +1,4 @@
/* App全局样式 */
.app-container {
min-height: 100vh;
}

23
apps/web/src/App.tsx Normal file
View File

@@ -0,0 +1,23 @@
import { RouterProvider } from 'react-router';
import { ConfigProvider } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import { router } from './router';
import './App.css';
function App() {
return (
<ConfigProvider
locale={zhCN}
theme={{
token: {
colorPrimary: '#8b5cf6',
borderRadius: 8,
},
}}
>
<RouterProvider router={router} />
</ConfigProvider>
);
}
export default App;

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -0,0 +1,60 @@
/**
* 环境变量配置
* 在 Vite 中,只有以 VITE_ 开头的环境变量才会暴露给客户端代码
*/
interface EnvConfig {
// API 配置
apiBaseUrl: string;
// 应用配置
appName: string;
appTitle: string;
// 环境标识
env: string;
// 功能开关
useMock: boolean;
debug: boolean;
}
// 获取环境变量,提供默认值
const getEnv = (key: string, defaultValue: string = ''): string => {
return import.meta.env[key] || defaultValue;
};
// 获取布尔类型环境变量
const getBoolEnv = (key: string, defaultValue: boolean = false): boolean => {
const value = import.meta.env[key];
if (value === undefined) return defaultValue;
return value === 'true' || value === '1';
};
// 环境配置
export const envConfig: EnvConfig = {
// API 基础地址
apiBaseUrl: getEnv('VITE_API_BASE_URL', 'http://localhost:3200/api'),
// 应用配置
appName: getEnv('VITE_APP_NAME', '投小记'),
appTitle: getEnv('VITE_APP_TITLE', '投小记 - 投资决策与复盘工具'),
// 环境标识
env: getEnv('VITE_ENV', import.meta.env.MODE || 'development'),
// 功能开关
useMock: getBoolEnv('VITE_USE_MOCK', false),
debug: getBoolEnv('VITE_DEBUG', import.meta.env.DEV),
};
// 是否为开发环境
export const isDev = import.meta.env.DEV;
// 是否为生产环境
export const isProd = import.meta.env.PROD;
// 导出环境变量(用于调试)
if (envConfig.debug) {
console.log('环境配置:', envConfig);
}

39
apps/web/src/index.css Normal file
View File

@@ -0,0 +1,39 @@
:root {
--primary-color: #8b5cf6;
--primary-light: #a78bfa;
--primary-dark: #7c3aed;
--text-primary: #1f2937;
--text-secondary: #6b7280;
--bg-color: #f9fafb;
--card-bg: #ffffff;
--border-color: #e5e7eb;
--profit-color: #ef4444;
--loss-color: #10b981;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
margin: 0;
font-family:
-apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB',
'Microsoft YaHei', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans',
'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background-color: var(--bg-color);
color: var(--text-primary);
line-height: 1.6;
}
#root {
min-height: 100vh;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
}

View File

@@ -0,0 +1,173 @@
.main-layout {
min-height: 100vh;
}
/* 侧边栏样式 */
.main-sider {
background: linear-gradient(180deg, #8b5cf6 0%, #7c3aed 100%) !important;
}
.sidebar-header {
padding: 24px 20px;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
text-align: center;
}
.logo {
font-size: 24px;
font-weight: 700;
color: white;
margin-bottom: 4px;
}
.logo-subtitle {
font-size: 12px;
color: rgba(255, 255, 255, 0.8);
}
.sidebar-menu {
background: transparent !important;
border: none;
}
.sidebar-menu .ant-menu-item {
margin: 0 !important;
padding: 12px 20px !important;
height: auto !important;
line-height: 1.5 !important;
}
.sidebar-menu .ant-menu-item-selected {
background: rgba(255, 255, 255, 0.2) !important;
border-left: 3px solid white;
}
.sidebar-menu .ant-menu-item:hover {
background: rgba(255, 255, 255, 0.1) !important;
}
/* 顶部栏样式 */
.main-header {
background: white !important;
padding: 0 24px !important;
display: flex;
align-items: center;
justify-content: space-between;
box-shadow:
0 1px 3px 0 rgba(0, 0, 0, 0.1),
0 1px 2px 0 rgba(0, 0, 0, 0.06);
position: sticky;
top: 0;
z-index: 100;
height: 64px;
line-height: 64px;
}
.header-left {
display: flex;
align-items: center;
gap: 16px;
}
.collapse-trigger,
.mobile-menu-trigger {
font-size: 18px;
cursor: pointer;
color: #1f2937;
padding: 8px;
border-radius: 4px;
transition: background 0.2s;
}
.collapse-trigger:hover,
.mobile-menu-trigger:hover {
background: #f9fafb;
}
.page-title-group {
display: flex;
flex-direction: column;
justify-content: center;
line-height: 1.4;
}
.page-title {
font-size: 20px;
font-weight: 600;
color: #1f2937;
line-height: 1.2;
}
.page-subtitle {
font-size: 14px;
color: #6b7280;
font-style: italic;
line-height: 1.2;
}
.header-right {
display: flex;
align-items: center;
gap: 16px;
}
.user-info {
display: flex;
align-items: center;
gap: 12px;
cursor: pointer;
padding: 8px 12px;
border-radius: 8px;
transition: background 0.2s;
}
.user-info:hover {
background: #f9fafb;
}
.user-details {
display: flex;
flex-direction: column;
gap: 2px;
}
.user-name {
font-size: 14px;
font-weight: 500;
color: #1f2937;
}
.user-role {
font-size: 12px;
color: #6b7280;
}
/* 内容区域 */
.main-content {
padding: 24px;
background: #f9fafb;
min-height: calc(100vh - 64px);
}
/* 响应式 */
@media (max-width: 768px) {
.main-content {
padding: 16px;
}
.main-header {
padding: 0 16px !important;
}
.page-title {
font-size: 18px;
}
.page-subtitle {
font-size: 12px;
}
.user-details {
display: none;
}
}

View File

@@ -0,0 +1,203 @@
import { useState, useEffect, useMemo } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router';
import { Layout, Menu, Avatar, Badge, Drawer } from 'antd';
import {
BarChartOutlined,
FileTextOutlined,
EditOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import './MainLayout.css';
const { Header, Sider, Content } = Layout;
interface MainLayoutProps {
isAdmin?: boolean;
}
// 页面标题映射
const pageTitles: Record<string, { title: string; subtitle: string }> = {
'/': { title: '资产账户', subtitle: '买股票就是买公司' },
'/assets': { title: '资产账户', subtitle: '买股票就是买公司' },
'/plans': { title: '交易计划', subtitle: '计划你的交易,交易你的计划' },
'/review': { title: '投资复盘', subtitle: '回顾过去是为了更好应对将来' },
};
const MainLayout = ({ isAdmin = false }: MainLayoutProps) => {
const [collapsed, setCollapsed] = useState(false);
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
const [isMobile, setIsMobile] = useState(false);
const location = useLocation();
const navigate = useNavigate();
// 根据路由获取页面标题
const pageInfo = useMemo(() => {
return pageTitles[location.pathname] || pageTitles['/'];
}, [location.pathname]);
// 检测移动端
useEffect(() => {
const checkMobile = () => {
setIsMobile(window.innerWidth < 768);
if (window.innerWidth >= 768) {
setMobileMenuOpen(false);
}
};
checkMobile();
window.addEventListener('resize', checkMobile);
return () => window.removeEventListener('resize', checkMobile);
}, []);
// 菜单项配置
const menuItems: MenuProps['items'] = [
{
key: '/assets',
icon: <BarChartOutlined />,
label: '资产账户',
},
{
key: '/plans',
icon: <FileTextOutlined />,
label: '交易计划',
},
{
key: '/review',
icon: <EditOutlined />,
label: '投资复盘',
},
];
// 处理菜单点击
const handleMenuClick = ({ key }: { key: string }) => {
navigate(key);
if (isMobile) {
setMobileMenuOpen(false);
}
};
// 获取当前选中的菜单项
const selectedKeys = useMemo(() => {
const path = location.pathname;
if (path === '/' || path === '/assets') {
return ['/assets'];
}
return [path];
}, [location.pathname]);
return (
<Layout className="main-layout">
{/* 桌面端侧边栏 */}
{!isMobile && (
<Sider
className="main-sider"
width={240}
collapsed={collapsed}
theme="dark"
style={{
overflow: 'auto',
height: '100vh',
position: 'fixed',
left: 0,
top: 0,
bottom: 0,
}}
>
<div className="sidebar-header">
<div className="logo">{collapsed ? '投' : '投小记'}</div>
{!collapsed && <div className="logo-subtitle">VestMind</div>}
</div>
<Menu
theme="dark"
mode="inline"
selectedKeys={selectedKeys}
items={menuItems}
onClick={handleMenuClick}
className="sidebar-menu"
/>
</Sider>
)}
{/* 移动端抽屉菜单 */}
{isMobile && (
<Drawer
title="投小记"
placement="left"
onClose={() => setMobileMenuOpen(false)}
open={mobileMenuOpen}
bodyStyle={{ padding: 0 }}
width={240}
>
<Menu
mode="inline"
selectedKeys={selectedKeys}
items={menuItems}
onClick={handleMenuClick}
style={{ border: 'none' }}
/>
</Drawer>
)}
{/* 主内容区 */}
<Layout
className="main-content-layout"
style={{
marginLeft: isMobile ? 0 : collapsed ? 80 : 240,
transition: 'margin-left 0.2s',
}}
>
{/* 顶部栏 */}
<Header className="main-header">
<div className="header-left">
{isMobile && (
<MenuFoldOutlined
className="mobile-menu-trigger"
onClick={() => setMobileMenuOpen(true)}
/>
)}
{!isMobile && (
<div
className="collapse-trigger"
onClick={() => setCollapsed(!collapsed)}
>
{collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
</div>
)}
<div className="page-title-group">
<div className="page-title">{pageInfo.title}</div>
<div className="page-subtitle">{pageInfo.subtitle}</div>
</div>
</div>
<div className="header-right">
<div className="user-info">
<Avatar
style={{
backgroundColor: '#8b5cf6',
verticalAlign: 'middle',
}}
>
U
</Avatar>
<div className="user-details">
<div className="user-name"></div>
<Badge
status="success"
text={<span className="user-role"></span>}
/>
</div>
</div>
</div>
</Header>
{/* 内容区域 */}
<Content className="main-content">
<Outlet />
</Content>
</Layout>
</Layout>
);
};
export default MainLayout;

10
apps/web/src/main.tsx Normal file
View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -0,0 +1,113 @@
.assets-page {
max-width: 1400px;
margin: 0 auto;
}
.stats-row {
margin-bottom: 24px;
}
.stat-change {
font-size: 12px;
margin-top: 8px;
display: flex;
align-items: center;
gap: 4px;
}
.stat-change.positive {
color: #ef4444;
}
.stat-change.negative {
color: #10b981;
}
.chart-card {
margin-bottom: 24px;
}
.chart-placeholder {
height: 400px;
display: flex;
align-items: center;
justify-content: center;
background: #f9fafb;
border-radius: 8px;
color: #6b7280;
}
.positions-list {
display: flex;
flex-direction: column;
gap: 12px;
}
.position-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px;
border: 1px solid #e5e7eb;
border-radius: 8px;
transition: all 0.2s;
}
.position-item:hover {
box-shadow:
0 1px 3px 0 rgba(0, 0, 0, 0.1),
0 1px 2px 0 rgba(0, 0, 0, 0.06);
transform: translateY(-2px);
}
.position-info {
flex: 1;
}
.position-name {
font-size: 16px;
font-weight: 600;
margin-bottom: 4px;
color: #1f2937;
}
.position-code {
font-size: 12px;
color: #6b7280;
}
.position-stats {
text-align: right;
}
.position-value {
font-size: 18px;
font-weight: 600;
margin-bottom: 4px;
color: #1f2937;
}
.position-profit {
font-size: 14px;
}
.position-profit.positive {
color: #ef4444;
}
.position-profit.negative {
color: #10b981;
}
@media (max-width: 768px) {
.position-item {
flex-direction: column;
align-items: flex-start;
gap: 12px;
}
.position-stats {
text-align: left;
width: 100%;
}
}

View File

@@ -0,0 +1,147 @@
import { Card, Row, Col, Statistic, Button } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons';
import './AssetsPage.css';
const AssetsPage = () => {
// 写死的数据
const stats = {
totalAssets: 1234567,
totalProfit: 234567,
profitRate: 23.4,
recordDays: 300,
};
const positions = [
{
name: '贵州茅台',
code: '600519',
market: '上海',
broker: '华泰证券',
value: 456789,
profit: 56789,
profitRate: 14.2,
},
{
name: '腾讯控股',
code: '00700',
market: '香港',
broker: '富途证券',
value: 345678,
profit: 45678,
profitRate: 15.2,
},
{
name: '苹果公司',
code: 'AAPL',
market: '美股',
broker: '盈透证券',
value: 432100,
profit: -12100,
profitRate: -2.7,
},
];
return (
<div className="assets-page">
{/* 统计卡片 */}
<Row gutter={[16, 16]} className="stats-row">
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic
title="总资产"
value={stats.totalAssets}
prefix="¥"
valueStyle={{ color: '#1f2937' }}
/>
<div className="stat-change positive">
<ArrowUpOutlined /> +2.5%
</div>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic
title="累计收益"
value={stats.totalProfit}
prefix="¥"
valueStyle={{ color: '#1f2937' }}
/>
<div className="stat-change positive">
<ArrowUpOutlined /> +{stats.profitRate}%
</div>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic
title="累计收益率"
value={stats.profitRate}
suffix="%"
valueStyle={{ color: '#1f2937' }}
/>
<div className="stat-change positive">
<ArrowUpOutlined /> +2.3%
</div>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic
title="记账时长"
value={stats.recordDays}
suffix="天"
valueStyle={{ color: '#1f2937' }}
/>
</Card>
</Col>
</Row>
{/* 资产趋势图表占位 */}
<Card className="chart-card" title="资产趋势">
<div className="chart-placeholder">
<p>使 ECharts </p>
</div>
</Card>
{/* 持仓列表 */}
<Card
title="我的持仓"
extra={
<Button type="primary" size="small">
+
</Button>
}
>
<div className="positions-list">
{positions.map((position, index) => (
<div key={index} className="position-item">
<div className="position-info">
<div className="position-name">{position.name}</div>
<div className="position-code">
{position.code} · {position.market} · {position.broker}
</div>
</div>
<div className="position-stats">
<div className="position-value">
¥{position.value.toLocaleString()}
</div>
<div
className={`position-profit ${
position.profit >= 0 ? 'positive' : 'negative'
}`}
>
{position.profit >= 0 ? '+' : ''}¥
{Math.abs(position.profit).toLocaleString()} (
{position.profitRate >= 0 ? '+' : ''}
{position.profitRate}%)
</div>
</div>
</div>
))}
</div>
</Card>
</div>
);
};
export default AssetsPage;

View File

@@ -0,0 +1,53 @@
.plans-page {
max-width: 1400px;
margin: 0 auto;
}
.plans-list {
display: flex;
flex-direction: column;
gap: 16px;
}
.plan-card {
margin-bottom: 0;
}
.plan-header {
display: flex;
justify-content: space-between;
align-items: start;
margin-bottom: 16px;
}
.plan-title {
font-size: 16px;
font-weight: 600;
color: #1f2937;
}
.plan-details {
margin-top: 12px;
}
.plan-detail-item {
font-size: 14px;
}
.plan-detail-label {
color: #6b7280;
margin-bottom: 4px;
font-size: 12px;
}
.plan-detail-value {
font-weight: 500;
color: #1f2937;
}
@media (max-width: 768px) {
.plan-header {
flex-direction: column;
gap: 8px;
}
}

View File

@@ -0,0 +1,105 @@
import { Card, Button, Tag, Row, Col } from 'antd';
import './PlansPage.css';
const PlansPage = () => {
// 写死的数据
const plans = [
{
id: 1,
title: '买入贵州茅台',
status: 'executing',
statusText: '执行中',
targetPrice: '¥1,800',
planAmount: '¥100,000',
deadline: '2024-12-31',
progress: 60,
},
{
id: 2,
title: '买入腾讯控股',
status: 'pending',
statusText: '待执行',
targetPrice: 'HK$380',
planAmount: '¥50,000',
deadline: '2024-11-30',
progress: 0,
},
{
id: 3,
title: '卖出苹果公司',
status: 'completed',
statusText: '已完成',
targetPrice: '$180',
planAmount: '¥200,000',
deadline: '2024-10-15',
progress: 100,
},
];
const getStatusColor = (status: string) => {
switch (status) {
case 'pending':
return 'warning';
case 'executing':
return 'processing';
case 'completed':
return 'success';
default:
return 'default';
}
};
return (
<div className="plans-page">
<Card
title="交易计划"
extra={
<Button type="primary" size="small">
+
</Button>
}
>
<div className="plans-list">
{plans.map((plan) => (
<Card key={plan.id} className="plan-card" hoverable>
<div className="plan-header">
<div className="plan-title">{plan.title}</div>
<Tag color={getStatusColor(plan.status)}>{plan.statusText}</Tag>
</div>
<Row gutter={[16, 16]} className="plan-details">
<Col xs={12} sm={6}>
<div className="plan-detail-item">
<div className="plan-detail-label"></div>
<div className="plan-detail-value">{plan.targetPrice}</div>
</div>
</Col>
<Col xs={12} sm={6}>
<div className="plan-detail-item">
<div className="plan-detail-label"></div>
<div className="plan-detail-value">{plan.planAmount}</div>
</div>
</Col>
<Col xs={12} sm={6}>
<div className="plan-detail-item">
<div className="plan-detail-label">
{plan.status === 'completed' ? '完成时间' : '截止时间'}
</div>
<div className="plan-detail-value">{plan.deadline}</div>
</div>
</Col>
<Col xs={12} sm={6}>
<div className="plan-detail-item">
<div className="plan-detail-label"></div>
<div className="plan-detail-value">{plan.progress}%</div>
</div>
</Col>
</Row>
</Card>
))}
</div>
</Card>
</div>
);
};
export default PlansPage;

View File

@@ -0,0 +1,28 @@
.review-page {
max-width: 1400px;
margin: 0 auto;
}
.timeline-content {
background: #ffffff;
border-radius: 8px;
padding: 16px;
border: 1px solid #e5e7eb;
}
.timeline-date {
font-size: 12px;
color: #6b7280;
margin-bottom: 8px;
}
.timeline-text {
font-size: 14px;
line-height: 1.6;
color: #1f2937;
}
.timeline-text strong {
color: #1f2937;
font-weight: 600;
}

View File

@@ -0,0 +1,60 @@
import { Card, Button, Timeline } from 'antd';
import './ReviewPage.css';
const ReviewPage = () => {
// 写死的数据
const reviews = [
{
id: 1,
date: '2024-10-20',
title: '买入贵州茅台',
content:
'今天以¥1,750的价格买入了100股贵州茅台。主要考虑是1茅台作为白酒龙头品牌价值难以复制2当前估值相对合理3长期看好消费升级趋势。计划持有3-5年。',
},
{
id: 2,
date: '2024-09-15',
title: '卖出部分腾讯控股',
content:
'以HK$350的价格卖出了200股腾讯控股主要是为了锁定部分利润。虽然长期看好但考虑到当前市场环境决定降低仓位。剩余持仓继续持有。',
},
{
id: 3,
date: '2024-08-01',
title: '月度复盘',
content:
'本月整体收益+5.2%主要贡献来自腾讯和茅台的上涨。需要反思的是1对市场波动反应过度频繁交易2应该更专注于长期价值投资3需要建立更系统的投资检查清单。',
},
];
return (
<div className="review-page">
<Card
title="投资复盘"
extra={
<Button type="primary" size="small">
+
</Button>
}
>
<Timeline
items={reviews.map((review) => ({
color: '#8b5cf6',
children: (
<div className="timeline-content">
<div className="timeline-date">{review.date}</div>
<div className="timeline-text">
<strong>{review.title}</strong>
<br />
{review.content}
</div>
</div>
),
}))}
/>
</Card>
</div>
);
};
export default ReviewPage;

View File

@@ -0,0 +1,30 @@
import { createBrowserRouter } from 'react-router';
import MainLayout from '../layouts/MainLayout';
import AssetsPage from '../pages/AssetsPage';
import PlansPage from '../pages/PlansPage';
import ReviewPage from '../pages/ReviewPage';
export const router = createBrowserRouter([
{
path: '/',
element: <MainLayout />,
children: [
{
index: true,
element: <AssetsPage />,
},
{
path: 'assets',
element: <AssetsPage />,
},
{
path: 'plans',
element: <PlansPage />,
},
{
path: 'review',
element: <ReviewPage />,
},
],
},
]);

View File

@@ -0,0 +1,95 @@
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { envConfig } from '../config/env';
// 创建 axios 实例
const apiClient: AxiosInstance = axios.create({
baseURL: envConfig.apiBaseUrl,
timeout: 30000, // 30秒超时
headers: {
'Content-Type': 'application/json',
},
});
// 请求拦截器
apiClient.interceptors.request.use(
(config) => {
// 可以在这里添加 token 等认证信息
// const token = localStorage.getItem('token')
// if (token) {
// config.headers.Authorization = `Bearer ${token}`
// }
if (envConfig.debug) {
console.log('请求:', config.method?.toUpperCase(), config.url);
}
return config;
},
(error) => {
if (envConfig.debug) {
console.error('请求错误:', error);
}
return Promise.reject(error);
}
);
// 响应拦截器
apiClient.interceptors.response.use(
(response: AxiosResponse) => {
if (envConfig.debug) {
console.log('响应:', response.config.url, response.data);
}
return response;
},
(error) => {
if (envConfig.debug) {
console.error('响应错误:', error.response?.data || error.message);
}
// 处理常见错误
if (error.response) {
switch (error.response.status) {
case 401:
// 未授权,可以跳转到登录页
// window.location.href = '/login'
break;
case 403:
console.error('没有权限访问该资源');
break;
case 404:
console.error('请求的资源不存在');
break;
case 500:
console.error('服务器内部错误');
break;
default:
console.error('请求失败:', error.response.data?.message || error.message);
}
} else if (error.request) {
console.error('网络错误,请检查网络连接');
}
return Promise.reject(error);
}
);
// 导出常用的请求方法
export const api = {
get: <T = any>(url: string, config?: AxiosRequestConfig) =>
apiClient.get<T>(url, config).then((res) => res.data),
post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
apiClient.post<T>(url, data, config).then((res) => res.data),
put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
apiClient.put<T>(url, data, config).then((res) => res.data),
patch: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
apiClient.patch<T>(url, data, config).then((res) => res.data),
delete: <T = any>(url: string, config?: AxiosRequestConfig) =>
apiClient.delete<T>(url, config).then((res) => res.data),
};
// 导出 axios 实例(用于特殊需求)
export default apiClient;

15
apps/web/src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1,15 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_PORT: string;
readonly VITE_API_BASE_URL: string;
readonly VITE_APP_NAME: string;
readonly VITE_APP_TITLE: string;
readonly VITE_ENV: string;
readonly VITE_USE_MOCK: string;
readonly VITE_DEBUG: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
apps/web/tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

21
apps/web/vite.config.ts Normal file
View File

@@ -0,0 +1,21 @@
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react-swc';
// https://vite.dev/config/
export default defineConfig(({ mode }) => {
// 加载环境变量
const env = loadEnv(mode, process.cwd(), '');
return {
plugins: [react()],
server: {
port: parseInt(env.VITE_PORT || '5173', 10),
host: true, // 允许外部访问
open: true, // 自动打开浏览器
},
preview: {
port: parseInt(env.VITE_PORT || '4173', 10),
host: true,
},
};
});

View File

@@ -1,13 +1,29 @@
{
"name": "vest-mind",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"packageManager": "pnpm@10.20.0"
"name": "vest-mind",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "pnpm -r --parallel dev",
"dev:api": "pnpm --filter api start:dev",
"dev:web": "pnpm --filter web dev",
"start": "pnpm -r --parallel start",
"start:api": "pnpm --filter api start",
"start:api:prod": "pnpm --filter api start:prod",
"start:web": "pnpm --filter web preview",
"build": "pnpm -r build",
"build:api": "pnpm --filter api build",
"build:web": "pnpm --filter web build",
"lint": "pnpm -r lint",
"lint:api": "pnpm --filter api lint",
"lint:web": "pnpm --filter web lint",
"test": "pnpm -r test",
"test:api": "pnpm --filter api test",
"format": "pnpm -r format",
"format:api": "pnpm --filter api format"
},
"keywords": [],
"author": "",
"license": "ISC",
"packageManager": "pnpm@10.20.0"
}

2543
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff