/** * 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 { // 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 { 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 { await fs.writeFile(this.customersFile, JSON.stringify(customers, null, 2)); } async createCustomer(data: { name: string; description?: string; tavus_environments?: TavusEnvironment[]; }): Promise { const customers = await this.loadCustomers(); // Check for duplicate names if (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>): Promise { const customers = await this.loadCustomers(); const index = customers.findIndex(c => c.id === id); if (index === -1) { throw new Error(`Customer not found: ${id}`); } // Check for duplicate names (if updating name) if (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 { const customers = await this.loadCustomers(); const index = customers.findIndex(c => c.id === id); if (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 { if (!isValidUUIDv7(id)) { return null; } const customers = await this.loadCustomers(); return customers.find(c => c.id === id) || null; } async getCustomerByName(name: string): Promise { const customers = await this.loadCustomers(); return customers.find(c => c.name === name) || null; } async listCustomers(): Promise { return await this.loadCustomers(); } async addTavusEnvironment(customerId: string, environment: TavusEnvironment): Promise { const customer = await this.getCustomer(customerId); if (!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 { const customer = await this.getCustomer(customerId); if (!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 { 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 { 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: { 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); if (!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; } }