/** * The entries screen (Funnelforms → Entries): the lead list of 5.0 in the frame of the other * admin pages, with key figures that filter it, a compact filter bar, the list as a table or a * board by lead status, changes to many entries at once and one entry in a side panel. * Filters, the view and the open entry live in the address, so links and the back button work. */ import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import { localeTag } from '@funnelforms/form-core'; import type { Appointment, BulkChanges, EntryDevice, EntriesApi, EntryDetail, EntryFigures, EntryFilter, EntryList, EntrySummary, EntryVisit, LeadStage, LeadStageTone, LeadStatus, PaymentStatus, SpamReason, UserRef } from '../api'; import { addressOf, avatarTone, byLeadStatus, change, DEVICES, entryEmail, entryName, entryPhone, exportLink, figureMoments, filtered, initials, MAX_STAGE_NAME, MAX_STAGES, moveStage, parseTags, periodStart, relativeTime, STAGE_TONES, stageInputs, stageNameProblem, standardStages, stateFromAddress, valueText, type EntriesState, type Period } from '../entries'; import { pageLocale, zoneName } from '../appointments'; import { kindName } from './Actions'; import { EmptyState, Frame, FrameButton, Icon, Kpi, Pill, type PillTone } from './Frame'; import { __, sprintf } from './i18n'; import { Badge, Button, Dialog, icons, Notice, Spinner } from './ui'; export interface EntriesConfig { forms?: Array<{ id: number; title: string }>; /** Export link without filters; missing without the right to export. */ exportUrl?: string | null; builderUrl?: string | null; user?: { id: number; admin: boolean }; userLocale?: string; /** The lead stages of the site, the columns of the board (Funnelforms Pro). */ stages?: LeadStage[] | null; /** Whether the user may rename, add, order and delete the stages. */ editStages?: boolean; /** Whether the user may delete entries (a right of its own); missing counts as allowed. */ canDelete?: boolean; } const PER_PAGE = 25; const BOARD_SIZE = 100; type Tone = 'neutral' | 'success' | 'warning' | 'danger' | 'brand'; /** The site's lead stages, for every part of the screen that names or lists them. */ const StagesContext = createContext( [] ); /** Name of a lead stage: the site's own, else the standard name of the stages of 5.0, else its key. */ export function leadStatusName( status: LeadStatus, stages: readonly LeadStage[] = [] ): string { const own = stages.find( ( s ) => s.key === status ); if ( own ) { return own.name; } const standard: Record = { new: __( 'New', 'funnelforms-pro' ), contacted: __( 'Contacted', 'funnelforms-pro' ), won: __( 'Won', 'funnelforms-pro' ), lost: __( 'Lost', 'funnelforms-pro' ), }; return standard[ status ] ?? status; } /** Names of the colours a stage can have, as the stage dialog offers them. */ function toneName( tone: LeadStageTone ): string { return { info: __( 'Purple', 'funnelforms-pro' ), warning: __( 'Amber', 'funnelforms-pro' ), success: __( 'Green', 'funnelforms-pro' ), neutral: __( 'Grey', 'funnelforms-pro' ), danger: __( 'Red', 'funnelforms-pro' ), }[ tone ]; } /** Colour of a lead stage, the same in the table, on the board and in the panel. */ function stageTone( status: LeadStatus, stages: readonly LeadStage[] ): PillTone { return stages.find( ( s ) => s.key === status )?.tone ?? 'neutral'; } /** Why an entry is in the spam folder, as the panel says it. */ export function spamReasonName( reason: SpamReason ): string { return ( { honeypot: __( 'A hidden field was filled in, as bots do', 'funnelforms-pro' ), too_fast: __( 'Sent faster than the shortest time to fill in', 'funnelforms-pro' ), captcha_score: __( 'Low score of reCAPTCHA v3', 'funnelforms-pro' ), akismet: __( 'Akismet rates it as spam', 'funnelforms-pro' ), rule_words: __( 'Contains a word of the blocklist', 'funnelforms-pro' ), rule_email: __( 'E-mail address or domain of the blocklist', 'funnelforms-pro' ), rule_ip: __( 'IP address of the blocklist', 'funnelforms-pro' ), rule_disposable: __( 'Throwaway e-mail address', 'funnelforms-pro' ), }[ reason ] ?? reason ); } function paymentName( status: PaymentStatus ): string { return { open: __( 'Not paid yet', 'funnelforms-pro' ), pending: __( 'Payment pending', 'funnelforms-pro' ), paid: __( 'Paid', 'funnelforms-pro' ), failed: __( 'Payment failed', 'funnelforms-pro' ), canceled: __( 'Payment canceled', 'funnelforms-pro' ), refunded: __( 'Refunded', 'funnelforms-pro' ), disputed: __( 'Payment disputed', 'funnelforms-pro' ), }[ status ]; } const PAYMENT_TONE: Record = { open: 'neutral', pending: 'warning', paid: 'success', failed: 'danger', canceled: 'neutral', refunded: 'neutral', disputed: 'danger' }; function actionName( kind: string ): string { return 'optin' === kind ? __( 'Confirmation link (double opt-in)', 'funnelforms-pro' ) : kindName( kind ); } /** Date and time of an appointment in the time zone of its type, in the editor's language. */ export function appointmentTime( a: Pick ): string { try { return new Date( a.start ).toLocaleString( undefined, { dateStyle: 'full', timeStyle: 'short', timeZone: a.timezone || undefined } ); } catch { return new Date( a.start ).toLocaleString(); } } /** Name of a delivery the plugin queued itself (appointment mails); the job's name otherwise. */ export function deliveryName( action: string ): string { if ( action.startsWith( ':booking-cancel:' ) ) { return __( 'Appointment cancellation', 'funnelforms-pro' ); } if ( action.startsWith( ':booking:' ) ) { // ":booking::": a version above 0 is the mail about a moved appointment. return Number( action.split( ':' )[ 3 ] ) > 0 ? __( 'Appointment moved', 'funnelforms-pro' ) : __( 'Appointment invitation', 'funnelforms-pro' ); } if ( action.startsWith( ':reminder:' ) ) { return __( 'Appointment reminder', 'funnelforms-pro' ); } if ( action.startsWith( ':calendar:' ) ) { return __( 'Calendar entry', 'funnelforms-pro' ); } if ( action.startsWith( ':aicall:result:' ) ) { // The job that fetches the outcome of a call from ElevenLabs (Application\AiCalls::RESULT). return __( 'AI Phone Agent: result of the call', 'funnelforms-pro' ); } if ( action.startsWith( ':aicall:retry:' ) ) { return __( 'AI Phone Agent: next call', 'funnelforms-pro' ); } if ( ':abandon:1' === action ) { return __( 'Reminder to the visitor', 'funnelforms-pro' ); } if ( ':abandon:2' === action ) { return __( 'Second reminder to the visitor', 'funnelforms-pro' ); } if ( ':abandon:owner' === action ) { return __( 'Note about the abandoned lead', 'funnelforms-pro' ); } return action; } /** Badge of a visitor who left after typing the address, or of the entry such a visitor sent later. */ export function abandonBadge( entry: Pick ) { const state = entry.abandon?.state; if ( 'abandoned' === entry.status ) { const label = 'sent' === state ? __( 'Abandoned, reminded', 'funnelforms-pro' ) : 'stopped' === state ? __( 'Abandoned, no reminders', 'funnelforms-pro' ) : __( 'Abandoned', 'funnelforms-pro' ); return { label }; } return 'recovered' === state ? { __( 'Recovered by the reminder', 'funnelforms-pro' ) } : null; } function deliveryBadge( status: string ) { switch ( status ) { case 'sent': return { __( 'Sent', 'funnelforms-pro' ) }; case 'failed': return { __( 'Failed', 'funnelforms-pro' ) }; case 'skipped': return { __( 'Skipped', 'funnelforms-pro' ) }; case 'queued': return { __( 'Waiting', 'funnelforms-pro' ) }; case 'retrying': return { __( 'Trying again', 'funnelforms-pro' ) }; default: return { status }; } } /** The action a job belongs to: its channel, without the prefix of a run by hand (ActionQueue::AGAIN). */ export function deliveryAction( channel: string ): string { return channel.startsWith( ':again:' ) ? channel.slice( 7 ) : channel; } /** Why a step did nothing, in words, for the codes that are no failure; other codes as they are. */ function skipReason( code: string ): string { return ( { condition_not_met: __( 'Its condition does not apply to this entry', 'funnelforms-pro' ), no_recipient: __( 'Nobody to send to', 'funnelforms-pro' ), no_consent: __( 'No consent to be called', 'funnelforms-pro' ), }[ code ] ?? code ); } /** * What running an action again is called and what a click does, by kind: mails and messages are * sent, webhooks and CRM transfers run, the AI Phone Agent calls. */ export function againTexts( kind: string ): { button: string; what: string; done: string } { const sent = __( 'Started. The status updates in a few seconds.', 'funnelforms-pro' ); if ( 'aiCall' === kind ) { return { button: __( 'Call again', 'funnelforms-pro' ), what: __( 'The AI Phone Agent calls the lead again: right away inside its call hours, otherwise when they start. Consent and number are checked as for every call.', 'funnelforms-pro' ), done: __( 'Call planned. The result appears under AI Phone Agent.', 'funnelforms-pro' ), }; } if ( [ 'email', 'autoresponder', 'chat', 'sms', 'whatsapp', 'conversion', 'optin' ].includes( kind ) ) { return { button: 'optin' === kind ? __( 'Send link again', 'funnelforms-pro' ) : __( 'Send again', 'funnelforms-pro' ), what: __( 'This sends it once more, with the settings the form has now.', 'funnelforms-pro' ), done: sent }; } return { button: 'crm' === kind ? __( 'Transfer again', 'funnelforms-pro' ) : __( 'Trigger again', 'funnelforms-pro' ), what: __( 'This runs it once more for this entry, with the settings the form has now (for example a corrected address).', 'funnelforms-pro' ), done: sent, }; } /** * The notes of the team. The plugin notes each call of the AI Phone Agent as well (for the app and * the data export); the panel shows the calls in their own section, so not twice. */ export function teamNotes( entry: Pick ): EntryDetail[ 'notes' ] { const calls = ( entry.aiCalls ?? [] ).some( ( c ) => c.attempts.length > 0 ); return calls ? entry.notes.filter( ( n ) => null !== n.author ) : entry.notes; } /** Dates in the editor's language: in full, and as people say it ("5 min. ago"). */ interface Dates { ( iso: string | null ): string; ago: ( iso: string | null ) => string; } function useDates( locale?: string ): Dates { return useMemo( () => { const tag = localeTag( locale ); let format: Intl.DateTimeFormat; try { format = new Intl.DateTimeFormat( tag, { dateStyle: 'medium', timeStyle: 'short' } ); } catch { format = new Intl.DateTimeFormat( undefined, { dateStyle: 'medium', timeStyle: 'short' } ); } const full = ( iso: string | null ): string => ( iso ? format.format( new Date( iso ) ) : '' ); return Object.assign( full, { ago: ( iso: string | null ): string => relativeTime( iso, new Date(), locale ) } ); }, [ locale ] ); } function message( e: unknown ): string { return e instanceof Error ? e.message : String( e ); } /** Name of an entry for lists, with a fallback that is never empty. */ function title( entry: EntrySummary ): string { return entryName( entry ) || sprintf( __( 'Entry #%d', 'funnelforms-pro' ), entry.id ); } /** A number in the editor's language (1,234). */ function num( n: number ): string { return n.toLocaleString(); } /** The round mark of a person: initials in one of six colours, or a figure without a name. */ function Avatar( { name, size = 'md' }: { name: string; size?: 'sm' | 'md' | 'lg' } ) { const letters = initials( name ); return ( ); } /** When an entry came in, as people say it, with date and time on hover. */ function When( { iso, date }: { iso: string | null; date: Dates } ) { return iso ? ( ) : null; } /** The lead value of an entry (estimated order value, Pro) as a badge; nothing without one. */ function ValueBadge( { entry }: { entry: EntrySummary } ) { if ( 'free' === process.env.FUNNELFORMS_EDITION || null === entry.value || undefined === entry.value ) { return null; } return { sprintf( /* translators: %s: estimated order value of a lead, e.g. 1,250 */ __( 'Value %s', 'funnelforms-pro' ), entry.value.toLocaleString( undefined, { maximumFractionDigits: 2 } ) ) }; } function LeadPill( { status }: { status: LeadStatus } ) { const stages = useContext( StagesContext ); return { leadStatusName( status, stages ) }; } /** What "Show" filters: unread, sent or incomplete entries. */ function showValue( filter: EntryFilter ): string { return filter.status && 'spam' !== filter.status ? filter.status : false === filter.read ? 'unread' : ''; } /** The state of the address; Funnelforms Free has no lead status, tags, assignment or board, whatever the address says. */ function fromAddress( search: string, stages: readonly LeadStage[] ): EntriesState { const next = stateFromAddress( search, stages.map( ( s ) => s.key ) ); if ( 'free' !== process.env.FUNNELFORMS_EDITION ) { return next; } const filter: EntryFilter = { ...next.filter }; for ( const key of [ 'leadStatus', 'tag', 'assignedTo' ] as const ) { Reflect.deleteProperty( filter, key ); } return { ...next, filter, view: 'list' }; } export function EntriesScreen( { api, config = {} }: { api: EntriesApi; config?: EntriesConfig } ) { const [ stages, setStages ] = useState( () => ( config.stages?.length ? config.stages : standardStages( ( key ) => leadStatusName( key ) ) ) ); const [ state, setState ] = useState( () => fromAddress( window.location.search, stages ) ); // The stage being edited on the board, or ADD_STAGE while one is added. const [ stageEdit, setStageEdit ] = useState( null ); const [ data, setData ] = useState( null ); const [ error, setError ] = useState( null ); const [ notice, setNotice ] = useState<{ tone: 'success' | 'warning' | 'danger'; text: string } | null>( null ); const [ selected, setSelected ] = useState( [] ); const [ busy, setBusy ] = useState( false ); const [ tags, setTags ] = useState>( [] ); const [ assignees, setAssignees ] = useState( [] ); const [ search, setSearch ] = useState( state.filter.search ?? '' ); const [ figures, setFigures ] = useState( null ); const [ more, setMore ] = useState( false ); const date = useDates( config.userLocale ); // The address follows the state; the back button brings an earlier state back. const go = useCallback( ( next: EntriesState, replace = false ): void => { const url = addressOf( next, window.location.href ); if ( url !== window.location.href ) { window.history[ replace ? 'replaceState' : 'pushState' ]( null, '', url ); } setState( next ); }, [] ); useEffect( () => { const onPop = (): void => setState( fromAddress( window.location.search, stages ) ); window.addEventListener( 'popstate', onPop ); return () => window.removeEventListener( 'popstate', onPop ); }, [ stages ] ); const setFilter = ( changes: Partial, period: Period = state.period, view = state.view ): void => { const filter: EntryFilter = { ...state.filter, ...changes, page: undefined }; for ( const key of Object.keys( changes ) as Array ) { if ( undefined === changes[ key ] || '' === changes[ key ] ) { Reflect.deleteProperty( filter, key ); } } setSelected( [] ); go( { ...state, filter, period, view } ); }; const query = useMemo( (): EntryFilter => { const board = 'board' === state.view && 'spam' !== state.filter.status; const { leadStatus, ...rest } = state.filter; return { ...( board ? rest : { ...rest, leadStatus } ), after: periodStart( state.period ), page: board ? 1 : state.filter.page ?? 1, perPage: board ? BOARD_SIZE : PER_PAGE, }; }, [ state.filter, state.period, state.view ] ); // The key figures count the open entries of the chosen form. const figuresForm = state.filter.form; const loadFigures = useCallback( async (): Promise => { if ( ! api.entryFigures ) { return; } try { setFigures( await api.entryFigures( { form: figuresForm, ...figureMoments() } ) ); } catch { // The list works without them. } }, [ api, figuresForm ] ); useEffect( () => { void loadFigures(); }, [ loadFigures ] ); const reload = useCallback( async (): Promise => { setError( null ); try { setData( await api.entries( query ) ); } catch ( e ) { setError( message( e ) ); } }, [ api, query ] ); useEffect( () => { void reload(); }, [ reload ] ); const loadLists = useCallback( async (): Promise => { if ( 'free' === process.env.FUNNELFORMS_EDITION ) { // Tags and assignment are part of Funnelforms Pro. return; } try { const [ t, a ] = await Promise.all( [ api.entryTags(), api.assignees() ] ); setTags( t ); setAssignees( a ); } catch { // The filters work without them. } }, [ api ] ); useEffect( () => { void loadLists(); }, [ loadLists ] ); // Typing searches after a short pause. useEffect( () => { if ( search === ( state.filter.search ?? '' ) ) { return undefined; } const timer = setTimeout( () => setFilter( { search: search.trim() || undefined } ), 300 ); return () => clearTimeout( timer ); }, [ search ] ); const act = async ( work: () => Promise, done?: string ): Promise => { setBusy( true ); try { await work(); if ( done ) { setNotice( { tone: 'success', text: done } ); } await reload(); void loadFigures(); return true; } catch ( e ) { setNotice( { tone: 'danger', text: message( e ) } ); return false; } finally { setBusy( false ); } }; const bulk = async ( changes: BulkChanges, done: string ): Promise => { const ok = await act( () => api.bulkEntries( selected, changes ), done ); if ( ok ) { setSelected( [] ); if ( changes.addTags || changes.removeTags ) { void loadLists(); } } }; const open = ( id: number | null ): void => go( { ...state, entry: id } ); // The board's columns: saved at once for everyone, entries of a deleted stage move along. const canEditStages = !! config.editStages && !! api.saveLeadStages; // Answers the problem in words, or null when the stages are saved. const saveStages = async ( next: LeadStage[], done: string, moveTo?: Record ): Promise => { const save = api.saveLeadStages; if ( ! save ) { return null; } setBusy( true ); try { setStages( await save.call( api, stageInputs( next ), moveTo ) ); setNotice( { tone: 'success', text: done } ); if ( moveTo && state.filter.leadStatus && moveTo[ state.filter.leadStatus ] ) { // The filtered stage is gone. setFilter( { leadStatus: undefined } ); } else { await reload(); } void loadFigures(); return null; } catch ( e ) { return message( e ); } finally { setBusy( false ); } }; const moveColumn = ( key: LeadStatus, to: number ): void => { const from = stages.findIndex( ( s ) => s.key === key ); if ( from >= 0 && from !== to ) { void saveStages( moveStage( stages, from, to - from ), sprintf( /* translators: %s: name of a lead stage */ __( '“%s” moved.', 'funnelforms-pro' ), stages[ from ]?.name ?? '' ) ).then( ( problem ) => problem && setNotice( { tone: 'danger', text: problem } ) ); } }; const entries = data?.entries ?? []; const spam = 'spam' === state.filter.status; const archive = true === state.filter.archived && ! spam; const forms = config.forms ?? []; // The spam folder is a list; lead statuses mean nothing there. const board = 'board' === state.view && ! spam; const page = state.filter.page ?? 1; const clear = (): void => { setSearch( '' ); setSelected( [] ); go( { ...state, filter: archive ? { archived: true } : spam ? { status: 'spam' } : {}, period: '' } ); }; // Filters behind "Filters", shown as chips while they apply. const assigneeName = ( id: number ): string => ( 0 === id ? __( 'Nobody', 'funnelforms-pro' ) : id === config.user?.id ? __( 'Me', 'funnelforms-pro' ) : assignees.find( ( a ) => a.id === id )?.name ?? sprintf( __( 'User #%d', 'funnelforms-pro' ), id ) ); const showOptions = [ { value: '', label: __( 'All entries', 'funnelforms-pro' ) }, { value: 'unread', label: __( 'Unread', 'funnelforms-pro' ) }, { value: 'complete', label: __( 'Sent', 'funnelforms-pro' ) }, { value: 'partial', label: __( 'Incomplete', 'funnelforms-pro' ) }, ...( 'free' !== process.env.FUNNELFORMS_EDITION ? [ { value: 'abandoned', label: __( 'Abandoned', 'funnelforms-pro' ) } ] : [] ), ]; const chips: Array<{ key: string; label: string; remove: () => void }> = []; if ( undefined !== state.filter.assignedTo ) { chips.push( { key: 'assignedTo', label: sprintf( __( 'Assigned to: %s', 'funnelforms-pro' ), assigneeName( state.filter.assignedTo ) ), remove: () => setFilter( { assignedTo: undefined } ) } ); } if ( state.filter.tag ) { chips.push( { key: 'tag', label: sprintf( __( 'Tag: %s', 'funnelforms-pro' ), state.filter.tag ), remove: () => setFilter( { tag: undefined } ) } ); } if ( state.filter.device ) { chips.push( { key: 'device', label: sprintf( __( 'Device: %s', 'funnelforms-pro' ), deviceName( state.filter.device ) ), remove: () => setFilter( { device: undefined } ) } ); } if ( '' !== showValue( state.filter ) ) { chips.push( { key: 'show', label: showOptions.find( ( o ) => o.value === showValue( state.filter ) )?.label ?? '', remove: () => setFilter( { read: undefined, status: undefined } ) } ); } const week = figures && null !== figures.week ? change( figures.week, figures.previous ) : null; const toggleKpi = ( pressed: boolean, changes: Partial, period: Period, view = state.view ): void => { setFilter( pressed ? Object.fromEntries( Object.keys( changes ).map( ( k ) => [ k, undefined ] ) ) : { ...changes, archived: undefined }, period, view ); }; const frame = ( { 'free' === process.env.FUNNELFORMS_EDITION ? null : (
) } { config.exportUrl ? : null } } > { notice ? ( setNotice( null ) } /> }> { notice.text } ) : null } { api.entryFigures ? (
toggleKpi( 'today' === state.period && ! archive, {}, 'today' === state.period ? '' : 'today' ) } /> toggleKpi( false === state.filter.read && ! archive, { read: false, status: undefined }, state.period ) } /> 0 ? '+' : '' ) + num( week ) + ' %' ) } tone={ null === week || 0 === week ? '' : week > 0 ? 'up' : 'down' } pressed={ '7d' === state.period && ! archive } onClick={ () => toggleKpi( '7d' === state.period && ! archive, {}, '7d' === state.period ? '' : '7d' ) } /> { 'free' === process.env.FUNNELFORMS_EDITION || ! stages.some( ( s ) => 'won' === s.key ) ? null : ( 0 ? sprintf( __( '%s of the open entries', 'funnelforms-pro' ), ( Math.round( ( 1000 * ( figures.leads.won ?? 0 ) ) / figures.total ) / 10 ).toLocaleString() + ' %' ) : __( 'Mark leads as won in the table or on the board', 'funnelforms-pro' ) } pressed={ 'won' === state.filter.leadStatus && ! archive && ! board } onClick={ () => toggleKpi( 'won' === state.filter.leadStatus && ! archive && ! board, { leadStatus: 'won' }, state.period, 'list' ) } /> ) }
) : null }
( { value: String( f.id ), label: f.title || sprintf( __( 'Form #%d', 'funnelforms-pro' ), f.id ) } ) ) ] } onChange={ ( v ) => setFilter( { form: v ? Number( v ) : undefined } ) } /> { board || spam || 'free' === process.env.FUNNELFORMS_EDITION ? null : ( ( { value: s.key, label: s.name } ) ) ] } onChange={ ( v ) => setFilter( { leadStatus: ( v || undefined ) as LeadStatus | undefined } ) } /> ) } setFilter( {}, v as Period ) } /> { spam || 'free' === process.env.FUNNELFORMS_EDITION ? null : ( setFilter( { sort: ( v || undefined ) as EntryFilter[ 'sort' ] } ) } /> ) }
{ chips.length || filtered( state ) ? (
{ chips.map( ( c ) => ( { c.label } ) ) } { filtered( state ) ? ( ) : null }
) : null }
{ error ? (
void reload() }>{ __( 'Try again', 'funnelforms-pro' ) } }> { error }
) : null } { ! data && ! error ? : null } { data && 0 === entries.length && spam && ! filtered( state ) ? ( { __( 'Entries that look like spam land here instead of in your inbox. They send nothing and are deleted after the days set in the settings.', 'funnelforms-pro' ) } ) : null } { data && 0 === entries.length && ! ( spam && ! filtered( state ) ) ? ( filtered( state ) || archive ? ( { __( 'Clear filters', 'funnelforms-pro' ) } ) : undefined } > { archive && ! filtered( state ) ? __( 'Archived entries appear here.', 'funnelforms-pro' ) : __( 'Try other filters.', 'funnelforms-pro' ) } ) : ( { __( 'Go to your forms', 'funnelforms-pro' ) } ) : undefined } > { __( 'Entries of your forms appear here as soon as visitors send them.', 'funnelforms-pro' ) } ) ) : null } { data && entries.length && spam ? (

{ __( 'These entries sent no mail and ran no action. "Not spam" takes them back and sends what was held back.', 'funnelforms-pro' ) }

) : null } { data && entries.length && ! board ? : null } { data && entries.length && board ? (
void act( () => api.updateEntry( id, { leadStatus } ) ) } date={ date } editable={ canEditStages && ! busy } onEditStage={ ( key ) => setStageEdit( key ) } onAddStage={ () => setStageEdit( ADD_STAGE ) } onMoveStage={ moveColumn } /> { data.total > entries.length ?

{ sprintf( __( 'The board shows the newest %1$d of %2$d entries. Narrow the filters or use the table for the others.', 'funnelforms-pro' ), entries.length, data.total ) }

: null }
) : null } { data && entries.length ? (
{ sprintf( __( '%d entries', 'funnelforms-pro' ), num( data.total ) ) } { ! board && data.pages > 1 ? ( ) : null }
) : null }
{ selected.length ? void bulk( c, done ) } onClear={ () => setSelected( [] ) } /> : null } { null !== stageEdit ? ( s.key === stageEdit ) ?? null } busy={ busy } onClose={ () => setStageEdit( null ) } onSave={ async ( next, done, moveTo ) => { const problem = await saveStages( next, done, moveTo ); if ( null === problem ) { setStageEdit( null ); } return problem; } } /> ) : null } { null !== state.entry ? ( open( null ) } onChanged={ () => { void reload(); void loadLists(); void loadFigures(); } } onDeleted={ () => { open( null ); setNotice( { tone: 'success', text: __( 'Entry deleted.', 'funnelforms-pro' ) } ); void reload(); void loadFigures(); } } /> ) : null } ); return { frame }; } export function deviceName( device: EntryDevice ): string { return { desktop: __( 'Desktop', 'funnelforms-pro' ), tablet: __( 'Tablet', 'funnelforms-pro' ), mobile: __( 'Mobile', 'funnelforms-pro' ) }[ device ]; } /** A duration as people read it: 45 s, 3 min 05 s, 1 h 02 min. */ export function duration( seconds: number ): string { const s = Math.max( 0, Math.round( seconds ) ); if ( s < 60 ) { return sprintf( __( '%d s', 'funnelforms-pro' ), s ); } if ( s < 3600 ) { return sprintf( __( '%1$d min %2$s s', 'funnelforms-pro' ), Math.floor( s / 60 ), String( s % 60 ).padStart( 2, '0' ) ); } return sprintf( __( '%1$d h %2$s min', 'funnelforms-pro' ), Math.floor( s / 3600 ), String( Math.floor( ( s % 3600 ) / 60 ) ).padStart( 2, '0' ) ); } /** * Whether an address a visitor's browser sent may be a link: only web addresses. The plugin * keeps no others now, but entries imported from 3.x or saved earlier may hold anything. */ function webAddress( url: string ): boolean { return /^https?:\/\/[^/\s]/i.test( url.trim() ); } /** EntryDevice, browser, where the visitor came from and the time per step, longest step marked. */ function VisitSection( { visit }: { visit: EntryVisit } ) { const longest = Math.max( 0, ...visit.steps.map( ( s ) => s.seconds ) ); return (
{ visit.device ? { deviceName( visit.device ) } : null } { visit.browser ? { [ visit.browser, visit.os ].filter( Boolean ).join( ', ' ) } : null } { null !== visit.seconds ? { duration( visit.seconds ) } : null } { visit.referrer ? ( { webAddress( visit.referrer ) ? ( { visit.referrer.replace( /^https?:\/\//, '' ) } ) : ( visit.referrer ) } ) : null }
{ visit.steps.length ? ( { visit.steps.map( ( step ) => ( 0 && step.seconds === longest ? 'is-longest' : undefined }> ) ) }
{ __( 'Time per step', 'funnelforms-pro' ) }
{ step.title || step.node } { duration( step.seconds ) }
) : null }
); } /** A filter of the bar: a select that names itself and stands out while it filters. */ function BarSelect( { label, value, options, onChange }: { label: string; value: string; options: Array<{ value: string; label: string }>; onChange: ( value: string ) => void } ) { return ( ); } function FilterSelect( { label, value, options, onChange }: { label: string; value: string; options: Array<{ value: string; label: string }>; onChange: ( value: string ) => void } ) { return ( ); } function ExportMenu( { base, filter }: { base: string; filter: EntryFilter } ) { const menu = useRef( null ); // Closes when a click or Escape lands elsewhere. useEffect( () => { const close = ( e: Event ): void => { const details = menu.current; if ( details?.open && ( ( e instanceof KeyboardEvent && 'Escape' === e.key ) || ( ! ( e instanceof KeyboardEvent ) && ! details.contains( e.target as Node ) ) ) ) { details.open = false; } }; document.addEventListener( 'click', close ); document.addEventListener( 'keydown', close ); return () => { document.removeEventListener( 'click', close ); document.removeEventListener( 'keydown', close ); }; }, [] ); return (
{ __( 'Export', 'funnelforms-pro' ) }
{ __( 'CSV file', 'funnelforms-pro' ) } { 'free' === process.env.FUNNELFORMS_EDITION ? null : ( { __( 'For Excel', 'funnelforms-pro' ) } ) }

{ __( 'Exports the entries of the current filters, without search and period.', 'funnelforms-pro' ) }

); } function Tags( { tags, max = 3 }: { tags: string[]; max?: number } ) { if ( ! tags.length ) { return null; } return ( { tags.slice( 0, max ).map( ( t ) => ( { t } ) ) } { tags.length > max ? ( { '+' + ( tags.length - max ) } ) : null } ); } function Assignee( { user }: { user: UserRef | null } ) { return user ? ( { user.name } ) : ( – ); } function EntryTable( props: { entries: EntrySummary[]; selected: number[]; onSelect: ( ids: number[] ) => void; onOpen: ( id: number ) => void; date: Dates; busy: boolean; showForm: boolean; current: number | null } ) { const { entries, selected } = props; const all = entries.length > 0 && entries.every( ( e ) => selected.includes( e.id ) ); const some = ! all && entries.some( ( e ) => selected.includes( e.id ) ); const toggle = ( id: number ): void => props.onSelect( selected.includes( id ) ? selected.filter( ( s ) => s !== id ) : [ ...selected, id ] ); const head = useRef( null ); useEffect( () => { if ( head.current ) { head.current.indeterminate = some; } }, [ some ] ); return (
{ props.showForm ? : null } { 'free' === process.env.FUNNELFORMS_EDITION ? null : ( <> ) } { entries.map( ( entry ) => { const email = entryEmail( entry ); const name = title( entry ); const named = '' !== entryName( entry ); const sub = email && email !== name ? email : entryPhone( entry ); const classes = [ entry.read ? '' : 'is-unread', selected.includes( entry.id ) ? 'is-selected' : '', props.current === entry.id ? 'is-current' : '' ].filter( Boolean ).join( ' ' ); return ( { // The whole row opens the entry; its controls keep their own clicks. if ( ! ( e.target as HTMLElement ).closest( 'button, a, input, select, label' ) ) { props.onOpen( entry.id ); } } } > { props.showForm ? : null } { 'free' === process.env.FUNNELFORMS_EDITION ? null : ( <> ) } ); } ) }
props.onSelect( all ? [] : entries.map( ( e ) => e.id ) ) } /> { __( 'Contact', 'funnelforms-pro' ) }{ __( 'Form', 'funnelforms-pro' ) }{ __( 'Received', 'funnelforms-pro' ) }{ __( 'Lead status', 'funnelforms-pro' ) } { __( 'Tags', 'funnelforms-pro' ) } { __( 'Assigned to', 'funnelforms-pro' ) }
toggle( entry.id ) } /> { sub ? { sub } : null } { 'partial' === entry.status ? { __( 'Incomplete', 'funnelforms-pro' ) } : null } { abandonBadge( entry ) } { entry.payment ? { paymentName( entry.payment.status ) } : null } { null !== entry.score ? { sprintf( __( 'Score %s', 'funnelforms-pro' ), String( entry.score ) ) } : null } { entry.form?.title ?? '–' }
); } /** Stands for a stage being added in the stage dialog; keys have no colon. */ const ADD_STAGE = ':add'; /** What the board drags: an entry to another column, or a column to another place. */ const STAGE_DRAG = 'application/x-funnelforms-stage'; function Board( props: { entries: EntrySummary[]; onOpen: ( id: number ) => void; onMove: ( id: number, status: LeadStatus ) => void; date: Dates; /** The columns can be renamed, added, moved and deleted. */ editable?: boolean; onEditStage?: ( key: LeadStatus ) => void; onAddStage?: () => void; onMoveStage?: ( key: LeadStatus, to: number ) => void; } ) { const { entries, onOpen, onMove, date, editable = false } = props; const stages = useContext( StagesContext ); const columns = byLeadStatus( entries, stages.map( ( s ) => s.key ) ); const [ over, setOver ] = useState( null ); // The column being dragged by its title. const dragged = useRef( null ); return (
{ stages.map( ( stage, index ) => { const list = columns[ stage.key ] ?? []; return (
{ e.preventDefault(); setOver( stage.key ); } } onDragLeave={ () => setOver( null ) } onDrop={ ( e ) => { e.preventDefault(); setOver( null ); const column = dragged.current ?? e.dataTransfer.getData( STAGE_DRAG ); dragged.current = null; if ( column ) { if ( column !== stage.key ) { props.onMoveStage?.( column, index ); } return; } const id = Number( e.dataTransfer.getData( 'text/plain' ) ); const entry = entries.find( ( x ) => x.id === id ); if ( entry && entry.leadStatus !== stage.key ) { onMove( id, stage.key ); } } } >
{ dragged.current = stage.key; e.dataTransfer.setData( STAGE_DRAG, stage.key ); e.dataTransfer.effectAllowed = 'move'; } : undefined } onDragEnd={ () => ( dragged.current = null ) } >

{ editable ? ( ) : null }
{ list.length ? null :

{ __( 'Drag entries here', 'funnelforms-pro' ) }

} { list.map( ( entry ) => { const name = title( entry ); const email = entryEmail( entry ); const phone = entryPhone( entry ); const reach = email && email !== name ? email : phone; return (
e.dataTransfer.setData( 'text/plain', String( entry.id ) ) } onClick={ ( e ) => { // The whole card opens the entry, where the lead status can also be set without dragging. if ( ! ( e.target as HTMLElement ).closest( 'button, a' ) ) { onOpen( entry.id ); } } } >
{ reach ?

{ reach }

: null } { entry.form?.title ?

{ entry.form.title }

: null } { entry.tags.length ? : null } { email || phone || entry.assignedTo ? (
{ email ? ( ) : null } { phone ? ( ) : null } { entry.assignedTo ? ( ) : null }
) : null }
); } ) }
); } ) } { editable && stages.length < MAX_STAGES ? ( ) : null }
); } /** * What a board card says about a lead besides its name: incomplete or abandoned, the payment, the * score and the lead value. The column is the lead status, so the card does not repeat it. */ function CardBadges( { entry }: { entry: EntrySummary } ) { // Empty without any of them (hidden in CSS). return (
{ 'partial' === entry.status ? { __( 'Incomplete', 'funnelforms-pro' ) } : null } { abandonBadge( entry ) } { entry.payment ? { paymentName( entry.payment.status ) } : null } { null !== entry.score ? { sprintf( __( 'Score %s', 'funnelforms-pro' ), String( entry.score ) ) } : null }
); } /** The stages as options of a select; a stage the board no longer has stays choosable as it is. */ function StageOptions( { current }: { current?: LeadStatus } ) { const stages = useContext( StagesContext ); return ( <> { stages.map( ( s ) => ( ) ) } { current && ! stages.some( ( s ) => s.key === current ) ? : null } ); } /** * Edits one stage of the board, or adds one (stage null): its name, its colour, its place, and * deleting it, which asks where its entries go. The whole list is saved at once. */ function StageDialog( props: { stages: LeadStage[]; stage: LeadStage | null; busy: boolean; onClose: () => void; onSave: ( next: LeadStage[], done: string, moveTo?: Record ) => Promise } ) { const { stages, stage } = props; const [ name, setName ] = useState( stage?.name ?? '' ); const [ tone, setTone ] = useState( stage?.tone ?? ( STAGE_TONES.find( ( t ) => ! stages.some( ( s ) => s.tone === t ) ) ?? 'neutral' ) ); const [ index, setIndex ] = useState( () => ( stage ? stages.findIndex( ( s ) => s.key === stage.key ) : stages.length ) ); const [ deleting, setDeleting ] = useState( false ); const others = stages.filter( ( s ) => s.key !== stage?.key ); const [ target, setTarget ] = useState( () => ( others.find( ( s ) => 'new' === s.key ) ?? others[ 0 ] )?.key ?? '' ); const [ touched, setTouched ] = useState( false ); const [ error, setError ] = useState( null ); const problem = stageNameProblem( name, others.map( ( s ) => s.name ) ); const problemText = { '': '', empty: __( 'Give the stage a name.', 'funnelforms-pro' ), long: sprintf( /* translators: %d: most characters of a name */ __( 'At most %d characters.', 'funnelforms-pro' ), MAX_STAGE_NAME ), taken: __( 'Another stage has this name.', 'funnelforms-pro' ) }[ problem ]; const count = stage?.entries ?? 0; const total = stage ? stages.length : stages.length + 1; const save = async (): Promise => { setTouched( true ); if ( problem ) { return; } const own: LeadStage = { ...( stage ?? { key: '' } ), name: name.trim(), tone }; const rest = stages.filter( ( s ) => s.key !== stage?.key ); rest.splice( Math.min( index, rest.length ), 0, own ); setError( await props.onSave( rest, stage ? sprintf( /* translators: %s: name of the lead stage */ __( 'Stage “%s” saved.', 'funnelforms-pro' ), own.name ) : sprintf( /* translators: %s: name of the lead stage */ __( 'Stage “%s” added.', 'funnelforms-pro' ), own.name ) ) ); }; const remove = async (): Promise => { if ( ! stage ) { return; } setError( await props.onSave( others, count ? sprintf( /* translators: 1: deleted lead stage, 2: lead stage that took its entries */ __( 'Stage “%1$s” deleted; its entries are now in “%2$s”.', 'funnelforms-pro' ), stage.name, leadStatusName( target, stages ) ) : sprintf( /* translators: %s: name of the lead stage */ __( 'Stage “%s” deleted.', 'funnelforms-pro' ), stage.name ), { [ stage.key ]: target } ) ); }; return ( ) : ( <> ) } >
{ error ? { error } : null } { deleting && stage ? (

{ count ? sprintf( 1 === count ? /* translators: %s: name of the lead stage */ __( '1 entry is in “%s”. Where should it go?', 'funnelforms-pro' ) : /* translators: 1: name of the lead stage, 2: number of entries */ __( '%2$d entries are in “%1$s”. Where should they go?', 'funnelforms-pro' ), stage.name, count ) : sprintf( /* translators: %s: name of the lead stage */ __( 'No entries are in “%s”. The stage goes for everyone who works with the entries.', 'funnelforms-pro' ), stage.name ) }

{ count ? ( ) : null }
) : ( <>
setName( e.target.value ) } onBlur={ () => setTouched( true ) } onKeyDown={ ( e ) => { if ( 'Enter' === e.key ) { e.preventDefault(); void save(); } } } /> { touched && problem ? ( { problemText } ) : null }
{ __( 'Colour', 'funnelforms-pro' ) }
{ STAGE_TONES.map( ( t ) => ( ) ) }
{ __( 'Place on the board', 'funnelforms-pro' ) }
{ sprintf( /* translators: 1: place of the stage on the board, 2: number of stages */ __( 'Column %1$d of %2$d', 'funnelforms-pro' ), Math.min( index, total - 1 ) + 1, total ) }
{ stage ? (
{ stage.locked ? (

{ __( 'New entries arrive in this stage, so it stays. Rename it as you like.', 'funnelforms-pro' ) }

) : ( ) }
) : (

{ __( 'The stage is added for everyone who works with the entries.', 'funnelforms-pro' ) }

) } ) }
); } function BulkBar( props: { count: number; archive: boolean; spam?: boolean; assignees: UserRef[]; busy: boolean; canDelete: boolean; onApply: ( changes: BulkChanges, done: string ) => void; onClear: () => void } ) { const [ tagText, setTagText ] = useState( '' ); const [ confirm, setConfirm ] = useState( false ); const { count } = props; const stages = useContext( StagesContext ); return (
{ sprintf( __( '%d selected', 'funnelforms-pro' ), count ) }
); } function EntryPanel( props: { api: EntriesApi; id: number; assignees: UserRef[]; user?: { id: number; admin: boolean }; canDelete?: boolean; date: Dates; onClose: () => void; onChanged: () => void; onDeleted: () => void } ) { const { api, id, date } = props; const [ entry, setEntry ] = useState( null ); const [ error, setError ] = useState( null ); const [ notice, setNotice ] = useState<{ tone: 'success' | 'danger'; text: string } | null>( null ); const [ busy, setBusy ] = useState( false ); const [ note, setNote ] = useState( '' ); const [ tagText, setTagText ] = useState( '' ); const [ confirm, setConfirm ] = useState( false ); const panel = useRef( null ); // The look at the status of an action run again, a few seconds later. const later = useRef( undefined ); useEffect( () => () => window.clearTimeout( later.current ), [] ); const { onChanged } = props; const load = useCallback( async (): Promise => { try { let detail = await api.entry( id ); if ( ! detail.read ) { // Opening an entry marks it as read. detail = { ...detail, ...( await api.updateEntry( id, { read: true } ) ) }; onChanged(); } setEntry( detail ); } catch ( e ) { setError( message( e ) ); } }, [ api, id, onChanged ] ); useEffect( () => { void load(); }, [ id ] ); useEffect( () => { panel.current?.focus(); const onKey = ( e: KeyboardEvent ): void => { if ( 'Escape' === e.key && ! document.querySelector( 'dialog[open]' ) ) { props.onClose(); } }; document.addEventListener( 'keydown', onKey ); return () => document.removeEventListener( 'keydown', onKey ); }, [] ); const run = async ( work: () => Promise, done?: string, refresh = true ): Promise => { setBusy( true ); setNotice( null ); try { await work(); if ( done ) { setNotice( { tone: 'success', text: done } ); } if ( refresh ) { setEntry( await api.entry( id ) ); props.onChanged(); } return true; } catch ( e ) { setNotice( { tone: 'danger', text: message( e ) } ); return false; } finally { setBusy( false ); } }; const files = ( ids: number[] | undefined ) => ( entry?.files ?? [] ).filter( ( f ) => ids?.includes( f.id ) ); const email = entry ? entryEmail( entry ) : ''; const phone = entry ? entryPhone( entry ) : ''; return ( <>