Beautiful Open-Source Form Builder
Use Mentions in Payment Block (#1014)
Chirag Chhatrala3c081858aa2f
diff --git a/api/app/Http/Controllers/Forms/FormPaymentController.php b/api/app/Http/Controllers/Forms/FormPaymentController.phpindex 35bb3eba2..2df3b9289 100644--- a/api/app/Http/Controllers/Forms/FormPaymentController.php+++ b/api/app/Http/Controllers/Forms/FormPaymentController.php@@ -5,6 +5,7 @@ namespace App\Http\Controllers\Forms;use App\Http\Controllers\Controller;use App\Models\Forms\Form;use App\Models\OAuthProvider;+use App\Http\Requests\Forms\CreatePaymentIntentRequest;use App\Http\Requests\Forms\GetStripeAccountRequest;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Log;@@ -75,7 +76,7 @@ class FormPaymentController extends Controllerreturn $this->success(['stripeAccount' => $provider->provider_user_id]);}- public function createIntent(Form $form)+ public function createIntent(CreatePaymentIntentRequest $request, Form $form){// Disable payment features on self-hosted instancesif (config('app.self_hosted')) {@@ -108,10 +109,23 @@ class FormPaymentController extends Controllerreturn $this->error(['message' => 'Failed to find Stripe account']);}+ // Resolve amount from submission data+ $amount = $request->resolveAmount($paymentBlock['amount']);++ // Validate amount+ if (!is_numeric($amount) || $amount <= 0) {+ Log::warning('Invalid payment amount', [+ 'form_id' => $form->id,+ 'amount' => $amount,+ 'original_amount' => $paymentBlock['amount']+ ]);+ return $this->error(['message' => 'Invalid payment amount. Please ensure the amount field has a valid value.']);+ }+try {Log::info('Creating payment intent', ['form_id' => $form->id,- 'amount' => $paymentBlock['amount'],+ 'amount' => $amount,'currency' => $paymentBlock['currency']]);@@ -120,7 +134,7 @@ class FormPaymentController extends Controller$intent = PaymentIntent::create([// Use description from payment block if available, fallback to form title'description' => $paymentBlock['description'] ?? ('Form - ' . $form->title),- 'amount' => (int) ($paymentBlock['amount'] * 100), // Stripe requires amount in cents+ 'amount' => (int) ($amount * 100), // Stripe requires amount in cents'currency' => strtolower($paymentBlock['currency']),'payment_method_types' => ['card'],'metadata' => [diff --git a/api/app/Http/Requests/Forms/CreatePaymentIntentRequest.php b/api/app/Http/Requests/Forms/CreatePaymentIntentRequest.phpnew file mode 100644index 000000000..7657a6f02--- /dev/null+++ b/api/app/Http/Requests/Forms/CreatePaymentIntentRequest.php@@ -0,0 +1,52 @@+<?php++namespace App\Http\Requests\Forms;++use App\Open\MentionParser;+use Illuminate\Foundation\Http\FormRequest;++class CreatePaymentIntentRequest extends FormRequest+{+ public function authorize(): bool+ {+ return true; // Public endpoint+ }++ public function rules(): array+ {+ return [+ 'submission_data' => ['sometimes', 'array'],+ 'submission_data.*' => ['nullable'],+ ];+ }++ /**+ * Get formatted submission data for mention parsing.+ */+ public function getFormattedSubmissionData(): array+ {+ return collect($this->input('submission_data', []))+ ->map(fn ($value, $key) => ['id' => $key, 'value' => $value])+ ->values()+ ->all();+ }++ /**+ * Parse and resolve the payment amount from a raw value (which may contain mentions).+ */+ public function resolveAmount(mixed $rawAmount): ?float+ {+ $parsedAmount = (new MentionParser($rawAmount, $this->getFormattedSubmissionData()))+ ->parseAsText();++ $normalized = str_replace(',', '', $parsedAmount);+ $matches = [];+ $amount = null;++ if (preg_match('/-?\d+(?:\.\d+)?/', $normalized, $matches)) {+ $amount = (float) $matches[0];+ }++ return ($amount > 0) ? $amount : null;+ }+}diff --git a/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php b/api/app/Rules/PropertyValidators/PaymentPropertyValidator.phpindex c03ea17b3..e5d581e36 100644--- a/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php+++ b/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php@@ -54,9 +54,19 @@ class PaymentPropertyValidator implements PropertyValidatorInterfacereturn $errors;}- // Amount validation- if (!isset($property['amount']) || !is_numeric($property['amount']) || $property['amount'] < 1) {- $errors['amount'] = 'Amount must be a number of at least 1';+ // Amount validation - allow numeric value >= 1 or string with mention+ $amount = $property['amount'] ?? null;+ $isValidAmount = false;++ if (is_numeric($amount) && $amount >= 1) {+ $isValidAmount = true;+ } elseif (is_string($amount) && preg_match('/mention[-\w]*=/', $amount)) {+ // Amount contains a mention reference - will be parsed at runtime+ $isValidAmount = true;+ }++ if (!$isValidAmount) {+ $errors['amount'] = 'Amount must be a number of at least 1 or a field reference';return $errors;}diff --git a/api/tests/Feature/Forms/FormPaymentTest.php b/api/tests/Feature/Forms/FormPaymentTest.phpindex 24a199332..8f2bcbc9b 100644--- a/api/tests/Feature/Forms/FormPaymentTest.php+++ b/api/tests/Feature/Forms/FormPaymentTest.php@@ -81,3 +81,132 @@ it('cannot create payment intent with invalid stripe account', function () {'message' => 'Failed to find Stripe account']);});++describe('payment amount with mentions', function () {+ it('can parse amount from mention field reference', function () {+ // Get the number field ID from form properties+ $numberField = collect($this->form->properties)->firstWhere('type', 'number');++ // Update payment block with mention-based amount+ $mentionHtml = '<span mention="true" mention-field-id="' . $numberField['id'] . '">Number</span>';+ $properties = collect($this->form->properties)->map(function ($block) use ($mentionHtml) {+ if ($block['type'] === 'payment') {+ $block['amount'] = $mentionHtml;+ }+ return $block;+ })->all();++ $this->form->update(['properties' => $properties]);++ // Submit with submission data containing the referenced field value+ // Note: This will fail at Stripe API level (no real credentials), but validates parsing works+ $response = $this->postJson(route('forms.stripe-connect.create-intent', $this->form->slug), [+ 'submission_data' => [+ $numberField['id'] => 50.00+ ]+ ]);++ // Should not get "Invalid payment amount" error - parsing worked+ $response->assertStatus(400);+ expect($response->json('message'))->not->toBe('Invalid payment amount. Please ensure the amount field has a valid value.');+ });++ it('returns error when mention resolves to invalid amount', function () {+ // Get a text field ID from form properties+ $textField = collect($this->form->properties)->firstWhere('type', 'text');++ // Update payment block with mention-based amount+ $mentionHtml = '<span mention="true" mention-field-id="' . $textField['id'] . '">Text</span>';+ $properties = collect($this->form->properties)->map(function ($block) use ($mentionHtml) {+ if ($block['type'] === 'payment') {+ $block['amount'] = $mentionHtml;+ }+ return $block;+ })->all();++ $this->form->update(['properties' => $properties]);++ // Submit with submission data containing non-numeric value+ $this->postJson(route('forms.stripe-connect.create-intent', $this->form->slug), [+ 'submission_data' => [+ $textField['id'] => 'not a number'+ ]+ ])+ ->assertStatus(400)+ ->assertJson([+ 'message' => 'Invalid payment amount. Please ensure the amount field has a valid value.'+ ]);+ });++ it('returns error when mention field is empty', function () {+ // Get the number field ID from form properties+ $numberField = collect($this->form->properties)->firstWhere('type', 'number');++ // Update payment block with mention-based amount+ $mentionHtml = '<span mention="true" mention-field-id="' . $numberField['id'] . '">Number</span>';+ $properties = collect($this->form->properties)->map(function ($block) use ($mentionHtml) {+ if ($block['type'] === 'payment') {+ $block['amount'] = $mentionHtml;+ }+ return $block;+ })->all();++ $this->form->update(['properties' => $properties]);++ // Submit without the referenced field in submission data+ $this->postJson(route('forms.stripe-connect.create-intent', $this->form->slug), [+ 'submission_data' => []+ ])+ ->assertStatus(400)+ ->assertJson([+ 'message' => 'Invalid payment amount. Please ensure the amount field has a valid value.'+ ]);+ });++ it('can parse amount with currency symbols and commas', function () {+ $numberField = collect($this->form->properties)->firstWhere('type', 'number');++ $mentionHtml = '<span mention="true" mention-field-id="' . $numberField['id'] . '">Number</span>';+ $properties = collect($this->form->properties)->map(function ($block) use ($mentionHtml) {+ if ($block['type'] === 'payment') {+ $block['amount'] = $mentionHtml;+ }+ return $block;+ })->all();++ $this->form->update(['properties' => $properties]);++ $response = $this->postJson(route('forms.stripe-connect.create-intent', $this->form->slug), [+ 'submission_data' => [+ $numberField['id'] => '$1,234.50'+ ]+ ]);++ $response->assertStatus(400);+ expect($response->json('message'))->not->toBe('Invalid payment amount. Please ensure the amount field has a valid value.');+ });++ it('returns error when mention resolves to negative amount', function () {+ $numberField = collect($this->form->properties)->firstWhere('type', 'number');++ $mentionHtml = '<span mention="true" mention-field-id="' . $numberField['id'] . '">Number</span>';+ $properties = collect($this->form->properties)->map(function ($block) use ($mentionHtml) {+ if ($block['type'] === 'payment') {+ $block['amount'] = $mentionHtml;+ }+ return $block;+ })->all();++ $this->form->update(['properties' => $properties]);++ $this->postJson(route('forms.stripe-connect.create-intent', $this->form->slug), [+ 'submission_data' => [+ $numberField['id'] => -10+ ]+ ])+ ->assertStatus(400)+ ->assertJson([+ 'message' => 'Invalid payment amount. Please ensure the amount field has a valid value.'+ ]);+ });+});diff --git a/api/tests/Unit/Rules/PaymentPropertyValidatorTest.php b/api/tests/Unit/Rules/PaymentPropertyValidatorTest.phpnew file mode 100644index 000000000..c4d29c52e--- /dev/null+++ b/api/tests/Unit/Rules/PaymentPropertyValidatorTest.php@@ -0,0 +1,130 @@+<?php++use App\Rules\PropertyValidators\PaymentPropertyValidator;+use App\Models\OAuthProvider;+use App\Models\User;+use App\Models\Workspace;++uses(\Tests\TestCase::class);++beforeEach(function () {+ $this->user = User::factory()->create();+ $this->workspace = Workspace::factory()->create();+ $this->workspace->users()->attach($this->user->id, ['role' => 'admin']);++ // Create OAuth provider for Stripe+ $this->stripeAccount = OAuthProvider::factory()->for($this->user)->create([+ 'provider' => 'stripe',+ 'provider_user_id' => 'acct_test123'+ ]);+});++describe('amount validation', function () {+ it('accepts numeric amount greater than or equal to 1', function () {+ $validator = new PaymentPropertyValidator($this->workspace);++ $property = [+ 'type' => 'payment',+ 'amount' => 99.99,+ 'currency' => 'USD',+ 'stripe_account_id' => $this->stripeAccount->id+ ];++ $errors = $validator->validate($property, 0, ['properties' => [$property]]);++ expect($errors)->toBeEmpty();+ });++ it('rejects numeric amount less than 1', function () {+ $validator = new PaymentPropertyValidator($this->workspace);++ $property = [+ 'type' => 'payment',+ 'amount' => 0.5,+ 'currency' => 'USD',+ 'stripe_account_id' => $this->stripeAccount->id+ ];++ $errors = $validator->validate($property, 0, ['properties' => [$property]]);++ expect($errors)->toHaveKey('amount');+ expect($errors['amount'])->toBe('Amount must be a number of at least 1 or a field reference');+ });++ it('accepts amount with mention field reference', function () {+ $validator = new PaymentPropertyValidator($this->workspace);++ $mentionHtml = '<span mention="true" mention-field-id="field-123">Number Field</span>';+ $property = [+ 'type' => 'payment',+ 'amount' => $mentionHtml,+ 'currency' => 'USD',+ 'stripe_account_id' => $this->stripeAccount->id+ ];++ $errors = $validator->validate($property, 0, ['properties' => [$property]]);++ expect($errors)->toBeEmpty();+ });++ it('accepts amount with mention field containing currency symbol', function () {+ $validator = new PaymentPropertyValidator($this->workspace);++ $mentionHtml = '<span mention="true" mention-field-id="field-123">$50.00</span>';+ $property = [+ 'type' => 'payment',+ 'amount' => $mentionHtml,+ 'currency' => 'USD',+ 'stripe_account_id' => $this->stripeAccount->id+ ];++ $errors = $validator->validate($property, 0, ['properties' => [$property]]);++ expect($errors)->toBeEmpty();+ });++ it('rejects string amount without mention', function () {+ $validator = new PaymentPropertyValidator($this->workspace);++ $property = [+ 'type' => 'payment',+ 'amount' => 'invalid amount',+ 'currency' => 'USD',+ 'stripe_account_id' => $this->stripeAccount->id+ ];++ $errors = $validator->validate($property, 0, ['properties' => [$property]]);++ expect($errors)->toHaveKey('amount');+ expect($errors['amount'])->toBe('Amount must be a number of at least 1 or a field reference');+ });++ it('rejects missing amount', function () {+ $validator = new PaymentPropertyValidator($this->workspace);++ $property = [+ 'type' => 'payment',+ 'currency' => 'USD',+ 'stripe_account_id' => $this->stripeAccount->id+ ];++ $errors = $validator->validate($property, 0, ['properties' => [$property]]);++ expect($errors)->toHaveKey('amount');+ });+});++describe('non-payment blocks', function () {+ it('skips validation for non-payment blocks', function () {+ $validator = new PaymentPropertyValidator($this->workspace);++ $property = [+ 'type' => 'text',+ 'name' => 'Text Field'+ ];++ $errors = $validator->validate($property, 0, ['properties' => [$property]]);++ expect($errors)->toBeEmpty();+ });+});diff --git a/client/components/forms/heavy/PaymentInput.client.vue b/client/components/forms/heavy/PaymentInput.client.vueindex 650918265..710b287cf 100644--- a/client/components/forms/heavy/PaymentInput.client.vue+++ b/client/components/forms/heavy/PaymentInput.client.vue@@ -156,7 +156,9 @@ const props = defineProps({isAdminPreview: { type: Boolean, default: false },color: { type: String, default: '#000000' },isDark: { type: Boolean, default: false },- paymentData: { type: Object, default: null }+ paymentData: { type: Object, default: null },+ prefillName: { type: String, default: '' },+ prefillEmail: { type: String, default: '' }})const emit = defineEmits([])@@ -173,11 +175,25 @@ const publishableKey = computed(() => {const card = ref(null)const stripeElementsRef = ref(null)-const cardHolderName = ref('')-const cardHolderEmail = ref('')+const cardHolderName = ref(props.prefillName || '')+const cardHolderEmail = ref(props.prefillEmail || '')const isCardFocused = ref(false)const isStripeJsLoaded = ref(false)+// Watch for prefill changes to update card holder details+watch(() => props.prefillName, (newVal) => {+ const resolved = newVal ?? ''+ if (resolved !== cardHolderName.value) {+ cardHolderName.value = resolved+ }+})+watch(() => props.prefillEmail, (newVal) => {+ const resolved = newVal ?? ''+ if (resolved !== cardHolderEmail.value) {+ cardHolderEmail.value = resolved+ }+})+// Get Stripe elements from paymentDataconst stripeElements = computed(() => props.paymentData?.stripeElements)const stripeState = computed(() => stripeElements.value?.state || {})diff --git a/client/components/open/forms/BlockRenderer.vue b/client/components/open/forms/BlockRenderer.vueindex a584d9550..01edbea76 100644--- a/client/components/open/forms/BlockRenderer.vue+++ b/client/components/open/forms/BlockRenderer.vue@@ -100,6 +100,7 @@ import ClientOnlyWrapper from '~/components/global/ClientOnlyWrapper.vue'import { useComponentRegistry } from '~/composables/components/useComponentRegistry'import TextBlock from '~/components/forms/core/TextBlock.vue'import { shuffleArray } from '~/lib/utils.js'+import { useParseMention } from '@/composables/components/useParseMention'const props = defineProps({block: { type: Object, required: false, default: null },@@ -284,8 +285,26 @@ const boundProps = computed(() => {} else if (field.type === 'payment') {inputProperties.direction = form.value.layout_rtl ? 'rtl' : 'ltr'inputProperties.currency = field.currency- inputProperties.amount = field.amount+ // Parse amount with mentions - field.amount may contain mention HTML+ const parsedAmount = useParseMention(field.amount, true, form.value, dataForm.value)+ const sanitizedAmount = parsedAmount+ .replace(/<[^>]*>/g, '')+ .replace(/,/g, '')+ .trim()+ const amountMatch = sanitizedAmount.match(/-?\d+(\.\d+)?/)+ const numericAmount = amountMatch ? parseFloat(amountMatch[0]) : NaN+ inputProperties.amount = (!isNaN(numericAmount) && numericAmount > 0) ? numericAmount : 0inputProperties.oauthProviderId = field.stripe_account_id++ // Parse prefill fields with mentions+ if (field.prefill_name) {+ const parsed = useParseMention(field.prefill_name, true, form.value, dataForm.value)+ inputProperties.prefillName = parsed.replace(/<[^>]*>/g, '').trim()+ }+ if (field.prefill_email) {+ const parsed = useParseMention(field.prefill_email, true, form.value, dataForm.value)+ inputProperties.prefillEmail = parsed.replace(/<[^>]*>/g, '').trim()+ }if (props.formManager?.payment) {try { inputProperties.paymentData = props.formManager.payment.getPaymentData(field) } catch (e) { console.error(e) }}diff --git a/client/components/open/forms/fields/components/FieldOptions.vue b/client/components/open/forms/fields/components/FieldOptions.vueindex cf5583399..0480503c5 100644--- a/client/components/open/forms/fields/components/FieldOptions.vue+++ b/client/components/open/forms/fields/components/FieldOptions.vue@@ -215,6 +215,7 @@<PaymentFieldOptionsv-if="field.type === 'payment'":field="field"+ :form="form"/><!-- Text Options -->diff --git a/client/components/open/forms/fields/components/PaymentFieldOptions.vue b/client/components/open/forms/fields/components/PaymentFieldOptions.vueindex 0aeabbd8d..8fd93ab80 100644--- a/client/components/open/forms/fields/components/PaymentFieldOptions.vue+++ b/client/components/open/forms/fields/components/PaymentFieldOptions.vue@@ -17,16 +17,36 @@:searchable="true":disabled="stripeAccounts.length === 0"/>- <text-input+ <MentionInput+ class="mt-4"name="amount"label="Amount"native-type="number":form="field"+ :mentions="form.properties":required="true":disabled="stripeAccounts.length === 0"/>+ <MentionInput+ class="mt-4"+ name="prefill_name"+ label="Name on Card"+ :form="field"+ :mentions="form.properties"+ :disabled="stripeAccounts.length === 0"+ />+ <MentionInput+ class="mt-4"+ name="prefill_email"+ label="Billing Email"+ :form="field"+ :mentions="form.properties"+ :disabled="stripeAccounts.length === 0"+ />+<div v-if="stripeAccounts.length > 0"><select-input+ class="mt-4"name="stripe_account_id"label="Stripe Account":options="stripeAccounts"@@ -72,6 +92,10 @@ const props = defineProps({field: {type: Object,required: true+ },+ form: {+ type: Object,+ required: true}})diff --git a/client/lib/forms/composables/useFormPayment.js b/client/lib/forms/composables/useFormPayment.jsindex fca2d908e..99c2bebda 100644--- a/client/lib/forms/composables/useFormPayment.js+++ b/client/lib/forms/composables/useFormPayment.js@@ -66,7 +66,7 @@ export function useFormPayment(formConfig, form) {}// Use formsApi for the payment intent creation- const response = await formsApi.stripe.createPaymentIntent(formSlug)+ const response = await formsApi.stripe.createPaymentIntent(formSlug, { submission_data: form.data() ?? [] })// Handle response structure with type and intent fieldsif (response?.type === 'success' && response?.intent?.secret) {