Merge branch 'dev' into feat/ab/sh-336-dashboard
|
Before Width: | Height: | Size: 139 KiB After Width: | Height: | Size: 142 KiB |
|
Before Width: | Height: | Size: 116 KiB After Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 143 KiB After Width: | Height: | Size: 146 KiB |
|
Before Width: | Height: | Size: 100 KiB After Width: | Height: | Size: 103 KiB |
|
Before Width: | Height: | Size: 98 KiB After Width: | Height: | Size: 101 KiB |
|
Before Width: | Height: | Size: 98 KiB After Width: | Height: | Size: 101 KiB |
|
Before Width: | Height: | Size: 101 KiB After Width: | Height: | Size: 104 KiB |
|
Before Width: | Height: | Size: 108 KiB After Width: | Height: | Size: 111 KiB |
|
Before Width: | Height: | Size: 39 KiB After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 139 KiB After Width: | Height: | Size: 144 KiB |
|
Before Width: | Height: | Size: 99 KiB After Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 112 KiB After Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 144 KiB After Width: | Height: | Size: 148 KiB |
|
Before Width: | Height: | Size: 117 KiB After Width: | Height: | Size: 120 KiB |
|
Before Width: | Height: | Size: 39 KiB After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 185 KiB After Width: | Height: | Size: 189 KiB |
121
e2e/work-orders/wo-number-sh-placeholder.spec.ts
Normal 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([]);
|
||||
});
|
||||
});
|
||||
|
|
@ -204,6 +204,12 @@ async function openWorkOrderPage(page: Page, mode: "default" | "empty" | "error"
|
|||
});
|
||||
}
|
||||
|
||||
async function expectWorkOrderPageReady(page: Page) {
|
||||
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible({
|
||||
timeout: 90_000,
|
||||
});
|
||||
}
|
||||
|
||||
async function expectStableScreenshot(page: Page, name: string) {
|
||||
await page.waitForTimeout(250);
|
||||
await page.evaluate(
|
||||
|
|
@ -217,15 +223,18 @@ async function expectStableScreenshot(page: Page, name: string) {
|
|||
}
|
||||
|
||||
test.describe("Work Orders deterministic pixel regression", () => {
|
||||
test.setTimeout(120_000);
|
||||
|
||||
test("list", async ({ page }) => {
|
||||
await openWorkOrderPage(page);
|
||||
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible();
|
||||
await expectWorkOrderPageReady(page);
|
||||
await expect(page.getByText("WO-501").first()).toBeVisible();
|
||||
await expectStableScreenshot(page, "wo-list.png");
|
||||
});
|
||||
|
||||
test("filters", async ({ page }) => {
|
||||
await openWorkOrderPage(page);
|
||||
await expectWorkOrderPageReady(page);
|
||||
await page.getByRole("button", { name: "Advanced Filters" }).click();
|
||||
await expect(page.getByRole("dialog", { name: "Advanced Filters" })).toBeVisible();
|
||||
await expectStableScreenshot(page, "wo-filters.png");
|
||||
|
|
@ -233,6 +242,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
|
|||
|
||||
test("new", async ({ page }) => {
|
||||
await openWorkOrderPage(page);
|
||||
await expectWorkOrderPageReady(page);
|
||||
await page.getByRole("button", { name: "New WO" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Type & schedule" })).toBeVisible();
|
||||
await expectStableScreenshot(page, "wo-new.png");
|
||||
|
|
@ -240,6 +250,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
|
|||
|
||||
test("detail", async ({ page }) => {
|
||||
await openWorkOrderPage(page);
|
||||
await expectWorkOrderPageReady(page);
|
||||
const row = page.locator("#wo-row-1");
|
||||
await row.hover();
|
||||
await row.getByRole("button", { name: "View details" }).click();
|
||||
|
|
@ -249,7 +260,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
|
|||
|
||||
test("empty", async ({ page }) => {
|
||||
await openWorkOrderPage(page, "empty");
|
||||
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible();
|
||||
await expectWorkOrderPageReady(page);
|
||||
await page.getByLabel("Search work orders").fill("zz");
|
||||
await expect(page.getByText("No work orders match your search")).toBeVisible();
|
||||
await expectStableScreenshot(page, "wo-empty.png");
|
||||
|
|
@ -257,7 +268,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
|
|||
|
||||
test("error", async ({ page }) => {
|
||||
await openWorkOrderPage(page, "error");
|
||||
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible();
|
||||
await expectWorkOrderPageReady(page);
|
||||
const alert = page.getByRole("main").getByRole("alert");
|
||||
await expect(alert).toBeVisible();
|
||||
await expect(alert).toContainText(/server error/i);
|
||||
|
|
@ -267,6 +278,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
|
|||
test("mobile", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await openWorkOrderPage(page);
|
||||
await expectWorkOrderPageReady(page);
|
||||
await expect(page.getByText("WO-501").first()).toBeVisible();
|
||||
await expectStableScreenshot(page, "wo-mobile.png");
|
||||
|
||||
|
|
|
|||
|
|
@ -77,6 +77,9 @@ export const API_PATHS = {
|
|||
deleteEmployees: "Employee/DeleteEmployees",
|
||||
dropdown: "Employee/Dropdown",
|
||||
},
|
||||
teamMember: {
|
||||
getList: "User",
|
||||
},
|
||||
contact: {
|
||||
getList: "Contact/GetContactList",
|
||||
getContacts: "Contact/GetContacts",
|
||||
|
|
@ -160,6 +163,9 @@ export const API_PATHS = {
|
|||
update: "DropdownOptions/Update",
|
||||
delete: "DropdownOptions",
|
||||
},
|
||||
services: {
|
||||
list: "services",
|
||||
},
|
||||
user: {
|
||||
list: "User",
|
||||
},
|
||||
|
|
|
|||
|
|
@ -0,0 +1,110 @@
|
|||
import {
|
||||
Avatar,
|
||||
Button,
|
||||
CircularProgress,
|
||||
Paper,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import type { TeamMemberListItem } from "@/domain/team-members/types/team-member";
|
||||
|
||||
const HEADINGS = ["Team Member", "Role", "Service Area", "Phone", "Email", "Color", "Status"];
|
||||
|
||||
function memberStatusLabel(status: TeamMemberListItem["status"]) {
|
||||
return status === "Active" ? "Active" : "Inactive";
|
||||
}
|
||||
|
||||
export function TeamMembersTable({
|
||||
rows,
|
||||
isLoading,
|
||||
hasError,
|
||||
tab,
|
||||
onOpen,
|
||||
}: {
|
||||
rows: TeamMemberListItem[];
|
||||
isLoading: boolean;
|
||||
hasError: boolean;
|
||||
tab: "active" | "inactive";
|
||||
onOpen: (member: TeamMemberListItem) => void;
|
||||
}) {
|
||||
return (
|
||||
<TableContainer component={Paper} variant="outlined">
|
||||
<Table stickyHeader size="small" sx={{ minWidth: 900 }}>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
{HEADINGS.map((heading) => (
|
||||
<TableCell key={heading} className="font-semibold">
|
||||
{heading}
|
||||
</TableCell>
|
||||
))}
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Actions
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{isLoading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={8} align="center" sx={{ py: 8 }}>
|
||||
<CircularProgress size={28} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : hasError ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={8} align="center" sx={{ py: 8 }}>
|
||||
<Typography sx={{ fontWeight: 600 }}>Unable to load team members</Typography>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Check your connection and try again.
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : rows.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={8} align="center" sx={{ py: 8 }}>
|
||||
<Typography sx={{ fontWeight: 600 }}>No {tab} team members found</Typography>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Try a different search, or add a new team member.
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
rows.map((member) => (
|
||||
<TableRow
|
||||
key={String(member.id)}
|
||||
hover
|
||||
onClick={() => onOpen(member)}
|
||||
sx={{ cursor: "pointer" }}
|
||||
>
|
||||
<TableCell>{member.name || "—"}</TableCell>
|
||||
<TableCell>{member.role || "—"}</TableCell>
|
||||
<TableCell>{member.serviceArea || "—"}</TableCell>
|
||||
<TableCell>{member.phone || "—"}</TableCell>
|
||||
<TableCell>{member.email || "—"}</TableCell>
|
||||
<TableCell>
|
||||
<Avatar sx={{ width: 22, height: 22, bgcolor: member.color || "primary.main" }} />
|
||||
</TableCell>
|
||||
<TableCell>{memberStatusLabel(member.status)}</TableCell>
|
||||
<TableCell align="right">
|
||||
<Button
|
||||
size="small"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onOpen(member);
|
||||
}}
|
||||
>
|
||||
View
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
);
|
||||
}
|
||||
193
src/app/(protected)/team-members/index.tsx
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
import { useState } from "react";
|
||||
import { useDebounce } from "@/hooks/use-debounce";
|
||||
import { useTeamMembersList } from "@/domain/team-members/use-cases/use-team-members-list";
|
||||
import type { TeamMemberListItem } from "@/domain/team-members/types/team-member";
|
||||
import {
|
||||
Alert,
|
||||
Avatar,
|
||||
Box,
|
||||
Button,
|
||||
Chip,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
Drawer,
|
||||
IconButton,
|
||||
Stack,
|
||||
Tab,
|
||||
Tabs,
|
||||
TextField,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import { TeamMembersTable } from "./_components/team-members-table";
|
||||
|
||||
type StatusTab = "active" | "inactive";
|
||||
|
||||
const STATUS_LABELS: Record<StatusTab, "Active" | "Inactive"> = {
|
||||
active: "Active",
|
||||
inactive: "Inactive",
|
||||
};
|
||||
|
||||
function MemberStatus({ status }: { status: TeamMemberListItem["status"] }) {
|
||||
return <Chip size="small" label={status} color={status === "Active" ? "success" : "default"} />;
|
||||
}
|
||||
|
||||
function TeamMemberDrawer({
|
||||
member,
|
||||
onClose,
|
||||
}: {
|
||||
member: TeamMemberListItem | null;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Drawer anchor="right" open={Boolean(member)} onClose={onClose}>
|
||||
<Box sx={{ width: { xs: "100vw", sm: 380 }, p: 3 }}>
|
||||
<Stack
|
||||
direction="row"
|
||||
sx={{ alignItems: "center", justifyContent: "space-between", mb: 3 }}
|
||||
>
|
||||
<Typography variant="h6">Team Member</Typography>
|
||||
<IconButton aria-label="Close team member details" onClick={onClose}>
|
||||
<CloseIcon />
|
||||
</IconButton>
|
||||
</Stack>
|
||||
{member !== null && (
|
||||
<Stack spacing={2}>
|
||||
<Stack direction="row" spacing={2} sx={{ alignItems: "center" }}>
|
||||
<Avatar sx={{ bgcolor: member.color || "primary.main" }}>
|
||||
{member.name.slice(0, 1).toUpperCase() || "?"}
|
||||
</Avatar>
|
||||
<Box>
|
||||
<Typography variant="h6">{member.name || "—"}</Typography>
|
||||
<Typography color="text.secondary">{member.role || "—"}</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
<MemberStatus status={member.status} />
|
||||
<Typography>
|
||||
<strong>Service Area:</strong> {member.serviceArea || "—"}
|
||||
</Typography>
|
||||
<Typography>
|
||||
<strong>Phone:</strong> {member.phone || "—"}
|
||||
</Typography>
|
||||
<Typography>
|
||||
<strong>Email:</strong> {member.email || "—"}
|
||||
</Typography>
|
||||
</Stack>
|
||||
)}
|
||||
</Box>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
export default function TeamMembersListPage() {
|
||||
const [search, setSearch] = useState("");
|
||||
const [tab, setTab] = useState<StatusTab>("active");
|
||||
const [selectedMember, setSelectedMember] = useState<TeamMemberListItem | null>(null);
|
||||
const [addMemberOpen, setAddMemberOpen] = useState(false);
|
||||
const debouncedSearch = useDebounce(search, 300).trim().toLowerCase();
|
||||
const { data, isLoading, error } = useTeamMembersList();
|
||||
const allMembers = data?.items ?? [];
|
||||
|
||||
const activeCount = allMembers.filter((member) => member.status === "Active").length;
|
||||
const inactiveCount = allMembers.length - activeCount;
|
||||
const rows = allMembers
|
||||
.filter((member) => member.status === STATUS_LABELS[tab])
|
||||
.filter((member) => !debouncedSearch || member.name.toLowerCase().includes(debouncedSearch));
|
||||
|
||||
return (
|
||||
<Box
|
||||
className="flex h-full flex-col overflow-hidden"
|
||||
sx={{ backgroundColor: "var(--color-bg-page)" }}
|
||||
>
|
||||
<Stack
|
||||
direction={{ xs: "column", sm: "row" }}
|
||||
spacing={2}
|
||||
sx={{
|
||||
alignItems: { xs: "stretch", sm: "center" },
|
||||
justifyContent: "space-between",
|
||||
p: 2.5,
|
||||
backgroundColor: "var(--color-bg-surface)",
|
||||
borderBottom: "1px solid var(--color-border)",
|
||||
}}
|
||||
>
|
||||
<Box>
|
||||
<Typography variant="h4" component="h1">
|
||||
Team Members
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.75 }}>
|
||||
{allMembers.length} team member{allMembers.length === 1 ? "" : "s"} · {activeCount}{" "}
|
||||
active
|
||||
</Typography>
|
||||
</Box>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: "center" }}>
|
||||
<TextField
|
||||
size="small"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder="Search team member…"
|
||||
aria-label="Search team member"
|
||||
sx={{ width: 224 }}
|
||||
/>
|
||||
<Button variant="contained" size="small" onClick={() => setAddMemberOpen(true)}>
|
||||
Add Member
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
||||
<Tabs
|
||||
value={tab}
|
||||
onChange={(_event, value: StatusTab) => setTab(value)}
|
||||
aria-label="Team member status"
|
||||
>
|
||||
<Tab value="active" label={`Active ${activeCount}`} />
|
||||
<Tab value="inactive" label={`Inactive ${inactiveCount}`} />
|
||||
</Tabs>
|
||||
|
||||
{Boolean(error) && (
|
||||
<Alert severity="error">
|
||||
{error instanceof Error ? error.message : "Failed to load team members"}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Box sx={{ flex: 1, overflow: "auto", p: 2 }}>
|
||||
<TeamMembersTable
|
||||
rows={rows}
|
||||
isLoading={isLoading}
|
||||
hasError={Boolean(error)}
|
||||
tab={tab}
|
||||
onOpen={setSelectedMember}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Stack
|
||||
direction="row"
|
||||
sx={{
|
||||
justifyContent: "space-between",
|
||||
px: 2,
|
||||
py: 1,
|
||||
borderTop: "1px solid var(--color-border)",
|
||||
backgroundColor: "var(--color-bg-surface)",
|
||||
}}
|
||||
>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{rows.length} {tab} team member{rows.length === 1 ? "" : "s"}
|
||||
{debouncedSearch ? " · filtered" : ""}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{activeCount} active · {inactiveCount} inactive
|
||||
</Typography>
|
||||
</Stack>
|
||||
|
||||
<TeamMemberDrawer member={selectedMember} onClose={() => setSelectedMember(null)} />
|
||||
<Dialog open={addMemberOpen} onClose={() => setAddMemberOpen(false)}>
|
||||
<DialogTitle>Add Member</DialogTitle>
|
||||
<DialogContent>Member details will be added here.</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setAddMemberOpen(false)}>Close</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 ?? "",
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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: "",
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -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" }],
|
||||
|
|
|
|||
30
src/domain/services/api/services-api.ts
Normal 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));
|
||||
},
|
||||
};
|
||||
71
src/domain/services/mappers/service-mapper.ts
Normal 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 !== "") : [];
|
||||
}
|
||||
11
src/domain/services/types/service.ts
Normal 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[];
|
||||
}
|
||||
|
|
@ -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,
|
||||
});
|
||||
}
|
||||
13
src/domain/team-members/api/team-members-api.ts
Normal file
|
|
@ -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<TeamMemberListResult> => {
|
||||
const data = await apiGet<unknown>(API_PATHS.teamMember.getList);
|
||||
const items = handleApiResponse<unknown[]>(data);
|
||||
return { items: mapTeamMemberListItems(Array.isArray(items) ? items : []) };
|
||||
},
|
||||
};
|
||||
45
src/domain/team-members/mappers/team-member-mapper.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import type { TeamMemberListItem } from "@/domain/team-members/types/team-member";
|
||||
|
||||
function readString(record: Record<string, unknown>, ...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<string, unknown>, ...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<string, unknown>;
|
||||
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);
|
||||
}
|
||||
15
src/domain/team-members/types/team-member.ts
Normal file
|
|
@ -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[];
|
||||
}
|
||||
11
src/domain/team-members/use-cases/use-team-members-list.ts
Normal file
|
|
@ -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<TeamMemberListResult, Error> {
|
||||
return useQuery({
|
||||
queryKey: queryKeys.teamMembers.list(),
|
||||
queryFn: teamMembersApi.getList,
|
||||
});
|
||||
}
|
||||
|
|
@ -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]);
|
||||
|
||||
|
|
|
|||
|
|
@ -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 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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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) : "",
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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`. */
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
},
|
||||
|
|
|
|||
33
src/domain/work-orders/utils/wo-number-input.ts
Normal 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);
|
||||
}
|
||||
|
|
@ -49,6 +49,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: (range: DashboardRangeKey, dispatcherId: string | null = null) =>
|
||||
|
|
@ -68,6 +72,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>) =>
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -79,6 +79,7 @@ describe("WizardStepLocationServiceSelect — vendor clear on service change", (
|
|||
|
||||
expect(onPatch).toHaveBeenCalledWith({
|
||||
pm: "Electrical",
|
||||
serviceId: "3",
|
||||
extraServices: [],
|
||||
vendorId: "",
|
||||
vendorName: "",
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
});
|
||||
});
|
||||
48
src/test/domain/services/api/services-api.test.ts
Normal 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([]);
|
||||
});
|
||||
});
|
||||
28
src/test/domain/team-members/team-member-mapper.test.ts
Normal file
|
|
@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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", () => {
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||