Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
suejung-sentry committed Jan 7, 2025
1 parent 747f183 commit 2ccab2c
Show file tree
Hide file tree
Showing 6 changed files with 248 additions and 118 deletions.
7 changes: 6 additions & 1 deletion src/pages/PlanPage/PlanPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import config from 'config'

import { SentryRoute } from 'sentry'

import { useStripeSetupIntent } from 'services/account/useStripeSetupIntent'
import LoadingLogo from 'ui/LoadingLogo'

import { PlanProvider } from './context'
Expand Down Expand Up @@ -37,6 +38,7 @@ function PlanPage() {
const { data: ownerData } = useSuspenseQueryV5(
PlanPageDataQueryOpts({ owner, provider })
)
const { data: setupIntent } = useStripeSetupIntent({ owner, provider })

if (config.IS_SELF_HOSTED || !ownerData?.isCurrentUserPartOfOrg) {
return <Redirect to={`/${provider}/${owner}`} />
Expand All @@ -45,7 +47,10 @@ function PlanPage() {
return (
<div className="flex flex-col gap-4">
<Tabs />
<Elements stripe={stripePromise}>
<Elements
stripe={stripePromise}
options={{ clientSecret: setupIntent?.clientSecret }}
>
<PlanProvider>
<PlanBreadcrumb />
<Suspense fallback={<Loader />}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import PaymentMethod from './PaymentMethod'
import Button from 'ui/Button'
import { useState } from 'react'
import A from 'ui/A'
import EditablePaymentMethod from './EditPaymentMethod'
import EditPaymentMethod from './EditPaymentMethod'

interface URLParams {
provider: string
Expand All @@ -29,8 +29,6 @@ function BillingDetails() {
return null
}

console.log('iseditmode', isEditMode)

return (
<div className="flex flex-col divide-y border">
{/* Billing Details Section */}
Expand Down Expand Up @@ -68,7 +66,12 @@ function BillingDetails() {
)}
</div>
{isEditMode ? (
<EditablePaymentMethod />
<EditPaymentMethod
isEditMode={isEditMode}
setEditMode={setEditMode}
provider={provider}
owner={owner}
/>
) : (
<>
<EmailAddress />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,121 +1,22 @@
import {
Elements,
PaymentElement,
useElements,
useStripe,
} from '@stripe/react-stripe-js'
import { loadStripe } from '@stripe/stripe-js'
import React, { useState } from 'react'

import Button from 'ui/Button'

import AddressForm from '../Address/AddressForm'

// TODO - fetch from API
const STRIPE_PUBLISHABLE_KEY = process.env.STRIPE_PUBLISHABLE_KEY || ''
const MANUALLY_FETCHED_CLIENT_SECRET = process.env.STRIPE_CLIENT_SECRET || ''

const stripePromise = loadStripe(STRIPE_PUBLISHABLE_KEY)

interface PaymentFormProps {
clientSecret: string
}

const PaymentForm: React.FC<PaymentFormProps> = () => {
const stripe = useStripe()
const elements = useElements()
const [isSubmitting, setIsSubmitting] = useState(false)
const [errorMessage, setErrorMessage] = useState<string | null>(null)

const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault()
setIsSubmitting(true)
setErrorMessage(null)

if (!stripe || !elements) {
setErrorMessage('Stripe has not loaded yet. Please try again.')
setIsSubmitting(false)
return
}

const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
// eslint-disable-next-line camelcase
return_url: 'https://codecov.io',
},
})

if (error) {
setErrorMessage(error.message || 'An unexpected error occurred.')
setIsSubmitting(false)
} else {
setIsSubmitting(false)
}
}

return (
<div>
<PaymentElement
options={{
layout: 'tabs',
defaultValues: {
billingDetails: {
name: 'John Doe',
},
},
}}
/>
<div className="mb-8 mt-4 flex gap-1">
<Button
hook="submit-address-update"
type="submit"
variant="primary"
disabled={isSubmitting} // TODO - handle
onClick={handleSubmit}
to={undefined}
>
Save
</Button>
<Button
type="button"
hook="cancel-address-update"
variant="plain"
// disabled={isLoading}
onClick={() => console.log('TODO - implement me')} // TODO - implement me
to={undefined}
>
Cancel
</Button>
</div>

{errorMessage && <div className="text-red-500">{errorMessage}</div>}
</div>
)
}

const PaymentPage: React.FC<{ clientSecret: string }> = ({ clientSecret }) => {
const options = {
clientSecret,
appearance: {
theme: 'stripe' as const,
},
}
import EditPaymentMethodForm from './EditPaymentMethodForm'

return (
<Elements stripe={stripePromise} options={options}>
<PaymentForm clientSecret={clientSecret} />
</Elements>
)
interface EditPaymentMethodProps {
isEditMode: boolean
setEditMode: (isEditMode: boolean) => void
provider: string
owner: string
}

interface EditablePaymentMethodProps {
clientSecret: string
}

const EditPaymentMethod: React.FC<EditablePaymentMethodProps> = () => {
const clientSecret = MANUALLY_FETCHED_CLIENT_SECRET // TODO - fetch from API

const EditPaymentMethod = ({
isEditMode,
setEditMode,
provider,
owner,
}: EditPaymentMethodProps) => {
const [activeTab, setActiveTab] = useState<'primary' | 'secondary'>('primary')

return (
Expand Down Expand Up @@ -143,13 +44,23 @@ const EditPaymentMethod: React.FC<EditablePaymentMethodProps> = () => {
<div className="m-4">
{activeTab === 'primary' && (
<div>
<PaymentPage clientSecret={clientSecret} />
<EditPaymentMethodForm
isEditMode={isEditMode}

Check failure on line 48 in src/pages/PlanPage/subRoutes/CurrentOrgPlan/BillingDetails/EditPaymentMethod/EditPaymentMethod.tsx

View workflow job for this annotation

GitHub Actions / Upload Bundle Stats - Production

Type '{ isEditMode: boolean; setEditMode: (isEditMode: boolean) => void; provider: string; owner: string; }' is not assignable to type 'IntrinsicAttributes & PaymentMethodFormProps'.

Check failure on line 48 in src/pages/PlanPage/subRoutes/CurrentOrgPlan/BillingDetails/EditPaymentMethod/EditPaymentMethod.tsx

View workflow job for this annotation

GitHub Actions / Upload Bundle Stats - Staging

Type '{ isEditMode: boolean; setEditMode: (isEditMode: boolean) => void; provider: string; owner: string; }' is not assignable to type 'IntrinsicAttributes & PaymentMethodFormProps'.

Check failure on line 48 in src/pages/PlanPage/subRoutes/CurrentOrgPlan/BillingDetails/EditPaymentMethod/EditPaymentMethod.tsx

View workflow job for this annotation

GitHub Actions / Run Type Checker

Type '{ isEditMode: boolean; setEditMode: (isEditMode: boolean) => void; provider: string; owner: string; }' is not assignable to type 'IntrinsicAttributes & PaymentMethodFormProps'.
setEditMode={setEditMode}
provider={provider}
owner={owner}
/>
<AddressForm closeForm={() => {}} provider={''} owner={''} />
</div>
)}
{activeTab === 'secondary' && (
<div>
<PaymentPage clientSecret={clientSecret} />
<EditPaymentMethodForm
isEditMode={isEditMode}

Check failure on line 59 in src/pages/PlanPage/subRoutes/CurrentOrgPlan/BillingDetails/EditPaymentMethod/EditPaymentMethod.tsx

View workflow job for this annotation

GitHub Actions / Upload Bundle Stats - Production

Type '{ isEditMode: boolean; setEditMode: (isEditMode: boolean) => void; provider: string; owner: string; }' is not assignable to type 'IntrinsicAttributes & PaymentMethodFormProps'.

Check failure on line 59 in src/pages/PlanPage/subRoutes/CurrentOrgPlan/BillingDetails/EditPaymentMethod/EditPaymentMethod.tsx

View workflow job for this annotation

GitHub Actions / Upload Bundle Stats - Staging

Type '{ isEditMode: boolean; setEditMode: (isEditMode: boolean) => void; provider: string; owner: string; }' is not assignable to type 'IntrinsicAttributes & PaymentMethodFormProps'.
setEditMode={setEditMode}
provider={provider}
owner={owner}
/>
<AddressForm closeForm={() => {}} provider={''} owner={''} />
</div>
)}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { PaymentElement, useElements } from '@stripe/react-stripe-js'
import cs from 'classnames'
import { useState } from 'react'

import { useUpdatePaymentMethod } from 'services/account/useUpdatePaymentMethod'
import { Theme, useThemeContext } from 'shared/ThemeContext'
import Button from 'ui/Button'

interface PaymentMethodFormProps {
closeForm: () => void
provider: string
owner: string
}

const EditPaymentMethodForm = ({
closeForm,
provider,
owner,
}: PaymentMethodFormProps) => {
const [errorState, setErrorState] = useState('')

Check failure on line 20 in src/pages/PlanPage/subRoutes/CurrentOrgPlan/BillingDetails/EditPaymentMethod/EditPaymentMethodForm.tsx

View workflow job for this annotation

GitHub Actions / Run Lint

'setErrorState' is assigned a value but never used. Allowed unused elements of array destructuring must match /^_/u
const { theme } = useThemeContext()
const isDarkMode = theme === Theme.DARK

Check failure on line 22 in src/pages/PlanPage/subRoutes/CurrentOrgPlan/BillingDetails/EditPaymentMethod/EditPaymentMethodForm.tsx

View workflow job for this annotation

GitHub Actions / Run Lint

'isDarkMode' is assigned a value but never used. Allowed unused vars must match /^_/u

const elements = useElements()
const {
mutate: updatePaymentMethod,
isLoading,
error,
reset,
} = useUpdatePaymentMethod({
provider,
owner,
})

function submit(e: React.FormEvent) {
e.preventDefault()

if (!elements) {
return null
}

updatePaymentMethod(elements.getElement(PaymentElement), {
onSuccess: closeForm,
})
}

const showError = (error && !reset) || errorState

return (
<form onSubmit={submit} aria-label="form">
<div className={cs('flex flex-col gap-3')}>
<div className="mt-2 flex flex-col gap-2">
<PaymentElement
options={{
layout: 'tabs',
defaultValues: {
billingDetails: {
name: 'John Doe',
},
},
}}
/>
<p className="mt-1 text-ds-primary-red">
{showError && (error?.message || errorState)}
</p>
<div className="mb-8 mt-4 flex gap-1">
<Button
hook="update-payment"
type="submit"
variant="primary"
disabled={isLoading}
to={undefined}
>
Update
</Button>
<Button
type="button"
hook="cancel-payment"
variant="plain"
disabled={isLoading}
onClick={closeForm}
to={undefined}
>
Cancel
</Button>
</div>
</div>
</div>
</form>
)
}

export default EditPaymentMethodForm
55 changes: 55 additions & 0 deletions src/services/account/useStripeSetupIntent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { useQuery } from '@tanstack/react-query'
import { z } from 'zod'

import Api from 'shared/api'
import { NetworkErrorObject } from 'shared/api/helpers'

export const StripeSetupIntentSchema = z.object({
clientSecret: z.string(),
})

export interface UseStripeSetupIntentArgs {
provider: string
owner: string
opts?: {
enabled?: boolean
}
}

function fetchStripeSetupIntent({
provider,
owner,
signal,
}: {
provider: string
owner: string
signal?: AbortSignal
}) {
const path = `/${provider}/${owner}/account-details/setup_intent`
return Api.get({ path, provider, signal })
}

export function useStripeSetupIntent({
provider,
owner,
opts = {},
}: UseStripeSetupIntentArgs) {
return useQuery({
queryKey: ['setupIntent', provider, owner],
queryFn: ({ signal }) =>
fetchStripeSetupIntent({ provider, owner, signal }).then((res) => {
const parsedRes = StripeSetupIntentSchema.safeParse(res)

if (!parsedRes.success) {
return Promise.reject({
status: 404,
data: {},
dev: 'useStripeSetupIntent - 404 failed to parse',
} satisfies NetworkErrorObject)
}

return parsedRes.data
}),
...opts,
})
}
Loading

0 comments on commit 2ccab2c

Please sign in to comment.