feat: self-serve signup Phase 2 (frontend cutover) (#162)
Some checks failed
CI / e2e (push) Has been cancelled
CI / frontend (push) Has been cancelled
CI / backend (push) Has been cancelled
Mirror to GitHub / mirror (push) Has been cancelled

Co-authored-by: Michael Chihlas <michael@resolutionflow.com>
Co-committed-by: Michael Chihlas <michael@resolutionflow.com>
This commit was merged in pull request #162.
This commit is contained in:
2026-05-07 18:42:20 +00:00
committed by chihlasm
parent f918b766b0
commit f1be3abcc5
123 changed files with 11563 additions and 559 deletions

View File

@@ -0,0 +1,56 @@
import type { ReactNode } from 'react'
import { useAuthStore } from '@/store/authStore'
import { EmailVerificationWall } from './EmailVerificationWall'
interface EmailVerificationGateProps {
children: ReactNode
/**
* Override the grace period (in days). Day `gracePeriodDays + 1` and beyond
* trigger the wall. Defaults to 6 — the spec says Day 16 unverified renders
* children and Day 7+ renders the wall.
*/
gracePeriodDays?: number
}
const MS_PER_DAY = 24 * 60 * 60 * 1000
/** Whole days elapsed between two ISO timestamps (floored). */
function daysSince(iso: string, now: number = Date.now()): number {
const created = Date.parse(iso)
if (Number.isNaN(created)) {
// Defensive: bad timestamp — treat as just-signed-up so we don't
// accidentally lock anyone out.
return 0
}
return Math.floor((now - created) / MS_PER_DAY)
}
/**
* Wraps protected content. While the current user is past the grace period
* without having verified their email, renders `<EmailVerificationWall />`
* instead of children.
*
* Behavior:
* - No user (signed out): renders children (let route guards handle auth).
* - User has `email_verified_at`: renders children.
* - Day 16 unverified: renders children (banner is shown elsewhere).
* - Day 7+ unverified: renders the wall.
*/
export function EmailVerificationGate({
children,
gracePeriodDays = 6,
}: EmailVerificationGateProps) {
const user = useAuthStore((s) => s.user)
if (!user) return <>{children}</>
if (user.email_verified_at) return <>{children}</>
const elapsed = daysSince(user.created_at)
if (elapsed > gracePeriodDays) {
return <EmailVerificationWall />
}
return <>{children}</>
}
export default EmailVerificationGate

View File

@@ -0,0 +1,90 @@
import { useState } from 'react'
import { Loader2, MailCheck } from 'lucide-react'
import { authApi } from '@/api/auth'
import { useAuthStore } from '@/store/authStore'
import { toast } from '@/lib/toast'
import { cn } from '@/lib/utils'
interface EmailVerificationWallProps {
className?: string
}
/**
* Hard wall shown after the email-verification grace period expires.
*
* Minimal v1 — Task 37 will refine copy, layout, and add the
* `/verify-email?token=...` route handling. Until then this gives
* Day 7+ unverified users a way to re-send the verification email
* or sign out.
*/
export function EmailVerificationWall({ className }: EmailVerificationWallProps) {
const user = useAuthStore((s) => s.user)
const logout = useAuthStore((s) => s.logout)
const [isSending, setIsSending] = useState(false)
const handleResend = async () => {
setIsSending(true)
try {
await authApi.sendVerificationEmail()
toast.success('Verification email sent')
} catch {
toast.error('Failed to send verification email')
} finally {
setIsSending(false)
}
}
const handleLogout = async () => {
try {
await logout()
} catch {
// logout swallows API errors internally
}
}
return (
<div
className={cn(
'flex min-h-[60vh] items-center justify-center px-4 py-12',
className,
)}
data-testid="email-verification-wall"
>
<div className="w-full max-w-md rounded-lg border border-default bg-card p-6 text-center">
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full border border-default bg-elevated text-muted-foreground">
<MailCheck className="h-5 w-5" aria-hidden="true" />
</div>
<h2 className="text-lg font-semibold text-heading">
Verify your email to continue
</h2>
<p className="mt-2 text-sm text-muted-foreground">
{user?.email
? `We sent a verification link to ${user.email}. Click it to unlock your account.`
: 'Check your inbox for the verification link we sent when you signed up.'}
</p>
<div className="mt-6 flex flex-col gap-2">
<button
type="button"
onClick={handleResend}
disabled={isSending}
data-testid="resend-button"
className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50"
>
{isSending && <Loader2 className="h-4 w-4 animate-spin" />}
Resend verification email
</button>
<button
type="button"
onClick={handleLogout}
data-testid="sign-out-button"
className="rounded-md border border-default bg-elevated px-4 py-2 text-sm font-medium text-primary transition-colors hover:bg-white/[0.06]"
>
Sign out
</button>
</div>
</div>
</div>
)
}
export default EmailVerificationWall

View File

@@ -0,0 +1,42 @@
import type { ReactNode } from 'react'
import { useFeature } from '@/hooks/useFeature'
import { UpgradePrompt } from './UpgradePrompt'
interface FeatureGateProps {
/** Feature flag key (e.g. `psa_integration`). Must match a backend `feature_flags.flag_key`. */
feature: string
/**
* Rendered when the feature is enabled for the current account.
*/
children: ReactNode
/**
* Rendered when the feature is disabled. Defaults to `<UpgradePrompt feature={feature} />`.
* Pass `null` to render nothing.
*/
fallback?: ReactNode
}
/**
* Conditionally renders `children` based on whether `feature` is enabled
* for the current account.
*
* This is a UX affordance — the security boundary is the backend
* `require_feature` dependency. Never trust this gate for authorization.
*/
export function FeatureGate({ feature, children, fallback }: FeatureGateProps) {
const enabled = useFeature(feature)
if (enabled) {
return <>{children}</>
}
// Use explicit fallback when provided, otherwise render the standard prompt.
// `null` is a valid fallback (renders nothing).
if (fallback !== undefined) {
return <>{fallback}</>
}
return <UpgradePrompt feature={feature} />
}
export default FeatureGate

View File

@@ -0,0 +1,111 @@
import { Lock, Sparkles } from 'lucide-react'
import { Link } from 'react-router-dom'
import { cn } from '@/lib/utils'
interface UpgradePromptProps {
feature: string
className?: string
}
interface FeatureMeta {
/** Display name shown in the prompt heading. */
displayName: string
/** Plan that unlocks this feature. */
requiredPlan: string
/** Optional one-line value pitch. */
description?: string
}
/**
* Mapping from feature flag key to display metadata.
*
* v1: small inline table maintained here. If this grows, lift to
* `frontend/src/lib/featureCatalog.ts` and source from a backend endpoint.
*
* Keys must match `feature_flags.flag_key` on the backend.
*/
const FEATURE_CATALOG: Record<string, FeatureMeta> = {
psa_integration: {
displayName: 'PSA Integration',
requiredPlan: 'Pro',
description: 'Sync tickets and assets with your PSA in real time.',
},
kb_accelerator: {
displayName: 'Knowledge Base Accelerator',
requiredPlan: 'Pro',
description: 'Auto-generate troubleshooting flows from your existing KB.',
},
ai_builder: {
displayName: 'AI Builder',
requiredPlan: 'Pro',
description: 'Generate decision trees from natural-language prompts.',
},
branching_logic: {
displayName: 'Branching Logic',
requiredPlan: 'Pro',
},
custom_branding: {
displayName: 'Custom Branding',
requiredPlan: 'Pro',
},
api_access: {
displayName: 'API Access',
requiredPlan: 'Pro',
},
sso: {
displayName: 'Single Sign-On',
requiredPlan: 'Enterprise',
},
}
/** Humanize an unknown feature key for the fallback display name. */
function humanizeFeatureKey(key: string): string {
return key
.split('_')
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(' ')
}
/**
* Standardized "this feature is on Pro" affordance.
*
* Renders a locked panel with a CTA that routes to the plan-selection page.
* The actual gating is enforced server-side via `require_feature` — this is UX.
*/
export function UpgradePrompt({ feature, className }: UpgradePromptProps) {
const meta = FEATURE_CATALOG[feature]
const displayName = meta?.displayName ?? humanizeFeatureKey(feature)
const requiredPlan = meta?.requiredPlan ?? 'Pro'
const description = meta?.description
return (
<div
className={cn(
'flex flex-col items-center justify-center gap-3 rounded-lg border border-default bg-white/[0.04] px-6 py-10 text-center',
className,
)}
data-testid="upgrade-prompt"
>
<div className="flex h-10 w-10 items-center justify-center rounded-full border border-default bg-elevated text-muted-foreground">
<Lock className="h-4 w-4" aria-hidden="true" />
</div>
<div className="space-y-1">
<h3 className="text-base font-semibold text-heading">
{displayName} is available on {requiredPlan}
</h3>
{description && (
<p className="max-w-md text-sm text-muted-foreground">{description}</p>
)}
</div>
<Link
to="/account/billing/select-plan"
className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
>
<Sparkles className="h-4 w-4" aria-hidden="true" />
Upgrade to {requiredPlan}
</Link>
</div>
)
}
export default UpgradePrompt

View File

@@ -0,0 +1,123 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import { BrowserRouter } from 'react-router-dom'
import { EmailVerificationGate } from '../EmailVerificationGate'
import { useAuthStore } from '@/store/authStore'
import type { User } from '@/types'
function makeUser(overrides: Partial<User> = {}): User {
return {
id: 'user-1',
email: 'test@example.com',
name: 'Test User',
role: 'engineer',
is_super_admin: false,
is_active: true,
must_change_password: false,
account_id: 'acct-1',
account_role: 'engineer',
team_id: null,
created_at: '2026-05-01T00:00:00Z',
last_login: null,
phone: null,
job_title: null,
timezone: 'UTC',
avatar_url: null,
email_verified_at: null,
...overrides,
}
}
const FROZEN_NOW = new Date('2026-05-06T00:00:00Z')
function renderWithRouter(ui: React.ReactElement) {
return render(<BrowserRouter>{ui}</BrowserRouter>)
}
describe('EmailVerificationGate', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(FROZEN_NOW)
useAuthStore.setState({ user: null, token: null, isAuthenticated: false })
})
afterEach(() => {
vi.useRealTimers()
})
it('renders children when no user is signed in', () => {
renderWithRouter(
<EmailVerificationGate>
<div>protected</div>
</EmailVerificationGate>,
)
expect(screen.getByText('protected')).toBeInTheDocument()
})
it('renders children when user has verified email', () => {
useAuthStore.setState({
user: makeUser({ email_verified_at: '2026-04-01T00:00:00Z' }),
})
renderWithRouter(
<EmailVerificationGate>
<div>protected</div>
</EmailVerificationGate>,
)
expect(screen.getByText('protected')).toBeInTheDocument()
})
it('renders children on day 1 unverified (within grace)', () => {
// created 1 day before frozen now.
useAuthStore.setState({
user: makeUser({ created_at: '2026-05-05T00:00:00Z' }),
})
renderWithRouter(
<EmailVerificationGate>
<div>protected</div>
</EmailVerificationGate>,
)
expect(screen.getByText('protected')).toBeInTheDocument()
})
it('renders children on day 6 unverified (last day of grace)', () => {
// created 6 days before frozen now.
useAuthStore.setState({
user: makeUser({ created_at: '2026-04-30T00:00:00Z' }),
})
renderWithRouter(
<EmailVerificationGate>
<div>protected</div>
</EmailVerificationGate>,
)
expect(screen.getByText('protected')).toBeInTheDocument()
})
it('renders wall on day 7 unverified user', () => {
// created 7 days before frozen now -> elapsed=7, > grace=6 -> wall.
useAuthStore.setState({
user: makeUser({ created_at: '2026-04-29T00:00:00Z' }),
})
renderWithRouter(
<EmailVerificationGate>
<div>protected</div>
</EmailVerificationGate>,
)
expect(screen.queryByText('protected')).not.toBeInTheDocument()
expect(screen.getByTestId('email-verification-wall')).toBeInTheDocument()
expect(screen.getByText(/Verify your email to continue/i)).toBeInTheDocument()
})
it('renders wall on day 8 unverified user', () => {
// created 8 days before frozen now.
useAuthStore.setState({
user: makeUser({ created_at: '2026-04-28T00:00:00Z' }),
})
renderWithRouter(
<EmailVerificationGate>
<div>protected</div>
</EmailVerificationGate>,
)
expect(screen.queryByText('protected')).not.toBeInTheDocument()
expect(screen.getByTestId('email-verification-wall')).toBeInTheDocument()
})
})

View File

@@ -0,0 +1,67 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import { BrowserRouter } from 'react-router-dom'
import { FeatureGate } from '../FeatureGate'
import { useBillingStore } from '@/store/billingStore'
function renderWithRouter(ui: React.ReactElement) {
return render(<BrowserRouter>{ui}</BrowserRouter>)
}
describe('FeatureGate', () => {
beforeEach(() => {
useBillingStore.setState({
subscription: null,
planBilling: null,
planLimits: {},
enabledFeatures: {},
isLoading: false,
error: null,
})
})
it('renders children when flag enabled, fallback when disabled', () => {
// Disabled by default — renders default UpgradePrompt fallback.
const { unmount } = renderWithRouter(
<FeatureGate feature="psa_integration">
<div>protected content</div>
</FeatureGate>,
)
expect(screen.queryByText('protected content')).not.toBeInTheDocument()
expect(screen.getByTestId('upgrade-prompt')).toBeInTheDocument()
unmount()
// Enabled — renders children.
useBillingStore.setState({ enabledFeatures: { psa_integration: true } })
renderWithRouter(
<FeatureGate feature="psa_integration">
<div>protected content</div>
</FeatureGate>,
)
expect(screen.getByText('protected content')).toBeInTheDocument()
expect(screen.queryByTestId('upgrade-prompt')).not.toBeInTheDocument()
})
it('renders custom fallback when disabled', () => {
renderWithRouter(
<FeatureGate
feature="psa_integration"
fallback={<div>custom fallback</div>}
>
<div>protected</div>
</FeatureGate>,
)
expect(screen.getByText('custom fallback')).toBeInTheDocument()
expect(screen.queryByText('protected')).not.toBeInTheDocument()
})
it('renders nothing when fallback is null and feature disabled', () => {
const { container } = renderWithRouter(
<FeatureGate feature="psa_integration" fallback={null}>
<div>protected</div>
</FeatureGate>,
)
expect(screen.queryByText('protected')).not.toBeInTheDocument()
expect(container.textContent).toBe('')
})
})

View File

@@ -0,0 +1,30 @@
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import { BrowserRouter } from 'react-router-dom'
import { UpgradePrompt } from '../UpgradePrompt'
function renderWithRouter(ui: React.ReactElement) {
return render(<BrowserRouter>{ui}</BrowserRouter>)
}
describe('UpgradePrompt', () => {
it('renders display name and required plan from catalog', () => {
renderWithRouter(<UpgradePrompt feature="psa_integration" />)
expect(
screen.getByText(/PSA Integration is available on Pro/i),
).toBeInTheDocument()
})
it('CTA navigates to /account/billing/select-plan', () => {
renderWithRouter(<UpgradePrompt feature="psa_integration" />)
const cta = screen.getByRole('link', { name: /Upgrade to Pro/i })
expect(cta).toHaveAttribute('href', '/account/billing/select-plan')
})
it('humanizes unknown feature keys and falls back to Pro', () => {
renderWithRouter(<UpgradePrompt feature="some_new_feature" />)
expect(
screen.getByText(/Some New Feature is available on Pro/i),
).toBeInTheDocument()
})
})

View File

@@ -0,0 +1,170 @@
import { useState } from 'react'
import { Link } from 'react-router-dom'
import { ArrowRight, X } from 'lucide-react'
import { dismissOnboarding } from '@/api/onboarding'
import type { OnboardingStatus } from '@/api/onboarding'
import { useTrialBanner } from '@/hooks/useTrialBanner'
import type { TrialBannerStage } from '@/hooks/useTrialBanner'
import { useOnboardingStatus } from '@/hooks/useOnboardingStatus'
/**
* Next-step card — surfaces the single highest-priority incomplete onboarding
* item with a primary CTA. Replaces the old multi-item `OnboardingChecklist`
* widget at the top of the dashboard.
*
* `useOnboardingStatusQuery` is exported as a tiny shared hook so the parent
* page can decide whether to render the surrounding "Show all setup steps"
* toggle without duplicating the fetch.
*
* Returns `null` when:
* - status hasn't loaded yet
* - `status.dismissed` is true
* - all items are complete
*
* Priority order (first incomplete wins):
* 1. Verify your email
* 2. Set up your shop
* 3. Run your first FlowPilot session
* 4. Connect your PSA
* 5. Invite a teammate
* 6. Pick a plan (only when trial stage is warning / urgent / expired)
*/
export interface NextStepItem {
/** Stable id used in tests + analytics. */
key: string
title: string
description: string
ctaLabel: string
ctaPath: string
}
const PLAN_GATE_STAGES: ReadonlyArray<TrialBannerStage> = [
'warning',
'urgent',
'expired',
]
/**
* Pure helper — picks the highest-priority incomplete item, or `null` when
* all relevant items are done. Exported for direct unit testing.
*/
// eslint-disable-next-line react-refresh/only-export-components -- pure helper exported for focused unit tests
export function pickNextStep(
status: OnboardingStatus,
trialStage: TrialBannerStage | null,
): NextStepItem | null {
if (!status.email_verified) {
return {
key: 'verify_email',
title: 'Verify your email',
description: 'Confirm your address to keep your account active after the grace period.',
ctaLabel: 'Verify email',
ctaPath: '/verify-email',
}
}
if (!status.shop_setup_done) {
return {
key: 'shop_setup',
title: 'Set up your shop',
description: 'Tell us a bit about your team so ResolutionFlow can tailor itself.',
ctaLabel: 'Set up shop',
ctaPath: '/welcome/step-1',
}
}
if (!status.ran_session) {
return {
key: 'ran_session',
title: 'Run your first FlowPilot session',
description: 'Paste a ticket or pick a flow to see ResolutionFlow in action.',
ctaLabel: 'Start a session',
ctaPath: '/',
}
}
if (!status.connected_psa) {
return {
key: 'connected_psa',
title: 'Connect your PSA',
description: 'Sync tickets from ConnectWise, Autotask, or HaloPSA.',
ctaLabel: 'Connect PSA',
ctaPath: '/account/integrations',
}
}
if (!status.invited_teammate) {
return {
key: 'invited_teammate',
title: 'Invite a teammate',
description: 'ResolutionFlow gets stronger when your whole team is on it.',
ctaLabel: 'Invite teammate',
ctaPath: '/account',
}
}
if (trialStage && PLAN_GATE_STAGES.includes(trialStage)) {
return {
key: 'pick_plan',
title: 'Pick a plan',
description: 'Your trial is wrapping up — pick a plan to keep using ResolutionFlow.',
ctaLabel: 'Pick a plan',
ctaPath: '/account/billing/select-plan',
}
}
return null
}
export function NextStepCard() {
const status = useOnboardingStatus()
const [locallyDismissed, setLocallyDismissed] = useState(false)
const { stage } = useTrialBanner()
if (!status || status.dismissed || locallyDismissed) return null
const next = pickNextStep(status, stage)
if (!next) return null
const handleDismiss = async () => {
setLocallyDismissed(true)
try {
await dismissOnboarding()
} catch {
// Already hidden locally — best-effort persist.
}
}
return (
<div
className="card-interactive overflow-hidden p-4 fade-in"
data-testid="next-step-card"
style={{ animationDelay: '150ms' }}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<p className="font-sans text-[0.625rem] uppercase tracking-[0.12em] font-semibold text-muted-foreground">
Next step
</p>
<h3 className="mt-1 text-base font-semibold text-foreground">{next.title}</h3>
<p className="mt-1 text-sm text-muted-foreground">{next.description}</p>
</div>
<button
type="button"
onClick={handleDismiss}
aria-label="Dismiss setup prompts"
className="rounded-md p-1 text-muted-foreground hover:text-foreground hover:bg-[rgba(255,255,255,0.04)] transition-colors shrink-0"
>
<X size={16} />
</button>
</div>
<div className="mt-3">
<Link
to={next.ctaPath}
data-testid="next-step-cta"
className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground transition-colors hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1"
>
{next.ctaLabel}
<ArrowRight size={14} />
</Link>
</div>
</div>
)
}
export default NextStepCard

View File

@@ -1,160 +0,0 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Check, X, ChevronRight } from 'lucide-react'
import { cn } from '@/lib/utils'
import { getOnboardingStatus, dismissOnboarding } from '@/api/onboarding'
import type { OnboardingStatus } from '@/api/onboarding'
interface ChecklistItem {
key: keyof OnboardingStatus
label: string
path: string
}
const SOLO_ITEMS: ChecklistItem[] = [
{ key: 'ran_session', label: 'Try troubleshooting a ticket', path: '/' },
{ key: 'exported_session', label: 'Review your session notes', path: '/sessions' },
{ key: 'created_flow', label: 'Explore guided flows', path: '/trees' },
{ key: 'tried_ai_assistant', label: 'Check out the Script Builder', path: '/script-builder' },
]
const TEAM_ITEMS: ChecklistItem[] = [
{ key: 'ran_session', label: 'Try troubleshooting a ticket', path: '/' },
{ key: 'exported_session', label: 'Review your session notes', path: '/sessions' },
{ key: 'invited_teammate', label: 'Invite a team member', path: '/account' },
{ key: 'created_flow', label: 'Explore guided flows', path: '/trees' },
{ key: 'connected_psa', label: 'Connect your PSA', path: '/account/integrations' },
]
export function OnboardingChecklist() {
const navigate = useNavigate()
const [status, setStatus] = useState<OnboardingStatus | null>(null)
const [dismissed, setDismissed] = useState(false)
const [allComplete, setAllComplete] = useState(false)
useEffect(() => {
getOnboardingStatus()
.then(setStatus)
.catch(() => {
// Silently fail — don't show checklist if endpoint unavailable
})
}, [])
const items = status?.is_team_user ? TEAM_ITEMS : SOLO_ITEMS
const completedCount = status
? items.filter((item) => status[item.key]).length
: 0
const totalCount = items.length
const isAllDone = completedCount === totalCount && status !== null
useEffect(() => {
if (isAllDone) {
const timer = setTimeout(() => setAllComplete(true), 2000)
return () => clearTimeout(timer)
}
}, [isAllDone])
// Don't render if dismissed, fully complete, or not loaded yet
if (!status || status.dismissed || dismissed || allComplete) return null
const progressPercent = totalCount > 0 ? (completedCount / totalCount) * 100 : 0
const handleDismiss = async () => {
setDismissed(true)
try {
await dismissOnboarding()
} catch {
// Already hidden locally
}
}
return (
<div className="card-interactive overflow-hidden fade-in" style={{ animationDelay: '150ms' }}>
{/* Progress bar */}
<div className="h-1 w-full bg-[rgba(255,255,255,0.04)]">
<div
className="h-full bg-primary transition-all duration-500 ease-out"
style={{ width: `${progressPercent}%` }}
/>
</div>
<div className="p-4">
{/* Header */}
<div className="flex items-center justify-between mb-3">
<div>
<p className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground">
Getting Started
</p>
<p className="text-sm text-foreground mt-0.5">
{isAllDone ? (
<span className="text-accent-text font-semibold">You're all set!</span>
) : (
<span>
<span className="text-accent-text font-semibold">{completedCount}</span>
{' '}of {totalCount} complete
</span>
)}
</p>
</div>
<button
onClick={handleDismiss}
className="rounded-md p-1 text-muted-foreground hover:text-foreground hover:bg-[rgba(255,255,255,0.04)] transition-colors"
aria-label="Dismiss onboarding checklist"
>
<X size={16} />
</button>
</div>
{/* Checklist items */}
<ul className="space-y-1">
{items.map((item) => {
const done = status[item.key]
return (
<li key={item.key}>
<button
onClick={() => !done && navigate(item.path)}
disabled={done}
className={cn(
'w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors text-left',
done
? 'cursor-default'
: 'hover:bg-[rgba(255,255,255,0.04)]'
)}
>
{/* Checkbox */}
<span
className={cn(
'flex h-5 w-5 shrink-0 items-center justify-center rounded-md border transition-colors',
done
? 'bg-primary border-transparent'
: 'border-border'
)}
>
{done && <Check size={12} className="text-white" />}
</span>
{/* Label */}
<span
className={cn(
'flex-1',
done
? 'text-muted-foreground line-through'
: 'text-foreground'
)}
>
{item.label}
</span>
{/* Arrow for incomplete items */}
{!done && (
<ChevronRight size={14} className="text-muted-foreground shrink-0" />
)}
</button>
</li>
)
})}
</ul>
</div>
</div>
)
}

View File

@@ -0,0 +1,137 @@
import { Link } from 'react-router-dom'
import { Check, ChevronRight } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { OnboardingStatus } from '@/api/onboarding'
import { useTrialBanner } from '@/hooks/useTrialBanner'
import type { TrialBannerStage } from '@/hooks/useTrialBanner'
import { useOnboardingStatus } from '@/hooks/useOnboardingStatus'
/**
* Unified setup checklist — single list (no SOLO/TEAM bifurcation).
*
* Replaces the old `OnboardingChecklist` widget. Items match `NextStepCard`'s
* priority order. The "Pick a plan" item is gated on the trial stage.
*
* Surfaced behind a "Show all setup steps" toggle on the dashboard so the
* always-visible surface is just the single next-step card.
*/
interface ChecklistItem {
key: string
label: string
path: string
done: boolean
}
const PLAN_GATE_STAGES: ReadonlyArray<TrialBannerStage> = [
'warning',
'urgent',
'expired',
]
// eslint-disable-next-line react-refresh/only-export-components -- pure helper exported for focused unit tests
export function buildChecklistItems(
status: OnboardingStatus,
trialStage: TrialBannerStage | null,
): ChecklistItem[] {
const items: ChecklistItem[] = [
{
key: 'verify_email',
label: 'Verify your email',
path: '/verify-email',
done: status.email_verified,
},
{
key: 'shop_setup',
label: 'Set up your shop',
path: '/welcome/step-1',
done: status.shop_setup_done,
},
{
key: 'ran_session',
label: 'Run your first FlowPilot session',
path: '/',
done: status.ran_session,
},
{
key: 'connected_psa',
label: 'Connect your PSA',
path: '/account/integrations',
done: status.connected_psa,
},
{
key: 'invited_teammate',
label: 'Invite a teammate',
path: '/account',
done: status.invited_teammate,
},
]
if (trialStage && PLAN_GATE_STAGES.includes(trialStage)) {
items.push({
key: 'pick_plan',
label: 'Pick a plan',
path: '/account/billing/select-plan',
done: false,
})
}
return items
}
export function SetupChecklist() {
const status = useOnboardingStatus()
const { stage } = useTrialBanner()
if (!status || status.dismissed) return null
const items = buildChecklistItems(status, stage)
const completedCount = items.filter((i) => i.done).length
const totalCount = items.length
return (
<div className="card-interactive overflow-hidden" data-testid="setup-checklist">
<div className="px-4 pt-3 pb-2">
<p className="font-sans text-[0.625rem] uppercase tracking-[0.12em] font-semibold text-muted-foreground">
Setup steps · {completedCount} of {totalCount}
</p>
</div>
<ul className="px-2 pb-2 space-y-1">
{items.map((item) => (
<li key={item.key}>
{item.done ? (
<div
className="w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm cursor-default"
data-testid={`checklist-item-${item.key}`}
data-done="true"
>
<span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md border border-transparent bg-primary">
<Check size={12} className="text-white" />
</span>
<span className="flex-1 text-muted-foreground line-through">
{item.label}
</span>
</div>
) : (
<Link
to={item.path}
className={cn(
'w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors text-left',
'hover:bg-[rgba(255,255,255,0.04)]',
)}
data-testid={`checklist-item-${item.key}`}
data-done="false"
>
<span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md border border-border" />
<span className="flex-1 text-foreground">{item.label}</span>
<ChevronRight size={14} className="text-muted-foreground shrink-0" />
</Link>
)}
</li>
))}
</ul>
</div>
)
}
export default SetupChecklist

View File

@@ -0,0 +1,148 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { BrowserRouter } from 'react-router-dom'
import { NextStepCard, pickNextStep } from '../NextStepCard'
import { useBillingStore } from '@/store/billingStore'
import type { OnboardingStatus } from '@/api/onboarding'
vi.mock('@/api/onboarding', () => {
const mockGet = vi.fn()
const mockDismiss = vi.fn()
return {
getOnboardingStatus: mockGet,
dismissOnboarding: mockDismiss,
}
})
import {
getOnboardingStatus as _getOnboardingStatus,
} from '@/api/onboarding'
const getOnboardingStatus = _getOnboardingStatus as unknown as ReturnType<typeof vi.fn>
function makeStatus(overrides: Partial<OnboardingStatus> = {}): OnboardingStatus {
return {
created_flow: false,
ran_session: false,
exported_session: false,
tried_ai_assistant: false,
invited_teammate: false,
connected_psa: false,
is_team_user: false,
dismissed: false,
email_verified: false,
shop_setup_done: false,
...overrides,
}
}
function renderWithRouter(ui: React.ReactElement) {
return render(<BrowserRouter>{ui}</BrowserRouter>)
}
function setBillingComplimentary() {
// 'complimentary' status -> stage 'complimentary' (not in plan-gate set), so the
// "Pick a plan" item stays hidden — perfect default for unrelated tests.
useBillingStore.setState({
subscription: {
status: 'complimentary',
plan: 'pro',
current_period_start: '2026-05-01T00:00:00Z',
current_period_end: null,
cancel_at_period_end: false,
seat_limit: null,
has_pro_entitlement: true,
is_paid: true,
},
planBilling: null,
planLimits: {},
enabledFeatures: {},
isLoading: false,
error: null,
})
}
describe('NextStepCard', () => {
beforeEach(() => {
getOnboardingStatus.mockReset()
setBillingComplimentary()
})
it('renders Verify your email when email unverified', async () => {
getOnboardingStatus.mockResolvedValue(makeStatus({ email_verified: false }))
renderWithRouter(<NextStepCard />)
await waitFor(() => {
expect(screen.getByTestId('next-step-card')).toBeInTheDocument()
})
expect(screen.getByRole('heading', { name: /Verify your email/i })).toBeInTheDocument()
})
it('renders Set up your shop after email verified', async () => {
getOnboardingStatus.mockResolvedValue(
makeStatus({ email_verified: true, shop_setup_done: false }),
)
renderWithRouter(<NextStepCard />)
await waitFor(() => {
expect(screen.getByRole('heading', { name: /Set up your shop/i })).toBeInTheDocument()
})
})
it('renders Run your first FlowPilot session after shop setup', async () => {
getOnboardingStatus.mockResolvedValue(
makeStatus({
email_verified: true,
shop_setup_done: true,
ran_session: false,
}),
)
renderWithRouter(<NextStepCard />)
await waitFor(() => {
expect(
screen.getByRole('heading', { name: /Run your first FlowPilot session/i }),
).toBeInTheDocument()
})
})
it('hidden when all items done', async () => {
getOnboardingStatus.mockResolvedValue(
makeStatus({
email_verified: true,
shop_setup_done: true,
ran_session: true,
connected_psa: true,
invited_teammate: true,
}),
)
const { container } = renderWithRouter(<NextStepCard />)
// Resolve the awaited promise.
await waitFor(() => expect(getOnboardingStatus).toHaveBeenCalled())
expect(container.querySelector('[data-testid="next-step-card"]')).toBeNull()
})
it('hidden when onboarding_dismissed', async () => {
getOnboardingStatus.mockResolvedValue(makeStatus({ dismissed: true }))
const { container } = renderWithRouter(<NextStepCard />)
await waitFor(() => expect(getOnboardingStatus).toHaveBeenCalled())
expect(container.querySelector('[data-testid="next-step-card"]')).toBeNull()
})
it('Pick a plan item appears when trial stage is warning or later', () => {
// Direct unit-test on the pure picker — easier than coordinating both the
// billing store + the network mock + a fake clock for stage='warning'.
const allDoneExceptPlan = makeStatus({
email_verified: true,
shop_setup_done: true,
ran_session: true,
connected_psa: true,
invited_teammate: true,
})
expect(pickNextStep(allDoneExceptPlan, 'pristine')).toBeNull()
expect(pickNextStep(allDoneExceptPlan, 'paid')).toBeNull()
expect(pickNextStep(allDoneExceptPlan, 'complimentary')).toBeNull()
expect(pickNextStep(allDoneExceptPlan, 'warning')?.key).toBe('pick_plan')
expect(pickNextStep(allDoneExceptPlan, 'urgent')?.key).toBe('pick_plan')
expect(pickNextStep(allDoneExceptPlan, 'expired')?.key).toBe('pick_plan')
})
})

View File

@@ -0,0 +1,123 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { BrowserRouter } from 'react-router-dom'
import { SetupChecklist, buildChecklistItems } from '../SetupChecklist'
import { useBillingStore } from '@/store/billingStore'
import type { OnboardingStatus } from '@/api/onboarding'
vi.mock('@/api/onboarding', () => {
const mockGet = vi.fn()
return {
getOnboardingStatus: mockGet,
dismissOnboarding: vi.fn(),
}
})
import { getOnboardingStatus as _getOnboardingStatus } from '@/api/onboarding'
const getOnboardingStatus = _getOnboardingStatus as unknown as ReturnType<typeof vi.fn>
function makeStatus(overrides: Partial<OnboardingStatus> = {}): OnboardingStatus {
return {
created_flow: false,
ran_session: false,
exported_session: false,
tried_ai_assistant: false,
invited_teammate: false,
connected_psa: false,
is_team_user: false,
dismissed: false,
email_verified: false,
shop_setup_done: false,
...overrides,
}
}
function renderWithRouter(ui: React.ReactElement) {
return render(<BrowserRouter>{ui}</BrowserRouter>)
}
function setBillingComplimentary() {
useBillingStore.setState({
subscription: {
status: 'complimentary',
plan: 'pro',
current_period_start: '2026-05-01T00:00:00Z',
current_period_end: null,
cancel_at_period_end: false,
seat_limit: null,
has_pro_entitlement: true,
is_paid: true,
},
planBilling: null,
planLimits: {},
enabledFeatures: {},
isLoading: false,
error: null,
})
}
describe('SetupChecklist', () => {
beforeEach(() => {
getOnboardingStatus.mockReset()
setBillingComplimentary()
})
it('renders unified list with no SOLO/TEAM headers', async () => {
getOnboardingStatus.mockResolvedValue(makeStatus())
renderWithRouter(<SetupChecklist />)
await waitFor(() => {
expect(screen.getByTestId('setup-checklist')).toBeInTheDocument()
})
// Single unified list — no team/solo section dividers (the old component had
// separate SOLO_ITEMS / TEAM_ITEMS branches; the new one is one flat list).
expect(screen.queryByText(/^SOLO$/)).toBeNull()
expect(screen.queryByText(/^TEAM$/)).toBeNull()
expect(screen.queryByText(/Solo users/i)).toBeNull()
expect(screen.queryByText(/Team users/i)).toBeNull()
// Core items present.
expect(screen.getByText(/Verify your email/i)).toBeInTheDocument()
expect(screen.getByText(/Set up your shop/i)).toBeInTheDocument()
expect(screen.getByText(/Run your first FlowPilot session/i)).toBeInTheDocument()
expect(screen.getByText(/Connect your PSA/i)).toBeInTheDocument()
expect(screen.getByText(/Invite a teammate/i)).toBeInTheDocument()
})
it('does NOT include the stale tried_ai_assistant / Script Builder item', async () => {
getOnboardingStatus.mockResolvedValue(makeStatus())
renderWithRouter(<SetupChecklist />)
await waitFor(() => {
expect(screen.getByTestId('setup-checklist')).toBeInTheDocument()
})
expect(screen.queryByText(/Script Builder/i)).toBeNull()
expect(screen.queryByText(/AI Assistant/i)).toBeNull()
})
it('hidden when onboarding_dismissed', async () => {
getOnboardingStatus.mockResolvedValue(makeStatus({ dismissed: true }))
const { container } = renderWithRouter(<SetupChecklist />)
await waitFor(() => expect(getOnboardingStatus).toHaveBeenCalled())
expect(container.querySelector('[data-testid="setup-checklist"]')).toBeNull()
})
describe('buildChecklistItems', () => {
it('does not include "Pick a plan" when stage is pristine', () => {
const items = buildChecklistItems(makeStatus(), 'pristine')
expect(items.find((i) => i.key === 'pick_plan')).toBeUndefined()
})
it('includes "Pick a plan" when stage is warning', () => {
const items = buildChecklistItems(makeStatus(), 'warning')
expect(items.find((i) => i.key === 'pick_plan')).toBeDefined()
})
it('includes "Pick a plan" when stage is urgent or expired', () => {
expect(
buildChecklistItems(makeStatus(), 'urgent').find((i) => i.key === 'pick_plan'),
).toBeDefined()
expect(
buildChecklistItems(makeStatus(), 'expired').find((i) => i.key === 'pick_plan'),
).toBeDefined()
})
})
})

View File

@@ -4,15 +4,20 @@ import { Menu, X, LayoutGrid, Clock, AlertTriangle, GitBranch, Wand2, BarChart3,
import { useAuthStore } from '@/store/authStore'
import { usePermissions } from '@/hooks/usePermissions'
import { useUserPreferencesStore } from '@/store/userPreferencesStore'
import { useBillingPoll } from '@/hooks/useBillingPoll'
import { BrandLogo } from '@/components/common/BrandLogo'
import { TopBar } from './TopBar'
import { Sidebar } from './Sidebar'
import { EmailVerificationBanner } from './EmailVerificationBanner'
import { EmailVerificationGate } from '@/components/common/EmailVerificationGate'
import { ViewTransitionOutlet } from './ViewTransitionOutlet'
import { FeedbackWidget } from '@/components/common/FeedbackWidget'
import { cn } from '@/lib/utils'
export function AppLayout() {
// Poll /billing/state every 60s while authenticated. Hook no-ops when logged out.
useBillingPoll()
const location = useLocation()
const navigate = useNavigate()
const { user, logout } = useAuthStore()
@@ -169,7 +174,9 @@ export function AppLayout() {
{/* Main Content */}
<main className="main-content flex flex-col overflow-hidden min-h-0">
<EmailVerificationBanner />
<ViewTransitionOutlet />
<EmailVerificationGate>
<ViewTransitionOutlet />
</EmailVerificationGate>
</main>
</div>

View File

@@ -5,7 +5,39 @@ import { useAuthStore } from '@/store/authStore'
import { cn } from '@/lib/utils'
import { toast } from '@/lib/toast'
export function EmailVerificationBanner() {
const MS_PER_DAY = 24 * 60 * 60 * 1000
/**
* Whole days elapsed between an ISO timestamp and now (floored).
*
* Mirrors the helper in `EmailVerificationGate` — keep the two in sync so the
* banner hides on the same day the wall appears (Day 7+ unverified). Defensive
* on bad timestamps: treats unparseable input as "just signed up" so we never
* accidentally hide the banner on a real unverified user.
*/
function daysSince(iso: string, now: number = Date.now()): number {
const created = Date.parse(iso)
if (Number.isNaN(created)) return 0
return Math.floor((now - created) / MS_PER_DAY)
}
interface EmailVerificationBannerProps {
/**
* Override the grace period (in days). Day `gracePeriodDays + 1` and beyond
* suppress the banner — `EmailVerificationGate` shows the wall instead.
* Defaults to 6 (matches the gate).
*/
gracePeriodDays?: number
}
/**
* Top-of-dashboard bar shown to users who signed up but haven't verified their
* email yet. Hides itself once the grace period expires (the wall takes over)
* and once the user dismisses it for the session.
*/
export function EmailVerificationBanner({
gracePeriodDays = 6,
}: EmailVerificationBannerProps = {}) {
const user = useAuthStore((s) => s.user)
const [dismissed, setDismissed] = useState(false)
const [isSending, setIsSending] = useState(false)
@@ -19,6 +51,11 @@ export function EmailVerificationBanner() {
if (!user || user.email_verified_at || dismissed || !verificationEnabled) return null
// Past grace period: the wall takes over inside <EmailVerificationGate>.
// Keep the banner out of the way so we don't double-show messaging.
const elapsed = daysSince(user.created_at)
if (elapsed > gracePeriodDays) return null
const handleResend = async () => {
setIsSending(true)
try {
@@ -32,22 +69,29 @@ export function EmailVerificationBanner() {
}
return (
<div className="flex items-center gap-3 border-b border-amber-400/20 bg-amber-400/5 px-4 py-2 text-sm">
<AlertTriangle className="h-4 w-4 shrink-0 text-amber-400" />
<span className="text-amber-200">
<div
data-testid="email-verification-banner"
className="flex items-center gap-3 border-b border-warning/20 bg-warning-dim px-4 py-2 text-sm"
>
<AlertTriangle className="h-4 w-4 shrink-0 text-warning" />
<span className="text-foreground">
Your email is not verified.
</span>
<button
type="button"
onClick={handleResend}
disabled={isSending}
data-testid="banner-resend-button"
className={cn(
'text-amber-400 underline hover:text-amber-300 disabled:opacity-50'
'text-warning underline hover:opacity-80 disabled:opacity-50',
)}
>
{isSending ? <Loader2 className="inline h-3 w-3 animate-spin" /> : 'Resend verification email'}
</button>
<button
type="button"
onClick={() => setDismissed(true)}
aria-label="Dismiss"
className="ml-auto text-muted-foreground hover:text-foreground"
>
<X className="h-4 w-4" />

View File

@@ -6,6 +6,7 @@ import { usePermissions } from '@/hooks/usePermissions'
import { BrandLogo } from '@/components/common/BrandLogo'
import { CommandPalette } from './CommandPalette'
import { NotificationsPanel } from './NotificationsPanel'
import { TrialPill } from './TrialPill'
import { cn } from '@/lib/utils'
export function TopBar() {
@@ -110,6 +111,9 @@ export function TopBar() {
{/* Spacer - push actions to right */}
<div className="flex-1" />
{/* Billing-state pill (trial countdown / paid tier / past_due / etc.) */}
<TrialPill />
{/* Action buttons */}
<div className="flex items-center gap-1">
<Link

View File

@@ -0,0 +1,147 @@
import { Link } from 'react-router-dom'
import { Clock } from 'lucide-react'
import { useTrialBanner } from '@/hooks/useTrialBanner'
import { useBillingStore } from '@/store/billingStore'
import { cn } from '@/lib/utils'
/**
* Topbar billing-state pill.
*
* Reads `useTrialBanner()` to map subscription state → label + tone.
* Returns `null` when there is nothing to display (e.g. subscription not yet
* loaded). Clickable variants (expired / past_due / canceled) render as
* keyboard-focusable `<Link>`s; static variants render as `<span>`.
*
* Mobile: when the topbar is too narrow, the label collapses to a clock icon
* with a `title` tooltip carrying the full text.
*/
interface PillContent {
/** Full label shown on >= sm. */
label: string
/** Short label for mobile (sm:hidden); typically a single token / icon. */
shortLabel?: string
/** Tailwind classes applied to the pill (color tokens). */
toneClass: string
/** When set, render as a clickable Link to this route. */
href?: string
/** Extra emphasis (used by `urgent` to differentiate from `warning`). */
emphasized?: boolean
}
const BASE_CLASS =
'trial-pill inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium transition-colors whitespace-nowrap'
export function TrialPill() {
const { stage, daysRemaining } = useTrialBanner()
const planBilling = useBillingStore((s) => s.planBilling)
const content = resolveContent(stage, daysRemaining, planBilling?.display_name ?? null)
if (!content) return null
const className = cn(
BASE_CLASS,
content.toneClass,
content.emphasized && 'font-semibold',
content.href &&
'cursor-pointer hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1 focus-visible:ring-offset-bg-sidebar',
)
const inner = (
<>
<span className="hidden sm:inline">{content.label}</span>
<span className="sm:hidden inline-flex items-center" aria-hidden="true">
<Clock size={14} />
</span>
</>
)
if (content.href) {
return (
<Link
to={content.href}
className={className}
title={content.label}
data-testid="trial-pill"
>
{inner}
</Link>
)
}
return (
<span
className={className}
title={content.label}
data-testid="trial-pill"
>
{inner}
</span>
)
}
function resolveContent(
stage: ReturnType<typeof useTrialBanner>['stage'],
daysRemaining: number | null,
paidDisplayName: string | null,
): PillContent | null {
switch (stage) {
case null:
return null
case 'pristine': {
const days = daysRemaining ?? 0
return {
label: `Pro trial · ${days}d`,
toneClass: 'text-info bg-info-dim',
}
}
case 'warning': {
const days = daysRemaining ?? 0
return {
label: `Pro trial · ${days}d`,
toneClass: 'text-warning bg-warning-dim',
}
}
case 'urgent':
return {
label: 'Pro trial · today',
toneClass: 'text-warning bg-warning-dim',
emphasized: true,
}
case 'expired':
return {
label: 'Trial expired — pick a plan',
toneClass: 'text-danger bg-danger-dim',
href: '/account/billing/select-plan',
}
case 'paid':
return {
label: paidDisplayName ?? 'Pro',
toneClass: 'text-muted-foreground bg-elevated',
}
case 'complimentary':
return {
label: 'Complimentary Pro',
toneClass: 'text-accent bg-accent-dim',
}
case 'past_due':
return {
label: 'Payment failed — update card',
toneClass: 'text-warning bg-warning-dim',
href: '/account/billing',
}
case 'canceled':
return {
label: 'Reactivate',
toneClass: 'text-warning bg-warning-dim',
href: '/account/billing/select-plan',
}
default: {
const _exhaustive: never = stage
void _exhaustive
return null
}
}
}
export default TrialPill

View File

@@ -0,0 +1,123 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import { MemoryRouter, Routes, Route } from 'react-router-dom'
import { AppLayout } from '../AppLayout'
import { useAuthStore } from '@/store/authStore'
import type { User } from '@/types'
// Mock heavy/external pieces so this stays a focused integration test for the
// gate placement. We don't care that TopBar/Sidebar render real content here —
// only that the EmailVerificationGate is in the tree and gates the outlet.
vi.mock('@/hooks/useBillingPoll', () => ({
useBillingPoll: () => undefined,
}))
vi.mock('@/hooks/usePermissions', () => ({
usePermissions: () => ({ effectiveRole: 'engineer' }),
}))
vi.mock('../TopBar', () => ({
TopBar: () => <div data-testid="top-bar" />,
}))
vi.mock('../Sidebar', () => ({
Sidebar: () => <div data-testid="sidebar" />,
}))
vi.mock('../EmailVerificationBanner', () => ({
EmailVerificationBanner: () => <div data-testid="email-verification-banner-mock" />,
}))
vi.mock('@/components/common/FeedbackWidget', () => ({
FeedbackWidget: () => null,
}))
vi.mock('@/api/auth', () => ({
authApi: {
getVerificationStatus: vi.fn().mockResolvedValue({ enabled: true }),
sendVerificationEmail: vi.fn().mockResolvedValue(undefined),
},
}))
vi.mock('@/lib/toast', () => ({
toast: { success: vi.fn(), error: vi.fn() },
}))
function makeUser(overrides: Partial<User> = {}): User {
return {
id: 'user-1',
email: 'test@example.com',
name: 'Test User',
role: 'engineer',
is_super_admin: false,
is_active: true,
must_change_password: false,
account_id: 'acct-1',
account_role: 'engineer',
team_id: null,
created_at: '2026-05-01T00:00:00Z',
last_login: null,
phone: null,
job_title: null,
timezone: 'UTC',
avatar_url: null,
email_verified_at: null,
...overrides,
}
}
const FROZEN_NOW = new Date('2026-05-06T00:00:00Z')
function renderAppLayout() {
return render(
<MemoryRouter initialEntries={['/']}>
<Routes>
<Route element={<AppLayout />}>
<Route
index
element={<div data-testid="child-route-content">child route</div>}
/>
</Route>
</Routes>
</MemoryRouter>,
)
}
describe('AppLayout — EmailVerificationGate wiring', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(FROZEN_NOW)
useAuthStore.setState({ user: null, token: null, isAuthenticated: false })
})
afterEach(() => {
vi.useRealTimers()
useAuthStore.setState({ user: null, token: null, isAuthenticated: false })
})
it('renders the wall and hides the child route on day 8 unverified', () => {
// created 8 days before frozen now -> elapsed=8, > grace=6 -> wall.
useAuthStore.setState({
user: makeUser({ created_at: '2026-04-28T00:00:00Z' }),
})
renderAppLayout()
expect(screen.getByTestId('email-verification-wall')).toBeInTheDocument()
expect(screen.queryByTestId('child-route-content')).not.toBeInTheDocument()
})
it('renders the child route within the grace period (day 1 unverified)', () => {
useAuthStore.setState({
user: makeUser({ created_at: '2026-05-05T00:00:00Z' }),
})
renderAppLayout()
expect(screen.getByTestId('child-route-content')).toBeInTheDocument()
expect(
screen.queryByTestId('email-verification-wall'),
).not.toBeInTheDocument()
})
})

View File

@@ -0,0 +1,119 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { EmailVerificationBanner } from '../EmailVerificationBanner'
import { useAuthStore } from '@/store/authStore'
import { authApi } from '@/api/auth'
import type { User } from '@/types'
vi.mock('@/api/auth', () => ({
authApi: {
getVerificationStatus: vi.fn(),
sendVerificationEmail: vi.fn(),
},
}))
vi.mock('@/lib/toast', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}))
function makeUser(overrides: Partial<User> = {}): User {
return {
id: 'user-1',
email: 'test@example.com',
name: 'Test User',
role: 'engineer',
is_super_admin: false,
is_active: true,
must_change_password: false,
account_id: 'acct-1',
account_role: 'engineer',
team_id: null,
created_at: '2026-05-01T00:00:00Z',
last_login: null,
phone: null,
job_title: null,
timezone: 'UTC',
avatar_url: null,
email_verified_at: null,
...overrides,
}
}
const FROZEN_NOW = new Date('2026-05-06T00:00:00Z')
describe('EmailVerificationBanner', () => {
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true })
vi.setSystemTime(FROZEN_NOW)
useAuthStore.setState({ user: null, token: null, isAuthenticated: false })
vi.mocked(authApi.getVerificationStatus).mockResolvedValue({
enabled: true,
})
vi.mocked(authApi.sendVerificationEmail).mockResolvedValue(undefined)
})
afterEach(() => {
vi.useRealTimers()
vi.clearAllMocks()
})
it('hides past grace day-7+', async () => {
// Created 8 days before frozen now -> elapsed=8, > grace=6.
useAuthStore.setState({
user: makeUser({ created_at: '2026-04-28T00:00:00Z' }),
})
const { container } = render(<EmailVerificationBanner />)
// Wait long enough for any pending verification-status fetch to resolve.
await waitFor(() => {
expect(authApi.getVerificationStatus).toHaveBeenCalled()
})
expect(
screen.queryByTestId('email-verification-banner'),
).not.toBeInTheDocument()
expect(container.firstChild).toBeNull()
})
it('renders within the grace window', async () => {
// Created 1 day before frozen now -> elapsed=1, within grace.
useAuthStore.setState({
user: makeUser({ created_at: '2026-05-05T00:00:00Z' }),
})
render(<EmailVerificationBanner />)
await waitFor(() => {
expect(
screen.getByTestId('email-verification-banner'),
).toBeInTheDocument()
})
})
it('resend triggers API call', async () => {
useAuthStore.setState({
user: makeUser({ created_at: '2026-05-05T00:00:00Z' }),
})
render(<EmailVerificationBanner />)
await waitFor(() => {
expect(
screen.getByTestId('email-verification-banner'),
).toBeInTheDocument()
})
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
await user.click(screen.getByTestId('banner-resend-button'))
await waitFor(() => {
expect(authApi.sendVerificationEmail).toHaveBeenCalledTimes(1)
})
})
})

View File

@@ -0,0 +1,155 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { TrialPill } from '../TrialPill'
import { useBillingStore } from '@/store/billingStore'
import type { SubscriptionState, PlanBillingState } from '@/types/billing'
const FROZEN_NOW = new Date('2026-05-06T12:00:00Z')
function renderPill() {
return render(
<MemoryRouter>
<TrialPill />
</MemoryRouter>,
)
}
function setBilling(opts: {
subscription: SubscriptionState | null
planBilling?: PlanBillingState | null
}) {
useBillingStore.setState({
subscription: opts.subscription,
planBilling: opts.planBilling ?? null,
planLimits: {},
enabledFeatures: {},
isLoading: false,
error: null,
})
}
function isoDaysFromNow(days: number): string {
const d = new Date(FROZEN_NOW.getTime() + days * 24 * 60 * 60 * 1000)
return d.toISOString()
}
describe('TrialPill', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(FROZEN_NOW)
useBillingStore.setState({
subscription: null,
planBilling: null,
planLimits: {},
enabledFeatures: {},
isLoading: false,
error: null,
})
})
afterEach(() => {
vi.useRealTimers()
})
it('renders Pro trial · Nd for pristine stage', () => {
setBilling({
subscription: {
status: 'trialing',
plan: 'pro',
current_period_start: FROZEN_NOW.toISOString(),
current_period_end: isoDaysFromNow(12),
cancel_at_period_end: false,
seat_limit: 5,
has_pro_entitlement: true,
is_paid: false,
},
})
renderPill()
const pill = screen.getByTestId('trial-pill')
expect(pill).toHaveTextContent(/Pro trial · 12d/)
// Pristine uses info tone tokens.
expect(pill.className).toContain('text-info')
expect(pill.className).toContain('bg-info-dim')
})
it('renders Trial expired CTA for expired stage', () => {
setBilling({
subscription: {
status: 'trialing',
plan: 'pro',
current_period_start: isoDaysFromNow(-14),
current_period_end: isoDaysFromNow(-1), // already past
cancel_at_period_end: false,
seat_limit: 5,
has_pro_entitlement: false,
is_paid: false,
},
})
renderPill()
const pill = screen.getByTestId('trial-pill')
expect(pill).toHaveTextContent(/Trial expired — pick a plan/)
// Clickable: rendered as anchor/link.
expect(pill.tagName).toBe('A')
expect(pill.getAttribute('href')).toBe('/account/billing/select-plan')
})
it('renders Complimentary Pro tag for complimentary subscription', () => {
setBilling({
subscription: {
status: 'complimentary',
plan: 'pro',
current_period_start: null,
current_period_end: null,
cancel_at_period_end: false,
seat_limit: null,
has_pro_entitlement: true,
is_paid: true,
},
})
renderPill()
const pill = screen.getByTestId('trial-pill')
expect(pill).toHaveTextContent(/Complimentary Pro/)
// Friendly tag, not clickable.
expect(pill.tagName).toBe('SPAN')
expect(pill.className).toContain('text-accent')
})
it('is hidden when subscription is null', () => {
setBilling({ subscription: null })
const { container } = renderPill()
expect(screen.queryByTestId('trial-pill')).not.toBeInTheDocument()
expect(container.firstChild).toBeNull()
})
it('past_due variant is clickable and links to /account/billing', () => {
setBilling({
subscription: {
status: 'past_due',
plan: 'pro',
current_period_start: isoDaysFromNow(-30),
current_period_end: isoDaysFromNow(-2),
cancel_at_period_end: false,
seat_limit: 5,
has_pro_entitlement: false,
is_paid: true,
},
})
renderPill()
const pill = screen.getByTestId('trial-pill')
expect(pill).toHaveTextContent(/Payment failed — update card/)
expect(pill.tagName).toBe('A')
expect(pill.getAttribute('href')).toBe('/account/billing')
})
})