This commit is contained in:
Iliyan Angelov
2025-11-16 20:05:08 +02:00
parent 98ccd5b6ff
commit 48353cde9c
118 changed files with 9488 additions and 1336 deletions

View File

@@ -0,0 +1,63 @@
import apiClient from './apiClient';
export type CookiePolicySettings = {
analytics_enabled: boolean;
marketing_enabled: boolean;
preferences_enabled: boolean;
};
export type CookiePolicySettingsResponse = {
status: string;
data: CookiePolicySettings;
updated_at?: string;
updated_by?: string | null;
};
export type CookieIntegrationSettings = {
ga_measurement_id?: string | null;
fb_pixel_id?: string | null;
};
export type CookieIntegrationSettingsResponse = {
status: string;
data: CookieIntegrationSettings;
updated_at?: string;
updated_by?: string | null;
};
const adminPrivacyService = {
getCookiePolicy: async (): Promise<CookiePolicySettingsResponse> => {
const res = await apiClient.get<CookiePolicySettingsResponse>(
'/admin/privacy/cookie-policy'
);
return res.data;
},
updateCookiePolicy: async (
payload: CookiePolicySettings
): Promise<CookiePolicySettingsResponse> => {
const res = await apiClient.put<CookiePolicySettingsResponse>(
'/admin/privacy/cookie-policy',
payload
);
return res.data;
},
getIntegrations: async (): Promise<CookieIntegrationSettingsResponse> => {
const res = await apiClient.get<CookieIntegrationSettingsResponse>(
'/admin/privacy/integrations'
);
return res.data;
},
updateIntegrations: async (
payload: CookieIntegrationSettings
): Promise<CookieIntegrationSettingsResponse> => {
const res = await apiClient.put<CookieIntegrationSettingsResponse>(
'/admin/privacy/integrations',
payload
);
return res.data;
},
};
export default adminPrivacyService;

View File

@@ -1,85 +1,212 @@
import axios from 'axios';
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
// Base URL from environment or default. Ensure it points to the
// server API root (append '/api' if not provided) so frontend calls
// like '/bookings/me' resolve to e.g. 'http://localhost:8000/api/bookings/me'.
// Base URL from environment or default
const rawBase = import.meta.env.VITE_API_URL || 'http://localhost:8000';
// Normalize base and ensure a single /api suffix. If the provided
// VITE_API_URL already points to the API root (contains '/api'),
// don't append another '/api'.
const normalized = String(rawBase).replace(/\/$/, '');
const API_BASE_URL = /\/api(\/?$)/i.test(normalized)
? normalized
: normalized + '/api';
// Create axios instance
// Retry configuration
const MAX_RETRIES = 3;
const RETRY_DELAY = 1000; // 1 second
const RETRYABLE_STATUS_CODES = [408, 429, 500, 502, 503, 504];
// Create axios instance with enhanced configuration
const apiClient = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
timeout: 10000,
timeout: 30000, // 30 seconds timeout
withCredentials: true, // Enable sending cookies
});
// Request interceptor - Add token to header
// Retry logic helper
const retryRequest = async (
error: AxiosError,
retryCount: number = 0
): Promise<any> => {
const config = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
// Don't retry if already retried or not a retryable error
if (
config._retry ||
retryCount >= MAX_RETRIES ||
!error.config ||
!error.response ||
!RETRYABLE_STATUS_CODES.includes(error.response.status)
) {
return Promise.reject(error);
}
config._retry = true;
// Exponential backoff
const delay = RETRY_DELAY * Math.pow(2, retryCount);
await new Promise(resolve => setTimeout(resolve, delay));
console.log(`Retrying request (${retryCount + 1}/${MAX_RETRIES}): ${config.url}`);
return apiClient.request(config);
};
// Request interceptor - Add token and request ID
apiClient.interceptors.request.use(
(config) => {
// Normalize request URL: if a request path accidentally begins
// with '/api', strip that prefix so it will be appended to
// our baseURL exactly once. This prevents double '/api/api'
// when code uses absolute '/api/...' paths.
(config: InternalAxiosRequestConfig) => {
// Normalize request URL
if (config.url && typeof config.url === 'string') {
if (config.url.startsWith('/api/')) {
config.url = config.url.replace(/^\/api/, '');
}
// Also avoid accidental double slashes after concatenation
config.url = config.url.replace(/\/\/+/, '/');
}
// Add authorization token
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
// Generate and add request ID for tracking
const requestId = crypto.randomUUID ? crypto.randomUUID() :
`${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
config.headers['X-Request-ID'] = requestId;
// Add timestamp for request tracking
(config as any).metadata = { startTime: new Date() };
return config;
},
(error) => {
(error: AxiosError) => {
return Promise.reject(error);
}
);
// Response interceptor - Handle common errors
// Response interceptor - Handle errors with retry logic
apiClient.interceptors.response.use(
(response) => response,
(error) => {
// Handle network errors
(response) => {
// Log request duration
const config = response.config as InternalAxiosRequestConfig & { metadata?: any };
if (config.metadata?.startTime) {
const duration = new Date().getTime() - config.metadata.startTime.getTime();
if (duration > 1000) { // Log slow requests (>1s)
console.warn(`Slow request detected: ${config.url} took ${duration}ms`);
}
}
// Extract request ID from response headers for debugging
const requestId = response.headers['x-request-id'];
if (requestId && import.meta.env.DEV) {
console.debug(`Request completed: ${config.url} [${requestId}]`);
}
return response;
},
async (error: AxiosError) => {
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
// Handle network errors (no response)
if (!error.response) {
if (error.code === 'ECONNABORTED') {
return Promise.reject({
...error,
message: 'Request timeout. Please check your connection and try again.',
});
}
// Retry network errors
if (originalRequest && !originalRequest._retry) {
return retryRequest(error);
}
console.error('Network error:', error);
// You can show a toast notification here
return Promise.reject({
...error,
message: 'Network error. Please check ' +
'your internet connection.',
message: 'Network error. Please check your internet connection.',
});
}
if (error.response?.status === 401) {
// Token expired or invalid
const status = error.response.status;
const requestId = error.response.headers['x-request-id'];
// Handle 401 Unauthorized
if (status === 401) {
localStorage.removeItem('token');
localStorage.removeItem('userInfo');
window.location.href = '/login';
}
// Handle other HTTP errors
if (error.response?.status >= 500) {
console.error('Server error:', error);
// Don't redirect if already on login page
if (!window.location.pathname.includes('/login')) {
window.location.href = '/login';
}
const errorMessage = (error.response?.data as any)?.message || 'Session expired. Please login again.';
return Promise.reject({
...error,
message: 'Server error. Please try again later.',
message: errorMessage,
});
}
return Promise.reject(error);
// Handle 403 Forbidden
if (status === 403) {
const errorMessage = (error.response?.data as any)?.message || 'You do not have permission to access this resource.';
return Promise.reject({
...error,
message: errorMessage,
});
}
// Handle 404 Not Found
if (status === 404) {
const errorMessage = (error.response?.data as any)?.message || 'Resource not found.';
return Promise.reject({
...error,
message: errorMessage,
});
}
// Handle 429 Too Many Requests (rate limiting)
if (status === 429) {
const retryAfter = error.response.headers['retry-after'];
return Promise.reject({
...error,
message: `Too many requests. ${retryAfter ? `Please try again after ${retryAfter} seconds.` : 'Please try again later.'}`,
retryAfter: retryAfter ? parseInt(retryAfter) : undefined,
});
}
// Handle 5xx server errors with retry
if (status >= 500 && status < 600) {
if (originalRequest && !originalRequest._retry) {
return retryRequest(error);
}
console.error(`Server error [${requestId || 'unknown'}]:`, error);
const errorMessage = (error.response?.data as any)?.message || 'Server error. Please try again later.';
return Promise.reject({
...error,
message: errorMessage,
requestId,
});
}
// Handle validation errors (400)
if (status === 400) {
const errorData = error.response.data as any;
return Promise.reject({
...error,
message: errorData?.message || errorData?.errors?.[0]?.message || 'Invalid request. Please check your input.',
errors: errorData?.errors || [],
});
}
// For other errors, extract message from response
const errorMessage = (error.response.data as any)?.message || error.message || 'An error occurred';
return Promise.reject({
...error,
message: errorMessage,
requestId,
});
}
);

View File

@@ -0,0 +1,116 @@
import apiClient from './apiClient';
/**
* Audit Log API Service
*/
export interface AuditLog {
id: number;
user_id?: number;
action: string;
resource_type: string;
resource_id?: number;
ip_address?: string;
user_agent?: string;
request_id?: string;
details?: any;
status: string;
error_message?: string;
created_at: string;
user?: {
id: number;
full_name: string;
email: string;
};
}
export interface AuditLogListResponse {
status: string;
data: {
logs: AuditLog[];
pagination: {
total: number;
page: number;
limit: number;
totalPages: number;
};
};
}
export interface AuditLogStatsResponse {
status: string;
data: {
total: number;
by_status: {
success: number;
failed: number;
error: number;
};
top_actions: Array<{
action: string;
count: number;
}>;
top_resource_types: Array<{
resource_type: string;
count: number;
}>;
};
}
export interface AuditLogFilters {
action?: string;
resource_type?: string;
user_id?: number;
status?: string;
search?: string;
start_date?: string;
end_date?: string;
page?: number;
limit?: number;
}
class AuditService {
/**
* Get audit logs with filters
*/
async getAuditLogs(filters: AuditLogFilters = {}): Promise<AuditLogListResponse> {
const params = new URLSearchParams();
if (filters.action) params.append('action', filters.action);
if (filters.resource_type) params.append('resource_type', filters.resource_type);
if (filters.user_id) params.append('user_id', filters.user_id.toString());
if (filters.status) params.append('status', filters.status);
if (filters.search) params.append('search', filters.search);
if (filters.start_date) params.append('start_date', filters.start_date);
if (filters.end_date) params.append('end_date', filters.end_date);
if (filters.page) params.append('page', filters.page.toString());
if (filters.limit) params.append('limit', filters.limit.toString());
const response = await apiClient.get(`/audit-logs/?${params.toString()}`);
return response.data;
}
/**
* Get audit log by ID
*/
async getAuditLogById(id: number): Promise<{ status: string; data: { log: AuditLog } }> {
const response = await apiClient.get(`/audit-logs/${id}`);
return response.data;
}
/**
* Get audit log statistics
*/
async getAuditStats(startDate?: string, endDate?: string): Promise<AuditLogStatsResponse> {
const params = new URLSearchParams();
if (startDate) params.append('start_date', startDate);
if (endDate) params.append('end_date', endDate);
const response = await apiClient.get(`/audit-logs/stats?${params.toString()}`);
return response.data;
}
}
export const auditService = new AuditService();
export default auditService;

View File

@@ -132,6 +132,25 @@ const authService = {
);
return response.data;
},
/**
* Update profile
*/
updateProfile: async (
data: {
full_name?: string;
email?: string;
phone_number?: string;
password?: string;
currentPassword?: string;
}
): Promise<AuthResponse> => {
const response = await apiClient.put<AuthResponse>(
'/api/auth/profile',
data
);
return response.data;
},
};
export default authService;

View File

@@ -2,6 +2,9 @@ import apiClient from './apiClient';
/**
* Banner API Service
*
* NOTE: To avoid hammering the API, we add a very lightweight
* in-memory + optional localStorage cache for read endpoints.
*/
export interface Banner {
@@ -27,28 +30,211 @@ export interface BannerListResponse {
message?: string;
}
// ---------- Simple client-side cache ----------
type CacheEntry = {
timestamp: number;
response: BannerListResponse;
};
const BANNER_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
const memoryCache = new Map<string, CacheEntry>();
const getCacheKey = (position?: string) =>
position ? `banners:position:${position}` : 'banners:active';
const isCacheValid = (entry: CacheEntry | undefined) => {
if (!entry) return false;
return Date.now() - entry.timestamp < BANNER_CACHE_TTL_MS;
};
const loadFromStorage = (key: string): CacheEntry | undefined => {
if (typeof window === 'undefined') return undefined;
try {
const raw = window.localStorage.getItem(key);
if (!raw) return undefined;
const parsed = JSON.parse(raw) as CacheEntry;
return isCacheValid(parsed) ? parsed : undefined;
} catch {
return undefined;
}
};
const saveToStorage = (key: string, entry: CacheEntry) => {
if (typeof window === 'undefined') return;
try {
window.localStorage.setItem(key, JSON.stringify(entry));
} catch {
// ignore storage errors (quota, disabled, etc.)
}
};
const getCachedOrFetch = async (
key: string,
fetcher: () => Promise<BannerListResponse>
): Promise<BannerListResponse> => {
// 1) Check in-memory cache
const inMemory = memoryCache.get(key);
if (isCacheValid(inMemory)) {
return inMemory!.response;
}
// 2) Check localStorage cache (fills memory cache if valid)
const fromStorage = loadFromStorage(key);
if (fromStorage) {
memoryCache.set(key, fromStorage);
return fromStorage.response;
}
// 3) Fetch from API and cache result
const response = await fetcher();
const entry: CacheEntry = {
timestamp: Date.now(),
response,
};
memoryCache.set(key, entry);
saveToStorage(key, entry);
return response;
};
/**
* Get banners by position
*
* Cached per-position on the client for a short TTL.
*/
export const getBannersByPosition = async (
position: string = 'home'
): Promise<BannerListResponse> => {
const response = await apiClient.get('/banners', {
params: { position },
const key = getCacheKey(position);
return getCachedOrFetch(key, async () => {
const response = await apiClient.get('/banners', {
params: { position },
});
return response.data;
});
return response.data;
};
/**
* Get all active banners
*
* Cached on the client for a short TTL.
*/
export const getActiveBanners = async ():
export const getActiveBanners = async ():
Promise<BannerListResponse> => {
const response = await apiClient.get('/banners');
const key = getCacheKey();
return getCachedOrFetch(key, async () => {
const response = await apiClient.get('/banners');
return response.data;
});
};
/**
* Get all banners (admin)
*/
export const getAllBanners = async (
params?: { position?: string; page?: number; limit?: number }
): Promise<BannerListResponse> => {
const response = await apiClient.get('/banners', { params });
return response.data;
};
export default {
/**
* Get banner by ID
*/
export const getBannerById = async (
id: number
): Promise<{ success: boolean; data: { banner: Banner } }> => {
const response = await apiClient.get(`/banners/${id}`);
return response.data;
};
/**
* Create banner
*/
export const createBanner = async (
data: {
title: string;
description?: string;
image_url: string;
link?: string;
position?: string;
display_order?: number;
start_date?: string;
end_date?: string;
}
): Promise<{ success: boolean; data: { banner: Banner }; message: string }> => {
const response = await apiClient.post('/banners', data);
return response.data;
};
/**
* Update banner
*/
export const updateBanner = async (
id: number,
data: {
title?: string;
description?: string;
image_url?: string;
link?: string;
position?: string;
display_order?: number;
is_active?: boolean;
start_date?: string;
end_date?: string;
}
): Promise<{ success: boolean; data: { banner: Banner }; message: string }> => {
const response = await apiClient.put(`/banners/${id}`, data);
return response.data;
};
/**
* Delete banner
*/
export const deleteBanner = async (
id: number
): Promise<{ success: boolean; message: string }> => {
const response = await apiClient.delete(`/banners/${id}`);
return response.data;
};
/**
* Upload banner image
*/
export const uploadBannerImage = async (
file: File
): Promise<{ success: boolean; data: { image_url: string; full_url: string }; message: string }> => {
const formData = new FormData();
formData.append('image', file);
const response = await apiClient.post('/banners/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
return response.data;
};
export interface BannerService {
getBannersByPosition: typeof getBannersByPosition;
getActiveBanners: typeof getActiveBanners;
getAllBanners: typeof getAllBanners;
getBannerById: typeof getBannerById;
createBanner: typeof createBanner;
updateBanner: typeof updateBanner;
deleteBanner: typeof deleteBanner;
uploadBannerImage: typeof uploadBannerImage;
}
const bannerService: BannerService = {
getBannersByPosition,
getActiveBanners,
getAllBanners,
getBannerById,
createBanner,
updateBanner,
deleteBanner,
uploadBannerImage,
};
export default bannerService as BannerService;

View File

@@ -0,0 +1,57 @@
import apiClient from './apiClient';
/**
* Customer Dashboard API Service
*/
export interface CustomerDashboardStats {
total_bookings: number;
total_spending: number;
currently_staying: number;
upcoming_bookings: Array<{
id: number;
booking_number: string;
check_in_date: string;
check_out_date: string;
status: string;
total_price: number;
room?: {
id: number;
room_number: string;
room_type: {
name: string;
};
};
}>;
recent_activity: Array<{
action: string;
booking_id: number;
booking_number: string;
created_at: string;
room?: {
room_number: string;
};
}>;
booking_change_percentage: number;
spending_change_percentage: number;
}
export interface CustomerDashboardResponse {
success: boolean;
status?: string;
data: CustomerDashboardStats;
message?: string;
}
/**
* Get customer dashboard statistics
*/
export const getCustomerDashboardStats = async (): Promise<CustomerDashboardResponse> => {
const response = await apiClient.get('/reports/customer/dashboard');
return response.data;
};
export default {
getCustomerDashboardStats,
};

View File

@@ -30,4 +30,8 @@ export { default as promotionService } from './promotionService';
export type * from './promotionService';
export { default as reportService } from './reportService';
export { default as dashboardService } from './dashboardService';
export { default as auditService } from './auditService';
export type { CustomerDashboardStats, CustomerDashboardResponse } from './dashboardService';
export type * from './reportService';
export type * from './auditService';

View File

@@ -0,0 +1,84 @@
import apiClient from './apiClient';
export type CookieCategoryPreferences = {
necessary: boolean;
analytics: boolean;
marketing: boolean;
preferences: boolean;
};
export type CookieConsent = {
version: number;
updated_at: string;
has_decided: boolean;
categories: CookieCategoryPreferences;
};
export type CookieConsentResponse = {
status: string;
data: CookieConsent;
};
export type UpdateCookieConsentRequest = {
analytics?: boolean;
marketing?: boolean;
preferences?: boolean;
};
export type PublicPrivacyConfig = {
policy: {
analytics_enabled: boolean;
marketing_enabled: boolean;
preferences_enabled: boolean;
};
integrations: {
ga_measurement_id?: string | null;
fb_pixel_id?: string | null;
};
};
export type PublicPrivacyConfigResponse = {
status: string;
data: PublicPrivacyConfig;
};
const privacyService = {
/**
* Fetch current cookie consent from the backend.
*/
getCookieConsent: async (): Promise<CookieConsent> => {
const response = await apiClient.get<CookieConsentResponse>(
'/privacy/cookie-consent'
);
return response.data.data;
},
/**
* Fetch public privacy configuration:
* - global policy flags
* - integration IDs (e.g. GA4, Meta Pixel)
*/
getPublicConfig: async (): Promise<PublicPrivacyConfig> => {
const response = await apiClient.get<PublicPrivacyConfigResponse>(
'/privacy/config'
);
return response.data.data;
},
/**
* Update cookie consent preferences on the backend.
*/
updateCookieConsent: async (
payload: UpdateCookieConsentRequest
): Promise<CookieConsent> => {
const response = await apiClient.post<CookieConsentResponse>(
'/privacy/cookie-consent',
payload
);
return response.data.data;
},
};
export default privacyService;