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
This commit is contained in:
Alexandre Brandizzi 2026-09-17 13:14:09 -03:00 • committed by GitHub
commit 04a248fd53
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 377 additions and 7 deletions

View file

@ -155,6 +155,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

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

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

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

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