/**
* ImportExport - CSV / WP Users / WooCommerce import, CSV export.
*/
import { useState, useEffect, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Button, SelectControl, CheckboxControl, Spinner } from '@aime/wp-components';
import useApi from '../../../hooks/useApi';
import Card from '../../common/Card';
import Notice from '../../common/Notice';
import CsvImportModal from '../../common/CsvImportModal';
const SOURCE_OPTIONS = [
{ label: __( 'CSV', 'ai-marketing-expert' ), value: 'csv' },
{ label: __( 'WordPress Users', 'ai-marketing-expert' ), value: 'wp_users' },
{ label: __( 'WooCommerce Customers', 'ai-marketing-expert' ), value: 'woocommerce' },
];
const IMPORT_STATUS_OPTIONS = [
{ 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 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 SKIP_REASON_LABELS = {
invalid_email: __( 'Invalid format', 'ai-marketing-expert' ),
blocked_domain: __( 'Blocked/test domain', 'ai-marketing-expert' ),
blocked_tld: __( 'Blocked test TLD', 'ai-marketing-expert' ),
blocked_prefix: __( 'Fake/test address', 'ai-marketing-expert' ),
disposable_email: __( 'Disposable/temp email', 'ai-marketing-expert' ),
role_based_email: __( 'Role-based email', 'ai-marketing-expert' ),
spam_pattern: __( 'Spam pattern', 'ai-marketing-expert' ),
gmail_dot_variant: __( 'Gmail dot variant', 'ai-marketing-expert' ),
no_mx_record: __( 'No mail server', 'ai-marketing-expert' ),
duplicate: __( 'Duplicate', 'ai-marketing-expert' ),
no_tld: __( 'No valid TLD', 'ai-marketing-expert' ),
};
const ImportExport = () => {
const { post, get, loading, error, clearError } = useApi();
const [ source, setSource ] = useState( 'csv' );
const [ doubleOptin, setDoubleOptin ] = useState( false );
const [ result, setResult ] = useState( null );
const [ showCsvModal, setShowCsvModal ] = useState( false );
const [ showValidationModal, setShowValidationModal ] = useState( false );
const [ lists, setLists ] = useState( [] );
const [ tags, setTags ] = useState( [] );
const [ validation, setValidation ] = useState( DEFAULT_VALIDATION );
const [ selectedLists, setSelectedLists ] = useState( [] );
const [ selectedTags, setSelectedTags ] = useState( [] );
const [ updateExisting, setUpdateExisting ] = useState( false );
const [ newStatus, setNewStatus ] = useState( 'subscribed' );
const updateValidation = ( key, value ) => {
setValidation( ( prev ) => ( { ...prev, [ key ]: value } ) );
};
const validationForRequest = () => validation;
const renderSkipReasons = () => {
const reasons = Object.entries( result?.skip_reasons || {} ).filter( ( [ , count ] ) => count > 0 );
if ( reasons.length === 0 ) return null;
return (
{ __( 'Skipped breakdown:', 'ai-marketing-expert' ) }
{ reasons.map( ( [ reason, count ] ) => (
{ SKIP_REASON_LABELS[ reason ] || reason }: { count }
) ) }
);
};
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( () => { fetchMeta(); }, [ fetchMeta ] );
const runImport = async () => {
setResult( null );
try {
const payload = {
source,
double_optin: doubleOptin,
validation: validationForRequest(),
list_ids: selectedLists,
tag_ids: selectedTags,
update_existing: updateExisting,
new_status: newStatus,
};
const res = await post( '/email/subscribers/import', payload );
setShowValidationModal( false );
setResult( res );
} catch ( e ) { /* */ }
};
const handleImport = async () => {
setResult( null );
if ( source === 'csv' ) {
setShowCsvModal( true );
return;
}
setShowValidationModal( true );
};
const handleExport = async () => {
try {
const res = await get( '/email/subscribers?per_page=99999' );
const rows = ( res.items || [] ).map( ( s ) =>
[ s.email, s.first_name, s.last_name, s.status ].join( ',' )
);
const csv = [ 'email,first_name,last_name,status', ...rows ].join( '\n' );
const blob = new Blob( [ csv ], { type: 'text/csv' } );
const url = URL.createObjectURL( blob );
const a = document.createElement( 'a' );
a.href = url;
a.download = `subscribers-${ new Date().toISOString().slice( 0, 10 ) }.csv`;
a.click();
URL.revokeObjectURL( url );
} catch ( e ) { /* */ }
};
return (
{ error &&
}
{ result && (
<>
setResult( null ) } />
{ renderSkipReasons() }
>
) }
{ __( 'Validation & Cleanup', 'ai-marketing-expert' ) }
updateValidation( 'skip_invalid_format', v ) } />
updateValidation( 'skip_disposable', v ) } />
updateValidation( 'skip_test_fake', v ) } />
updateValidation( 'skip_role_based', v ) } />
updateValidation( 'skip_spam_patterns', v ) } />
updateValidation( 'check_mx', v ) } />
{ source === 'wp_users' && (
{ __( 'All WordPress users will be imported as subscribers.', 'ai-marketing-expert' ) }
) }
{ source === 'woocommerce' && (
{ __( 'All WooCommerce customers will be imported as subscribers.', 'ai-marketing-expert' ) }
) }
{ source !== 'csv' && (
<>
{ __( 'Lists', 'ai-marketing-expert' ) }
{ lists.map( ( list ) => {
const isSelected = selectedLists.includes( list.id );
return setSelectedLists( isSelected ? selectedLists.filter( ( id ) => id !== list.id ) : [ ...selectedLists, list.id ] ) }>{ list.title } ;
} ) }
{ lists.length === 0 && { __( 'No lists available.', 'ai-marketing-expert' ) } }
{ __( 'Tags', 'ai-marketing-expert' ) }
{ tags.map( ( tag ) => {
const isSelected = selectedTags.includes( tag.id );
return setSelectedTags( isSelected ? selectedTags.filter( ( id ) => id !== tag.id ) : [ ...selectedTags, tag.id ] ) }>{ tag.color && }{ tag.title } ;
} ) }
{ tags.length === 0 && { __( 'No tags available.', 'ai-marketing-expert' ) } }
>
) }
{ source !== 'csv' && (
) }
{ loading
? <> { __( 'Importing...', 'ai-marketing-expert' ) }>
: source === 'csv' ? __( 'Upload CSV & Import', 'ai-marketing-expert' ) : __( 'Import', 'ai-marketing-expert' )
}
{ __( 'Download all subscribers as a CSV file.', 'ai-marketing-expert' ) }
{ loading
? <> { __( 'Exporting...', 'ai-marketing-expert' ) }>
: __( 'Download CSV', 'ai-marketing-expert' )
}
{ showCsvModal && (
setShowCsvModal( false ) }
onImported={ ( res ) => {
setShowCsvModal( false );
setResult( res );
} }
/>
) }
{ showValidationModal && (
{ if ( e.target === e.currentTarget ) setShowValidationModal( false ); } }>
e.stopPropagation() }>
{ __( 'Review Import Validation', 'ai-marketing-expert' ) }
setShowValidationModal( false ) }>×
{ source === 'wp_users'
? __( 'WordPress users will be validated with these cleanup rules before they are imported as subscribers.', 'ai-marketing-expert' )
: __( 'WooCommerce customers will be validated with these cleanup rules before they are imported as subscribers.', 'ai-marketing-expert' )
}
{ __( 'Validation & Cleanup', 'ai-marketing-expert' ) }
updateValidation( 'skip_invalid_format', v ) } />
updateValidation( 'skip_disposable', v ) } />
updateValidation( 'skip_test_fake', v ) } />
updateValidation( 'skip_role_based', v ) } />
updateValidation( 'skip_spam_patterns', v ) } />
updateValidation( 'check_mx', v ) } />
{ __( 'Lists', 'ai-marketing-expert' ) }
{ lists.map( ( list ) => {
const isSelected = selectedLists.includes( list.id );
return setSelectedLists( isSelected ? selectedLists.filter( ( id ) => id !== list.id ) : [ ...selectedLists, list.id ] ) }>{ list.title } ;
} ) }
{ lists.length === 0 && { __( 'No lists available.', 'ai-marketing-expert' ) } }
{ __( 'Tags', 'ai-marketing-expert' ) }
{ tags.map( ( tag ) => {
const isSelected = selectedTags.includes( tag.id );
return setSelectedTags( isSelected ? selectedTags.filter( ( id ) => id !== tag.id ) : [ ...selectedTags, tag.id ] ) }>{ tag.color && }{ tag.title } ;
} ) }
{ tags.length === 0 && { __( 'No tags available.', 'ai-marketing-expert' ) } }
setShowValidationModal( false ) }>{ __( 'Cancel', 'ai-marketing-expert' ) }
{ loading ? __( 'Importing...', 'ai-marketing-expert' ) : __( 'Confirm Import', 'ai-marketing-expert' ) }
) }
);
};
export default ImportExport;