Add repairs domain with tickets, line items, batches, and service templates

Full-stack implementation of instrument repair tracking: DB schema with
repair_ticket, repair_line_item, repair_batch, and repair_service_template
tables. Backend services and routes with pagination/search/sort. 20 API
tests covering CRUD, status workflow, line items, and batch operations.
Admin frontend with ticket list, detail with status progression, line item
management, batch list/detail with approval workflow, and new ticket form
with searchable account picker and intake photo uploads.
This commit is contained in:
Ryan Moon
2026-03-29 09:12:40 -05:00
parent 1d48f0befa
commit f17bbff02c
20 changed files with 2791 additions and 1 deletions

View File

@@ -0,0 +1,103 @@
import { queryOptions } from '@tanstack/react-query'
import { api } from '@/lib/api-client'
import type { RepairTicket, RepairLineItem, RepairBatch } from '@/types/repair'
import type { PaginatedResponse, PaginationInput } from '@forte/shared/schemas'
// --- Repair Tickets ---
export const repairTicketKeys = {
all: ['repair-tickets'] as const,
list: (params: PaginationInput) => [...repairTicketKeys.all, 'list', params] as const,
detail: (id: string) => [...repairTicketKeys.all, 'detail', id] as const,
}
export function repairTicketListOptions(params: PaginationInput) {
return queryOptions({
queryKey: repairTicketKeys.list(params),
queryFn: () => api.get<PaginatedResponse<RepairTicket>>('/v1/repair-tickets', params),
})
}
export function repairTicketDetailOptions(id: string) {
return queryOptions({
queryKey: repairTicketKeys.detail(id),
queryFn: () => api.get<RepairTicket>(`/v1/repair-tickets/${id}`),
})
}
export const repairTicketMutations = {
create: (data: Record<string, unknown>) =>
api.post<RepairTicket>('/v1/repair-tickets', data),
update: (id: string, data: Record<string, unknown>) =>
api.patch<RepairTicket>(`/v1/repair-tickets/${id}`, data),
updateStatus: (id: string, status: string) =>
api.post<RepairTicket>(`/v1/repair-tickets/${id}/status`, { status }),
delete: (id: string) =>
api.del<RepairTicket>(`/v1/repair-tickets/${id}`),
}
// --- Repair Line Items ---
export const repairLineItemKeys = {
all: (ticketId: string) => ['repair-tickets', ticketId, 'line-items'] as const,
list: (ticketId: string, params: PaginationInput) => [...repairLineItemKeys.all(ticketId), params] as const,
}
export function repairLineItemListOptions(ticketId: string, params: PaginationInput) {
return queryOptions({
queryKey: repairLineItemKeys.list(ticketId, params),
queryFn: () => api.get<PaginatedResponse<RepairLineItem>>(`/v1/repair-tickets/${ticketId}/line-items`, params),
})
}
export const repairLineItemMutations = {
create: (ticketId: string, data: Record<string, unknown>) =>
api.post<RepairLineItem>(`/v1/repair-tickets/${ticketId}/line-items`, data),
update: (id: string, data: Record<string, unknown>) =>
api.patch<RepairLineItem>(`/v1/repair-line-items/${id}`, data),
delete: (id: string) =>
api.del<RepairLineItem>(`/v1/repair-line-items/${id}`),
}
// --- Repair Batches ---
export const repairBatchKeys = {
all: ['repair-batches'] as const,
list: (params: PaginationInput) => [...repairBatchKeys.all, 'list', params] as const,
detail: (id: string) => [...repairBatchKeys.all, 'detail', id] as const,
tickets: (batchId: string, params: PaginationInput) => [...repairBatchKeys.all, batchId, 'tickets', params] as const,
}
export function repairBatchListOptions(params: PaginationInput) {
return queryOptions({
queryKey: repairBatchKeys.list(params),
queryFn: () => api.get<PaginatedResponse<RepairBatch>>('/v1/repair-batches', params),
})
}
export function repairBatchDetailOptions(id: string) {
return queryOptions({
queryKey: repairBatchKeys.detail(id),
queryFn: () => api.get<RepairBatch>(`/v1/repair-batches/${id}`),
})
}
export function repairBatchTicketsOptions(batchId: string, params: PaginationInput) {
return queryOptions({
queryKey: repairBatchKeys.tickets(batchId, params),
queryFn: () => api.get<PaginatedResponse<RepairTicket>>(`/v1/repair-batches/${batchId}/tickets`, params),
})
}
export const repairBatchMutations = {
create: (data: Record<string, unknown>) =>
api.post<RepairBatch>('/v1/repair-batches', data),
update: (id: string, data: Record<string, unknown>) =>
api.patch<RepairBatch>(`/v1/repair-batches/${id}`, data),
updateStatus: (id: string, status: string) =>
api.post<RepairBatch>(`/v1/repair-batches/${id}/status`, { status }),
approve: (id: string) =>
api.post<RepairBatch>(`/v1/repair-batches/${id}/approve`, {}),
reject: (id: string) =>
api.post<RepairBatch>(`/v1/repair-batches/${id}/reject`, {}),
}

View File

@@ -16,10 +16,16 @@ import { Route as AuthenticatedUsersRouteImport } from './routes/_authenticated/
import { Route as AuthenticatedProfileRouteImport } from './routes/_authenticated/profile' import { Route as AuthenticatedProfileRouteImport } from './routes/_authenticated/profile'
import { Route as AuthenticatedHelpRouteImport } from './routes/_authenticated/help' import { Route as AuthenticatedHelpRouteImport } from './routes/_authenticated/help'
import { Route as AuthenticatedRolesIndexRouteImport } from './routes/_authenticated/roles/index' import { Route as AuthenticatedRolesIndexRouteImport } from './routes/_authenticated/roles/index'
import { Route as AuthenticatedRepairsIndexRouteImport } from './routes/_authenticated/repairs/index'
import { Route as AuthenticatedRepairBatchesIndexRouteImport } from './routes/_authenticated/repair-batches/index'
import { Route as AuthenticatedMembersIndexRouteImport } from './routes/_authenticated/members/index' import { Route as AuthenticatedMembersIndexRouteImport } from './routes/_authenticated/members/index'
import { Route as AuthenticatedAccountsIndexRouteImport } from './routes/_authenticated/accounts/index' import { Route as AuthenticatedAccountsIndexRouteImport } from './routes/_authenticated/accounts/index'
import { Route as AuthenticatedRolesNewRouteImport } from './routes/_authenticated/roles/new' import { Route as AuthenticatedRolesNewRouteImport } from './routes/_authenticated/roles/new'
import { Route as AuthenticatedRolesRoleIdRouteImport } from './routes/_authenticated/roles/$roleId' import { Route as AuthenticatedRolesRoleIdRouteImport } from './routes/_authenticated/roles/$roleId'
import { Route as AuthenticatedRepairsNewRouteImport } from './routes/_authenticated/repairs/new'
import { Route as AuthenticatedRepairsTicketIdRouteImport } from './routes/_authenticated/repairs/$ticketId'
import { Route as AuthenticatedRepairBatchesNewRouteImport } from './routes/_authenticated/repair-batches/new'
import { Route as AuthenticatedRepairBatchesBatchIdRouteImport } from './routes/_authenticated/repair-batches/$batchId'
import { Route as AuthenticatedMembersMemberIdRouteImport } from './routes/_authenticated/members/$memberId' import { Route as AuthenticatedMembersMemberIdRouteImport } from './routes/_authenticated/members/$memberId'
import { Route as AuthenticatedAccountsNewRouteImport } from './routes/_authenticated/accounts/new' import { Route as AuthenticatedAccountsNewRouteImport } from './routes/_authenticated/accounts/new'
import { Route as AuthenticatedAccountsAccountIdRouteImport } from './routes/_authenticated/accounts/$accountId' import { Route as AuthenticatedAccountsAccountIdRouteImport } from './routes/_authenticated/accounts/$accountId'
@@ -63,6 +69,18 @@ const AuthenticatedRolesIndexRoute = AuthenticatedRolesIndexRouteImport.update({
path: '/roles/', path: '/roles/',
getParentRoute: () => AuthenticatedRoute, getParentRoute: () => AuthenticatedRoute,
} as any) } as any)
const AuthenticatedRepairsIndexRoute =
AuthenticatedRepairsIndexRouteImport.update({
id: '/repairs/',
path: '/repairs/',
getParentRoute: () => AuthenticatedRoute,
} as any)
const AuthenticatedRepairBatchesIndexRoute =
AuthenticatedRepairBatchesIndexRouteImport.update({
id: '/repair-batches/',
path: '/repair-batches/',
getParentRoute: () => AuthenticatedRoute,
} as any)
const AuthenticatedMembersIndexRoute = const AuthenticatedMembersIndexRoute =
AuthenticatedMembersIndexRouteImport.update({ AuthenticatedMembersIndexRouteImport.update({
id: '/members/', id: '/members/',
@@ -86,6 +104,29 @@ const AuthenticatedRolesRoleIdRoute =
path: '/roles/$roleId', path: '/roles/$roleId',
getParentRoute: () => AuthenticatedRoute, getParentRoute: () => AuthenticatedRoute,
} as any) } as any)
const AuthenticatedRepairsNewRoute = AuthenticatedRepairsNewRouteImport.update({
id: '/repairs/new',
path: '/repairs/new',
getParentRoute: () => AuthenticatedRoute,
} as any)
const AuthenticatedRepairsTicketIdRoute =
AuthenticatedRepairsTicketIdRouteImport.update({
id: '/repairs/$ticketId',
path: '/repairs/$ticketId',
getParentRoute: () => AuthenticatedRoute,
} as any)
const AuthenticatedRepairBatchesNewRoute =
AuthenticatedRepairBatchesNewRouteImport.update({
id: '/repair-batches/new',
path: '/repair-batches/new',
getParentRoute: () => AuthenticatedRoute,
} as any)
const AuthenticatedRepairBatchesBatchIdRoute =
AuthenticatedRepairBatchesBatchIdRouteImport.update({
id: '/repair-batches/$batchId',
path: '/repair-batches/$batchId',
getParentRoute: () => AuthenticatedRoute,
} as any)
const AuthenticatedMembersMemberIdRoute = const AuthenticatedMembersMemberIdRoute =
AuthenticatedMembersMemberIdRouteImport.update({ AuthenticatedMembersMemberIdRouteImport.update({
id: '/members/$memberId', id: '/members/$memberId',
@@ -144,10 +185,16 @@ export interface FileRoutesByFullPath {
'/accounts/$accountId': typeof AuthenticatedAccountsAccountIdRouteWithChildren '/accounts/$accountId': typeof AuthenticatedAccountsAccountIdRouteWithChildren
'/accounts/new': typeof AuthenticatedAccountsNewRoute '/accounts/new': typeof AuthenticatedAccountsNewRoute
'/members/$memberId': typeof AuthenticatedMembersMemberIdRoute '/members/$memberId': typeof AuthenticatedMembersMemberIdRoute
'/repair-batches/$batchId': typeof AuthenticatedRepairBatchesBatchIdRoute
'/repair-batches/new': typeof AuthenticatedRepairBatchesNewRoute
'/repairs/$ticketId': typeof AuthenticatedRepairsTicketIdRoute
'/repairs/new': typeof AuthenticatedRepairsNewRoute
'/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute '/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
'/roles/new': typeof AuthenticatedRolesNewRoute '/roles/new': typeof AuthenticatedRolesNewRoute
'/accounts/': typeof AuthenticatedAccountsIndexRoute '/accounts/': typeof AuthenticatedAccountsIndexRoute
'/members/': typeof AuthenticatedMembersIndexRoute '/members/': typeof AuthenticatedMembersIndexRoute
'/repair-batches/': typeof AuthenticatedRepairBatchesIndexRoute
'/repairs/': typeof AuthenticatedRepairsIndexRoute
'/roles/': typeof AuthenticatedRolesIndexRoute '/roles/': typeof AuthenticatedRolesIndexRoute
'/accounts/$accountId/members': typeof AuthenticatedAccountsAccountIdMembersRoute '/accounts/$accountId/members': typeof AuthenticatedAccountsAccountIdMembersRoute
'/accounts/$accountId/payment-methods': typeof AuthenticatedAccountsAccountIdPaymentMethodsRoute '/accounts/$accountId/payment-methods': typeof AuthenticatedAccountsAccountIdPaymentMethodsRoute
@@ -163,10 +210,16 @@ export interface FileRoutesByTo {
'/': typeof AuthenticatedIndexRoute '/': typeof AuthenticatedIndexRoute
'/accounts/new': typeof AuthenticatedAccountsNewRoute '/accounts/new': typeof AuthenticatedAccountsNewRoute
'/members/$memberId': typeof AuthenticatedMembersMemberIdRoute '/members/$memberId': typeof AuthenticatedMembersMemberIdRoute
'/repair-batches/$batchId': typeof AuthenticatedRepairBatchesBatchIdRoute
'/repair-batches/new': typeof AuthenticatedRepairBatchesNewRoute
'/repairs/$ticketId': typeof AuthenticatedRepairsTicketIdRoute
'/repairs/new': typeof AuthenticatedRepairsNewRoute
'/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute '/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
'/roles/new': typeof AuthenticatedRolesNewRoute '/roles/new': typeof AuthenticatedRolesNewRoute
'/accounts': typeof AuthenticatedAccountsIndexRoute '/accounts': typeof AuthenticatedAccountsIndexRoute
'/members': typeof AuthenticatedMembersIndexRoute '/members': typeof AuthenticatedMembersIndexRoute
'/repair-batches': typeof AuthenticatedRepairBatchesIndexRoute
'/repairs': typeof AuthenticatedRepairsIndexRoute
'/roles': typeof AuthenticatedRolesIndexRoute '/roles': typeof AuthenticatedRolesIndexRoute
'/accounts/$accountId/members': typeof AuthenticatedAccountsAccountIdMembersRoute '/accounts/$accountId/members': typeof AuthenticatedAccountsAccountIdMembersRoute
'/accounts/$accountId/payment-methods': typeof AuthenticatedAccountsAccountIdPaymentMethodsRoute '/accounts/$accountId/payment-methods': typeof AuthenticatedAccountsAccountIdPaymentMethodsRoute
@@ -185,10 +238,16 @@ export interface FileRoutesById {
'/_authenticated/accounts/$accountId': typeof AuthenticatedAccountsAccountIdRouteWithChildren '/_authenticated/accounts/$accountId': typeof AuthenticatedAccountsAccountIdRouteWithChildren
'/_authenticated/accounts/new': typeof AuthenticatedAccountsNewRoute '/_authenticated/accounts/new': typeof AuthenticatedAccountsNewRoute
'/_authenticated/members/$memberId': typeof AuthenticatedMembersMemberIdRoute '/_authenticated/members/$memberId': typeof AuthenticatedMembersMemberIdRoute
'/_authenticated/repair-batches/$batchId': typeof AuthenticatedRepairBatchesBatchIdRoute
'/_authenticated/repair-batches/new': typeof AuthenticatedRepairBatchesNewRoute
'/_authenticated/repairs/$ticketId': typeof AuthenticatedRepairsTicketIdRoute
'/_authenticated/repairs/new': typeof AuthenticatedRepairsNewRoute
'/_authenticated/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute '/_authenticated/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
'/_authenticated/roles/new': typeof AuthenticatedRolesNewRoute '/_authenticated/roles/new': typeof AuthenticatedRolesNewRoute
'/_authenticated/accounts/': typeof AuthenticatedAccountsIndexRoute '/_authenticated/accounts/': typeof AuthenticatedAccountsIndexRoute
'/_authenticated/members/': typeof AuthenticatedMembersIndexRoute '/_authenticated/members/': typeof AuthenticatedMembersIndexRoute
'/_authenticated/repair-batches/': typeof AuthenticatedRepairBatchesIndexRoute
'/_authenticated/repairs/': typeof AuthenticatedRepairsIndexRoute
'/_authenticated/roles/': typeof AuthenticatedRolesIndexRoute '/_authenticated/roles/': typeof AuthenticatedRolesIndexRoute
'/_authenticated/accounts/$accountId/members': typeof AuthenticatedAccountsAccountIdMembersRoute '/_authenticated/accounts/$accountId/members': typeof AuthenticatedAccountsAccountIdMembersRoute
'/_authenticated/accounts/$accountId/payment-methods': typeof AuthenticatedAccountsAccountIdPaymentMethodsRoute '/_authenticated/accounts/$accountId/payment-methods': typeof AuthenticatedAccountsAccountIdPaymentMethodsRoute
@@ -207,10 +266,16 @@ export interface FileRouteTypes {
| '/accounts/$accountId' | '/accounts/$accountId'
| '/accounts/new' | '/accounts/new'
| '/members/$memberId' | '/members/$memberId'
| '/repair-batches/$batchId'
| '/repair-batches/new'
| '/repairs/$ticketId'
| '/repairs/new'
| '/roles/$roleId' | '/roles/$roleId'
| '/roles/new' | '/roles/new'
| '/accounts/' | '/accounts/'
| '/members/' | '/members/'
| '/repair-batches/'
| '/repairs/'
| '/roles/' | '/roles/'
| '/accounts/$accountId/members' | '/accounts/$accountId/members'
| '/accounts/$accountId/payment-methods' | '/accounts/$accountId/payment-methods'
@@ -226,10 +291,16 @@ export interface FileRouteTypes {
| '/' | '/'
| '/accounts/new' | '/accounts/new'
| '/members/$memberId' | '/members/$memberId'
| '/repair-batches/$batchId'
| '/repair-batches/new'
| '/repairs/$ticketId'
| '/repairs/new'
| '/roles/$roleId' | '/roles/$roleId'
| '/roles/new' | '/roles/new'
| '/accounts' | '/accounts'
| '/members' | '/members'
| '/repair-batches'
| '/repairs'
| '/roles' | '/roles'
| '/accounts/$accountId/members' | '/accounts/$accountId/members'
| '/accounts/$accountId/payment-methods' | '/accounts/$accountId/payment-methods'
@@ -247,10 +318,16 @@ export interface FileRouteTypes {
| '/_authenticated/accounts/$accountId' | '/_authenticated/accounts/$accountId'
| '/_authenticated/accounts/new' | '/_authenticated/accounts/new'
| '/_authenticated/members/$memberId' | '/_authenticated/members/$memberId'
| '/_authenticated/repair-batches/$batchId'
| '/_authenticated/repair-batches/new'
| '/_authenticated/repairs/$ticketId'
| '/_authenticated/repairs/new'
| '/_authenticated/roles/$roleId' | '/_authenticated/roles/$roleId'
| '/_authenticated/roles/new' | '/_authenticated/roles/new'
| '/_authenticated/accounts/' | '/_authenticated/accounts/'
| '/_authenticated/members/' | '/_authenticated/members/'
| '/_authenticated/repair-batches/'
| '/_authenticated/repairs/'
| '/_authenticated/roles/' | '/_authenticated/roles/'
| '/_authenticated/accounts/$accountId/members' | '/_authenticated/accounts/$accountId/members'
| '/_authenticated/accounts/$accountId/payment-methods' | '/_authenticated/accounts/$accountId/payment-methods'
@@ -315,6 +392,20 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedRolesIndexRouteImport preLoaderRoute: typeof AuthenticatedRolesIndexRouteImport
parentRoute: typeof AuthenticatedRoute parentRoute: typeof AuthenticatedRoute
} }
'/_authenticated/repairs/': {
id: '/_authenticated/repairs/'
path: '/repairs'
fullPath: '/repairs/'
preLoaderRoute: typeof AuthenticatedRepairsIndexRouteImport
parentRoute: typeof AuthenticatedRoute
}
'/_authenticated/repair-batches/': {
id: '/_authenticated/repair-batches/'
path: '/repair-batches'
fullPath: '/repair-batches/'
preLoaderRoute: typeof AuthenticatedRepairBatchesIndexRouteImport
parentRoute: typeof AuthenticatedRoute
}
'/_authenticated/members/': { '/_authenticated/members/': {
id: '/_authenticated/members/' id: '/_authenticated/members/'
path: '/members' path: '/members'
@@ -343,6 +434,34 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedRolesRoleIdRouteImport preLoaderRoute: typeof AuthenticatedRolesRoleIdRouteImport
parentRoute: typeof AuthenticatedRoute parentRoute: typeof AuthenticatedRoute
} }
'/_authenticated/repairs/new': {
id: '/_authenticated/repairs/new'
path: '/repairs/new'
fullPath: '/repairs/new'
preLoaderRoute: typeof AuthenticatedRepairsNewRouteImport
parentRoute: typeof AuthenticatedRoute
}
'/_authenticated/repairs/$ticketId': {
id: '/_authenticated/repairs/$ticketId'
path: '/repairs/$ticketId'
fullPath: '/repairs/$ticketId'
preLoaderRoute: typeof AuthenticatedRepairsTicketIdRouteImport
parentRoute: typeof AuthenticatedRoute
}
'/_authenticated/repair-batches/new': {
id: '/_authenticated/repair-batches/new'
path: '/repair-batches/new'
fullPath: '/repair-batches/new'
preLoaderRoute: typeof AuthenticatedRepairBatchesNewRouteImport
parentRoute: typeof AuthenticatedRoute
}
'/_authenticated/repair-batches/$batchId': {
id: '/_authenticated/repair-batches/$batchId'
path: '/repair-batches/$batchId'
fullPath: '/repair-batches/$batchId'
preLoaderRoute: typeof AuthenticatedRepairBatchesBatchIdRouteImport
parentRoute: typeof AuthenticatedRoute
}
'/_authenticated/members/$memberId': { '/_authenticated/members/$memberId': {
id: '/_authenticated/members/$memberId' id: '/_authenticated/members/$memberId'
path: '/members/$memberId' path: '/members/$memberId'
@@ -437,10 +556,16 @@ interface AuthenticatedRouteChildren {
AuthenticatedAccountsAccountIdRoute: typeof AuthenticatedAccountsAccountIdRouteWithChildren AuthenticatedAccountsAccountIdRoute: typeof AuthenticatedAccountsAccountIdRouteWithChildren
AuthenticatedAccountsNewRoute: typeof AuthenticatedAccountsNewRoute AuthenticatedAccountsNewRoute: typeof AuthenticatedAccountsNewRoute
AuthenticatedMembersMemberIdRoute: typeof AuthenticatedMembersMemberIdRoute AuthenticatedMembersMemberIdRoute: typeof AuthenticatedMembersMemberIdRoute
AuthenticatedRepairBatchesBatchIdRoute: typeof AuthenticatedRepairBatchesBatchIdRoute
AuthenticatedRepairBatchesNewRoute: typeof AuthenticatedRepairBatchesNewRoute
AuthenticatedRepairsTicketIdRoute: typeof AuthenticatedRepairsTicketIdRoute
AuthenticatedRepairsNewRoute: typeof AuthenticatedRepairsNewRoute
AuthenticatedRolesRoleIdRoute: typeof AuthenticatedRolesRoleIdRoute AuthenticatedRolesRoleIdRoute: typeof AuthenticatedRolesRoleIdRoute
AuthenticatedRolesNewRoute: typeof AuthenticatedRolesNewRoute AuthenticatedRolesNewRoute: typeof AuthenticatedRolesNewRoute
AuthenticatedAccountsIndexRoute: typeof AuthenticatedAccountsIndexRoute AuthenticatedAccountsIndexRoute: typeof AuthenticatedAccountsIndexRoute
AuthenticatedMembersIndexRoute: typeof AuthenticatedMembersIndexRoute AuthenticatedMembersIndexRoute: typeof AuthenticatedMembersIndexRoute
AuthenticatedRepairBatchesIndexRoute: typeof AuthenticatedRepairBatchesIndexRoute
AuthenticatedRepairsIndexRoute: typeof AuthenticatedRepairsIndexRoute
AuthenticatedRolesIndexRoute: typeof AuthenticatedRolesIndexRoute AuthenticatedRolesIndexRoute: typeof AuthenticatedRolesIndexRoute
} }
@@ -453,10 +578,17 @@ const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
AuthenticatedAccountsAccountIdRouteWithChildren, AuthenticatedAccountsAccountIdRouteWithChildren,
AuthenticatedAccountsNewRoute: AuthenticatedAccountsNewRoute, AuthenticatedAccountsNewRoute: AuthenticatedAccountsNewRoute,
AuthenticatedMembersMemberIdRoute: AuthenticatedMembersMemberIdRoute, AuthenticatedMembersMemberIdRoute: AuthenticatedMembersMemberIdRoute,
AuthenticatedRepairBatchesBatchIdRoute:
AuthenticatedRepairBatchesBatchIdRoute,
AuthenticatedRepairBatchesNewRoute: AuthenticatedRepairBatchesNewRoute,
AuthenticatedRepairsTicketIdRoute: AuthenticatedRepairsTicketIdRoute,
AuthenticatedRepairsNewRoute: AuthenticatedRepairsNewRoute,
AuthenticatedRolesRoleIdRoute: AuthenticatedRolesRoleIdRoute, AuthenticatedRolesRoleIdRoute: AuthenticatedRolesRoleIdRoute,
AuthenticatedRolesNewRoute: AuthenticatedRolesNewRoute, AuthenticatedRolesNewRoute: AuthenticatedRolesNewRoute,
AuthenticatedAccountsIndexRoute: AuthenticatedAccountsIndexRoute, AuthenticatedAccountsIndexRoute: AuthenticatedAccountsIndexRoute,
AuthenticatedMembersIndexRoute: AuthenticatedMembersIndexRoute, AuthenticatedMembersIndexRoute: AuthenticatedMembersIndexRoute,
AuthenticatedRepairBatchesIndexRoute: AuthenticatedRepairBatchesIndexRoute,
AuthenticatedRepairsIndexRoute: AuthenticatedRepairsIndexRoute,
AuthenticatedRolesIndexRoute: AuthenticatedRolesIndexRoute, AuthenticatedRolesIndexRoute: AuthenticatedRolesIndexRoute,
} }

View File

@@ -5,7 +5,7 @@ import { useAuthStore } from '@/stores/auth.store'
import { myPermissionsOptions } from '@/api/rbac' import { myPermissionsOptions } from '@/api/rbac'
import { Avatar } from '@/components/shared/avatar-upload' import { Avatar } from '@/components/shared/avatar-upload'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Users, UserRound, HelpCircle, Shield, UserCog, LogOut, User } from 'lucide-react' import { Users, UserRound, HelpCircle, Shield, UserCog, LogOut, User, Wrench, Package } from 'lucide-react'
export const Route = createFileRoute('/_authenticated')({ export const Route = createFileRoute('/_authenticated')({
beforeLoad: () => { beforeLoad: () => {
@@ -57,6 +57,7 @@ function AuthenticatedLayout() {
} }
const canViewAccounts = !permissionsLoaded || hasPermission('accounts.view') const canViewAccounts = !permissionsLoaded || hasPermission('accounts.view')
const canViewRepairs = !permissionsLoaded || hasPermission('repairs.view')
const canViewUsers = !permissionsLoaded || hasPermission('users.view') const canViewUsers = !permissionsLoaded || hasPermission('users.view')
return ( return (
@@ -77,6 +78,12 @@ function AuthenticatedLayout() {
<NavLink to="/members" icon={<UserRound className="h-4 w-4" />} label="Members" /> <NavLink to="/members" icon={<UserRound className="h-4 w-4" />} label="Members" />
</> </>
)} )}
{canViewRepairs && (
<>
<NavLink to="/repairs" icon={<Wrench className="h-4 w-4" />} label="Repairs" />
<NavLink to="/repair-batches" icon={<Package className="h-4 w-4" />} label="Repair Batches" />
</>
)}
{canViewUsers && ( {canViewUsers && (
<div className="mt-4 mb-1 px-3"> <div className="mt-4 mb-1 px-3">
<span className="text-xs font-semibold text-sidebar-foreground/50 uppercase tracking-wide">Admin</span> <span className="text-xs font-semibold text-sidebar-foreground/50 uppercase tracking-wide">Admin</span>

View File

@@ -0,0 +1,160 @@
import { createFileRoute, useParams, useNavigate } from '@tanstack/react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { repairBatchDetailOptions, repairBatchMutations, repairBatchKeys, repairBatchTicketsOptions } from '@/api/repairs'
import { usePagination } from '@/hooks/use-pagination'
import { DataTable, type Column } from '@/components/shared/data-table'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { ArrowLeft, Check, X } from 'lucide-react'
import { toast } from 'sonner'
import { useAuthStore } from '@/stores/auth.store'
import type { RepairTicket } from '@/types/repair'
export const Route = createFileRoute('/_authenticated/repair-batches/$batchId')({
validateSearch: (search: Record<string, unknown>) => ({
page: Number(search.page) || 1,
limit: Number(search.limit) || 25,
q: (search.q as string) || undefined,
sort: (search.sort as string) || undefined,
order: (search.order as 'asc' | 'desc') || 'asc',
}),
component: RepairBatchDetailPage,
})
const ticketColumns: Column<RepairTicket>[] = [
{ key: 'ticket_number', header: 'Ticket #', sortable: true, render: (t) => <span className="font-mono text-sm">{t.ticketNumber}</span> },
{ key: 'customer_name', header: 'Instrument', render: (t) => <>{t.instrumentDescription ?? '-'}</> },
{ key: 'status', header: 'Status', sortable: true, render: (t) => <Badge variant="outline">{t.status.replace('_', ' ')}</Badge> },
{ key: 'problem', header: 'Problem', render: (t) => <span className="truncate max-w-[200px] block">{t.problemDescription}</span> },
]
function RepairBatchDetailPage() {
const { batchId } = useParams({ from: '/_authenticated/repair-batches/$batchId' })
const navigate = useNavigate()
const queryClient = useQueryClient()
const hasPermission = useAuthStore((s) => s.hasPermission)
const { params, setPage, setSort } = usePagination()
const { data: batch, isLoading } = useQuery(repairBatchDetailOptions(batchId))
const { data: ticketsData, isLoading: ticketsLoading } = useQuery(repairBatchTicketsOptions(batchId, params))
const approveMutation = useMutation({
mutationFn: () => repairBatchMutations.approve(batchId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repairBatchKeys.detail(batchId) })
toast.success('Batch approved')
},
onError: (err) => toast.error(err.message),
})
const rejectMutation = useMutation({
mutationFn: () => repairBatchMutations.reject(batchId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repairBatchKeys.detail(batchId) })
toast.success('Batch rejected')
},
onError: (err) => toast.error(err.message),
})
const statusMutation = useMutation({
mutationFn: (status: string) => repairBatchMutations.updateStatus(batchId, status),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repairBatchKeys.detail(batchId) })
toast.success('Status updated')
},
onError: (err) => toast.error(err.message),
})
if (isLoading) {
return <div className="space-y-4"><Skeleton className="h-8 w-48" /><Skeleton className="h-64 w-full" /></div>
}
if (!batch) {
return <p className="text-muted-foreground">Batch not found</p>
}
function handleTicketClick(ticket: RepairTicket) {
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: {} as any })
}
return (
<div className="space-y-6 max-w-4xl">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repair-batches', search: {} as any })}>
<ArrowLeft className="h-4 w-4" />
</Button>
<div className="flex-1">
<h1 className="text-2xl font-bold">Batch #{batch.batchNumber}</h1>
<p className="text-sm text-muted-foreground">{batch.contactName ?? 'No contact'}</p>
</div>
<Badge variant="outline" className="text-sm px-3 py-1">{batch.status.replace('_', ' ')}</Badge>
<Badge variant={batch.approvalStatus === 'approved' ? 'default' : batch.approvalStatus === 'rejected' ? 'destructive' : 'secondary'} className="text-sm px-3 py-1">
{batch.approvalStatus}
</Badge>
</div>
{/* Actions */}
<div className="flex gap-2">
{hasPermission('repairs.admin') && batch.approvalStatus === 'pending' && (
<>
<Button onClick={() => approveMutation.mutate()} disabled={approveMutation.isPending}>
<Check className="mr-2 h-4 w-4" />Approve
</Button>
<Button variant="destructive" onClick={() => rejectMutation.mutate()} disabled={rejectMutation.isPending}>
<X className="mr-2 h-4 w-4" />Reject
</Button>
</>
)}
{hasPermission('repairs.edit') && batch.status === 'intake' && (
<Button variant="secondary" onClick={() => statusMutation.mutate('in_progress')}>Start Work</Button>
)}
{hasPermission('repairs.edit') && batch.status === 'in_progress' && (
<Button variant="secondary" onClick={() => statusMutation.mutate('completed')}>Mark Completed</Button>
)}
</div>
{/* Batch Info */}
<div className="grid grid-cols-2 gap-6">
<Card>
<CardHeader><CardTitle className="text-lg">Contact</CardTitle></CardHeader>
<CardContent className="space-y-2 text-sm">
<div><span className="text-muted-foreground">Name:</span> {batch.contactName ?? '-'}</div>
<div><span className="text-muted-foreground">Phone:</span> {batch.contactPhone ?? '-'}</div>
<div><span className="text-muted-foreground">Email:</span> {batch.contactEmail ?? '-'}</div>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="text-lg">Details</CardTitle></CardHeader>
<CardContent className="space-y-2 text-sm">
<div><span className="text-muted-foreground">Instruments:</span> {batch.receivedCount}/{batch.instrumentCount}</div>
<div><span className="text-muted-foreground">Due:</span> {batch.dueDate ? new Date(batch.dueDate).toLocaleDateString() : '-'}</div>
<div><span className="text-muted-foreground">Estimated Total:</span> {batch.estimatedTotal ? `$${batch.estimatedTotal}` : '-'}</div>
{batch.notes && <div><span className="text-muted-foreground">Notes:</span> {batch.notes}</div>}
</CardContent>
</Card>
</div>
{/* Tickets in batch */}
<Card>
<CardHeader><CardTitle className="text-lg">Tickets ({ticketsData?.pagination.total ?? 0})</CardTitle></CardHeader>
<CardContent>
<DataTable
columns={ticketColumns}
data={ticketsData?.data ?? []}
loading={ticketsLoading}
page={params.page}
totalPages={ticketsData?.pagination.totalPages ?? 1}
total={ticketsData?.pagination.total ?? 0}
sort={params.sort}
order={params.order}
onPageChange={setPage}
onSort={setSort}
onRowClick={handleTicketClick}
/>
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,121 @@
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { repairBatchListOptions } from '@/api/repairs'
import { usePagination } from '@/hooks/use-pagination'
import { DataTable, type Column } from '@/components/shared/data-table'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Plus, Search } from 'lucide-react'
import { useAuthStore } from '@/stores/auth.store'
import type { RepairBatch } from '@/types/repair'
export const Route = createFileRoute('/_authenticated/repair-batches/')({
validateSearch: (search: Record<string, unknown>) => ({
page: Number(search.page) || 1,
limit: Number(search.limit) || 25,
q: (search.q as string) || undefined,
sort: (search.sort as string) || undefined,
order: (search.order as 'asc' | 'desc') || 'desc',
}),
component: RepairBatchesListPage,
})
const columns: Column<RepairBatch>[] = [
{
key: 'batch_number',
header: 'Batch #',
sortable: true,
render: (b) => <span className="font-mono text-sm">{b.batchNumber ?? '-'}</span>,
},
{
key: 'contact',
header: 'Contact',
render: (b) => <span className="font-medium">{b.contactName ?? '-'}</span>,
},
{
key: 'status',
header: 'Status',
sortable: true,
render: (b) => <Badge variant="outline">{b.status.replace('_', ' ')}</Badge>,
},
{
key: 'approval',
header: 'Approval',
render: (b) => {
const v = b.approvalStatus === 'approved' ? 'default' : b.approvalStatus === 'rejected' ? 'destructive' : 'secondary'
return <Badge variant={v}>{b.approvalStatus}</Badge>
},
},
{
key: 'instruments',
header: 'Instruments',
render: (b) => <>{b.receivedCount}/{b.instrumentCount}</>,
},
{
key: 'due_date',
header: 'Due',
sortable: true,
render: (b) => <>{b.dueDate ? new Date(b.dueDate).toLocaleDateString() : '-'}</>,
},
]
function RepairBatchesListPage() {
const navigate = useNavigate()
const hasPermission = useAuthStore((s) => s.hasPermission)
const { params, setPage, setSearch, setSort } = usePagination()
const [searchInput, setSearchInput] = useState(params.q ?? '')
const { data, isLoading } = useQuery(repairBatchListOptions(params))
function handleSearchSubmit(e: React.FormEvent) {
e.preventDefault()
setSearch(searchInput)
}
function handleRowClick(batch: RepairBatch) {
navigate({ to: '/repair-batches/$batchId', params: { batchId: batch.id }, search: {} as any })
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Repair Batches</h1>
{hasPermission('repairs.edit') && (
<Button onClick={() => navigate({ to: '/repair-batches/new' })}>
<Plus className="mr-2 h-4 w-4" />
New Batch
</Button>
)}
</div>
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search batches..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
className="pl-9"
/>
</div>
<Button type="submit" variant="secondary">Search</Button>
</form>
<DataTable
columns={columns}
data={data?.data ?? []}
loading={isLoading}
page={params.page}
totalPages={data?.pagination.totalPages ?? 1}
total={data?.pagination.total ?? 0}
sort={params.sort}
order={params.order}
onPageChange={setPage}
onSort={setSort}
onRowClick={handleRowClick}
/>
</div>
)
}

View File

@@ -0,0 +1,124 @@
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useQuery, useMutation } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { RepairBatchCreateSchema } from '@forte/shared/schemas'
import { repairBatchMutations } from '@/api/repairs'
import { accountListOptions } from '@/api/accounts'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { ArrowLeft } from 'lucide-react'
import { toast } from 'sonner'
export const Route = createFileRoute('/_authenticated/repair-batches/new')({
component: NewRepairBatchPage,
})
function NewRepairBatchPage() {
const navigate = useNavigate()
const { data: accountsData } = useQuery(accountListOptions({ page: 1, limit: 100, order: 'asc', sort: 'name' }))
const {
register,
handleSubmit,
setValue,
formState: { errors },
} = useForm({
resolver: zodResolver(RepairBatchCreateSchema),
defaultValues: {
accountId: '',
contactName: '',
contactPhone: '',
contactEmail: '',
instrumentCount: 0,
notes: '',
},
})
const mutation = useMutation({
mutationFn: repairBatchMutations.create,
onSuccess: (batch) => {
toast.success('Repair batch created')
navigate({ to: '/repair-batches/$batchId', params: { batchId: batch.id }, search: {} as any })
},
onError: (err) => toast.error(err.message),
})
const accounts = accountsData?.data ?? []
return (
<div className="space-y-6 max-w-2xl">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repair-batches', search: {} as any })}>
<ArrowLeft className="h-4 w-4" />
</Button>
<h1 className="text-2xl font-bold">New Repair Batch</h1>
</div>
<Card>
<CardHeader>
<CardTitle className="text-lg">Batch Details</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit((data) => mutation.mutate(data))} className="space-y-4">
<div className="space-y-2">
<Label>Account (School) *</Label>
<Select onValueChange={(v) => setValue('accountId', v)}>
<SelectTrigger>
<SelectValue placeholder="Select account" />
</SelectTrigger>
<SelectContent>
{accounts.map((a: { id: string; name: string }) => (
<SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
))}
</SelectContent>
</Select>
{errors.accountId && <p className="text-sm text-destructive">{errors.accountId.message}</p>}
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Contact Name</Label>
<Input {...register('contactName')} />
</div>
<div className="space-y-2">
<Label>Contact Phone</Label>
<Input {...register('contactPhone')} />
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Contact Email</Label>
<Input type="email" {...register('contactEmail')} />
</div>
<div className="space-y-2">
<Label>Instrument Count</Label>
<Input type="number" {...register('instrumentCount', { valueAsNumber: true })} />
</div>
</div>
<div className="space-y-2">
<Label>Notes</Label>
<Textarea {...register('notes')} rows={3} placeholder="e.g. Annual instrument checkup for band program" />
</div>
<div className="flex gap-2">
<Button type="submit" disabled={mutation.isPending}>
{mutation.isPending ? 'Creating...' : 'Create Batch'}
</Button>
<Button variant="secondary" type="button" onClick={() => navigate({ to: '/repair-batches', search: {} as any })}>
Cancel
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,284 @@
import { useState } from 'react'
import { createFileRoute, useParams, useNavigate } from '@tanstack/react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { repairTicketDetailOptions, repairTicketMutations, repairTicketKeys, repairLineItemListOptions, repairLineItemMutations, repairLineItemKeys } from '@/api/repairs'
import { usePagination } from '@/hooks/use-pagination'
import { DataTable, type Column } from '@/components/shared/data-table'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
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 } from 'lucide-react'
import { toast } from 'sonner'
import { useAuthStore } from '@/stores/auth.store'
import type { RepairLineItem } from '@/types/repair'
export const Route = createFileRoute('/_authenticated/repairs/$ticketId')({
validateSearch: (search: Record<string, unknown>) => ({
page: Number(search.page) || 1,
limit: Number(search.limit) || 25,
q: (search.q as string) || undefined,
sort: (search.sort as string) || undefined,
order: (search.order as 'asc' | 'desc') || 'asc',
}),
component: RepairTicketDetailPage,
})
const STATUS_LABELS: Record<string, string> = {
intake: 'Intake',
diagnosing: 'Diagnosing',
pending_approval: 'Pending Approval',
approved: 'Approved',
in_progress: 'In Progress',
pending_parts: 'Pending Parts',
ready: 'Ready for Pickup',
picked_up: 'Picked Up',
delivered: 'Delivered',
cancelled: 'Cancelled',
}
const STATUS_FLOW = ['intake', 'diagnosing', 'pending_approval', 'approved', 'in_progress', 'ready', 'picked_up']
function RepairTicketDetailPage() {
const { ticketId } = useParams({ from: '/_authenticated/repairs/$ticketId' })
const navigate = useNavigate()
const queryClient = useQueryClient()
const hasPermission = useAuthStore((s) => s.hasPermission)
const [addItemOpen, setAddItemOpen] = useState(false)
const { params, setPage, setSort } = usePagination()
const { data: ticket, isLoading } = useQuery(repairTicketDetailOptions(ticketId))
const { data: lineItemsData, isLoading: itemsLoading } = useQuery(repairLineItemListOptions(ticketId, params))
const statusMutation = useMutation({
mutationFn: (status: string) => repairTicketMutations.updateStatus(ticketId, status),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repairTicketKeys.detail(ticketId) })
toast.success('Status updated')
},
onError: (err) => toast.error(err.message),
})
const deleteItemMutation = useMutation({
mutationFn: repairLineItemMutations.delete,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repairLineItemKeys.all(ticketId) })
toast.success('Line item removed')
},
onError: (err) => toast.error(err.message),
})
if (isLoading) {
return (
<div className="space-y-4">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-64 w-full" />
</div>
)
}
if (!ticket) {
return <p className="text-muted-foreground">Repair ticket not found</p>
}
const currentIdx = STATUS_FLOW.indexOf(ticket.status)
const nextStatus = currentIdx >= 0 && currentIdx < STATUS_FLOW.length - 1 ? STATUS_FLOW[currentIdx + 1] : null
const lineItemColumns: Column<RepairLineItem>[] = [
{
key: 'item_type',
header: 'Type',
sortable: true,
render: (i) => <Badge variant="outline">{i.itemType.replace('_', ' ')}</Badge>,
},
{ key: 'description', header: 'Description', render: (i) => <>{i.description}</> },
{ key: 'qty', header: 'Qty', render: (i) => <>{i.qty}</> },
{ key: 'unit_price', header: 'Unit Price', render: (i) => <>${i.unitPrice}</> },
{ key: 'total_price', header: 'Total', render: (i) => <span className="font-medium">${i.totalPrice}</span> },
{
key: 'actions',
header: '',
render: (i) => hasPermission('repairs.admin') ? (
<Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); deleteItemMutation.mutate(i.id) }}>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
) : null,
},
]
return (
<div className="space-y-6 max-w-4xl">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repairs', search: {} as any })}>
<ArrowLeft className="h-4 w-4" />
</Button>
<div className="flex-1">
<h1 className="text-2xl font-bold">Ticket #{ticket.ticketNumber}</h1>
<p className="text-sm text-muted-foreground">{ticket.customerName}</p>
</div>
<Badge variant={ticket.status === 'cancelled' ? 'destructive' : 'default'} className="text-sm px-3 py-1">
{STATUS_LABELS[ticket.status]}
</Badge>
</div>
{/* Status Actions */}
{hasPermission('repairs.edit') && ticket.status !== 'cancelled' && ticket.status !== 'picked_up' && ticket.status !== 'delivered' && (
<div className="flex gap-2">
{nextStatus && (
<Button onClick={() => statusMutation.mutate(nextStatus)} disabled={statusMutation.isPending}>
Move to {STATUS_LABELS[nextStatus]}
</Button>
)}
{ticket.status === 'in_progress' && (
<Button variant="secondary" onClick={() => statusMutation.mutate('pending_parts')} disabled={statusMutation.isPending}>
Pending Parts
</Button>
)}
{hasPermission('repairs.admin') && (
<Button variant="destructive" onClick={() => statusMutation.mutate('cancelled')} disabled={statusMutation.isPending}>
Cancel
</Button>
)}
</div>
)}
{/* Ticket Details */}
<div className="grid grid-cols-2 gap-6">
<Card>
<CardHeader><CardTitle className="text-lg">Customer</CardTitle></CardHeader>
<CardContent className="space-y-2 text-sm">
<div><span className="text-muted-foreground">Name:</span> {ticket.customerName}</div>
<div><span className="text-muted-foreground">Phone:</span> {ticket.customerPhone ?? '-'}</div>
<div><span className="text-muted-foreground">Account:</span> {ticket.accountId ?? 'Walk-in'}</div>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="text-lg">Instrument</CardTitle></CardHeader>
<CardContent className="space-y-2 text-sm">
<div><span className="text-muted-foreground">Description:</span> {ticket.instrumentDescription ?? '-'}</div>
<div><span className="text-muted-foreground">Serial:</span> {ticket.serialNumber ?? '-'}</div>
<div><span className="text-muted-foreground">Condition:</span> {ticket.conditionIn ?? '-'}</div>
</CardContent>
</Card>
</div>
<Card>
<CardHeader><CardTitle className="text-lg">Problem & Notes</CardTitle></CardHeader>
<CardContent className="space-y-2 text-sm">
<div><span className="text-muted-foreground">Problem:</span> {ticket.problemDescription}</div>
{ticket.conditionInNotes && <div><span className="text-muted-foreground">Condition Notes:</span> {ticket.conditionInNotes}</div>}
{ticket.technicianNotes && <div><span className="text-muted-foreground">Tech Notes:</span> {ticket.technicianNotes}</div>}
<div className="flex gap-6 pt-2">
<div><span className="text-muted-foreground">Estimate:</span> {ticket.estimatedCost ? `$${ticket.estimatedCost}` : '-'}</div>
<div><span className="text-muted-foreground">Actual:</span> {ticket.actualCost ? `$${ticket.actualCost}` : '-'}</div>
<div><span className="text-muted-foreground">Promised:</span> {ticket.promisedDate ? new Date(ticket.promisedDate).toLocaleDateString() : '-'}</div>
</div>
</CardContent>
</Card>
{/* Line Items */}
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="text-lg">Line Items</CardTitle>
{hasPermission('repairs.edit') && (
<AddLineItemDialog ticketId={ticketId} open={addItemOpen} onOpenChange={setAddItemOpen} />
)}
</CardHeader>
<CardContent>
<DataTable
columns={lineItemColumns}
data={lineItemsData?.data ?? []}
loading={itemsLoading}
page={params.page}
totalPages={lineItemsData?.pagination.totalPages ?? 1}
total={lineItemsData?.pagination.total ?? 0}
sort={params.sort}
order={params.order}
onPageChange={setPage}
onSort={setSort}
/>
</CardContent>
</Card>
</div>
)
}
function AddLineItemDialog({ ticketId, open, onOpenChange }: { ticketId: string; open: boolean; onOpenChange: (open: boolean) => void }) {
const queryClient = useQueryClient()
const [itemType, setItemType] = useState('labor')
const [description, setDescription] = useState('')
const [qty, setQty] = useState('1')
const [unitPrice, setUnitPrice] = useState('0')
const mutation = useMutation({
mutationFn: (data: Record<string, unknown>) => repairLineItemMutations.create(ticketId, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repairLineItemKeys.all(ticketId) })
toast.success('Line item added')
onOpenChange(false)
setDescription('')
setQty('1')
setUnitPrice('0')
},
onError: (err) => toast.error(err.message),
})
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
const q = parseFloat(qty) || 1
const up = parseFloat(unitPrice) || 0
mutation.mutate({
itemType,
description,
qty: q,
unitPrice: up,
totalPrice: q * up,
})
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogTrigger asChild>
<Button size="sm"><Plus className="mr-2 h-4 w-4" />Add Item</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader><DialogTitle>Add Line Item</DialogTitle></DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label>Type</Label>
<Select value={itemType} onValueChange={setItemType}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="labor">Labor</SelectItem>
<SelectItem value="part">Part</SelectItem>
<SelectItem value="flat_rate">Flat Rate</SelectItem>
<SelectItem value="misc">Misc</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Description *</Label>
<Input value={description} onChange={(e) => setDescription(e.target.value)} required />
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Qty</Label>
<Input type="number" step="0.001" value={qty} onChange={(e) => setQty(e.target.value)} />
</div>
<div className="space-y-2">
<Label>Unit Price</Label>
<Input type="number" step="0.01" value={unitPrice} onChange={(e) => setUnitPrice(e.target.value)} />
</div>
</div>
<Button type="submit" disabled={mutation.isPending}>
{mutation.isPending ? 'Adding...' : 'Add'}
</Button>
</form>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,153 @@
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { repairTicketListOptions } from '@/api/repairs'
import { usePagination } from '@/hooks/use-pagination'
import { DataTable, type Column } from '@/components/shared/data-table'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Plus, Search } from 'lucide-react'
import { useAuthStore } from '@/stores/auth.store'
import type { RepairTicket } from '@/types/repair'
export const Route = createFileRoute('/_authenticated/repairs/')({
validateSearch: (search: Record<string, unknown>) => ({
page: Number(search.page) || 1,
limit: Number(search.limit) || 25,
q: (search.q as string) || undefined,
sort: (search.sort as string) || undefined,
order: (search.order as 'asc' | 'desc') || 'desc',
}),
component: RepairsListPage,
})
function statusBadge(status: string) {
const variants: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
intake: 'outline',
diagnosing: 'secondary',
pending_approval: 'secondary',
approved: 'default',
in_progress: 'default',
pending_parts: 'secondary',
ready: 'default',
picked_up: 'outline',
delivered: 'outline',
cancelled: 'destructive',
}
const labels: Record<string, string> = {
intake: 'Intake',
diagnosing: 'Diagnosing',
pending_approval: 'Pending Approval',
approved: 'Approved',
in_progress: 'In Progress',
pending_parts: 'Pending Parts',
ready: 'Ready',
picked_up: 'Picked Up',
delivered: 'Delivered',
cancelled: 'Cancelled',
}
return <Badge variant={variants[status] ?? 'outline'}>{labels[status] ?? status}</Badge>
}
const columns: Column<RepairTicket>[] = [
{
key: 'ticket_number',
header: 'Ticket #',
sortable: true,
render: (t) => <span className="font-mono text-sm">{t.ticketNumber ?? '-'}</span>,
},
{
key: 'customer_name',
header: 'Customer',
sortable: true,
render: (t) => <span className="font-medium">{t.customerName}</span>,
},
{
key: 'instrument',
header: 'Instrument',
render: (t) => <>{t.instrumentDescription ?? '-'}</>,
},
{
key: 'status',
header: 'Status',
sortable: true,
render: (t) => statusBadge(t.status),
},
{
key: 'intake_date',
header: 'Intake',
sortable: true,
render: (t) => <>{new Date(t.intakeDate).toLocaleDateString()}</>,
},
{
key: 'promised_date',
header: 'Promised',
sortable: true,
render: (t) => <>{t.promisedDate ? new Date(t.promisedDate).toLocaleDateString() : '-'}</>,
},
{
key: 'estimated_cost',
header: 'Estimate',
render: (t) => <>{t.estimatedCost ? `$${t.estimatedCost}` : '-'}</>,
},
]
function RepairsListPage() {
const navigate = useNavigate()
const hasPermission = useAuthStore((s) => s.hasPermission)
const { params, setPage, setSearch, setSort } = usePagination()
const [searchInput, setSearchInput] = useState(params.q ?? '')
const { data, isLoading } = useQuery(repairTicketListOptions(params))
function handleSearchSubmit(e: React.FormEvent) {
e.preventDefault()
setSearch(searchInput)
}
function handleRowClick(ticket: RepairTicket) {
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: {} as any })
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Repairs</h1>
{hasPermission('repairs.edit') && (
<Button onClick={() => navigate({ to: '/repairs/new' })}>
<Plus className="mr-2 h-4 w-4" />
New Repair
</Button>
)}
</div>
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search repairs..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
className="pl-9"
/>
</div>
<Button type="submit" variant="secondary">Search</Button>
</form>
<DataTable
columns={columns}
data={data?.data ?? []}
loading={isLoading}
page={params.page}
totalPages={data?.pagination.totalPages ?? 1}
total={data?.pagination.total ?? 0}
sort={params.sort}
order={params.order}
onPageChange={setPage}
onSort={setSort}
onRowClick={handleRowClick}
/>
</div>
)
}

View File

@@ -0,0 +1,314 @@
import { useState, useRef } from 'react'
import { createFileRoute, useNavigate, Link } from '@tanstack/react-router'
import { useQuery, useMutation } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { RepairTicketCreateSchema } from '@forte/shared/schemas'
import { repairTicketMutations } from '@/api/repairs'
import { accountListOptions } from '@/api/accounts'
import { useAuthStore } from '@/stores/auth.store'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { ArrowLeft, Search, Plus, Upload, X, ImageIcon } from 'lucide-react'
import { toast } from 'sonner'
import type { Account } from '@/types/account'
export const Route = createFileRoute('/_authenticated/repairs/new')({
component: NewRepairPage,
})
function NewRepairPage() {
const navigate = useNavigate()
const token = useAuthStore((s) => s.token)
// Account search
const [accountSearch, setAccountSearch] = useState('')
const [selectedAccount, setSelectedAccount] = useState<Account | null>(null)
const [showAccountDropdown, setShowAccountDropdown] = useState(false)
// Photos
const [photos, setPhotos] = useState<File[]>([])
const photoInputRef = useRef<HTMLInputElement>(null)
const { data: accountsData } = useQuery(
accountListOptions({ page: 1, limit: 20, q: accountSearch || undefined, order: 'asc', sort: 'name' }),
)
const {
register,
handleSubmit,
setValue,
watch,
formState: { errors },
} = useForm({
resolver: zodResolver(RepairTicketCreateSchema),
defaultValues: {
customerName: '',
customerPhone: '',
instrumentDescription: '',
serialNumber: '',
problemDescription: '',
conditionIn: undefined,
estimatedCost: undefined,
accountId: undefined,
},
})
const mutation = useMutation({
mutationFn: async (data: Record<string, unknown>) => {
const ticket = await repairTicketMutations.create(data)
// Upload photos after ticket creation
for (const photo of photos) {
const formData = new FormData()
formData.append('file', photo)
formData.append('entityType', 'repair_ticket')
formData.append('entityId', ticket.id)
formData.append('category', 'intake')
await fetch('/v1/files', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: formData,
})
}
return ticket
},
onSuccess: (ticket) => {
toast.success('Repair ticket created')
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: {} as any })
},
onError: (err) => toast.error(err.message),
})
function selectAccount(account: Account) {
setSelectedAccount(account)
setShowAccountDropdown(false)
setAccountSearch('')
setValue('accountId', account.id)
setValue('customerName', account.name)
setValue('customerPhone', account.phone ?? '')
}
function clearAccount() {
setSelectedAccount(null)
setValue('accountId', undefined)
setValue('customerName', '')
setValue('customerPhone', '')
}
function addPhotos(e: React.ChangeEvent<HTMLInputElement>) {
const files = Array.from(e.target.files ?? [])
setPhotos((prev) => [...prev, ...files])
e.target.value = ''
}
function removePhoto(index: number) {
setPhotos((prev) => prev.filter((_, i) => i !== index))
}
const accounts = accountsData?.data ?? []
return (
<div className="space-y-6 max-w-4xl">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repairs', search: {} as any })}>
<ArrowLeft className="h-4 w-4" />
</Button>
<h1 className="text-2xl font-bold">New Repair Ticket</h1>
</div>
<form onSubmit={handleSubmit((data) => mutation.mutate(data))} className="space-y-6">
{/* Customer Section */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="text-lg">Customer</CardTitle>
<Link to="/accounts/new" className="text-sm text-primary hover:underline flex items-center gap-1">
<Plus className="h-3 w-3" />
New Account
</Link>
</div>
</CardHeader>
<CardContent className="space-y-4">
{/* Account search */}
{!selectedAccount ? (
<div className="relative">
<Label>Search Account</Label>
<div className="relative mt-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Type to search accounts..."
value={accountSearch}
onChange={(e) => {
setAccountSearch(e.target.value)
setShowAccountDropdown(true)
}}
onFocus={() => setShowAccountDropdown(true)}
className="pl-9"
/>
</div>
{showAccountDropdown && accountSearch.length > 0 && (
<div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-60 overflow-auto">
{accounts.length === 0 ? (
<div className="p-3 text-sm text-muted-foreground">No accounts found</div>
) : (
accounts.map((a) => (
<button
key={a.id}
type="button"
className="w-full text-left px-3 py-2 text-sm hover:bg-accent flex items-center justify-between"
onClick={() => selectAccount(a)}
>
<div>
<span className="font-medium">{a.name}</span>
{a.phone && <span className="text-muted-foreground ml-2">{a.phone}</span>}
</div>
{a.accountNumber && <span className="text-xs text-muted-foreground font-mono">#{a.accountNumber}</span>}
</button>
))
)}
</div>
)}
<p className="text-xs text-muted-foreground mt-1">Or fill in customer details manually below for walk-ins</p>
</div>
) : (
<div className="flex items-center justify-between p-3 rounded-md border bg-muted/30">
<div>
<p className="font-medium">{selectedAccount.name}</p>
<div className="flex gap-4 text-sm text-muted-foreground">
{selectedAccount.phone && <span>{selectedAccount.phone}</span>}
{selectedAccount.email && <span>{selectedAccount.email}</span>}
{selectedAccount.accountNumber && <span className="font-mono">#{selectedAccount.accountNumber}</span>}
</div>
</div>
<Button type="button" variant="ghost" size="sm" onClick={clearAccount}>
<X className="h-4 w-4" />
</Button>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Customer Name *</Label>
<Input {...register('customerName')} />
{errors.customerName && <p className="text-sm text-destructive">{errors.customerName.message}</p>}
</div>
<div className="space-y-2">
<Label>Phone</Label>
<Input {...register('customerPhone')} />
</div>
</div>
</CardContent>
</Card>
{/* Instrument Section */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Instrument</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Instrument Description</Label>
<Input {...register('instrumentDescription')} placeholder="e.g. Yamaha Trumpet YTR-2330" />
</div>
<div className="space-y-2">
<Label>Serial Number</Label>
<Input {...register('serialNumber')} />
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Condition at Intake</Label>
<Select onValueChange={(v) => setValue('conditionIn', v as any)}>
<SelectTrigger>
<SelectValue placeholder="Select condition" />
</SelectTrigger>
<SelectContent>
<SelectItem value="excellent">Excellent</SelectItem>
<SelectItem value="good">Good</SelectItem>
<SelectItem value="fair">Fair</SelectItem>
<SelectItem value="poor">Poor</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Estimated Cost</Label>
<Input type="number" step="0.01" {...register('estimatedCost', { valueAsNumber: true })} />
</div>
</div>
<div className="space-y-2">
<Label>Problem Description *</Label>
<Textarea {...register('problemDescription')} rows={3} placeholder="Describe the issue..." />
{errors.problemDescription && <p className="text-sm text-destructive">{errors.problemDescription.message}</p>}
</div>
</CardContent>
</Card>
{/* Photos Section */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Intake Photos</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<p className="text-sm text-muted-foreground">Optional document instrument condition at intake</p>
<div className="flex flex-wrap gap-3">
{photos.map((photo, i) => (
<div key={i} className="relative group">
<img
src={URL.createObjectURL(photo)}
alt={`Intake photo ${i + 1}`}
className="h-24 w-24 object-cover rounded-md border"
/>
<button
type="button"
className="absolute -top-2 -right-2 h-5 w-5 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
onClick={() => removePhoto(i)}
>
<X className="h-3 w-3" />
</button>
</div>
))}
<button
type="button"
className="h-24 w-24 rounded-md border-2 border-dashed border-muted-foreground/30 flex flex-col items-center justify-center text-muted-foreground hover:border-primary hover:text-primary transition-colors"
onClick={() => photoInputRef.current?.click()}
>
<ImageIcon className="h-6 w-6 mb-1" />
<span className="text-xs">Add Photo</span>
</button>
</div>
<input
ref={photoInputRef}
type="file"
accept="image/jpeg,image/png,image/webp"
multiple
className="hidden"
onChange={addPhotos}
/>
</CardContent>
</Card>
{/* Submit */}
<div className="flex gap-2">
<Button type="submit" disabled={mutation.isPending} size="lg">
{mutation.isPending ? 'Creating...' : 'Create Ticket'}
</Button>
<Button variant="secondary" type="button" size="lg" onClick={() => navigate({ to: '/repairs', search: {} as any })}>
Cancel
</Button>
</div>
</form>
</div>
)
}

View File

@@ -0,0 +1,68 @@
export interface RepairTicket {
id: string
companyId: string
locationId: string | null
repairBatchId: string | null
ticketNumber: string | null
accountId: string | null
customerName: string
customerPhone: string | null
inventoryUnitId: string | null
instrumentDescription: string | null
serialNumber: string | null
conditionIn: 'excellent' | 'good' | 'fair' | 'poor' | null
conditionInNotes: string | null
problemDescription: string
technicianNotes: string | null
status: 'intake' | 'diagnosing' | 'pending_approval' | 'approved' | 'in_progress' | 'pending_parts' | 'ready' | 'picked_up' | 'delivered' | 'cancelled'
assignedTechnicianId: string | null
estimatedCost: string | null
actualCost: string | null
intakeDate: string
promisedDate: string | null
completedDate: string | null
legacyId: string | null
createdAt: string
updatedAt: string
}
export interface RepairLineItem {
id: string
repairTicketId: string
itemType: 'labor' | 'part' | 'flat_rate' | 'misc'
description: string
productId: string | null
qty: string
unitPrice: string
totalPrice: string
cost: string | null
technicianId: string | null
createdAt: string
}
export interface RepairBatch {
id: string
companyId: string
locationId: string | null
batchNumber: string | null
accountId: string
contactName: string | null
contactPhone: string | null
contactEmail: string | null
status: 'intake' | 'in_progress' | 'pending_approval' | 'approved' | 'completed' | 'delivered' | 'cancelled'
approvalStatus: 'pending' | 'approved' | 'rejected'
approvedBy: string | null
approvedAt: string | null
pickupDate: string | null
dueDate: string | null
completedDate: string | null
deliveredDate: string | null
instrumentCount: number
receivedCount: number
estimatedTotal: string | null
actualTotal: string | null
notes: string | null
legacyId: string | null
createdAt: string
updatedAt: string
}

View File

@@ -0,0 +1,265 @@
import { suite } from '../lib/context.js'
suite('Repairs', { tags: ['repairs', 'crud'] }, (t) => {
// --- Repair Tickets ---
t.test('creates a repair ticket (walk-in)', { tags: ['tickets', 'create'] }, async () => {
const res = await t.api.post('/v1/repair-tickets', {
customerName: 'Walk-In Customer',
customerPhone: '555-0100',
instrumentDescription: 'Yamaha Trumpet',
problemDescription: 'Stuck valve, needs cleaning',
conditionIn: 'fair',
})
t.assert.status(res, 201)
t.assert.equal(res.data.customerName, 'Walk-In Customer')
t.assert.equal(res.data.status, 'intake')
t.assert.ok(res.data.ticketNumber, 'should auto-generate ticket number')
t.assert.equal(res.data.ticketNumber.length, 6)
t.assert.ok(res.data.id)
})
t.test('creates a repair ticket with account link', { tags: ['tickets', 'create'] }, async () => {
const acct = await t.api.post('/v1/accounts', { name: 'Repair Customer', billingMode: 'consolidated' })
t.assert.status(acct, 201)
const res = await t.api.post('/v1/repair-tickets', {
customerName: 'Repair Customer',
accountId: acct.data.id,
problemDescription: 'Broken bridge on violin',
instrumentDescription: 'Student Violin 4/4',
conditionIn: 'poor',
})
t.assert.status(res, 201)
t.assert.equal(res.data.accountId, acct.data.id)
})
t.test('lists repair tickets with pagination', { tags: ['tickets', 'read', 'pagination'] }, async () => {
await t.api.post('/v1/repair-tickets', { customerName: 'List Test A', problemDescription: 'Issue A' })
await t.api.post('/v1/repair-tickets', { customerName: 'List Test B', problemDescription: 'Issue B' })
const res = await t.api.get('/v1/repair-tickets', { limit: 100 })
t.assert.status(res, 200)
t.assert.ok(res.data.data.length >= 2)
t.assert.ok(res.data.pagination.total >= 2)
})
t.test('searches repair tickets by customer name', { tags: ['tickets', 'search'] }, async () => {
await t.api.post('/v1/repair-tickets', { customerName: 'Searchable Trumpet Guy', problemDescription: 'Dent' })
const res = await t.api.get('/v1/repair-tickets', { q: 'Trumpet Guy' })
t.assert.status(res, 200)
t.assert.ok(res.data.data.some((t: { customerName: string }) => t.customerName === 'Searchable Trumpet Guy'))
})
t.test('gets repair ticket by id', { tags: ['tickets', 'read'] }, async () => {
const created = await t.api.post('/v1/repair-tickets', { customerName: 'Get By ID', problemDescription: 'Test' })
const res = await t.api.get(`/v1/repair-tickets/${created.data.id}`)
t.assert.status(res, 200)
t.assert.equal(res.data.customerName, 'Get By ID')
})
t.test('returns 404 for missing repair ticket', { tags: ['tickets', 'read'] }, async () => {
const res = await t.api.get('/v1/repair-tickets/a0000000-0000-0000-0000-999999999999')
t.assert.status(res, 404)
})
t.test('updates a repair ticket', { tags: ['tickets', 'update'] }, async () => {
const created = await t.api.post('/v1/repair-tickets', { customerName: 'Before Update', problemDescription: 'Old issue' })
const res = await t.api.patch(`/v1/repair-tickets/${created.data.id}`, { customerName: 'After Update', estimatedCost: 150 })
t.assert.status(res, 200)
t.assert.equal(res.data.customerName, 'After Update')
t.assert.equal(res.data.estimatedCost, '150.00')
})
t.test('updates ticket status through lifecycle', { tags: ['tickets', 'status'] }, async () => {
const created = await t.api.post('/v1/repair-tickets', { customerName: 'Status Test', problemDescription: 'Lifecycle' })
t.assert.equal(created.data.status, 'intake')
const diag = await t.api.post(`/v1/repair-tickets/${created.data.id}/status`, { status: 'diagnosing' })
t.assert.status(diag, 200)
t.assert.equal(diag.data.status, 'diagnosing')
const prog = await t.api.post(`/v1/repair-tickets/${created.data.id}/status`, { status: 'in_progress' })
t.assert.equal(prog.data.status, 'in_progress')
const ready = await t.api.post(`/v1/repair-tickets/${created.data.id}/status`, { status: 'ready' })
t.assert.equal(ready.data.status, 'ready')
t.assert.ok(ready.data.completedDate, 'should set completedDate on ready')
const picked = await t.api.post(`/v1/repair-tickets/${created.data.id}/status`, { status: 'picked_up' })
t.assert.equal(picked.data.status, 'picked_up')
})
t.test('soft-deletes (cancels) a repair ticket', { tags: ['tickets', 'delete'] }, async () => {
const created = await t.api.post('/v1/repair-tickets', { customerName: 'To Cancel', problemDescription: 'Cancel me' })
const res = await t.api.del(`/v1/repair-tickets/${created.data.id}`)
t.assert.status(res, 200)
t.assert.equal(res.data.status, 'cancelled')
})
t.test('sorts tickets by customer name descending', { tags: ['tickets', 'sort'] }, async () => {
await t.api.post('/v1/repair-tickets', { customerName: 'AAA Sort First', problemDescription: 'Sort test' })
await t.api.post('/v1/repair-tickets', { customerName: 'ZZZ Sort Last', problemDescription: 'Sort test' })
const res = await t.api.get('/v1/repair-tickets', { sort: 'customer_name', order: 'desc', limit: 100 })
t.assert.status(res, 200)
const names = res.data.data.map((t: { customerName: string }) => t.customerName)
const zIdx = names.findIndex((n: string) => n.includes('ZZZ'))
const aIdx = names.findIndex((n: string) => n.includes('AAA'))
t.assert.ok(zIdx < aIdx, 'ZZZ should come before AAA in desc order')
})
// --- Repair Line Items ---
t.test('creates line items (labor, part, flat_rate)', { tags: ['line-items', 'create'] }, async () => {
const ticket = await t.api.post('/v1/repair-tickets', { customerName: 'Line Item Test', problemDescription: 'Needs work' })
const labor = await t.api.post(`/v1/repair-tickets/${ticket.data.id}/line-items`, {
itemType: 'labor',
description: 'Mechanical overhaul',
qty: 2.5,
unitPrice: 65,
totalPrice: 162.50,
})
t.assert.status(labor, 201)
t.assert.equal(labor.data.itemType, 'labor')
t.assert.equal(labor.data.description, 'Mechanical overhaul')
const part = await t.api.post(`/v1/repair-tickets/${ticket.data.id}/line-items`, {
itemType: 'part',
description: 'Valve guide',
qty: 3,
unitPrice: 2.50,
totalPrice: 7.50,
})
t.assert.status(part, 201)
t.assert.equal(part.data.itemType, 'part')
const flatRate = await t.api.post(`/v1/repair-tickets/${ticket.data.id}/line-items`, {
itemType: 'flat_rate',
description: 'Bow Rehair — Full Size',
qty: 1,
unitPrice: 50,
totalPrice: 50,
})
t.assert.status(flatRate, 201)
t.assert.equal(flatRate.data.itemType, 'flat_rate')
})
t.test('lists line items for a ticket', { tags: ['line-items', 'read'] }, async () => {
const ticket = await t.api.post('/v1/repair-tickets', { customerName: 'List Items', problemDescription: 'Test' })
await t.api.post(`/v1/repair-tickets/${ticket.data.id}/line-items`, { itemType: 'labor', description: 'Work A', qty: 1, unitPrice: 50, totalPrice: 50 })
await t.api.post(`/v1/repair-tickets/${ticket.data.id}/line-items`, { itemType: 'part', description: 'Part B', qty: 2, unitPrice: 10, totalPrice: 20 })
const res = await t.api.get(`/v1/repair-tickets/${ticket.data.id}/line-items`, { limit: 100 })
t.assert.status(res, 200)
t.assert.equal(res.data.data.length, 2)
t.assert.ok(res.data.pagination)
})
t.test('updates a line item', { tags: ['line-items', 'update'] }, async () => {
const ticket = await t.api.post('/v1/repair-tickets', { customerName: 'Update Item', problemDescription: 'Test' })
const item = await t.api.post(`/v1/repair-tickets/${ticket.data.id}/line-items`, { itemType: 'labor', description: 'Old desc', qty: 1, unitPrice: 50, totalPrice: 50 })
const res = await t.api.patch(`/v1/repair-line-items/${item.data.id}`, { description: 'New desc', unitPrice: 75, totalPrice: 75 })
t.assert.status(res, 200)
t.assert.equal(res.data.description, 'New desc')
t.assert.equal(res.data.unitPrice, '75.00')
})
t.test('deletes a line item', { tags: ['line-items', 'delete'] }, async () => {
const ticket = await t.api.post('/v1/repair-tickets', { customerName: 'Delete Item', problemDescription: 'Test' })
const item = await t.api.post(`/v1/repair-tickets/${ticket.data.id}/line-items`, { itemType: 'misc', description: 'To delete', qty: 1, unitPrice: 10, totalPrice: 10 })
const res = await t.api.del(`/v1/repair-line-items/${item.data.id}`)
t.assert.status(res, 200)
const list = await t.api.get(`/v1/repair-tickets/${ticket.data.id}/line-items`, { limit: 100 })
t.assert.equal(list.data.data.length, 0)
})
// --- Repair Batches ---
t.test('creates a repair batch', { tags: ['batches', 'create'] }, async () => {
const acct = await t.api.post('/v1/accounts', { name: 'Lincoln High School', billingMode: 'consolidated' })
const res = await t.api.post('/v1/repair-batches', {
accountId: acct.data.id,
contactName: 'Band Director',
contactPhone: '555-0200',
instrumentCount: 15,
notes: 'Annual instrument checkup',
})
t.assert.status(res, 201)
t.assert.ok(res.data.batchNumber)
t.assert.equal(res.data.batchNumber.length, 6)
t.assert.equal(res.data.status, 'intake')
t.assert.equal(res.data.approvalStatus, 'pending')
t.assert.equal(res.data.instrumentCount, 15)
})
t.test('lists repair batches', { tags: ['batches', 'read'] }, async () => {
const res = await t.api.get('/v1/repair-batches', { limit: 100 })
t.assert.status(res, 200)
t.assert.ok(res.data.data.length >= 1)
t.assert.ok(res.data.pagination)
})
t.test('adds tickets to a batch', { tags: ['batches', 'tickets'] }, async () => {
const acct = await t.api.post('/v1/accounts', { name: 'Batch School', billingMode: 'consolidated' })
const batch = await t.api.post('/v1/repair-batches', { accountId: acct.data.id, instrumentCount: 2 })
const ticket1 = await t.api.post('/v1/repair-tickets', {
customerName: 'Batch School',
repairBatchId: batch.data.id,
problemDescription: 'Flute needs pads',
instrumentDescription: 'Flute',
})
const ticket2 = await t.api.post('/v1/repair-tickets', {
customerName: 'Batch School',
repairBatchId: batch.data.id,
problemDescription: 'Clarinet needs cork',
instrumentDescription: 'Clarinet',
})
t.assert.equal(ticket1.data.repairBatchId, batch.data.id)
t.assert.equal(ticket2.data.repairBatchId, batch.data.id)
const tickets = await t.api.get(`/v1/repair-batches/${batch.data.id}/tickets`, { limit: 100 })
t.assert.status(tickets, 200)
t.assert.equal(tickets.data.data.length, 2)
})
t.test('approves a batch', { tags: ['batches', 'approve'] }, async () => {
const acct = await t.api.post('/v1/accounts', { name: 'Approve School', billingMode: 'consolidated' })
const batch = await t.api.post('/v1/repair-batches', { accountId: acct.data.id })
const res = await t.api.post(`/v1/repair-batches/${batch.data.id}/approve`, {})
t.assert.status(res, 200)
t.assert.equal(res.data.approvalStatus, 'approved')
t.assert.ok(res.data.approvedBy)
t.assert.ok(res.data.approvedAt)
})
t.test('rejects a batch', { tags: ['batches', 'reject'] }, async () => {
const acct = await t.api.post('/v1/accounts', { name: 'Reject School', billingMode: 'consolidated' })
const batch = await t.api.post('/v1/repair-batches', { accountId: acct.data.id })
const res = await t.api.post(`/v1/repair-batches/${batch.data.id}/reject`, {})
t.assert.status(res, 200)
t.assert.equal(res.data.approvalStatus, 'rejected')
})
t.test('updates batch status', { tags: ['batches', 'status'] }, async () => {
const acct = await t.api.post('/v1/accounts', { name: 'Status School', billingMode: 'consolidated' })
const batch = await t.api.post('/v1/repair-batches', { accountId: acct.data.id })
const prog = await t.api.post(`/v1/repair-batches/${batch.data.id}/status`, { status: 'in_progress' })
t.assert.equal(prog.data.status, 'in_progress')
const done = await t.api.post(`/v1/repair-batches/${batch.data.id}/status`, { status: 'completed' })
t.assert.equal(done.data.status, 'completed')
t.assert.ok(done.data.completedDate)
})
})

View File

@@ -0,0 +1,78 @@
-- Repair domain enums
CREATE TYPE "repair_ticket_status" AS ENUM ('intake', 'diagnosing', 'pending_approval', 'approved', 'in_progress', 'pending_parts', 'ready', 'picked_up', 'delivered', 'cancelled');
CREATE TYPE "repair_line_item_type" AS ENUM ('labor', 'part', 'flat_rate', 'misc');
CREATE TYPE "repair_condition_in" AS ENUM ('excellent', 'good', 'fair', 'poor');
CREATE TYPE "repair_batch_status" AS ENUM ('intake', 'in_progress', 'pending_approval', 'approved', 'completed', 'delivered', 'cancelled');
CREATE TYPE "repair_batch_approval" AS ENUM ('pending', 'approved', 'rejected');
-- Repair batches (defined first — tickets FK to it)
CREATE TABLE "repair_batch" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"company_id" uuid NOT NULL REFERENCES "company"("id"),
"location_id" uuid REFERENCES "location"("id"),
"batch_number" varchar(50),
"account_id" uuid NOT NULL REFERENCES "account"("id"),
"contact_name" varchar(255),
"contact_phone" varchar(50),
"contact_email" varchar(255),
"status" "repair_batch_status" NOT NULL DEFAULT 'intake',
"approval_status" "repair_batch_approval" NOT NULL DEFAULT 'pending',
"approved_by" uuid REFERENCES "user"("id"),
"approved_at" timestamp with time zone,
"pickup_date" timestamp with time zone,
"due_date" timestamp with time zone,
"completed_date" timestamp with time zone,
"delivered_date" timestamp with time zone,
"instrument_count" integer NOT NULL DEFAULT 0,
"received_count" integer NOT NULL DEFAULT 0,
"estimated_total" numeric(10, 2),
"actual_total" numeric(10, 2),
"notes" text,
"legacy_id" varchar(255),
"created_at" timestamp with time zone NOT NULL DEFAULT now(),
"updated_at" timestamp with time zone NOT NULL DEFAULT now()
);
-- Repair tickets
CREATE TABLE "repair_ticket" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"company_id" uuid NOT NULL REFERENCES "company"("id"),
"location_id" uuid REFERENCES "location"("id"),
"repair_batch_id" uuid REFERENCES "repair_batch"("id"),
"ticket_number" varchar(50),
"account_id" uuid REFERENCES "account"("id"),
"customer_name" varchar(255) NOT NULL,
"customer_phone" varchar(50),
"inventory_unit_id" uuid REFERENCES "inventory_unit"("id"),
"instrument_description" text,
"serial_number" varchar(255),
"condition_in" "repair_condition_in",
"condition_in_notes" text,
"problem_description" text NOT NULL,
"technician_notes" text,
"status" "repair_ticket_status" NOT NULL DEFAULT 'intake',
"assigned_technician_id" uuid REFERENCES "user"("id"),
"estimated_cost" numeric(10, 2),
"actual_cost" numeric(10, 2),
"intake_date" timestamp with time zone NOT NULL DEFAULT now(),
"promised_date" timestamp with time zone,
"completed_date" timestamp with time zone,
"legacy_id" varchar(255),
"created_at" timestamp with time zone NOT NULL DEFAULT now(),
"updated_at" timestamp with time zone NOT NULL DEFAULT now()
);
-- Repair line items
CREATE TABLE "repair_line_item" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"repair_ticket_id" uuid NOT NULL REFERENCES "repair_ticket"("id"),
"item_type" "repair_line_item_type" NOT NULL,
"description" varchar(255) NOT NULL,
"product_id" uuid REFERENCES "product"("id"),
"qty" numeric(10, 3) NOT NULL DEFAULT 1,
"unit_price" numeric(10, 2) NOT NULL DEFAULT 0,
"total_price" numeric(10, 2) NOT NULL DEFAULT 0,
"cost" numeric(10, 2),
"technician_id" uuid REFERENCES "user"("id"),
"created_at" timestamp with time zone NOT NULL DEFAULT now()
);

View File

@@ -0,0 +1,15 @@
CREATE TABLE "repair_service_template" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"company_id" uuid NOT NULL REFERENCES "company"("id"),
"name" varchar(255) NOT NULL,
"instrument_type" varchar(100),
"size" varchar(50),
"description" text,
"item_type" "repair_line_item_type" NOT NULL DEFAULT 'flat_rate',
"default_price" numeric(10, 2) NOT NULL DEFAULT 0,
"default_cost" numeric(10, 2),
"sort_order" integer NOT NULL DEFAULT 0,
"is_active" boolean NOT NULL DEFAULT true,
"created_at" timestamp with time zone NOT NULL DEFAULT now(),
"updated_at" timestamp with time zone NOT NULL DEFAULT now()
);

View File

@@ -106,6 +106,20 @@
"when": 1774740000000, "when": 1774740000000,
"tag": "0014_user_is_active", "tag": "0014_user_is_active",
"breakpoints": true "breakpoints": true
},
{
"idx": 15,
"version": "7",
"when": 1774750000000,
"tag": "0015_repairs",
"breakpoints": true
},
{
"idx": 16,
"version": "7",
"when": 1774760000000,
"tag": "0016_repair_service_templates",
"breakpoints": true
} }
] ]
} }

View File

@@ -0,0 +1,169 @@
import {
pgTable,
uuid,
varchar,
text,
timestamp,
boolean,
integer,
numeric,
pgEnum,
} from 'drizzle-orm/pg-core'
import { companies, locations } from './stores.js'
import { accounts } from './accounts.js'
import { inventoryUnits, products } from './inventory.js'
import { users } from './users.js'
// --- Enums ---
export const repairTicketStatusEnum = pgEnum('repair_ticket_status', [
'intake',
'diagnosing',
'pending_approval',
'approved',
'in_progress',
'pending_parts',
'ready',
'picked_up',
'delivered',
'cancelled',
])
export const repairLineItemTypeEnum = pgEnum('repair_line_item_type', [
'labor',
'part',
'flat_rate',
'misc',
])
export const repairConditionInEnum = pgEnum('repair_condition_in', [
'excellent',
'good',
'fair',
'poor',
])
export const repairBatchStatusEnum = pgEnum('repair_batch_status', [
'intake',
'in_progress',
'pending_approval',
'approved',
'completed',
'delivered',
'cancelled',
])
export const repairBatchApprovalEnum = pgEnum('repair_batch_approval', [
'pending',
'approved',
'rejected',
])
// --- Tables ---
// Defined before repairTickets because tickets FK to batches
export const repairBatches = pgTable('repair_batch', {
id: uuid('id').primaryKey().defaultRandom(),
companyId: uuid('company_id')
.notNull()
.references(() => companies.id),
locationId: uuid('location_id').references(() => locations.id),
batchNumber: varchar('batch_number', { length: 50 }),
accountId: uuid('account_id')
.notNull()
.references(() => accounts.id),
contactName: varchar('contact_name', { length: 255 }),
contactPhone: varchar('contact_phone', { length: 50 }),
contactEmail: varchar('contact_email', { length: 255 }),
status: repairBatchStatusEnum('status').notNull().default('intake'),
approvalStatus: repairBatchApprovalEnum('approval_status').notNull().default('pending'),
approvedBy: uuid('approved_by').references(() => users.id),
approvedAt: timestamp('approved_at', { withTimezone: true }),
pickupDate: timestamp('pickup_date', { withTimezone: true }),
dueDate: timestamp('due_date', { withTimezone: true }),
completedDate: timestamp('completed_date', { withTimezone: true }),
deliveredDate: timestamp('delivered_date', { withTimezone: true }),
instrumentCount: integer('instrument_count').notNull().default(0),
receivedCount: integer('received_count').notNull().default(0),
estimatedTotal: numeric('estimated_total', { precision: 10, scale: 2 }),
actualTotal: numeric('actual_total', { precision: 10, scale: 2 }),
notes: text('notes'),
legacyId: varchar('legacy_id', { length: 255 }),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
})
export const repairTickets = pgTable('repair_ticket', {
id: uuid('id').primaryKey().defaultRandom(),
companyId: uuid('company_id')
.notNull()
.references(() => companies.id),
locationId: uuid('location_id').references(() => locations.id),
repairBatchId: uuid('repair_batch_id').references(() => repairBatches.id),
ticketNumber: varchar('ticket_number', { length: 50 }),
accountId: uuid('account_id').references(() => accounts.id),
customerName: varchar('customer_name', { length: 255 }).notNull(),
customerPhone: varchar('customer_phone', { length: 50 }),
inventoryUnitId: uuid('inventory_unit_id').references(() => inventoryUnits.id),
instrumentDescription: text('instrument_description'),
serialNumber: varchar('serial_number', { length: 255 }),
conditionIn: repairConditionInEnum('condition_in'),
conditionInNotes: text('condition_in_notes'),
problemDescription: text('problem_description').notNull(),
technicianNotes: text('technician_notes'),
status: repairTicketStatusEnum('status').notNull().default('intake'),
assignedTechnicianId: uuid('assigned_technician_id').references(() => users.id),
estimatedCost: numeric('estimated_cost', { precision: 10, scale: 2 }),
actualCost: numeric('actual_cost', { precision: 10, scale: 2 }),
intakeDate: timestamp('intake_date', { withTimezone: true }).notNull().defaultNow(),
promisedDate: timestamp('promised_date', { withTimezone: true }),
completedDate: timestamp('completed_date', { withTimezone: true }),
legacyId: varchar('legacy_id', { length: 255 }),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
})
export const repairLineItems = pgTable('repair_line_item', {
id: uuid('id').primaryKey().defaultRandom(),
repairTicketId: uuid('repair_ticket_id')
.notNull()
.references(() => repairTickets.id),
itemType: repairLineItemTypeEnum('item_type').notNull(),
description: varchar('description', { length: 255 }).notNull(),
productId: uuid('product_id').references(() => products.id),
qty: numeric('qty', { precision: 10, scale: 3 }).notNull().default('1'),
unitPrice: numeric('unit_price', { precision: 10, scale: 2 }).notNull().default('0'),
totalPrice: numeric('total_price', { precision: 10, scale: 2 }).notNull().default('0'),
cost: numeric('cost', { precision: 10, scale: 2 }),
technicianId: uuid('technician_id').references(() => users.id),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
})
export const repairServiceTemplates = pgTable('repair_service_template', {
id: uuid('id').primaryKey().defaultRandom(),
companyId: uuid('company_id')
.notNull()
.references(() => companies.id),
name: varchar('name', { length: 255 }).notNull(),
instrumentType: varchar('instrument_type', { length: 100 }),
size: varchar('size', { length: 50 }),
description: text('description'),
itemType: repairLineItemTypeEnum('item_type').notNull().default('flat_rate'),
defaultPrice: numeric('default_price', { precision: 10, scale: 2 }).notNull().default('0'),
defaultCost: numeric('default_cost', { precision: 10, scale: 2 }),
sortOrder: integer('sort_order').notNull().default(0),
isActive: boolean('is_active').notNull().default(true),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
})
// --- Type exports ---
export type RepairTicket = typeof repairTickets.$inferSelect
export type RepairTicketInsert = typeof repairTickets.$inferInsert
export type RepairLineItem = typeof repairLineItems.$inferSelect
export type RepairLineItemInsert = typeof repairLineItems.$inferInsert
export type RepairBatch = typeof repairBatches.$inferSelect
export type RepairBatchInsert = typeof repairBatches.$inferInsert
export type RepairServiceTemplate = typeof repairServiceTemplates.$inferSelect
export type RepairServiceTemplateInsert = typeof repairServiceTemplates.$inferInsert

View File

@@ -15,6 +15,7 @@ import { productRoutes } from './routes/v1/products.js'
import { lookupRoutes } from './routes/v1/lookups.js' import { lookupRoutes } from './routes/v1/lookups.js'
import { fileRoutes } from './routes/v1/files.js' import { fileRoutes } from './routes/v1/files.js'
import { rbacRoutes } from './routes/v1/rbac.js' import { rbacRoutes } from './routes/v1/rbac.js'
import { repairRoutes } from './routes/v1/repairs.js'
import { RbacService } from './services/rbac.service.js' import { RbacService } from './services/rbac.service.js'
export async function buildApp() { export async function buildApp() {
@@ -65,6 +66,7 @@ export async function buildApp() {
await app.register(lookupRoutes, { prefix: '/v1' }) await app.register(lookupRoutes, { prefix: '/v1' })
await app.register(fileRoutes, { prefix: '/v1' }) await app.register(fileRoutes, { prefix: '/v1' })
await app.register(rbacRoutes, { prefix: '/v1' }) await app.register(rbacRoutes, { prefix: '/v1' })
await app.register(repairRoutes, { prefix: '/v1' })
// Auto-seed system permissions on startup // Auto-seed system permissions on startup
app.addHook('onReady', async () => { app.addHook('onReady', async () => {

View File

@@ -0,0 +1,209 @@
import type { FastifyPluginAsync } from 'fastify'
import {
PaginationSchema,
RepairTicketCreateSchema,
RepairTicketUpdateSchema,
RepairTicketStatusUpdateSchema,
RepairLineItemCreateSchema,
RepairLineItemUpdateSchema,
RepairBatchCreateSchema,
RepairBatchUpdateSchema,
RepairBatchStatusUpdateSchema,
RepairServiceTemplateCreateSchema,
RepairServiceTemplateUpdateSchema,
} from '@forte/shared/schemas'
import { RepairTicketService, RepairLineItemService, RepairBatchService, RepairServiceTemplateService } from '../../services/repair.service.js'
export const repairRoutes: FastifyPluginAsync = async (app) => {
// --- Repair Tickets ---
app.post('/repair-tickets', { preHandler: [app.authenticate, app.requirePermission('repairs.edit')] }, async (request, reply) => {
const parsed = RepairTicketCreateSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const ticket = await RepairTicketService.create(app.db, request.companyId, parsed.data)
return reply.status(201).send(ticket)
})
app.get('/repair-tickets', { preHandler: [app.authenticate, app.requirePermission('repairs.view')] }, async (request, reply) => {
const params = PaginationSchema.parse(request.query)
const result = await RepairTicketService.list(app.db, request.companyId, params)
return reply.send(result)
})
app.get('/repair-tickets/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.view')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const ticket = await RepairTicketService.getById(app.db, request.companyId, id)
if (!ticket) return reply.status(404).send({ error: { message: 'Repair ticket not found', statusCode: 404 } })
return reply.send(ticket)
})
app.patch('/repair-tickets/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.edit')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const parsed = RepairTicketUpdateSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const ticket = await RepairTicketService.update(app.db, request.companyId, id, parsed.data)
if (!ticket) return reply.status(404).send({ error: { message: 'Repair ticket not found', statusCode: 404 } })
return reply.send(ticket)
})
app.post('/repair-tickets/:id/status', { preHandler: [app.authenticate, app.requirePermission('repairs.edit')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const parsed = RepairTicketStatusUpdateSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const ticket = await RepairTicketService.updateStatus(app.db, request.companyId, id, parsed.data.status)
if (!ticket) return reply.status(404).send({ error: { message: 'Repair ticket not found', statusCode: 404 } })
return reply.send(ticket)
})
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, request.companyId, id)
if (!ticket) return reply.status(404).send({ error: { message: 'Repair ticket not found', statusCode: 404 } })
return reply.send(ticket)
})
// --- Repair Line Items ---
app.post('/repair-tickets/:ticketId/line-items', { preHandler: [app.authenticate, app.requirePermission('repairs.edit')] }, async (request, reply) => {
const { ticketId } = request.params as { ticketId: string }
const parsed = RepairLineItemCreateSchema.safeParse({ ...(request.body as object), repairTicketId: ticketId })
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const item = await RepairLineItemService.create(app.db, parsed.data)
return reply.status(201).send(item)
})
app.get('/repair-tickets/:ticketId/line-items', { preHandler: [app.authenticate, app.requirePermission('repairs.view')] }, async (request, reply) => {
const { ticketId } = request.params as { ticketId: string }
const params = PaginationSchema.parse(request.query)
const result = await RepairLineItemService.listByTicket(app.db, ticketId, params)
return reply.send(result)
})
app.patch('/repair-line-items/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.edit')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const parsed = RepairLineItemUpdateSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const item = await RepairLineItemService.update(app.db, id, parsed.data)
if (!item) return reply.status(404).send({ error: { message: 'Line item not found', statusCode: 404 } })
return reply.send(item)
})
app.delete('/repair-line-items/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.admin')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const item = await RepairLineItemService.delete(app.db, id)
if (!item) return reply.status(404).send({ error: { message: 'Line item not found', statusCode: 404 } })
return reply.send(item)
})
// --- Repair Batches ---
app.post('/repair-batches', { preHandler: [app.authenticate, app.requirePermission('repairs.edit')] }, async (request, reply) => {
const parsed = RepairBatchCreateSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const batch = await RepairBatchService.create(app.db, request.companyId, parsed.data)
return reply.status(201).send(batch)
})
app.get('/repair-batches', { preHandler: [app.authenticate, app.requirePermission('repairs.view')] }, async (request, reply) => {
const params = PaginationSchema.parse(request.query)
const result = await RepairBatchService.list(app.db, request.companyId, params)
return reply.send(result)
})
app.get('/repair-batches/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.view')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const batch = await RepairBatchService.getById(app.db, request.companyId, id)
if (!batch) return reply.status(404).send({ error: { message: 'Repair batch not found', statusCode: 404 } })
return reply.send(batch)
})
app.patch('/repair-batches/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.edit')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const parsed = RepairBatchUpdateSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const batch = await RepairBatchService.update(app.db, request.companyId, id, parsed.data)
if (!batch) return reply.status(404).send({ error: { message: 'Repair batch not found', statusCode: 404 } })
return reply.send(batch)
})
app.post('/repair-batches/:id/status', { preHandler: [app.authenticate, app.requirePermission('repairs.edit')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const parsed = RepairBatchStatusUpdateSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const batch = await RepairBatchService.updateStatus(app.db, request.companyId, id, parsed.data.status)
if (!batch) return reply.status(404).send({ error: { message: 'Repair batch not found', statusCode: 404 } })
return reply.send(batch)
})
app.post('/repair-batches/:id/approve', { preHandler: [app.authenticate, app.requirePermission('repairs.admin')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const batch = await RepairBatchService.approve(app.db, request.companyId, id, request.user.id)
if (!batch) return reply.status(404).send({ error: { message: 'Repair batch not found', statusCode: 404 } })
return reply.send(batch)
})
app.post('/repair-batches/:id/reject', { preHandler: [app.authenticate, app.requirePermission('repairs.admin')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const batch = await RepairBatchService.reject(app.db, request.companyId, id)
if (!batch) return reply.status(404).send({ error: { message: 'Repair batch not found', statusCode: 404 } })
return reply.send(batch)
})
app.get('/repair-batches/:batchId/tickets', { preHandler: [app.authenticate, app.requirePermission('repairs.view')] }, async (request, reply) => {
const { batchId } = request.params as { batchId: string }
const params = PaginationSchema.parse(request.query)
const result = await RepairTicketService.listByBatch(app.db, request.companyId, batchId, params)
return reply.send(result)
})
// --- Repair Service Templates ---
app.post('/repair-service-templates', { preHandler: [app.authenticate, app.requirePermission('repairs.admin')] }, async (request, reply) => {
const parsed = RepairServiceTemplateCreateSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const template = await RepairServiceTemplateService.create(app.db, request.companyId, parsed.data)
return reply.status(201).send(template)
})
app.get('/repair-service-templates', { preHandler: [app.authenticate, app.requirePermission('repairs.view')] }, async (request, reply) => {
const params = PaginationSchema.parse(request.query)
const result = await RepairServiceTemplateService.list(app.db, request.companyId, params)
return reply.send(result)
})
app.patch('/repair-service-templates/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.admin')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const parsed = RepairServiceTemplateUpdateSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const template = await RepairServiceTemplateService.update(app.db, request.companyId, id, parsed.data)
if (!template) return reply.status(404).send({ error: { message: 'Template not found', statusCode: 404 } })
return reply.send(template)
})
app.delete('/repair-service-templates/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.admin')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const template = await RepairServiceTemplateService.delete(app.db, request.companyId, id)
if (!template) return reply.status(404).send({ error: { message: 'Template not found', statusCode: 404 } })
return reply.send(template)
})
}

View File

@@ -0,0 +1,427 @@
import { eq, and, count, type Column } from 'drizzle-orm'
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
import {
repairTickets,
repairLineItems,
repairBatches,
repairServiceTemplates,
} from '../db/schema/repairs.js'
import type {
RepairTicketCreateInput,
RepairTicketUpdateInput,
RepairLineItemCreateInput,
RepairLineItemUpdateInput,
RepairBatchCreateInput,
RepairBatchUpdateInput,
RepairServiceTemplateCreateInput,
RepairServiceTemplateUpdateInput,
PaginationInput,
} from '@forte/shared/schemas'
import {
withPagination,
withSort,
buildSearchCondition,
paginatedResponse,
} from '../utils/pagination.js'
async function generateUniqueNumber(
db: PostgresJsDatabase<any>,
table: typeof repairTickets | typeof repairBatches,
column: typeof repairTickets.ticketNumber | typeof repairBatches.batchNumber,
companyId: string,
companyIdColumn: Column,
): Promise<string> {
for (let attempt = 0; attempt < 10; attempt++) {
const num = String(Math.floor(100000 + Math.random() * 900000))
const [existing] = await db
.select({ id: table.id })
.from(table)
.where(and(eq(companyIdColumn, companyId), eq(column, num)))
.limit(1)
if (!existing) return num
}
return String(Math.floor(10000000 + Math.random() * 90000000))
}
export const RepairTicketService = {
async create(db: PostgresJsDatabase<any>, companyId: string, input: RepairTicketCreateInput) {
const ticketNumber = await generateUniqueNumber(
db, repairTickets, repairTickets.ticketNumber, companyId, repairTickets.companyId,
)
const [ticket] = await db
.insert(repairTickets)
.values({
companyId,
ticketNumber,
customerName: input.customerName,
customerPhone: input.customerPhone,
accountId: input.accountId,
locationId: input.locationId,
repairBatchId: input.repairBatchId,
inventoryUnitId: input.inventoryUnitId,
instrumentDescription: input.instrumentDescription,
serialNumber: input.serialNumber,
conditionIn: input.conditionIn,
conditionInNotes: input.conditionInNotes,
problemDescription: input.problemDescription,
technicianNotes: input.technicianNotes,
assignedTechnicianId: input.assignedTechnicianId,
estimatedCost: input.estimatedCost?.toString(),
promisedDate: input.promisedDate ? new Date(input.promisedDate) : undefined,
})
.returning()
return ticket
},
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
const [ticket] = await db
.select()
.from(repairTickets)
.where(and(eq(repairTickets.id, id), eq(repairTickets.companyId, companyId)))
.limit(1)
return ticket ?? null
},
async list(db: PostgresJsDatabase<any>, companyId: string, params: PaginationInput) {
const baseWhere = eq(repairTickets.companyId, companyId)
const searchCondition = params.q
? buildSearchCondition(params.q, [
repairTickets.ticketNumber,
repairTickets.customerName,
repairTickets.customerPhone,
repairTickets.instrumentDescription,
repairTickets.serialNumber,
])
: undefined
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
const sortableColumns: Record<string, Column> = {
ticket_number: repairTickets.ticketNumber,
customer_name: repairTickets.customerName,
status: repairTickets.status,
intake_date: repairTickets.intakeDate,
promised_date: repairTickets.promisedDate,
created_at: repairTickets.createdAt,
}
let query = db.select().from(repairTickets).where(where).$dynamic()
query = withSort(query, params.sort, params.order, sortableColumns, repairTickets.createdAt)
query = withPagination(query, params.page, params.limit)
const [data, [{ total }]] = await Promise.all([
query,
db.select({ total: count() }).from(repairTickets).where(where),
])
return paginatedResponse(data, total, params.page, params.limit)
},
async listByBatch(db: PostgresJsDatabase<any>, companyId: string, batchId: string, params: PaginationInput) {
const baseWhere = and(eq(repairTickets.companyId, companyId), eq(repairTickets.repairBatchId, batchId))
const searchCondition = params.q
? buildSearchCondition(params.q, [repairTickets.ticketNumber, repairTickets.customerName, repairTickets.instrumentDescription])
: undefined
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
const sortableColumns: Record<string, Column> = {
ticket_number: repairTickets.ticketNumber,
customer_name: repairTickets.customerName,
status: repairTickets.status,
created_at: repairTickets.createdAt,
}
let query = db.select().from(repairTickets).where(where).$dynamic()
query = withSort(query, params.sort, params.order, sortableColumns, repairTickets.createdAt)
query = withPagination(query, params.page, params.limit)
const [data, [{ total }]] = await Promise.all([
query,
db.select({ total: count() }).from(repairTickets).where(where),
])
return paginatedResponse(data, total, params.page, params.limit)
},
async update(db: PostgresJsDatabase<any>, companyId: string, id: string, input: RepairTicketUpdateInput) {
const values: Record<string, unknown> = { ...input, updatedAt: new Date() }
if (input.estimatedCost !== undefined) values.estimatedCost = input.estimatedCost.toString()
if (input.promisedDate !== undefined) values.promisedDate = input.promisedDate ? new Date(input.promisedDate) : null
const [ticket] = await db
.update(repairTickets)
.set(values)
.where(and(eq(repairTickets.id, id), eq(repairTickets.companyId, companyId)))
.returning()
return ticket ?? null
},
async updateStatus(db: PostgresJsDatabase<any>, companyId: string, id: string, status: string) {
const updates: Record<string, unknown> = { status, updatedAt: new Date() }
if (status === 'ready' || status === 'picked_up' || status === 'delivered') {
updates.completedDate = new Date()
}
const [ticket] = await db
.update(repairTickets)
.set(updates)
.where(and(eq(repairTickets.id, id), eq(repairTickets.companyId, companyId)))
.returning()
return ticket ?? null
},
async delete(db: PostgresJsDatabase<any>, companyId: string, id: string) {
// Soft-cancel: set status to cancelled rather than hard delete
const [ticket] = await db
.update(repairTickets)
.set({ status: 'cancelled', updatedAt: new Date() })
.where(and(eq(repairTickets.id, id), eq(repairTickets.companyId, companyId)))
.returning()
return ticket ?? null
},
}
export const RepairLineItemService = {
async create(db: PostgresJsDatabase<any>, input: RepairLineItemCreateInput) {
const [item] = await db
.insert(repairLineItems)
.values({
repairTicketId: input.repairTicketId,
itemType: input.itemType,
description: input.description,
productId: input.productId,
qty: input.qty?.toString(),
unitPrice: input.unitPrice?.toString(),
totalPrice: input.totalPrice?.toString(),
cost: input.cost?.toString(),
technicianId: input.technicianId,
})
.returning()
return item
},
async listByTicket(db: PostgresJsDatabase<any>, ticketId: string, params: PaginationInput) {
const where = eq(repairLineItems.repairTicketId, ticketId)
const sortableColumns: Record<string, Column> = {
item_type: repairLineItems.itemType,
created_at: repairLineItems.createdAt,
}
let query = db.select().from(repairLineItems).where(where).$dynamic()
query = withSort(query, params.sort, params.order, sortableColumns, repairLineItems.createdAt)
query = withPagination(query, params.page, params.limit)
const [data, [{ total }]] = await Promise.all([
query,
db.select({ total: count() }).from(repairLineItems).where(where),
])
return paginatedResponse(data, total, params.page, params.limit)
},
async update(db: PostgresJsDatabase<any>, id: string, input: RepairLineItemUpdateInput) {
const values: Record<string, unknown> = { ...input }
if (input.qty !== undefined) values.qty = input.qty.toString()
if (input.unitPrice !== undefined) values.unitPrice = input.unitPrice.toString()
if (input.totalPrice !== undefined) values.totalPrice = input.totalPrice.toString()
if (input.cost !== undefined) values.cost = input.cost.toString()
const [item] = await db
.update(repairLineItems)
.set(values)
.where(eq(repairLineItems.id, id))
.returning()
return item ?? null
},
async delete(db: PostgresJsDatabase<any>, id: string) {
const [item] = await db
.delete(repairLineItems)
.where(eq(repairLineItems.id, id))
.returning()
return item ?? null
},
}
export const RepairBatchService = {
async create(db: PostgresJsDatabase<any>, companyId: string, input: RepairBatchCreateInput) {
const batchNumber = await generateUniqueNumber(
db, repairBatches, repairBatches.batchNumber, companyId, repairBatches.companyId,
)
const [batch] = await db
.insert(repairBatches)
.values({
companyId,
batchNumber,
accountId: input.accountId,
locationId: input.locationId,
contactName: input.contactName,
contactPhone: input.contactPhone,
contactEmail: input.contactEmail,
pickupDate: input.pickupDate ? new Date(input.pickupDate) : undefined,
dueDate: input.dueDate ? new Date(input.dueDate) : undefined,
instrumentCount: input.instrumentCount,
notes: input.notes,
})
.returning()
return batch
},
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
const [batch] = await db
.select()
.from(repairBatches)
.where(and(eq(repairBatches.id, id), eq(repairBatches.companyId, companyId)))
.limit(1)
return batch ?? null
},
async list(db: PostgresJsDatabase<any>, companyId: string, params: PaginationInput) {
const baseWhere = eq(repairBatches.companyId, companyId)
const searchCondition = params.q
? buildSearchCondition(params.q, [repairBatches.batchNumber, repairBatches.contactName, repairBatches.contactEmail])
: undefined
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
const sortableColumns: Record<string, Column> = {
batch_number: repairBatches.batchNumber,
status: repairBatches.status,
due_date: repairBatches.dueDate,
created_at: repairBatches.createdAt,
}
let query = db.select().from(repairBatches).where(where).$dynamic()
query = withSort(query, params.sort, params.order, sortableColumns, repairBatches.createdAt)
query = withPagination(query, params.page, params.limit)
const [data, [{ total }]] = await Promise.all([
query,
db.select({ total: count() }).from(repairBatches).where(where),
])
return paginatedResponse(data, total, params.page, params.limit)
},
async update(db: PostgresJsDatabase<any>, companyId: string, id: string, input: RepairBatchUpdateInput) {
const values: Record<string, unknown> = { ...input, updatedAt: new Date() }
if (input.pickupDate !== undefined) values.pickupDate = input.pickupDate ? new Date(input.pickupDate) : null
if (input.dueDate !== undefined) values.dueDate = input.dueDate ? new Date(input.dueDate) : null
const [batch] = await db
.update(repairBatches)
.set(values)
.where(and(eq(repairBatches.id, id), eq(repairBatches.companyId, companyId)))
.returning()
return batch ?? null
},
async updateStatus(db: PostgresJsDatabase<any>, companyId: string, id: string, status: string) {
const updates: Record<string, unknown> = { status, updatedAt: new Date() }
if (status === 'completed') updates.completedDate = new Date()
if (status === 'delivered') updates.deliveredDate = new Date()
const [batch] = await db
.update(repairBatches)
.set(updates)
.where(and(eq(repairBatches.id, id), eq(repairBatches.companyId, companyId)))
.returning()
return batch ?? null
},
async approve(db: PostgresJsDatabase<any>, companyId: string, id: string, approvedBy: string) {
const [batch] = await db
.update(repairBatches)
.set({
approvalStatus: 'approved',
approvedBy,
approvedAt: new Date(),
updatedAt: new Date(),
})
.where(and(eq(repairBatches.id, id), eq(repairBatches.companyId, companyId)))
.returning()
return batch ?? null
},
async reject(db: PostgresJsDatabase<any>, companyId: string, id: string) {
const [batch] = await db
.update(repairBatches)
.set({
approvalStatus: 'rejected',
updatedAt: new Date(),
})
.where(and(eq(repairBatches.id, id), eq(repairBatches.companyId, companyId)))
.returning()
return batch ?? null
},
}
export const RepairServiceTemplateService = {
async create(db: PostgresJsDatabase<any>, companyId: string, input: RepairServiceTemplateCreateInput) {
const [template] = await db
.insert(repairServiceTemplates)
.values({
companyId,
name: input.name,
instrumentType: input.instrumentType,
size: input.size,
description: input.description,
itemType: input.itemType,
defaultPrice: input.defaultPrice?.toString(),
defaultCost: input.defaultCost?.toString(),
sortOrder: input.sortOrder,
})
.returning()
return template
},
async list(db: PostgresJsDatabase<any>, companyId: string, params: PaginationInput) {
const baseWhere = and(eq(repairServiceTemplates.companyId, companyId), eq(repairServiceTemplates.isActive, true))
const searchCondition = params.q
? buildSearchCondition(params.q, [repairServiceTemplates.name, repairServiceTemplates.instrumentType, repairServiceTemplates.size, repairServiceTemplates.description])
: undefined
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
const sortableColumns: Record<string, Column> = {
name: repairServiceTemplates.name,
instrument_type: repairServiceTemplates.instrumentType,
default_price: repairServiceTemplates.defaultPrice,
sort_order: repairServiceTemplates.sortOrder,
created_at: repairServiceTemplates.createdAt,
}
let query = db.select().from(repairServiceTemplates).where(where).$dynamic()
query = withSort(query, params.sort, params.order, sortableColumns, repairServiceTemplates.sortOrder)
query = withPagination(query, params.page, params.limit)
const [data, [{ total }]] = await Promise.all([
query,
db.select({ total: count() }).from(repairServiceTemplates).where(where),
])
return paginatedResponse(data, total, params.page, params.limit)
},
async update(db: PostgresJsDatabase<any>, companyId: string, id: string, input: RepairServiceTemplateUpdateInput) {
const values: Record<string, unknown> = { ...input, updatedAt: new Date() }
if (input.defaultPrice !== undefined) values.defaultPrice = input.defaultPrice.toString()
if (input.defaultCost !== undefined) values.defaultCost = input.defaultCost.toString()
const [template] = await db
.update(repairServiceTemplates)
.set(values)
.where(and(eq(repairServiceTemplates.id, id), eq(repairServiceTemplates.companyId, companyId)))
.returning()
return template ?? null
},
async delete(db: PostgresJsDatabase<any>, companyId: string, id: string) {
const [template] = await db
.update(repairServiceTemplates)
.set({ isActive: false, updatedAt: new Date() })
.where(and(eq(repairServiceTemplates.id, id), eq(repairServiceTemplates.companyId, companyId)))
.returning()
return template ?? null
},
}

View File

@@ -66,3 +66,33 @@ export type {
InventoryUnitCreateInput, InventoryUnitCreateInput,
InventoryUnitUpdateInput, InventoryUnitUpdateInput,
} from './inventory.schema.js' } from './inventory.schema.js'
export {
RepairTicketStatus,
RepairLineItemType,
RepairConditionIn,
RepairBatchStatus,
RepairBatchApproval,
RepairTicketCreateSchema,
RepairTicketUpdateSchema,
RepairTicketStatusUpdateSchema,
RepairLineItemCreateSchema,
RepairLineItemUpdateSchema,
RepairBatchCreateSchema,
RepairBatchUpdateSchema,
RepairBatchStatusUpdateSchema,
RepairServiceTemplateCreateSchema,
RepairServiceTemplateUpdateSchema,
} from './repairs.schema.js'
export type {
RepairTicketCreateInput,
RepairTicketUpdateInput,
RepairTicketStatusUpdateInput,
RepairLineItemCreateInput,
RepairLineItemUpdateInput,
RepairBatchCreateInput,
RepairBatchUpdateInput,
RepairBatchStatusUpdateInput,
RepairServiceTemplateCreateInput,
RepairServiceTemplateUpdateInput,
} from './repairs.schema.js'

View File

@@ -0,0 +1,115 @@
import { z } from 'zod'
/** Coerce empty strings to undefined — solves HTML form inputs sending '' for blank optional fields */
function opt<T extends z.ZodTypeAny>(schema: T) {
return z.preprocess((v) => (v === '' ? undefined : v), schema.optional())
}
// --- Status / Type enums ---
export const RepairTicketStatus = z.enum([
'intake', 'diagnosing', 'pending_approval', 'approved',
'in_progress', 'pending_parts', 'ready', 'picked_up', 'delivered', 'cancelled',
])
export type RepairTicketStatus = z.infer<typeof RepairTicketStatus>
export const RepairLineItemType = z.enum(['labor', 'part', 'flat_rate', 'misc'])
export type RepairLineItemType = z.infer<typeof RepairLineItemType>
export const RepairConditionIn = z.enum(['excellent', 'good', 'fair', 'poor'])
export type RepairConditionIn = z.infer<typeof RepairConditionIn>
export const RepairBatchStatus = z.enum([
'intake', 'in_progress', 'pending_approval', 'approved', 'completed', 'delivered', 'cancelled',
])
export type RepairBatchStatus = z.infer<typeof RepairBatchStatus>
export const RepairBatchApproval = z.enum(['pending', 'approved', 'rejected'])
export type RepairBatchApproval = z.infer<typeof RepairBatchApproval>
// --- Repair Ticket schemas ---
export const RepairTicketCreateSchema = z.object({
customerName: z.string().min(1).max(255),
customerPhone: opt(z.string().max(50)),
accountId: opt(z.string().uuid()),
locationId: opt(z.string().uuid()),
repairBatchId: opt(z.string().uuid()),
inventoryUnitId: opt(z.string().uuid()),
instrumentDescription: opt(z.string()),
serialNumber: opt(z.string().max(255)),
conditionIn: opt(RepairConditionIn),
conditionInNotes: opt(z.string()),
problemDescription: z.string().min(1),
technicianNotes: opt(z.string()),
assignedTechnicianId: opt(z.string().uuid()),
estimatedCost: z.coerce.number().min(0).optional(),
promisedDate: opt(z.string()),
})
export type RepairTicketCreateInput = z.infer<typeof RepairTicketCreateSchema>
export const RepairTicketUpdateSchema = RepairTicketCreateSchema.partial()
export type RepairTicketUpdateInput = z.infer<typeof RepairTicketUpdateSchema>
export const RepairTicketStatusUpdateSchema = z.object({
status: RepairTicketStatus,
})
export type RepairTicketStatusUpdateInput = z.infer<typeof RepairTicketStatusUpdateSchema>
// --- Repair Line Item schemas ---
export const RepairLineItemCreateSchema = z.object({
repairTicketId: z.string().uuid(),
itemType: RepairLineItemType,
description: z.string().min(1).max(255),
productId: opt(z.string().uuid()),
qty: z.coerce.number().min(0).default(1),
unitPrice: z.coerce.number().min(0).default(0),
totalPrice: z.coerce.number().min(0).default(0),
cost: z.coerce.number().min(0).optional(),
technicianId: opt(z.string().uuid()),
})
export type RepairLineItemCreateInput = z.infer<typeof RepairLineItemCreateSchema>
export const RepairLineItemUpdateSchema = RepairLineItemCreateSchema.omit({ repairTicketId: true }).partial()
export type RepairLineItemUpdateInput = z.infer<typeof RepairLineItemUpdateSchema>
// --- Repair Batch schemas ---
export const RepairBatchCreateSchema = z.object({
accountId: z.string().uuid(),
locationId: opt(z.string().uuid()),
contactName: opt(z.string().max(255)),
contactPhone: opt(z.string().max(50)),
contactEmail: opt(z.string().email()),
pickupDate: opt(z.string()),
dueDate: opt(z.string()),
instrumentCount: z.coerce.number().int().min(0).default(0),
notes: opt(z.string()),
})
export type RepairBatchCreateInput = z.infer<typeof RepairBatchCreateSchema>
export const RepairBatchUpdateSchema = RepairBatchCreateSchema.partial()
export type RepairBatchUpdateInput = z.infer<typeof RepairBatchUpdateSchema>
export const RepairBatchStatusUpdateSchema = z.object({
status: RepairBatchStatus,
})
export type RepairBatchStatusUpdateInput = z.infer<typeof RepairBatchStatusUpdateSchema>
// --- Repair Service Template schemas ---
export const RepairServiceTemplateCreateSchema = z.object({
name: z.string().min(1).max(255),
instrumentType: opt(z.string().max(100)),
size: opt(z.string().max(50)),
description: opt(z.string()),
itemType: RepairLineItemType.default('flat_rate'),
defaultPrice: z.coerce.number().min(0).default(0),
defaultCost: z.coerce.number().min(0).optional(),
sortOrder: z.coerce.number().int().default(0),
})
export type RepairServiceTemplateCreateInput = z.infer<typeof RepairServiceTemplateCreateSchema>
export const RepairServiceTemplateUpdateSchema = RepairServiceTemplateCreateSchema.partial()
export type RepairServiceTemplateUpdateInput = z.infer<typeof RepairServiceTemplateUpdateSchema>