import { useEffect, useMemo, useRef, useState } from '@wordpress/element';
import { __, _n, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useUi, useIcon } from '../runtime';
import { apiGet, apiPost } from '../api/client';
import ImportSources from './ImportSources';
import TagDialog from './TagDialog';
import { ToggleRow } from '../shell/settings-layout';
import {
fetchKnown,
parseCsv,
summarizeImport,
uniqueEmails,
} from '../lib/csv';
import {
detectPreset,
genericResult,
isStop,
statusFromCell,
statusKey,
withGroups,
} from '../lib/import-presets';
import {
CHOOSABLE_STATUSES,
CONTACT_STATUSES,
errorText,
number,
statusOf,
} from '../lib/format';
const DEFAULT_OPTIONS = {
skip_duplicates: true,
default_status: 'subscribed',
default_source: 'csv_import',
group_ids: [],
skip_suspicious: true,
};
/** Rows the invalid-address list shows. */
const INVALID_SHOWN = 100;
/** Rows read for a status column's hint. */
const HINT_ROWS = 1000;
const NONE = {};
const NO_COLUMNS = [];
/** Who an export of one status holds (MailerLite exports one at a time). */
const WHO = () => [
{ value: 'subscribed', label: __( 'Active subscribers', 'mailpuff' ) },
{ value: 'pending', label: __( 'Unconfirmed', 'mailpuff' ) },
{ value: 'unsubscribed', label: __( 'Unsubscribed', 'mailpuff' ) },
{ value: 'bounced', label: __( 'Bounced', 'mailpuff' ) },
{ value: 'complained', label: __( 'Spam complaints', 'mailpuff' ) },
];
const OPERATORS = () => [
{ value: 'equals', label: __( 'equals', 'mailpuff' ) },
{ value: 'not_equals', label: __( 'does not equal', 'mailpuff' ) },
{ value: 'contains', label: __( 'contains', 'mailpuff' ) },
{ value: 'is_empty', label: __( 'is empty', 'mailpuff' ) },
{ value: 'is_not_empty', label: __( 'is not empty', 'mailpuff' ) },
{ value: 'greater_than', label: __( 'is greater than', 'mailpuff' ) },
];
const NO_VALUE = [ 'is_empty', 'is_not_empty' ];
const CORE_FIELDS = () => [
{ value: '', label: __( 'Skip', 'mailpuff' ) },
{ value: 'email', label: __( 'Email', 'mailpuff' ) },
{ value: 'first_name', label: __( 'First name', 'mailpuff' ) },
{ value: 'last_name', label: __( 'Last name', 'mailpuff' ) },
{ value: 'full_name', label: __( 'Full name', 'mailpuff' ) },
{ value: 'status', label: __( 'Status', 'mailpuff' ) },
{ value: 'created_at', label: __( 'Signup date', 'mailpuff' ) },
{ value: 'confirmed_at', label: __( 'Confirmed date', 'mailpuff' ) },
{ value: 'groups', label: __( 'Tags', 'mailpuff' ) },
{ value: 'source', label: __( 'Source', 'mailpuff' ) },
{ value: 'customer_type', label: __( 'Customer type', 'mailpuff' ) },
{ value: 'gross_revenue', label: __( 'Revenue', 'mailpuff' ) },
];
/**
* The second line of a column's row: how its status words come in, or its
* first value.
*
* @param {Object[]} rows Parsed rows.
* @param {string} header Column.
* @param {string} target What it is matched to.
* @param {Object} statusMap Status map.
* @param {string} defaultStatus Status for a row that gives none.
* @return {string|undefined} Text.
*/
function columnHint( rows, header, target, statusMap, defaultStatus ) {
if ( target !== 'status' ) {
return String( rows[ 0 ]?.[ header ] ?? '' ) || undefined;
}
const seen = new Map();
for ( const row of rows.slice( 0, HINT_ROWS ) ) {
const raw = String( row[ header ] ?? '' ).trim();
const key = statusKey( raw );
if ( key && ! seen.has( key ) ) {
seen.set(
key,
`${ raw } → ${
statusOf(
statusFromCell( raw, statusMap ) || defaultStatus
).label
}`
);
}
if ( seen.size > 4 ) {
break;
}
}
return [ ...seen.values() ].slice( 0, 4 ).join( ' · ' ) || undefined;
}
/**
* Optional rules: "if a column matches, then add to a tag, set the status
* or set the source". They run top to bottom for every row.
* @param root0
* @param root0.headers
* @param root0.rules
* @param root0.onChange
* @param root0.groups
*/
function Rules( { headers, rules, onChange, groups } ) {
const { ui } = useUi();
const { Button, Input, NativeSelect } = ui;
const Trash = useIcon( 'Trash' );
const Plus = useIcon( 'Plus' );
const patch = ( i, change ) =>
onChange(
rules.map( ( r, idx ) => ( idx === i ? { ...r, ...change } : r ) )
);
return (
{ rules.map( ( rule, i ) => (
patch( i, { column: e.target.value } )
}
>
{ headers.map( ( h ) => (
{ h }
) ) }
patch( i, { operator: e.target.value } )
}
>
{ OPERATORS().map( ( o ) => (
{ o.label }
) ) }
{ ! NO_VALUE.includes( rule.operator ) && (
patch( i, { value: e.target.value } )
}
/>
) }
patch( i, {
action: e.target.value,
action_value: '',
} )
}
>
{ __( 'Add to tag', 'mailpuff' ) }
{ __( 'Set status', 'mailpuff' ) }
{ __( 'Set source', 'mailpuff' ) }
{ rule.action === 'add_to_group' && (
patch( i, { action_value: e.target.value } )
}
>
{ __( 'Choose a tag', 'mailpuff' ) }
{ groups.map( ( g ) => (
{ g.name }
) ) }
) }
{ rule.action === 'set_status' && (
patch( i, { action_value: e.target.value } )
}
>
{ CHOOSABLE_STATUSES.map( ( value ) => (
{ statusOf( value ).label }
) ) }
) }
{ rule.action === 'set_source' && (
patch( i, { action_value: e.target.value } )
}
/>
) }
onChange( rules.filter( ( _, idx ) => idx !== i ) )
}
>
) ) }
onChange( [
...rules,
{
column: headers[ 0 ] || '',
operator: 'equals',
value: '',
action: 'add_to_group',
action_value: groups[ 0 ]
? String( groups[ 0 ].id )
: '',
},
] )
}
>
{ __( 'Add rule', 'mailpuff' ) }
);
}
/**
* The tag names a file's Tags columns hold, each once (case aside), split
* the way the import splits them.
*
* @param {Object[]} rows Parsed rows.
* @param {Object} mapping Column => target.
* @return {string[]} Names.
*/
function tagsInFile( rows, mapping ) {
const columns = Object.keys( mapping ).filter(
( h ) => mapping[ h ] === 'groups'
);
const seen = new Map();
if ( ! columns.length ) {
return [];
}
rows.forEach( ( row ) =>
columns.forEach( ( h ) =>
String( row[ h ] ?? '' )
.split( /[,;|]/ )
.map( ( name ) =>
name
.trim()
.replace( /^"+|"+$/g, '' )
.trim()
)
.filter( Boolean )
.forEach( ( name ) => {
if ( ! seen.has( name.toLowerCase() ) ) {
seen.set( name.toLowerCase(), name );
}
} )
)
);
return [ ...seen.values() ];
}
/**
* The tags everyone in the file gets: chips with a remove button and an
* Add tag menu, as on a subscriber's page, ending with New tag.
*
* @param {Object} props
* @param {Object[]} props.groups Every tag.
* @param {number[]} props.value The chosen tag ids.
* @param {Function} props.onChange Gets the next ids.
* @param {Function} props.onNew Opens New tag.
* @return {Element} The chips.
*/
function TagChips( { groups, value, onChange, onNew } ) {
const { ui } = useUi();
const { Button, Chip, DropdownItem, DropdownMenu, DropdownSeparator } = ui;
const Plus = useIcon( 'Plus' );
const chosen = value
.map( ( id ) => groups.find( ( g ) => Number( g.id ) === id ) )
.filter( Boolean );
const rest = groups.filter( ( g ) => ! value.includes( Number( g.id ) ) );
return (
{ chosen.map( ( g ) => (
onChange(
value.filter( ( id ) => id !== Number( g.id ) )
)
}
>
{ g.name }
) ) }
{ __( 'Add tag', 'mailpuff' ) }
}
>
{ rest.map( ( g ) => (
onChange( [ ...value, Number( g.id ) ] )
}
>
{ g.name }
) ) }
{ rest.length > 0 && }
{ __( 'New tag…', 'mailpuff' ) }
);
}
/**
* Which service the file came from, in one quiet line, with a way back to a
* plain column match. For an export that holds one status and does not say
* which, it asks.
* @param root0
* @param root0.detected
* @param root0.who
* @param root0.onWho
* @param root0.onReset
*/
function DetectedStrip( { detected, who, onWho, onReset } ) {
const { ui } = useUi();
const { Button, NativeSelect } = ui;
const notes = {
unsubscribed: sprintf(
/* translators: %s: service name, such as Mailchimp. */
__(
'These people unsubscribed in %s. They come in as unsubscribed and get no email.',
'mailpuff'
),
detected.label
),
bounced: sprintf(
/* translators: %s: service name, such as Mailchimp. */
__(
'%s removed these addresses after they bounced. They come in as bounced and get no email.',
'mailpuff'
),
detected.label
),
complained: sprintf(
/* translators: %s: service name, such as Mailchimp. */
__(
'These people marked email from %s as spam. They come in as complained and get no email.',
'mailpuff'
),
detected.label
),
};
let note = notes[ detected.fileStatus ] || '';
if ( detected.hint === 'no_status' ) {
note = sprintf(
/* translators: %s: service name, such as Substack. */
__(
'This %s export does not say who turned off emails. The export from its Settings page does, so use that one if you can.',
'mailpuff'
),
detected.label
);
} else if ( detected.defaultStatus === 'not_subscribed' ) {
note = __(
'These contacts never subscribed. They come in as not subscribed and get no newsletters.',
'mailpuff'
);
}
return (
{ sprintf(
/* translators: 1: service name, such as Mailchimp. 2: number of columns. */
_n(
'Looks like a %1$s export. We matched %2$s column.',
'Looks like a %1$s export. We matched %2$s columns.',
detected.matched,
'mailpuff'
),
detected.label,
number( detected.matched )
) }
{ note && (
{ note }
) }
{ detected.askStatus && (
{ sprintf(
/* translators: %s: service name, such as MailerLite. */
__(
'%s exports one status at a time. Who is in this file?',
'mailpuff'
),
detected.label
) }
onWho( e.target.value ) }
>
{ __( 'Choose', 'mailpuff' ) }
{ WHO().map( ( o ) => (
{ o.label }
) ) }
) }
{ sprintf(
/* translators: %s: service name, such as Mailchimp. */
__( 'Not from %s?', 'mailpuff' ),
detected.label
) }
);
}
/**
* What the import will do, before it starts: new and existing subscribers,
* the duplicate rows and invalid addresses taken out, and the statuses that
* come in.
* @param root0
* @param root0.summary
* @param root0.checking
* @param root0.checkFailed
* @param root0.skipDuplicates
* @param root0.tagLine
*/
function Summary( {
summary,
checking,
checkFailed,
skipDuplicates,
tagLine,
} ) {
const { ui } = useUi();
const { Button, KeyValueList } = ui;
const [ showInvalid, setShowInvalid ] = useState( false );
const pending = ! summary.checked;
const waiting = checking
? __( 'Checking…', 'mailpuff' )
: __( 'Not checked', 'mailpuff' );
const existing = [];
if ( summary.updated ) {
existing.push(
sprintf(
/* translators: %s: number of subscribers. */
__( '%s updated', 'mailpuff' ),
number( summary.updated )
)
);
}
if ( summary.kept ) {
existing.push(
sprintf(
/* translators: %s: number of subscribers. */
__( '%s kept as they are', 'mailpuff' ),
number( summary.kept )
)
);
}
const statuses = CONTACT_STATUSES.filter( ( s ) => summary.statuses[ s ] )
.map(
( s ) =>
`${ statusOf( s ).label } ${ number( summary.statuses[ s ] ) }`
)
.join( ' · ' );
const items = [
{
label: __( 'New subscribers', 'mailpuff' ),
value: pending ? waiting : number( summary.added ),
},
{
label: __( 'Already subscribers', 'mailpuff' ),
value: pending ? waiting : existing.join( ', ' ) || number( 0 ),
},
];
if ( summary.duplicates ) {
items.push( {
label: __( 'Duplicate rows', 'mailpuff' ),
value: sprintf(
/* translators: %s: number of rows. */
_n(
'%s row in this file removed',
'%s rows in this file removed',
summary.duplicates,
'mailpuff'
),
number( summary.duplicates )
),
} );
}
if ( summary.invalid.length ) {
items.push( {
label: __( 'Invalid addresses', 'mailpuff' ),
value: (
{ sprintf(
/* translators: %s: number of rows. */
_n(
'%s skipped',
'%s skipped',
summary.invalid.length,
'mailpuff'
),
number( summary.invalid.length )
) }
setShowInvalid( ! showInvalid ) }
>
{ showInvalid
? __( 'Hide', 'mailpuff' )
: __( 'Show', 'mailpuff' ) }
),
} );
}
if ( summary.suspicious ) {
items.push( {
label: __( 'Unusable addresses', 'mailpuff' ),
value: sprintf(
/* translators: %s: number of addresses. */
_n(
'%s skipped',
'%s skipped',
summary.suspicious,
'mailpuff'
),
number( summary.suspicious )
),
} );
}
if ( summary.suppressed ) {
items.push( {
label: __( 'Opted out before', 'mailpuff' ),
value: sprintf(
/* translators: %s: number of addresses. */
_n(
'%s address unsubscribed, bounced or complained earlier and stays that way',
'%s addresses unsubscribed, bounced or complained earlier and stay that way',
summary.suppressed,
'mailpuff'
),
number( summary.suppressed )
),
} );
}
if ( tagLine ) {
items.push( {
label: __( 'Tags', 'mailpuff' ),
value: tagLine,
} );
}
if ( statuses ) {
items.push( {
label: skipDuplicates
? __( 'Statuses', 'mailpuff' )
: __( 'Statuses after import', 'mailpuff' ),
value: statuses,
} );
}
return (
{ showInvalid && (
{ summary.invalid.slice( 0, INVALID_SHOWN ).map( ( r ) => (
{ sprintf(
/* translators: %s: row number in the file. */
__( 'Row %s', 'mailpuff' ),
number( r.row )
) }
{ ' ' }
{ r.value || __( '(empty)', 'mailpuff' ) }
) ) }
{ summary.invalid.length > INVALID_SHOWN && (
{ sprintf(
/* translators: %s: number of rows. */
__( 'and %s more', 'mailpuff' ),
number( summary.invalid.length - INVALID_SHOWN )
) }
) }
) }
{ checkFailed && (
{ __(
'We could not check which of these are already subscribers. The import still checks every address.',
'mailpuff'
) }
) }
);
}
/**
* Polls an import job and shows its progress and the final tallies.
* @param root0
* @param root0.jobId
* @param root0.total
* @param root0.onDone
*/
function Progress( { jobId, total, onDone } ) {
const { ui } = useUi();
const { KeyValueList, Notice, ProgressBar } = ui;
const [ job, setJob ] = useState( {
status: 'pending',
total,
processed: 0,
imported: 0,
updated: 0,
skipped: 0,
failed: 0,
duplicates: 0,
invalid: 0,
errors: [],
} );
useEffect( () => {
let cancelled = false;
let timer;
const poll = async () => {
try {
const res = await apiGet( `contacts/import/${ jobId }` );
if ( cancelled ) {
return;
}
setJob( res );
if (
[ 'complete', 'failed', 'cancelled' ].includes( res.status )
) {
onDone?.( res );
return;
}
} catch {
// A transient error: keep polling.
}
timer = setTimeout( poll, 1200 );
};
poll();
return () => {
cancelled = true;
clearTimeout( timer );
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ jobId ] );
const done = job.status === 'complete';
const failed = job.status === 'failed';
const items = [
{
label: __( 'Added', 'mailpuff' ),
value: number( job.imported ),
},
{
label: __( 'Updated', 'mailpuff' ),
value: number( job.updated ),
},
{
label: __( 'Skipped', 'mailpuff' ),
value: number( job.skipped ),
},
{
label: __( 'Failed', 'mailpuff' ),
value: number( job.failed ),
},
];
if ( job.duplicates ) {
items.push( {
label: __( 'Duplicate rows', 'mailpuff' ),
value: number( job.duplicates ),
} );
}
if ( job.invalid ) {
items.push( {
label: __( 'Invalid addresses', 'mailpuff' ),
value: number( job.invalid ),
} );
}
return (
{ failed && (
{ job.errors?.length
? job.errors.join( ' ' )
: __( 'The import failed.', 'mailpuff' ) }
) }
{ done && (
{ __( 'Import complete.', 'mailpuff' ) }
) }
{ ! done && ! failed && (
) }
);
}
/**
* Import contacts from a CSV: one drawer with the file, the column match, the
* options and optional rules, a summary, then the progress. A file another
* service exported is recognised (lib/import-presets.js) and its columns and
* statuses are matched for you.
*
* A page of its own under Subscribers (`view=import`), not a drawer: the
* file, the columns, the options and the summary, with the actions at the
* foot of the page.
*
* @param {Object} root0 The props.
* @param {Function} root0.onDone Leaves the page, after an import or a cancel.
*/
export default function ImportView( { onDone } ) {
// The page is the import: its queries run while it is shown.
const open = true;
const { ui, kit } = useUi();
const {
Button,
Card,
CardContent,
Field,
Input,
NativeSelect,
Notice,
EmptyState,
Row,
RowList,
SegmentedControl,
toast,
} = ui;
const qc = useQueryClient();
const inputRef = useRef( null );
const Upload = useIcon( 'Upload' );
const [ file, setFile ] = useState( null );
const [ parsing, setParsing ] = useState( false );
const [ parseError, setParseError ] = useState( '' );
const [ headers, setHeaders ] = useState( [] );
const [ rows, setRows ] = useState( [] );
const [ mapping, setMapping ] = useState( {} );
const [ detected, setDetected ] = useState( null );
const [ who, setWho ] = useState( '' );
const [ delimiter, setDelimiter ] = useState( ',' );
const [ options, setOptions ] = useState( DEFAULT_OPTIONS );
const [ rules, setRules ] = useState( [] );
const [ starting, setStarting ] = useState( false );
const [ jobId, setJobId ] = useState( null );
// A Mailchimp zip that was opened: its name and its files.
const [ zip, setZip ] = useState( null );
// The rows an import from another plugin starts with.
const [ jobTotal, setJobTotal ] = useState( 0 );
const [ newTag, setNewTag ] = useState( false );
const [ dragging, setDragging ] = useState( false );
const [ newField, setNewField ] = useState( '' );
const { data: groupsData } = useQuery( {
queryKey: [ 'groups' ],
queryFn: () => apiGet( 'groups' ),
enabled: open,
} );
const groups = groupsData?.items || [];
const { data: fieldsData } = useQuery( {
queryKey: [ 'custom-fields' ],
queryFn: () => apiGet( 'custom-fields' ),
enabled: open,
} );
const customFields = Array.isArray( fieldsData ) ? fieldsData : [];
const statusMap = detected?.statusMap || NONE;
// An export of one status: the person says which; a stop status then
// marks every row, any other is the default.
let fileStatus = detected?.fileStatus || '';
if ( detected?.askStatus ) {
fileStatus = isStop( who ) ? who : '';
}
const needsWho = Boolean( detected?.askStatus ) && ! who;
// Which addresses are already subscribers: asked once per file and email
// column, so the summary can say what is new.
const emailHeader = Object.keys( mapping ).find(
( h ) => mapping[ h ] === 'email'
);
const emails = useMemo(
() => uniqueEmails( rows, emailHeader ),
[ rows, emailHeader ]
);
const fileKey = file
? `${ file.name }:${ file.size }:${ file.lastModified }`
: '';
const check = useQuery( {
queryKey: [ 'import-check', fileKey, emailHeader ],
queryFn: () =>
fetchKnown( emails, ( batch ) =>
apiPost( 'contacts/import/check', { emails: batch } )
),
enabled: open && ! jobId && emails.length > 0,
staleTime: Infinity,
retry: false,
} );
const summary = useMemo(
() =>
summarizeImport( rows, mapping, {
statusMap,
fileStatus,
defaultStatus: options.default_status,
rules,
skipDuplicates: options.skip_duplicates,
skipSuspicious: options.skip_suspicious,
known: check.data || null,
} ),
[
rows,
mapping,
statusMap,
fileStatus,
options.default_status,
options.skip_duplicates,
options.skip_suspicious,
rules,
check.data,
]
);
const hints = useMemo( () => {
const out = {};
headers.forEach( ( h ) => {
out[ h ] = columnHint(
rows,
h,
mapping[ h ],
statusMap,
options.default_status
);
} );
return out;
}, [ headers, rows, mapping, statusMap, options.default_status ] );
const hasEmail = Boolean( emailHeader );
const willImport = Math.max(
0,
summary.unique - summary.suspicious - summary.suppressed
);
// The tags this import gives: the chosen ones, the rules' and the
// file's, each once; "new" are the file's names no tag has yet.
const fileTags = useMemo(
() => tagsInFile( rows, mapping ),
[ rows, mapping ]
);
const nameOf = ( id ) =>
groups.find( ( g ) => Number( g.id ) === Number( id ) )?.name;
const tagNames = new Map();
[
...options.group_ids.map( nameOf ),
...rules
.filter( ( r ) => r.action === 'add_to_group' && r.action_value )
.map( ( r ) => nameOf( r.action_value ) ),
...fileTags,
]
.filter( Boolean )
.forEach( ( name ) => tagNames.set( name.toLowerCase(), name ) );
const known = new Set( groups.map( ( g ) => g.name.toLowerCase() ) );
const freshTags = fileTags.filter(
( n ) => ! known.has( n.toLowerCase() )
);
let tagLine = '';
if ( tagNames.size && freshTags.length ) {
tagLine = sprintf(
/* translators: 1: number of tags, 2: how many are new. */
_n(
'%1$s tag (%2$s new)',
'%1$s tags (%2$s new)',
tagNames.size,
'mailpuff'
),
number( tagNames.size ),
number( freshTags.length )
);
} else if ( tagNames.size ) {
tagLine = sprintf(
/* translators: %s: number of tags. */
_n( '%s tag', '%s tags', tagNames.size, 'mailpuff' ),
number( tagNames.size )
);
}
const reset = () => {
setFile( null );
setHeaders( [] );
setRows( [] );
setMapping( {} );
setDetected( null );
setWho( '' );
setDelimiter( ',' );
setOptions( DEFAULT_OPTIONS );
setRules( [] );
setJobId( null );
setParseError( '' );
qc.removeQueries( { queryKey: [ 'import-check' ] } );
};
const close = () => {
reset();
onDone();
};
const applyDetection = ( found ) => {
setDetected( found );
// A column of tags (Tags, Lists, Groups) is matched to Tags at once.
setMapping(
withGroups( found.mapping, found.groupColumns || NO_COLUMNS, true )
);
setWho( '' );
setOptions( ( o ) => ( {
...o,
default_status:
found.defaultStatus || DEFAULT_OPTIONS.default_status,
} ) );
};
const chooseWho = ( value ) => {
setWho( value );
if ( ! isStop( value ) ) {
setOptions( ( o ) => ( { ...o, default_status: value } ) );
}
};
const choose = async ( picked ) => {
if ( ! picked ) {
return;
}
let f = picked;
setZip( null );
// Mailchimp's audience export: the server opens the zip and gives
// back one CSV, each row with its status, read like any other file.
if ( picked.name.toLowerCase().endsWith( '.zip' ) ) {
setFile( picked );
setParsing( true );
setParseError( '' );
try {
const body = new FormData();
body.append( 'file', picked );
const res = await apiFetch( {
path: 'mailpuff/v1/contacts/import/mailchimp',
method: 'POST',
body,
} );
f = new File( [ res.csv ], 'mailchimp-audience.csv', {
type: 'text/csv',
} );
setZip( { name: picked.name, files: res.files || [] } );
} catch ( err ) {
setParsing( false );
setFile( null );
setParseError(
errorText(
err,
__( 'Could not read this zip.', 'mailpuff' )
)
);
return;
}
}
if ( ! f.name.toLowerCase().endsWith( '.csv' ) ) {
setParseError(
sprintf(
/* translators: %s: file name. */
__(
'“%s” is not a CSV file or a Mailchimp export.',
'mailpuff'
),
f.name
)
);
return;
}
setFile( f );
setParsing( true );
setParseError( '' );
try {
const { headers: h, rows: r, delimiter: d } = await parseCsv( f );
if ( ! h.length || ! r.length ) {
setParseError( __( 'No rows found in this CSV.', 'mailpuff' ) );
setHeaders( [] );
setRows( [] );
setDetected( null );
} else {
setHeaders( h );
setRows( r );
setDelimiter( d );
applyDetection( detectPreset( h, r.slice( 0, 50 ), f.name ) );
}
} catch {
setParseError( __( 'Could not read this CSV file.', 'mailpuff' ) );
}
setParsing( false );
};
const createField = async () => {
const label = newField.trim();
if ( ! label ) {
return;
}
try {
const list = await apiPost( 'custom-fields', {
label,
type: 'text',
} );
qc.setQueryData( [ 'custom-fields' ], list );
setNewField( '' );
} catch ( err ) {
toast.error(
errorText(
err,
__( 'Could not create the field.', 'mailpuff' )
)
);
}
};
const start = async () => {
if ( ! file ) {
return;
}
setStarting( true );
try {
const used = Object.values( mapping )
.filter( ( v ) => String( v ).startsWith( 'meta:' ) )
.map( ( v ) => v.slice( 5 ) );
const body = new FormData();
body.append( 'file', file );
body.append( 'mapping', JSON.stringify( mapping ) );
body.append(
'options',
JSON.stringify( {
...options,
status_map: statusMap,
file_status: fileStatus,
delimiter,
preset:
detected && detected.id !== 'generic'
? detected.id
: '',
} )
);
body.append( 'rules', JSON.stringify( rules ) );
body.append(
'custom_fields',
JSON.stringify(
customFields.filter( ( f ) => used.includes( f.key ) )
)
);
const res = await apiFetch( {
path: 'mailpuff/v1/contacts/import',
method: 'POST',
body,
headers: {},
} );
setJobId( res.job_id );
} catch ( err ) {
toast.error(
errorText(
err,
__( 'The import could not start.', 'mailpuff' )
)
);
}
setStarting( false );
};
const setOption = ( key ) => ( value ) =>
setOptions( ( o ) => ( { ...o, [ key ]: value } ) );
const running = !! jobId;
const recognised = detected && detected.id !== 'generic';
const footer = running ? (
{ __( 'Done', 'mailpuff' ) }
) : (
<>
{ __( 'Cancel', 'mailpuff' ) }
{ sprintf(
/* translators: %s: number of subscribers. */
_n(
'Import %s subscriber',
'Import %s subscribers',
willImport,
'mailpuff'
),
number( willImport )
) }
>
);
const picker = (
{
choose( e.target.files[ 0 ] );
e.target.value = '';
} }
/>
);
const pick = () => inputRef.current?.click();
const shownTags = fileTags.slice( 0, 6 ).join( ', ' );
return (
{ running && (
) }
{ ! running && ! file && (
<>
{ /* The file first: most imports are a CSV from another
service, dropped or chosen. */ }
{
e.preventDefault();
setDragging( true );
} }
onDragLeave={ () => setDragging( false ) }
onDrop={ ( e ) => {
e.preventDefault();
setDragging( false );
choose( e.dataTransfer.files[ 0 ] );
} }
>
}
title={ __( 'Drop a CSV file here', 'mailpuff' ) }
description={ __(
'Exports from Mailchimp, Kit, beehiiv, Substack, MailerLite, FluentCRM and Groundhogg are matched for you.',
'mailpuff'
) }
actions={
{ __( 'Choose a file', 'mailpuff' ) }
}
/>
{ picker }
{ parseError && (
{ parseError }
) }
{
setJobTotal( Number( started.total ) || 0 );
setJobId( started.job_id );
} }
/>
>
) }
{ ! running && file && (
<>
{ zip ? zip.name : file.name }
{ parsing
? __( 'Reading', 'mailpuff' )
: sprintf(
/* translators: %s: number of rows. */
_n(
'%s row',
'%s rows',
summary.total,
'mailpuff'
),
number( summary.total )
) }
{ zip && ! parsing
? ` · ${ zip.files
.map(
( z ) =>
`${ statusOf(
z.status
).label.toLowerCase() } ${ number(
z.rows
) }`
)
.join( ', ' ) }`
: '' }
{ __( 'Change file', 'mailpuff' ) }
{ picker }
{ parseError && (
{ parseError }
) }
{ rows.length > 0 && recognised && (
applyDetection(
genericResult(
headers,
rows.slice( 0, 50 )
)
)
}
/>
) }
{ rows.length > 0 && (
<>
}
/>
{ ! hasEmail && (
{ __(
'Match one column to Email to continue.',
'mailpuff'
) }
) }
{ headers.map( ( h ) => (
setMapping( {
...mapping,
[ h ]: e.target
.value,
} )
}
>
{ CORE_FIELDS().map(
( f ) => (
{ f.label }
)
) }
{ customFields.length >
0 && (
{ customFields.map(
( cf ) => (
{
cf.label
}
)
) }
) }
}
/>
) ) }
setNewTag( true )
}
/>
{ fileTags.length > 0 && (
{ fileTags.length > 6
? sprintf(
/* translators: 1: tag names, 2: how many more. */
__(
'%1$s and %2$s more',
'mailpuff'
),
shownTags,
number(
fileTags.length -
6
)
)
: shownTags }
{ freshTags.length > 0 && (
{ ` · ${ sprintf(
/* translators: %s: number of new tags. */
__(
'%s new',
'mailpuff'
),
number(
freshTags.length
)
) }` }
) }
) }
{ ( a11y ) => (
setOption(
'default_status'
)( e.target.value )
}
>
{ CHOOSABLE_STATUSES.map(
( value ) => (
{
statusOf(
value
).label
}
)
) }
) }
setOption(
'skip_duplicates'
)( v === 'keep' )
}
options={ [
{
value: 'keep',
label: __(
'Keep their details',
'mailpuff'
),
},
{
value: 'update',
label: __(
'Update them',
'mailpuff'
),
},
] }
/>
{ hasEmail && (
) }
>
) }
>
) }
setNewTag( false ) }
onSaved={ ( saved ) => {
setNewTag( false );
qc.invalidateQueries( { queryKey: [ 'groups' ] } );
if ( saved?.id ) {
setOptions( ( o ) => ( {
...o,
group_ids: [ ...o.group_ids, Number( saved.id ) ],
} ) );
}
} }
/>
{ footer }
);
}