Compare commits

...

46 commits

Author SHA1 Message Date
Alexandre Brandizzi
2f659bb6cd
Merge branch 'dev' into feat/ab/sh-326-team-member 2026-09-17 14:26:24 -03:00
Alexandre Brandizzi
c0b511ed12
Merge pull request #218 from Sea-Haven-Industries/fix/ab/sh-375-edit-error-copy
SH-375: keep backend validation text out of work-order edit errors
2026-09-17 14:18:12 -03:00
Alexandre Brandizzi
8d2adb4472
Merge branch 'dev' into fix/ab/sh-375-edit-error-copy 2026-09-17 14:04:19 -03:00
Codex Review Integration
8bc6c5e687 Merge remote-tracking branch 'origin/dev' into feat/ab/sh-326-team-member
# Conflicts:
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-error.png
2026-09-17 14:00:03 -03:00
Alexandre Brandizzi
1e1b58c560
Merge pull request #211 from Sea-Haven-Industries/feat/ab/sh-324-team-members-list
SH-324: add searchable team member registry
2026-09-17 13:42:13 -03:00
Alexandre Brandizzi
d6518bc065
Merge branch 'dev' into feat/ab/sh-324-team-members-list 2026-09-17 13:28:10 -03:00
Alexandre Brandizzi
04a248fd53
Merge pull request #210 from Sea-Haven-Industries/feat/ab/sh-187-service-picker
Some checks are pending
Frontend checks / Build and test (push) Waiting to run
Frontend checks / governance (push) Waiting to run
Frontend checks / Visual regression (push) Waiting to run
Deploy dev content / Deploy shoc-frontend-new-dev through Terraform (push) Waiting to run
SH-187: Use Services registry in work-order picker
2026-09-17 13:14:09 -03:00
Alexandre Brandizzi
c991c9e89f
Merge branch 'dev' into feat/ab/sh-187-service-picker 2026-09-17 13:02:18 -03:00
Alexandre Brandizzi
56a7895950
Merge pull request #206 from Sea-Haven-Industries/fix/ab/sh-320-inline-sh-prefix-wo-number
SH-320: accept SH-prefixed placeholder work-order numbers
2026-09-17 13:00:19 -03:00
Alexandre Brandizzi
8427182209
Merge branch 'dev' into feat/ab/sh-187-service-picker 2026-09-17 12:58:17 -03:00
Alexandre Brandizzi
a9247a1997
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-17 12:50:18 -03:00
Codex Review Integration
b551421115 fix(work-orders): show duplicate-WO copy for edit conflicts (SH-375)
A duplicate work order number edit returns 422 DuplicateWoNumber from the
board PATCH endpoint, which mapped to the generic save-failed copy. Add the
code to the known validation copy map so edits reuse the same duplicate-WO
product text as create, and share the message constant across both paths.
2026-09-17 06:15:23 -03:00
Codex Review Integration
5c093e8c26 Merge remote-tracking branch 'origin/dev' into fix/ab/sh-375-edit-error-copy 2026-09-17 05:59:25 -03:00
Codex Review Integration
824001dc5e fix(work-orders): make service picker search placeholder type-neutral 2026-09-17 01:40:58 -03:00
Codex Review Integration
7cef338e34 Merge remote-tracking branch 'origin/dev' into feat/ab/sh-324-team-members-list
# Conflicts:
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-add.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-detail.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-edit.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-empty.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-error.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-filter.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-inactive.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-list.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-mobile-navigation.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-detail.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-empty.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-error.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-filters.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-list.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-new.png
2026-09-17 00:49:09 -03:00
Alexandre Brandizzi
5e4999b4f2
Merge pull request #207 from Sea-Haven-Industries/fix/ab/sh-359-wo-board-column-order
Some checks are pending
Frontend checks / Build and test (push) Waiting to run
Frontend checks / governance (push) Waiting to run
Frontend checks / Visual regression (push) Waiting to run
Deploy dev content / Deploy shoc-frontend-new-dev through Terraform (push) Waiting to run
SH-359: place Completed Date before Comp Doc
2026-09-16 23:54:15 -03:00
Alexandre Brandizzi
bc40c17285
Merge branch 'dev' into fix/ab/sh-359-wo-board-column-order 2026-09-16 23:44:07 -03:00
Codex Review Integration
ae255f59a6 fix(team-members): destructure load error prop (SH-324) 2026-09-16 22:58:46 -03:00
Codex Review Integration
9160dd472a test(work-orders): refresh startup visual baselines (SH-324) 2026-09-16 22:53:03 -03:00
Codex Review Integration
a4ce537ed6 test(work-orders): tolerate cold visual page startup (SH-324) 2026-09-16 22:50:55 -03:00
Codex Review Integration
4bee428c71 test(team-members): refresh sidebar visual baselines (SH-324) 2026-09-16 22:39:09 -03:00
Codex Review Integration
1df3e5d292 fix(team-members): render load failures distinctly (SH-324) 2026-09-16 22:38:53 -03:00
Codex Review Integration
49923c9a02 test(work-orders): target the Insert WO # placeholder in the SH number e2e
The inline create row now renders the empty WO # cell as a required
"Insert WO # *" field instead of "-", so the spec waited for a cell that
no longer exists.
2026-09-16 22:07:46 -03:00
Alexandre Brandizzi
e6f5199da9
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 21:56:20 -03:00
Codex Review Integration
2d54ff12f8 fix(work-orders): show fixed copy for edit conflict toasts (SH-375) 2026-09-16 21:22:07 -03:00
Codex Review Integration
afc98a9daa fix(work-orders): normalize partial-save and generic edit error toasts (SH-375) 2026-09-16 21:20:16 -03:00
Codex Review Integration
fc25d8f7c7 fix(work-orders): show generic copy for unknown edit errors (SH-375) 2026-09-16 21:14:25 -03:00
Alexandre Brandizzi
c0d3300ab1
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 20:48:14 -03:00
Alexandre Brandizzi
6682fcd7c2
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 20:30:17 -03:00
Alexandre Brandizzi
7aa964aa0f
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 20:16:15 -03:00
Alexandre Brandizzi
85a6dad0f9
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 20:00:13 -03:00
Alexandre Brandizzi
ace66f52e5
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 19:46:22 -03:00
Alexandre Brandizzi
ef199e19b6
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 19:34:20 -03:00
Codex Review Integration
71756ca3a5 fix(work-orders): clear registry service when WO type changes
Selecting a work-order type on wizard step 1 only patched type and
severity, leaving pm, serviceId, extraServices, and the vendor filtered
by that service in the draft. Switching type (e.g. PM -> Reactive) then
submitted a serviceId that is not in the new type's registry list, which
backend ResolveServiceAsync (SH-187/#131) rejects as ServiceInvalid and
the create toast renders as the generic "Unable to create the work
order". Clear the service and its vendor whenever the type actually
changes; re-selecting the same type leaves the selection untouched.
2026-09-16 19:33:08 -03:00
Alexandre Brandizzi
a793e1c2d9
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 19:18:18 -03:00
Alexandre Brandizzi
b120b43b0f
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 19:04:14 -03:00
Alexandre Brandizzi
cd611fd09c
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 18:52:23 -03:00
Alexandre Brandizzi
551ed863f4
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 18:38:20 -03:00
Alexandre Brandizzi
ac2642d5b9
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 18:28:25 -03:00
Codex Review Integration
3a902bfebe feat(work-orders): use services registry picker 2026-09-16 18:26:55 -03:00
Codex Review Integration
4eb929e1c8 test(work-orders): remove query devtools overlay after navigation
Also drops ticket keys from shipped comments and test names.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 15:15:52 -03:00
Alexandre Brandizzi
2d8a35a08a
Merge branch 'dev' into fix/ab/sh-359-wo-board-column-order 2026-09-16 15:08:07 -03:00
Codex Review Integration
62825d2c70 chore(workorders): remove ticket keys from column comments 2026-09-16 15:05:25 -03:00
Codex Review Integration
4649fd00da fix(work-orders): place Completed Date before Comp Doc on the board 2026-09-16 13:21:48 -03:00
Codex Review Integration
050e3f5134 test(work-orders): cover SH placeholder WO numbers on the board 2026-09-16 13:13:35 -03:00
Codex Review Integration
45b988c522 fix(work-orders): accept SH placeholder numbers in the inline WO number field 2026-09-16 13:12:24 -03:00
37 changed files with 1087 additions and 58 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

After

Width:  |  Height:  |  Size: 101 KiB

View file

@ -0,0 +1,121 @@
import { expect, test, type Page, type Route } from "@playwright/test";
const FROZEN_NOW = "2026-08-19T15:00:00.000Z";
const TEST_USER = {
token: "wo-number-sh-placeholder-e2e-token",
expiration: "2030-01-01T00:00:00.000Z",
email: "admin@seahavenind.com",
userRoles: "Admin",
phoneNumber: "5551234567",
fullname: "Work Order E2E Admin",
id: "1",
};
async function fulfillJson(route: Route, body: unknown, status = 200) {
await route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
}
async function hideQueryDevtools(page: Page) {
await page.addStyleTag({
content:
".tsqd-parent-container { display: none !important; pointer-events: none !important; }",
});
await page.locator(".tsqd-parent-container").evaluateAll((nodes) => {
for (const node of nodes) {
node.remove();
}
});
}
const REAL_ROW = {
id: 1000,
woNumber: "12345678901",
workOrderType: 2,
siteCode: "DAL1",
lifecycleStatusLabel: "Scheduled",
scheduledDate: "2026-08-19",
dispatcherId: "1",
dispatcherName: "Pat Dispatcher",
pm: "HVAC",
};
async function mockBoard(page: Page, patches: unknown[]) {
await page.route(
(url) => url.pathname.startsWith("/api/"),
async (route) => {
const request = route.request();
const url = request.url();
if (request.method() !== "GET") {
patches.push({ url, body: request.postDataJSON() });
await fulfillJson(route, {}, 500);
return;
}
if (url.includes("workorders/board/search")) {
await fulfillJson(route, { items: [REAL_ROW], totalCount: 1, page: 0, pageSize: 50 });
return;
}
if (url.includes("workorders/board")) {
await fulfillJson(route, {
weekStart: "2026-08-17",
weekEnd: "2026-08-21",
counts: { returned: 1, total: 1 },
unscheduled: [],
scheduled: [REAL_ROW],
});
return;
}
await fulfillJson(route, { data: [], items: [] });
},
);
}
test.describe("inline WO number SH placeholder", () => {
test.setTimeout(60_000);
test.beforeEach(async ({ page }) => {
await page.clock.install({ time: new Date(FROZEN_NOW) });
await page.clock.resume();
await page.addInitScript((user) => {
localStorage.setItem("auth", JSON.stringify(user));
}, TEST_USER);
});
test("keeps a typed SH number on a new inline row and blocks downgrading a saved real number", async ({
page,
}) => {
const mutations: unknown[] = [];
await mockBoard(page, mutations);
await page.goto("/workorders");
await hideQueryDevtools(page);
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible({
timeout: 20_000,
});
await expect(page.getByText("12345678901").first()).toBeVisible();
await page
.getByRole("button", { name: /Add WO/ })
.first()
.click();
await page
.getByText(/^Insert WO #/)
.first()
.click();
const draftInput = page.getByLabel("Work order number");
await draftInput.fill("SH00001");
await draftInput.press("Enter");
await expect(draftInput).toHaveCount(0);
await expect(page.getByText("SH00001", { exact: true })).toBeVisible();
await expect(page.getByText(/must be 11 digits/)).toHaveCount(0);
await page.getByText("12345678901", { exact: true }).first().click();
const savedInput = page.getByLabel("Work order number");
await savedInput.fill("SH00009");
await savedInput.press("Enter");
await expect(
page.getByText("Cannot replace an APM work order number with an internal number"),
).toBeVisible();
await expect(page.getByText("12345678901", { exact: true }).first()).toBeVisible();
expect(mutations).toEqual([]);
});
});

View file

@ -160,6 +160,9 @@ export const API_PATHS = {
update: "DropdownOptions/Update",
delete: "DropdownOptions",
},
services: {
list: "services",
},
user: {
list: "User",
},

View file

@ -28,6 +28,7 @@ export function buildInlineDraftCreateInput(
scheduledOn: draft.scheduledOn,
dueDate: draft.dueDate,
pm: draft.pm,
serviceId: null,
extraServices: draft.extraServices ?? [],
avetaRequired: Boolean(draft.avetaRequired),
pmNote: draft.serviceNotes ?? "",

View file

@ -3,6 +3,12 @@ import { toast } from "react-toastify";
import { workOrdersApi } from "@/domain/work-orders/api/work-orders-api";
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
import { findDuplicateWoNumberRow } from "@/domain/work-orders/utils/find-duplicate-wo-number-row";
import {
WO_NUMBER_DOWNGRADE_MESSAGE,
WO_NUMBER_FORMAT_MESSAGE,
isValidBoardWoNumber,
isWoNumberDowngrade,
} from "@/domain/work-orders/utils/wo-number-input";
import { EditableWONumberInput } from "./editable-wo-number-input";
import { HighlightText } from "./highlight-text";
import { AddOnPill, CarriedOverCounterPill, RescheduleCounterPill } from "./wo-counter-pills";
@ -26,6 +32,9 @@ type EditableWONumberCellProps = {
requiredPlaceholder?: string;
};
/** Inline-create rows pass this id; their number is draft state, never a saved WO number. */
const UNSAVED_DRAFT_ID = "draft";
async function resolveDuplicateWoNumber(
draft: string,
allOrders: WorkOrderTableRow[],
@ -88,8 +97,14 @@ export function EditableWONumberCell({
setEditing(false);
return;
}
if (draft.length !== 11) {
toast("Work order number must be exactly 11 digits");
if (!isValidBoardWoNumber(draft)) {
toast(WO_NUMBER_FORMAT_MESSAGE);
return;
}
if (String(currentId) !== UNSAVED_DRAFT_ID && isWoNumberDowngrade(value, draft)) {
toast.error(WO_NUMBER_DOWNGRADE_MESSAGE);
setDraft(value);
setEditing(false);
return;
}
setIsChecking(true);
@ -122,14 +137,14 @@ export function EditableWONumberCell({
const handleBlur = () => {
if (isChecking) return;
if (draft !== value && draft.length === 11) {
if (draft !== value && isValidBoardWoNumber(draft)) {
commit();
return;
}
setEditing(false);
};
const invalid = editing && draft.length > 0 && draft.length !== 11;
const invalid = editing && draft.length > 0 && !isValidBoardWoNumber(draft);
if (locked) {
return (

View file

@ -1,3 +1,5 @@
import { sanitizeBoardWoNumberInput } from "@/domain/work-orders/utils/wo-number-input";
type EditableWONumberInputProps = {
draft: string;
invalid: boolean;
@ -21,9 +23,8 @@ export function EditableWONumberInput({
<input
autoFocus
disabled={isChecking}
inputMode="numeric"
value={draft}
onChange={(event) => onChange(event.target.value.replace(/\D/g, "").slice(0, 11))}
onChange={(event) => onChange(sanitizeBoardWoNumberInput(event.target.value))}
onFocus={(event) => event.target.select()}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => {
@ -36,7 +37,7 @@ export function EditableWONumberInput({
}
}}
onBlur={onBlur ?? onCommit}
placeholder="12345678901"
placeholder="e.g. 12345678901 or SH00001"
aria-label="Work order number"
aria-invalid={invalid}
className="font-mono focus:outline-none"

View file

@ -39,7 +39,7 @@ export function PmTypePickerPopover({
autoFocus
value={search}
onChange={(e) => onSearchChange(e.target.value)}
placeholder="Search PM type…"
placeholder="Search service…"
className="w-full rounded border border-border bg-[var(--color-bg-surface)] px-2 py-1 text-xs text-[var(--color-text-primary)] focus:outline-none"
/>
</div>

View file

@ -11,9 +11,10 @@ export const WO_TABLE_COLS = [
{ key: "vendor", label: "VENDOR", w: 184 },
{ key: "appt", label: "APPT TIME", w: 128 },
{ key: "status", label: "STATUS", w: 148 },
// Completed Date gates the Completion Document, so it sits between Status and Comp Doc.
{ key: "completed", label: "COMPLETED DATE", w: 130 },
{ key: "doc", label: "COMP DOC", w: 84 },
{ key: "uplift", label: "UPLIFT", w: 108 },
{ key: "completed", label: "COMPLETED DATE", w: 130 },
{ key: "actions", label: "", w: 100 },
] as const;

View file

@ -105,6 +105,17 @@ export function WoTableRowServiceCells({
onRequestComplete={() => handlers.onRequestComplete?.(row)}
/>
</td>
<td
className="group/cell"
style={{ padding: "0 14px", ...mutationCellStyle }}
onClick={(e) => e.stopPropagation()}
>
<DateCell
value={row.completedDate}
q={search}
onSave={(date) => onPatchRow({ completedDate: date })}
/>
</td>
<td style={{ padding: "0 14px" }} onClick={(e) => e.stopPropagation()}>
<CompDocCell
status={row.docStatus}
@ -126,17 +137,6 @@ export function WoTableRowServiceCells({
}
/>
</td>
<td
className="group/cell"
style={{ padding: "0 14px", ...mutationCellStyle }}
onClick={(e) => e.stopPropagation()}
>
<DateCell
value={row.completedDate}
q={search}
onSave={(date) => onPatchRow({ completedDate: date })}
/>
</td>
</>
);
}

View file

@ -82,7 +82,10 @@ export function NewWoWizard({
locationDetail={wizard.locationDetail}
locationDetailLoading={wizard.locationDetailLoading}
locationDetailError={wizard.locationDetailError}
services={wizard.problems.map((p) => ({ id: p.id, value: p.value }))}
services={wizard.services.map((service) => ({
id: service.id,
value: service.name,
}))}
showErrors={wizard.showErrors}
svcOpen={wizard.svcOpen}
onSvcOpenChange={wizard.setSvcOpen}

View file

@ -2,8 +2,6 @@ import { useEffect } from "react";
import { guardDialogClose } from "@/lib/dialog-guard";
import { useDropdownOptionsByCategory } from "@/domain/settings/dropdown-options/use-cases/use-dropdown-options-by-category";
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
import type { WorkOrderWizardDraft } from "@/domain/work-orders/types/work-order-wizard";
@ -16,6 +14,7 @@ import { useCreateWorkOrderFromWizard } from "@/domain/work-orders/use-cases/use
import { useNewWoWizardDraft } from "@/app/(protected)/workorders/_components/wizard/use-new-wo-wizard-draft";
import { useWizardDuplicateActions } from "@/app/(protected)/workorders/_components/wizard/use-wizard-duplicate-actions";
import { useWizardPocAutofill } from "@/app/(protected)/workorders/_components/wizard/use-wizard-poc-autofill";
import { useServicesForWorkOrderType } from "@/domain/services/use-cases/use-services-for-work-order-type";
type UseNewWoWizardControllerArgs = {
open: boolean;
@ -32,7 +31,7 @@ export function useNewWoWizardController({
const draftState = useNewWoWizardDraft(open);
const { data: locations = [] } = useLocationSites();
const { data: problems = [] } = useDropdownOptionsByCategory("Problem");
const { data: registryServices = [] } = useServicesForWorkOrderType(draftState.draft.type);
const {
data: locationDetail,
isLoading: locationDetailLoading,
@ -78,7 +77,7 @@ export function useNewWoWizardController({
...draftState,
patchDraft,
locations,
problems,
services: registryServices,
locationDetail,
locationDetailLoading,
locationDetailError,

View file

@ -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={
<Droplets size={16} className="shrink-0" style={{ color: "var(--muted-foreground)" }} />
}
searchPlaceholder="Search PM type…"
searchPlaceholder="Search services…"
options={services.map((s) => {
const Icon = getPmTypeIcon(s.value);
return {

View file

@ -270,9 +270,23 @@ export function WizardStepTypeSchedule({
<WoTypePicker
selected={draft.type}
onSelect={(t) => {
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: "",
}
: {}),
});
}}
/>

View file

@ -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<Exclude<WOType, "Overdue">, 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<Service[]> => {
const data = await apiGet<unknown>(API_PATHS.services.list, {
searchParams: { isActive: true },
});
return mapServices(handleApiResponse(data));
},
getActiveForWorkOrderType: async (workOrderType: WOType): Promise<Service[]> => {
if (workOrderType === "Overdue") return [];
const data = await apiGet<unknown>(API_PATHS.services.list, {
searchParams: { isActive: true, workOrderType: TYPE_TO_API[workOrderType] },
});
return mapServices(handleApiResponse(data));
},
};

View file

@ -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<string, unknown> {
return typeof raw === "object" && raw !== null ? (raw as Record<string, unknown>) : {};
}
function readId(item: Record<string, unknown>): string | number {
const value = item.id ?? item.Id;
return typeof value === "string" || typeof value === "number" ? value : "";
}
function readString(item: Record<string, unknown>, ...keys: string[]): string {
for (const key of keys) {
const value = item[key];
if (typeof value === "string") return value.trim();
}
return "";
}
function readBool(item: Record<string, unknown>, ...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 !== "") : [];
}

View file

@ -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[];
}

View file

@ -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<Service[], Error> {
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<Service[], Error> {
return useQuery({
queryKey: queryKeys.services.active(),
queryFn: () => servicesApi.getActive(),
staleTime: 60 * 1000,
});
}

View file

@ -1,12 +1,12 @@
import { isHTTPError, isNetworkError, isTimeoutError } from "ky";
import { mapHttpStatusToMessage } from "@/api/api-error";
import { DISPATCH_REQUIRED_MESSAGE } from "@/domain/work-orders/errors/board-patch-errors";
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.";
const DUPLICATE_WO_NUMBER_MESSAGE =
"This work order number is already assigned to another work order.";
/** Statuses whose mapped copy is fixed product text, never the response body. */
const FIXED_COPY_STATUSES = new Set([401, 403, 404, 500]);

View file

@ -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 {
@ -24,10 +26,64 @@ export class BoardPatchValidationError extends Error {
export const DISPATCH_REQUIRED_MESSAGE = "Select a vendor company before saving.";
/** why: backend field names must never be exposed through user-facing board toasts. */
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<string, string> = 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 DISPATCH_REQUIRED_MESSAGE;
}
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;
}
}

View file

@ -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) {

View file

@ -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) : "",

View file

@ -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;

View file

@ -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`. */

View file

@ -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,

View file

@ -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<WorkOrderTableRow> {
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;
}
@ -155,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;
@ -165,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();
},

View file

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

View file

@ -61,6 +61,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<string, unknown>) =>

View file

@ -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(
<EditableWONumberCell
value={value}
rescheduleCount={0}
currentId={currentId}
allOrders={[]}
onSave={onSave}
/>,
);
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();
});
});

View file

@ -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(
<WizardStepLocationServiceSelect
draft={draft}
services={[
{ id: "1", value: "HVAC" },
{ id: "2", value: "Plumbing" },
]}
svcOpen={false}
onSvcOpenChange={vi.fn()}
svcSearch=""
onSvcSearchChange={vi.fn()}
onUpdate={vi.fn()}
onPatch={vi.fn()}
/>,
);
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(
<PmTypePickerPopover
anchorEl={anchor}
search=""
filtered={["HVAC", "Plumbing"]}
value=""
showAddDetails={false}
onSearchChange={vi.fn()}
onClose={vi.fn()}
onPick={vi.fn()}
onAddDetails={vi.fn()}
/>,
);
expect(screen.getByPlaceholderText("Search service…")).toBeTruthy();
expect(screen.queryByPlaceholderText("Search PM type…")).toBeNull();
});
});

View file

@ -79,6 +79,7 @@ describe("WizardStepLocationServiceSelect — vendor clear on service change", (
expect(onPatch).toHaveBeenCalledWith({
pm: "Electrical",
serviceId: "3",
extraServices: [],
vendorId: "",
vendorName: "",

View file

@ -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(
<WizardStepTypeSchedule draft={draft} users={USERS} onUpdate={vi.fn()} onPatch={onPatch} />,
);
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(
<WizardStepTypeSchedule draft={draft} users={USERS} onUpdate={vi.fn()} onPatch={onPatch} />,
);
fireEvent.click(screen.getByRole("button", { name: /Scheduled preventive maintenance/ }));
const patch = onPatch.mock.calls[0][0] as Partial<WorkOrderWizardDraft>;
expect(patch).not.toHaveProperty("pm");
expect(patch).not.toHaveProperty("serviceId");
expect(patch).not.toHaveProperty("extraServices");
expect(patch).not.toHaveProperty("vendorId");
});
});

View file

@ -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: () => <span>cell:service</span>,
}));
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/vendor-cell", () => ({
VendorCell: () => <span>cell:vendor</span>,
}));
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/appt-time-cell", () => ({
ApptTimeCell: () => <span>cell:appt</span>,
}));
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/status-cell", () => ({
StatusCell: () => <span>cell:status</span>,
}));
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/date-cell", () => ({
DateCell: () => <span>cell:completed</span>,
}));
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/comp-doc-cell", () => ({
CompDocCell: () => <span>cell:doc</span>,
}));
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/uplift-cell", () => ({
UpliftCell: () => <span>cell:uplift</span>,
}));
/** 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(
<table>
<WoTableHead />
</table>,
{ 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(
<table>
<tbody>
<tr data-testid="row">
<WoTableRowServiceCells
row={row}
vendors={[]}
pmTypes={[]}
handlers={{} as unknown as WoTableRowHandlers}
onPatchRow={vi.fn()}
/>
</tr>
</tbody>
</table>,
{ 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",
]);
});
});

View file

@ -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([]);
});
});

View file

@ -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", () => {

View file

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

View file

@ -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", () => {

View file

@ -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 <QueryClientProvider client={createTestQueryClient()}>{children}</QueryClientProvider>;
}
type FakeResponse = { status: number; body: Record<string, unknown> };
/** 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<unknown> {
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);
});
});