Merge branch 'dev' into feat/ab/sh-195-date-header-tooltips
|
Before Width: | Height: | Size: 140 KiB After Width: | Height: | Size: 137 KiB |
|
Before Width: | Height: | Size: 112 KiB After Width: | Height: | Size: 110 KiB |
|
Before Width: | Height: | Size: 144 KiB After Width: | Height: | Size: 142 KiB |
|
Before Width: | Height: | Size: 98 KiB After Width: | Height: | Size: 99 KiB |
|
Before Width: | Height: | Size: 96 KiB After Width: | Height: | Size: 98 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 96 KiB |
|
Before Width: | Height: | Size: 102 KiB After Width: | Height: | Size: 101 KiB |
|
Before Width: | Height: | Size: 111 KiB After Width: | Height: | Size: 108 KiB |
|
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 45 KiB |
114
e2e/vendors/vendors.spec.ts
vendored
|
|
@ -97,6 +97,7 @@ async function mockVendorApi(
|
|||
listError?: boolean;
|
||||
deactivationBlocked?: boolean;
|
||||
deleteConflict?: boolean;
|
||||
groupedDirectory?: boolean;
|
||||
legacyGateway?: boolean;
|
||||
longText?: boolean;
|
||||
} = {},
|
||||
|
|
@ -147,7 +148,7 @@ async function mockVendorApi(
|
|||
},
|
||||
}),
|
||||
);
|
||||
await page.route("**/api/Vendor/GetVendorList*", async (route) => {
|
||||
await page.route("**/api/Vendor/GetVendorDirectoryList*", async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
state.listUrls.push(url.toString());
|
||||
if (options.listError && url.searchParams.get("pageSize") !== "1") {
|
||||
|
|
@ -168,8 +169,38 @@ async function mockVendorApi(
|
|||
(!company || vendor.CompanyName === company),
|
||||
);
|
||||
const isCount = url.searchParams.get("pageSize") === "1";
|
||||
const responseRows = filtered.map((vendor) => {
|
||||
if (!options.groupedDirectory) return vendor;
|
||||
const technicians = [
|
||||
{
|
||||
Id: vendor.Id,
|
||||
ContactName: vendor.ContactName,
|
||||
Email: vendor.Email,
|
||||
Phone: vendor.Phone,
|
||||
TradeSpecialties: vendor.TradeSpecialties,
|
||||
IsActive: vendor.IsActive,
|
||||
TotalJobs: vendor.TotalJobs,
|
||||
},
|
||||
];
|
||||
if (vendor.Id === 1) {
|
||||
technicians.push({
|
||||
Id: 91,
|
||||
ContactName: "Robin Rivers",
|
||||
Email: "robin@gateway.test",
|
||||
Phone: "314-555-0191",
|
||||
TradeSpecialties: "Drain Cleaning",
|
||||
IsActive: true,
|
||||
TotalJobs: 18,
|
||||
});
|
||||
}
|
||||
return {
|
||||
...vendor,
|
||||
TotalJobs: technicians.reduce((sum, item) => sum + item.TotalJobs, 0),
|
||||
Technicians: technicians,
|
||||
};
|
||||
});
|
||||
await fulfillJson(route, {
|
||||
Data: isCount ? filtered.slice(0, 1) : filtered,
|
||||
Data: isCount ? responseRows.slice(0, 1) : responseRows,
|
||||
TotalCount: filtered.length,
|
||||
PageNumber: 1,
|
||||
PageSize: Number(url.searchParams.get("pageSize") ?? 12),
|
||||
|
|
@ -367,6 +398,43 @@ async function mockVendorApi(
|
|||
}
|
||||
|
||||
test.describe("Vendor directory prototype parity", () => {
|
||||
test("renders company-owned columns and the grouped technician roster", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await mockVendorApi(page, { groupedDirectory: true });
|
||||
await page.goto("/vendors");
|
||||
|
||||
const expectedHeaders = [
|
||||
"Company",
|
||||
"Company Phone",
|
||||
"Company Email",
|
||||
"Street Address",
|
||||
"City",
|
||||
"State",
|
||||
"Trade",
|
||||
"Technician",
|
||||
"Technician Phone",
|
||||
"Total Jobs",
|
||||
"Status",
|
||||
];
|
||||
await expect(page.getByRole("columnheader")).toHaveCount(expectedHeaders.length + 1);
|
||||
for (const header of expectedHeaders) {
|
||||
await expect(page.getByRole("columnheader", { name: header, exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
const gatewayRow = page.getByRole("button", {
|
||||
name: "Open vendor details for Gateway Plumbing",
|
||||
});
|
||||
await expect(gatewayRow).toContainText("Adam Whyte");
|
||||
await expect(gatewayRow).toContainText("90");
|
||||
const rosterBadge = gatewayRow.getByTestId("vendor-technician-badge");
|
||||
await expect(rosterBadge).toHaveText("+1");
|
||||
await rosterBadge.hover();
|
||||
await expect(page.getByRole("tooltip")).toHaveText("Robin Rivers");
|
||||
await rosterBadge.focus();
|
||||
await expect(rosterBadge).toBeFocused();
|
||||
await expect(page.getByRole("tooltip")).toHaveText("Robin Rivers");
|
||||
});
|
||||
|
||||
test("covers status tabs, global counts, search, facets, table fields, and filtered footer", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
|
@ -381,21 +449,24 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
await expect(heading).toHaveCSS("font-weight", "800");
|
||||
await expect(heading).toHaveCSS("line-height", "33px");
|
||||
await expect(heading).toHaveCSS("letter-spacing", "-0.6px");
|
||||
await expect(page.getByText("3 technicians · 2 active")).toBeVisible();
|
||||
await expect(page.getByText("2 active companies").first()).toBeVisible();
|
||||
await expect(page.getByRole("tab", { name: "Active (2)" })).toHaveAttribute(
|
||||
"aria-selected",
|
||||
"true",
|
||||
);
|
||||
for (const heading of [
|
||||
"Company",
|
||||
"Technician",
|
||||
"Location",
|
||||
"Company Phone",
|
||||
"Company Email",
|
||||
"Street Address",
|
||||
"City",
|
||||
"State",
|
||||
"Trade",
|
||||
"Phone",
|
||||
"Email",
|
||||
"Technician",
|
||||
"Technician Phone",
|
||||
"Total Jobs",
|
||||
]) {
|
||||
await expect(page.getByRole("columnheader", { name: heading })).toBeVisible();
|
||||
await expect(page.getByRole("columnheader", { name: heading, exact: true })).toBeVisible();
|
||||
}
|
||||
await expect(page.getByRole("columnheader", { name: "Status" })).toBeVisible();
|
||||
const activeTabBox = await page.getByRole("tab", { name: "Active (2)" }).boundingBox();
|
||||
|
|
@ -403,10 +474,11 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
const tableContainerBox = await page.locator("table").locator("..").boundingBox();
|
||||
expect(tableContainerBox).toMatchObject({ x: 260, y: 212.5, width: 1164 });
|
||||
expect(tableContainerBox?.height).toBeCloseTo(738, 0);
|
||||
expect((await page.locator("table").boundingBox())?.width).toBe(1550);
|
||||
expect((await page.getByRole("columnheader", { name: "Company" }).boundingBox())?.height).toBe(
|
||||
47,
|
||||
);
|
||||
expect((await page.locator("table").boundingBox())?.width).toBe(2050);
|
||||
expect(
|
||||
(await page.getByRole("columnheader", { name: "Company", exact: true }).boundingBox())
|
||||
?.height,
|
||||
).toBe(47);
|
||||
expect((await page.locator("tbody tr").first().boundingBox())?.height).toBe(52);
|
||||
await expect(page.getByText("Gateway Plumbing")).toBeVisible();
|
||||
const tradeBadge = page.getByTestId("vendor-trade-badge").first();
|
||||
|
|
@ -419,13 +491,13 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
await expect(page.getByRole("dialog")).toHaveCount(0);
|
||||
await tradeBadge.press("Enter");
|
||||
await expect(page.getByRole("dialog")).toHaveCount(0);
|
||||
await expect(page.getByText("2 active technicians")).toBeVisible();
|
||||
await expect(page.getByText("2 active companies").last()).toBeVisible();
|
||||
await expect(page.getByText("2 active · 1 inactive")).toBeVisible();
|
||||
await captureVisual(page, "/tmp/seahaven-vendor-implemented-list.png");
|
||||
|
||||
await page.getByPlaceholder("Search name, company, trade…").fill("metro");
|
||||
await expect(page.getByText("Metro HVAC")).toBeVisible();
|
||||
await expect(page.getByText(/1 active technician · filtered/)).toBeVisible();
|
||||
await expect(page.getByText(/1 active company · filtered/)).toBeVisible();
|
||||
expect(state.listUrls.some((url) => new URL(url).searchParams.get("search") === "metro")).toBe(
|
||||
true,
|
||||
);
|
||||
|
|
@ -442,8 +514,8 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
await page.getByRole("option", { name: /Gateway Plumbing/ }).click();
|
||||
await page.getByRole("button", { name: "Apply filters" }).click();
|
||||
await expect(page.getByText("Gateway Plumbing").first()).toBeVisible();
|
||||
await expect(page.getByText("1 technician · filtered by")).toBeVisible();
|
||||
await expect(page.getByText(/1 active technician · filtered/)).toBeVisible();
|
||||
await expect(page.getByText("1 company · filtered by")).toBeVisible();
|
||||
await expect(page.getByText(/1 active company · filtered/)).toBeVisible();
|
||||
expect(
|
||||
state.listUrls.some(
|
||||
(url) => new URL(url).searchParams.get("companies[0]") === "Gateway Plumbing",
|
||||
|
|
@ -451,7 +523,7 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
).toBe(true);
|
||||
|
||||
await page.getByRole("tab", { name: "Inactive (1)" }).click();
|
||||
await expect(page.getByText("No inactive technicians found")).toBeVisible();
|
||||
await expect(page.getByText("No inactive companies found")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Clear all" }).click();
|
||||
await expect(page.getByText("Drain Cleaning Bros")).toBeVisible();
|
||||
await expect(page.getByRole("columnheader", { name: "Status" })).toBeVisible();
|
||||
|
|
@ -466,10 +538,10 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
const row = page.locator("tbody tr").first();
|
||||
const fields = [
|
||||
{ cellIndex: 0, testId: "vendor-text-company", value: LONG_TEXT_VENDOR.CompanyName },
|
||||
{ cellIndex: 1, testId: "vendor-text-technician", value: LONG_TEXT_VENDOR.ContactName },
|
||||
{ cellIndex: 2, testId: "vendor-text-location", value: LONG_TEXT_VENDOR.Address },
|
||||
{ cellIndex: 4, testId: "vendor-text-phone", value: LONG_TEXT_VENDOR.Phone },
|
||||
{ cellIndex: 5, testId: "vendor-text-email", value: LONG_TEXT_VENDOR.Email },
|
||||
{ cellIndex: 2, testId: "vendor-text-company-email", value: LONG_TEXT_VENDOR.Email },
|
||||
{ cellIndex: 3, testId: "vendor-text-street-address", value: LONG_TEXT_VENDOR.Address },
|
||||
{ cellIndex: 7, testId: "vendor-text-technician", value: LONG_TEXT_VENDOR.ContactName },
|
||||
{ cellIndex: 8, testId: "vendor-text-technician-phone", value: LONG_TEXT_VENDOR.Phone },
|
||||
];
|
||||
|
||||
for (const expected of fields) {
|
||||
|
|
|
|||
8
e2e/vendors/vendors.visual.spec.ts
vendored
|
|
@ -119,7 +119,7 @@ async function mockVendorApi(page: Page, mode: "default" | "empty" | "error" = "
|
|||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.endsWith("/api/Vendor/GetVendorList")) {
|
||||
if (url.pathname.endsWith("/api/Vendor/GetVendorDirectoryList")) {
|
||||
const isCount = url.searchParams.get("pageSize") === "1";
|
||||
if (mode === "error" && !isCount) {
|
||||
await fulfillJson(route, { message: "Vendor directory unavailable" }, 500);
|
||||
|
|
@ -243,8 +243,12 @@ test.describe("Vendor deterministic pixel regression", () => {
|
|||
|
||||
test("empty", async ({ page }) => {
|
||||
await openVendorPage(page, "empty");
|
||||
await expect(page.getByText("No active technicians found")).toBeVisible();
|
||||
const emptyState = page.getByText("No active companies found");
|
||||
await expect(emptyState).toBeVisible();
|
||||
await expectStableScreenshot(page, "vendor-empty.png");
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expect(emptyState).toBeInViewport();
|
||||
});
|
||||
|
||||
test("error", async ({ page }) => {
|
||||
|
|
|
|||
|
|
@ -125,6 +125,7 @@ export const API_PATHS = {
|
|||
},
|
||||
vendor: {
|
||||
getList: "Vendor/GetVendorList",
|
||||
getDirectoryList: "Vendor/GetVendorDirectoryList",
|
||||
getById: "Vendor/GetById",
|
||||
create: "Vendor/Create",
|
||||
update: "Vendor/Update",
|
||||
|
|
|
|||
|
|
@ -0,0 +1,237 @@
|
|||
import { useCallback, useRef, useState, type KeyboardEvent } from "react";
|
||||
import {
|
||||
useFieldArray,
|
||||
type Control,
|
||||
type FieldErrors,
|
||||
type UseFormRegister,
|
||||
} from "react-hook-form";
|
||||
import AddIcon from "@mui/icons-material/Add";
|
||||
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutlined";
|
||||
import DragIndicatorIcon from "@mui/icons-material/DragIndicator";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Chip,
|
||||
IconButton,
|
||||
Paper,
|
||||
Stack,
|
||||
TextField,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import type {
|
||||
LocationContactFormValues,
|
||||
LocationFormValues,
|
||||
} from "@/domain/locations/schemas/location-schema";
|
||||
|
||||
interface ContactRowProps {
|
||||
canRemove: boolean;
|
||||
dragIndex: number | null;
|
||||
errors: FieldErrors<LocationContactFormValues>;
|
||||
fieldId: string;
|
||||
index: number;
|
||||
isLast: boolean;
|
||||
register: UseFormRegister<LocationFormValues>;
|
||||
onDragEnd: () => void;
|
||||
onDragStart: (index: number) => void;
|
||||
onDrop: (index: number) => void;
|
||||
onRemove: (index: number) => void;
|
||||
onKeyboardMove: (from: number, to: number) => void;
|
||||
}
|
||||
|
||||
function ContactRow({
|
||||
canRemove,
|
||||
dragIndex,
|
||||
errors,
|
||||
fieldId,
|
||||
index,
|
||||
isLast,
|
||||
register,
|
||||
onDragEnd,
|
||||
onDragStart,
|
||||
onDrop,
|
||||
onRemove,
|
||||
onKeyboardMove,
|
||||
}: ContactRowProps) {
|
||||
const handleRef = useRef<HTMLSpanElement | null>(null);
|
||||
const isDragging = dragIndex === index;
|
||||
const isDropTarget = dragIndex !== null && dragIndex !== index;
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent<HTMLSpanElement>) => {
|
||||
if (event.key === "ArrowUp" && index > 0) {
|
||||
event.preventDefault();
|
||||
onKeyboardMove(index, index - 1);
|
||||
}
|
||||
if (event.key === "ArrowDown" && !isLast) {
|
||||
event.preventDefault();
|
||||
onKeyboardMove(index, index + 1);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Paper
|
||||
variant="outlined"
|
||||
component="div"
|
||||
onDragOver={(event) => {
|
||||
if (dragIndex !== null) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
onDrop(index);
|
||||
}}
|
||||
className="transition-opacity"
|
||||
sx={{ opacity: isDragging ? 0.5 : 1, borderStyle: isDropTarget ? "dashed" : "solid" }}
|
||||
>
|
||||
<Stack
|
||||
direction={{ xs: "column", sm: "row" }}
|
||||
spacing={1.5}
|
||||
sx={{ alignItems: "center", p: 1.5 }}
|
||||
>
|
||||
<Tooltip title="Drag to reorder. Use arrow keys to move up or down.">
|
||||
<Box
|
||||
component="span"
|
||||
ref={handleRef}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={`Reorder contact ${index + 1}. Use arrow up or down to move.`}
|
||||
draggable
|
||||
data-field-id={fieldId}
|
||||
onDragStart={(event) => {
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
event.dataTransfer.setData("text/plain", String(index));
|
||||
onDragStart(index);
|
||||
}}
|
||||
onDragEnd={onDragEnd}
|
||||
onKeyDown={handleKeyDown}
|
||||
sx={{ cursor: "grab", display: "inline-flex", color: "text.secondary" }}
|
||||
>
|
||||
<DragIndicatorIcon fontSize="small" />
|
||||
</Box>
|
||||
</Tooltip>
|
||||
{index === 0 && <Chip label="Main" size="small" color="primary" variant="outlined" />}
|
||||
<TextField
|
||||
{...register(`contacts.${index}.name` as const)}
|
||||
label={index === 0 ? "Contact Name (Main)" : "Contact Name"}
|
||||
required
|
||||
error={Boolean(errors?.name)}
|
||||
helperText={errors?.name?.message}
|
||||
fullWidth
|
||||
size="small"
|
||||
slotProps={{ htmlInput: { maxLength: 100 } }}
|
||||
/>
|
||||
<TextField
|
||||
{...register(`contacts.${index}.phone` as const)}
|
||||
label="Phone"
|
||||
required
|
||||
error={Boolean(errors?.phone)}
|
||||
helperText={errors?.phone?.message}
|
||||
fullWidth
|
||||
size="small"
|
||||
slotProps={{ htmlInput: { maxLength: 20 } }}
|
||||
/>
|
||||
<Tooltip title={canRemove ? "Remove" : "At least one contact is required"}>
|
||||
<span>
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label={`Remove contact ${index + 1}`}
|
||||
disabled={!canRemove}
|
||||
onClick={() => onRemove(index)}
|
||||
>
|
||||
<DeleteOutlineIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
interface LocationContactsFieldArrayProps {
|
||||
control: Control<LocationFormValues>;
|
||||
errors: FieldErrors<LocationFormValues>;
|
||||
register: UseFormRegister<LocationFormValues>;
|
||||
}
|
||||
|
||||
export function LocationContactsFieldArray({
|
||||
control,
|
||||
errors,
|
||||
register,
|
||||
}: LocationContactsFieldArrayProps) {
|
||||
const { fields, append, remove, move } = useFieldArray({
|
||||
control,
|
||||
name: "contacts",
|
||||
keyName: "fieldKey",
|
||||
});
|
||||
const [dragIndex, setDragIndex] = useState<number | null>(null);
|
||||
const rootRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const focusHandle = useCallback((fieldId: string) => {
|
||||
requestAnimationFrame(() => {
|
||||
const handle = rootRef.current?.querySelector<HTMLElement>(`[data-field-id="${fieldId}"]`);
|
||||
handle?.focus();
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleKeyboardMove = useCallback(
|
||||
(from: number, to: number) => {
|
||||
if (to < 0 || to >= fields.length) {
|
||||
return;
|
||||
}
|
||||
const fieldId = fields[from]?.fieldKey;
|
||||
move(from, to);
|
||||
if (fieldId) {
|
||||
focusHandle(fieldId);
|
||||
}
|
||||
},
|
||||
[fields, move, focusHandle],
|
||||
);
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(index: number) => {
|
||||
if (dragIndex !== null && dragIndex !== index) {
|
||||
move(dragIndex, index);
|
||||
}
|
||||
setDragIndex(null);
|
||||
},
|
||||
[dragIndex, move],
|
||||
);
|
||||
|
||||
return (
|
||||
<Box ref={rootRef}>
|
||||
<Stack direction="row" sx={{ alignItems: "center", justifyContent: "space-between" }}>
|
||||
<Typography variant="subtitle2" className="font-semibold uppercase">
|
||||
Contacts
|
||||
</Typography>
|
||||
<Button
|
||||
size="small"
|
||||
variant="text"
|
||||
startIcon={<AddIcon fontSize="small" />}
|
||||
onClick={() => append({ name: "", phone: "" })}
|
||||
>
|
||||
Add Contact
|
||||
</Button>
|
||||
</Stack>
|
||||
<Stack spacing={1.5} className="mt-2">
|
||||
{fields.map((field, index) => (
|
||||
<ContactRow
|
||||
key={field.fieldKey}
|
||||
canRemove={fields.length > 1}
|
||||
dragIndex={dragIndex}
|
||||
errors={errors.contacts?.[index] ?? {}}
|
||||
fieldId={field.fieldKey}
|
||||
index={index}
|
||||
isLast={index === fields.length - 1}
|
||||
register={register}
|
||||
onDragEnd={() => setDragIndex(null)}
|
||||
onDragStart={setDragIndex}
|
||||
onDrop={handleDrop}
|
||||
onRemove={remove}
|
||||
onKeyboardMove={handleKeyboardMove}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
|
@ -12,6 +12,7 @@ import {
|
|||
import type { AccountListItem } from "@/domain/accounts/types/account";
|
||||
import type { LocationFormValues } from "@/domain/locations/schemas/location-schema";
|
||||
import { LOCATION_STATUS_OPTIONS } from "@/domain/locations/types/location";
|
||||
import { LocationContactsFieldArray } from "./location-contacts-field-array";
|
||||
import { StateSelect } from "./state-select";
|
||||
|
||||
interface SharedFieldsProps {
|
||||
|
|
@ -109,24 +110,7 @@ export function LocationContactFields({ control, errors, register }: SharedField
|
|||
<Typography variant="subtitle1" className="font-semibold">
|
||||
Contact Information
|
||||
</Typography>
|
||||
<Stack direction={{ xs: "column", md: "row" }} spacing={2}>
|
||||
<TextField
|
||||
{...register("phone")}
|
||||
label="Phone"
|
||||
required
|
||||
error={Boolean(errors.phone)}
|
||||
helperText={errors.phone?.message}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
{...register("contact")}
|
||||
label="Contact Person"
|
||||
required
|
||||
error={Boolean(errors.contact)}
|
||||
helperText={errors.contact?.message}
|
||||
fullWidth
|
||||
/>
|
||||
</Stack>
|
||||
<LocationContactsFieldArray control={control} errors={errors} register={register} />
|
||||
<Stack direction={{ xs: "column", md: "row" }} spacing={2}>
|
||||
<TextField
|
||||
{...register("contactEmail")}
|
||||
|
|
|
|||
|
|
@ -55,8 +55,10 @@ export default function LocationFormPage() {
|
|||
city: location.city ?? "",
|
||||
state: normalizeStateCode(location.state) ?? "",
|
||||
zipCode: location.zipCode ?? "",
|
||||
phone: location.phone ?? "",
|
||||
contact: location.contact ?? "",
|
||||
contacts:
|
||||
location.contacts && location.contacts.length > 0
|
||||
? location.contacts
|
||||
: [{ name: location.contact ?? "", phone: location.phone ?? "" }],
|
||||
contactEmail: location.contactEmail ?? "",
|
||||
status: (location.status as LocationFormValues["status"]) || "Active",
|
||||
});
|
||||
|
|
|
|||
|
|
@ -0,0 +1,46 @@
|
|||
import { Chip, Stack, Tooltip, Typography } from "@mui/material";
|
||||
import type { LocationListItem } from "@/domain/locations/types/location";
|
||||
|
||||
/** Main contact name with a `+N` chip; hover/focus lists the remaining contact names. */
|
||||
export function LocationsContactsCell({ row }: { row: LocationListItem }) {
|
||||
const contacts = row.contacts ?? [];
|
||||
const mainName = row.contact || contacts[0]?.name || "";
|
||||
const remainingNames = contacts
|
||||
.slice(1)
|
||||
.map((contact) => contact.name.trim())
|
||||
.filter((name) => name !== "");
|
||||
|
||||
if (mainName === "") {
|
||||
return (
|
||||
<Typography variant="body2" component="span">
|
||||
—
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
|
||||
if (remainingNames.length === 0) {
|
||||
return (
|
||||
<Typography variant="body2" component="span">
|
||||
{mainName}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
|
||||
const remainingLabel = remainingNames.join(", ");
|
||||
|
||||
return (
|
||||
<Stack direction="row" spacing={0.5} sx={{ alignItems: "center" }}>
|
||||
<Typography variant="body2" component="span">
|
||||
{mainName}
|
||||
</Typography>
|
||||
<Tooltip title={remainingLabel}>
|
||||
<Chip
|
||||
label={`+${remainingNames.length}`}
|
||||
size="small"
|
||||
tabIndex={0}
|
||||
aria-label={`${remainingNames.length} more contacts: ${remainingLabel}`}
|
||||
/>
|
||||
</Tooltip>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
|
@ -15,6 +15,7 @@ import {
|
|||
Typography,
|
||||
} from "@mui/material";
|
||||
import type { LocationListItem } from "@/domain/locations/types/location";
|
||||
import { LocationsContactsCell } from "./locations-contacts-cell";
|
||||
import { StateAreaCell } from "./state-area-cell";
|
||||
|
||||
interface LocationsTableProps {
|
||||
|
|
@ -74,7 +75,9 @@ export function LocationsTable({ isLoading, onDelete, onEdit, rows }: LocationsT
|
|||
<StateAreaCell state={row.state} />
|
||||
</TableCell>
|
||||
<TableCell>{row.phone || "—"}</TableCell>
|
||||
<TableCell>{row.contact || "—"}</TableCell>
|
||||
<TableCell>
|
||||
<LocationsContactsCell row={row} />
|
||||
</TableCell>
|
||||
<TableCell>{row.status || "—"}</TableCell>
|
||||
<TableCell align="right">
|
||||
<Tooltip title="Edit">
|
||||
|
|
|
|||
339
src/app/(protected)/vendors/_components/vendor-table-row.tsx
vendored
Normal file
|
|
@ -0,0 +1,339 @@
|
|||
import { type KeyboardEvent, type MouseEvent, type ReactNode } from "react";
|
||||
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
|
||||
import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
|
||||
import { Avatar, Box, IconButton, Link, Stack, TableCell, TableRow, Tooltip } from "@mui/material";
|
||||
import { VendorStatusBadge } from "./vendor-status-badge";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import type { VendorDirectoryTechnician, VendorListItem } from "@/domain/vendors/types/vendor";
|
||||
|
||||
function stopPropagation(event: MouseEvent): void {
|
||||
event.stopPropagation();
|
||||
}
|
||||
function stopBadgeKeyDown(event: KeyboardEvent): void {
|
||||
if (event.key !== "Enter" && event.key !== " ") return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
const truncatedTextSx = {
|
||||
display: "block",
|
||||
minWidth: 0,
|
||||
maxWidth: "100%",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
};
|
||||
|
||||
function TruncatedText({
|
||||
value,
|
||||
testId,
|
||||
focusable = false,
|
||||
href,
|
||||
variant,
|
||||
}: {
|
||||
value: string;
|
||||
testId: string;
|
||||
focusable?: boolean;
|
||||
href?: string;
|
||||
variant?: "description";
|
||||
}) {
|
||||
const hasValue = value !== "—";
|
||||
const content = href ? (
|
||||
<Link
|
||||
href={href}
|
||||
underline="hover"
|
||||
color="inherit"
|
||||
data-testid={testId}
|
||||
sx={truncatedTextSx}
|
||||
onClick={stopPropagation}
|
||||
>
|
||||
{value}
|
||||
</Link>
|
||||
) : variant ? (
|
||||
<Text variant={variant} data-testid={testId} sx={{ ...truncatedTextSx, flex: "1 1 auto" }}>
|
||||
{value}
|
||||
</Text>
|
||||
) : (
|
||||
<Box
|
||||
component="span"
|
||||
data-testid={testId}
|
||||
tabIndex={focusable && hasValue ? 0 : undefined}
|
||||
sx={truncatedTextSx}
|
||||
>
|
||||
{value}
|
||||
</Box>
|
||||
);
|
||||
return (
|
||||
<Tooltip title={hasValue ? value : ""} placement="top" arrow describeChild>
|
||||
{content}
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function OverflowBadge({
|
||||
count,
|
||||
label,
|
||||
kind,
|
||||
}: {
|
||||
count: number;
|
||||
label: string;
|
||||
kind: "trade" | "technician";
|
||||
}) {
|
||||
const noun = count === 1 ? kind : `${kind}s`;
|
||||
const ariaLabel = `+${count} more ${noun}${kind === "trade" ? `: ${label}` : ""}`;
|
||||
return (
|
||||
<Tooltip title={label} placement="top" arrow>
|
||||
<Box
|
||||
component="span"
|
||||
tabIndex={0}
|
||||
aria-label={ariaLabel}
|
||||
data-testid={`vendor-${kind}-badge`}
|
||||
className="focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-[var(--color-primary)]"
|
||||
onClick={stopPropagation}
|
||||
onKeyDown={stopBadgeKeyDown}
|
||||
sx={{
|
||||
flexShrink: 0,
|
||||
borderRadius: "9999px",
|
||||
backgroundColor: "var(--color-bg-muted)",
|
||||
px: 0.75,
|
||||
py: 0.25,
|
||||
fontSize: 10.5,
|
||||
lineHeight: 1.2,
|
||||
}}
|
||||
>
|
||||
+{count}
|
||||
</Box>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function CellText({
|
||||
value,
|
||||
testId,
|
||||
href,
|
||||
focusable,
|
||||
}: {
|
||||
value: string;
|
||||
testId: string;
|
||||
href?: string;
|
||||
focusable?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<TableCell sx={{ color: "var(--color-muted-foreground)", overflow: "hidden" }}>
|
||||
<TruncatedText
|
||||
value={value.trim() || "—"}
|
||||
testId={testId}
|
||||
href={href}
|
||||
focusable={focusable}
|
||||
/>
|
||||
</TableCell>
|
||||
);
|
||||
}
|
||||
|
||||
function CompanyCells({ row }: { row: VendorListItem }) {
|
||||
const phone = row.companyPhone.trim();
|
||||
const email = row.email.trim();
|
||||
return (
|
||||
<>
|
||||
<TableCell sx={{ overflow: "hidden" }}>
|
||||
<TruncatedText
|
||||
value={row.companyName || "—"}
|
||||
testId="vendor-text-company"
|
||||
variant="description"
|
||||
/>
|
||||
</TableCell>
|
||||
<CellText
|
||||
value={phone}
|
||||
testId="vendor-text-company-phone"
|
||||
href={phone ? `tel:${phone}` : undefined}
|
||||
/>
|
||||
<CellText
|
||||
value={email}
|
||||
testId="vendor-text-company-email"
|
||||
href={email ? `mailto:${email}` : undefined}
|
||||
/>
|
||||
<CellText value={row.address} testId="vendor-text-street-address" focusable />
|
||||
<CellText value={row.city} testId="vendor-text-city" focusable />
|
||||
<CellText value={row.state} testId="vendor-text-state" focusable />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function orderedTechnicians(row: VendorListItem): VendorDirectoryTechnician[] {
|
||||
const technicians = row.technicians ?? [];
|
||||
const primaryIndex =
|
||||
row.id == null ? -1 : technicians.findIndex((item) => String(item.id) === String(row.id));
|
||||
if (primaryIndex <= 0) return technicians;
|
||||
return [technicians[primaryIndex]!, ...technicians.filter((_, index) => index !== primaryIndex)];
|
||||
}
|
||||
|
||||
function primaryTechnician(row: VendorListItem, technicians: VendorDirectoryTechnician[]) {
|
||||
return (
|
||||
technicians[0] ?? {
|
||||
id: row.id ?? "",
|
||||
contactName: row.contactName,
|
||||
email: "",
|
||||
phone: row.phone,
|
||||
preferredContact: row.preferredContact,
|
||||
tradeSpecialties: row.tradeSpecialties,
|
||||
isActive: row.isActive,
|
||||
totalJobs: row.totalJobs,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function TradeCell({ value }: { value: string }) {
|
||||
const trades = value
|
||||
.split(",")
|
||||
.map((trade) => trade.trim())
|
||||
.filter(Boolean);
|
||||
const omitted = trades.slice(1);
|
||||
return (
|
||||
<TableCell sx={{ color: "var(--color-muted-foreground)" }}>
|
||||
{trades.length === 0 ? (
|
||||
"—"
|
||||
) : (
|
||||
<Stack direction="row" spacing={0.5} sx={{ alignItems: "center" }}>
|
||||
<span>{trades[0]}</span>
|
||||
{omitted.length > 0 && (
|
||||
<OverflowBadge count={omitted.length} label={omitted.join(", ")} kind="trade" />
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
</TableCell>
|
||||
);
|
||||
}
|
||||
|
||||
function getInitials(name: string): string {
|
||||
const parts = name.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) return "?";
|
||||
return `${parts[0]?.[0] ?? ""}${parts.length > 1 ? (parts[parts.length - 1]?.[0] ?? "") : ""}`.toUpperCase();
|
||||
}
|
||||
|
||||
function TechnicianCells({ row }: { row: VendorListItem }) {
|
||||
const technicians = orderedTechnicians(row);
|
||||
const primary = primaryTechnician(row, technicians);
|
||||
const omitted = technicians.slice(1);
|
||||
const phone = primary.phone.trim();
|
||||
return (
|
||||
<>
|
||||
<TableCell sx={{ overflow: "hidden" }}>
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={1.25}
|
||||
sx={{ alignItems: "center", minWidth: 0, overflow: "hidden" }}
|
||||
>
|
||||
<Avatar
|
||||
sx={{
|
||||
width: 28,
|
||||
height: 28,
|
||||
flexShrink: 0,
|
||||
backgroundColor: "var(--color-bg-muted)",
|
||||
color: "var(--color-primary)",
|
||||
fontSize: 10.5,
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
{getInitials(primary.contactName)}
|
||||
</Avatar>
|
||||
<TruncatedText
|
||||
value={primary.contactName || "—"}
|
||||
testId="vendor-text-technician"
|
||||
variant="description"
|
||||
/>
|
||||
{omitted.length > 0 && (
|
||||
<OverflowBadge
|
||||
count={omitted.length}
|
||||
label={omitted.map((item) => item.contactName || "Unnamed technician").join(", ")}
|
||||
kind="technician"
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
</TableCell>
|
||||
<CellText
|
||||
value={phone}
|
||||
testId="vendor-text-technician-phone"
|
||||
href={phone ? `tel:${phone}` : undefined}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function RowActions({
|
||||
row,
|
||||
onOpenDetail,
|
||||
onOpenEdit,
|
||||
}: {
|
||||
row: VendorListItem;
|
||||
onOpenDetail: () => void;
|
||||
onOpenEdit: () => void;
|
||||
}) {
|
||||
const action = (label: string, icon: ReactNode, handler: () => void) => (
|
||||
<Tooltip title={label}>
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label={`${label} vendor ${row.companyName}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
handler();
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
);
|
||||
return (
|
||||
<TableCell align="right">
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={0.5}
|
||||
className="vendor-row-actions"
|
||||
sx={{ alignItems: "center", justifyContent: "flex-end" }}
|
||||
>
|
||||
{action("View", <VisibilityOutlinedIcon fontSize="small" />, onOpenDetail)}
|
||||
{action("Edit", <EditOutlinedIcon fontSize="small" />, onOpenEdit)}
|
||||
</Stack>
|
||||
</TableCell>
|
||||
);
|
||||
}
|
||||
|
||||
export function VendorTableRow({
|
||||
row,
|
||||
onOpenDetail,
|
||||
onOpenEdit,
|
||||
}: {
|
||||
row: VendorListItem;
|
||||
onOpenDetail: (row: VendorListItem) => void;
|
||||
onOpenEdit: (row: VendorListItem) => void;
|
||||
}) {
|
||||
const openDetail = () => onOpenDetail(row);
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.target instanceof Element && event.target.closest("a, button")) return;
|
||||
if (event.key !== "Enter" && event.key !== " ") return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
openDetail();
|
||||
};
|
||||
return (
|
||||
<TableRow
|
||||
hover
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
aria-label={`Open vendor details for ${row.companyName}`}
|
||||
sx={{ cursor: "pointer" }}
|
||||
onClick={openDetail}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
<CompanyCells row={row} />
|
||||
<TradeCell value={row.tradeSpecialties} />
|
||||
<TechnicianCells row={row} />
|
||||
<TableCell align="center">{row.totalJobs ?? 0}</TableCell>
|
||||
<TableCell>
|
||||
<Box sx={{ pl: 1 }}>
|
||||
<VendorStatusBadge isActive={row.isActive} />
|
||||
</Box>
|
||||
</TableCell>
|
||||
<RowActions row={row} onOpenDetail={openDetail} onOpenEdit={() => onOpenEdit(row)} />
|
||||
</TableRow>
|
||||
);
|
||||
}
|
||||
|
|
@ -6,7 +6,6 @@ import { Text } from "@/components/ui/text";
|
|||
import { ToolbarButton } from "@/components/ui/toolbar-button";
|
||||
|
||||
interface VendorsListToolbarProps {
|
||||
globalCount: number;
|
||||
activeCount: number;
|
||||
isFetching: boolean;
|
||||
isLoading: boolean;
|
||||
|
|
@ -18,7 +17,6 @@ interface VendorsListToolbarProps {
|
|||
}
|
||||
|
||||
export function VendorsListToolbar({
|
||||
globalCount,
|
||||
activeCount,
|
||||
isFetching,
|
||||
isLoading,
|
||||
|
|
@ -33,7 +31,7 @@ export function VendorsListToolbar({
|
|||
surface
|
||||
className="-mx-4 -mt-4"
|
||||
title="Vendors / Technicians"
|
||||
subtitle={`${globalCount} technicians · ${activeCount} active`}
|
||||
subtitle={`${activeCount} active ${activeCount === 1 ? "company" : "companies"}`}
|
||||
actions={
|
||||
<>
|
||||
<SearchInput
|
||||
|
|
@ -93,7 +91,7 @@ export function VendorAppliedFiltersBar({
|
|||
return (
|
||||
<Stack direction="row" spacing={1} className="flex flex-wrap items-center">
|
||||
<Text variant="caption" tone="muted">
|
||||
{resultCount} {resultCount === 1 ? "technician" : "technicians"} · filtered by
|
||||
{resultCount} {resultCount === 1 ? "company" : "companies"} · filtered by
|
||||
</Text>
|
||||
{chips.map((chip) => (
|
||||
<Chip
|
||||
|
|
@ -148,8 +146,7 @@ export function VendorsListFooter({
|
|||
}}
|
||||
>
|
||||
<Text variant="caption" as="span" sx={{ color: "#6b7a96", fontSize: 11, lineHeight: 1.5 }}>
|
||||
{totalCount} {isActive ? "active" : "inactive"}{" "}
|
||||
{totalCount === 1 ? "technician" : "technicians"}
|
||||
{totalCount} {isActive ? "active" : "inactive"} {totalCount === 1 ? "company" : "companies"}
|
||||
{isFiltered && " · filtered"}
|
||||
</Text>
|
||||
<Text variant="caption" as="span" sx={{ color: "#6b7a96", fontSize: 11, lineHeight: 1.5 }}>
|
||||
|
|
|
|||
|
|
@ -1,13 +1,6 @@
|
|||
import { type KeyboardEvent, type MouseEvent } from "react";
|
||||
import SearchOffOutlinedIcon from "@mui/icons-material/SearchOffOutlined";
|
||||
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
|
||||
import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
|
||||
import {
|
||||
Avatar,
|
||||
Box,
|
||||
CircularProgress,
|
||||
IconButton,
|
||||
Link,
|
||||
Paper,
|
||||
Stack,
|
||||
Table,
|
||||
|
|
@ -16,297 +9,24 @@ import {
|
|||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Tooltip,
|
||||
} from "@mui/material";
|
||||
import { VendorStatusBadge } from "./vendor-status-badge";
|
||||
import { VendorTableRow } from "./vendor-table-row";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import type { VendorListItem } from "@/domain/vendors/types/vendor";
|
||||
|
||||
const TABLE_COLUMNS = [
|
||||
"Company",
|
||||
"Technician",
|
||||
"Location",
|
||||
"Company Phone",
|
||||
"Company Email",
|
||||
"Street Address",
|
||||
"City",
|
||||
"State",
|
||||
"Trade",
|
||||
"Phone",
|
||||
"Email",
|
||||
"Technician",
|
||||
"Technician Phone",
|
||||
"Total Jobs",
|
||||
] as const;
|
||||
|
||||
function getInitials(name: string): string {
|
||||
const parts = name.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) return "?";
|
||||
const first = parts[0]?.[0] ?? "";
|
||||
const last = parts.length > 1 ? (parts[parts.length - 1]?.[0] ?? "") : "";
|
||||
return (first + last).toUpperCase();
|
||||
}
|
||||
|
||||
function splitTrades(value: string | undefined): string[] {
|
||||
return (value ?? "")
|
||||
.split(",")
|
||||
.map((trade) => trade.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function stopPropagation(event: MouseEvent): void {
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
function stopTradeBadgeKeyDown(event: KeyboardEvent): void {
|
||||
if (event.key !== "Enter" && event.key !== " ") return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
interface TruncatedTextProps {
|
||||
value: string;
|
||||
testId: string;
|
||||
focusable?: boolean;
|
||||
href?: string;
|
||||
color?: string;
|
||||
variant?: "description";
|
||||
}
|
||||
|
||||
const truncatedTextSx = {
|
||||
display: "block",
|
||||
minWidth: 0,
|
||||
maxWidth: "100%",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
};
|
||||
|
||||
function TruncatedText({
|
||||
value,
|
||||
testId,
|
||||
focusable = false,
|
||||
href,
|
||||
color = "inherit",
|
||||
variant,
|
||||
}: TruncatedTextProps) {
|
||||
const hasValue = value !== "—";
|
||||
const content = href ? (
|
||||
<Link
|
||||
href={href}
|
||||
underline="hover"
|
||||
color="inherit"
|
||||
data-testid={testId}
|
||||
sx={{ ...truncatedTextSx, color }}
|
||||
onClick={stopPropagation}
|
||||
>
|
||||
{value}
|
||||
</Link>
|
||||
) : variant ? (
|
||||
<Text
|
||||
variant={variant}
|
||||
data-testid={testId}
|
||||
sx={{ ...truncatedTextSx, color, flex: "1 1 auto" }}
|
||||
>
|
||||
{value}
|
||||
</Text>
|
||||
) : (
|
||||
<Box
|
||||
component="span"
|
||||
data-testid={testId}
|
||||
tabIndex={focusable && hasValue ? 0 : undefined}
|
||||
sx={{ ...truncatedTextSx, color }}
|
||||
>
|
||||
{value}
|
||||
</Box>
|
||||
);
|
||||
|
||||
return (
|
||||
<Tooltip title={hasValue ? value : ""} placement="top" arrow describeChild>
|
||||
{content}
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function getVendorDisplayValues(row: VendorListItem) {
|
||||
const cityStateText = [row.city.trim(), row.state.trim()].filter(Boolean).join(", ");
|
||||
return {
|
||||
locationText: cityStateText || row.address.trim() || "—",
|
||||
phoneText: row.phone.trim() || row.companyPhone.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
interface VendorTableRowProps {
|
||||
row: VendorListItem;
|
||||
onOpenDetail: (row: VendorListItem) => void;
|
||||
onOpenEdit: (row: VendorListItem) => void;
|
||||
}
|
||||
|
||||
function VendorTradeCell({
|
||||
primaryTrade,
|
||||
omittedTrades,
|
||||
}: {
|
||||
primaryTrade: string;
|
||||
omittedTrades: string[];
|
||||
}) {
|
||||
const extraTrades = omittedTrades.length;
|
||||
return (
|
||||
<TableCell sx={{ color: "var(--color-muted-foreground)" }}>
|
||||
{primaryTrade === "—" ? (
|
||||
"—"
|
||||
) : (
|
||||
<Stack direction="row" spacing={0.5} sx={{ alignItems: "center" }}>
|
||||
<span>{primaryTrade}</span>
|
||||
{extraTrades > 0 && (
|
||||
<Tooltip title={omittedTrades.join(", ")} placement="top" arrow>
|
||||
<Box
|
||||
component="span"
|
||||
tabIndex={0}
|
||||
aria-label={`+${extraTrades} more ${extraTrades === 1 ? "trade" : "trades"}: ${omittedTrades.join(", ")}`}
|
||||
data-testid="vendor-trade-badge"
|
||||
className="focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-[var(--color-primary)]"
|
||||
onClick={stopPropagation}
|
||||
onKeyDown={stopTradeBadgeKeyDown}
|
||||
sx={{
|
||||
borderRadius: "9999px",
|
||||
backgroundColor: "var(--color-bg-muted)",
|
||||
px: 0.75,
|
||||
py: 0.25,
|
||||
fontSize: 10.5,
|
||||
lineHeight: 1.2,
|
||||
}}
|
||||
>
|
||||
+{extraTrades}
|
||||
</Box>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
</TableCell>
|
||||
);
|
||||
}
|
||||
|
||||
function VendorTableRow({ row, onOpenDetail, onOpenEdit }: VendorTableRowProps) {
|
||||
const trades = splitTrades(row.tradeSpecialties);
|
||||
const primaryTrade = trades[0] ?? "—";
|
||||
const omittedTrades = trades.slice(1);
|
||||
const { locationText, phoneText } = getVendorDisplayValues(row);
|
||||
const rowKey = String(row.id ?? `company-${row.companyId ?? ""}`);
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Enter" && event.key !== " ") return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onOpenDetail(row);
|
||||
};
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
key={rowKey}
|
||||
hover
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
aria-label={`Open vendor details for ${row.companyName}`}
|
||||
sx={{ cursor: "pointer" }}
|
||||
onClick={() => onOpenDetail(row)}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
<TableCell sx={{ overflow: "hidden" }}>
|
||||
<TruncatedText
|
||||
value={row.companyName || "—"}
|
||||
testId="vendor-text-company"
|
||||
variant="description"
|
||||
color="var(--color-foreground)"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell sx={{ overflow: "hidden" }}>
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={1.25}
|
||||
sx={{ alignItems: "center", minWidth: 0, overflow: "hidden" }}
|
||||
>
|
||||
<Avatar
|
||||
sx={{
|
||||
width: 28,
|
||||
height: 28,
|
||||
flexShrink: 0,
|
||||
backgroundColor: "var(--color-bg-muted)",
|
||||
color: "var(--color-primary)",
|
||||
fontSize: 10.5,
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
{getInitials(row.contactName)}
|
||||
</Avatar>
|
||||
<TruncatedText
|
||||
value={row.contactName || "—"}
|
||||
testId="vendor-text-technician"
|
||||
variant="description"
|
||||
color="var(--color-foreground)"
|
||||
/>
|
||||
</Stack>
|
||||
</TableCell>
|
||||
<TableCell sx={{ color: "var(--color-muted-foreground)", overflow: "hidden" }}>
|
||||
<TruncatedText
|
||||
value={locationText}
|
||||
testId="vendor-text-location"
|
||||
focusable
|
||||
color="var(--color-muted-foreground)"
|
||||
/>
|
||||
</TableCell>
|
||||
<VendorTradeCell primaryTrade={primaryTrade} omittedTrades={omittedTrades} />
|
||||
<TableCell sx={{ color: "var(--color-muted-foreground)", overflow: "hidden" }}>
|
||||
<TruncatedText
|
||||
value={phoneText || "—"}
|
||||
testId="vendor-text-phone"
|
||||
href={phoneText ? `tel:${phoneText}` : undefined}
|
||||
color="var(--color-muted-foreground)"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell sx={{ overflow: "hidden" }}>
|
||||
<TruncatedText
|
||||
value={row.email || "—"}
|
||||
testId="vendor-text-email"
|
||||
href={row.email ? `mailto:${row.email}` : undefined}
|
||||
color="#6b7a96"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell align="center">{row.totalJobs ?? 0}</TableCell>
|
||||
<TableCell>
|
||||
<Box sx={{ pl: 1 }}>
|
||||
<VendorStatusBadge isActive={row.isActive} />
|
||||
</Box>
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={0.5}
|
||||
className="vendor-row-actions"
|
||||
sx={{ alignItems: "center", justifyContent: "flex-end" }}
|
||||
>
|
||||
<Tooltip title="View details">
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label={`View vendor ${row.companyName}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onOpenDetail(row);
|
||||
}}
|
||||
>
|
||||
<VisibilityOutlinedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Tooltip title="Edit">
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label={`Edit vendor ${row.companyName}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onOpenEdit(row);
|
||||
}}
|
||||
>
|
||||
<EditOutlinedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Stack>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}
|
||||
|
||||
interface VendorsTableProps {
|
||||
rows: VendorListItem[];
|
||||
isActive: boolean;
|
||||
|
|
@ -328,7 +48,6 @@ export function VendorsTable({
|
|||
}: VendorsTableProps) {
|
||||
const showEmptyRow = !isLoading && !showError && rows.length === 0;
|
||||
const columnCount = TABLE_COLUMNS.length + 2;
|
||||
|
||||
return (
|
||||
<TableContainer
|
||||
component={Paper}
|
||||
|
|
@ -340,13 +59,14 @@ export function VendorsTable({
|
|||
overflow: "auto",
|
||||
borderRadius: 1.5,
|
||||
fontSize: 13,
|
||||
containerType: "inline-size",
|
||||
}}
|
||||
>
|
||||
<Table
|
||||
size="small"
|
||||
stickyHeader
|
||||
sx={{
|
||||
minWidth: 1550,
|
||||
minWidth: 2050,
|
||||
tableLayout: "fixed",
|
||||
"& .MuiTableCell-head": {
|
||||
backgroundColor: "var(--color-bg-muted)",
|
||||
|
|
@ -368,26 +88,15 @@ export function VendorsTable({
|
|||
lineHeight: 1.43,
|
||||
whiteSpace: "nowrap",
|
||||
},
|
||||
"& .vendor-row-actions": {
|
||||
opacity: { xs: 1, md: 0 },
|
||||
transition: "opacity 120ms ease",
|
||||
},
|
||||
"& .vendor-row-actions": { opacity: { xs: 1, md: 0 }, transition: "opacity 120ms ease" },
|
||||
"& .MuiTableRow-root:hover .vendor-row-actions, & .MuiTableRow-root:focus-within .vendor-row-actions":
|
||||
{
|
||||
opacity: 1,
|
||||
},
|
||||
{ opacity: 1 },
|
||||
}}
|
||||
>
|
||||
<colgroup>
|
||||
<col style={{ width: 196.34375 }} />
|
||||
<col style={{ width: 207.25 }} />
|
||||
<col style={{ width: 152.703125 }} />
|
||||
<col style={{ width: 218.15625 }} />
|
||||
<col style={{ width: 152.703125 }} />
|
||||
<col style={{ width: 251.90625 }} />
|
||||
<col style={{ width: 109.078125 }} />
|
||||
<col style={{ width: 119.984375 }} />
|
||||
<col style={{ width: 141.875 }} />
|
||||
{[190, 160, 220, 220, 140, 100, 190, 220, 170, 110, 120, 130].map((width, index) => (
|
||||
<col key={`${width}-${index}`} style={{ width }} />
|
||||
))}
|
||||
</colgroup>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
|
|
@ -403,18 +112,21 @@ export function VendorsTable({
|
|||
<TableBody>
|
||||
{isLoading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={columnCount} align="center" className="py-10">
|
||||
<CircularProgress size={28} />
|
||||
<TableCell colSpan={columnCount} className="py-10">
|
||||
<Stack sx={{ width: "calc(100cqw - 24px)", alignItems: "center" }}>
|
||||
<CircularProgress size={28} />
|
||||
</Stack>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : showEmptyRow ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={columnCount} align="center" className="py-10">
|
||||
<Stack spacing={1} sx={{ alignItems: "center" }}>
|
||||
<TableCell colSpan={columnCount} className="py-10">
|
||||
<Stack spacing={1} sx={{ width: "calc(100cqw - 24px)", alignItems: "center" }}>
|
||||
<SearchOffOutlinedIcon sx={{ color: "text.secondary", fontSize: 32 }} />
|
||||
<Text variant="description" className="font-semibold">
|
||||
{`No ${isActive ? "active" : "inactive"} technicians found`}
|
||||
</Text>
|
||||
<Text
|
||||
variant="description"
|
||||
className="font-semibold"
|
||||
>{`No ${isActive ? "active" : "inactive"} companies found`}</Text>
|
||||
<Text variant="caption" tone="muted">
|
||||
{isFiltered
|
||||
? "Try a different search, or add a new vendor."
|
||||
|
|
|
|||
17
src/app/(protected)/vendors/index.tsx
vendored
|
|
@ -15,7 +15,7 @@ import { useVendorListState } from "./_components/use-vendor-list-state";
|
|||
import type { VendorFilters } from "./_components/vendor-filters";
|
||||
import type { VendorListItem } from "@/domain/vendors/types/vendor";
|
||||
import { useVendorFacets } from "@/domain/vendors/use-cases/use-vendor-facets";
|
||||
import { useVendorsList } from "@/domain/vendors/use-cases/use-vendors-list";
|
||||
import { useVendorDirectoryList } from "@/domain/vendors/use-cases/use-vendor-directory-list";
|
||||
|
||||
interface AppliedChip {
|
||||
category: keyof VendorFilters;
|
||||
|
|
@ -125,9 +125,17 @@ export default function VendorsListPage() {
|
|||
const deactivation = useVendorDeactivation(closeDetail);
|
||||
|
||||
const { data: facets } = useVendorFacets(filters.isActive);
|
||||
const { data, isLoading, isFetching, error } = useVendorsList(filters.listParams);
|
||||
const { data: activeCountData } = useVendorsList({ isActive: true, page: 1, pageSize: 1 });
|
||||
const { data: inactiveCountData } = useVendorsList({ isActive: false, page: 1, pageSize: 1 });
|
||||
const { data, isLoading, isFetching, error } = useVendorDirectoryList(filters.listParams);
|
||||
const { data: activeCountData } = useVendorDirectoryList({
|
||||
isActive: true,
|
||||
page: 1,
|
||||
pageSize: 1,
|
||||
});
|
||||
const { data: inactiveCountData } = useVendorDirectoryList({
|
||||
isActive: false,
|
||||
page: 1,
|
||||
pageSize: 1,
|
||||
});
|
||||
|
||||
const rows = data?.items ?? [];
|
||||
const totalCount = data?.totalCount ?? 0;
|
||||
|
|
@ -143,7 +151,6 @@ export default function VendorsListPage() {
|
|||
return (
|
||||
<Box className="flex h-full flex-col overflow-hidden px-4 pt-4 pb-0">
|
||||
<VendorsListToolbar
|
||||
globalCount={activeCount + inactiveCount}
|
||||
activeCount={activeCount}
|
||||
isFetching={isFetching}
|
||||
isLoading={isLoading}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
import type { Location, LocationListItem, LocationSite } from "@/domain/locations/types/location";
|
||||
import type {
|
||||
Location,
|
||||
LocationContact,
|
||||
LocationListItem,
|
||||
LocationSite,
|
||||
} from "@/domain/locations/types/location";
|
||||
|
||||
function readString(record: Record<string, unknown>, ...keys: string[]): string {
|
||||
for (const key of keys) {
|
||||
|
|
@ -90,9 +95,31 @@ export function mapLocationSites(rawItems: unknown[]): LocationSite[] {
|
|||
return rawItems.map(mapLocationSite);
|
||||
}
|
||||
|
||||
/** Reads the additive contacts array; returns [] when absent or malformed. */
|
||||
export function mapLocationContacts(raw: unknown): LocationContact[] {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [];
|
||||
}
|
||||
return raw.map((entry) => {
|
||||
const item = (typeof entry === "object" && entry !== null ? entry : {}) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
const id = item.id ?? item.Id;
|
||||
return {
|
||||
...(typeof id === "number" && Number.isInteger(id) && id > 0 ? { id } : {}),
|
||||
name: readString(item, "name", "Name", "contact", "Contact"),
|
||||
phone: readString(item, "phone", "Phone"),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function mapLocationListItem(raw: unknown): LocationListItem {
|
||||
const item = (typeof raw === "object" && raw !== null ? raw : {}) as Record<string, unknown>;
|
||||
|
||||
const contacts = mapLocationContacts(item.contacts ?? item.Contacts);
|
||||
const mainContact = contacts[0];
|
||||
|
||||
return {
|
||||
id: readId(item),
|
||||
name: readString(item, "name", "Name"),
|
||||
|
|
@ -100,11 +127,14 @@ export function mapLocationListItem(raw: unknown): LocationListItem {
|
|||
city: readString(item, "city", "City"),
|
||||
state: readString(item, "state", "State"),
|
||||
zipCode: readString(item, "zipCode", "ZipCode", "Zip"),
|
||||
phone: readString(item, "phone", "Phone"),
|
||||
contact: readString(item, "contact", "Contact", "contactPerson", "ContactPerson"),
|
||||
phone: mainContact ? mainContact.phone : readString(item, "phone", "Phone"),
|
||||
contact: mainContact
|
||||
? mainContact.name
|
||||
: readString(item, "contact", "Contact", "contactPerson", "ContactPerson"),
|
||||
contactEmail: readString(item, "contactEmail", "ContactEmail"),
|
||||
status: readString(item, "status", "Status"),
|
||||
accountId: readOptionalId(item),
|
||||
contacts: contacts.length > 0 ? contacts : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -122,6 +152,12 @@ export function mapLocation(raw: unknown): Location {
|
|||
.join(", ") ||
|
||||
undefined;
|
||||
|
||||
const contacts = mapLocationContacts(item.contacts ?? item.Contacts);
|
||||
const mainContact = contacts[0];
|
||||
const legacyPhone = readString(item, "phone", "Phone") || undefined;
|
||||
const legacyContact =
|
||||
readString(item, "contact", "Contact", "contactPerson", "ContactPerson") || undefined;
|
||||
|
||||
return {
|
||||
id: readId(item) || undefined,
|
||||
name: readString(item, "name", "Name") || undefined,
|
||||
|
|
@ -129,31 +165,58 @@ export function mapLocation(raw: unknown): Location {
|
|||
city: readString(item, "city", "City") || undefined,
|
||||
state: readString(item, "state", "State") || undefined,
|
||||
zipCode: readString(item, "zipCode", "ZipCode", "Zip") || undefined,
|
||||
phone: readString(item, "phone", "Phone") || undefined,
|
||||
contact: readString(item, "contact", "Contact") || undefined,
|
||||
phone: mainContact ? mainContact.phone : legacyPhone,
|
||||
contact: mainContact ? mainContact.name : legacyContact,
|
||||
contactEmail: readString(item, "contactEmail", "ContactEmail") || undefined,
|
||||
status: readString(item, "status", "Status") || undefined,
|
||||
accountId: readOptionalId(item) || undefined,
|
||||
contacts: contacts.length > 0 ? contacts : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/** Request payload contacts: trimmed, in displayed order. */
|
||||
export function mapContactsToBackend(raw: unknown): LocationContact[] {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [];
|
||||
}
|
||||
return raw
|
||||
.map((entry) => {
|
||||
const item = (typeof entry === "object" && entry !== null ? entry : {}) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
return {
|
||||
...(typeof item.id === "number" && Number.isInteger(item.id) && item.id > 0
|
||||
? { id: item.id }
|
||||
: {}),
|
||||
name: readString(item, "name", "Name", "contact", "Contact").trim(),
|
||||
phone: readString(item, "phone", "Phone").trim(),
|
||||
};
|
||||
})
|
||||
.filter((contact) => contact.name !== "" || contact.phone !== "");
|
||||
}
|
||||
|
||||
export function mapLocationToBackend(location: unknown): Record<string, unknown> {
|
||||
const item = (typeof location === "object" && location !== null ? location : {}) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
|
||||
const contacts = mapContactsToBackend(item.contacts ?? item.Contacts);
|
||||
const mainContact = contacts[0];
|
||||
|
||||
const payload: Record<string, unknown> = {
|
||||
name: item.name ?? "",
|
||||
address: item.address ?? "",
|
||||
city: item.city ?? "",
|
||||
state: item.state ?? "",
|
||||
zipCode: item.zipCode ?? "",
|
||||
phone: item.phone ?? "",
|
||||
contact: item.contact ?? "",
|
||||
phone: mainContact ? mainContact.phone : (item.phone ?? ""),
|
||||
contact: mainContact ? mainContact.name : (item.contact ?? ""),
|
||||
contactEmail: item.contactEmail ?? "",
|
||||
status: item.status ?? "Active",
|
||||
accountId: item.accountId ?? "",
|
||||
contacts,
|
||||
};
|
||||
|
||||
const id = item.id ?? item.Id;
|
||||
|
|
|
|||
|
|
@ -2,6 +2,16 @@ import { z } from "zod";
|
|||
import { US_STATE_CODES } from "@/data/areas";
|
||||
import { LOCATION_STATUS_OPTIONS } from "@/domain/locations/types/location";
|
||||
|
||||
export const locationContactSchema = z.object({
|
||||
id: z.number().int().positive().optional(),
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, "Contact person is required")
|
||||
.max(100, "Contact person cannot exceed 100 characters"),
|
||||
phone: z.string().trim().min(1, "Phone is required").max(20, "Phone cannot exceed 20 characters"),
|
||||
});
|
||||
|
||||
export const locationSchema = z.object({
|
||||
name: z.string().min(1, "Name is required"),
|
||||
accountId: z.string().optional(),
|
||||
|
|
@ -11,13 +21,13 @@ export const locationSchema = z.object({
|
|||
.union([z.enum(US_STATE_CODES), z.literal("")])
|
||||
.refine((state): boolean => state !== "", { message: "State is required" }),
|
||||
zipCode: z.string().min(1, "Zip code is required"),
|
||||
phone: z.string().min(1, "Phone is required"),
|
||||
contact: z.string().min(1, "Contact person is required"),
|
||||
contacts: z.array(locationContactSchema).min(1, "At least one contact is required"),
|
||||
contactEmail: z.string().min(1, "Contact email is required").email("Invalid email address"),
|
||||
status: z.enum(LOCATION_STATUS_OPTIONS, { message: "Status is required" }),
|
||||
});
|
||||
|
||||
export type LocationFormValues = z.infer<typeof locationSchema>;
|
||||
export type LocationContactFormValues = z.infer<typeof locationContactSchema>;
|
||||
|
||||
export const locationDefaultValues: LocationFormValues = {
|
||||
name: "",
|
||||
|
|
@ -26,8 +36,7 @@ export const locationDefaultValues: LocationFormValues = {
|
|||
city: "",
|
||||
state: "",
|
||||
zipCode: "",
|
||||
phone: "",
|
||||
contact: "",
|
||||
contacts: [{ name: "", phone: "" }],
|
||||
contactEmail: "",
|
||||
status: "Active",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,12 @@
|
|||
import type { StateCode } from "@/data/areas";
|
||||
|
||||
/** Site contact row; the first entry in `contacts` is the Main contact. */
|
||||
export interface LocationContact {
|
||||
id?: number;
|
||||
name: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
export interface LocationListItem {
|
||||
id: string | number;
|
||||
name: string;
|
||||
|
|
@ -12,6 +19,8 @@ export interface LocationListItem {
|
|||
contactEmail: string;
|
||||
status: string;
|
||||
accountId: string | number;
|
||||
/** Additive contacts payload; `contact`/`phone` mirror the first entry. */
|
||||
contacts?: LocationContact[];
|
||||
}
|
||||
|
||||
export interface Location {
|
||||
|
|
@ -26,6 +35,8 @@ export interface Location {
|
|||
contactEmail?: string;
|
||||
status?: string;
|
||||
accountId?: string | number;
|
||||
/** Additive contacts payload; the first entry is the Main contact. */
|
||||
contacts?: LocationContact[];
|
||||
}
|
||||
|
||||
/** Site option from GET locations/sites (wizard / board create). */
|
||||
|
|
|
|||
18
src/domain/vendors/api/vendors-api.ts
vendored
|
|
@ -76,6 +76,24 @@ export const vendorsApi = {
|
|||
};
|
||||
},
|
||||
|
||||
// SH-281: grouped company rows come from the dedicated directory endpoint;
|
||||
// Vendor/GetVendorList stays on the legacy technician-level contract.
|
||||
getDirectoryList: async (params: VendorsListParams = {}): Promise<VendorsListResult> => {
|
||||
const data = await apiGet<unknown>(API_PATHS.vendor.getDirectoryList, {
|
||||
searchParams: buildListParams(params),
|
||||
});
|
||||
const paginated = handlePaginatedResponse<unknown>(data, {
|
||||
page: params.page,
|
||||
pageSize: params.pageSize,
|
||||
});
|
||||
return {
|
||||
items: mapVendorListItems(paginated.items),
|
||||
totalCount: paginated.totalCount,
|
||||
page: paginated.page,
|
||||
pageSize: paginated.pageSize,
|
||||
};
|
||||
},
|
||||
|
||||
getFacets: async (params?: VendorFacetsParams): Promise<VendorFacets> => {
|
||||
const data = await apiGet<unknown>(API_PATHS.vendor.facets, {
|
||||
searchParams: buildFacetsParams(params),
|
||||
|
|
|
|||
37
src/domain/vendors/mappers/vendor-mapper.ts
vendored
|
|
@ -1,6 +1,7 @@
|
|||
import type {
|
||||
Vendor,
|
||||
VendorDeactivationImpact,
|
||||
VendorDirectoryTechnician,
|
||||
VendorFacetCompany,
|
||||
VendorFacetJobBucket,
|
||||
VendorFacetLocation,
|
||||
|
|
@ -108,7 +109,7 @@ function readBool(record: Record<string, unknown>, ...keys: string[]): boolean {
|
|||
|
||||
export function mapVendorListItem(raw: unknown): VendorListItem {
|
||||
const item = asRecord(raw);
|
||||
return {
|
||||
const mapped = {
|
||||
id: readId(item),
|
||||
companyId: readCompanyId(item),
|
||||
companyName: readString(item, "companyName", "CompanyName"),
|
||||
|
|
@ -126,6 +127,40 @@ export function mapVendorListItem(raw: unknown): VendorListItem {
|
|||
isActive: readBool(item, "isActive", "IsActive"),
|
||||
preferredContact: readPreferredContact(item, "preferredContact", "PreferredContact"),
|
||||
};
|
||||
const rawTechnicians = item.technicians ?? item.Technicians;
|
||||
const technicians = Array.isArray(rawTechnicians)
|
||||
? rawTechnicians.map(mapVendorDirectoryTechnician)
|
||||
: mapped.id == null
|
||||
? []
|
||||
: [
|
||||
{
|
||||
id: mapped.id,
|
||||
contactName: mapped.contactName,
|
||||
email: mapped.email,
|
||||
phone: mapped.phone,
|
||||
preferredContact: mapped.preferredContact,
|
||||
tradeSpecialties: mapped.tradeSpecialties,
|
||||
isActive: mapped.isActive,
|
||||
totalJobs: mapped.totalJobs,
|
||||
},
|
||||
];
|
||||
|
||||
return { ...mapped, technicians };
|
||||
}
|
||||
|
||||
function mapVendorDirectoryTechnician(raw: unknown): VendorDirectoryTechnician {
|
||||
const item = asRecord(raw);
|
||||
const id = readId(item);
|
||||
return {
|
||||
id: id ?? "",
|
||||
contactName: readString(item, "contactName", "ContactName"),
|
||||
email: readString(item, "email", "Email"),
|
||||
phone: readString(item, "phone", "Phone"),
|
||||
preferredContact: readPreferredContact(item, "preferredContact", "PreferredContact"),
|
||||
tradeSpecialties: readString(item, "tradeSpecialties", "TradeSpecialties"),
|
||||
isActive: readBool(item, "isActive", "IsActive"),
|
||||
totalJobs: readNumber(item, "totalJobs", "TotalJobs"),
|
||||
};
|
||||
}
|
||||
|
||||
export function mapVendorListItems(rawItems: unknown[]): VendorListItem[] {
|
||||
|
|
|
|||
13
src/domain/vendors/types/vendor.ts
vendored
|
|
@ -2,6 +2,17 @@ export type VendorPreferredContact = "Phone" | "Email" | "Text";
|
|||
|
||||
export const VENDOR_PREFERRED_CONTACT_VALUES: VendorPreferredContact[] = ["Phone", "Email", "Text"];
|
||||
|
||||
export interface VendorDirectoryTechnician {
|
||||
id: string | number;
|
||||
contactName: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
preferredContact: VendorPreferredContact;
|
||||
tradeSpecialties: string;
|
||||
isActive: boolean;
|
||||
totalJobs: number;
|
||||
}
|
||||
|
||||
export interface VendorListItem {
|
||||
id: string | number | null;
|
||||
companyId: string | number | null;
|
||||
|
|
@ -19,6 +30,8 @@ export interface VendorListItem {
|
|||
tradeSpecialties: string;
|
||||
isActive: boolean;
|
||||
preferredContact: VendorPreferredContact;
|
||||
/** Present on company-grouped directory responses; optional for legacy clients/fixtures. */
|
||||
technicians?: VendorDirectoryTechnician[];
|
||||
}
|
||||
|
||||
export interface Vendor {
|
||||
|
|
|
|||
14
src/domain/vendors/use-cases/use-vendor-directory-list.ts
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { keepPreviousData, useQuery, type UseQueryResult } from "@tanstack/react-query";
|
||||
import { vendorsApi } from "@/domain/vendors/api/vendors-api";
|
||||
import type { VendorsListParams, VendorsListResult } from "@/domain/vendors/types/vendor";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
|
||||
export function useVendorDirectoryList(
|
||||
params: VendorsListParams,
|
||||
): UseQueryResult<VendorsListResult, Error> {
|
||||
return useQuery({
|
||||
queryKey: queryKeys.vendors.directoryList(params as Record<string, unknown>),
|
||||
queryFn: () => vendorsApi.getDirectoryList(params),
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
|
|
@ -68,6 +68,8 @@ export const queryKeys = {
|
|||
all: ["vendors"] as const,
|
||||
list: (params?: Record<string, unknown>) =>
|
||||
[...queryKeys.vendors.all, "list", params ?? {}] as const,
|
||||
directoryList: (params?: Record<string, unknown>) =>
|
||||
[...queryKeys.vendors.all, "directoryList", params ?? {}] as const,
|
||||
detail: (id: string | number) => [...queryKeys.vendors.all, "detail", id] as const,
|
||||
facets: (isActive?: boolean) => [...queryKeys.vendors.all, "facets", isActive ?? null] as const,
|
||||
dropdown: (trade?: string, siteZip?: string) =>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,178 @@
|
|||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { fireEvent, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { LocationContactsFieldArray } from "@/app/(protected)/locations/_components/location-contacts-field-array";
|
||||
import {
|
||||
locationDefaultValues,
|
||||
locationSchema,
|
||||
type LocationFormValues,
|
||||
} from "@/domain/locations/schemas/location-schema";
|
||||
import { renderWithProviders } from "@/test/test-utils";
|
||||
|
||||
const dataTransferStub = {
|
||||
setData: vi.fn(),
|
||||
effectAllowed: "none" as DataTransfer["effectAllowed"],
|
||||
};
|
||||
|
||||
function ContactsHarness({
|
||||
initialContacts,
|
||||
onSubmit = vi.fn(),
|
||||
}: {
|
||||
initialContacts: LocationFormValues["contacts"];
|
||||
onSubmit?: (values: LocationFormValues) => void;
|
||||
}) {
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
register,
|
||||
formState: { errors },
|
||||
} = useForm<LocationFormValues>({
|
||||
resolver: zodResolver(locationSchema),
|
||||
defaultValues: {
|
||||
...locationDefaultValues,
|
||||
name: "Dallas DC",
|
||||
address: "3811 Distribution Dr",
|
||||
city: "Dallas",
|
||||
state: "TX",
|
||||
zipCode: "70068",
|
||||
contactEmail: "jane@example.com",
|
||||
contacts: initialContacts,
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)} noValidate>
|
||||
<LocationContactsFieldArray control={control} errors={errors} register={register} />
|
||||
<button type="submit">Save</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function nameInputs(): HTMLInputElement[] {
|
||||
return screen.getAllByLabelText(/^Contact Name/) as HTMLInputElement[];
|
||||
}
|
||||
|
||||
/** 1-based handle position: `handleFor(2)` is the second row's drag handle. */
|
||||
function handleFor(position: number): HTMLElement {
|
||||
return screen.getByRole("button", {
|
||||
name: `Reorder contact ${position}. Use arrow up or down to move.`,
|
||||
});
|
||||
}
|
||||
|
||||
describe("LocationContactsFieldArray", () => {
|
||||
it("marks the first row as Main and disables removal when only one remains", () => {
|
||||
renderWithProviders(
|
||||
<ContactsHarness initialContacts={[{ name: "Jane", phone: "(421) 433-0032" }]} />,
|
||||
{ withAuth: false },
|
||||
);
|
||||
|
||||
expect(screen.getByText("Main")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/^Contact Name \(Main\)/)).toHaveValue("Jane");
|
||||
expect(screen.getByLabelText("Remove contact 1")).toBeDisabled();
|
||||
});
|
||||
|
||||
it("adds and removes contact rows", () => {
|
||||
renderWithProviders(
|
||||
<ContactsHarness initialContacts={[{ name: "Jane", phone: "(421) 433-0032" }]} />,
|
||||
{ withAuth: false },
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /add contact/i }));
|
||||
|
||||
expect(nameInputs()).toHaveLength(2);
|
||||
expect(screen.getByLabelText("Remove contact 1")).toBeEnabled();
|
||||
expect(screen.getByText("Main")).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByLabelText("Remove contact 2"));
|
||||
expect(nameInputs()).toHaveLength(1);
|
||||
expect(screen.getByLabelText("Remove contact 1")).toBeDisabled();
|
||||
});
|
||||
|
||||
it("reorders with keyboard ArrowUp and keeps focus on the moved handle", async () => {
|
||||
renderWithProviders(
|
||||
<ContactsHarness
|
||||
initialContacts={[
|
||||
{ id: 11, name: "Jane", phone: "(421) 433-0032" },
|
||||
{ id: 12, name: "Bob", phone: "(421) 433-0033" },
|
||||
]}
|
||||
/>,
|
||||
{ withAuth: false },
|
||||
);
|
||||
|
||||
expect(nameInputs().map((input) => input.value)).toEqual(["Jane", "Bob"]);
|
||||
|
||||
const bobHandle = handleFor(2);
|
||||
bobHandle.focus();
|
||||
fireEvent.keyDown(bobHandle, { key: "ArrowUp" });
|
||||
|
||||
expect(nameInputs().map((input) => input.value)).toEqual(["Bob", "Jane"]);
|
||||
await waitFor(() => {
|
||||
expect(document.activeElement).toBe(handleFor(1));
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores ArrowDown on the last row", () => {
|
||||
renderWithProviders(
|
||||
<ContactsHarness
|
||||
initialContacts={[
|
||||
{ name: "Jane", phone: "(421) 433-0032" },
|
||||
{ name: "Bob", phone: "(421) 433-0033" },
|
||||
]}
|
||||
/>,
|
||||
{ withAuth: false },
|
||||
);
|
||||
|
||||
fireEvent.keyDown(handleFor(2), { key: "ArrowDown" });
|
||||
|
||||
expect(nameInputs().map((input) => input.value)).toEqual(["Jane", "Bob"]);
|
||||
});
|
||||
|
||||
it("reorders with native drag events from the handle", () => {
|
||||
renderWithProviders(
|
||||
<ContactsHarness
|
||||
initialContacts={[
|
||||
{ name: "Jane", phone: "(421) 433-0032" },
|
||||
{ name: "Bob", phone: "(421) 433-0033" },
|
||||
]}
|
||||
/>,
|
||||
{ withAuth: false },
|
||||
);
|
||||
|
||||
fireEvent.dragStart(handleFor(1), { dataTransfer: dataTransferStub });
|
||||
fireEvent.drop(nameInputs()[1].closest("div") as HTMLElement, {
|
||||
dataTransfer: dataTransferStub,
|
||||
});
|
||||
|
||||
expect(nameInputs().map((input) => input.value)).toEqual(["Bob", "Jane"]);
|
||||
});
|
||||
|
||||
it("submits contacts in displayed order", async () => {
|
||||
const onSubmit = vi.fn();
|
||||
renderWithProviders(
|
||||
<ContactsHarness
|
||||
initialContacts={[
|
||||
{ id: 11, name: "Jane", phone: "(421) 433-0032" },
|
||||
{ id: 12, name: "Bob", phone: "(421) 433-0033" },
|
||||
]}
|
||||
onSubmit={onSubmit}
|
||||
/>,
|
||||
{ withAuth: false },
|
||||
);
|
||||
|
||||
fireEvent.keyDown(handleFor(2), { key: "ArrowUp" });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
expect(onSubmit.mock.calls[0][0]).toEqual(
|
||||
expect.objectContaining({
|
||||
contacts: [
|
||||
{ id: 12, name: "Bob", phone: "(421) 433-0033" },
|
||||
{ id: 11, name: "Jane", phone: "(421) 433-0032" },
|
||||
],
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
import { fireEvent, screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LocationsContactsCell } from "@/app/(protected)/locations/_components/locations-contacts-cell";
|
||||
import type { LocationListItem } from "@/domain/locations/types/location";
|
||||
import { renderWithProviders } from "@/test/test-utils";
|
||||
|
||||
function rowWithContacts(overrides: Partial<LocationListItem>): LocationListItem {
|
||||
return {
|
||||
id: 1,
|
||||
name: "Dallas DC",
|
||||
address: "3811 Distribution Dr",
|
||||
city: "Dallas",
|
||||
state: "TX",
|
||||
zipCode: "70068",
|
||||
phone: "(421) 433-0032",
|
||||
contact: "Jane",
|
||||
contactEmail: "jane@example.com",
|
||||
status: "Active",
|
||||
accountId: 7,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("LocationsContactsCell", () => {
|
||||
it("renders only the main contact name when a single contact exists", () => {
|
||||
renderWithProviders(
|
||||
<LocationsContactsCell
|
||||
row={rowWithContacts({ contacts: [{ name: "Jane", phone: "(421) 433-0032" }] })}
|
||||
/>,
|
||||
{ withAuth: false },
|
||||
);
|
||||
|
||||
expect(screen.getByText("Jane")).toBeInTheDocument();
|
||||
expect(screen.queryByText(/^\+\d+$/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a +N chip and lists remaining contact names on hover", async () => {
|
||||
renderWithProviders(
|
||||
<LocationsContactsCell
|
||||
row={rowWithContacts({
|
||||
contacts: [
|
||||
{ name: "Jane", phone: "(421) 433-0032" },
|
||||
{ name: "Bob", phone: "(421) 433-0033" },
|
||||
{ name: "Carol", phone: "(421) 433-0034" },
|
||||
],
|
||||
})}
|
||||
/>,
|
||||
{ withAuth: false },
|
||||
);
|
||||
|
||||
const chip = screen.getByText("+2");
|
||||
expect(chip).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("2 more contacts: Bob, Carol")).toBeInTheDocument();
|
||||
|
||||
fireEvent.mouseOver(chip);
|
||||
expect(await screen.findByText("Bob, Carol")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("falls back to the legacy contact field without a chip", () => {
|
||||
renderWithProviders(<LocationsContactsCell row={rowWithContacts({})} />, {
|
||||
withAuth: false,
|
||||
});
|
||||
|
||||
expect(screen.getByText("Jane")).toBeInTheDocument();
|
||||
expect(screen.queryByText(/^\+\d+$/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders a placeholder when no contact exists", () => {
|
||||
renderWithProviders(
|
||||
<LocationsContactsCell row={rowWithContacts({ contact: "", phone: "" })} />,
|
||||
{ withAuth: false },
|
||||
);
|
||||
|
||||
expect(screen.getByText("—")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
@ -27,8 +27,7 @@ function StateSelectHarness({
|
|||
address: "3811 Distribution Dr",
|
||||
city: "Dallas",
|
||||
zipCode: "70068",
|
||||
phone: "(421) 433-0032",
|
||||
contact: "Jane",
|
||||
contacts: [{ name: "Jane", phone: "(421) 433-0032" }],
|
||||
contactEmail: "jane@example.com",
|
||||
status: "Active",
|
||||
},
|
||||
|
|
|
|||
|
|
@ -0,0 +1,50 @@
|
|||
import { describe, expect, it, vi } from "vitest";
|
||||
import { screen } from "@testing-library/react";
|
||||
import VendorPosListPage from "@/app/(protected)/vendor-pos/index";
|
||||
import { renderWithProviders } from "@/test/test-utils";
|
||||
|
||||
const useVendorPosList = vi.fn();
|
||||
const useVendorsList = vi.fn();
|
||||
const useVendorDirectoryList = vi.fn();
|
||||
|
||||
vi.mock("@/domain/vendor-pos/use-cases/use-vendor-pos-list", () => ({
|
||||
useVendorPosList: (...args: unknown[]) => useVendorPosList(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@/domain/vendors/use-cases/use-vendors-list", () => ({
|
||||
useVendorsList: (...args: unknown[]) => useVendorsList(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@/domain/vendors/use-cases/use-vendor-directory-list", () => ({
|
||||
useVendorDirectoryList: (...args: unknown[]) => useVendorDirectoryList(...args),
|
||||
}));
|
||||
|
||||
describe("VendorPosListPage vendor source", () => {
|
||||
it("keeps the legacy technician-level vendors list with pageSize 500", () => {
|
||||
useVendorPosList.mockReturnValue({
|
||||
data: { items: [], totalCount: 0, page: 1, pageSize: 12 },
|
||||
isLoading: false,
|
||||
isFetching: false,
|
||||
error: null,
|
||||
});
|
||||
useVendorsList.mockReturnValue({
|
||||
data: { items: [], totalCount: 0, page: 1, pageSize: 500 },
|
||||
isLoading: false,
|
||||
isFetching: false,
|
||||
error: null,
|
||||
});
|
||||
useVendorDirectoryList.mockReturnValue({
|
||||
data: { items: [], totalCount: 0, page: 1, pageSize: 500 },
|
||||
isLoading: false,
|
||||
isFetching: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
renderWithProviders(<VendorPosListPage />, { route: "/vendor-pos", withAuth: false });
|
||||
|
||||
expect(useVendorsList).toHaveBeenCalledWith({ page: 1, pageSize: 500 });
|
||||
expect(useVendorsList).toHaveBeenCalledTimes(1);
|
||||
expect(useVendorDirectoryList).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole("table")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
@ -5,12 +5,12 @@ import VendorsListPage from "@/app/(protected)/vendors/index";
|
|||
import type { VendorCompanyRoster, VendorListItem } from "@/domain/vendors/types/vendor";
|
||||
import { renderWithProviders } from "@/test/test-utils";
|
||||
|
||||
const useVendorsList = vi.fn();
|
||||
const useVendorDirectoryList = vi.fn();
|
||||
const useVendorCompanyRoster = vi.fn();
|
||||
const useVendorDeactivationImpact = vi.fn();
|
||||
const mutate = vi.fn();
|
||||
vi.mock("@/domain/vendors/use-cases/use-vendors-list", () => ({
|
||||
useVendorsList: (...args: unknown[]) => useVendorsList(...args),
|
||||
vi.mock("@/domain/vendors/use-cases/use-vendor-directory-list", () => ({
|
||||
useVendorDirectoryList: (...args: unknown[]) => useVendorDirectoryList(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@/domain/vendors/use-cases/use-vendor-company-roster", () => ({
|
||||
|
|
@ -108,15 +108,22 @@ function setupDefaults() {
|
|||
describe("VendorsListPage", () => {
|
||||
it("renders prototype-aligned status and two row actions in both tabs", async () => {
|
||||
setupDefaults();
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], params.isActive ? 1 : 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([inactiveVendor], 1);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], params.isActive ? 1 : 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([inactiveVendor], 1);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
expect(screen.getByRole("heading", { name: "Vendors / Technicians" })).toBeInTheDocument();
|
||||
expect(screen.getByText("St. Louis, MO")).toBeInTheDocument();
|
||||
expect(screen.getByRole("columnheader", { name: "Company Phone" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("columnheader", { name: "Company Email" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("columnheader", { name: "Street Address" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("columnheader", { name: "Technician Phone" })).toBeInTheDocument();
|
||||
expect(screen.getByText("St. Louis")).toBeInTheDocument();
|
||||
expect(screen.getByText("MO")).toBeInTheDocument();
|
||||
expect(screen.getByRole("columnheader", { name: "Status" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("cell", { name: "Active" })).toBeInTheDocument();
|
||||
expect(
|
||||
|
|
@ -134,7 +141,58 @@ describe("VendorsListPage", () => {
|
|||
expect(screen.queryByRole("button", { name: "Deactivate vendor" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("prefers trimmed city and state over address and technician phone over company phone", () => {
|
||||
it("renders one company row with the primary technician and a keyboard-accessible roster badge", async () => {
|
||||
setupDefaults();
|
||||
const groupedVendor: VendorListItem = {
|
||||
...activeVendor,
|
||||
id: 22,
|
||||
contactName: "Promoted Technician",
|
||||
totalJobs: 9,
|
||||
technicians: [
|
||||
{
|
||||
id: 11,
|
||||
contactName: "Older Technician",
|
||||
email: "older@gateway.test",
|
||||
phone: "314-555-0111",
|
||||
preferredContact: "Phone",
|
||||
tradeSpecialties: "Plumbing",
|
||||
isActive: true,
|
||||
totalJobs: 4,
|
||||
},
|
||||
{
|
||||
id: 22,
|
||||
contactName: "Promoted Technician",
|
||||
email: "promoted@gateway.test",
|
||||
phone: "314-555-0222",
|
||||
preferredContact: "Email",
|
||||
tradeSpecialties: "HVAC",
|
||||
isActive: true,
|
||||
totalJobs: 5,
|
||||
},
|
||||
],
|
||||
};
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([groupedVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
expect(screen.getAllByText("Gateway Plumbing")).toHaveLength(1);
|
||||
expect(screen.getByText("Promoted Technician")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "314-555-0222" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("cell", { name: "9" })).toBeInTheDocument();
|
||||
|
||||
const rosterBadge = screen.getByTestId("vendor-technician-badge");
|
||||
expect(rosterBadge).toHaveTextContent("+1");
|
||||
expect(rosterBadge).toHaveAttribute("tabindex", "0");
|
||||
await userEvent.hover(rosterBadge);
|
||||
expect(await screen.findByRole("tooltip")).toHaveTextContent("Older Technician");
|
||||
});
|
||||
|
||||
it("renders company location and contact fields in separate columns", () => {
|
||||
setupDefaults();
|
||||
const vendorWithAllFields: VendorListItem = {
|
||||
...activeVendor,
|
||||
|
|
@ -144,21 +202,29 @@ describe("VendorsListPage", () => {
|
|||
state: " MO ",
|
||||
phone: " (314) 555-0198 ",
|
||||
};
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([vendorWithAllFields], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([vendorWithAllFields], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
expect(screen.getByText("St. Louis, MO")).toBeInTheDocument();
|
||||
expect(screen.queryByText(/1 Market St/)).not.toBeInTheDocument();
|
||||
const phoneLink = screen.getByRole("link", { name: "(314) 555-0198" });
|
||||
expect(phoneLink).toHaveAttribute("href", "tel:(314) 555-0198");
|
||||
expect(screen.queryByText("(314) 555-0100")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("1 Market St")).toBeInTheDocument();
|
||||
expect(screen.getByText("St. Louis")).toBeInTheDocument();
|
||||
expect(screen.getByText("MO")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "(314) 555-0198" })).toHaveAttribute(
|
||||
"href",
|
||||
"tel:(314) 555-0198",
|
||||
);
|
||||
expect(screen.getByRole("link", { name: "(314) 555-0100" })).toHaveAttribute(
|
||||
"href",
|
||||
"tel:(314) 555-0100",
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the trimmed address and company phone when technician fields are absent", () => {
|
||||
it("keeps company and technician phone ownership separate when technician phone is absent", () => {
|
||||
setupDefaults();
|
||||
const fallbackVendor: VendorListItem = {
|
||||
...activeVendor,
|
||||
|
|
@ -168,10 +234,12 @@ describe("VendorsListPage", () => {
|
|||
state: "",
|
||||
phone: " ",
|
||||
};
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([fallbackVendor], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([fallbackVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
|
|
@ -179,6 +247,7 @@ describe("VendorsListPage", () => {
|
|||
const companyPhoneLink = screen.getByRole("link", { name: "(314) 555-0100" });
|
||||
expect(companyPhoneLink).toHaveAttribute("href", "tel:(314) 555-0100");
|
||||
expect(screen.queryByText(/555-0198/)).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId("vendor-text-technician-phone")).toHaveTextContent("—");
|
||||
});
|
||||
|
||||
it("truncates every textual table field and reveals each full value", async () => {
|
||||
|
|
@ -199,19 +268,21 @@ describe("VendorsListPage", () => {
|
|||
city: "",
|
||||
state: "",
|
||||
};
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([fallbackVendor], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([fallbackVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
const fields = [
|
||||
{ testId: "vendor-text-company", value: longCompany },
|
||||
{ testId: "vendor-text-technician", value: longTechnician },
|
||||
{ testId: "vendor-text-location", value: longAddress },
|
||||
{ testId: "vendor-text-phone", value: longPhone },
|
||||
{ testId: "vendor-text-email", value: longEmail },
|
||||
{ testId: "vendor-text-street-address", value: longAddress },
|
||||
{ testId: "vendor-text-technician-phone", value: longPhone },
|
||||
{ testId: "vendor-text-company-email", value: longEmail },
|
||||
];
|
||||
|
||||
for (const field of fields) {
|
||||
|
|
@ -231,10 +302,18 @@ describe("VendorsListPage", () => {
|
|||
await waitFor(() => expect(screen.queryByRole("tooltip")).not.toBeInTheDocument());
|
||||
}
|
||||
|
||||
expect(screen.getByTestId("vendor-text-phone")).toHaveAttribute("href", `tel:${longPhone}`);
|
||||
expect(screen.getByTestId("vendor-text-email")).toHaveAttribute("href", `mailto:${longEmail}`);
|
||||
expect(screen.getByTestId("vendor-text-technician-phone")).toHaveAttribute(
|
||||
"href",
|
||||
`tel:${longPhone}`,
|
||||
);
|
||||
expect(screen.getByTestId("vendor-text-company-email")).toHaveAttribute(
|
||||
"href",
|
||||
`mailto:${longEmail}`,
|
||||
);
|
||||
fireEvent.keyDown(screen.getByTestId("vendor-text-company-email"), { key: "Enter" });
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
|
||||
const locationText = screen.getByTestId("vendor-text-location");
|
||||
const locationText = screen.getByTestId("vendor-text-street-address");
|
||||
fireEvent.keyDown(document, { key: "Tab" });
|
||||
locationText.focus();
|
||||
expect(locationText).toHaveFocus();
|
||||
|
|
@ -250,10 +329,12 @@ describe("VendorsListPage", () => {
|
|||
...activeVendor,
|
||||
tradeSpecialties: "Backflow Preventers, Water Heaters, Drain Cleaning",
|
||||
};
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([multiTradeVendor], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([multiTradeVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
|
|
@ -277,10 +358,12 @@ describe("VendorsListPage", () => {
|
|||
|
||||
it("does not show the +N badge when the vendor has a single trade", () => {
|
||||
setupDefaults();
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
|
|
@ -301,10 +384,12 @@ describe("VendorsListPage", () => {
|
|||
...activeVendor,
|
||||
tradeSpecialties: "Backflow Preventers, Water Heaters, Drain Cleaning",
|
||||
};
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([multiTradeVendor], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([multiTradeVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
|
|
@ -325,10 +410,12 @@ describe("VendorsListPage", () => {
|
|||
...activeVendor,
|
||||
tradeSpecialties: "Backflow Preventers, Water Heaters",
|
||||
};
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([multiTradeVendor], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([multiTradeVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
|
|
@ -345,15 +432,17 @@ describe("VendorsListPage", () => {
|
|||
companyName: `Vendor ${index + 1}`,
|
||||
}));
|
||||
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], params.isActive ? 25 : 0);
|
||||
return result(pageVendors, 25);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], params.isActive ? 25 : 0);
|
||||
return result(pageVendors, 25);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
expect(screen.getByText(/25 active technicians/)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/3 active technicians/)).not.toBeInTheDocument();
|
||||
expect(screen.getAllByText(/25 active companies/)).not.toHaveLength(0);
|
||||
expect(screen.queryByText(/3 active companies/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens the detail drawer when a row is clicked or activated by keyboard", async () => {
|
||||
|
|
@ -365,10 +454,12 @@ describe("VendorsListPage", () => {
|
|||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
|
|
@ -406,10 +497,12 @@ describe("VendorsListPage", () => {
|
|||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
|
|
@ -447,10 +540,12 @@ describe("VendorsListPage", () => {
|
|||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
|
|
@ -477,10 +572,12 @@ describe("VendorsListPage", () => {
|
|||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
|
|
@ -508,10 +605,12 @@ describe("VendorsListPage", () => {
|
|||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
|
|
@ -533,10 +632,12 @@ describe("VendorsListPage", () => {
|
|||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([companyOnlyVendor], 1) : result([], 0);
|
||||
});
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([companyOnlyVendor], 1) : result([], 0);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
|
|
@ -547,4 +648,24 @@ describe("VendorsListPage", () => {
|
|||
"Gateway Plumbing",
|
||||
);
|
||||
});
|
||||
|
||||
it("loads rows and status counts through the directory hook", async () => {
|
||||
setupDefaults();
|
||||
useVendorDirectoryList.mockImplementation(
|
||||
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], params.isActive ? 3 : 2);
|
||||
return result([activeVendor], 3);
|
||||
},
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
expect(useVendorDirectoryList).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ page: 1, pageSize: 48 }),
|
||||
);
|
||||
expect(useVendorDirectoryList).toHaveBeenCalledWith({ isActive: true, page: 1, pageSize: 1 });
|
||||
expect(useVendorDirectoryList).toHaveBeenCalledWith({ isActive: false, page: 1, pageSize: 1 });
|
||||
expect(screen.getByRole("tab", { name: "Active (3)" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("tab", { name: "Inactive (2)" })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
94
src/test/domain/locations/mappers/location-mapper.test.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
mapLocation,
|
||||
mapLocationListItem,
|
||||
mapLocationToBackend,
|
||||
} from "@/domain/locations/mappers/location-mapper";
|
||||
|
||||
describe("location contacts hydration", () => {
|
||||
it("maps the response contacts array and derives the main contact fields", () => {
|
||||
const item = mapLocationListItem({
|
||||
id: 1,
|
||||
name: "Dallas DC",
|
||||
contacts: [
|
||||
{ name: "Jane", phone: "(421) 433-0032" },
|
||||
{ name: "Bob", phone: "(421) 433-0033" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(item.contacts).toEqual([
|
||||
{ name: "Jane", phone: "(421) 433-0032" },
|
||||
{ name: "Bob", phone: "(421) 433-0033" },
|
||||
]);
|
||||
expect(item.contact).toBe("Jane");
|
||||
expect(item.phone).toBe("(421) 433-0032");
|
||||
});
|
||||
|
||||
it("falls back to legacy contact/phone fields when no contacts array exists", () => {
|
||||
const item = mapLocationListItem({
|
||||
id: 2,
|
||||
contact: "Bob",
|
||||
phone: "(312) 555-0100",
|
||||
});
|
||||
|
||||
expect(item.contacts).toBeUndefined();
|
||||
expect(item.contact).toBe("Bob");
|
||||
expect(item.phone).toBe("(312) 555-0100");
|
||||
});
|
||||
|
||||
it("hydrates detail contacts and mirrors the first row in contact/phone", () => {
|
||||
const detail = mapLocation({
|
||||
id: 3,
|
||||
contacts: [{ id: 31, name: "Carol", phone: "555-0143" }],
|
||||
});
|
||||
|
||||
expect(detail.contacts).toEqual([{ id: 31, name: "Carol", phone: "555-0143" }]);
|
||||
expect(detail.contact).toBe("Carol");
|
||||
expect(detail.phone).toBe("555-0143");
|
||||
});
|
||||
|
||||
it("keeps legacy detail contact/phone for zero-contact data", () => {
|
||||
const detail = mapLocation({ id: 4, contact: "Legacy Person", phone: "555-0199" });
|
||||
|
||||
expect(detail.contacts).toBeUndefined();
|
||||
expect(detail.contact).toBe("Legacy Person");
|
||||
expect(detail.phone).toBe("555-0199");
|
||||
});
|
||||
});
|
||||
|
||||
describe("mapLocationToBackend contacts payload", () => {
|
||||
it("sends trimmed contacts in displayed order and derives legacy fields from the first", () => {
|
||||
const payload = mapLocationToBackend({
|
||||
name: "Dallas DC",
|
||||
address: "3811 Distribution Dr",
|
||||
city: "Dallas",
|
||||
state: "TX",
|
||||
zipCode: "70068",
|
||||
contactEmail: "jane@example.com",
|
||||
status: "Active",
|
||||
contacts: [
|
||||
{ id: 41, name: " Jane ", phone: " (421) 433-0032 " },
|
||||
{ name: "Bob", phone: "(421) 433-0033" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(payload.contacts).toEqual([
|
||||
{ id: 41, name: "Jane", phone: "(421) 433-0032" },
|
||||
{ name: "Bob", phone: "(421) 433-0033" },
|
||||
]);
|
||||
expect(payload.contact).toBe("Jane");
|
||||
expect(payload.phone).toBe("(421) 433-0032");
|
||||
});
|
||||
|
||||
it("keeps legacy contact/phone untouched when no contacts are provided", () => {
|
||||
const payload = mapLocationToBackend({
|
||||
name: "Legacy DC",
|
||||
contact: "Legacy Person",
|
||||
phone: "555-0199",
|
||||
});
|
||||
|
||||
expect(payload.contact).toBe("Legacy Person");
|
||||
expect(payload.phone).toBe("555-0199");
|
||||
expect(payload.contacts).toEqual([]);
|
||||
});
|
||||
});
|
||||
65
src/test/domain/locations/schemas/location-schema.test.ts
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
locationDefaultValues,
|
||||
locationSchema,
|
||||
type LocationFormValues,
|
||||
} from "@/domain/locations/schemas/location-schema";
|
||||
|
||||
const validBase: LocationFormValues = {
|
||||
...locationDefaultValues,
|
||||
name: "Dallas DC",
|
||||
address: "3811 Distribution Dr",
|
||||
city: "Dallas",
|
||||
state: "TX",
|
||||
zipCode: "70068",
|
||||
contactEmail: "jane@example.com",
|
||||
};
|
||||
|
||||
describe("locationSchema contacts", () => {
|
||||
it("accepts one fully populated contact", () => {
|
||||
const result = locationSchema.safeParse({
|
||||
...validBase,
|
||||
contacts: [{ name: "Jane", phone: "(421) 433-0032" }],
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("requires at least one contact", () => {
|
||||
const result = locationSchema.safeParse({ ...validBase, contacts: [] });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
expect(result.error.issues[0]?.message).toBe("At least one contact is required");
|
||||
}
|
||||
});
|
||||
|
||||
it("requires a name and a phone on every row", () => {
|
||||
const result = locationSchema.safeParse({
|
||||
...validBase,
|
||||
contacts: [
|
||||
{ name: "Jane", phone: "" },
|
||||
{ name: " ", phone: "(421) 433-0032" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
const messages = result.error.issues.map((issue) => issue.message);
|
||||
expect(messages).toContain("Phone is required");
|
||||
expect(messages).toContain("Contact person is required");
|
||||
}
|
||||
});
|
||||
|
||||
it("trims name and phone values on parse", () => {
|
||||
const result = locationSchema.safeParse({
|
||||
...validBase,
|
||||
contacts: [{ name: " Jane ", phone: " (421) 433-0032 " }],
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.contacts[0]).toEqual({ name: "Jane", phone: "(421) 433-0032" });
|
||||
}
|
||||
});
|
||||
});
|
||||
136
src/test/domain/vendors/api/vendors-api.test.ts
vendored
|
|
@ -28,11 +28,24 @@ describe("vendorsApi.getList", () => {
|
|||
CompanyId: "co-1",
|
||||
CompanyName: "Gateway Plumbing",
|
||||
ContactName: "Adam Whyte",
|
||||
Email: "dispatch@gateway.test",
|
||||
Phone: "314-555-0198",
|
||||
Address: "1 Market St",
|
||||
City: "St. Louis",
|
||||
State: "MO",
|
||||
IsActive: false,
|
||||
PreferredContact: "Email",
|
||||
Technicians: [
|
||||
{
|
||||
Id: 7,
|
||||
ContactName: "Adam Whyte",
|
||||
Email: "adam@gateway.test",
|
||||
Phone: "314-555-0198",
|
||||
TradeSpecialties: "Plumbing",
|
||||
IsActive: false,
|
||||
TotalJobs: 3,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
TotalCount: 1,
|
||||
|
|
@ -52,9 +65,39 @@ describe("vendorsApi.getList", () => {
|
|||
isActive: false,
|
||||
companyId: "co-1",
|
||||
preferredContact: "Email",
|
||||
technicians: [
|
||||
expect.objectContaining({
|
||||
id: 7,
|
||||
email: "adam@gateway.test",
|
||||
phone: "314-555-0198",
|
||||
totalJobs: 3,
|
||||
}),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("synthesizes one technician for a legacy ungrouped response", async () => {
|
||||
apiGet.mockResolvedValueOnce({
|
||||
Data: [
|
||||
{
|
||||
Id: 9,
|
||||
CompanyName: "Legacy Co",
|
||||
ContactName: "Legacy Tech",
|
||||
Email: "legacy@example.test",
|
||||
Phone: "555-0109",
|
||||
IsActive: true,
|
||||
},
|
||||
],
|
||||
TotalCount: 1,
|
||||
});
|
||||
|
||||
const result = await vendorsApi.getList();
|
||||
|
||||
expect(result.items[0]?.technicians).toEqual([
|
||||
expect.objectContaining({ id: 9, contactName: "Legacy Tech", phone: "555-0109" }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("forwards all selected facets as repeated indexed query parameters", async () => {
|
||||
await vendorsApi.getList({
|
||||
companies: ["Gateway Plumbing", "Metro HVAC"],
|
||||
|
|
@ -283,3 +326,96 @@ describe("vendorsApi.getList", () => {
|
|||
await expect(vendorsApi.delete(8)).rejects.toThrow("Conflict");
|
||||
});
|
||||
});
|
||||
|
||||
describe("vendorsApi.getDirectoryList", () => {
|
||||
beforeEach(() => {
|
||||
apiGet.mockReset();
|
||||
apiGet.mockResolvedValue({
|
||||
Data: [
|
||||
{
|
||||
Id: 7,
|
||||
CompanyId: "co-1",
|
||||
CompanyName: "Gateway Plumbing",
|
||||
ContactName: "Adam Whyte",
|
||||
Email: "dispatch@gateway.test",
|
||||
Phone: "314-555-0198",
|
||||
Address: "1 Market St",
|
||||
City: "St. Louis",
|
||||
State: "MO",
|
||||
IsActive: false,
|
||||
PreferredContact: "Email",
|
||||
Technicians: [
|
||||
{
|
||||
Id: 7,
|
||||
ContactName: "Adam Whyte",
|
||||
Email: "adam@gateway.test",
|
||||
Phone: "314-555-0198",
|
||||
TradeSpecialties: "Plumbing",
|
||||
IsActive: false,
|
||||
TotalJobs: 3,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
TotalCount: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("targets the dedicated directory endpoint while getList keeps the legacy route", async () => {
|
||||
await vendorsApi.getDirectoryList({ search: "gateway", isActive: false, page: 1 });
|
||||
await vendorsApi.getList({ search: "gateway", isActive: false, page: 1 });
|
||||
|
||||
expect(API_PATHS.vendor.getDirectoryList).toBe("Vendor/GetVendorDirectoryList");
|
||||
expect(API_PATHS.vendor.getList).toBe("Vendor/GetVendorList");
|
||||
expect(apiGet).toHaveBeenNthCalledWith(1, API_PATHS.vendor.getDirectoryList, {
|
||||
searchParams: { search: "gateway", isActive: "false", page: 1, pageSize: 12 },
|
||||
});
|
||||
expect(apiGet).toHaveBeenNthCalledWith(2, API_PATHS.vendor.getList, {
|
||||
searchParams: { search: "gateway", isActive: "false", page: 1, pageSize: 12 },
|
||||
});
|
||||
});
|
||||
|
||||
it("builds directory query parameters with the same repeated facet encoding", async () => {
|
||||
await vendorsApi.getDirectoryList({
|
||||
companies: ["Gateway Plumbing", "Metro HVAC"],
|
||||
trades: ["Plumbing"],
|
||||
locations: ["St. Louis, MO"],
|
||||
jobBuckets: ["50-99"],
|
||||
});
|
||||
|
||||
expect(apiGet).toHaveBeenCalledWith(API_PATHS.vendor.getDirectoryList, {
|
||||
searchParams: {
|
||||
search: "",
|
||||
page: 1,
|
||||
pageSize: 12,
|
||||
"companies[0]": "Gateway Plumbing",
|
||||
"companies[1]": "Metro HVAC",
|
||||
"trades[0]": "Plumbing",
|
||||
"locations[0]": "St. Louis, MO",
|
||||
"jobBuckets[0]": "50-99",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("maps grouped company rows with the shared grouped-row mapper", async () => {
|
||||
const result = await vendorsApi.getDirectoryList({ isActive: false, page: 1 });
|
||||
|
||||
expect(result.items[0]).toMatchObject({
|
||||
companyId: "co-1",
|
||||
companyName: "Gateway Plumbing",
|
||||
address: "1 Market St",
|
||||
city: "St. Louis",
|
||||
state: "MO",
|
||||
isActive: false,
|
||||
technicians: [
|
||||
expect.objectContaining({
|
||||
id: 7,
|
||||
contactName: "Adam Whyte",
|
||||
email: "adam@gateway.test",
|
||||
phone: "314-555-0198",
|
||||
totalJobs: 3,
|
||||
}),
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
80
src/test/domain/vendors/use-cases/use-vendor-directory-list.test.tsx
vendored
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
const getDirectoryList = vi.fn();
|
||||
const getList = vi.fn();
|
||||
|
||||
vi.mock("@/domain/vendors/api/vendors-api", () => ({
|
||||
vendorsApi: {
|
||||
getDirectoryList: (...args: unknown[]) => getDirectoryList(...args),
|
||||
getList: (...args: unknown[]) => getList(...args),
|
||||
},
|
||||
}));
|
||||
|
||||
import { useVendorDirectoryList } from "@/domain/vendors/use-cases/use-vendor-directory-list";
|
||||
import { useVendorsList } from "@/domain/vendors/use-cases/use-vendors-list";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
|
||||
const emptyResult = { items: [], totalCount: 0, page: 1, pageSize: 12 };
|
||||
|
||||
function createClient(): QueryClient {
|
||||
return new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
}
|
||||
|
||||
function makeWrapper(client: QueryClient) {
|
||||
return function Wrapper({ children }: { children: ReactNode }) {
|
||||
return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
|
||||
};
|
||||
}
|
||||
|
||||
describe("useVendorDirectoryList", () => {
|
||||
beforeEach(() => {
|
||||
getDirectoryList.mockReset();
|
||||
getList.mockReset();
|
||||
getDirectoryList.mockResolvedValue(emptyResult);
|
||||
getList.mockResolvedValue(emptyResult);
|
||||
});
|
||||
|
||||
it("fetches through the directory endpoint, never the legacy list", async () => {
|
||||
const { result } = renderHook(() => useVendorDirectoryList({ isActive: true, page: 1 }), {
|
||||
wrapper: makeWrapper(createClient()),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(getDirectoryList).toHaveBeenCalledWith({ isActive: true, page: 1 });
|
||||
expect(getList).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a query key distinct from the legacy list key", () => {
|
||||
const params = { isActive: true, page: 1, pageSize: 12 };
|
||||
|
||||
expect(queryKeys.vendors.directoryList(params)).not.toEqual(queryKeys.vendors.list(params));
|
||||
expect(queryKeys.vendors.directoryList(params)).toEqual(
|
||||
queryKeys.vendors.directoryList(params),
|
||||
);
|
||||
expect(queryKeys.vendors.directoryList(params)[1]).toBe("directoryList");
|
||||
expect(queryKeys.vendors.list(params)[1]).toBe("list");
|
||||
});
|
||||
|
||||
it("caches directory and legacy results independently for the same params", async () => {
|
||||
const params = { isActive: true, page: 1 } as const;
|
||||
const client = createClient();
|
||||
const directory = renderHook(() => useVendorDirectoryList({ ...params }), {
|
||||
wrapper: makeWrapper(client),
|
||||
});
|
||||
const legacy = renderHook(() => useVendorsList({ ...params }), {
|
||||
wrapper: makeWrapper(client),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(directory.result.current.isSuccess).toBe(true));
|
||||
await waitFor(() => expect(legacy.result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(getDirectoryList).toHaveBeenCalledTimes(1);
|
||||
expect(getList).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||