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 8981eb7
Show file tree
Hide file tree
Showing 5 changed files with 182 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}
setEditMode={setEditMode}
provider={provider}
owner={owner}
/>
<AddressForm closeForm={() => {}} provider={''} owner={''} />
</div>
)}
{activeTab === 'secondary' && (
<div>
<PaymentPage clientSecret={clientSecret} />
<EditPaymentMethodForm
isEditMode={isEditMode}
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,90 @@
import { PaymentElement, useElements, useStripe } from "@stripe/react-stripe-js"
import { useState } from "react"
import { Button } from "react-day-picker"

interface PaymentMethodFormProps {
isEditMode: boolean
setEditMode: (isEditMode: boolean) => void
provider: string
owner: string
}

const EditPaymentMethodForm = ({
isEditMode,

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

View workflow job for this annotation

GitHub Actions / Run Lint

'isEditMode' is defined but never used. Allowed unused args must match /^_/u
setEditMode,

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

View workflow job for this annotation

GitHub Actions / Run Lint

'setEditMode' is defined but never used. Allowed unused args must match /^_/u
provider,

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

View workflow job for this annotation

GitHub Actions / Run Lint

'provider' is defined but never used. Allowed unused args must match /^_/u
owner,

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

View workflow job for this annotation

GitHub Actions / Run Lint

'owner' is defined but never used. Allowed unused args must match /^_/u
}: PaymentMethodFormProps) => {
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-payment-method-update"

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

View workflow job for this annotation

GitHub Actions / Run Type Checker

Type '{ children: string; hook: string; type: "submit"; variant: string; disabled: boolean; onClick: (event: FormEvent<Element>) => Promise<void>; to: undefined; }' is not assignable to type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "ref"> & RefAttributes<...>'.

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

View workflow job for this annotation

GitHub Actions / Upload Bundle Stats - Staging

Type '{ children: string; hook: string; type: "submit"; variant: string; disabled: boolean; onClick: (event: FormEvent<Element>) => Promise<void>; to: undefined; }' is not assignable to type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "ref"> & RefAttributes<...>'.

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

View workflow job for this annotation

GitHub Actions / Upload Bundle Stats - Production

Type '{ children: string; hook: string; type: "submit"; variant: string; disabled: boolean; onClick: (event: FormEvent<Element>) => Promise<void>; to: undefined; }' is not assignable to type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "ref"> & RefAttributes<...>'.
type="submit"
variant="primary"
disabled={isSubmitting} // TODO - handle
onClick={handleSubmit}
to={undefined}
>
Save
</Button>
<Button
type="button"
hook="cancel-payment-method-update"

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

View workflow job for this annotation

GitHub Actions / Upload Bundle Stats - Staging

Type '{ children: string; type: "button"; hook: string; variant: string; onClick: () => void; to: undefined; }' is not assignable to type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "ref"> & RefAttributes<...>'.

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

View workflow job for this annotation

GitHub Actions / Upload Bundle Stats - Production

Type '{ children: string; type: "button"; hook: string; variant: string; onClick: () => void; to: undefined; }' is not assignable to type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "ref"> & RefAttributes<...>'.
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>
)
}

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,
})
}

0 comments on commit 8981eb7

Please sign in to comment.