feat(07-02): ReviewStep component and wizard completion/skip logic

- ReviewStep shows read-only grouped summary with income, items, totals
- handleComplete creates categories + template items with duplicate handling
- handleSkipSetup marks setup_completed without creating data
- Double-submit prevention via completing state
- Toast notifications for success/error/partial failure
- Query invalidation to prevent redirect loops
This commit is contained in:
2026-04-20 21:10:07 +02:00
parent 7b16ec2e9e
commit 396d342d57
2 changed files with 245 additions and 16 deletions

View File

@@ -1,12 +1,19 @@
import { useState } from "react"
import { useTranslation } from "react-i18next"
import { useNavigate } from "react-router-dom"
import { useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
import { useAuth } from "@/hooks/useAuth"
import { useWizardState } from "@/hooks/useWizardState"
import { useCategories } from "@/hooks/useCategories"
import { useTemplate } from "@/hooks/useTemplate"
import { supabase } from "@/lib/supabase"
import { PRESETS } from "@/data/presets"
import type { Profile } from "@/lib/types"
import { WizardStepper } from "@/components/setup/WizardStepper"
import { IncomeStep } from "@/components/setup/IncomeStep"
import { RecurringItemsStep } from "@/components/setup/RecurringItemsStep"
import { ReviewStep } from "@/components/setup/ReviewStep"
import { Button } from "@/components/ui/button"
import {
Card,
@@ -20,8 +27,14 @@ import { useEffect } from "react"
export default function SetupPage() {
const { t } = useTranslation()
const { user, loading: authLoading } = useAuth()
const navigate = useNavigate()
const queryClient = useQueryClient()
const [profile, setProfile] = useState<Profile | null>(null)
const [profileLoading, setProfileLoading] = useState(true)
const [completing, setCompleting] = useState(false)
const { categories, create } = useCategories()
const { createItem } = useTemplate()
useEffect(() => {
if (!user) return
@@ -38,7 +51,7 @@ export default function SetupPage() {
const userId = user?.id ?? ""
const currency = profile?.currency ?? "EUR"
const { state, setStep, setIncome, toggleItem, setItemAmount } =
const { state, setStep, setIncome, toggleItem, setItemAmount, clearState } =
useWizardState(userId)
const [incomeError, setIncomeError] = useState<string | null>(null)
@@ -89,6 +102,7 @@ export default function SetupPage() {
function handleSkipStep() {
if (state.currentStep === 1) setStep(2)
else if (state.currentStep === 2) setStep(3)
else if (state.currentStep === 3) handleSkipSetup()
}
function handleStepClick(step: 1 | 2 | 3) {
@@ -97,10 +111,98 @@ export default function SetupPage() {
}
}
async function handleComplete() {
setCompleting(true)
try {
const checkedItems = PRESETS.filter(
(p) => state.selectedItems[p.slug]?.checked
)
// 1. Determine unique category types needed
const typesNeeded = [...new Set(checkedItems.map((i) => i.type))]
// 2. Create one category per type
const categoryMap: Record<string, string> = {}
for (const type of typesNeeded) {
try {
const cat = await create.mutateAsync({
name: t(`categories.types.${type}`),
type,
})
categoryMap[type] = cat.id
} catch (e: any) {
// Unique constraint violation (23505) = category already exists, fetch it
if (e?.code === "23505" || e?.message?.includes("duplicate")) {
const existing = categories.find((c) => c.type === type)
if (existing) categoryMap[type] = existing.id
} else {
throw e
}
}
}
// 3. If categories were fetched from cache but not found, refetch
if (Object.keys(categoryMap).length < typesNeeded.length) {
await queryClient.invalidateQueries({ queryKey: ["categories"] })
}
// 4. Create template items for each checked preset
let partialFailure = false
for (const item of checkedItems) {
try {
await createItem.mutateAsync({
category_id: categoryMap[item.type],
item_tier: item.item_tier,
budgeted_amount: state.selectedItems[item.slug].amount,
})
} catch {
partialFailure = true
}
}
// 5. Mark setup complete
await supabase
.from("profiles")
.update({ setup_completed: true })
.eq("id", user!.id)
// 6. Clear wizard state
clearState()
// 7. Invalidate queries to prevent redirect loop
await queryClient.invalidateQueries({ queryKey: ["categories"] })
await queryClient.invalidateQueries({ queryKey: ["template-items"] })
// 8. Toast and redirect
if (partialFailure) {
toast.error(t("setup.toast.partialError"))
} else {
toast.success(t("setup.toast.success"))
}
navigate("/", { replace: true })
} catch {
toast.error(t("setup.toast.error"))
} finally {
setCompleting(false)
}
}
async function handleSkipSetup() {
clearState()
await supabase
.from("profiles")
.update({ setup_completed: true })
.eq("id", user!.id)
navigate("/", { replace: true })
}
return (
<div className="flex min-h-screen items-center justify-center bg-background p-4">
<div className="w-full max-w-2xl">
<WizardStepper currentStep={state.currentStep} onStepClick={handleStepClick} />
<WizardStepper
currentStep={state.currentStep}
onStepClick={handleStepClick}
/>
<Card className="w-full border border-border shadow-sm">
<CardHeader className="pb-2">
@@ -132,35 +234,42 @@ export default function SetupPage() {
)}
{state.currentStep === 3 && (
<div className="py-8 text-center text-muted-foreground">
<p>Review step coming in next plan</p>
</div>
<ReviewStep
income={state.income}
selectedItems={state.selectedItems}
currency={currency}
/>
)}
{/* Bottom navigation */}
<div className="flex justify-between items-center pt-4 border-t border-border">
<div className="flex gap-2">
{state.currentStep > 1 && (
<Button variant="ghost" onClick={handleBack}>
<Button
variant="ghost"
onClick={handleBack}
disabled={completing}
>
{t("setup.back")}
</Button>
)}
{state.currentStep < 3 && (
<Button
variant="ghost"
className="text-muted-foreground"
onClick={handleSkipStep}
>
{t("setup.skip")}
</Button>
)}
<Button
variant="ghost"
className="text-muted-foreground"
onClick={handleSkipStep}
disabled={completing}
>
{t("setup.skip")}
</Button>
</div>
<div>
{state.currentStep < 3 && (
<Button onClick={handleNext}>{t("setup.next")}</Button>
)}
{state.currentStep === 3 && (
<Button disabled>{t("setup.complete")}</Button>
<Button onClick={handleComplete} disabled={completing}>
{t("setup.complete")}
</Button>
)}
</div>
</div>
@@ -170,6 +279,8 @@ export default function SetupPage() {
<button
type="button"
className="mt-4 text-sm text-muted-foreground underline block mx-auto"
onClick={handleSkipSetup}
disabled={completing}
>
{t("setup.skipSetup")}
</button>