/** * Content Analytics — the Content Generator landing page. * * Five equal KPI cards, a hand-rolled div bar chart and a row of status chips * floating in an empty card is what this was. Nothing on it outranked anything * else, and the one number worth acting on — how much finished content is * sitting unpublished — was not on the page at all. */ import { useState, useEffect, useCallback } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; import { Button } from '@aime/wp-components'; import { ResponsiveContainer, ComposedChart, Bar, Line, XAxis, YAxis, Tooltip, CartesianGrid, Legend, } from 'recharts'; import useApi from '../../../hooks/useApi'; import Card from '../../common/Card'; import Loader from '../../common/Loader'; import Notice from '../../common/Notice'; import EmptyState from '../../common/EmptyState'; import ArcGauge from '../../common/ArcGauge'; import { RankRow } from '../../common/RankBar'; import { ARTICLE_STATUS_LABELS, ARTICLE_STATUS_COLORS } from '../../../utils/constants'; const RANGES = [ 7, 30, 90 ]; /* * Recharts writes stroke and fill as SVG presentation attributes, where a * `var()` never resolves — so the Content Generator accent has to be repeated * as a literal here. This is the one documented exception to the cascade rule, * and these must stay in step with `[data-module="content-generator"]` in * global.scss. * * Published is a lighter step of the same indigo, not a second colour: the two * series are the same articles at two moments in their life, and two unrelated * hues would claim they were unrelated things. */ const CONTENT = '#4338CA'; const CONTENT_SOFT = '#A5B4FC'; const CHART_GRID = '#eaf2ea'; const CHART_TICK = '#5f7562'; const TOOLTIP_STYLE = { borderRadius: 8, border: '1px solid var(--aime-border-light, #e3ece4)', boxShadow: '0 8px 24px rgba(20, 45, 22, 0.12)', fontSize: 13, }; /* * Pipeline order — not alphabetical, and deliberately not sorted by count. Read * in count order a status list tells you which pile is biggest. Read in stage * order it tells you *where the work stopped*, which is the only thing this * card can say that the totals above it cannot. */ const PIPELINE_ORDER = [ 'draft', 'generating', 'ready', 'review', 'scheduled', 'published', 'archived', ]; const isoDay = ( date ) => { const y = date.getFullYear(); const m = String( date.getMonth() + 1 ).padStart( 2, '0' ); const d = String( date.getDate() ).padStart( 2, '0' ); return `${ y }-${ m }-${ d }`; }; /* * The endpoint groups by date and returns only the days that had a row, so a * 30-day window with four busy days comes back as four points. Plotted raw, * those four sit shoulder to shoulder and three weeks of silence between two of * them renders exactly as wide as a single overnight gap — the axis lies about * the shape of the work. Scaffolding every day in the range back in at zero is * what makes the spacing true. * * Dates the API returns that fall outside the scaffold are kept rather than * dropped: a timezone difference between PHP's gmdate and the browser can put a * real row one day either side of the window, and silently losing it would be * worse than one extra tick. */ const buildSeries = ( days, created, published ) => { const byDate = {}; const cursor = new Date(); cursor.setHours( 0, 0, 0, 0 ); for ( let i = days - 1; i >= 0; i-- ) { const day = new Date( cursor ); day.setDate( day.getDate() - i ); const key = isoDay( day ); byDate[ key ] = { date: key, created: 0, published: 0 }; } const apply = ( rows, field ) => { ( rows || [] ).forEach( ( row ) => { const key = String( row.date || '' ).slice( 0, 10 ); if ( ! key ) { return; } if ( ! byDate[ key ] ) { byDate[ key ] = { date: key, created: 0, published: 0 }; } byDate[ key ][ field ] = Number( row.count ) || 0; } ); }; apply( created, 'created' ); apply( published, 'published' ); return Object.values( byDate ) .sort( ( a, b ) => a.date.localeCompare( b.date ) ) .map( ( point ) => ( { ...point, label: point.date.slice( 5 ) } ) ); }; const ContentAnalytics = ( { onNavigate } ) => { const { get, loading, error, clearError } = useApi(); const [ stats, setStats ] = useState( null ); const [ days, setDays ] = useState( 30 ); const load = useCallback( async ( range ) => { try { const res = await get( `/content/analytics/overview?days=${ range }` ); setStats( res ); } catch ( e ) { // The Notice above renders whatever useApi captured. } }, [ get ] ); useEffect( () => { load( days ); }, [ load, days ] ); if ( loading && ! stats ) { return ; } const totals = stats?.totals || {}; const totalArticles = Number( totals.total_articles || 0 ); const totalPublished = Number( totals.total_published || 0 ); const totalWords = Number( totals.total_words || 0 ); const avgWords = Number( totals.avg_word_count || 0 ); const avgSeo = Math.max( 0, Math.min( Number( totals.avg_seo_score || 0 ), 100 ) ); const avgReadability = Math.max( 0, Math.min( Number( totals.avg_readability || 0 ), 100 ) ); const publishedPercent = totalArticles > 0 ? ( totalPublished / totalArticles ) * 100 : 0; /* ── Pipeline ─────────────────────────────────────────── */ const statusCounts = {}; ( stats?.status_breakdown || [] ).forEach( ( row ) => { statusCounts[ row.status ] = Number( row.count ) || 0; } ); // A status the constants file has never heard of still has articles in it, // so unknown keys are appended rather than filtered away. const orderedKeys = [ ...PIPELINE_ORDER, ...Object.keys( statusCounts ).filter( ( key ) => ! PIPELINE_ORDER.includes( key ) ), ]; const pipelineTotal = Object.values( statusCounts ).reduce( ( sum, n ) => sum + n, 0 ); const pipelinePeak = Math.max( 0, ...Object.values( statusCounts ) ); const pipeline = orderedKeys .filter( ( key ) => ( statusCounts[ key ] || 0 ) > 0 ) .map( ( key ) => ( { key, label: ARTICLE_STATUS_LABELS[ key ] || key, count: statusCounts[ key ], color: ARTICLE_STATUS_COLORS[ key ] || '#9e9e9e', // Scaled to the biggest stage, not to the total. Against the total a // seven-stage pipeline draws seven slivers and nothing is comparable; // against the peak the longest bar fills the track and every other one // is read as a fraction of it. percent: pipelinePeak > 0 ? ( statusCounts[ key ] / pipelinePeak ) * 100 : 0, } ) ); /* * Finished work that is not live is the one thing on this page worth acting * on today, so it is the headline rather than a chip. When there is none, the * headline falls back to the share that did make it out — a card that leads * with a zero has spent its largest type on nothing. */ const readyCount = Number( statusCounts.ready || 0 ); const headlineValue = readyCount > 0 ? readyCount.toLocaleString() : `${ Math.round( publishedPercent ) }%`; const headlineCaption = readyCount > 0 ? __( 'Finished, not published yet', 'ai-marketing-expert' ) : __( 'Of the library is published', 'ai-marketing-expert' ); /* ── Tones ────────────────────────────────────────────── */ const tones = stats?.top_tones || []; const tonePeak = Math.max( 0, ...tones.map( ( t ) => Number( t.count ) || 0 ) ); /* ── Time series ──────────────────────────────────────── */ const series = buildSeries( days, stats?.articles_over_time, stats?.published_over_time ); const seriesHasData = series.some( ( p ) => p.created > 0 || p.published > 0 ); // Roughly ten ticks whatever the range, so 90 days does not print 90 dates. const tickInterval = Math.max( 0, Math.ceil( series.length / 10 ) - 1 ); const rangeToggle = (
{ RANGES.map( ( option ) => ( ) ) }
); return (
{ error && }

{ __( 'Content Generator', 'ai-marketing-expert' ) }

{ rangeToggle }
{ /* * Three gauges instead of five flat KPI cards. Each one is a bounded * number with a full — a share and two scores — which is what an arc * can honestly draw. The counts those rates came from sit in the chips * underneath, where a count belongs. */ }
{ __( 'Library', 'ai-marketing-expert' ) } { `${ Math.round( publishedPercent ) }%` } { __( 'Published', 'ai-marketing-expert' ) }
{ __( 'Articles', 'ai-marketing-expert' ) } { totalArticles.toLocaleString() }
{ __( 'Words written', 'ai-marketing-expert' ) } { totalWords.toLocaleString() }
{ __( 'SEO', 'ai-marketing-expert' ) } { avgSeo || '—' } { __( 'Avg SEO score', 'ai-marketing-expert' ) }

{ avgSeo > 0 ? __( 'Averaged across every article that has been scored.', 'ai-marketing-expert' ) : __( 'Nothing scored yet — generate an article to get a score.', 'ai-marketing-expert' ) }

{ __( 'Readability', 'ai-marketing-expert' ) } { avgReadability || '—' } { __( 'Avg readability', 'ai-marketing-expert' ) }

{ avgWords > 0 ? sprintf( /* translators: %s: average word count per article. */ __( 'Across articles averaging %s words each.', 'ai-marketing-expert' ), avgWords.toLocaleString() ) : __( 'No finished articles to measure yet.', 'ai-marketing-expert' ) }

{ seriesHasData ? ( { /* * Published is a line, not a second bar. Grouped bars over * 90 days are two pixels wide each; and these are not two * things measured the same way — one is output, the other * is what got out the door. */ } ) : ( ) } { pipeline.length > 0 ? (
{ headlineValue } { headlineCaption }
    { pipeline.map( ( stage ) => ( ) ) }

{ sprintf( /* translators: %s: total number of articles. */ __( '%s articles, every status, all time.', 'ai-marketing-expert' ), pipelineTotal.toLocaleString() ) }

) : ( ) }
{ tones.length > 0 ? (
    { tones.map( ( tone ) => ( 0 ? ( ( Number( tone.count ) || 0 ) / tonePeak ) * 100 : 0 } color={ CONTENT } /> ) ) }
) : ( ) }
onNavigate( 'articles' ) }> { __( 'View All', 'ai-marketing-expert' ) } } > { stats?.recent_articles?.length > 0 ? ( { stats.recent_articles.map( ( a ) => ( onNavigate( 'edit-article', { id: a.id } ) } > ) ) }
{ __( 'Title', 'ai-marketing-expert' ) } { __( 'Status', 'ai-marketing-expert' ) } { __( 'Words', 'ai-marketing-expert' ) } { __( 'SEO', 'ai-marketing-expert' ) }
{ a.title || __( 'Untitled', 'ai-marketing-expert' ) } { ARTICLE_STATUS_LABELS[ a.status ] || a.status } { ( Number( a.actual_word_count ) || 0 ).toLocaleString() } { a.seo_score || '—' }
) : ( /* * The endpoint filters this list by the same window as the * chart, so an established site with a quiet month lands here * with a full library. The copy has to say that rather than * claim there are no articles. */ 0 ? __( 'No articles were created in the selected range. Widen it above, or open the full list.', 'ai-marketing-expert' ) : __( 'Generate your first article and it will appear here.', 'ai-marketing-expert' ) } /> ) }
); }; export default ContentAnalytics;