Files
GNX-WEB/frontEnd/lib/api/contactService.ts
Iliyan Angelov 366f28677a update
2025-11-24 03:52:08 +02:00

132 lines
3.2 KiB
TypeScript

/**
* Contact API Service
* Handles communication with the Django REST API for contact form submissions
*/
import { API_CONFIG } from '@/lib/config/api';
export interface ContactFormData {
first_name: string;
last_name: string;
email: string;
phone?: string;
company: string;
job_title: string;
industry?: string;
company_size?: string;
project_type?: string;
timeline?: string;
budget?: string;
message: string;
newsletter_subscription: boolean;
privacy_consent: boolean;
}
export interface ContactSubmissionResponse {
message: string;
submission_id: number;
status: string;
}
export interface ApiError {
message: string;
errors?: Record<string, string[]>;
status: number;
}
class ContactApiService {
private baseUrl: string;
constructor() {
this.baseUrl = `${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.CONTACT}`;
}
/**
* Submit a contact form to the Django API
*/
async submitContactForm(data: ContactFormData): Promise<ContactSubmissionResponse> {
try {
const response = await fetch(`${this.baseUrl}/submissions/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(
errorData.message ||
errorData.detail ||
`HTTP error! status: ${response.status}`
);
}
const result = await response.json();
return result;
} catch (error) {
if (error instanceof Error) {
throw new Error(`Failed to submit contact form: ${error.message}`);
}
throw new Error('Failed to submit contact form: Unknown error');
}
}
/**
* Get contact submission statistics (admin only)
*/
async getContactStats(): Promise<any> {
try {
const response = await fetch(`${this.baseUrl}/submissions/stats/`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
if (error instanceof Error) {
throw new Error(`Failed to fetch contact stats: ${error.message}`);
}
throw new Error('Failed to fetch contact stats: Unknown error');
}
}
/**
* Get recent contact submissions (admin only)
*/
async getRecentSubmissions(): Promise<any[]> {
try {
const response = await fetch(`${this.baseUrl}/submissions/recent/`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
if (error instanceof Error) {
throw new Error(`Failed to fetch recent submissions: ${error.message}`);
}
throw new Error('Failed to fetch recent submissions: Unknown error');
}
}
}
// Create and export a singleton instance
export const contactApiService = new ContactApiService();
// Export the class for testing purposes
export default ContactApiService;