/** * Dashboard home page - aggregated analytics from all modules. */ import { useState, useEffect } from '@wordpress/element'; import { __, _n, sprintf } from '@wordpress/i18n'; import { Button } from '@aime/wp-components'; import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, Tooltip, CartesianGrid, } from 'recharts'; import Card from '../../common/Card'; import ArcGauge from '../../common/ArcGauge'; import Loader from '../../common/Loader'; import Notice from '../../common/Notice'; import EmptyState from '../../common/EmptyState'; import useApi from '../../../hooks/useApi'; import { apiGet } from '../../../utils/api'; import { menuUrl } from '../../../utils/menuUrl'; /** * Room wayfinding colours. * * These MUST match the --aime-room-* tokens in src/styles/global.scss and the * [data-module] accent themes above them. The Overview is a launchpad: a bar, * line or stripe standing for Email has to be the same colour the Email module * paints itself, or the dashboard sends people to the wrong door. * * Literal hex rather than var() because Recharts writes stroke/fill as SVG * presentation attributes, where custom properties do not resolve. */ const ROOM = { email: '#BE123C', content: '#4338CA', seo: '#B45309', chatbot: '#7C3AED', social: '#0E7490', /* * Workflow Automation is not a sixth room — the stylesheet has no * `[data-module="workflow-automation"]` accent, and inventing one here would * put a colour on the page that no other surface in the plugin can match. * It runs the other five, so it takes the house green: the corridor colour, * not a room colour. */ workflow: '#1B5E20', }; // Chart chrome, tinted to the green canvas instead of a cool blue-grey. const CHART_GRID = '#eaf2ea'; const CHART_TICK = '#5f7562'; const CHART_CURSOR = '#8fa893'; // Draw order for the stacked activity chart. Fixed rather than derived, so a // band never swaps position between two renders of the same data. const SERIES = [ 'email', 'content', 'seo', 'chatbot', 'social' ]; /** * Ranges the activity endpoint will actually honour. * * The REST route clamps `days` to 7–90, so offering a year would be a control * that silently returns three months. Every option here is a range the server * can really answer. */ const RANGES = [ 7, 30, 90 ]; /** * Activity chart tooltip. * * Recharts' default tooltip is an unstyled white box that ignores the card * language around it, and on a stacked chart it lists the series bottom-up — * the reverse of the order they are painted, so the colour you are pointing at * is never the row your eye lands on first. This reverses the payload and adds * the total, which is the number a stack is actually asking you to read. */ const ActivityTooltip = ( { active, payload, label } ) => { if ( ! active || ! payload?.length ) { return null; } const total = payload.reduce( ( sum, entry ) => sum + Number( entry.value || 0 ), 0 ); return (
{ label }
{ __( 'Total', 'ai-marketing-expert' ) } { total.toLocaleString() }
); }; /** * Stacked activity chart. * * Five separate lines answered "how is each module trending" and nothing else; * at the density this data arrives in they mostly crossed each other. Stacked * bands answer the question the dashboard is actually for — is anything * happening, and which room is driving it — and the height of the stack is * legible from across the room in a way five 2px strokes never were. */ const ActivityChart = ( { data, labels, height = 300 } ) => ( { SERIES.map( ( key ) => ( ) ) } { /* Horizontal rules only. Vertical ones fence the bands into columns and fight the shape the stack is drawing. */ } } cursor={ { stroke: CHART_CURSOR, strokeDasharray: '3 3' } } /> { SERIES.map( ( key ) => ( ) ) } ); const OverviewPage = () => { const { loading, get } = useApi(); const [ stats, setStats ] = useState( null ); const [ error, setError ] = useState( '' ); const [ aiProviderCount, setAiProviderCount ] = useState( null ); const [ smtpConnectionCount, setSmtpConnectionCount ] = useState( null ); const [ connectionsFailed, setConnectionsFailed ] = useState( false ); const [ activityTrends, setActivityTrends ] = useState( [] ); const [ trendsFailed, setTrendsFailed ] = useState( false ); const [ trendsLoading, setTrendsLoading ] = useState( true ); const [ rangeDays, setRangeDays ] = useState( 30 ); useEffect( () => { loadStats(); loadConnectionCounts(); }, [] ); // The chart owns its own fetch because it is the only thing on the page // with a control attached to it. Re-running the whole dashboard to change a // date range would blank four cards that did not change. useEffect( () => { loadActivityTrends( rangeDays ); }, [ rangeDays ] ); const loadStats = async () => { try { const data = await get( '/dashboard/stats' ); setStats( data ); } catch ( err ) { setError( err.message || __( 'Could not load your dashboard stats. Reload the page to try again.', 'ai-marketing-expert' ) ); } }; const loadActivityTrends = async ( days ) => { setTrendsLoading( true ); setTrendsFailed( false ); try { const data = await get( '/dashboard/activity-trends', { days } ); setActivityTrends( Array.isArray( data ) ? data : [] ); } catch ( e ) { // An empty array and a failed request look identical downstream, and // the empty state for this chart says "Nothing has run yet." — which // is a claim about the user's data, not about the request. Saying it // when we never got an answer is worse than saying nothing. setActivityTrends( [] ); setTrendsFailed( true ); } finally { setTrendsLoading( false ); } }; const loadConnectionCounts = async () => { const [ aiResult, smtpResult ] = await Promise.allSettled( [ apiGet( '/ai/connections' ), apiGet( '/email/smtp' ), ] ); if ( aiResult.status === 'fulfilled' ) { setAiProviderCount( Array.isArray( aiResult.value?.connections ) ? aiResult.value.connections.length : 0 ); } if ( smtpResult.status === 'fulfilled' ) { setSmtpConnectionCount( Array.isArray( smtpResult.value ) ? smtpResult.value.length : 0 ); } // A lookup that never resolved leaves its count at null forever, which // would pin the hero in its loading skin for the rest of the session. // Record the failure so the page can settle without claiming to know // what is or is not connected. if ( aiResult.status === 'rejected' || smtpResult.status === 'rejected' ) { setConnectionsFailed( true ); } }; if ( loading && ! stats ) { return ; } const email = stats?.modules?.[ 'email-marketing' ] || {}; const content = stats?.modules?.[ 'content-generator' ] || {}; const chatbot = stats?.modules?.chatbot || {}; const social = stats?.modules?.[ 'social-media' ] || {}; const seo = stats?.modules?.seo || {}; const workflow = stats?.modules?.[ 'workflow-automation' ] || {}; /* ------ First-run setup gate ------ * A setup prompt is only honest when we actually know the answer. A count * of null means "not looked up yet" and a failed lookup means "unknown" — * neither is "not configured", so neither one earns a prompt. Telling * someone to connect a provider they already connected is worse than * saying nothing. */ const connectionsLoaded = connectionsFailed || ( aiProviderCount !== null && smtpConnectionCount !== null ); const showAiProviderConnect = aiProviderCount === 0; const showSmtpConnect = smtpConnectionCount === 0; const showDashboardNotice = connectionsLoaded && ( showAiProviderConnect || showSmtpConnect ); const showDashboardHero = ! connectionsLoaded || showDashboardNotice; // Nothing generated by AI works until a provider key exists, so this one // gates the value of every other module and outranks the SMTP prompt. const needsFirstSetup = showDashboardNotice && showAiProviderConnect; /* ------ Hero copy ------ * The hero only exists while something is unconfigured, so it should name * the thing that is unconfigured. Describing what a dashboard is, to * somebody already looking at the dashboard, spends the one piece of * prominent space on the page saying nothing. */ const heroCopy = ! connectionsLoaded ? { title: __( 'Checking your setup…', 'ai-marketing-expert' ), body: '', } : needsFirstSetup ? { title: __( 'Add an AI provider key to switch the modules on.', 'ai-marketing-expert' ), body: __( 'Articles, SEO suggestions, chat replies, and social posts are generated with your own API key, so no module produces output until one is connected. You can add several providers and set a fallback order later.', 'ai-marketing-expert' ), } : { title: __( 'Connect an SMTP service to start sending email.', 'ai-marketing-expert' ), body: __( 'Subscribers, campaigns, and automations are already stored on this site, but WordPress needs an SMTP connection to deliver them. Every other module works without it.', 'ai-marketing-expert' ), }; /* * The band holds three gauges, and a gauge needs a bounded number — a count * has no full, so an arc drawn over one is decoration. Open rate is bounded * by definition. Lead capture rate is derived here rather than read from the * API because no endpoint returns it: it is the share of conversations the * bot turned into a lead, which is the only chatbot number that answers * "is this working" rather than "did this happen". */ const emailOpenRateValue = Math.max( 0, Math.min( Number( email.open_rate || 0 ), 100 ) ); const chatbotConversations = Number( chatbot.total_conversations || 0 ); const chatbotLeadRateValue = chatbotConversations > 0 ? Math.max( 0, Math.min( ( Number( chatbot.leads_captured || 0 ) / chatbotConversations ) * 100, 100 ) ) : 0; const seriesLabels = { email: __( 'Email', 'ai-marketing-expert' ), content: __( 'Content', 'ai-marketing-expert' ), seo: __( 'SEO', 'ai-marketing-expert' ), chatbot: __( 'Chatbot', 'ai-marketing-expert' ), social: __( 'Social', 'ai-marketing-expert' ), }; /* ------ Module summary cards ------ * `lead` is the module's health signal and renders as the card's big * number. `share` is the part-of-whole pair that used to need a whole * two-slice donut of its own — a stacked bar says the same thing in 8px of * height and reads at a glance across five cards, which five separate pie * charts never did. `stats` is the supporting detail. * * `activity` is the "has this room produced anything at all" test behind * the rooms-in-use gauge. It sums the module's own totals rather than a * single field, because a module counts as in use whether the user made * bots or conversations, keywords or audits. */ const modules = [ { key: 'email', title: __( 'Email Marketing', 'ai-marketing-expert' ), color: ROOM.email, href: menuUrl( 'email' ), lead: { label: __( 'Open Rate', 'ai-marketing-expert' ), value: `${ parseFloat( email.open_rate || 0 ).toFixed( 1 ) }%`, }, share: { label: __( 'Active', 'ai-marketing-expert' ), value: Number( email.active_contacts || 0 ), restLabel: __( 'Unengaged', 'ai-marketing-expert' ), totalLabel: __( 'Subscribers', 'ai-marketing-expert' ), total: Number( email.total_contacts || 0 ), }, stats: [ { label: __( 'Campaigns', 'ai-marketing-expert' ), value: email.total_campaigns || 0 }, { label: __( 'Emails Sent', 'ai-marketing-expert' ), value: email.emails_sent || 0 }, { label: __( 'Automations', 'ai-marketing-expert' ), value: email.total_automations || 0 }, ], activity: Number( email.total_campaigns || 0 ) + Number( email.emails_sent || 0 ) + Number( email.total_contacts || 0 ), }, { key: 'content', title: __( 'Content Generator', 'ai-marketing-expert' ), color: ROOM.content, href: menuUrl( 'content' ), lead: { label: __( 'Published', 'ai-marketing-expert' ), value: content.published_articles || 0, }, share: { label: __( 'Published', 'ai-marketing-expert' ), value: Number( content.published_articles || 0 ), restLabel: __( 'Drafts', 'ai-marketing-expert' ), totalLabel: __( 'Articles', 'ai-marketing-expert' ), total: Number( content.total_articles || 0 ), }, stats: [ { label: __( 'Average SEO score', 'ai-marketing-expert' ), value: `${ parseFloat( content.avg_seo_score || 0 ).toFixed( 0 ) }%` }, { label: __( 'Total Words', 'ai-marketing-expert' ), value: Number( content.total_words || 0 ).toLocaleString() }, ], activity: Number( content.total_articles || 0 ), }, { key: 'seo', title: __( 'SEO Analyzer', 'ai-marketing-expert' ), color: ROOM.seo, href: menuUrl( 'seo' ), lead: { label: __( 'Average score', 'ai-marketing-expert' ), value: `${ parseFloat( seo.avg_audit_score || 0 ).toFixed( 0 ) }%`, }, share: { label: __( 'Tracked', 'ai-marketing-expert' ), value: Number( seo.tracked_keywords || 0 ), restLabel: __( 'Untracked', 'ai-marketing-expert' ), totalLabel: __( 'Keywords', 'ai-marketing-expert' ), total: Number( seo.total_keywords || 0 ), }, stats: [ { label: __( 'Audits', 'ai-marketing-expert' ), value: seo.total_audits || 0 }, ], activity: Number( seo.total_keywords || 0 ) + Number( seo.total_audits || 0 ), }, { key: 'chatbot', title: __( 'AI Chatbot', 'ai-marketing-expert' ), color: ROOM.chatbot, href: menuUrl( 'chatbot' ), lead: { label: __( 'Active Chats', 'ai-marketing-expert' ), value: chatbot.active_conversations || 0, }, share: { label: __( 'Active', 'ai-marketing-expert' ), value: Number( chatbot.active_conversations || 0 ), restLabel: __( 'Closed', 'ai-marketing-expert' ), totalLabel: __( 'Conversations', 'ai-marketing-expert' ), total: Number( chatbot.total_conversations || 0 ), }, stats: [ { label: __( 'Bots', 'ai-marketing-expert' ), value: chatbot.total_bots || 0 }, { label: __( 'Messages', 'ai-marketing-expert' ), value: chatbot.total_messages || 0 }, { label: __( 'Leads', 'ai-marketing-expert' ), value: chatbot.leads_captured || 0 }, ], activity: Number( chatbot.total_bots || 0 ) + Number( chatbot.total_conversations || 0 ), }, { key: 'social', title: __( 'Social Media', 'ai-marketing-expert' ), color: ROOM.social, href: menuUrl( 'social' ), lead: { label: __( 'Scheduled', 'ai-marketing-expert' ), value: social.scheduled_posts || 0, }, share: { label: __( 'Published', 'ai-marketing-expert' ), value: Number( social.published_month || 0 ), restLabel: __( 'Pending', 'ai-marketing-expert' ), totalLabel: __( 'Posts this month', 'ai-marketing-expert' ), total: Number( social.posts_this_month || 0 ), }, stats: [ { label: __( 'Accounts', 'ai-marketing-expert' ), value: social.total_accounts || 0 }, ], activity: Number( social.total_accounts || 0 ) + Number( social.posts_this_month || 0 ), }, { key: 'workflow', title: __( 'Workflow Automation', 'ai-marketing-expert' ), color: ROOM.workflow, href: menuUrl( 'workflow-automation' ), lead: { label: __( 'Active Workflows', 'ai-marketing-expert' ), value: workflow.active_workflows || 0, }, share: { label: __( 'Active', 'ai-marketing-expert' ), value: Number( workflow.active_workflows || 0 ), restLabel: __( 'Paused', 'ai-marketing-expert' ), totalLabel: __( 'Workflows', 'ai-marketing-expert' ), total: Number( workflow.total_workflows || 0 ), }, stats: [ { label: __( 'Runs (30d)', 'ai-marketing-expert' ), value: workflow.runs_last_30_days || 0 }, ], activity: Number( workflow.total_workflows || 0 ) + Number( workflow.runs_last_30_days || 0 ), }, ]; /* ------ Rooms in use ------ * The lead card on a launchpad should answer the question people actually * open a launchpad with: is this thing doing anything yet. Six rooms, and * the arc says how many are lit. Every other number on the page is inside * one room; this is the only one about the building. */ const roomsInUse = modules.filter( ( mod ) => mod.activity > 0 ).length; const unknownCount = '—'; const quickModuleLinks = [ { label: __( 'Email Marketing', 'ai-marketing-expert' ), href: menuUrl( 'email' ) }, { label: __( 'SEO Analyzer', 'ai-marketing-expert' ), href: menuUrl( 'seo' ) }, { label: __( 'Content Generator', 'ai-marketing-expert' ), href: menuUrl( 'content' ) }, { label: __( 'AI Chatbot', 'ai-marketing-expert' ), href: menuUrl( 'chatbot' ) }, { label: __( 'Social Media', 'ai-marketing-expert' ), href: menuUrl( 'social' ) }, { label: __( 'Workflow Automation', 'ai-marketing-expert' ), href: menuUrl( 'workflow-automation' ) }, { label: __( 'AI Providers', 'ai-marketing-expert' ), href: menuUrl( 'ai-providers' ) }, ]; const rangeNote = sprintf( /* translators: %d: number of days covered by the activity chart. */ _n( 'Last %d day', 'Last %d days', rangeDays, 'ai-marketing-expert' ), rangeDays ); // The range control is not gated. The chart under it plots this site's own // data on every tier, so every option here changes something real. const rangeToggle = (
{ RANGES.map( ( days ) => ( ) ) }
); return (
{ /* Page header */ }

{ __( 'Dashboard', 'ai-marketing-expert' ) }

{ error && } { showDashboardHero && (
{ __( 'Getting started', 'ai-marketing-expert' ) }

{ heroCopy.title }

{ heroCopy.body &&

{ heroCopy.body }

}
) }
{ quickModuleLinks.map( ( item ) => ( { item.label } ) ) }
{ /* ── Summary band ────────────────────────────────────────── Three gauges, largest first: the building, then the two bounded scores worth watching daily. Everything else on the page is a count, and a count is not a gauge. */ }
{ __( 'Workspace', 'ai-marketing-expert' ) } { roomsInUse } { sprintf( /* translators: %d: total number of modules. */ __( 'of %d modules in use', 'ai-marketing-expert' ), modules.length ) }
{ __( 'AI providers', 'ai-marketing-expert' ) } { aiProviderCount === null ? unknownCount : aiProviderCount }
{ __( 'SMTP connections', 'ai-marketing-expert' ) } { smtpConnectionCount === null ? unknownCount : smtpConnectionCount }
{ __( 'Email Marketing', 'ai-marketing-expert' ) } { `${ emailOpenRateValue.toFixed( 1 ) }%` } { __( 'Open rate', 'ai-marketing-expert' ) } { Number( email.emails_sent || 0 ) > 0 ? (
{ __( 'Emails sent', 'ai-marketing-expert' ) } { Number( email.emails_sent || 0 ).toLocaleString() }
{ __( 'Campaigns', 'ai-marketing-expert' ) } { Number( email.total_campaigns || 0 ).toLocaleString() }
) : (

{ __( 'No campaign has gone out yet, so there is no open rate to read.', 'ai-marketing-expert' ) } { ' ' } { __( 'Create a campaign', 'ai-marketing-expert' ) }

) }
{ __( 'AI Chatbot', 'ai-marketing-expert' ) } { `${ chatbotLeadRateValue.toFixed( 0 ) }%` } { __( 'Lead capture rate', 'ai-marketing-expert' ) } { chatbotConversations > 0 ? (
{ __( 'Conversations', 'ai-marketing-expert' ) } { chatbotConversations.toLocaleString() }
{ __( 'Leads captured', 'ai-marketing-expert' ) } { Number( chatbot.leads_captured || 0 ).toLocaleString() }
) : (

{ __( 'No one has talked to a bot yet, so there is no capture rate to read.', 'ai-marketing-expert' ) } { ' ' } { __( 'Set up a chatbot', 'ai-marketing-expert' ) }

) }
{ /* ── Activity ────────────────────────────────────────────── */ } { __( 'Activity', 'ai-marketing-expert' ) } { rangeNote } } actions={ rangeToggle } >
{ activityTrends.length > 0 ? ( <> { /* The legend sits above the plot, not below it. A legend is a key, and a key you read after the thing it unlocks is a key you read twice. Left-aligned so it lands on the same scan line the card title starts. */ }
    { SERIES.map( ( key ) => (
  • { seriesLabels[ key ] }
  • ) ) }
) : trendsFailed ? ( ) : trendsLoading ? ( { /* Module Summary Cards */ }

{ __( 'Module Overview', 'ai-marketing-expert' ) }

{ modules.map( ( mod ) => { const shareTotal = mod.share.total; const sharePercent = shareTotal > 0 ? Math.min( 100, Math.max( 0, ( mod.share.value / shareTotal ) * 100 ) ) : 0; const shareRest = Math.max( 0, shareTotal - mod.share.value ); return ( { __( 'View →', 'ai-marketing-expert' ) } } >
{ mod.lead.value } { mod.lead.label }
{ /* Part of whole. The bar is decoration on top of the legend below it, which carries both numbers as text, so it stays out of the accessibility tree. */ }
{ mod.share.label } { mod.share.value.toLocaleString() } { mod.share.restLabel } { shareRest.toLocaleString() }
{ mod.stats.map( ( item ) => (
{ item.value } { item.label }
) ) }
); } ) }
); }; export default OverviewPage;