Files
Twilioapp/src/utils/database.ts
T
2025-06-28 14:20:17 +08:00

358 lines
9.2 KiB
TypeScript

import { User, TranslationCall, DocumentTranslation, Appointment, Language } from '@/types';
// 模拟数据库连接配置
interface DatabaseConfig {
host: string;
port: number;
database: string;
username: string;
password: string;
}
class DatabaseManager {
private config: DatabaseConfig;
private isConnected: boolean = false;
constructor(config: DatabaseConfig) {
this.config = config;
}
// 连接数据库
async connect(): Promise<boolean> {
try {
// 模拟数据库连接
console.log('正在连接数据库...');
await new Promise(resolve => setTimeout(resolve, 1000));
this.isConnected = true;
console.log('数据库连接成功');
return true;
} catch (error) {
console.error('数据库连接失败:', error);
return false;
}
}
// 断开数据库连接
async disconnect(): Promise<void> {
this.isConnected = false;
console.log('数据库连接已断开');
}
// 检查连接状态
isDbConnected(): boolean {
return this.isConnected;
}
// 用户相关操作
async getUser(userId: string): Promise<User | null> {
if (!this.isConnected) {
throw new Error('数据库未连接');
}
// 模拟查询用户数据
const mockUser: User = {
id: userId,
name: '张三',
email: 'zhangsan@example.com',
phone: '+86 138 0013 8000',
avatar: '',
role: 'user',
status: 'active',
createdAt: '2023-01-15T00:00:00Z',
updatedAt: '2024-01-15T00:00:00Z',
preferences: {
language: 'zh-CN',
timezone: 'Asia/Shanghai',
notifications: {
email: true,
sms: true,
push: true,
},
theme: 'light',
},
subscription: {
id: 'sub_1',
userId,
plan: 'premium',
status: 'active',
startDate: '2023-01-15T00:00:00Z',
endDate: '2024-01-15T00:00:00Z',
features: ['ai_translation', 'human_translation', 'document_translation'],
},
};
return mockUser;
}
async updateUser(userId: string, userData: Partial<User>): Promise<boolean> {
if (!this.isConnected) {
throw new Error('数据库未连接');
}
// 模拟更新用户数据
console.log(`更新用户 ${userId} 的数据:`, userData);
await new Promise(resolve => setTimeout(resolve, 500));
return true;
}
// 通话记录相关操作
async getCallRecords(userId: string, limit: number = 20): Promise<TranslationCall[]> {
if (!this.isConnected) {
throw new Error('数据库未连接');
}
// 模拟查询通话记录
const mockCallRecords: TranslationCall[] = [
{
id: '1',
userId,
type: 'ai',
status: 'completed',
sourceLanguage: 'zh-CN',
targetLanguage: 'en-US',
startTime: '2024-01-15T10:30:00Z',
endTime: '2024-01-15T10:45:00Z',
duration: 900,
cost: 12.50,
rating: 5,
translatorName: 'AI翻译助手',
},
{
id: '2',
userId,
type: 'human',
status: 'completed',
sourceLanguage: 'en-US',
targetLanguage: 'ja-JP',
startTime: '2024-01-14T14:20:00Z',
endTime: '2024-01-14T14:50:00Z',
duration: 1800,
cost: 45.00,
rating: 5,
translatorName: '田中太郎',
},
];
return mockCallRecords;
}
async createCallRecord(callData: Omit<TranslationCall, 'id'>): Promise<string> {
if (!this.isConnected) {
throw new Error('数据库未连接');
}
const newId = Date.now().toString();
console.log('创建新的通话记录:', { id: newId, ...callData });
await new Promise(resolve => setTimeout(resolve, 500));
return newId;
}
// 文档翻译相关操作
async getDocuments(userId: string): Promise<DocumentTranslation[]> {
if (!this.isConnected) {
throw new Error('数据库未连接');
}
const mockDocuments: DocumentTranslation[] = [
{
id: '1',
userId,
fileName: '商业计划书.pdf',
fileSize: 2048576,
fileType: 'application/pdf',
fileUrl: '/uploads/business_plan.pdf',
translatedFileUrl: '/uploads/business_plan_en.pdf',
sourceLanguage: 'zh-CN',
targetLanguage: 'en-US',
status: 'completed',
progress: 100,
cost: 25.00,
pageCount: 15,
wordCount: 3500,
createdAt: '2024-01-15T09:00:00Z',
updatedAt: '2024-01-15T09:30:00Z',
completedAt: '2024-01-15T09:30:00Z',
quality: 'professional',
},
{
id: '2',
userId,
fileName: '技术文档.docx',
fileSize: 1536000,
fileType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
fileUrl: '/uploads/tech_doc.docx',
sourceLanguage: 'zh-CN',
targetLanguage: 'ja-JP',
status: 'processing',
progress: 65,
cost: 18.00,
pageCount: 8,
wordCount: 2100,
createdAt: '2024-01-15T11:00:00Z',
updatedAt: '2024-01-15T11:30:00Z',
quality: 'professional',
},
];
return mockDocuments;
}
async createDocument(documentData: Omit<DocumentTranslation, 'id'>): Promise<string> {
if (!this.isConnected) {
throw new Error('数据库未连接');
}
const newId = Date.now().toString();
console.log('创建新的文档翻译记录:', { id: newId, ...documentData });
await new Promise(resolve => setTimeout(resolve, 500));
return newId;
}
// 预约相关操作
async getAppointments(userId: string): Promise<Appointment[]> {
if (!this.isConnected) {
throw new Error('数据库未连接');
}
const mockAppointments: Appointment[] = [
{
id: '1',
userId,
title: '商务会议翻译',
description: '重要商务会议,需要专业翻译',
type: 'human',
sourceLanguage: 'zh-CN',
targetLanguage: 'en-US',
startTime: '2024-01-20T14:00:00Z',
endTime: '2024-01-20T16:00:00Z',
status: 'confirmed',
cost: 200.00,
reminderSent: false,
createdAt: '2024-01-15T09:00:00Z',
updatedAt: '2024-01-15T09:00:00Z',
},
{
id: '2',
userId,
title: '医疗咨询翻译',
description: '医疗咨询预约翻译服务',
type: 'video',
sourceLanguage: 'en-US',
targetLanguage: 'zh-CN',
startTime: '2024-01-22T10:30:00Z',
endTime: '2024-01-22T11:30:00Z',
status: 'scheduled',
cost: 150.00,
reminderSent: false,
createdAt: '2024-01-15T10:00:00Z',
updatedAt: '2024-01-15T10:00:00Z',
},
];
return mockAppointments;
}
async createAppointment(appointmentData: Omit<Appointment, 'id'>): Promise<string> {
if (!this.isConnected) {
throw new Error('数据库未连接');
}
const newId = Date.now().toString();
console.log('创建新的预约记录:', { id: newId, ...appointmentData });
await new Promise(resolve => setTimeout(resolve, 500));
return newId;
}
async updateAppointment(appointmentId: string, appointmentData: Partial<Appointment>): Promise<boolean> {
if (!this.isConnected) {
throw new Error('数据库未连接');
}
console.log(`更新预约 ${appointmentId} 的数据:`, appointmentData);
await new Promise(resolve => setTimeout(resolve, 500));
return true;
}
async deleteAppointment(appointmentId: string): Promise<boolean> {
if (!this.isConnected) {
throw new Error('数据库未连接');
}
console.log(`删除预约 ${appointmentId}`);
await new Promise(resolve => setTimeout(resolve, 500));
return true;
}
// 语言相关操作
async getLanguages(): Promise<Language[]> {
const mockLanguages: Language[] = [
{
code: 'zh-CN',
name: 'Chinese (Simplified)',
level: 'native',
},
{
code: 'en-US',
name: 'English (US)',
level: 'fluent',
},
{
code: 'ja-JP',
name: 'Japanese',
level: 'fluent',
},
{
code: 'ko-KR',
name: 'Korean',
level: 'intermediate',
},
{
code: 'es-ES',
name: 'Spanish',
level: 'intermediate',
},
{
code: 'fr-FR',
name: 'French',
level: 'basic',
},
];
return mockLanguages;
}
// 统计数据
async getStatistics(userId: string): Promise<any> {
if (!this.isConnected) {
throw new Error('数据库未连接');
}
return {
totalCalls: 156,
totalMinutes: 2340,
totalDocuments: 23,
totalAppointments: 8,
monthlyStats: {
calls: 12,
documents: 5,
appointments: 3,
spending: 450.00,
},
};
}
}
// 创建数据库实例
const dbConfig: DatabaseConfig = {
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT || '5432'),
database: process.env.DB_NAME || 'twilioapp',
username: process.env.DB_USER || 'postgres',
password: process.env.DB_PASSWORD || 'password',
};
export const database = new DatabaseManager(dbConfig);
// 导出类型
export type { DatabaseConfig };
export { DatabaseManager };