12 Commits

Author SHA1 Message Date
ryan
45fd6d34eb feat: email receipts and repair estimates
All checks were successful
CI / ci (pull_request) Successful in 24s
CI / e2e (pull_request) Successful in 1m2s
Backend:
- Server-side HTML email templates (receipt + estimate) with inline CSS
- POST /v1/transactions/:id/email-receipt with per-transaction rate limiting
- POST /v1/repair-tickets/:id/email-estimate with per-ticket rate limiting
- customerEmail field added to receipt and ticket detail responses
- Test email provider for API tests (logs instead of sending)

Frontend:
- POS payment dialog Email button enabled with inline email input
- Pre-fills customer email from linked account
- Repair ticket detail page has Email Estimate button with dialog
- Pre-fills from account email

Tests:
- 12 unit tests for email template renderers
- 8 API tests for email receipt/estimate endpoints and validation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 20:32:52 +00:00
30233b430f Merge pull request 'fix: move PIN warning banner to authenticated layout for all pages' (#12) from feature/user-profile into main
All checks were successful
Build & Release / build (push) Successful in 1m16s
Reviewed-on: #12
2026-04-05 20:03:56 +00:00
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
7bca854058 Merge pull request 'feat: tabbed profile page with PIN setup and auto employee numbers' (#11) from feature/user-profile into main
All checks were successful
Build & Release / build (push) Successful in 1m19s
Reviewed-on: #11
2026-04-05 19:43:53 +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
ea9aceec46 Merge pull request 'feat: password reset flow with welcome emails' (#9) from feature/password-reset into main
All checks were successful
Build & Release / build (push) Successful in 1m16s
Reviewed-on: #9
2026-04-05 17:12:06 +00:00
ryan
bc8613bbbc feat: password reset flow with welcome emails
All checks were successful
CI / ci (pull_request) Successful in 27s
CI / e2e (pull_request) Successful in 1m0s
- POST /auth/forgot-password with welcome/reset email templates
- POST /auth/reset-password with Zod validation, 4-hour tokens
- Per-email rate limiting (3/hr) via Valkey, no user enumeration
- Login page "Forgot password?" toggle with inline form
- /reset-password page for setting new password from email link
- Initial user seed sends welcome email instead of requiring password
- CLI script for force-resetting passwords via kubectl exec
- APP_URL env var in chart, removed INITIAL_USER_PASSWORD

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 17:09:23 +00:00
27 changed files with 1724 additions and 161 deletions

View File

@@ -93,18 +93,14 @@ spec:
secretKeyRef:
name: lunarfront-secrets
key: business-name
- name: APP_URL
value: "https://{{ .Values.ingress.host }}"
- name: INITIAL_USER_EMAIL
valueFrom:
secretKeyRef:
name: lunarfront-secrets
key: initial-user-email
optional: true
- name: INITIAL_USER_PASSWORD
valueFrom:
secretKeyRef:
name: lunarfront-secrets
key: initial-user-password
optional: true
- name: INITIAL_USER_FIRST_NAME
valueFrom:
secretKeyRef:

View File

@@ -14,3 +14,11 @@ interface LoginResponse {
export async function login(email: string, password: string): Promise<LoginResponse> {
return api.post<LoginResponse>('/v1/auth/login', { email, password })
}
export async function forgotPassword(email: string): Promise<{ message: string }> {
return api.post<{ message: string }>('/v1/auth/forgot-password', { email })
}
export async function resetPassword(token: string, newPassword: string): Promise<{ message: string }> {
return api.post<{ message: string }>('/v1/auth/reset-password', { token, newPassword })
}

View File

@@ -84,6 +84,7 @@ export function POSPaymentDialog({ open, onOpenChange, paymentMethod, transactio
queryKey: ['pos', 'receipt', result?.id],
queryFn: () => api.get<{
transaction: Transaction & { lineItems: { description: string; qty: number; unitPrice: string; taxAmount: string; lineTotal: string; discountAmount: string }[] }
customerEmail: string | null
company: { name: string; phone: string | null; email: string | null; address: { street?: string; city?: string; state?: string; zip?: string } | null }
location: { name: string; phone: string | null; email: string | null; address: { street?: string; city?: string; state?: string; zip?: string } | null }
}>(`/v1/transactions/${result!.id}/receipt`),
@@ -91,6 +92,19 @@ export function POSPaymentDialog({ open, onOpenChange, paymentMethod, transactio
})
const [showReceipt, setShowReceipt] = useState(false)
const [emailMode, setEmailMode] = useState(false)
const [emailAddress, setEmailAddress] = useState('')
const [emailSent, setEmailSent] = useState(false)
const emailReceiptMutation = useMutation({
mutationFn: () => api.post<{ message: string }>(`/v1/transactions/${result!.id}/email-receipt`, { email: emailAddress }),
onSuccess: () => {
toast.success('Receipt emailed')
setEmailMode(false)
setEmailSent(true)
},
onError: (err) => toast.error(err.message),
})
if (completed && result) {
const changeGiven = parseFloat(result.changeGiven ?? '0')
@@ -140,14 +154,47 @@ export function POSPaymentDialog({ open, onOpenChange, paymentMethod, transactio
)}
</div>
<div className="w-full grid grid-cols-2 gap-2">
<Button variant="outline" className="h-11 gap-2" onClick={() => setShowReceipt(true)}>
<Printer className="h-4 w-4" />Receipt
</Button>
<Button variant="outline" className="h-11 gap-2" disabled>
<Mail className="h-4 w-4" />Email
</Button>
</div>
{emailMode ? (
<div className="w-full space-y-2">
<Label className="text-xs text-muted-foreground">Email receipt to:</Label>
<div className="flex gap-2">
<Input
type="email"
value={emailAddress}
onChange={(e) => setEmailAddress(e.target.value)}
placeholder="customer@example.com"
className="h-9"
autoFocus
/>
<Button
size="sm"
className="h-9 px-4"
onClick={() => emailReceiptMutation.mutate()}
disabled={!emailAddress || emailReceiptMutation.isPending}
>
{emailReceiptMutation.isPending ? 'Sending...' : 'Send'}
</Button>
</div>
<Button variant="ghost" size="sm" className="text-xs" onClick={() => setEmailMode(false)}>Cancel</Button>
</div>
) : (
<div className="w-full grid grid-cols-2 gap-2">
<Button variant="outline" className="h-11 gap-2" onClick={() => setShowReceipt(true)}>
<Printer className="h-4 w-4" />Receipt
</Button>
<Button
variant="outline"
className="h-11 gap-2"
onClick={() => {
setEmailAddress(receiptData?.customerEmail ?? '')
setEmailMode(true)
}}
disabled={emailSent}
>
<Mail className="h-4 w-4" />{emailSent ? 'Sent' : 'Email'}
</Button>
</div>
)}
<Button className="w-full h-12 text-base" onClick={handleDone}>
New Sale

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

@@ -9,6 +9,7 @@
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root'
import { Route as ResetPasswordRouteImport } from './routes/reset-password'
import { Route as PosRouteImport } from './routes/pos'
import { Route as LoginRouteImport } from './routes/login'
import { Route as AuthenticatedRouteImport } from './routes/_authenticated'
@@ -58,6 +59,11 @@ import { Route as AuthenticatedAccountsAccountIdMembersRouteImport } from './rou
import { Route as AuthenticatedAccountsAccountIdEnrollmentsRouteImport } from './routes/_authenticated/accounts/$accountId/enrollments'
import { Route as AuthenticatedLessonsScheduleInstructorsInstructorIdRouteImport } from './routes/_authenticated/lessons/schedule/instructors/$instructorId'
const ResetPasswordRoute = ResetPasswordRouteImport.update({
id: '/reset-password',
path: '/reset-password',
getParentRoute: () => rootRouteImport,
} as any)
const PosRoute = PosRouteImport.update({
id: '/pos',
path: '/pos',
@@ -337,6 +343,7 @@ export interface FileRoutesByFullPath {
'/': typeof AuthenticatedIndexRoute
'/login': typeof LoginRoute
'/pos': typeof PosRoute
'/reset-password': typeof ResetPasswordRoute
'/help': typeof AuthenticatedHelpRoute
'/profile': typeof AuthenticatedProfileRoute
'/settings': typeof AuthenticatedSettingsRoute
@@ -385,6 +392,7 @@ export interface FileRoutesByFullPath {
export interface FileRoutesByTo {
'/login': typeof LoginRoute
'/pos': typeof PosRoute
'/reset-password': typeof ResetPasswordRoute
'/help': typeof AuthenticatedHelpRoute
'/profile': typeof AuthenticatedProfileRoute
'/settings': typeof AuthenticatedSettingsRoute
@@ -435,6 +443,7 @@ export interface FileRoutesById {
'/_authenticated': typeof AuthenticatedRouteWithChildren
'/login': typeof LoginRoute
'/pos': typeof PosRoute
'/reset-password': typeof ResetPasswordRoute
'/_authenticated/help': typeof AuthenticatedHelpRoute
'/_authenticated/profile': typeof AuthenticatedProfileRoute
'/_authenticated/settings': typeof AuthenticatedSettingsRoute
@@ -487,6 +496,7 @@ export interface FileRouteTypes {
| '/'
| '/login'
| '/pos'
| '/reset-password'
| '/help'
| '/profile'
| '/settings'
@@ -535,6 +545,7 @@ export interface FileRouteTypes {
to:
| '/login'
| '/pos'
| '/reset-password'
| '/help'
| '/profile'
| '/settings'
@@ -584,6 +595,7 @@ export interface FileRouteTypes {
| '/_authenticated'
| '/login'
| '/pos'
| '/reset-password'
| '/_authenticated/help'
| '/_authenticated/profile'
| '/_authenticated/settings'
@@ -635,10 +647,18 @@ export interface RootRouteChildren {
AuthenticatedRoute: typeof AuthenticatedRouteWithChildren
LoginRoute: typeof LoginRoute
PosRoute: typeof PosRoute
ResetPasswordRoute: typeof ResetPasswordRoute
}
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/reset-password': {
id: '/reset-password'
path: '/reset-password'
fullPath: '/reset-password'
preLoaderRoute: typeof ResetPasswordRouteImport
parentRoute: typeof rootRouteImport
}
'/pos': {
id: '/pos'
path: '/pos'
@@ -1112,6 +1132,7 @@ const rootRouteChildren: RootRouteChildren = {
AuthenticatedRoute: AuthenticatedRouteWithChildren,
LoginRoute: LoginRoute,
PosRoute: PosRoute,
ResetPasswordRoute: ResetPasswordRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)

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,6 +104,59 @@ function ProfilePage() {
onError: (err) => toast.error(err.message),
})
return (
<Card>
<CardHeader>
<CardTitle className="text-lg">Account</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{profile?.id && (
<div className="flex items-center gap-4">
<AvatarUpload entityType="user" entityId={profile.id} size="lg" />
<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>
)}
<div className="space-y-2">
<Label>Email</Label>
<Input value={profile?.email ?? ''} disabled className="opacity-60" />
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>First Name</Label>
<Input value={firstName} onChange={(e) => setFirstName(e.target.value)} />
</div>
<div className="space-y-2">
<Label>Last Name</Label>
<Input value={lastName} onChange={(e) => setLastName(e.target.value)} />
</div>
</div>
<Button
onClick={() => updateProfileMutation.mutate({ firstName, lastName })}
disabled={updateProfileMutation.isPending}
>
{updateProfileMutation.isPending ? 'Saving...' : 'Save'}
</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: () => {
@@ -72,6 +168,26 @@ function ProfilePage() {
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')
@@ -84,47 +200,24 @@ function ProfilePage() {
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 max-w-2xl">
<h1 className="text-2xl font-bold">Profile</h1>
<Card>
<CardHeader>
<CardTitle className="text-lg">Account</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{profile?.id && (
<div className="flex items-center gap-4">
<AvatarUpload entityType="user" entityId={profile.id} size="lg" />
<div>
<p className="font-medium">{profile.firstName} {profile.lastName}</p>
<p className="text-sm text-muted-foreground">{profile.email}</p>
</div>
</div>
)}
<div className="space-y-2">
<Label>Email</Label>
<Input value={profile?.email ?? ''} disabled className="opacity-60" />
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>First Name</Label>
<Input value={firstName} onChange={(e) => setFirstName(e.target.value)} />
</div>
<div className="space-y-2">
<Label>Last Name</Label>
<Input value={lastName} onChange={(e) => setLastName(e.target.value)} />
</div>
</div>
<Button
onClick={() => updateProfileMutation.mutate({ firstName, lastName })}
disabled={updateProfileMutation.isPending}
>
{updateProfileMutation.isPending ? 'Saving...' : 'Save'}
</Button>
</CardContent>
</Card>
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-lg">Change Password</CardTitle>
@@ -150,53 +243,113 @@ function ProfilePage() {
<Card>
<CardHeader>
<CardTitle className="text-lg">Appearance</CardTitle>
<CardTitle className="text-lg">POS PIN</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label>Mode</Label>
<div className="flex gap-2">
{[
{ value: 'light' as const, icon: Sun, label: 'Light' },
{ value: 'dark' as const, icon: Moon, label: 'Dark' },
{ value: 'system' as const, icon: Monitor, label: 'System' },
].map((m) => (
<Button
key={m.value}
variant={mode === m.value ? 'default' : 'secondary'}
size="sm"
onClick={() => setMode(m.value)}
>
<m.icon className="mr-2 h-4 w-4" />
{m.label}
{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>
))}
</div>
</div>
<Separator />
<div className="space-y-2">
<Label>Color Theme</Label>
<div className="flex gap-2 flex-wrap">
{themes.map((t) => (
<Button
key={t.name}
variant={colorTheme === t.name ? 'default' : 'secondary'}
size="sm"
onClick={() => setColorTheme(t.name)}
>
<span
className="mr-2 h-3 w-3 rounded-full border inline-block"
style={{ backgroundColor: `hsl(${t.light.primary})` }}
/>
{t.label}
<Button variant="outline" onClick={() => removePinMutation.mutate()} disabled={removePinMutation.isPending}>
{removePinMutation.isPending ? 'Removing...' : 'Remove PIN'}
</Button>
))}
</div>
</div>
</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>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label>Mode</Label>
<div className="flex gap-2">
{[
{ value: 'light' as const, icon: Sun, label: 'Light' },
{ value: 'dark' as const, icon: Moon, label: 'Dark' },
{ value: 'system' as const, icon: Monitor, label: 'System' },
].map((m) => (
<Button
key={m.value}
variant={mode === m.value ? 'default' : 'secondary'}
size="sm"
onClick={() => setMode(m.value)}
>
<m.icon className="mr-2 h-4 w-4" />
{m.label}
</Button>
))}
</div>
</div>
<Separator />
<div className="space-y-2">
<Label>Color Theme</Label>
<div className="flex gap-2 flex-wrap">
{themes.map((t) => (
<Button
key={t.name}
variant={colorTheme === t.name ? 'default' : 'secondary'}
size="sm"
onClick={() => setColorTheme(t.name)}
>
<span
className="mr-2 h-3 w-3 rounded-full border inline-block"
style={{ backgroundColor: `hsl(${t.light.primary})` }}
/>
{t.label}
</Button>
))}
</div>
</div>
</CardContent>
</Card>
)
}

View File

@@ -21,7 +21,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { ArrowLeft, Plus, Trash2, RotateCcw, Save, Search } from 'lucide-react'
import { ArrowLeft, Plus, Trash2, RotateCcw, Save, Search, Mail } from 'lucide-react'
import { PdfModal } from '@/components/repairs/pdf-modal'
import { toast } from 'sonner'
import { useAuthStore } from '@/stores/auth.store'
@@ -78,6 +78,17 @@ function RepairTicketDetailPage() {
const { data: lineItemsData, isLoading: itemsLoading } = useQuery(repairLineItemListOptions(ticketId, params))
const [editFields, setEditFields] = useState<Record<string, string>>({})
const [emailEstimateOpen, setEmailEstimateOpen] = useState(false)
const [estimateEmail, setEstimateEmail] = useState('')
const emailEstimateMutation = useMutation({
mutationFn: () => api.post<{ message: string }>(`/v1/repair-tickets/${ticketId}/email-estimate`, { email: estimateEmail }),
onSuccess: () => {
toast.success('Estimate emailed')
setEmailEstimateOpen(false)
},
onError: (err) => toast.error(err.message),
})
const statusMutation = useMutation({
mutationFn: (status: string) => repairTicketMutations.updateStatus(ticketId, status),
@@ -188,6 +199,37 @@ function RepairTicketDetailPage() {
<h1 className="text-2xl font-bold">Ticket #{ticket.ticketNumber}</h1>
<p className="text-sm text-muted-foreground">{ticket.customerName} {ticket.itemDescription ?? 'No item description'}</p>
</div>
<Dialog open={emailEstimateOpen} onOpenChange={setEmailEstimateOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm" className="gap-2" onClick={() => setEstimateEmail((ticket as any).customerEmail ?? '')}>
<Mail className="h-4 w-4" />Email Estimate
</Button>
</DialogTrigger>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle>Email Estimate</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label>Send to</Label>
<Input
type="email"
value={estimateEmail}
onChange={(e) => setEstimateEmail(e.target.value)}
placeholder="customer@example.com"
autoFocus
/>
</div>
<Button
className="w-full"
onClick={() => emailEstimateMutation.mutate()}
disabled={!estimateEmail || emailEstimateMutation.isPending}
>
{emailEstimateMutation.isPending ? 'Sending...' : 'Send Estimate'}
</Button>
</div>
</DialogContent>
</Dialog>
<PdfModal ticket={ticket} lineItems={lineItemsData?.data ?? []} ticketId={ticketId} />
</div>

View File

@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react'
import { createFileRoute, useRouter, redirect } from '@tanstack/react-router'
import { useAuthStore } from '@/stores/auth.store'
import { login } from '@/api/auth'
import { login, forgotPassword } from '@/api/auth'
interface Branding {
name: string | null
@@ -26,6 +26,8 @@ function LoginPage() {
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const [branding, setBranding] = useState<Branding | null>(null)
const [forgotMode, setForgotMode] = useState(false)
const [forgotSent, setForgotSent] = useState(false)
useEffect(() => {
fetch('/v1/store/branding')
@@ -72,42 +74,117 @@ function LoginPage() {
<p className="text-sm mt-1" style={{ color: '#6b7a8d' }}>Small Business Management</p>
)}
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Email</label>
<input
type="email"
placeholder="you@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
{error && (
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
)}
<button
type="submit"
disabled={loading}
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
>
{loading ? 'Signing in...' : 'Sign in'}
</button>
</form>
{forgotMode ? (
forgotSent ? (
<div className="text-center space-y-4">
<p className="text-sm" style={{ color: '#b0bec5' }}>If an account exists with that email, you will receive a password reset link.</p>
<button
onClick={() => { setForgotMode(false); setForgotSent(false); setError('') }}
className="text-xs"
style={{ color: '#6b7a8d' }}
>
Back to sign in
</button>
</div>
) : (
<form onSubmit={async (e) => {
e.preventDefault()
setError('')
setLoading(true)
try {
await forgotPassword(email)
setForgotSent(true)
} catch (err) {
setError(err instanceof Error ? err.message : 'Something went wrong')
} finally {
setLoading(false)
}
}} className="space-y-4">
<p className="text-sm" style={{ color: '#b0bec5' }}>Enter your email and we'll send you a reset link.</p>
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Email</label>
<input
type="email"
placeholder="you@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
{error && (
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
)}
<button
type="submit"
disabled={loading}
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
>
{loading ? 'Sending...' : 'Send reset link'}
</button>
<div className="text-center">
<button
type="button"
onClick={() => { setForgotMode(false); setError('') }}
className="text-xs"
style={{ color: '#6b7a8d' }}
>
Back to sign in
</button>
</div>
</form>
)
) : (
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Email</label>
<input
type="email"
placeholder="you@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
{error && (
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
)}
<button
type="submit"
disabled={loading}
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
>
{loading ? 'Signing in...' : 'Sign in'}
</button>
<div className="text-center">
<button
type="button"
onClick={() => { setForgotMode(true); setError('') }}
className="text-xs"
style={{ color: '#6b7a8d' }}
>
Forgot password?
</button>
</div>
</form>
)}
</div>
</div>
)

View File

@@ -0,0 +1,154 @@
import { useState, useEffect } from 'react'
import { createFileRoute, Link } from '@tanstack/react-router'
import { resetPassword } from '@/api/auth'
interface Branding {
name: string | null
hasLogo: boolean
}
export const Route = createFileRoute('/reset-password')({
component: ResetPasswordPage,
})
function ResetPasswordPage() {
const { token } = Route.useSearch() as { token?: string }
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const [success, setSuccess] = useState(false)
const [branding, setBranding] = useState<Branding | null>(null)
useEffect(() => {
fetch('/v1/store/branding')
.then((r) => r.ok ? r.json() : null)
.then((data) => { if (data) setBranding(data) })
.catch(() => {})
}, [])
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
setError('')
if (!token) {
setError('Missing reset token. Please use the link from your email.')
return
}
if (password !== confirmPassword) {
setError('Passwords do not match')
return
}
if (password.length < 12) {
setError('Password must be at least 12 characters')
return
}
setLoading(true)
try {
await resetPassword(token, password)
setSuccess(true)
} catch (err) {
setError(err instanceof Error ? err.message : 'Reset failed. The link may have expired.')
} finally {
setLoading(false)
}
}
return (
<div
className="flex min-h-screen items-center justify-center"
style={{ background: 'linear-gradient(135deg, #0f1724 0%, #142038 100%)' }}
>
<div
className="w-full max-w-sm rounded-xl border p-8 shadow-2xl"
style={{ backgroundColor: '#131c2e', borderColor: '#1e2d45' }}
>
<div className="text-center mb-8">
{branding?.hasLogo ? (
<img src="/v1/store/logo" alt={branding.name ?? 'Store'} className="max-h-14 max-w-[220px] object-contain mx-auto" />
) : (
<h1 className="text-3xl font-bold" style={{ color: '#d8dfe9' }}>{branding?.name ?? 'LunarFront'}</h1>
)}
{branding?.name ? (
<p className="text-[10px] mt-2" style={{ color: '#4a5568' }}>Powered by <span style={{ color: '#6b7a8d' }}>LunarFront</span></p>
) : (
<p className="text-sm mt-1" style={{ color: '#6b7a8d' }}>Small Business Management</p>
)}
</div>
{success ? (
<div className="text-center space-y-4">
<p style={{ color: '#81c784' }}>Password reset successfully.</p>
<Link
to="/login"
className="inline-block h-9 rounded-md border px-4 py-2 text-sm font-medium transition-colors"
style={{ color: '#d0d8e0', borderColor: '#3a4a62' }}
>
Sign in
</Link>
</div>
) : !token ? (
<div className="text-center space-y-4">
<p style={{ color: '#e57373' }}>Invalid reset link. Please request a new one.</p>
<Link
to="/login"
className="inline-block h-9 rounded-md border px-4 py-2 text-sm font-medium transition-colors"
style={{ color: '#d0d8e0', borderColor: '#3a4a62' }}
>
Back to sign in
</Link>
</div>
) : (
<>
<h2 className="text-lg font-semibold text-center mb-4" style={{ color: '#d8dfe9' }}>Set new password</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>New password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={12}
placeholder="At least 12 characters"
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Confirm password</label>
<input
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
/>
</div>
{error && (
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
)}
<button
type="submit"
disabled={loading}
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
>
{loading ? 'Resetting...' : 'Reset password'}
</button>
<div className="text-center">
<Link to="/login" className="text-xs" style={{ color: '#6b7a8d' }}>
Back to sign in
</Link>
</div>
</form>
</>
)}
</div>
</div>
)
}

View File

@@ -0,0 +1,144 @@
import { describe, it, expect } from 'bun:test'
import {
renderReceiptEmailHtml,
renderReceiptEmailText,
renderEstimateEmailHtml,
renderEstimateEmailText,
} from '../../src/utils/email-templates.js'
const mockReceipt = {
transaction: {
transactionNumber: 'TXN-20260405-001',
subtotal: '100.00',
discountTotal: '10.00',
taxTotal: '7.43',
total: '97.43',
paymentMethod: 'cash',
amountTendered: '100.00',
changeGiven: '2.57',
roundingAdjustment: null,
completedAt: '2026-04-05T12:00:00Z',
lineItems: [
{ description: 'Guitar Strings', qty: 2, unitPrice: '12.99', taxAmount: '2.14', lineTotal: '25.98', discountAmount: null },
{ description: 'Tuner', qty: 1, unitPrice: '74.02', taxAmount: '5.29', lineTotal: '74.02', discountAmount: null },
],
},
company: { name: 'Test Store', phone: '555-1234', email: 'store@test.com', address: { street: '123 Main St', city: 'Austin', state: 'TX', zip: '78701' } },
location: null,
}
const mockTicket = {
ticketNumber: 'RPR-001',
customerName: 'Jane Doe',
customerPhone: '555-5678',
itemDescription: 'Acoustic Guitar',
serialNumber: 'AG-12345',
problemDescription: 'Cracked neck joint',
estimatedCost: '250.00',
promisedDate: '2026-04-12',
status: 'pending_approval',
}
const mockLineItems = [
{ itemType: 'labor', description: 'Neck repair', qty: 1, unitPrice: '150.00', totalPrice: '150.00' },
{ itemType: 'part', description: 'Wood glue & clamps', qty: 1, unitPrice: '25.00', totalPrice: '25.00' },
{ itemType: 'flat_rate', description: 'Setup & restring', qty: 1, unitPrice: '75.00', totalPrice: '75.00' },
]
const mockCompany = { name: 'Test Store', phone: '555-1234', email: 'store@test.com', address: null }
describe('renderReceiptEmailHtml', () => {
it('renders HTML with transaction details', () => {
const html = renderReceiptEmailHtml(mockReceipt as any)
expect(html).toContain('TXN-20260405-001')
expect(html).toContain('Test Store')
expect(html).toContain('Guitar Strings')
expect(html).toContain('Tuner')
expect(html).toContain('$97.43')
expect(html).toContain('$100.00')
expect(html).toContain('Powered by LunarFront')
})
it('includes discount when present', () => {
const html = renderReceiptEmailHtml(mockReceipt as any)
expect(html).toContain('Discount')
expect(html).toContain('$10.00')
})
it('includes payment details for cash', () => {
const html = renderReceiptEmailHtml(mockReceipt as any)
expect(html).toContain('Cash')
expect(html).toContain('$2.57')
})
it('includes receipt config when provided', () => {
const config = { receipt_footer: 'Thank you!', receipt_return_policy: '30-day returns' }
const html = renderReceiptEmailHtml(mockReceipt as any, config)
expect(html).toContain('Thank you!')
expect(html).toContain('30-day returns')
})
it('includes company address', () => {
const html = renderReceiptEmailHtml(mockReceipt as any)
expect(html).toContain('123 Main St')
expect(html).toContain('Austin')
})
})
describe('renderReceiptEmailText', () => {
it('renders plain text with transaction details', () => {
const text = renderReceiptEmailText(mockReceipt as any)
expect(text).toContain('TXN-20260405-001')
expect(text).toContain('Guitar Strings')
expect(text).toContain('Total: $97.43')
expect(text).toContain('Cash')
})
})
describe('renderEstimateEmailHtml', () => {
it('renders HTML with ticket details', () => {
const html = renderEstimateEmailHtml(mockTicket as any, mockLineItems as any, mockCompany as any)
expect(html).toContain('RPR-001')
expect(html).toContain('Jane Doe')
expect(html).toContain('Acoustic Guitar')
expect(html).toContain('AG-12345')
expect(html).toContain('Cracked neck joint')
expect(html).toContain('$250.00')
expect(html).toContain('Powered by LunarFront')
})
it('renders line items with types', () => {
const html = renderEstimateEmailHtml(mockTicket as any, mockLineItems as any, mockCompany as any)
expect(html).toContain('Labor')
expect(html).toContain('Neck repair')
expect(html).toContain('Part')
expect(html).toContain('Flat Rate')
expect(html).toContain('Setup &amp; restring')
})
it('includes promised date', () => {
const html = renderEstimateEmailHtml(mockTicket as any, mockLineItems as any, mockCompany as any)
expect(html).toContain('Estimated completion')
expect(html).toContain('Apr')
})
it('renders without line items using estimatedCost', () => {
const html = renderEstimateEmailHtml(mockTicket as any, [], mockCompany as any)
expect(html).toContain('$250.00')
})
it('includes company phone', () => {
const html = renderEstimateEmailHtml(mockTicket as any, mockLineItems as any, mockCompany as any)
expect(html).toContain('555-1234')
})
})
describe('renderEstimateEmailText', () => {
it('renders plain text with ticket details', () => {
const text = renderEstimateEmailText(mockTicket as any, mockLineItems as any, mockCompany as any)
expect(text).toContain('RPR-001')
expect(text).toContain('Jane Doe')
expect(text).toContain('Neck repair')
expect(text).toContain('$250.00')
})
})

View File

@@ -114,6 +114,10 @@ async function setupDatabase() {
await testSql`INSERT INTO module_config (slug, name, description, licensed, enabled) VALUES (${m.slug}, ${m.name}, ${m.description}, true, ${m.enabled}) ON CONFLICT (slug) DO NOTHING`
}
// Seed test email provider so email endpoints work without real provider
await testSql`INSERT INTO app_settings (key, value, is_encrypted) VALUES ('email.provider', 'test', false) ON CONFLICT (key) DO NOTHING`
await testSql`INSERT INTO app_settings (key, value, is_encrypted) VALUES ('email.from_address', 'Test Store <noreply@test.com>', false) ON CONFLICT (key) DO NOTHING`
await testSql.end()
console.log(' Database ready')
}

View File

@@ -1051,4 +1051,48 @@ suite('POS', { tags: ['pos'] }, (t) => {
// Cleanup
await t.api.post(`/v1/drawer/${drawer.data.id}/close`, { closingBalance: 100 })
})
// ─── Email Receipt ──────────────────────────────────────────────────────────
t.test('emails a receipt for a completed transaction', { tags: ['transactions', 'email'] }, async () => {
// Create and complete a transaction
const txn = await t.api.post('/v1/transactions', { transactionType: 'sale', locationId: LOCATION_ID })
await t.api.post(`/v1/transactions/${txn.data.id}/line-items`, { description: 'Email Test Item', qty: 1, unitPrice: 25 })
await t.api.post(`/v1/transactions/${txn.data.id}/complete`, { paymentMethod: 'card_present' })
const res = await t.api.post(`/v1/transactions/${txn.data.id}/email-receipt`, { email: 'customer@test.com' })
t.assert.status(res, 200)
t.assert.equal(res.data.message, 'Receipt sent')
t.assert.equal(res.data.sentTo, 'customer@test.com')
})
t.test('rejects email receipt with invalid email', { tags: ['transactions', 'email', 'validation'] }, async () => {
const txn = await t.api.post('/v1/transactions', { transactionType: 'sale', locationId: LOCATION_ID })
await t.api.post(`/v1/transactions/${txn.data.id}/line-items`, { description: 'Bad Email Item', qty: 1, unitPrice: 10 })
await t.api.post(`/v1/transactions/${txn.data.id}/complete`, { paymentMethod: 'card_present' })
const res = await t.api.post(`/v1/transactions/${txn.data.id}/email-receipt`, { email: 'not-an-email' })
t.assert.status(res, 400)
})
t.test('rejects email receipt with missing body', { tags: ['transactions', 'email', 'validation'] }, async () => {
const txn = await t.api.post('/v1/transactions', { transactionType: 'sale', locationId: LOCATION_ID })
await t.api.post(`/v1/transactions/${txn.data.id}/line-items`, { description: 'No Body Item', qty: 1, unitPrice: 10 })
await t.api.post(`/v1/transactions/${txn.data.id}/complete`, { paymentMethod: 'card_present' })
const res = await t.api.post(`/v1/transactions/${txn.data.id}/email-receipt`, {})
t.assert.status(res, 400)
})
t.test('receipt response includes customerEmail', { tags: ['transactions', 'email'] }, async () => {
// Create account with email
const acct = await t.api.post('/v1/accounts', { name: 'Email Customer', email: 'acct@test.com', billingMode: 'consolidated' })
const txn = await t.api.post('/v1/transactions', { transactionType: 'sale', locationId: LOCATION_ID, accountId: acct.data.id })
await t.api.post(`/v1/transactions/${txn.data.id}/line-items`, { description: 'Account Item', qty: 1, unitPrice: 50 })
await t.api.post(`/v1/transactions/${txn.data.id}/complete`, { paymentMethod: 'card_present' })
const receipt = await t.api.get(`/v1/transactions/${txn.data.id}/receipt`)
t.assert.status(receipt, 200)
t.assert.equal(receipt.data.customerEmail, 'acct@test.com')
})
})

View File

@@ -510,4 +510,55 @@ suite('Repairs', { tags: ['repairs'] }, (t) => {
const fileRes = await fetch(`${t.baseUrl}${signedRes.data.url}`)
t.assert.equal(fileRes.status, 200)
})
// ─── Email Estimate ─────────────────────────────────────────────────────────
t.test('emails a repair estimate', { tags: ['tickets', 'email'] }, async () => {
const ticket = await t.api.post('/v1/repair-tickets', {
customerName: 'Email Estimate Customer',
itemDescription: 'Broken Laptop',
problemDescription: 'Won\'t power on',
conditionIn: 'poor',
estimatedCost: 200,
})
await t.api.post(`/v1/repair-tickets/${ticket.data.id}/line-items`, {
itemType: 'labor',
description: 'Diagnostic fee',
qty: 1,
unitPrice: 50,
})
const res = await t.api.post(`/v1/repair-tickets/${ticket.data.id}/email-estimate`, { email: 'customer@test.com' })
t.assert.status(res, 200)
t.assert.equal(res.data.message, 'Estimate sent')
t.assert.equal(res.data.sentTo, 'customer@test.com')
})
t.test('rejects estimate email with invalid email', { tags: ['tickets', 'email', 'validation'] }, async () => {
const ticket = await t.api.post('/v1/repair-tickets', {
customerName: 'Bad Email Customer',
problemDescription: 'Test',
conditionIn: 'good',
})
const res = await t.api.post(`/v1/repair-tickets/${ticket.data.id}/email-estimate`, { email: 'bad' })
t.assert.status(res, 400)
})
t.test('returns 404 for estimate email on nonexistent ticket', { tags: ['tickets', 'email', 'validation'] }, async () => {
const res = await t.api.post('/v1/repair-tickets/00000000-0000-0000-0000-000000000000/email-estimate', { email: 'test@test.com' })
t.assert.status(res, 404)
})
t.test('ticket detail includes customerEmail from account', { tags: ['tickets', 'email'] }, async () => {
const acct = await t.api.post('/v1/accounts', { name: 'Repair Email Acct', email: 'repair@test.com', billingMode: 'consolidated' })
const ticket = await t.api.post('/v1/repair-tickets', {
customerName: 'Repair Email Acct',
accountId: acct.data.id,
problemDescription: 'Email test',
conditionIn: 'good',
})
const detail = await t.api.get(`/v1/repair-tickets/${ticket.data.id}`)
t.assert.status(detail, 200)
t.assert.equal(detail.data.customerEmail, 'repair@test.com')
})
})

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,23 +37,66 @@ 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'
async function seedInitialUser(app: Awaited<ReturnType<typeof buildApp>>) {
const email = process.env.INITIAL_USER_EMAIL
const password = process.env.INITIAL_USER_PASSWORD
const firstName = process.env.INITIAL_USER_FIRST_NAME
const lastName = process.env.INITIAL_USER_LAST_NAME
if (!email || !password || !firstName || !lastName) return
if (!email || !firstName || !lastName) return
const existing = await app.db.select({ id: users.id }).from(users).limit(1)
if (existing.length > 0) return
const passwordHash = await bcrypt.hash(password, 10)
await app.db.insert(users).values({ email, passwordHash, firstName, lastName, role: 'admin' })
// Create user with a random password — they'll set their real one via the welcome email
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
try {
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '4h' })
const appUrl = process.env.APP_URL ?? `https://${process.env.HOSTNAME ?? 'localhost'}`
const resetLink = `${appUrl}/reset-password?token=${resetToken}`
const [store] = await app.db.select({ name: companies.name }).from(companies).limit(1)
const storeName = store?.name ?? process.env.BUSINESS_NAME ?? 'LunarFront'
await EmailService.send(app.db, {
to: email,
subject: `Welcome to ${storeName} — Set your password`,
html: `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px;">
<h2 style="color: #1a1a2e; margin-bottom: 8px;">${storeName}</h2>
<p style="color: #555; margin-bottom: 24px;">Hi ${firstName},</p>
<p style="color: #555;">Your account has been created. Click the button below to set your password and get started:</p>
<div style="text-align: center; margin: 32px 0;">
<a href="${resetLink}" style="background-color: #1a1a2e; color: #fff; padding: 12px 32px; border-radius: 6px; text-decoration: none; font-weight: 500;">Set Your Password</a>
</div>
<p style="color: #888; font-size: 13px;">This link expires in 4 hours. If it expires, you can request a new one from the login page.</p>
<hr style="border: none; border-top: 1px solid #eee; margin: 32px 0;" />
<p style="color: #aaa; font-size: 11px;">Powered by LunarFront</p>
</div>
`,
text: `Hi ${firstName}, welcome to ${storeName}! Set your password here: ${resetLink} — This link expires in 4 hours.`,
})
app.log.info({ email }, 'Welcome email sent to initial user')
} catch (err) {
app.log.error({ email, error: (err as Error).message }, 'Failed to send welcome email — user can use forgot password')
}
}
async function seedEmailSettings(app: Awaited<ReturnType<typeof buildApp>>) {

View File

@@ -1,8 +1,10 @@
import type { FastifyPluginAsync } from 'fastify'
import { eq } from 'drizzle-orm'
import bcrypt from 'bcryptjs'
import { RegisterSchema, LoginSchema, PinLoginSchema, SetPinSchema } from '@lunarfront/shared/schemas'
import { RegisterSchema, LoginSchema, PinLoginSchema, SetPinSchema, ForgotPasswordSchema, ResetPasswordSchema } from '@lunarfront/shared/schemas'
import { users } from '../../db/schema/users.js'
import { companies } from '../../db/schema/stores.js'
import { EmailService } from '../../services/email.service.js'
const SALT_ROUNDS = 10
@@ -151,24 +153,22 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
const [user] = await app.db.select({ id: users.id, email: users.email }).from(users).where(eq(users.id, userId)).limit(1)
if (!user) return reply.status(404).send({ error: { message: 'User not found', statusCode: 404 } })
// Generate a signed reset token that expires in 1 hour
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '1h' })
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '4h' })
const resetLink = `${process.env.APP_URL ?? 'http://localhost:5173'}/reset-password?token=${resetToken}`
request.log.info({ userId, generatedBy: request.user.id }, 'Password reset link generated')
return reply.send({ resetLink, expiresIn: '1 hour' })
return reply.send({ resetLink, expiresIn: '4 hours' })
})
// Reset password with token
app.post('/auth/reset-password', async (request, reply) => {
const { token, newPassword } = request.body as { token?: string; newPassword?: string }
if (!token || !newPassword) {
return reply.status(400).send({ error: { message: 'token and newPassword are required', statusCode: 400 } })
}
if (newPassword.length < 12) {
return reply.status(400).send({ error: { message: 'Password must be at least 12 characters', statusCode: 400 } })
const parsed = ResetPasswordSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const { token, newPassword } = parsed.data
try {
const payload = app.jwt.verify<{ userId: string; purpose: string }>(token)
if (payload.purpose !== 'password-reset') {
@@ -185,6 +185,86 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
}
})
// Forgot password / resend welcome — public, always returns success (no user enumeration)
// Pass ?type=welcome for welcome emails, defaults to reset
app.post('/auth/forgot-password', rateLimitConfig, async (request, reply) => {
const parsed = ForgotPasswordSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const { email } = parsed.data
const isWelcome = (request.query as { type?: string }).type === 'welcome'
// Rate limit per email — max 3 emails per hour
const emailKey = `pwd-reset:${email.toLowerCase()}`
const count = await app.redis.incr(emailKey)
if (count === 1) await app.redis.expire(emailKey, 3600)
if (count > 3) {
return reply.send({ message: 'If an account exists with that email, you will receive an email.' })
}
// Always return success — don't reveal whether the email exists
const [user] = await app.db.select({ id: users.id, firstName: users.firstName }).from(users).where(eq(users.email, email)).limit(1)
if (user) {
try {
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '4h' })
const appUrl = process.env.APP_URL ?? 'http://localhost:5173'
const resetLink = `${appUrl}/reset-password?token=${resetToken}`
const [store] = await app.db.select({ name: companies.name }).from(companies).limit(1)
const storeName = store?.name ?? 'LunarFront'
if (isWelcome) {
await EmailService.send(app.db, {
to: email,
subject: `Welcome to ${storeName} — Set your password`,
html: `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px;">
<h2 style="color: #1a1a2e; margin-bottom: 8px;">${storeName}</h2>
<p style="color: #555; margin-bottom: 24px;">Hi ${user.firstName},</p>
<p style="color: #555;">Your account has been created. Click the button below to set your password and get started:</p>
<div style="text-align: center; margin: 32px 0;">
<a href="${resetLink}" style="background-color: #1a1a2e; color: #fff; padding: 12px 32px; border-radius: 6px; text-decoration: none; font-weight: 500;">Set Your Password</a>
</div>
<p style="color: #888; font-size: 13px;">This link expires in 4 hours. If it expires, you can request a new one from the login page.</p>
<hr style="border: none; border-top: 1px solid #eee; margin: 32px 0;" />
<p style="color: #aaa; font-size: 11px;">Powered by LunarFront</p>
</div>
`,
text: `Hi ${user.firstName}, welcome to ${storeName}! Set your password here: ${resetLink} — This link expires in 4 hours.`,
})
} else {
await EmailService.send(app.db, {
to: email,
subject: `Reset your password — ${storeName}`,
html: `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px;">
<h2 style="color: #1a1a2e; margin-bottom: 8px;">${storeName}</h2>
<p style="color: #555; margin-bottom: 24px;">Hi ${user.firstName},</p>
<p style="color: #555;">We received a request to reset your password. Click the button below to choose a new one:</p>
<div style="text-align: center; margin: 32px 0;">
<a href="${resetLink}" style="background-color: #1a1a2e; color: #fff; padding: 12px 32px; border-radius: 6px; text-decoration: none; font-weight: 500;">Reset Password</a>
</div>
<p style="color: #888; font-size: 13px;">This link expires in 4 hours. If you didn't request this, you can safely ignore this email.</p>
<hr style="border: none; border-top: 1px solid #eee; margin: 32px 0;" />
<p style="color: #aaa; font-size: 11px;">Powered by LunarFront</p>
</div>
`,
text: `Hi ${user.firstName}, reset your password here: ${resetLink} — This link expires in 4 hours.`,
})
}
request.log.info({ userId: user.id, type: isWelcome ? 'welcome' : 'reset' }, 'Password email sent')
} catch (err) {
request.log.error({ email, error: (err as Error).message }, 'Failed to send password email')
}
}
return reply.send({ message: 'If an account exists with that email, you will receive a password reset link.' })
})
// Get current user profile
app.get('/auth/me', { preHandler: [app.authenticate] }, async (request, reply) => {
const [user] = await app.db
@@ -194,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)
@@ -201,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

View File

@@ -13,7 +13,13 @@ import {
RepairServiceTemplateCreateSchema,
RepairServiceTemplateUpdateSchema,
} from '@lunarfront/shared/schemas'
import { eq } from 'drizzle-orm'
import { z } from 'zod'
import { RepairTicketService, RepairLineItemService, RepairBatchService, RepairNoteService, RepairServiceTemplateService } from '../../services/repair.service.js'
import { accounts } from '../../db/schema/accounts.js'
import { companies } from '../../db/schema/stores.js'
import { EmailService } from '../../services/email.service.js'
import { renderEstimateEmailHtml, renderEstimateEmailText } from '../../utils/email-templates.js'
export const repairRoutes: FastifyPluginAsync = async (app) => {
// --- Repair Tickets ---
@@ -59,7 +65,14 @@ export const repairRoutes: FastifyPluginAsync = async (app) => {
const { id } = request.params as { id: string }
const ticket = await RepairTicketService.getById(app.db, id)
if (!ticket) return reply.status(404).send({ error: { message: 'Repair ticket not found', statusCode: 404 } })
return reply.send(ticket)
let customerEmail: string | null = null
if (ticket.accountId) {
const [acct] = await app.db.select({ email: accounts.email }).from(accounts).where(eq(accounts.id, ticket.accountId)).limit(1)
customerEmail = acct?.email ?? null
}
return reply.send({ ...ticket, customerEmail })
})
app.patch('/repair-tickets/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.edit')] }, async (request, reply) => {
@@ -84,6 +97,42 @@ export const repairRoutes: FastifyPluginAsync = async (app) => {
return reply.send(ticket)
})
app.post('/repair-tickets/:id/email-estimate', { preHandler: [app.authenticate, app.requirePermission('repairs.view')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const parsed = z.object({ email: z.string().email() }).safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Valid email is required', statusCode: 400 } })
}
// Rate limit: max 5 emails per ticket per hour
const rateKey = `email-estimate:${id}`
const count = await app.redis.incr(rateKey)
if (count === 1) await app.redis.expire(rateKey, 3600)
if (count > 5) {
return reply.status(429).send({ error: { message: 'Too many emails for this estimate. Try again later.', statusCode: 429 } })
}
const ticket = await RepairTicketService.getById(app.db, id)
if (!ticket) return reply.status(404).send({ error: { message: 'Repair ticket not found', statusCode: 404 } })
const lineItemsResult = await RepairLineItemService.listByTicket(app.db, id, { page: 1, limit: 500 })
const [company] = await app.db.select().from(companies).limit(1)
if (!company) return reply.status(500).send({ error: { message: 'Store not configured', statusCode: 500 } })
const html = renderEstimateEmailHtml(ticket as any, lineItemsResult.data as any[], { name: company.name, phone: company.phone, email: company.email, address: company.address as any })
const text = renderEstimateEmailText(ticket as any, lineItemsResult.data as any[], { name: company.name, phone: company.phone, email: company.email, address: company.address as any })
await EmailService.send(app.db, {
to: parsed.data.email,
subject: `Repair Estimate — Ticket #${ticket.ticketNumber}`,
html,
text,
})
request.log.info({ ticketId: id, email: parsed.data.email, userId: request.user.id }, 'Estimate email sent')
return reply.send({ message: 'Estimate sent', sentTo: parsed.data.email })
})
app.delete('/repair-tickets/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.admin')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const ticket = await RepairTicketService.delete(app.db, id)

View File

@@ -7,7 +7,11 @@ import {
ApplyDiscountSchema,
CompleteTransactionSchema,
} from '@lunarfront/shared/schemas'
import { inArray } from 'drizzle-orm'
import { TransactionService } from '../../services/transaction.service.js'
import { appConfig } from '../../db/schema/stores.js'
import { EmailService } from '../../services/email.service.js'
import { renderReceiptEmailHtml, renderReceiptEmailText } from '../../utils/email-templates.js'
const FromRepairBodySchema = z.object({
locationId: z.string().uuid().optional(),
@@ -64,6 +68,45 @@ export const transactionRoutes: FastifyPluginAsync = async (app) => {
return reply.send(receipt)
})
app.post('/transactions/:id/email-receipt', { preHandler: [app.authenticate, app.requirePermission('pos.view')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const parsed = z.object({ email: z.string().email() }).safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Valid email is required', statusCode: 400 } })
}
// Rate limit: max 5 emails per transaction per hour
const rateKey = `email-receipt:${id}`
const count = await app.redis.incr(rateKey)
if (count === 1) await app.redis.expire(rateKey, 3600)
if (count > 5) {
return reply.status(429).send({ error: { message: 'Too many emails for this receipt. Try again later.', statusCode: 429 } })
}
const receipt = await TransactionService.getReceipt(app.db, id)
const storeName = receipt.company?.name ?? 'Store'
// Fetch receipt config
const configRows = await app.db.select({ key: appConfig.key, value: appConfig.value })
.from(appConfig)
.where(inArray(appConfig.key, ['receipt_header', 'receipt_footer', 'receipt_return_policy', 'receipt_social']))
const config: Record<string, string> = {}
for (const row of configRows) if (row.value) config[row.key] = row.value
const html = renderReceiptEmailHtml(receipt as any, config)
const text = renderReceiptEmailText(receipt as any, config)
await EmailService.send(app.db, {
to: parsed.data.email,
subject: `Your receipt from ${storeName}${receipt.transaction.transactionNumber}`,
html,
text,
})
request.log.info({ transactionId: id, email: parsed.data.email, userId: request.user.id }, 'Receipt email sent')
return reply.send({ message: 'Receipt sent', sentTo: parsed.data.email })
})
app.post('/transactions/:id/line-items', { preHandler: [app.authenticate, app.requirePermission('pos.edit')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const parsed = TransactionLineItemCreateSchema.safeParse(request.body)

View File

@@ -0,0 +1,51 @@
#!/usr/bin/env bun
/**
* Force-reset a user's password from the command line.
*
* Usage:
* bun run packages/backend/src/scripts/reset-password.ts <email> <new-password>
*
* From a customer pod:
* kubectl exec -n customer-tvs deploy/customer-tvs-backend -- \
* bun run src/scripts/reset-password.ts user@example.com NewPassword123!
*/
import postgres from 'postgres'
import { drizzle } from 'drizzle-orm/postgres-js'
import { eq } from 'drizzle-orm'
import bcrypt from 'bcryptjs'
import { users } from '../db/schema/users.js'
const [email, newPassword] = process.argv.slice(2)
if (!email || !newPassword) {
console.error('Usage: bun run reset-password.ts <email> <new-password>')
process.exit(1)
}
if (newPassword.length < 12) {
console.error('Error: Password must be at least 12 characters')
process.exit(1)
}
const databaseUrl = process.env.DATABASE_URL
if (!databaseUrl) {
console.error('Error: DATABASE_URL is not set')
process.exit(1)
}
const sql = postgres(databaseUrl)
const db = drizzle(sql)
const [user] = await db.select({ id: users.id, email: users.email }).from(users).where(eq(users.email, email)).limit(1)
if (!user) {
console.error(`Error: No user found with email "${email}"`)
await sql.end()
process.exit(1)
}
const hash = await bcrypt.hash(newPassword, 10)
await db.update(users).set({ passwordHash: hash, updatedAt: new Date() }).where(eq(users.id, user.id))
console.log(`Password reset for ${email} (user ${user.id})`)
await sql.end()

View File

@@ -87,6 +87,21 @@ class SmtpProvider implements EmailProvider {
}
}
class TestProvider implements EmailProvider {
static lastEmail: SendOpts | null = null
static emails: SendOpts[] = []
async send(opts: SendOpts): Promise<void> {
TestProvider.lastEmail = opts
TestProvider.emails.push(opts)
}
static reset() {
TestProvider.lastEmail = null
TestProvider.emails = []
}
}
export const EmailService = {
async send(db: PostgresJsDatabase<any>, opts: SendOpts): Promise<void> {
const provider = await SettingsService.get(db, 'email.provider')
@@ -99,8 +114,14 @@ export const EmailService = {
return new SendGridProvider(db).send(opts)
case 'smtp':
return new SmtpProvider().send(opts)
case 'test':
return new TestProvider().send(opts)
default:
throw new Error('Email provider not configured. Set email.provider in app_settings.')
}
},
getTestEmails: () => TestProvider.emails,
getLastTestEmail: () => TestProvider.lastEmail,
resetTestEmails: () => TestProvider.reset(),
}

View File

@@ -10,6 +10,7 @@ import {
import { products, inventoryUnits } from '../db/schema/inventory.js'
import { repairTickets, repairLineItems } from '../db/schema/repairs.js'
import { companies, locations } from '../db/schema/stores.js'
import { accounts } from '../db/schema/accounts.js'
import { NotFoundError, ValidationError, ConflictError } from '../lib/errors.js'
import { TaxService } from './tax.service.js'
import type {
@@ -473,8 +474,16 @@ export const TransactionService = {
location = loc ?? null
}
// Resolve customer email from linked account
let customerEmail: string | null = null
if (txn.accountId) {
const [acct] = await db.select({ email: accounts.email }).from(accounts).where(eq(accounts.id, txn.accountId)).limit(1)
customerEmail = acct?.email ?? null
}
return {
transaction: txn,
customerEmail,
company: company
? {
name: company.name,

View File

@@ -0,0 +1,319 @@
/**
* Server-side HTML email template renderers for receipts and repair estimates.
* Uses inline CSS for email-client compatibility.
*/
interface Address {
street?: string
city?: string
state?: string
zip?: string
}
interface CompanyInfo {
name: string
phone?: string | null
email?: string | null
address?: Address | null
}
interface ReceiptLineItem {
description: string
qty: number
unitPrice: string
taxAmount: string
lineTotal: string
discountAmount?: string | null
}
interface ReceiptTransaction {
transactionNumber: string
subtotal: string
discountTotal: string
taxTotal: string
total: string
paymentMethod: string | null
amountTendered: string | null
changeGiven: string | null
roundingAdjustment: string | null
completedAt: string | null
lineItems: ReceiptLineItem[]
}
interface ReceiptConfig {
receipt_header?: string
receipt_footer?: string
receipt_return_policy?: string
receipt_social?: string
}
interface ReceiptData {
transaction: ReceiptTransaction
company: CompanyInfo | null
location: CompanyInfo | null
}
interface RepairLineItem {
itemType: string
description: string
qty: number
unitPrice: string
totalPrice: string
}
interface RepairTicket {
ticketNumber: string
customerName: string
customerPhone?: string | null
itemDescription?: string | null
serialNumber?: string | null
problemDescription?: string | null
estimatedCost?: string | null
promisedDate?: string | null
status: string
}
// ── Shared layout ──────────────────────────────────────────────────────────
function wrapEmailLayout(storeName: string, bodyHtml: string): string {
return `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px; color: #333;">
<h2 style="color: #1a1a2e; margin: 0 0 24px 0; font-size: 20px;">${esc(storeName)}</h2>
${bodyHtml}
<hr style="border: none; border-top: 1px solid #eee; margin: 32px 0;" />
<p style="color: #aaa; font-size: 11px; margin: 0;">Powered by LunarFront</p>
</div>
`
}
function esc(s: string): string {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}
function formatAddress(addr?: Address | null): string {
if (!addr) return ''
const parts = [addr.street, [addr.city, addr.state].filter(Boolean).join(', '), addr.zip].filter(Boolean)
return parts.join('<br />')
}
function formatDate(dateStr: string | null): string {
if (!dateStr) return ''
const d = new Date(dateStr)
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' })
}
function formatDateOnly(dateStr: string | null): string {
if (!dateStr) return ''
const d = new Date(dateStr)
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
}
const PAYMENT_LABELS: Record<string, string> = {
cash: 'Cash',
card_present: 'Card',
card_keyed: 'Card (Keyed)',
check: 'Check',
store_credit: 'Store Credit',
other: 'Other',
}
const TYPE_LABELS: Record<string, string> = {
labor: 'Labor',
part: 'Part',
flat_rate: 'Flat Rate',
misc: 'Misc',
consumable: 'Consumable',
}
// ── Receipt email ──────────────────────────────────────────────────────────
export function renderReceiptEmailHtml(data: ReceiptData, config?: ReceiptConfig): string {
const txn = data.transaction
const storeName = data.company?.name ?? 'Store'
let companyBlock = ''
if (data.company) {
const addr = formatAddress(data.company.address)
companyBlock = `
<div style="font-size: 13px; color: #666; margin-bottom: 16px;">
${addr ? `<div>${addr}</div>` : ''}
${data.company.phone ? `<div>${esc(data.company.phone)}</div>` : ''}
</div>
`
}
const headerText = config?.receipt_header ? `<p style="font-size: 13px; color: #555; margin: 0 0 16px 0;">${esc(config.receipt_header)}</p>` : ''
const lineRows = txn.lineItems.map(item => `
<tr>
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px;">${esc(item.description)}</td>
<td style="padding: 6px 8px; border-bottom: 1px solid #f0f0f0; font-size: 13px; text-align: center;">${item.qty}</td>
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px; text-align: right;">$${item.unitPrice}</td>
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px; text-align: right;">$${item.lineTotal}</td>
</tr>
`).join('')
const discountRow = parseFloat(txn.discountTotal) > 0
? `<tr><td style="padding: 4px 0; font-size: 13px;">Discount</td><td style="padding: 4px 0; font-size: 13px; text-align: right; color: #e57373;">-$${txn.discountTotal}</td></tr>`
: ''
const roundingRow = txn.roundingAdjustment && parseFloat(txn.roundingAdjustment) !== 0
? `<tr><td style="padding: 4px 0; font-size: 13px;">Rounding</td><td style="padding: 4px 0; font-size: 13px; text-align: right;">$${txn.roundingAdjustment}</td></tr>`
: ''
const paymentBlock = txn.paymentMethod ? `
<div style="margin-top: 16px; font-size: 13px; color: #666;">
<div>Paid by: ${PAYMENT_LABELS[txn.paymentMethod] ?? txn.paymentMethod}</div>
${txn.amountTendered && txn.paymentMethod === 'cash' ? `<div>Tendered: $${txn.amountTendered}</div>` : ''}
${txn.changeGiven && parseFloat(txn.changeGiven) > 0 ? `<div>Change: $${txn.changeGiven}</div>` : ''}
</div>
` : ''
const footerText = config?.receipt_footer ? `<p style="font-size: 12px; color: #888; margin: 16px 0 0 0; text-align: center;">${esc(config.receipt_footer)}</p>` : ''
const policyText = config?.receipt_return_policy ? `<p style="font-size: 11px; color: #999; margin: 8px 0 0 0; text-align: center;">${esc(config.receipt_return_policy)}</p>` : ''
const socialText = config?.receipt_social ? `<p style="font-size: 11px; color: #999; margin: 4px 0 0 0; text-align: center;">${esc(config.receipt_social)}</p>` : ''
const body = `
${companyBlock}
${headerText}
<div style="background: #f9f9f9; border-radius: 8px; padding: 16px; margin-bottom: 16px;">
<div style="font-size: 13px; color: #666;">
<strong style="color: #333;">Receipt #${esc(txn.transactionNumber)}</strong><br />
${formatDate(txn.completedAt)}
</div>
</div>
<table style="width: 100%; border-collapse: collapse; margin-bottom: 16px;">
<thead>
<tr style="border-bottom: 2px solid #eee;">
<th style="padding: 6px 0; font-size: 12px; text-align: left; color: #888; font-weight: 600;">Item</th>
<th style="padding: 6px 8px; font-size: 12px; text-align: center; color: #888; font-weight: 600;">Qty</th>
<th style="padding: 6px 0; font-size: 12px; text-align: right; color: #888; font-weight: 600;">Price</th>
<th style="padding: 6px 0; font-size: 12px; text-align: right; color: #888; font-weight: 600;">Total</th>
</tr>
</thead>
<tbody>
${lineRows}
</tbody>
</table>
<table style="width: 50%; margin-left: auto; border-collapse: collapse;">
<tr><td style="padding: 4px 0; font-size: 13px;">Subtotal</td><td style="padding: 4px 0; font-size: 13px; text-align: right;">$${txn.subtotal}</td></tr>
${discountRow}
<tr><td style="padding: 4px 0; font-size: 13px;">Tax</td><td style="padding: 4px 0; font-size: 13px; text-align: right;">$${txn.taxTotal}</td></tr>
${roundingRow}
<tr style="border-top: 2px solid #333;"><td style="padding: 8px 0; font-size: 15px; font-weight: 700;">Total</td><td style="padding: 8px 0; font-size: 15px; font-weight: 700; text-align: right;">$${txn.total}</td></tr>
</table>
${paymentBlock}
${footerText}
${policyText}
${socialText}
`
return wrapEmailLayout(storeName, body)
}
export function renderReceiptEmailText(data: ReceiptData, config?: ReceiptConfig): string {
const txn = data.transaction
const storeName = data.company?.name ?? 'Store'
const lines = [
storeName,
`Receipt #${txn.transactionNumber}`,
formatDate(txn.completedAt),
'',
...txn.lineItems.map(i => `${i.description} x${i.qty}$${i.lineTotal}`),
'',
`Subtotal: $${txn.subtotal}`,
...(parseFloat(txn.discountTotal) > 0 ? [`Discount: -$${txn.discountTotal}`] : []),
`Tax: $${txn.taxTotal}`,
`Total: $${txn.total}`,
'',
...(txn.paymentMethod ? [`Paid by: ${PAYMENT_LABELS[txn.paymentMethod] ?? txn.paymentMethod}`] : []),
...(config?.receipt_footer ? ['', config.receipt_footer] : []),
]
return lines.join('\n')
}
// ── Repair estimate email ──────────────────────────────────────────────────
export function renderEstimateEmailHtml(ticket: RepairTicket, lineItems: RepairLineItem[], company: CompanyInfo): string {
const storeName = company.name
const lineRows = lineItems.map(item => `
<tr>
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px;">${TYPE_LABELS[item.itemType] ?? item.itemType}</td>
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px;">${esc(item.description)}</td>
<td style="padding: 6px 8px; border-bottom: 1px solid #f0f0f0; font-size: 13px; text-align: center;">${item.qty}</td>
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px; text-align: right;">$${item.unitPrice}</td>
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px; text-align: right;">$${item.totalPrice}</td>
</tr>
`).join('')
const estimatedTotal = ticket.estimatedCost
? `<tr style="border-top: 2px solid #333;"><td colspan="4" style="padding: 8px 0; font-size: 15px; font-weight: 700;">Estimated Total</td><td style="padding: 8px 0; font-size: 15px; font-weight: 700; text-align: right;">$${ticket.estimatedCost}</td></tr>`
: ''
const lineItemTotal = lineItems.reduce((sum, i) => sum + parseFloat(i.totalPrice), 0).toFixed(2)
const lineItemTotalRow = !ticket.estimatedCost && lineItems.length > 0
? `<tr style="border-top: 2px solid #333;"><td colspan="4" style="padding: 8px 0; font-size: 15px; font-weight: 700;">Estimated Total</td><td style="padding: 8px 0; font-size: 15px; font-weight: 700; text-align: right;">$${lineItemTotal}</td></tr>`
: ''
const body = `
<div style="background: #f9f9f9; border-radius: 8px; padding: 16px; margin-bottom: 16px;">
<div style="font-size: 13px; color: #666;">
<strong style="color: #333;">Repair Estimate — Ticket #${esc(ticket.ticketNumber)}</strong><br />
${esc(ticket.customerName)}
</div>
</div>
<div style="margin-bottom: 16px; font-size: 13px; color: #555;">
${ticket.itemDescription ? `<div><strong>Item:</strong> ${esc(ticket.itemDescription)}${ticket.serialNumber ? ` (S/N: ${esc(ticket.serialNumber)})` : ''}</div>` : ''}
${ticket.problemDescription ? `<div style="margin-top: 4px;"><strong>Issue:</strong> ${esc(ticket.problemDescription)}</div>` : ''}
${ticket.promisedDate ? `<div style="margin-top: 4px;"><strong>Estimated completion:</strong> ${formatDateOnly(ticket.promisedDate)}</div>` : ''}
</div>
${lineItems.length > 0 ? `
<table style="width: 100%; border-collapse: collapse; margin-bottom: 16px;">
<thead>
<tr style="border-bottom: 2px solid #eee;">
<th style="padding: 6px 0; font-size: 12px; text-align: left; color: #888; font-weight: 600;">Type</th>
<th style="padding: 6px 0; font-size: 12px; text-align: left; color: #888; font-weight: 600;">Description</th>
<th style="padding: 6px 8px; font-size: 12px; text-align: center; color: #888; font-weight: 600;">Qty</th>
<th style="padding: 6px 0; font-size: 12px; text-align: right; color: #888; font-weight: 600;">Price</th>
<th style="padding: 6px 0; font-size: 12px; text-align: right; color: #888; font-weight: 600;">Total</th>
</tr>
</thead>
<tbody>
${lineRows}
${estimatedTotal}
${lineItemTotalRow}
</tbody>
</table>
` : `
${ticket.estimatedCost ? `<div style="font-size: 15px; font-weight: 700; margin-bottom: 16px;">Estimated Cost: $${ticket.estimatedCost}</div>` : ''}
`}
<p style="font-size: 12px; color: #888;">This is an estimate and the final cost may vary. Please contact us with any questions.</p>
${company.phone ? `<p style="font-size: 12px; color: #888; margin-top: 4px;">Phone: ${esc(company.phone)}</p>` : ''}
`
return wrapEmailLayout(storeName, body)
}
export function renderEstimateEmailText(ticket: RepairTicket, lineItems: RepairLineItem[], company: CompanyInfo): string {
const lines = [
company.name,
`Repair Estimate — Ticket #${ticket.ticketNumber}`,
`Customer: ${ticket.customerName}`,
'',
...(ticket.itemDescription ? [`Item: ${ticket.itemDescription}${ticket.serialNumber ? ` (S/N: ${ticket.serialNumber})` : ''}`] : []),
...(ticket.problemDescription ? [`Issue: ${ticket.problemDescription}`] : []),
...(ticket.promisedDate ? [`Estimated completion: ${formatDateOnly(ticket.promisedDate)}`] : []),
'',
...lineItems.map(i => `${TYPE_LABELS[i.itemType] ?? i.itemType}: ${i.description} x${i.qty}$${i.totalPrice}`),
'',
...(ticket.estimatedCost ? [`Estimated Total: $${ticket.estimatedCost}`] : []),
'',
'This is an estimate and the final cost may vary.',
...(company.phone ? [`Phone: ${company.phone}`] : []),
]
return lines.join('\n')
}

View File

@@ -27,3 +27,14 @@ export const SetPinSchema = z.object({
pin: z.string().min(4).max(6).regex(/^\d+$/, 'PIN must be digits only'),
})
export type SetPinInput = z.infer<typeof SetPinSchema>
export const ForgotPasswordSchema = z.object({
email: z.string().email(),
})
export type ForgotPasswordInput = z.infer<typeof ForgotPasswordSchema>
export const ResetPasswordSchema = z.object({
token: z.string().min(1),
newPassword: z.string().min(12, 'Password must be at least 12 characters').max(128),
})
export type ResetPasswordInput = z.infer<typeof ResetPasswordSchema>

View File

@@ -1,8 +1,8 @@
export { PaginationSchema } from './pagination.schema.js'
export type { PaginationInput, PaginatedResponse } from './pagination.schema.js'
export { UserRole, RegisterSchema, LoginSchema, PinLoginSchema, SetPinSchema } from './auth.schema.js'
export type { RegisterInput, LoginInput, PinLoginInput, SetPinInput } from './auth.schema.js'
export { UserRole, RegisterSchema, LoginSchema, PinLoginSchema, SetPinSchema, ForgotPasswordSchema, ResetPasswordSchema } from './auth.schema.js'
export type { RegisterInput, LoginInput, PinLoginInput, SetPinInput, ForgotPasswordInput, ResetPasswordInput } from './auth.schema.js'
export {
BillingMode,