Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Free trial (#99)

Bill Yang1628b01b64a0
diff --git a/client/src/app/[site]/components/Header/Header.tsx b/client/src/app/[site]/components/Header/Header.tsx
index cff298862..5b4c5f6ce 100644
--- a/client/src/app/[site]/components/Header/Header.tsx
+++ b/client/src/app/[site]/components/Header/Header.tsx
@@ -1,10 +1,20 @@
"use client";
+import { FreeTrialBanner } from "../../../../components/FreeTrialBanner";
import { userStore } from "../../../../lib/userStore";
import { UsageBanners } from "./UsageBanners";
export function Header() {
const { user } = userStore();
- return <div className="flex flex-col">{user && <UsageBanners />}</div>;
+ return (
+ <div className="flex flex-col">
+ {user && (
+ <>
+ <FreeTrialBanner />
+ <UsageBanners />
+ </>
+ )}
+ </div>
+ );
}
diff --git a/client/src/app/page.tsx b/client/src/app/page.tsx
index 7db237ec3..cd5044fef 100644
--- a/client/src/app/page.tsx
+++ b/client/src/app/page.tsx
@@ -11,6 +11,7 @@ import { Button } from "../components/ui/button";
import { Card, CardDescription, CardTitle } from "../components/ui/card";
import { AddSite } from "./components/AddSite";
import { CreateOrganizationDialog } from "../components/CreateOrganizationDialog";
+import { FreeTrialBanner } from "../components/FreeTrialBanner";
export default function Home() {
const {
@@ -43,6 +44,7 @@ export default function Home() {
return (
<StandardPage>
+ <FreeTrialBanner />
<div className="flex justify-between items-center mb-4">
<div className="text-2xl font-bold">Websites</div>
<AddSite disabled={hasNoOrganizations || disabled} />
diff --git a/client/src/app/settings/subscription/components/ExpiredTrialPlan.tsx b/client/src/app/settings/subscription/components/ExpiredTrialPlan.tsx
new file mode 100644
index 000000000..0ca594080
--- /dev/null
+++ b/client/src/app/settings/subscription/components/ExpiredTrialPlan.tsx
@@ -0,0 +1,55 @@
+import { AlertTriangle, ArrowRight } from "lucide-react";
+import { useRouter } from "next/navigation";
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from "../../../../components/ui/alert";
+import { Button } from "../../../../components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "../../../../components/ui/card";
+
+interface ExpiredTrialPlanProps {
+ message?: string;
+}
+
+export function ExpiredTrialPlan({ message }: ExpiredTrialPlanProps) {
+ const router = useRouter();
+
+ const defaultMessage =
+ "Your 14-day free trial has ended. You need to subscribe to continue using the analytics service.";
+
+ return (
+ <div className="space-y-6">
+ <Card>
+ <CardHeader>
+ <CardTitle>Trial Expired</CardTitle>
+ <CardDescription>
+ Your free trial has expired. Subscribe to a plan to continue using
+ the service.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-6">
+ <Alert className="bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800">
+ <AlertTriangle className="h-4 w-4 text-amber-500 dark:text-amber-400" />
+ <AlertTitle>Subscription Required</AlertTitle>
+ <AlertDescription>{message || defaultMessage}</AlertDescription>
+ </Alert>
+ </div>
+ </CardContent>
+ <CardFooter>
+ <Button onClick={() => router.push("/subscribe")} variant={"success"}>
+ Subscribe Now <ArrowRight className="ml-2 h-4 w-4" />
+ </Button>
+ </CardFooter>
+ </Card>
+ </div>
+ );
+}
diff --git a/client/src/app/settings/subscription/components/FreePlan.tsx b/client/src/app/settings/subscription/components/FreePlan.tsx
deleted file mode 100644
index 7deca23e8..000000000
--- a/client/src/app/settings/subscription/components/FreePlan.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { ArrowRight } from "lucide-react";
-import { Button } from "../../../../components/ui/button";
-import {
- Card,
- CardContent,
- CardDescription,
- CardFooter,
- CardHeader,
- CardTitle,
-} from "../../../../components/ui/card";
-import { Progress } from "../../../../components/ui/progress";
-import { DEFAULT_EVENT_LIMIT } from "../utils/constants";
-import { getPlanDetails } from "../utils/planUtils";
-import { useStripeSubscription } from "../utils/useStripeSubscription";
-import { PlanFeaturesCard } from "./PlanFeaturesCard";
-import { useRouter } from "next/navigation";
-
-export function FreePlan() {
- const {
- data: activeSubscription,
- isLoading,
- error: subscriptionError,
- refetch,
- } = useStripeSubscription();
-
- const currentUsage = activeSubscription?.monthlyEventCount || 0;
-
- const router = useRouter();
-
- return (
- <div className="space-y-6">
- <Card>
- <CardHeader>
- <CardTitle>Free Plan</CardTitle>
- <CardDescription>
- You are currently on the Free Plan. Upgrade to unlock more events.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="space-y-6">
- <div className="space-y-2">
- <h3 className="font-medium mb-2">Usage</h3>
- <div className="space-y-4">
- <div>
- <div className="flex justify-between mb-1">
- <span className="text-sm">Events</span>
- <span className="text-sm">
- {currentUsage.toLocaleString()} /{" "}
- {DEFAULT_EVENT_LIMIT.toLocaleString()}
- </span>
- </div>
- <Progress
- value={Math.min(
- (currentUsage / DEFAULT_EVENT_LIMIT) * 100,
- 100
- )}
- />
- </div>
- </div>
- </div>
- </div>
- </CardContent>
- <CardFooter>
- <Button onClick={() => router.push("/subscribe")} variant={"success"}>
- Upgrade Plan <ArrowRight className="ml-2 h-4 w-4" />
- </Button>
- </CardFooter>
- </Card>
-
- <PlanFeaturesCard currentPlan={getPlanDetails("free")} />
- </div>
- );
-}
diff --git a/client/src/app/settings/subscription/components/ProPlan.tsx b/client/src/app/settings/subscription/components/ProPlan.tsx
index 187be9768..971364e44 100644
--- a/client/src/app/settings/subscription/components/ProPlan.tsx
+++ b/client/src/app/settings/subscription/components/ProPlan.tsx
@@ -3,7 +3,6 @@ import { toast } from "sonner";
import { Button } from "../../../../components/ui/button";
import { Card, CardContent } from "../../../../components/ui/card";
import { Progress } from "../../../../components/ui/progress";
-import { DEFAULT_EVENT_LIMIT } from "../utils/constants";
import { formatDate, getPlanDetails, PlanTemplate } from "../utils/planUtils";
import { useStripeSubscription } from "../utils/useStripeSubscription";
import { PlanFeaturesCard } from "./PlanFeaturesCard";
@@ -21,7 +20,7 @@ export function ProPlan() {
const [isProcessing, setIsProcessing] = useState(false);
const [actionError, setActionError] = useState<string | null>(null);
- const eventLimit = activeSubscription?.eventLimit || DEFAULT_EVENT_LIMIT;
+ const eventLimit = activeSubscription?.eventLimit || 0;
const currentUsage = activeSubscription?.monthlyEventCount || 0;
const usagePercentage =
eventLimit > 0 ? Math.min((currentUsage / eventLimit) * 100, 100) : 0;
diff --git a/client/src/app/settings/subscription/components/TrialPlan.tsx b/client/src/app/settings/subscription/components/TrialPlan.tsx
new file mode 100644
index 000000000..f659146fb
--- /dev/null
+++ b/client/src/app/settings/subscription/components/TrialPlan.tsx
@@ -0,0 +1,105 @@
+import { ArrowRight, Clock } from "lucide-react";
+import { Button } from "../../../../components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "../../../../components/ui/card";
+import { Progress } from "../../../../components/ui/progress";
+import { TRIAL_EVENT_LIMIT } from "../utils/constants";
+import { formatDate, getPlanDetails } from "../utils/planUtils";
+import { useStripeSubscription } from "../utils/useStripeSubscription";
+import { useRouter } from "next/navigation";
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from "../../../../components/ui/alert";
+import { PlanFeaturesCard } from "./PlanFeaturesCard";
+
+export function TrialPlan() {
+ const {
+ data: activeSubscription,
+ isLoading,
+ error: subscriptionError,
+ } = useStripeSubscription();
+
+ const router = useRouter();
+
+ if (!activeSubscription) return null;
+
+ const currentUsage = activeSubscription?.monthlyEventCount || 0;
+ const daysRemaining = activeSubscription?.trialDaysRemaining || 0;
+ const trialEndDate = activeSubscription?.currentPeriodEnd
+ ? new Date(activeSubscription.currentPeriodEnd)
+ : null;
+
+ const trialPlanDetails = getPlanDetails("trial");
+
+ return (
+ <div className="space-y-6">
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center">
+ Trial Plan <Clock className="ml-2 h-5 w-5 text-blue-500" />
+ </CardTitle>
+ <CardDescription>
+ You are currently on a 14-day free trial with up to 100,000 events.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-6">
+ <Alert className="bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800">
+ <Clock className="h-4 w-4 text-blue-500 dark:text-blue-400" />
+ <AlertTitle>Trial Status</AlertTitle>
+ <AlertDescription>
+ {daysRemaining > 0 ? (
+ <>
+ Your trial ends in <strong>{daysRemaining} days</strong>
+ {trialEndDate && <> on {formatDate(trialEndDate)}</>}
+ </>
+ ) : (
+ <>
+ Your trial ends today. Subscribe to continue using the
+ service.
+ </>
+ )}
+ </AlertDescription>
+ </Alert>
+
+ <div className="space-y-2">
+ <h3 className="font-medium mb-2">Usage</h3>
+ <div className="space-y-4">
+ <div>
+ <div className="flex justify-between mb-1">
+ <span className="text-sm">Events</span>
+ <span className="text-sm">
+ {currentUsage.toLocaleString()} /{" "}
+ {TRIAL_EVENT_LIMIT.toLocaleString()}
+ </span>
+ </div>
+ <Progress
+ value={Math.min(
+ (currentUsage / TRIAL_EVENT_LIMIT) * 100,
+ 100
+ )}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </CardContent>
+ <CardFooter>
+ <Button onClick={() => router.push("/subscribe")} variant={"success"}>
+ Upgrade To Pro <ArrowRight className="ml-2 h-4 w-4" />
+ </Button>
+ </CardFooter>
+ </Card>
+
+ {trialPlanDetails && <PlanFeaturesCard currentPlan={trialPlanDetails} />}
+ </div>
+ );
+}
diff --git a/client/src/app/settings/subscription/page.tsx b/client/src/app/settings/subscription/page.tsx
index a6b0c5a5d..34893eb77 100644
--- a/client/src/app/settings/subscription/page.tsx
+++ b/client/src/app/settings/subscription/page.tsx
@@ -2,11 +2,12 @@
import { Card, CardContent } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
-import { FreePlan } from "./components/FreePlan";
import { ProPlan } from "./components/ProPlan";
import { useStripeSubscription } from "./utils/useStripeSubscription";
import { useUserOrganizations } from "../../../api/admin/organizations";
import { NoOrganization } from "../../../components/NoOrganization";
+import { TrialPlan } from "./components/TrialPlan";
+import { ExpiredTrialPlan } from "./components/ExpiredTrialPlan";
export default function SubscriptionPage() {
const { data: activeSubscription, isLoading: isLoadingSubscription } =
@@ -19,8 +20,32 @@ export default function SubscriptionPage() {
const isLoading = isLoadingSubscription || isLoadingOrganizations;
+ // Determine which plan to display
+ const renderPlanComponent = () => {
+ if (!hasOrganization) {
+ return (
+ <NoOrganization message="You need to be part of an organization to manage your subscription." />
+ );
+ }
+
+ if (!activeSubscription) {
+ return <ExpiredTrialPlan />;
+ }
+
+ // Check if trial expired
+ if (activeSubscription.status === "expired") {
+ return <ExpiredTrialPlan message={activeSubscription.message} />;
+ }
+
+ if (activeSubscription.isTrial) {
+ return <TrialPlan />;
+ }
+
+ return <ProPlan />;
+ };
+
return (
- <div className=" py-2">
+ <div className="py-2">
<div className="flex justify-between items-center mb-4">
<div>
<h1 className="text-3xl font-bold tracking-tight">Subscription</h1>
@@ -40,14 +65,8 @@ export default function SubscriptionPage() {
</div>
</CardContent>
</Card>
- ) : !activeSubscription ? (
- hasOrganization ? (
- <FreePlan />
- ) : (
- <NoOrganization message="You need to be part of an organization to manage your subscription." />
- )
) : (
- <ProPlan />
+ renderPlanComponent()
)}
</div>
);
diff --git a/client/src/app/settings/subscription/utils/constants.ts b/client/src/app/settings/subscription/utils/constants.ts
index a85781867..6906bbf81 100644
--- a/client/src/app/settings/subscription/utils/constants.ts
+++ b/client/src/app/settings/subscription/utils/constants.ts
@@ -1,2 +1,4 @@
// Default event limit if not specified in subscription
export const DEFAULT_EVENT_LIMIT = 20000;
+export const TRIAL_EVENT_LIMIT = 100000;
+export const TRIAL_DURATION_DAYS = 14;
diff --git a/client/src/app/settings/subscription/utils/planUtils.tsx b/client/src/app/settings/subscription/utils/planUtils.tsx
index 2b0c29e67..d30509296 100644
--- a/client/src/app/settings/subscription/utils/planUtils.tsx
+++ b/client/src/app/settings/subscription/utils/planUtils.tsx
@@ -1,5 +1,6 @@
-import { Clock, Shield } from "lucide-react";
+import { Clock, Shield, Zap } from "lucide-react";
import { STRIPE_PRICES } from "@/lib/stripe";
+import { DEFAULT_EVENT_LIMIT, TRIAL_EVENT_LIMIT } from "./constants";
// Define interfaces for plan data
export interface PlanTemplate {
@@ -19,6 +20,25 @@ export const getPlanDetails = (
): PlanTemplate | null => {
if (!planName) return null;
+ // Handle the case for trial separately
+ if (planName === "trial") {
+ return {
+ id: "trial",
+ name: "Trial",
+ price: "$0",
+ interval: "trial",
+ description: "Try all Pro features free for 14 days",
+ features: [
+ `${TRIAL_EVENT_LIMIT.toLocaleString()} events during trial`,
+ "All Pro features included",
+ "No credit card required",
+ ],
+ color:
+ "bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-900 dark:to-indigo-900",
+ icon: <Zap className="h-5 w-5 text-blue-500" />,
+ };
+ }
+
const tier = planName.startsWith("pro") ? "pro" : "free";
const stripePlan = STRIPE_PRICES.find((p) => p.name === planName);
@@ -29,7 +49,10 @@ export const getPlanDetails = (
price: "$0",
interval: "month",
description: "Get started with basic analytics",
- features: ["10,000 events per month", "6 month data retention"],
+ features: [
+ `${DEFAULT_EVENT_LIMIT.toLocaleString()} events per month`,
+ "6 month data retention",
+ ],
color:
"bg-gradient-to-br from-gray-100 to-gray-200 dark:from-gray-800 dark:to-gray-900",
icon: <Clock className="h-5 w-5" />,
diff --git a/client/src/app/settings/subscription/utils/useStripeSubscription.ts b/client/src/app/settings/subscription/utils/useStripeSubscription.ts
index 1b686bfa2..701893c2b 100644
--- a/client/src/app/settings/subscription/utils/useStripeSubscription.ts
+++ b/client/src/app/settings/subscription/utils/useStripeSubscription.ts
@@ -10,6 +10,9 @@ interface SubscriptionData {
eventLimit: number;
interval: string;
cancelAtPeriodEnd?: boolean;
+ isTrial?: boolean;
+ trialDaysRemaining?: number;
+ message?: string; // For expired trial message
}
export function useStripeSubscription() {
@@ -31,7 +34,17 @@ export function useStripeSubscription() {
}
}
- return response.json();
+ const data = await response.json();
+
+ // If status is expired, the trial has ended and no subscription exists
+ if (data.status === "expired") {
+ return {
+ status: "expired",
+ message: data.message,
+ };
+ }
+
+ return data;
};
const { data, isLoading, error, refetch } = useQuery<SubscriptionData>({
diff --git a/client/src/app/subscribe/page.tsx b/client/src/app/subscribe/page.tsx
index 475ece389..96df9032f 100644
--- a/client/src/app/subscribe/page.tsx
+++ b/client/src/app/subscribe/page.tsx
@@ -27,7 +27,7 @@ const EVENT_TIERS = [
// Define types for plans
interface PlanTemplate {
- id: "free" | "pro";
+ id: "pro";
name: string;
price?: string;
interval?: string;
@@ -55,18 +55,8 @@ interface StripePrice {
};
}
-// Plan templates
+// Plan templates - only Pro plan since free tier is removed
const PLAN_TEMPLATES: PlanTemplate[] = [
- {
- id: "free",
- name: "Free",
- price: "$0",
- interval: "month",
- description: "Get started with basic analytics",
- baseFeatures: ["6 month data retention"],
- color:
- "bg-gradient-to-br from-neutral-100 to-neutral-200 dark:from-neutral-800 dark:to-neutral-900",
- },
{
id: "pro",
name: "Pro",
@@ -84,20 +74,19 @@ function getFormattedPrice(price: number): string {
// Find the appropriate price for a tier at current event limit
function findPriceForTier(
- tier: "free" | "pro",
eventLimit: number,
interval: "month" | "year"
): StripePrice | null {
// Determine if we need to look for annual plans
const isAnnual = interval === "year";
- const namePattern = isAnnual ? `${tier}-annual` : tier;
+ const namePattern = isAnnual ? "pro-annual" : "pro";
// Filter plans by name pattern (with or without -annual suffix) and interval
const plans = STRIPE_PRICES.filter(
(plan) =>
(isAnnual
- ? plan.name.startsWith(tier) && plan.name.includes("-annual")
- : plan.name.startsWith(tier) && !plan.name.includes("-annual")) &&
+ ? plan.name.startsWith("pro") && plan.name.includes("-annual")
+ : plan.name.startsWith("pro") && !plan.name.includes("-annual")) &&
plan.interval === interval
);
@@ -118,127 +107,103 @@ function calculateSavings(monthlyPrice: number, annualPrice: number): string {
}
export default function Subscribe() {
- const [selectedTier, setSelectedTier] = useState<"free" | "pro">("free");
- const [eventLimitIndex, setEventLimitIndex] = useState<number>(0); // Default to 20k (index 0)
+ const [eventLimitIndex, setEventLimitIndex] = useState<number>(0); // Default to 100k (index 0)
const [isAnnual, setIsAnnual] = useState<boolean>(true);
const [isLoading, setIsLoading] = useState(false);
const { data: sessionData } = authClient.useSession();
const eventLimit = EVENT_TIERS[eventLimitIndex];
- // TODO: Implement proper check if user already has an active subscription
- const isFreeAvailable = !!sessionData?.user; // Placeholder check based on login
-
// Handle subscription
- async function handleSubscribe(planId: "free" | "pro"): Promise<void> {
- if (planId === "free") {
- return;
- }
-
+ async function handleSubscribe(): Promise<void> {
// Check if user is logged in directly
if (!sessionData?.user) {
toast.error("Please log in to subscribe.");
return;
}
- if (planId === "pro") {
- const selectedTierPrice = findPriceForTier(
- "pro",
- eventLimit,
- isAnnual ? "year" : "month"
- );
+ const selectedTierPrice = findPriceForTier(
+ eventLimit,
+ isAnnual ? "year" : "month"
+ );
- if (!selectedTierPrice) {
- toast.error(
- "Selected pricing plan not found. Please adjust the slider."
- );
- return;
- }
+ if (!selectedTierPrice) {
+ toast.error("Selected pricing plan not found. Please adjust the slider.");
+ return;
+ }
- setIsLoading(true);
- try {
- // Use NEXT_PUBLIC_BACKEND_URL if available, otherwise use relative path for same-origin requests
- const baseUrl = window.location.origin;
- const successUrl = `${baseUrl}/settings/subscription?session_id={CHECKOUT_SESSION_ID}`;
- const cancelUrl = `${baseUrl}/subscribe`;
-
- const response = await fetch(
- `${BACKEND_URL}/stripe/create-checkout-session`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- credentials: "include", // Send cookies
- body: JSON.stringify({
- priceId: selectedTierPrice.priceId,
- successUrl: successUrl,
- cancelUrl: cancelUrl,
- }),
- }
- );
-
- const data = await response.json();
-
- if (!response.ok) {
- throw new Error(data.error || "Failed to create checkout session.");
+ setIsLoading(true);
+ try {
+ // Use NEXT_PUBLIC_BACKEND_URL if available, otherwise use relative path for same-origin requests
+ const baseUrl = window.location.origin;
+ const successUrl = `${baseUrl}/settings/subscription?session_id={CHECKOUT_SESSION_ID}`;
+ const cancelUrl = `${baseUrl}/subscribe`;
+
+ const response = await fetch(
+ `${BACKEND_URL}/stripe/create-checkout-session`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ credentials: "include", // Send cookies
+ body: JSON.stringify({
+ priceId: selectedTierPrice.priceId,
+ successUrl: successUrl,
+ cancelUrl: cancelUrl,
+ }),
}
+ );
- if (data.checkoutUrl) {
- window.location.href = data.checkoutUrl; // Redirect to Stripe checkout
- } else {
- throw new Error("Checkout URL not received.");
- }
- } catch (error: any) {
- toast.error(`Subscription failed: ${error.message}`);
- setIsLoading(false); // Stop loading on error
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.error || "Failed to create checkout session.");
}
+
+ if (data.checkoutUrl) {
+ window.location.href = data.checkoutUrl; // Redirect to Stripe checkout
+ } else {
+ throw new Error("Checkout URL not received.");
+ }
+ } catch (error: any) {
+ toast.error(`Subscription failed: ${error.message}`);
+ setIsLoading(false); // Stop loading on error
}
}
// Handle slider changes
function handleSliderChange(value: number[]): void {
setEventLimitIndex(value[0]);
-
- // If event limit is over 20k, ensure free plan is not selected
- if (EVENT_TIERS[value[0]] > 10_000 && selectedTier === "free") {
- setSelectedTier("pro");
- }
}
// Find the current prices for each tier based on the event limit
const interval = isAnnual ? "year" : "month";
- const basicTierPrice = findPriceForTier("pro", eventLimit, interval);
+ const proPricing = findPriceForTier(eventLimit, interval);
// Also get monthly prices for savings calculation
- const basicMonthly = findPriceForTier("pro", eventLimit, "month");
- const basicAnnual = findPriceForTier("pro", eventLimit, "year");
+ const proMonthly = findPriceForTier(eventLimit, "month");
+ const proAnnual = findPriceForTier(eventLimit, "year");
// Generate plan objects with current state
const plans: Plan[] = PLAN_TEMPLATES.map((template) => {
const plan = { ...template } as Plan;
- if (plan.id === "pro") {
- const tierPrice = basicTierPrice;
- plan.price = tierPrice ? getFormattedPrice(tierPrice.price) : "$19+";
- plan.interval = isAnnual ? "year" : "month";
+ const tierPrice = proPricing;
+ plan.price = tierPrice ? getFormattedPrice(tierPrice.price) : "$19+";
+ plan.interval = isAnnual ? "year" : "month";
- if (basicMonthly && basicAnnual) {
- plan.monthlyPrice = basicMonthly.price;
- plan.annualPrice = basicAnnual.price;
- plan.savings = calculateSavings(basicMonthly.price, basicAnnual.price);
- }
- } else {
- plan.price = "$0";
- plan.interval = "month";
+ if (proMonthly && proAnnual) {
+ plan.monthlyPrice = proMonthly.price;
+ plan.annualPrice = proAnnual.price;
+ plan.savings = calculateSavings(proMonthly.price, proAnnual.price);
}
// Add event limit feature at the beginning
- const eventFeature =
- plan.id === "free"
- ? "10,000 events per month"
- : `${Math.max(eventLimit, 100_000).toLocaleString()} events per month`;
-
+ const eventFeature = `${Math.max(
+ eventLimit,
+ 100_000
+ ).toLocaleString()} events per month`;
plan.features = [eventFeature, ...plan.baseFeatures];
return plan;
@@ -252,19 +217,20 @@ export default function Subscribe() {
Choose Your Analytics Plan
</h1>
<p className="text-lg text-neutral-600 dark:text-neutral-400 mb-6">
- Find the perfect plan to track your site's performance
+ Upgrade for more events and advanced features
+ </p>
+ <p className="text-neutral-500 dark:text-neutral-400">
+ Your 14-day trial gives you access to all Pro features with up to
+ 100,000 events. Subscribe to continue using the service after your
+ trial ends.
</p>
</div>
- <div className="grid gap-8 md:grid-cols-[300px_auto] max-w-4xl mx-auto">
+ <div className="max-w-xl mx-auto">
{plans.map((plan) => (
<div key={plan.id} className="transition-all duration-300 h-full">
<Card
- className={`flex flex-col h-full transition-transform duration-300 transform hover:scale-[1.01] hover:shadow-md cursor-pointer overflow-hidden ${
- plan.id === "free" && !isFreeAvailable
- ? "opacity-50 cursor-not-allowed"
- : ""
- }`}
+ className={`flex flex-col h-full transition-transform duration-300 transform hover:scale-[1.01] hover:shadow-md cursor-pointer overflow-hidden`}
>
<div className={`${plan.color} h-3 w-full`}></div>
@@ -275,97 +241,93 @@ export default function Subscribe() {
</CardDescription>
</CardHeader>
- {plan.id === "pro" && (
- <>
- <CardContent className="pb-0">
- {/* Billing toggle buttons */}
- <div className="flex justify-center mb-6">
- <div className="bg-neutral-100 dark:bg-neutral-800 p-1 rounded-lg inline-flex relative">
- <button
- onClick={() => setIsAnnual(false)}
- className={cn(
- "px-6 py-2 rounded-lg text-sm font-medium transition-all",
- !isAnnual
- ? "bg-white dark:bg-neutral-700 shadow-sm text-black dark:text-white"
- : "text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-neutral-200"
- )}
- >
- Monthly
- </button>
- <div className="relative">
- <button
- onClick={() => setIsAnnual(true)}
- className={cn(
- "px-6 py-2 rounded-lg text-sm font-medium transition-all",
- isAnnual
- ? "bg-white dark:bg-neutral-700 shadow-sm text-black dark:text-white"
- : "text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-neutral-200"
- )}
- >
- Annual
- </button>
- <Badge
- className="absolute -top-4 -right-2 text-white border-0 pointer-events-none"
- variant="green"
- >
- 2 months free
- </Badge>
- </div>
- </div>
+ <CardContent className="pb-0">
+ {/* Billing toggle buttons */}
+ <div className="flex justify-center mb-6">
+ <div className="bg-neutral-100 dark:bg-neutral-800 p-1 rounded-lg inline-flex relative">
+ <button
+ onClick={() => setIsAnnual(false)}
+ className={cn(
+ "px-6 py-2 rounded-lg text-sm font-medium transition-all",
+ !isAnnual
+ ? "bg-white dark:bg-neutral-700 shadow-sm text-black dark:text-white"
+ : "text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-neutral-200"
+ )}
+ >
+ Monthly
+ </button>
+ <div className="relative">
+ <button
+ onClick={() => setIsAnnual(true)}
+ className={cn(
+ "px-6 py-2 rounded-lg text-sm font-medium transition-all",
+ isAnnual
+ ? "bg-white dark:bg-neutral-700 shadow-sm text-black dark:text-white"
+ : "text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-neutral-200"
+ )}
+ >
+ Annual
+ </button>
+ <Badge
+ className="absolute -top-4 -right-2 text-white border-0 pointer-events-none"
+ variant="green"
+ >
+ 2 months free
+ </Badge>
</div>
-
- {/* Event slider */}
- <div className="mb-6">
- <div className="mb-4">
- <div className="flex justify-between mb-2 items-center">
- <div className="text-neutral-600 dark:text-neutral-400 text-sm">
- Events per month
- <div className="font-bold text-lg text-white">
- {eventLimit.toLocaleString()}
- </div>
- </div>
- <div className="flex items-baseline">
- <span className="text-3xl font-bold text-neutral-900 dark:text-white">
- {plan.price}
- </span>
- {plan.interval && (
- <span className="ml-1 text-neutral-500">
- /{plan.interval}
- </span>
- )}
- </div>
+ </div>
+ </div>
+
+ {/* Event slider */}
+ <div className="mb-6">
+ <div className="mb-4">
+ <div className="flex justify-between mb-2 items-center">
+ <div className="text-neutral-600 dark:text-neutral-400 text-sm">
+ Events per month
+ <div className="font-bold text-lg text-white">
+ {eventLimit.toLocaleString()}
</div>
</div>
-
- <Slider
- defaultValue={[0]} // Default to index 0 (20k)
- max={EVENT_TIERS.length - 1}
- min={0}
- step={1}
- onValueChange={handleSliderChange}
- className="mb-3"
- />
-
- <div className="flex justify-between text-xs text-neutral-500">
- {EVENT_TIERS.map((tier, index) => (
- <span
- key={index}
- className={
- eventLimitIndex === index
- ? "font-bold text-white"
- : ""
- }
- >
- {tier >= 1_000_000
- ? `${tier / 1_000_000}M`
- : `${tier / 1_000}K`}
+ <div className="flex items-baseline">
+ <span className="text-3xl font-bold text-neutral-900 dark:text-white">
+ {plan.price}
+ </span>
+ {plan.interval && (
+ <span className="ml-1 text-neutral-500">
+ /{plan.interval}
</span>
- ))}
+ )}
</div>
</div>
- </CardContent>
- </>
- )}
+ </div>
+
+ <Slider
+ defaultValue={[0]} // Default to index 0 (100k)
+ max={EVENT_TIERS.length - 1}
+ min={0}
+ step={1}
+ onValueChange={handleSliderChange}
+ className="mb-3"
+ />
+
+ <div className="flex justify-between text-xs text-neutral-500">
+ {EVENT_TIERS.map((tier, index) => (
+ <span
+ key={index}
+ className={
+ eventLimitIndex === index
+ ? "font-bold text-white"
+ : ""
+ }
+ >
+ {tier >= 1_000_000
+ ? `${tier / 1_000_000}M`
+ : `${tier / 1_000}K`}
+ </span>
+ ))}
+ </div>
+ </div>
+ </CardContent>
<CardContent className={"pt-0 flex-grow"}>
<div className="w-full h-px bg-neutral-200 dark:bg-neutral-800 mb-4"></div>
@@ -384,26 +346,14 @@ export default function Subscribe() {
</CardContent>
<CardFooter>
- {plan.id === "pro" ? (
- <Button
- onClick={() => handleSubscribe(plan.id)}
- className="w-full"
- disabled={isLoading}
- variant="success"
- >
- {isLoading
- ? "Processing..."
- : `Subscribe to ${plan.name}`}
- </Button>
- ) : (
- <Button
- className="w-full border-neutral-300 text-gray-700 dark:border-neutral-700 dark:text-neutral-300"
- variant="outline"
- disabled={!isFreeAvailable}
- >
- {isFreeAvailable ? "Current Plan" : "Not Available"}
- </Button>
- )}
+ <Button
+ onClick={handleSubscribe}
+ className="w-full"
+ disabled={isLoading}
+ variant="success"
+ >
+ {isLoading ? "Processing..." : `Subscribe to ${plan.name}`}
+ </Button>
</CardFooter>
</Card>
</div>
diff --git a/client/src/components/FreeTrialBanner.tsx b/client/src/components/FreeTrialBanner.tsx
new file mode 100644
index 000000000..d7c3651c2
--- /dev/null
+++ b/client/src/components/FreeTrialBanner.tsx
@@ -0,0 +1,91 @@
+import { AlertTriangle, ArrowRight, Clock } from "lucide-react";
+import { Alert, AlertDescription, AlertTitle } from "./ui/alert";
+import { useStripeSubscription } from "../app/settings/subscription/utils/useStripeSubscription";
+import Link from "next/link";
+import { Button } from "./ui/button";
+
+export function FreeTrialBanner() {
+ const { data: subscription } = useStripeSubscription();
+
+ // Don't show the banner if no subscription data or if there's a paid subscription
+ if (
+ !subscription ||
+ (subscription.status === "active" && !subscription.isTrial)
+ ) {
+ return null;
+ }
+
+ // Format numbers with commas
+ const formatNumber = (num: number = 0) => {
+ return num.toLocaleString();
+ };
+
+ // Active trial banner - slightly more visible but still minimal
+ if (!subscription.isTrial) {
+ const daysRemaining = subscription.trialDaysRemaining || 0;
+ const eventLimit = subscription.eventLimit || 100000;
+ const eventsUsed = subscription.monthlyEventCount || 0;
+
+ return (
+ <div className="px-4 py-3 border-b border-blue-100 dark:border-blue-800/30 bg-blue-50/80 dark:bg-blue-900/20 text-sm flex justify-between items-center mb-4">
+ <div className="text-blue-700 dark:text-blue-300 flex items-center font-medium">
+ <Clock className="h-4 w-4 mr-2 text-blue-500 dark:text-blue-400 flex-shrink-0" />
+ <span>
+ Free trial: <strong>{daysRemaining}</strong> days remaining – Using{" "}
+ <strong>{formatNumber(eventsUsed)}</strong> of{" "}
+ {formatNumber(eventLimit)} events
+ </span>
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ className="text-xs h-7 px-3 text-blue-600 hover:text-blue-700 hover:bg-blue-100/60 dark:text-blue-300 dark:hover:text-blue-200 dark:hover:bg-blue-800/30 border-blue-200 dark:border-blue-800/50"
+ asChild
+ >
+ <Link href="/subscribe">
+ Upgrade <ArrowRight className="ml-1 h-3 w-3" />
+ </Link>
+ </Button>
+ </div>
+ );
+ }
+
+ // Trial expired banner - keep prominent
+ if (subscription.status === "expired") {
+ return (
+ <div className="m-4 mb-0">
+ <Alert className="p-4 bg-amber-50 border-amber-200 dark:bg-amber-900/20 dark:border-amber-800">
+ <div className="flex items-start space-x-3">
+ <AlertTriangle className="h-5 w-5 mt-0.5 text-amber-500 dark:text-amber-400" />
+ <div className="flex-1">
+ <AlertTitle className="text-base font-semibold mb-1 text-amber-700 dark:text-amber-400">
+ Your Free Trial Has Ended
+ </AlertTitle>
+ <div className="mb-2 text-sm text-amber-700 dark:text-amber-400">
+ Your 14-day free trial has expired. Subscribe to continue using
+ our analytics services.
+ </div>
+
+ <div className="flex flex-col space-y-2 sm:flex-row sm:space-y-0 sm:space-x-2 items-start sm:items-center">
+ <AlertDescription className="text-sm text-amber-700 dark:text-amber-400">
+ Choose a subscription plan to continue collecting analytics
+ data.
+ </AlertDescription>
+ <Button
+ className="bg-amber-500 hover:bg-amber-600 text-white border-amber-400 hover:border-amber-500 py-1 h-auto text-sm"
+ asChild
+ >
+ <Link href="/subscribe">
+ Subscribe Now <ArrowRight className="ml-1 h-3 w-3" />
+ </Link>
+ </Button>
+ </div>
+ </div>
+ </div>
+ </Alert>
+ </div>
+ );
+ }
+
+ return null;
+}
diff --git a/server/src/api/stripe/getSubscription.ts b/server/src/api/stripe/getSubscription.ts
index e9cc5d0ec..44159ee6a 100644
--- a/server/src/api/stripe/getSubscription.ts
+++ b/server/src/api/stripe/getSubscription.ts
@@ -3,7 +3,12 @@ import { stripe } from "../../lib/stripe.js";
import { db } from "../../db/postgres/postgres.js";
import { user as userSchema } from "../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
-import { STRIPE_PRICES, StripePlan } from "../../lib/const.js";
+import {
+ STRIPE_PRICES,
+ StripePlan,
+ TRIAL_DURATION_DAYS,
+ TRIAL_EVENT_LIMIT,
+} from "../../lib/const.js";
import Stripe from "stripe";
// Function to find plan details by price ID
@@ -21,6 +26,7 @@ export async function getSubscriptionInner(userId: string) {
.select({
stripeCustomerId: userSchema.stripeCustomerId,
monthlyEventCount: userSchema.monthlyEventCount,
+ createdAt: userSchema.createdAt,
})
.from(userSchema)
.where(eq(userSchema.id, userId))
@@ -28,60 +34,89 @@ export async function getSubscriptionInner(userId: string) {
const user = userResult[0];
- if (!user || !user.stripeCustomerId) {
- // If no customer ID, they definitely don't have a subscription
+ if (!user) {
return null;
}
- // 2. List active subscriptions for the customer from Stripe
- const subscriptions = await (stripe as Stripe).subscriptions.list({
- customer: user.stripeCustomerId,
- status: "active", // Only fetch active subscriptions
- limit: 1, // Users should only have one active subscription in this model
- expand: ["data.plan.product"], // Expand to get product details if needed
- });
-
- if (subscriptions.data.length === 0) {
- // No active subscription found
- return null;
+ // Check if user has an active Stripe subscription
+ if (user.stripeCustomerId) {
+ // 2. List active subscriptions for the customer from Stripe
+ const subscriptions = await (stripe as Stripe).subscriptions.list({
+ customer: user.stripeCustomerId,
+ status: "active", // Only fetch active subscriptions
+ limit: 1, // Users should only have one active subscription in this model
+ expand: ["data.plan.product"], // Expand to get product details if needed
+ });
+
+ if (subscriptions.data.length > 0) {
+ const sub = subscriptions.data[0];
+ const priceId = sub.items.data[0]?.price.id;
+
+ if (!priceId) {
+ throw new Error("Subscription item price ID not found");
+ }
+
+ // 3. Find corresponding plan details from your constants
+ const planDetails = findPlanDetails(priceId);
+
+ if (!planDetails) {
+ console.error("Plan details not found for price ID:", priceId);
+ // Still return the basic subscription info even if local plan details missing
+ return {
+ id: sub.id,
+ planName: "Unknown Plan", // Indicate missing details
+ status: sub.status,
+ currentPeriodEnd: new Date(sub.current_period_end * 1000),
+ eventLimit: 0, // Unknown limit
+ monthlyEventCount: user.monthlyEventCount,
+ interval: sub.items.data[0]?.price.recurring?.interval ?? "unknown",
+ };
+ }
+
+ // 4. Format and return the subscription data
+ const responseData = {
+ id: sub.id,
+ planName: planDetails.name,
+ status: sub.status,
+ currentPeriodEnd: new Date(sub.current_period_end * 1000), // Convert Unix timestamp to Date
+ eventLimit: planDetails.limits.events,
+ monthlyEventCount: user.monthlyEventCount,
+ interval: sub.items.data[0]?.price.recurring?.interval ?? "unknown",
+ };
+
+ return responseData;
+ }
}
- const sub = subscriptions.data[0];
- const priceId = sub.items.data[0]?.price.id;
-
- if (!priceId) {
- throw new Error("Subscription item price ID not found");
- }
+ // If we get here, the user has no active paid subscription
+ // Check if they're in the trial period
+ const createdAt = new Date(user.createdAt);
+ const now = new Date();
+ const trialEndDate = new Date(createdAt);
+ trialEndDate.setDate(trialEndDate.getDate() + TRIAL_DURATION_DAYS);
- // 3. Find corresponding plan details from your constants
- const planDetails = findPlanDetails(priceId);
+ const isInTrialPeriod = now < trialEndDate;
- if (!planDetails) {
- console.error("Plan details not found for price ID:", priceId);
- // Still return the basic subscription info even if local plan details missing
+ if (isInTrialPeriod) {
+ // User is in trial period
return {
- id: sub.id,
- planName: "Unknown Plan", // Indicate missing details
- status: sub.status,
- currentPeriodEnd: new Date(sub.current_period_end * 1000),
- eventLimit: 0, // Unknown limit
+ id: null,
+ planName: "trial",
+ status: "trialing",
+ currentPeriodEnd: trialEndDate,
+ eventLimit: TRIAL_EVENT_LIMIT,
monthlyEventCount: user.monthlyEventCount,
- interval: sub.items.data[0]?.price.recurring?.interval ?? "unknown",
+ interval: "month",
+ isTrial: true,
+ trialDaysRemaining: Math.ceil(
+ (trialEndDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)
+ ),
};
}
- // 4. Format and return the subscription data
- const responseData = {
- id: sub.id,
- planName: planDetails.name,
- status: sub.status,
- currentPeriodEnd: new Date(sub.current_period_end * 1000), // Convert Unix timestamp to Date
- eventLimit: planDetails.limits.events,
- monthlyEventCount: user.monthlyEventCount,
- interval: sub.items.data[0]?.price.recurring?.interval ?? "unknown",
- };
-
- return responseData;
+ // User has no subscription and trial has ended - return null
+ // No free plan fallback
+ return null;
}
export async function getSubscription(
@@ -97,6 +132,14 @@ export async function getSubscription(
try {
const responseData = await getSubscriptionInner(userId);
+ // If trial has expired and no subscription, inform the user
+ if (!responseData) {
+ return reply.send({
+ status: "expired",
+ message: "Your trial has expired. Please subscribe to continue.",
+ });
+ }
+
return reply.send(responseData);
} catch (error: any) {
console.error("Get Subscription Error:", error);
diff --git a/server/src/cron/monthly-usage-checker.ts b/server/src/cron/monthly-usage-checker.ts
index 097875ae2..19b03389d 100644
--- a/server/src/cron/monthly-usage-checker.ts
+++ b/server/src/cron/monthly-usage-checker.ts
@@ -6,22 +6,21 @@ import { db } from "../db/postgres/postgres.js";
import { processResults } from "../api/analytics/utils.js";
import { stripe } from "../lib/stripe.js";
import Stripe from "stripe";
+import { DateTime } from "luxon";
// Default event limit for users without an active subscription
-const DEFAULT_EVENT_LIMIT = 10_000;
+const DEFAULT_EVENT_LIMIT = 0;
+
+const TRIAL_EVENT_LIMIT = 1_000_000;
// Global set to track site IDs that have exceeded their monthly limits
export const sitesOverLimit = new Set<number>();
/**
- * Gets the first day of the current month in YYYY-MM-DD format
+ * Gets the first day of the current month in YYYY-MM-DD format using Luxon
*/
function getStartOfMonth(): string {
- const date = new Date();
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
- 2,
- "0"
- )}-01`;
+ return DateTime.now().startOf("month").toISODate() as string;
}
/**
@@ -62,8 +61,19 @@ async function getSiteIdsForUser(userId: string): Promise<number[]> {
async function getUserSubscriptionInfo(userData: {
id: string;
stripeCustomerId: string | null;
+ createdAt: string;
+ email: string;
}): Promise<[number, string | null]> {
if (!userData.stripeCustomerId) {
+ const createdAtDate = DateTime.fromSQL(userData.createdAt);
+ const daysSinceCreation = Math.abs(createdAtDate.diffNow("days").days);
+
+ // If the user was created in the last 14 days, use the trial limit
+ if (daysSinceCreation < 14) {
+ // For trial users, use their account creation date as the starting point for counting events
+ return [TRIAL_EVENT_LIMIT, createdAtDate.toISODate() as string];
+ }
+
// No Stripe customer ID, use default limit and start of current month
return [DEFAULT_EVENT_LIMIT, getStartOfMonth()];
}
@@ -98,17 +108,46 @@ async function getUserSubscriptionInfo(userData: {
(plan.annualDiscountPriceId && plan.annualDiscountPriceId === priceId)
);
+ // Get the event limit from the plan
const eventLimit = planDetails
- ? planDetails.limits.events
+ ? planDetails.limits.events // This is already the monthly event limit, regardless of billing interval
: DEFAULT_EVENT_LIMIT;
- const periodStart = sub.current_period_start
- ? new Date(sub.current_period_start * 1000).toISOString().split("T")[0]
- : getStartOfMonth();
+
+ // For the period start, we need to handle several cases:
+ const currentMonthStart = getStartOfMonth();
+ let periodStart = currentMonthStart;
+
+ if (sub.current_period_start) {
+ // Convert subscription start timestamp to DateTime
+ const subscriptionStartDate = DateTime.fromSeconds(
+ sub.current_period_start
+ );
+ const currentMonth = DateTime.now().startOf("month");
+
+ // If the subscription started within the current month, use that as the start date
+ // This ensures we don't count events from before they subscribed (e.g., during their free trial)
+ if (subscriptionStartDate >= currentMonth) {
+ periodStart = subscriptionStartDate.toISODate() as string;
+ console.log(
+ `[Monthly Usage Checker] User ${userData.email} subscribed during current month on ${periodStart}. Using subscription start date for counting.`
+ );
+ } else {
+ console.log(
+ `[Monthly Usage Checker] User ${userData.email} subscription started before current month. Using month start for counting.`
+ );
+ }
+ }
+
+ // Include subscription info for logging purposes
+ const interval = sub.items.data[0]?.price.recurring?.interval || "unknown";
+ console.log(
+ `[Monthly Usage Checker] User ${userData.email} has a ${interval} subscription.`
+ );
return [eventLimit, periodStart];
} catch (error: any) {
console.error(
- `Error fetching Stripe subscription info for user ${userData.id}:`,
+ `Error fetching Stripe subscription info for user ${userData.email}:`,
error
);
// Fallback to default limit and current month start on Stripe API error
@@ -169,6 +208,7 @@ export async function updateUsersMonthlyUsage() {
id: user.id,
email: user.email,
stripeCustomerId: user.stripeCustomerId,
+ createdAt: user.createdAt,
})
.from(user);
@@ -212,12 +252,15 @@ export async function updateUsersMonthlyUsage() {
);
}
+ // Format additional date info for logging if available
+ const periodInfo = periodStart
+ ? `period started ${periodStart}`
+ : "this month";
+
console.log(
`[Monthly Usage Checker] Updated user ${
userData.email
- }: ${pageviewCount.toLocaleString()} events, limit ${eventLimit.toLocaleString()}, period started ${
- periodStart || "this month"
- }`
+ }: ${pageviewCount.toLocaleString()} events, limit ${eventLimit.toLocaleString()}, ${periodInfo}`
);
} catch (error) {
console.error(
diff --git a/server/src/lib/const.ts b/server/src/lib/const.ts
index 73b0dfb8b..fb963bb8e 100644
--- a/server/src/lib/const.ts
+++ b/server/src/lib/const.ts
@@ -4,6 +4,10 @@ dotenv.config();
export const IS_CLOUD = process.env.CLOUD === "true";
+// Trial constants
+export const TRIAL_DURATION_DAYS = 14;
+export const TRIAL_EVENT_LIMIT = 100000;
+
// Define a type for the plan objects
export interface StripePlan {
priceId: string;