Spaces:
Running

axeronis
feat: booking system overhaul - remove debounce, day/week/month views, resource filter, drag-n-drop, Telegram notifications
b38cc4d
Raw History Blame Contribute Delete
18.3 kB
import axios from 'axios'
// Import types from centralized types module
import type {
Lead,
Message,
Conversation,
Tenant,
LeadStats,
ProcessingStatus,
SenderType,
BusinessType,
AISummaryJson,
} from '@/types'
// Re-export types for backward compatibility
export type { Lead, Message, Conversation, Tenant, LeadStats }
export type { ProcessingStatus, SenderType, BusinessType, AISummaryJson }
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
console.log('🔗 API URL:', API_BASE_URL)
export const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
})
// Add JWT token to all requests
api.interceptors.request.use(
(config) => {
// Get token from localStorage
const token = localStorage.getItem('auth_token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(error) => {
return Promise.reject(error)
}
)
// Handle 401 errors (invalid/expired token)
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
// Clear token and redirect to login
localStorage.removeItem('auth_token')
if (typeof window !== 'undefined') {
window.location.href = '/login'
}
}
return Promise.reject(error)
}
)
export const tenantsApi = {
getMe: async () => {
const response = await api.get<Tenant>('/api/v1/tenants/me')
return response.data
},
update: async (tenantId: string, data: Partial<Tenant>) => {
const response = await api.patch<Tenant>(`/api/v1/tenants/${tenantId}`, data)
return response.data
}
}
// API functions
export const leadsApi = {
getLeads: async (params?: {
status?: string
heat_level?: string
skip?: number
limit?: number
}) => {
const response = await api.get<Lead[]>(`/api/v1/leads`, { params })
return response.data
},
getLead: async (leadId: string) => {
const response = await api.get<Lead>(`/api/v1/leads/${leadId}`)
return response.data
},
getConversation: async (leadId: string) => {
const response = await api.get<Conversation>(`/api/v1/leads/${leadId}/conversation`)
return response.data
},
takeover: async (leadId: string, managerId: string) => {
const response = await api.post(`/api/v1/leads/${leadId}/takeover`, {
manager_id: managerId
})
return response.data
},
getStats: async () => {
const response = await api.get<LeadStats>(`/api/v1/leads/stats`)
return response.data
},
updateStage: async (leadId: string, stageId: string) => {
const response = await api.patch(`/api/v1/leads/${leadId}/stage`, {
stage_id: stageId
})
return response.data
},
toggleAI: async (leadId: string, isAIActive: boolean) => {
const response = await api.post(`/api/v1/leads/${leadId}/toggle-ai`, {
is_ai_active: isAIActive
})
return response.data
},
sendMessage: async (leadId: string, conversationId: string, message: string) => {
const response = await api.post('/api/v1/chats/send', {
lead_id: leadId,
conversation_id: conversationId,
message: message
})
return response.data
},
sendMessageWithMedia: async (leadId: string, conversationId: string, message: string, file?: File | null, audioBlob?: Blob | null) => {
const formData = new FormData()
formData.append('lead_id', leadId)
formData.append('conversation_id', conversationId)
formData.append('message', message)
if (file) {
formData.append('file', file)
}
if (audioBlob) {
formData.append('audio', audioBlob, 'voice.webm')
}
const response = await api.post('/api/v1/chats/send-media', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
return response.data
},
deleteLead: async (leadId: string, clearCache: boolean = false) => {
const response = await api.delete(`/api/v1/leads/${leadId}`, {
params: { clear_cache: clearCache }
})
return response.data
},
resetLead: async (leadId: string) => {
const response = await api.post(`/api/v1/leads/${leadId}/reset`)
return response.data
}
}
export const knowledgeApi = {
addKnowledge: async (data: {
content: string
source_type?: string
category?: string
tags?: string
}) => {
const response = await api.post(`/api/v1/knowledge/add`, data)
return response.data
},
search: async (query: string, top_k: number = 5) => {
const response = await api.post(`/api/v1/knowledge/search`, {
query,
top_k
})
return response.data
},
list: async (params?: {
category?: string
skip?: number
limit?: number
}) => {
const response = await api.get(`/api/v1/knowledge/list`, { params })
return response.data
},
upload: async (file: File) => {
const formData = new FormData()
formData.append('file', file)
const response = await api.post(`/api/v1/knowledge/upload`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
return response.data
},
delete: async (knowledgeId: string) => {
const response = await api.delete(`/api/v1/knowledge/${knowledgeId}`)
return response.data
},
update: async (knowledgeId: string, data: { content?: string; category?: string }) => {
const response = await api.put(`/api/v1/knowledge/${knowledgeId}`, data)
return response.data
},
// Payment Methods
getPaymentMethods: async () => {
const response = await api.get('/api/v1/knowledge/payment-methods')
return response.data
},
createPaymentMethod: async (data: any) => {
const response = await api.post('/api/v1/knowledge/payment-methods', data)
return response.data
},
updatePaymentMethod: async (id: string, data: any) => {
const response = await api.patch(`/api/v1/knowledge/payment-methods/${id}`, data)
return response.data
},
deletePaymentMethod: async (id: string) => {
const response = await api.delete(`/api/v1/knowledge/payment-methods/${id}`)
return response.data
},
// Knowledge Files
getKnowledgeFiles: async () => {
const response = await api.get('/api/v1/knowledge/files')
return response.data
},
createKnowledgeFile: async (data: any) => {
const response = await api.post('/api/v1/knowledge/files', data)
return response.data
},
updateKnowledgeFile: async (id: string, data: any) => {
const response = await api.patch(`/api/v1/knowledge/files/${id}`, data)
return response.data
},
deleteKnowledgeFile: async (id: string) => {
const response = await api.delete(`/api/v1/knowledge/files/${id}`)
return response.data
}
}
// Channels API
export const channelsApi = {
// Telegram
getTelegramStatus: async () => {
const response = await api.get('/api/v1/channels/telegram/status')
return response.data
},
connectTelegram: async (botToken: string) => {
const response = await api.post('/api/v1/channels/telegram/connect', {
bot_token: botToken
})
return response.data
},
disconnectTelegram: async () => {
const response = await api.delete('/api/v1/channels/telegram/disconnect')
return response.data
},
// WhatsApp
getWhatsAppStatus: async () => {
const response = await api.get('/api/v1/channels/meta/whatsapp/status')
return response.data
},
connectWhatsApp: async (accessToken: string, phoneNumberId: string, businessAccountId: string) => {
const response = await api.post('/api/v1/channels/whatsapp/connect', {
access_token: accessToken,
phone_number_id: phoneNumberId,
business_account_id: businessAccountId
})
return response.data
},
disconnectWhatsApp: async () => {
const response = await api.delete('/api/v1/channels/meta/whatsapp/disconnect')
return response.data
},
// Instagram
getLinkedInStatus: async () => {
const response = await api.get('/api/v1/channels/linkedin/status')
return response.data
},
connectLinkedIn: async (data: {
access_token: string
organization_id: string
verify_token: string
jsession_id?: string
}) => {
const response = await api.post('/api/v1/channels/linkedin/connect', data)
return response.data
},
disconnectLinkedIn: async () => {
const response = await api.delete('/api/v1/channels/linkedin/disconnect')
return response.data
},
// WhatsApp QR (Grey API)
generateWhatsAppQR: async () => {
console.log('🔍 Sending WhatsApp QR request...')
const response = await api.post('/api/v1/channels/whatsapp/qr/generate')
console.log('✅ WhatsApp QR response:', response.data)
return response.data
},
getWhatsAppQRStatus: async () => {
const response = await api.get('/api/v1/channels/whatsapp/qr/status')
return response.data
},
disconnectWhatsAppQR: async () => {
const response = await api.post('/api/v1/channels/whatsapp/qr/disconnect')
return response.data
}
}
// Billing API
export const billingApi = {
getFranchiseStatus: async () => {
const response = await api.get('/api/v1/billing/franchise-status')
return response.data
},
buyFranchise: async () => {
const response = await api.post('/api/v1/billing/buy-franchise')
return response.data
},
getTenantInfo: async () => {
const response = await api.get('/api/v1/tenants/me')
return response.data
},
calculateOverage: async () => {
const response = await api.get('/api/v1/billing/overage/calculate')
return response.data
},
downgradeSubscription: async (planId: string) => {
const response = await api.post('/api/v1/billing/subscription/downgrade', {
plan_id: planId
})
return response.data
},
cancelSubscription: async (reason: string, feedback: string) => {
const response = await api.post('/api/v1/billing/subscription/cancel', {
reason,
feedback
})
return response.data
},
upgradeSubscription: async (planId: string) => {
const response = await api.post('/api/v1/billing/subscription/upgrade', {
plan_id: planId
})
return response.data
},
convertTrial: async (planId: string) => {
const response = await api.post('/api/v1/billing/subscription/convert-trial', {
plan_id: planId
})
return response.data
}
}
// Playbook API
export const playbookApi = {
getStages: async () => {
const response = await api.get('/api/v1/playbook/stages')
return response.data
},
getCustomFields: async () => {
const response = await api.get('/api/v1/playbook/custom-fields')
return response.data
},
getTemplates: async () => {
const response = await api.get('/api/v1/playbook/templates')
return response.data
},
createStage: async (data: any) => {
const response = await api.post('/api/v1/playbook/stages', data)
return response.data
},
updateStage: async (stageId: string, data: any) => {
const response = await api.put(`/api/v1/playbook/stages/${stageId}`, data)
return response.data
},
deleteStage: async (stageId: string) => {
const response = await api.delete(`/api/v1/playbook/stages/${stageId}`)
return response.data
},
reorderStages: async (stageIds: string[]) => {
const response = await api.post('/api/v1/playbook/stages/reorder', {
stage_ids: stageIds
})
return response.data
},
applyTemplate: async (templateId: string) => {
const response = await api.post(`/api/v1/playbook/stages/template/${templateId}`)
return response.data
},
generateWithAI: async () => {
const response = await api.post('/api/v1/playbook/stages/generate')
return response.data
}
}
// Products API (Visual Commerce)
export const productsApi = {
getProducts: async (params?: {
search?: string
min_price?: number
max_price?: number
limit?: number
}) => {
const response = await api.get('/api/v1/products/', { params })
return response.data
},
getProduct: async (productId: string) => {
const response = await api.get(`/api/v1/products/${productId}`)
return response.data
},
createProduct: async (data: any) => {
const response = await api.post('/api/v1/products/', data)
return response.data
},
updateProduct: async (productId: string, data: any) => {
const response = await api.put(`/api/v1/products/${productId}`, data)
return response.data
},
deleteProduct: async (productId: string) => {
const response = await api.delete(`/api/v1/products/${productId}`)
return response.data
},
uploadImage: async (file: File) => {
const formData = new FormData()
formData.append('file', file)
const response = await api.post('/api/v1/products/upload-image', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
return response.data
}
}
// Admin API
export const adminApi = {
updateSubscription: async (tenantId: string, data: {
plan?: string
status?: string
extend_days?: number
set_expiration?: string
}) => {
const response = await api.patch(`/api/v1/admin/tenants/${tenantId}/subscription`, data)
return response.data
}
}
// Bookings API
export const bookingsApi = {
getAppointments: async (params?: { start_date?: string, end_date?: string, status?: string }) => {
const response = await api.get('/api/v1/bookings/', { params })
return response.data
},
createAppointment: async (data: any) => {
const response = await api.post('/api/v1/bookings/', data)
return response.data
},
cancelAppointment: async (appointmentId: string) => {
const response = await api.delete(`/api/v1/bookings/${appointmentId}`)
return response.data
},
getAppointmentsByLead: async (leadId: string) => {
const response = await api.get(`/api/v1/bookings/lead/${leadId}`)
return response.data
},
getServices: async () => {
const response = await api.get('/api/v1/bookings/services')
return response.data
},
getBookingSettings: async () => {
const response = await api.get('/api/v1/bookings/settings')
return response.data
},
updateAppointment: async (appointmentId: string, data: {
start_time?: string
end_time?: string
status?: string
resource_id?: string | null
notes?: string
}) => {
const response = await api.patch(`/api/v1/bookings/${appointmentId}`, data)
return response.data
},
// Resources API
getResources: async () => {
const response = await api.get('/api/v1/bookings/resources')
return response.data
},
createResource: async (data: {
name: string,
description?: string,
working_hours?: Record<string, { start: string, end: string }>,
sort_order?: number,
service_ids?: string[],
telegram_chat_id?: string,
user_id?: string
}) => {
const response = await api.post('/api/v1/bookings/resources', data)
return response.data
},
updateResource: async (resourceId: string, data: {
name?: string,
description?: string,
working_hours?: Record<string, { start: string, end: string }> | null,
sort_order?: number,
is_active?: boolean,
service_ids?: string[],
telegram_chat_id?: string,
user_id?: string | null
}) => {
const response = await api.patch(`/api/v1/bookings/resources/${resourceId}`, data)
return response.data
},
getTeamMembers: async () => {
const response = await api.get('/api/v1/team/members')
return response.data
},
deleteResource: async (resourceId: string, hard: boolean = false) => {
const response = await api.delete(`/api/v1/bookings/resources/${resourceId}`, { params: { hard } })
return response.data
},
getAvailableResources: async (startTime: string, endTime: string, serviceId?: string) => {
const params: any = { start_time: startTime, end_time: endTime }
if (serviceId) params.service_id = serviceId
const response = await api.get('/api/v1/bookings/resources/available', { params })
return response.data
}
}
// Google Sheets API
export const googleSheetsApi = {
getStatus: async () => {
const response = await api.get('/api/v1/integrations/google-sheets/status')
return response.data
},
preview: async (sheetUrl: string, sheetName: string = 'Sheet1') => {
const response = await api.post('/api/v1/integrations/google-sheets/preview', {
sheet_url: sheetUrl,
sheet_name: sheetName
})
return response.data
},
connect: async (data: {
sheet_url: string,
sheet_name: string,
mapping: Record<string, string>,
sync_enabled: boolean
}) => {
const response = await api.post('/api/v1/integrations/google-sheets/connect', data)
return response.data
},
sync: async () => {
const response = await api.post('/api/v1/integrations/google-sheets/sync')
return response.data
},
disconnect: async () => {
const response = await api.delete('/api/v1/integrations/google-sheets/disconnect')
return response.data
}
}
// Upload API - File uploads to Supabase Storage
export const uploadApi = {
// Upload any file
uploadFile: async (file: File): Promise<{ ok: boolean; url: string; filename: string }> => {
const formData = new FormData()
formData.append('file', file)
const response = await api.post('/api/v1/upload/file', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
return response.data
},
// Upload image specifically
uploadImage: async (file: File): Promise<{ ok: boolean; url: string; filename: string }> => {
const formData = new FormData()
formData.append('file', file)
const response = await api.post('/api/v1/upload/image', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
return response.data
},
// Upload document (PDF, DOC)
uploadDocument: async (file: File): Promise<{ ok: boolean; url: string; filename: string }> => {
const formData = new FormData()
formData.append('file', file)
const response = await api.post('/api/v1/upload/document', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
return response.data
}
}