Co-authored-by: domfelipe <53182096+domfelipe@users.noreply.github.com>
This commit is contained in:
gpt-engineer-app[bot] 2026-04-17 17:02:12 +00:00
parent 0eb8689a27
commit fa8bee0e36
7 changed files with 271 additions and 0 deletions

34
src/hooks/use-auth.ts Normal file
View file

@ -0,0 +1,34 @@
"use client";
import { useEffect, useState } from "react";
import type { Session, User } from "@supabase/supabase-js";
import { supabase } from "@/integrations/supabase/client";
interface AuthState {
user: User | null;
session: Session | null;
loading: boolean;
}
export function useAuth(): AuthState {
const [state, setState] = useState<AuthState>({
user: null,
session: null,
loading: true,
});
useEffect(() => {
// CRITICAL: subscribe BEFORE getSession (avoid missed events)
const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
setState({ user: session?.user ?? null, session, loading: false });
});
supabase.auth.getSession().then(({ data: { session } }) => {
setState({ user: session?.user ?? null, session, loading: false });
});
return () => subscription.unsubscribe();
}, []);
return state;
}

68
src/hooks/use-profile.ts Normal file
View file

@ -0,0 +1,68 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "./use-auth";
export interface Profile {
id: string;
full_name: string;
company_name: string | null;
cpf_cnpj: string | null;
phone: string | null;
avatar_url: string | null;
stripe_customer_id: string | null;
onboarding_completed: boolean;
}
export function useProfile() {
const { user } = useAuth();
return useQuery({
queryKey: ["profile", user?.id],
enabled: !!user,
queryFn: async (): Promise<Profile | null> => {
if (!user) return null;
const { data, error } = await supabase
.from("profiles")
.select("*")
.eq("id", user.id)
.maybeSingle();
if (error) throw error;
return data as Profile | null;
},
});
}
export interface SubscriptionRow {
id: string;
user_id: string;
plan_id: string | null;
stripe_subscription_id: string | null;
status: "active" | "trialing" | "past_due" | "canceled" | "incomplete" | "incomplete_expired" | "unpaid";
billing_cycle: "monthly" | "yearly";
current_period_start: string | null;
current_period_end: string | null;
cancel_at_period_end: boolean;
}
export function useSubscription() {
const { user } = useAuth();
return useQuery({
queryKey: ["subscription", user?.id],
enabled: !!user,
queryFn: async (): Promise<SubscriptionRow | null> => {
if (!user) return null;
const { data, error } = await supabase
.from("subscriptions")
.select("*")
.eq("user_id", user.id)
.order("created_at", { ascending: false })
.limit(1)
.maybeSingle();
if (error) throw error;
return data as SubscriptionRow | null;
},
});
}