/** * "Calculations": prices, scores and other numbers computed from the answers, in the settings of * the form. Formulas are typed as text ([key] for a field, functions such as round() or if(), * {id} for another result) with pickers for fields, results and functions, tried out with test * answers right below, and stored as the expression tree; the plugin computes them again on the * server. */ import React, { useRef, useState } from 'react'; import type { CalcFunction, Calculation, Field, FormDocument } from '@funnelforms/form-schema'; import { addCalculation, addResultRule, calculationUses, formatResult, formulaRefs, formulaVars, nameCalculation, printFormula, readFormula, removeCalculation, removeEdgeOf, renameFieldKey, resultPaths, resultPlaces, setFormula, setOtherwise, setResultRule, showResultIn, testValues, type CalculationUse, type FormulaResult, type ResultOp, type ResultPlace } from '../calculations'; import { findNode, nodeName } from '../document'; import type { Recipe } from '../store'; import { useEnv } from './context'; import { AskAiButton } from './AiForm'; import { fieldTitle } from './describe'; import { __, sprintf } from './i18n'; import { TypeIcon } from './typeIcons'; import { Badge, Button, Field as FieldRow, icons, Notice, Select, TextInput } from './ui'; import { DateTestAnswer, LeadValueToggle, LookupTable, moreFunctionHelp, ResultTexts } from './CalculationsPlus'; /** Field types whose answers count in calculations (Domain\Form\Calculator). */ const NUMERIC = [ 'choice', 'dropdown', 'slider', 'number', 'rating', 'text', 'textarea', 'repeat' ]; /** Field types whose number of answers counts with count([key]). */ const COUNTED = [ 'file', 'signature', 'email', 'phone', 'url', 'date', 'time', 'address', 'booking' ]; function useChange(): ( recipe: Recipe, key?: string ) => void { return useEnv().store.getState().change; } /** Fields a formula can use, one per key (fields may share a key). */ export function formulaFields( doc: FormDocument ): Field[] { const out = new Map(); for ( const node of doc.nodes ) { if ( 'step' !== node.type ) { continue; } for ( const field of node.fields ) { if ( ( NUMERIC.includes( field.type ) || COUNTED.includes( field.type ) ) && ! out.has( field.key ) ) { out.set( field.key, field ); } } } return [ ...out.values() ]; } function parseError( result: Extract ): string { switch ( result.error ) { case 'empty': return __( 'Enter a formula, e.g. [quantity] * 25.', 'funnelforms-pro' ); case 'unexpected': return sprintf( __( 'The formula cannot be read from character %d on. Use numbers, fields in [brackets], + - * / % ^, parentheses and functions.', 'funnelforms-pro' ), result.at + 1 ); case 'parenthesis': return sprintf( __( 'A parenthesis is not closed or not opened (character %d).', 'funnelforms-pro' ), result.at + 1 ); case 'end': return __( 'The formula ends too early.', 'funnelforms-pro' ); case 'function': return sprintf( __( 'There is no function by this name (character %d). Choose one under Functions.', 'funnelforms-pro' ), result.at + 1 ); case 'arguments': return sprintf( __( 'The function at character %d gets too many or too few values. Separate them with a semicolon.', 'funnelforms-pro' ), result.at + 1 ); case 'reference': return sprintf( __( '{%s} is not a calculation of this form.', 'funnelforms-pro' ), result.ref ); case 'cycle': return __( 'The calculations would use each other in a circle. A calculation cannot use itself, not even through another one.', 'funnelforms-pro' ); } } function whereName( use: CalculationUse ): string { const names: Record = { path: __( 'a path', 'funnelforms-pro' ), text: __( 'a text', 'funnelforms-pro' ), result: __( 'a live result', 'funnelforms-pro' ), payment: __( 'the payment', 'funnelforms-pro' ), conversion: __( 'a conversion', 'funnelforms-pro' ), score: __( 'the lead score', 'funnelforms-pro' ), quiz: __( 'the quiz', 'funnelforms-pro' ), calculation: __( 'another calculation', 'funnelforms-pro' ), value: __( 'the lead value', 'funnelforms-pro' ), }; return names[ use ]; } /** The functions as the editor offers them: what to insert and what it does. */ function functionHelp(): Array<{ fn: CalcFunction | 'count'; insert: string; text: string }> { return [ { fn: 'round', insert: 'round(; 2)', text: __( 'Rounds to decimal places: round([price]; 2). With -2 to hundreds.', 'funnelforms-pro' ) }, { fn: 'floor', insert: 'floor()', text: __( 'Rounds down: floor([m2] / 10).', 'funnelforms-pro' ) }, { fn: 'ceil', insert: 'ceil()', text: __( 'Rounds up: ceil([persons] / 4) cars.', 'funnelforms-pro' ) }, { fn: 'min', insert: 'min(; )', text: __( 'The smallest value: min([discount]; 20).', 'funnelforms-pro' ) }, { fn: 'max', insert: 'max(; )', text: __( 'The largest value: max(49; [rooms] * 15) for a minimum price.', 'funnelforms-pro' ) }, { fn: 'if', insert: 'if(; ; )', text: __( 'If, then, else: if([m2] > 100; 0.9; 1). Compare with < <= > >= = !=.', 'funnelforms-pro' ) }, { fn: 'sum', insert: 'sum(; )', text: __( 'Adds up: sum([a]; [b]; [c]).', 'funnelforms-pro' ) }, { fn: 'avg', insert: 'avg(; )', text: __( 'The average: avg([rating1]; [rating2]).', 'funnelforms-pro' ) }, { fn: 'count', insert: 'count()', text: __( 'How many answers a field has: count([extras]) * 15.', 'funnelforms-pro' ) }, { fn: 'abs', insert: 'abs()', text: __( 'The value without its sign.', 'funnelforms-pro' ) }, { fn: 'sqrt', insert: 'sqrt()', text: __( 'The square root: sqrt([area]) for the side of a square.', 'funnelforms-pro' ) }, { fn: 'and', insert: 'and(; )', text: __( '1 when all hold: and([a] > 1; [b] > 1).', 'funnelforms-pro' ) }, { fn: 'or', insert: 'or(; )', text: __( '1 when one of them holds.', 'funnelforms-pro' ) }, { fn: 'not', insert: 'not()', text: __( '1 when it does not hold: not([extras] > 0).', 'funnelforms-pro' ) }, ]; } export function CalculationsSection( { doc }: { doc: FormDocument } ) { const { readOnly } = useEnv(); const change = useChange(); const [ open, setOpen ] = useState( null ); const add = (): void => { let id = ''; change( ( d ) => { id = addCalculation( d, sprintf( __( 'Calculation %d', 'funnelforms-pro' ), d.calculations.length + 1 ) ); } ); setOpen( id ); }; const results = testValues( doc, {} ); return (

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

{ __( 'Compute prices, scores or other numbers from the answers. Show them in steps, on the thank-you page and in mails, use them in paths, for the payment or as lead score.', 'funnelforms-pro' ) }

    { doc.calculations.map( ( calc ) => { const expanded = open === calc.id; const uses = calculationUses( doc, calc.id ); return (
  • { expanded ? (
    ) : null }
  • ); } ) }
{ doc.calculations.length ? (