7 Commits

Author SHA1 Message Date
ryan
924a28e201 feat: forced PIN setup modal on all authenticated pages
All checks were successful
CI / ci (pull_request) Successful in 29s
CI / e2e (pull_request) Successful in 1m7s
Replaces the alert banner with a blocking modal dialog that requires
users to set a PIN before they can use the app. Cannot be dismissed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 20:01:14 +00:00
ryan
2cd646ddea fix: remove unused Link import from profile page
All checks were successful
CI / ci (pull_request) Successful in 27s
CI / e2e (pull_request) Successful in 1m6s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 19:57:31 +00:00
ryan
3f9e125412 fix: move PIN warning banner to authenticated layout for all pages
Some checks failed
CI / ci (pull_request) Failing after 26s
CI / e2e (pull_request) Has been skipped
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 19:51:39 +00:00
ryan
96d2a966d7 feat: tabbed profile page with PIN setup and auto employee numbers
All checks were successful
CI / ci (pull_request) Successful in 25s
CI / e2e (pull_request) Successful in 55s
- Profile page split into Account, Security, Appearance tabs
- Security tab: change password + set/change/remove POS PIN
- Warning banner with link to Security tab when no PIN is set
- /auth/me returns employeeNumber and hasPin
- Migration 0046: Postgres trigger auto-assigns sequential employee
  numbers starting at 1001, backfills existing users
- Added shadcn Alert component

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 19:41:36 +00:00
ryan
666ae8d59b fix: assign Admin RBAC role to initial user on seed
All checks were successful
Build & Release / build (push) Successful in 22s
Without this, the initial user has no permissions and sees no modules.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 17:38:53 +00:00
67f1e4a26a Merge pull request 'feat: set browser tab title and favicon from customer branding' (#10) from feature/password-reset into main
All checks were successful
Build & Release / build (push) Successful in 1m20s
Reviewed-on: #10
2026-04-05 17:19:53 +00:00
ryan
613784a1cc feat: set browser tab title and favicon from customer branding
All checks were successful
CI / ci (pull_request) Successful in 27s
CI / e2e (pull_request) Successful in 1m15s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 17:15:32 +00:00
8 changed files with 450 additions and 92 deletions

View File

@@ -0,0 +1,66 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
{
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive:
"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Alert({
className,
variant,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
)
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
className
)}
{...props}
/>
)
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",
className
)}
{...props}
/>
)
}
export { Alert, AlertTitle, AlertDescription }

View File

@@ -1,11 +1,29 @@
import { createRootRoute, Outlet } from '@tanstack/react-router'
import { Toaster } from 'sonner'
import { useEffect } from 'react'
export const Route = createRootRoute({
component: RootLayout,
})
function RootLayout() {
useEffect(() => {
fetch('/v1/store/branding')
.then((r) => r.ok ? r.json() : null)
.then((data: { name: string | null; hasLogo: boolean } | null) => {
if (!data) return
if (data.name) document.title = data.name
if (data.hasLogo) {
const link = document.querySelector<HTMLLinkElement>('link[rel="icon"]')
?? document.createElement('link')
link.rel = 'icon'
link.href = '/v1/store/logo'
document.head.appendChild(link)
}
})
.catch(() => {})
}, [])
return (
<>
<Outlet />

View File

@@ -1,5 +1,5 @@
import { createFileRoute, Outlet, Link, redirect, useRouter } from '@tanstack/react-router'
import { useQuery } from '@tanstack/react-query'
import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query'
import { queryOptions } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import { api } from '@/lib/api-client'
@@ -9,6 +9,9 @@ import { moduleListOptions } from '@/api/modules'
import { Avatar } from '@/components/shared/avatar-upload'
import { Button } from '@/components/ui/button'
import { Users, UserRound, HelpCircle, Shield, UserCog, LogOut, User, Wrench, Package, ClipboardList, FolderOpen, KeyRound, Settings, PanelLeftClose, PanelLeft, CalendarDays, GraduationCap, CalendarRange, BookOpen, BookMarked, Package2, Tag, Truck, ShoppingCart } from 'lucide-react'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { toast } from 'sonner'
export const Route = createFileRoute('/_authenticated')({
beforeLoad: () => {
@@ -104,6 +107,58 @@ function NavGroup({ label, children, collapsed }: { label: string; children: Rea
)
}
function SetPinModal() {
const queryClient = useQueryClient()
const [pin, setPin] = useState('')
const [confirmPin, setConfirmPin] = useState('')
const [error, setError] = useState('')
const setPinMutation = useMutation({
mutationFn: () => api.post('/v1/auth/set-pin', { pin }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
toast.success('PIN set successfully')
},
onError: (err) => setError(err.message),
})
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
setError('')
if (pin.length < 4 || pin.length > 6) { setError('PIN must be 4-6 digits'); return }
if (!/^\d+$/.test(pin)) { setError('PIN must be digits only'); return }
if (pin !== confirmPin) { setError('PINs do not match'); return }
setPinMutation.mutate()
}
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
<div className="w-full max-w-sm rounded-xl border bg-card p-6 shadow-xl">
<h2 className="text-lg font-semibold mb-1">Set your POS PIN</h2>
<p className="text-sm text-muted-foreground mb-4">
A PIN is required to use the Point of Sale. Choose a 4-6 digit PIN you'll use to unlock the terminal.
</p>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>PIN</Label>
<Input type="password" inputMode="numeric" maxLength={6} value={pin} onChange={(e) => setPin(e.target.value)} placeholder="****" autoFocus />
</div>
<div className="space-y-2">
<Label>Confirm PIN</Label>
<Input type="password" inputMode="numeric" maxLength={6} value={confirmPin} onChange={(e) => setConfirmPin(e.target.value)} placeholder="****" />
</div>
</div>
{error && <p className="text-sm text-destructive">{error}</p>}
<Button type="submit" className="w-full" disabled={setPinMutation.isPending}>
{setPinMutation.isPending ? 'Setting...' : 'Set PIN'}
</Button>
</form>
</div>
</div>
)
}
function AuthenticatedLayout() {
const router = useRouter()
const user = useAuthStore((s) => s.user)
@@ -112,6 +167,13 @@ function AuthenticatedLayout() {
const setPermissions = useAuthStore((s) => s.setPermissions)
const permissionsLoaded = useAuthStore((s) => s.permissionsLoaded)
// Fetch profile for PIN warning
const { data: profile } = useQuery(queryOptions({
queryKey: ['auth', 'me'],
queryFn: () => api.get<{ hasPin: boolean }>('/v1/auth/me'),
enabled: !!useAuthStore.getState().token,
}))
// Fetch permissions on mount
const { data: permData } = useQuery({
...myPermissionsOptions(),
@@ -263,6 +325,7 @@ function AuthenticatedLayout() {
</div>
</nav>
<main className="flex-1 p-6 min-h-screen">
{profile && !profile.hasPin && <SetPinModal />}
<Outlet />
</main>
</div>

View File

@@ -11,10 +11,22 @@ import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Separator } from '@/components/ui/separator'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { Sun, Moon, Monitor } from 'lucide-react'
import { toast } from 'sonner'
import { AvatarUpload } from '@/components/shared/avatar-upload'
interface Profile {
id: string
email: string
firstName: string
lastName: string
role: string
employeeNumber: string | null
hasPin: boolean
createdAt: string
}
export const Route = createFileRoute('/_authenticated/profile')({
component: ProfilePage,
})
@@ -22,21 +34,56 @@ export const Route = createFileRoute('/_authenticated/profile')({
function profileOptions() {
return queryOptions({
queryKey: ['auth', 'me'],
queryFn: () => api.get<{ id: string; email: string; firstName: string; lastName: string }>('/v1/auth/me'),
queryFn: () => api.get<Profile>('/v1/auth/me'),
})
}
function ProfilePage() {
const { tab } = Route.useSearch() as { tab?: string }
const queryClient = useQueryClient()
const setAuth = useAuthStore((s) => s.setAuth)
const storeUser = useAuthStore((s) => s.user)
const storeToken = useAuthStore((s) => s.token)
const { mode, colorTheme, setMode, setColorTheme } = useThemeStore()
const { data: profile } = useQuery(profileOptions())
const [firstName, setFirstName] = useState('')
const [lastName, setLastName] = useState('')
return (
<div className="space-y-6 max-w-2xl">
<h1 className="text-2xl font-bold">Profile</h1>
<Tabs defaultValue={tab === 'security' || tab === 'appearance' ? tab : 'account'}>
<TabsList>
<TabsTrigger value="account">Account</TabsTrigger>
<TabsTrigger value="security">Security</TabsTrigger>
<TabsTrigger value="appearance">Appearance</TabsTrigger>
</TabsList>
<TabsContent value="account">
<AccountTab profile={profile} queryClient={queryClient} setAuth={setAuth} storeUser={storeUser} storeToken={storeToken} />
</TabsContent>
<TabsContent value="security">
<SecurityTab profile={profile} queryClient={queryClient} />
</TabsContent>
<TabsContent value="appearance">
<AppearanceTab />
</TabsContent>
</Tabs>
</div>
)
}
function AccountTab({ profile, queryClient, setAuth, storeUser, storeToken }: {
profile: Profile | undefined
queryClient: ReturnType<typeof useQueryClient>
setAuth: (token: string, user: any) => void
storeUser: any
storeToken: string | null
}) {
const [firstName, setFirstName] = useState(profile?.firstName ?? '')
const [lastName, setLastName] = useState(profile?.lastName ?? '')
const [nameLoaded, setNameLoaded] = useState(false)
if (profile && !nameLoaded) {
@@ -45,12 +92,8 @@ function ProfilePage() {
setNameLoaded(true)
}
const [currentPassword, setCurrentPassword] = useState('')
const [newPassword, setNewPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const updateProfileMutation = useMutation({
mutationFn: (data: Record<string, unknown>) => api.patch<{ id: string; email: string; firstName: string; lastName: string }>('/v1/auth/me', data),
mutationFn: (data: Record<string, unknown>) => api.patch<Profile>('/v1/auth/me', data),
onSuccess: (updated) => {
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
if (storeToken && storeUser) {
@@ -61,33 +104,7 @@ function ProfilePage() {
onError: (err) => toast.error(err.message),
})
const changePasswordMutation = useMutation({
mutationFn: () => api.post('/v1/auth/change-password', { currentPassword, newPassword }),
onSuccess: () => {
setCurrentPassword('')
setNewPassword('')
setConfirmPassword('')
toast.success('Password changed')
},
onError: (err) => toast.error(err.message),
})
function handlePasswordChange() {
if (newPassword.length < 12) {
toast.error('Password must be at least 12 characters')
return
}
if (newPassword !== confirmPassword) {
toast.error('Passwords do not match')
return
}
changePasswordMutation.mutate()
}
return (
<div className="space-y-6 max-w-2xl">
<h1 className="text-2xl font-bold">Profile</h1>
<Card>
<CardHeader>
<CardTitle className="text-lg">Account</CardTitle>
@@ -99,6 +116,9 @@ function ProfilePage() {
<div>
<p className="font-medium">{profile.firstName} {profile.lastName}</p>
<p className="text-sm text-muted-foreground">{profile.email}</p>
{profile.employeeNumber && (
<p className="text-xs text-muted-foreground">Employee #{profile.employeeNumber}</p>
)}
</div>
</div>
)}
@@ -124,7 +144,80 @@ function ProfilePage() {
</Button>
</CardContent>
</Card>
)
}
function SecurityTab({ profile, queryClient }: {
profile: Profile | undefined
queryClient: ReturnType<typeof useQueryClient>
}) {
const [currentPassword, setCurrentPassword] = useState('')
const [newPassword, setNewPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [pin, setPin] = useState('')
const [confirmPin, setConfirmPin] = useState('')
const changePasswordMutation = useMutation({
mutationFn: () => api.post('/v1/auth/change-password', { currentPassword, newPassword }),
onSuccess: () => {
setCurrentPassword('')
setNewPassword('')
setConfirmPassword('')
toast.success('Password changed')
},
onError: (err) => toast.error(err.message),
})
const setPinMutation = useMutation({
mutationFn: () => api.post('/v1/auth/set-pin', { pin }),
onSuccess: () => {
setPin('')
setConfirmPin('')
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
toast.success('PIN set')
},
onError: (err) => toast.error(err.message),
})
const removePinMutation = useMutation({
mutationFn: () => api.del('/v1/auth/pin'),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
toast.success('PIN removed')
},
onError: (err) => toast.error(err.message),
})
function handlePasswordChange() {
if (newPassword.length < 12) {
toast.error('Password must be at least 12 characters')
return
}
if (newPassword !== confirmPassword) {
toast.error('Passwords do not match')
return
}
changePasswordMutation.mutate()
}
function handleSetPin() {
if (pin.length < 4 || pin.length > 6) {
toast.error('PIN must be 4-6 digits')
return
}
if (!/^\d+$/.test(pin)) {
toast.error('PIN must be digits only')
return
}
if (pin !== confirmPin) {
toast.error('PINs do not match')
return
}
setPinMutation.mutate()
}
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-lg">Change Password</CardTitle>
@@ -148,6 +241,67 @@ function ProfilePage() {
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">POS PIN</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{profile?.employeeNumber && (
<p className="text-sm text-muted-foreground">
Your employee number is <span className="font-mono font-medium text-foreground">{profile.employeeNumber}</span>.
To unlock the POS, enter your employee number followed by your PIN.
</p>
)}
{profile?.hasPin ? (
<>
<p className="text-sm text-muted-foreground">You have a PIN set. You can change or remove it below.</p>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>New PIN (4-6 digits)</Label>
<Input type="password" inputMode="numeric" maxLength={6} value={pin} onChange={(e) => setPin(e.target.value)} placeholder="****" />
</div>
<div className="space-y-2">
<Label>Confirm PIN</Label>
<Input type="password" inputMode="numeric" maxLength={6} value={confirmPin} onChange={(e) => setConfirmPin(e.target.value)} placeholder="****" />
</div>
</div>
<div className="flex gap-2">
<Button onClick={handleSetPin} disabled={setPinMutation.isPending}>
{setPinMutation.isPending ? 'Saving...' : 'Change PIN'}
</Button>
<Button variant="outline" onClick={() => removePinMutation.mutate()} disabled={removePinMutation.isPending}>
{removePinMutation.isPending ? 'Removing...' : 'Remove PIN'}
</Button>
</div>
</>
) : (
<>
<p className="text-sm text-muted-foreground">Set a PIN to unlock the Point of Sale terminal.</p>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>PIN (4-6 digits)</Label>
<Input type="password" inputMode="numeric" maxLength={6} value={pin} onChange={(e) => setPin(e.target.value)} placeholder="****" />
</div>
<div className="space-y-2">
<Label>Confirm PIN</Label>
<Input type="password" inputMode="numeric" maxLength={6} value={confirmPin} onChange={(e) => setConfirmPin(e.target.value)} placeholder="****" />
</div>
</div>
<Button onClick={handleSetPin} disabled={setPinMutation.isPending}>
{setPinMutation.isPending ? 'Saving...' : 'Set PIN'}
</Button>
</>
)}
</CardContent>
</Card>
</div>
)
}
function AppearanceTab() {
const { mode, colorTheme, setMode, setColorTheme } = useThemeStore()
return (
<Card>
<CardHeader>
<CardTitle className="text-lg">Appearance</CardTitle>
@@ -197,6 +351,5 @@ function ProfilePage() {
</div>
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,31 @@
-- Auto-assign employee_number on user insert if not provided
CREATE OR REPLACE FUNCTION assign_employee_number()
RETURNS TRIGGER AS $$
DECLARE next_num INT;
BEGIN
IF NEW.employee_number IS NULL OR NEW.employee_number = '' THEN
SELECT COALESCE(MAX(employee_number::int), 1000) + 1
INTO next_num
FROM "user"
WHERE employee_number ~ '^\d+$';
NEW.employee_number := next_num::text;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS trg_assign_employee_number ON "user";
CREATE TRIGGER trg_assign_employee_number
BEFORE INSERT ON "user"
FOR EACH ROW
EXECUTE FUNCTION assign_employee_number();
-- Backfill any users missing an employee number
DO $$ DECLARE r RECORD; num INT;
BEGIN
SELECT COALESCE(MAX(employee_number::int), 1000) INTO num FROM "user" WHERE employee_number ~ '^\d+$';
FOR r IN (SELECT id FROM "user" WHERE employee_number IS NULL OR employee_number = '' ORDER BY created_at) LOOP
num := num + 1;
UPDATE "user" SET employee_number = num::text WHERE id = r.id;
END LOOP;
END $$;

View File

@@ -323,6 +323,13 @@
"when": 1775770000000,
"tag": "0045_registers-reports",
"breakpoints": true
},
{
"idx": 46,
"version": "7",
"when": 1775860000000,
"tag": "0046_auto-employee-number",
"breakpoints": true
}
]
}

View File

@@ -37,8 +37,10 @@ import { RbacService } from './services/rbac.service.js'
import { ModuleService } from './services/module.service.js'
import { AppConfigService } from './services/config.service.js'
import { SettingsService } from './services/settings.service.js'
import { eq } from 'drizzle-orm'
import { users } from './db/schema/users.js'
import { companies } from './db/schema/stores.js'
import { roles, userRoles } from './db/schema/rbac.js'
import { EmailService } from './services/email.service.js'
import bcrypt from 'bcryptjs'
@@ -55,6 +57,13 @@ async function seedInitialUser(app: Awaited<ReturnType<typeof buildApp>>) {
const tempPassword = crypto.randomUUID()
const passwordHash = await bcrypt.hash(tempPassword, 10)
const [user] = await app.db.insert(users).values({ email, passwordHash, firstName, lastName, role: 'admin' }).returning({ id: users.id })
// Assign the Admin RBAC role
const [adminRole] = await app.db.select({ id: roles.id }).from(roles).where(eq(roles.name, 'Admin')).limit(1)
if (adminRole) {
await app.db.insert(userRoles).values({ userId: user.id, roleId: adminRole.id })
}
app.log.info({ email }, 'Initial admin user created')
// Send welcome email with password setup link

View File

@@ -274,6 +274,8 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
firstName: users.firstName,
lastName: users.lastName,
role: users.role,
employeeNumber: users.employeeNumber,
pinHash: users.pinHash,
createdAt: users.createdAt,
})
.from(users)
@@ -281,7 +283,16 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
.limit(1)
if (!user) return reply.status(404).send({ error: { message: 'User not found', statusCode: 404 } })
return reply.send(user)
return reply.send({
id: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
role: user.role,
employeeNumber: user.employeeNumber,
hasPin: !!user.pinHash,
createdAt: user.createdAt,
})
})
// Update current user profile