Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

系统架构

整体架构概览

本系统采用现代化的前后端分离架构,基于微服务设计理念,构建了一个功能完整、可扩展的人力资源管理系统。

技术栈总览

graph TB
    subgraph "🌐 前端层 (Frontend Layer)"
        A1["⚛️ Next.js 15.5.2<br/>React 19.1.0<br/>TypeScript"]
        A2["🎨 Tailwind CSS<br/>Radix UI<br/>Lucide React"]
        A3["🔧 React Context<br/>Hook Form<br/>Zod Validation"]
    end
    
    subgraph "🚪 API网关层 (API Gateway Layer)"
        B1["🔐 CORS Middleware<br/>Authentication<br/>Rate Limiting"]
        B2["🔄 Request/Response<br/>Transformation<br/>Logging"]
        B3["⚖️ API Gateway<br/>Service Discovery<br/>Load Balancing"]
    end
    
    subgraph "⚙️ 后端层 (Backend Layer)"
        C1["🚀 FastAPI Framework<br/>SQLAlchemy 2.0<br/>Pydantic Models"]
        C2["📊 Alembic Migrations<br/>PostgreSQL<br/>Redis Cache"]
        C3["🔒 JWT Authentication<br/>OAuth2<br/>Security"]
    end
    
    subgraph "💾 数据层 (Database Layer)"
        D1["🗄️ PostgreSQL Primary<br/>Redis Cache<br/>File Storage"]
        D2["🔄 Database Migrations<br/>Backup & Recovery<br/>Data Security"]
        D3["🌐 Data Replication<br/>Disaster Recovery<br/>Monitoring"]
    end
    
    A1 --> B1
    A2 --> B2
    A3 --> B3
    B1 --> C1
    B2 --> C2
    B3 --> C3
    C1 --> D1
    C2 --> D2
    C3 --> D3
    
    classDef frontend fill:#e3f2fd,stroke:#1976d2,stroke-width:4px,color:#000
    classDef gateway fill:#f3e5f5,stroke:#7b1fa2,stroke-width:4px,color:#000
    classDef backend fill:#e8f5e8,stroke:#388e3c,stroke-width:4px,color:#000
    classDef database fill:#fff3e0,stroke:#f57c00,stroke-width:4px,color:#000
    
    class A1,A2,A3 frontend
    class B1,B2,B3 gateway
    class C1,C2,C3 backend
    class D1,D2,D3 database

前端架构设计

1. 技术架构层次

graph TB
    subgraph "🎨 表现层 (Presentation Layer)"
        A1["📱 Pages & App Router<br/>Components<br/>UI Library"]
        A2["⚛️ Next.js 15.5.2<br/>React 19.1.0<br/>TypeScript"]
        A3["🖥️ User Interface<br/>Responsive Design<br/>Accessibility"]
    end
    
    subgraph "🧠 业务逻辑层 (Business Logic Layer)"
        B1["⚙️ Services<br/>Hooks<br/>Context"]
        B2["🔄 State Management<br/>React Context API<br/>Custom Hooks"]
        B3["📋 Business Rules<br/>Validation Logic<br/>Workflow Engine"]
    end
    
    subgraph "🔌 数据访问层 (Data Access Layer)"
        C1["🌐 API Client<br/>HTTP Client<br/>Type Definitions"]
        C2["📡 Axios-like Client<br/>TypeScript Types<br/>Error Handling"]
        C3["🔄 Data Transformation<br/>Caching Strategy<br/>Offline Support"]
    end
    
    A1 --> B1
    A2 --> B2
    A3 --> B3
    B1 --> C1
    B2 --> C2
    B3 --> C3
    
    classDef presentation fill:#e3f2fd,stroke:#1976d2,stroke-width:4px,color:#000
    classDef business fill:#e8f5e8,stroke:#388e3c,stroke-width:4px,color:#000
    classDef data fill:#fce4ec,stroke:#c2185b,stroke-width:4px,color:#000
    
    class A1,A2,A3 presentation
    class B1,B2,B3 business
    class C1,C2,C3 data

2. 组件架构设计

页面组件结构

app/
├── (auth)/                    # 认证相关页面
│   └── login/
├── (dashboard)/               # 仪表盘页面
│   └── page.tsx
├── attendance/                # 考勤管理模块
│   ├── page.tsx              # 考勤首页
│   ├── records/              # 考勤记录
│   ├── leave/                # 请假管理
│   ├── overtime/             # 加班管理
│   └── reports/              # 考勤报表
├── employees/                 # 员工管理模块
│   ├── page.tsx              # 员工列表
│   ├── profiles/             # 员工档案
│   ├── search/               # 员工搜索
│   └── status/               # 员工状态
├── organization/              # 组织架构模块
│   ├── departments/          # 部门管理
│   ├── positions/           # 岗位管理
│   └── chart/               # 组织架构图
└── ...                      # 其他业务模块

组件层次结构

components/
├── ui/                       # 基础UI组件
│   ├── button.tsx           # 按钮组件
│   ├── input.tsx            # 输入框组件
│   ├── table.tsx            # 表格组件
│   └── ...                  # 其他基础组件
├── layout/                  # 布局组件
│   ├── navigation.tsx       # 导航组件
│   ├── sidebar.tsx          # 侧边栏组件
│   └── header.tsx           # 头部组件
├── business/                 # 业务组件
│   ├── employee-card.tsx    # 员工卡片
│   ├── department-tree.tsx  # 部门树
│   └── attendance-form.tsx  # 考勤表单
└── common/                   # 通用组件
    ├── loading.tsx          # 加载组件
    ├── error-boundary.tsx   # 错误边界
    └── modal.tsx            # 模态框组件

3. 状态管理架构

全局状态管理

// 认证状态
interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  loading: boolean;
}

// 主题状态
interface ThemeState {
  theme: 'light' | 'dark';
  systemTheme: boolean;
}

// 应用状态
interface AppState {
  sidebarOpen: boolean;
  notifications: Notification[];
  loading: boolean;
}

状态管理流程

graph LR
    A["👤 User Action<br/>用户操作"] --> B["🧩 Component<br/>组件"]
    B --> C["🔄 Context/Hook<br/>状态管理"]
    C --> D["⚙️ Service<br/>业务服务"]
    D --> E["🌐 API Client<br/>API调用"]
    E --> F["🚀 Backend<br/>后端服务"]
    F --> G["📨 Response<br/>响应数据"]
    G --> H["🔄 State Update<br/>状态更新"]
    H --> A
    
    classDef user fill:#e8f5e8,stroke:#2e7d32,stroke-width:4px,color:#000
    classDef component fill:#e3f2fd,stroke:#1976d2,stroke-width:4px,color:#000
    classDef state fill:#f3e5f5,stroke:#7b1fa2,stroke-width:4px,color:#000
    classDef service fill:#fff3e0,stroke:#f57c00,stroke-width:4px,color:#000
    classDef api fill:#fce4ec,stroke:#c2185b,stroke-width:4px,color:#000
    classDef backend fill:#e0f2f1,stroke:#00695c,stroke-width:4px,color:#000
    classDef response fill:#f1f8e9,stroke:#558b2f,stroke-width:4px,color:#000
    classDef update fill:#fff8e1,stroke:#ff8f00,stroke-width:4px,color:#000
    
    class A user
    class B component
    class C state
    class D service
    class E api
    class F backend
    class G response
    class H update

4. 路由架构设计

App Router结构

app/
├── layout.tsx                # 根布局
├── page.tsx                  # 首页
├── loading.tsx              # 全局加载
├── error.tsx                # 全局错误
├── not-found.tsx            # 404页面
├── globals.css              # 全局样式
└── themes.css               # 主题样式

路由保护机制

// 路由保护组件
<ProtectedRoute>
  <LayoutWrapper>
    <Navigation />
    <PageContent />
  </LayoutWrapper>
</ProtectedRoute>

后端架构设计

1. 分层架构设计

graph TB
    subgraph "🌐 API路由层 (API Router Layer)"
        A1["🚀 FastAPI Routers<br/>Middleware<br/>Authentication"]
        A2["✅ Request Validation<br/>Response Serialization<br/>Error Handling"]
        A3["📚 API Documentation<br/>OpenAPI Schema<br/>Versioning"]
    end
    
    subgraph "🧠 业务逻辑层 (Business Service Layer)"
        B1["⚙️ Business Logic<br/>Data Processing<br/>Validation"]
        B2["🏗️ Service Classes<br/>Business Rules<br/>Workflow Engine"]
        B3["🔧 Domain Services<br/>Transaction Management<br/>Event Handling"]
    end
    
    subgraph "🔌 数据访问层 (Data Access Layer)"
        C1["📊 CRUD Operations<br/>Database Queries<br/>Data Mapping"]
        C2["🗃️ SQLAlchemy ORM<br/>Repository Pattern<br/>Query Optimization"]
        C3["✅ Data Validation<br/>Type Conversion<br/>Error Handling"]
    end
    
    subgraph "💾 数据存储层 (Database Storage Layer)"
        D1["🐘 PostgreSQL<br/>Redis Cache<br/>File Storage"]
        D2["🔄 Database Migrations<br/>Backup & Recovery<br/>Data Security"]
        D3["⚡ Connection Pooling<br/>Query Caching<br/>Performance Monitoring"]
    end
    
    A1 --> B1
    A2 --> B2
    A3 --> B3
    B1 --> C1
    B2 --> C2
    B3 --> C3
    C1 --> D1
    C2 --> D2
    C3 --> D3
    
    classDef router fill:#e8f5e8,stroke:#2e7d32,stroke-width:4px,color:#000
    classDef business fill:#e3f2fd,stroke:#1976d2,stroke-width:4px,color:#000
    classDef data fill:#fff3e0,stroke:#f57c00,stroke-width:4px,color:#000
    classDef storage fill:#fce4ec,stroke:#c2185b,stroke-width:4px,color:#000
    
    class A1,A2,A3 router
    class B1,B2,B3 business
    class C1,C2,C3 data
    class D1,D2,D3 storage

2. 模块化架构设计

核心模块结构

app/
├── core/                     # 核心模块
│   ├── config.py             # 配置管理
│   ├── database.py           # 数据库连接
│   ├── auth.py              # 认证授权
│   └── security.py          # 安全相关
├── models/                   # 数据模型
│   ├── user.py              # 用户模型
│   ├── employee.py          # 员工模型
│   ├── department.py        # 部门模型
│   ├── attendance.py        # 考勤模型
│   └── ...                  # 其他模型
├── schemas/                  # 数据模式
│   ├── user.py              # 用户模式
│   ├── employee.py          # 员工模式
│   └── ...                  # 其他模式
├── crud/                     # 数据访问
│   ├── user.py              # 用户CRUD
│   ├── employee.py          # 员工CRUD
│   └── ...                  # 其他CRUD
├── routers/                  # API路由
│   ├── auth.py              # 认证路由
│   ├── users.py             # 用户路由
│   ├── employees.py         # 员工路由
│   └── ...                  # 其他路由
└── services/                 # 业务服务
    ├── auth_service.py      # 认证服务
    ├── employee_service.py   # 员工服务
    └── ...                  # 其他服务

业务模块划分

业务模块架构:
├── 用户管理模块 (User Management)
│   ├── 用户认证 (Authentication)
│   ├── 权限控制 (Authorization)
│   └── 用户档案 (User Profile)
├── 员工管理模块 (Employee Management)
│   ├── 员工档案 (Employee Profile)
│   ├── 状态管理 (Status Management)
│   └── 家庭信息 (Family Information)
├── 组织架构模块 (Organization)
│   ├── 部门管理 (Department)
│   ├── 岗位管理 (Position)
│   └── 组织图表 (Org Chart)
├── 考勤管理模块 (Attendance)
│   ├── 考勤记录 (Attendance Records)
│   ├── 请假管理 (Leave Management)
│   └── 加班管理 (Overtime Management)
├── 招聘管理模块 (Recruitment)
│   ├── 招聘需求 (Requirements)
│   ├── 简历管理 (Resume Management)
│   └── 面试流程 (Interview Process)
└── 其他业务模块...

3. 数据模型架构

核心实体关系图

erDiagram
    User {
        int id PK "主键"
        string username "用户名"
        string email "邮箱"
        string role "角色"
        boolean is_active "激活状态"
        timestamp created_at "创建时间"
    }
    
    Employee {
        int id PK "主键"
        string employee_id "员工编号"
        int user_id FK "用户ID"
        string name "姓名"
        int department_id FK "部门ID"
        int position_id FK "岗位ID"
        date hire_date "入职日期"
        string employment_status "在职状态"
        boolean is_active "激活状态"
    }
    
    Department {
        int id PK "主键"
        string name "部门名称"
        string code "部门编码"
        int parent_id FK "上级部门"
        int manager_id FK "部门经理"
        int level "部门层级"
        boolean is_active "激活状态"
    }
    
    Position {
        int id PK "主键"
        string title "岗位名称"
        string code "岗位编码"
        int department_id FK "所属部门"
        string level "岗位级别"
        string category "岗位类别"
        boolean is_active "激活状态"
    }
    
    Attendance {
        int id PK "主键"
        int employee_id FK "员工ID"
        date date "考勤日期"
        time check_in "上班时间"
        time check_out "下班时间"
        string status "考勤状态"
        int work_hours "工作时长"
    }
    
    LeaveRequest {
        int id PK "主键"
        int employee_id FK "员工ID"
        string leave_type "请假类型"
        date start_date "开始日期"
        date end_date "结束日期"
        string status "审批状态"
        int approved_by FK "审批人"
    }
    
    User ||--o| Employee : "has profile"
    Employee }o--|| Department : "belongs to"
    Employee }o--|| Position : "has position"
    Employee ||--o{ Attendance : "has records"
    Employee ||--o{ LeaveRequest : "requests leave"
    Department ||--o{ Department : "parent-child"
    Department ||--o{ Position : "contains"
    Employee ||--o{ Employee : "manages"

数据访问模式

# Repository Pattern
class EmployeeRepository:
    def __init__(self, db: Session):
        self.db = db
    
    def get_by_id(self, id: int) -> Employee:
        return self.db.query(Employee).filter(Employee.id == id).first()
    
    def get_by_department(self, dept_id: int) -> List[Employee]:
        return self.db.query(Employee).filter(Employee.department_id == dept_id).all()
    
    def create(self, employee_data: EmployeeCreate) -> Employee:
        employee = Employee(**employee_data.dict())
        self.db.add(employee)
        self.db.commit()
        return employee

4. API架构设计

RESTful API设计

API端点设计:
├── 认证相关 (Authentication)
│   POST   /api/v1/auth/login          # 用户登录
│   POST   /api/v1/auth/refresh        # 刷新令牌
│   GET    /api/v1/auth/me             # 获取当前用户
├── 用户管理 (User Management)
│   GET    /api/v1/users/              # 获取用户列表
│   POST   /api/v1/users/              # 创建用户
│   GET    /api/v1/users/{id}          # 获取用户详情
│   PUT    /api/v1/users/{id}          # 更新用户
│   DELETE /api/v1/users/{id}          # 删除用户
├── 员工管理 (Employee Management)
│   GET    /api/v1/employees/           # 获取员工列表
│   POST   /api/v1/employees/           # 创建员工
│   GET    /api/v1/employees/{id}       # 获取员工详情
│   PUT    /api/v1/employees/{id}       # 更新员工
│   DELETE /api/v1/employees/{id}      # 删除员工
└── 其他业务模块...

API响应格式

// 成功响应
{
  "data": {
    "id": 1,
    "name": "张三",
    "email": "zhangsan@example.com"
  },
  "message": "操作成功",
  "status_code": 200
}

// 分页响应
{
  "items": [...],
  "total": 100,
  "page": 1,
  "size": 20,
  "pages": 5
}

// 错误响应
{
  "detail": "错误描述",
  "status_code": 400
}

数据架构设计

1. 数据库设计

数据库选择

  • 主数据库: PostgreSQL (关系型数据库)
  • 缓存数据库: Redis (内存数据库)
  • 文件存储: 本地文件系统 / 云存储

数据库架构

graph TB
    subgraph "🚀 应用层 (Application Layer)"
        A1["⚡ FastAPI Framework<br/>SQLAlchemy ORM<br/>Pydantic Models"]
        A2["✅ Data Validation<br/>Serialization<br/>Business Logic"]
        A3["🌐 API Endpoints<br/>Request Handling<br/>Response Formatting"]
    end
    
    subgraph "🔌 连接层 (Connection Layer)"
        B1["🏊 Connection Pool<br/>Transaction Management<br/>Query Cache"]
        B2["📊 Connection Monitoring<br/>Performance Tuning<br/>Resource Management"]
        B3["🔒 Connection Security<br/>SSL/TLS<br/>Authentication"]
    end
    
    subgraph "💾 存储层 (Storage Layer)"
        C1["🐘 PostgreSQL Primary<br/>Redis Cache<br/>File Storage"]
        C2["🔄 Data Replication<br/>Backup & Recovery<br/>Security & Encryption"]
        C3["📦 Data Archiving<br/>Compression<br/>Indexing Strategy"]
    end
    
    A1 --> B1
    A2 --> B2
    A3 --> B3
    B1 --> C1
    B2 --> C2
    B3 --> C3
    
    classDef application fill:#e8f5e8,stroke:#2e7d32,stroke-width:4px,color:#000
    classDef connection fill:#e3f2fd,stroke:#1976d2,stroke-width:4px,color:#000
    classDef storage fill:#fff3e0,stroke:#f57c00,stroke-width:4px,color:#000
    
    class A1,A2,A3 application
    class B1,B2,B3 connection
    class C1,C2,C3 storage

数据表设计

-- 用户表
CREATE TABLE "user" (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    full_name VARCHAR(100) NOT NULL,
    role VARCHAR(20) DEFAULT 'employee',
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE
);

-- 员工表
CREATE TABLE "employee" (
    id SERIAL PRIMARY KEY,
    employee_id VARCHAR(20) UNIQUE NOT NULL,
    user_id INTEGER REFERENCES "user"(id),
    name VARCHAR(100) NOT NULL,
    department_id INTEGER NOT NULL,
    position_id INTEGER NOT NULL,
    hire_date DATE NOT NULL,
    employment_status VARCHAR(20) DEFAULT 'active',
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE
);

-- 部门表
CREATE TABLE "department" (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    code VARCHAR(20) UNIQUE NOT NULL,
    parent_id INTEGER REFERENCES "department"(id),
    manager_id INTEGER REFERENCES "employee"(id),
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE
);

2. 缓存架构设计

缓存策略

graph TB
    subgraph "📱 应用层缓存 (Application Cache Layer)"
        A1["⚛️ React Query<br/>SWR<br/>Local Storage"]
        A2["💾 Session Storage<br/>Memory Cache<br/>Component State"]
        A3["🌐 Browser Cache<br/>HTTP Cache<br/>CDN Cache"]
    end
    
    subgraph "🔄 服务层缓存 (Service Cache Layer)"
        B1["🔴 Redis Cache<br/>Memory Cache<br/>Query Cache"]
        B2["⏰ Cache Invalidation<br/>TTL Management<br/>Cache Warming"]
        B3["🌐 Distributed Cache<br/>Cache Clustering<br/>Failover"]
    end
    
    subgraph "🗄️ 数据库层缓存 (Database Cache Layer)"
        C1["🐘 PostgreSQL Query Cache<br/>Connection Pool<br/>Index Cache"]
        C2["💾 Buffer Pool<br/>Query Plan Cache<br/>Statistics Cache"]
        C3["📊 Read Replicas<br/>Master-Slave<br/>Sharding"]
    end
    
    A1 --> B1
    A2 --> B2
    A3 --> B3
    B1 --> C1
    B2 --> C2
    B3 --> C3
    
    classDef appCache fill:#e8f5e8,stroke:#2e7d32,stroke-width:4px,color:#000
    classDef serviceCache fill:#e3f2fd,stroke:#1976d2,stroke-width:4px,color:#000
    classDef dbCache fill:#fff3e0,stroke:#f57c00,stroke-width:4px,color:#000
    
    class A1,A2,A3 appCache
    class B1,B2,B3 serviceCache
    class C1,C2,C3 dbCache

缓存层次

// 前端缓存策略
interface CacheStrategy {
  // 用户数据缓存
  user: {
    ttl: 300, // 5分钟
    storage: 'memory'
  };
  
  // 员工数据缓存
  employees: {
    ttl: 600, // 10分钟
    storage: 'localStorage'
  };
  
  // 部门数据缓存
  departments: {
    ttl: 1800, // 30分钟
    storage: 'sessionStorage'
  };
}

安全架构设计

1. 认证授权架构

认证流程

graph LR
    A["👤 用户登录<br/>User Login"] --> B["🔐 用户名/密码验证<br/>Credential Validation"]
    B --> C["🎫 JWT Token生成<br/>Token Generation"]
    C --> D["💾 前端存储Token<br/>Token Storage"]
    D --> E["🌐 API请求<br/>API Request"]
    E --> F["✅ Token验证<br/>Token Validation"]
    F --> G["🔍 权限检查<br/>Permission Check"]
    G --> H["⚙️ 业务逻辑执行<br/>Business Logic"]
    H --> I["⏰ Token过期<br/>Token Expiry"]
    I --> J["🔄 自动刷新<br/>Auto Refresh"]
    J --> K["🆕 新Token生成<br/>New Token"]
    K --> E
    
    classDef login fill:#e8f5e8,stroke:#2e7d32,stroke-width:4px,color:#000
    classDef validation fill:#e3f2fd,stroke:#1976d2,stroke-width:4px,color:#000
    classDef token fill:#f3e5f5,stroke:#7b1fa2,stroke-width:4px,color:#000
    classDef storage fill:#fff3e0,stroke:#f57c00,stroke-width:4px,color:#000
    classDef request fill:#fce4ec,stroke:#c2185b,stroke-width:4px,color:#000
    classDef check fill:#e0f2f1,stroke:#00695c,stroke-width:4px,color:#000
    classDef logic fill:#f1f8e9,stroke:#558b2f,stroke-width:4px,color:#000
    classDef refresh fill:#fff8e1,stroke:#ff8f00,stroke-width:4px,color:#000
    
    class A login
    class B validation
    class C,K token
    class D storage
    class E request
    class F,G check
    class H logic
    class I,J refresh

权限控制模型

graph TB
    subgraph "👥 RBAC权限模型 (Role-Based Access Control)"
        A["👤 User<br/>用户账户"] --> B["🎭 Role<br/>角色"]
        B --> C["🔑 Permission<br/>权限"]
        C --> D["📁 Resource<br/>资源"]
    end
    
    subgraph "🎭 角色类型 (Role Types)"
        E["👑 admin<br/>超级管理员"]
        F["👨‍💼 hr<br/>HR管理员"]
        G["👨‍💻 manager<br/>部门经理"]
        H["👤 employee<br/>普通员工"]
    end
    
    subgraph "🔑 权限类型 (Permission Types)"
        I["👁️ read<br/>读取权限"]
        J["✏️ write<br/>写入权限"]
        K["🗑️ delete<br/>删除权限"]
        L["✅ approve<br/>审批权限"]
    end
    
    subgraph "📁 资源类型 (Resource Types)"
        M["👥 employee<br/>员工管理"]
        N["🏢 department<br/>部门管理"]
        O["⏰ attendance<br/>考勤管理"]
        P["💰 payroll<br/>薪酬管理"]
    end
    
    B --> E
    B --> F
    B --> G
    B --> H
    C --> I
    C --> J
    C --> K
    C --> L
    D --> M
    D --> N
    D --> O
    D --> P
    
    classDef user fill:#e8f5e8,stroke:#2e7d32,stroke-width:4px,color:#000
    classDef role fill:#e3f2fd,stroke:#1976d2,stroke-width:4px,color:#000
    classDef permission fill:#f3e5f5,stroke:#7b1fa2,stroke-width:4px,color:#000
    classDef resource fill:#fff3e0,stroke:#f57c00,stroke-width:4px,color:#000
    classDef roleType fill:#fce4ec,stroke:#c2185b,stroke-width:4px,color:#000
    classDef permType fill:#e0f2f1,stroke:#00695c,stroke-width:4px,color:#000
    classDef resType fill:#f1f8e9,stroke:#558b2f,stroke-width:4px,color:#000
    
    class A user
    class B role
    class C permission
    class D resource
    class E,F,G,H roleType
    class I,J,K,L permType
    class M,N,O,P resType

权限矩阵

graph TB
    subgraph "权限矩阵 (Permission Matrix)"
        A["超级管理员<br/>Super Admin"] --> A1["员工管理: CRUD<br/>Employee Management"]
        A --> A2["部门管理: CRUD<br/>Department Management"]
        A --> A3["考勤管理: CRUD<br/>Attendance Management"]
        A --> A4["薪酬管理: CRUD<br/>Payroll Management"]
        A --> A5["系统设置: CRUD<br/>System Settings"]
        
        B["HR管理员<br/>HR Admin"] --> B1["员工管理: CRUD<br/>Employee Management"]
        B --> B2["部门管理: CRUD<br/>Department Management"]
        B --> B3["考勤管理: CRUD<br/>Attendance Management"]
        B --> B4["薪酬管理: Read<br/>Payroll Read Only"]
        B --> B5["系统设置: Read<br/>System Read Only"]
        
        C["部门经理<br/>Department Manager"] --> C1["员工管理: CRUD<br/>Employee Management"]
        C --> C2["部门管理: Read<br/>Department Read Only"]
        C --> C3["考勤管理: CRUD<br/>Attendance Management"]
        C --> C4["薪酬管理: Read<br/>Payroll Read Only"]
        C --> C5["系统设置: Read<br/>System Read Only"]
        
        D["普通员工<br/>Employee"] --> D1["员工管理: Read<br/>Employee Read Only"]
        D --> D2["部门管理: Read<br/>Department Read Only"]
        D --> D3["考勤管理: CRUD<br/>Attendance Management"]
        D --> D4["薪酬管理: Read<br/>Payroll Read Only"]
        D --> D5["系统设置: Read<br/>System Read Only"]
    end
    
    classDef superAdmin fill:#ffebee,stroke:#c62828,stroke-width:3px,color:#000
    classDef hrAdmin fill:#e8f5e8,stroke:#2e7d32,stroke-width:3px,color:#000
    classDef manager fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#000
    classDef employee fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#000
    
    class A,A1,A2,A3,A4,A5 superAdmin
    class B,B1,B2,B3,B4,B5 hrAdmin
    class C,C1,C2,C3,C4,C5 manager
    class D,D1,D2,D3,D4,D5 employee

2. 数据安全架构

数据加密策略

graph TB
    subgraph "传输层安全 (Transport Security Layer)"
        A1["HTTPS/TLS 1.3<br/>Certificate Pinning<br/>HSTS"]
        A2["SSL/TLS Encryption<br/>Certificate Management<br/>Secure Protocols"]
    end
    
    subgraph "应用层安全 (Application Security Layer)"
        B1["JWT Token<br/>OAuth2<br/>CORS"]
        B2["CSRF Protection<br/>XSS Prevention<br/>Input Validation"]
    end
    
    subgraph "数据层安全 (Data Security Layer)"
        C1["Password Hashing<br/>Data Encryption<br/>Audit Logging"]
        C2["Database Encryption<br/>Field-level Encryption<br/>Key Management"]
    end
    
    A1 --> B1
    A2 --> B1
    B1 --> C1
    B2 --> C1
    C1 --> C2
    
    classDef transport fill:#e8f5e8,stroke:#2e7d32,stroke-width:3px,color:#000
    classDef application fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#000
    classDef data fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#000
    
    class A1,A2 transport
    class B1,B2 application
    class C1,C2 data

安全措施

# 密码安全
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# 数据加密
from cryptography.fernet import Fernet
encryption_key = Fernet.generate_key()
cipher_suite = Fernet(encryption_key)

# 审计日志
class AuditLog:
    def log_action(self, user_id: int, action: str, resource: str):
        log_entry = {
            "user_id": user_id,
            "action": action,
            "resource": resource,
            "timestamp": datetime.utcnow(),
            "ip_address": request.client.host
        }
        # 记录到审计日志表

部署架构设计

1. 容器化部署

Docker架构

graph TB
    subgraph "🌐 前端容器 (Frontend Container)"
        A1["⚛️ Next.js App<br/>🔧 Nginx<br/>📁 Static Assets"]
        A2["🔌 Port: 3000 Dev<br/>🔌 Port: 80 Prod<br/>🔒 SSL Termination"]
    end
    
    subgraph "🚀 后端容器 (Backend Container)"
        B1["⚡ FastAPI App<br/>🦄 Uvicorn<br/>🐍 Python 3.13"]
        B2["🔌 Port: 8000<br/>❤️ Health Checks<br/>📈 Auto-scaling"]
    end
    
    subgraph "💾 数据库容器 (Database Container)"
        C1["🐘 PostgreSQL 15<br/>🔴 Redis 7<br/>💾 Data Volumes"]
        C2["🔌 Port: 5432 PostgreSQL<br/>🔌 Port: 6379 Redis<br/>🔄 Backup & Recovery"]
    end
    
    A1 --> B1
    A2 --> B2
    B1 --> C1
    B2 --> C2
    
    classDef frontend fill:#e8f5e8,stroke:#2e7d32,stroke-width:4px,color:#000
    classDef backend fill:#e3f2fd,stroke:#1976d2,stroke-width:4px,color:#000
    classDef database fill:#fff3e0,stroke:#f57c00,stroke-width:4px,color:#000
    
    class A1,A2 frontend
    class B1,B2 backend
    class C1,C2 database

Docker Compose配置

version: '3.8'
services:
  frontend:
    build: ./frontend
    ports:
      - "3000:3000"
    environment:
      - NEXT_PUBLIC_API_URL=http://backend:8000
    depends_on:
      - backend

  backend:
    build: ./backend
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgresql://user:password@db:5432/hr_db
      - REDIS_URL=redis://redis:6379
    depends_on:
      - db
      - redis

  db:
    image: postgres:15
    environment:
      - POSTGRES_DB=hr_db
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=password
    volumes:
      - postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

volumes:
  postgres_data:

2. 生产环境架构

负载均衡架构

graph TB
    subgraph "负载均衡器 (Load Balancer)"
        A1["Nginx<br/>SSL Termination<br/>Health Checks"]
        A2["Load Balancing<br/>SSL Offloading<br/>Rate Limiting"]
    end
    
    subgraph "应用服务器集群 (Application Cluster)"
        B1["Frontend Servers 2+<br/>Static Assets<br/>CDN"]
        B2["Backend Servers 2+<br/>API Services<br/>Microservices"]
        B3["Auto-scaling<br/>Health Monitoring<br/>Failover"]
    end
    
    subgraph "数据库集群 (Database Cluster)"
        C1["PostgreSQL Master/Slave<br/>Read Replicas<br/>Connection Pooling"]
        C2["Redis Cluster<br/>Cache Layer<br/>Session Storage"]
        C3["Backup & Recovery<br/>Data Replication<br/>Disaster Recovery"]
    end
    
    A1 --> B1
    A2 --> B1
    A1 --> B2
    A2 --> B2
    B1 --> C1
    B2 --> C1
    B3 --> C1
    C1 --> C2
    C2 --> C3
    
    classDef loadbalancer fill:#e8f5e8,stroke:#2e7d32,stroke-width:3px,color:#000
    classDef application fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#000
    classDef database fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#000
    
    class A1,A2 loadbalancer
    class B1,B2,B3 application
    class C1,C2,C3 database

监控架构

graph TB
    subgraph "应用监控 (Application Monitoring)"
        A1["Prometheus<br/>Metrics Collection<br/>Time Series DB"]
        A2["Grafana<br/>Dashboards<br/>Visualization"]
        A3["AlertManager<br/>Alerting<br/>Notifications"]
        A4["Logging<br/>ELK Stack<br/>Log Analysis"]
    end
    
    subgraph "基础设施监控 (Infrastructure Monitoring)"
        B1["System Metrics<br/>CPU/Memory/Disk<br/>Network I/O"]
        B2["Database Metrics<br/>Query Performance<br/>Connection Pool"]
        B3["Application Metrics<br/>Response Time<br/>Error Rates"]
    end
    
    A1 --> B1
    A2 --> B1
    A3 --> B1
    A4 --> B1
    A1 --> B2
    A2 --> B2
    A3 --> B2
    A4 --> B2
    A1 --> B3
    A2 --> B3
    A3 --> B3
    A4 --> B3
    
    classDef monitoring fill:#e8f5e8,stroke:#2e7d32,stroke-width:3px,color:#000
    classDef infrastructure fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#000
    
    class A1,A2,A3,A4 monitoring
    class B1,B2,B3 infrastructure

扩展性架构设计

1. 微服务架构演进

当前单体架构

graph TB
    subgraph "单体应用 (Monolithic Application)"
        A[Frontend + Backend + Database in Single Deployment]
    end

微服务架构演进

graph TB
    subgraph "🔧 微服务架构 (Microservices Architecture)"
        A1["👤 User Service<br/>🔐 Authentication<br/>🔑 Authorization"]
        A2["👥 Employee Service<br/>👤 Employee Management<br/>📋 Profile Management"]
        A3["⏰ Attendance Service<br/>⏱️ Time Tracking<br/>📅 Leave Management"]
        A4["🏢 Organization Service<br/>🏢 Department Management<br/>💼 Position Management"]
        A5["🎯 Recruitment Service<br/>📝 Hiring Process<br/>💬 Interview Management"]
    end
    
    subgraph "🌐 服务网格 (Service Mesh)"
        B1["🚪 API Gateway<br/>🔍 Service Discovery<br/>⚖️ Load Balancing"]
        B2["📋 Service Registry<br/>❤️ Health Checks<br/>🔌 Circuit Breaker"]
        B3["📨 Message Queue<br/>📡 Event Streaming<br/>🔄 Async Communication"]
    end
    
    A1 --> B1
    A2 --> B1
    A3 --> B1
    A4 --> B1
    A5 --> B1
    B1 --> B2
    B2 --> B3
    
    classDef microservice fill:#e8f5e8,stroke:#2e7d32,stroke-width:4px,color:#000
    classDef mesh fill:#e3f2fd,stroke:#1976d2,stroke-width:4px,color:#000
    
    class A1,A2,A3,A4,A5 microservice
    class B1,B2,B3 mesh

2. 插件化架构

插件系统设计

graph TB
    subgraph "🏗️ 核心系统 (Core System)"
        A1["👤 User Management<br/>🔐 Authentication<br/>⚙️ Basic HR Functions"]
        A2["👥 Employee Management<br/>🏢 Department Management<br/>💼 Position Management"]
    end
    
    subgraph "🔌 插件系统 (Plugin System)"
        B1["⚙️ Workflow Engine<br/>🤖 Process Automation<br/>✅ Approval Workflows"]
        B2["📊 Report Engine<br/>📋 Custom Reports<br/>📈 Data Visualization"]
        B3["📨 Notification System<br/>📧 Email/SMS<br/>📱 Push Notifications"]
        B4["🔗 Third-party Integrations<br/>🔌 API Connectors<br/>🔄 Data Synchronization"]
        B5["🔧 Custom Modules<br/>⚙️ Business Logic<br/>🎯 Domain-specific Features"]
    end
    
    A1 --> B1
    A2 --> B1
    A1 --> B2
    A2 --> B2
    A1 --> B3
    A2 --> B3
    A1 --> B4
    A2 --> B4
    A1 --> B5
    A2 --> B5
    
    classDef core fill:#e8f5e8,stroke:#2e7d32,stroke-width:4px,color:#000
    classDef plugin fill:#e3f2fd,stroke:#1976d2,stroke-width:4px,color:#000
    
    class A1,A2 core
    class B1,B2,B3,B4,B5 plugin

插件接口设计

// 插件接口定义
interface Plugin {
  name: string;
  version: string;
  description: string;
  initialize(): Promise<void>;
  destroy(): Promise<void>;
}

// 工作流插件
interface WorkflowPlugin extends Plugin {
  executeWorkflow(workflowId: string, data: any): Promise<any>;
  getWorkflowDefinition(id: string): Promise<WorkflowDefinition>;
}

// 报表插件
interface ReportPlugin extends Plugin {
  generateReport(reportId: string, params: any): Promise<ReportData>;
  getReportTemplate(id: string): Promise<ReportTemplate>;
}

性能优化架构

1. 前端性能优化

代码分割策略

graph TB
    subgraph "代码分割 (Code Splitting Strategy)"
        A1["Route-based Splitting<br/>Page-level Code Splitting<br/>Route Lazy Loading"]
        A2["Component-based Splitting<br/>Component Lazy Loading<br/>Feature-based Splitting"]
        A3["Dynamic Imports<br/>Dynamic Component Loading<br/>Conditional Imports"]
        A4["Lazy Loading<br/>On-demand Loading<br/>Progressive Loading"]
    end
    
    classDef splitting fill:#e8f5e8,stroke:#2e7d32,stroke-width:3px,color:#000
    
    class A1,A2,A3,A4 splitting

缓存策略

graph TB
    subgraph "缓存层次 (Cache Layers)"
        A1["Browser Cache<br/>HTTP Cache<br/>Local Storage"]
        A2["CDN Cache<br/>Static Assets<br/>Global Distribution"]
        A3["Application Cache<br/>Memory Cache<br/>Component State"]
        A4["Database Query Cache<br/>Query Result Cache<br/>Connection Pool"]
        A5["Redis Cache<br/>Distributed Cache<br/>Session Storage"]
    end
    
    A1 --> A2
    A2 --> A3
    A3 --> A4
    A4 --> A5
    
    classDef cache fill:#e8f5e8,stroke:#2e7d32,stroke-width:3px,color:#000
    
    class A1,A2,A3,A4,A5 cache

2. 后端性能优化

数据库优化

-- 索引优化
CREATE INDEX idx_employee_department ON employee(department_id);
CREATE INDEX idx_employee_status ON employee(employment_status);
CREATE INDEX idx_attendance_date ON attendance(date);

-- 查询优化
EXPLAIN ANALYZE SELECT * FROM employee 
WHERE department_id = 1 AND employment_status = 'active';

缓存优化

# Redis缓存策略
@cache(ttl=300)  # 5分钟缓存
def get_employee_by_id(employee_id: int):
    return employee_crud.get(db, id=employee_id)

@cache(ttl=1800)  # 30分钟缓存
def get_department_tree():
    return department_crud.get_tree_structure(db)

总结

本系统架构设计具有以下特点:

  1. 现代化技术栈: 采用最新的前后端技术,保证系统的先进性和可维护性
  2. 分层架构设计: 清晰的分层架构,职责分离,易于维护和扩展
  3. 微服务就绪: 当前单体架构,但设计上支持向微服务架构演进
  4. 安全可靠: 多层次的安全防护,保证系统安全
  5. 高性能: 完善的缓存策略和性能优化
  6. 可扩展: 插件化设计,支持功能扩展和第三方集成
  7. 可监控: 完善的监控和日志系统,便于运维管理

该架构设计为人力资源管理系统提供了坚实的技术基础,能够满足企业级应用的各种需求。