Skip to content

Commit

Permalink
chore: use user object to read subscription
Browse files Browse the repository at this point in the history
  • Loading branch information
svedova committed May 29, 2024
1 parent bd25d6e commit 3f19e15
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 125 deletions.
97 changes: 44 additions & 53 deletions src/pages/user/account/_components/SubscriptionDetails.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { useEffect, useState, useContext, useMemo } from "react";
import Spinner from "~/components/Spinner";
import InfoBox from "~/components/InfoBoxV2";
import LoadingButton from "@mui/lab/LoadingButton";
import Box from "@mui/material/Box";
import Chip from "@mui/material/Chip";
import WarningIcon from "@mui/icons-material/Warning";
import Container from "~/components/Container";
import { AuthContext } from "~/pages/auth/Auth.context";
import { useFetchSubscription, fetchCheckoutEndpoint } from "../actions";
import { fetchCheckoutEndpoint } from "../actions";
import { SubscriptionName } from "../actions/fetch_subscriptions";
import PricingSlider, { SubscriptionTier, WhatsIncluded } from "./Pricing";
import { Typography } from "@mui/material";
Expand Down Expand Up @@ -44,7 +42,6 @@ const subscriptionToTier: Record<SubscriptionName, SubscriptionTier> = {

const SubscriptionDetails: React.FC = (): React.ReactElement => {
const { user } = useContext(AuthContext);
const { loading, error, subscription } = useFetchSubscription();
const [checkoutLoading, setCheckoutLoading] = useState(false);
const [tier, setTier] = useState<SubscriptionTier>("100");

Expand All @@ -58,11 +55,11 @@ const SubscriptionDetails: React.FC = (): React.ReactElement => {
}
}, [user?.freeTrialEnds]);

const subscriptionTier = subscriptionToTier[user?.package.id || "free"];

useEffect(() => {
if (subscription?.name) {
setTier(subscriptionToTier[subscription.name]);
}
}, [subscription?.name]);
setTier(subscriptionTier);
}, [subscriptionTier]);

return (
<Container>
Expand All @@ -79,19 +76,17 @@ const SubscriptionDetails: React.FC = (): React.ReactElement => {
}}
>
Subscription
{!loading && (
{
<Chip
color="warning"
label={
"Current: " +
(subscription?.name === "free"
(user?.package?.id === "free"
? `Free trial${user?.isPaymentRequired ? " expired" : ""}`
: `up to ${
subscriptionToTier[subscription?.name || "free"]
} deployments`)
: `up to ${subscriptionTier} deployments`)
}
/>
)}
}
</Typography>
{freeTrialEnds && (
<Typography
Expand All @@ -112,46 +107,42 @@ const SubscriptionDetails: React.FC = (): React.ReactElement => {
listen and make your experience with Stormkit even better.
</Typography>
)}
{loading && <Spinner width={6} height={6} primary />}
{!loading && error && <InfoBox type="error">{error}</InfoBox>}
{!loading && !error && (
<Box sx={{ display: "flex", flexDirection: "column" }}>
<Box sx={{ bgcolor: "rgba(0,0,0,0.1)", p: 4 }}>
<PricingSlider
tier={subscriptionToTier[subscription?.name || "free"]}
onTierChange={t => setTier(t)}
/>
</Box>
<Box sx={{ mt: 4, mb: 8 }}>
<WhatsIncluded tier={tier} />
</Box>
<Box sx={{ mt: 2, textAlign: "right" }}>
<LoadingButton
onClick={e => {
e.preventDefault();
setCheckoutLoading(true);
fetchCheckoutEndpoint(tier).then(url => {
window.location.assign(url);
});
}}
href={`${paymentLink(tier)}?client_reference_id=${
user?.id
}&prefilled_email=${user?.email}`}
disabled={tier === "1000+"}
loading={checkoutLoading}
color="secondary"
variant="contained"
sx={{
":hover": {
color: "white !important",
},
}}
>
Go to Stripe Customer Portal
</LoadingButton>
</Box>
<Box sx={{ display: "flex", flexDirection: "column" }}>
<Box sx={{ bgcolor: "rgba(0,0,0,0.1)", p: 4 }}>
<PricingSlider
tier={subscriptionTier}
onTierChange={t => setTier(t)}
/>
</Box>
)}
<Box sx={{ mt: 4, mb: 8 }}>
<WhatsIncluded tier={tier} />
</Box>
<Box sx={{ mt: 2, textAlign: "right" }}>
<LoadingButton
onClick={e => {
e.preventDefault();
setCheckoutLoading(true);
fetchCheckoutEndpoint(tier).then(url => {
window.location.assign(url);
});
}}
href={`${paymentLink(tier)}?client_reference_id=${
user?.id
}&prefilled_email=${user?.email}`}
disabled={tier === "1000+"}
loading={checkoutLoading}
color="secondary"
variant="contained"
sx={{
":hover": {
color: "white !important",
},
}}
>
Go to Stripe Customer Portal
</LoadingButton>
</Box>
</Box>
</Box>
</Container>
);
Expand Down
64 changes: 0 additions & 64 deletions src/pages/user/account/actions/fetch_subscriptions.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,8 @@
import { useEffect, useState } from "react";
import api from "~/utils/api/Api";

export type StatusName = "trialing" | "active";
export type SubscriptionName = "enterprise" | "medium" | "starter" | "free";

export type Subscription = {
concurrentBuilds: boolean; // Number of concurrent builds allowed
remainingApps: boolean; // -1 for unlimited
currentPlan: {
current_period_end: number;
current_period_start: number;
cancel_at: number;
cancel_at_period_end: boolean;
};
name: SubscriptionName;
stripeClientId: string;
totalApps: number;
};

interface FetchSubscriptionReturnValue {
loading: boolean;
error: string | null;
subscription: Subscription | undefined;
}

interface FetchSubscriptionAPIResponse {
subscription: Subscription;
}

export const fetchCheckoutEndpoint = (deployments: string): Promise<string> => {
return api
.fetch<{ url: string }>(
Expand All @@ -37,42 +12,3 @@ export const fetchCheckoutEndpoint = (deployments: string): Promise<string> => {
return res.url;
});
};

export const useFetchSubscription = (): FetchSubscriptionReturnValue => {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [subscription, setSubscription] = useState<Subscription>();

useEffect(() => {
let unmounted = false;

setLoading(true);
setError(null);

api
.fetch<FetchSubscriptionAPIResponse>("/user/subscription")
.then(res => {
if (!unmounted) {
setSubscription(res.subscription || {});
}
})
.catch(() => {
if (!unmounted) {
setError(
"Something went wrong file fetching subscriptions. Please try again. If the problem persists reach us out through Discord or email."
);
}
})
.finally(() => {
if (!unmounted) {
setLoading(false);
}
});

return () => {
unmounted = true;
};
}, [api]);

return { loading, error, subscription };
};
10 changes: 2 additions & 8 deletions src/pages/user/account/actions/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
import { Subscription as Stype } from "./fetch_subscriptions";

export {
useFetchSubscription,
fetchCheckoutEndpoint,
} from "./fetch_subscriptions";
import api from "~/utils/api/Api";

export { fetchCheckoutEndpoint } from "./fetch_subscriptions";
export { usePersonalAccessTokenState } from "./personal_access_token";
export type Subscription = Stype;
import api from "~/utils/api/Api";

export const deleteUser = async () => {
return await api.delete(`/user`);
Expand Down

0 comments on commit 3f19e15

Please sign in to comment.