Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | /** * Customer Management Service * * Handles customer CRUD operations, UUID v7 generation, * and persistent storage using JSON files (for now). */ import * as fs from 'fs/promises'; import * as path from 'path'; import { generateUUIDv7, isValidUUIDv7 } from '../utils/uuid-v7'; import type { Customer, TavusEnvironment, CustomerStats, SystemStats } from '../types/customer.types'; export class CustomerService { private dataPath: string; private customersFile: string; constructor(dataPath?: string) { // Store customer data at project root level, not in backup-data this.dataPath = dataPath || path.resolve(process.cwd(), 'customer-data'); this.customersFile = path.join(this.dataPath, 'customers.json'); } async initialize(): Promise<void> { // Ensure data directory exists await fs.mkdir(this.dataPath, { recursive: true }); // Initialize customers file if it doesn't exist try { await fs.access(this.customersFile); } catch { await this.saveCustomers([]); } } private async loadCustomers(): Promise<Customer[]> { try { const data = await fs.readFile(this.customersFile, 'utf-8'); return JSON.parse(data); } catch (error) { console.warn('Could not load customers file:', error); return []; } } private async saveCustomers(customers: Customer[]): Promise<void> { await fs.writeFile(this.customersFile, JSON.stringify(customers, null, 2)); } async createCustomer(data: { name: string; description?: string; tavus_environments?: TavusEnvironment[]; }): Promise<Customer> { const customers = await this.loadCustomers(); // Check for duplicate names Iif (customers.some(c => c.name === data.name)) { throw new Error(`Customer with name "${data.name}" already exists`); } const now = new Date().toISOString(); const customer: Customer = { id: generateUUIDv7(), name: data.name, description: data.description, created_at: now, updated_at: now, tavus_environments: data.tavus_environments || [] }; customers.push(customer); await this.saveCustomers(customers); console.log(`✅ Created customer: ${customer.name} (${customer.id})`); return customer; } async updateCustomer(id: string, updates: Partial<Pick<Customer, 'name' | 'description' | 'tavus_environments'>>): Promise<Customer> { const customers = await this.loadCustomers(); const index = customers.findIndex(c => c.id === id); Iif (index === -1) { throw new Error(`Customer not found: ${id}`); } // Check for duplicate names (if updating name) Iif (updates.name && customers.some((c, i) => i !== index && c.name === updates.name)) { throw new Error(`Customer with name "${updates.name}" already exists`); } customers[index] = { ...customers[index], ...updates, updated_at: new Date().toISOString() }; await this.saveCustomers(customers); console.log(`✅ Updated customer: ${customers[index].name} (${id})`); return customers[index]; } async deleteCustomer(id: string): Promise<void> { const customers = await this.loadCustomers(); const index = customers.findIndex(c => c.id === id); Iif (index === -1) { throw new Error(`Customer not found: ${id}`); } const customer = customers[index]; customers.splice(index, 1); await this.saveCustomers(customers); console.log(`🗑️ Deleted customer: ${customer.name} (${id})`); } async getCustomer(id: string): Promise<Customer | null> { Iif (!isValidUUIDv7(id)) { return null; } const customers = await this.loadCustomers(); return customers.find(c => c.id === id) || null; } async getCustomerByName(name: string): Promise<Customer | null> { const customers = await this.loadCustomers(); return customers.find(c => c.name === name) || null; } async listCustomers(): Promise<Customer[]> { return await this.loadCustomers(); } async addTavusEnvironment(customerId: string, environment: TavusEnvironment): Promise<Customer> { const customer = await this.getCustomer(customerId); Iif (!customer) { throw new Error(`Customer not found: ${customerId}`); } // Remove existing environment of the same type customer.tavus_environments = customer.tavus_environments.filter( env => env.environment !== environment.environment ); // Add new environment customer.tavus_environments.push(environment); return await this.updateCustomer(customerId, { tavus_environments: customer.tavus_environments }); } async removeTavusEnvironment(customerId: string, environment: 'production' | 'staging' | 'testing'): Promise<Customer> { const customer = await this.getCustomer(customerId); Iif (!customer) { throw new Error(`Customer not found: ${customerId}`); } customer.tavus_environments = customer.tavus_environments.filter( env => env.environment !== environment ); return await this.updateCustomer(customerId, { tavus_environments: customer.tavus_environments }); } async getSystemStats(): Promise<SystemStats> { const customers = await this.loadCustomers(); const allEnvironments = customers.flatMap(c => c.tavus_environments.map(env => env.environment)); const uniqueEnvironments = [...new Set(allEnvironments)] as ('production' | 'staging' | 'testing')[]; return { total_customers: customers.length, total_personas: 0, // Will be populated by PersonaAssignmentService total_orphaned_personas: 0, // Will be populated by PersonaAssignmentService total_backups: 0, // Will be populated by backup system environments_tracked: uniqueEnvironments }; } async getCustomerStats(): Promise<CustomerStats[]> { const customers = await this.loadCustomers(); return customers.map(customer => ({ customer_id: customer.id, customer_name: customer.name, total_personas: 0, // Will be populated by PersonaAssignmentService total_backups: 0, // Will be populated by backup system environments: customer.tavus_environments.map(env => env.environment), last_backup_at: undefined, // Will be populated by backup system first_backup_at: undefined // Will be populated by backup system })); } // Migration helpers for existing data async migrateFromEnvironmentBasedIds(environmentMappings: Array<{ oldId: string; customerName: string; environment: 'production' | 'staging' | 'testing'; apiKey: string; }>): Promise<{ [oldId: string]: string }> { const idMap: { [oldId: string]: string } = {}; for (const mapping of environmentMappings) { // Check if customer already exists by name let customer = await this.getCustomerByName(mapping.customerName); Iif (!customer) { // Create new customer customer = await this.createCustomer({ name: mapping.customerName, description: `Migrated from ${mapping.oldId}` }); } // Add Tavus environment await this.addTavusEnvironment(customer.id, { environment: mapping.environment, api_key: mapping.apiKey, is_active: true }); idMap[mapping.oldId] = customer.id; } return idMap; } } |