🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Refactor subscription components to improve structure and reusability… (#933)
Goldflag22e767bb0d05
diff --git a/client/messages/cs.json b/client/messages/cs.jsonindex 73fbcf2a5..5d928b9b1 100644--- a/client/messages/cs.json+++ b/client/messages/cs.json@@ -1130,12 +1130,16 @@"rbrahO": "Zavřít","4cfxQk": "AppSumo plán úrovně {tier}","pIN/qH": "Máš AppSumo doživotní plán s až {limit} událostmi měsíčně.",- "x6GhQj": "Limit událostí překročen",+ "ja2Zok": "Upgradovat na Pro","IpNrN4": "Překročil jsi měsíční limit událostí. Pro pokračování sběru analytiky prosím upgraduj na plán Pro.",+ "6dqYnF": "",+ "P7PLVj": "",+ "/0TOL5": "",+ "FgydNe": "",+ "x6GhQj": "Limit událostí překročen","96ejG8": "Blížíš se k limitu","S7U3Nx": "Blížíš se k měsíčnímu limitu událostí. Zvaž upgrade na placený plán pro vyšší limity.","wbsq7O": "Využití",- "ja2Zok": "Upgradovat na Pro","rd5F5r": "","kdqPM0": "Máš vlastní plán s až {limit} zobrazeními stránek měsíčně.","kTH3Q2": "Překročil jsi měsíční limit událostí. Pro pomoc prosím kontaktuj podporu.",@@ -1162,5 +1166,10 @@"5YSWst": "Skript je nainstalován a funguje správně.","EIQFLe": "Tag skriptu nalezen, ale nespouští se","+x0BAO": "Skript nebyl detekován",- "rOpS8J": "Rybbit v{latest} je k dispozici (máš v{current})"+ "rOpS8J": "Rybbit v{latest} je k dispozici (máš v{current})",+ "raz91s": "Zaplaceno",+ "N7QE9K": "Otevřená",+ "6VtPnS": "Zrušená",+ "T6S3Fn": "Nevymahatelná",+ "fS4iqP": "Koncept"}diff --git a/client/messages/de.json b/client/messages/de.jsonindex 83e22a309..5ca91d100 100644--- a/client/messages/de.json+++ b/client/messages/de.json@@ -1130,12 +1130,16 @@"rbrahO": "Schließen","4cfxQk": "AppSumo Plan Stufe {tier}","pIN/qH": "Sie sind im AppSumo-Lifetime-Plan mit bis zu {limit} Events pro Monat.",- "x6GhQj": "Event-Limit überschritten",+ "ja2Zok": "Auf Pro upgraden","IpNrN4": "Sie haben Ihr monatliches Event-Limit überschritten. Bitte upgraden Sie auf einen Pro-Plan, um weiterhin Analysen zu sammeln.",+ "6dqYnF": "",+ "P7PLVj": "",+ "/0TOL5": "",+ "FgydNe": "",+ "x6GhQj": "Event-Limit überschritten","96ejG8": "Limit fast erreicht","S7U3Nx": "Sie nähern sich Ihrem monatlichen Event-Limit. Erwägen Sie ein Upgrade auf einen kostenpflichtigen Plan für höhere Limits.","wbsq7O": "Nutzung",- "ja2Zok": "Auf Pro upgraden","rd5F5r": "Benutzerdefinierter Plan","kdqPM0": "Sie haben einen individuellen Plan mit bis zu {limit} Seitenaufrufen pro Monat.","kTH3Q2": "Sie haben Ihr monatliches Event-Limit überschritten. Bitte kontaktieren Sie den Support.",@@ -1162,5 +1166,10 @@"5YSWst": "Skript ist installiert und läuft korrekt.","EIQFLe": "Script-Tag gefunden, wird aber nicht ausgeführt","+x0BAO": "Skript nicht erkannt",- "rOpS8J": "Rybbit v{latest} ist verfügbar (Sie verwenden v{current})"+ "rOpS8J": "Rybbit v{latest} ist verfügbar (Sie verwenden v{current})",+ "raz91s": "Bezahlt",+ "N7QE9K": "Offen",+ "6VtPnS": "Storniert",+ "T6S3Fn": "Uneinbringlich",+ "fS4iqP": "Entwurf"}diff --git a/client/messages/en.json b/client/messages/en.jsonindex d00da9f27..a791728d7 100644--- a/client/messages/en.json+++ b/client/messages/en.json@@ -1130,12 +1130,16 @@"rbrahO": "Close","4cfxQk": "AppSumo Plan Tier {tier}","pIN/qH": "You are on the AppSumo lifetime plan with up to {limit} events per month.",- "x6GhQj": "Event Limit Exceeded",+ "ja2Zok": "Upgrade To Pro","IpNrN4": "You have exceeded your monthly event limit. Please upgrade to a Pro plan to continue collecting analytics.",+ "6dqYnF": "Invoices",+ "P7PLVj": "Date",+ "/0TOL5": "Amount",+ "FgydNe": "View",+ "x6GhQj": "Event Limit Exceeded","96ejG8": "Approaching Limit","S7U3Nx": "You are approaching your monthly event limit. Consider upgrading to a paid plan for higher limits.","wbsq7O": "Usage",- "ja2Zok": "Upgrade To Pro","rd5F5r": "Custom Plan","kdqPM0": "You have a custom plan with up to {limit} pageviews per month.","kTH3Q2": "You have exceeded your monthly event limit. Please contact support for assistance.",@@ -1162,5 +1166,10 @@"5YSWst": "Script is installed and running correctly.","EIQFLe": "Script tag found but not executing","+x0BAO": "Script not detected",- "rOpS8J": "Rybbit v{latest} is available (you're on v{current})"+ "rOpS8J": "Rybbit v{latest} is available (you're on v{current})",+ "raz91s": "Paid",+ "N7QE9K": "Open",+ "6VtPnS": "Void",+ "T6S3Fn": "Uncollectible",+ "fS4iqP": "Draft"}diff --git a/client/messages/es.json b/client/messages/es.jsonindex d57d0a9c4..48bf9a981 100644--- a/client/messages/es.json+++ b/client/messages/es.json@@ -1130,12 +1130,16 @@"rbrahO": "Cerrar","4cfxQk": "Nivel de plan AppSumo {tier}","pIN/qH": "Estás en el plan de por vida de AppSumo con hasta {limit} eventos por mes.",- "x6GhQj": "Límite de eventos excedido",+ "ja2Zok": "Actualizar a Pro","IpNrN4": "Has excedido tu límite de eventos mensuales. Por favor, actualiza a un plan Pro para seguir recopilando analíticas.",+ "6dqYnF": "",+ "P7PLVj": "",+ "/0TOL5": "",+ "FgydNe": "",+ "x6GhQj": "Límite de eventos excedido","96ejG8": "Acercándose al límite","S7U3Nx": "Te estás acercando a tu límite de eventos mensuales. Considera actualizar a un plan de pago para obtener límites más altos.","wbsq7O": "Uso",- "ja2Zok": "Actualizar a Pro","rd5F5r": "Plan personalizado","kdqPM0": "Tienes un plan personalizado con hasta {limit} visitas por mes.","kTH3Q2": "Has excedido tu límite mensual de eventos. Por favor, contacta con soporte para obtener ayuda.",@@ -1162,5 +1166,10 @@"5YSWst": "El script está instalado y funcionando correctamente.","EIQFLe": "Etiqueta de script encontrada pero no se está ejecutando","+x0BAO": "Script no detectado",- "rOpS8J": "Rybbit v{latest} está disponible (estás en v{current})"+ "rOpS8J": "Rybbit v{latest} está disponible (estás en v{current})",+ "raz91s": "Pagado",+ "N7QE9K": "Abierto",+ "6VtPnS": "Anulado",+ "T6S3Fn": "Incobrable",+ "fS4iqP": "Borrador"}diff --git a/client/messages/fr.json b/client/messages/fr.jsonindex 15aaeea7d..d6177b981 100644--- a/client/messages/fr.json+++ b/client/messages/fr.json@@ -1130,12 +1130,16 @@"rbrahO": "Fermer","4cfxQk": "Plan AppSumo Niveau {tier}","pIN/qH": "Vous êtes sur le plan à vie AppSumo avec jusqu'à {limit} événements par mois.",- "x6GhQj": "Limite d'événements dépassée",+ "ja2Zok": "Passer à Pro","IpNrN4": "Vous avez dépassé votre limite mensuelle d'événements. Veuillez passer à un plan Pro pour continuer à collecter des analyses.",+ "6dqYnF": "",+ "P7PLVj": "",+ "/0TOL5": "",+ "FgydNe": "",+ "x6GhQj": "Limite d'événements dépassée","96ejG8": "Approche de la limite","S7U3Nx": "Vous approchez de votre limite mensuelle d'événements. Envisagez de passer à un plan payant pour des limites plus élevées.","wbsq7O": "Utilisation",- "ja2Zok": "Passer à Pro","rd5F5r": "Plan personnalisé","kdqPM0": "Vous avez un plan personnalisé avec jusqu'à {limit} pages vues par mois.","kTH3Q2": "Vous avez dépassé votre limite mensuelle d'événements. Veuillez contacter le support.",@@ -1162,5 +1166,10 @@"5YSWst": "Le script est installé et fonctionne correctement.","EIQFLe": "Balise script trouvée mais ne s'exécute pas","+x0BAO": "Script non détecté",- "rOpS8J": "Rybbit v{latest} est disponible (vous utilisez v{current})"+ "rOpS8J": "Rybbit v{latest} est disponible (vous utilisez v{current})",+ "raz91s": "Payé",+ "N7QE9K": "Ouvert",+ "6VtPnS": "Annulé",+ "T6S3Fn": "Irrécouvrable",+ "fS4iqP": "Brouillon"}diff --git a/client/messages/it.json b/client/messages/it.jsonindex 48fec204d..5c5d4b1d0 100644--- a/client/messages/it.json+++ b/client/messages/it.json@@ -1130,12 +1130,16 @@"rbrahO": "Chiudi","4cfxQk": "Piano AppSumo Livello {tier}","pIN/qH": "Sei nel piano a vita AppSumo con fino a {limit} eventi al mese.",- "x6GhQj": "Limite Eventi Superato",+ "ja2Zok": "Passa a Pro","IpNrN4": "Hai superato il tuo limite di eventi mensili. Passa a un piano Pro per continuare a raccogliere analisi.",+ "6dqYnF": "",+ "P7PLVj": "",+ "/0TOL5": "",+ "FgydNe": "",+ "x6GhQj": "Limite Eventi Superato","96ejG8": "In Avvicinamento al Limite","S7U3Nx": "Ti stai avvicinando al tuo limite di eventi mensili. Considera di passare a un piano a pagamento per limiti superiori.","wbsq7O": "Utilizzo",- "ja2Zok": "Passa a Pro","rd5F5r": "Piano personalizzato","kdqPM0": "Hai un piano personalizzato con fino a {limit} visualizzazioni di pagina al mese.","kTH3Q2": "Hai superato il tuo limite di eventi mensili. Contatta il supporto per assistenza.",@@ -1162,5 +1166,10 @@"5YSWst": "Lo script è installato e funzionante correttamente.","EIQFLe": "Tag script trovato ma non in esecuzione","+x0BAO": "Script non rilevato",- "rOpS8J": "Rybbit v{latest} è disponibile (sei sulla v{current})"+ "rOpS8J": "Rybbit v{latest} è disponibile (sei sulla v{current})",+ "raz91s": "Pagato",+ "N7QE9K": "Aperto",+ "6VtPnS": "Annullato",+ "T6S3Fn": "Inesigibile",+ "fS4iqP": "Bozza"}diff --git a/client/messages/ja.json b/client/messages/ja.jsonindex 98d8786c4..46f2b87d1 100644--- a/client/messages/ja.json+++ b/client/messages/ja.json@@ -1130,12 +1130,16 @@"rbrahO": "閉じる","4cfxQk": "AppSumoプランティア{tier}","pIN/qH": "AppSumoライフタイムプランで月{limit}イベントまでご利用いただけます。",- "x6GhQj": "イベント上限超過",+ "ja2Zok": "Proにアップグレード","IpNrN4": "月間イベント上限を超えました。アナリティクスの収集を続けるにはProプランにアップグレードしてください。",+ "6dqYnF": "",+ "P7PLVj": "",+ "/0TOL5": "",+ "FgydNe": "",+ "x6GhQj": "イベント上限超過","96ejG8": "上限に近づいています","S7U3Nx": "月間イベント上限に近づいています。より高い上限にするには有料プランへのアップグレードをご検討ください。","wbsq7O": "使用量",- "ja2Zok": "Proにアップグレード","rd5F5r": "カスタムプラン","kdqPM0": "カスタムプランで月{limit}ページビューまでご利用いただけます。","kTH3Q2": "月間イベント上限を超えました。サポートにお問い合わせください。",@@ -1162,5 +1166,10 @@"5YSWst": "スクリプトは正常にインストールされ、実行されています。","EIQFLe": "スクリプトタグは見つかりましたが、実行されていません","+x0BAO": "スクリプトが検出されません",- "rOpS8J": "Rybbit v{latest}が利用可能です(現在v{current})"+ "rOpS8J": "Rybbit v{latest}が利用可能です(現在v{current})",+ "raz91s": "支払い済み",+ "N7QE9K": "未払い",+ "6VtPnS": "無効",+ "T6S3Fn": "回収不能",+ "fS4iqP": "下書き"}diff --git a/client/messages/ko.json b/client/messages/ko.jsonindex 219e1df71..fd7f02bad 100644--- a/client/messages/ko.json+++ b/client/messages/ko.json@@ -1130,12 +1130,16 @@"rbrahO": "닫기","4cfxQk": "AppSumo 플랜 등급 {tier}","pIN/qH": "월 최대 {limit}개 이벤트의 AppSumo 평생 플랜을 사용 중입니다.",- "x6GhQj": "이벤트 한도 초과",+ "ja2Zok": "Pro로 업그레이드","IpNrN4": "월별 이벤트 한도를 초과했습니다. 분석 수집을 계속하려면 Pro 플랜으로 업그레이드하세요.",+ "6dqYnF": "",+ "P7PLVj": "",+ "/0TOL5": "",+ "FgydNe": "",+ "x6GhQj": "이벤트 한도 초과","96ejG8": "한도에 근접 중","S7U3Nx": "월별 이벤트 한도에 근접하고 있습니다. 더 높은 한도를 위해 유료 플랜으로 업그레이드를 고려하세요.","wbsq7O": "사용량",- "ja2Zok": "Pro로 업그레이드","rd5F5r": "맞춤 플랜","kdqPM0": "월 최대 {limit}개 페이지뷰의 사용자 정의 플랜입니다.","kTH3Q2": "월별 이벤트 한도를 초과했습니다. 지원팀에 문의해 주세요.",@@ -1162,5 +1166,10 @@"5YSWst": "스크립트가 설치되어 올바르게 실행 중입니다.","EIQFLe": "스크립트 태그는 발견되었지만 실행되지 않고 있습니다","+x0BAO": "스크립트가 감지되지 않음",- "rOpS8J": "Rybbit v{latest}를 사용할 수 있습니다 (현재 v{current})"+ "rOpS8J": "Rybbit v{latest}를 사용할 수 있습니다 (현재 v{current})",+ "raz91s": "결제 완료",+ "N7QE9K": "미결제",+ "6VtPnS": "무효",+ "T6S3Fn": "회수 불가",+ "fS4iqP": "초안"}diff --git a/client/messages/pl.json b/client/messages/pl.jsonindex 59e2f3dbd..27385d0d4 100644--- a/client/messages/pl.json+++ b/client/messages/pl.json@@ -1130,12 +1130,16 @@"rbrahO": "Zamknij","4cfxQk": "Plan AppSumo Tier {tier}","pIN/qH": "Jesteś na dożywotnim planie AppSumo z limitem do {limit} zdarzeń miesięcznie.",- "x6GhQj": "Przekroczono limit zdarzeń",+ "ja2Zok": "Ulepsz do Pro","IpNrN4": "Przekroczyłeś swój miesięczny limit zdarzeń. Ulepsz do planu Pro, aby kontynuować zbieranie danych analitycznych.",+ "6dqYnF": "",+ "P7PLVj": "",+ "/0TOL5": "",+ "FgydNe": "",+ "x6GhQj": "Przekroczono limit zdarzeń","96ejG8": "Zbliżanie się do limitu","S7U3Nx": "Zbliżasz się do miesięcznego limitu zdarzeń. Rozważ ulepszenie do płatnego planu dla wyższych limitów.","wbsq7O": "Wykorzystanie",- "ja2Zok": "Ulepsz do Pro","rd5F5r": "Plan niestandardowy","kdqPM0": "Masz niestandardowy plan z limitem do {limit} odsłon miesięcznie.","kTH3Q2": "Przekroczyłeś swój miesięczny limit zdarzeń. Skontaktuj się z pomocą techniczną.",@@ -1162,5 +1166,10 @@"5YSWst": "Skrypt jest zainstalowany i działa poprawnie.","EIQFLe": "Znaleziono tag skryptu, ale nie jest wykonywany","+x0BAO": "Skrypt nie wykryty",- "rOpS8J": "Rybbit v{latest} jest dostępny (masz v{current})"+ "rOpS8J": "Rybbit v{latest} jest dostępny (masz v{current})",+ "raz91s": "Opłacone",+ "N7QE9K": "Otwarte",+ "6VtPnS": "Anulowane",+ "T6S3Fn": "Nieściągalne",+ "fS4iqP": "Szkic"}diff --git a/client/messages/pt.json b/client/messages/pt.jsonindex a02855994..5114a516e 100644--- a/client/messages/pt.json+++ b/client/messages/pt.json@@ -1130,12 +1130,16 @@"rbrahO": "Fechar","4cfxQk": "Plano AppSumo Tier {tier}","pIN/qH": "Você está no plano vitalício AppSumo com até {limit} eventos por mês.",- "x6GhQj": "Limite de Eventos Excedido",+ "ja2Zok": "Atualizar Para Pro","IpNrN4": "Você excedeu seu limite mensal de eventos. Por favor, atualize para um plano Pro para continuar coletando análises.",+ "6dqYnF": "",+ "P7PLVj": "",+ "/0TOL5": "",+ "FgydNe": "",+ "x6GhQj": "Limite de Eventos Excedido","96ejG8": "Aproximando-se do Limite","S7U3Nx": "Você está se aproximando do seu limite mensal de eventos. Considere atualizar para um plano pago para limites maiores.","wbsq7O": "Uso",- "ja2Zok": "Atualizar Para Pro","rd5F5r": "Plano personalizado","kdqPM0": "Você tem um plano personalizado com até {limit} visualizações de página por mês.","kTH3Q2": "Você excedeu seu limite mensal de eventos. Por favor, entre em contato com o suporte para assistência.",@@ -1162,5 +1166,10 @@"5YSWst": "Script está instalado e funcionando corretamente.","EIQFLe": "Tag de script encontrada mas não executando","+x0BAO": "Script não detectado",- "rOpS8J": "Rybbit v{latest} está disponível (você está na v{current})"+ "rOpS8J": "Rybbit v{latest} está disponível (você está na v{current})",+ "raz91s": "Pago",+ "N7QE9K": "Aberto",+ "6VtPnS": "Anulado",+ "T6S3Fn": "Incobrável",+ "fS4iqP": "Rascunho"}diff --git a/client/messages/zh.json b/client/messages/zh.jsonindex c5fc2fc4d..4535aa526 100644--- a/client/messages/zh.json+++ b/client/messages/zh.json@@ -1130,12 +1130,16 @@"rbrahO": "关闭","4cfxQk": "AppSumo 计划层级 {tier}","pIN/qH": "您目前处于 AppSumo 终身计划,每月事件上限为 {limit} 个。",- "x6GhQj": "超出事件限制",+ "ja2Zok": "升级到 Pro","IpNrN4": "您已超过每月事件限制。请升级至 Pro 计划以继续收集分析数据。",+ "6dqYnF": "",+ "P7PLVj": "",+ "/0TOL5": "",+ "FgydNe": "",+ "x6GhQj": "超出事件限制","96ejG8": "接近限制","S7U3Nx": "您正在接近每月的事件限制。考虑升级到付费计划以获得更高的额度。","wbsq7O": "使用情况",- "ja2Zok": "升级到 Pro","rd5F5r": "自定义计划","kdqPM0": "您拥有一个定制计划,每月最高可达 {limit} 次页面浏览量。","kTH3Q2": "您已超出每月的事件限制。请联系支持以获得帮助。",@@ -1162,5 +1166,10 @@"5YSWst": "脚本已安装并正常运行。","EIQFLe": "找到了脚本标签,但未执行","+x0BAO": "未检测到脚本",- "rOpS8J": "Rybbit v{latest} 现已发布(您当前使用的是 v{current})"+ "rOpS8J": "Rybbit v{latest} 现已发布(您当前使用的是 v{current})",+ "raz91s": "已付款",+ "N7QE9K": "未付款",+ "6VtPnS": "已作废",+ "T6S3Fn": "无法收回",+ "fS4iqP": "草稿"}diff --git a/client/src/app/signup/page.tsx b/client/src/app/signup/page.tsxindex e7644e6e3..aa6da64df 100644--- a/client/src/app/signup/page.tsx+++ b/client/src/app/signup/page.tsx@@ -1,7 +1,7 @@"use client";import { AuthError } from "@/components/auth/AuthError";-import { CheckoutModal } from "@/components/subscription/CheckoutModal";+import { CheckoutModal } from "@/components/subscription/components/CheckoutModal";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";import { Check } from "lucide-react";import { useExtracted } from "next-intl";diff --git a/client/src/app/subscribe/components/PricingCards.tsx b/client/src/app/subscribe/components/PricingCards.tsxindex 9a0637227..8b439fef8 100644--- a/client/src/app/subscribe/components/PricingCards.tsx+++ b/client/src/app/subscribe/components/PricingCards.tsx@@ -19,7 +19,7 @@ import {formatEventTier} from "./utils";-import { CheckoutModal } from "@/components/subscription/CheckoutModal";+import { CheckoutModal } from "@/components/subscription/components/CheckoutModal";import { useRouter } from "next/navigation";import { useQueryState } from "nuqs";diff --git a/client/src/components/subscription/AppSumoPlan.tsx b/client/src/components/subscription/AppSumoPlan.tsxindex 57d3287d8..df42fefcb 100644--- a/client/src/components/subscription/AppSumoPlan.tsx+++ b/client/src/components/subscription/AppSumoPlan.tsx@@ -1,14 +1,14 @@import { authClient } from "@/lib/auth";-import { AlertTriangle, ArrowRight } from "lucide-react";+import { ArrowRight } from "lucide-react";import { useExtracted } from "next-intl";import { useRouter } from "next/navigation";-import { DEFAULT_EVENT_LIMIT } from "../../lib/subscription/constants";import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";-import { Alert, AlertDescription, AlertTitle } from "../ui/alert";import { Button } from "../ui/button";-import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "../ui/card";-import { Progress } from "../ui/progress";import { UsageChart } from "../UsageChart";+import { PlanCard } from "./components/PlanCard";+import { UsageLimitAlerts } from "./components/UsageLimitAlerts";+import { UsageProgressBar } from "./components/UsageProgressBar";+import { useUsageStats } from "./components/useUsageStats";export function AppSumoPlan() {const t = useExtracted();@@ -16,74 +16,33 @@ export function AppSumoPlan() {const { data: activeOrg } = authClient.useActiveOrganization();const router = useRouter();- // Get the active organization IDconst organizationId = activeOrg?.id;+ const { currentUsage, limit, percentageUsed, isNearLimit, isLimitExceeded } = useUsageStats(subscription);if (!subscription) return null;- const currentUsage = subscription?.monthlyEventCount || 0;- const limit = subscription?.eventLimit || DEFAULT_EVENT_LIMIT;-- // Calculate percentage of limit used- const percentageUsed = Math.min((currentUsage / limit) * 100, 100);- const isNearLimit = percentageUsed > 80;- const isLimitExceeded = currentUsage >= limit;-return (- <div className="space-y-6">- <Card>- <CardHeader>- <CardTitle className="flex items-center">{t("AppSumo Plan Tier {tier}", { tier: subscription.planName.split("-")[1] })}</CardTitle>- <CardDescription>- {t("You are on the AppSumo lifetime plan with up to {limit} events per month.", { limit: subscription?.eventLimit.toLocaleString() })}- </CardDescription>- </CardHeader>- <CardContent>- <div className="space-y-6">- {isLimitExceeded ? (- <Alert className="bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800">- <AlertTriangle className="h-4 w-4 text-red-500 dark:text-red-400" />- <AlertTitle>{t("Event Limit Exceeded")}</AlertTitle>- <AlertDescription>- {t("You have exceeded your monthly event limit. Please upgrade to a Pro plan to continue collecting analytics.")}- </AlertDescription>- </Alert>- ) : (- isNearLimit && (- <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>{t("Approaching Limit")}</AlertTitle>- <AlertDescription>- {t("You are approaching your monthly event limit. Consider upgrading to a paid plan for higher limits.")}- </AlertDescription>- </Alert>- )- )}-- <div className="space-y-2">- <h3 className="font-medium mb-2">{t("Usage")}</h3>- <div className="space-y-4">- <div>- <div className="flex justify-between mb-1">- <span className="text-sm">{t("Events")}</span>- <span className="text-sm">- {currentUsage.toLocaleString()} / {limit.toLocaleString()}- </span>- </div>- <Progress value={percentageUsed} className={isNearLimit ? "bg-amber-100 dark:bg-amber-900" : ""} />- </div>- </div>- </div>-- {organizationId && <UsageChart organizationId={organizationId} />}- </div>- </CardContent>- <CardFooter>- <Button onClick={() => router.push("/subscribe")} variant={"success"}>- {t("Upgrade To Pro")} <ArrowRight className="ml-2 h-4 w-4" />- </Button>- </CardFooter>- </Card>- </div>+ <PlanCard+ title={t("AppSumo Plan Tier {tier}", { tier: subscription.planName.split("-")[1] })}+ description={t("You are on the AppSumo lifetime plan with up to {limit} events per month.", { limit: subscription?.eventLimit.toLocaleString() })}+ footer={+ <Button onClick={() => router.push("/subscribe")} variant={"success"}>+ {t("Upgrade To Pro")} <ArrowRight className="ml-2 h-4 w-4" />+ </Button>+ }+ >+ <UsageLimitAlerts+ isLimitExceeded={isLimitExceeded}+ isNearLimit={isNearLimit}+ exceededMessage={t("You have exceeded your monthly event limit. Please upgrade to a Pro plan to continue collecting analytics.")}+ />+ <UsageProgressBar+ currentUsage={currentUsage}+ limit={limit}+ percentageUsed={percentageUsed}+ isNearLimit={isNearLimit}+ />+ {organizationId && <UsageChart organizationId={organizationId} />}+ </PlanCard>);}diff --git a/client/src/components/subscription/CustomPlan.tsx b/client/src/components/subscription/CustomPlan.tsxindex dcce7fcb6..db63d0730 100644--- a/client/src/components/subscription/CustomPlan.tsx+++ b/client/src/components/subscription/CustomPlan.tsx@@ -1,12 +1,12 @@import { authClient } from "@/lib/auth";-import { AlertTriangle, Sparkles } from "lucide-react";+import { Sparkles } from "lucide-react";import { useExtracted } from "next-intl";-import { DEFAULT_EVENT_LIMIT } from "../../lib/subscription/constants";import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";-import { Alert, AlertDescription, AlertTitle } from "../ui/alert";-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card";-import { Progress } from "../ui/progress";import { UsageChart } from "../UsageChart";+import { PlanCard } from "./components/PlanCard";+import { UsageLimitAlerts } from "./components/UsageLimitAlerts";+import { UsageProgressBar } from "./components/UsageProgressBar";+import { useUsageStats } from "./components/useUsageStats";export function CustomPlan() {const t = useExtracted();@@ -14,89 +14,52 @@ export function CustomPlan() {const { data: activeOrg } = authClient.useActiveOrganization();const organizationId = activeOrg?.id;+ const { currentUsage, limit, percentageUsed, isNearLimit, isLimitExceeded } = useUsageStats(subscription);if (!subscription) return null;- const currentUsage = subscription?.monthlyEventCount || 0;- const limit = subscription?.eventLimit || DEFAULT_EVENT_LIMIT;-- const percentageUsed = Math.min((currentUsage / limit) * 100, 100);- const isNearLimit = percentageUsed > 80;- const isLimitExceeded = currentUsage >= limit;-- const formatLimit = (value: number | null) => (value === null ? "Unlimited" : value.toLocaleString());+ const formatLimit = (value: number | null) => (value === null ? t("Unlimited") : value.toLocaleString());return (- <div className="space-y-6">- <Card>- <CardHeader>- <CardTitle className="flex items-center gap-2">- <Sparkles className="h-5 w-5" />- {t("Custom Plan")}- </CardTitle>- <CardDescription>- {t("You have a custom plan with up to {limit} pageviews per month.", {- limit: limit.toLocaleString(),- })}- </CardDescription>- </CardHeader>- <CardContent>- <div className="space-y-6">- {isLimitExceeded ? (- <Alert className="bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800">- <AlertTriangle className="h-4 w-4 text-red-500 dark:text-red-400" />- <AlertTitle>{t("Event Limit Exceeded")}</AlertTitle>- <AlertDescription>- {t("You have exceeded your monthly event limit. Please contact support for assistance.")}- </AlertDescription>- </Alert>- ) : (- isNearLimit && (- <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>{t("Approaching Limit")}</AlertTitle>- <AlertDescription>- {t(- "You are approaching your monthly event limit. Please contact support if you need more capacity."- )}- </AlertDescription>- </Alert>- )- )}-- <div className="space-y-2">- <h3 className="font-medium mb-2">{t("Usage")}</h3>- <div className="space-y-4">- <div>- <div className="flex justify-between mb-1">- <span className="text-sm">{t("Events")}</span>- <span className="text-sm">- {currentUsage.toLocaleString()} / {limit.toLocaleString()}- </span>- </div>- <Progress value={percentageUsed} className={isNearLimit ? "bg-amber-100 dark:bg-amber-900" : ""} />- </div>- </div>- </div>+ <PlanCard+ title={+ <>+ <Sparkles className="h-5 w-5" />+ {t("Custom Plan")}+ </>+ }+ description={t("You have a custom plan with up to {limit} pageviews per month.", {+ limit: limit.toLocaleString(),+ })}+ >+ <UsageLimitAlerts+ isLimitExceeded={isLimitExceeded}+ isNearLimit={isNearLimit}+ exceededMessage={t("You have exceeded your monthly event limit. Please contact support for assistance.")}+ nearLimitMessage={t("You are approaching your monthly event limit. Please contact support if you need more capacity.")}+ />+ <UsageProgressBar+ currentUsage={currentUsage}+ limit={limit}+ percentageUsed={percentageUsed}+ isNearLimit={isNearLimit}+ />- <div className="space-y-2">- <h3 className="font-medium mb-2">{t("Plan Limits")}</h3>- <div className="grid grid-cols-2 gap-4">- <div className="rounded-lg border p-3">- <div className="text-sm text-muted-foreground">{t("Websites")}</div>- <div className="text-lg font-semibold">{formatLimit(subscription.siteLimit)}</div>- </div>- <div className="rounded-lg border p-3">- <div className="text-sm text-muted-foreground">{t("Team Members")}</div>- <div className="text-lg font-semibold">{formatLimit(subscription.memberLimit)}</div>- </div>- </div>- </div>-- {organizationId && <UsageChart organizationId={organizationId} />}+ <div className="space-y-2">+ <h3 className="font-medium mb-2">{t("Plan Limits")}</h3>+ <div className="grid grid-cols-2 gap-4">+ <div className="rounded-lg border p-3">+ <div className="text-sm text-muted-foreground">{t("Websites")}</div>+ <div className="text-lg font-semibold">{formatLimit(subscription.siteLimit)}</div>+ </div>+ <div className="rounded-lg border p-3">+ <div className="text-sm text-muted-foreground">{t("Team Members")}</div>+ <div className="text-lg font-semibold">{formatLimit(subscription.memberLimit)}</div></div>- </CardContent>- </Card>- </div>+ </div>+ </div>++ {organizationId && <UsageChart organizationId={organizationId} />}+ </PlanCard>);}diff --git a/client/src/components/subscription/ExpiredTrialPlan.tsx b/client/src/components/subscription/ExpiredTrialPlan.tsxindex 756ae0cd0..3618cde86 100644--- a/client/src/components/subscription/ExpiredTrialPlan.tsx+++ b/client/src/components/subscription/ExpiredTrialPlan.tsx@@ -3,7 +3,7 @@ import { useExtracted } from "next-intl";import { useRouter } from "next/navigation";import { Alert, AlertDescription, AlertTitle } from "../ui/alert";import { Button } from "../ui/button";-import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "../ui/card";+import { PlanCard } from "./components/PlanCard";interface ExpiredTrialPlanProps {message?: string;@@ -16,29 +16,20 @@ export function ExpiredTrialPlan({ message }: ExpiredTrialPlanProps) {const defaultMessage = t("Your 14-day free trial has ended. You need to subscribe to continue tracking visits again.");return (- <div className="space-y-6">- <Card>- <CardHeader>- <CardTitle>{t("Trial Expired")}</CardTitle>- <CardDescription>- {t("Your free trial has expired. Subscribe to a plan to continue tracking visits again.")}- </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>{t("Subscription Required")}</AlertTitle>- <AlertDescription>{message || defaultMessage}</AlertDescription>- </Alert>- </div>- </CardContent>- <CardFooter>- <Button onClick={() => router.push("/subscribe")} variant={"success"}>- {t("Subscribe Now")} <ArrowRight className="ml-2 h-4 w-4" />- </Button>- </CardFooter>- </Card>- </div>+ <PlanCard+ title={t("Trial Expired")}+ description={t("Your free trial has expired. Subscribe to a plan to continue tracking visits again.")}+ footer={+ <Button onClick={() => router.push("/subscribe")} variant={"success"}>+ {t("Subscribe Now")} <ArrowRight className="ml-2 h-4 w-4" />+ </Button>+ }+ >+ <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>{t("Subscription Required")}</AlertTitle>+ <AlertDescription>{message || defaultMessage}</AlertDescription>+ </Alert>+ </PlanCard>);}diff --git a/client/src/components/subscription/FreePlan.tsx b/client/src/components/subscription/FreePlan.tsxindex 449233e4d..efb5a6bb4 100644--- a/client/src/components/subscription/FreePlan.tsx+++ b/client/src/components/subscription/FreePlan.tsx@@ -1,14 +1,15 @@import { authClient } from "@/lib/auth";-import { AlertTriangle, ArrowRight } from "lucide-react";+import { ArrowRight } from "lucide-react";import { useExtracted } from "next-intl";import { useRouter } from "next/navigation";import { DEFAULT_EVENT_LIMIT } from "../../lib/subscription/constants";import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";-import { Alert, AlertDescription, AlertTitle } from "../ui/alert";import { Button } from "../ui/button";-import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "../ui/card";-import { Progress } from "../ui/progress";import { UsageChart } from "../UsageChart";+import { PlanCard } from "./components/PlanCard";+import { UsageLimitAlerts } from "./components/UsageLimitAlerts";+import { UsageProgressBar } from "./components/UsageProgressBar";+import { useUsageStats } from "./components/useUsageStats";export function FreePlan() {const t = useExtracted();@@ -16,74 +17,33 @@ export function FreePlan() {const { data: activeOrg } = authClient.useActiveOrganization();const router = useRouter();- // Get the active organization IDconst organizationId = activeOrg?.id;+ const { currentUsage, limit, percentageUsed, isNearLimit, isLimitExceeded } = useUsageStats(subscription);if (!subscription) return null;- const currentUsage = subscription?.monthlyEventCount || 0;- const limit = subscription?.eventLimit || DEFAULT_EVENT_LIMIT;-- // Calculate percentage of limit used- const percentageUsed = Math.min((currentUsage / limit) * 100, 100);- const isNearLimit = percentageUsed > 80;- const isLimitExceeded = currentUsage >= limit;-return (- <div className="space-y-6">- <Card>- <CardHeader>- <CardTitle className="flex items-center">{t("Free Plan")}</CardTitle>- <CardDescription>- {t("You are on the Free plan with up to {limit} pageviews per month.", { limit: DEFAULT_EVENT_LIMIT.toLocaleString() })}- </CardDescription>- </CardHeader>- <CardContent>- <div className="space-y-6">- {isLimitExceeded ? (- <Alert className="bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800">- <AlertTriangle className="h-4 w-4 text-red-500 dark:text-red-400" />- <AlertTitle>{t("Event Limit Exceeded")}</AlertTitle>- <AlertDescription>- {t("You have exceeded your monthly event limit. Please upgrade to a Pro plan to continue collecting analytics.")}- </AlertDescription>- </Alert>- ) : (- isNearLimit && (- <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>{t("Approaching Limit")}</AlertTitle>- <AlertDescription>- {t("You are approaching your monthly event limit. Consider upgrading to a paid plan for higher limits.")}- </AlertDescription>- </Alert>- )- )}-- <div className="space-y-2">- <h3 className="font-medium mb-2">{t("Usage")}</h3>- <div className="space-y-4">- <div>- <div className="flex justify-between mb-1">- <span className="text-sm">{t("Events")}</span>- <span className="text-sm">- {currentUsage.toLocaleString()} / {limit.toLocaleString()}- </span>- </div>- <Progress value={percentageUsed} className={isNearLimit ? "bg-amber-100 dark:bg-amber-900" : ""} />- </div>- </div>- </div>-- {organizationId && <UsageChart organizationId={organizationId} />}- </div>- </CardContent>- <CardFooter>- <Button onClick={() => router.push("/subscribe")} variant={"success"}>- {t("Upgrade To Pro")} <ArrowRight className="ml-2 h-4 w-4" />- </Button>- </CardFooter>- </Card>- </div>+ <PlanCard+ title={t("Free Plan")}+ description={t("You are on the Free plan with up to {limit} pageviews per month.", { limit: DEFAULT_EVENT_LIMIT.toLocaleString() })}+ footer={+ <Button onClick={() => router.push("/subscribe")} variant={"success"}>+ {t("Upgrade To Pro")} <ArrowRight className="ml-2 h-4 w-4" />+ </Button>+ }+ >+ <UsageLimitAlerts+ isLimitExceeded={isLimitExceeded}+ isNearLimit={isNearLimit}+ exceededMessage={t("You have exceeded your monthly event limit. Please upgrade to a Pro plan to continue collecting analytics.")}+ />+ <UsageProgressBar+ currentUsage={currentUsage}+ limit={limit}+ percentageUsed={percentageUsed}+ isNearLimit={isNearLimit}+ />+ {organizationId && <UsageChart organizationId={organizationId} />}+ </PlanCard>);}diff --git a/client/src/components/subscription/OverridePlan.tsx b/client/src/components/subscription/OverridePlan.tsxindex a46c23f6f..de24f582c 100644--- a/client/src/components/subscription/OverridePlan.tsx+++ b/client/src/components/subscription/OverridePlan.tsx@@ -1,13 +1,13 @@import { authClient } from "@/lib/auth";-import { AlertTriangle, Shield } from "lucide-react";+import { Shield } from "lucide-react";import { useExtracted } from "next-intl";-import { DEFAULT_EVENT_LIMIT } from "../../lib/subscription/constants";import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";-import { Alert, AlertDescription, AlertTitle } from "../ui/alert";-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card";-import { Progress } from "../ui/progress";import { UsageChart } from "../UsageChart";import { getPlanType } from "../../lib/stripe";+import { PlanCard } from "./components/PlanCard";+import { UsageLimitAlerts } from "./components/UsageLimitAlerts";+import { UsageProgressBar } from "./components/UsageProgressBar";+import { useUsageStats } from "./components/useUsageStats";export function OverridePlan() {const t = useExtracted();@@ -15,16 +15,10 @@ export function OverridePlan() {const { data: activeOrg } = authClient.useActiveOrganization();const organizationId = activeOrg?.id;+ const { currentUsage, limit, percentageUsed, isNearLimit, isLimitExceeded } = useUsageStats(subscription);if (!subscription) return null;- const currentUsage = subscription?.monthlyEventCount || 0;- const limit = subscription?.eventLimit || DEFAULT_EVENT_LIMIT;-- const percentageUsed = Math.min((currentUsage / limit) * 100, 100);- const isNearLimit = percentageUsed > 80;- const isLimitExceeded = currentUsage >= limit;-const formatPlanName = (name: string) => {const eventMatch = name.match(/(\d+)(k|m)/i);if (!eventMatch) return name;@@ -37,58 +31,28 @@ export function OverridePlan() {};return (- <div className="space-y-6">- <Card>- <CardHeader>- <CardTitle className="flex items-center gap-2">- <Shield className="h-5 w-5" />- {t("{plan} Plan", { plan: formatPlanName(subscription.planName) })}- </CardTitle>- <CardDescription>- {t("You have a custom plan with up to {limit} pageviews per month.", { limit: subscription?.eventLimit.toLocaleString() })}- </CardDescription>- </CardHeader>- <CardContent>- <div className="space-y-6">- {isLimitExceeded ? (- <Alert className="bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800">- <AlertTriangle className="h-4 w-4 text-red-500 dark:text-red-400" />- <AlertTitle>{t("Event Limit Exceeded")}</AlertTitle>- <AlertDescription>- {t("You have exceeded your monthly event limit. Please contact support for assistance.")}- </AlertDescription>- </Alert>- ) : (- isNearLimit && (- <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>{t("Approaching Limit")}</AlertTitle>- <AlertDescription>- {t("You are approaching your monthly event limit. Please contact support if you need more capacity.")}- </AlertDescription>- </Alert>- )- )}-- <div className="space-y-2">- <h3 className="font-medium mb-2">{t("Usage")}</h3>- <div className="space-y-4">- <div>- <div className="flex justify-between mb-1">- <span className="text-sm">{t("Events")}</span>- <span className="text-sm">- {currentUsage.toLocaleString()} / {limit.toLocaleString()}- </span>- </div>- <Progress value={percentageUsed} className={isNearLimit ? "bg-amber-100 dark:bg-amber-900" : ""} />- </div>- </div>- </div>-- {organizationId && <UsageChart organizationId={organizationId} />}- </div>- </CardContent>- </Card>- </div>+ <PlanCard+ title={+ <>+ <Shield className="h-5 w-5" />+ {t("{plan} Plan", { plan: formatPlanName(subscription.planName) })}+ </>+ }+ description={t("You have a custom plan with up to {limit} pageviews per month.", { limit: subscription?.eventLimit.toLocaleString() })}+ >+ <UsageLimitAlerts+ isLimitExceeded={isLimitExceeded}+ isNearLimit={isNearLimit}+ exceededMessage={t("You have exceeded your monthly event limit. Please contact support for assistance.")}+ nearLimitMessage={t("You are approaching your monthly event limit. Please contact support if you need more capacity.")}+ />+ <UsageProgressBar+ currentUsage={currentUsage}+ limit={limit}+ percentageUsed={percentageUsed}+ isNearLimit={isNearLimit}+ />+ {organizationId && <UsageChart organizationId={organizationId} />}+ </PlanCard>);}diff --git a/client/src/components/subscription/PaidPlain/PaidPlan.tsx b/client/src/components/subscription/PaidPlain/PaidPlan.tsxindex b271b25ab..61890e897 100644--- a/client/src/components/subscription/PaidPlain/PaidPlan.tsx+++ b/client/src/components/subscription/PaidPlain/PaidPlan.tsx@@ -11,6 +11,7 @@ import { formatDate } from "../../../lib/subscription/planUtils";import { useStripeSubscription } from "../../../lib/subscription/useStripeSubscription";import { UsageChart } from "../../UsageChart";import { authClient } from "@/lib/auth";+import { InvoicesCard } from "../components/InvoicesCard";import { PlanDialog } from "./PlanDialog";export function PaidPlan() {@@ -218,6 +219,7 @@ export function PaidPlan() {</div></CardContent></Card>+ <InvoicesCard /></div>);}diff --git a/client/src/components/subscription/PaidPlain/PlanDialog.tsx b/client/src/components/subscription/PaidPlain/PlanDialog.tsxindex 56f5e7810..35daafaa3 100644--- a/client/src/components/subscription/PaidPlain/PlanDialog.tsx+++ b/client/src/components/subscription/PaidPlain/PlanDialog.tsx@@ -6,7 +6,7 @@ import { getStripePrices, STRIPE_TIERS } from "@/lib/stripe";import { usePreviewSubscriptionUpdate, useUpdateSubscription } from "@/lib/subscription/useSubscriptionMutations";import { cn } from "@/lib/utils";import { useState } from "react";-import { CheckoutModal } from "../CheckoutModal";+import { CheckoutModal } from "../components/CheckoutModal";import { PlanChangePreviewDialog } from "./PlanChangePreviewDialog";interface PlanDialogProps {diff --git a/client/src/components/subscription/CheckoutModal.tsx b/client/src/components/subscription/components/CheckoutModal.tsxsimilarity index 100%rename from client/src/components/subscription/CheckoutModal.tsxrename to client/src/components/subscription/components/CheckoutModal.tsxdiff --git a/client/src/components/subscription/components/InvoicesCard.tsx b/client/src/components/subscription/components/InvoicesCard.tsxnew file mode 100644index 000000000..81c1d38a8--- /dev/null+++ b/client/src/components/subscription/components/InvoicesCard.tsx@@ -0,0 +1,122 @@+import { authClient } from "@/lib/auth";+import { useQuery } from "@tanstack/react-query";+import { ExternalLink } from "lucide-react";+import { useExtracted, useLocale } from "next-intl";+import { authedFetch } from "../../../api/utils";+import { IS_CLOUD } from "../../../lib/const";+import { Badge } from "../../ui/badge";+import { Card, CardContent, CardHeader, CardTitle } from "../../ui/card";++interface Invoice {+ id: string;+ number: string | null;+ status: string | null;+ amountDue: number;+ amountPaid: number;+ currency: string;+ created: number;+ periodStart: number;+ periodEnd: number;+ hostedInvoiceUrl: string | null;+ invoicePdf: string | null;+}++function useInvoices() {+ const { data: activeOrg } = authClient.useActiveOrganization();++ return useQuery<Invoice[]>({+ queryKey: ["stripe-invoices", activeOrg?.id],+ queryFn: () => authedFetch<Invoice[]>(`/stripe/invoices?organizationId=${activeOrg!.id}`),+ enabled: !!activeOrg && IS_CLOUD,+ staleTime: 5 * 60 * 1000,+ });+}++function formatCurrency(amount: number, currency: string, locale: string) {+ return new Intl.NumberFormat(locale, {+ style: "currency",+ currency: currency.toUpperCase(),+ }).format(amount / 100);+}++function formatDate(timestamp: number, locale: string) {+ return new Date(timestamp * 1000).toLocaleDateString(locale, {+ year: "numeric",+ month: "short",+ day: "numeric",+ });+}++const statusVariants: Record<string, "success" | "warning" | "secondary" | "destructive"> = {+ paid: "success",+ open: "warning",+ void: "secondary",+ uncollectible: "destructive",+ draft: "secondary",+};++const statusLabels: Record<string, string> = {+ paid: "Paid",+ open: "Open",+ void: "Void",+ uncollectible: "Uncollectible",+ draft: "Draft",+};++export function InvoicesCard() {+ const t = useExtracted();+ const locale = useLocale();+ const { data: invoices, isLoading } = useInvoices();++ if (isLoading || !invoices || invoices.length === 0) {+ return null;+ }++ return (+ <Card>+ <CardHeader>+ <CardTitle>{t("Invoices")}</CardTitle>+ </CardHeader>+ <CardContent>+ <div className="overflow-x-auto">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b border-neutral-200 dark:border-neutral-800">+ <th className="text-left py-2 pr-4 font-medium text-muted-foreground">{t("Date")}</th>+ <th className="text-left py-2 pr-4 font-medium text-muted-foreground">{t("Status")}</th>+ <th className="text-right py-2 pr-4 font-medium text-muted-foreground">{t("Amount")}</th>+ <th className="text-right py-2 font-medium text-muted-foreground"></th>+ </tr>+ </thead>+ <tbody>+ {invoices.map((invoice) => (+ <tr key={invoice.id} className="border-b border-neutral-200/50 dark:border-neutral-800/50 last:border-0">+ <td className="py-2.5 pr-4">{formatDate(invoice.created, locale)}</td>+ <td className="py-2.5 pr-4">+ <Badge variant={statusVariants[invoice.status ?? ""] ?? "secondary"}>+ {t(statusLabels[invoice.status ?? ""] ?? invoice.status ?? "")}+ </Badge>+ </td>+ <td className="py-2.5 pr-4 text-right">{formatCurrency(invoice.amountPaid || invoice.amountDue, invoice.currency, locale)}</td>+ <td className="py-2.5 text-right">+ {invoice.hostedInvoiceUrl && (+ <a+ href={invoice.hostedInvoiceUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-1 text-sm transition-colors hover:underline"+ >+ {t("View")}+ <ExternalLink className="h-4 w-4" />+ </a>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/client/src/components/subscription/components/PlanCard.tsx b/client/src/components/subscription/components/PlanCard.tsxnew file mode 100644index 000000000..f29946b8f--- /dev/null+++ b/client/src/components/subscription/components/PlanCard.tsx@@ -0,0 +1,28 @@+import { ReactNode } from "react";+import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "../../ui/card";+import { InvoicesCard } from "./InvoicesCard";++interface PlanCardProps {+ title: ReactNode;+ description: ReactNode;+ children: ReactNode;+ footer?: ReactNode;+}++export function PlanCard({ title, description, children, footer }: PlanCardProps) {+ return (+ <div className="space-y-6">+ <Card>+ <CardHeader>+ <CardTitle className="flex items-center gap-2">{title}</CardTitle>+ <CardDescription>{description}</CardDescription>+ </CardHeader>+ <CardContent>+ <div className="space-y-6">{children}</div>+ </CardContent>+ {footer && <CardFooter>{footer}</CardFooter>}+ </Card>+ <InvoicesCard />+ </div>+ );+}diff --git a/client/src/components/subscription/components/UsageLimitAlerts.tsx b/client/src/components/subscription/components/UsageLimitAlerts.tsxnew file mode 100644index 000000000..247252fb0--- /dev/null+++ b/client/src/components/subscription/components/UsageLimitAlerts.tsx@@ -0,0 +1,47 @@+import { AlertTriangle } from "lucide-react";+import { useExtracted } from "next-intl";+import { Alert, AlertDescription, AlertTitle } from "../../ui/alert";++interface UsageLimitAlertsProps {+ isLimitExceeded: boolean;+ isNearLimit: boolean;+ exceededMessage?: string;+ nearLimitMessage?: string;+}++export function UsageLimitAlerts({+ isLimitExceeded,+ isNearLimit,+ exceededMessage,+ nearLimitMessage,+}: UsageLimitAlertsProps) {+ const t = useExtracted();++ if (isLimitExceeded) {+ return (+ <Alert className="bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800">+ <AlertTriangle className="h-4 w-4 text-red-500 dark:text-red-400" />+ <AlertTitle>{t("Event Limit Exceeded")}</AlertTitle>+ <AlertDescription>+ {exceededMessage ||+ t("You have exceeded your monthly event limit. Please upgrade to a Pro plan to continue collecting analytics.")}+ </AlertDescription>+ </Alert>+ );+ }++ if (isNearLimit) {+ return (+ <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>{t("Approaching Limit")}</AlertTitle>+ <AlertDescription>+ {nearLimitMessage ||+ t("You are approaching your monthly event limit. Consider upgrading to a paid plan for higher limits.")}+ </AlertDescription>+ </Alert>+ );+ }++ return null;+}diff --git a/client/src/components/subscription/components/UsageProgressBar.tsx b/client/src/components/subscription/components/UsageProgressBar.tsxnew file mode 100644index 000000000..785d9e43e--- /dev/null+++ b/client/src/components/subscription/components/UsageProgressBar.tsx@@ -0,0 +1,30 @@+import { useExtracted } from "next-intl";+import { Progress } from "../../ui/progress";++interface UsageProgressBarProps {+ currentUsage: number;+ limit: number;+ percentageUsed: number;+ isNearLimit: boolean;+}++export function UsageProgressBar({ currentUsage, limit, percentageUsed, isNearLimit }: UsageProgressBarProps) {+ const t = useExtracted();++ return (+ <div className="space-y-2">+ <h3 className="font-medium mb-2">{t("Usage")}</h3>+ <div className="space-y-4">+ <div>+ <div className="flex justify-between mb-1">+ <span className="text-sm">{t("Events")}</span>+ <span className="text-sm">+ {currentUsage.toLocaleString()} / {limit.toLocaleString()}+ </span>+ </div>+ <Progress value={percentageUsed} className={isNearLimit ? "bg-amber-100 dark:bg-amber-900" : ""} />+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/subscription/components/useUsageStats.ts b/client/src/components/subscription/components/useUsageStats.tsnew file mode 100644index 000000000..c6428cdfe--- /dev/null+++ b/client/src/components/subscription/components/useUsageStats.ts@@ -0,0 +1,16 @@+import { DEFAULT_EVENT_LIMIT } from "../../../lib/subscription/constants";++interface SubscriptionData {+ monthlyEventCount?: number;+ eventLimit?: number;+}++export function useUsageStats(subscription: SubscriptionData | null | undefined) {+ const currentUsage = subscription?.monthlyEventCount || 0;+ const limit = subscription?.eventLimit || DEFAULT_EVENT_LIMIT;+ const percentageUsed = Math.min((currentUsage / limit) * 100, 100);+ const isNearLimit = percentageUsed > 80;+ const isLimitExceeded = currentUsage >= limit;++ return { currentUsage, limit, percentageUsed, isNearLimit, isLimitExceeded };+}diff --git a/server/src/api/stripe/getInvoices.ts b/server/src/api/stripe/getInvoices.tsnew file mode 100644index 000000000..f3a73f7af--- /dev/null+++ b/server/src/api/stripe/getInvoices.ts@@ -0,0 +1,80 @@+import { eq, and } from "drizzle-orm";+import { FastifyReply, FastifyRequest } from "fastify";+import { db } from "../../db/postgres/postgres.js";+import { organization, member } from "../../db/postgres/schema.js";+import { stripe } from "../../lib/stripe.js";++export async function getInvoices(+ request: FastifyRequest<{+ Querystring: {+ organizationId: string;+ };+ }>,+ reply: FastifyReply+) {+ const userId = request.user?.id;+ const { organizationId } = request.query;++ if (!userId) {+ return reply.status(401).send({ error: "Unauthorized" });+ }++ if (!organizationId) {+ return reply.status(400).send({ error: "Organization ID is required" });+ }++ if (!stripe) {+ return reply.status(500).send({ error: "Stripe is not configured" });+ }++ // Verify user is a member of this organization+ const memberResult = await db+ .select({ role: member.role })+ .from(member)+ .where(and(eq(member.userId, userId), eq(member.organizationId, organizationId)))+ .limit(1);++ if (!memberResult.length) {+ return reply.status(403).send({ error: "You do not have access to this organization" });+ }++ try {+ // Get the organization's Stripe customer ID+ const orgResult = await db+ .select({ stripeCustomerId: organization.stripeCustomerId })+ .from(organization)+ .where(eq(organization.id, organizationId))+ .limit(1);++ const org = orgResult[0];+ if (!org?.stripeCustomerId) {+ return reply.send([]);+ }++ const invoices = await stripe.invoices.list({+ customer: org.stripeCustomerId,+ limit: 100,+ });++ const formatted = invoices.data.map((invoice) => ({+ id: invoice.id,+ number: invoice.number,+ status: invoice.status,+ amountDue: invoice.amount_due,+ amountPaid: invoice.amount_paid,+ currency: invoice.currency,+ created: invoice.created,+ periodStart: invoice.period_start,+ periodEnd: invoice.period_end,+ hostedInvoiceUrl: invoice.hosted_invoice_url,+ invoicePdf: invoice.invoice_pdf,+ }));++ return reply.send(formatted);+ } catch (error: any) {+ console.error("Get Invoices Error:", error);+ return reply.status(500).send({+ error: "Failed to fetch invoices",+ });+ }+}diff --git a/server/src/api/stripe/index.ts b/server/src/api/stripe/index.tsindex 35598a92c..0c48597d1 100644--- a/server/src/api/stripe/index.ts+++ b/server/src/api/stripe/index.ts@@ -1,6 +1,7 @@// Stripeexport { createCheckoutSession } from "./createCheckoutSession.js";export { createPortalSession } from "./createPortalSession.js";+export { getInvoices } from "./getInvoices.js";export { getSubscription } from "./getSubscription.js";export { previewSubscriptionUpdate } from "./previewSubscriptionUpdate.js";export { updateSubscription } from "./updateSubscription.js";diff --git a/server/src/index.ts b/server/src/index.tsindex 153b0ac4e..997ead823 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -91,6 +91,7 @@ import {import {createCheckoutSession,createPortalSession,+ getInvoices,getSubscription,handleWebhook,previewSubscriptionUpdate,@@ -354,6 +355,7 @@ async function stripeAdminRoutes(fastify: FastifyInstance) {fastify.post("/stripe/preview-subscription-update", authOnly, previewSubscriptionUpdate);fastify.post("/stripe/update-subscription", authOnly, updateSubscription);fastify.get("/stripe/subscription", authOnly, getSubscription);+ fastify.get("/stripe/invoices", authOnly, getInvoices);fastify.post("/stripe/webhook", { config: { rawBody: true } }, handleWebhook); // Public - Stripe webhook// Admin Routes