/** * openwaService.ts * Direct OpenWA API client for iFixKart admin panel. * Routes through the Next.js /openwa/* proxy to http://localhost:8088 * with API key injected server-side via the rewrite. * * OpenWA runs on port 8088 with Baileys engine. * API Key: stored in /mnt/fam/SERVER/IfixKartEcommerce/Backend/OpenWA/data/.api-key */ const OPENWA_API_KEY = 'owa_k1_df65037ea78c5ca9f19c63a6fb591e1d766581705c1dde392f098f6364387948'; // ─── Types ──────────────────────────────────────────────────────────────────── export interface OWASession { id: string; name: string; status: 'starting' | 'qr' | 'ready' | 'disconnected' | 'failed'; phone?: string; pushName?: string; connectedAt?: string; lastActive?: string; engineLoaded: boolean; } export interface OWAChat { id: string; name: string; isGroup: boolean; kind: 'individual' | 'group' | 'channel'; unreadCount: number; timestamp: number; lastMessage: string; archived: boolean; pinned: boolean; muted: boolean; muteExpiration?: number; } export interface OWAMessage { id: string; sessionId: string; waMessageId: string; chatId: string; chatName?: string; author?: string; from: string; to: string; body: string; type: string; direction: 'incoming' | 'outgoing'; timestamp: number; metadata?: Record; mediaPath?: string; mediaMimetype?: string; status: string; createdAt: string; } export interface OWAContact { id: string; name: string; number: string; isMyContact: boolean; isBlocked: boolean; } export interface OWAMessagesResponse { messages: OWAMessage[]; total: number; } // ─── Internal fetch helper ───────────────────────────────────────────────── async function openwaFetch(path: string, options: RequestInit = {}): Promise { const url = `/openwa${path.startsWith('/') ? path : '/' + path}`; const res = await fetch(url, { ...options, headers: { 'Content-Type': 'application/json', 'X-API-Key': OPENWA_API_KEY, ...(options.headers || {}), }, cache: 'no-store', }); if (!res.ok) { const text = await res.text().catch(() => ''); throw new Error(`OpenWA API error ${res.status}: ${text}`); } const contentType = res.headers.get('content-type') || ''; if (contentType.includes('application/json')) { return res.json() as Promise; } return {} as T; } // ─── Service ────────────────────────────────────────────────────────────────── export const openwaService = { // ── Sessions ────────────────────────────────────────────────────────────── /** List all WhatsApp sessions */ getSessions: (): Promise => { return openwaFetch('/api/sessions'); }, /** Get the first ready session, or null */ getReadySession: async (): Promise => { try { const sessions = await openwaFetch('/api/sessions'); return sessions.find((s) => s.status === 'ready') || sessions[0] || null; } catch { return null; } }, // ── Chats ───────────────────────────────────────────────────────────────── /** List chats for a session */ getChats: (sessionId: string, limit = 50): Promise => { return openwaFetch(`/api/sessions/${sessionId}/chats?limit=${limit}`); }, // ── Messages ────────────────────────────────────────────────────────────── /** Get stored messages (all or filtered by chatId) */ getMessages: (sessionId: string, params: { chatId?: string; limit?: number } = {}): Promise => { const query = new URLSearchParams(); if (params.chatId) query.set('chatId', params.chatId); if (params.limit) query.set('limit', String(params.limit)); return openwaFetch(`/api/sessions/${sessionId}/messages?${query.toString()}`); }, /** Send a plain text message */ sendText: (sessionId: string, chatId: string, text: string): Promise => { return openwaFetch(`/api/sessions/${sessionId}/messages/send-text`, { method: 'POST', body: JSON.stringify({ chatId, text }), }); }, // ── Contacts ────────────────────────────────────────────────────────────── /** List contacts for a session */ getContacts: (sessionId: string, limit = 100): Promise => { return openwaFetch(`/api/sessions/${sessionId}/contacts?limit=${limit}`); }, /** Send official quotation directly over OpenWA API */ sendQuotationWhatsApp: async (params: { customerName?: string; name?: string; customerPhone?: string; phone?: string; quoteTitle?: string; title?: string; amount: number | string; terms?: string; }): Promise<{ success: boolean; chatId: string; message: string; error?: string }> => { try { const session = await openwaService.getReadySession(); if (!session) { return { success: false, chatId: '', message: '', error: 'No active WhatsApp session found. Please pair device in Gateway.' }; } const targetPhone = params.customerPhone || params.phone || ''; const cleanDigits = targetPhone.replace(/\D/g, ''); const fullPhone = cleanDigits.length === 10 ? `91${cleanDigits}` : cleanDigits; const chatId = fullPhone.includes('@') ? fullPhone : `${fullPhone}@c.us`; const targetName = params.customerName || params.name || 'Customer'; const targetTitle = params.quoteTitle || params.title || 'Quotation Estimate'; const formattedAmount = Number(params.amount).toLocaleString('en-IN'); const message = `Hello ${targetName},\n\nHere is your official iFixKart quotation.\n\nItem: ${targetTitle}\nAmount: ₹${formattedAmount}\nTerms: ${params.terms || 'Standard Warranty'}\n\nThank you!`; await openwaService.sendText(session.id, chatId, message); return { success: true, chatId: fullPhone, message }; } catch (err: any) { console.error('Failed to dispatch OpenWA quotation:', err); return { success: false, chatId: '', message: '', error: err.message || 'Failed to dispatch via OpenWA API' }; } }, // ── Health ──────────────────────────────────────────────────────────────── getHealth: (): Promise<{ status: string; timestamp: string; version: string }> => { return openwaFetch('/api/health'); }, };