feat: 完善前后端核心功能模块

后端:
- 新增认证(auth)、任务(tasks)、映射(mappings)、对账(reconciliation)、异常(exceptions)、导出(exports) API
- 新增核心模块: database, security, permissions, tenant, exceptions, error_handlers
- 新增数据模型: user, company, reconciliation_task, field_mapping, uploaded_file 等
- 新增服务层: ai_recognizer, file_parser, file_storage, mapping, reconciliation 等
- 添加数据库迁移脚本

前端:
- 新增登录页面和仪表盘页面
- 新增任务列表、任务详情、字段映射页面
- 新增异常处理页面和规则设置页面
- 新增 API 代理路由 /api/[...path]
- 新增 UI 组件库 (button, card, dialog, input, table 等)
- 新增 auth 组件 (ProtectedRoute, PermissionGate)
- 新增 layout 组件 (Header, Sidebar)
- 新增 mapping 组件 (FieldMappingTable, AISuggestionPanel)
- 新增 API 客户端和 hooks (useAsync, useToast, usePermission 等)
- 新增状态管理 (auth-store, company-store, ui-store)
- 集成 Tailwind CSS 和 shadcn/ui 组件库

其他:
- 添加 Alembic 数据库迁移配置
- 添加初始化示例数据脚本
- 更新项目文档
This commit is contained in:
freedakgmail
2026-07-07 09:04:47 +08:00
parent 8487f6eadf
commit 33b4c734aa
117 changed files with 22070 additions and 295 deletions
+122
View File
@@ -0,0 +1,122 @@
import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import type { ApiError, ApiResponse } from './types';
// 创建 Axios 实例
const createApiClient = (): AxiosInstance => {
const baseURL = process.env.NEXT_PUBLIC_API_URL || '';
const instance = axios.create({
baseURL,
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
});
// 请求拦截器
instance.interceptors.request.use(
(config) => {
// 自动添加 JWT Token
if (typeof window !== 'undefined') {
const token = localStorage.getItem('auth_token');
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
// 添加企业 ID
const companyId = localStorage.getItem('company_id');
if (companyId && config.headers) {
config.headers['X-Company-ID'] = companyId;
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 响应拦截器
instance.interceptors.response.use(
(response: AxiosResponse) => {
return response;
},
(error: AxiosError<ApiError>) => {
// 统一错误处理
const apiError: ApiError = {
code: 'UNKNOWN_ERROR',
message: '未知错误',
};
if (error.response) {
// 服务器返回错误
const { data, status } = error.response;
if (data && typeof data === 'object' && 'error' in data) {
const errorData = data as { error: { code: string; message: string; details?: unknown } };
apiError.code = errorData.error.code;
apiError.message = errorData.error.message;
apiError.details = errorData.error.details;
} else {
apiError.code = `HTTP_${status}`;
apiError.message = error.message;
}
// 401 未授权 - 跳转登录
if (status === 401) {
if (typeof window !== 'undefined') {
localStorage.removeItem('auth_token');
localStorage.removeItem('company_id');
window.location.href = '/login';
}
}
} else if (error.request) {
// 请求发送但无响应
apiError.code = 'NETWORK_ERROR';
apiError.message = '网络错误,请检查连接';
} else {
// 其他错误
apiError.message = error.message;
}
return Promise.reject(apiError);
}
);
return instance;
};
// API 客户端单例
export const apiClient = createApiClient();
// 通用请求方法封装
export const api = {
get: async <T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> => {
const response = await apiClient.get<T>(url, config);
return { data: response.data, status: response.status };
},
post: async <T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResponse<T>> => {
const response = await apiClient.post<T>(url, data, config);
return { data: response.data, status: response.status };
},
put: async <T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResponse<T>> => {
const response = await apiClient.put<T>(url, data, config);
return { data: response.data, status: response.status };
},
patch: async <T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResponse<T>> => {
const response = await apiClient.patch<T>(url, data, config);
return { data: response.data, status: response.status };
},
delete: async <T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> => {
const response = await apiClient.delete<T>(url, config);
return { data: response.data, status: response.status };
},
};
export default apiClient;
+96
View File
@@ -0,0 +1,96 @@
/**
* API 端点常量
*/
export const ENDPOINTS = {
// 健康检查
HEALTH: '/api/health',
// 认证相关
AUTH: {
LOGIN: '/api/auth/login',
LOGOUT: '/api/auth/logout',
ME: '/api/auth/me',
REFRESH: '/api/auth/refresh',
},
// 企业相关
COMPANY: {
LIST: '/api/companies',
DETAIL: (id: number | string) => `/api/companies/${id}`,
CREATE: '/api/companies',
UPDATE: (id: number | string) => `/api/companies/${id}`,
DELETE: (id: number | string) => `/api/companies/${id}`,
},
// 用户相关
USER: {
LIST: '/api/users',
DETAIL: (id: number | string) => `/api/users/${id}`,
CREATE: '/api/users',
UPDATE: (id: number | string) => `/api/users/${id}`,
DELETE: (id: number | string) => `/api/users/${id}`,
UPDATE_ROLE: (id: number | string) => `/api/users/${id}/role`,
},
// 文件上传
FILE: {
UPLOAD: '/api/files/upload',
DOWNLOAD: (id: number | string) => `/api/files/${id}/download`,
DELETE: (id: number | string) => `/api/files/${id}`,
},
// 任务相关
TASK: {
LIST: '/api/tasks',
STATS: '/api/tasks/stats',
DETAIL: (id: number | string) => `/api/tasks/${id}`,
CREATE: '/api/tasks',
UPDATE: (id: number | string) => `/api/tasks/${id}`,
DELETE: (id: number | string) => `/api/tasks/${id}`,
RECONCILE: (id: number | string) => `/api/reconciliation/execute/${id}`,
RESULT: (id: number | string) => `/api/reconciliation/result/${id}`,
EXPORT: (id: number | string) => `/api/exports/task/${id}`,
},
// 异常相关
ANOMALY: {
LIST: '/api/anomalies',
DETAIL: (id: number | string) => `/api/anomalies/${id}`,
CONFIRM: (id: number | string) => `/api/anomalies/${id}/confirm`,
IGNORE: (id: number | string) => `/api/anomalies/${id}/ignore`,
},
// 分析相关
ANALYSIS: {
LABOR_COST: (taskId: number | string) => `/api/analysis/labor-cost/${taskId}`,
TREND: '/api/analysis/trend',
SUMMARY: '/api/analysis/summary',
},
// 凭证相关
VOUCHER: {
GENERATE: (taskId: number | string) => `/api/vouchers/generate/${taskId}`,
EXPORT: (taskId: number | string) => `/api/vouchers/export/${taskId}`,
},
// 审计日志
AUDIT: {
LIST: '/api/audit-logs',
},
// 字段映射
MAPPING: {
LIST: '/api/mappings',
TASK_MAPPINGS: (taskId: number | string) => `/api/mappings/task/${taskId}`,
RECOGNIZE: '/api/mappings/recognize',
CONFIRM: '/api/mappings/confirm',
DETAIL: (mappingId: number | string) => `/api/mappings/${mappingId}`,
UPDATE: (mappingId: number | string) => `/api/mappings/${mappingId}`,
SAVE_AS_RULE: (mappingId: number | string) => `/api/mappings/${mappingId}/save-as-rule`,
RULES_LIST: '/api/mappings/rules/list',
RULE_STATUS: (ruleId: number | string) => `/api/mappings/rules/${ruleId}/status`,
RULE_DELETE: (ruleId: number | string) => `/api/mappings/rules/${ruleId}`,
},
} as const;
export default ENDPOINTS;
+133
View File
@@ -0,0 +1,133 @@
/**
* API 响应类型
*/
export interface ApiResponse<T = unknown> {
data: T;
status: number;
}
/**
* API 错误类型
*/
export interface ApiError {
code: string;
message: string;
details?: unknown;
}
/**
* 分页响应类型
*/
export interface PaginatedResponse<T = unknown> {
items: T[];
total: number;
page: number;
page_size: number;
total_pages: number;
}
/**
* 分页请求参数
*/
export interface PaginationParams {
page?: number;
page_size?: number;
}
/**
* 通用 ID 参数
*/
export interface IdParams {
id: number | string;
}
// ===== 字段映射类型 =====
export interface FieldMappingResponse {
id: number;
company_id: number;
file_id: number;
source_field: string;
standard_field: string;
confidence: number;
reasoning?: string;
sample_values?: unknown[];
is_skipped: boolean;
confirmed: boolean;
confirmed_by?: number;
confirmed_at?: string;
}
export interface FileMappingSummary {
file_id: number;
file_type: string;
file_name: string;
total_fields: number;
confirmed_fields: number;
high_confidence: number;
medium_confidence: number;
low_confidence: number;
mappings: FieldMappingResponse[];
}
export interface TaskMappingOverview {
task_id: number;
total_files: number;
total_fields: number;
confirmed_fields: number;
needs_review: boolean;
files: FileMappingSummary[];
}
export interface CompanyRuleResponse {
id: number;
company_id: number;
rule_type: string;
match_condition: Record<string, unknown>;
target_value: string;
priority: number;
status: string;
description?: string;
match_count: number;
last_used_at?: string;
created_at: string;
updated_at: string;
}
export interface ConfirmMappingsRequest {
mapping_ids: number[];
}
export interface ConfirmMappingsResponse {
confirmed_count: number;
mappings: FieldMappingResponse[];
}
export interface SaveAsRuleResponse {
rule_id: number;
source_field: string;
target_field: string;
message: string;
}
// ===== 任务类型 =====
export interface ReconciliationTask {
id: number;
company_id: number;
name: string;
period: string;
status: string;
file_ids?: Record<string, number>;
mapping_completed: boolean;
mapping_confirmed_at?: string;
mapping_confirmed_by?: number;
total_employees?: number;
matched_count?: number;
exception_count?: number;
reconciliation_result?: unknown;
error_message?: string;
created_by?: number;
created_at: string;
updated_at: string;
}
+48
View File
@@ -0,0 +1,48 @@
import { useCallback, useState } from 'react';
/**
* 异步请求状态
*/
export interface AsyncState<T> {
data: T | null;
loading: boolean;
error: Error | null;
}
/**
* 异步请求 Hook
* 用于管理异步请求的加载状态、数据和错误
*/
export function useAsync<T = unknown>() {
const [state, setState] = useState<AsyncState<T>>({
data: null,
loading: false,
error: null,
});
const execute = useCallback(async (asyncFunction: () => Promise<T>) => {
setState({ data: null, loading: true, error: null });
try {
const result = await asyncFunction();
setState({ data: result, loading: false, error: null });
return result;
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
setState({ data: null, loading: false, error: err });
throw err;
}
}, []);
const reset = useCallback(() => {
setState({ data: null, loading: false, error: null });
}, []);
return {
...state,
execute,
reset,
};
}
export default useAsync;
+77
View File
@@ -0,0 +1,77 @@
'use client';
import { useCallback, useState } from 'react';
/**
* 确认对话框配置
*/
export interface ConfirmOptions {
title?: string;
message: string;
confirmText?: string;
cancelText?: string;
type?: 'info' | 'warning' | 'danger';
}
/**
* 确认对话框状态
*/
interface ConfirmState {
isOpen: boolean;
options: ConfirmOptions | null;
resolve: ((value: boolean) => void) | null;
}
/**
* 确认对话框 Hook
* 用于显示确认对话框并等待用户响应
*/
export function useConfirm() {
const [state, setState] = useState<ConfirmState>({
isOpen: false,
options: null,
resolve: null,
});
const confirm = useCallback((options: ConfirmOptions): Promise<boolean> => {
return new Promise((resolve) => {
setState({
isOpen: true,
options: {
title: '确认',
confirmText: '确定',
cancelText: '取消',
type: 'info',
...options,
},
resolve,
});
});
}, []);
const handleConfirm = useCallback(() => {
if (state.resolve) {
state.resolve(true);
}
setState({ isOpen: false, options: null, resolve: null });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state.resolve]);
const handleCancel = useCallback(() => {
if (state.resolve) {
state.resolve(false);
}
setState({ isOpen: false, options: null, resolve: null });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state.resolve]);
return {
confirm,
isOpen: state.isOpen,
options: state.options,
handleConfirm,
handleCancel,
};
}
export default useConfirm;
+69
View File
@@ -0,0 +1,69 @@
import { useCallback, useEffect, useRef, useState } from 'react';
/**
* 防抖 Hook
* 延迟执行函数,直到停止调用一段时间后才执行
*
* @param value - 要防抖的值
* @param delay - 延迟时间(毫秒)
* @returns 防抖后的值
*/
export function useDebounce<T>(value: T, delay: number = 500): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
/**
* 防抖回调 Hook
* 延迟执行回调函数
*
* @param callback - 要防抖的回调函数
* @param delay - 延迟时间(毫秒)
* @returns 防抖后的回调函数
*/
export function useDebouncedCallback<T extends (...args: unknown[]) => unknown>(
callback: T,
delay: number = 500
): (...args: Parameters<T>) => void {
const timeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);
const callbackRef = useRef<T>(callback);
// 保持最新的 callback 引用
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return useCallback(
(...args: Parameters<T>) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
callbackRef.current(...args);
}, delay);
},
[delay]
);
}
export default useDebounce;
+49
View File
@@ -0,0 +1,49 @@
import { useAuthStore } from '@/lib/stores/auth-store';
/**
* 权限检查 Hook
*/
export function usePermission() {
const { user } = useAuthStore();
/**
* 检查用户是否有指定权限
*/
const hasPermission = (permission: string): boolean => {
if (!user) return false;
return user.permissions?.includes(permission) ?? false;
};
/**
* 检查用户是否有指定角色
*/
const hasRole = (role: string): boolean => {
if (!user) return false;
return user.role === role;
};
/**
* 检查用户是否有任一权限
*/
const hasAnyPermission = (permissions: string[]): boolean => {
if (!user) return false;
return permissions.some((permission) => hasPermission(permission));
};
/**
* 检查用户是否拥有所有权限
*/
const hasAllPermissions = (permissions: string[]): boolean => {
if (!user) return false;
return permissions.every((permission) => hasPermission(permission));
};
return {
hasPermission,
hasRole,
hasAnyPermission,
hasAllPermissions,
};
}
export default usePermission;
+90
View File
@@ -0,0 +1,90 @@
'use client';
import { useCallback, useState } from 'react';
/**
* Toast 消息类型
*/
export type ToastType = 'success' | 'error' | 'info' | 'warning';
/**
* Toast 消息接口
*/
export interface Toast {
id: string;
type: ToastType;
message: string;
duration?: number;
}
/**
* Toast Hook
* 用于显示全局通知消息
*/
export function useToast() {
const [toasts, setToasts] = useState<Toast[]>([]);
const removeToast = useCallback((id: string) => {
setToasts((prev) => prev.filter((toast) => toast.id !== id));
}, []);
const addToast = useCallback((type: ToastType, message: string, duration: number = 3000) => {
const id = `toast-${Date.now()}-${Math.random()}`;
const toast: Toast = { id, type, message, duration };
setToasts((prev) => [...prev, toast]);
if (duration > 0) {
setTimeout(() => {
removeToast(id);
}, duration);
}
return id;
}, [removeToast]);
const success = useCallback(
(message: string, duration?: number) => {
return addToast('success', message, duration);
},
[addToast]
);
const error = useCallback(
(message: string, duration?: number) => {
return addToast('error', message, duration);
},
[addToast]
);
const info = useCallback(
(message: string, duration?: number) => {
return addToast('info', message, duration);
},
[addToast]
);
const warning = useCallback(
(message: string, duration?: number) => {
return addToast('warning', message, duration);
},
[addToast]
);
const clear = useCallback(() => {
setToasts([]);
}, []);
return {
toasts,
addToast,
removeToast,
success,
error,
info,
warning,
clear,
};
}
export default useToast;
+92
View File
@@ -0,0 +1,92 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
/**
* 用户信息接口
*/
export interface User {
id: number;
email: string;
full_name: string;
role: string;
permissions: string[];
company_id: number;
}
/**
* 认证状态接口
*/
interface AuthState {
user: User | null;
token: string | null;
isAuthenticated: boolean;
// Actions
login: (user: User, token: string) => void;
logout: () => void;
setUser: (user: User) => void;
updateUser: (userData: Partial<User>) => void;
}
/**
* 认证状态 Store
* 使用 localStorage 持久化
*/
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
user: null,
token: null,
isAuthenticated: false,
login: (user, token) => {
// 保存到 localStorage
if (typeof window !== 'undefined') {
localStorage.setItem('auth_token', token);
localStorage.setItem('company_id', String(user.company_id));
}
set({
user,
token,
isAuthenticated: true,
});
},
logout: () => {
// 清除 localStorage
if (typeof window !== 'undefined') {
localStorage.removeItem('auth_token');
localStorage.removeItem('company_id');
// 清除 cookie
document.cookie = 'auth_token=; path=/; max-age=0; SameSite=Lax';
document.cookie = 'company_id=; path=/; max-age=0; SameSite=Lax';
}
set({
user: null,
token: null,
isAuthenticated: false,
});
},
setUser: (user) => {
set({ user, isAuthenticated: true });
},
updateUser: (userData) => {
set((state) => ({
user: state.user ? { ...state.user, ...userData } : null,
}));
},
}),
{
name: 'auth-storage',
partialize: (state) => ({
user: state.user,
token: state.token,
isAuthenticated: state.isAuthenticated,
}),
}
)
);
+96
View File
@@ -0,0 +1,96 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
/**
* 企业信息接口
*/
export interface Company {
id: number;
name: string;
plan: string;
status: string;
max_users: number;
is_trial: boolean;
data_retention_months: number;
created_at: string;
updated_at: string;
}
/**
* 企业状态接口
*/
interface CompanyState {
currentCompany: Company | null;
companies: Company[];
// Actions
setCompany: (company: Company) => void;
setCompanies: (companies: Company[]) => void;
addCompany: (company: Company) => void;
updateCompany: (companyId: number, companyData: Partial<Company>) => void;
removeCompany: (companyId: number) => void;
clearCompanies: () => void;
}
/**
* 企业状态 Store
* 使用 localStorage 持久化
*/
export const useCompanyStore = create<CompanyState>()(
persist(
(set) => ({
currentCompany: null,
companies: [],
setCompany: (company) => {
// 保存当前企业 ID 到 localStorage
if (typeof window !== 'undefined') {
localStorage.setItem('company_id', String(company.id));
}
set({ currentCompany: company });
},
setCompanies: (companies) => {
set({ companies });
},
addCompany: (company) => {
set((state) => ({
companies: [...state.companies, company],
}));
},
updateCompany: (companyId, companyData) => {
set((state) => ({
companies: state.companies.map((c) =>
c.id === companyId ? { ...c, ...companyData } : c
),
currentCompany:
state.currentCompany?.id === companyId
? { ...state.currentCompany, ...companyData }
: state.currentCompany,
}));
},
removeCompany: (companyId) => {
set((state) => ({
companies: state.companies.filter((c) => c.id !== companyId),
currentCompany:
state.currentCompany?.id === companyId ? null : state.currentCompany,
}));
},
clearCompanies: () => {
set({ companies: [], currentCompany: null });
},
}),
{
name: 'company-storage',
partialize: (state) => ({
currentCompany: state.currentCompany,
companies: state.companies,
}),
}
)
);
+76
View File
@@ -0,0 +1,76 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
/**
* UI 状态接口
*/
interface UIState {
// 侧边栏状态
sidebarOpen: boolean;
// 主题
theme: 'light' | 'dark' | 'system';
// 加载状态
loading: boolean;
loadingMessage: string;
// Actions
toggleSidebar: () => void;
setSidebarOpen: (open: boolean) => void;
setTheme: (theme: 'light' | 'dark' | 'system') => void;
setLoading: (loading: boolean, message?: string) => void;
}
/**
* UI 状态 Store
* 使用 localStorage 持久化部分状态
*/
export const useUIStore = create<UIState>()(
persist(
(set) => ({
sidebarOpen: true,
theme: 'light',
loading: false,
loadingMessage: '',
toggleSidebar: () => {
set((state) => ({ sidebarOpen: !state.sidebarOpen }));
},
setSidebarOpen: (open) => {
set({ sidebarOpen: open });
},
setTheme: (theme) => {
// 更新 DOM 元素的主题类
if (typeof window !== 'undefined') {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
if (theme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
root.classList.add(systemTheme);
} else {
root.classList.add(theme);
}
}
set({ theme });
},
setLoading: (loading, message = '') => {
set({ loading, loadingMessage: message });
},
}),
{
name: 'ui-storage',
partialize: (state) => ({
sidebarOpen: state.sidebarOpen,
theme: state.theme,
}),
}
)
);
+6
View File
@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}