This commit is contained in:
IGNY8 VPS (Salman)
2025-11-29 19:50:22 +00:00
parent 302e14196c
commit 492a83ebcb
4 changed files with 569 additions and 294 deletions

View File

@@ -5,18 +5,15 @@ import {
AlertTriangle,
Loader2,
Activity,
Info,
Clock,
Globe,
RefreshCw,
TestTube,
Wrench,
Database
Wrench
} from 'lucide-react';
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';
import { API_BASE_URL, fetchAPI } from '../../services/api';
// Types for WordPress integration debugging
interface IntegrationHealth {
@@ -51,54 +48,57 @@ export default function WordPressIntegrationDebug() {
// State
const [debugEnabled, setDebugEnabled] = useState(false);
const [loading, setLoading] = useState(false);
const [initializing, setInitializing] = useState(true);
const [pollingInterval, setPollingInterval] = useState<any>(null);
const [integrationHealth, setIntegrationHealth] = useState<IntegrationHealth | null>(null);
const [syncEvents, setSyncEvents] = useState<SyncEvent[]>([]);
const [dataValidation, setDataValidation] = useState<DataValidation[]>([]);
const [integrationId, setIntegrationId] = useState<number | null>(null);
// Get active site from store
const { activeSite } = useSiteStore();
const toast = useToast();
// 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;
};
// Check if integration exists for the active site
useEffect(() => {
const checkIntegration = async () => {
if (!activeSite) {
setInitializing(false);
return;
}
try {
setInitializing(true);
const data = await fetchAPI(`/v1/integration/integrations/?site_id=${activeSite.id}`);
const integrations = data.results || [];
if (integrations.length > 0) {
const wpIntegration = integrations.find((i: any) => i.platform === 'wordpress');
if (wpIntegration) {
setIntegrationId(wpIntegration.id);
setDebugEnabled(wpIntegration.credentials_json?.debug_enabled || false);
}
}
} catch (error) {
console.error('[WP-DEBUG] Failed to check integration:', error);
} finally {
setInitializing(false);
}
};
checkIntegration();
}, [activeSite]);
// 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('[WP-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}`;
// Always allow debug-status calls to check if integration exists
if (!integrationId && !path.includes('/integrations/?')) {
console.log('[WP-DEBUG] Skipping API call - no integration configured:', path);
return { response: { ok: false, status: 0 } as Response, data: null };
}
const options: RequestInit = {
method,
headers,
credentials: 'include',
};
if (body && method !== 'GET') {
@@ -110,19 +110,19 @@ export default function WordPressIntegrationDebug() {
console.log('[WP-DEBUG] API Call:', method, path, body ? { body } : {});
}
const response = await fetch(`${API_BASE_URL}${path}`, options);
const data = await response.json();
const data = await fetchAPI(path, options);
if (debugEnabled) {
console.log('[WP-DEBUG] API Response:', response.status, data);
console.log('[WP-DEBUG] API Response:', data);
}
return { response, data };
} catch (error) {
return { response: { ok: true, status: 200 } as Response, data };
} catch (error: any) {
if (debugEnabled) {
console.error('[WP-DEBUG] API Error:', error);
}
throw error;
const errorData = error.response || { detail: error.message || 'Request failed' };
return { response: { ok: false, status: error.status || 500 } as Response, data: errorData };
}
};
@@ -133,6 +133,11 @@ export default function WordPressIntegrationDebug() {
return;
}
if (!integrationId) {
toast.error('No WordPress integration found for this site');
return;
}
try {
setLoading(true);
@@ -147,11 +152,12 @@ export default function WordPressIntegrationDebug() {
startPolling();
// Trigger debug mode on WordPress plugin if integrated
if (activeSite.id) {
await apiCall(`/integration/integrations/${activeSite.id}/trigger-debug/`, 'POST', {
debug_enabled: true
});
}
await apiCall(`/v1/integration/integrations/${integrationId}/trigger-debug/`, 'POST', {
debug_enabled: true
});
// Load initial debug data
await loadDebugData();
} else {
console.log('[WP-DEBUG] 🔒 WordPress Debug mode DISABLED');
toast.info('WordPress debug mode disabled - reduced logging');
@@ -160,11 +166,9 @@ export default function WordPressIntegrationDebug() {
stopPolling();
// Disable debug on WordPress
if (activeSite.id) {
await apiCall(`/integration/integrations/${activeSite.id}/trigger-debug/`, 'POST', {
debug_enabled: false
});
}
await apiCall(`/v1/integration/integrations/${integrationId}/trigger-debug/`, 'POST', {
debug_enabled: false
});
}
} catch (error) {
console.error('[WP-DEBUG] Failed to toggle debug mode:', error);
@@ -200,7 +204,10 @@ export default function WordPressIntegrationDebug() {
// Load all debug data
const loadDebugData = useCallback(async () => {
if (!activeSite || !debugEnabled) return;
if (!activeSite || !integrationId) {
console.log('[WP-DEBUG] Skipping load - no site or integration');
return;
}
try {
setLoading(true);
@@ -209,32 +216,30 @@ export default function WordPressIntegrationDebug() {
// Load integration health
await loadIntegrationHealth();
// Load sync events
await loadSyncEvents();
// Load validation data
await loadDataValidation();
// Load sync events if debug is enabled
if (debugEnabled) {
await loadSyncEvents();
await loadDataValidation();
}
console.log('[WP-DEBUG] ✅ WordPress debug data loaded successfully');
} catch (error) {
console.error('[WP-DEBUG] ❌ Failed to load WordPress debug data:', error);
if (debugEnabled) {
toast.error('Failed to load WordPress debug data');
}
// Don't show toast error on initial load
} finally {
setLoading(false);
}
}, [activeSite, debugEnabled]);
}, [activeSite, integrationId, debugEnabled]);
// Load integration health
const loadIntegrationHealth = async () => {
if (!activeSite) return;
if (!integrationId) return;
try {
const { data } = await apiCall(`/integration/integrations/${activeSite.id}/debug-status/`);
const { data } = await apiCall(`/v1/integration/integrations/${integrationId}/debug-status/`);
if (data?.success) {
setIntegrationHealth(data.data.health);
if (data?.health) {
setIntegrationHealth(data.health);
console.log('[WP-DEBUG] 💚 Integration health loaded');
}
} catch (error) {
@@ -244,14 +249,14 @@ export default function WordPressIntegrationDebug() {
// Load sync events
const loadSyncEvents = async () => {
if (!activeSite) return;
if (!integrationId) return;
try {
const { data } = await apiCall(`/integration/integrations/${activeSite.id}/debug-status/?include_events=true`);
const { data } = await apiCall(`/v1/integration/integrations/${integrationId}/debug-status/?include_events=true`);
if (data?.success && data.data?.events) {
setSyncEvents(data.data.events);
console.log('[WP-DEBUG] 📜 Loaded', data.data.events.length, 'WordPress sync events');
if (data?.events) {
setSyncEvents(data.events);
console.log('[WP-DEBUG] 📜 Loaded', data.events.length, 'WordPress sync events');
}
} catch (error) {
console.error('[WP-DEBUG] Failed to load sync events:', error);
@@ -260,13 +265,13 @@ export default function WordPressIntegrationDebug() {
// Load data validation matrix
const loadDataValidation = async () => {
if (!activeSite) return;
if (!integrationId) return;
try {
const { data } = await apiCall(`/integration/integrations/${activeSite.id}/debug-status/?include_validation=true`);
const { data } = await apiCall(`/v1/integration/integrations/${integrationId}/debug-status/?include_validation=true`);
if (data?.success && data.data?.validation) {
setDataValidation(data.data.validation);
if (data?.validation) {
setDataValidation(data.validation);
console.log('[WP-DEBUG] 🧩 Loaded WordPress data validation matrix');
}
} catch (error) {
@@ -276,19 +281,22 @@ export default function WordPressIntegrationDebug() {
// Interactive tools
const testConnection = async () => {
if (!activeSite) return;
if (!integrationId) {
toast.error('No WordPress integration found');
return;
}
try {
setLoading(true);
console.log('[WP-DEBUG] 🔧 Testing connection to WordPress...');
const { data } = await apiCall(`/integration/integrations/${activeSite.id}/test-connection/`, 'POST');
const { data } = await apiCall(`/v1/integration/integrations/${integrationId}/test-connection/`, 'POST');
if (data?.success) {
toast.success('WordPress connection test successful');
await loadIntegrationHealth(); // Refresh health data
} else {
toast.error('WordPress connection test failed: ' + data?.message);
toast.error('WordPress connection test failed: ' + (data?.message || 'Unknown error'));
}
} catch (error) {
console.error('[WP-DEBUG] Connection test error:', error);
@@ -298,6 +306,69 @@ export default function WordPressIntegrationDebug() {
}
};
// Load initial data when component mounts or integration changes
useEffect(() => {
if (!initializing && integrationId) {
loadDebugData();
}
}, [integrationId, initializing]);
// Start/stop polling based on debug state
useEffect(() => {
if (debugEnabled && integrationId) {
startPolling();
} else {
stopPolling();
}
return () => stopPolling();
}, [debugEnabled, integrationId]);
// Effects - Load initial data when site changes or integration found
useEffect(() => {
if (activeSite && integrationId && !initializing) {
loadDebugData();
// Auto-start polling for real-time updates if debug enabled
if (debugEnabled) {
startPolling();
}
}
return () => {
stopPolling();
};
}, [activeSite, integrationId, initializing]);
// Show loading state while initializing
if (initializing) {
return (
<div className="p-8 text-center">
<Loader2 className="h-8 w-8 animate-spin mx-auto text-blue-600 dark:text-blue-400" />
<p className="text-sm text-gray-500 dark:text-gray-400 mt-2">Loading WordPress integration...</p>
</div>
);
}
// Show message if no integration is configured
if (!integrationId) {
return (
<div className="p-8">
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-900/50 rounded-lg p-6 text-center">
<AlertTriangle className="h-12 w-12 text-yellow-600 dark:text-yellow-400 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
No WordPress Integration Found
</h3>
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
This site doesn't have a WordPress integration configured yet.
</p>
<p className="text-sm text-gray-600 dark:text-gray-400">
Please configure a WordPress integration in the <strong>Settings → Integration</strong> page first.
</p>
</div>
</div>
);
}
const resyncSiteMetadata = async () => {
if (!activeSite) return;
@@ -333,9 +404,9 @@ export default function WordPressIntegrationDebug() {
const { data } = await apiCall(`/integration/integrations/${activeSite.id}/validate-content/${id}/`);
if (data?.success) {
if (data) {
toast.success('WordPress post validation completed');
setDataValidation(data.data.validation || []);
setDataValidation(data.validation || []);
} else {
toast.error('WordPress validation failed: ' + data?.message);
}
@@ -347,100 +418,40 @@ export default function WordPressIntegrationDebug() {
}
};
// Effects
useEffect(() => {
// Load initial data when site changes
if (activeSite && debugEnabled) {
loadDebugData();
}
}, [activeSite, debugEnabled, loadDebugData]);
useEffect(() => {
// Cleanup polling on unmount
return () => {
stopPolling();
};
}, []);
return (
<div className="space-y-6">
{/* Debug Header with Site Selector and Toggle */}
<div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
<div className="flex items-center justify-between mb-4">
<div>
<h2 className="text-xl font-bold text-gray-900 dark:text-white">
IGNY8 WordPress Integration Debug
</h2>
<p className="text-gray-600 dark:text-gray-400 mt-1">
Real-time monitoring of WordPress bridge plugin and content synchronization
{/* No WordPress Integration Found */}
{initializing ? (
<div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6 text-center">
<Loader2 className="h-8 w-8 animate-spin mx-auto text-gray-400 mb-2" />
<p className="text-gray-600 dark:text-gray-400">Checking for WordPress integration...</p>
</div>
) : !integrationId && activeSite ? (
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-900/50 rounded-lg p-6">
<div className="flex items-start space-x-3">
<AlertTriangle className="h-8 w-8 text-yellow-500 mt-0.5" />
<div>
<p className="text-lg font-semibold text-yellow-800 dark:text-yellow-200">No WordPress Integration Found</p>
<p className="text-sm text-yellow-600 dark:text-yellow-300 mt-2">
This site doesn't have a WordPress integration configured yet.
</p>
<p className="text-xs text-yellow-600 dark:text-yellow-400 mt-2">
Please configure a WordPress integration in <span className="font-medium">Settings Integration</span> page first.
</p>
</div>
</div>
</div>
) : !activeSite ? (
<div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
<div className="text-center py-12">
<Globe className="h-12 w-12 mx-auto text-gray-400 mb-4" />
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">No Site Selected</h3>
<p className="text-gray-500 dark:text-gray-400">
Please select a site to view WordPress integration debug data.
</p>
</div>
{/* Debug Toggle */}
<div className="flex items-center space-x-3">
<label className="flex items-center space-x-2 cursor-pointer">
<span className={`text-sm font-medium ${debugEnabled ? 'text-green-600' : 'text-gray-500'}`}>
WP Debug Mode
</span>
<button
onClick={() => toggleDebugMode(!debugEnabled)}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
debugEnabled ? 'bg-green-600' : 'bg-gray-200'
}`}
disabled={loading}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
debugEnabled ? 'translate-x-6' : 'translate-x-1'
}`}
/>
</button>
</label>
{debugEnabled && pollingInterval && (
<div className="flex items-center space-x-1 text-xs text-green-600">
<Activity className="h-3 w-3 animate-pulse" />
<span>Live</span>
</div>
)}
</div>
</div>
{/* Site Selector */}
<div className="mb-6">
<SiteAndSectorSelector />
</div>
{/* Debug Status Info */}
{debugEnabled ? (
<div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-900/50 rounded-lg p-4">
<div className="flex items-start space-x-3">
<CheckCircle className="h-5 w-5 text-green-500 mt-0.5" />
<div>
<p className="text-sm text-green-800 dark:text-green-200 font-medium">WordPress Debug Mode Active</p>
<p className="text-xs text-green-600 dark:text-green-300 mt-1">
Real-time monitoring enabled for {activeSite?.name || 'selected site'}.
WordPress bridge plugin logs are being captured and will auto-disable after 24h.
</p>
</div>
</div>
</div>
) : (
<div className="bg-gray-50 dark:bg-gray-800/50 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
<div className="flex items-start space-x-3">
<Info className="h-5 w-5 text-gray-500 mt-0.5" />
<div>
<p className="text-sm text-gray-800 dark:text-gray-200 font-medium">WordPress Debug Mode Disabled</p>
<p className="text-xs text-gray-600 dark:text-gray-400 mt-1">
Enable debug mode above to start monitoring WordPress integration events and detailed sync logs.
</p>
</div>
</div>
</div>
)}
</div>
{debugEnabled && activeSite ? (
) : (
<>
{/* Integration Health Summary */}
<div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
@@ -638,32 +649,6 @@ export default function WordPressIntegrationDebug() {
</div>
)}
</>
) : debugEnabled && !activeSite ? (
<div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
<div className="text-center py-12">
<Globe className="h-12 w-12 mx-auto text-gray-400 mb-4" />
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">No Site Selected</h3>
<p className="text-gray-500 dark:text-gray-400 mb-4">
Please select a site above to enable WordPress integration debug monitoring.
</p>
<p className="text-xs text-gray-400">
Only sites with WordPress integrations will show debug data.
</p>
</div>
</div>
) : (
<div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
<div className="text-center py-12">
<Database className="h-12 w-12 mx-auto text-gray-400 mb-4" />
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">WordPress Debug Disabled</h3>
<p className="text-gray-500 dark:text-gray-400 mb-4">
Enable the WordPress debug toggle above to start monitoring integration events.
</p>
<p className="text-xs text-gray-400">
This will track content sync, plugin health, and API calls in real-time.
</p>
</div>
</div>
)}
</div>
);