NewPaymentMethodElement.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /**
  2. * Set up as a separate component, as we need any component using stripe/elements to be wrapped in Elements.
  3. *
  4. * If Elements is on a higher level, we risk losing all form state in case a payment fails.
  5. */
  6. import { zodResolver } from '@hookform/resolvers/zod'
  7. import { AddressElement, PaymentElement, useElements, useStripe } from '@stripe/react-stripe-js'
  8. import type { PaymentMethod } from '@stripe/stripe-js'
  9. import {
  10. StripeAddressElementChangeEvent,
  11. StripeAddressElementOptions,
  12. type SetupIntent,
  13. } from '@stripe/stripe-js'
  14. import { Form } from '@ui/components/shadcn/ui/form'
  15. import { Check, ChevronsUpDown } from 'lucide-react'
  16. import { forwardRef, useEffect, useId, useImperativeHandle, useMemo, useRef, useState } from 'react'
  17. import { useForm } from 'react-hook-form'
  18. import { toast } from 'sonner'
  19. import {
  20. Button,
  21. Checkbox,
  22. cn,
  23. Command,
  24. CommandEmpty,
  25. CommandGroup,
  26. CommandInput,
  27. CommandItem,
  28. CommandList,
  29. FormControl,
  30. FormField,
  31. FormItem,
  32. FormMessage,
  33. Input,
  34. Popover,
  35. PopoverContent,
  36. PopoverTrigger,
  37. } from 'ui'
  38. import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
  39. import { z } from 'zod'
  40. import { TAX_IDS } from '@/components/interfaces/Organization/BillingSettings/BillingCustomerData/TaxID.constants'
  41. import {
  42. getEffectiveTaxCountry,
  43. resolveStoredTaxId,
  44. } from '@/components/interfaces/Organization/BillingSettings/BillingCustomerData/TaxID.utils'
  45. import type { CustomerAddress, CustomerTaxId } from '@/data/organizations/types'
  46. import { getURL } from '@/lib/helpers'
  47. export const BillingCustomerDataSchema = z.object({
  48. tax_id_type: z.string(),
  49. tax_id_value: z.string().min(2, {
  50. message: 'Tax ID needs to be set.',
  51. }),
  52. tax_id_name: z.string(),
  53. })
  54. type BillingCustomerDataFormValues = z.infer<typeof BillingCustomerDataSchema>
  55. export type PaymentMethodElementRef = {
  56. confirmSetup: () => Promise<
  57. | {
  58. setupIntent: SetupIntent
  59. address: CustomerAddress
  60. customerName: string
  61. taxId: CustomerTaxId | null
  62. }
  63. | undefined
  64. >
  65. createPaymentMethod: () => Promise<
  66. | {
  67. paymentMethod: PaymentMethod
  68. address: CustomerAddress | null
  69. customerName: string | null
  70. taxId: CustomerTaxId | null
  71. }
  72. | undefined
  73. >
  74. getFormValues: () => Promise<
  75. | {
  76. address: CustomerAddress
  77. customerName: string
  78. taxId: CustomerTaxId | null
  79. }
  80. | undefined
  81. >
  82. }
  83. export const NewPaymentMethodElement = forwardRef(
  84. (
  85. {
  86. email,
  87. readOnly,
  88. currentAddress,
  89. currentTaxId,
  90. customerName,
  91. onAddressChange,
  92. onAddressIncomplete,
  93. onTaxIdChange,
  94. }: {
  95. email?: string | null | undefined
  96. readOnly: boolean
  97. currentAddress?: CustomerAddress | null
  98. currentTaxId?: CustomerTaxId | null
  99. customerName?: string | undefined
  100. onAddressChange?: (address: CustomerAddress) => void
  101. onAddressIncomplete?: () => void
  102. onTaxIdChange?: (taxId: CustomerTaxId | null) => void
  103. },
  104. ref
  105. ) => {
  106. const stripe = useStripe()
  107. const elements = useElements()
  108. const form = useForm<BillingCustomerDataFormValues>({
  109. resolver: zodResolver(BillingCustomerDataSchema as any),
  110. defaultValues: {
  111. tax_id_name: currentTaxId
  112. ? (resolveStoredTaxId(currentTaxId.type, currentTaxId.country, currentAddress?.country)
  113. ?.name ?? '')
  114. : '',
  115. tax_id_type: currentTaxId ? currentTaxId.type : '',
  116. tax_id_value: currentTaxId ? currentTaxId.value : '',
  117. },
  118. })
  119. // To avoid rendering the business checkbox prematurely and causing weird layout shifts, we wait until the address element is fully loaded
  120. const [fullyLoaded, setFullyLoaded] = useState(false)
  121. const [showTaxIDsPopover, setShowTaxIDsPopover] = useState(false)
  122. const taxIdListboxId = useId()
  123. const onSelectTaxIdType = (name: string) => {
  124. const selectedTaxIdOption = TAX_IDS.find((option) => option.name === name)
  125. if (!selectedTaxIdOption) return
  126. form.setValue('tax_id_type', selectedTaxIdOption.type)
  127. form.setValue('tax_id_value', '')
  128. form.setValue('tax_id_name', name)
  129. }
  130. const { tax_id_name, tax_id_value } = form.watch()
  131. const selectedTaxId = TAX_IDS.find((option) => option.name === tax_id_name)
  132. const [purchasingAsBusiness, setPurchasingAsBusiness] = useState(currentTaxId != null)
  133. const [stripeAddress, setStripeAddress] = useState<
  134. StripeAddressElementChangeEvent['value'] | undefined
  135. >(undefined)
  136. useEffect(() => {
  137. if (!onTaxIdChange) return
  138. if (purchasingAsBusiness && selectedTaxId && tax_id_value) {
  139. onTaxIdChange({
  140. country: getEffectiveTaxCountry(selectedTaxId),
  141. type: selectedTaxId.type,
  142. value: tax_id_value,
  143. })
  144. } else {
  145. onTaxIdChange(null)
  146. }
  147. }, [purchasingAsBusiness, selectedTaxId, tax_id_value, onTaxIdChange])
  148. const addressCountry = stripeAddress?.address.country
  149. const availableTaxIds = useMemo(() => {
  150. const country = addressCountry || null
  151. return TAX_IDS.filter((taxId) => country == null || taxId.countryIso2 === country).sort(
  152. (a, b) => a.country.localeCompare(b.country)
  153. )
  154. }, [addressCountry])
  155. const createPaymentMethod = async (): ReturnType<
  156. PaymentMethodElementRef['createPaymentMethod']
  157. > => {
  158. if (!stripe || !elements) return
  159. const isValid = await form.trigger()
  160. if (
  161. purchasingAsBusiness &&
  162. availableTaxIds.length > 0 &&
  163. (!isValid || !form.getValues('tax_id_value'))
  164. ) {
  165. return
  166. }
  167. await elements.submit()
  168. // To avoid double 3DS confirmation, we just create the payment method here, as there might be a confirmation step while doing the actual payment
  169. const { error, paymentMethod } = await stripe.createPaymentMethod({
  170. elements,
  171. })
  172. if (error || paymentMethod == null) {
  173. toast.error(error?.message ?? ' Failed to process card details')
  174. return
  175. }
  176. const addressElement = await elements.getElement('address')!.getValue()
  177. return {
  178. paymentMethod,
  179. address: {
  180. ...addressElement.value.address,
  181. line2: addressElement.value.address.line2 || undefined,
  182. },
  183. customerName: addressElement.value.name,
  184. taxId: getConfiguredTaxId(),
  185. }
  186. }
  187. function getConfiguredTaxId(): CustomerTaxId | null {
  188. const isValidForCountry = selectedTaxId && availableTaxIds.includes(selectedTaxId)
  189. return purchasingAsBusiness && isValidForCountry
  190. ? {
  191. country: getEffectiveTaxCountry(selectedTaxId),
  192. type: selectedTaxId.type,
  193. value: form.getValues('tax_id_value'),
  194. }
  195. : null
  196. }
  197. const confirmSetup = async (): ReturnType<PaymentMethodElementRef['confirmSetup']> => {
  198. if (!stripe || !elements) return
  199. await elements.submit()
  200. const { error, setupIntent } = await stripe.confirmSetup({
  201. elements,
  202. redirect: 'if_required',
  203. confirmParams: { return_url: `${getURL()}/org/_/billing` },
  204. })
  205. if (error || setupIntent == null) {
  206. toast.error(error?.message ?? ' Failed to process card details')
  207. return
  208. }
  209. const addressElement = await elements.getElement('address')!.getValue()
  210. return {
  211. setupIntent,
  212. address: {
  213. ...addressElement.value.address,
  214. line2: addressElement.value.address.line2 || undefined,
  215. },
  216. customerName: addressElement.value.name,
  217. taxId: getConfiguredTaxId(),
  218. }
  219. }
  220. const getFormValues = async (): ReturnType<PaymentMethodElementRef['getFormValues']> => {
  221. if (!elements) return
  222. const isValid = await form.trigger()
  223. if (
  224. purchasingAsBusiness &&
  225. availableTaxIds.length > 0 &&
  226. (!isValid || !form.getValues('tax_id_value'))
  227. ) {
  228. return
  229. }
  230. const { error: submitError } = await elements.submit()
  231. if (submitError) return
  232. const addressElement = await elements.getElement('address')!.getValue()
  233. return {
  234. address: {
  235. ...addressElement.value.address,
  236. line2: addressElement.value.address.line2 || undefined,
  237. },
  238. customerName: addressElement.value.name,
  239. taxId: getConfiguredTaxId(),
  240. }
  241. }
  242. useImperativeHandle(ref, () => ({
  243. createPaymentMethod,
  244. confirmSetup,
  245. getFormValues,
  246. }))
  247. const addressOptions: StripeAddressElementOptions = useMemo(
  248. () => ({
  249. mode: 'billing',
  250. autocomplete: {
  251. apiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_KEY!,
  252. mode: 'google_maps_api',
  253. },
  254. display: { name: purchasingAsBusiness ? 'organization' : 'full' },
  255. // Use live form state (stripeAddress) so the address survives remounts triggered
  256. // by the purchasingAsBusiness toggle (which changes the key prop). Without this,
  257. // the element resets to the original currentAddress prop, causing the country to
  258. // revert and the tax ID selector to fall out of sync.
  259. defaultValues: {
  260. address: stripeAddress?.address ?? currentAddress ?? undefined,
  261. name: stripeAddress?.name ?? customerName,
  262. },
  263. }),
  264. [purchasingAsBusiness]
  265. )
  266. // Reset tax ID fields when the billing country changes and preselect the
  267. // first available tax ID for the new country.
  268. const prevCountryRef = useRef(addressCountry)
  269. useEffect(() => {
  270. if (!addressCountry) return
  271. const isCountryChange =
  272. prevCountryRef.current !== undefined && prevCountryRef.current !== addressCountry
  273. prevCountryRef.current = addressCountry
  274. // On country change: always reset to the new country's default
  275. // On initial load: only preselect if there's no existing tax id
  276. if (isCountryChange || !currentTaxId) {
  277. if (availableTaxIds.length) {
  278. const taxIdOption = availableTaxIds[0]
  279. form.setValue('tax_id_type', taxIdOption.type)
  280. form.setValue('tax_id_value', '')
  281. form.setValue('tax_id_name', taxIdOption.name)
  282. } else {
  283. form.setValue('tax_id_type', '')
  284. form.setValue('tax_id_value', '')
  285. form.setValue('tax_id_name', '')
  286. }
  287. }
  288. }, [availableTaxIds, addressCountry, currentTaxId, form])
  289. return (
  290. <div className="space-y-2">
  291. <p className="text-sm text-foreground-lighter">
  292. Please ensure CVC and postal codes match what’s on file for your card.
  293. </p>
  294. <PaymentElement
  295. options={{
  296. layout: 'tabs',
  297. defaultValues: { billingDetails: { email: email ?? undefined } },
  298. readOnly,
  299. }}
  300. />
  301. {fullyLoaded && (
  302. <div className="flex items-center space-x-2 py-4">
  303. <Checkbox
  304. id="business"
  305. checked={purchasingAsBusiness}
  306. onCheckedChange={() => setPurchasingAsBusiness(!purchasingAsBusiness)}
  307. />
  308. <label htmlFor="business" className="text-foreground text-sm leading-none">
  309. I’m purchasing as a business
  310. </label>
  311. </div>
  312. )}
  313. <AddressElement
  314. options={addressOptions}
  315. // Force reload after changing purchasingAsBusiness setting, it seems like the element does not reload otherwise
  316. key={`address-elements-${purchasingAsBusiness}`}
  317. onChange={(evt) => {
  318. setStripeAddress(evt.value)
  319. if (evt.complete) {
  320. onAddressChange?.({
  321. ...evt.value.address,
  322. line2: evt.value.address.line2 || undefined,
  323. })
  324. } else {
  325. onAddressIncomplete?.()
  326. }
  327. }}
  328. onReady={() => setFullyLoaded(true)}
  329. />
  330. {purchasingAsBusiness && availableTaxIds.length > 0 && (
  331. <Form {...form}>
  332. <div className="grid grid-cols-2 gap-x-2 w-full">
  333. <FormField
  334. name="tax_id_name"
  335. control={form.control}
  336. render={() => (
  337. <FormItemLayout hideMessage layout="vertical">
  338. <Popover open={showTaxIDsPopover} onOpenChange={setShowTaxIDsPopover}>
  339. <PopoverTrigger asChild>
  340. <FormControl>
  341. <Button
  342. type="default"
  343. role="combobox"
  344. size="medium"
  345. aria-expanded={showTaxIDsPopover}
  346. aria-controls={taxIdListboxId}
  347. className={cn(
  348. 'w-full justify-between h-[34px]',
  349. !selectedTaxId && 'text-muted'
  350. )}
  351. iconRight={
  352. <ChevronsUpDown
  353. className="ml-2 h-4 w-4 shrink-0 opacity-50"
  354. strokeWidth={1.5}
  355. />
  356. }
  357. >
  358. {selectedTaxId
  359. ? `${selectedTaxId.country} - ${selectedTaxId.name}`
  360. : 'Select tax ID'}
  361. </Button>
  362. </FormControl>
  363. </PopoverTrigger>
  364. <PopoverContent
  365. id={taxIdListboxId}
  366. sameWidthAsTrigger
  367. className="p-0"
  368. align="start"
  369. >
  370. <Command>
  371. <CommandInput placeholder="Search tax ID..." />
  372. <CommandList>
  373. <CommandEmpty>No tax ID found.</CommandEmpty>
  374. <CommandGroup>
  375. {availableTaxIds.map((option) => (
  376. <CommandItem
  377. key={option.name}
  378. value={`${option.country} - ${option.name}`}
  379. onSelect={() => {
  380. onSelectTaxIdType(option.name)
  381. setShowTaxIDsPopover(false)
  382. }}
  383. >
  384. <Check
  385. className={cn(
  386. 'mr-2 h-4 w-4',
  387. selectedTaxId?.name === option.name
  388. ? 'opacity-100'
  389. : 'opacity-0'
  390. )}
  391. />
  392. {option.country} - {option.name}
  393. </CommandItem>
  394. ))}
  395. </CommandGroup>
  396. </CommandList>
  397. </Command>
  398. </PopoverContent>
  399. </Popover>
  400. <FormMessage />
  401. </FormItemLayout>
  402. )}
  403. />
  404. {selectedTaxId && (
  405. <FormField
  406. name="tax_id_value"
  407. control={form.control}
  408. render={({ field }) => (
  409. <FormItem>
  410. <FormControl>
  411. <Input {...field} placeholder={selectedTaxId?.placeholder} />
  412. </FormControl>
  413. <FormMessage />
  414. </FormItem>
  415. )}
  416. />
  417. )}
  418. </div>
  419. </Form>
  420. )}
  421. </div>
  422. )
  423. }
  424. )
  425. NewPaymentMethodElement.displayName = 'NewPaymentMethodElement'