/**
* Campaign Progress - live stats for a sending/sent campaign.
*/
import { useState, useEffect, useCallback, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Button, TextControl, Spinner } from '@aime/wp-components';
import {
ResponsiveContainer, BarChart, Bar, AreaChart, Area, XAxis, YAxis, Tooltip, CartesianGrid, PieChart, Pie, Cell, Legend,
} from 'recharts';
import useApi from '../../../hooks/useApi';
import Card from '../../common/Card';
import Loader from '../../common/Loader';
import Notice from '../../common/Notice';
import { toSiteInput, siteInputToUtc } from '../../../utils/datetime';
const COLORS = [ '#3858e9', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6' ];
const getCountryFlag = ( code ) => {
if ( ! code || typeof code !== 'string' || code.length !== 2 ) return '๐';
try {
return String.fromCodePoint(
...code.toUpperCase().split( '' ).map( ( c ) => 0x1F1E6 + c.charCodeAt( 0 ) - 65 )
);
} catch ( e ) {
return '๐';
}
};
const getCountryName = ( code ) => {
if ( ! code ) return __( 'Unknown location', 'ai-marketing-expert' );
try {
return new Intl.DisplayNames( [ 'en' ], { type: 'region' } ).of( code.toUpperCase() ) || code;
} catch ( e ) {
return code;
}
};
const formatDuration = ( seconds ) => {
const total = Math.max( 0, Number( seconds ) || 0 );
const days = Math.floor( total / 86400 );
const hours = Math.floor( ( total % 86400 ) / 3600 );
const minutes = Math.floor( ( total % 3600 ) / 60 );
const secs = total % 60;
return { days, hours, minutes, seconds: secs };
};
const toLocalInputValue = ( value ) => toSiteInput( value );
const toUtcMysqlValue = ( value ) => siteInputToUtc( value );
const getLinkLabel = ( url ) => {
if ( ! url ) return __( 'Unknown link', 'ai-marketing-expert' );
try {
const parsed = new URL( url, window.location.origin );
// Strip the campaign tracking prefix we add when wrapping links for
// click tracking (e.g. /?aime_track=click&hash=...&token=...&url=...
// &sig=...). The original destination is in the `url` param and
// reading it is more useful than displaying the opaque tracking
// query string.
if ( parsed.searchParams && parsed.searchParams.get( 'aime_track' ) ) {
const original = parsed.searchParams.get( 'url' );
if ( original ) {
return getLinkLabel( original );
}
}
// Return the full destination URL.
return parsed.href;
} catch ( e ) {
return url;
}
};
const MIN_PROGRESS_VISIBLE_MS = 2000;
const LIVE_PROGRESS_INTERVAL_MS = 15000;
const RECIPIENTS_PER_PAGE = 25;
const CampaignProgress = ( { id, sendStartedAt = 0, onBack, onNavigate } ) => {
const { get, post, loading, error, clearError } = useApi();
const [ data, setData ] = useState( null );
const [ report, setReport ] = useState( null );
const [ scheduleValue, setScheduleValue ] = useState( '' );
const [ savingSchedule, setSavingSchedule ] = useState( false );
const [ scheduleNotice, setScheduleNotice ] = useState( null );
const [ togglingQueue, setTogglingQueue ] = useState( false );
const [ endingQueue, setEndingQueue ] = useState( false );
const [ creatingCopy, setCreatingCopy ] = useState( false );
const [ recentProcessed, setRecentProcessed ] = useState( 0 );
const [ activeRecipientTab, setActiveRecipientTab ] = useState( 'sent' );
const [ recipientPage, setRecipientPage ] = useState( 1 );
const [ nowTick, setNowTick ] = useState( Date.now() );
const [ loadFailed, setLoadFailed ] = useState( false );
const [ showTemplatePreview, setShowTemplatePreview ] = useState( false );
const pollRef = useRef();
const processRef = useRef( false );
const lastCompletedRef = useRef( null );
const applyProgressData = useCallback( ( nextData ) => {
const completed = ( nextData?.sent || 0 ) + ( nextData?.failed || 0 );
const backendProcessed = Number( nextData?.processed_now ) || 0;
if ( lastCompletedRef.current !== null ) {
const delta = Math.max( 0, completed - lastCompletedRef.current );
setRecentProcessed( backendProcessed || delta );
} else {
setRecentProcessed( backendProcessed );
}
lastCompletedRef.current = completed;
setData( nextData );
}, [] );
const fetchProgress = useCallback( async () => {
try {
const res = await get( `/email/campaigns/${ id }/progress` );
applyProgressData( res );
setLoadFailed( false );
} catch ( e ) {
setLoadFailed( true );
}
}, [ get, id, applyProgressData ] );
const fetchReport = useCallback( async () => {
try {
const res = await get( `/email/analytics/campaigns/${ id }` );
setReport( res );
} catch ( e ) { /* */ }
}, [ get, id ] );
const processAndRefresh = useCallback( async () => {
if ( processRef.current ) return;
processRef.current = true;
try {
const res = await post( `/email/campaigns/${ id }/process` );
applyProgressData( res );
fetchReport();
} catch ( e ) {
fetchProgress();
} finally {
processRef.current = false;
}
}, [ post, id, fetchProgress, fetchReport ] );
const handleQueueToggle = async () => {
if ( processRef.current || togglingQueue ) return;
const action = effectiveStatus === 'paused' ? 'resume' : 'pause';
setTogglingQueue( true );
try {
const res = await post( `/email/campaigns/${ id }/process`, { action } );
applyProgressData( res );
fetchReport();
} catch ( e ) { /* error surfaced via useApi's error state */ } finally {
setTogglingQueue( false );
}
};
const handleEndCampaign = async () => {
if ( processRef.current || togglingQueue || endingQueue ) return;
// eslint-disable-next-line no-alert
if ( ! window.confirm( __( 'End this campaign now? Remaining unsent emails will be cancelled and cannot be resumed.', 'ai-marketing-expert' ) ) ) {
return;
}
setEndingQueue( true );
try {
const res = await post( `/email/campaigns/${ id }/process`, { action: 'end' } );
applyProgressData( res );
fetchReport();
} catch ( e ) { /* error surfaced via useApi's error state */ } finally {
setEndingQueue( false );
}
};
const handleUseForNewCampaign = async () => {
if ( creatingCopy ) return;
setCreatingCopy( true );
try {
// Reuse the existing duplicate endpoint: it clones the campaign as a
// draft ("
(Copy)") without touching this campaign's stats.
const res = await post( `/email/campaigns/${ id }/duplicate` );
if ( res?.id ) {
onNavigate?.( 'campaign-editor', { id: res.id } );
return;
}
} catch ( e ) { /* error surfaced via useApi's error state */ }
setCreatingCopy( false );
};
useEffect( () => {
// Fetch immediately on mount โ the interval alone would leave the
// page empty (and show a false "not found") for the first 15s.
fetchProgress();
fetchReport();
pollRef.current = setInterval( () => {
fetchProgress();
fetchReport();
}, LIVE_PROGRESS_INTERVAL_MS );
return () => clearInterval( pollRef.current );
}, [ fetchProgress, fetchReport ] );
useEffect( () => {
if ( ! data || ! [ 'working', 'sending' ].includes( data.status ) ) return;
// Kick the first processing tick immediately so sending begins within a
// second or two of landing here, then keep ticking on the live interval.
processAndRefresh();
const timer = setInterval( processAndRefresh, LIVE_PROGRESS_INTERVAL_MS );
return () => clearInterval( timer );
}, [ data?.status, processAndRefresh ] );
/* Stop polling once campaign is fully sent or failed. */
useEffect( () => {
if ( data && ( data.status === 'sent' || data.status === 'failed' ) ) {
clearInterval( pollRef.current );
}
}, [ data ] );
useEffect( () => {
if ( data?.scheduled_at ) {
setScheduleValue( toLocalInputValue( data.scheduled_at ) );
}
}, [ data?.scheduled_at ] );
useEffect( () => {
const timer = setInterval( () => setNowTick( Date.now() ), 1000 );
return () => clearInterval( timer );
}, [] );
useEffect( () => {
if ( ! sendStartedAt ) return;
window.requestAnimationFrame( () => {
window.scrollTo( { top: 0, behavior: 'smooth' } );
document.getElementById( 'wpbody-content' )?.scrollIntoView( { behavior: 'smooth', block: 'start' } );
} );
}, [ sendStartedAt ] );
if ( loading && ! data ) {
return ;
}
if ( ! data ) {
if ( loadFailed ) {
return ;
}
return ;
}
const kpis = [
{ label: __( 'Sent', 'ai-marketing-expert' ), value: data.sent || 0 },
{ label: __( 'Opened', 'ai-marketing-expert' ), value: data.opened || 0 },
{ label: __( 'Clicks', 'ai-marketing-expert' ), value: data.clicks || 0 },
{ label: __( 'Failed', 'ai-marketing-expert' ), value: data.failed || 0 },
{ label: __( 'Unsubscribes', 'ai-marketing-expert' ), value: data.unsubscribes || 0 },
];
const pieData = [
{ name: __( 'Opened', 'ai-marketing-expert' ), value: data.opened || 0 },
{ name: __( 'Not Opened', 'ai-marketing-expert' ), value: Math.max( 0, ( data.sent || 0 ) - ( data.opened || 0 ) ) },
];
const totalRecipients = Math.max( data.total || 0, ( data.sent || 0 ) + ( data.pending || 0 ) + ( data.failed || 0 ) );
const remaining = Math.max( 0, totalRecipients - ( data.sent || 0 ) - ( data.failed || 0 ) );
const sendingNow = Math.max( 0, Math.min( remaining, data.pending || 0 ) );
const rawProgressPercent = totalRecipients > 0 ? Math.round( ( ( ( data.sent || 0 ) + ( data.failed || 0 ) ) / totalRecipients ) * 100 ) : 0;
const completedCount = ( data.sent || 0 ) + ( data.failed || 0 );
const activeBatch = totalRecipients > 0 ? Math.max( 0, Math.min( recentProcessed || Number( data.processed_now ) || 0, remaining + ( recentProcessed || 0 ) ) ) : 0;
const effectiveStatus = data.status || data.campaign?.status || '';
const scheduledTimeRemaining = effectiveStatus === 'scheduled' && data.scheduled_at
? Math.max( 0, Math.floor( ( new Date( `${ data.scheduled_at.replace( ' ', 'T' ) }Z` ).getTime() - nowTick ) / 1000 ) )
: 0;
const isScheduled = effectiveStatus === 'scheduled';
const isSending = [ 'working', 'sending' ].includes( effectiveStatus );
const isPaused = effectiveStatus === 'paused';
const canToggleQueue = ( isSending || isPaused ) && ! togglingQueue && ! processRef.current;
const isMinimumProgressVisible = Boolean( ! isScheduled && ! isSending && ! isPaused && sendStartedAt && ( nowTick - sendStartedAt ) < MIN_PROGRESS_VISIBLE_MS );
const showSendingPanel = isSending || isPaused || isMinimumProgressVisible;
const displayStatus = isMinimumProgressVisible ? 'sending' : effectiveStatus;
const progressPercent = showSendingPanel && rawProgressPercent === 0 && totalRecipients > 0 ? 3 : rawProgressPercent;
const showReports = ! isScheduled && ! showSendingPanel;
const clickToOpenRate = data.opened > 0 ? Math.round( ( ( data.clicks || 0 ) / data.opened ) * 1000 ) / 10 : 0;
const topLinks = report?.top_links?.slice( 0, 5 ) || [];
const maxLinkClicks = Math.max( 1, ...topLinks.map( ( link ) => Number( link.clicks ) || 0 ) );
const topLocations = report?.top_locations_by_opens || [];
const maxLocationOpens = Math.max( 1, ...topLocations.map( ( loc ) => Number( loc.opens ) || 0 ) );
const totalReportOpens = Number( report?.opens_count ?? data.opened ) || 0;
const countdown = formatDuration( scheduledTimeRemaining );
const countdownItems = [
{ label: __( 'Days', 'ai-marketing-expert' ), value: countdown.days, color: '#3858e9' },
{ label: __( 'Hours', 'ai-marketing-expert' ), value: countdown.hours, color: '#18864b' },
{ label: __( 'Minutes', 'ai-marketing-expert' ), value: countdown.minutes, color: '#125f8d' },
{ label: __( 'Seconds', 'ai-marketing-expert' ), value: countdown.seconds, color: '#6b1839' },
];
const recipientTabs = [
{ key: 'sent', label: __( 'Sent', 'ai-marketing-expert' ) },
{ key: 'opened', label: __( 'Opened', 'ai-marketing-expert' ) },
{ key: 'clicked', label: __( 'Clicked', 'ai-marketing-expert' ) },
{ key: 'unsubscribed', label: __( 'Unsubscribed', 'ai-marketing-expert' ) },
{ key: 'complained', label: __( 'Complained', 'ai-marketing-expert' ) },
{ key: 'bounced', label: __( 'Bounced', 'ai-marketing-expert' ) },
];
const recipientLists = report?.recipients || {};
const activeRecipients = recipientLists[ activeRecipientTab ] || [];
const activeRecipientTotal = recipientLists.counts?.[ activeRecipientTab ] ?? activeRecipients.length;
const recipientTotalPages = Math.max( 1, Math.ceil( activeRecipientTotal / RECIPIENTS_PER_PAGE ) );
const safeRecipientPage = Math.min( recipientPage, recipientTotalPages );
const paginatedRecipients = activeRecipients.slice( ( safeRecipientPage - 1 ) * RECIPIENTS_PER_PAGE, safeRecipientPage * RECIPIENTS_PER_PAGE );
const handleScheduleSave = async () => {
setSavingSchedule( true );
setScheduleNotice( null );
try {
await post( `/email/campaigns/${ id }/send`, { scheduled_at: toUtcMysqlValue( scheduleValue ) } );
setScheduleNotice( { type: 'success', message: __( 'Schedule updated.', 'ai-marketing-expert' ) } );
fetchProgress();
} catch ( e ) {
setScheduleNotice( { type: 'error', message: e.message } );
}
setSavingSchedule( false );
};
return (
{ error &&
}
{ __( '\u2190 Back to Campaigns', 'ai-marketing-expert' ) }
{ data.campaign?.title || __( 'Campaign Progress', 'ai-marketing-expert' ) }
{ displayStatus }
{ scheduleNotice &&
setScheduleNotice( null ) } /> }
{ isScheduled && (
{ countdownItems.map( ( item ) => (
{ String( item.value ).padStart( 2, '0' ) }
{ item.label }
) ) }
{ savingSchedule ? <> { __( 'Saving...', 'ai-marketing-expert' ) }> : __( 'Update Schedule', 'ai-marketing-expert' ) }
) }
{ showSendingPanel && (
{ __( 'Your emails are sending right now', 'ai-marketing-expert' ) }
{ totalRecipients > 0
? __( 'Progress updates automatically as WordPress cron completes each batch.', 'ai-marketing-expert' )
: __( 'Preparing the recipient queue. Counts will appear as soon as the audience is resolved.', 'ai-marketing-expert' )
}
{ togglingQueue
? ( isPaused ? __( 'Resuming...', 'ai-marketing-expert' ) : __( 'Pausing...', 'ai-marketing-expert' ) )
: ( isPaused ? __( 'Resume', 'ai-marketing-expert' ) : __( 'Pause', 'ai-marketing-expert' ) ) }
{ endingQueue ? __( 'Ending...', 'ai-marketing-expert' ) : __( 'End Campaign', 'ai-marketing-expert' ) }
{ isPaused ? __( 'Paused', 'ai-marketing-expert' ) : __( 'Sending', 'ai-marketing-expert' ) }
{ totalRecipients }
{ __( 'Total Emails', 'ai-marketing-expert' ) }
{ activeBatch }
{ __( 'Sending Now', 'ai-marketing-expert' ) }
{ data.sent || 0 }
{ __( 'Total Sent', 'ai-marketing-expert' ) }
{ remaining }
{ __( 'Remaining', 'ai-marketing-expert' ) }
{ completedCount }
{ __( 'Processed', 'ai-marketing-expert' ) }
{ data.failed || 0 }
{ __( 'Failed', 'ai-marketing-expert' ) }
) }
{ showReports && (
<>
{ __( 'Total Sent', 'ai-marketing-expert' ) }
{ data.sent || 0 }
{ totalRecipients } { __( 'queued', 'ai-marketing-expert' ) }
{ __( 'Open Rate', 'ai-marketing-expert' ) }
{ data.open_rate || 0 }%
{ data.opened || 0 } { __( 'unique opens', 'ai-marketing-expert' ) }
{ __( 'Click Rate', 'ai-marketing-expert' ) }
{ data.click_rate || 0 }%
{ data.clicks || 0 } { __( 'unique clicks', 'ai-marketing-expert' ) }
{ __( 'Click to Open (CTOR)', 'ai-marketing-expert' ) }
{ clickToOpenRate }%
{ __( 'of openers clicked', 'ai-marketing-expert' ) }
{ __( 'Unsubscribes / Bounces', 'ai-marketing-expert' ) }
{ data.sent > 0 ? Math.round( ( ( ( data.unsubscribes || 0 ) + ( data.bounces || data.failed || 0 ) ) / data.sent ) * 1000 ) / 10 : 0 }%
{ data.unsubscribes || 0 } { __( 'unsub', 'ai-marketing-expert' ) } ยท { data.bounces || data.failed || 0 } { __( 'bounced', 'ai-marketing-expert' ) }
{ topLocations.length > 0 ? (
{ topLocations.slice( 0, 5 ).map( ( loc, index ) => {
const opens = Number( loc.opens ) || 0;
const pct = loc.pct != null ? loc.pct : ( totalReportOpens > 0 ? Math.round( ( opens / totalReportOpens ) * 1000 ) / 10 : 0 );
const barWidth = Math.max( 5, Math.min( 100, Math.round( ( opens / maxLocationOpens ) * 100 ) ) );
const countryCode = ( loc.country || '' ).toUpperCase();
return (
{ getCountryFlag( countryCode ) }
{ getCountryName( countryCode ) }
{ opens }
{ pct }%
);
} ) }
) : (
๐
{ __( 'No location data yet', 'ai-marketing-expert' ) }
{ __( 'Country opens are automatically resolved from incoming tracking requests as recipients open this campaign.', 'ai-marketing-expert' ) }
)}
{ topLinks.length > 0 ? (
{ topLinks.map( ( link, index ) => {
const clicks = Number( link.clicks ) || 0;
const fullUrl = getLinkLabel( link.url );
return (
);
} ) }
) : (
๐
{ __( 'No link clicks yet', 'ai-marketing-expert' ) }
{ __( 'Tracked links will appear here after recipients click campaign links.', 'ai-marketing-expert' ) }
) }
{ Boolean( report?.opens_timeline?.length > 0 ) && (
) }
{ recipientTabs.map( ( tab ) => {
const count = recipientLists.counts?.[ tab.key ] ?? ( recipientLists[ tab.key ] || [] ).length;
return (
{ setActiveRecipientTab( tab.key ); setRecipientPage( 1 ); } }
>
{ tab.label }
{ count }
);
} ) }
{ activeRecipients.length > 0 ? (
{ __( 'Recipient', 'ai-marketing-expert' ) }
{ __( 'Opens', 'ai-marketing-expert' ) }
{ __( 'Clicks', 'ai-marketing-expert' ) }
{ __( 'Status', 'ai-marketing-expert' ) }
{ paginatedRecipients.map( ( recipient ) => (
{ recipient.name || recipient.email || __( 'Unknown recipient', 'ai-marketing-expert' ) }
{ recipient.email && { recipient.email } }
{ recipient.note && activeRecipientTab === 'bounced' && { recipient.note } }
{ recipient.open_count || 0 }
{ recipient.click_count || 0 }
{ recipient.status }
) ) }
{ activeRecipientTotal > RECIPIENTS_PER_PAGE && (
setRecipientPage( safeRecipientPage - 1 ) }>
{ __( 'Previous', 'ai-marketing-expert' ) }
{ safeRecipientPage } / { recipientTotalPages }
= recipientTotalPages } onClick={ () => setRecipientPage( safeRecipientPage + 1 ) }>
{ __( 'Next', 'ai-marketing-expert' ) }
) }
) : (
{ __( 'No recipients in this list yet', 'ai-marketing-expert' ) }
{ __( 'Recipient activity will appear here as opens, clicks, unsubscribes, or bounces are recorded.', 'ai-marketing-expert' ) }
) }
>
) }
{ /* Email template preview + reuse action */ }
{ Boolean( data.campaign?.email_body ) && (
{ __( 'Email Template Preview', 'ai-marketing-expert' ) }
{ data.campaign?.email_subject && (
{ __( 'Subject:', 'ai-marketing-expert' ) } { data.campaign.email_subject }
) }
setShowTemplatePreview( ( prev ) => ! prev ) }
>
{ showTemplatePreview ? __( 'Hide Preview', 'ai-marketing-expert' ) : __( 'Show Preview', 'ai-marketing-expert' ) }
{ creatingCopy ? __( 'Creating draft...', 'ai-marketing-expert' ) : __( 'Use for New Campaign', 'ai-marketing-expert' ) }
}
>
{ showTemplatePreview ? (
) : (
{ __( 'Click "Show Preview" above to inspect the rendered HTML email content sent to recipients.', 'ai-marketing-expert' ) }
) }
) }
);
};
export default CampaignProgress;