wp-igny8 debug

This commit is contained in:
alorig
2025-11-29 23:13:01 +05:00
parent 062d09d899
commit 79618baede
2 changed files with 1058 additions and 16 deletions

View File

@@ -1,7 +1,11 @@
import { useState, useEffect, useCallback } from "react"; import React, { useState, useEffect, useCallback, useRef } from "react";
import PageMeta from "../../components/common/PageMeta"; import PageMeta from "../../components/common/PageMeta";
import ComponentCard from "../../components/common/ComponentCard"; import ComponentCard from "../../components/common/ComponentCard";
import SiteAndSectorSelector from "../../components/common/SiteAndSectorSelector";
import WordPressIntegrationDebug from "./WordPressIntegrationDebug";
import { API_BASE_URL, fetchAPI } from "../../services/api"; import { API_BASE_URL, fetchAPI } from "../../services/api";
import { useSiteStore } from "../../store/siteStore";
import { useToast } from "../../components/ui/toast/ToastContainer";
interface HealthCheck { interface HealthCheck {
name: string; name: string;
@@ -10,6 +14,9 @@ interface HealthCheck {
message?: string; message?: string;
details?: string; details?: string;
lastChecked?: string; lastChecked?: string;
step?: string;
payloadKeys?: string[];
responseCode?: number;
} }
interface ModuleHealth { interface ModuleHealth {
@@ -18,39 +25,105 @@ interface ModuleHealth {
checks: HealthCheck[]; checks: HealthCheck[];
} }
interface SyncEvent {
id: string;
timestamp: string;
direction: '📤 IGNY8 → WP' | '📥 WP → IGNY8';
trigger: string;
contentId?: number;
taskId?: number;
status: 'success' | 'partial' | 'failed';
steps: SyncEventStep[];
payload?: any;
response?: any;
}
interface SyncEventStep {
step: string;
file: string;
status: 'success' | 'warning' | 'failed' | 'skipped';
details: string;
error?: string;
duration?: number;
}
interface DataSyncValidation {
field: string;
sentByIgny8: boolean;
receivedByWP: boolean;
storedInWP: boolean;
verifiedInWPPost: boolean;
error?: string;
}
interface IntegrationHealth {
overall: 'healthy' | 'warning' | 'error';
lastSyncIgny8ToWP?: string;
lastSyncWPToIgny8?: string;
lastSiteMetadataCheck?: string;
wpApiReachable: boolean;
wpStatusEndpoint: boolean;
wpMetadataEndpoint: boolean;
apiKeyValid: boolean;
jwtTokenValid: boolean;
}
const getStatusColor = (status: string) => { const getStatusColor = (status: string) => {
switch (status) { switch (status) {
case 'healthy': return 'text-green-600 dark:text-green-400'; case 'healthy':
case 'warning': return 'text-yellow-600 dark:text-yellow-400'; case 'success': return 'text-green-600 dark:text-green-400';
case 'error': return 'text-red-600 dark:text-red-400'; case 'warning':
case 'partial': return 'text-yellow-600 dark:text-yellow-400';
case 'error':
case 'failed': return 'text-red-600 dark:text-red-400';
case 'checking': return 'text-blue-600 dark:text-blue-400'; case 'checking': return 'text-blue-600 dark:text-blue-400';
case 'skipped': return 'text-gray-600 dark:text-gray-400';
default: return 'text-gray-600 dark:text-gray-400'; default: return 'text-gray-600 dark:text-gray-400';
} }
}; };
const getStatusBadge = (status: string) => { const getStatusBadge = (status: string) => {
switch (status) { switch (status) {
case 'healthy': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'; case 'healthy':
case 'warning': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400'; case 'success': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400';
case 'error': return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400'; case 'warning':
case 'partial': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
case 'error':
case 'failed': return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
case 'checking': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400'; case 'checking': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400';
case 'skipped': return 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400';
default: return 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400'; default: return 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400';
} }
}; };
const getStatusIcon = (status: string) => { const getStatusIcon = (status: string) => {
switch (status) { switch (status) {
case 'healthy': return '✓'; case 'healthy':
case 'warning': return ''; case 'success': return '';
case 'error': return '✗'; case 'warning':
case 'partial': return '⚠';
case 'error':
case 'failed': return '✗';
case 'checking': return '⟳'; case 'checking': return '⟳';
case 'skipped': return '—';
default: return '?'; default: return '?';
} }
}; };
export default function DebugStatus() { export default function DebugStatus() {
const [moduleHealths, setModuleHealths] = useState<ModuleHealth[]>([]); const { activeSite } = useSiteStore();
const toast = useToast();
// 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 [loading, setLoading] = useState(false);
const [pollingInterval, setPollingInterval] = useState<NodeJS.Timeout | null>(null);
// Data state
const [moduleHealths, setModuleHealths] = useState<ModuleHealth[]>([]);
// Helper to get auth token // Helper to get auth token
const getAuthToken = () => { const getAuthToken = () => {
@@ -70,8 +143,14 @@ export default function DebugStatus() {
return token; return token;
}; };
// Helper to make authenticated API calls // Helper to make authenticated API calls with debug awareness
const apiCall = async (path: string, method: string = 'GET', body?: any) => { 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 token = getAuthToken();
const headers: HeadersInit = { const headers: HeadersInit = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@@ -91,11 +170,266 @@ export default function DebugStatus() {
options.body = JSON.stringify(body); options.body = JSON.stringify(body);
} }
const response = await fetch(`${API_BASE_URL}${path}`, options); try {
const data = await response.json(); if (debugEnabled) {
return { response, data }; 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) // Check database schema field mappings (the issues we just fixed)
const checkDatabaseSchemaMapping = useCallback(async (): Promise<HealthCheck> => { const checkDatabaseSchemaMapping = useCallback(async (): Promise<HealthCheck> => {
try { try {
@@ -569,7 +903,38 @@ export default function DebugStatus() {
</button> </button>
</div> </div>
{/* Overall Health Summary */} {/* Tab Navigation */}
<div className="bg-white dark:bg-gray-800 shadow rounded-lg">
<div className="border-b border-gray-200 dark:border-gray-700">
<nav className="flex space-x-8 px-6">
<button
onClick={() => setActiveTab('system-health')}
className={`py-4 px-2 border-b-2 font-medium text-sm transition-colors ${
activeTab === 'system-health'
? 'border-blue-500 text-blue-600 dark:text-blue-400'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
}`}
>
System Health
</button>
<button
onClick={() => setActiveTab('wp-integration')}
className={`py-4 px-2 border-b-2 font-medium text-sm transition-colors ${
activeTab === 'wp-integration'
? 'border-blue-500 text-blue-600 dark:text-blue-400'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
}`}
>
IGNY8 WordPress
</button>
</nav>
</div>
</div>
{/* Tab Content */}
{activeTab === 'system-health' ? (
<div className="space-y-6">
{/* Overall Health Summary */}
<ComponentCard <ComponentCard
title={ title={
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
@@ -750,6 +1115,11 @@ export default function DebugStatus() {
</div> </div>
</div> </div>
</ComponentCard> </ComponentCard>
</div>
) : (
// WordPress Integration Debug Tab
<WordPressIntegrationDebug />
)}
</div> </div>
</> </>
); );

View File

@@ -0,0 +1,672 @@
import React, { useState, useEffect, useCallback } from 'react';
import {
CheckCircle,
XCircle,
AlertTriangle,
Loader2,
Activity,
Info,
Clock,
Globe,
RefreshCw,
TestTube,
Wrench,
Database
} from 'lucide-react';
import { toast } from 'react-hot-toast';
import SiteAndSectorSelector from '../../components/common/SiteAndSectorSelector';
import { useSiteStore } from '../../store/siteStore';
// Types for WordPress integration debugging
interface IntegrationHealth {
api_status: 'healthy' | 'error';
api_message: string;
last_api_check: string;
plugin_active: boolean;
plugin_version: string;
debug_mode: boolean;
sync_healthy: boolean;
pending_syncs: number;
last_sync: string | null;
}
interface SyncEvent {
type: 'sync' | 'error' | 'webhook' | 'debug';
action: string;
description: string;
timestamp: string;
details?: any;
}
interface DataValidation {
field_name: string;
igny8_value: string;
wp_value: string;
matches: boolean;
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<NodeJS.Timeout | null>(null);
const [integrationHealth, setIntegrationHealth] = useState<IntegrationHealth | null>(null);
const [syncEvents, setSyncEvents] = useState<SyncEvent[]>([]);
const [dataValidation, setDataValidation] = useState<DataValidation[]>([]);
// Get active site from store
const { activeSite } = useSiteStore();
// 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('[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}`;
}
const options: RequestInit = {
method,
headers,
credentials: 'include',
};
if (body && method !== 'GET') {
options.body = JSON.stringify(body);
}
try {
if (debugEnabled) {
console.log('[WP-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('[WP-DEBUG] API Response:', response.status, data);
}
return { response, data };
} catch (error) {
if (debugEnabled) {
console.error('[WP-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('[WP-DEBUG] 🎯 WordPress Debug mode ENABLED for site:', activeSite.name);
toast.success('WordPress 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('[WP-DEBUG] 🔒 WordPress Debug mode DISABLED');
toast.info('WordPress 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('[WP-DEBUG] Failed to toggle debug mode:', error);
toast.error('Failed to toggle WordPress 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('[WP-DEBUG] ⏰ Started polling for WordPress debug updates');
};
// Stop polling
const stopPolling = () => {
if (pollingInterval) {
clearInterval(pollingInterval);
setPollingInterval(null);
console.log('[WP-DEBUG] ⏸️ Stopped polling');
}
};
// Load all debug data
const loadDebugData = useCallback(async () => {
if (!activeSite || !debugEnabled) return;
try {
setLoading(true);
console.log('[WP-DEBUG] 📊 Loading WordPress debug data for site:', activeSite.name);
// Load integration health
await loadIntegrationHealth();
// Load sync events
await loadSyncEvents();
// Load validation data
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');
}
} 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('[WP-DEBUG] 💚 Integration health loaded');
}
} catch (error) {
console.error('[WP-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('[WP-DEBUG] 📜 Loaded', data.data.events.length, 'WordPress sync events');
}
} catch (error) {
console.error('[WP-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('[WP-DEBUG] 🧩 Loaded WordPress data validation matrix');
}
} catch (error) {
console.error('[WP-DEBUG] Failed to load data validation:', error);
}
};
// Interactive tools
const testConnection = async () => {
if (!activeSite) return;
try {
setLoading(true);
console.log('[WP-DEBUG] 🔧 Testing connection to WordPress...');
const { data } = await apiCall(`/integration/integrations/${activeSite.id}/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);
}
} catch (error) {
console.error('[WP-DEBUG] Connection test error:', error);
toast.error('WordPress connection test failed');
} finally {
setLoading(false);
}
};
const resyncSiteMetadata = async () => {
if (!activeSite) return;
try {
setLoading(true);
console.log('[WP-DEBUG] 🔄 Re-syncing WordPress site metadata...');
const { data } = await apiCall(`/integration/integrations/${activeSite.id}/resync-metadata/`, 'POST');
if (data?.success) {
toast.success('WordPress site metadata re-synced successfully');
await loadDebugData(); // Refresh all data
} else {
toast.error('WordPress re-sync failed: ' + data?.message);
}
} catch (error) {
console.error('[WP-DEBUG] Metadata resync error:', error);
toast.error('WordPress metadata re-sync failed');
} finally {
setLoading(false);
}
};
const validatePostSync = async (taskId?: number) => {
if (!activeSite) return;
const id = taskId || prompt('Enter Task ID to validate WordPress sync:');
if (!id) return;
try {
setLoading(true);
console.log('[WP-DEBUG] 🔍 Validating WordPress post sync for task:', id);
const { data } = await apiCall(`/integration/integrations/${activeSite.id}/validate-content/${id}/`);
if (data?.success) {
toast.success('WordPress post validation completed');
setDataValidation(data.data.validation || []);
} else {
toast.error('WordPress validation failed: ' + data?.message);
}
} catch (error) {
console.error('[WP-DEBUG] Post validation error:', error);
toast.error('WordPress post validation failed');
} finally {
setLoading(false);
}
};
// 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
</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">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-medium text-gray-900 dark:text-white">WordPress Bridge Health</h3>
<div className="flex space-x-2">
<button
onClick={testConnection}
disabled={loading}
className="inline-flex items-center px-3 py-1 text-xs bg-blue-100 hover:bg-blue-200 text-blue-700 rounded-md disabled:opacity-50"
>
<TestTube className="h-3 w-3 mr-1" />
Test Connection
</button>
<button
onClick={resyncSiteMetadata}
disabled={loading}
className="inline-flex items-center px-3 py-1 text-xs bg-yellow-100 hover:bg-yellow-200 text-yellow-700 rounded-md disabled:opacity-50"
>
<RefreshCw className="h-3 w-3 mr-1" />
Re-sync Metadata
</button>
<button
onClick={() => validatePostSync()}
disabled={loading}
className="inline-flex items-center px-3 py-1 text-xs bg-purple-100 hover:bg-purple-200 text-purple-700 rounded-md disabled:opacity-50"
>
<Wrench className="h-3 w-3 mr-1" />
Validate Content
</button>
</div>
</div>
{integrationHealth ? (
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium">API Connection</span>
{integrationHealth.api_status === 'healthy' ? (
<CheckCircle className="h-4 w-4 text-green-500" />
) : (
<XCircle className="h-4 w-4 text-red-500" />
)}
</div>
<p className="text-xs text-gray-600 dark:text-gray-400">{integrationHealth.api_message}</p>
<div className="text-xs text-gray-500 mt-1">
Last: {new Date(integrationHealth.last_api_check).toLocaleTimeString()}
</div>
</div>
<div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium">Plugin Status</span>
{integrationHealth.plugin_active ? (
<CheckCircle className="h-4 w-4 text-green-500" />
) : (
<XCircle className="h-4 w-4 text-red-500" />
)}
</div>
<p className="text-xs text-gray-600 dark:text-gray-400">
Version: {integrationHealth.plugin_version || 'Unknown'}
</p>
<div className="text-xs text-gray-500 mt-1">
Debug: {integrationHealth.debug_mode ? 'Enabled' : 'Disabled'}
</div>
</div>
<div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium">Sync Status</span>
{integrationHealth.sync_healthy ? (
<CheckCircle className="h-4 w-4 text-green-500" />
) : (
<AlertTriangle className="h-4 w-4 text-yellow-500" />
)}
</div>
<p className="text-xs text-gray-600 dark:text-gray-400">
{integrationHealth.pending_syncs || 0} pending
</p>
<div className="text-xs text-gray-500 mt-1">
Last: {integrationHealth.last_sync ?
new Date(integrationHealth.last_sync).toLocaleTimeString() : 'Never'}
</div>
</div>
</div>
) : (
<div className="text-center py-4 text-gray-500">
<Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />
Loading WordPress integration health...
</div>
)}
</div>
{/* Live Action Logs */}
<div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">Live WordPress Sync Events</h3>
{syncEvents.length > 0 ? (
<div className="space-y-3 max-h-96 overflow-y-auto">
{syncEvents.slice().reverse().map((event, idx) => (
<div key={idx} className="border-l-4 border-gray-200 dark:border-gray-600 pl-4 py-2">
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-2 text-sm">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
event.type === 'sync' ? 'bg-blue-100 text-blue-700' :
event.type === 'error' ? 'bg-red-100 text-red-700' :
event.type === 'webhook' ? 'bg-green-100 text-green-700' :
'bg-gray-100 text-gray-700'
}`}>
{event.type}
</span>
<span className="font-medium truncate">{event.action}</span>
</div>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">{event.description}</p>
{event.details && (
<details className="mt-2">
<summary className="text-xs text-blue-600 cursor-pointer hover:underline">
View Details
</summary>
<pre className="mt-2 text-xs bg-gray-50 dark:bg-gray-700 p-2 rounded border overflow-x-auto">
{typeof event.details === 'string' ? event.details : JSON.stringify(event.details, null, 2)}
</pre>
</details>
)}
</div>
<div className="text-xs text-gray-500 whitespace-nowrap ml-4">
{new Date(event.timestamp).toLocaleTimeString()}
</div>
</div>
</div>
))}
</div>
) : (
<div className="text-center py-8 text-gray-500">
<Clock className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p>No WordPress sync events yet. Actions will appear here in real-time.</p>
<p className="text-xs mt-2">Content publishing, metadata sync, and webhook calls will be logged here.</p>
</div>
)}
</div>
{/* Data Validation Matrix */}
{dataValidation.length > 0 && (
<div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">Data Sync Validation</h3>
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-700">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Field
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
IGNY8 Value
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
WordPress Value
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Status
</th>
</tr>
</thead>
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
{dataValidation.map((validation, idx) => (
<tr key={idx} className="hover:bg-gray-50 dark:hover:bg-gray-700">
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">
{validation.field_name}
</td>
<td className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400 max-w-xs truncate">
{validation.igny8_value || <span className="text-gray-400 italic">empty</span>}
</td>
<td className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400 max-w-xs truncate">
{validation.wp_value || <span className="text-gray-400 italic">empty</span>}
</td>
<td className="px-6 py-4 whitespace-nowrap">
{validation.matches ? (
<CheckCircle className="h-4 w-4 text-green-500" />
) : (
<div className="flex items-center space-x-1">
<XCircle className="h-4 w-4 text-red-500" />
{validation.error && (
<span className="text-xs text-red-600">{validation.error}</span>
)}
</div>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</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>
);
}