import { useEffect, useState } from '@wordpress/element'; import { __, _n, sprintf } from '@wordpress/i18n'; import { keepPreviousData } from '@tanstack/react-query'; import { useIcon, useUi } from '../runtime'; import { apiPost, apiPut } from '../api/client'; import { useContacts } from '../hooks/use-contacts'; import { useFields } from '../hooks/use-fields'; import { isComplete, needsValue, OPS, opLabel } from '../lib/fields'; import { argsToFilter, filterToArgs, groupIds, STATUS_OF_TAB, statusList, tabOf, } from '../lib/contact-filter'; import { errorText, number, prettify, statusOf } from '../lib/format'; import { engagementLabel } from '../lib/inactive'; /** * New segment and Edit segment, one dialog: a name and who is in it, with a * live "N match · M can be emailed" line. A segment is a saved filter * (`Mailpuff_Contact_Filter`): it keeps itself up to date. * * Who is in it is the conditions the contact filter knows today, and a * person must meet every one: a status, any of the chosen tags, a source, a * customer type, engagement, custom field conditions, and the search a list * was saved with. Each is * a row of `conditionRows()` reading and writing the same filter, so a rule * builder (all, any or none of a list of rules) can take their place later * and still hand `/segments` one `filter`. * * @param {Object} props * @param {boolean} props.open Whether it shows. * @param {?Object} props.segment The segment edited, or null for a new one. * @param {Object} props.filter A new segment's filter to start from (the * list's, from "Save as segment"). * @param {Array} props.tags The tags (`{ id, name }`). * @param {Object} props.facets Sources and customer types. * @param {Function} props.onClose Called to close it. * @param {Function} props.onSaved Called with the saved segment. * @return {Element} The dialog. */ export default function SegmentDialog( { open, segment = null, filter = null, tags = [], facets = null, onClose, onSaved, } ) { const { ui } = useUi(); const { Button, Dialog, Field, Input, toast } = ui; const [ name, setName ] = useState( '' ); const [ draft, setDraft ] = useState( {} ); const [ saving, setSaving ] = useState( false ); const { data: fieldDefs = [] } = useFields(); const isNew = ! segment?.id; // A field condition still being written counts nobody until it is whole, // and the segment saves once every one is. const conditions = draft.fields || []; const ready = conditions.every( ( c ) => isComplete( c, fieldDefs ) ); const counted = { ...draft }; const whole = conditions.filter( ( c ) => isComplete( c, fieldDefs ) ); if ( whole.length ) { counted.fields = whole; } else { delete counted.fields; } // Each opening starts from the segment, or from the list's filter. The // filter goes through the address shape, so it is clean and known. useEffect( () => { if ( open ) { setName( segment?.name || '' ); setDraft( argsToFilter( filterToArgs( segment ? segment.filter : filter ) ) ); } }, [ open, segment, filter ] ); // `reach` is what a campaign to it would reach now, as Review counts it. const { data: preview, isFetching } = useContacts( { ...filterToArgs( counted ), per_page: 1, with_reach: 1 }, { enabled: !! open, placeholderData: keepPreviousData } ); const save = async () => { const trimmed = name.trim(); if ( ! trimmed || saving || ! ready ) { return; } setSaving( true ); try { const saved = isNew ? await apiPost( 'segments', { name: trimmed, filter: draft } ) : await apiPut( `segments/${ segment.id }`, { name: trimmed, filter: draft, } ); onSaved( saved || { ...segment, name: trimmed, filter: draft } ); } catch ( err ) { toast.error( errorText( err, __( 'Could not save the segment.', 'mailpuff' ) ) ); } finally { setSaving( false ); } }; const matches = Number( preview?.total ) || 0; const reach = Number( preview?.reach ) || 0; return ( ! next && onClose() } title={ isNew ? __( 'New segment', 'mailpuff' ) : __( 'Edit segment', 'mailpuff' ) } footer={ <> } >
{ ( a11y ) => ( setName( e.target.value ) } /> ) } { const next = { ...draft }; if ( list.length ) { next.fields = list; } else { delete next.fields; } setDraft( next ); } } />

{ preview || ! isFetching ? sprintf( /* translators: 1: number of subscribers who match, 2: how many of them a campaign reaches. */ _n( '%1$s matches · %2$s can be emailed', '%1$s match · %2$s can be emailed', matches, 'mailpuff' ), number( matches ), number( reach ) ) : __( 'Counting…', 'mailpuff' ) }

); } /** * The status choices, as the list's Status menu has them, plus the one a * segment holds that none of them asks for exactly. * * @param {string} custom That status, or ''. * @return {Array<{value: string, label: string}>} Choices. */ function statusChoices( custom ) { const choices = [ { value: 'all', label: __( 'Any status', 'mailpuff' ) }, { value: 'subscribed', label: __( 'Subscribed', 'mailpuff' ) }, { value: 'pending', label: __( 'Pending', 'mailpuff' ) }, { value: 'not_subscribed', label: __( 'Not subscribed', 'mailpuff' ) }, { value: 'unsubscribed', label: __( 'Unsubscribed', 'mailpuff' ) }, { value: 'bounced', label: __( 'Bounced', 'mailpuff' ) }, ]; if ( custom ) { choices.push( { value: 'custom', label: custom .split( ',' ) .map( ( s ) => statusOf( s ).label ) .join( ', ' ), } ); } return choices; } /** * The conditions, each a part of one filter. Unset parts are left out of * it, so an empty filter is everybody. * * @param {Object} props * @param {Object} props.filter A segment-shaped filter. * @param {Function} props.onChange Called with the next filter. * @param {Array} props.tags The tags. * @param {Object} props.facets Sources and customer types. * @return {Element} The rows. */ function ConditionRows( { filter, onChange, tags, facets } ) { const { ui } = useUi(); const { Checkbox, Field, Input, NativeSelect } = ui; const set = ( key, value ) => { const next = { ...filter }; if ( value === '' || ( Array.isArray( value ) && ! value.length ) ) { delete next[ key ]; } else { next[ key ] = value; } onChange( next ); }; const tab = tabOf( filter.status ); const custom = tab === 'custom' ? statusList( filter.status ) : ''; const chosenTags = groupIds( filter.group_ids ); // A value the facets no longer list (nobody has it now) stays choosable. const withCurrent = ( list, value ) => value && ! list.includes( value ) ? [ ...list, value ] : list; const sources = withCurrent( facets?.sources || [], filter.source ); const types = withCurrent( facets?.customer_types || [], filter.customer_type ); const toggleTag = ( id ) => set( 'group_ids', chosenTags.includes( id ) ? chosenTags.filter( ( t ) => t !== id ) : [ ...chosenTags, id ].sort( ( a, b ) => a - b ) ); return ( <>
{ ( a11y ) => ( set( 'status', e.target.value === 'custom' ? custom : STATUS_OF_TAB[ e.target.value ] || '' ) } > { statusChoices( custom ).map( ( c ) => ( ) ) } ) } { ( a11y ) => ( set( 'engagement', e.target.value ) } > { filter.engagement && filter.engagement !== 'inactive' && ( ) } ) } { sources.length > 0 && ( { ( a11y ) => ( set( 'source', e.target.value ) } > { sources.map( ( s ) => ( ) ) } ) } ) } { types.length > 0 && ( { ( a11y ) => ( set( 'customer_type', e.target.value ) } > { types.map( ( t ) => ( ) ) } ) } ) }
{ () => tags.length > 0 ? (
{ tags.map( ( t ) => ( toggleTag( Number( t.id ) ) } /> ) ) }
) : (

{ __( 'No tags yet', 'mailpuff' ) }

) }
{ /* A list saved with a search keeps it; it shows so it can go. */ } { filter.search !== undefined && ( { ( a11y ) => ( onChange( { ...filter, search: e.target.value, } ) } /> ) } ) } ); } /** * Conditions on the owner's custom fields, each a row: the field, the * condition its type takes, and a value where one is needed. A person must * meet every one. Nothing shows while the site has no fields. * * @param {Object} props * @param {Array} props.conditions `{ key, op, value? }`. * @param {Array} props.fields The fields (`{ key, label, type }`). * @param {Function} props.onChange Called with the next conditions. * @return {?Element} The rows. */ function FieldConditions( { conditions, fields, onChange } ) { const { ui } = useUi(); const { Button, Field, IconButton, Input, NativeSelect } = ui; const Plus = useIcon( 'Plus' ); const Close = useIcon( 'X' ); if ( ! fields.length && ! conditions.length ) { return null; } const fresh = ( key ) => { const field = fields.find( ( f ) => f.key === key ) || fields[ 0 ]; const op = OPS[ field.type ][ 0 ]; return needsValue( op ) ? { key: field.key, op, value: '' } : { key: field.key, op }; }; const change = ( i, next ) => onChange( conditions.map( ( c, j ) => ( j === i ? next : c ) ) ); return ( { () => (
{ conditions.map( ( condition, i ) => { const field = fields.find( ( f ) => f.key === condition.key ); const ops = field ? OPS[ field.type ] : [ condition.op ]; let inputType = 'text'; if ( condition.op === 'within_days' || field?.type === 'number' ) { inputType = 'number'; } else if ( field?.type === 'date' ) { inputType = 'date'; } return (
change( i, fresh( e.target.value ) ) } > { ! field && ( ) } { fields.map( ( f ) => ( ) ) } { const op = e.target.value; change( i, needsValue( op ) ? { key: condition.key, op, value: condition.value ?? '', } : { key: condition.key, op } ); } } > { ops.map( ( op ) => ( ) ) } { needsValue( condition.op ) ? ( change( i, { ...condition, value: e.target.value, } ) } /> ) : ( ) } onChange( conditions.filter( ( _c, j ) => j !== i ) ) } >
); } ) } { fields.length > 0 && (
) }
) }
); }