/** * Settings of the form beyond its look, shown in the properties when nothing is selected: * access (password, time window, entry limit, time limit), confirming the e-mail address (double opt-in), * payment and spam protection. The plugin checks all of them on the server. */ import React, { useEffect, useState } from 'react'; import { useStore } from 'zustand'; import type { FormDocument, Payment, Settings, Text } from '@funnelforms/form-schema'; import { createAction, emailFields } from '../actions'; import { euPrivacy } from '../privacy'; import type { Connection, FormSummary } from '../api'; import { nodeName, text } from '../document'; import { editText, fallbackText, withText } from '../languages'; import { formProtection, spamProtection } from '../spam'; import type { Recipe } from '../store'; import { ConnectionPicker } from './Actions'; import { useEnv } from './context'; import { __, sprintf } from './i18n'; import { Badge, Button, Field as FieldRow, icons, Notice, NumberInput, Select, TextInput, Toggle } from './ui'; type Access = NonNullable; function useChange(): ( recipe: Recipe, key?: string ) => void { return useEnv().store.getState().change; } /** The value of a datetime-local input for an ISO time, in the editor's time zone. */ export function localInput( iso: string | undefined ): string { if ( ! iso ) { return ''; } const d = new Date( iso ); if ( Number.isNaN( d.getTime() ) ) { return ''; } const pad = ( n: number ): string => String( n ).padStart( 2, '0' ); return `${ d.getFullYear() }-${ pad( d.getMonth() + 1 ) }-${ pad( d.getDate() ) }T${ pad( d.getHours() ) }:${ pad( d.getMinutes() ) }`; } /** ISO time with the editor's offset for the value of a datetime-local input. */ export function isoFromInput( value: string ): string | undefined { const d = new Date( value ); if ( '' === value || Number.isNaN( d.getTime() ) ) { return undefined; } const pad = ( n: number ): string => String( Math.abs( n ) ).padStart( 2, '0' ); const offset = -d.getTimezoneOffset(); return `${ value.slice( 0, 16 ) }:00${ offset >= 0 ? '+' : '-' }${ pad( Math.trunc( offset / 60 ) ) }:${ pad( offset % 60 ) }`; } /** Changes the access settings; empty ones are removed, and with them `access` itself. */ function setAccess( d: FormDocument, recipe: ( a: Access ) => void ): void { const access: Access = { ...( d.settings.access ?? {} ) }; recipe( access ); // The closed message belongs to the limits; without them it would never show. if ( undefined === access.maxEntries && undefined === access.opensAt && undefined === access.closesAt ) { access.closedMessage = undefined; } if ( ! access.loginRequired ) { access.loginRequired = undefined; access.loginMessage = undefined; } const kept = Object.fromEntries( Object.entries( access ).filter( ( [ , v ] ) => undefined !== v ) ) as Access; if ( Object.keys( kept ).length ) { d.settings.access = kept; } else { delete d.settings.access; } } export function AccessSection( { doc }: { doc: FormDocument } ) { const { api, readOnly, lang } = useEnv(); const change = useChange(); const access = doc.settings.access ?? {}; const locale = doc.locales.default; const timeLimit = doc.settings.timeLimit; const [ password, setPassword ] = useState( null ); const [ busy, setBusy ] = useState( false ); const [ error, setError ] = useState( null ); const limited = undefined !== access.maxEntries || undefined !== access.opensAt || undefined !== access.closesAt; const reversed = access.opensAt && access.closesAt && new Date( access.closesAt ).getTime() <= new Date( access.opensAt ).getTime(); const savePassword = async (): Promise => { setBusy( true ); setError( null ); try { const hash = await api.passwordHash( password ?? '' ); change( ( d ) => setAccess( d, ( a ) => void ( a.password = { hash } ) ) ); setPassword( null ); } catch ( e ) { setError( e instanceof Error ? e.message : String( e ) ); } setBusy( false ); }; const time = ( key: 'opensAt' | 'closesAt', label: string ) => ( { ( id ) => ( { const v = isoFromInput( e.target.value ); change( ( d ) => setAccess( d, ( a ) => void ( a[ key ] = v ) ), 'access:' + key ); } } /> ) } ); return (

{ __( 'Access', 'funnelforms-pro' ) }

{ access.password && null === password ? (

{ __( 'Visitors need a password to see the form.', 'funnelforms-pro' ) }

) : null } { ! access.password && null === password ? ( ) : null } { null !== password ? ( <> { error ? { error } : null }
) : null } ! readOnly && change( ( d ) => setAccess( d, ( a ) => void ( a.loginRequired = on || undefined ) ) ) } /> { access.loginRequired ? ( change( ( d ) => setAccess( d, ( a ) => void ( a.loginMessage = '' === v && lang === locale ? undefined : withText( a.loginMessage, lang, v, locale ) ) ), 'access:login' ) } hint={ __( 'Empty for the standard text. The login link comes below it.', 'funnelforms-pro' ) } /> ) : null } change( ( d ) => setAccess( d, ( a ) => void ( a.maxEntries = undefined === v || v < 1 ? undefined : Math.floor( v ) ) ), 'access:max' ) } /> { time( 'opensAt', __( 'Open from', 'funnelforms-pro' ) ) } { time( 'closesAt', __( 'Open until', 'funnelforms-pro' ) ) } { reversed ? { __( 'The form closes before it opens, so it never takes entries.', 'funnelforms-pro' ) } : null } { limited ? ( change( ( d ) => setAccess( d, ( a ) => void ( a.closedMessage = '' === v && lang === locale ? undefined : withText( a.closedMessage, lang, v, locale ) ) ), 'access:message' ) } hint={ __( 'Empty for the standard text.', 'funnelforms-pro' ) } /> ) : null } change( ( d ) => { if ( undefined === v || v < 1 ) { delete d.settings.timeLimit; } else { d.settings.timeLimit = { ...d.settings.timeLimit, minutes: Math.min( 1440, Math.floor( v ) ) }; } }, 'time:minutes' ) } hint={ __( 'Counts from the visitor\'s first click. Visitors see the time left; entries sent later are not accepted.', 'funnelforms-pro' ) } /> { timeLimit ? ( change( ( d ) => { if ( d.settings.timeLimit ) { const message = '' === v && lang === locale ? undefined : withText( d.settings.timeLimit.message, lang, v, locale ); d.settings.timeLimit = { minutes: d.settings.timeLimit.minutes, ...( message ? { message } : {} ) }; } }, 'time:message' ) } hint={ __( 'Empty for the standard text.', 'funnelforms-pro' ) } /> ) : null }
); } /** Default texts of the confirmation mail, in the editor's language. */ function optInTexts( locale: string ): { subject: Text; body: Text; confirmation: Text } { return { subject: { [ locale ]: __( 'Please confirm your e-mail address', 'funnelforms-pro' ) }, body: { [ locale ]: __( 'Please confirm your e-mail address with this link:', 'funnelforms-pro' ) + '\n\n{{confirm_url}}' }, confirmation: { [ locale ]: '

' + __( 'Thank you, your e-mail address is confirmed.', 'funnelforms-pro' ) + '

' }, }; } export function DoubleOptInSection( { doc }: { doc: FormDocument } ) { const { readOnly, lang } = useEnv(); const change = useChange(); const optIn = doc.settings.doubleOptIn; const locale = doc.locales.default; const emails = emailFields( doc ); const edit = ( key: 'subject' | 'body' | 'confirmation' ) => ( v: string ): void => change( ( d ) => { if ( d.settings.doubleOptIn ) { d.settings.doubleOptIn[ key ] = withText( d.settings.doubleOptIn[ key ], lang, v, locale ); } }, 'optin:' + key ); return (

{ __( 'Confirm e-mail address', 'funnelforms-pro' ) }

{ const first = emails[ 0 ]; if ( readOnly || ( on && ! first ) ) { return; } change( ( d ) => { if ( on && first ) { d.settings.doubleOptIn = { field: first.id, ...optInTexts( locale ) }; } else { delete d.settings.doubleOptIn; } } ); } } /> { ! optIn && ! emails.length ?

{ __( 'Needs an e-mail field in a contact step.', 'funnelforms-pro' ) }

: null } { optIn ? ( <> ( { value: f.id, label: text( f.label, locale ) || f.key } ) ) } onChange={ ( v ) => set( ( a ) => void ( a.field = v ) ) } /> { emails.some( ( f ) => f.id === abandon.field ) ? null : { __( 'The e-mail field of the reminder no longer exists. Choose another one.', 'funnelforms-pro' ) } } ( { value: b.id, label: b.label } ) ) ] } onChange={ ( v ) => set( ( a ) => void ( a.consentField = v || undefined ) ) } hint={ __( 'Its text should say that you send one reminder, e.g. "Remind me by e-mail if I leave before sending."', 'funnelforms-pro' ) } /> { boxes.some( ( b ) => b.id === abandon.consentField ) ? null : { __( 'Add a consent box to the contact step and choose it here, or use the notice.', 'funnelforms-pro' ) } } ) : ( ) } set( ( a ) => void ( a.layout = v ) ) } hint={ __( 'The sender is that of the form\'s first mail to visitors, else the site\'s.', 'funnelforms-pro' ) } /> set( ( a ) => ( on ? ( a.secondAfterHours = 24 ) : delete a.secondAfterHours ) ) } /> set( ( a ) => ( on ? ( a.notifyOwner = true ) : delete a.notifyOwner ) ) } />

{ __( 'Each address gets reminders of this form once in 30 days. Abandoned entries are listed under Entries and deleted after 30 days.', 'funnelforms-pro' ) }

) : null }
); } const CURRENCIES = [ 'EUR','USD', 'GBP', 'CHF', 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'CAD', 'AUD' ]; /** What is still missing for the payment to work. */ export function paymentGaps( payment: Payment, doc: FormDocument ): Array<'connection' | 'amount'> { const out: Array<'connection' | 'amount'> = []; if ( ! /^(stripe|paypal|mollie):/.test( payment.connection ) ) { out.push( 'connection' ); } if ( 'fixed' in payment.amount ? ! ( payment.amount.fixed > 0 ) : ! doc.calculations.some( ( c ) => 'calculation' in payment.amount && c.id === payment.amount.calculation ) ) { out.push( 'amount' ); } return out; } /** Text fields of the steps and contact steps, which can take a coupon code. */ export function couponFields( doc: FormDocument ): Array<{ id: string; label: string }> { const locale = doc.locales.default; const out: Array<{ id: string; label: string }> = []; for ( const node of doc.nodes ) { if ( 'end' !== node.type ) { for ( const f of node.fields ) { if ( 'text' === f.type ) { out.push( { id: f.id, label: ( text( f.label, locale ).replace( /<[^>]*>/g, '' ) || f.key ) + ' [' + f.key + ']' } ); } } } } return out; } /** A coupon code as the plugin takes it: letters, digits, - and _, up to 40. */ export function cleanCode( value: string ): string { return value.replace( /[^A-Za-z0-9_-]/g, '' ).slice( 0, 40 ); } /** Coupons: codes visitors type into a text field of the form; the plugin takes their discount off. */ function Coupons( { doc, payment, set }: { doc: FormDocument; payment: Payment; set: ( recipe: ( p: Payment ) => void, key?: string ) => void } ) { const { readOnly } = useEnv(); const fields = couponFields( doc ); const coupons = payment.coupons ?? []; const seen = new Set(); const duplicate = coupons.some( ( c ) => { const code = c.code.toLowerCase(); const again = seen.has( code ); seen.add( code ); return again; } ); return (

{ __( 'Coupons', 'funnelforms-pro' ) }

{ fields.length ? ( set( ( p ) => void ( p.coupons && p.coupons[ i ] && ( p.coupons[ i ].code = cleanCode( e.target.value ) ) ), `coupon-code:${ i }` ) } /> set( ( p ) => { const coupon = p.coupons?.[ i ]; const value = Number( e.target.value ); if ( coupon ) { const percent = undefined !== coupon.percent || undefined === coupon.amount; delete coupon.percent; delete coupon.amount; if ( value > 0 ) { coupon[ percent ? 'percent' : 'amount' ] = percent ? Math.min( 100, value ) : value; } } }, `coupon-value:${ i }` ) } /> ) : null }
); } export function PaymentSection( { doc }: { doc: FormDocument } ) { const { api, rights, readOnly, lang } = useEnv(); const change = useChange(); const payment = doc.settings.payment; const locale = doc.locales.default; const [ connections, setConnections ] = useState( [] ); useEffect( () => { let live = true; api.connections().then( ( list ) => live && setConnections( list ), () => undefined ); return () => { live = false; }; }, [ api ] ); const set = ( recipe: ( p: Payment ) => void, key?: string ): void => change( ( d ) => { if ( d.settings.payment ) { recipe( d.settings.payment ); } }, key && 'payment:' + key ); const emails = emailFields( doc ); const contacts = doc.nodes.filter( ( n ) => 'contact' === n.type ); const gaps = payment ? paymentGaps( payment, doc ) : []; const provider = payment?.connection.split( ':' )[ 0 ] ?? ''; return (

{ __( 'Payment', 'funnelforms-pro' ) }

! readOnly && change( ( d ) => { if ( on ) { const calc = d.calculations[ 0 ]; d.settings.payment = { connection: '', amount: calc ? { calculation: calc.id } : { fixed: 0 }, currency: 'EUR', mode: 'payment', description: { [ locale ]: d.title }, ...( emailFields( d )[ 0 ] ? { emailField: emailFields( d )[ 0 ]?.id } : {} ), }; } else { delete d.settings.payment; // Actions waiting for a payment would never run. for ( const action of d.actions ) { action.on = 'submit'; } } } ) } /> { payment && ! rights.entries ? { __( 'Changes to the payment need the right to see entries. You can prepare them; someone with that right publishes them.', 'funnelforms-pro' ) } : null } { payment ? ( <> { gaps.includes( 'connection' ) ? { __( 'Choose the account that receives the payments.', 'funnelforms-pro' ) } : null } set( ( p ) => void ( p.connection = v ) ) } onConnection={ ( c ) => setConnections( ( list ) => [ ...list, c ] ) } /> { connections.find( ( c ) => c.ref === payment.connection )?.test ? ( { __( 'This account uses test keys: nobody is charged, and entries mark the payments as test payments. Connect the live keys before the form goes live.', 'funnelforms-pro' ) } ) : null } ( { value: c, label: c } ) ) } onChange={ ( v ) => set( ( p ) => void ( p.currency = v ) ) } /> label={ __( 'Charge', 'funnelforms-pro' ) } value={ payment.mode } options={ [ { value: 'payment', label: __( 'The whole amount', 'funnelforms-pro' ) }, { value: 'deposit', label: __( 'A deposit', 'funnelforms-pro' ) }, ...( 'stripe' === provider || 'subscription' === payment.mode ? [ { value: 'subscription' as const, label: __( 'A subscription', 'funnelforms-pro' ) } ] : [] ), ] } onChange={ ( v ) => set( ( p ) => { p.mode = v; if ( 'deposit' === v ) { p.depositPercent = p.depositPercent ?? 30; } else { delete p.depositPercent; } if ( 'subscription' === v ) { p.interval = p.interval ?? 'month'; } else { delete p.interval; } } ) } /> { 'deposit' === payment.mode ? ( set( ( p ) => void ( p.depositPercent = Math.min( 99, Math.max( 1, Math.round( v ?? 30 ) ) ) ), 'deposit' ) } /> ) : null } { 'subscription' === payment.mode ? ( <> ( { value: f.id, label: text( f.label, locale ) || f.key } ) ) ] } onChange={ ( v ) => set( ( p ) => { if ( v ) { p.emailField = v; } else { delete p.emailField; } } ) } /> ) : null } { contacts.length > 1 || payment.node ? (