/**
* Workflow Analytics — the Workflow Automation landing page.
*
* The module had no analytics at all. The list answered "did it run" with a
* date and a lifetime counter, and the error log answered "what broke" one
* incident at a time. Neither answers the question that actually matters for
* unattended automation: *is this working*. A workflow that has run 24 times
* and failed 24 times looks identical, on the list, to one that has never
* missed.
*
* Every number here comes from rows the engine already wrote — execution
* outcomes, step tallies, timestamps, and per-step output statuses. Nothing
* new is instrumented; it was all being recorded and none of it was read.
*/
import { useState, useEffect, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import {
ResponsiveContainer,
BarChart,
Bar,
XAxis,
YAxis,
Tooltip,
CartesianGrid,
Legend,
} from 'recharts';
import { apiGet } from '../../../utils/api';
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 { formatDateTime } from '../../../utils/datetime';
import { Button } from '../../common/WpComponents';
const RANGES = [ 7, 30, 90 ];
/*
* Recharts writes stroke and fill as SVG presentation attributes, where a
* `var()` never resolves — so these are literals. Workflow Automation takes no
* room light: it is house forest green, like the lobby, because it is the room
* that operates all the others rather than one of them.
*
* The outcome ramp is the system's own status palette, not a decorative scale.
* Success is leaf green, partial is the warning amber, failed is the error red,
* and skipped is deliberately desaturated — a skipped run is not a failure, it
* is the free-plan cap refusing to start one, and colouring it like damage
* would blame the workflow for the plan.
*/
const OUTCOME = {
success: '#2E7D32',
partial: '#F9A825',
failed: '#D32F2F',
skipped: '#cbd8cc',
};
const HOUSE = '#1B5E20';
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,
};
const WF_STATUS_COLORS = {
active: '#2E7D32',
paused: '#F9A825',
draft: '#8fa893',
};
const WF_STATUS_LABELS = {
active: __( 'Active', 'ai-marketing-expert' ),
paused: __( 'Paused', 'ai-marketing-expert' ),
draft: __( 'Draft', 'ai-marketing-expert' ),
};
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 days that had a run, so a
* 30-day window with four busy days comes back as four points. Plotted raw,
* three weeks of silence between two of them renders exactly as wide as a
* single overnight gap and the axis lies about the shape of the work.
* Scaffolding every day back in at zero is what makes the spacing true — and
* for a schedule-driven module the *gaps* are the finding, so this matters more
* here than anywhere else in the plugin.
*
* Rows outside the scaffold are kept rather than dropped: a timezone difference
* between PHP's gmdate and the browser can put a real run one day either side
* of the window, and silently losing it is worse than one extra tick.
*/
const buildSeries = ( days, rows ) => {
const byDate = {};
const blank = () => ( { success: 0, partial: 0, failed: 0, skipped: 0 } );
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, ...blank() };
}
( rows || [] ).forEach( ( row ) => {
const key = String( row.date || '' ).slice( 0, 10 );
if ( ! key ) {
return;
}
if ( ! byDate[ key ] ) {
byDate[ key ] = { date: key, ...blank() };
}
if ( byDate[ key ][ row.status ] !== undefined ) {
byDate[ key ][ row.status ] = Number( row.count ) || 0;
}
} );
return Object.values( byDate )
.sort( ( a, b ) => a.date.localeCompare( b.date ) )
.map( ( point ) => ( { ...point, label: point.date.slice( 5 ) } ) );
};
/**
* Seconds as something a person reads at a glance. Runs here span a two-second
* notification and a six-minute article generation, so a raw seconds column
* would make the reader do the division on every row.
*
* @param {number} seconds Duration in seconds.
* @return {string} Formatted duration.
*/
const formatDuration = ( seconds ) => {
const total = Math.max( 0, Math.round( Number( seconds ) || 0 ) );
if ( total === 0 ) {
return '—';
}
if ( total < 60 ) {
/* translators: %d: seconds. */
return sprintf( __( '%ds', 'ai-marketing-expert' ), total );
}
const mins = Math.floor( total / 60 );
const secs = total % 60;
if ( mins < 60 ) {
return secs
/* translators: 1: minutes, 2: seconds. */
? sprintf( __( '%1$dm %2$ds', 'ai-marketing-expert' ), mins, secs )
/* translators: %d: minutes. */
: sprintf( __( '%dm', 'ai-marketing-expert' ), mins );
}
/* translators: 1: hours, 2: minutes. */
return sprintf( __( '%1$dh %2$dm', 'ai-marketing-expert' ), Math.floor( mins / 60 ), mins % 60 );
};
const WorkflowAnalytics = ( { onNavigate } ) => {
const [ loading, setLoading ] = useState( true );
const [ error, setError ] = useState( '' );
const [ stats, setStats ] = useState( null );
const [ days, setDays ] = useState( 30 );
const load = useCallback( async ( range ) => {
setLoading( true );
try {
const res = await apiGet( `/workflow-automation/analytics?days=${ range }` );
setStats( res );
setError( '' );
} catch ( e ) {
setError( e?.message || __( 'Failed to load analytics.', 'ai-marketing-expert' ) );
} finally {
setLoading( false );
}
}, [] );
useEffect( () => {
load( days );
}, [ load, days ] );
if ( loading && ! stats ) {
return
{ partialRuns > 0 ? sprintf( /* translators: %s: number of partly failed runs. */ __( '%s runs finished with some steps missing.', 'ai-marketing-expert' ), partialRuns.toLocaleString() ) : __( 'Every run that started got all the way through its steps.', 'ai-marketing-expert' ) }
{ runsFinished > 0 ? sprintf( /* translators: 1: unattended runs, 2: manual runs. */ __( '%1$s fired from a schedule or trigger, %2$s from Run now.', 'ai-marketing-expert' ), unattendedRuns.toLocaleString(), manualRuns.toLocaleString() ) : __( 'No finished runs in this window yet.', 'ai-marketing-expert' ) }
{ sprintf( /* translators: 1: average run duration, 2: slowest run duration. */ __( 'Runs take %1$s on average; the slowest took %2$s.', 'ai-marketing-expert' ), formatDuration( avgSeconds ), formatDuration( maxSeconds ) ) }
) }{ __( 'Failures per action, with the share of its attempts that failed.', 'ai-marketing-expert' ) } { ' ' }
> ) : ({ stepsSucceeded > 0 ? __( 'No step failed in this window. Nothing here needs your attention.', 'ai-marketing-expert' ) : __( 'No steps have run in this window, so there is nothing to diagnose yet.', 'ai-marketing-expert' ) }
) }| { __( 'Workflow', 'ai-marketing-expert' ) } | { __( 'Status', 'ai-marketing-expert' ) } | { __( 'Runs', 'ai-marketing-expert' ) } | { __( 'Clean', 'ai-marketing-expert' ) } | { __( 'Avg time', 'ai-marketing-expert' ) } | { __( 'Last run', 'ai-marketing-expert' ) } |
|---|---|---|---|---|---|
| { wf.name || __( '(untitled)', 'ai-marketing-expert' ) } | { WF_STATUS_LABELS[ wf.status ] || wf.status } | { Number( wf.runs || 0 ).toLocaleString() } | { /* * A bar, not another percentage column. Nine rows of * "94.2%" is nine numbers to read in sequence; nine * bars on a shared baseline is one shape, and the * odd one out is visible before it is read. */ }0 ? OUTCOME.failed : OUTCOME.success, } } /> { `${ Math.round( Number( wf.success_rate ) || 0 ) }%` } | { formatDuration( wf.avg_seconds ) } | { formatDateTime( wf.last_run_at ) } |
{ sprintf( /* translators: %s: number of active workflows with no runs. */ __( '%s active workflows did not run at all in this window — check their schedule or trigger.', 'ai-marketing-expert' ), idleActive.toLocaleString() ) }
) } > ) : (