diff --git a/src/integrations/supabase/types.ts b/src/integrations/supabase/types.ts index 6ba0e35..cd38c86 100644 --- a/src/integrations/supabase/types.ts +++ b/src/integrations/supabase/types.ts @@ -186,6 +186,66 @@ export type Database = { } Relationships: [] } + subscriptions: { + Row: { + cancel_at_period_end: boolean + collection_method: string | null + company_name: string | null + created_at: string + current_period_end: string | null + current_period_start: string | null + customer_email: string + environment: string + id: string + kg_per_week: number | null + monthly_amount: number | null + price_id: string | null + status: string + stripe_customer_id: string + stripe_subscription_id: string + updated_at: string + user_id: string | null + } + Insert: { + cancel_at_period_end?: boolean + collection_method?: string | null + company_name?: string | null + created_at?: string + current_period_end?: string | null + current_period_start?: string | null + customer_email: string + environment?: string + id?: string + kg_per_week?: number | null + monthly_amount?: number | null + price_id?: string | null + status?: string + stripe_customer_id: string + stripe_subscription_id: string + updated_at?: string + user_id?: string | null + } + Update: { + cancel_at_period_end?: boolean + collection_method?: string | null + company_name?: string | null + created_at?: string + current_period_end?: string | null + current_period_start?: string | null + customer_email?: string + environment?: string + id?: string + kg_per_week?: number | null + monthly_amount?: number | null + price_id?: string | null + status?: string + stripe_customer_id?: string + stripe_subscription_id?: string + updated_at?: string + user_id?: string | null + } + Relationships: [] + } user_roles: { Row: { created_at: string @@ -212,6 +272,10 @@ export type Database = { [_ in never]: never } Functions: { + has_active_kaka_subscription: { + Args: { user_uuid: string } + Returns: boolean + } has_role: { Args: { _role: Database["public"]["Enums"]["app_role"] diff --git a/src/pages/Account.tsx b/src/pages/Account.tsx index 054aae1..08dfcbf 100644 --- a/src/pages/Account.tsx +++ b/src/pages/Account.tsx @@ -7,8 +7,9 @@ import { Label } from "@/components/ui/label"; import { useAuth } from "@/hooks/useAuth"; import { useToast } from "@/hooks/use-toast"; import { supabase } from "@/integrations/supabase/client"; +import { getStripeEnvironment, hasPaymentsConfigured } from "@/lib/stripe"; import Header from "@/components/Header"; -import { Save, Package } from "lucide-react"; +import { Save, Package, ExternalLink } from "lucide-react"; // Validate Stockholm postal codes (100 00 - 199 99) @@ -53,6 +54,16 @@ const getPostalCodeError = (postalCode: string) => { return null; }; +interface SubscriptionRow { + id: string; + status: string; + kg_per_week: number | null; + monthly_amount: number | null; + current_period_end: string | null; + cancel_at_period_end: boolean; + collection_method: string | null; +} + const Account = () => { const [profile, setProfile] = useState({ company_name: "", @@ -68,6 +79,8 @@ const Account = () => { }); const [isLoading, setIsLoading] = useState(true); const [isSaving, setIsSaving] = useState(false); + const [subscription, setSubscription] = useState(null); + const [openingPortal, setOpeningPortal] = useState(false); const { user, loading: authLoading, signOut } = useAuth(); const { toast } = useToast(); const navigate = useNavigate(); @@ -87,9 +100,57 @@ const Account = () => { if (user) { fetchProfile(); + fetchSubscription(); } }, [user, authLoading, navigate]); + const fetchSubscription = async () => { + if (!user) return; + try { + const env = hasPaymentsConfigured() ? getStripeEnvironment() : "sandbox"; + const { data } = await supabase + .from("subscriptions") + .select("id, status, kg_per_week, monthly_amount, current_period_end, cancel_at_period_end, collection_method") + .eq("user_id", user.id) + .eq("environment", env) + .order("created_at", { ascending: false }) + .limit(1) + .maybeSingle(); + setSubscription((data as SubscriptionRow | null) ?? null); + } catch (e) { + console.error("fetchSubscription error:", e); + } + }; + + const handleManageSubscription = async () => { + if (!hasPaymentsConfigured()) { + toast({ title: "Betalningar inte konfigurerade", variant: "destructive" }); + return; + } + setOpeningPortal(true); + try { + const { data, error } = await supabase.functions.invoke("create-portal-session", { + body: { + return_url: `${window.location.origin}/account`, + environment: getStripeEnvironment(), + }, + }); + if (error) throw error; + if ((data as any)?.error) throw new Error((data as any).error); + const url = (data as any)?.url; + if (!url) throw new Error("Ingen portal-URL mottagen"); + window.open(url, "_blank", "noopener,noreferrer"); + } catch (e: any) { + toast({ + title: "Kunde inte öppna kundportalen", + description: e?.message ?? String(e), + variant: "destructive", + }); + } finally { + setOpeningPortal(false); + } + }; + const fetchProfile = async () => { try { const { data, error } = await supabase @@ -302,26 +363,90 @@ const Account = () => {

Mitt abonnemang

-
-

- Du har för närvarande inget aktivt abonnemang. -

- -
+ {subscription ? ( +
+
+
+
+ Ditt abonnemang +
+
+ {subscription.kg_per_week ?? "—"} kg / vecka +
+ {subscription.monthly_amount && ( +
+ {Math.round(subscription.monthly_amount * 1.25).toLocaleString("sv-SE")} kr/mån ink moms + {" · "} + {subscription.collection_method === "send_invoice" ? "Faktura" : "Kort"} +
+ )} +
+ + {subscription.cancel_at_period_end + ? "Avslutas vid periodens slut" + : subscription.status === "active" + ? "Aktiv" + : subscription.status === "trialing" + ? "Provperiod" + : subscription.status === "past_due" + ? "Obetald – Stripe försöker igen" + : subscription.status === "canceled" + ? "Avslutad" + : subscription.status} + +
+ + {subscription.current_period_end && ( +

+ {subscription.cancel_at_period_end || subscription.status === "canceled" + ? "Sista leveransperiod till: " + : "Nästa förnyelse: "} + {new Date(subscription.current_period_end).toLocaleDateString("sv-SE")} +

+ )} + + +

+ Ändra kort, ladda ner fakturor eller säg upp — tillgång kvar till periodens slut. +

+
+ ) : ( +
+

+ Du har för närvarande inget aktivt abonnemang. +

+ +
+ )}