# 审计系统 API

**版本**: v1.0.0  
**基础路径**: `/api/v1/audit`  
**状态**: ✅ 核心功能已实现  
**最后更新**: 2025-12-07

---

## 概述

审计系统 API 提供审计日志的查询、统计、导出和完整性验证功能。所有接口遵循 FFOA 统一 API 规范。

### 通用约定

| 约定 | 说明 |
|------|------|
| **基础路径** | `/api/v1/audit` |
| **时间格式** | UTC ISO 8601（如 `2025-12-07T10:30:00.123Z`），前端负责本地化 |
| **认证方式** | Bearer Token（`Authorization: Bearer <token>`） |
| **请求头** | `Content-Type: application/json` |
| **响应格式** | 统一 `{ success, data, message?, timestamp, path }` 结构 |

---

## 认证与权限

### 角色权限矩阵

| 角色 | 可访问接口 | 数据范围 | 脱敏策略 |
|------|-----------|---------|---------|
| `admin` | 所有接口 | 全部数据 | 密码/Token 脱敏 |
| `auditor` | 日志、实体、用户、统计、完整性验证 | 全部数据 | 密码/Token 脱敏 |
| `finance` | `/financial` + `/logs`(部分) | 仅 `isFinancial=true` 记录 | 完整业务字段 |
| `security` | `/sensitive` + 异常统计 | 仅 `isSensitive=true` 记录 | 看不到财务金额 |
| `developer` | `/trace/:traceId` | 仅追踪链路 | 不返回 oldValue/newValue |

### 权限装饰器

```typescript
@RequirePermissions('audit:read')   // 基础查询
@RequirePermissions('audit:export') // 导出权限
@RequirePermissions('audit:verify') // 完整性验证
@RequirePermissions('audit:admin')  // 管理员操作
```

---

## 公共类型定义

### 统一响应格式

#### 成功响应

```typescript
interface ApiResponse<T> {
  success: true;
  data: T;
  message?: string;
  timestamp: string;       // ISO 8601 格式
  path: string;            // 请求路径
}
```

#### 分页响应

```typescript
interface PaginatedResponse<T> {
  success: true;
  data: {
    items: T[];
    total: number;
    page: number;
    limit: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
  timestamp: string;
  path: string;
}
```

#### 错误响应

```typescript
interface ApiError {
  success: false;
  error: {
    code: string;          // 机器可读错误码
    message: string;       // 人类可读消息
    details?: any;         // 详细信息
    field?: string;        // 字段级错误
    errors?: FieldError[]; // 多字段验证错误
  };
  timestamp: string;
  path: string;
  method: string;
  statusCode: number;
}

interface FieldError {
  field: string;
  message: string;
  value?: any;
  constraint?: string;
}
```

### 通用查询参数

```typescript
interface CommonQueryParams {
  // 多租户/多区域（必需，用于数据隔离）
  // 通常从用户会话中自动注入，无需前端显式传递
  region: string;            // 部署区域: cn / us / eu / ap
  tenantId: string;          // 租户 ID
  
  // 风险/合规级别
  riskLevel?: RiskLevel;
  complianceLevel?: ComplianceLevel;
  
  // 排序（仅允许指定字段）
  sortBy?: 'when' | 'module' | 'action' | 'userId';  // 默认 'when'
  sortOrder?: 'asc' | 'desc';                        // 默认 'desc'
}
```

**多租户隔离说明**：
- `region` 和 `tenantId` 为**必需参数**，用于审计数据的隔离查询
- 通常从用户会话中自动注入，无需前端显式传递
- 不同租户之间的审计日志完全隔离，无法跨租户查询

**排序字段限制**：
- `sortBy` 仅允许：`when`、`module`、`action`、`userId`
- 默认：`sortBy = 'when'`，`sortOrder = 'desc'`（最近的操作在最前）

### 数据脱敏说明

> **重要**: `oldValue` / `newValue` / `changes` 中的敏感字段（密码、Token、身份证号等）在**写入时**即已脱敏，API 返回的是脱敏后的数据（如 `***REDACTED***`），不会通过 API 返回原文。

---

## 时间跨度限制速查表

| 接口 | 时间跨度限制 | 说明 |
|------|-------------|------|
| `GET /audit/logs` | ≤ 90 天 | 通用查询，防止大范围全量扫描 |
| `GET /audit/financial` | ≤ 1 年 | 财务操作查询，`startDate`/`endDate` 必填 |
| `POST /audit/verify-integrity` | 建议 ≤ 30 天 | 同步校验，超过可能超时（504） |
| `POST /audit/export` | 无硬限制 | 但超过 10 万条将返回 `AUDIT_EXPORT_TOO_LARGE` |

---

## API 列表

### 审计日志查询

| 方法 | 路径 | 说明 | 权限 |
|------|------|------|------|
| GET | `/api/v1/audit/logs` | 查询审计日志 | `audit:read` |
| GET | `/api/v1/audit/logs/:id` | 获取审计日志详情 | `audit:read` |
| GET | `/api/v1/audit/entity/:type/:id` | 获取实体审计历史 | `audit:read` |
| GET | `/api/v1/audit/user/:userId` | 获取用户操作历史 | `audit:read` |
| GET | `/api/v1/audit/financial` | 获取财务操作日志 | `audit:read:financial` |
| GET | `/api/v1/audit/sensitive` | 获取敏感操作日志 | `audit:read:sensitive` |
| GET | `/api/v1/audit/trace/:traceId` | 按追踪 ID 获取请求链路 | `audit:trace` |

### 统计与报表

| 方法 | 路径 | 说明 | 权限 |
|------|------|------|------|
| POST | `/api/v1/audit/statistics` | 获取统计分析 | `audit:statistics` |
| POST | `/api/v1/audit/export` | 导出审计日志 | `audit:export` |

### 完整性验证

| 方法 | 路径 | 说明 | 权限 |
|------|------|------|------|
| POST | `/api/v1/audit/verify-integrity` | 即时验证完整性（同步） | `audit:verify` |
| POST | `/api/v1/audit/integrity-check` | 触发后台完整性检查任务（异步） | `audit:admin` |
| GET | `/api/v1/audit/integrity-check/:jobId` | 查询检查任务状态 | `audit:admin` |

---

## 接口详情

### GET /api/v1/audit/logs

查询审计日志列表。

#### 请求参数（Query）

```typescript
interface QueryAuditLogDto {
  // 时间范围（跨度最大 90 天）
  startDate?: string;      // ISO 8601 格式
  endDate?: string;        // ISO 8601 格式
  
  // 过滤条件
  userId?: string;         // 操作用户 ID
  module?: AuditModule;    // 模块名称（推荐枚举，见下方说明）
  action?: AuditAction;    // 操作类型（枚举）
  entityType?: string;     // 实体类型
  entityId?: string;       // 实体 ID
  status?: AuditStatus;    // 操作状态
  isFinancial?: boolean;   // 是否财务操作
  isSensitive?: boolean;   // 是否敏感操作
  riskLevel?: RiskLevel;   // 风险级别
  complianceLevel?: ComplianceLevel; // 合规级别
  
  // 关键词搜索（在 what、why、user.username 中模糊搜索）
  keyword?: string;
  
  // 排序
  sortBy?: 'when' | 'module' | 'action' | 'userId';
  sortOrder?: 'asc' | 'desc';
  
  // 分页
  page?: number;           // 默认 1
  limit?: number;          // 默认 50，最大 200
}
```

#### 约束说明

- `startDate` 和 `endDate` 之间跨度最大为 **90 天**，超出返回 `AUDIT_QUERY_TIME_RANGE_TOO_LARGE`
- 默认排序：`when` 字段按**降序**排列（最近的操作在最前）
- `limit` 最大值为 200

#### keyword 搜索说明

`keyword` 参数会在以下字段中进行**模糊搜索**（ILIKE）：

| 搜索字段 | 说明 | 示例 |
|---------|------|------|
| `what` | 操作描述 | "创建用户"、"修改密码" |
| `why` | 操作原因/备注 | "新员工入职"、"权限调整" |
| `user.username` | 操作人用户名 | "zhangsan"、"admin" |

**前端建议**：提供搜索框让用户输入关键词，可同时匹配操作内容和操作人。

#### 响应

```typescript
interface AuditLogListResponse {
  success: true;
  data: {
    items: AuditLogItem[];
    total: number;
    page: number;
    limit: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
  timestamp: string;
  path: string;
}

interface AuditLogItem {
  id: string;
  region: string;
  tenantId: string;
  
  // 5W1H
  who: string;
  what: string;
  when: string;           // ISO 8601
  where: string;          // IP 地址
  why?: string;
  how: string;            // API / UI / CLI / SYSTEM
  
  // 操作详情
  module: string;
  action: AuditAction;
  entityType: string;
  entityId: string;
  
  // 状态
  status: AuditStatus;
  duration?: number;      // 执行耗时(ms)
  
  // 合规信息
  riskLevel: RiskLevel;
  complianceLevel: ComplianceLevel;
  isFinancial: boolean;
  isSensitive: boolean;
  
  // 操作用户
  user?: {
    id: string;
    username: string;
    displayName?: string;
  };
}
```

#### 示例

**请求**

```bash
curl -X GET 'http://localhost:3001/api/v1/audit/logs?page=1&limit=20&module=User&startDate=2025-12-01T00:00:00.000Z&endDate=2025-12-07T23:59:59.999Z' \
  -H 'Authorization: Bearer <token>'
```

**响应**

```json
{
  "success": true,
  "data": {
    "items": [
      {
        "id": "audit-001",
        "region": "cn",
        "tenantId": "tenant-001",
        "who": "zhangsan",
        "what": "创建用户",
        "when": "2025-12-07T10:30:00.123Z",
        "where": "192.168.1.100",
        "why": "新员工入职",
        "how": "API",
        "module": "User",
        "action": "CREATE",
        "entityType": "User",
        "entityId": "user-002",
        "status": "SUCCESS",
        "duration": 234,
        "riskLevel": "MEDIUM",
        "complianceLevel": "MEDIUM",
        "isFinancial": false,
        "isSensitive": false,
        "user": {
          "id": "user-001",
          "username": "zhangsan",
          "displayName": "张三"
        }
      }
    ],
    "total": 1234,
    "page": 1,
    "limit": 20,
    "totalPages": 62,
    "hasNext": true,
    "hasPrev": false
  },
  "timestamp": "2025-12-07T10:35:00.000Z",
  "path": "/api/v1/audit/logs"
}
```

---

### GET /api/v1/audit/logs/:id

获取单条审计日志详情。

#### 路径参数

| 参数 | 类型 | 必需 | 说明 |
|------|------|------|------|
| id | string | 是 | 审计日志 ID |

#### 响应

```typescript
interface AuditLogDetailResponse {
  success: true;
  data: AuditLogDetail;
  timestamp: string;
  path: string;
}

interface AuditLogDetail extends AuditLogItem {
  // 变更内容（详情接口返回）
  oldValue?: Record<string, any>;
  newValue?: Record<string, any>;
  changes?: ChangeDetail[];
  
  // 上下文信息
  sessionId: string;
  traceId: string;
  requestId: string;
  
  // 环境信息
  ipAddress: string;
  userAgent: string;
  deviceId?: string;
  geoLocation?: string;
  
  // 错误信息（如果失败）
  errorMessage?: string;
  
  // 完整性信息
  previousHash?: string;
  currentHash: string;
  
  // 元数据
  createdAt: string;
  retentionYears: number;
}

interface ChangeDetail {
  field: string;
  from: any;
  to: any;
}
```

#### 示例

**请求**

```bash
curl -X GET 'http://localhost:3001/api/v1/audit/logs/audit-001' \
  -H 'Authorization: Bearer <token>'
```

**响应**

```json
{
  "success": true,
  "data": {
    "id": "audit-001",
    "region": "cn",
    "tenantId": "tenant-001",
    "who": "zhangsan",
    "what": "更新用户邮箱",
    "when": "2025-12-07T10:30:00.123Z",
    "where": "192.168.1.100",
    "why": "用户申请变更",
    "how": "API",
    "module": "User",
    "action": "UPDATE",
    "entityType": "User",
    "entityId": "user-002",
    "status": "SUCCESS",
    "duration": 234,
    "riskLevel": "MEDIUM",
    "complianceLevel": "MEDIUM",
    "isFinancial": false,
    "isSensitive": false,
    "oldValue": {
      "email": "old@example.com"
    },
    "newValue": {
      "email": "new@example.com"
    },
    "changes": [
      {
        "field": "email",
        "from": "old@example.com",
        "to": "new@example.com"
      }
    ],
    "sessionId": "session-abc",
    "traceId": "trace-xyz",
    "requestId": "req-123",
    "ipAddress": "192.168.1.100",
    "userAgent": "Mozilla/5.0...",
    "previousHash": "abc123...",
    "currentHash": "def456...",
    "createdAt": "2025-12-07T10:30:00.123Z",
    "retentionYears": 3,
    "user": {
      "id": "user-001",
      "username": "zhangsan",
      "displayName": "张三"
    }
  },
  "timestamp": "2025-12-07T10:35:00.000Z",
  "path": "/api/v1/audit/logs/audit-001"
}
```

---

### GET /api/v1/audit/entity/:type/:id

获取指定实体的审计历史（时间线视图）。

#### 路径参数

| 参数 | 类型 | 必需 | 说明 |
|------|------|------|------|
| type | string | 是 | 实体类型（User, Form, Approval 等） |
| id | string | 是 | 实体 ID |

#### 请求参数（Query）

```typescript
interface EntityAuditQuery {
  page?: number;           // 默认 1
  limit?: number;          // 默认 50
  includeDiff?: boolean;   // 是否返回详细 changes diff，默认 true
}
```

#### 排序说明

- 默认按 `when` **升序**排列（时间线视图，从早到晚）

#### 响应

```typescript
interface EntityAuditResponse {
  success: true;
  data: {
    entityType: string;
    entityId: string;
    history: EntityAuditItem[];
    total: number;
    page: number;
    limit: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
  timestamp: string;
  path: string;
}

interface EntityAuditItem {
  id: string;
  action: AuditAction;
  when: string;
  who: string;
  oldValue?: Record<string, any>;
  newValue?: Record<string, any>;
  changes?: ChangeDetail[];
  status: AuditStatus;
  user?: {
    id: string;
    username: string;
    displayName?: string;
  };
}
```

#### 示例

**请求**

```bash
curl -X GET 'http://localhost:3001/api/v1/audit/entity/User/user-001?includeDiff=true' \
  -H 'Authorization: Bearer <token>'
```

**响应**

```json
{
  "success": true,
  "data": {
    "entityType": "User",
    "entityId": "user-001",
    "history": [
      {
        "id": "audit-001",
        "action": "CREATE",
        "when": "2025-12-01T10:00:00.000Z",
        "who": "hr-admin",
        "newValue": {
          "username": "zhangsan",
          "email": "old@example.com"
        },
        "status": "SUCCESS",
        "user": {
          "id": "user-hr",
          "username": "hr-admin",
          "displayName": "HR 管理员"
        }
      },
      {
        "id": "audit-003",
        "action": "UPDATE",
        "when": "2025-12-07T14:00:00.000Z",
        "who": "admin",
        "changes": [
          {
            "field": "email",
            "from": "old@example.com",
            "to": "new@example.com"
          }
        ],
        "status": "SUCCESS",
        "user": {
          "id": "user-admin",
          "username": "admin",
          "displayName": "系统管理员"
        }
      }
    ],
    "total": 2,
    "page": 1,
    "limit": 50,
    "totalPages": 1,
    "hasNext": false,
    "hasPrev": false
  },
  "timestamp": "2025-12-07T15:00:00.000Z",
  "path": "/api/v1/audit/entity/User/user-001"
}
```

---

### GET /api/v1/audit/user/:userId

获取指定用户的操作历史。

#### 路径参数

| 参数 | 类型 | 必需 | 说明 |
|------|------|------|------|
| userId | string | 是 | 用户 ID |

#### 请求参数（Query）

```typescript
interface UserAuditQuery {
  startDate?: string;
  endDate?: string;
  module?: string;
  action?: AuditAction;
  isSensitive?: boolean;   // 筛选敏感操作
  isFinancial?: boolean;   // 筛选财务操作
  riskLevel?: RiskLevel;
  page?: number;
  limit?: number;
}
```

#### 响应

```typescript
interface UserAuditResponse {
  success: true;
  data: {
    userId: string;
    username: string;
    displayName?: string;
    operations: UserOperationItem[];
    summary: UserOperationSummary;
    total: number;
    page: number;
    limit: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
  timestamp: string;
  path: string;
}

interface UserOperationItem {
  id: string;
  action: AuditAction;
  module: string;
  when: string;
  entityType: string;
  entityId: string;
  what: string;
  status: AuditStatus;
  riskLevel: RiskLevel;
  isFinancial: boolean;
  isSensitive: boolean;
}

interface UserOperationSummary {
  total: number;
  byAction: Record<AuditAction, number>;
  byModule: Record<string, number>;
  sensitiveCount: number;
  financialCount: number;
  failedCount: number;
}
```

#### 示例

**请求**

```bash
curl -X GET 'http://localhost:3001/api/v1/audit/user/user-001?isSensitive=true&riskLevel=HIGH' \
  -H 'Authorization: Bearer <token>'
```

**响应**

```json
{
  "success": true,
  "data": {
    "userId": "user-001",
    "username": "zhangsan",
    "displayName": "张三",
    "operations": [
      {
        "id": "audit-005",
        "action": "PASSWORD_CHANGE",
        "module": "User",
        "when": "2025-12-07T15:00:00.000Z",
        "entityType": "User",
        "entityId": "user-001",
        "what": "修改密码",
        "status": "SUCCESS",
        "riskLevel": "HIGH",
        "isFinancial": false,
        "isSensitive": true
      }
    ],
    "summary": {
      "total": 150,
      "byAction": {
        "CREATE": 30,
        "UPDATE": 80,
        "DELETE": 10,
        "APPROVE": 25,
        "PASSWORD_CHANGE": 5
      },
      "byModule": {
        "User": 50,
        "Approval": 60,
        "Form": 40
      },
      "sensitiveCount": 5,
      "financialCount": 12,
      "failedCount": 3
    },
    "total": 1,
    "page": 1,
    "limit": 50,
    "totalPages": 1,
    "hasNext": false,
    "hasPrev": false
  },
  "timestamp": "2025-12-07T16:00:00.000Z",
  "path": "/api/v1/audit/user/user-001"
}
```

---

### GET /api/v1/audit/financial

获取财务操作日志。

#### 请求参数（Query）

```typescript
interface FinancialAuditQuery {
  startDate: string;       // 必需，ISO 8601
  endDate: string;         // 必需，ISO 8601（跨度最大 1 年）
  userId?: string;
  action?: AuditAction;    // PAYMENT, REFUND, INVOICE_GENERATE 等
  module?: string;
  page?: number;
  limit?: number;
  sortBy?: 'when' | 'module' | 'action' | 'userId';
  sortOrder?: 'asc' | 'desc';
}
```

#### 约束说明

- `startDate` 和 `endDate` **必填**
- 时间跨度最大 **1 年**（365 天）
- 接口**自动过滤** `isFinancial = true` 的记录

#### 响应

```typescript
interface FinancialAuditResponse {
  success: true;
  data: {
    items: FinancialAuditItem[];
    summary: FinancialSummary;
    total: number;
    page: number;
    limit: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
  timestamp: string;
  path: string;
}

interface FinancialAuditItem extends AuditLogItem {
  oldValue?: Record<string, any>;
  newValue?: Record<string, any>;
  retentionYears: number;  // 保留年限（财务操作为 7 年）
}

interface FinancialSummary {
  total: number;
  byAction: Record<AuditAction, number>;
  byModule: Record<string, number>;
}
```

#### 示例

**请求**

```bash
curl -X GET 'http://localhost:3001/api/v1/audit/financial?startDate=2025-01-01T00:00:00.000Z&endDate=2025-12-31T23:59:59.999Z' \
  -H 'Authorization: Bearer <token>'
```

**响应**

```json
{
  "success": true,
  "data": {
    "items": [
      {
        "id": "audit-010",
        "region": "cn",
        "tenantId": "tenant-001",
        "who": "finance-admin",
        "what": "执行付款",
        "when": "2025-12-07T10:00:00.000Z",
        "where": "192.168.1.50",
        "how": "API",
        "module": "Payment",
        "action": "PAYMENT",
        "entityType": "Payment",
        "entityId": "payment-001",
        "status": "SUCCESS",
        "duration": 500,
        "riskLevel": "HIGH",
        "complianceLevel": "HIGH",
        "isFinancial": true,
        "isSensitive": true,
        "oldValue": { "status": "PENDING" },
        "newValue": { "status": "COMPLETED", "amount": 10000 },
        "retentionYears": 7
      }
    ],
    "summary": {
      "total": 50,
      "byAction": {
        "PAYMENT": 30,
        "REFUND": 5,
        "INVOICE_GENERATE": 15
      },
      "byModule": {
        "Payment": 35,
        "Invoice": 15
      }
    },
    "total": 50,
    "page": 1,
    "limit": 50,
    "totalPages": 1,
    "hasNext": false,
    "hasPrev": false
  },
  "timestamp": "2025-12-07T11:00:00.000Z",
  "path": "/api/v1/audit/financial"
}
```

---

### GET /api/v1/audit/sensitive

获取敏感操作日志。

#### 请求参数（Query）

```typescript
interface SensitiveAuditQuery {
  startDate?: string;
  endDate?: string;
  userId?: string;
  action?: AuditAction;    // PASSWORD_CHANGE, ROLE_CHANGE, PERMISSION_CHANGE 等
  riskLevel?: RiskLevel;
  page?: number;
  limit?: number;
}
```

#### 字段来源说明

> 响应字段来源于 `SensitiveOperationLog` 表，字段可能随安全策略扩展（如 IP、设备信息、地理位置、MFA 状态等）。

#### 响应

```typescript
interface SensitiveAuditResponse {
  success: true;
  data: {
    items: SensitiveAuditItem[];
    total: number;
    page: number;
    limit: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
  timestamp: string;
  path: string;
}

interface SensitiveAuditItem extends AuditLogItem {
  // 敏感操作特有字段
  mfaVerified: boolean;        // 是否通过 MFA 验证
  deviceId?: string;           // 设备 ID
  geoLocation?: string;        // 地理位置
  requiresApproval: boolean;   // 是否需要审批
  approvedBy?: string;         // 批准人 ID
  approvalTime?: string;       // 批准时间
}
```

#### 示例

**请求**

```bash
curl -X GET 'http://localhost:3001/api/v1/audit/sensitive?riskLevel=HIGH' \
  -H 'Authorization: Bearer <token>'
```

**响应**

```json
{
  "success": true,
  "data": {
    "items": [
      {
        "id": "audit-020",
        "region": "cn",
        "tenantId": "tenant-001",
        "who": "user-001",
        "what": "修改密码",
        "when": "2025-12-07T11:00:00.000Z",
        "where": "192.168.1.100",
        "how": "UI",
        "module": "User",
        "action": "PASSWORD_CHANGE",
        "entityType": "User",
        "entityId": "user-001",
        "status": "SUCCESS",
        "riskLevel": "HIGH",
        "complianceLevel": "HIGH",
        "isFinancial": false,
        "isSensitive": true,
        "mfaVerified": true,
        "deviceId": "device-abc123",
        "geoLocation": "Shanghai, China",
        "requiresApproval": false
      }
    ],
    "total": 20,
    "page": 1,
    "limit": 50,
    "totalPages": 1,
    "hasNext": false,
    "hasPrev": false
  },
  "timestamp": "2025-12-07T12:00:00.000Z",
  "path": "/api/v1/audit/sensitive"
}
```

---

### GET /api/v1/audit/trace/:traceId

按追踪 ID 获取请求链路（用于问题排查）。

#### 路径参数

| 参数 | 类型 | 必需 | 说明 |
|------|------|------|------|
| traceId | string | 是 | 追踪 ID |

#### 字段来源说明

> 此接口为排查用途，仅返回与链路相关的**最小字段集合**，不暴露具体业务数据。`developer` 角色调用时不返回 `oldValue` / `newValue` 字段。

#### 响应

```typescript
interface TraceAuditResponse {
  success: true;
  data: {
    traceId: string;
    logs: TraceLogItem[];
    totalDuration: number;  // 链路总耗时(ms)
  };
  timestamp: string;
  path: string;
}

interface TraceLogItem {
  id: string;
  action: AuditAction;
  module: string;
  when: string;
  duration: number;
  status: AuditStatus;
  errorMessage?: string;
}
```

#### 示例

**请求**

```bash
curl -X GET 'http://localhost:3001/api/v1/audit/trace/trace-xyz-123' \
  -H 'Authorization: Bearer <token>'
```

**响应**

```json
{
  "success": true,
  "data": {
    "traceId": "trace-xyz-123",
    "logs": [
      {
        "id": "audit-001",
        "action": "CREATE",
        "module": "Approval",
        "when": "2025-12-07T10:00:00.000Z",
        "duration": 10,
        "status": "SUCCESS"
      },
      {
        "id": "audit-002",
        "action": "APPROVE",
        "module": "Approval",
        "when": "2025-12-07T10:00:00.100Z",
        "duration": 15,
        "status": "SUCCESS"
      }
    ],
    "totalDuration": 25
  },
  "timestamp": "2025-12-07T10:05:00.000Z",
  "path": "/api/v1/audit/trace/trace-xyz-123"
}
```

---

### POST /api/v1/audit/statistics

获取统计分析数据。

#### 请求体

```typescript
interface AuditStatisticsRequest {
  startDate: string;        // 必需，ISO 8601
  endDate: string;          // 必需，ISO 8601
  
  // 可选过滤
  module?: string;
  userId?: string;
  
  // 预留字段（当前忽略，返回所有维度）
  groupBy?: 'day' | 'module' | 'action' | 'user';
}
```

#### 说明

- `groupBy` 为预留字段，当前版本**返回所有维度统计**（byModule/byAction/byDay）
- 未来 v2 版本可能按 `groupBy` 返回单一维度

#### 响应

```typescript
interface AuditStatisticsResponse {
  success: true;
  data: {
    period: {
      start: string;
      end: string;
    };
    summary: StatisticsSummary;
    byModule: ModuleCount[];
    byAction: ActionCount[];
    byDay: DayCount[];
    byUser?: UserCount[];  // 仅 admin/auditor 可见
  };
  timestamp: string;
  path: string;
}

interface StatisticsSummary {
  total: number;
  success: number;
  failed: number;
  financial: number;
  sensitive: number;
}

interface ModuleCount {
  module: string;
  count: number;
  successRate: number;  // 成功率百分比
}

interface ActionCount {
  action: AuditAction;
  count: number;
}

interface DayCount {
  date: string;  // YYYY-MM-DD
  count: number;
}

interface UserCount {
  userId: string;
  username: string;
  count: number;
}
```

#### 示例

**请求**

```bash
curl -X POST 'http://localhost:3001/api/v1/audit/statistics' \
  -H 'Authorization: Bearer <token>' \
  -H 'Content-Type: application/json' \
  -d '{
    "startDate": "2025-12-01T00:00:00.000Z",
    "endDate": "2025-12-07T23:59:59.999Z"
  }'
```

**响应**

```json
{
  "success": true,
  "data": {
    "period": {
      "start": "2025-12-01T00:00:00.000Z",
      "end": "2025-12-07T23:59:59.999Z"
    },
    "summary": {
      "total": 15230,
      "success": 15100,
      "failed": 130,
      "financial": 450,
      "sensitive": 89
    },
    "byModule": [
      { "module": "User", "count": 5000, "successRate": 99.2 },
      { "module": "Approval", "count": 3500, "successRate": 98.5 },
      { "module": "Form", "count": 4000, "successRate": 99.8 }
    ],
    "byAction": [
      { "action": "CREATE", "count": 2000 },
      { "action": "UPDATE", "count": 8000 },
      { "action": "APPROVE", "count": 3000 },
      { "action": "DELETE", "count": 500 }
    ],
    "byDay": [
      { "date": "2025-12-01", "count": 2000 },
      { "date": "2025-12-02", "count": 2500 },
      { "date": "2025-12-03", "count": 2100 },
      { "date": "2025-12-04", "count": 2300 },
      { "date": "2025-12-05", "count": 2400 },
      { "date": "2025-12-06", "count": 1930 },
      { "date": "2025-12-07", "count": 2000 }
    ]
  },
  "timestamp": "2025-12-07T16:00:00.000Z",
  "path": "/api/v1/audit/statistics"
}
```

---

### POST /api/v1/audit/verify-integrity

即时验证指定时间段的审计日志完整性（同步执行）。

#### 请求体

```typescript
interface IntegrityVerifyRequest {
  startDate?: string;  // ISO 8601，默认 7 天前
  endDate?: string;    // ISO 8601，默认当前时间
}
```

#### 约束说明

- 时间范围过大时可能超时（504），建议 ≤ 30 天
- 大范围检查请使用 `/integrity-check` 异步接口

#### 响应

```typescript
interface IntegrityVerifyResponse {
  success: true;
  data: {
    verified: boolean;        // 是否通过验证
    totalRecords: number;     // 检查的记录数
    passCount: number;        // 通过数
    failCount: number;        // 失败数
    failures: IntegrityFailure[];  // 失败详情
    verifiedAt: string;       // 验证时间
    duration: number;         // 验证耗时(ms)
  };
  timestamp: string;
  path: string;
}

interface IntegrityFailure {
  logId: string;
  type: 'HASH_CHAIN_BROKEN' | 'HASH_MISMATCH' | 'INVALID_GENESIS' | 'SIGNATURE_INVALID';
  message: string;
  expectedHash?: string;  // HASH_CHAIN_BROKEN / HASH_MISMATCH / INVALID_GENESIS 提供
  actualHash?: string;    // HASH_CHAIN_BROKEN / HASH_MISMATCH / INVALID_GENESIS 提供
}
```

#### 示例

**请求**

```bash
curl -X POST 'http://localhost:3001/api/v1/audit/verify-integrity' \
  -H 'Authorization: Bearer <token>' \
  -H 'Content-Type: application/json' \
  -d '{
    "startDate": "2025-12-01T00:00:00.000Z",
    "endDate": "2025-12-07T23:59:59.999Z"
  }'
```

**成功响应**

```json
{
  "success": true,
  "data": {
    "verified": true,
    "totalRecords": 15230,
    "passCount": 15230,
    "failCount": 0,
    "failures": [],
    "verifiedAt": "2025-12-07T16:00:00.000Z",
    "duration": 3456
  },
  "timestamp": "2025-12-07T16:00:03.456Z",
  "path": "/api/v1/audit/verify-integrity"
}
```

**失败响应**

```json
{
  "success": true,
  "data": {
    "verified": false,
    "totalRecords": 15230,
    "passCount": 15228,
    "failCount": 2,
    "failures": [
      {
        "logId": "audit-1234",
        "type": "HASH_CHAIN_BROKEN",
        "message": "Hash chain broken between audit-1233 and audit-1234",
        "expectedHash": "abc123...",
        "actualHash": "xyz789..."
      },
      {
        "logId": "audit-5678",
        "type": "HASH_MISMATCH",
        "message": "Calculated hash does not match stored hash",
        "expectedHash": "def456...",
        "actualHash": "uvw012..."
      }
    ],
    "verifiedAt": "2025-12-07T16:00:00.000Z",
    "duration": 3456
  },
  "timestamp": "2025-12-07T16:00:03.456Z",
  "path": "/api/v1/audit/verify-integrity"
}
```

---

### POST /api/v1/audit/integrity-check

触发后台完整性检查任务（异步执行）。

#### 请求体

```typescript
interface IntegrityCheckRequest {
  startDate?: string;      // ISO 8601
  endDate?: string;        // ISO 8601
  scope?: 'ALL' | 'FINANCIAL_ONLY';  // 检查范围，默认 ALL
}
```

#### 响应

```typescript
interface IntegrityCheckResponse {
  success: true;
  data: {
    jobId: string;
    status: 'QUEUED' | 'RUNNING' | 'COMPLETED' | 'FAILED';
    createdAt: string;
    estimatedDuration?: number;  // 预估耗时(秒)
  };
  message: string;
  timestamp: string;
  path: string;
}
```

#### 示例

**请求**

```bash
curl -X POST 'http://localhost:3001/api/v1/audit/integrity-check' \
  -H 'Authorization: Bearer <token>' \
  -H 'Content-Type: application/json' \
  -d '{
    "scope": "FINANCIAL_ONLY"
  }'
```

**响应**

```json
{
  "success": true,
  "data": {
    "jobId": "check-job-001",
    "status": "QUEUED",
    "createdAt": "2025-12-07T16:00:00.000Z",
    "estimatedDuration": 300
  },
  "message": "完整性检查任务已排队",
  "timestamp": "2025-12-07T16:00:00.000Z",
  "path": "/api/v1/audit/integrity-check"
}
```

---

### GET /api/v1/audit/integrity-check/:jobId

查询完整性检查任务状态。

#### 路径参数

| 参数 | 类型 | 必需 | 说明 |
|------|------|------|------|
| jobId | string | 是 | 任务 ID |

#### 响应

```typescript
interface IntegrityCheckJobResponse {
  success: true;
  data: {
    jobId: string;
    status: 'QUEUED' | 'RUNNING' | 'COMPLETED' | 'FAILED';
    createdAt: string;
    startedAt?: string;
    completedAt?: string;
    result?: {
      verified: boolean;
      totalRecords: number;
      passCount: number;
      failCount: number;
      failures?: IntegrityFailure[];
    };
    error?: string;
  };
  timestamp: string;
  path: string;
}
```

#### 示例

**请求**

```bash
curl -X GET 'http://localhost:3001/api/v1/audit/integrity-check/check-job-001' \
  -H 'Authorization: Bearer <token>'
```

**响应（已完成）**

```json
{
  "success": true,
  "data": {
    "jobId": "check-job-001",
    "status": "COMPLETED",
    "createdAt": "2025-12-07T16:00:00.000Z",
    "startedAt": "2025-12-07T16:00:05.000Z",
    "completedAt": "2025-12-07T16:05:30.000Z",
    "result": {
      "verified": true,
      "totalRecords": 150000,
      "passCount": 150000,
      "failCount": 0
    }
  },
  "timestamp": "2025-12-07T16:10:00.000Z",
  "path": "/api/v1/audit/integrity-check/check-job-001"
}
```

---

### POST /api/v1/audit/export

导出审计日志。

#### 请求体

```typescript
interface AuditExportRequest {
  startDate: string;       // 必需，ISO 8601
  endDate: string;         // 必需，ISO 8601
  format: 'csv' | 'excel' | 'json';
  
  filters?: {
    userId?: string;
    module?: string;
    action?: AuditAction;
    entityType?: string;
    isFinancial?: boolean;
    isSensitive?: boolean;
    riskLevel?: RiskLevel;
    status?: AuditStatus;
  };
  
  // 导出字段选择（可选，默认导出所有标准字段）
  fields?: string[];
}
```

#### 约束说明

- 预估导出条数超过 **10 万条**时，返回 `AUDIT_EXPORT_TOO_LARGE`
- 建议调用方缩小时间范围或增加过滤条件
- **未来方向**: 将提供异步导出接口 `/api/v1/audit/export/jobs`

#### 响应

**成功时返回文件流**：
- `Content-Type`: `application/octet-stream` (csv/json) 或 `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` (excel)
- `Content-Disposition`: `attachment; filename="audit-logs-2025-12-07.csv"`

**超出限制时返回错误**：

```json
{
  "success": false,
  "error": {
    "code": "AUDIT_EXPORT_TOO_LARGE",
    "message": "导出数据量过大，预估 150000 条，超过限制 100000 条",
    "details": {
      "estimatedCount": 150000,
      "maxAllowed": 100000
    }
  },
  "timestamp": "2025-12-07T16:00:00.000Z",
  "path": "/api/v1/audit/export",
  "method": "POST",
  "statusCode": 400
}
```

#### 示例

**请求**

```bash
curl -X POST 'http://localhost:3001/api/v1/audit/export' \
  -H 'Authorization: Bearer <token>' \
  -H 'Content-Type: application/json' \
  -d '{
    "startDate": "2025-01-01T00:00:00.000Z",
    "endDate": "2025-03-31T23:59:59.999Z",
    "format": "excel",
    "filters": {
      "isFinancial": true
    }
  }' \
  -o audit-financial-q1.xlsx
```

---

## 错误码

### 通用错误码

| 错误码 | HTTP 状态 | 说明 |
|--------|----------|------|
| `UNAUTHORIZED` | 401 | 未认证或 Token 过期 |
| `FORBIDDEN` | 403 | 无权限访问 |
| `NOT_FOUND` | 404 | 资源不存在 |
| `VALIDATION_ERROR` | 400 | 请求参数验证失败 |
| `INTERNAL_SERVER_ERROR` | 500 | 服务器内部错误 |
| `GATEWAY_TIMEOUT` | 504 | 请求超时 |

### 审计系统专用错误码

| 错误码 | HTTP 状态 | 说明 |
|--------|----------|------|
| `AUDIT_PERMISSION_DENIED` | 403 | 无审计查询权限 |
| `AUDIT_LOG_NOT_FOUND` | 404 | 审计日志不存在 |
| `AUDIT_QUERY_INVALID_PARAMS` | 400 | 查询参数无效 |
| `AUDIT_QUERY_TIME_RANGE_TOO_LARGE` | 400 | 时间范围过大（最大 90 天） |
| `AUDIT_EXPORT_TOO_LARGE` | 400 | 导出数据量过大（超过 10 万条） |
| `AUDIT_INTEGRITY_CHECK_IN_PROGRESS` | 409 | 完整性检查正在进行中 |
| `AUDIT_INTEGRITY_CHECK_NOT_FOUND` | 404 | 完整性检查任务不存在 |

### 错误响应示例

**400 - 验证错误**

```json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "请求参数验证失败",
    "errors": [
      {
        "field": "startDate",
        "message": "startDate 必须是有效的 ISO 8601 日期格式",
        "value": "invalid-date",
        "constraint": "isISO8601"
      }
    ]
  },
  "timestamp": "2025-12-07T10:30:00.000Z",
  "path": "/api/v1/audit/logs",
  "method": "GET",
  "statusCode": 400
}
```

**403 - 权限不足**

```json
{
  "success": false,
  "error": {
    "code": "AUDIT_PERMISSION_DENIED",
    "message": "无权限查询财务审计日志",
    "details": "需要 audit:read:financial 权限"
  },
  "timestamp": "2025-12-07T10:30:00.000Z",
  "path": "/api/v1/audit/financial",
  "method": "GET",
  "statusCode": 403
}
```

**404 - 资源不存在**

```json
{
  "success": false,
  "error": {
    "code": "AUDIT_LOG_NOT_FOUND",
    "message": "审计日志不存在",
    "details": "审计日志 ID 'audit-xyz' 不存在"
  },
  "timestamp": "2025-12-07T10:30:00.000Z",
  "path": "/api/v1/audit/logs/audit-xyz",
  "method": "GET",
  "statusCode": 404
}
```

---

## 数据模型

### AuditModule 推荐枚举

> **说明**: `module` 字段为字符串类型，以下为推荐值。业务模块可按需扩展，但建议使用统一的 PascalCase 命名。

```typescript
// 推荐模块枚举（非强制，可扩展）
type AuditModule = 
  // 用户与权限
  | 'User'           // 用户管理
  | 'Role'           // 角色管理
  | 'Permission'     // 权限管理
  | 'Session'        // 会话管理
  
  // 组织架构
  | 'Department'     // 部门管理
  | 'Position'       // 职位管理
  | 'Employee'       // 员工管理
  
  // 表单与审批
  | 'Form'           // 表单管理
  | 'FormDefinition' // 表单定义
  | 'FormInstance'   // 表单实例
  | 'Approval'       // 审批流程
  | 'ApprovalTask'   // 审批任务
  
  // 财务相关
  | 'Payment'        // 付款
  | 'Invoice'        // 发票
  | 'Expense'        // 费用报销
  | 'Budget'         // 预算
  
  // 系统管理
  | 'System'         // 系统配置
  | 'Audit'          // 审计日志
  | 'Config'         // 配置项
  | 'Backup'         // 备份
  
  // 其他业务模块（按需扩展）
  | string;          // 允许自定义模块名
```

### AuditAction 枚举

```typescript
enum AuditAction {
  // CRUD 操作
  CREATE = 'CREATE',
  READ = 'READ',
  UPDATE = 'UPDATE',
  DELETE = 'DELETE',
  BULK_UPDATE = 'BULK_UPDATE',
  BULK_DELETE = 'BULK_DELETE',
  
  // 审批操作
  APPROVE = 'APPROVE',
  REJECT = 'REJECT',
  RETURN = 'RETURN',
  FORWARD = 'FORWARD',
  WITHDRAW = 'WITHDRAW',
  
  // 用户操作
  LOGIN = 'LOGIN',
  LOGOUT = 'LOGOUT',
  LOGIN_FAILED = 'LOGIN_FAILED',
  PASSWORD_CHANGE = 'PASSWORD_CHANGE',
  PERMISSION_CHANGE = 'PERMISSION_CHANGE',
  ROLE_CHANGE = 'ROLE_CHANGE',
  
  // 系统操作
  CONFIG_CHANGE = 'CONFIG_CHANGE',
  BACKUP = 'BACKUP',
  RESTORE = 'RESTORE',
  EXPORT = 'EXPORT',
  IMPORT = 'IMPORT',
  
  // 财务操作
  PAYMENT = 'PAYMENT',
  REFUND = 'REFUND',
  INVOICE_GENERATE = 'INVOICE_GENERATE',
  FINANCIAL_CLOSE = 'FINANCIAL_CLOSE',
}
```

### AuditStatus 枚举

```typescript
enum AuditStatus {
  SUCCESS = 'SUCCESS',
  FAILED = 'FAILED',
  PARTIAL = 'PARTIAL',
  PENDING = 'PENDING',
}
```

### RiskLevel 枚举

> **说明**: RiskLevel 表示操作的风险程度，用于告警配置和审计人员关注度。

```typescript
enum RiskLevel {
  HIGH = 'HIGH',      // 高风险：权限变更、财务操作、系统配置、盘点差异
  MEDIUM = 'MEDIUM',  // 中风险：数据创建/修改/删除、审批操作
  LOW = 'LOW',        // 低风险：数据读取、一般查询、草稿保存
}
```

### ComplianceLevel 枚举

> **说明**: ComplianceLevel 决定数据保留年限，与 RiskLevel 独立但通常相关。

```typescript
enum ComplianceLevel {
  HIGH = 'HIGH',      // SOX 高相关：财务、权限、系统配置（保留 7 年）
  MEDIUM = 'MEDIUM',  // 一般业务操作（保留 5 年）
  LOW = 'LOW',        // 低风险操作（保留 3 年）
}
```

### RiskLevel 与 ComplianceLevel 的关系

| RiskLevel | 通常对应的 ComplianceLevel | 说明 |
|-----------|---------------------------|------|
| HIGH | HIGH | 财务、权限变更等高风险操作，需长期保留 |
| MEDIUM | MEDIUM | 一般业务操作，中等保留期 |
| LOW | LOW | 查询、草稿等低风险操作，短期保留 |

> **注意**: 两者独立设置，允许特殊场景（如某些 HIGH 风险操作因业务需要设置为 MEDIUM 保留期）。

---

## DTO 定义

### 请求 DTO

```typescript
// 审计日志查询
class QueryAuditLogDto {
  @IsOptional()
  @IsISO8601()
  startDate?: string;

  @IsOptional()
  @IsISO8601()
  endDate?: string;

  @IsOptional()
  @IsString()
  userId?: string;

  @IsOptional()
  @IsString()
  module?: string;

  @IsOptional()
  @IsEnum(AuditAction)
  action?: AuditAction;

  @IsOptional()
  @IsString()
  entityType?: string;

  @IsOptional()
  @IsString()
  entityId?: string;

  @IsOptional()
  @IsEnum(AuditStatus)
  status?: AuditStatus;

  @IsOptional()
  @IsBoolean()
  @Transform(({ value }) => value === 'true')
  isFinancial?: boolean;

  @IsOptional()
  @IsBoolean()
  @Transform(({ value }) => value === 'true')
  isSensitive?: boolean;

  @IsOptional()
  @IsEnum(RiskLevel)
  riskLevel?: RiskLevel;

  @IsOptional()
  @IsEnum(ComplianceLevel)
  complianceLevel?: ComplianceLevel;

  @IsOptional()
  @IsString()
  keyword?: string;

  @IsOptional()
  @IsIn(['when', 'module', 'action', 'userId'])
  sortBy?: 'when' | 'module' | 'action' | 'userId' = 'when';

  @IsOptional()
  @IsIn(['asc', 'desc'])
  sortOrder?: 'asc' | 'desc' = 'desc';

  @IsOptional()
  @IsInt()
  @Min(1)
  @Transform(({ value }) => parseInt(value, 10))
  page?: number = 1;

  @IsOptional()
  @IsInt()
  @Min(1)
  @Max(200)
  @Transform(({ value }) => parseInt(value, 10))
  limit?: number = 50;
}

// 统计请求
class AuditStatisticsDto {
  @IsISO8601()
  startDate: string;

  @IsISO8601()
  endDate: string;

  @IsOptional()
  @IsString()
  module?: string;

  @IsOptional()
  @IsString()
  userId?: string;

  @IsOptional()
  @IsIn(['day', 'module', 'action', 'user'])
  groupBy?: 'day' | 'module' | 'action' | 'user';
}

// 完整性验证请求
class IntegrityVerifyDto {
  @IsOptional()
  @IsISO8601()
  startDate?: string;

  @IsOptional()
  @IsISO8601()
  endDate?: string;
}

// 导出请求
class AuditExportDto {
  @IsISO8601()
  startDate: string;

  @IsISO8601()
  endDate: string;

  @IsIn(['csv', 'excel', 'json'])
  format: 'csv' | 'excel' | 'json';

  @IsOptional()
  @ValidateNested()
  @Type(() => AuditExportFiltersDto)
  filters?: AuditExportFiltersDto;

  @IsOptional()
  @IsArray()
  @IsString({ each: true })
  fields?: string[];
}

class AuditExportFiltersDto {
  @IsOptional()
  @IsString()
  userId?: string;

  @IsOptional()
  @IsString()
  module?: string;

  @IsOptional()
  @IsEnum(AuditAction)
  action?: AuditAction;

  @IsOptional()
  @IsString()
  entityType?: string;

  @IsOptional()
  @IsBoolean()
  isFinancial?: boolean;

  @IsOptional()
  @IsBoolean()
  isSensitive?: boolean;

  @IsOptional()
  @IsEnum(RiskLevel)
  riskLevel?: RiskLevel;

  @IsOptional()
  @IsEnum(AuditStatus)
  status?: AuditStatus;
}
```

---

## 使用示例

### cURL 示例

```bash
# 查询审计日志
curl -X GET 'http://localhost:3001/api/v1/audit/logs?page=1&limit=20&module=User' \
  -H 'Authorization: Bearer <token>'

# 查询实体历史
curl -X GET 'http://localhost:3001/api/v1/audit/entity/User/user-001?includeDiff=true' \
  -H 'Authorization: Bearer <token>'

# 查询用户操作（筛选敏感操作）
curl -X GET 'http://localhost:3001/api/v1/audit/user/user-001?isSensitive=true&riskLevel=HIGH' \
  -H 'Authorization: Bearer <token>'

# 即时验证完整性
curl -X POST 'http://localhost:3001/api/v1/audit/verify-integrity' \
  -H 'Authorization: Bearer <token>' \
  -H 'Content-Type: application/json' \
  -d '{"startDate": "2025-12-01T00:00:00.000Z", "endDate": "2025-12-07T23:59:59.999Z"}'

# 触发异步完整性检查
curl -X POST 'http://localhost:3001/api/v1/audit/integrity-check' \
  -H 'Authorization: Bearer <token>' \
  -H 'Content-Type: application/json' \
  -d '{"scope": "FINANCIAL_ONLY"}'

# 导出财务日志
curl -X POST 'http://localhost:3001/api/v1/audit/export' \
  -H 'Authorization: Bearer <token>' \
  -H 'Content-Type: application/json' \
  -d '{"startDate": "2025-01-01T00:00:00.000Z", "endDate": "2025-03-31T23:59:59.999Z", "format": "excel", "filters": {"isFinancial": true}}' \
  -o audit-financial-q1.xlsx
```

### TypeScript 客户端示例

```typescript
import apiClient, { ApiClientError } from '@/lib/api-client';

// 查询审计日志
async function getAuditLogs(params: QueryAuditLogDto) {
  try {
    const response = await apiClient.get('/audit/logs', { params });
    return response.items;
  } catch (error) {
    if (error instanceof ApiClientError) {
      if (error.code === 'AUDIT_QUERY_TIME_RANGE_TOO_LARGE') {
        alert('时间范围过大，请缩小到 90 天以内');
      }
    }
    throw error;
  }
}

// 获取实体历史
async function getEntityHistory(type: string, id: string) {
  const response = await apiClient.get(`/audit/entity/${type}/${id}`);
  return response.history;
}

// 验证完整性
async function verifyIntegrity(startDate: string, endDate: string) {
  const response = await apiClient.post('/audit/verify-integrity', {
    startDate,
    endDate,
  });
  
  if (!response.verified) {
    console.error('完整性验证失败:', response.failures);
  }
  
  return response;
}

// 导出审计日志
async function exportAuditLogs(params: AuditExportDto) {
  const response = await apiClient.post('/audit/export', params, {
    responseType: 'blob',
  });
  
  // 创建下载链接
  const url = window.URL.createObjectURL(response);
  const link = document.createElement('a');
  link.href = url;
  link.download = `audit-logs-${new Date().toISOString().split('T')[0]}.${params.format}`;
  link.click();
}
```

---

## 📊 合规报表 API

### POST /api/v1/audit/reports/sox

生成 SOX 合规报表。

**权限**: `audit:report:sox`

**请求参数**:
```typescript
{
  startDate: string;  // ISO 8601
  endDate: string;    // ISO 8601
}
```

**响应示例**:
```json
{
  "success": true,
  "data": {
    "reportType": "SOX_COMPLIANCE",
    "reportPeriod": {
      "start": "2025-01-01T00:00:00.000Z",
      "end": "2025-12-31T23:59:59.999Z"
    },
    "generatedAt": "2025-12-19T11:30:00.000Z",
    "sections": {
      "financialOperations": {
        "totalOperations": 1234,
        "operationsByType": [
          { "action": "PAYMENT", "count": 567 },
          { "action": "REFUND", "count": 123 }
        ],
        "topUsers": [
          { "username": "finance_admin", "operationCount": 456 }
        ]
      },
      "accessControlChanges": {
        "totalChanges": 89,
        "changesByType": {
          "roleAssignments": 45,
          "permissionChanges": 44
        }
      },
      "highRiskOperations": {
        "totalHighRisk": 156,
        "byModule": { "User": 67, "Approval": 89 }
      },
      "integrityChecks": {
        "totalChecks": 365,
        "passedChecks": 365,
        "failedChecks": 0,
        "passRate": 100
      }
    },
    "complianceStatus": {
      "status": "COMPLIANT",
      "summary": "审计日志符合 SOX 合规要求"
    }
  }
}
```

---

### GET /api/v1/audit/reports/gdpr/:userId

生成 GDPR 数据访问报告（数据主体访问请求）。

**权限**: `audit:report:gdpr`

**路径参数**:
- `userId` - 数据主体用户 ID

**响应示例**:
```json
{
  "success": true,
  "data": {
    "reportType": "GDPR_DATA_ACCESS",
    "dataSubject": { "userId": "user-001" },
    "summary": {
      "totalAccesses": 1567,
      "uniqueAccessors": 12
    },
    "accessors": [
      { "username": "hr_manager", "accessCount": 345 },
      { "username": "admin", "accessCount": 123 }
    ],
    "recentAccesses": [...]
  }
}
```

---

### POST /api/v1/audit/reports/anomaly

生成异常操作检测报告。

**权限**: `audit:report:anomaly`

**请求参数**:
```typescript
{
  startDate: string;
  endDate: string;
}
```

**响应示例**:
```json
{
  "success": true,
  "data": {
    "reportType": "ANOMALY_DETECTION",
    "anomalies": {
      "loginFailures": {
        "detected": 3,
        "anomalies": [
          { "username": "user123", "failureCount": 12, "severity": "HIGH" }
        ]
      },
      "bulkOperations": {
        "detected": 2,
        "operations": [...]
      },
      "afterHoursOps": {
        "detected": 15
      }
    },
    "severity": "MEDIUM"
  }
}
```

---

### POST /api/v1/audit/reports/sox/export

导出 SOX 合规报表为 CSV 格式。

**权限**: `audit:report:sox`

**请求参数**: 同 `/reports/sox`

**响应**: CSV 文件下载

---

## 🚨 告警 API

### POST /api/v1/audit/alerts/batch-check

批量检查最近的告警（通常由定时任务调用）。

**权限**: `audit:admin`

**请求参数**:
```typescript
{
  since?: string;  // ISO 8601, 默认: 最近1小时
}
```

**响应示例**:
```json
{
  "success": true,
  "data": {
    "period": {
      "start": "2025-12-19T10:00:00.000Z",
      "end": "2025-12-19T11:00:00.000Z"
    },
    "alertCount": 5,
    "alerts": [
      {
        "userId": "user-001",
        "username": "john_doe",
        "alertType": "CONTINUOUS_FAILURES",
        "severity": "HIGH",
        "count": 7,
        "details": {
          "action": "LOGIN_FAILED",
          "threshold": 5
        }
      }
    ]
  }
}
```

---

### GET /api/v1/audit/alerts/user/:userId

检查特定用户的告警状态。

**权限**: `audit:admin`

**路径参数**:
- `userId` - 用户 ID

**响应示例**:
```json
{
  "success": true,
  "data": {
    "hasActiveAlerts": true,
    "alerts": [
      {
        "type": "OPERATION_SPIKE",
        "description": "今日操作量 150 次，超过平均值 30 次的 3 倍",
        "severity": "MEDIUM"
      }
    ],
    "riskScore": 45
  }
}
```

---

### POST /api/v1/audit/alerts/detect-failures

检测用户连续失败模式。

**权限**: `audit:admin`

**请求参数**:
```typescript
{
  userId: string;
  action: string;      // AuditAction
  timeWindow?: number; // 时间窗口（分钟），默认: 30
}
```

**响应示例**:
```json
{
  "success": true,
  "data": {
    "detected": true,
    "failureCount": 8,
    "shouldLock": true  // 建议锁定账户
  }
}
```

---

### POST /api/v1/audit/alerts/detect-anomaly

检测用户异常操作模式。

**权限**: `audit:admin`

**请求参数**:
```typescript
{
  userId: string;
  days?: number;  // 检测天数，默认: 7
}
```

**响应示例**:
```json
{
  "success": true,
  "data": {
    "detected": true,
    "anomalies": [
      {
        "type": "OPERATION_SPIKE",
        "description": "今日操作量异常",
        "severity": "MEDIUM"
      },
      {
        "type": "HIGH_FAILURE_RATE",
        "description": "失败率 35%，超过 20% 阈值",
        "severity": "HIGH"
      }
    ]
  }
}
```

---

## 📚 API 端点总览

### 原有端点 (12个)
1. `GET /audit/logs` - 查询审计日志
2. `GET /audit/logs/:id` - 获取详情
3. `GET /audit/entity/:type/:id` - 实体历史
4. `GET /audit/user/:userId` - 用户历史
5. `GET /audit/financial` - 财务日志
6. `GET /audit/sensitive` - 敏感日志
7. `GET /audit/trace/:traceId` - 追踪链路
8. `POST /audit/statistics` - 统计分析
9. `POST /audit/verify-integrity` - 即时验证
10. `POST /audit/integrity-check` - 异步检查
11. `GET /audit/integrity-check/:jobId` - 检查状态
12. `POST /audit/export` - 导出日志

### 新增端点 (8个) 🆕
13. `POST /audit/reports/sox` - SOX 合规报表
14. `GET /audit/reports/gdpr/:userId` - GDPR 数据访问报告
15. `POST /audit/reports/anomaly` - 异常检测报告
16. `POST /audit/reports/sox/export` - 导出 SOX 报表 CSV
17. `POST /audit/alerts/batch-check` - 批量告警检查
18. `GET /audit/alerts/user/:userId` - 用户告警状态
19. `POST /audit/alerts/detect-failures` - 检测连续失败
20. `POST /audit/alerts/detect-anomaly` - 检测异常模式

**总计**: 20 个 API 端点

---

## 相关文档

- [审计系统 PRD](PRD.md) - 产品需求文档
- [审计系统架构](ARCHITECTURE.md) - 架构设计
- [配置指南](CONFIGURATION.md) - 环境配置和部署
- [审计系统 TODO](TODO.md) - 开发待办
- [API 规范](../../../docs/standards/API_STANDARDS.md) - FFOA API 规范

---

**文档维护**: FFOA 开发团队  
**更新频率**: API 变更时更新  
**最后更新**: 2025-12-19
