/**
* Workflow List — shows all workflows with status, next run, and quick actions.
*/
import { useState, useEffect, useCallback, useRef } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { apiGet, apiPost, apiPut, apiDelete } from '../../../utils/api';
import { toast } from '../../common/Toast';
import Card from '../../common/Card';
import Loader from '../../common/Loader';
import ConfirmModal from '../../common/ConfirmModal';
import LoadingBtn from '../../common/LoadingBtn';
import TestRunModal from './TestRunModal';
import { formatDateTime } from '../../../utils/datetime';
import { Button } from '../../common/WpComponents';
import AiWorkflowModal from './AiWorkflowModal';
const STATUS_LABELS = {
active: __( 'Active', 'ai-marketing-expert' ),
paused: __( 'Paused', 'ai-marketing-expert' ),
draft: __( 'Draft', 'ai-marketing-expert' ),
};
// Stored as UTC; rendered in the site timezone and format (Settings → General).
const formatDate = ( value ) => formatDateTime( value );
const WorkflowList = ( { onNavigate } ) => {
const [ loading, setLoading ] = useState( true );
const [ workflows, setWorkflows ] = useState( [] );
const [ usage, setUsage ] = useState( null );
const [ runningId, setRunningId ] = useState( null );
const [ runStatuses, setRunStatuses ] = useState( {} ); // wfId → queued|running|success|partial|failed
const [ togglingId, setTogglingId ] = useState( null );
const [ confirmDelete, setConfirmDelete ] = useState( null );
const [ testRunWf, setTestRunWf ] = useState( null );
const [ triggers, setTriggers ] = useState( [] );
const [ aiModalOpen, setAiModalOpen ] = useState( false );
const [ brandVoices, setBrandVoices ] = useState( [] );
const pollsRef = useRef( {} );
useEffect( () => () => {
Object.values( pollsRef.current ).forEach( clearInterval );
}, [] );
const load = useCallback( async () => {
setLoading( true );
try {
const res = await apiGet( '/workflow-automation/workflows' );
setWorkflows( res?.workflows || [] );
} catch ( e ) {
toast( e?.message || __( 'Failed to load workflows.', 'ai-marketing-expert' ), 'error' );
} finally {
setLoading( false );
}
// Meters move whenever a workflow is activated, deleted, or run.
try {
const res = await apiGet( '/workflow-automation/usage' );
setUsage( res?.usage || null );
} catch ( e ) { /* meters are advisory; never block the list */ }
}, [] );
useEffect( () => {
load();
// Trigger definitions provide the sample-payload fields for test runs.
apiGet( '/workflow-automation/triggers' )
.then( ( res ) => setTriggers( res?.triggers || [] ) )
.catch( () => {} );
apiGet( '/content/brand-voices' )
.then( ( res ) => setBrandVoices( res?.items || [] ) )
.catch( () => {} );
}, [ load ] );
const handleAiGenerated = ( generatedWf ) => {
onNavigate( 'edit-workflow', { initialWorkflow: generatedWf } );
};
const pollExecution = useCallback( ( wfId, executionId ) => {
if ( pollsRef.current[ wfId ] ) {
clearInterval( pollsRef.current[ wfId ] );
}
pollsRef.current[ wfId ] = setInterval( async () => {
try {
const res = await apiGet( `/workflow-automation/executions/${ executionId }` );
const status = res?.execution?.status;
if ( ! status ) {
return;
}
setRunStatuses( ( prev ) => ( { ...prev, [ wfId ]: status } ) );
if ( ! [ 'queued', 'running' ].includes( status ) ) {
clearInterval( pollsRef.current[ wfId ] );
delete pollsRef.current[ wfId ];
toast(
status === 'success'
? __( 'Workflow run finished successfully.', 'ai-marketing-expert' )
: `${ __( 'Workflow run finished:', 'ai-marketing-expert' ) } ${ status }`,
status === 'success' ? 'success' : 'warning'
);
load();
}
} catch ( e ) { /* ignore transient poll errors */ }
}, 3000 );
}, [ load ] );
const queueRun = async ( wf, event = null ) => {
setRunningId( wf.id );
try {
const res = await apiPost(
`/workflow-automation/workflows/${ wf.id }/run`,
event && Object.keys( event ).length ? { event } : {}
);
if ( res?.queued && res?.execution_id ) {
toast( __( 'Run queued…', 'ai-marketing-expert' ), 'info' );
setRunStatuses( ( prev ) => ( { ...prev, [ wf.id ]: 'queued' } ) );
pollExecution( wf.id, res.execution_id );
}
} catch ( e ) {
toast( e?.message || __( 'Run failed.', 'ai-marketing-expert' ), 'error' );
} finally {
setRunningId( null );
}
};
const runNow = ( wf ) => {
// Event workflows get their data from the trigger; ask for a sample
// payload so a manual run behaves like a real one.
if ( wf.trigger_type === 'event' ) {
const trig = ( triggers || [] ).find( ( t ) => t.key === wf.trigger_event );
if ( trig && trig.available === false ) {
const req = trig.requires_label || trig.requires_plugin || __( 'Plugin', 'ai-marketing-expert' );
toast(
sprintf(
__( 'Cannot run workflow: Trigger requires "%s", which is not installed or active on this site.', 'ai-marketing-expert' ),
req
),
'error'
);
return;
}
setTestRunWf( wf );
return;
}
queueRun( wf );
};
const toggleStatus = async ( wf ) => {
const next = wf.status === 'active' ? 'paused' : 'active';
setTogglingId( wf.id );
try {
await apiPut( `/workflow-automation/workflows/${ wf.id }`, { status: next } );
toast(
next === 'active'
? __( 'Workflow activated.', 'ai-marketing-expert' )
: __( 'Workflow paused.', 'ai-marketing-expert' ),
'success'
);
load();
} catch ( e ) {
toast( e?.message || __( 'Could not update status.', 'ai-marketing-expert' ), 'error' );
} finally {
setTogglingId( null );
}
};
const doDelete = async () => {
const wf = confirmDelete;
setConfirmDelete( null );
try {
await apiDelete( `/workflow-automation/workflows/${ wf.id }` );
toast( __( 'Workflow deleted.', 'ai-marketing-expert' ), 'success' );
load();
} catch ( e ) {
toast( e?.message || __( 'Delete failed.', 'ai-marketing-expert' ), 'error' );
}
};
// `load()` also runs after a delete, a duplicate and a manual run. Blanking
// the whole list for those refetches threw the page away and rebuilt it; the
// list stays on screen and only the first load shows a skeleton.
if ( loading && ! workflows.length ) {
return
{ __( 'No workflows yet. Create one to automate content, SEO, email, and social tasks on a schedule or event.', 'ai-marketing-expert' ) }
| { __( 'Name', 'ai-marketing-expert' ) } | { __( 'Status', 'ai-marketing-expert' ) } | { __( 'Next run', 'ai-marketing-expert' ) } | { __( 'Last run', 'ai-marketing-expert' ) } | { __( 'Runs', 'ai-marketing-expert' ) } | { __( 'Actions', 'ai-marketing-expert' ) } |
|---|---|---|---|---|---|
|
{ isUnavailable && (
⚠️ { sprintf( __( 'Requires %s (not installed)', 'ai-marketing-expert' ), reqLabel ) }
) }
{ ( wf.description || wf.trigger_event === 'woo_cart_abandoned' ) && (
{ wf.description }
{ wf.trigger_event === 'woo_cart_abandoned' && (
General.', 'ai-marketing-expert' ), wf.woo_cart_cutoff_minutes || window.aimeData?.wooCartCutoffMinutes || 30 ) }
>
⏱️ { sprintf( __( 'Triggers after %d mins of inactivity', 'ai-marketing-expert' ), wf.woo_cart_cutoff_minutes || window.aimeData?.wooCartCutoffMinutes || 30 ) }
) }
) }
|
{ STATUS_LABELS[ wf.status ] || wf.status } | { formatDate( wf.next_run_at ) } | { formatDate( wf.last_run_at ) } | { wf.run_count } |
{ runStatuses[ wf.id ] && (
{ runStatuses[ wf.id ] }
) }
{ runningId === wf.id || [ 'queued', 'running' ].includes( runStatuses[ wf.id ] ) ? (
|