Stripe Payment (#679)

* oAuth for Stripe

* Stripe Payment Frontend - WIP

* Payment block backend validation and new package for stripe

* change stripe scopes

* update PaymentBlockConfigurationRule

* Set loader on provider modal

* stripe oauth

* PaymentFieldOptions as seprate component

* validate Stripe account

* Payment intent

* Stripe Payment as composable

* confirmCardPayment working

* Set payment errors on form.errors

* Validate card other fields

* Store payment id to database and on submission add link for view payment on stripe

* FormPaymentController no need auth middleware

* paymentinput error display on field

* Make payment block as input
change 'nf-payment' to 'payment'

* Refactor payment processing and error handling

* Multi lang & direction support on payment

* reset card on change direction or local

* use connected account for loadstripe

* validate OAuthProvider before delete it

* payment improvements

* display payment by stripe

* use stripe_currencies.json

* Form Payment testcase

* Enhance form auto-save behavior for payment forms

* Restrict payment block in self-hosted environments

* validate form before process payment

* Refactor Nuxt Configuration for Improved Development Server Settings

- Removed the existing Vite server configuration for hot module replacement (HMR) as it was no longer necessary.
- Introduced a new `devServer` configuration to specify the host and port for the development server, allowing for more flexible environment setup based on environment variables.

These changes aim to streamline the development process by enhancing server configuration and ensuring better adaptability to different environments.

* Enhance Payment Handling and User Experience in Forms

- Refactored `FormPaymentController` to improve handling of Stripe account retrieval, including better error messages for both editor preview and public forms.
- Updated `OAuthProviderController` to utilize caching for OAuth connection context, enhancing performance and user experience during account connections.
- Improved `PaymentInput.client.vue` to display a loading state and a preview message for users, guiding them to save the form for payment activation.
- Modified various components to standardize payment-related messages and improve localization support across multiple languages.
- Removed the deprecated `connections.vue` page to streamline the codebase.

These changes aim to enhance the overall user experience when handling payments and improve the maintainability of the payment-related components.

* Refactor Payment Handling and Enhance User Experience in Forms

- Updated `FormPaymentController` to utilize a new method for checking if the Stripe provider belongs to any workspace user, improving security and error logging.
- Modified `OAuthProviderController` to streamline the OAuth provider creation process by directly using the service object.
- Enhanced `Workspace` model with a new method to verify provider ownership, improving code clarity and maintainability.
- Improved `PaymentInput.client.vue` to handle loading states and error messages more effectively, enhancing user feedback during payment processing.
- Refactored `useFormInput.js` to include an `isAdminPreview` prop for better context handling in form components.

These changes aim to improve the overall user experience when handling payments and enhance the maintainability of the payment-related components.

* Enhance Payment Validation and User Experience in Forms

- Updated `UserFormRequest` to improve workspace handling during form submissions, allowing for better context in validation rules.
- Modified `PaymentBlockConfigurationRule` to include workspace validation, ensuring that payment providers are associated with the correct workspace, enhancing security and error logging.
- Improved `PaymentInput.client.vue` to dynamically determine the success state of payment processing, providing clearer user feedback.
- Updated various localization files to include a payment disclaimer, ensuring users are informed about credit card charges during payment processing.

These changes aim to enhance the overall user experience when handling payments and improve the maintainability of payment-related components.

* Enhance Payment Features and User Experience in Forms

- Added checks in `FormPaymentController` to disable payment features for self-hosted instances, improving clarity for users regarding feature availability.
- Updated `PaymentBlockConfigurationRule` to change the minimum amount validation from 0.5 to 1, ensuring stricter payment requirements.
- Enhanced `PaymentInput.client.vue` with dark mode support for various UI elements, improving accessibility and user experience in different themes.
- Modified `useFormInput.js` to include an `isDark` prop, allowing for better theme handling in form components.
- Updated error messages in `useStripeElements.js` to include periods for consistency and improved user feedback.

These changes aim to enhance the overall user experience when handling payments and improve the maintainability of payment-related components.

* Enhance Payment Input Component with Focus Handling and Theme Support

- Updated `PaymentInput.client.vue` to include focus and blur event handlers, improving user interaction by visually indicating when the card input is focused.
- Enhanced theme support by adding new properties in `form-themes.js` for `PaymentInput`, allowing for better styling and transitions based on focus state.
- Introduced a new `isCardFocused` reactive reference to manage the focus state of the card input, enhancing the overall user experience.

These changes aim to improve the usability and visual feedback of the payment input component, aligning with recent enhancements to user experience in payment forms.

* Refactor Payment Handling and Improve Code Consistency

- Updated various files to enhance code consistency by adding spaces in arrow function definitions, improving readability and adhering to coding standards.
- Modified `PaymentBlockConfigurationRule.php`, `FormPaymentController.php`, and `Workspace.php` to ensure uniformity in the use of arrow functions.
- Enhanced `PaymentInput.client.vue` and other components by improving the formatting of template elements for better visual structure.
- Updated `useStripeElements.js` to streamline state management and improve clarity in the handling of Stripe elements.

These changes aim to improve code maintainability and readability across the payment handling components, ensuring a more consistent coding style throughout the codebase.

* Enhance Form Model and Logging Configuration

- Added a new 'auto_save' boolean property to the Form model, allowing for automatic saving of form data.
- Updated the logging configuration to include a 'combined' channel that stacks multiple log channels, improving logging flexibility and error tracking.
- Modified the FormFactory to set a default value for 'auto_save' to false, ensuring consistent behavior across form instances.
- Improved error message structure in FormPaymentTest to provide clearer feedback when a payment block is missing.

These changes aim to enhance the functionality of forms and improve logging capabilities, contributing to better maintainability and user experience.

* Update api/config/logging.php

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Refactor Payment Error Handling and Localization Updates

- Updated `FormPaymentTest.php` to improve code consistency by adding spaces in arrow function definitions, enhancing readability.
- Modified `useStripeElements.js` to replace hardcoded error messages with localized strings, improving user experience and maintainability.
- Enhanced various localization files (e.g., `en.json`, `fr.json`, `de.json`, etc.) to include new error messages related to payment processing, ensuring users receive clear and consistent feedback across different languages.

These changes aim to enhance the clarity of error handling in payment processes and improve the overall user experience through better localization support.

* Enhance AddFormBlock and FieldOptions with Authentication Checks

- Added an icon to indicate authentication requirements for blocks in `AddFormBlock.vue`, improving user awareness of access restrictions.
- Implemented alert notifications using `useAlert()` for unauthorized block additions and input cloning, enhancing user feedback.
- Updated `FieldOptions.vue` to conditionally render payment field options, ensuring relevant options are displayed based on the field type.
- Modified `blocks_types.json` to include an `auth_required` property for specific block types, facilitating authentication checks.

These changes aim to improve user experience by providing clear indications of authentication requirements and enhancing form functionality.

* Enhance Authentication Checks in AddFormBlock Component

- Updated `AddFormBlock.vue` to conditionally render authentication-required icons based on user authentication status, improving user awareness of access restrictions.
- Implemented additional authentication checks in the `addBlock` and `handleInputClone` functions, utilizing `useAlert()` for notifying users when login is required to add blocks or clone inputs.
- Introduced a computed property to manage the authenticated state, streamlining the authentication logic within the component.

These changes aim to enhance user experience by providing clear indications of authentication requirements and improving the functionality of the form component.

* Enhance PaymentInput Component with Disabled State Support

- Updated `PaymentInput.client.vue` to include a `disabled` prop for the card holder name and email inputs, improving form accessibility and user experience by preventing interaction when necessary.
- Modified the card options to respect the `disabled` state, ensuring consistent behavior across the payment input fields.

These changes aim to enhance the usability of the payment input component by providing better control over user interactions.

* Add Payment Condition Logic and Update Filters

- Introduced a new payment condition in `FormLogicConditionChecker.php` to handle 'paid' and 'not_paid' states, enhancing form logic capabilities.
- Added corresponding payment comparators in `open_filters.json` for both API and client, ensuring consistent validation and expected types for payment conditions.
- Updated the JavaScript logic in `FormLogicConditionChecker.js` to include the new payment condition checks, improving the overall functionality of form conditions.

These changes aim to enhance the form logic related to payment states, providing better validation and user experience in payment-related forms.

* Refactor Authentication Checks in AddFormBlock and Working Form Store

- Removed redundant authentication checks from `AddFormBlock.vue` for adding blocks and cloning inputs, streamlining the logic.
- Centralized authentication validation in `working_form.js` to ensure consistent user feedback when authentication is required for specific block types.
- Enhanced user experience by utilizing `useAlert()` for notifying users about login requirements, improving clarity and interaction.

These changes aim to simplify the authentication logic and improve user notifications regarding access restrictions in form components.

* Refactor Feature Flags and Update Payment Input Logic

- Updated `FeatureFlagsController.php` to utilize the `Cache` facade directly, improving code clarity and consistency.
- Modified `PaymentInput.client.vue` to enhance the display logic for payment previews, ensuring a better user experience by conditionally showing messages based on the state of the Stripe account.
- Removed the `STRIPE_PUBLISHABLE_KEY` from `runtimeConfig.js` to streamline the configuration and replaced it with a computed property that retrieves the key from feature flags, improving maintainability.
- Adjusted the `.env.example` file to maintain consistency in environment variable definitions.

These changes aim to enhance the clarity of feature flag management and improve the user experience in payment interactions by refining the logic and configuration handling.

* Update Stripe Configuration in Services

- Modified the `services.php` configuration file to enhance the Stripe integration by providing default values for `client_secret` and `redirect` URI. This change ensures that the application can fallback to a predefined secret and a specific callback URL, improving the robustness of the payment service setup.

These changes aim to streamline the configuration process for Stripe, ensuring that necessary values are always available for the application to function correctly.

---------

Co-authored-by: Chirag Chhatrala <chirag.chhatrala@gmail.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This commit is contained in:
Julien Nahum
2025-04-10 12:04:25 +02:00
committed by GitHub
parent e14d1003ee
commit 5cb07191db
80 changed files with 5228 additions and 764 deletions

View File

@@ -1,3 +1,5 @@
<template></template>
<script setup>
import { pendingSubmission as pendingSubmissionFun } from "~/composables/forms/pendingSubmission.js"

View File

@@ -298,7 +298,6 @@ export default {
if (form.busy) return
this.loading = true
form.post('/forms/' + this.form.slug + '/answer').then((data) => {
this.submittedData = form.data()
useAmplitude().logEvent('form_submission', {

View File

@@ -31,7 +31,9 @@
group="form-elements"
item-key="id"
class="grid grid-cols-12 relative transition-all w-full"
:class="{'rounded-md bg-blue-50 dark:bg-gray-800':draggingNewBlock}"
:class="[
draggingNewBlock ? 'rounded-md bg-blue-50 dark:bg-gray-800' : '',
]"
ghost-class="ghost-item"
filter=".not-draggable"
:animation="200"
@@ -83,6 +85,7 @@
v-if="isLastPage"
name="submit-btn"
:submit-form="submitForm"
:loading="dataForm.busy"
/>
<open-form-button
v-else-if="currentFieldsPageBreak"
@@ -98,6 +101,14 @@
<div v-if="!currentFieldsPageBreak && !isLastPage">
{{ $t('forms.wrong_form_structure') }}
</div>
<div
v-if="paymentBlock"
class="mt-6 flex justify-center w-full"
>
<p class="text-xs text-gray-400 dark:text-gray-500 flex text-center max-w-md">
{{ $t('forms.payment.payment_disclaimer') }}
</p>
</div>
</div>
</form>
</template>
@@ -115,6 +126,7 @@ import FormProgressbar from './FormProgressbar.vue'
import { storeToRefs } from 'pinia'
import { FormMode, createFormModeStrategy } from "~/lib/forms/FormModeStrategy.js"
import clonedeep from 'clone-deep'
import { provideStripeElements } from '~/composables/useStripeElements'
export default {
name: 'OpenForm',
@@ -159,6 +171,9 @@ export default {
const dataForm = ref(useForm())
const config = useRuntimeConfig()
// Provide Stripe elements to be used by child components
const stripeElements = provideStripeElements()
const hasCaptchaProviders = computed(() => {
return config.public.hCaptchaSiteKey || config.public.recaptchaSiteKey
})
@@ -167,9 +182,10 @@ export default {
dataForm,
recordsStore,
workingFormStore,
stripeElements,
isIframe: useIsIframe(),
draggingNewBlock: computed(() => workingFormStore.draggingNewBlock),
pendingSubmission: pendingSubmission(props.form),
pendingSubmission: import.meta.client ? pendingSubmission(props.form) : { get: () => ({}), set: () => {} },
formPageIndex: storeToRefs(workingFormStore).formPageIndex,
// Used for admin previews
@@ -296,6 +312,9 @@ export default {
'--form-color': this.form.color
}
},
paymentBlock() {
return (this.currentFields) ? this.currentFields.find(field => field.type === 'payment') : null
},
isCaptchaProviderAvailable() {
const config = useRuntimeConfig()
if (this.form.captcha_provider === 'recaptcha') {
@@ -369,27 +388,42 @@ export default {
},
methods: {
submitForm() {
if (!this.isAutoSubmit && this.formPageIndex !== this.fieldGroups.length - 1) return
async submitForm() {
this.dataForm.busy = true
try {
if (!await this.nextPage()) {
this.dataForm.busy = false
return
}
if (this.form.use_captcha && import.meta.client) {
this.$refs.captcha?.reset()
}
if (!this.isAutoSubmit && this.formPageIndex !== this.fieldGroups.length - 1) {
this.dataForm.busy = false
return
}
if (this.form.editable_submissions && this.form.submission_id) {
this.dataForm.submission_id = this.form.submission_id
}
if (this.form.use_captcha && import.meta.client) {
this.$refs.captcha?.reset()
}
this.$refs['form-timer'].stopTimer()
this.dataForm.completion_time = this.$refs['form-timer'].completionTime
if (this.form.editable_submissions && this.form.submission_id) {
this.dataForm.submission_id = this.form.submission_id
}
this.$refs['form-timer'].stopTimer()
this.dataForm.completion_time = this.$refs['form-timer'].completionTime
// Add validation strategy check
if (!this.formModeStrategy.validation.validateOnSubmit) {
this.$emit('submit', this.dataForm, this.onSubmissionFailure)
return
}
// Add validation strategy check
if (!this.formModeStrategy.validation.validateOnSubmit) {
this.$emit('submit', this.dataForm, this.onSubmissionFailure)
return
} catch (error) {
this.handleValidationError(error)
this.dataForm.busy = false
}
this.$emit('submit', this.dataForm, this.onSubmissionFailure)
},
/**
* Handle form submission failure
@@ -397,6 +431,8 @@ export default {
onSubmissionFailure() {
this.$refs['form-timer'].startTimer()
this.isAutoSubmit = false
this.dataForm.busy = false
if (this.fieldGroups.length > 1) {
this.showFirstPageWithError()
}
@@ -501,14 +537,17 @@ export default {
},
tryInitFormFromPendingSubmission() {
if (this.isPublicFormPage && this.form.auto_save) {
const pendingData = this.pendingSubmission.get()
if (pendingData && Object.keys(pendingData).length !== 0) {
this.updatePendingDataFields(pendingData)
this.dataForm.resetAndFill(pendingData)
return true
}
if (!this.pendingSubmission || !this.isPublicFormPage || !this.form.auto_save) {
return false
}
const pendingData = this.pendingSubmission.get()
if (pendingData && Object.keys(pendingData).length !== 0) {
this.updatePendingDataFields(pendingData)
this.dataForm.resetAndFill(pendingData)
return true
}
return false
},
@@ -582,22 +621,146 @@ export default {
this.formPageIndex--
this.scrollToTop()
},
nextPage() {
async nextPage() {
if (!this.formModeStrategy.validation.validateOnNextPage) {
this.formPageIndex++
if (!this.isLastPage) {
this.formPageIndex++
}
this.scrollToTop()
return true
}
try {
this.dataForm.busy = true
const fieldsToValidate = this.currentFields
.filter(f => f.type !== 'payment')
.map(f => f.id)
// Validate non-payment fields first
if (fieldsToValidate.length > 0) {
await this.dataForm.validate('POST', `/forms/${this.form.slug}/answer`, {}, fieldsToValidate)
}
// Process payment if needed
if (!await this.doPayment()) {
return false // Payment failed or was required but not completed
}
// If validation and payment are successful, proceed
if (!this.isLastPage) {
this.formPageIndex++
this.scrollToTop()
}
return true
} catch (error) {
this.handleValidationError(error)
return false
} finally {
this.dataForm.busy = false
}
},
async doPayment() {
// Use the stripeElements from setup instead of calling useStripeElements
const { state: stripeState, processPayment, isCardPopulated, isReadyForPayment } = this.stripeElements
// Check if there's a payment block in the current step
if (!this.paymentBlock) {
return true // No payment needed for this step
}
const fieldsToValidate = this.currentFields.map(f => f.id)
this.dataForm.busy = true
this.dataForm.validate('POST', '/forms/' + this.form.slug + '/answer', {}, fieldsToValidate)
.then(() => {
this.formPageIndex++
// Skip if payment is already processed in the stripe state
if (stripeState.intentId) {
return true
}
// Skip if payment ID already exists in the form data
const paymentFieldValue = this.dataFormValue[this.paymentBlock.id]
if (paymentFieldValue && typeof paymentFieldValue === 'string' && paymentFieldValue.startsWith('pi_')) {
// If we have a valid payment intent ID in the form data, sync it to the stripe state
stripeState.intentId = paymentFieldValue
return true
}
// Check for the stripe object itself, not just the ready flag
if (stripeState.isStripeInstanceReady && !stripeState.stripe) {
stripeState.isStripeInstanceReady = false
}
// Only process payment if required or card has data
const shouldProcessPayment = this.paymentBlock.required || isCardPopulated.value
if (shouldProcessPayment) {
// If not ready yet, try a brief wait
if (!isReadyForPayment.value) {
try {
this.dataForm.busy = true
// Just wait a second to see if state updates (it should be reactive now)
await new Promise(resolve => setTimeout(resolve, 1000))
// Check if we're ready now
if (!isReadyForPayment.value) {
// Provide detailed diagnostics
let errorMsg = 'Payment system not ready. '
const details = []
if (!stripeState.stripeAccountId) {
details.push('No Stripe account connected')
}
if (!stripeState.isStripeInstanceReady) {
details.push('Stripe.js not initialized')
}
if (!stripeState.isCardElementReady) {
details.push('Card element not initialized')
}
errorMsg += details.join(', ') + '. Please refresh and try again.'
useAlert().error(errorMsg)
return false
}
} catch (error) {
return false
} finally {
this.dataForm.busy = false
}
}
try {
this.dataForm.busy = true
const result = await processPayment(this.form.slug, this.paymentBlock.required)
if (!result.success) {
// Handle payment error
if (result.error?.message) {
this.dataForm.errors.set(this.paymentBlock.id, result.error.message)
useAlert().error(result.error.message)
} else {
useAlert().error('Payment processing failed. Please try again.')
}
return false
}
// Payment successful
if (result.paymentIntent?.status === 'succeeded') {
useAlert().success('Thank you! Your payment is successful.')
return true
}
// Fallback error
useAlert().error('Something went wrong with the payment. Please try again.')
return false
} catch (error) {
useAlert().error(error?.message || 'Payment failed')
return false
} finally {
this.dataForm.busy = false
this.scrollToTop()
}).catch(this.handleValidationError)
return false
}
}
return true // Payment not required or no card data
},
scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' })

View File

@@ -19,7 +19,7 @@
>
<div
v-if="isAdminPreview"
class="absolute translate-y-full lg:translate-y-0 -bottom-1 left-1/2 -translate-x-1/2 lg:-translate-x-full lg:-left-1 lg:top-1 lg:bottom-0 hidden group-hover/nffield:block"
class="absolute translate-y-full lg:translate-y-0 -bottom-1 left-1/2 -translate-x-1/2 lg:-translate-x-full lg:-left-1 lg:top-1 lg:bottom-0 hidden group-hover/nffield:block z-10"
>
<div
class="flex lg:flex-col bg-white !bg-white dark:!bg-white border rounded-md shadow-sm z-50 p-[1px] relative"
@@ -32,7 +32,7 @@
<UTooltip
text="Add new field"
:popper="{ placement: 'right' }"
class="z-[100]"
:ui="{ container: 'z-50' }"
>
<Icon
name="i-heroicons-plus-circle-20-solid"
@@ -48,7 +48,7 @@
<UTooltip
text="Edit field settings"
:popper="{ placement: 'right' }"
class="z-[100]"
:ui="{ container: 'z-50' }"
>
<Icon
name="heroicons:cog-8-tooth-20-solid"
@@ -64,7 +64,7 @@
<UTooltip
text="Delete field"
:popper="{ placement: 'right' }"
class="z-[100]"
:ui="{ container: 'z-50' }"
>
<Icon
name="heroicons:trash-20-solid"
@@ -80,6 +80,7 @@
v-bind="inputProperties(field)"
:required="isFieldRequired"
:disabled="isFieldDisabled ? true : null"
:is-admin-preview="isAdminPreview"
/>
<template v-else>
<div
@@ -232,6 +233,7 @@ export default {
if (field.type === 'phone_number' && !field.use_simple_text_input) {
return 'PhoneInput'
}
return {
text: 'TextInput',
rich_text: 'RichTextAreaInput',
@@ -248,7 +250,8 @@ export default {
email: 'TextInput',
phone_number: 'TextInput',
matrix: 'MatrixInput',
barcode: 'BarcodeInput'
barcode: 'BarcodeInput',
payment: 'PaymentInput'
}[field.type]
},
isPublicFormPage() {
@@ -422,6 +425,11 @@ export default {
inputProperties.unavailableCountries = field.unavailable_countries ?? []
} else if (field.type === 'text' && field.secret_input) {
inputProperties.nativeType = 'password'
} else if (field.type === 'payment') {
inputProperties.direction = this.form.layout_rtl ? 'rtl' : 'ltr'
inputProperties.currency = field.currency
inputProperties.amount = field.amount
inputProperties.oauthProviderId = field.stripe_account_id
}
return inputProperties

View File

@@ -42,6 +42,11 @@
>
{{ element.title }}
</p>
<Icon
v-if="element.auth_required && !authenticated"
name="heroicons:lock-closed"
class="text-gray-400 w-4 h-4"
/>
</div>
</template>
</draggable>
@@ -73,6 +78,11 @@
>
{{ element.title }}
</p>
<Icon
v-if="element.auth_required && !authenticated"
name="heroicons:lock-closed"
class="text-gray-400 w-4 h-4"
/>
</div>
</template>
</draggable>
@@ -86,6 +96,8 @@ import blocksTypes from '~/data/blocks_types.json'
import BlockTypeIcon from '../BlockTypeIcon.vue'
const workingFormStore = useWorkingFormStore()
const authStore = useAuthStore()
const authenticated = computed(() => authStore.check)
const inputBlocks = computed(() => Object.values(blocksTypes).filter(block => !block.name.startsWith('nf-')))
const layoutBlocks = computed(() => Object.values(blocksTypes).filter(block => block.name.startsWith('nf-')))
@@ -95,10 +107,12 @@ const closeSidebar = () => {
}
const addBlock = (type) => {
workingFormStore.addBlock(type)
}
const handleInputClone = (item) => {
return item.name
}

View File

@@ -24,12 +24,21 @@
:form="form"
label="Auto save form response"
help="Saves form progress, allowing respondents to resume later."
class="mt-4"
:disabled="hasPaymentBlock"
/>
<UAlert
v-if="hasPaymentBlock"
color="primary"
variant="subtle"
title="You have a payment block in your form. so can't disable auto save"
class="max-w-md"
/>
<flat-select-input
:form="submissionOptions"
name="databaseAction"
class="max-w-xs"
class="mt-4 max-w-xs"
label="Database Submission Action"
:options="[
{ name: 'Create new record', value: 'create' },
@@ -133,7 +142,7 @@
enable-mentions
:mentions="form.properties"
name="submitted_text"
class="w-full"
class="w-full mt-4"
:form="form"
label="Success page text"
:required="false"
@@ -231,4 +240,8 @@ watch(submissionOptions, (val) => {
if (val.submissionMode === 'default') form.value.redirect_url = null
if (val.databaseAction === 'create') form.value.database_fields_update = null
}, { deep: true })
const hasPaymentBlock = computed(() => {
return form.value.properties.some(property => property.type === 'payment')
})
</script>

View File

@@ -194,6 +194,11 @@
@update:model-value="field = $event"
/>
<PaymentFieldOptions
v-if="field.type === 'payment'"
:field="field"
/>
<!-- Text Options -->
<div
v-if="field.type === 'text' && displayBasedOnAdvanced"
@@ -477,7 +482,7 @@
label="Pre-filled value"
/>
<text-input
v-else-if="!['files', 'signature', 'rich_text'].includes(field.type)"
v-else-if="!['files', 'signature', 'rich_text', 'payment'].includes(field.type)"
name="prefill"
class="mt-3"
:form="field"
@@ -605,6 +610,7 @@ import timezones from '~/data/timezones.json'
import countryCodes from '~/data/country_codes.json'
import CountryFlag from 'vue-country-flag-next'
import MatrixFieldOptions from './MatrixFieldOptions.vue'
import PaymentFieldOptions from './PaymentFieldOptions.vue'
import HiddenRequiredDisabled from './HiddenRequiredDisabled.vue'
import EditorSectionHeader from '~/components/open/forms/components/form-components/EditorSectionHeader.vue'
import { format } from 'date-fns'
@@ -613,7 +619,7 @@ import blocksTypes from '~/data/blocks_types.json'
export default {
name: 'FieldOptions',
components: { CountryFlag, MatrixFieldOptions, HiddenRequiredDisabled, EditorSectionHeader },
components: { CountryFlag, MatrixFieldOptions, HiddenRequiredDisabled, EditorSectionHeader, PaymentFieldOptions },
props: {
field: {
type: Object,
@@ -629,7 +635,7 @@ export default {
},
data() {
return {
typesWithoutPlaceholder: ['date', 'checkbox', 'files'],
typesWithoutPlaceholder: ['date', 'checkbox', 'files', 'payment'],
editorToolbarCustom: [
['bold', 'italic', 'underline', 'link']
],

View File

@@ -0,0 +1,139 @@
<template>
<div
v-if="field.type === 'payment'"
class="px-4"
>
<EditorSectionHeader
icon="i-heroicons-credit-card-20-solid"
title="Payment"
/>
<select-input
name="currency"
label="Currency"
:options="currencyList"
:form="field"
:required="true"
:searchable="true"
:disabled="stripeAccounts.length === 0"
/>
<text-input
name="amount"
label="Amount"
native-type="number"
:form="field"
:required="true"
:disabled="stripeAccounts.length === 0"
/>
<div v-if="stripeAccounts.length > 0">
<select-input
name="stripe_account_id"
label="Stripe Account"
:options="stripeAccounts"
:form="field"
:required="true"
/>
<p class="mt-4 text-sm text-center text-bold">
OR
</p>
</div>
<UButton
class="mt-4"
icon="i-heroicons-arrow-right"
block
trailing
:loading="stripeLoading"
@click.prevent="connectStripe"
>
Connect Stripe Account
</UButton>
<p class="text-sm text-gray-500 mt-3">
<a
target="#"
class="text-gray-500 cursor-pointer text-sm"
@click.prevent="crisp.openHelpdeskArticle('how-to-collect-payment-svig30')"
>
<Icon
name="heroicons:information-circle-16-solid"
class="h-3 w-3 mt-1"
/>
Learn how to accept payments
</a>
</p>
</div>
</template>
<script setup>
import EditorSectionHeader from '~/components/open/forms/components/form-components/EditorSectionHeader.vue'
import stripeCurrencies from "~/data/stripe_currencies.json"
import { useWindowMessage, WindowMessageTypes } from '~/composables/useWindowMessage'
const props = defineProps({
field: {
type: Object,
required: true
}
})
const crisp = useCrisp()
const providersStore = useOAuthProvidersStore()
const stripeLoading = ref(false)
// Setup window message listener for Stripe connection
const { listen, cleanup } = useWindowMessage()
onMounted(async () => {
await providersStore.fetchOAuthProviders()
if(props.field?.currency === undefined || props.field?.currency === null) {
props.field.currency = 'USD'
}
if(props.field?.amount === undefined || props.field?.amount === null) {
props.field.amount = 10
}
// Auto-select first Stripe account if none is selected
if (!props.field.stripe_account_id && stripeAccounts.value.length > 0) {
props.field.stripe_account_id = stripeAccounts.value[0].value
}
// Listen for Stripe connection message
listen(async () => {
await providersStore.fetchOAuthProviders()
// Auto-select first Stripe account after refresh if one isn't already selected (or maybe always select the newest? for now, first)
if (stripeAccounts.value.length > 0) {
props.field.stripe_account_id = stripeAccounts.value[0].value
}
useAlert().success('Stripe accounts updated.')
}, {
useMessageChannel: false,
acknowledge: false
}, `${WindowMessageTypes.OAUTH_PROVIDER_CONNECTED}:stripe`)
})
onUnmounted(() => {
// Cleanup listener (optional, as useWindowMessage handles it)
cleanup()
})
const stripeAccounts = computed(() => providersStore.getAll.filter((item) => item.provider === 'stripe').map((item) => ({
name: item.name + (item.email ? ' (' + item.email + ')' : ''),
value: item.id
})))
const currencyList = computed(() => {
return stripeCurrencies.map((item) => ({
name: item.name,
value: item.code
}))
})
const connectStripe = () => {
stripeLoading.value = true
providersStore.connect('stripe', false, true, true)
setTimeout(() => {
stripeLoading.value = false
}, 10000)
}
</script>

View File

@@ -148,6 +148,7 @@ import OpenMatrix from "./components/OpenMatrix.vue"
import OpenDate from "./components/OpenDate.vue"
import OpenFile from "./components/OpenFile.vue"
import OpenCheckbox from "./components/OpenCheckbox.vue"
import OpenPayment from "./components/OpenPayment.vue"
import ResizableTh from "./components/ResizableTh.vue"
import RecordOperations from "../components/RecordOperations.vue"
import clonedeep from "clone-deep"
@@ -218,6 +219,7 @@ export default {
email: shallowRef(OpenText),
phone_number: shallowRef(OpenText),
signature: shallowRef(OpenFile),
payment: shallowRef(OpenPayment),
barcode: shallowRef(OpenText),
},
}

View File

@@ -0,0 +1,39 @@
<template>
<span
v-if="value"
class="-mb-2"
>
<UButton
:to="paymentUrl"
icon="i-heroicons-arrow-top-right-on-square"
size="xs"
variant="link"
label="View Payment"
target="_blank"
trailing
/>
</span>
</template>
<script>
export default {
components: { },
props: {
value: {
type: Object,
},
},
data() {
return {}
},
computed: {
paymentUrl() {
if (!this.value) return null
const isLocal = useRuntimeConfig().public.env === 'local'
return `https://dashboard.stripe.com${isLocal ? '/test' : ''}/payments/${this.value}`
},
},
}
</script>