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

Improvement to subscription display #902

Merged
merged 16 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 4 additions & 1 deletion app/components/subscription/customer-portal-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ export const CustomerPortalForm = ({
const customerPortalFetcher = useFetcher();
const isProcessing = isFormProcessing(customerPortalFetcher.state);
return (
<customerPortalFetcher.Form method="post" action="customer-portal">
<customerPortalFetcher.Form
method="post"
action="/settings/subscription/customer-portal"
>
<Button disabled={isProcessing}>
{isProcessing ? "Redirecting to Customer Portal..." : buttonText}
</Button>
Expand Down
41 changes: 41 additions & 0 deletions app/components/subscription/no-subscription.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { useCurrentOrganization } from "~/hooks/use-current-organization-id";
import { useUserData } from "~/hooks/use-user-data";
import { CustomerPortalForm } from "./customer-portal-form";
import { plansIconsMap } from "./prices";
import { Button } from "../shared/button";

export const NoSubscription = () => {
const currentOrganization = useCurrentOrganization();
const user = useUserData();

const userIsOwner = user?.id === currentOrganization?.owner.id;

return (
<div className="flex size-full items-center justify-center">
<div className="text-center">
<div className="mb-2 inline-flex scale-125 items-center justify-center rounded-full border-[5px] border-solid border-primary-50 bg-primary-100 p-1.5 text-primary">
<i className=" inline-flex min-h-[30px] min-w-[30px] items-center justify-center">
{plansIconsMap["tier_2"]}
</i>
</div>
<h2 className="mb-2">Workspace disabled</h2>
<p className="max-w-[550px] text-gray-600">
{userIsOwner
? "The subscription for this workspace has expired and is therefore set to inactive. Renew your subscription to start using this Team workspace again."
: "The subscription for this workspace has expired and is therefore set to inactive. Please contact the owner of the workspace for more information."}
</p>
<div className="mt-4 flex justify-center gap-2">
{userIsOwner && (
<CustomerPortalForm buttonText={"Manage subscription"} />
)}
<Button
to={`mailto:${currentOrganization?.owner.email}`}
variant="secondary"
>
Contact owner
</Button>
</div>
</div>
</div>
);
};
37 changes: 32 additions & 5 deletions app/components/subscription/price-cta.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Form } from "@remix-run/react";
import { Form, useLoaderData } from "@remix-run/react";
import type { loader } from "~/routes/_layout+/settings.subscription";
import { CustomerPortalForm } from "./customer-portal-form";
import type { Price } from "./prices";
import { Button } from "../shared/button";
Expand All @@ -10,8 +11,13 @@ export const PriceCta = ({
price: Price;
subscription: Object | null;
}) => {
const { usedFreeTrial } = useLoaderData<typeof loader>();

if (price.id === "free") return null;

const isTeamSubscriptionColumn =
price.product.metadata.shelf_tier === "tier_2";

if (subscription) {
return (
<CustomerPortalForm
Expand All @@ -21,9 +27,30 @@ export const PriceCta = ({
}

return (
<Form method="post">
<input type="hidden" name="priceId" value={price.id} />
<Button type="submit">Upgrade to {price.product.name}</Button>
</Form>
<>
<Form method="post">
<input type="hidden" name="priceId" value={price.id} />
<input
type="hidden"
name="shelfTier"
value={price.product.metadata.shelf_tier}
/>
<Button type="submit" name="intent" value="subscribe">
Upgrade to {price.product.name}
</Button>

{isTeamSubscriptionColumn && !subscription && !usedFreeTrial && (
<Button
variant="secondary"
className="mt-2"
type="submit"
name="intent"
value="trial"
>
Start 14 day free trial
</Button>
)}
</Form>
</>
);
};
2 changes: 1 addition & 1 deletion app/components/subscription/prices.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export interface Price {
} | null;
}

const plansIconsMap: { [key: string]: JSX.Element } = {
export const plansIconsMap: { [key: string]: JSX.Element } = {
free: <SingleLayerIcon />,
tier_1: <DoubleLayerIcon />,
tier_2: <MultiLayerIcon />,
Expand Down
17 changes: 14 additions & 3 deletions app/components/subscription/successful-subscription-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Button } from "../shared/button";
export default function SuccessfulSubscriptionModal() {
const [params, setParams] = useSearchParams();
const success = params.get("success") || false;
const isTeam = params.get("team") || false;
const handleBackdropClose = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target !== e.currentTarget) return;
Expand Down Expand Up @@ -41,9 +42,19 @@ export default function SuccessfulSubscriptionModal() {
Thank you, all {activeProduct?.name} features are unlocked.
</p>
</div>
<Button width="full" to="/assets" variant="primary">
Get started
</Button>
{isTeam ? (
<Button
width="full"
to="/settings/workspace/new"
variant="primary"
>
Create your Team workspace
</Button>
) : (
<Button width="full" to="/assets" variant="primary">
Get started
</Button>
)}
</div>
</dialog>
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "User" ADD COLUMN "usedFreeTrial" BOOLEAN NOT NULL DEFAULT false;
1 change: 1 addition & 0 deletions app/database/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ model User {
firstName String?
lastName String?
profilePicture String?
usedFreeTrial Boolean @default(false)
onboarded Boolean @default(false)
customerId String? @unique // Stripe customer id
tierId TierId @default(free)
Expand Down
6 changes: 6 additions & 0 deletions app/modules/organization/service.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,12 @@ export async function getUserOrganizations({ userId }: { userId: string }) {
userId: true,
updatedAt: true,
currency: true,
owner: {
select: {
id: true,
email: true,
},
},
},
},
},
Expand Down
11 changes: 4 additions & 7 deletions app/modules/tier/service.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,13 +253,10 @@ export async function getOrganizationTierLimit({
organizations,
}: {
organizationId?: string;
organizations: {
id: string;
type: OrganizationType;
name: string;
imageId: string | null;
userId: string;
}[];
organizations: Pick<
Organization,
"id" | "type" | "name" | "imageId" | "userId"
>[];
}) {
try {
/** Find the current organization as we need the owner */
Expand Down
1 change: 1 addition & 0 deletions app/modules/user/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface UpdateUserPayload {
onboarded?: User["onboarded"];
password?: string;
confirmPassword?: string;
usedFreeTrial?: boolean;
}

export interface UpdateUserResponse {
Expand Down
14 changes: 12 additions & 2 deletions app/routes/_layout+/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Sidebar from "~/components/layout/sidebar/sidebar";
import { useCrisp } from "~/components/marketing/crisp";
import { Spinner } from "~/components/shared/spinner";
import { Toaster } from "~/components/shared/toast";
import { NoSubscription } from "~/components/subscription/no-subscription";
import { config } from "~/config/shelf.config";
import { db } from "~/database/db.server";
import { getSelectedOrganisation } from "~/modules/organization/context.server";
Expand All @@ -24,6 +25,7 @@ import { data, error } from "~/utils/http.server";
import type { CustomerWithSubscriptions } from "~/utils/stripe.server";

import {
disabledTeamOrg,
getCustomerActiveSubscription,
getStripeCustomer,
stripe,
Expand Down Expand Up @@ -115,6 +117,11 @@ export async function loader({ context, request }: LoaderFunctionArgs) {
minimizedSidebar: cookie.minimizedSidebar,
isAdmin: user?.roles.some((role) => role.name === Roles["ADMIN"]),
canUseBookings: canUseBookings(currentOrganization),
/** THis is used to disable team organizations when the currentOrg is Team and no subscription is present */
disabledTeamOrg: await disabledTeamOrg({
currentOrganization,
organizations,
}),
}),
{
headers: [setCookie(await userPrefs.serialize(cookie))],
Expand All @@ -128,7 +135,8 @@ export async function loader({ context, request }: LoaderFunctionArgs) {

export default function App() {
useCrisp();
const { currentOrganizationId } = useLoaderData<typeof loader>();
const { currentOrganizationId, disabledTeamOrg } =
useLoaderData<typeof loader>();
const [workspaceSwitching] = useAtom(switchingWorkspaceAtom);

return (
Expand All @@ -142,7 +150,9 @@ export default function App() {
<Sidebar />
<main className=" flex-1 bg-gray-25 px-4 pb-6 md:w-[calc(100%-312px)]">
<div className="flex h-full flex-1 flex-col">
{workspaceSwitching ? (
{disabledTeamOrg ? (
<NoSubscription />
) : workspaceSwitching ? (
<div className="flex size-full flex-col items-center justify-center text-center">
<Spinner />
<p className="mt-2">Activating workspace...</p>
Expand Down
36 changes: 21 additions & 15 deletions app/routes/_layout+/settings.subscription.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { Prices } from "~/components/subscription/prices";
import SuccessfulSubscriptionModal from "~/components/subscription/successful-subscription-modal";
import { db } from "~/database/db.server";

import { getUserByID } from "~/modules/user/service.server";
import { getUserByID, updateUser } from "~/modules/user/service.server";
import { appendToMetaTitle } from "~/utils/append-to-meta-title";
import { ENABLE_PREMIUM_FEATURES } from "~/utils/env";
import { ShelfError, makeShelfError } from "~/utils/error";
Expand All @@ -39,7 +39,6 @@ import {
getStripeCustomer,
getActiveProduct,
getCustomerActiveSubscription,
getCustomerTrialSubscription,
} from "~/utils/stripe.server";

export async function loader({ context, request }: LoaderFunctionArgs) {
Expand Down Expand Up @@ -67,24 +66,19 @@ export async function loader({ context, request }: LoaderFunctionArgs) {
)) as CustomerWithSubscriptions)
: null;

/** Get the trial subscription */
const trialSubscription = getCustomerTrialSubscription({ customer });

/** Get a normal subscription */
const subscription = getCustomerActiveSubscription({ customer });

const activeSubscription = subscription || trialSubscription;

/* Get the prices and products from Stripe */
const prices = await getStripePricesAndProducts();

let activeProduct = null;
if (customer && activeSubscription) {
if (customer && subscription) {
/** Get the active subscription ID */

activeProduct = getActiveProduct({
prices,
priceId: activeSubscription?.items.data[0].plan.id || null,
priceId: subscription?.items.data[0].plan.id || null,
});
}

Expand All @@ -94,17 +88,18 @@ export async function loader({ context, request }: LoaderFunctionArgs) {
subTitle: "Pick an account plan that fits your workflow.",
prices,
customer,
subscription: activeSubscription,
subscription: subscription,
activeProduct,
usedFreeTrial: user.usedFreeTrial,
expiration: {
date: new Date(
(activeSubscription?.current_period_end as number) * 1000
(subscription?.current_period_end as number) * 1000
).toLocaleDateString(),
time: new Date(
(activeSubscription?.current_period_end as number) * 1000
(subscription?.current_period_end as number) * 1000
).toLocaleTimeString(),
},
isTrialSubscription: !!activeSubscription?.trial_end,
isTrialSubscription: !!subscription?.trial_end,
})
);
} catch (cause) {
Expand All @@ -125,9 +120,13 @@ export async function action({ context, request }: ActionFunctionArgs) {
action: PermissionAction.update,
});

const { priceId } = parseData(
const { priceId, intent, shelfTier } = parseData(
await request.formData(),
z.object({ priceId: z.string() })
z.object({
priceId: z.string(),
intent: z.enum(["trial", "subscribe"]),
shelfTier: z.enum(["tier_1", "tier_2"]),
})
);

const user = await db.user
Expand Down Expand Up @@ -170,8 +169,15 @@ export async function action({ context, request }: ActionFunctionArgs) {
priceId,
domainUrl: getDomainUrl(request),
customerId: customerId,
intent,
shelfTier,
});

/** Update the user flag to mark them for having a trial */
if (intent === "trial" && stripeRedirectUrl) {
await updateUser({ id: userId, usedFreeTrial: true });
}

return redirect(stripeRedirectUrl);
} catch (cause) {
const reason = makeShelfError(cause, { userId });
Expand Down
Loading
Loading