/** * 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 */ import { generateQuotationPdfBase64 } from '@/utils/pdfGenerator'; 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 a document / PDF file message */ sendDocument: (sessionId: string, params: { chatId: string; base64?: string; url?: string; mimetype?: string; filename?: string; caption?: string; }): Promise => { return openwaFetch(`/api/sessions/${sessionId}/messages/send-document`, { method: 'POST', body: JSON.stringify(params), }); }, /** Send official quotation directly over OpenWA API with attached PDF Document */ sendQuotationWhatsApp: async (params: { customerName?: string; name?: string; customerPhone?: string; phone?: string; quoteTitle?: string; title?: string; amount: number | string; terms?: string; items?: Array<{ description: string; qty?: number; unit_price?: number }>; subtotal?: number; taxAmount?: number; quoteNumber?: string; pdfUrl?: string; customMessage?: 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 qNum = params.quoteNumber || `SQ-2026-${Math.floor(100 + Math.random() * 900)}`; let message = params.customMessage; if (!message) { const lineItemsStr = params.items && params.items.length > 0 ? params.items.map(it => `• ${it.description} (Qty ${it.qty || 1}) - ₹${((it.qty || 1) * (it.unit_price || 0)).toLocaleString('en-IN')}`).join('\n') : `• ${targetTitle} - ₹${formattedAmount}`; message = `📄 *iFIXKART OFFICIAL SALES & REPAIR QUOTATION*\n\nHello ${targetName},\n\nHere is your official itemized price quotation document:\n\n${lineItemsStr}\n\n*Grand Total Amount:* ₹${formattedAmount}\n*Warranty & Terms:* ${params.terms || '6-Month iFixKart IMEI Warranty'}\n\nThank you for choosing iFixKart!`; } // 1. Send Text Summary Message await openwaService.sendText(session.id, chatId, message); // 2. Generate PDF Base64 & Dispatch Official PDF Document Attachment (.pdf) try { const totalNum = Number(params.amount) || 0; const subtotalNum = params.subtotal || Math.round(totalNum / 1.18); const taxNum = params.taxAmount || (totalNum - subtotalNum); const pdfBase64 = generateQuotationPdfBase64({ quoteNumber: qNum, customerName: targetName, customerPhone: targetPhone, date: new Date().toLocaleDateString('en-IN'), items: params.items && params.items.length > 0 ? params.items : [{ description: targetTitle, qty: 1, unit_price: subtotalNum }], subtotal: subtotalNum, taxAmount: taxNum, grandTotal: totalNum, terms: params.terms }); await openwaService.sendDocument(session.id, { chatId, base64: pdfBase64, mimetype: 'application/pdf', filename: `Quotation_${qNum}.pdf`, caption: `📄 Official Quotation PDF: ${qNum}` }); } catch (pdfErr) { console.warn('PDF Document Attachment dispatch error:', pdfErr); } 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'); }, };