feat(work-orders): use services registry picker

This commit is contained in:
Codex Review Integration 2026-09-16 18:26:55 -03:00
parent 07734d8361
commit 3a902bfebe
18 changed files with 236 additions and 5 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

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

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

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