Skip to content

Beautiful Open-Source Form Builder

Add AI formula generation feature (#1194)

Chirag Chhatralaaee4c97d545a
diff --git a/api/app/Http/Controllers/Forms/AiFormController.php b/api/app/Http/Controllers/Forms/AiFormController.php
index 92dfb3312..5c851da1d 100644
--- a/api/app/Http/Controllers/Forms/AiFormController.php
+++ b/api/app/Http/Controllers/Forms/AiFormController.php
@@ -5,7 +5,9 @@ namespace App\Http\Controllers\Forms;
use App\Http\Controllers\Controller;
use App\Http\Requests\AiGenerateFieldsRequest;
use App\Http\Requests\AiGenerateFormRequest;
+use App\Http\Requests\AiGenerateFormulaRequest;
use App\Models\Forms\AI\AiFormCompletion;
+use Illuminate\Http\Request;
class AiFormController extends Controller
{
@@ -25,14 +27,28 @@ class AiFormController extends Controller
public function show(AiFormCompletion $aiFormCompletion)
{
+ if ($aiFormCompletion->type === AiFormCompletion::TYPE_FORMULA) {
+ abort(404);
+ }
+
if ($aiFormCompletion->ip != request()->ip()) {
return $this->error('You are not authorized to view this AI completion.', 403);
}
- return $this->success([
- 'message' => 'Your data is ready! Feel free to customize it to your needs before publishing.',
- 'ai_form_completion' => $aiFormCompletion,
- ]);
+ return $this->showCompletion($aiFormCompletion);
+ }
+
+ public function showFormula(Request $request, AiFormCompletion $aiFormCompletion)
+ {
+ if (
+ $aiFormCompletion->type !== AiFormCompletion::TYPE_FORMULA
+ || $aiFormCompletion->user_id === null
+ || (int) $aiFormCompletion->user_id !== (int) $request->user()->id
+ ) {
+ abort(404);
+ }
+
+ return $this->showCompletion($aiFormCompletion);
}
public function generateFields(AiGenerateFieldsRequest $request)
@@ -50,4 +66,26 @@ class AiFormController extends Controller
])->id,
]);
}
+
+ public function generateFormula(AiGenerateFormulaRequest $request)
+ {
+ return $this->success([
+ 'message' => 'Generating your formula, please wait...',
+ 'ai_form_completion_id' => AiFormCompletion::create([
+ 'type' => AiFormCompletion::TYPE_FORMULA,
+ 'form_prompt' => $request->input('formula_prompt'),
+ 'context' => $request->input('context', []),
+ 'user_id' => $request->user()->id,
+ 'ip' => $request->ip(),
+ ])->id,
+ ]);
+ }
+
+ private function showCompletion(AiFormCompletion $aiFormCompletion)
+ {
+ return $this->success([
+ 'message' => 'Your data is ready! Feel free to customize it to your needs before publishing.',
+ 'ai_form_completion' => $aiFormCompletion,
+ ]);
+ }
}
diff --git a/api/app/Http/Requests/AiGenerateFormulaRequest.php b/api/app/Http/Requests/AiGenerateFormulaRequest.php
new file mode 100644
index 000000000..97f9ea3b6
--- /dev/null
+++ b/api/app/Http/Requests/AiGenerateFormulaRequest.php
@@ -0,0 +1,21 @@
+<?php
+
+namespace App\Http\Requests;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+class AiGenerateFormulaRequest extends FormRequest
+{
+ public function rules(): array
+ {
+ return [
+ 'formula_prompt' => 'required|string|max:10000',
+ 'context' => 'nullable|array',
+ 'context.fields' => 'nullable|array',
+ 'context.computed_variables' => 'nullable|array',
+ 'context.current_formula' => 'nullable|string|max:10000',
+ 'context.current_variable' => 'nullable|array',
+ 'context.current_variable.name' => 'nullable|string|max:255',
+ ];
+ }
+}
diff --git a/api/app/Jobs/Form/GenerateAiFormula.php b/api/app/Jobs/Form/GenerateAiFormula.php
new file mode 100644
index 000000000..f5338f742
--- /dev/null
+++ b/api/app/Jobs/Form/GenerateAiFormula.php
@@ -0,0 +1,67 @@
+<?php
+
+namespace App\Jobs\Form;
+
+use App\Models\Forms\AI\AiFormCompletion;
+use App\Service\AI\Prompts\Form\GenerateFormulaPrompt;
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
+
+class GenerateAiFormula implements ShouldQueue
+{
+ use Dispatchable;
+ use InteractsWithQueue;
+ use Queueable;
+ use SerializesModels;
+
+ public function __construct(public AiFormCompletion $completion)
+ {
+ }
+
+ public function handle(): void
+ {
+ $this->completion->update([
+ 'status' => AiFormCompletion::STATUS_PROCESSING,
+ ]);
+
+ try {
+ $context = $this->completion->context ?? [];
+ $fields = $context['fields'] ?? [];
+ $computedVariables = $context['computed_variables'] ?? [];
+ $currentFormula = $context['current_formula'] ?? null;
+ $currentVariable = $context['current_variable'] ?? [];
+ $currentVariableName = is_array($currentVariable) ? ($currentVariable['name'] ?? null) : null;
+
+ $result = GenerateFormulaPrompt::run(
+ $this->completion->form_prompt,
+ $fields,
+ $computedVariables,
+ $currentFormula,
+ $currentVariableName,
+ );
+
+ $this->completion->update([
+ 'status' => AiFormCompletion::STATUS_COMPLETED,
+ 'result' => json_encode($result),
+ ]);
+ } catch (\Exception $e) {
+ $this->onError($e);
+ }
+ }
+
+ public function failed(\Throwable $exception): void
+ {
+ $this->onError($exception);
+ }
+
+ private function onError(\Throwable $e): void
+ {
+ $this->completion->update([
+ 'status' => AiFormCompletion::STATUS_FAILED,
+ 'error' => $e->getMessage(),
+ ]);
+ }
+}
diff --git a/api/app/Models/Forms/AI/AiFormCompletion.php b/api/app/Models/Forms/AI/AiFormCompletion.php
index b3f7929f4..4c6b04241 100644
--- a/api/app/Models/Forms/AI/AiFormCompletion.php
+++ b/api/app/Models/Forms/AI/AiFormCompletion.php
@@ -4,8 +4,11 @@ namespace App\Models\Forms\AI;
use App\Jobs\Form\GenerateAiForm;
use App\Jobs\Form\GenerateAiFormFields;
+use App\Jobs\Form\GenerateAiFormula;
+use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
class AiFormCompletion extends Model
{
@@ -18,11 +21,13 @@ class AiFormCompletion extends Model
public const TYPE_FORM = 'form';
public const TYPE_FIELDS = 'fields';
+ public const TYPE_FORMULA = 'formula';
protected $table = 'ai_form_completions';
protected $fillable = [
'form_prompt',
+ 'user_id',
'status',
'result',
'ip',
@@ -45,6 +50,11 @@ class AiFormCompletion extends Model
];
}
+ public function user(): BelongsTo
+ {
+ return $this->belongsTo(User::class);
+ }
+
protected static function booted()
{
// Dispatch completion job on creation
@@ -53,6 +63,8 @@ class AiFormCompletion extends Model
GenerateAIForm::dispatch($completion);
} elseif ($completion->type === self::TYPE_FIELDS) {
GenerateAiFormFields::dispatch($completion);
+ } elseif ($completion->type === self::TYPE_FORMULA) {
+ GenerateAiFormula::dispatch($completion);
}
});
}
diff --git a/api/app/Providers/RouteServiceProvider.php b/api/app/Providers/RouteServiceProvider.php
index 5c04774e1..26952e914 100644
--- a/api/app/Providers/RouteServiceProvider.php
+++ b/api/app/Providers/RouteServiceProvider.php
@@ -84,6 +84,17 @@ class RouteServiceProvider extends ServiceProvider
return Limit::perMinute(180)->by($request->user()?->id ?: $request->ip());
});
+ RateLimiter::for('ai-formula-generation', function (Request $request) {
+ $identifier = $request->user()
+ ? 'user:' . $request->user()->getAuthIdentifier()
+ : 'ip:' . $request->ip();
+
+ return [
+ Limit::perMinute(10)->by('ai-formula-generation:minute:' . $identifier),
+ Limit::perHour(100)->by('ai-formula-generation:hour:' . $identifier),
+ ];
+ });
+
RateLimiter::for('public-uploads', function (Request $request) {
$identifier = $request->user()
? 'user:' . $request->user()->getAuthIdentifier()
diff --git a/api/app/Service/AI/Prompts/Form/GenerateFormulaPrompt.php b/api/app/Service/AI/Prompts/Form/GenerateFormulaPrompt.php
new file mode 100644
index 000000000..d04d87eb0
--- /dev/null
+++ b/api/app/Service/AI/Prompts/Form/GenerateFormulaPrompt.php
@@ -0,0 +1,312 @@
+<?php
+
+namespace App\Service\AI\Prompts\Form;
+
+use App\Service\AI\Prompts\Prompt;
+use App\Service\Formulas\Functions\FunctionRegistry;
+use App\Service\Formulas\Parser;
+use App\Service\Formulas\Validator;
+
+class GenerateFormulaPrompt extends Prompt
+{
+ protected ?float $temperature = 0.3;
+
+ protected ?int $maxTokens = 1024;
+
+ protected string $model = 'gpt-5.4-mini';
+
+ public const PROMPT_TEMPLATE = <<<'EOD'
+ Generate a formula for a computed variable based on the user's requirement.
+
+ <requirement>
+ {formulaPrompt}
+ </requirement>
+
+ <available_fields>
+ {availableFields}
+ </available_fields>
+
+ <available_computed_variables>
+ {availableVariables}
+ </available_computed_variables>
+
+ <current_formula>
+ {currentFormulaContext}
+ </current_formula>
+
+ <critical_rules>
+ - ONLY reference fields and variables from the lists above — never invent field names
+ - Every dynamic value MUST be wrapped in curly braces as a mention: {Field Name}
+ - When a current formula is provided, modify it according to the requirement and preserve its intent unless the user asks to replace it
+ - When no current variable name is provided, generate a concise, descriptive variable name (2 to 5 words)
+ - The formula MUST be syntactically valid:
+ * Every opening parenthesis "(" must have a matching closing ")"
+ * Function calls always end with a closing parenthesis, e.g. IF(cond, a, b)
+ * Commas separate function arguments inside the parentheses
+ * No trailing commas or missing arguments
+ - Double-check parentheses balance before responding
+ </critical_rules>
+
+ <formula_syntax>
+ - Field mentions: {Field Name} — must match an available field exactly
+ - Variable mentions: {Variable Name} — must match an available computed variable exactly
+ - Operators: +, -, *, /
+ - Comparisons: =, <>, <, >, <=, >=
+ - Functions: FUNCTION_NAME(arg1, arg2, ...)
+ - Strings: "hello" (double quotes only)
+ - Booleans: TRUE, FALSE
+ - Numbers: 42, 3.14, 0.9
+ </formula_syntax>
+
+ <available_functions>
+ {availableFunctions}
+ </available_functions>
+
+ <examples>
+ - Multiply price by quantity: {Price} * {Quantity}
+ - 10% discount for bulk: IF({Quantity} > 100, {Price} * {Quantity} * 0.9, {Price} * {Quantity})
+ - Full name: CONCAT({First Name}, " ", {Last Name})
+ - Null-safe total: IFBLANK({Price}, 0) * IFBLANK({Quantity}, 1)
+ - Nested IF: IF({Score} > 90, "A", IF({Score} > 80, "B", "C"))
+ </examples>
+
+ Return a JSON object with the formula and variable_name. Set variable_name to null when a current variable name is already provided.
+ EOD;
+
+ protected ?array $jsonSchema = [
+ 'type' => 'object',
+ 'required' => ['formula', 'variable_name'],
+ 'additionalProperties' => false,
+ 'properties' => [
+ 'formula' => [
+ 'type' => 'string',
+ 'description' => 'The generated formula using field/variable names in curly braces',
+ ],
+ 'variable_name' => [
+ 'type' => ['string', 'null'],
+ 'description' => 'A concise name for a new computed variable, or null when it already has a name',
+ ],
+ ],
+ ];
+
+ public function __construct(
+ public string $formulaPrompt,
+ public array $fields = [],
+ public array $computedVariables = [],
+ public ?string $currentFormula = null,
+ public ?string $currentVariableName = null,
+ ) {
+ parent::__construct();
+ }
+
+ protected function getSystemMessage(): ?string
+ {
+ return 'You are an AI assistant specialized in generating formulas for OpnForm computed variables. You only output syntactically valid formulas. Every field reference uses curly-brace mentions. Always ensure parentheses are balanced and function calls are complete.';
+ }
+
+ protected function getPromptTemplate(): string
+ {
+ return self::PROMPT_TEMPLATE;
+ }
+
+ public function execute(): array
+ {
+ $maxAttempts = 3;
+ $lastError = null;
+
+ for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
+ $result = parent::execute();
+ $formula = trim($result['formula'] ?? '');
+ $variableName = blank($this->currentVariableName)
+ ? trim($result['variable_name'] ?? '')
+ : null;
+
+ // Strip markdown code fences if AI wraps the formula
+ $formula = preg_replace('/^```[a-z]*\s*/i', '', $formula);
+ $formula = preg_replace('/\s*```$/', '', $formula);
+ $formula = trim($formula);
+
+ if ($formula === '') {
+ $lastError = 'AI returned an empty formula.';
+ continue;
+ }
+
+ // Convert field names to IDs for validation
+ $storageFormula = $this->convertMentionsToIds($formula);
+
+ // Validate syntax via Parser
+ try {
+ Parser::parse($storageFormula);
+ } catch (\Throwable $e) {
+ $lastError = "Syntax error: {$e->getMessage()}";
+ continue;
+ }
+
+ // Validate field references
+ $validator = new Validator([
+ 'availableFields' => $this->buildValidatorFields(),
+ 'availableVariables' => $this->buildValidatorVariables(),
+ ]);
+ $validationResult = $validator->validate($storageFormula);
+
+ if (! $validationResult->valid) {
+ $lastError = $validationResult->errors[0]['message'] ?? 'Invalid formula';
+ continue;
+ }
+
+ return [
+ 'formula' => $storageFormula,
+ 'variable_name' => $variableName ?: null,
+ ];
+ }
+
+ throw new \RuntimeException("Failed to generate a valid formula after {$maxAttempts} attempts. Last error: {$lastError}");
+ }
+
+ protected function getPromptVariables(): array
+ {
+ $variables = parent::getPromptVariables();
+ $variables['{availableFields}'] = $this->formatFields();
+ $variables['{availableVariables}'] = $this->formatComputedVariables();
+ $variables['{currentFormulaContext}'] = $this->formatCurrentFormula();
+ $variables['{availableFunctions}'] = $this->formatFunctions();
+
+ return $variables;
+ }
+
+ private function convertMentionsToIds(string $formula): string
+ {
+ $nameToId = [];
+
+ foreach ($this->fields as $field) {
+ if (! empty($field['name']) && ! empty($field['id'])) {
+ $nameToId[strtolower($field['name'])] = $field['id'];
+ }
+ }
+
+ foreach ($this->computedVariables as $variable) {
+ if (! empty($variable['name']) && ! empty($variable['id'])) {
+ $nameToId[strtolower($variable['name'])] = $variable['id'];
+ }
+ }
+
+ if (empty($nameToId)) {
+ return $formula;
+ }
+
+ return preg_replace_callback('/\{([^}]+)\}/', function (array $matches) use ($nameToId) {
+ $name = trim($matches[1]);
+ $id = $nameToId[strtolower($name)] ?? null;
+
+ return '{' . ($id ?? $name) . '}';
+ }, $formula);
+ }
+
+ private function buildValidatorFields(): array
+ {
+ return array_map(fn ($f) => [
+ 'id' => $f['id'] ?? $f['name'] ?? '',
+ 'name' => $f['name'] ?? '',
+ 'type' => $f['type'] ?? 'text',
+ ], $this->fields);
+ }
+
+ private function buildValidatorVariables(): array
+ {
+ return array_map(fn ($v) => [
+ 'id' => $v['id'] ?? $v['name'] ?? '',
+ 'name' => $v['name'] ?? '',
+ ], $this->computedVariables);
+ }
+
+ private function formatFields(): string
+ {
+ if (empty($this->fields)) {
+ return 'No form fields available';
+ }
+
+ $lines = ['Use these exact mentions in the formula:'];
+ foreach ($this->fields as $field) {
+ $name = $field['name'] ?? 'Unnamed field';
+ $type = $field['type'] ?? 'unknown';
+ $lines[] = "- {" . $name . "} (type: {$type})";
+ }
+
+ return implode("\n", $lines);
+ }
+
+ private function formatComputedVariables(): string
+ {
+ if (empty($this->computedVariables)) {
+ return 'No other computed variables available';
+ }
+
+ $lines = ['Use these exact mentions in the formula:'];
+ foreach ($this->computedVariables as $variable) {
+ $name = $variable['name'] ?? 'Unnamed variable';
+ $lines[] = "- {" . $name . "}";
+ }
+
+ return implode("\n", $lines);
+ }
+
+ private function formatCurrentFormula(): string
+ {
+ if (blank($this->currentFormula)) {
+ return 'No current formula is available. Generate a new formula.';
+ }
+
+ $variableName = filled($this->currentVariableName)
+ ? " for the variable \"{$this->currentVariableName}\""
+ : '';
+
+ return "Current formula{$variableName}:\n{$this->currentFormula}";
+ }
+
+ private function formatFunctions(): string
+ {
+ $signatures = [
+ 'SUM(value1, value2, ...)' => 'Adds numbers together',
+ 'AVERAGE(value1, value2, ...)' => 'Returns the arithmetic mean',
+ 'MIN(value1, value2, ...)' => 'Returns the smallest value',
+ 'MAX(value1, value2, ...)' => 'Returns the largest value',
+ 'ROUND(number, decimals?)' => 'Rounds to decimal places',
+ 'FLOOR(number)' => 'Rounds down to integer',
+ 'CEIL(number)' => 'Rounds up to integer',
+ 'ABS(number)' => 'Absolute value',
+ 'MOD(number, divisor)' => 'Remainder after division',
+ 'POWER(base, exponent)' => 'Raises to a power',
+ 'SQRT(number)' => 'Square root',
+ 'CONCAT(text1, text2, ...)' => 'Joins text strings',
+ 'UPPER(text)' => 'Uppercase text',
+ 'LOWER(text)' => 'Lowercase text',
+ 'TRIM(text)' => 'Removes leading/trailing spaces',
+ 'LEFT(text, count)' => 'Leftmost characters',
+ 'RIGHT(text, count)' => 'Rightmost characters',
+ 'MID(text, start, count)' => 'Substring',
+ 'LEN(text)' => 'Text length',
+ 'IF(condition, trueValue, falseValue)' => 'Conditional',
+ 'AND(...)' => 'All conditions true',
+ 'OR(...)' => 'Any condition true',
+ 'NOT(value)' => 'Logical negation',
+ 'ISBLANK(value)' => 'True if blank',
+ 'IFBLANK(value, default)' => 'Returns default if blank',
+ 'COALESCE(value1, value2, ...)' => 'First non-blank value',
+ 'COUNT(value)' => 'Count items in multi-select',
+ 'CONTAINS(array, value)' => 'True if array contains value',
+ 'JOIN(array, separator)' => 'Join array into text',
+ ];
+
+ $available = array_flip(array_map('strtoupper', FunctionRegistry::getAll()));
+ $lines = [];
+
+ foreach ($signatures as $signature => $description) {
+ $name = strtoupper(strtok($signature, '('));
+ if (isset($available[$name])) {
+ $lines[] = "- {$signature}: {$description}";
+ }
+ }
+
+ return implode("\n", $lines);
+ }
+}
diff --git a/api/app/Service/Formulas/Validator.php b/api/app/Service/Formulas/Validator.php
index 4808a9196..d37e71de3 100644
--- a/api/app/Service/Formulas/Validator.php
+++ b/api/app/Service/Formulas/Validator.php
@@ -6,6 +6,59 @@ use App\Service\Formulas\Functions\FunctionRegistry;
class Validator
{
+ private const FUNCTION_ARGUMENTS = [
+ // Math functions
+ 'SUM' => ['min' => 1],
+ 'AVERAGE' => ['min' => 1],
+ 'MIN' => ['min' => 1],
+ 'MAX' => ['min' => 1],
+ 'ROUND' => ['min' => 1, 'max' => 2],
+ 'FLOOR' => ['min' => 1, 'max' => 1],
+ 'CEIL' => ['min' => 1, 'max' => 1],
+ 'ABS' => ['min' => 1, 'max' => 1],
+ 'MOD' => ['min' => 2, 'max' => 2],
+ 'POWER' => ['min' => 2, 'max' => 2],
+ 'SQRT' => ['min' => 1, 'max' => 1],
+
+ // Text functions
+ 'CONCAT' => ['min' => 1],
+ 'UPPER' => ['min' => 1, 'max' => 1],
+ 'LOWER' => ['min' => 1, 'max' => 1],
+ 'TRIM' => ['min' => 1, 'max' => 1],
+ 'LEFT' => ['min' => 2, 'max' => 2],
+ 'RIGHT' => ['min' => 2, 'max' => 2],
+ 'MID' => ['min' => 3, 'max' => 3],
+ 'LEN' => ['min' => 1, 'max' => 1],
+ 'SUBSTITUTE' => ['min' => 3, 'max' => 4],
+ 'REPLACE' => ['min' => 4, 'max' => 4],
+ 'FIND' => ['min' => 2, 'max' => 3],
+ 'SEARCH' => ['min' => 2, 'max' => 3],
+ 'REPT' => ['min' => 2, 'max' => 2],
+ 'TEXT' => ['min' => 2, 'max' => 2],
+
+ // Logic functions
+ 'IF' => ['min' => 2, 'max' => 3],
+ 'AND' => ['min' => 1],
+ 'OR' => ['min' => 1],
+ 'NOT' => ['min' => 1, 'max' => 1],
+ 'XOR' => ['min' => 2],
+ 'ISBLANK' => ['min' => 1, 'max' => 1],
+ 'ISNUMBER' => ['min' => 1, 'max' => 1],
+ 'ISTEXT' => ['min' => 1, 'max' => 1],
+ 'IFERROR' => ['min' => 2, 'max' => 2],
+ 'IFBLANK' => ['min' => 2, 'max' => 2],
+ 'COALESCE' => ['min' => 1],
+ 'SWITCH' => ['min' => 3],
+ 'IFS' => ['min' => 2],
+ 'CHOOSE' => ['min' => 2],
+
+ // Array functions
+ 'COUNT' => ['min' => 1, 'max' => 1],
+ 'ISEMPTY' => ['min' => 1, 'max' => 1],
+ 'CONTAINS' => ['min' => 2, 'max' => 2],
+ 'JOIN' => ['min' => 1, 'max' => 2],
+ ];
+
private array $availableFields;
private array $availableVariables;
private ?string $currentVariableId;
@@ -95,6 +148,30 @@ class Validator
return;
}
+ $requirements = self::FUNCTION_ARGUMENTS[$funcName] ?? null;
+ $argumentCount = count($node['args']);
+
+ if ($requirements !== null && isset($requirements['min']) && $argumentCount < $requirements['min']) {
+ $minimum = $requirements['min'];
+ $argumentLabel = $minimum === 1 ? 'argument' : 'arguments';
+
+ if (($requirements['max'] ?? null) === $minimum) {
+ $result->addError("Function {$funcName}() requires exactly {$minimum} {$argumentLabel}, but got {$argumentCount}.");
+ } else {
+ $result->addError("Function {$funcName}() requires at least {$minimum} {$argumentLabel}, but got {$argumentCount}.");
+ }
+
+ return;
+ }
+
+ if ($requirements !== null && isset($requirements['max']) && $argumentCount > $requirements['max']) {
+ $maximum = $requirements['max'];
+ $argumentLabel = $maximum === 1 ? 'argument' : 'arguments';
+ $result->addError("Function {$funcName}() accepts at most {$maximum} {$argumentLabel}, but got {$argumentCount}.");
+
+ return;
+ }
+
// Validate function arguments
foreach ($node['args'] as $arg) {
$this->validateNode($arg, $result);
diff --git a/api/database/migrations/2026_07_07_072800_add_formula_type_to_ai_form_completions_table.php b/api/database/migrations/2026_07_07_072800_add_formula_type_to_ai_form_completions_table.php
new file mode 100644
index 000000000..89e7d35a5
--- /dev/null
+++ b/api/database/migrations/2026_07_07_072800_add_formula_type_to_ai_form_completions_table.php
@@ -0,0 +1,40 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ public function up(): void
+ {
+ $driver = DB::getDriverName();
+
+ if ($driver === 'mysql') {
+ Schema::table('ai_form_completions', function (Blueprint $table) {
+ $table->enum('type', ['form', 'fields', 'formula'])->default('form')->change();
+ });
+ } elseif ($driver === 'pgsql') {
+ DB::statement('ALTER TABLE ai_form_completions DROP CONSTRAINT ai_form_completions_type_check');
+ DB::statement("ALTER TABLE ai_form_completions ADD CONSTRAINT ai_form_completions_type_check CHECK (type::text = ANY (ARRAY['form'::text, 'fields'::text, 'formula'::text]))");
+ } else {
+ Schema::table('ai_form_completions', function (Blueprint $table) {
+ $table->string('type')->default('form')->change();
+ });
+ }
+ }
+
+ public function down(): void
+ {
+ $driver = DB::getDriverName();
+
+ if ($driver === 'mysql') {
+ Schema::table('ai_form_completions', function (Blueprint $table) {
+ $table->enum('type', ['form', 'fields'])->default('form')->change();
+ });
+ } elseif ($driver === 'pgsql') {
+ DB::statement('ALTER TABLE ai_form_completions DROP CONSTRAINT ai_form_completions_type_check');
+ DB::statement("ALTER TABLE ai_form_completions ADD CONSTRAINT ai_form_completions_type_check CHECK (type::text = ANY (ARRAY['form'::text, 'fields'::text]))");
+ }
+ }
+};
diff --git a/api/database/migrations/2026_07_15_110000_add_user_id_to_ai_form_completions_table.php b/api/database/migrations/2026_07_15_110000_add_user_id_to_ai_form_completions_table.php
new file mode 100644
index 000000000..a70d42e29
--- /dev/null
+++ b/api/database/migrations/2026_07_15_110000_add_user_id_to_ai_form_completions_table.php
@@ -0,0 +1,22 @@
+<?php
+
+use App\Models\User;
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ public function up(): void
+ {
+ Schema::table('ai_form_completions', function (Blueprint $table) {
+ $table->foreignIdFor(User::class)->nullable()->constrained()->cascadeOnDelete();
+ });
+ }
+
+ public function down(): void
+ {
+ Schema::table('ai_form_completions', function (Blueprint $table) {
+ $table->dropConstrainedForeignId('user_id');
+ });
+ }
+};
diff --git a/api/routes/api.php b/api/routes/api.php
index 6bee33d74..634fd7a24 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -463,8 +463,14 @@ Route::prefix('forms')->name('forms.')->group(function () {
// AI
Route::post('ai/generate', [\App\Http\Controllers\Forms\AiFormController::class, 'generateForm'])->name('ai.generate');
+ Route::get('ai/formula/{aiFormCompletion}', [\App\Http\Controllers\Forms\AiFormController::class, 'showFormula'])
+ ->middleware('auth.multi')
+ ->name('ai.formula.show');
Route::get('ai/{aiFormCompletion}', [\App\Http\Controllers\Forms\AiFormController::class, 'show'])->name('ai.show');
Route::post('ai/generate-fields', [\App\Http\Controllers\Forms\AiFormController::class, 'generateFields'])->name('ai.generate-fields');
+ Route::post('ai/generate-formula', [\App\Http\Controllers\Forms\AiFormController::class, 'generateFormula'])
+ ->middleware(['auth.multi', 'throttle:ai-formula-generation'])
+ ->name('ai.generate-formula');
});
/**
diff --git a/api/tests/Feature/Forms/AiFormulaGenerationTest.php b/api/tests/Feature/Forms/AiFormulaGenerationTest.php
new file mode 100644
index 000000000..47ef537c6
--- /dev/null
+++ b/api/tests/Feature/Forms/AiFormulaGenerationTest.php
@@ -0,0 +1,655 @@
+<?php
+
+use App\Jobs\Form\GenerateAiFormula;
+use App\Models\Forms\AI\AiFormCompletion;
+use App\Service\AI\Prompts\Form\GenerateFormulaPrompt;
+use App\Service\OpenAi\GptCompleter;
+use Illuminate\Routing\Middleware\ThrottleRequests;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Queue;
+
+$testFields = [
+ ['id' => 'uuid-price', 'name' => 'Price', 'type' => 'number'],
+ ['id' => 'uuid-quantity', 'name' => 'Quantity', 'type' => 'number'],
+ ['id' => 'uuid-name', 'name' => 'Full Name', 'type' => 'text'],
+];
+
+$testVariables = [
+ ['id' => 'uuid-subtotal', 'name' => 'Subtotal'],
+];
+
+beforeEach(function () {
+ config()->set('services.openai.api_key', 'test-fake-key');
+});
+
+describe('AI Formula Generation', function () use ($testFields, $testVariables) {
+
+ describe('API endpoint POST /forms/ai/generate-formula', function () {
+ beforeEach(function () {
+ Queue::fake();
+ });
+
+ it('requires authentication', function () {
+ $this->postJson(route('forms.ai.generate-formula'), [
+ 'formula_prompt' => 'Multiply price by quantity',
+ ])->assertUnauthorized();
+ });
+
+ it('creates an ai_form_completion with formula type', function () {
+ $user = $this->actingAsUser();
+
+ $response = $this->postJson(route('forms.ai.generate-formula'), [
+ 'formula_prompt' => 'Multiply price by quantity',
+ 'context' => [
+ 'fields' => [
+ ['id' => 'uuid-1', 'name' => 'Price', 'type' => 'number'],
+ ['id' => 'uuid-2', 'name' => 'Quantity', 'type' => 'number'],
+ ],
+ 'computed_variables' => [],
+ ],
+ ]);
+
+ $response->assertSuccessful()
+ ->assertJsonStructure(['type', 'message', 'ai_form_completion_id']);
+
+ $completionId = $response->json('ai_form_completion_id');
+ $this->assertDatabaseHas('ai_form_completions', [
+ 'id' => $completionId,
+ 'type' => 'formula',
+ 'form_prompt' => 'Multiply price by quantity',
+ 'user_id' => $user->id,
+ ]);
+ });
+
+ it('validates formula_prompt is required', function () {
+ $this->actingAsUser();
+
+ $response = $this->postJson(route('forms.ai.generate-formula'), [
+ 'context' => ['fields' => []],
+ ]);
+
+ $response->assertStatus(422)
+ ->assertJsonValidationErrors(['formula_prompt']);
+ });
+
+ it('validates formula_prompt max length', function () {
+ $this->actingAsUser();
+
+ $response = $this->postJson(route('forms.ai.generate-formula'), [
+ 'formula_prompt' => str_repeat('a', 10001),
+ 'context' => ['fields' => []],
+ ]);
+
+ $response->assertStatus(422)
+ ->assertJsonValidationErrors(['formula_prompt']);
+ });
+
+ it('stores context with field and variable data', function () {
+ $this->actingAsUser();
+
+ $context = [
+ 'fields' => [
+ ['id' => 'f1', 'name' => 'Name', 'type' => 'text'],
+ ['id' => 'f2', 'name' => 'Email', 'type' => 'email'],
+ ],
+ 'computed_variables' => [
+ ['id' => 'v1', 'name' => 'Full Info'],
+ ],
+ ];
+
+ $response = $this->postJson(route('forms.ai.generate-formula'), [
+ 'formula_prompt' => 'Concatenate name and email',
+ 'context' => $context,
+ ]);
+
+ $response->assertSuccessful();
+
+ $completion = AiFormCompletion::find($response->json('ai_form_completion_id'));
+ expect($completion->context)->toBe($context);
+ expect($completion->type)->toBe('formula');
+ });
+
+ it('stores the existing formula context when updating a formula', function () {
+ $this->actingAsUser();
+
+ $context = [
+ 'fields' => [],
+ 'computed_variables' => [],
+ 'current_formula' => '{Price} * {Quantity}',
+ 'current_variable' => ['name' => 'Total Price'],
+ ];
+
+ $response = $this->postJson(route('forms.ai.generate-formula'), [
+ 'formula_prompt' => 'Apply a 10% discount',
+ 'context' => $context,
+ ]);
+
+ $response->assertSuccessful();
+
+ $completion = AiFormCompletion::find($response->json('ai_form_completion_id'));
+ expect($completion->context)->toBe($context);
+ });
+
+ it('accepts request without context', function () {
+ $this->actingAsUser();
+
+ $response = $this->postJson(route('forms.ai.generate-formula'), [
+ 'formula_prompt' => 'Add 1 + 1',
+ ]);
+
+ $response->assertSuccessful();
+ });
+
+ it('throttles formula generation to ten requests per minute', function () {
+ $this->withMiddleware(ThrottleRequests::class);
+ $this->actingAsUser();
+ Cache::flush();
+
+ for ($attempt = 0; $attempt < 10; $attempt++) {
+ $this->postJson(route('forms.ai.generate-formula'), [
+ 'formula_prompt' => "Add {$attempt} + 1",
+ ])->assertSuccessful();
+ }
+
+ $this->postJson(route('forms.ai.generate-formula'), [
+ 'formula_prompt' => 'This request should be throttled',
+ ])->assertStatus(429);
+ });
+
+ it('uses the dedicated formula generation rate limiter', function () {
+ $route = app('router')->getRoutes()->getByName('forms.ai.generate-formula');
+
+ expect($route->middleware())
+ ->toContain('throttle:ai-formula-generation');
+ });
+ });
+
+ describe('Job dispatch', function () {
+ it('dispatches GenerateAiFormula when formula completion is created', function () {
+ Queue::fake();
+
+ AiFormCompletion::create([
+ 'type' => AiFormCompletion::TYPE_FORMULA,
+ 'form_prompt' => 'Sum two numbers',
+ 'context' => ['fields' => [], 'computed_variables' => []],
+ 'ip' => '127.0.0.1',
+ ]);
+
+ Queue::assertPushed(GenerateAiFormula::class);
+ });
+
+ it('does not dispatch GenerateAiFormula for form type', function () {
+ Queue::fake();
+
+ AiFormCompletion::create([
+ 'type' => AiFormCompletion::TYPE_FORM,
+ 'form_prompt' => 'Create a contact form',
+ 'ip' => '127.0.0.1',
+ ]);
+
+ Queue::assertNotPushed(GenerateAiFormula::class);
+ });
+
+ it('does not dispatch GenerateAiFormula for fields type', function () {
+ Queue::fake();
+
+ AiFormCompletion::create([
+ 'type' => AiFormCompletion::TYPE_FIELDS,
+ 'form_prompt' => 'Add an email field',
+ 'ip' => '127.0.0.1',
+ ]);
+
+ Queue::assertNotPushed(GenerateAiFormula::class);
+ });
+ });
+
+ describe('GenerateFormulaPrompt - mention conversion', function () use ($testFields, $testVariables) {
+ it('converts field name mentions to IDs', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $method = new ReflectionMethod($prompt, 'convertMentionsToIds');
+ $method->setAccessible(true);
+
+ $result = $method->invoke($prompt, '{Price} * {Quantity}');
+ expect($result)->toBe('{uuid-price} * {uuid-quantity}');
+ });
+
+ it('converts case-insensitively', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $method = new ReflectionMethod($prompt, 'convertMentionsToIds');
+ $method->setAccessible(true);
+
+ $result = $method->invoke($prompt, '{price} * {QUANTITY}');
+ expect($result)->toBe('{uuid-price} * {uuid-quantity}');
+ });
+
+ it('converts variable mentions to IDs', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $method = new ReflectionMethod($prompt, 'convertMentionsToIds');
+ $method->setAccessible(true);
+
+ $result = $method->invoke($prompt, '{Subtotal} * 1.1');
+ expect($result)->toBe('{uuid-subtotal} * 1.1');
+ });
+
+ it('leaves unknown mentions unchanged', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $method = new ReflectionMethod($prompt, 'convertMentionsToIds');
+ $method->setAccessible(true);
+
+ $result = $method->invoke($prompt, '{Unknown} + {Price}');
+ expect($result)->toBe('{Unknown} + {uuid-price}');
+ });
+
+ it('handles formula with no mentions', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $method = new ReflectionMethod($prompt, 'convertMentionsToIds');
+ $method->setAccessible(true);
+
+ $result = $method->invoke($prompt, '1 + 2 * 3');
+ expect($result)->toBe('1 + 2 * 3');
+ });
+
+ it('handles field names with spaces', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $method = new ReflectionMethod($prompt, 'convertMentionsToIds');
+ $method->setAccessible(true);
+
+ $result = $method->invoke($prompt, 'UPPER({Full Name})');
+ expect($result)->toBe('UPPER({uuid-name})');
+ });
+ });
+
+ describe('GenerateFormulaPrompt - prompt formatting', function () use ($testFields, $testVariables) {
+ it('formats fields as mentions with types', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $method = new ReflectionMethod($prompt, 'formatFields');
+ $method->setAccessible(true);
+
+ $result = $method->invoke($prompt);
+ expect($result)->toContain('{Price} (type: number)');
+ expect($result)->toContain('{Quantity} (type: number)');
+ expect($result)->toContain('{Full Name} (type: text)');
+ expect($result)->toContain('Use these exact mentions');
+ });
+
+ it('formats computed variables as mentions', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $method = new ReflectionMethod($prompt, 'formatComputedVariables');
+ $method->setAccessible(true);
+
+ $result = $method->invoke($prompt);
+ expect($result)->toContain('{Subtotal}');
+ expect($result)->toContain('Use these exact mentions');
+ });
+
+ it('returns fallback text for empty fields', function () use ($testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', [], $testVariables);
+
+ $method = new ReflectionMethod($prompt, 'formatFields');
+ $method->setAccessible(true);
+
+ expect($method->invoke($prompt))->toBe('No form fields available');
+ });
+
+ it('returns fallback text for empty variables', function () use ($testFields) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, []);
+
+ $method = new ReflectionMethod($prompt, 'formatComputedVariables');
+ $method->setAccessible(true);
+
+ expect($method->invoke($prompt))->toBe('No other computed variables available');
+ });
+
+ it('includes the current formula when updating a computed variable', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt(
+ 'Apply a discount',
+ $testFields,
+ $testVariables,
+ '{Price} * {Quantity}',
+ 'Total Price',
+ );
+
+ $method = new ReflectionMethod($prompt, 'formatCurrentFormula');
+ $method->setAccessible(true);
+
+ expect($method->invoke($prompt))
+ ->toContain('Current formula for the variable "Total Price"')
+ ->toContain('{Price} * {Quantity}');
+ });
+
+ it('lists available functions', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $method = new ReflectionMethod($prompt, 'formatFunctions');
+ $method->setAccessible(true);
+
+ $result = $method->invoke($prompt);
+ expect($result)->toContain('IF(condition, trueValue, falseValue)');
+ expect($result)->toContain('SUM(value1, value2, ...)');
+ expect($result)->toContain('CONCAT(text1, text2, ...)');
+ });
+ });
+
+ describe('GenerateFormulaPrompt - execute with mocked AI', function () use ($testFields, $testVariables) {
+ it('returns valid formula converted to field IDs', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('multiply price by quantity', $testFields, $testVariables);
+
+ $mockCompleter = Mockery::mock(GptCompleter::class);
+ $mockCompleter->shouldReceive('setJsonSchema')->andReturnSelf();
+ $mockCompleter->shouldReceive('setSystemMessage')->andReturnSelf();
+ $mockCompleter->shouldReceive('completeChat')->andReturnSelf();
+ $mockCompleter->shouldReceive('getArray')->andReturn([
+ 'formula' => '{Price} * {Quantity}',
+ ]);
+
+ $prompt->setGptCompleter($mockCompleter);
+ $result = $prompt->execute();
+
+ expect($result['formula'])->toBe('{uuid-price} * {uuid-quantity}');
+ });
+
+ it('returns an AI-generated variable name when the variable is unnamed', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('multiply price by quantity', $testFields, $testVariables);
+
+ $mockCompleter = Mockery::mock(GptCompleter::class);
+ $mockCompleter->shouldReceive('setJsonSchema')->andReturnSelf();
+ $mockCompleter->shouldReceive('setSystemMessage')->andReturnSelf();
+ $mockCompleter->shouldReceive('completeChat')->andReturnSelf();
+ $mockCompleter->shouldReceive('getArray')->andReturn([
+ 'formula' => '{Price} * {Quantity}',
+ 'variable_name' => 'Total Price',
+ ]);
+
+ $prompt->setGptCompleter($mockCompleter);
+ $result = $prompt->execute();
+
+ expect($result)
+ ->toMatchArray([
+ 'formula' => '{uuid-price} * {uuid-quantity}',
+ 'variable_name' => 'Total Price',
+ ]);
+ });
+
+ it('does not return a generated variable name when the variable is already named', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('multiply price by quantity', $testFields, $testVariables, null, 'Order Total');
+
+ $mockCompleter = Mockery::mock(GptCompleter::class);
+ $mockCompleter->shouldReceive('setJsonSchema')->andReturnSelf();
+ $mockCompleter->shouldReceive('setSystemMessage')->andReturnSelf();
+ $mockCompleter->shouldReceive('completeChat')->andReturnSelf();
+ $mockCompleter->shouldReceive('getArray')->andReturn([
+ 'formula' => '{Price} * {Quantity}',
+ 'variable_name' => null,
+ ]);
+
+ $prompt->setGptCompleter($mockCompleter);
+ $result = $prompt->execute();
+
+ expect($result['variable_name'])->toBeNull();
+ });
+
+ it('retries on syntax error then returns valid formula', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('discount formula', $testFields, $testVariables);
+
+ $mockCompleter = Mockery::mock(GptCompleter::class);
+ $mockCompleter->shouldReceive('setJsonSchema')->andReturnSelf();
+ $mockCompleter->shouldReceive('setSystemMessage')->andReturnSelf();
+ $mockCompleter->shouldReceive('completeChat')->andReturnSelf();
+ $mockCompleter->shouldReceive('getArray')
+ ->andReturn(
+ ['formula' => 'IF({Price} > 100, {Price} * 0.9, {Price}'],
+ ['formula' => 'IF({Price} > 100, {Price} * 0.9, {Price})'],
+ );
+
+ $prompt->setGptCompleter($mockCompleter);
+ $result = $prompt->execute();
+
+ expect($result['formula'])->toBe('IF({uuid-price} > 100, {uuid-price} * 0.9, {uuid-price})');
+ });
+
+ it('retries on unknown field reference then returns valid formula', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $mockCompleter = Mockery::mock(GptCompleter::class);
+ $mockCompleter->shouldReceive('setJsonSchema')->andReturnSelf();
+ $mockCompleter->shouldReceive('setSystemMessage')->andReturnSelf();
+ $mockCompleter->shouldReceive('completeChat')->andReturnSelf();
+ $mockCompleter->shouldReceive('getArray')
+ ->andReturn(
+ ['formula' => '{Nonexistent} + 1'],
+ ['formula' => '{Price} + 1'],
+ );
+
+ $prompt->setGptCompleter($mockCompleter);
+ $result = $prompt->execute();
+
+ expect($result['formula'])->toBe('{uuid-price} + 1');
+ });
+
+ it('retries on an invalid function argument count then returns a valid formula', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $mockCompleter = Mockery::mock(GptCompleter::class);
+ $mockCompleter->shouldReceive('setJsonSchema')->andReturnSelf();
+ $mockCompleter->shouldReceive('setSystemMessage')->andReturnSelf();
+ $mockCompleter->shouldReceive('completeChat')->andReturnSelf();
+ $mockCompleter->shouldReceive('getArray')
+ ->andReturn(
+ ['formula' => 'MOD({Price})'],
+ ['formula' => 'MOD({Price}, 2)'],
+ );
+
+ $prompt->setGptCompleter($mockCompleter);
+ $result = $prompt->execute();
+
+ expect($result['formula'])->toBe('MOD({uuid-price}, 2)');
+ });
+
+ it('throws RuntimeException after max retries with invalid formulas', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $mockCompleter = Mockery::mock(GptCompleter::class);
+ $mockCompleter->shouldReceive('setJsonSchema')->andReturnSelf();
+ $mockCompleter->shouldReceive('setSystemMessage')->andReturnSelf();
+ $mockCompleter->shouldReceive('completeChat')->andReturnSelf();
+ $mockCompleter->shouldReceive('getArray')
+ ->andReturn(['formula' => 'IF({Price} > 100, {Price}']);
+
+ $prompt->setGptCompleter($mockCompleter);
+
+ expect(fn () => $prompt->execute())
+ ->toThrow(\RuntimeException::class, 'Failed to generate a valid formula after 3 attempts');
+ });
+
+ it('strips markdown code fences from AI response', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $mockCompleter = Mockery::mock(GptCompleter::class);
+ $mockCompleter->shouldReceive('setJsonSchema')->andReturnSelf();
+ $mockCompleter->shouldReceive('setSystemMessage')->andReturnSelf();
+ $mockCompleter->shouldReceive('completeChat')->andReturnSelf();
+ $mockCompleter->shouldReceive('getArray')->andReturn([
+ 'formula' => "```\n{Price} * {Quantity}\n```",
+ ]);
+
+ $prompt->setGptCompleter($mockCompleter);
+ $result = $prompt->execute();
+
+ expect($result['formula'])->toBe('{uuid-price} * {uuid-quantity}');
+ });
+
+ it('throws on empty formula after all retries', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('test', $testFields, $testVariables);
+
+ $mockCompleter = Mockery::mock(GptCompleter::class);
+ $mockCompleter->shouldReceive('setJsonSchema')->andReturnSelf();
+ $mockCompleter->shouldReceive('setSystemMessage')->andReturnSelf();
+ $mockCompleter->shouldReceive('completeChat')->andReturnSelf();
+ $mockCompleter->shouldReceive('getArray')
+ ->andReturn(['formula' => '']);
+
+ $prompt->setGptCompleter($mockCompleter);
+
+ expect(fn () => $prompt->execute())
+ ->toThrow(\RuntimeException::class, 'AI returned an empty formula');
+ });
+
+ it('accepts formulas using only available computed variables', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('add tax', $testFields, $testVariables);
+
+ $mockCompleter = Mockery::mock(GptCompleter::class);
+ $mockCompleter->shouldReceive('setJsonSchema')->andReturnSelf();
+ $mockCompleter->shouldReceive('setSystemMessage')->andReturnSelf();
+ $mockCompleter->shouldReceive('completeChat')->andReturnSelf();
+ $mockCompleter->shouldReceive('getArray')->andReturn([
+ 'formula' => '{Subtotal} * 1.1',
+ ]);
+
+ $prompt->setGptCompleter($mockCompleter);
+ $result = $prompt->execute();
+
+ expect($result['formula'])->toBe('{uuid-subtotal} * 1.1');
+ });
+
+ it('handles complex nested formulas correctly', function () use ($testFields, $testVariables) {
+ $prompt = new GenerateFormulaPrompt('complex calc', $testFields, $testVariables);
+
+ $mockCompleter = Mockery::mock(GptCompleter::class);
+ $mockCompleter->shouldReceive('setJsonSchema')->andReturnSelf();
+ $mockCompleter->shouldReceive('setSystemMessage')->andReturnSelf();
+ $mockCompleter->shouldReceive('completeChat')->andReturnSelf();
+ $mockCompleter->shouldReceive('getArray')->andReturn([
+ 'formula' => 'IF({Quantity} > 100, {Price} * {Quantity} * 0.9, {Price} * {Quantity})',
+ ]);
+
+ $prompt->setGptCompleter($mockCompleter);
+ $result = $prompt->execute();
+
+ expect($result['formula'])->toBe('IF({uuid-quantity} > 100, {uuid-price} * {uuid-quantity} * 0.9, {uuid-price} * {uuid-quantity})');
+ });
+ });
+
+ describe('Polling GET /forms/ai/formula/{completion}', function () {
+ beforeEach(function () {
+ Queue::fake();
+ });
+
+ it('requires authentication', function () {
+ $owner = $this->createUser();
+ $completion = AiFormCompletion::create([
+ 'type' => AiFormCompletion::TYPE_FORMULA,
+ 'form_prompt' => 'Sum fields',
+ 'user_id' => $owner->id,
+ 'ip' => request()->ip(),
+ ]);
+
+ $this->getJson(route('forms.ai.formula.show', $completion->id))
+ ->assertUnauthorized();
+ });
+
+ it('returns completed formula result', function () {
+ $user = $this->actingAsUser();
+
+ $completion = AiFormCompletion::create([
+ 'type' => AiFormCompletion::TYPE_FORMULA,
+ 'form_prompt' => 'Sum fields',
+ 'context' => ['fields' => [['id' => 'f1', 'name' => 'A', 'type' => 'number']]],
+ 'user_id' => $user->id,
+ 'ip' => request()->ip(),
+ ]);
+ $completion->update([
+ 'status' => AiFormCompletion::STATUS_COMPLETED,
+ 'result' => json_encode(['formula' => '{f1} + 1']),
+ ]);
+
+ $response = $this->getJson(route('forms.ai.formula.show', $completion->id));
+
+ $response->assertSuccessful()
+ ->assertJsonPath('ai_form_completion.status', 'completed')
+ ->assertJsonPath('ai_form_completion.result', json_encode(['formula' => '{f1} + 1']));
+ });
+
+ it('returns processing status while in progress', function () {
+ $user = $this->actingAsUser();
+
+ $completion = AiFormCompletion::create([
+ 'type' => AiFormCompletion::TYPE_FORMULA,
+ 'form_prompt' => 'Something',
+ 'context' => ['fields' => []],
+ 'user_id' => $user->id,
+ 'ip' => request()->ip(),
+ ]);
+ $completion->update(['status' => AiFormCompletion::STATUS_PROCESSING]);
+
+ $response = $this->getJson(route('forms.ai.formula.show', $completion->id));
+
+ $response->assertSuccessful()
+ ->assertJsonPath('ai_form_completion.status', 'processing');
+ });
+
+ it('returns failed status with error', function () {
+ $user = $this->actingAsUser();
+
+ $completion = AiFormCompletion::create([
+ 'type' => AiFormCompletion::TYPE_FORMULA,
+ 'form_prompt' => 'Invalid thing',
+ 'context' => ['fields' => []],
+ 'user_id' => $user->id,
+ 'ip' => request()->ip(),
+ ]);
+ $completion->update([
+ 'status' => AiFormCompletion::STATUS_FAILED,
+ 'error' => 'Failed to generate a valid formula after 3 attempts.',
+ ]);
+
+ $response = $this->getJson(route('forms.ai.formula.show', $completion->id));
+
+ $response->assertSuccessful()
+ ->assertJsonPath('ai_form_completion.status', 'failed');
+ });
+
+ it('rejects a different user on the same IP', function () {
+ $this->withServerVariables(['REMOTE_ADDR' => '192.0.2.10']);
+ $owner = $this->createUser();
+ $otherUser = $this->createUser();
+ $completion = AiFormCompletion::create([
+ 'type' => AiFormCompletion::TYPE_FORMULA,
+ 'form_prompt' => 'test',
+ 'context' => ['fields' => []],
+ 'user_id' => $owner->id,
+ 'ip' => '192.0.2.10',
+ ]);
+ $completion->update([
+ 'status' => AiFormCompletion::STATUS_COMPLETED,
+ 'result' => json_encode(['formula' => '1 + 1']),
+ ]);
+
+ $this->actingAsUser($otherUser);
+
+ $this->getJson(route('forms.ai.formula.show', $completion->id))
+ ->assertNotFound();
+ });
+
+ it('does not expose formula results through legacy public polling', function () {
+ $owner = $this->createUser();
+ $completion = AiFormCompletion::create([
+ 'type' => AiFormCompletion::TYPE_FORMULA,
+ 'form_prompt' => 'Sum fields',
+ 'context' => ['fields' => []],
+ 'user_id' => $owner->id,
+ 'ip' => request()->ip(),
+ ]);
+
+ $this->getJson(route('forms.ai.show', $completion->id))
+ ->assertNotFound();
+ });
+ });
+});
diff --git a/api/tests/Unit/Service/Formulas/ValidatorTest.php b/api/tests/Unit/Service/Formulas/ValidatorTest.php
index e3662a36c..4b2471b7d 100644
--- a/api/tests/Unit/Service/Formulas/ValidatorTest.php
+++ b/api/tests/Unit/Service/Formulas/ValidatorTest.php
@@ -90,6 +90,26 @@ describe('Formula Validator', function () {
expect($result->valid)->toBe(false);
expect($result->errors[0]['message'])->toContain('Did you mean');
});
+
+ it('rejects function calls with too few arguments', function () {
+ $validator = new Validator([
+ 'availableFields' => [['id' => 'field1', 'name' => 'Field 1']],
+ ]);
+ $result = $validator->validate('MOD({field1})');
+
+ expect($result->valid)->toBe(false);
+ expect($result->errors[0]['message'])->toBe('Function MOD() requires exactly 2 arguments, but got 1.');
+ });
+
+ it('rejects function calls with too many arguments', function () {
+ $validator = new Validator([
+ 'availableFields' => [['id' => 'field1', 'name' => 'Field 1']],
+ ]);
+ $result = $validator->validate('COUNT({field1}, 1)');
+
+ expect($result->valid)->toBe(false);
+ expect($result->errors[0]['message'])->toBe('Function COUNT() accepts at most 1 argument, but got 2.');
+ });
});
describe('computed variable validation', function () {
diff --git a/client/api/forms.js b/client/api/forms.js
index 00aa372b6..f1e1147b8 100644
--- a/client/api/forms.js
+++ b/client/api/forms.js
@@ -56,6 +56,8 @@ export const formsApi = {
ai: {
generate: (data) => apiService.post('/forms/ai/generate', data),
generateFields: (data) => apiService.post('/forms/ai/generate-fields', data),
+ generateFormula: (data) => apiService.post('/forms/ai/generate-formula', data),
+ getFormula: (generationId, options) => apiService.get(`/forms/ai/formula/${generationId}`, options),
get: (generationId, options) => apiService.get(`/forms/ai/${generationId}`, options)
},
diff --git a/client/components/forms/heavy/components/MentionDropdown.vue b/client/components/forms/heavy/components/MentionDropdown.vue
index 9ac733d48..e3b3190c5 100644
--- a/client/components/forms/heavy/components/MentionDropdown.vue
+++ b/client/components/forms/heavy/components/MentionDropdown.vue
@@ -69,6 +69,21 @@
</div>
</div>
</div>
+
+ <div
+ v-if="canCreateComputedVariable"
+ class="w-full max-w-xs border-t pt-2 mt-2"
+ >
+ <UButton
+ color="neutral"
+ variant="ghost"
+ icon="i-heroicons-variable"
+ block
+ @click="createComputedVariable"
+ >
+ Create variable
+ </UButton>
+ </div>
</div>
<div class="flex border-t pt-2 -mx-2 px-2 justify-end space-x-2">
@@ -126,6 +141,8 @@ defineShortcuts({
const selectedField = ref(null)
const fallbackValue = ref('')
+const openComputedVariableCreator = inject('openComputedVariableCreator', null)
+const canCreateComputedVariable = computed(() => typeof openComputedVariableCreator === 'function')
const filteredMentions = computed(() => {
return props.mentions.filter(mention => blocksTypes[mention.type]?.is_input ?? false)
@@ -138,6 +155,11 @@ function selectField(field, insert = false) {
}
}
+function createComputedVariable() {
+ cancel()
+ openComputedVariableCreator()
+}
+
watch(() => props.mentionState.open, (newValue) => {
if (newValue) {
selectedField.value = null
@@ -159,4 +181,4 @@ const cancel = () => {
props.mentionState.onCancel()
}
}
-</script>
\ No newline at end of file
+</script>
diff --git a/client/components/open/forms/components/FormEditor.vue b/client/components/open/forms/components/FormEditor.vue
index af39cf9ee..694761ce4 100644
--- a/client/components/open/forms/components/FormEditor.vue
+++ b/client/components/open/forms/components/FormEditor.vue
@@ -176,6 +176,10 @@ const formEditorNavbar = ref(null)
const route = useRoute()
const { emitFormSaved, emitNavigateBack } = useEditorEmbedBridge()
+provide('openComputedVariableCreator', () => {
+ formEditorNavbar.value?.openComputedVariableCreator()
+})
+
// Sidebar resizing using composable
const {
elementRef,
diff --git a/client/components/open/forms/components/FormEditorNavbar.vue b/client/components/open/forms/components/FormEditorNavbar.vue
index 36616590f..bedbde3dc 100644
--- a/client/components/open/forms/components/FormEditorNavbar.vue
+++ b/client/components/open/forms/components/FormEditorNavbar.vue
@@ -174,7 +174,17 @@ function openComputedVariable({ variableId, variableIndex }) {
settingsModal.value = true
}
-defineExpose({ openComputedVariable })
+function openComputedVariableCreator() {
+ computedVariableEditRequestId += 1
+ computedVariableEditRequest.value = {
+ create: true,
+ requestId: computedVariableEditRequestId,
+ }
+ settingsModalActiveTab.value = 'variables'
+ settingsModal.value = true
+}
+
+defineExpose({ openComputedVariable, openComputedVariableCreator })
const isSelfHosted = computed(() => useFeatureFlag('self_hosted'))
</script>
diff --git a/client/components/open/forms/components/computed-variables/AiFormulaGenerator.vue b/client/components/open/forms/components/computed-variables/AiFormulaGenerator.vue
new file mode 100644
index 000000000..ab7d7a698
--- /dev/null
+++ b/client/components/open/forms/components/computed-variables/AiFormulaGenerator.vue
@@ -0,0 +1,196 @@
+<template>
+ <UPopover
+ v-model:open="isPopoverOpen"
+ arrow
+ :content="{ side: 'bottom', align: 'end' }"
+ >
+ <UButton
+ size="xs"
+ color="neutral"
+ variant="ghost"
+ icon="i-heroicons-sparkles"
+ :loading="loading"
+ >
+ {{ actionLabel }}
+ </UButton>
+
+ <template #content>
+ <div class="p-4 w-80">
+ <div class="space-y-2">
+ <p class="text-sm font-medium">{{ popoverTitle }}</p>
+ <p class="text-xs text-neutral-500">
+ {{ popoverDescription }}
+ </p>
+
+ <TextAreaInput
+ name="formula_prompt"
+ :disabled="loading"
+ :form="aiFormula"
+ :placeholder="promptPlaceholder"
+ />
+
+ <UButton
+ class="mt-2"
+ icon="i-heroicons-sparkles"
+ :label="actionLabel"
+ block
+ :loading="loading"
+ @click="handleGenerate"
+ />
+ </div>
+ </div>
+ </template>
+ </UPopover>
+</template>
+
+<script setup>
+import { formsApi } from '~/api'
+import { formulaToDisplay, formulaToStorage } from '~/lib/formulas/index.js'
+
+const props = defineProps({
+ form: {
+ type: Object,
+ required: true
+ },
+ currentFormula: {
+ type: String,
+ default: ''
+ },
+ currentVariable: {
+ type: Object,
+ default: null
+ },
+ otherVariables: {
+ type: Array,
+ default: () => []
+ }
+})
+
+const emit = defineEmits(['generated', 'generated-name'])
+
+const unsupportedFieldTypes = ['matrix']
+const isPopoverOpen = ref(false)
+const loading = ref(false)
+const aiRequestId = ref(null)
+
+const aiFormula = useForm({
+ formula_prompt: ''
+})
+
+const hasExistingFormula = computed(() => Boolean(props.currentFormula?.trim()))
+const actionLabel = computed(() => hasExistingFormula.value ? 'Update with AI' : 'Generate with AI')
+const popoverTitle = computed(() => hasExistingFormula.value ? 'Update formula with AI' : 'Generate formula with AI')
+const popoverDescription = computed(() => hasExistingFormula.value
+ ? 'Describe the change you want. AI will use the current formula and your form fields.'
+ : 'Describe what you want to calculate and AI will generate a formula using your form fields.'
+)
+const promptPlaceholder = computed(() => hasExistingFormula.value
+ ? 'e.g., Apply a 10% discount when quantity is over 100'
+ : 'e.g., Multiply price by quantity and apply 10% discount when quantity is over 100'
+)
+
+const availableFields = computed(() => {
+ return (props.form?.properties || [])
+ .filter(p => p.type && !p.type.startsWith('nf-') && !unsupportedFieldTypes.includes(p.type))
+ .map((p, index) => ({
+ id: p.id || `field_${index}_${(p.name || '').toLowerCase().replace(/\s+/g, '_')}`,
+ name: p.name,
+ type: p.type
+ }))
+})
+
+const formulaContext = computed(() => {
+ const context = {
+ fields: availableFields.value.map(field => ({
+ name: field.name,
+ type: field.type
+ })),
+ computed_variables: props.otherVariables.map(variable => ({
+ name: variable.name
+ })),
+ current_variable: {
+ name: props.currentVariable?.name ?? ''
+ }
+ }
+
+ if (hasExistingFormula.value) {
+ context.current_formula = formulaToDisplay(
+ props.currentFormula,
+ availableFields.value,
+ props.otherVariables
+ )
+ }
+
+ return context
+})
+
+const handleGenerate = () => {
+ if (loading.value) return
+
+ if (!aiFormula.formula_prompt?.trim()) {
+ useAlert().warning('Please describe the formula you want to generate.')
+ return
+ }
+
+ loading.value = true
+ aiRequestId.value = null
+
+ formsApi.ai.generateFormula({
+ formula_prompt: aiFormula.formula_prompt.trim(),
+ context: formulaContext.value
+ }).then(data => {
+ aiRequestId.value = data.ai_form_completion_id
+ fetchGeneratedFormula(data.ai_form_completion_id)
+ }).catch(error => {
+ console.error('Failed to generate formula:', error)
+ useAlert().error(error.response?.data?.message ?? 'Failed to generate formula.')
+ loading.value = false
+ })
+}
+
+const fetchGeneratedFormula = (generationId) => {
+ if (!aiRequestId.value) {
+ loading.value = false
+ return
+ }
+
+ const checkFormulaStatus = () => {
+ if (!aiRequestId.value) {
+ loading.value = false
+ return
+ }
+
+ formsApi.ai.getFormula(generationId).then(data => {
+ if (data.ai_form_completion.status === 'completed') {
+ if (aiRequestId.value) {
+ const result = JSON.parse(data.ai_form_completion.result)
+ const storageFormula = formulaToStorage(
+ result.formula,
+ availableFields.value,
+ props.otherVariables
+ )
+ emit('generated', storageFormula)
+ if (!props.currentVariable?.name?.trim() && result.variable_name?.trim()) {
+ emit('generated-name', result.variable_name.trim())
+ }
+ }
+ loading.value = false
+ isPopoverOpen.value = false
+ useAlert().success(hasExistingFormula.value ? 'Formula updated successfully.' : 'Formula generated successfully.')
+ aiFormula.formula_prompt = ''
+ } else if (data.ai_form_completion.status === 'failed') {
+ useAlert().error(data.ai_form_completion.error ?? 'Something went wrong, please try again.')
+ loading.value = false
+ } else {
+ setTimeout(checkFormulaStatus, 4000)
+ }
+ }).catch(error => {
+ console.error(error)
+ useAlert().error(error.response?.data?.message ?? 'Failed to generate formula.')
+ loading.value = false
+ })
+ }
+
+ checkFormulaStatus()
+}
+</script>
diff --git a/client/components/open/forms/components/computed-variables/ComputedVariablesTab.vue b/client/components/open/forms/components/computed-variables/ComputedVariablesTab.vue
index 09186853a..2743362a9 100644
--- a/client/components/open/forms/components/computed-variables/ComputedVariablesTab.vue
+++ b/client/components/open/forms/components/computed-variables/ComputedVariablesTab.vue
@@ -138,6 +138,11 @@ watch(() => props.editRequest, (request) => {
return
}
+ if (request.create) {
+ openCreateModal()
+ return
+ }
+
const indexedVariable = Number.isInteger(request.variableIndex)
? computedVariables.value[request.variableIndex]
: null
diff --git a/client/components/open/forms/components/computed-variables/FormulaDefinitionPanel.vue b/client/components/open/forms/components/computed-variables/FormulaDefinitionPanel.vue
index b67774293..9d89535ba 100644
--- a/client/components/open/forms/components/computed-variables/FormulaDefinitionPanel.vue
+++ b/client/components/open/forms/components/computed-variables/FormulaDefinitionPanel.vue
@@ -36,15 +36,25 @@
<label class="block text-sm font-medium text-gray-700">
Formula <span class="text-red-500">*</span>
</label>
- <UButton
- size="xs"
- color="neutral"
- variant="ghost"
- icon="i-heroicons-question-mark-circle"
- @click="$emit('show-reference')"
- >
- Function Reference
- </UButton>
+ <div class="flex items-center gap-1">
+ <AiFormulaGenerator
+ :form="form"
+ :current-formula="currentFormula"
+ :current-variable="localVariable"
+ :other-variables="otherVariables"
+ @generated="$emit('update:formula', $event)"
+ @generated-name="$emit('update:name', $event)"
+ />
+ <UButton
+ size="xs"
+ color="neutral"
+ variant="ghost"
+ icon="i-heroicons-question-mark-circle"
+ @click="$emit('show-reference')"
+ >
+ Function Reference
+ </UButton>
+ </div>
</div>
<FormulaEditor
@@ -90,6 +100,7 @@
<script setup>
import FormulaEditor from './FormulaEditor.vue'
+import AiFormulaGenerator from './AiFormulaGenerator.vue'
defineProps({
localVariable: {
@@ -120,4 +131,3 @@ defineProps({
defineEmits(['update:name', 'update:formula', 'validation', 'show-reference'])
</script>
-
diff --git a/client/components/open/forms/components/computed-variables/FormulaEditor.vue b/client/components/open/forms/components/computed-variables/FormulaEditor.vue
index f1868dc00..a30d4a922 100644
--- a/client/components/open/forms/components/computed-variables/FormulaEditor.vue
+++ b/client/components/open/forms/components/computed-variables/FormulaEditor.vue
@@ -291,6 +291,8 @@ watch(() => props.modelValue, (newVal) => {
editorRef.value.innerHTML = toDisplayFormat(newVal)
}
}
+
+ validateAndEmit()
})
// Debounce timer for highlighting
diff --git a/client/test/unit/formulas/validator.test.ts b/client/test/unit/formulas/validator.test.ts
index c9f55adee..737273bdb 100644
--- a/client/test/unit/formulas/validator.test.ts
+++ b/client/test/unit/formulas/validator.test.ts
@@ -67,6 +67,24 @@ describe('Formula Validator', () => {
expect(result.valid).toBe(false)
expect(result.errors[0].message).toContain('Did you mean')
})
+
+ it('rejects function calls with too few arguments', () => {
+ const result = validateFormula('MOD({field1})', {
+ availableFields: [{ id: 'field1', name: 'Field 1' }]
+ })
+
+ expect(result.valid).toBe(false)
+ expect(result.errors[0].message).toBe('Function MOD() requires exactly 2 arguments, but got 1.')
+ })
+
+ it('rejects function calls with too many arguments', () => {
+ const result = validateFormula('COUNT({field1}, 1)', {
+ availableFields: [{ id: 'field1', name: 'Field 1' }]
+ })
+
+ expect(result.valid).toBe(false)
+ expect(result.errors[0].message).toBe('Function COUNT() accepts at most 1 argument, but got 2.')
+ })
})
describe('computed variable validation', () => {