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

@@ -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')
})
})