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 ( ); } /** * 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 ( <>
{ __( 'No tags yet', 'mailpuff' ) }
) }