/** * Subscribers / Contacts list - paginated table with bulk operations. */ import { useState, useEffect, useCallback } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; import { Button, SelectControl, SearchControl, CheckboxControl } from '@aime/wp-components'; import useApi from '../../../hooks/useApi'; import Card from '../../common/Card'; import Loader from '../../common/Loader'; import Notice from '../../common/Notice'; import CsvImportModal from '../../common/CsvImportModal'; const STATUS_OPTIONS = [ { label: __( 'All Statuses', 'ai-marketing-expert' ), value: '' }, { label: __( 'Subscribed', 'ai-marketing-expert' ), value: 'subscribed' }, { label: __( 'Unsubscribed', 'ai-marketing-expert' ), value: 'unsubscribed' }, { label: __( 'Pending', 'ai-marketing-expert' ), value: 'pending' }, { label: __( 'Bounced', 'ai-marketing-expert' ), value: 'bounced' }, { label: __( 'Complained', 'ai-marketing-expert' ), value: 'complained' }, ]; const STATUS_BADGES = { subscribed: 'aime-badge-success', unsubscribed: 'aime-badge-error', pending: 'aime-badge-warning', bounced: 'aime-badge-error', complained: 'aime-badge-error', }; const DEFAULT_VALIDATION = { skip_invalid_format: true, skip_disposable: true, skip_test_fake: true, skip_role_based: false, skip_spam_patterns: true, check_mx: false, }; const Subscribers = ( { onNavigate } ) => { const { get, post, del, loading, error, clearError } = useApi(); const [ items, setItems ] = useState( [] ); const [ total, setTotal ] = useState( 0 ); const [ page, setPage ] = useState( 1 ); const [ perPage ] = useState( 20 ); const [ search, setSearch ] = useState( '' ); const [ status, setStatus ] = useState( '' ); const [ audienceFilter, setAudienceFilter ] = useState( '' ); // "list:3" | "tag:5" | "" const [ selected, setSelected ] = useState( [] ); const [ allMatchingSelected, setAllMatchingSelected ] = useState( false ); const [ notice, setNotice ] = useState( null ); const [ showAddModal, setShowAddModal ] = useState( false ); const [ newContact, setNewContact ] = useState( { email: '', first_name: '', last_name: '', status: 'subscribed', phone: '', list_ids: [], tag_ids: [] } ); const [ tags, setTags ] = useState( [] ); const [ lists, setLists ] = useState( [] ); const [ showBulkModal, setShowBulkModal ] = useState( null ); const [ bulkTagIds, setBulkTagIds ] = useState( [] ); const [ bulkListIds, setBulkListIds ] = useState( [] ); const [ showExportModal, setShowExportModal ] = useState( false ); const [ exportMode, setExportMode ] = useState( 'all' ); const [ exportListId, setExportListId ] = useState( '' ); const [ exportTagId, setExportTagId ] = useState( '' ); const [ exporting, setExporting ] = useState( false ); /* Import modal */ const [ showImportModal, setShowImportModal ] = useState( false ); const [ importSource, setImportSource ] = useState( '' ); const [ showCsvModal, setShowCsvModal ] = useState( false ); const [ importValidation, setImportValidation ] = useState( DEFAULT_VALIDATION ); const [ importDoubleOptin, setImportDoubleOptin ] = useState( false ); const [ importListIds, setImportListIds ] = useState( [] ); const [ importTagIds, setImportTagIds ] = useState( [] ); const [ importUpdateExisting, setImportUpdateExisting ] = useState( false ); const [ importNewStatus, setImportNewStatus ] = useState( 'subscribed' ); const updateImportValidation = ( key, value ) => { setImportValidation( ( prev ) => ( { ...prev, [ key ]: value } ) ); }; const importValidationForRequest = () => importValidation; const resetImportOptions = () => { setImportSource( '' ); setImportDoubleOptin( false ); setImportListIds( [] ); setImportTagIds( [] ); setImportUpdateExisting( false ); setImportNewStatus( 'subscribed' ); }; const fetchItems = useCallback( async () => { try { const params = { page, per_page: perPage, search, status }; if ( audienceFilter ) { const [ type, id ] = audienceFilter.split( ':' ); if ( type === 'list' ) params.list_id = id; else if ( type === 'tag' ) params.tag_id = id; } const res = await get( '/email/subscribers', params ); setItems( res.items || [] ); setTotal( res.total || 0 ); } catch ( e ) { /* useApi sets error */ } }, [ get, page, perPage, search, status, audienceFilter ] ); const fetchMeta = useCallback( async () => { try { const [ t, l ] = await Promise.all( [ get( '/email/tags' ), get( '/email/lists' ), ] ); setTags( t || [] ); setLists( l || [] ); } catch ( e ) { /* */ } }, [ get ] ); useEffect( () => { fetchItems(); }, [ fetchItems ] ); useEffect( () => { fetchMeta(); }, [ fetchMeta ] ); const handleAdd = async () => { try { await post( '/email/subscribers', newContact ); setShowAddModal( false ); setNewContact( { email: '', first_name: '', last_name: '', status: 'subscribed', phone: '', list_ids: [], tag_ids: [] } ); setNotice( { type: 'success', message: __( 'Contact added.', 'ai-marketing-expert' ) } ); fetchItems(); } catch ( e ) { setNotice( { type: 'error', message: e.message } ); } }; const handleBulk = async ( action, extras = {} ) => { if ( ! selected.length && ! allMatchingSelected ) return; const count = allMatchingSelected ? total : selected.length; if ( action === 'delete' && ! window.confirm( sprintf( __( 'Delete %d selected contact(s)? This cannot be undone.', 'ai-marketing-expert' ), count ) ) ) { return; } try { const payload = allMatchingSelected ? (() => { const base = { action, all_matching: true, search, status }; if ( audienceFilter ) { const [ type, id ] = audienceFilter.split( ':' ); if ( type === 'list' ) base.list_id = id; else if ( type === 'tag' ) base.tag_id = id; } return { ...base, ...extras }; } )() : { action, ids: selected, ...extras }; const res = await post( '/email/subscribers/bulk', payload ); setSelected( [] ); setAllMatchingSelected( false ); setNotice( { type: 'success', message: res?.message || __( 'Bulk action completed.', 'ai-marketing-expert' ) } ); fetchItems(); } catch ( e ) { setNotice( { type: 'error', message: e.message } ); } }; const handleDelete = async ( id ) => { if ( ! window.confirm( __( 'Delete this contact?', 'ai-marketing-expert' ) ) ) return; try { await del( `/email/subscribers/${ id }` ); setNotice( { type: 'success', message: __( 'Contact deleted.', 'ai-marketing-expert' ) } ); fetchItems(); } catch ( e ) { setNotice( { type: 'error', message: e.message } ); } }; const handleImport = ( res ) => { setShowImportModal( false ); setShowCsvModal( false ); resetImportOptions(); const parts = [ `${ __( 'Imported:', 'ai-marketing-expert' ) } ${ res.imported || 0 }` ]; if ( res.updated ) parts.push( `${ __( 'Updated:', 'ai-marketing-expert' ) } ${ res.updated }` ); parts.push( `${ __( 'Skipped:', 'ai-marketing-expert' ) } ${ res.skipped || 0 }` ); setNotice( { type: 'success', message: `${ __( 'Import complete!', 'ai-marketing-expert' ) } ${ parts.join( ', ' ) }` } ); fetchItems(); }; const handleSourceImport = async () => { if ( importSource === 'csv' ) { setShowImportModal( false ); setShowCsvModal( true ); return; } try { const res = await post( '/email/subscribers/import', { source: importSource, double_optin: importDoubleOptin, validation: importValidationForRequest(), list_ids: importListIds, tag_ids: importTagIds, update_existing: importUpdateExisting, new_status: importNewStatus, } ); handleImport( res ); } catch ( e ) { if ( importValidation.check_mx ) { clearError(); setShowImportModal( false ); resetImportOptions(); await fetchItems(); setNotice( { type: 'warning', message: __( 'The import request took longer than the browser expected while checking MX records. Contacts were refreshed; please review the list before importing again.', 'ai-marketing-expert' ), } ); return; } setNotice( { type: 'error', message: e.message || __( 'Import failed.', 'ai-marketing-expert' ) } ); } }; const csvValue = ( value ) => { const text = value === null || value === undefined ? '' : String( value ); return /[",\n\r]/.test( text ) ? `"${ text.replace( /"/g, '""' ) }"` : text; }; const handleExport = async () => { const params = { per_page: 99999 }; let suffix = 'all'; if ( exportMode === 'list' ) { if ( ! exportListId ) return; params.list_id = exportListId; suffix = `list-${ exportListId }`; } if ( exportMode === 'tag' ) { if ( ! exportTagId ) return; params.tag_id = exportTagId; suffix = `tag-${ exportTagId }`; } setExporting( true ); try { const res = await get( '/email/subscribers', params ); const rows = ( res.items || [] ).map( ( sub ) => [ sub.email, sub.first_name, sub.last_name, sub.phone, sub.status, ( sub.lists || [] ).map( ( list ) => ( typeof list === 'string' ? list : ( list?.title || list?.name || '' ) ) ).filter( Boolean ).join( '; ' ), ( sub.tags || [] ).map( ( tag ) => ( typeof tag === 'string' ? tag : ( tag?.title || tag?.name || '' ) ) ).filter( Boolean ).join( '; ' ), sub.created_at, ].map( csvValue ).join( ',' ) ); const csv = [ 'email,first_name,last_name,phone,status,lists,tags,created_at', ...rows ].join( '\n' ); const blob = new Blob( [ csv ], { type: 'text/csv;charset=utf-8' } ); const url = URL.createObjectURL( blob ); const a = document.createElement( 'a' ); a.href = url; a.download = `subscribers-${ suffix }-${ new Date().toISOString().slice( 0, 10 ) }.csv`; a.click(); URL.revokeObjectURL( url ); setShowExportModal( false ); setNotice( { type: 'success', message: sprintf( __( 'Exported %d contact(s).', 'ai-marketing-expert' ), rows.length ) } ); } catch ( e ) { setNotice( { type: 'error', message: e.message } ); } setExporting( false ); }; const toggleAll = () => { if ( selected.length === items.length ) { setSelected( [] ); setAllMatchingSelected( false ); } else { setSelected( items.map( ( i ) => i.id ) ); setAllMatchingSelected( false ); } }; const toggleOne = ( id ) => { setAllMatchingSelected( false ); setSelected( ( prev ) => prev.includes( id ) ? prev.filter( ( x ) => x !== id ) : [ ...prev, id ] ); }; const totalPages = Math.ceil( total / perPage ); const resetFiltersAndReload = ( updater ) => ( v ) => { updater( v ); setPage( 1 ); setSelected( [] ); setAllMatchingSelected( false ); }; const audienceFilterOptions = [ { label: __( 'All Contacts', 'ai-marketing-expert' ), value: '' }, ...( lists.length > 0 ? [ { label: __( 'Lists', 'ai-marketing-expert' ), disabled: true } ] : [] ), ...lists.map( ( l ) => ( { label: `\u00A0\u00A0${ l.title || l.name || `List #${ l.id }` }`, value: `list:${ l.id }` } ) ), ...( tags.length > 0 ? [ { label: __( 'Tags', 'ai-marketing-expert' ), disabled: true } ] : [] ), ...tags.map( ( t ) => ( { label: `\u00A0\u00A0${ t.title || t.name || `Tag #${ t.id }` }`, value: `tag:${ t.id }` } ) ), ]; return (
|
|
{ __( 'Contact', 'ai-marketing-expert' ) } | { __( 'Status', 'ai-marketing-expert' ) } | { __( 'Tags', 'ai-marketing-expert' ) } | { __( 'Lists', 'ai-marketing-expert' ) } | { __( 'Created', 'ai-marketing-expert' ) } | { __( 'Actions', 'ai-marketing-expert' ) } |
|---|---|---|---|---|---|---|
| { __( 'No contacts found.', 'ai-marketing-expert' ) } | ||||||
|
|
{ sub.status } | { ( sub.tags || [] ).map( ( t ) => { const label = typeof t === 'string' ? t : ( t?.title || t?.name || '' ); if ( ! label ) return null; return ( { label } ); } ) } | { ( sub.lists || [] ).map( ( l ) => { const label = typeof l === 'string' ? l : ( l?.title || l?.name || '' ); if ( ! label ) return null; return ( { label } ); } ) } | { sub.created_at ? sub.created_at.split( ' ' )[ 0 ] : '\u2014' } | ||