From 302e14196c9a9bddab0cc21c03c68a8a1cca2b13 Mon Sep 17 00:00:00 2001 From: alorig <220087330+alorig@users.noreply.github.com> Date: Sat, 29 Nov 2025 23:16:56 +0500 Subject: [PATCH] sda --- frontend/src/pages/Settings/DebugStatus.tsx | 311 +----------------- .../Settings/WordPressIntegrationDebug.tsx | 10 +- 2 files changed, 5 insertions(+), 316 deletions(-) diff --git a/frontend/src/pages/Settings/DebugStatus.tsx b/frontend/src/pages/Settings/DebugStatus.tsx index 714a0730..527f329f 100644 --- a/frontend/src/pages/Settings/DebugStatus.tsx +++ b/frontend/src/pages/Settings/DebugStatus.tsx @@ -117,319 +117,10 @@ export default function DebugStatus() { // Tab navigation state const [activeTab, setActiveTab] = useState<'system-health' | 'wp-integration'>('system-health'); - // Debug state - const [debugEnabled, setDebugEnabled] = useState(false); - const [loading, setLoading] = useState(false); - const [pollingInterval, setPollingInterval] = useState(null); - // Data state + const [loading, setLoading] = useState(false); const [moduleHealths, setModuleHealths] = useState([]); - // Helper to get auth token - const getAuthToken = () => { - const token = localStorage.getItem('auth_token') || - (() => { - try { - const authStorage = localStorage.getItem('auth-storage'); - if (authStorage) { - const parsed = JSON.parse(authStorage); - return parsed?.state?.token || ''; - } - } catch (e) { - // Ignore parsing errors - } - return ''; - })(); - return token; - }; - - // Helper to make authenticated API calls with debug awareness - const apiCall = async (path: string, method: string = 'GET', body?: any) => { - // Skip API calls if debug is disabled (unless it's essential) - if (!debugEnabled && !path.includes('/debug-status/')) { - console.log('[DEBUG] Skipping API call - debug disabled:', path); - return { response: null, data: null }; - } - - const token = getAuthToken(); - const headers: HeadersInit = { - 'Content-Type': 'application/json', - }; - - if (token) { - headers['Authorization'] = `Bearer ${token}`; - } - - const options: RequestInit = { - method, - headers, - credentials: 'include', - }; - - if (body && method !== 'GET') { - options.body = JSON.stringify(body); - } - - try { - if (debugEnabled) { - console.log('[DEBUG] API Call:', method, path, body ? { body } : {}); - } - - const response = await fetch(`${API_BASE_URL}${path}`, options); - const data = await response.json(); - - if (debugEnabled) { - console.log('[DEBUG] API Response:', response.status, data); - } - - return { response, data }; - } catch (error) { - if (debugEnabled) { - console.error('[DEBUG] API Error:', error); - } - throw error; - } - }; - - // Toggle debug mode - const toggleDebugMode = async (enabled: boolean) => { - if (!activeSite) { - toast.error('Please select a site first'); - return; - } - - try { - setLoading(true); - - // Set local debug state first for immediate UI response - setDebugEnabled(enabled); - - if (enabled) { - console.log('[DEBUG] 🎯 Debug mode ENABLED for site:', activeSite.name); - toast.success('Debug mode enabled - verbose logging started'); - - // Start polling for updates - startPolling(); - - // Trigger debug mode on WordPress plugin if integrated - if (activeSite.id) { - await apiCall(`/integration/integrations/${activeSite.id}/trigger-debug/`, 'POST', { - debug_enabled: true - }); - } - } else { - console.log('[DEBUG] πŸ”’ Debug mode DISABLED'); - toast.info('Debug mode disabled - reduced logging'); - - // Stop polling - stopPolling(); - - // Disable debug on WordPress - if (activeSite.id) { - await apiCall(`/integration/integrations/${activeSite.id}/trigger-debug/`, 'POST', { - debug_enabled: false - }); - } - } - } catch (error) { - console.error('[DEBUG] Failed to toggle debug mode:', error); - toast.error('Failed to toggle debug mode'); - setDebugEnabled(!enabled); // Revert - } finally { - setLoading(false); - } - }; - - // Start polling for debug data - const startPolling = () => { - if (pollingInterval) return; - - const interval = setInterval(() => { - if (debugEnabled && activeSite) { - loadDebugData(); - } - }, 5000); // Poll every 5 seconds when debug is enabled - - setPollingInterval(interval); - console.log('[DEBUG] ⏰ Started polling for debug updates'); - }; - - // Stop polling - const stopPolling = () => { - if (pollingInterval) { - clearInterval(pollingInterval); - setPollingInterval(null); - console.log('[DEBUG] ⏸️ Stopped polling'); - } - }; - - // Load all debug data - const loadDebugData = useCallback(async () => { - if (!activeSite || !debugEnabled) return; - - try { - setLoading(true); - console.log('[DEBUG] πŸ“Š Loading debug data for site:', activeSite.name); - - // Load integration health - await loadIntegrationHealth(); - - // Load sync events - await loadSyncEvents(); - - // Load validation data - await loadDataValidation(); - - // Load module health (existing logic) - await checkAllModules(); - - console.log('[DEBUG] βœ… Debug data loaded successfully'); - } catch (error) { - console.error('[DEBUG] ❌ Failed to load debug data:', error); - if (debugEnabled) { - toast.error('Failed to load debug data'); - } - } finally { - setLoading(false); - } - }, [activeSite, debugEnabled]); - - // Load integration health - const loadIntegrationHealth = async () => { - if (!activeSite) return; - - try { - const { data } = await apiCall(`/integration/integrations/${activeSite.id}/debug-status/`); - - if (data?.success) { - setIntegrationHealth(data.data.health); - console.log('[DEBUG] πŸ’š Integration health loaded'); - } - } catch (error) { - console.error('[DEBUG] Failed to load integration health:', error); - } - }; - - // Load sync events - const loadSyncEvents = async () => { - if (!activeSite) return; - - try { - const { data } = await apiCall(`/integration/integrations/${activeSite.id}/debug-status/?include_events=true`); - - if (data?.success && data.data?.events) { - setSyncEvents(data.data.events); - console.log('[DEBUG] πŸ“œ Loaded', data.data.events.length, 'sync events'); - } - } catch (error) { - console.error('[DEBUG] Failed to load sync events:', error); - } - }; - - // Load data validation matrix - const loadDataValidation = async () => { - if (!activeSite) return; - - try { - const { data } = await apiCall(`/integration/integrations/${activeSite.id}/debug-status/?include_validation=true`); - - if (data?.success && data.data?.validation) { - setDataValidation(data.data.validation); - console.log('[DEBUG] 🧩 Loaded data validation matrix'); - } - } catch (error) { - console.error('[DEBUG] Failed to load data validation:', error); - } - }; - - // Interactive tools - const testConnection = async () => { - if (!activeSite) return; - - try { - setLoading(true); - console.log('[DEBUG] πŸ”§ Testing connection to WordPress...'); - - const { data } = await apiCall(`/integration/integrations/${activeSite.id}/test-connection/`, 'POST'); - - if (data?.success) { - toast.success('Connection test successful'); - await loadIntegrationHealth(); // Refresh health data - } else { - toast.error('Connection test failed: ' + data?.message); - } - } catch (error) { - console.error('[DEBUG] Connection test error:', error); - toast.error('Connection test failed'); - } finally { - setLoading(false); - } - }; - - const resyncSiteMetadata = async () => { - if (!activeSite) return; - - try { - setLoading(true); - console.log('[DEBUG] πŸ”„ Re-syncing site metadata...'); - - const { data } = await apiCall(`/integration/integrations/${activeSite.id}/resync-metadata/`, 'POST'); - - if (data?.success) { - toast.success('Site metadata re-synced successfully'); - await loadDebugData(); // Refresh all data - } else { - toast.error('Re-sync failed: ' + data?.message); - } - } catch (error) { - console.error('[DEBUG] Metadata resync error:', error); - toast.error('Metadata re-sync failed'); - } finally { - setLoading(false); - } - }; - - const validatePostSync = async (taskId?: number) => { - if (!activeSite) return; - - const id = taskId || prompt('Enter Task ID to validate:'); - if (!id) return; - - try { - setLoading(true); - console.log('[DEBUG] πŸ” Validating post sync for task:', id); - - const { data } = await apiCall(`/integration/integrations/${activeSite.id}/validate-content/${id}/`); - - if (data?.success) { - toast.success('Post validation completed'); - setDataValidation(data.data.validation || []); - } else { - toast.error('Validation failed: ' + data?.message); - } - } catch (error) { - console.error('[DEBUG] Post validation error:', error); - toast.error('Post validation failed'); - } finally { - setLoading(false); - } - }; - - // Effects - useEffect(() => { - // Load initial data when site changes - if (activeSite && debugEnabled) { - loadDebugData(); - } - }, [activeSite, debugEnabled]); - - useEffect(() => { - // Cleanup polling on unmount - return () => { - stopPolling(); - }; - }, []); - // Check database schema field mappings (the issues we just fixed) const checkDatabaseSchemaMapping = useCallback(async (): Promise => { try { diff --git a/frontend/src/pages/Settings/WordPressIntegrationDebug.tsx b/frontend/src/pages/Settings/WordPressIntegrationDebug.tsx index abbfaeb3..c814ae36 100644 --- a/frontend/src/pages/Settings/WordPressIntegrationDebug.tsx +++ b/frontend/src/pages/Settings/WordPressIntegrationDebug.tsx @@ -13,9 +13,10 @@ import { Wrench, Database } from 'lucide-react'; -import { toast } from 'react-hot-toast'; import SiteAndSectorSelector from '../../components/common/SiteAndSectorSelector'; import { useSiteStore } from '../../store/siteStore'; +import { useToast } from '../../components/ui/toast/ToastContainer'; +import { API_BASE_URL } from '../../services/api'; // Types for WordPress integration debugging interface IntegrationHealth { @@ -46,21 +47,18 @@ interface DataValidation { error?: string; } -const API_BASE_URL = process.env.NODE_ENV === 'production' - ? 'https://app.igny8.com/api' - : 'http://localhost:8000/api'; - export default function WordPressIntegrationDebug() { // State const [debugEnabled, setDebugEnabled] = useState(false); const [loading, setLoading] = useState(false); - const [pollingInterval, setPollingInterval] = useState(null); + const [pollingInterval, setPollingInterval] = useState(null); const [integrationHealth, setIntegrationHealth] = useState(null); const [syncEvents, setSyncEvents] = useState([]); const [dataValidation, setDataValidation] = useState([]); // Get active site from store const { activeSite } = useSiteStore(); + const toast = useToast(); // Helper to get auth token const getAuthToken = () => {