Disable the debug console logs for production

This commit is contained in:
Tola Leng
2025-07-10 22:14:17 +07:00
parent 917d8a6d29
commit 2d2bd790b0
33 changed files with 270 additions and 270 deletions
+12 -12
View File
@@ -22,13 +22,13 @@ export interface AlertConfiguration {
export const alertConfigService = {
async getAlertConfigurations(): Promise<AlertConfiguration[]> {
console.info("Fetching alert configurations");
// console.info("Fetching alert configurations");
try {
const response = await pb.collection('alert_configurations').getList(1, 50);
console.info("Alert configurations response:", response);
// console.info("Alert configurations response:", response);
return response.items as AlertConfiguration[];
} catch (error) {
console.error("Error fetching alert configurations:", error);
// console.error("Error fetching alert configurations:", error);
toast({
title: "Error",
description: "Failed to load notification settings",
@@ -39,17 +39,17 @@ export const alertConfigService = {
},
async createAlertConfiguration(config: Omit<AlertConfiguration, 'id' | 'collectionId' | 'collectionName' | 'created' | 'updated'>): Promise<AlertConfiguration | null> {
console.info("Creating alert configuration:", config);
// console.info("Creating alert configuration:", config);
try {
const result = await pb.collection('alert_configurations').create(config);
console.info("Alert configuration created:", result);
// console.info("Alert configuration created:", result);
toast({
title: "Success",
description: "Notification settings saved successfully",
});
return result as AlertConfiguration;
} catch (error) {
console.error("Error creating alert configuration:", error);
// console.error("Error creating alert configuration:", error);
toast({
title: "Error",
description: "Failed to save notification settings",
@@ -60,17 +60,17 @@ export const alertConfigService = {
},
async updateAlertConfiguration(id: string, config: Partial<AlertConfiguration>): Promise<AlertConfiguration | null> {
console.info(`Updating alert configuration ${id}:`, config);
// console.info(`Updating alert configuration ${id}:`, config);
try {
const result = await pb.collection('alert_configurations').update(id, config);
console.info("Alert configuration updated:", result);
// console.info("Alert configuration updated:", result);
toast({
title: "Success",
description: "Notification settings updated successfully",
});
return result as AlertConfiguration;
} catch (error) {
console.error("Error updating alert configuration:", error);
// console.error("Error updating alert configuration:", error);
toast({
title: "Error",
description: "Failed to update notification settings",
@@ -81,17 +81,17 @@ export const alertConfigService = {
},
async deleteAlertConfiguration(id: string): Promise<boolean> {
console.info(`Deleting alert configuration ${id}`);
// console.info(`Deleting alert configuration ${id}`);
try {
await pb.collection('alert_configurations').delete(id);
console.info("Alert configuration deleted");
// console.info("Alert configuration deleted");
toast({
title: "Success",
description: "Notification channel removed",
});
return true;
} catch (error) {
console.error("Error deleting alert configuration:", error);
// console.error("Error deleting alert configuration:", error);
toast({
title: "Error",
description: "Failed to remove notification channel",
+7 -7
View File
@@ -19,7 +19,7 @@ export const authService = {
try {
// First try to login as a regular admin user
try {
console.log("Attempting to login as admin user");
// console.log("Attempting to login as admin user");
const authData = await pb.collection('users').authWithPassword(email, password);
return {
@@ -30,7 +30,7 @@ export const authService = {
role: authData.record.role || "admin"
};
} catch (error) {
console.log("Failed to login as admin, trying as superadmin", error);
// console.log("Failed to login as admin, trying as superadmin", error);
// If regular user login fails, try superadmin
const authData = await pb.collection('_superusers').authWithPassword(email, password);
@@ -44,7 +44,7 @@ export const authService = {
};
}
} catch (error) {
console.error('Login failed:', error);
// console.error('Login failed:', error);
throw new Error('Authentication failed. Please check your credentials.');
}
},
@@ -63,7 +63,7 @@ export const authService = {
if (!userData) return null;
// Log the full user data for debugging
console.log("Raw user data from authStore:", userData);
//console.log("Raw user data from authStore:", userData);
// Determine if this is a superadmin by checking the collection name
const isSuperAdmin = userData.collectionName === '_superusers';
@@ -90,13 +90,13 @@ export const authService = {
try {
// Fetch the latest user data from the server
const userId = (pb.authStore.model as any).id;
console.log("Refreshing user data for ID:", userId);
// console.log("Refreshing user data for ID:", userId);
// Use the getOne method directly to refresh the auth store
await pb.collection('users').getOne(userId);
console.log("User data refreshed successfully");
// console.log("User data refreshed successfully");
} catch (error) {
console.error('Failed to refresh user data:', error);
// console.error('Failed to refresh user data:', error);
}
}
};
@@ -3,12 +3,12 @@ import { IncidentItem } from './types';
// Export functions to update and invalidate the cache
export const updateCache = (data: IncidentItem[]) => {
console.log(`Updating cache with ${data.length} incidents`);
// console.log(`Updating cache with ${data.length} incidents`);
// The actual cache is now maintained in incidentFetch.ts
};
// Reset cache and request state
export const invalidateCache = () => {
console.log('Invalidating incidents cache');
// console.log('Invalidating incidents cache');
// The invalidation is handled in incidentFetch.ts implementation
};
@@ -25,7 +25,7 @@ export const isCacheValid = (): boolean => {
export const getAllIncidents = async (forceRefresh = false): Promise<IncidentItem[]> => {
// If a request is in progress, wait for it to complete rather than making a new one
if (isRequestInProgress) {
console.log('Request already in progress, waiting for completion');
// console.log('Request already in progress, waiting for completion');
try {
if (pendingRequest) {
await pendingRequest;
@@ -39,12 +39,12 @@ export const getAllIncidents = async (forceRefresh = false): Promise<IncidentIte
// Use cache if available, not expired, and not forced refresh
if (!forceRefresh && isCacheValid()) {
console.log('Using cached incidents data from', new Date(incidentsCache!.timestamp).toLocaleTimeString());
// console.log('Using cached incidents data from', new Date(incidentsCache!.timestamp).toLocaleTimeString());
return incidentsCache!.data;
}
try {
console.log('Fetching all incidents from API...');
// console.log('Fetching all incidents from API...');
isRequestInProgress = true;
// Implement timeout for the request
@@ -72,7 +72,7 @@ export const getAllIncidents = async (forceRefresh = false): Promise<IncidentIte
isRequestInProgress = false;
if (!result || !result.items) {
console.warn('No incidents found in API response');
// console.warn('No incidents found in API response');
return [];
}
@@ -81,7 +81,7 @@ export const getAllIncidents = async (forceRefresh = false): Promise<IncidentIte
// Update cache
updateCache(normalizedItems);
console.log(`Fetched ${normalizedItems.length} incidents at ${new Date().toLocaleTimeString()}`);
// console.log(`Fetched ${normalizedItems.length} incidents at ${new Date().toLocaleTimeString()}`);
return normalizedItems;
} catch (error) {
if ((error as any)?.isAbort) {
@@ -89,7 +89,7 @@ export const getAllIncidents = async (forceRefresh = false): Promise<IncidentIte
return incidentsCache?.data || [];
}
console.error('Error fetching incidents:', error);
// console.error('Error fetching incidents:', error);
// Clear states to allow retry
pendingRequest = null;
@@ -102,7 +102,7 @@ export const getAllIncidents = async (forceRefresh = false): Promise<IncidentIte
// Still return cached data even on error
if (incidentsCache) {
console.log('Returning stale cached data after error');
// console.log('Returning stale cached data after error');
return incidentsCache.data;
}
@@ -113,13 +113,13 @@ export const getAllIncidents = async (forceRefresh = false): Promise<IncidentIte
// Get incident by id
export const getIncidentById = async (id: string): Promise<IncidentItem | null> => {
try {
console.log(`Fetching incident with ID: ${id}`);
// console.log(`Fetching incident with ID: ${id}`);
// First check if the incident exists in the cache
if (isCacheValid() && incidentsCache) {
const cachedIncident = incidentsCache.data.find(incident => incident.id === id);
if (cachedIncident) {
console.log('Incident found in cache');
// console.log('Incident found in cache');
return cachedIncident;
}
}
@@ -136,7 +136,7 @@ export const getIncidentById = async (id: string): Promise<IncidentItem | null>
return normalizedIncident;
} catch (error) {
console.error(`Error fetching incident with ID ${id}:`, error);
// console.error(`Error fetching incident with ID ${id}:`, error);
if (error instanceof Error) {
throw new Error(`Failed to fetch incident: ${error.message}`);
@@ -16,20 +16,20 @@ export const maintenanceNotificationService = {
*/
async sendMaintenanceNotification({ maintenance, notificationType }: NotificationParams): Promise<boolean> {
try {
console.log(`Preparing to send ${notificationType} notification for maintenance: ${maintenance.title}`);
// console.log(`Preparing to send ${notificationType} notification for maintenance: ${maintenance.title}`);
// Get notification channel ID - try both fields
let notificationChannelId = maintenance.notification_channel_id;
// If notification_channel_id is empty, try to use notification_id
if (!notificationChannelId && maintenance.notification_id) {
console.log(`No notification_channel_id found, using notification_id: ${maintenance.notification_id}`);
// console.log(`No notification_channel_id found, using notification_id: ${maintenance.notification_id}`);
notificationChannelId = maintenance.notification_id;
}
// Check if maintenance has notification channel configured
if (!notificationChannelId) {
console.log("No notification channel configured for this maintenance");
// console.log("No notification channel configured for this maintenance");
return false;
}
@@ -41,19 +41,19 @@ export const maintenanceNotificationService = {
const config = await pb.collection('alert_configurations').getOne(notificationChannelId);
notificationConfig = config as unknown as AlertConfiguration;
} catch (error) {
console.error("Failed to fetch notification configuration:", error);
// console.error("Failed to fetch notification configuration:", error);
return false;
}
if (!notificationConfig.enabled) {
console.log("Notification channel is disabled");
// console.log("Notification channel is disabled");
return false;
}
// Create notification message based on type
const message = this.generateMaintenanceMessage(maintenance, notificationType);
console.log(`Sending ${notificationConfig.notification_type} notification with message: ${message}`);
// console.log(`Sending ${notificationConfig.notification_type} notification with message: ${message}`);
// Send notification based on channel type
if (notificationConfig.notification_type === 'telegram') {
@@ -62,10 +62,10 @@ export const maintenanceNotificationService = {
// Add more notification types here as needed
console.log(`Unsupported notification type: ${notificationConfig.notification_type}`);
// console.log(`Unsupported notification type: ${notificationConfig.notification_type}`);
return false;
} catch (error) {
console.error("Error sending maintenance notification:", error);
// console.error("Error sending maintenance notification:", error);
return false;
}
},
@@ -115,12 +115,12 @@ export const maintenanceNotificationService = {
// Set up scheduled maintenance notifications
export const setupMaintenanceNotificationsScheduler = () => {
console.log("Setting up maintenance notifications scheduler");
// console.log("Setting up maintenance notifications scheduler");
// Check every minute for maintenance that needs notifications
const checkInterval = setInterval(async () => {
try {
console.log("Checking for maintenance notifications to send...");
// console.log("Checking for maintenance notifications to send...");
const now = new Date();
// Fetch upcoming and ongoing maintenance
@@ -143,7 +143,7 @@ export const setupMaintenanceNotificationsScheduler = () => {
startTime <= new Date(now.getTime() + 60000) &&
startTime > new Date(now.getTime() - 60000)) {
console.log(`Maintenance ${maintenance.title} is starting now, sending notification`);
// console.log(`Maintenance ${maintenance.title} is starting now, sending notification`);
await maintenanceNotificationService.sendMaintenanceNotification({
maintenance,
notificationType: 'start'
@@ -160,7 +160,7 @@ export const setupMaintenanceNotificationsScheduler = () => {
endTime <= new Date(now.getTime() + 60000) &&
endTime > new Date(now.getTime() - 60000)) {
console.log(`Maintenance ${maintenance.title} is ending now, sending notification`);
// console.log(`Maintenance ${maintenance.title} is ending now, sending notification`);
await maintenanceNotificationService.sendMaintenanceNotification({
maintenance,
notificationType: 'end'
@@ -173,7 +173,7 @@ export const setupMaintenanceNotificationsScheduler = () => {
}
}
} catch (error) {
console.error("Error checking maintenance notifications:", error);
// console.error("Error checking maintenance notifications:", error);
}
}, 60000); // Check every minute
@@ -186,7 +186,7 @@ let notificationScheduler: NodeJS.Timeout | null = null;
export const initMaintenanceNotifications = () => {
if (notificationScheduler === null) {
notificationScheduler = setupMaintenanceNotificationsScheduler();
console.log("Maintenance notifications scheduler initialized");
// console.log("Maintenance notifications scheduler initialized");
}
};
@@ -194,6 +194,6 @@ export const stopMaintenanceNotifications = () => {
if (notificationScheduler !== null) {
clearInterval(notificationScheduler);
notificationScheduler = null;
console.log("Maintenance notifications scheduler stopped");
// console.log("Maintenance notifications scheduler stopped");
}
};
@@ -12,13 +12,13 @@ export async function startAllActiveServices(): Promise<void> {
filter: 'status != "paused"'
});
console.log(`Starting monitoring for ${result.items.length} active services`);
// console.log(`Starting monitoring for ${result.items.length} active services`);
// Start monitoring each active service
for (const service of result.items) {
await startMonitoringService(service.id);
}
} catch (error) {
console.error("Error starting all active services:", error);
// console.error("Error starting all active services:", error);
}
}
@@ -9,7 +9,7 @@ export async function startMonitoringService(serviceId: string): Promise<void> {
try {
// First check if the service is already being monitored
if (monitoringIntervals.has(serviceId)) {
console.log(`Service ${serviceId} is already being monitored`);
// console.log(`Service ${serviceId} is already being monitored`);
return;
}
@@ -18,11 +18,11 @@ export async function startMonitoringService(serviceId: string): Promise<void> {
// If service was manually paused, don't auto-resume
if (service.status === "paused") {
console.log(`Service ${serviceId} (${service.name}) is paused. Not starting monitoring.`);
// console.log(`Service ${serviceId} (${service.name}) is paused. Not starting monitoring.`);
return;
}
console.log(`Starting monitoring for service ${serviceId} (${service.name})`);
// console.log(`Starting monitoring for service ${serviceId} (${service.name})`);
// Update the service status to active/up in the database
await pb.collection('services').update(serviceId, {
@@ -32,18 +32,18 @@ export async function startMonitoringService(serviceId: string): Promise<void> {
// The actual service checking is now handled by the Go microservice
// This frontend service just tracks the monitoring state
const intervalMs = (service.heartbeat_interval || 60) * 1000;
console.log(`Service ${service.name} monitoring delegated to backend service`);
// console.log(`Service ${service.name} monitoring delegated to backend service`);
// Store a placeholder interval to track that this service is being monitored
const intervalId = window.setInterval(() => {
console.log(`Monitoring active for service ${service.name} (handled by backend)`);
// console.log(`Monitoring active for service ${service.name} (handled by backend)`);
}, intervalMs);
// Store the interval ID for this service
monitoringIntervals.set(serviceId, intervalId);
console.log(`Monitoring registered for service ${serviceId}`);
// console.log(`Monitoring registered for service ${serviceId}`);
} catch (error) {
console.error("Error starting service monitoring:", error);
// console.error("Error starting service monitoring:", error);
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ export const serviceService = {
regional_monitoring_enabled: item.regional_status === "enabled", // Backward compatibility
}));
} catch (error) {
console.error("Error fetching services:", error);
// console.error("Error fetching services:", error);
throw new Error('Failed to load services data.');
}
},
@@ -8,7 +8,7 @@ import { toast } from "sonner";
*/
export const fetchSSLCertificates = async (): Promise<SSLCertificate[]> => {
try {
console.log("Fetching SSL certificates from PocketBase...");
// console.log("Fetching SSL certificates from PocketBase...");
// Using the direct API path to fetch SSL certificates
const endpoint = "/api/collections/ssl_certificates/records";
@@ -23,7 +23,7 @@ export const fetchSSLCertificates = async (): Promise<SSLCertificate[]> => {
const queryString = new URLSearchParams(params as any).toString();
const fullEndpoint = `${endpoint}?${queryString}`;
console.log("Fetching SSL certificates from:", fullEndpoint);
// console.log("Fetching SSL certificates from:", fullEndpoint);
const response = await pb.send(fullEndpoint, {
method: "GET",
headers: {
@@ -39,14 +39,14 @@ export const fetchSSLCertificates = async (): Promise<SSLCertificate[]> => {
throw new Error("Invalid response format from PocketBase API");
}
console.log("Received SSL certificates:", response.items.length);
// console.log("Received SSL certificates:", response.items.length);
// Map items to SSLCertificate[] type with validation
return response.items.map(item => {
const cert = item as SSLCertificate;
// Log certificate details for debugging
console.log(`Certificate for ${cert.domain}: Issued by ${cert.issuer_o}, Days left: ${cert.days_left}`);
// console.log(`Certificate for ${cert.domain}: Issued by ${cert.issuer_o}, Days left: ${cert.days_left}`);
// Ensure dates are valid
try {
@@ -54,7 +54,7 @@ export const fetchSSLCertificates = async (): Promise<SSLCertificate[]> => {
if (cert.valid_till) new Date(cert.valid_till).toISOString();
if (cert.last_notified) new Date(cert.last_notified).toISOString();
} catch (e) {
console.warn("Invalid date found in certificate", cert.id, e);
// console.warn("Invalid date found in certificate", cert.id, e);
// Fix invalid dates if needed
if (cert.valid_from && isNaN(new Date(cert.valid_from).getTime())) {
cert.valid_from = new Date().toISOString();
@@ -74,7 +74,7 @@ export const fetchSSLCertificates = async (): Promise<SSLCertificate[]> => {
const diffTime = expirationDate.getTime() - currentDate.getTime();
cert.days_left = Math.ceil(diffTime / (1000 * 3600 * 24));
} catch (e) {
console.warn("Error calculating days_left for certificate", cert.id, e);
// console.warn("Error calculating days_left for certificate", cert.id, e);
cert.days_left = 0;
}
}
@@ -82,7 +82,7 @@ export const fetchSSLCertificates = async (): Promise<SSLCertificate[]> => {
return cert;
});
} catch (error) {
console.error("Error fetching SSL certificates:", error);
// console.error("Error fetching SSL certificates:", error);
toast.error("Failed to fetch SSL certificates. Please try again later.");
throw error;
}
+20 -20
View File
@@ -31,7 +31,7 @@ const getCollectionForServiceType = (serviceType: string): string => {
export const uptimeService = {
async recordUptimeData(data: UptimeData): Promise<void> {
try {
console.log(`Recording uptime data for service ${data.serviceId || data.service_id}: Status ${data.status}, Response time: ${data.responseTime}ms`);
// console.log(`Recording uptime data for service ${data.serviceId || data.service_id}: Status ${data.status}, Response time: ${data.responseTime}ms`);
const options = {
$autoCancel: false,
@@ -50,9 +50,9 @@ export const uptimeService = {
const keysToDelete = Array.from(uptimeCache.keys()).filter(key => key.includes(`uptime_${serviceId}`));
keysToDelete.forEach(key => uptimeCache.delete(key));
console.log(`Uptime data recorded successfully with ID: ${record.id}`);
// console.log(`Uptime data recorded successfully with ID: ${record.id}`);
} catch (error) {
console.error("Error recording uptime data:", error);
// console.error("Error recording uptime data:", error);
throw new Error(`Failed to record uptime data: ${error}`);
}
},
@@ -66,7 +66,7 @@ export const uptimeService = {
): Promise<UptimeData[]> {
try {
if (!serviceId) {
console.log('No serviceId provided to getUptimeHistory');
// console.log('No serviceId provided to getUptimeHistory');
return [];
}
@@ -75,13 +75,13 @@ export const uptimeService = {
// Check cache
const cached = uptimeCache.get(cacheKey);
if (cached && (Date.now() - cached.timestamp) < cached.expiresIn) {
console.log(`Using cached uptime history for service ${serviceId}`);
// console.log(`Using cached uptime history for service ${serviceId}`);
return cached.data;
}
// Determine the correct collection based on service type
const collection = serviceType ? getCollectionForServiceType(serviceType) : 'uptime_data';
console.log(`Fetching default uptime history for service ${serviceId} from collection ${collection}, limit: ${limit}`);
// console.log(`Fetching default uptime history for service ${serviceId} from collection ${collection}, limit: ${limit}`);
// Build filter to get records for specific service_id
let filter = `service_id='${serviceId}'`;
@@ -91,7 +91,7 @@ export const uptimeService = {
const startUTC = startDate.toISOString();
const endUTC = endDate.toISOString();
console.log(`Date filter: ${startUTC} to ${endUTC}`);
// console.log(`Date filter: ${startUTC} to ${endUTC}`);
filter += ` && timestamp >= "${startUTC}" && timestamp <= "${endUTC}"`;
}
@@ -102,16 +102,16 @@ export const uptimeService = {
$cancelKey: `uptime_history_${serviceId}_${Date.now()}`
};
console.log(`Filter query for default data: ${filter} on collection: ${collection}`);
// console.log(`Filter query for default data: ${filter} on collection: ${collection}`);
const response = await pb.collection(collection).getList(1, limit, options);
console.log(`Fetched ${response.items.length} records for service ${serviceId} from ${collection}`);
// console.log(`Fetched ${response.items.length} records for service ${serviceId} from ${collection}`);
if (response.items.length > 0) {
console.log(`Date range in results: ${response.items[response.items.length - 1].timestamp} to ${response.items[0].timestamp}`);
// console.log(`Date range in results: ${response.items[response.items.length - 1].timestamp} to ${response.items[0].timestamp}`);
} else {
console.log(`No records found for service_id '${serviceId}' in collection: ${collection}`);
// console.log(`No records found for service_id '${serviceId}' in collection: ${collection}`);
}
// Transform the response items to UptimeData format
@@ -137,18 +137,18 @@ export const uptimeService = {
return uptimeData;
} catch (error) {
console.error(`Error fetching uptime history for service ${serviceId}:`, error);
// console.error(`Error fetching uptime history for service ${serviceId}:`, error);
// Try to return cached data as fallback
const cacheKey = `uptime_${serviceId}_${limit}_${startDate?.toISOString() || ''}_${endDate?.toISOString() || ''}_${serviceType || 'default'}_default`;
const cached = uptimeCache.get(cacheKey);
if (cached) {
console.log(`Using expired cached data for service ${serviceId} due to fetch error`);
// console.log(`Using expired cached data for service ${serviceId} due to fetch error`);
return cached.data;
}
// Return empty array instead of throwing to prevent UI crashes
console.log(`Returning empty array for service ${serviceId} due to fetch error`);
// console.log(`Returning empty array for service ${serviceId} due to fetch error`);
return [];
}
},
@@ -164,7 +164,7 @@ export const uptimeService = {
): Promise<UptimeData[]> {
try {
if (!regionName || !agentId) {
console.log('No region name or agent ID provided for regional query');
// console.log('No region name or agent ID provided for regional query');
return [];
}
@@ -173,13 +173,13 @@ export const uptimeService = {
// Check cache
const cached = uptimeCache.get(cacheKey);
if (cached && (Date.now() - cached.timestamp) < cached.expiresIn) {
console.log(`Using cached regional uptime history for service ${serviceId}`);
// console.log(`Using cached regional uptime history for service ${serviceId}`);
return cached.data;
}
// Determine the correct collection based on service type
const collection = serviceType ? getCollectionForServiceType(serviceType) : 'uptime_data';
console.log(`Fetching regional uptime history from collection: ${collection} for service: ${serviceId}, region: ${regionName}, agent: ${agentId}`);
// console.log(`Fetching regional uptime history from collection: ${collection} for service: ${serviceId}, region: ${regionName}, agent: ${agentId}`);
// Build filter for regional agent data
let filter = `service_id="${serviceId}" && region_name="${regionName}" && agent_id="${agentId}"`;
@@ -190,7 +190,7 @@ export const uptimeService = {
filter += ` && timestamp>="${startISO}" && timestamp<="${endISO}"`;
}
console.log(`Regional filter query: ${filter} on collection: ${collection}`);
// console.log(`Regional filter query: ${filter} on collection: ${collection}`);
const records = await pb.collection(collection).getList(1, limit, {
sort: '-timestamp',
@@ -199,7 +199,7 @@ export const uptimeService = {
$cancelKey: `regional_uptime_history_${serviceId}_${Date.now()}`
});
console.log(`Retrieved ${records.items.length} regional uptime records from ${collection} for region ${regionName}, agent ${agentId}`);
// console.log(`Retrieved ${records.items.length} regional uptime records from ${collection} for region ${regionName}, agent ${agentId}`);
const uptimeData = records.items.map(item => ({
id: item.id,
@@ -224,7 +224,7 @@ export const uptimeService = {
return uptimeData;
} catch (error) {
const collectionForError = serviceType ? getCollectionForServiceType(serviceType) : 'uptime_data';
console.error(`Error fetching regional uptime history from ${collectionForError}:`, error);
// console.error(`Error fetching regional uptime history from ${collectionForError}:`, error);
return [];
}
}
+30 -30
View File
@@ -58,7 +58,7 @@ const convertToUserType = (record: any, role: string = "admin"): User => {
export const userService = {
async getUsers(): Promise<User[] | null> {
try {
console.log("Calling getUsers API");
// console.log("Calling getUsers API");
// Get both regular users and superadmins
const regularUsers = await pb.collection('users').getList(1, 50, {
@@ -71,9 +71,9 @@ export const userService = {
superadminUsers = await pb.collection('_superusers').getList(1, 50, {
sort: 'created',
});
console.log("Successfully fetched superadmin users:", superadminUsers);
// console.log("Successfully fetched superadmin users:", superadminUsers);
} catch (error) {
console.log("No superadmin collection or access rights:", error);
// console.log("No superadmin collection or access rights:", error);
}
// Combine both user types and mark superadmins
@@ -82,39 +82,39 @@ export const userService = {
...superadminUsers.items.map((user: any) => convertToUserType(user, "superadmin"))
];
console.log("Combined users list:", allUsers);
// console.log("Combined users list:", allUsers);
return allUsers;
} catch (error) {
console.error("Failed to fetch users:", error);
// console.error("Failed to fetch users:", error);
return null;
}
},
async getUser(id: string): Promise<User | null> {
try {
console.log(`Fetching user with ID: ${id}`);
// console.log(`Fetching user with ID: ${id}`);
// Try fetching from regular users first
try {
const user = await pb.collection('users').getOne(id);
console.log("User fetch result (regular user):", user);
// console.log("User fetch result (regular user):", user);
return convertToUserType(user, user.role || "admin");
} catch (error) {
console.log("User not found in regular users, trying superadmin collection");
// console.log("User not found in regular users, trying superadmin collection");
}
// If not found, try in superadmins
try {
const user = await pb.collection('_superusers').getOne(id);
console.log("User fetch result (superadmin):", user);
// console.log("User fetch result (superadmin):", user);
return convertToUserType(user, "superadmin");
} catch (error) {
console.log("User not found in superadmin collection either");
// console.log("User not found in superadmin collection either");
return null;
}
} catch (error) {
console.error(`Failed to fetch user ${id}:`, error);
// console.error(`Failed to fetch user ${id}:`, error);
return null;
}
},
@@ -130,11 +130,11 @@ export const userService = {
}
});
console.log("Updating user with clean data:", cleanData);
// console.log("Updating user with clean data:", cleanData);
// If there's nothing to update, return the current user
if (Object.keys(cleanData).length === 0) {
console.log("No changes to update");
// console.log("No changes to update");
const currentUser = await this.getUser(id);
return currentUser;
}
@@ -197,16 +197,16 @@ export const userService = {
await pb.collection('_superusers').delete(id);
updatedUser = convertToUserType(newRegularUser, "admin");
}
console.log("User transferred between collections due to role change");
// console.log("User transferred between collections due to role change");
} catch (error) {
console.error("Failed to transfer user between collections:", error);
// console.error("Failed to transfer user between collections:", error);
throw new Error("Failed to change user role: " + (error instanceof Error ? error.message : "Unknown error"));
}
} else {
// Regular update without changing collections
if (Object.keys(cleanData).length > 0) {
console.log("Final update payload to PocketBase:", cleanData);
// console.log("Final update payload to PocketBase:", cleanData);
try {
// Use the appropriate collection
@@ -214,15 +214,15 @@ export const userService = {
const updatedRecord = await pb.collection(collection).update(id, cleanData);
updatedUser = convertToUserType(updatedRecord, isCurrentlySuperadmin ? "superadmin" : "admin");
console.log("PocketBase update response:", updatedUser);
// console.log("PocketBase update response:", updatedUser);
// If email was updated successfully, show success message
if (hasEmailChange) {
console.log("Email updated successfully to:", emailToUpdate);
// console.log("Email updated successfully to:", emailToUpdate);
}
} catch (error) {
console.error("Error updating user:", error);
// console.error("Error updating user:", error);
// Provide more specific error messages for email issues
if (hasEmailChange && error instanceof Error) {
@@ -241,7 +241,7 @@ export const userService = {
return updatedUser;
} catch (error) {
console.error("Failed to update user:", error);
// console.error("Failed to update user:", error);
throw error; // Re-throw to handle in the component
}
},
@@ -253,7 +253,7 @@ export const userService = {
await pb.collection('users').delete(id);
return true;
} catch (error) {
console.log("User not found in regular users, trying superadmin collection");
// console.log("User not found in regular users, trying superadmin collection");
}
// If not found, try deleting from superadmin collection
@@ -261,11 +261,11 @@ export const userService = {
await pb.collection('_superusers').delete(id);
return true;
} catch (error) {
console.error("Failed to delete user from either collection:", error);
// console.error("Failed to delete user from either collection:", error);
return false;
}
} catch (error) {
console.error("Failed to delete user:", error);
// console.error("Failed to delete user:", error);
return false;
}
},
@@ -282,7 +282,7 @@ export const userService = {
if (cleanData.avatar.startsWith('http') ||
cleanData.avatar.startsWith('/upload/') ||
cleanData.avatar.includes('api.dicebear.com')) {
console.log("Removing avatar URL for new user creation:", cleanData.avatar);
// console.log("Removing avatar URL for new user creation:", cleanData.avatar);
delete cleanData.avatar;
}
}
@@ -291,18 +291,18 @@ export const userService = {
const isSuperAdmin = cleanData.role === "superadmin";
const collection = isSuperAdmin ? '_superusers' : 'users';
console.log(`Creating new user in ${collection} collection with data:`, {
...cleanData,
password: "[REDACTED]",
passwordConfirm: "[REDACTED]"
});
/// console.log(`Creating new user in ${collection} collection with data:`, {
// ...cleanData,
// password: "[REDACTED]",
// passwordConfirm: "[REDACTED]"
// });
// Create the user in the appropriate collection
const result = await pb.collection(collection).create(cleanData);
return convertToUserType(result, isSuperAdmin ? "superadmin" : "admin");
} catch (error) {
console.error("Failed to create user:", error);
// console.error("Failed to create user:", error);
throw error;
}
}