feat: stripe connect atom (#16190)

* update stripe service

* init endpoints for stripe connect atom

* update stripe controller

* update stripe service

* add generic function to create app credential

* update stripe controller

* update stripe service

* add handler to construct redirectUrl

* restructure files for better readibility

* better naming

* replace STRIPE_PRIVATE_KEY with STRIPE_API_KEY

* fix naming

* remove unused query param

* frontend for stripe connect atom

* custom hooks for stripe connect atom

* abstract response schema into separate file

* fixup

* input dto for stripe controller

* update stripe module

* update endpoints module to include stripe module

* updatte stripe module

* fixups and add check endpoint to stripe controller

* add method to check stripe account

* add helper fn to get on error return value

* update stripe connect atom

* custom hook to check user stripe credentials

* add stripe connect to atom exports

* update stripe connect styling

* add qs stringify package

* translations for stripe connect atom

* updaet typing

* update output dtos for stripe endpoints

* add error message

* fix merge conflicts

* add stripe connect atom to atom exports

* add query param for error rediect link

* add handler for onCheck success and error redirect link

* update index value

* fix merge conflicts

* fixup

* resolve merge conflicts

* war with merge conflicts

* update examples app

---------

Co-authored-by: Morgan <[email protected]>
This commit is contained in:
Rajiv SahalandMorgan authored and GitHub committed 2024-09-30 19:56:22 +05:30
1 parent f46c3c65fb
commit c88811aeee
17 files changed
+522 -7

No files matched your search

@@ -0,0 +1,72 @@
import type { FC } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui";
import type { OnCheckErrorType, UseCheckProps } from "../../hooks/connect/useCheck";
import { useCheck } from "../../hooks/stripe/useCheck";
import { useConnect } from "../../hooks/stripe/useConnect";
import { AtomsWrapper } from "../../src/components/atoms-wrapper";
import { cn } from "../../src/lib/utils";
type StripeConnectProps = {
className?: string;
label: string;
alreadyConnectedLabel: string;
loadingLabel: string;
onCheckError?: OnCheckErrorType;
redir?: string;
errorRedir?: string;
initialData: UseCheckProps["initialData"];
onCheckSuccess?: () => void;
};
export const StripeConnect: FC<Partial<StripeConnectProps>> = ({
label,
className,
loadingLabel,
alreadyConnectedLabel,
redir,
errorRedir,
onCheckError,
initialData,
onCheckSuccess,
}) => {
const { t } = useLocale();
const { connect } = useConnect(redir, errorRedir);
const { allowConnect, checked } = useCheck({
onCheckError,
onCheckSuccess,
initialData,
});
let displayedLabel = label || t("stripe_connect_atom_label");
const isChecking = !checked;
const isDisabled = isChecking || !allowConnect;
if (isChecking) {
displayedLabel = loadingLabel || t("stripe_connect_atom_loading_label");
} else if (!allowConnect) {
displayedLabel = alreadyConnectedLabel || t("stripe_connect_atom_already_connected_label");
}
return (
<AtomsWrapper>
<Button
StartIcon="calendar"
color="primary"
disabled={isDisabled}
className={cn(
"",
className,
isChecking && "animate-pulse",
isDisabled && "cursor-not-allowed",
!isDisabled && "cursor-pointer"
)}
onClick={() => connect()}>
{displayedLabel}
</Button>
</AtomsWrapper>
);
};
@@ -0,0 +1,62 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import type { CALENDARS } from "@calcom/platform-constants";
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
import type { ApiErrorResponse, ApiResponse } from "@calcom/platform-types";
import http from "../../lib/http";
import { useAtomsContext } from "../useAtomsContext";
export interface UseCheckProps {
onCheckError?: OnCheckErrorType;
onCheckSuccess?: () => void;
initialData?: {
status: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
data: {
allowConnect: boolean;
checked: boolean;
};
};
}
const stripeQueryKey = ["get-stripe-check"];
export type OnCheckErrorType = (err: ApiErrorResponse) => void;
export const getQueryKey = (calendar: (typeof CALENDARS)[number]) => [`get-${calendar}-check`];
export const useCheck = ({ onCheckError, initialData, onCheckSuccess }: UseCheckProps) => {
const { isInit, accessToken } = useAtomsContext();
const queryClient = useQueryClient();
const { data: check, refetch } = useQuery({
queryKey: stripeQueryKey,
staleTime: 6000,
enabled: isInit && !!accessToken,
queryFn: () => {
return http
?.get<ApiResponse<{ checked: boolean; allowConnect: boolean }>>(`/stripe/check`)
.then(({ data: responseBody }) => {
if (responseBody.status === SUCCESS_STATUS) {
onCheckSuccess();
return { status: SUCCESS_STATUS, data: { allowConnect: false, checked: true } };
}
onCheckError?.(responseBody);
return { status: ERROR_STATUS, data: { allowConnect: true, checked: true } };
})
.catch((err) => {
onCheckError?.(err);
return { status: ERROR_STATUS, data: { allowConnect: true, checked: true } };
});
},
initialData,
});
return {
allowConnect: check?.data?.allowConnect ?? false,
checked: check?.data?.checked ?? false,
refetch: () => {
queryClient.setQueryData(stripeQueryKey, {
status: SUCCESS_STATUS,
data: { allowConnect: false, checked: false },
});
refetch();
},
};
};
@@ -0,0 +1,45 @@
import { useQuery } from "@tanstack/react-query";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
import type { ApiResponse } from "@calcom/platform-types";
import http from "../../lib/http";
export const useGetRedirectUrl = (redir?: string, errorRedir?: string) => {
const authUrl = useQuery({
queryKey: ["get-stripe-connect-redirect-uri"],
staleTime: Infinity,
enabled: false,
queryFn: () => {
return http
?.get<ApiResponse<{ authUrl: string }>>(
`/stripe/connect${redir ? `?redir=${encodeURIComponent(redir)}` : "?redir="}${
errorRedir ? `&errorRedir=${encodeURIComponent(errorRedir)}` : ""
}`
)
.then(({ data: responseBody }) => {
if (responseBody.status === SUCCESS_STATUS) {
return responseBody.data.authUrl;
}
if (responseBody.status === ERROR_STATUS) throw new Error(responseBody.error.message);
return "";
});
},
});
return authUrl;
};
export const useConnect = (redir?: string, errorRedir?: string) => {
const { refetch } = useGetRedirectUrl(redir, errorRedir);
const connect = async () => {
const redirectUri = await refetch();
if (redirectUri.data) {
window.location.href = redirectUri.data;
}
};
return { connect };
};
+1
View File
@@ -25,3 +25,4 @@ export { DestinationCalendarSettingsPlatformWrapper as DestinationCalendarSettin
export { CalendarSettingsPlatformWrapper as CalendarSettings } from "./calendar-settings/index";
export type { UpdateScheduleInput_2024_06_11 as UpdateScheduleBody } from "@calcom/platform-types";
export { EventTypePlatformWrapper as EventTypeSettings } from "./event-types/wrappers/EventTypePlatformWrapper";
export { StripeConnect } from "./connect/stripe/StripeConnect";
@@ -1,7 +1,7 @@
import { Navbar } from "@/components/Navbar";
import { Inter, Poppins } from "next/font/google";
import { GcalConnect, Connect } from "@calcom/atoms";
import { Connect, StripeConnect } from "@calcom/atoms";
const inter = Inter({ subsets: ["latin"] });
const poppins = Poppins({ subsets: ["latin"], weight: ["400", "800"] });
@@ -20,7 +20,7 @@ export default function Home(props: { calUsername: string; calEmail: string }) {
To get started, connect your google calendar.
</p>
<div className="flex flex-row gap-4">
<GcalConnect
<Connect.GoogleCalendar
redir="http://localhost:4321/calendars"
className="h-[40px] bg-gradient-to-r from-[#8A2387] via-[#E94057] to-[#F27121] text-center text-base font-semibold text-transparent text-white hover:bg-orange-700"
/>
@@ -33,6 +33,13 @@ export default function Home(props: { calUsername: string; calEmail: string }) {
isMultiCalendar={true}
className="h-[40px] bg-gradient-to-r from-[#8A2387] via-[#E94057] to-[#F27121] text-center text-base font-semibold text-transparent text-white hover:bg-orange-700"
/>
<StripeConnect
className="h-[40px] bg-gradient-to-r from-[#E94057] via-[#E94057] to-[#E94057] text-center text-base font-semibold text-transparent text-white hover:bg-orange-700"
errorRedir="http://localhost:4321/availability"
onCheckSuccess={() => {
console.log("stripe account connected successfully".toLocaleUpperCase());
}}
/>
</div>
</div>
<div className="hidden lg:block">