Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Donation flow more fixes #1991

Merged
merged 14 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions public/locales/bg/donation-flow.json
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@
}
},
"alerts": {
"subscription-unauthorized": "Ако желаете да правите ежемесечни дарения, моля влезте с вашия профил в платформата или се регистрирайте, ако все още не сте го направили",
"error": "Нещо се обърка, моля опитайте пак или презаредете страницата"
},
"total": "Общо"
Expand Down
4 changes: 4 additions & 0 deletions public/locales/en/donation-flow.json
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@
"title": "Transaction",
"description": "The transaction is only to compensate the transfer and is calculated based on your method of payment. \"Podkrepi.bg\" works with 0% commission."
},
"alerts": {
"subscription-unauthorized": "If you wish to make monthly donations, please sign in with your account or register on the platform if you still have not.",
"error": "Something went wrong, please try again or refresh the page"
},
"total": "Total",
"field": {
"anonymous": {
Expand Down
15 changes: 10 additions & 5 deletions src/components/client/donation-flow/DonationFlowForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,14 @@ export const validationSchema: yup.SchemaOf<DonationFormData> = yup
export function DonationFlowForm() {
const formikRef = useRef<FormikProps<DonationFormData> | null>(null)
const { t } = useTranslation('donation-flow')
const { campaign, setupIntent, paymentError, setPaymentError, idempotencyKey } = useDonationFlow()
const { campaign, setupIntent, paymentError, setPaymentError } = useDonationFlow()
const stripe = useStripe()
const elements = useElements()
const router = useRouter()
const updateSetupIntentMutation = useUpdateSetupIntent()
const cancelSetupIntentMutation = useCancelSetupIntent()
const paymentMethodSectionRef = React.useRef<HTMLDivElement>(null)
const authenticationSectionRef = React.useRef<HTMLDivElement>(null)
const stripeChargeRef = React.useRef<string>(idempotencyKey)
const [showCancelDialog, setShowCancelDialog] = React.useState(false)
const [submitPaymentLoading, setSubmitPaymentLoading] = React.useState(false)
const { data: { user: person } = { user: null } } = useCurrentPerson()
Expand Down Expand Up @@ -172,11 +171,19 @@ export function DonationFlowForm() {
return
}

if (values.mode === 'subscription' && !session?.user?.sub) {
setSubmitPaymentLoading(false)
formikRef.current?.setFieldError(
'authentication',
t('step.summary.alerts.subscription-unauthorized'),
)
return
}

// Update the setup intent with the latest calculated amount
try {
const updatedIntent = await updateSetupIntentMutation.mutateAsync({
id: setupIntent.id,
idempotencyKey,
payload: {
metadata: {
type: person?.company ? DonationType.corporate : DonationType.donation,
Expand All @@ -199,7 +206,6 @@ export function DonationFlowForm() {
campaign,
values,
session,
stripeChargeRef.current,
)
router.push(
`${window.location.origin}${routes.campaigns.donationStatus(campaign.slug)}?p_status=${
Expand All @@ -212,7 +218,6 @@ export function DonationFlowForm() {
type: 'invalid_request_error',
message: (error as StripeError).message ?? t('step.summary.alerts.error'),
})
stripeChargeRef.current = crypto.randomUUID()
return
}

Expand Down
7 changes: 1 addition & 6 deletions src/components/client/donation-flow/DonationFlowPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,16 @@ import { CampaignResponse } from 'gql/campaigns'
export default function DonationFlowPage({
slug,
setupIntent,
idempotencyKey,
}: {
slug: string
setupIntent: Stripe.SetupIntent
idempotencyKey: string
}) {
const { data } = useViewCampaign(slug)
//This query needs to be prefetched in the pages folder
//otherwise on the first render the data will be undefined
const campaign = data?.campaign as CampaignResponse
return (
<DonationFlowProvider
campaign={campaign}
setupIntent={setupIntent}
idempotencyKey={idempotencyKey}>
<DonationFlowProvider campaign={campaign} setupIntent={setupIntent}>
<StripeElementsProvider>
<DonationFlowLayout campaign={campaign}>
<DonationFlowForm />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,21 @@ type DonationContext = {
setPaymentError: React.Dispatch<React.SetStateAction<StripeError | null>>
campaign: CampaignResponse
stripe: Promise<StripeType | null>
idempotencyKey: string
}

const DonationFlowContext = React.createContext({} as DonationContext)

export const DonationFlowProvider = ({
campaign,
setupIntent,
idempotencyKey,
children,
}: PropsWithChildren<{
campaign: CampaignResponse
setupIntent: Stripe.SetupIntent
idempotencyKey: string
}>) => {
const [paymentError, setPaymentError] = React.useState<StripeError | null>(null)

const value = {
idempotencyKey,
setupIntent,
paymentError,
setPaymentError,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ export async function confirmStripePayment(
campaign: CampaignResponse,
values: DonationFormData,
session: Session | null,
idempotencyKey: string,
): Promise<StripeJS.PaymentIntent> {
if (setupIntent.status !== DonationFormPaymentStatus.SUCCEEDED) {
const { error: intentError } = await stripe.confirmSetup({
Expand All @@ -30,12 +29,7 @@ export async function confirmStripePayment(
throw intentError
}
}
const payment = await createIntentFromSetup(
setupIntent.id,
idempotencyKey,
values.mode as PaymentMode,
session,
)
const payment = await createIntentFromSetup(setupIntent.id, values.mode as PaymentMode, session)

if (payment.data.status === DonationFormPaymentStatus.REQUIRES_ACTION) {
const { error: confirmPaymentError } = await stripe.confirmCardPayment(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,13 @@ export default function PaymentMethod({
{
value: 'card',
label: t('step.payment-method.field.method.card'),
icon: <CardIcon sx={{ width: 80, height: 80, minWidth: 421 }} />,
icon: <CardIcon sx={{ width: 80, height: 80, minWidth: 480 }} />,
disabled: false,
},
{
value: 'bank',
label: t('step.payment-method.field.method.bank'),
icon: <BankIcon sx={{ width: 80, height: 80, minWidth: 421 }} />,
icon: <BankIcon sx={{ width: 80, height: 80, minWidth: 480 }} />,
disabled: mode.value === 'subscription',
},
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,17 @@ export const TaxesCheckbox = () => {
/>
</Grid2>
</Grid2>
<Trans
t={t}
i18nKey="step.payment-method.alert.calculated-fees"
values={{
amount: moneyPublicDecimals2(amountWithoutFees.value),
fees: moneyPublicDecimals2(amountWithFees.value - amountWithoutFees.value),
totalAmount: moneyPublicDecimals2(amountWithFees.value),
}}
/>
{!!amountWithFees.value && (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this to assertain that the value is a non-zero number? As in !isNaN(amountWithFees.value) && amountWithFees.value > 0

It's hard to read. And also negative numbers give true value as well => !!-1 === true

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea is to show the text from below only if amountWithFees.value is truthy value. The double negation is needed in order to convert the amountWithFees.value to boolean, otherwise if we just pass amountWithFees.value it would display 0 in the DOM.

<Trans
t={t}
i18nKey="step.payment-method.alert.calculated-fees"
values={{
amount: moneyPublicDecimals2(amountWithoutFees.value),
fees: moneyPublicDecimals2(amountWithFees.value - amountWithoutFees.value),
totalAmount: moneyPublicDecimals2(amountWithFees.value),
}}
/>
)}
</>
)
}
5 changes: 3 additions & 2 deletions src/components/common/ExternalLink.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Link, LinkProps } from '@mui/material'
import { LinkProps } from '@mui/material'
import { PropsWithChildren } from 'react'
import Link from './Link'

type ExternalLinkParams = PropsWithChildren<LinkProps>

export default function ExternalLink({ children, ...props }: ExternalLinkParams) {
return (
<Link target="_blank" rel="noreferrer noopener" {...props}>
<Link target="_blank" rel="noreferrer noopener" {...props} sx={{ textDecoration: 'none' }}>
{children}
</Link>
)
Expand Down
2 changes: 1 addition & 1 deletion src/components/common/Link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ import { LinkProps, Link as MuiLink } from '@mui/material'
import NextLink from 'next/link'

export default function Link(props: LinkProps<'a'>) {
return <MuiLink component={NextLink} {...props} />
return <MuiLink component={NextLink} {...props} sx={{ textDecoration: 'none' }} />
}
15 changes: 12 additions & 3 deletions src/components/common/form/RadioButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,20 +70,29 @@ type RadioButtonProps = {
error?: boolean
}

function RadioButton({ checked, label, muiRadioButtonProps, value, error }: RadioButtonProps) {
function RadioButton({
checked,
label,
muiRadioButtonProps,
value,
disabled,
error,
}: RadioButtonProps) {
return (
<StyledRadioButton error={error}>
<FormControlLabel
value={value}
className={`${classes.radioWrapper} ${checked ? classes.checked : null}`}
sx={checked ? {} : undefined}
disabled={disabled}
sx={disabled ? { backgroundColor: '#e0e0e0', opacity: 0.7 } : {}}
className={`${classes.radioWrapper} ${checked && !disabled ? classes.checked : null}`}
label={
<Typography className={classes.label} sx={{ wordBreak: 'break-word' }}>
{label}
</Typography>
}
control={
<Radio
disabled={disabled}
icon={<div className={`${classes.circle}`} />}
checkedIcon={
<Check color="primary" className={checked ? classes.checkIcon : undefined} />
Expand Down
1 change: 0 additions & 1 deletion src/gql/donations.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ export type CancelSetupIntentInput = {

export type UpdateSetupIntentInput = {
id: string
idempotencyKey: string
payload: Stripe.SetupIntentUpdateParams
}

Expand Down
4 changes: 1 addition & 3 deletions src/pages/campaigns/donation/[slug]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,17 @@ export const getServerSideProps: GetServerSideProps = async (ctx: GetServerSideP
)

//Generate idempotencyKey to prevent duplicate creation of resources in stripe
const idempotencyKey = crypto.randomUUID()

//create and prefetch the payment intent
const { data: setupIntent } = await apiClient.post<
Stripe.SetupIntentCreateParams,
AxiosResponse<Stripe.SetupIntentCreateParams>
>(endpoints.donation.createSetupIntent.url, idempotencyKey)
>(endpoints.donation.createSetupIntent.url)

return {
props: {
slug,
setupIntent,
idempotencyKey,
dehydratedState: dehydrate(client),
...(await serverSideTranslations(ctx.locale ?? 'bg', [
'common',
Expand Down
12 changes: 6 additions & 6 deletions src/service/apiEndpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,19 +154,19 @@ export const endpoints = {
createSubscriptionPayment: <Endpoint>{ url: '/stripe/create-subscription', method: 'POST' },
createPaymentIntent: <Endpoint>{ url: '/stripe/payment-intent', method: 'POST' },
createSetupIntent: <Endpoint>{ url: '/stripe/setup-intent', method: 'POST' },
createPaymentIntentFromSetup: (id: string, idempotencyKey: string) =>
createPaymentIntentFromSetup: (id: string) =>
<Endpoint>{
url: `/stripe/setup-intent/${id}/payment-intent?idempotency-key=${idempotencyKey}`,
url: `/stripe/setup-intent/${id}/payment-intent`,
method: 'POST',
},
createSubscriptionFromSetup: (id: string, idempotencyKey: string) =>
createSubscriptionFromSetup: (id: string) =>
<Endpoint>{
url: `/stripe/setup-intent/${id}/subscription?idempotency-key=${idempotencyKey}`,
url: `/stripe/setup-intent/${id}/subscription`,
method: 'POST',
},
updateSetupIntent: (id: string, idempotencyKey: string) =>
updateSetupIntent: (id: string) =>
<Endpoint>{
url: `/stripe/setup-intent/${id}?idempotency-key=${idempotencyKey}`,
url: `/stripe/setup-intent/${id}`,
method: 'POST',
},
cancelSetupIntent: (id: string) =>
Expand Down
13 changes: 4 additions & 9 deletions src/service/donation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,11 @@ export function useUpdateSetupIntent() {
//Create payment intent useing the react-query mutation
const { data: session } = useSession()
return useMutation({
mutationFn: async ({ id, idempotencyKey, payload }: UpdateSetupIntentInput) => {
mutationFn: async ({ id, payload }: UpdateSetupIntentInput) => {
return await apiClient.post<
Stripe.SetupIntentUpdateParams,
AxiosResponse<Stripe.SetupIntent>
>(
endpoints.donation.updateSetupIntent(id, idempotencyKey).url,
payload,
authConfig(session?.accessToken),
)
>(endpoints.donation.updateSetupIntent(id).url, payload, authConfig(session?.accessToken))
},
})
}
Expand Down Expand Up @@ -84,14 +80,13 @@ export function useCreateSubscriptionPayment() {

export async function createIntentFromSetup(
setupIntentId: string,
idempotencyKey: string,
mode: PaymentMode,
session: Session | null,
): Promise<AxiosResponse<Stripe.PaymentIntent>> {
return await apiClient.post<PaymentMode, AxiosResponse<Stripe.PaymentIntent>, AxiosError<Error>>(
mode === 'one-time'
? endpoints.donation.createPaymentIntentFromSetup(setupIntentId, idempotencyKey).url
: endpoints.donation.createSubscriptionFromSetup(setupIntentId, idempotencyKey).url,
? endpoints.donation.createPaymentIntentFromSetup(setupIntentId).url
: endpoints.donation.createSubscriptionFromSetup(setupIntentId).url,
undefined,
authConfig(session?.accessToken),
)
Expand Down
Loading