+ {primaryRequired && (
+
+ POC phone
+
+ )}
onPocPhoneChange(event.target.value)}
placeholder="POC phone"
diff --git a/src/app/(protected)/workorders/_components/wizard/mini-calendar.tsx b/src/app/(protected)/workorders/_components/wizard/mini-calendar.tsx
index e9aa9dab..5b494167 100644
--- a/src/app/(protected)/workorders/_components/wizard/mini-calendar.tsx
+++ b/src/app/(protected)/workorders/_components/wizard/mini-calendar.tsx
@@ -12,6 +12,8 @@ type MiniCalendarProps = {
range?: boolean;
rangeStart?: string;
rangeEnd?: string;
+ /** Days before this ISO date are disabled (SH-356 Due Date floor). */
+ minDate?: string;
};
export function MiniCalendar({
@@ -20,9 +22,11 @@ export function MiniCalendar({
range,
rangeStart = "",
rangeEnd = "",
+ minDate = "",
}: MiniCalendarProps) {
const initRaw = range ? rangeStart || value : value;
- const init = /^\d{4}-\d{2}-\d{2}$/.test(initRaw) ? initRaw : todayIso();
+ const fallback = minDate > todayIso() ? minDate : todayIso();
+ const init = /^\d{4}-\d{2}-\d{2}$/.test(initRaw) ? initRaw : fallback;
const [iy, im] = init.split("-").map(Number);
const [viewY, setViewY] = useState(iy);
const [viewM, setViewM] = useState(im);
@@ -94,6 +98,7 @@ export function MiniCalendar({
}
const iso = `${viewY}-${pad2(viewM)}-${pad2(day)}`;
const isToday = iso === today;
+ const beforeMin = Boolean(minDate) && iso < minDate;
const { bg, fg, radius, filled } = getMiniCalendarCellStyle({
iso,
value,
@@ -107,8 +112,9 @@ export function MiniCalendar({
-
+
>
);
}
diff --git a/src/app/(protected)/workorders/_components/wizard/wizard-step-location-poc-fields.tsx b/src/app/(protected)/workorders/_components/wizard/wizard-step-location-poc-fields.tsx
index 61bf4927..c7916686 100644
--- a/src/app/(protected)/workorders/_components/wizard/wizard-step-location-poc-fields.tsx
+++ b/src/app/(protected)/workorders/_components/wizard/wizard-step-location-poc-fields.tsx
@@ -26,6 +26,7 @@ export function WizardStepLocationPocFields({
onAdditionalContactsChange={(contacts) => onUpdate("additionalContacts", contacts)}
helperText="Auto-filled from records — edit if outdated"
showPrimaryErrors={showErrors && pocIncomplete}
+ primaryRequired
/>
);
}
diff --git a/src/app/(protected)/workorders/_components/wizard/wizard-step-location-service-select.tsx b/src/app/(protected)/workorders/_components/wizard/wizard-step-location-service-select.tsx
index bfefcf5d..baadd66e 100644
--- a/src/app/(protected)/workorders/_components/wizard/wizard-step-location-service-select.tsx
+++ b/src/app/(protected)/workorders/_components/wizard/wizard-step-location-service-select.tsx
@@ -32,8 +32,10 @@ export function WizardStepLocationServiceSelect({
nextPm !== draft.pm ? { vendorId: "", vendorName: "", techPhone: "" } : {};
const selectSvc = (p: string) => {
+ const selected = services.find((service) => service.value === p);
onPatch({
pm: p,
+ serviceId: selected?.id ?? null,
extraServices: [],
...clearVendorIfPrimaryChanged(p),
});
@@ -48,7 +50,7 @@ export function WizardStepLocationServiceSelect({
icon={
}
- searchPlaceholder="Search PM type…"
+ searchPlaceholder="Search services…"
options={services.map((s) => {
const Icon = getPmTypeIcon(s.value);
return {
diff --git a/src/app/(protected)/workorders/_components/wizard/wizard-step-type-schedule.tsx b/src/app/(protected)/workorders/_components/wizard/wizard-step-type-schedule.tsx
index f4df71a3..7a655742 100644
--- a/src/app/(protected)/workorders/_components/wizard/wizard-step-type-schedule.tsx
+++ b/src/app/(protected)/workorders/_components/wizard/wizard-step-type-schedule.tsx
@@ -29,6 +29,10 @@ import {
import { WizardSeverityPicker } from "@/app/(protected)/workorders/_components/wizard/wizard-severity-picker";
import { CheckCircle2, Clock, Flame, Users, Wrench, Zap } from "lucide-react";
import type { ElementType } from "react";
+import {
+ clearDueDateBeforeSchedule,
+ resolveDueDateFloor,
+} from "@/domain/work-orders/utils/due-date-floor";
const WO_TYPE_ICONS: Record
= {
PM: Wrench,
@@ -165,6 +169,7 @@ function WizardTypeScheduleDates({ draft, onUpdate, onPatch }: WizardTypeSchedul
onChange={(iso) =>
onPatch(
withAutoScheduleStatus(draft, {
+ ...clearDueDateBeforeSchedule(draft.dueDate, iso),
scheduledOn: iso,
scheduleWeekOnly: false,
scheduleEnd: "",
@@ -177,6 +182,7 @@ function WizardTypeScheduleDates({ draft, onUpdate, onPatch }: WizardTypeSchedul
onChangeWeek={(w) =>
onPatch(
withAutoScheduleStatus(draft, {
+ ...clearDueDateBeforeSchedule(draft.dueDate, w),
scheduledOn: w,
scheduleWeekOnly: Boolean(w),
scheduleEnd: "",
@@ -189,6 +195,7 @@ function WizardTypeScheduleDates({ draft, onUpdate, onPatch }: WizardTypeSchedul
onChangeRange={(s, e) =>
onPatch(
withAutoScheduleStatus(draft, {
+ ...clearDueDateBeforeSchedule(draft.dueDate, s),
scheduledOn: s,
scheduleEnd: e,
schedMode: "range",
@@ -211,6 +218,7 @@ function WizardTypeScheduleDates({ draft, onUpdate, onPatch }: WizardTypeSchedul
onUpdate("dueDate", iso)}
/>
@@ -262,9 +270,23 @@ export function WizardStepTypeSchedule({
{
+ const typeChanged = t !== draft.type;
onPatch({
type: t,
severity: nextSeverityForType(draft.type, t, draft.severity),
+ // A registry service is scoped to its work-order type, so a service picked
+ // under the previous type fails backend ResolveServiceAsync (SH-187/#131).
+ // Clear the service (and its vendor, filtered by the service) on a type change.
+ ...(typeChanged
+ ? {
+ pm: "",
+ serviceId: null,
+ extraServices: [],
+ vendorId: "",
+ vendorName: "",
+ techPhone: "",
+ }
+ : {}),
});
}}
/>
diff --git a/src/app/(protected)/workorders/_hooks/use-work-orders-board-source.ts b/src/app/(protected)/workorders/_hooks/use-work-orders-board-source.ts
index 7522bb47..cbc1da83 100644
--- a/src/app/(protected)/workorders/_hooks/use-work-orders-board-source.ts
+++ b/src/app/(protected)/workorders/_hooks/use-work-orders-board-source.ts
@@ -33,7 +33,8 @@ export function useWorkOrdersBoardSource(filters: FiltersReturn): WorkOrdersBoar
() =>
buildResolvedBoardSearchParams({
advApplied: filters.advApplied,
- search: filters.search,
+ // Advanced Filters are global by design; the week-scoped keyword box has no effect.
+ search: "",
page: filters.page,
pageSize: filters.pageSize,
sortBy: filters.sortBy,
@@ -43,7 +44,6 @@ export function useWorkOrdersBoardSource(filters: FiltersReturn): WorkOrdersBoar
}),
[
filters.advApplied,
- filters.search,
filters.page,
filters.pageSize,
filters.sortBy,
diff --git a/src/app/(protected)/workorders/_hooks/use-work-orders-list-page.ts b/src/app/(protected)/workorders/_hooks/use-work-orders-list-page.ts
index 266d84e3..182a98e5 100644
--- a/src/app/(protected)/workorders/_hooks/use-work-orders-list-page.ts
+++ b/src/app/(protected)/workorders/_hooks/use-work-orders-list-page.ts
@@ -8,6 +8,7 @@ import {
} from "@/domain/work-orders/use-cases/use-work-order-detail";
import { useWorkOrderUsers } from "@/domain/work-orders/use-cases/use-work-orders-list";
import { useWorkOrderTableMutations } from "@/domain/work-orders/use-cases/use-work-order-table-mutations";
+import { shouldCompleteAfterCompletionDoc } from "@/domain/work-orders/utils/completion-doc-auto-complete";
import {
patchWorkOrderAsCanceled,
patchWorkOrderAsCompleted,
@@ -112,7 +113,17 @@ export function useWorkOrdersListPage() {
generatedAt: data.generatedAt,
};
setCompletionDocs((prev) => ({ ...prev, [String(row.id)]: nextData }));
- await patchFieldAsync(row.id, { docStatus: status });
+ const saved = await patchFieldAsync(row.id, { docStatus: status });
+ if (saved.kind !== "board" || !shouldCompleteAfterCompletionDoc(status, saved.row)) {
+ return;
+ }
+ try {
+ // Generation is the one automatic completion — no confirmation dialog.
+ await patchFieldAsync(row.id, { status: "Completed" }, saved.row);
+ } catch {
+ // The document is saved; the table mutation already surfaced the status error and
+ // refetched, so the WO stays in its prior status for a manual retry.
+ }
};
return {
diff --git a/src/app/(protected)/workorders/index.tsx b/src/app/(protected)/workorders/index.tsx
index 571251cb..e12e040d 100644
--- a/src/app/(protected)/workorders/index.tsx
+++ b/src/app/(protected)/workorders/index.tsx
@@ -43,10 +43,12 @@ export default function WorkOrdersListPage() {
actions={
filters.setAdvOpen(true)}
onNewWorkOrder={() => page.setWizardOpen(true)}
activeFilterCount={filters.activeFilterCount}
+ advancedFiltersActive={filters.advApplied != null}
isFetching={tableData.isFetching && !tableData.isLoading}
/>
}
diff --git a/src/config/menu.ts b/src/config/menu.ts
index 3974c0dc..c5b6fce4 100644
--- a/src/config/menu.ts
+++ b/src/config/menu.ts
@@ -10,6 +10,7 @@ import {
Bell,
BarChart3,
Star,
+ Users,
} from "lucide-react";
export type NavItemDef = {
@@ -58,6 +59,10 @@ export const navGroups: NavGroup[] = [
{ label: "Sites", icon: MapPin, path: "/locations" },
],
},
+ {
+ title: "TEAM",
+ items: [{ label: "Team Members", icon: Users, path: "/team-members" }],
+ },
// {
// title: "INTERNAL",
// items: [{ label: "Documents", icon: FileText, path: "/documents" }],
diff --git a/src/domain/services/api/services-api.ts b/src/domain/services/api/services-api.ts
new file mode 100644
index 00000000..58ba217c
--- /dev/null
+++ b/src/domain/services/api/services-api.ts
@@ -0,0 +1,30 @@
+import { apiGet } from "@/api/api";
+import { API_PATHS } from "@/api/api-paths";
+import { handleApiResponse } from "@/api/handle-api-response";
+import { mapServices } from "@/domain/services/mappers/service-mapper";
+import type { Service } from "@/domain/services/types/service";
+import { WORK_ORDER_TYPE_API } from "@/domain/work-orders/types/work-order-board";
+import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
+
+const TYPE_TO_API: Record, number> = {
+ PM: WORK_ORDER_TYPE_API.PM,
+ Reactive: WORK_ORDER_TYPE_API.Reactive,
+ Emergency: WORK_ORDER_TYPE_API.Emergency,
+};
+
+export const servicesApi = {
+ getActive: async (): Promise => {
+ const data = await apiGet(API_PATHS.services.list, {
+ searchParams: { isActive: true },
+ });
+ return mapServices(handleApiResponse(data));
+ },
+
+ getActiveForWorkOrderType: async (workOrderType: WOType): Promise => {
+ if (workOrderType === "Overdue") return [];
+ const data = await apiGet(API_PATHS.services.list, {
+ searchParams: { isActive: true, workOrderType: TYPE_TO_API[workOrderType] },
+ });
+ return mapServices(handleApiResponse(data));
+ },
+};
diff --git a/src/domain/services/mappers/service-mapper.ts b/src/domain/services/mappers/service-mapper.ts
new file mode 100644
index 00000000..4b6d6f6e
--- /dev/null
+++ b/src/domain/services/mappers/service-mapper.ts
@@ -0,0 +1,71 @@
+import type { Service } from "@/domain/services/types/service";
+import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
+
+function asRecord(raw: unknown): Record {
+ return typeof raw === "object" && raw !== null ? (raw as Record) : {};
+}
+
+function readId(item: Record): string | number {
+ const value = item.id ?? item.Id;
+ return typeof value === "string" || typeof value === "number" ? value : "";
+}
+
+function readString(item: Record, ...keys: string[]): string {
+ for (const key of keys) {
+ const value = item[key];
+ if (typeof value === "string") return value.trim();
+ }
+ return "";
+}
+
+function readBool(item: Record, ...keys: string[]): boolean {
+ for (const key of keys) {
+ const value = item[key];
+ if (typeof value === "boolean") return value;
+ }
+ return false;
+}
+
+function mapWorkOrderType(value: unknown): WOType | null {
+ if (typeof value === "number") {
+ return value === 2 ? "PM" : value === 3 ? "Emergency" : value === 6 ? "Reactive" : null;
+ }
+ if (typeof value === "string") {
+ const normalized = value.trim().toLowerCase();
+ return normalized === "pm" || normalized === "preventivemaintenance"
+ ? "PM"
+ : normalized === "emergency"
+ ? "Emergency"
+ : normalized === "reactive"
+ ? "Reactive"
+ : null;
+ }
+ return null;
+}
+
+export function mapService(raw: unknown): Service {
+ const item = asRecord(raw);
+ const types = item.supportedWorkOrderTypes ?? item.SupportedWorkOrderTypes;
+ return {
+ id: readId(item),
+ name: readString(item, "name", "Name"),
+ trade: readString(item, "trade", "Trade"),
+ iconKey: readString(item, "iconKey", "IconKey"),
+ requiresCompletionDocument: readBool(
+ item,
+ "requiresCompletionDocument",
+ "RequiresCompletionDocument",
+ ),
+ isActive: readBool(item, "isActive", "IsActive"),
+ supportedWorkOrderTypes: Array.isArray(types)
+ ? types.flatMap((value) => {
+ const mapped = mapWorkOrderType(value);
+ return mapped ? [mapped] : [];
+ })
+ : [],
+ };
+}
+
+export function mapServices(raw: unknown): Service[] {
+ return Array.isArray(raw) ? raw.map(mapService).filter((service) => service.id !== "") : [];
+}
diff --git a/src/domain/services/types/service.ts b/src/domain/services/types/service.ts
new file mode 100644
index 00000000..fa7a87d9
--- /dev/null
+++ b/src/domain/services/types/service.ts
@@ -0,0 +1,11 @@
+import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
+
+export interface Service {
+ id: string | number;
+ name: string;
+ trade: string;
+ iconKey: string;
+ requiresCompletionDocument: boolean;
+ isActive: boolean;
+ supportedWorkOrderTypes: WOType[];
+}
diff --git a/src/domain/services/use-cases/use-services-for-work-order-type.ts b/src/domain/services/use-cases/use-services-for-work-order-type.ts
new file mode 100644
index 00000000..6dd8d4ac
--- /dev/null
+++ b/src/domain/services/use-cases/use-services-for-work-order-type.ts
@@ -0,0 +1,25 @@
+import { useQuery, type UseQueryResult } from "@tanstack/react-query";
+import { servicesApi } from "@/domain/services/api/services-api";
+import type { Service } from "@/domain/services/types/service";
+import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
+import { queryKeys } from "@/infra/query-key/query-key";
+
+export function useServicesForWorkOrderType(
+ workOrderType: WOType | "",
+): UseQueryResult {
+ const effectiveType = workOrderType || "PM";
+ return useQuery({
+ queryKey: queryKeys.services.byWorkOrderType(effectiveType),
+ queryFn: () => servicesApi.getActiveForWorkOrderType(effectiveType),
+ enabled: effectiveType !== "Overdue",
+ staleTime: 60 * 1000,
+ });
+}
+
+export function useActiveServices(): UseQueryResult {
+ return useQuery({
+ queryKey: queryKeys.services.active(),
+ queryFn: () => servicesApi.getActive(),
+ staleTime: 60 * 1000,
+ });
+}
diff --git a/src/domain/team-members/api/team-members-api.ts b/src/domain/team-members/api/team-members-api.ts
new file mode 100644
index 00000000..9b58b486
--- /dev/null
+++ b/src/domain/team-members/api/team-members-api.ts
@@ -0,0 +1,13 @@
+import { apiGet } from "@/api/api";
+import { API_PATHS } from "@/api/api-paths";
+import { handleApiResponse } from "@/api/handle-api-response";
+import { mapTeamMemberListItems } from "@/domain/team-members/mappers/team-member-mapper";
+import type { TeamMemberListResult } from "@/domain/team-members/types/team-member";
+
+export const teamMembersApi = {
+ getList: async (): Promise => {
+ const data = await apiGet(API_PATHS.teamMember.getList);
+ const items = handleApiResponse(data);
+ return { items: mapTeamMemberListItems(Array.isArray(items) ? items : []) };
+ },
+};
diff --git a/src/domain/team-members/mappers/team-member-mapper.ts b/src/domain/team-members/mappers/team-member-mapper.ts
new file mode 100644
index 00000000..ada426ce
--- /dev/null
+++ b/src/domain/team-members/mappers/team-member-mapper.ts
@@ -0,0 +1,45 @@
+import type { TeamMemberListItem } from "@/domain/team-members/types/team-member";
+
+function readString(record: Record, ...keys: string[]): string {
+ for (const key of keys) {
+ const value = record[key];
+ if (typeof value === "string") return value;
+ if (typeof value === "number") return String(value);
+ }
+ return "";
+}
+
+function readBoolean(record: Record, ...keys: string[]): boolean {
+ for (const key of keys) {
+ const value = record[key];
+ if (typeof value === "boolean") return value;
+ if (typeof value === "string") return value.toLowerCase() === "true";
+ }
+ return false;
+}
+
+export function mapTeamMemberListItem(raw: unknown): TeamMemberListItem {
+ const record = (typeof raw === "object" && raw !== null ? raw : {}) as Record;
+ const id = record.id ?? record.Id;
+ const status =
+ readString(record, "status", "Status").toLowerCase() === "inactive" ||
+ readBoolean(record, "isDeleted", "IsDeleted")
+ ? "Inactive"
+ : "Active";
+
+ return {
+ id: typeof id === "string" || typeof id === "number" ? id : "",
+ name: readString(record, "name", "Name"),
+ role: readString(record, "role", "Role", "roleName", "RoleName"),
+ serviceArea: readString(record, "serviceArea", "ServiceArea", "locations", "Locations"),
+ phone: readString(record, "phone", "Phone"),
+ email: readString(record, "email", "Email"),
+ color: readString(record, "color", "Color"),
+ status,
+ isAccountOwner: readBoolean(record, "isAccountOwner", "IsAccountOwner"),
+ };
+}
+
+export function mapTeamMemberListItems(rawItems: unknown[]): TeamMemberListItem[] {
+ return rawItems.map(mapTeamMemberListItem);
+}
diff --git a/src/domain/team-members/types/team-member.ts b/src/domain/team-members/types/team-member.ts
new file mode 100644
index 00000000..9aafdb97
--- /dev/null
+++ b/src/domain/team-members/types/team-member.ts
@@ -0,0 +1,15 @@
+export interface TeamMemberListItem {
+ id: string | number;
+ name: string;
+ role: string;
+ serviceArea: string;
+ phone: string;
+ email: string;
+ color: string;
+ status: "Active" | "Inactive";
+ isAccountOwner: boolean;
+}
+
+export interface TeamMemberListResult {
+ items: TeamMemberListItem[];
+}
diff --git a/src/domain/team-members/use-cases/use-team-members-list.ts b/src/domain/team-members/use-cases/use-team-members-list.ts
new file mode 100644
index 00000000..b22f95e0
--- /dev/null
+++ b/src/domain/team-members/use-cases/use-team-members-list.ts
@@ -0,0 +1,11 @@
+import { useQuery, type UseQueryResult } from "@tanstack/react-query";
+import { teamMembersApi } from "@/domain/team-members/api/team-members-api";
+import type { TeamMemberListResult } from "@/domain/team-members/types/team-member";
+import { queryKeys } from "@/infra/query-key/query-key";
+
+export function useTeamMembersList(): UseQueryResult {
+ return useQuery({
+ queryKey: queryKeys.teamMembers.list(),
+ queryFn: teamMembersApi.getList,
+ });
+}
diff --git a/src/domain/vendors/api/vendors-api.ts b/src/domain/vendors/api/vendors-api.ts
index fda4215e..3d925b76 100644
--- a/src/domain/vendors/api/vendors-api.ts
+++ b/src/domain/vendors/api/vendors-api.ts
@@ -56,6 +56,7 @@ function buildListParams(params: VendorsListParams): Record area.id !== "" && area.name !== "")
+ : [],
locations: Array.isArray(locationsRaw) ? locationsRaw.map(mapFacetLocation) : [],
jobBuckets: Array.isArray(jobBucketsRaw) ? jobBucketsRaw.map(mapFacetJobBucket) : [],
};
diff --git a/src/domain/vendors/mappers/vendor-roster-mapper.ts b/src/domain/vendors/mappers/vendor-roster-mapper.ts
index 27672d30..9fd986d0 100644
--- a/src/domain/vendors/mappers/vendor-roster-mapper.ts
+++ b/src/domain/vendors/mappers/vendor-roster-mapper.ts
@@ -92,10 +92,18 @@ export function mapVendorCompanyRoster(raw: unknown): VendorCompanyRoster {
zip: readString(item, "zip", "Zip", "zipCode", "ZipCode"),
googleMapsUrl: readString(item, "googleMapsUrl", "GoogleMapsUrl"),
notes: readString(item, "notes", "Notes"),
+ areaId: readString(item, "areaId", "AreaId"),
+ areaName: readString(item, "areaName", "AreaName"),
technicians: mapRosterTechnicians(item.technicians ?? item.Technicians),
};
}
+/** Form Area ids are strings; the API takes a positive integer id or null (Unassigned). */
+export function toBackendAreaId(value: unknown): number | null {
+ const parsed = Number(typeof value === "string" ? value.trim() : value);
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
+}
+
export function mapRosterTechnicianToBackend(technician: unknown): Record {
const item = asRecord(technician);
const payload: Record = {
@@ -130,6 +138,11 @@ export function mapVendorRosterToBackend(values: unknown): Record = { ...patch.companyFields };
if (companyFields.companyPhone !== undefined)
companyFields.companyPhone = toCanonicalPhone(companyFields.companyPhone);
+ // An edited Area is sent as an id or an explicit null (Unassigned).
+ if (companyFields.areaId !== undefined)
+ companyFields.areaId = toBackendAreaId(companyFields.areaId);
payload.companyFields = companyFields;
}
return payload;
diff --git a/src/domain/vendors/schemas/vendor-roster-schema.ts b/src/domain/vendors/schemas/vendor-roster-schema.ts
index fb05edee..1f590cbe 100644
--- a/src/domain/vendors/schemas/vendor-roster-schema.ts
+++ b/src/domain/vendors/schemas/vendor-roster-schema.ts
@@ -54,6 +54,8 @@ const baseCompanyFields = {
notes: z
.string()
.max(VENDOR_NOTES_MAX_LENGTH, `Notes must be ${VENDOR_NOTES_MAX_LENGTH} characters or fewer`),
+ // Optional stable Area id; "" means Unassigned. Admin-only to change.
+ areaId: z.string(),
technicians: z.array(rosterTechnicianSchema),
};
@@ -107,5 +109,6 @@ export const emptyVendorCompanyRosterForm: VendorCompanyRosterFormValues = {
state: "",
zip: "",
notes: "",
+ areaId: "",
technicians: [],
};
diff --git a/src/domain/vendors/types/vendor.ts b/src/domain/vendors/types/vendor.ts
index d7747afc..878e2336 100644
--- a/src/domain/vendors/types/vendor.ts
+++ b/src/domain/vendors/types/vendor.ts
@@ -30,6 +30,10 @@ export interface VendorListItem {
tradeSpecialties: string;
isActive: boolean;
preferredContact: VendorPreferredContact;
+ /** Stable Area id as a string; "" when the company is Unassigned. */
+ areaId: string;
+ /** Area display name; "" when the company is Unassigned. */
+ areaName: string;
/** Present on company-grouped directory responses; optional for legacy clients/fixtures. */
technicians?: VendorDirectoryTechnician[];
}
@@ -63,6 +67,8 @@ export interface VendorsListParams {
trades?: string[];
locations?: string[];
jobBuckets?: string[];
+ /** Stable Area ids or the "__unassigned__" sentinel. */
+ areas?: string[];
}
export interface VendorsListResult {
@@ -95,9 +101,19 @@ export interface VendorFacetJobBucket {
label: string;
}
+/** Active Area catalogue option. `id` is the stable areas[n] filter value. */
+export interface VendorFacetArea {
+ id: string;
+ name: string;
+}
+
+/** Wire value that selects companies without an Area. */
+export const VENDOR_AREA_UNASSIGNED = "__unassigned__";
+
export interface VendorFacets {
companies: VendorFacetCompany[];
trades: string[];
+ areas: VendorFacetArea[];
locations: VendorFacetLocation[];
jobBuckets: VendorFacetJobBucket[];
}
@@ -147,6 +163,9 @@ export interface VendorCompanyRoster {
zip: string;
googleMapsUrl: string;
notes: string;
+ /** Stable Area id as a string; "" when the company is Unassigned. */
+ areaId: string;
+ areaName: string;
technicians: VendorRosterTechnician[];
}
diff --git a/src/domain/vendors/use-cases/use-save-vendor-company-roster.ts b/src/domain/vendors/use-cases/use-save-vendor-company-roster.ts
index fdfb055a..89e35054 100644
--- a/src/domain/vendors/use-cases/use-save-vendor-company-roster.ts
+++ b/src/domain/vendors/use-cases/use-save-vendor-company-roster.ts
@@ -38,6 +38,7 @@ const COMPANY_FIELDS = [
"state",
"zip",
"notes",
+ "areaId",
] as const;
const TECHNICIAN_FIELDS = [
diff --git a/src/domain/work-orders/constants/wo-table-header-tooltips.ts b/src/domain/work-orders/constants/wo-table-header-tooltips.ts
new file mode 100644
index 00000000..24ff23be
--- /dev/null
+++ b/src/domain/work-orders/constants/wo-table-header-tooltips.ts
@@ -0,0 +1,17 @@
+/**
+ * Help copy for date-column headers on the work orders board table.
+ * Keyed by the `WO_TABLE_COLS` column key; only columns with copy here show a
+ * header help icon. `appt` (Appt Time) is an intentional open point — do not
+ * add it without a business-rule decision.
+ */
+export const WO_TABLE_HEADER_TOOLTIPS = {
+ sched: "The date the work is planned to happen. Setting it moves the work order to Scheduled.",
+ due: "The deadline for the work — when it must be completed by.",
+ completed: "The date the vendor actually finished the work. Required to complete the work order.",
+} as const;
+
+export function getWoTableHeaderTooltip(colKey: string): string | undefined {
+ return colKey in WO_TABLE_HEADER_TOOLTIPS
+ ? WO_TABLE_HEADER_TOOLTIPS[colKey as keyof typeof WO_TABLE_HEADER_TOOLTIPS]
+ : undefined;
+}
diff --git a/src/domain/work-orders/errors/board-create-errors.ts b/src/domain/work-orders/errors/board-create-errors.ts
new file mode 100644
index 00000000..60437ef2
--- /dev/null
+++ b/src/domain/work-orders/errors/board-create-errors.ts
@@ -0,0 +1,45 @@
+import { isHTTPError, isNetworkError, isTimeoutError } from "ky";
+import { mapHttpStatusToMessage } from "@/api/api-error";
+import {
+ DISPATCH_REQUIRED_MESSAGE,
+ DUPLICATE_WO_NUMBER_MESSAGE,
+} from "@/domain/work-orders/errors/board-patch-errors";
+
+export const BOARD_CREATE_FAILED_MESSAGE = "Unable to create the work order. Please try again.";
+
+/** Statuses whose mapped copy is fixed product text, never the response body. */
+const FIXED_COPY_STATUSES = new Set([401, 403, 404, 500]);
+
+function readErrorCode(data: unknown): string | undefined {
+ if (typeof data !== "object" || data === null) {
+ return undefined;
+ }
+ const record = data as Record;
+ const code = record.code ?? record.Code;
+ return typeof code === "string" ? code : undefined;
+}
+
+/**
+ * why: board create returns backend validation text ("siteCode is required.",
+ * "vendorId is required when setting appointment fields.") that must never reach the
+ * screen. Unknown failures fall back to generic copy, not to `error.message`.
+ */
+export function boardCreateErrorMessage(error: unknown): string {
+ if (isHTTPError(error)) {
+ const code = readErrorCode(error.data);
+ if (code === "DispatchRequired") {
+ return DISPATCH_REQUIRED_MESSAGE;
+ }
+ if (code === "DuplicateWoNumber") {
+ return DUPLICATE_WO_NUMBER_MESSAGE;
+ }
+ const status = error.response.status;
+ return FIXED_COPY_STATUSES.has(status)
+ ? mapHttpStatusToMessage(status)
+ : BOARD_CREATE_FAILED_MESSAGE;
+ }
+ if (isNetworkError(error) || isTimeoutError(error)) {
+ return error.message;
+ }
+ return BOARD_CREATE_FAILED_MESSAGE;
+}
diff --git a/src/domain/work-orders/errors/board-patch-errors.ts b/src/domain/work-orders/errors/board-patch-errors.ts
index d4e9fdbd..98481f87 100644
--- a/src/domain/work-orders/errors/board-patch-errors.ts
+++ b/src/domain/work-orders/errors/board-patch-errors.ts
@@ -1,3 +1,5 @@
+import { isNetworkError, isTimeoutError } from "ky";
+import { ApiError, mapHttpStatusToMessage } from "@/api/api-error";
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
export class BoardPatchConflictError extends Error {
@@ -22,10 +24,66 @@ export class BoardPatchValidationError extends Error {
}
}
-/** why: backend field names must never be exposed through user-facing board toasts. */
+export const DISPATCH_REQUIRED_MESSAGE = "Select a vendor company before saving.";
+
+export const BOARD_PATCH_FAILED_MESSAGE = "Unable to save the work order. Please try again.";
+
+export const NO_PERSISTABLE_FIELDS_MESSAGE =
+ "These changes cannot be saved on the board. Refresh and edit a supported field.";
+
+export const DUPLICATE_WO_NUMBER_MESSAGE =
+ "This work order number is already assigned to another work order.";
+
+const KNOWN_VALIDATION_COPY: ReadonlyMap = new Map([
+ ["DispatchRequired", DISPATCH_REQUIRED_MESSAGE],
+ ["NoPersistableFields", NO_PERSISTABLE_FIELDS_MESSAGE],
+ // why: editing a WO number to one that already exists returns 422 DuplicateWoNumber;
+ // show the same product copy as create, not the generic save-failed fallback.
+ ["DuplicateWoNumber", DUPLICATE_WO_NUMBER_MESSAGE],
+]);
+
+/**
+ * why: board PATCH validation text ("vendorId is required…", object ids, backend codes)
+ * must never reach the screen. Unknown codes fall back to generic copy, not `error.message`.
+ */
export function boardPatchValidationMessage(error: BoardPatchValidationError): string {
- if (error.code === "DispatchRequired") {
- return "Select a vendor company before saving.";
- }
- return error.message;
+ return KNOWN_VALIDATION_COPY.get(error.code) ?? BOARD_PATCH_FAILED_MESSAGE;
+}
+
+export const BOARD_PATCH_CONFLICT_MESSAGE =
+ "This work order was changed by someone else. Refresh to see the latest before saving again.";
+
+export const PARTIAL_SAVE_PREFIX = "Some changes were saved, but the rest were not.";
+
+/** Statuses whose mapped copy is fixed product text, never the response body. */
+const FIXED_COPY_STATUSES = new Set([401, 403, 404, 500]);
+
+/** why: any board edit failure toast must use product copy, never backend text or field keys. */
+export function boardPatchErrorMessage(error: unknown): string {
+ if (error instanceof BoardPatchConflictError) {
+ return BOARD_PATCH_CONFLICT_MESSAGE;
+ }
+ if (error instanceof BoardPatchValidationError) {
+ return boardPatchValidationMessage(error);
+ }
+ if (error instanceof ApiError && FIXED_COPY_STATUSES.has(error.status)) {
+ return mapHttpStatusToMessage(error.status);
+ }
+ if (isNetworkError(error) || isTimeoutError(error)) {
+ return error.message;
+ }
+ return BOARD_PATCH_FAILED_MESSAGE;
+}
+
+/** Thrown when a multi-field board edit fails after some fields already persisted. */
+export class BoardPatchPartialSaveError extends Error {
+ readonly partialRow: WorkOrderTableRow;
+ readonly failure: unknown;
+
+ constructor(partialRow: WorkOrderTableRow, failure: unknown) {
+ super(`${PARTIAL_SAVE_PREFIX} ${boardPatchErrorMessage(failure)}`);
+ this.name = "BoardPatchPartialSaveError";
+ this.partialRow = partialRow;
+ this.failure = failure;
+ }
}
diff --git a/src/domain/work-orders/mappers/assign-wizard-service-poc-fields.ts b/src/domain/work-orders/mappers/assign-wizard-service-poc-fields.ts
index 32e87840..e45381e7 100644
--- a/src/domain/work-orders/mappers/assign-wizard-service-poc-fields.ts
+++ b/src/domain/work-orders/mappers/assign-wizard-service-poc-fields.ts
@@ -19,6 +19,10 @@ export function assignWizardServicePocFields(
payload.primaryService = primaryService;
}
+ if (draft.serviceId != null) {
+ payload.serviceId = draft.serviceId;
+ }
+
const serviceNotes = trimOrUndefined(draft.pmNote);
if (serviceNotes) {
diff --git a/src/domain/work-orders/mappers/work-order-table-row-mapper.ts b/src/domain/work-orders/mappers/work-order-table-row-mapper.ts
index d1d4afc3..2f019989 100644
--- a/src/domain/work-orders/mappers/work-order-table-row-mapper.ts
+++ b/src/domain/work-orders/mappers/work-order-table-row-mapper.ts
@@ -400,6 +400,7 @@ export function mapWorkOrderTableRow(raw: unknown): WorkOrderTableRow {
locationId:
typeof locationIdRaw === "string" || typeof locationIdRaw === "number" ? locationIdRaw : "",
pm: readString(item, "pm", "PM", "problem", "Problem", "service", "Service", "trade", "Trade"),
+ serviceId: readNumber(item, "serviceId", "ServiceId"),
serviceNotes: readString(item, "serviceNotes", "ServiceNotes", "pmNote", "PmNote"),
extraServices: readStringArray(item, "extraServices", "ExtraServices"),
vendorId: vendorIdNum != null ? String(vendorIdNum) : "",
diff --git a/src/domain/work-orders/types/work-order-board.ts b/src/domain/work-orders/types/work-order-board.ts
index 4c5606b4..b7f2693a 100644
--- a/src/domain/work-orders/types/work-order-board.ts
+++ b/src/domain/work-orders/types/work-order-board.ts
@@ -105,6 +105,8 @@ export interface WorkOrderBoardCreatePayload {
trade?: string;
/** Primary service label; persisted as board `pm`. */
primaryService?: string;
+ /** Registry service identity; the backend validates active/type-compatible selections. */
+ serviceId?: string | number;
/** Services beyond primary; order preserved. */
extraServices?: string[];
/** Issue detail from Service & Notes (`pmNote` in draft). */
@@ -171,6 +173,7 @@ export interface WorkOrderBoardRowApi {
originalDate?: string | null;
originalWeek?: string | null;
workOrderType?: number | null;
+ serviceId?: number | null;
isPastDue?: boolean;
siteCode?: string | null;
locationName?: string | null;
diff --git a/src/domain/work-orders/types/work-order-table-row.ts b/src/domain/work-orders/types/work-order-table-row.ts
index d362f931..179f6c95 100644
--- a/src/domain/work-orders/types/work-order-table-row.ts
+++ b/src/domain/work-orders/types/work-order-table-row.ts
@@ -60,6 +60,7 @@ export interface WorkOrderTableRow {
location: string;
locationId: string | number;
pm: string;
+ serviceId?: string | number | null;
/** Issue detail from Service & Notes. */
serviceNotes: string;
/** Additional services beyond primary `pm`. */
diff --git a/src/domain/work-orders/types/work-order-wizard.ts b/src/domain/work-orders/types/work-order-wizard.ts
index f13b387e..ca1e94ad 100644
--- a/src/domain/work-orders/types/work-order-wizard.ts
+++ b/src/domain/work-orders/types/work-order-wizard.ts
@@ -37,6 +37,8 @@ export interface WorkOrderWizardDraft {
scheduledOn: string;
dueDate: string;
pm: string;
+ /** Registry service selected for this work order; null keeps the optional field empty. */
+ serviceId: string | number | null;
/** Extra services beyond primary `pm` (Service & Notes). */
extraServices: string[];
/** Free-text note attached to the service (Service & Notes). */
@@ -82,6 +84,7 @@ export const EMPTY_WIZARD_DRAFT: WorkOrderWizardDraft = {
scheduledOn: "",
dueDate: "",
pm: "",
+ serviceId: null,
extraServices: [],
pmNote: "",
avetaRequired: false,
diff --git a/src/domain/work-orders/use-cases/use-create-work-order-from-wizard.ts b/src/domain/work-orders/use-cases/use-create-work-order-from-wizard.ts
index 205f010e..4aa4c8b8 100644
--- a/src/domain/work-orders/use-cases/use-create-work-order-from-wizard.ts
+++ b/src/domain/work-orders/use-cases/use-create-work-order-from-wizard.ts
@@ -4,6 +4,8 @@ import { toast } from "react-toastify";
import { workOrdersApi } from "@/domain/work-orders/api/work-orders-api";
+import { boardCreateErrorMessage } from "@/domain/work-orders/errors/board-create-errors";
+
import type { WorkOrderDetail } from "@/domain/work-orders/types/work-order";
import type { WorkOrderWizardDraft } from "@/domain/work-orders/types/work-order-wizard";
@@ -27,7 +29,7 @@ export function useCreateWorkOrderFromWizard(
},
onError: (error: Error) => {
- toast.error(error.message || "Failed to create work order");
+ toast.error(boardCreateErrorMessage(error));
},
});
}
diff --git a/src/domain/work-orders/use-cases/use-work-order-table-mutations.ts b/src/domain/work-orders/use-cases/use-work-order-table-mutations.ts
index 6922c367..c0fbbe65 100644
--- a/src/domain/work-orders/use-cases/use-work-order-table-mutations.ts
+++ b/src/domain/work-orders/use-cases/use-work-order-table-mutations.ts
@@ -3,9 +3,11 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "react-toastify";
import { workOrdersApi } from "@/domain/work-orders/api/work-orders-api";
import {
- boardPatchValidationMessage,
+ boardPatchErrorMessage,
BoardPatchConflictError,
+ BoardPatchPartialSaveError,
BoardPatchValidationError,
+ NO_PERSISTABLE_FIELDS_MESSAGE,
} from "@/domain/work-orders/errors/board-patch-errors";
import { mapApiStatusToWizard } from "@/domain/work-orders/mappers/wizard-draft-mapper";
import {
@@ -58,10 +60,7 @@ async function applyBoardFieldOps(
): Promise {
const ops = expandTablePatchToBoardFieldOps(patch);
if (ops.length === 0) {
- throw new BoardPatchValidationError(
- "NoPersistableFields",
- "These changes cannot be saved on the board. Refresh and edit a supported field.",
- );
+ throw new BoardPatchValidationError("NoPersistableFields", NO_PERSISTABLE_FIELDS_MESSAGE);
}
const current = getRow?.(id);
@@ -77,14 +76,7 @@ async function applyBoardFieldOps(
completedOps += 1;
} catch (error) {
if (completedOps > 0) {
- const field = op.field;
- const partial = new Error(
- `Schedule update partially saved (${completedOps}/${ops.length} fields). Failed on "${field}": ${
- error instanceof Error ? error.message : "Unknown error"
- }`,
- );
- (partial as Error & { partialRow?: WorkOrderTableRow }).partialRow = latest;
- throw partial;
+ throw new BoardPatchPartialSaveError(latest, error);
}
throw error;
}
@@ -134,11 +126,17 @@ export function useWorkOrderTableMutations(
mutationFn: ({
id,
persistPatch,
+ baseRow,
}: {
id: string | number;
patch: WorkOrderTablePatch;
persistPatch: WorkOrderTablePatch;
- }) => enqueuePatch(id, () => runWorkOrderTablePatch(id, persistPatch, getRow)),
+ /** Server row from a just-settled patch; its rowVersion is fresher than the table snapshot. */
+ baseRow?: WorkOrderTableRow;
+ }) =>
+ enqueuePatch(id, () =>
+ runWorkOrderTablePatch(id, persistPatch, baseRow ? () => baseRow : getRow),
+ ),
onMutate: async ({ id, persistPatch }) => {
onPatch(id, persistPatch);
},
@@ -149,9 +147,8 @@ export function useWorkOrderTableMutations(
invalidate();
},
onError: (error: Error, { id }) => {
- const partialRow = (error as Error & { partialRow?: WorkOrderTableRow }).partialRow;
- if (partialRow) {
- onPatch(id, partialRow);
+ if (error instanceof BoardPatchPartialSaveError) {
+ onPatch(id, error.partialRow);
toast.error(error.message);
invalidate();
return;
@@ -159,13 +156,10 @@ export function useWorkOrderTableMutations(
if (error instanceof BoardPatchConflictError && error.currentState) {
onPatch(id, error.currentState);
- toast.error(error.message || "Conflict — refreshed with latest data");
- } else if (error instanceof BoardPatchValidationError) {
- clearPatch(id);
- toast.error(boardPatchValidationMessage(error));
+ toast.error(boardPatchErrorMessage(error));
} else {
clearPatch(id);
- toast.error(error.message || "Failed to update work order");
+ toast.error(boardPatchErrorMessage(error));
}
invalidate();
},
@@ -182,9 +176,13 @@ export function useWorkOrderTableMutations(
);
};
- const patchFieldAsync = (id: string | number, patch: WorkOrderTablePatch) => {
- const persistPatch = resolvePatch(id, patch);
- return patchMutation.mutateAsync({ id, patch, persistPatch });
+ const patchFieldAsync = (
+ id: string | number,
+ patch: WorkOrderTablePatch,
+ baseRow?: WorkOrderTableRow,
+ ) => {
+ const persistPatch = baseRow ? mergeAutoSchedulePatch(baseRow, patch) : resolvePatch(id, patch);
+ return patchMutation.mutateAsync({ id, patch, persistPatch, baseRow });
};
return {
diff --git a/src/domain/work-orders/utils/board-audit-action-rules.ts b/src/domain/work-orders/utils/board-audit-action-rules.ts
index 4a9a4c72..e522356f 100644
--- a/src/domain/work-orders/utils/board-audit-action-rules.ts
+++ b/src/domain/work-orders/utils/board-audit-action-rules.ts
@@ -39,24 +39,53 @@ function formatSeverityAuditLabel(raw: string): string {
return raw;
}
-function tryTypeRule({ fieldKey, actionKey, newValue }: AuditActionRuleContext): string | null {
+const CLEARED_AUDIT_VALUE: FormattedAuditValue = { text: "—", isQuotedList: false };
+
+/** `from X to Y` whenever the previous value is known; a cleared value reads as "—". */
+function formatFieldChangeSentence(
+ label: string,
+ oldValue: FormattedAuditValue,
+ newValue: FormattedAuditValue,
+): string | null {
+ if (!oldValue.text && !newValue.text) return null;
+ const next = wrapAuditValue(newValue.text ? newValue : CLEARED_AUDIT_VALUE);
+ if (oldValue.text) {
+ return `Changed ${label} from ${wrapAuditValue(oldValue)} to ${next}`;
+ }
+ return `Changed ${label} to ${next}`;
+}
+
+function tryTypeRule({
+ fieldKey,
+ actionKey,
+ oldValue,
+ newValue,
+}: AuditActionRuleContext): string | null {
const matches =
fieldKey === "type" ||
fieldKey === "workordertype" ||
fieldKey === "wotype" ||
actionKey === "typechanged" ||
actionKey.includes("workordertype");
- if (!matches || !newValue.text) return null;
+ if (!matches) return null;
- return `Changed Type to ${wrapAuditValue(newValue)}`;
+ return formatFieldChangeSentence("Type", oldValue, newValue);
}
-function trySeverityRule({ fieldKey, actionKey, newValue }: AuditActionRuleContext): string | null {
- const matches = fieldKey.includes("severity") || actionKey.includes("severity");
- if (!matches || !newValue.text) return null;
+function severityValue(value: FormattedAuditValue): FormattedAuditValue {
+ return value.text ? { text: formatSeverityAuditLabel(value.text), isQuotedList: false } : value;
+}
- const labeled = { text: formatSeverityAuditLabel(newValue.text), isQuotedList: false };
- return `Changed Severity to ${wrapAuditValue(labeled)}`;
+function trySeverityRule({
+ fieldKey,
+ actionKey,
+ oldValue,
+ newValue,
+}: AuditActionRuleContext): string | null {
+ const matches = fieldKey.includes("severity") || actionKey.includes("severity");
+ if (!matches) return null;
+
+ return formatFieldChangeSentence("Severity", severityValue(oldValue), severityValue(newValue));
}
function tryStatusRule({
diff --git a/src/domain/work-orders/utils/completion-doc-auto-complete.ts b/src/domain/work-orders/utils/completion-doc-auto-complete.ts
new file mode 100644
index 00000000..e27f0318
--- /dev/null
+++ b/src/domain/work-orders/utils/completion-doc-auto-complete.ts
@@ -0,0 +1,25 @@
+import type { CompDocSaveStatus } from "@/domain/work-orders/types/completion-doc";
+import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
+import {
+ getClosabilityGaps,
+ tableRowToClosabilityInput,
+} from "@/domain/work-orders/utils/wo-closability";
+
+/**
+ * Completion is manual with confirmation, except that generating the completion document
+ * completes the WO — but only when the closability gate passes on the persisted row.
+ * Not-required (NN) and drafts never complete; Past Due rows must be
+ * rescheduled before any status change, so they are left for the dispatcher.
+ */
+export function shouldCompleteAfterCompletionDoc(
+ status: CompDocSaveStatus,
+ row: WorkOrderTableRow,
+): boolean {
+ if (status !== "Yes" || row.docStatus !== "Yes") {
+ return false;
+ }
+ if (row.status === "Completed" || row.status === "Canceled" || row.isPastDue) {
+ return false;
+ }
+ return getClosabilityGaps(tableRowToClosabilityInput(row)).length === 0;
+}
diff --git a/src/domain/work-orders/utils/due-date-floor.ts b/src/domain/work-orders/utils/due-date-floor.ts
new file mode 100644
index 00000000..95f8eb54
--- /dev/null
+++ b/src/domain/work-orders/utils/due-date-floor.ts
@@ -0,0 +1,27 @@
+/**
+ * SH-356: a Due Date can never be earlier than Schedule On.
+ *
+ * The floor is the concrete Schedule On day, the start of a date range, or — for a
+ * week-only schedule (SH-110) — the first day of the target week.
+ */
+export function resolveDueDateFloor(schedule: {
+ scheduledOn?: string | null;
+ targetWeek?: string | null;
+}): string {
+ return schedule.scheduledOn?.trim() || schedule.targetWeek?.trim() || "";
+}
+
+export function isDueDateBeforeFloor(dueDate: string | null | undefined, floor: string): boolean {
+ return Boolean(dueDate && floor && dueDate < floor);
+}
+
+/**
+ * Patch fragment for a Schedule On change: clears an existing Due Date that the new
+ * schedule would leave in the past. Never bumps it to a guessed value.
+ */
+export function clearDueDateBeforeSchedule(
+ dueDate: string | null | undefined,
+ nextFloor: string,
+): { dueDate?: string } {
+ return isDueDateBeforeFloor(dueDate, nextFloor) ? { dueDate: "" } : {};
+}
diff --git a/src/domain/work-orders/utils/format-audit-timestamp.ts b/src/domain/work-orders/utils/format-audit-timestamp.ts
new file mode 100644
index 00000000..4d987df4
--- /dev/null
+++ b/src/domain/work-orders/utils/format-audit-timestamp.ts
@@ -0,0 +1,24 @@
+const AUDIT_DATE_PATTERN = /\b\d{1,2}\/\d{1,2}(\/\d{2,4})?\b/;
+
+/**
+ * Every entry, manual or system, shows a complete timestamp — `09/15/2026 · 7:42 PM`.
+ * Pre-formatted API strings are kept only when they already carry a calendar date.
+ */
+export function formatAuditTimestamp(value: string): string {
+ if (!value) return "";
+ if (AUDIT_DATE_PATTERN.test(value) && /\b(AM|PM)\b/i.test(value)) return value;
+
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return value;
+
+ const datePart = date.toLocaleDateString("en-US", {
+ month: "2-digit",
+ day: "2-digit",
+ year: "numeric",
+ });
+ const timePart = date.toLocaleTimeString("en-US", {
+ hour: "numeric",
+ minute: "2-digit",
+ });
+ return `${datePart} · ${timePart}`;
+}
diff --git a/src/domain/work-orders/utils/format-board-audit-action.ts b/src/domain/work-orders/utils/format-board-audit-action.ts
index 05ebe168..e29cbcbd 100644
--- a/src/domain/work-orders/utils/format-board-audit-action.ts
+++ b/src/domain/work-orders/utils/format-board-audit-action.ts
@@ -127,6 +127,10 @@ function formatGenericAuditFallback(args: {
if (newValue.text) {
return `Changed ${label} to ${wrapAuditValue(newValue)}`;
}
- if (action) return action;
+ if (oldValue.text) {
+ return `Changed ${label} from ${wrapAuditValue(oldValue)} to "—"`;
+ }
+ // Never surface a raw audit enum such as "FieldChanged" as the sentence.
+ if (fieldName && action) return `Updated ${label}`;
return "Updated work order";
}
diff --git a/src/domain/work-orders/utils/partition-slide-over-media.ts b/src/domain/work-orders/utils/partition-slide-over-media.ts
index 5de1e4ad..7092c696 100644
--- a/src/domain/work-orders/utils/partition-slide-over-media.ts
+++ b/src/domain/work-orders/utils/partition-slide-over-media.ts
@@ -12,6 +12,11 @@ const EMPTY_OWNERSHIP: MediaSurfaceOwnership = {
extraOwnedIds: new Set(),
};
+/** Only Reactive and Emergency work orders render a media gallery on the Completion tab. */
+export function hasCompletionMediaGallery(type: string | null | undefined): boolean {
+ return type === "Emergency" || type === "Reactive";
+}
+
function isPhotoOrVideo(item: MediaFile): boolean {
return item.fileType === "image" || item.fileType === "video";
}
@@ -24,20 +29,25 @@ function isInFlight(item: MediaFile): boolean {
export function isCompletionSurfaceMedia(
item: MediaFile,
ownership: MediaSurfaceOwnership = EMPTY_OWNERSHIP,
+ completionHasGallery = true,
): boolean {
if (isInFlight(item)) return true;
if (COMPLETION_PURPOSES.has(item.purpose ?? "")) return true;
+ if (!completionHasGallery && item.purpose === "Extra") return false;
if (ownership.completionOwnedIds.has(item.id)) return true;
if (ownership.extraOwnedIds.has(item.id)) return false;
return item.purpose === "Extra" && isPhotoOrVideo(item);
}
+/** Without a Completion gallery, every Extra item (including photos/videos) belongs to Extras. */
export function isExtrasSurfaceMedia(
item: MediaFile,
ownership: MediaSurfaceOwnership = EMPTY_OWNERSHIP,
+ completionHasGallery = true,
): boolean {
if (item.purpose === "Aveta") return true;
if (item.purpose !== "Extra") return false;
+ if (!completionHasGallery) return true;
if (ownership.completionOwnedIds.has(item.id)) return false;
if (ownership.extraOwnedIds.has(item.id)) return true;
return !isPhotoOrVideo(item);
diff --git a/src/domain/work-orders/utils/wo-lifecycle-transitions.ts b/src/domain/work-orders/utils/wo-lifecycle-transitions.ts
index 264344eb..f0184ef9 100644
--- a/src/domain/work-orders/utils/wo-lifecycle-transitions.ts
+++ b/src/domain/work-orders/utils/wo-lifecycle-transitions.ts
@@ -11,8 +11,21 @@ import {
UPLIFT_PENDING_COMPLETED_TITLE,
} from "@/domain/work-orders/utils/wo-closability";
-/** AAP `ALL_STATUSES` — Canceled is kebab-only. */
-export const BOARD_INLINE_STATUSES: readonly WizardWOStatus[] = ALL_WIZARD_STATUSES;
+/**
+ * Lifecycle states the server derives (Incomplete from create, Scheduled from Schedule On).
+ * Past Due is an overlay, not a status. None of these may be picked manually on an existing WO.
+ */
+export const AUTOMATIC_LIFECYCLE_STATUSES: readonly WizardWOStatus[] = ["Incomplete", "Scheduled"];
+
+/** Manually selectable statuses for an existing WO — Canceled is kebab-only. */
+export const BOARD_INLINE_STATUSES: readonly WizardWOStatus[] = ALL_WIZARD_STATUSES.filter(
+ (status) => !AUTOMATIC_LIFECYCLE_STATUSES.includes(status),
+);
+
+/** Inline options for an existing WO never repeat its current status. */
+export function getInlineStatusTransitions(currentStatus: string): WizardWOStatus[] {
+ return BOARD_INLINE_STATUSES.filter((status) => status !== currentStatus);
+}
/** AAP `CREATION_STATUSES` — wizard Step 3 and inline create. */
export const CREATION_INLINE_STATUSES: readonly WizardWOStatus[] = [
diff --git a/src/domain/work-orders/utils/wo-number-input.ts b/src/domain/work-orders/utils/wo-number-input.ts
new file mode 100644
index 00000000..7f3ae624
--- /dev/null
+++ b/src/domain/work-orders/utils/wo-number-input.ts
@@ -0,0 +1,33 @@
+import { isRealWoNumber } from "@/domain/work-orders/utils/wo-closability";
+
+/** Board WO numbers are an 11-digit APM number or an SH placeholder of at most 11 characters. */
+export const BOARD_WO_NUMBER_MAX_LENGTH = 11;
+
+export const WO_NUMBER_FORMAT_MESSAGE =
+ "Work order number must be 11 digits or an SH number (e.g. SH00001)";
+
+export const WO_NUMBER_DOWNGRADE_MESSAGE =
+ "Cannot replace an APM work order number with an internal number";
+
+export function sanitizeBoardWoNumberInput(raw: string): string {
+ return raw
+ .replace(/[^a-zA-Z0-9]/g, "")
+ .toUpperCase()
+ .slice(0, BOARD_WO_NUMBER_MAX_LENGTH);
+}
+
+export function isProvisionalWoNumber(woNumber: string): boolean {
+ return /^SH/i.test(woNumber.trim());
+}
+
+export function isValidBoardWoNumber(woNumber: string): boolean {
+ return /^\d{11}$/.test(woNumber) || /^SH\d{1,9}$/i.test(woNumber);
+}
+
+/**
+ * Only an already-saved real APM number is protected from being replaced by an
+ * SH placeholder. A brand-new WO has no saved number, so the rule never applies there.
+ */
+export function isWoNumberDowngrade(savedWoNumber: string, nextWoNumber: string): boolean {
+ return isRealWoNumber(savedWoNumber) && isProvisionalWoNumber(nextWoNumber);
+}
diff --git a/src/infra/query-key/query-key.ts b/src/infra/query-key/query-key.ts
index c4a9e284..e094cf8b 100644
--- a/src/infra/query-key/query-key.ts
+++ b/src/infra/query-key/query-key.ts
@@ -47,6 +47,10 @@ export const queryKeys = {
[...queryKeys.employees.all, "list", params ?? {}] as const,
detail: (id: string | number) => [...queryKeys.employees.all, "detail", id] as const,
},
+ teamMembers: {
+ all: ["teamMembers"] as const,
+ list: () => [...queryKeys.teamMembers.all, "list"] as const,
+ },
dashboard: {
all: ["dashboard"] as const,
stats: () => [...queryKeys.dashboard.all, "stats"] as const,
@@ -56,6 +60,12 @@ export const queryKeys = {
byCategory: (category: string, parent?: string) =>
[...queryKeys.dropdownOptions.all, "byCategory", category, parent ?? ""] as const,
},
+ services: {
+ all: ["services"] as const,
+ active: () => [...queryKeys.services.all, "active"] as const,
+ byWorkOrderType: (workOrderType: string) =>
+ [...queryKeys.services.all, "byWorkOrderType", workOrderType] as const,
+ },
locations: {
all: ["locations"] as const,
list: (params?: Record) =>
diff --git a/src/test/app/(protected)/vendors/use-vendor-roster-form.test.tsx b/src/test/app/(protected)/vendors/use-vendor-roster-form.test.tsx
index 3202bd40..031b589e 100644
--- a/src/test/app/(protected)/vendors/use-vendor-roster-form.test.tsx
+++ b/src/test/app/(protected)/vendors/use-vendor-roster-form.test.tsx
@@ -68,6 +68,8 @@ const roster: VendorCompanyRoster = {
zip: "63101",
googleMapsUrl: "",
notes: "",
+ areaId: "",
+ areaName: "",
technicians: [],
};
@@ -134,6 +136,7 @@ function submitValues(
state: "MO",
zip: "63101",
notes: "",
+ areaId: "",
technicians,
};
}
@@ -300,6 +303,7 @@ describe("useVendorRosterForm prototype defaults", () => {
state: "",
zip: "",
notes: "",
+ areaId: "",
technicians: [
{
contactName: "",
diff --git a/src/test/app/(protected)/vendors/vendor-create-modal.test.tsx b/src/test/app/(protected)/vendors/vendor-create-modal.test.tsx
index e96fd031..355f99f1 100644
--- a/src/test/app/(protected)/vendors/vendor-create-modal.test.tsx
+++ b/src/test/app/(protected)/vendors/vendor-create-modal.test.tsx
@@ -12,6 +12,8 @@ import {
type VendorCompanyRosterFormValues,
} from "@/domain/vendors/schemas/vendor-roster-schema";
import { renderWithProviders } from "@/test/test-utils";
+import type { StateCode } from "@/data/areas";
+import { pickVendorState } from "./vendor-state-select";
vi.mock("@/domain/vendors/use-cases/use-vendor-facets", () => ({
useVendorFacets: () => ({ data: { companies: [], trades: [] }, isLoading: false }),
@@ -58,16 +60,18 @@ async function fillCompanyNameAndSubmit(name = "Gateway Plumbing") {
await userEvent.click(screen.getByRole("button", { name: "Add Vendor" }));
}
-function fillRequiredAddress({ street = "6735 Trippel Rd", city = "Theodore", state = "AL" } = {}) {
+function fillRequiredAddress({
+ street = "6735 Trippel Rd",
+ city = "Theodore",
+ state = "AL" as StateCode,
+} = {}) {
fireEvent.change(screen.getByRole("combobox", { name: "Street Address (required)" }), {
target: { value: street },
});
fireEvent.change(screen.getByRole("textbox", { name: "City (required)" }), {
target: { value: city },
});
- fireEvent.change(screen.getByRole("textbox", { name: "State (required)" }), {
- target: { value: state },
- });
+ pickVendorState(state);
}
describe("VendorCreateModal validation", () => {
diff --git a/src/test/app/(protected)/vendors/vendor-detail-drawer.test.tsx b/src/test/app/(protected)/vendors/vendor-detail-drawer.test.tsx
index 8777567d..0da2e959 100644
--- a/src/test/app/(protected)/vendors/vendor-detail-drawer.test.tsx
+++ b/src/test/app/(protected)/vendors/vendor-detail-drawer.test.tsx
@@ -39,6 +39,8 @@ const vendor: VendorListItem = {
tradeSpecialties: "",
isActive: true,
preferredContact: "Phone",
+ areaId: "",
+ areaName: "",
};
function rosterWith(technicians: Array>) {
@@ -57,6 +59,8 @@ function rosterWith(technicians: Array>) {
zip: "",
googleMapsUrl: "",
notes: "",
+ areaId: "",
+ areaName: "",
technicians,
},
isLoading: false,
diff --git a/src/test/app/(protected)/vendors/vendor-roster-address-fields.test.tsx b/src/test/app/(protected)/vendors/vendor-roster-address-fields.test.tsx
index 28a3b106..2a3bcc81 100644
--- a/src/test/app/(protected)/vendors/vendor-roster-address-fields.test.tsx
+++ b/src/test/app/(protected)/vendors/vendor-roster-address-fields.test.tsx
@@ -11,11 +11,15 @@ import {
} from "@/domain/vendors/schemas/vendor-roster-schema";
import { suggestAddresses } from "@/lib/address/vendor-address";
import { renderWithProviders } from "@/test/test-utils";
+import { formatStateOptionLabel, normalizeStateCode } from "@/data/areas";
+import { pickVendorState, stateField } from "./vendor-state-select";
const TYPED_STREET = "415 Murphy Rd";
const FIRST_SUGGESTION = suggestAddresses(TYPED_STREET)[0];
if (FIRST_SUGGESTION == null) throw new Error("expected a suggestion for the typed street");
+const FIRST_SUGGESTION_STATE = normalizeStateCode(FIRST_SUGGESTION.state);
+if (FIRST_SUGGESTION_STATE == null) throw new Error("expected a canonical suggestion state");
function AddressFormHarness({
onValid,
@@ -67,9 +71,7 @@ describe("VendorRosterFormFields address autocomplete", () => {
expect(screen.getByRole("textbox", { name: "City (required)" })).toHaveValue(
FIRST_SUGGESTION.city,
);
- expect(screen.getByRole("textbox", { name: "State (required)" })).toHaveValue(
- FIRST_SUGGESTION.state,
- );
+ expect(stateField()).toHaveValue(formatStateOptionLabel(FIRST_SUGGESTION_STATE));
});
it("submits the settled structured parts, not the option label", async () => {
@@ -104,14 +106,12 @@ describe("VendorRosterFormFields address autocomplete", () => {
expect(screen.getByRole("textbox", { name: "City (required)" })).toHaveValue(
FIRST_SUGGESTION.city,
);
- expect(screen.getByRole("textbox", { name: "State (required)" })).toHaveValue(
- FIRST_SUGGESTION.state,
- );
+ expect(stateField()).toHaveValue(formatStateOptionLabel(FIRST_SUGGESTION_STATE));
await user.click(screen.getByRole("button", { name: "Clear" }));
expect(street).toHaveValue("");
expect(screen.getByRole("textbox", { name: "City (required)" })).toHaveValue("");
- expect(screen.getByRole("textbox", { name: "State (required)" })).toHaveValue("");
+ expect(stateField()).toHaveValue("");
});
});
@@ -132,9 +132,7 @@ describe("VendorRosterFormFields map preview empty state", () => {
fireEvent.change(screen.getByRole("textbox", { name: "City (required)" }), {
target: { value: "Theodore" },
});
- fireEvent.change(screen.getByRole("textbox", { name: "State (required)" }), {
- target: { value: "AL" },
- });
+ pickVendorState("AL");
expect(await screen.findByTitle(`Map of ${TYPED_STREET} Theodore AL`)).toBeInTheDocument();
expect(screen.queryByRole("status")).not.toBeInTheDocument();
diff --git a/src/test/app/(protected)/vendors/vendor-service-area.test.tsx b/src/test/app/(protected)/vendors/vendor-service-area.test.tsx
new file mode 100644
index 00000000..bb19416a
--- /dev/null
+++ b/src/test/app/(protected)/vendors/vendor-service-area.test.tsx
@@ -0,0 +1,197 @@
+import { fireEvent, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { describe, expect, it, vi } from "vitest";
+import { VendorRosterFormFields } from "@/app/(protected)/vendors/_components/vendor-roster-form-fields";
+import { SERVICE_AREA_ADMIN_ONLY_MESSAGE } from "@/app/(protected)/vendors/_components/vendor-service-area-field";
+import { VendorFilterOptions } from "@/app/(protected)/vendors/_components/vendor-filter-options";
+import {
+ emptyVendorFilters,
+ serviceAreaFilterOptions,
+} from "@/app/(protected)/vendors/_components/vendor-filters";
+import {
+ emptyVendorCompanyRosterForm,
+ vendorCompanyRosterSchema,
+ type VendorCompanyRosterFormValues,
+} from "@/domain/vendors/schemas/vendor-roster-schema";
+import { VENDOR_AREA_UNASSIGNED, type VendorFacetArea } from "@/domain/vendors/types/vendor";
+import {
+ mapVendorRosterAdditivePatchToBackend,
+ mapVendorRosterToBackend,
+} from "@/domain/vendors/mappers/vendor-roster-mapper";
+import { mapVendorFacets, mapVendorListItem } from "@/domain/vendors/mappers/vendor-mapper";
+import { renderWithProviders } from "@/test/test-utils";
+import { pickVendorState, stateField } from "./vendor-state-select";
+
+const AREAS: VendorFacetArea[] = [
+ { id: "1", name: "East" },
+ { id: "2", name: "Central" },
+];
+
+function Harness({
+ canAssignArea,
+ currentArea = null,
+ defaults = {},
+ onValid,
+}: {
+ canAssignArea: boolean;
+ currentArea?: VendorFacetArea | null;
+ defaults?: Partial;
+ onValid: (values: VendorCompanyRosterFormValues) => void;
+}) {
+ const { control, handleSubmit, formState } = useForm({
+ defaultValues: { ...emptyVendorCompanyRosterForm, ...defaults },
+ resolver: zodResolver(vendorCompanyRosterSchema),
+ mode: "onChange",
+ });
+ return (
+
+ );
+}
+
+const COMPLETE_COMPANY: Partial = {
+ name: "Gateway Plumbing",
+ companyPhone: "(314) 555-0100",
+ address: "1 Market St",
+ city: "St. Louis",
+ state: "MO",
+};
+
+describe("Vendor Service Area field", () => {
+ it("lets an admin assign one Service Area by stable id", async () => {
+ const onValid = vi.fn();
+ renderWithProviders(, {
+ withAuth: false,
+ });
+
+ const area = screen.getByRole("combobox", { name: "Service Area (optional)" });
+ expect(area).toBeEnabled();
+ fireEvent.change(area, { target: { value: "Cen" } });
+ fireEvent.click(screen.getByRole("option", { name: "Central" }));
+ await userEvent.click(screen.getByRole("button", { name: "Submit" }));
+
+ await waitFor(() => expect(onValid).toHaveBeenCalledTimes(1));
+ expect((onValid.mock.calls[0]?.[0] as VendorCompanyRosterFormValues).areaId).toBe("2");
+ });
+
+ it("shows the saved Area read-only to non-admins and keeps it on submit", async () => {
+ const onValid = vi.fn();
+ renderWithProviders(
+ ,
+ { withAuth: false },
+ );
+
+ const area = screen.getByRole("combobox", { name: "Service Area (optional)" });
+ expect(area).toBeDisabled();
+ expect(area).toHaveValue("Archived Zone");
+ expect(screen.getByText(SERVICE_AREA_ADMIN_ONLY_MESSAGE)).toBeInTheDocument();
+ await userEvent.click(screen.getByRole("button", { name: "Submit" }));
+
+ await waitFor(() => expect(onValid).toHaveBeenCalledTimes(1));
+ expect((onValid.mock.calls[0]?.[0] as VendorCompanyRosterFormValues).areaId).toBe("9");
+ });
+
+ it("does not derive the Service Area from the selected State", () => {
+ renderWithProviders(, { withAuth: false });
+
+ pickVendorState("CA");
+
+ expect(stateField()).toHaveValue("California (CA)");
+ expect(screen.getByRole("combobox", { name: "Service Area (optional)" })).toHaveValue("");
+ expect(screen.queryByText(/Area:/)).not.toBeInTheDocument();
+ });
+});
+
+describe("Vendor State field", () => {
+ it("is a closed list: free text is not kept and legacy names show as codes", () => {
+ renderWithProviders(
+ ,
+ { withAuth: false },
+ );
+
+ expect(stateField()).toHaveValue("Missouri (MO)");
+ fireEvent.change(stateField(), { target: { value: "Ontario" } });
+ expect(screen.queryByRole("option", { name: /Ontario/ })).not.toBeInTheDocument();
+ fireEvent.blur(stateField());
+ expect(stateField()).toHaveValue("Missouri (MO)");
+ });
+});
+
+describe("Service Area contracts", () => {
+ it("orders filter options Unassigned first, then names A–Z", () => {
+ expect(
+ serviceAreaFilterOptions([
+ { id: "3", name: "West" },
+ { id: "4", name: "california" },
+ { id: "1", name: "East" },
+ ]).map((option) => option.id),
+ ).toEqual([VENDOR_AREA_UNASSIGNED, "4", "1", "3"]);
+ });
+
+ it("maps facet areas and directory Area fields from the API", () => {
+ expect(
+ mapVendorFacets({
+ Areas: [
+ { Id: 1, Name: "East" },
+ { Id: 0, Name: "" },
+ ],
+ }).areas,
+ ).toEqual([{ id: "1", name: "East" }]);
+ const row = mapVendorListItem({ Id: 1, AreaId: 2, AreaName: "Central" });
+ expect(row.areaId).toBe("2");
+ expect(row.areaName).toBe("Central");
+ });
+
+ it("round-trips form Areas, sends explicit null for Unassigned, and omits absent Areas", () => {
+ expect(mapVendorRosterToBackend({ name: "A", areaId: "3" }).areaId).toBe(3);
+ expect(mapVendorRosterToBackend({ name: "A", areaId: "" }).areaId).toBeNull();
+ expect(mapVendorRosterToBackend({ name: "A" })).not.toHaveProperty("areaId");
+ expect(
+ mapVendorRosterAdditivePatchToBackend({
+ rowVersion: "rv",
+ addTechnicians: [],
+ companyFields: { areaId: "" },
+ }).companyFields,
+ ).toEqual({ areaId: null });
+ expect(
+ mapVendorRosterAdditivePatchToBackend({ rowVersion: "rv", addTechnicians: [] }),
+ ).not.toHaveProperty("companyFields");
+ });
+});
+
+describe("Vendor Service Area filter section", () => {
+ it("sits between Trade and Location", () => {
+ const setDraft = vi.fn();
+ renderWithProviders(
+ ,
+ { withAuth: false },
+ );
+
+ expect(screen.getAllByRole("button").map((button) => button.textContent)).toEqual([
+ "Company",
+ "Trade",
+ "Service Area",
+ "Location",
+ "Total Jobs",
+ ]);
+ });
+});
diff --git a/src/test/app/(protected)/vendors/vendor-state-select.ts b/src/test/app/(protected)/vendors/vendor-state-select.ts
new file mode 100644
index 00000000..f8694649
--- /dev/null
+++ b/src/test/app/(protected)/vendors/vendor-state-select.ts
@@ -0,0 +1,15 @@
+import { fireEvent, screen } from "@testing-library/react";
+import { formatStateOptionLabel, type StateCode } from "@/data/areas";
+
+export const STATE_FIELD_NAME = "State (required)";
+
+export function stateField(): HTMLElement {
+ return screen.getByRole("combobox", { name: STATE_FIELD_NAME });
+}
+
+/** Picks a state from the closed vendor State list by its option label. */
+export function pickVendorState(code: StateCode): void {
+ const label = formatStateOptionLabel(code);
+ fireEvent.change(stateField(), { target: { value: label } });
+ fireEvent.click(screen.getByRole("option", { name: label }));
+}
diff --git a/src/test/app/(protected)/vendors/vendors-list.test.tsx b/src/test/app/(protected)/vendors/vendors-list.test.tsx
index ab905729..2b98c7f0 100644
--- a/src/test/app/(protected)/vendors/vendors-list.test.tsx
+++ b/src/test/app/(protected)/vendors/vendors-list.test.tsx
@@ -46,6 +46,8 @@ const activeVendor: VendorListItem = {
tradeSpecialties: "Backflow Preventers",
isActive: true,
preferredContact: "Email",
+ areaId: "",
+ areaName: "",
};
const inactiveVendor = {
@@ -67,6 +69,8 @@ const activeRoster: VendorCompanyRoster = {
zip: "",
googleMapsUrl: "",
notes: "",
+ areaId: "",
+ areaName: "",
technicians: [
{
id: 1,
@@ -668,4 +672,30 @@ describe("VendorsListPage", () => {
expect(screen.getByRole("tab", { name: "Active (3)" })).toBeInTheDocument();
expect(screen.getByRole("tab", { name: "Inactive (2)" })).toBeInTheDocument();
});
+
+ it("shows the Service Area column after State with Unassigned for companies without an Area", () => {
+ setupDefaults();
+ const assigned: VendorListItem = { ...activeVendor, areaId: "1", areaName: "East" };
+ const unassigned: VendorListItem = {
+ ...activeVendor,
+ id: 9,
+ companyId: "co-9",
+ companyName: "No Area Co",
+ };
+ useVendorDirectoryList.mockImplementation(
+ (params: { isActive?: boolean; pageSize?: number }) => {
+ if (params.pageSize === 1) return result([], 2);
+ return params.isActive ? result([assigned, unassigned], 2) : result([], 0);
+ },
+ );
+
+ renderWithProviders(, { route: "/vendors", withAuth: false });
+
+ const headers = screen.getAllByRole("columnheader").map((header) => header.textContent);
+ expect(headers.indexOf("Service Area")).toBe(headers.indexOf("State") + 1);
+ expect(headers.indexOf("Trade")).toBe(headers.indexOf("Service Area") + 1);
+ expect(
+ screen.getAllByTestId("vendor-text-service-area").map((cell) => cell.textContent),
+ ).toEqual(["East", "Unassigned"]);
+ });
});
diff --git a/src/test/app/(protected)/workorders/due-date-schedule-floor.test.tsx b/src/test/app/(protected)/workorders/due-date-schedule-floor.test.tsx
new file mode 100644
index 00000000..e6c41d50
--- /dev/null
+++ b/src/test/app/(protected)/workorders/due-date-schedule-floor.test.tsx
@@ -0,0 +1,194 @@
+import { fireEvent, render, renderHook, screen, within } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { SlideOverInfoTabEditView } from "@/app/(protected)/workorders/_components/detail/tabs/slide-over-info-tab-edit-view";
+import { WoTableInlineRow } from "@/app/(protected)/workorders/_components/list/table/wo-table-inline-row";
+import { useWoTableRowHandlers } from "@/app/(protected)/workorders/_components/list/table/use-wo-table-row-handlers";
+import { MiniCalendar } from "@/app/(protected)/workorders/_components/wizard/mini-calendar";
+import { WizardStepTypeSchedule } from "@/app/(protected)/workorders/_components/wizard/wizard-step-type-schedule";
+import { EMPTY_TABLE_DRAFT } from "@/domain/work-orders/types/work-order-table-row";
+import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
+import { EMPTY_WIZARD_DRAFT } from "@/domain/work-orders/types/work-order-wizard";
+import { pad2, todayIso } from "@/domain/work-orders/utils/wizard-date-utils";
+import { renderWithProviders } from "@/test/test-utils";
+
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/site-cell", () => ({
+ SiteCell: () => null,
+}));
+vi.mock(
+ "@/app/(protected)/workorders/_components/list/table/cells/editable-wo-number-cell",
+ () => ({ EditableWONumberCell: () => null }),
+);
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/type-cell", () => ({
+ TypeCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/assigned-to-cell", () => ({
+ AssignedToCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/appt-time-cell", () => ({
+ ApptTimeCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/pm-type-cell", () => ({
+ PMTypeCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/vendor-cell", () => ({
+ VendorCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/status-cell", () => ({
+ StatusCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/reschedule-notify", () => ({
+ rescheduleNotify: vi.fn(),
+ weekMoveNotify: vi.fn(),
+}));
+
+function day(n: number): string {
+ const [y, m] = todayIso().split("-").map(Number);
+ return `${y}-${pad2(m)}-${pad2(n)}`;
+}
+
+function rowByLabel(label: string) {
+ return screen.getByText(label, { selector: "span,label,div" }).closest("div")!;
+}
+
+describe("Due Date cannot be before Schedule On (SH-356)", () => {
+ it("disables calendar days before the floor", () => {
+ render();
+
+ expect(screen.getByRole("button", { name: "9" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "10" })).toBeEnabled();
+ expect(screen.getByRole("button", { name: "11" })).toBeEnabled();
+ });
+
+ describe("slide-over edit", () => {
+ const draft = { scheduledOn: day(10), dueDate: day(12) } as Partial;
+
+ function renderSlideOver(onDraftChange = vi.fn()) {
+ renderWithProviders(
+ ,
+ );
+ return onDraftChange;
+ }
+
+ it("disables Due Date days before Schedule On", async () => {
+ renderSlideOver();
+ fireEvent.click(within(rowByLabel("Due Date")).getByRole("button"));
+
+ expect(await screen.findByRole("button", { name: "9" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "10" })).toBeEnabled();
+ });
+
+ it("clears the Due Date when Schedule On moves past it", async () => {
+ const onDraftChange = renderSlideOver();
+ fireEvent.click(within(rowByLabel("Schedule On")).getAllByRole("button")[0]);
+ fireEvent.click(await screen.findByRole("button", { name: "15" }));
+
+ expect(onDraftChange).toHaveBeenCalledWith(
+ expect.objectContaining({ scheduledOn: day(15), dueDate: "" }),
+ );
+ });
+ });
+
+ it("wizard: clears Due Date on a later Schedule On and floors the Due Date picker", async () => {
+ const onPatch = vi.fn();
+ render(
+ ,
+ );
+
+ const dueDateButtons = within(rowByLabel("Due Date").parentElement!).getAllByRole("button");
+ fireEvent.click(dueDateButtons[dueDateButtons.length - 1]);
+ expect(await screen.findByRole("button", { name: "9" })).toBeDisabled();
+ fireEvent.keyDown(document.activeElement ?? document.body, { key: "Escape" });
+
+ const scheduleBlock = rowByLabel("Schedule On").parentElement!;
+ const scheduleButtons = within(scheduleBlock).getAllByRole("button");
+ fireEvent.click(scheduleButtons[scheduleButtons.length - 1]);
+ const calendars = await screen.findAllByRole("button", { name: "15" });
+ fireEvent.click(calendars[calendars.length - 1]);
+
+ expect(onPatch).toHaveBeenCalledWith(
+ expect.objectContaining({ scheduledOn: day(15), dueDate: "" }),
+ );
+ });
+
+ it("inline creation row: clears Due Date on a later Schedule On", async () => {
+ const onChange = vi.fn();
+ renderWithProviders(
+ ,
+ { withAuth: false },
+ );
+
+ const cells = screen.getAllByRole("cell");
+ const dateButtons = cells.flatMap((cell) => within(cell).queryAllByRole("button"));
+ const scheduleButton = dateButtons.find(
+ (b) => b.textContent?.includes(day(10).slice(5).replace("-", "/")) ?? false,
+ );
+ fireEvent.click(scheduleButton ?? dateButtons[0]);
+ fireEvent.click(await screen.findByRole("button", { name: "15" }));
+
+ expect(onChange).toHaveBeenCalledWith(
+ expect.objectContaining({ scheduledOn: day(15), dueDate: "" }),
+ );
+ });
+
+ it("board row: sends the Due Date clear in the same schedule patch", () => {
+ const onPatch = vi.fn();
+ const { result } = renderHook(() =>
+ useWoTableRowHandlers({
+ tableData: {
+ dragState: { current: { dragId: null, overId: null } },
+ setDragViz: vi.fn(),
+ reorderRows: vi.fn(),
+ endDrag: vi.fn(),
+ revealScheduledRow: vi.fn(),
+ setSelectedId: vi.fn(),
+ } as never,
+ weekMonday: "2026-05-18",
+ onNavigateToDay: vi.fn(),
+ onOpenSlideOver: vi.fn(),
+ onOpenMedia: vi.fn(),
+ onPatch,
+ onScheduleHighlight: vi.fn(),
+ }),
+ );
+
+ result.current.onScheduleDate("wo-1", "2026-05-21", "2026-05-20");
+ expect(onPatch).toHaveBeenLastCalledWith("wo-1", expect.objectContaining({ dueDate: "" }));
+
+ result.current.onScheduleRange("wo-1", "2026-05-19", "2026-05-22", "2026-05-20");
+ expect(onPatch.mock.lastCall?.[1]).not.toHaveProperty("dueDate");
+
+ result.current.onScheduleWeek("wo-1", "2026-05-25", "2026-05-20");
+ expect(onPatch).toHaveBeenLastCalledWith(
+ "wo-1",
+ expect.objectContaining({ targetWeek: "2026-05-25", dueDate: "" }),
+ );
+ });
+});
diff --git a/src/test/app/(protected)/workorders/editable-wo-number-cell-sh-placeholder.test.tsx b/src/test/app/(protected)/workorders/editable-wo-number-cell-sh-placeholder.test.tsx
new file mode 100644
index 00000000..ad16d2e8
--- /dev/null
+++ b/src/test/app/(protected)/workorders/editable-wo-number-cell-sh-placeholder.test.tsx
@@ -0,0 +1,105 @@
+import { fireEvent, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { toast } from "react-toastify";
+import { EditableWONumberCell } from "@/app/(protected)/workorders/_components/list/table/cells/editable-wo-number-cell";
+import { workOrdersApi } from "@/domain/work-orders/api/work-orders-api";
+import { renderWithProviders } from "@/test/test-utils";
+
+vi.mock("react-toastify", () => {
+ const toastFn = Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn() });
+ return { toast: toastFn };
+});
+
+vi.mock("@/domain/work-orders/api/work-orders-api", () => ({
+ workOrdersApi: { findByWoNumber: vi.fn() },
+}));
+
+function renderCell(value: string, currentId: string | number) {
+ const onSave = vi.fn();
+ renderWithProviders(
+ ,
+ );
+ return onSave;
+}
+
+function typeAndCommit(nextValue: string) {
+ fireEvent.click(screen.getByText(/./, { selector: "span" }));
+ const input = screen.getByLabelText("Work order number");
+ fireEvent.change(input, { target: { value: nextValue } });
+ fireEvent.keyDown(input, { key: "Enter" });
+}
+
+describe("EditableWONumberCell SH placeholder numbers", () => {
+ beforeEach(() => {
+ vi.mocked(workOrdersApi.findByWoNumber).mockResolvedValue(null as never);
+ vi.mocked(toast).mockClear();
+ vi.mocked(toast.error).mockClear();
+ });
+
+ it("saves a freshly typed SH number on a brand-new inline work order", async () => {
+ const onSave = renderCell("", "draft");
+
+ typeAndCommit("SH00001");
+
+ await waitFor(() => expect(onSave).toHaveBeenCalledWith("SH00001"));
+ expect(toast).not.toHaveBeenCalled();
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it("keeps a typed SH prefix instead of stripping it to digits", () => {
+ renderCell("", "draft");
+
+ fireEvent.click(screen.getByText("-"));
+ const input = screen.getByLabelText("Work order number");
+ fireEvent.change(input, { target: { value: "sh00001" } });
+
+ expect(input).toHaveValue("SH00001");
+ });
+
+ it("does not treat an unsaved inline draft number as a real number to protect", async () => {
+ const onSave = renderCell("12345678901", "draft");
+
+ typeAndCommit("SH00002");
+
+ await waitFor(() => expect(onSave).toHaveBeenCalledWith("SH00002"));
+ });
+
+ it("blocks replacing a saved real APM number with an SH number", async () => {
+ const onSave = renderCell("12345678901", 42);
+
+ typeAndCommit("SH00001");
+
+ await waitFor(() =>
+ expect(toast.error).toHaveBeenCalledWith(
+ "Cannot replace an APM work order number with an internal number",
+ ),
+ );
+ expect(onSave).not.toHaveBeenCalled();
+ expect(screen.getByText("12345678901")).toBeInTheDocument();
+ });
+
+ it("lets a saved SH number be replaced by a real 11-digit number", async () => {
+ const onSave = renderCell("SH00001", 42);
+
+ typeAndCommit("12345678901");
+
+ await waitFor(() => expect(onSave).toHaveBeenCalledWith("12345678901"));
+ });
+
+ it("still rejects a numeric number that is not 11 digits", () => {
+ const onSave = renderCell("", "draft");
+
+ typeAndCommit("12345");
+
+ expect(toast).toHaveBeenCalledWith(
+ "Work order number must be 11 digits or an SH number (e.g. SH00001)",
+ );
+ expect(onSave).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/test/app/(protected)/workorders/save-existing-row-type.test.ts b/src/test/app/(protected)/workorders/save-existing-row-type.test.ts
index 0ca3f3c9..86b6020c 100644
--- a/src/test/app/(protected)/workorders/save-existing-row-type.test.ts
+++ b/src/test/app/(protected)/workorders/save-existing-row-type.test.ts
@@ -42,6 +42,16 @@ describe("saveExistingRowType", () => {
expect(onPatch.mock.calls[0]![2]).toBeUndefined();
});
+ it("does not warn when moving between SEV 3–5", () => {
+ const onPatch = vi.fn();
+
+ saveExistingRowType(onPatch, { ...row, severity: 5 }, "Reactive", 3);
+
+ expect(toastWarn).not.toHaveBeenCalled();
+ expect(onPatch).toHaveBeenCalledWith(7, { type: "Reactive", severity: 3 });
+ expect(onPatch.mock.calls[0]![2]).toBeUndefined();
+ });
+
it("does not warn when clearing severity on a PM correction", () => {
const onPatch = vi.fn();
diff --git a/src/test/app/(protected)/workorders/service-picker-search-placeholder.test.tsx b/src/test/app/(protected)/workorders/service-picker-search-placeholder.test.tsx
new file mode 100644
index 00000000..7a2d7fa1
--- /dev/null
+++ b/src/test/app/(protected)/workorders/service-picker-search-placeholder.test.tsx
@@ -0,0 +1,56 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { WizardStepLocationServiceSelect } from "@/app/(protected)/workorders/_components/wizard/wizard-step-location-service-select";
+import { PmTypePickerPopover } from "@/app/(protected)/workorders/_components/list/table/cells/pm-type-picker-popover";
+import {
+ EMPTY_WIZARD_DRAFT,
+ type WorkOrderWizardDraft,
+} from "@/domain/work-orders/types/work-order-wizard";
+
+describe("service picker search placeholder", () => {
+ it("uses a type-neutral search placeholder in the wizard service picker", () => {
+ const draft: WorkOrderWizardDraft = { ...EMPTY_WIZARD_DRAFT, pm: "" };
+
+ render(
+ ,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /select service/i }));
+
+ expect(screen.getByPlaceholderText("Search services…")).toBeTruthy();
+ expect(screen.queryByPlaceholderText("Search PM type…")).toBeNull();
+ });
+
+ it("uses a type-neutral search placeholder in the table service picker popover", () => {
+ const anchor = document.createElement("button");
+
+ render(
+ ,
+ );
+
+ expect(screen.getByPlaceholderText("Search service…")).toBeTruthy();
+ expect(screen.queryByPlaceholderText("Search PM type…")).toBeNull();
+ });
+});
diff --git a/src/test/app/(protected)/workorders/severity-badge.test.tsx b/src/test/app/(protected)/workorders/severity-badge.test.tsx
new file mode 100644
index 00000000..2beb69ef
--- /dev/null
+++ b/src/test/app/(protected)/workorders/severity-badge.test.tsx
@@ -0,0 +1,47 @@
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, it, vi } from "vitest";
+import { SeverityBadge } from "@/app/(protected)/workorders/_components/list/table/cells/severity-badge";
+
+describe("SeverityBadge", () => {
+ it("shows description, Accept/Respond deadline, and after-hours on hover", async () => {
+ const user = userEvent.setup();
+ render();
+
+ await user.hover(screen.getByText("SEV 1"));
+
+ const tooltip = await screen.findByRole("tooltip");
+ expect(tooltip).toHaveTextContent(
+ "Business Critical Function Down · Accept: 15 min · Respond: 2 hrs · After hours: Yes",
+ );
+ expect(tooltip).not.toHaveTextContent(/Quote|Tech Notes|Invoice|Turnaround/i);
+
+ await user.unhover(screen.getByText("SEV 1"));
+ await waitFor(() => expect(screen.queryByRole("tooltip")).not.toBeInTheDocument());
+ });
+
+ it("transcribes the SEV table row for the given severity", async () => {
+ const user = userEvent.setup();
+ render();
+
+ await user.hover(screen.getByText("SEV 3"));
+
+ expect(await screen.findByRole("tooltip")).toHaveTextContent(
+ "Group Productivity Impaired · Accept: 2 hrs · Respond: 8 hrs (next day if after hours) · After hours: Approval required",
+ );
+ });
+
+ it("is a button only when it can reopen the severity control", async () => {
+ const onClick = vi.fn();
+ const user = userEvent.setup();
+ const { rerender } = render();
+ expect(screen.queryByRole("button")).not.toBeInTheDocument();
+
+ rerender();
+ const badge = screen.getByRole("button");
+ expect(badge).toHaveTextContent("SEV 2");
+ await user.click(badge);
+
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/test/app/(protected)/workorders/slide-over-audit-list-timestamp.test.tsx b/src/test/app/(protected)/workorders/slide-over-audit-list-timestamp.test.tsx
new file mode 100644
index 00000000..ac8d7393
--- /dev/null
+++ b/src/test/app/(protected)/workorders/slide-over-audit-list-timestamp.test.tsx
@@ -0,0 +1,54 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { SlideOverAuditList } from "@/app/(protected)/workorders/_components/detail/slide-over-audit-list";
+import type { WorkOrderAuditEntry } from "@/domain/work-orders/types/work-order";
+
+function statusEntry(overrides: Partial = {}): WorkOrderAuditEntry {
+ return {
+ id: "s1",
+ fieldName: "LifecycleStatus",
+ oldValue: "Pending",
+ newValue: "En Route",
+ action: "StatusChanged",
+ createdAt: "2026-09-15T19:42:00",
+ userName: "Alex Dispatcher",
+ type: "manual",
+ ...overrides,
+ };
+}
+
+describe("SlideOverAuditList timestamps (SH-361)", () => {
+ it("shows the date as well as the time on a manual status change", () => {
+ render();
+
+ expect(screen.getByText('Changed status from "Pending" to "En Route"')).toBeInTheDocument();
+ expect(screen.getByText(/^\d{2}\/\d{2}\/2026 · 7:42 PM$/)).toBeInTheDocument();
+ });
+
+ it("renders a type correction with its previous value (SH-363)", () => {
+ render(
+ ,
+ );
+
+ expect(screen.getByText('Changed Type from "PM" to "Reactive"')).toBeInTheDocument();
+ expect(screen.getByText('Changed Severity from "SEV 3" to "—"')).toBeInTheDocument();
+ expect(screen.queryByText("FieldChanged")).toBeNull();
+ });
+});
diff --git a/src/test/app/(protected)/workorders/slide-over-completion-service-gate.test.tsx b/src/test/app/(protected)/workorders/slide-over-completion-service-gate.test.tsx
new file mode 100644
index 00000000..d87162fe
--- /dev/null
+++ b/src/test/app/(protected)/workorders/slide-over-completion-service-gate.test.tsx
@@ -0,0 +1,46 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { SlideOverCompletionTab } from "@/app/(protected)/workorders/_components/detail/tabs/slide-over-completion-tab";
+import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
+
+function renderTab(pm: string, onOpenCompletionDoc = vi.fn()) {
+ const row = { id: "1", type: "PM", pm, docStatus: "No", rowVersion: "1" } as WorkOrderTableRow;
+ render(
+ ,
+ );
+ return onOpenCompletionDoc;
+}
+
+describe("SlideOverCompletionTab service gate", () => {
+ it("disables the completion document button until a service is selected", () => {
+ const onOpen = renderTab(" ");
+
+ const button = screen.getByRole("button", { name: /select service/i });
+ expect(button).toBeDisabled();
+ expect(
+ screen.getByText("Select a service before opening the completion document."),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /open completion document/i }),
+ ).not.toBeInTheDocument();
+
+ fireEvent.click(button);
+ expect(onOpen).not.toHaveBeenCalled();
+ });
+
+ it("opens the completion document when a service is selected", () => {
+ const onOpen = renderTab("HVAC Inspection");
+
+ const button = screen.getByRole("button", { name: /open completion document/i });
+ expect(button).toBeEnabled();
+ expect(screen.queryByText(/select service/i)).not.toBeInTheDocument();
+
+ fireEvent.click(button);
+ expect(onOpen).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/test/app/(protected)/workorders/slide-over-extras-aveta.test.tsx b/src/test/app/(protected)/workorders/slide-over-extras-aveta.test.tsx
index f788e250..ba674966 100644
--- a/src/test/app/(protected)/workorders/slide-over-extras-aveta.test.tsx
+++ b/src/test/app/(protected)/workorders/slide-over-extras-aveta.test.tsx
@@ -161,4 +161,40 @@ describe("SlideOverExtrasTab Aveta", () => {
expect(screen.getByRole("button", { name: "safety-form.pdf" })).toBeDisabled();
});
+
+ it("labels each extra item with its type and category", () => {
+ const sitePhoto: MediaFile = {
+ id: "m3",
+ name: "site.jpg",
+ fileType: "image",
+ url: "blob:3",
+ category: "Photo",
+ purpose: "Extra",
+ };
+ const walkthrough: MediaFile = {
+ id: "m4",
+ name: "walkthrough.mp4",
+ fileType: "video",
+ url: "blob:4",
+ category: "Video",
+ purpose: "Extra",
+ };
+
+ renderWithProviders(
+ ,
+ );
+
+ expect(screen.getByRole("group", { name: "Photo, Extra: site.jpg" })).toBeInTheDocument();
+ expect(
+ screen.getByRole("group", { name: "Video, Extra: walkthrough.mp4" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("group", { name: "PDF, Aveta: aveta-clearance.pdf" }),
+ ).toBeInTheDocument();
+ });
});
diff --git a/src/test/app/(protected)/workorders/status-cell-closability.test.tsx b/src/test/app/(protected)/workorders/status-cell-closability.test.tsx
index 31c90363..7f42d257 100644
--- a/src/test/app/(protected)/workorders/status-cell-closability.test.tsx
+++ b/src/test/app/(protected)/workorders/status-cell-closability.test.tsx
@@ -1,6 +1,7 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { StatusCell } from "@/app/(protected)/workorders/_components/list/table/cells/status-cell";
+import type { WizardWOStatus } from "@/domain/work-orders/types/work-order-wizard";
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
const incompleteRow = {
@@ -43,21 +44,62 @@ describe("StatusCell closability gate", () => {
expect(screen.queryByRole("button", { name: /^canceled$/i })).toBeNull();
});
- it("disables Scheduled when the row has no concrete date", () => {
+ it.each([
+ "Pending",
+ "En Route",
+ "On Site",
+ "In Progress",
+ "Rescheduled",
+ "Pending Quote",
+ ])("offers only manual transitions away from %s (SH-357, SH-358)", (current) => {
const onChangeStatus = vi.fn();
render(
,
);
- fireEvent.click(screen.getByRole("button", { name: /pending/i }));
- const scheduled = screen.getByRole("button", { name: /^scheduled$/i });
- expect(scheduled).toBeDisabled();
- fireEvent.click(scheduled);
- expect(onChangeStatus).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: new RegExp(current, "i") }));
+ const offered = Array.from(document.querySelectorAll(".MuiPopover-paper button")).map(
+ (button) => button.textContent?.trim(),
+ );
+
+ expect(offered).not.toContain("Incomplete");
+ expect(offered).not.toContain("Scheduled");
+ expect(offered).not.toContain("Past Due");
+ expect(offered).not.toContain("Canceled");
+ expect(offered).not.toContain(current);
+ expect(offered).toEqual(
+ [
+ "Pending",
+ "En Route",
+ "On Site",
+ "In Progress",
+ "Completed",
+ "Rescheduled",
+ "Pending Quote",
+ ].filter((status) => status !== current),
+ );
+ });
+
+ it("offers every manual status, and no automatic one, from Incomplete or Scheduled", () => {
+ for (const current of ["Incomplete", "Scheduled"] as const) {
+ const { unmount } = render(
+ ,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: new RegExp(current, "i") }));
+ expect(screen.getByRole("button", { name: /^pending$/i })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: /^incomplete$/i })).toBeNull();
+ expect(screen.queryByRole("button", { name: /^scheduled$/i })).toBeNull();
+ unmount();
+ }
});
it("limits creation options to Incomplete, Pending, and Scheduled", () => {
diff --git a/src/test/app/(protected)/workorders/use-slide-over-media-state.test.tsx b/src/test/app/(protected)/workorders/use-slide-over-media-state.test.tsx
index 87a74de5..dab9e3bd 100644
--- a/src/test/app/(protected)/workorders/use-slide-over-media-state.test.tsx
+++ b/src/test/app/(protected)/workorders/use-slide-over-media-state.test.tsx
@@ -278,4 +278,53 @@ describe("useSlideOverMediaState completion filter", () => {
expect(remounted.result.current.completionMedia).toHaveLength(0);
expect(remounted.result.current.extrasUploads.map((item) => item.id)).toEqual(["10"]);
});
+
+ it("shows Extra photos and videos in Extra Docs on PM work orders", () => {
+ const detail = detailWithMedia(
+ [
+ {
+ id: "10",
+ category: "Extra",
+ url: "https://cdn.example.com/site.jpg",
+ fileName: "site.jpg",
+ uploadedAt: "2026-07-15T18:00:00.0000000Z",
+ isLegacy: false,
+ },
+ {
+ id: "11",
+ category: "Extra",
+ url: "https://cdn.example.com/walkthrough.mp4",
+ fileName: "walkthrough.mp4",
+ uploadedAt: "2026-07-15T18:00:00.0000000Z",
+ isLegacy: false,
+ },
+ {
+ id: "4",
+ category: "Extra",
+ url: "https://cdn.example.com/extra.pdf",
+ fileName: "extra.pdf",
+ uploadedAt: "2026-07-15T18:00:00.0000000Z",
+ isLegacy: false,
+ },
+ ],
+ { id: 200, type: "PM" },
+ );
+
+ const { result } = renderHook(() =>
+ useSlideOverMediaState({
+ detailForRow: detail,
+ uploadMediaMutation: idleMutation(),
+ deleteMediaMutation: idleMutation(),
+ categorizeMediaMutation: idleMutation(),
+ }),
+ );
+
+ expect(result.current.completionMedia).toHaveLength(0);
+ expect(result.current.extrasUploads.map((item) => item.id)).toEqual(["10", "11", "4"]);
+ expect(result.current.extrasUploads.map((item) => item.fileType)).toEqual([
+ "image",
+ "video",
+ "pdf",
+ ]);
+ });
});
diff --git a/src/test/app/(protected)/workorders/use-work-orders-list-page-completion-doc.test.ts b/src/test/app/(protected)/workorders/use-work-orders-list-page-completion-doc.test.ts
new file mode 100644
index 00000000..60c004c7
--- /dev/null
+++ b/src/test/app/(protected)/workorders/use-work-orders-list-page-completion-doc.test.ts
@@ -0,0 +1,162 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { EMPTY_ADVANCED_FILTERS } from "@/domain/work-orders/types/work-order-advanced-filters";
+import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
+
+const patchField = vi.hoisted(() => vi.fn());
+const patchFieldAsync = vi.hoisted(() => vi.fn());
+
+vi.mock("react-toastify", () => ({
+ toast: {
+ warning: vi.fn(),
+ success: vi.fn(),
+ error: vi.fn(),
+ },
+}));
+
+vi.mock("@/app/(protected)/workorders/_hooks/use-work-orders-list-filters", () => ({
+ useWorkOrdersListFilters: () => ({
+ search: "",
+ handleSearchChange: vi.fn(),
+ advOpen: false,
+ setAdvOpen: vi.fn(),
+ advApplied: null,
+ advInitial: EMPTY_ADVANCED_FILTERS,
+ applyAdvancedFilters: vi.fn(),
+ clearAdvancedFilters: vi.fn(),
+ clearAdvancedFilterChip: vi.fn(),
+ activeFilterCount: 0,
+ weekMonday: "2026-07-20",
+ selectedDayIso: "2026-07-20",
+ setWeekMonday: vi.fn(),
+ setSelectedDayIso: vi.fn(),
+ navigateToDay: vi.fn(),
+ dispatcherIds: new Set(),
+ setDispatcherIds: vi.fn(),
+ types: new Set(),
+ setTypes: vi.fn(),
+ }),
+}));
+
+vi.mock("@/app/(protected)/workorders/_hooks/use-work-orders-table-data", () => ({
+ useWorkOrdersTableData: () => ({
+ rows: [],
+ totalCount: 0,
+ scopeTotalCount: 0,
+ isFetching: false,
+ isLoading: false,
+ setSelectedId: vi.fn(),
+ patchRow: vi.fn(),
+ clearRowPatch: vi.fn(),
+ }),
+}));
+
+vi.mock("@/domain/work-orders/use-cases/use-work-order-table-mutations", () => ({
+ useWorkOrderTableMutations: () => ({
+ patchField,
+ patchFieldAsync,
+ isPending: false,
+ }),
+}));
+
+vi.mock("@/domain/work-orders/use-cases/use-work-orders-list", () => ({
+ useWorkOrderUsers: () => ({ data: [], isLoading: false }),
+}));
+
+vi.mock("@/domain/work-orders/use-cases/use-work-order-detail", () => ({
+ useWorkOrderLocations: () => ({ data: [] }),
+ useWorkOrderVendors: () => ({ data: [] }),
+}));
+
+vi.mock("@/domain/settings/dropdown-options/use-cases/use-dropdown-options-by-category", () => ({
+ useDropdownOptionsByCategory: () => ({ data: [] }),
+}));
+
+import { useWorkOrdersListPage } from "@/app/(protected)/workorders/_hooks/use-work-orders-list-page";
+
+function closableRow(overrides: Partial = {}): WorkOrderTableRow {
+ return {
+ id: 77,
+ woNumber: "24866",
+ type: "PM",
+ dispatcherId: "u1",
+ dispatcherName: "Dispatcher",
+ company: "Vendor Co",
+ vendorId: "7",
+ tech: "Tech One",
+ completedDate: "2026-09-15",
+ pm: "HVAC",
+ status: "In Progress",
+ docStatus: "No",
+ mediaCount: 0,
+ isPastDue: false,
+ rowVersion: "v1",
+ upliftSummary: { hasUplift: false, pendingCount: 0 },
+ ...overrides,
+ } as WorkOrderTableRow;
+}
+
+describe("useWorkOrdersListPage completion document (SH-341)", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("completes the WO without confirmation once Generate persists the document", async () => {
+ const saved = closableRow({ docStatus: "Yes", rowVersion: "v2" });
+ patchFieldAsync.mockResolvedValueOnce({ kind: "board", row: saved });
+ patchFieldAsync.mockResolvedValueOnce({
+ kind: "board",
+ row: { ...saved, status: "Completed" },
+ });
+ const { result } = renderHook(() => useWorkOrdersListPage());
+
+ await result.current.saveCompletionDoc(closableRow(), { notes: "", generatedAt: "now" }, "Yes");
+
+ expect(patchFieldAsync).toHaveBeenNthCalledWith(1, 77, { docStatus: "Yes" });
+ expect(patchFieldAsync).toHaveBeenNthCalledWith(2, 77, { status: "Completed" }, saved);
+ expect(patchField).not.toHaveBeenCalled();
+ expect(result.current.confirmComplete).toBeNull();
+ });
+
+ it("does not complete on Save draft or Not required", async () => {
+ const { result } = renderHook(() => useWorkOrdersListPage());
+
+ patchFieldAsync.mockResolvedValueOnce({ kind: "board", row: closableRow({ docStatus: "No" }) });
+ await result.current.saveCompletionDoc(closableRow(), { notes: "", generatedAt: "" }, "No");
+ patchFieldAsync.mockResolvedValueOnce({ kind: "board", row: closableRow({ docStatus: "NN" }) });
+ await result.current.saveCompletionDoc(closableRow(), { notes: "", generatedAt: "" }, "NN");
+
+ expect(patchFieldAsync).toHaveBeenCalledTimes(2);
+ expect(patchFieldAsync).not.toHaveBeenCalledWith(
+ 77,
+ { status: "Completed" },
+ expect.anything(),
+ );
+ });
+
+ it("keeps the closability gate: a missing service leaves the status unchanged", async () => {
+ patchFieldAsync.mockResolvedValueOnce({
+ kind: "board",
+ row: closableRow({ docStatus: "Yes", pm: "" }),
+ });
+ const { result } = renderHook(() => useWorkOrdersListPage());
+
+ await result.current.saveCompletionDoc(closableRow(), { notes: "", generatedAt: "now" }, "Yes");
+
+ expect(patchFieldAsync).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps the generated document when the automatic completion is rejected", async () => {
+ patchFieldAsync.mockResolvedValueOnce({
+ kind: "board",
+ row: closableRow({ docStatus: "Yes" }),
+ });
+ patchFieldAsync.mockRejectedValueOnce(new Error("Work order was modified."));
+ const { result } = renderHook(() => useWorkOrdersListPage());
+
+ await expect(
+ result.current.saveCompletionDoc(closableRow(), { notes: "", generatedAt: "now" }, "Yes"),
+ ).resolves.toBeUndefined();
+ expect(patchFieldAsync).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/src/test/app/(protected)/workorders/wizard-service-clears-vendor.test.tsx b/src/test/app/(protected)/workorders/wizard-service-clears-vendor.test.tsx
index 3812fb63..c46f95df 100644
--- a/src/test/app/(protected)/workorders/wizard-service-clears-vendor.test.tsx
+++ b/src/test/app/(protected)/workorders/wizard-service-clears-vendor.test.tsx
@@ -79,6 +79,7 @@ describe("WizardStepLocationServiceSelect — vendor clear on service change", (
expect(onPatch).toHaveBeenCalledWith({
pm: "Electrical",
+ serviceId: "3",
extraServices: [],
vendorId: "",
vendorName: "",
diff --git a/src/test/app/(protected)/workorders/wizard-step-type-schedule-clears-service.test.tsx b/src/test/app/(protected)/workorders/wizard-step-type-schedule-clears-service.test.tsx
new file mode 100644
index 00000000..9c9582ee
--- /dev/null
+++ b/src/test/app/(protected)/workorders/wizard-step-type-schedule-clears-service.test.tsx
@@ -0,0 +1,69 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { WizardStepTypeSchedule } from "@/app/(protected)/workorders/_components/wizard/wizard-step-type-schedule";
+import {
+ EMPTY_WIZARD_DRAFT,
+ type WorkOrderWizardDraft,
+} from "@/domain/work-orders/types/work-order-wizard";
+
+const USERS = [{ id: "sarah", name: "Sarah Chen" }];
+
+describe("WizardStepTypeSchedule — service clear on type change", () => {
+ it("clears the service and its vendor when the work-order type changes", () => {
+ const onPatch = vi.fn();
+ const draft: WorkOrderWizardDraft = {
+ ...EMPTY_WIZARD_DRAFT,
+ type: "PM",
+ pm: "HVAC",
+ serviceId: "1",
+ extraServices: ["Plumbing"],
+ vendorId: "9",
+ vendorName: "Old Vendor",
+ techPhone: "555-0100",
+ };
+
+ render(
+ ,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /Reactive/ }));
+
+ expect(onPatch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: "Reactive",
+ pm: "",
+ serviceId: null,
+ extraServices: [],
+ vendorId: "",
+ vendorName: "",
+ techPhone: "",
+ }),
+ );
+ });
+
+ it("keeps the selected service when the same type is re-selected", () => {
+ const onPatch = vi.fn();
+ const draft: WorkOrderWizardDraft = {
+ ...EMPTY_WIZARD_DRAFT,
+ type: "PM",
+ pm: "HVAC",
+ serviceId: "1",
+ extraServices: ["Plumbing"],
+ vendorId: "9",
+ vendorName: "Old Vendor",
+ techPhone: "555-0100",
+ };
+
+ render(
+ ,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /Scheduled preventive maintenance/ }));
+
+ const patch = onPatch.mock.calls[0][0] as Partial;
+ expect(patch).not.toHaveProperty("pm");
+ expect(patch).not.toHaveProperty("serviceId");
+ expect(patch).not.toHaveProperty("extraServices");
+ expect(patch).not.toHaveProperty("vendorId");
+ });
+});
diff --git a/src/test/app/(protected)/workorders/wo-table-column-order.test.tsx b/src/test/app/(protected)/workorders/wo-table-column-order.test.tsx
new file mode 100644
index 00000000..aeee1da9
--- /dev/null
+++ b/src/test/app/(protected)/workorders/wo-table-column-order.test.tsx
@@ -0,0 +1,116 @@
+import { screen, within } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { WO_TABLE_COLS } from "@/app/(protected)/workorders/_components/list/table/wo-table-cols";
+import { WoTableHead } from "@/app/(protected)/workorders/_components/list/table/wo-table-head";
+import { WoTableRowServiceCells } from "@/app/(protected)/workorders/_components/list/table/wo-table-row-service-cells";
+import type { WoTableRowHandlers } from "@/app/(protected)/workorders/_components/list/table/wo-table-row";
+import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
+import { renderWithProviders } from "@/test/test-utils";
+
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/pm-type-cell", () => ({
+ PMTypeCell: () => cell:service,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/vendor-cell", () => ({
+ VendorCell: () => cell:vendor,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/appt-time-cell", () => ({
+ ApptTimeCell: () => cell:appt,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/status-cell", () => ({
+ StatusCell: () => cell:status,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/date-cell", () => ({
+ DateCell: () => cell:completed,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/comp-doc-cell", () => ({
+ CompDocCell: () => cell:doc,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/uplift-cell", () => ({
+ UpliftCell: () => cell:uplift,
+}));
+
+/** Documented left-to-right data column order for the Work Orders board. */
+const DOCUMENTED_ORDER = [
+ "SITE",
+ "WO",
+ "TYPE OF WO",
+ "ASSIGNED TO",
+ "SCHEDULE ON",
+ "DUE DATE",
+ "SERVICE",
+ "VENDOR",
+ "APPT TIME",
+ "STATUS",
+ "COMPLETED DATE",
+ "COMP DOC",
+ "UPLIFT",
+];
+
+describe("Work Orders board column order", () => {
+ it("renders the documented header order with grip/flag before Site and actions after Uplift", () => {
+ renderWithProviders(
+ ,
+ { withAuth: false },
+ );
+
+ const headers = screen.getAllByRole("columnheader").map((th) => th.textContent?.trim() ?? "");
+ expect(headers.filter(Boolean)).toEqual(expect.arrayContaining(DOCUMENTED_ORDER));
+ expect(WO_TABLE_COLS.map((col) => col.key)).toEqual([
+ "grip",
+ "flag",
+ "site",
+ "wo",
+ "type",
+ "assigned",
+ "sched",
+ "due",
+ "pm",
+ "vendor",
+ "appt",
+ "status",
+ "completed",
+ "doc",
+ "uplift",
+ "actions",
+ ]);
+ expect(WO_TABLE_COLS.map((col) => col.label).filter(Boolean)).toEqual(DOCUMENTED_ORDER);
+ });
+
+ it("renders row cells under the matching headers: Status, Completed Date, Comp Doc, Uplift", () => {
+ const row = {
+ id: 7,
+ upliftSummary: { hasUplift: false, pendingCount: 0 },
+ } as WorkOrderTableRow;
+ renderWithProviders(
+ ,
+ { withAuth: false },
+ );
+
+ const cells = within(screen.getByTestId("row"))
+ .getAllByRole("cell")
+ .map((td) => td.textContent);
+ expect(cells).toEqual([
+ "cell:service",
+ "cell:vendor",
+ "cell:appt",
+ "cell:status",
+ "cell:completed",
+ "cell:doc",
+ "cell:uplift",
+ ]);
+ });
+});
diff --git a/src/test/app/(protected)/workorders/wo-table-head-date-tooltips.test.tsx b/src/test/app/(protected)/workorders/wo-table-head-date-tooltips.test.tsx
new file mode 100644
index 00000000..a25bd953
--- /dev/null
+++ b/src/test/app/(protected)/workorders/wo-table-head-date-tooltips.test.tsx
@@ -0,0 +1,71 @@
+import { screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, it } from "vitest";
+
+import { WoTableHead } from "@/app/(protected)/workorders/_components/list/table/wo-table-head";
+import { getWoTableHeaderTooltip } from "@/domain/work-orders/constants/wo-table-header-tooltips";
+import { renderWithProviders } from "@/test/test-utils";
+
+const CASES = [
+ {
+ columnName: "SCHEDULE ON",
+ tooltip:
+ "The date the work is planned to happen. Setting it moves the work order to Scheduled.",
+ },
+ {
+ columnName: "DUE DATE",
+ tooltip: "The deadline for the work — when it must be completed by.",
+ },
+ {
+ columnName: "COMPLETED DATE",
+ tooltip: "The date the vendor actually finished the work. Required to complete the work order.",
+ },
+];
+
+function renderHead() {
+ return renderWithProviders(
+ ,
+ { withAuth: false },
+ );
+}
+
+describe("WoTableHead date column header tooltips (SH-195)", () => {
+ it.each(CASES)(
+ "shows the $columnName help icon and tooltip copy on hover",
+ async ({ columnName, tooltip }) => {
+ const user = userEvent.setup();
+ renderHead();
+
+ const header = screen.getByRole("columnheader", { name: new RegExp(`^${columnName}`) });
+ const icon = within(header).getByRole("button", { name: `${columnName} column help` });
+
+ await user.hover(icon);
+
+ const tip = await screen.findByText(tooltip);
+ expect(tip).toBeInTheDocument();
+ },
+ 15000,
+ );
+
+ it("moves focus to the help icon on tab and keeps it keyboard reachable", async () => {
+ const user = userEvent.setup();
+ renderHead();
+
+ const header = screen.getByRole("columnheader", { name: /^SCHEDULE ON/ });
+ const icon = within(header).getByRole("button", { name: "SCHEDULE ON column help" });
+
+ await user.tab();
+
+ expect(icon).toHaveFocus();
+ });
+
+ it("does not add a help icon to Appt Time (open point, not implemented)", () => {
+ renderHead();
+
+ const header = screen.getByRole("columnheader", { name: "APPT TIME" });
+ expect(within(header).queryByRole("img")).not.toBeInTheDocument();
+ expect(getWoTableHeaderTooltip("appt")).toBeUndefined();
+ });
+});
diff --git a/src/test/app/(protected)/workorders/wo-table-inline-row-required-fields.test.tsx b/src/test/app/(protected)/workorders/wo-table-inline-row-required-fields.test.tsx
new file mode 100644
index 00000000..f5817e84
--- /dev/null
+++ b/src/test/app/(protected)/workorders/wo-table-inline-row-required-fields.test.tsx
@@ -0,0 +1,121 @@
+import { fireEvent, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { PocContactFields } from "@/app/(protected)/workorders/_components/poc/poc-contact-fields";
+import { WoTableInlineRow } from "@/app/(protected)/workorders/_components/list/table/wo-table-inline-row";
+import {
+ EMPTY_TABLE_DRAFT,
+ type WorkOrderTableDraft,
+} from "@/domain/work-orders/types/work-order-table-row";
+import { renderWithProviders } from "@/test/test-utils";
+
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/type-cell", () => ({
+ TypeCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/assigned-to-cell", () => ({
+ AssignedToCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/date-cell", () => ({
+ DateCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/due-date-cell", () => ({
+ DueDateCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/pm-type-cell", () => ({
+ PMTypeCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/vendor-cell", () => ({
+ VendorCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/appt-time-cell", () => ({
+ ApptTimeCell: () => null,
+}));
+vi.mock("@/app/(protected)/workorders/_components/list/table/cells/status-cell", () => ({
+ StatusCell: () => null,
+}));
+
+function renderInlineRow(draft: WorkOrderTableDraft, onSave = vi.fn()) {
+ const ui = (d: WorkOrderTableDraft) => (
+
+ );
+ const view = renderWithProviders(ui(draft), { withAuth: false });
+ return { ...view, rerenderDraft: (d: WorkOrderTableDraft) => view.rerender(ui(d)) };
+}
+
+const COMPLETE_DRAFT: WorkOrderTableDraft = {
+ ...EMPTY_TABLE_DRAFT,
+ site: "BK5",
+ locationId: 9,
+ woNumber: "12345678901",
+ pocName: "Dana",
+ pocPhone: "555-0100",
+};
+
+describe("WoTableInlineRow required fields", () => {
+ it("marks Site and WO # as required without showing errors before a Save attempt", () => {
+ renderInlineRow(EMPTY_TABLE_DRAFT);
+
+ expect(screen.getByRole("button", { name: /^Site \*$/ })).toBeInTheDocument();
+ expect(screen.getByText("Insert WO #")).toHaveTextContent("Insert WO # *");
+ expect(screen.queryByText("Site is required")).not.toBeInTheDocument();
+ expect(screen.queryByText("Work order number is required")).not.toBeInTheDocument();
+ });
+
+ it("reveals field errors only after Save is attempted, then clears them once corrected", () => {
+ const onSave = vi.fn();
+ const { rerenderDraft } = renderInlineRow(EMPTY_TABLE_DRAFT, onSave);
+
+ fireEvent.click(screen.getByRole("button", { name: "Save work order" }));
+
+ expect(onSave).not.toHaveBeenCalled();
+ expect(screen.getByText("Site is required")).toBeInTheDocument();
+ expect(screen.getByText("Work order number is required")).toBeInTheDocument();
+
+ rerenderDraft(COMPLETE_DRAFT);
+
+ expect(screen.queryByText("Site is required")).not.toBeInTheDocument();
+ expect(screen.queryByText("Work order number is required")).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Save work order" }));
+ expect(onSave).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("PocContactFields required primary contact", () => {
+ it("labels POC name and phone with a required asterisk when the contact is required", () => {
+ renderWithProviders(
+ ,
+ { withAuth: false },
+ );
+
+ expect(screen.getByLabelText(/POC name/)).toHaveAttribute("placeholder", "POC name");
+ expect(screen.getByLabelText(/POC phone/)).toHaveAttribute("placeholder", "POC phone");
+ expect(screen.getByText("POC name").closest("label")).toHaveTextContent("POC name*");
+ expect(screen.getByText("POC phone").closest("label")).toHaveTextContent("POC phone*");
+ expect(screen.queryByText("Contact name is required")).not.toBeInTheDocument();
+ });
+});
diff --git a/src/test/app/(protected)/workorders/work-orders-board-core-affordances.test.tsx b/src/test/app/(protected)/workorders/work-orders-board-core-affordances.test.tsx
index c3fb07b9..7e4df369 100644
--- a/src/test/app/(protected)/workorders/work-orders-board-core-affordances.test.tsx
+++ b/src/test/app/(protected)/workorders/work-orders-board-core-affordances.test.tsx
@@ -189,7 +189,12 @@ vi.mock("@/app/(protected)/workorders/_components/list/table/wo-table", () => ({
describe("WorkOrdersListHeader slice affordances", () => {
it("hides New WO and Advanced Filters when callbacks are omitted", () => {
renderWithProviders(
- ,
+ ,
{ withAuth: false },
);
@@ -202,6 +207,7 @@ describe("WorkOrdersListHeader slice affordances", () => {
renderWithProviders(
({
+ searchBoard: vi.fn(),
+ getBoard: vi.fn(),
+ emptyList: [] as const,
+}));
+
+vi.mock("@/hooks/use-debounce", () => ({
+ useDebounce: (value: T) => value,
+}));
+
+vi.mock("@/domain/work-orders/api/work-orders-api", () => ({
+ workOrdersApi: {
+ searchBoard: (...args: unknown[]) => searchBoard(...args),
+ getBoard: (...args: unknown[]) => getBoard(...args),
+ },
+}));
+
+vi.mock("@/domain/work-orders/use-cases/use-work-order-detail", () => ({
+ useWorkOrderLocations: () => ({ data: emptyList }),
+ useWorkOrderVendors: () => ({ data: emptyList }),
+}));
+
+import { WorkOrdersListHeader } from "@/app/(protected)/workorders/_components/list/work-orders-list-header";
+import { useWorkOrdersBoardSource } from "@/app/(protected)/workorders/_hooks/use-work-orders-board-source";
+import { useWorkOrdersListFilters } from "@/app/(protected)/workorders/_hooks/use-work-orders-list-filters";
+
+const EMPTY_RESULT = { items: [], totalCount: 0, page: 0, pageSize: 25 };
+
+function useBoardWithFilters() {
+ const filters = useWorkOrdersListFilters();
+ useWorkOrdersBoardSource(filters);
+ return filters;
+}
+
+function renderBoardSource() {
+ const client = createTestQueryClient();
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ {children}
+ );
+ return renderHook(() => useBoardWithFilters(), { wrapper });
+}
+
+describe("keyword search scope indicator", () => {
+ it("shows no scope badge while the search box is empty", () => {
+ renderWithProviders(
+ ,
+ { withAuth: false },
+ );
+
+ expect(screen.queryByText(/searching within/i)).not.toBeInTheDocument();
+ });
+
+ it("names the active week while a keyword is typed", () => {
+ renderWithProviders(
+ ,
+ { withAuth: false },
+ );
+
+ expect(screen.getByText("Searching within 5/4–5/8")).toBeInTheDocument();
+ });
+
+ it("hides the scope label while Advanced Filters are active", () => {
+ renderWithProviders(
+ ,
+ { withAuth: false },
+ );
+
+ expect(screen.queryByText(/searching within/i)).not.toBeInTheDocument();
+ });
+});
+
+describe("keyword search vs Advanced Filters scope", () => {
+ beforeEach(() => {
+ searchBoard.mockReset().mockResolvedValue(EMPTY_RESULT);
+ getBoard.mockReset().mockResolvedValue(EMPTY_RESULT);
+ });
+
+ it("scopes keyword search to the active week", async () => {
+ const { result } = renderBoardSource();
+
+ act(() => {
+ result.current.setWeekMonday("2026-05-04");
+ result.current.handleSearchChange("hvac");
+ });
+
+ await waitFor(() =>
+ expect(getBoard).toHaveBeenCalledWith(
+ expect.objectContaining({ weekStart: "2026-05-04", weekEnd: "2026-05-08", search: "hvac" }),
+ ),
+ );
+ expect(searchBoard).not.toHaveBeenCalled();
+ });
+
+ it("keeps Advanced Filters global and ignores the week-scoped keyword", async () => {
+ const { result } = renderBoardSource();
+
+ act(() => {
+ result.current.handleSearchChange("hvac");
+ result.current.applyAdvancedFilters({ ...EMPTY_ADVANCED_FILTERS, rescheduled: true });
+ });
+
+ await waitFor(() => expect(searchBoard).toHaveBeenCalled());
+ const params = searchBoard.mock.lastCall?.[0] as Record;
+ expect(params.search).toBeUndefined();
+ expect(params).not.toHaveProperty("weekStart");
+ });
+});
diff --git a/src/test/domain/services/api/services-api.test.ts b/src/test/domain/services/api/services-api.test.ts
new file mode 100644
index 00000000..ab558d03
--- /dev/null
+++ b/src/test/domain/services/api/services-api.test.ts
@@ -0,0 +1,48 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { API_PATHS } from "@/api/api-paths";
+
+const apiGet = vi.fn();
+
+vi.mock("@/api/api", () => ({
+ apiGet: (...args: unknown[]) => apiGet(...args),
+}));
+
+import { servicesApi } from "@/domain/services/api/services-api";
+
+describe("servicesApi", () => {
+ beforeEach(() => {
+ apiGet.mockReset();
+ });
+
+ it("loads active services filtered by the selected work-order type", async () => {
+ apiGet.mockResolvedValue([
+ {
+ id: 7,
+ name: "HVAC inspection",
+ trade: "HVAC",
+ iconKey: "hvac-inspection",
+ isActive: true,
+ supportedWorkOrderTypes: [2, "Reactive"],
+ },
+ ]);
+
+ const services = await servicesApi.getActiveForWorkOrderType("PM");
+
+ expect(apiGet).toHaveBeenCalledWith(API_PATHS.services.list, {
+ searchParams: { isActive: true, workOrderType: 2 },
+ });
+ expect(services[0]).toMatchObject({
+ id: 7,
+ name: "HVAC inspection",
+ trade: "HVAC",
+ supportedWorkOrderTypes: ["PM", "Reactive"],
+ });
+ });
+
+ it("does not request services for the unsupported Overdue type", async () => {
+ const services = await servicesApi.getActiveForWorkOrderType("Overdue");
+
+ expect(apiGet).not.toHaveBeenCalled();
+ expect(services).toEqual([]);
+ });
+});
diff --git a/src/test/domain/team-members/team-member-mapper.test.ts b/src/test/domain/team-members/team-member-mapper.test.ts
new file mode 100644
index 00000000..7bfb208d
--- /dev/null
+++ b/src/test/domain/team-members/team-member-mapper.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+import { mapTeamMemberListItem } from "@/domain/team-members/mappers/team-member-mapper";
+
+describe("mapTeamMemberListItem", () => {
+ it("maps the existing User list response and derives inactive state", () => {
+ expect(
+ mapTeamMemberListItem({
+ Id: "u1",
+ Name: "Alex Smith",
+ RoleName: "Dispatcher",
+ Locations: "Central",
+ Email: "alex@example.com",
+ Status: "Inactive",
+ IsAccountOwner: true,
+ }),
+ ).toEqual({
+ id: "u1",
+ name: "Alex Smith",
+ role: "Dispatcher",
+ serviceArea: "Central",
+ phone: "",
+ email: "alex@example.com",
+ color: "",
+ status: "Inactive",
+ isAccountOwner: true,
+ });
+ });
+});
diff --git a/src/test/domain/vendors/api/vendors-api.test.ts b/src/test/domain/vendors/api/vendors-api.test.ts
index 8b33239e..38a6bd20 100644
--- a/src/test/domain/vendors/api/vendors-api.test.ts
+++ b/src/test/domain/vendors/api/vendors-api.test.ts
@@ -419,3 +419,24 @@ describe("vendorsApi.getDirectoryList", () => {
});
});
});
+
+describe("vendorsApi.getDirectoryList Service Area filter", () => {
+ beforeEach(() => {
+ apiGet.mockReset();
+ apiGet.mockResolvedValue({ Data: [], TotalCount: 0 });
+ });
+
+ it("sends areas[n] stable ids and the Unassigned sentinel", async () => {
+ await vendorsApi.getDirectoryList({ page: 1, areas: ["1", "__unassigned__"] });
+
+ expect(apiGet).toHaveBeenCalledWith(API_PATHS.vendor.getDirectoryList, {
+ searchParams: {
+ search: "",
+ page: 1,
+ pageSize: 12,
+ "areas[0]": "1",
+ "areas[1]": "__unassigned__",
+ },
+ });
+ });
+});
diff --git a/src/test/domain/vendors/mappers/vendor-roster-mapper.test.ts b/src/test/domain/vendors/mappers/vendor-roster-mapper.test.ts
index 4c9a463f..3f4beef9 100644
--- a/src/test/domain/vendors/mappers/vendor-roster-mapper.test.ts
+++ b/src/test/domain/vendors/mappers/vendor-roster-mapper.test.ts
@@ -40,6 +40,8 @@ describe("vendor roster mapper", () => {
zip: "",
googleMapsUrl: "",
notes: "",
+ areaId: "",
+ areaName: "",
technicians: [
{
id: 7,
diff --git a/src/test/domain/vendors/use-cases/use-save-vendor-company-roster-additive.test.tsx b/src/test/domain/vendors/use-cases/use-save-vendor-company-roster-additive.test.tsx
index aaec2167..b6dcae4d 100644
--- a/src/test/domain/vendors/use-cases/use-save-vendor-company-roster-additive.test.tsx
+++ b/src/test/domain/vendors/use-cases/use-save-vendor-company-roster-additive.test.tsx
@@ -40,6 +40,8 @@ const roster: VendorCompanyRoster = {
zip: "63101",
googleMapsUrl: "",
notes: "Preferred vendor",
+ areaId: "",
+ areaName: "",
technicians: [
{
id: 11,
@@ -75,6 +77,7 @@ function formValues(
state: roster.state,
zip: roster.zip,
notes: roster.notes,
+ areaId: roster.areaId,
technicians: [newTechnician],
...overrides,
};
diff --git a/src/test/domain/vendors/use-cases/use-save-vendor-company-roster.test.ts b/src/test/domain/vendors/use-cases/use-save-vendor-company-roster.test.ts
index 735ef2d7..3aabb058 100644
--- a/src/test/domain/vendors/use-cases/use-save-vendor-company-roster.test.ts
+++ b/src/test/domain/vendors/use-cases/use-save-vendor-company-roster.test.ts
@@ -14,6 +14,8 @@ const roster: VendorCompanyRoster = {
zip: "63101",
googleMapsUrl: "http://maps.example.test/legacy",
notes: "Legacy values remain untouched",
+ areaId: "",
+ areaName: "",
technicians: [
{
id: 7,
@@ -37,6 +39,7 @@ const values = {
state: roster.state,
zip: roster.zip,
notes: roster.notes,
+ areaId: roster.areaId,
technicians: roster.technicians.map((technician) => ({
id: technician.id,
contactName: technician.contactName,
diff --git a/src/test/domain/work-orders/api/work-orders-api.test.ts b/src/test/domain/work-orders/api/work-orders-api.test.ts
index 75f1e499..e295ed9d 100644
--- a/src/test/domain/work-orders/api/work-orders-api.test.ts
+++ b/src/test/domain/work-orders/api/work-orders-api.test.ts
@@ -140,6 +140,25 @@ describe("workOrdersApi.createFromBoard", () => {
locationId: 9,
});
});
+
+ it("includes the registry service id when selected in the wizard", async () => {
+ await workOrdersApi.createFromBoard({
+ ...EMPTY_WIZARD_DRAFT,
+ type: "Reactive",
+ siteCode: "BK5",
+ pm: "HVAC inspection",
+ serviceId: 7,
+ });
+
+ expect(apiPost).toHaveBeenCalledWith(
+ API_PATHS.workOrder.boardCreate,
+ expect.objectContaining({
+ workOrderType: 6,
+ primaryService: "HVAC inspection",
+ serviceId: 7,
+ }),
+ );
+ });
});
describe("workOrdersApi.update", () => {
@@ -615,6 +634,28 @@ describe("workOrdersApi.patchBoardField", () => {
}),
).rejects.toBeInstanceOf(BoardPatchConflictError);
});
+
+ it("throws BoardPatchValidationError with DuplicateWoNumber code on 422", async () => {
+ apiPatchFn.mockResolvedValue({
+ ok: false,
+ status: 422,
+ json: async () => ({
+ code: "DuplicateWoNumber",
+ message: "WO number already exists.",
+ }),
+ });
+
+ await expect(
+ workOrdersApi.patchBoardField(10, {
+ field: "woNumber",
+ value: "12345678901",
+ workOrderVersion: "AAAAAAA=",
+ }),
+ ).rejects.toMatchObject({
+ name: "BoardPatchValidationError",
+ code: "DuplicateWoNumber",
+ });
+ });
});
describe("workOrdersApi.createComment", () => {
diff --git a/src/test/domain/work-orders/errors/board-patch-errors.test.ts b/src/test/domain/work-orders/errors/board-patch-errors.test.ts
new file mode 100644
index 00000000..d38217cd
--- /dev/null
+++ b/src/test/domain/work-orders/errors/board-patch-errors.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+import {
+ BOARD_PATCH_CONFLICT_MESSAGE,
+ BOARD_PATCH_FAILED_MESSAGE,
+ BoardPatchConflictError,
+ BoardPatchValidationError,
+ DUPLICATE_WO_NUMBER_MESSAGE,
+ boardPatchErrorMessage,
+} from "@/domain/work-orders/errors/board-patch-errors";
+
+describe("boardPatchErrorMessage", () => {
+ it("maps a DuplicateWoNumber validation error to the duplicate-WO product copy", () => {
+ const error = new BoardPatchValidationError("DuplicateWoNumber", "WO number already exists.");
+
+ expect(boardPatchErrorMessage(error)).toBe(DUPLICATE_WO_NUMBER_MESSAGE);
+ });
+
+ it("never leaks backend validation text for unknown codes", () => {
+ const error = new BoardPatchValidationError("SomethingElse", "vendorId is required.");
+
+ expect(boardPatchErrorMessage(error)).toBe(BOARD_PATCH_FAILED_MESSAGE);
+ });
+
+ it("maps a conflict error to the concurrent-edit copy", () => {
+ const error = new BoardPatchConflictError("stale", null);
+
+ expect(boardPatchErrorMessage(error)).toBe(BOARD_PATCH_CONFLICT_MESSAGE);
+ });
+});
diff --git a/src/test/domain/work-orders/mappers/completed-date-board-column.test.ts b/src/test/domain/work-orders/mappers/completed-date-board-column.test.ts
index 9b74c71a..1820df72 100644
--- a/src/test/domain/work-orders/mappers/completed-date-board-column.test.ts
+++ b/src/test/domain/work-orders/mappers/completed-date-board-column.test.ts
@@ -4,10 +4,11 @@ import { expandScalarBoardOps } from "@/domain/work-orders/mappers/expand-scalar
import { mapWorkOrderTableRow } from "@/domain/work-orders/mappers/work-order-table-row-mapper";
describe("COMPLETED DATE board column wiring", () => {
- it("includes COMPLETED DATE column after COMP DOC", () => {
+ it("includes COMPLETED DATE column between STATUS and COMP DOC", () => {
const keys = WO_TABLE_COLS.map((col) => col.key);
expect(keys).toContain("completed");
- expect(keys.indexOf("completed")).toBeGreaterThan(keys.indexOf("doc"));
+ expect(keys.indexOf("completed")).toBe(keys.indexOf("status") + 1);
+ expect(keys.indexOf("completed")).toBeLessThan(keys.indexOf("doc"));
});
it("expands completedDate patch to board field op", () => {
diff --git a/src/test/domain/work-orders/use-cases/use-create-work-order-from-wizard-errors.test.tsx b/src/test/domain/work-orders/use-cases/use-create-work-order-from-wizard-errors.test.tsx
new file mode 100644
index 00000000..59392029
--- /dev/null
+++ b/src/test/domain/work-orders/use-cases/use-create-work-order-from-wizard-errors.test.tsx
@@ -0,0 +1,90 @@
+import { QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { HTTPError } from "ky";
+import type { ReactNode } from "react";
+import { toast } from "react-toastify";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { normalizeApiRequestError } from "@/api/api-error";
+import { EMPTY_WIZARD_DRAFT } from "@/domain/work-orders/types/work-order-wizard";
+import { useCreateWorkOrderFromWizard } from "@/domain/work-orders/use-cases/use-create-work-order-from-wizard";
+import { createTestQueryClient } from "@/test/test-utils";
+
+const createFromBoard = vi.fn();
+
+vi.mock("@/domain/work-orders/api/work-orders-api", () => ({
+ workOrdersApi: { createFromBoard: (...args: unknown[]) => createFromBoard(...args) },
+}));
+
+vi.mock("react-toastify", () => ({
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+
+/** Mirrors the ky client: HTTPError with parsed body, message normalized from it. */
+function backendError(status: number, body: Record): HTTPError {
+ const error = new HTTPError(
+ new Response(JSON.stringify(body), { status }),
+ new Request("https://api.example.test/workorders/board"),
+ {} as never,
+ );
+ error.data = body;
+ return normalizeApiRequestError(error) as HTTPError;
+}
+
+function wrapper({ children }: { children: ReactNode }) {
+ return {children};
+}
+
+async function createAndGetToast(error: unknown): Promise {
+ createFromBoard.mockRejectedValueOnce(error);
+ const { result } = renderHook(() => useCreateWorkOrderFromWizard(), { wrapper });
+ act(() => {
+ result.current.mutate(EMPTY_WIZARD_DRAFT);
+ });
+ await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));
+ return vi.mocked(toast.error).mock.calls[0]?.[0];
+}
+
+describe("useCreateWorkOrderFromWizard error copy", () => {
+ beforeEach(() => {
+ vi.mocked(toast.error).mockClear();
+ createFromBoard.mockReset();
+ });
+
+ it("never surfaces raw backend validation text from a 400", async () => {
+ const message = await createAndGetToast(
+ backendError(400, { status: "Validation Error", message: "siteCode is required." }),
+ );
+
+ expect(message).toBe("Unable to create the work order. Please try again.");
+ });
+
+ it("maps a coded 422 to product copy instead of the backend field name", async () => {
+ const message = await createAndGetToast(
+ backendError(422, {
+ code: "DispatchRequired",
+ message: "vendorId is required when setting appointment fields.",
+ }),
+ );
+
+ expect(message).toBe("Select a vendor company before saving.");
+ });
+
+ it("falls back to generic copy for unknown 422 codes", async () => {
+ const message = await createAndGetToast(
+ backendError(422, {
+ code: "InvalidLifecycleStatus",
+ message: "lifecycleStatus must be Incomplete, Pending, or Scheduled at create.",
+ }),
+ );
+
+ expect(message).toBe("Unable to create the work order. Please try again.");
+ });
+
+ it("keeps fixed permission copy for a 403", async () => {
+ const message = await createAndGetToast(
+ backendError(403, { code: "Forbidden", message: "accountId not permitted" }),
+ );
+
+ expect(message).toBe("You do not have permission to perform this action.");
+ });
+});
diff --git a/src/test/domain/work-orders/use-cases/use-work-order-table-mutations-errors.test.tsx b/src/test/domain/work-orders/use-cases/use-work-order-table-mutations-errors.test.tsx
new file mode 100644
index 00000000..d4105ff0
--- /dev/null
+++ b/src/test/domain/work-orders/use-cases/use-work-order-table-mutations-errors.test.tsx
@@ -0,0 +1,171 @@
+import { QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { toast } from "react-toastify";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ BOARD_PATCH_CONFLICT_MESSAGE,
+ BOARD_PATCH_FAILED_MESSAGE,
+ DISPATCH_REQUIRED_MESSAGE,
+ PARTIAL_SAVE_PREFIX,
+} from "@/domain/work-orders/errors/board-patch-errors";
+import type {
+ WorkOrderTablePatch,
+ WorkOrderTableRow,
+} from "@/domain/work-orders/types/work-order-table-row";
+import { useWorkOrderTableMutations } from "@/domain/work-orders/use-cases/use-work-order-table-mutations";
+import { createTestQueryClient } from "@/test/test-utils";
+
+vi.mock("react-toastify", () => ({
+ toast: { error: vi.fn(), success: vi.fn(), warning: vi.fn() },
+}));
+
+const ROW = { id: 7, rowVersion: "v1" } as WorkOrderTableRow;
+
+function wrapper({ children }: { children: ReactNode }) {
+ return {children};
+}
+
+type FakeResponse = { status: number; body: Record };
+
+/** Board PATCH goes through the real ky client; only the network responses are faked. */
+function respondWith(...responses: FakeResponse[]) {
+ const queue = [...responses];
+ globalThis.fetch = vi.fn(async () => {
+ const next = queue.shift() ?? responses[responses.length - 1];
+ return new Response(JSON.stringify(next.body), {
+ status: next.status,
+ headers: { "Content-Type": "application/json" },
+ });
+ }) as typeof fetch;
+}
+
+async function patchAndGetToast(
+ patch: WorkOrderTablePatch = { woNumber: "WO-100" },
+ expectedCalls = 1,
+ onPatch: (id: string | number, patch: WorkOrderTablePatch) => void = () => undefined,
+): Promise {
+ const { result } = renderHook(
+ () =>
+ useWorkOrderTableMutations({
+ onPatch,
+ clearPatch: () => undefined,
+ getRow: () => ROW,
+ }),
+ { wrapper },
+ );
+ act(() => {
+ result.current.patchField(7, patch);
+ });
+ await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));
+ expect(globalThis.fetch).toHaveBeenCalledTimes(expectedCalls);
+ return vi.mocked(toast.error).mock.calls[0]?.[0];
+}
+
+describe("useWorkOrderTableMutations edit error copy", () => {
+ const originalFetch = globalThis.fetch;
+
+ beforeEach(() => {
+ vi.mocked(toast.error).mockClear();
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ it("shows generic copy instead of backend text for an unknown 422 code", async () => {
+ respondWith({
+ status: 422,
+ body: {
+ code: "InvalidLifecycleStatus",
+ message: "lifecycleStatus cannot move from Completed for workOrderId 7.",
+ },
+ });
+
+ const message = await patchAndGetToast();
+
+ expect(message).toBe(BOARD_PATCH_FAILED_MESSAGE);
+ expect(message).not.toMatch(/lifecycleStatus|workOrderId|InvalidLifecycleStatus/);
+ });
+
+ it("keeps specific copy for DispatchRequired", async () => {
+ respondWith({
+ status: 422,
+ body: {
+ code: "DispatchRequired",
+ message: "vendorId is required when setting appointment fields.",
+ },
+ });
+
+ const message = await patchAndGetToast();
+
+ expect(message).toBe(DISPATCH_REQUIRED_MESSAGE);
+ });
+
+ it("shows generic copy instead of backend text for a non-422 failure", async () => {
+ respondWith({ status: 400, body: { message: "siteCode is required for accountId 42." } });
+
+ const message = await patchAndGetToast();
+
+ expect(message).toBe(BOARD_PATCH_FAILED_MESSAGE);
+ });
+
+ it("reports a partial save in plain language without backend field keys", async () => {
+ const onPatch = vi.fn();
+ respondWith(
+ { status: 200, body: { id: 7, workOrderNumber: "WO-100", rowVersion: "v2" } },
+ {
+ status: 422,
+ body: {
+ code: "SeverityInvalid",
+ message: "severity 3 is not allowed for workOrderType Emergency.",
+ },
+ },
+ );
+
+ const message = await patchAndGetToast({ woNumber: "WO-100", severity: 3 }, 2, onPatch);
+
+ expect(message).toBe(`${PARTIAL_SAVE_PREFIX} ${BOARD_PATCH_FAILED_MESSAGE}`);
+ expect(message).not.toMatch(/severity|woNumber|workOrderType|SeverityInvalid|\d\/\d/);
+ expect(onPatch).toHaveBeenCalledWith(7, expect.objectContaining({ rowVersion: "v2" }));
+ });
+
+ it("keeps DispatchRequired copy inside a partial save", async () => {
+ respondWith(
+ { status: 200, body: { id: 7, workOrderNumber: "WO-100", rowVersion: "v2" } },
+ {
+ status: 422,
+ body: { code: "DispatchRequired", message: "vendorId is required." },
+ },
+ );
+
+ const message = await patchAndGetToast({ woNumber: "WO-100", severity: 2 }, 2);
+
+ expect(message).toBe(`${PARTIAL_SAVE_PREFIX} ${DISPATCH_REQUIRED_MESSAGE}`);
+ });
+
+ it("shows fixed conflict copy and still applies the latest row on a 409", async () => {
+ const onPatch = vi.fn();
+ respondWith({
+ status: 409,
+ body: {
+ message: "RowVersion mismatch for workOrderId 7 (expected v1, found v3).",
+ currentState: { id: 7, workOrderNumber: "WO-099", rowVersion: "v3" },
+ },
+ });
+
+ const message = await patchAndGetToast({ woNumber: "WO-100" }, 1, onPatch);
+
+ expect(message).toBe(BOARD_PATCH_CONFLICT_MESSAGE);
+ expect(message).not.toMatch(/RowVersion|workOrderId|v3/);
+ expect(onPatch).toHaveBeenLastCalledWith(7, expect.objectContaining({ rowVersion: "v3" }));
+ });
+
+ it("shows fixed conflict copy when a 409 carries no latest row", async () => {
+ respondWith({ status: 409, body: { message: "RowVersion mismatch for workOrderId 7." } });
+
+ const message = await patchAndGetToast();
+
+ expect(message).toBe(BOARD_PATCH_CONFLICT_MESSAGE);
+ });
+});
diff --git a/src/test/domain/work-orders/use-cases/use-work-order-table-mutations.test.tsx b/src/test/domain/work-orders/use-cases/use-work-order-table-mutations.test.tsx
index d3e1095d..97f364b5 100644
--- a/src/test/domain/work-orders/use-cases/use-work-order-table-mutations.test.tsx
+++ b/src/test/domain/work-orders/use-cases/use-work-order-table-mutations.test.tsx
@@ -224,6 +224,35 @@ describe("useWorkOrderTableMutations completion-doc persistence", () => {
expect(serverState.scheduledDate).toBe(BASE_SERVER.scheduledDate);
expect(serverState.status).toBe(BASE_SERVER.status);
});
+ it("sends the follow-up status patch with the rowVersion of the just-saved row (SH-341)", async () => {
+ const staleTableRow = { ...BASE_ROW };
+ const { result } = renderHook(
+ () =>
+ useWorkOrderTableMutations({
+ onPatch: vi.fn(),
+ clearPatch: () => undefined,
+ getRow: () => staleTableRow,
+ }),
+ { wrapper: makeWrapper() },
+ );
+
+ let saved: Awaited> | undefined;
+ await act(async () => {
+ saved = await result.current.patchFieldAsync(42, { docStatus: "Yes" });
+ });
+ expect(saved?.kind).toBe("board");
+ const savedRow = saved?.kind === "board" ? saved.row : undefined;
+
+ await act(async () => {
+ await result.current.patchFieldAsync(42, { status: "Completed" }, savedRow);
+ });
+
+ expect(patchBoardField).toHaveBeenLastCalledWith(42, {
+ field: "lifecycleStatus",
+ value: "Completed",
+ workOrderVersion: "AAAAAAA=-next",
+ });
+ });
});
describe("maybeAutoSchedule on board patch", () => {
diff --git a/src/test/domain/work-orders/utils/completion-doc-auto-complete.test.ts b/src/test/domain/work-orders/utils/completion-doc-auto-complete.test.ts
new file mode 100644
index 00000000..ab12e39e
--- /dev/null
+++ b/src/test/domain/work-orders/utils/completion-doc-auto-complete.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest";
+import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
+import { shouldCompleteAfterCompletionDoc } from "@/domain/work-orders/utils/completion-doc-auto-complete";
+
+function closablePmRow(overrides: Partial = {}): WorkOrderTableRow {
+ return {
+ id: 42,
+ woNumber: "24866",
+ type: "PM",
+ dispatcherId: "u1",
+ dispatcherName: "Dispatcher",
+ company: "Vendor Co",
+ vendorId: "7",
+ tech: "Tech One",
+ completedDate: "2026-09-15",
+ pm: "HVAC",
+ status: "In Progress",
+ docStatus: "Yes",
+ mediaCount: 0,
+ isPastDue: false,
+ upliftSummary: { hasUplift: false, pendingCount: 0 },
+ ...overrides,
+ } as WorkOrderTableRow;
+}
+
+describe("shouldCompleteAfterCompletionDoc (SH-341)", () => {
+ it("completes a closable PM once the generated document is persisted", () => {
+ expect(shouldCompleteAfterCompletionDoc("Yes", closablePmRow())).toBe(true);
+ });
+
+ it("never completes on Save draft or Not required", () => {
+ expect(shouldCompleteAfterCompletionDoc("No", closablePmRow({ docStatus: "No" }))).toBe(false);
+ expect(shouldCompleteAfterCompletionDoc("NN", closablePmRow({ docStatus: "NN" }))).toBe(false);
+ });
+
+ it("does not complete when the server did not persist the document as generated", () => {
+ expect(shouldCompleteAfterCompletionDoc("Yes", closablePmRow({ docStatus: "No" }))).toBe(false);
+ });
+
+ it.each([
+ ["dispatcher", { dispatcherId: "", dispatcherName: "" }],
+ ["vendor", { company: "", vendorId: "" }],
+ ["completed date", { completedDate: "" }],
+ ["real WO number", { woNumber: "SH02137" }],
+ ["service", { pm: "" }],
+ ["pending uplift", { upliftSummary: { hasUplift: true, pendingCount: 1 } }],
+ ["photo on a Reactive WO", { type: "Reactive" as const, mediaCount: 0 }],
+ ])("keeps the SH-114 closability gate: missing %s blocks completion", (_label, overrides) => {
+ expect(shouldCompleteAfterCompletionDoc("Yes", closablePmRow(overrides))).toBe(false);
+ });
+
+ it("completes a Reactive WO that has its completion photo", () => {
+ expect(
+ shouldCompleteAfterCompletionDoc("Yes", closablePmRow({ type: "Reactive", mediaCount: 1 })),
+ ).toBe(true);
+ });
+
+ it("leaves Completed, Canceled, and Past Due rows unchanged", () => {
+ expect(shouldCompleteAfterCompletionDoc("Yes", closablePmRow({ status: "Completed" }))).toBe(
+ false,
+ );
+ expect(shouldCompleteAfterCompletionDoc("Yes", closablePmRow({ status: "Canceled" }))).toBe(
+ false,
+ );
+ expect(shouldCompleteAfterCompletionDoc("Yes", closablePmRow({ isPastDue: true }))).toBe(false);
+ });
+});
diff --git a/src/test/domain/work-orders/utils/due-date-floor.test.ts b/src/test/domain/work-orders/utils/due-date-floor.test.ts
new file mode 100644
index 00000000..b4c52c1b
--- /dev/null
+++ b/src/test/domain/work-orders/utils/due-date-floor.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+import {
+ clearDueDateBeforeSchedule,
+ isDueDateBeforeFloor,
+ resolveDueDateFloor,
+} from "@/domain/work-orders/utils/due-date-floor";
+
+describe("due date floor (SH-356)", () => {
+ it("uses the concrete or range-start Schedule On, else the target week's first day", () => {
+ expect(resolveDueDateFloor({ scheduledOn: "2026-09-10", targetWeek: "" })).toBe("2026-09-10");
+ expect(resolveDueDateFloor({ scheduledOn: "", targetWeek: "2026-09-14" })).toBe("2026-09-14");
+ expect(resolveDueDateFloor({ scheduledOn: "", targetWeek: "" })).toBe("");
+ expect(resolveDueDateFloor({ scheduledOn: null, targetWeek: undefined })).toBe("");
+ });
+
+ it("flags only a Due Date strictly before the floor", () => {
+ expect(isDueDateBeforeFloor("2026-09-09", "2026-09-10")).toBe(true);
+ expect(isDueDateBeforeFloor("2026-09-10", "2026-09-10")).toBe(false);
+ expect(isDueDateBeforeFloor("", "2026-09-10")).toBe(false);
+ expect(isDueDateBeforeFloor("2026-09-09", "")).toBe(false);
+ });
+
+ it("clears (never bumps) a Due Date the new schedule passes", () => {
+ expect(clearDueDateBeforeSchedule("2026-09-12", "2026-09-15")).toEqual({ dueDate: "" });
+ expect(clearDueDateBeforeSchedule("2026-09-12", "2026-09-12")).toEqual({});
+ expect(clearDueDateBeforeSchedule("2026-09-20", "2026-09-15")).toEqual({});
+ expect(clearDueDateBeforeSchedule("2026-09-12", "")).toEqual({});
+ });
+});
diff --git a/src/test/domain/work-orders/utils/format-audit-timestamp.test.ts b/src/test/domain/work-orders/utils/format-audit-timestamp.test.ts
new file mode 100644
index 00000000..c7bb498b
--- /dev/null
+++ b/src/test/domain/work-orders/utils/format-audit-timestamp.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+import { formatAuditTimestamp } from "@/domain/work-orders/utils/format-audit-timestamp";
+
+describe("formatAuditTimestamp (SH-361)", () => {
+ it("includes the calendar date and the time for an ISO audit time", () => {
+ const iso = "2026-09-15T19:42:00";
+ const date = new Date(iso);
+ const expectedDate = date.toLocaleDateString("en-US", {
+ month: "2-digit",
+ day: "2-digit",
+ year: "numeric",
+ });
+
+ const formatted = formatAuditTimestamp(iso);
+
+ expect(formatted).toBe(`${expectedDate} · 7:42 PM`);
+ expect(formatted).toMatch(/^\d{2}\/\d{2}\/\d{4} · \d{1,2}:\d{2} (AM|PM)$/);
+ });
+
+ it("distinguishes the same time of day on different dates", () => {
+ expect(formatAuditTimestamp("2026-09-14T09:48:00")).not.toBe(
+ formatAuditTimestamp("2026-09-15T09:48:00"),
+ );
+ });
+
+ it("keeps pre-formatted or unparseable strings unchanged", () => {
+ expect(formatAuditTimestamp("· 7:42 PM")).toBe("· 7:42 PM");
+ expect(formatAuditTimestamp("09/15/2026 · 7:42 PM")).toBe("09/15/2026 · 7:42 PM");
+ });
+
+ it("returns an empty string when there is no time", () => {
+ expect(formatAuditTimestamp("")).toBe("");
+ });
+});
diff --git a/src/test/domain/work-orders/utils/format-board-audit-action.test.ts b/src/test/domain/work-orders/utils/format-board-audit-action.test.ts
index 8c9ff415..e0a3f0b8 100644
--- a/src/test/domain/work-orders/utils/format-board-audit-action.test.ts
+++ b/src/test/domain/work-orders/utils/format-board-audit-action.test.ts
@@ -89,26 +89,67 @@ describe("formatBoardAuditAction", () => {
).toBe("WO marked as Past Due. Schedule On has passed without completion.");
});
- it("formats type correction as Changed Type to (AAP, new value only)", () => {
+ it("formats type correction with the previous and new type (SH-363)", () => {
expect(
formatBoardAuditAction({
- action: "FieldPatched",
+ action: "FieldChanged",
fieldName: "WorkOrderType",
oldValue: "PM",
+ newValue: "Reactive",
+ }),
+ ).toBe('Changed Type from "PM" to "Reactive"');
+ });
+
+ it("formats a first type assignment without a from clause", () => {
+ expect(
+ formatBoardAuditAction({
+ action: "FieldChanged",
+ fieldName: "WorkOrderType",
+ oldValue: "",
newValue: "Emergency",
}),
).toBe('Changed Type to "Emergency"');
});
- it("formats severity as Changed Severity to SEV N", () => {
+ it("formats severity with the previous and new SEV labels", () => {
expect(
formatBoardAuditAction({
- action: "FieldPatched",
+ action: "FieldChanged",
fieldName: "Severity",
oldValue: "3",
newValue: "1",
}),
- ).toBe('Changed Severity to "SEV 1"');
+ ).toBe('Changed Severity from "SEV 3" to "SEV 1"');
+ });
+
+ it("formats severity cleared by a type correction instead of a raw FieldChanged (SH-363)", () => {
+ expect(
+ formatBoardAuditAction({
+ action: "FieldChanged",
+ fieldName: "Severity",
+ oldValue: "3",
+ newValue: "",
+ }),
+ ).toBe('Changed Severity from "SEV 3" to "—"');
+ });
+
+ it("never renders a raw audit action enum for a cleared unknown field", () => {
+ const cleared = formatBoardAuditAction({
+ action: "FieldChanged",
+ fieldName: "VendorNte",
+ oldValue: "100",
+ newValue: "",
+ });
+ const empty = formatBoardAuditAction({
+ action: "FieldChanged",
+ fieldName: "VendorNte",
+ oldValue: "",
+ newValue: "",
+ });
+
+ expect(cleared).toBe('Changed vendor nte from "100" to "—"');
+ expect(empty).toBe("Updated vendor nte");
+ expect([cleared, empty]).not.toContain("FieldChanged");
});
it("falls back to from → to for unknown fields", () => {
diff --git a/src/test/domain/work-orders/utils/partition-slide-over-media.test.ts b/src/test/domain/work-orders/utils/partition-slide-over-media.test.ts
index 077eff57..1970db61 100644
--- a/src/test/domain/work-orders/utils/partition-slide-over-media.test.ts
+++ b/src/test/domain/work-orders/utils/partition-slide-over-media.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import type { MediaFile } from "@/domain/work-orders/types/work-order-media";
import {
+ hasCompletionMediaGallery,
isCompletionSurfaceMedia,
isExtrasSurfaceMedia,
} from "@/domain/work-orders/utils/partition-slide-over-media";
@@ -76,4 +77,33 @@ describe("partition-slide-over-media", () => {
}),
).toBe(true);
});
+
+ it("renders a Completion gallery only for Reactive and Emergency work orders", () => {
+ expect(hasCompletionMediaGallery("Reactive")).toBe(true);
+ expect(hasCompletionMediaGallery("Emergency")).toBe(true);
+ expect(hasCompletionMediaGallery("PM")).toBe(false);
+ expect(hasCompletionMediaGallery("Overdue")).toBe(false);
+ expect(hasCompletionMediaGallery("")).toBe(false);
+ });
+
+ it("puts Extra photos and videos on Extra Docs when Completion has no gallery", () => {
+ const photo = file({ id: "10", fileType: "image", purpose: "Extra" });
+ const video = file({ id: "11", fileType: "video", purpose: "Extra", category: "Video" });
+
+ for (const item of [photo, video]) {
+ expect(isCompletionSurfaceMedia(item, undefined, false)).toBe(false);
+ expect(isExtrasSurfaceMedia(item, undefined, false)).toBe(true);
+ }
+ });
+
+ it("ignores stale completion ownership when Completion has no gallery", () => {
+ const photo = file({ id: "10", fileType: "image", purpose: "Extra" });
+ const ownership = {
+ completionOwnedIds: new Set(["10"]),
+ extraOwnedIds: new Set(),
+ };
+
+ expect(isCompletionSurfaceMedia(photo, ownership, false)).toBe(false);
+ expect(isExtrasSurfaceMedia(photo, ownership, false)).toBe(true);
+ });
});
diff --git a/src/test/domain/work-orders/utils/severity-escalation.test.ts b/src/test/domain/work-orders/utils/severity-escalation.test.ts
index 812e40f9..22c2cc9a 100644
--- a/src/test/domain/work-orders/utils/severity-escalation.test.ts
+++ b/src/test/domain/work-orders/utils/severity-escalation.test.ts
@@ -18,6 +18,21 @@ describe("shouldAnnounceSeverityEscalation", () => {
expect(shouldAnnounceSeverityEscalation(2, 3)).toBe(false);
});
+ it("announces when severity rises from SEV 3–5 into SEV 2", () => {
+ expect(shouldAnnounceSeverityEscalation(5, 2)).toBe(true);
+ expect(shouldAnnounceSeverityEscalation(4, 2)).toBe(true);
+ });
+
+ it("does not announce moves between SEV 3–5", () => {
+ expect(shouldAnnounceSeverityEscalation(5, 3)).toBe(false);
+ expect(shouldAnnounceSeverityEscalation(4, 3)).toBe(false);
+ expect(shouldAnnounceSeverityEscalation(3, 5)).toBe(false);
+ });
+
+ it("does not announce SEV 1 to SEV 2 (already critical)", () => {
+ expect(shouldAnnounceSeverityEscalation(1, 2)).toBe(false);
+ });
+
it("does not announce SEV 2 to SEV 1 (already critical)", () => {
expect(shouldAnnounceSeverityEscalation(2, 1)).toBe(false);
});
diff --git a/src/test/domain/work-orders/utils/wo-lifecycle-transitions.test.ts b/src/test/domain/work-orders/utils/wo-lifecycle-transitions.test.ts
index 5e99b7a1..75ea23c6 100644
--- a/src/test/domain/work-orders/utils/wo-lifecycle-transitions.test.ts
+++ b/src/test/domain/work-orders/utils/wo-lifecycle-transitions.test.ts
@@ -1,12 +1,14 @@
import { describe, expect, it } from "vitest";
import { PENDING_UPLIFT_GAP } from "@/domain/work-orders/utils/wo-closability";
import {
+ AUTOMATIC_LIFECYCLE_STATUSES,
BOARD_INLINE_STATUSES,
COMPLETED_DOC_BLOCK_MSG,
COMPLETED_MEDIA_BLOCK_MSG,
CREATION_INLINE_STATUSES,
SCHEDULED_NEEDS_DATE_MSG,
formatAapCompletedBlockTitle,
+ getInlineStatusTransitions,
getStatusOptionState,
hasConcreteScheduleDate,
maybeAutoSchedulePatch,
@@ -17,11 +19,9 @@ import {
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
describe("wo-lifecycle-transitions", () => {
- it("lists AAP board statuses without Canceled", () => {
+ it("lists only manual board statuses: no automatic states and no Canceled (SH-169)", () => {
expect(BOARD_INLINE_STATUSES).toEqual([
- "Incomplete",
"Pending",
- "Scheduled",
"En Route",
"On Site",
"In Progress",
@@ -30,6 +30,21 @@ describe("wo-lifecycle-transitions", () => {
"Pending Quote",
]);
expect(BOARD_INLINE_STATUSES).not.toContain("Canceled");
+ for (const automatic of AUTOMATIC_LIFECYCLE_STATUSES) {
+ expect(BOARD_INLINE_STATUSES).not.toContain(automatic);
+ }
+ });
+
+ it("never offers the current status as a transition (SH-358)", () => {
+ expect(getInlineStatusTransitions("On Site")).toEqual([
+ "Pending",
+ "En Route",
+ "In Progress",
+ "Completed",
+ "Rescheduled",
+ "Pending Quote",
+ ]);
+ expect(getInlineStatusTransitions("Incomplete")).toEqual(BOARD_INLINE_STATUSES);
});
it("lists AAP creation statuses only", () => {