Merge branch 'dev' into fix/ab/sh-368-completion-uploads
|
Before Width: | Height: | Size: 140 KiB After Width: | Height: | Size: 142 KiB |
|
Before Width: | Height: | Size: 112 KiB After Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 144 KiB After Width: | Height: | Size: 146 KiB |
|
Before Width: | Height: | Size: 98 KiB After Width: | Height: | Size: 103 KiB |
|
Before Width: | Height: | Size: 96 KiB After Width: | Height: | Size: 101 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 101 KiB |
|
Before Width: | Height: | Size: 102 KiB After Width: | Height: | Size: 104 KiB |
|
Before Width: | Height: | Size: 111 KiB After Width: | Height: | Size: 111 KiB |
|
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 45 KiB |
|
Before Width: | Height: | Size: 140 KiB After Width: | Height: | Size: 144 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 111 KiB After Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 144 KiB After Width: | Height: | Size: 148 KiB |
|
Before Width: | Height: | Size: 116 KiB After Width: | Height: | Size: 120 KiB |
|
Before Width: | Height: | Size: 39 KiB After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 185 KiB After Width: | Height: | Size: 189 KiB |
196
e2e/vendors/vendors.spec.ts
vendored
|
|
@ -29,6 +29,8 @@ const activeVendors = [
|
||||||
TotalJobs: 72,
|
TotalJobs: 72,
|
||||||
IsActive: true,
|
IsActive: true,
|
||||||
PreferredContact: "Email",
|
PreferredContact: "Email",
|
||||||
|
AreaId: 1 as number | null,
|
||||||
|
AreaName: "East",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Id: 2,
|
Id: 2,
|
||||||
|
|
@ -47,9 +49,16 @@ const activeVendors = [
|
||||||
Notes: "",
|
Notes: "",
|
||||||
TotalJobs: 18,
|
TotalJobs: 18,
|
||||||
IsActive: true,
|
IsActive: true,
|
||||||
|
AreaId: null as number | null,
|
||||||
|
AreaName: "",
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const SERVICE_AREAS = [
|
||||||
|
{ id: 2, name: "Central" },
|
||||||
|
{ id: 1, name: "East" },
|
||||||
|
];
|
||||||
|
|
||||||
const inactiveVendors = [
|
const inactiveVendors = [
|
||||||
{
|
{
|
||||||
...activeVendors[0],
|
...activeVendors[0],
|
||||||
|
|
@ -97,6 +106,7 @@ async function mockVendorApi(
|
||||||
listError?: boolean;
|
listError?: boolean;
|
||||||
deactivationBlocked?: boolean;
|
deactivationBlocked?: boolean;
|
||||||
deleteConflict?: boolean;
|
deleteConflict?: boolean;
|
||||||
|
groupedDirectory?: boolean;
|
||||||
legacyGateway?: boolean;
|
legacyGateway?: boolean;
|
||||||
longText?: boolean;
|
longText?: boolean;
|
||||||
} = {},
|
} = {},
|
||||||
|
|
@ -134,6 +144,7 @@ async function mockVendorApi(
|
||||||
googleMapsUrl: vendor.GoogleMapsUrl,
|
googleMapsUrl: vendor.GoogleMapsUrl,
|
||||||
})),
|
})),
|
||||||
trades: ["Plumbing", "Backflow Preventers", "HVAC"],
|
trades: ["Plumbing", "Backflow Preventers", "HVAC"],
|
||||||
|
areas: SERVICE_AREAS,
|
||||||
locations: [
|
locations: [
|
||||||
{ city: "St. Louis", state: "MO", label: "St. Louis, MO" },
|
{ city: "St. Louis", state: "MO", label: "St. Louis, MO" },
|
||||||
{ city: "Clayton", state: "MO", label: "Clayton, MO" },
|
{ city: "Clayton", state: "MO", label: "Clayton, MO" },
|
||||||
|
|
@ -147,7 +158,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());
|
const url = new URL(route.request().url());
|
||||||
state.listUrls.push(url.toString());
|
state.listUrls.push(url.toString());
|
||||||
if (options.listError && url.searchParams.get("pageSize") !== "1") {
|
if (options.listError && url.searchParams.get("pageSize") !== "1") {
|
||||||
|
|
@ -159,17 +170,54 @@ async function mockVendorApi(
|
||||||
const source = vendorRecords.filter((vendor) => vendor.IsActive === isActive);
|
const source = vendorRecords.filter((vendor) => vendor.IsActive === isActive);
|
||||||
const search = (url.searchParams.get("search") ?? "").toLowerCase();
|
const search = (url.searchParams.get("search") ?? "").toLowerCase();
|
||||||
const company = url.searchParams.get("companies[0]");
|
const company = url.searchParams.get("companies[0]");
|
||||||
|
const areas = [...url.searchParams.entries()]
|
||||||
|
.filter(([key]) => key.startsWith("areas["))
|
||||||
|
.map(([, value]) => value);
|
||||||
const filtered = source.filter(
|
const filtered = source.filter(
|
||||||
(vendor) =>
|
(vendor) =>
|
||||||
(!search ||
|
(!search ||
|
||||||
`${vendor.CompanyName} ${vendor.ContactName} ${vendor.TradeSpecialties} ${vendor.City} ${vendor.State}`
|
`${vendor.CompanyName} ${vendor.ContactName} ${vendor.TradeSpecialties} ${vendor.City} ${vendor.State}`
|
||||||
.toLowerCase()
|
.toLowerCase()
|
||||||
.includes(search)) &&
|
.includes(search)) &&
|
||||||
(!company || vendor.CompanyName === company),
|
(!company || vendor.CompanyName === company) &&
|
||||||
|
(areas.length === 0 ||
|
||||||
|
areas.some((area) =>
|
||||||
|
area === "__unassigned__" ? vendor.AreaId == null : String(vendor.AreaId) === area,
|
||||||
|
)),
|
||||||
);
|
);
|
||||||
const isCount = url.searchParams.get("pageSize") === "1";
|
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, {
|
await fulfillJson(route, {
|
||||||
Data: isCount ? filtered.slice(0, 1) : filtered,
|
Data: isCount ? responseRows.slice(0, 1) : responseRows,
|
||||||
TotalCount: filtered.length,
|
TotalCount: filtered.length,
|
||||||
PageNumber: 1,
|
PageNumber: 1,
|
||||||
PageSize: Number(url.searchParams.get("pageSize") ?? 12),
|
PageSize: Number(url.searchParams.get("pageSize") ?? 12),
|
||||||
|
|
@ -213,6 +261,8 @@ async function mockVendorApi(
|
||||||
zip: anchor.Zip,
|
zip: anchor.Zip,
|
||||||
googleMapsUrl: anchor.GoogleMapsUrl,
|
googleMapsUrl: anchor.GoogleMapsUrl,
|
||||||
notes: anchor.Notes,
|
notes: anchor.Notes,
|
||||||
|
areaId: anchor.AreaId,
|
||||||
|
areaName: anchor.AreaName,
|
||||||
technicians: [
|
technicians: [
|
||||||
...vendorRecords
|
...vendorRecords
|
||||||
.filter((vendor) => vendor.CompanyId === anchor.CompanyId)
|
.filter((vendor) => vendor.CompanyId === anchor.CompanyId)
|
||||||
|
|
@ -276,6 +326,8 @@ async function mockVendorApi(
|
||||||
zip: anchor.Zip,
|
zip: anchor.Zip,
|
||||||
googleMapsUrl: anchor.GoogleMapsUrl,
|
googleMapsUrl: anchor.GoogleMapsUrl,
|
||||||
notes: anchor.Notes,
|
notes: anchor.Notes,
|
||||||
|
areaId: anchor.AreaId,
|
||||||
|
areaName: anchor.AreaName,
|
||||||
technicians: vendorRecords
|
technicians: vendorRecords
|
||||||
.filter((vendor) => vendor.CompanyId === anchor.CompanyId)
|
.filter((vendor) => vendor.CompanyId === anchor.CompanyId)
|
||||||
.map((vendor) => ({
|
.map((vendor) => ({
|
||||||
|
|
@ -367,6 +419,44 @@ async function mockVendorApi(
|
||||||
}
|
}
|
||||||
|
|
||||||
test.describe("Vendor directory prototype parity", () => {
|
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",
|
||||||
|
"Service Area",
|
||||||
|
"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 ({
|
test("covers status tabs, global counts, search, facets, table fields, and filtered footer", async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
|
|
@ -381,21 +471,25 @@ test.describe("Vendor directory prototype parity", () => {
|
||||||
await expect(heading).toHaveCSS("font-weight", "800");
|
await expect(heading).toHaveCSS("font-weight", "800");
|
||||||
await expect(heading).toHaveCSS("line-height", "33px");
|
await expect(heading).toHaveCSS("line-height", "33px");
|
||||||
await expect(heading).toHaveCSS("letter-spacing", "-0.6px");
|
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(
|
await expect(page.getByRole("tab", { name: "Active (2)" })).toHaveAttribute(
|
||||||
"aria-selected",
|
"aria-selected",
|
||||||
"true",
|
"true",
|
||||||
);
|
);
|
||||||
for (const heading of [
|
for (const heading of [
|
||||||
"Company",
|
"Company",
|
||||||
"Technician",
|
"Company Phone",
|
||||||
"Location",
|
"Company Email",
|
||||||
|
"Street Address",
|
||||||
|
"City",
|
||||||
|
"State",
|
||||||
|
"Service Area",
|
||||||
"Trade",
|
"Trade",
|
||||||
"Phone",
|
"Technician",
|
||||||
"Email",
|
"Technician Phone",
|
||||||
"Total Jobs",
|
"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();
|
await expect(page.getByRole("columnheader", { name: "Status" })).toBeVisible();
|
||||||
const activeTabBox = await page.getByRole("tab", { name: "Active (2)" }).boundingBox();
|
const activeTabBox = await page.getByRole("tab", { name: "Active (2)" }).boundingBox();
|
||||||
|
|
@ -403,10 +497,11 @@ test.describe("Vendor directory prototype parity", () => {
|
||||||
const tableContainerBox = await page.locator("table").locator("..").boundingBox();
|
const tableContainerBox = await page.locator("table").locator("..").boundingBox();
|
||||||
expect(tableContainerBox).toMatchObject({ x: 260, y: 212.5, width: 1164 });
|
expect(tableContainerBox).toMatchObject({ x: 260, y: 212.5, width: 1164 });
|
||||||
expect(tableContainerBox?.height).toBeCloseTo(738, 0);
|
expect(tableContainerBox?.height).toBeCloseTo(738, 0);
|
||||||
expect((await page.locator("table").boundingBox())?.width).toBe(1550);
|
expect((await page.locator("table").boundingBox())?.width).toBe(2200);
|
||||||
expect((await page.getByRole("columnheader", { name: "Company" }).boundingBox())?.height).toBe(
|
expect(
|
||||||
47,
|
(await page.getByRole("columnheader", { name: "Company", exact: true }).boundingBox())
|
||||||
);
|
?.height,
|
||||||
|
).toBe(47);
|
||||||
expect((await page.locator("tbody tr").first().boundingBox())?.height).toBe(52);
|
expect((await page.locator("tbody tr").first().boundingBox())?.height).toBe(52);
|
||||||
await expect(page.getByText("Gateway Plumbing")).toBeVisible();
|
await expect(page.getByText("Gateway Plumbing")).toBeVisible();
|
||||||
const tradeBadge = page.getByTestId("vendor-trade-badge").first();
|
const tradeBadge = page.getByTestId("vendor-trade-badge").first();
|
||||||
|
|
@ -419,13 +514,13 @@ test.describe("Vendor directory prototype parity", () => {
|
||||||
await expect(page.getByRole("dialog")).toHaveCount(0);
|
await expect(page.getByRole("dialog")).toHaveCount(0);
|
||||||
await tradeBadge.press("Enter");
|
await tradeBadge.press("Enter");
|
||||||
await expect(page.getByRole("dialog")).toHaveCount(0);
|
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 expect(page.getByText("2 active · 1 inactive")).toBeVisible();
|
||||||
await captureVisual(page, "/tmp/seahaven-vendor-implemented-list.png");
|
await captureVisual(page, "/tmp/seahaven-vendor-implemented-list.png");
|
||||||
|
|
||||||
await page.getByPlaceholder("Search name, company, trade…").fill("metro");
|
await page.getByPlaceholder("Search name, company, trade…").fill("metro");
|
||||||
await expect(page.getByText("Metro HVAC")).toBeVisible();
|
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(
|
expect(state.listUrls.some((url) => new URL(url).searchParams.get("search") === "metro")).toBe(
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
|
|
@ -442,8 +537,8 @@ test.describe("Vendor directory prototype parity", () => {
|
||||||
await page.getByRole("option", { name: /Gateway Plumbing/ }).click();
|
await page.getByRole("option", { name: /Gateway Plumbing/ }).click();
|
||||||
await page.getByRole("button", { name: "Apply filters" }).click();
|
await page.getByRole("button", { name: "Apply filters" }).click();
|
||||||
await expect(page.getByText("Gateway Plumbing").first()).toBeVisible();
|
await expect(page.getByText("Gateway Plumbing").first()).toBeVisible();
|
||||||
await expect(page.getByText("1 technician · filtered by")).toBeVisible();
|
await expect(page.getByText("1 company · filtered by")).toBeVisible();
|
||||||
await expect(page.getByText(/1 active technician · filtered/)).toBeVisible();
|
await expect(page.getByText(/1 active company · filtered/)).toBeVisible();
|
||||||
expect(
|
expect(
|
||||||
state.listUrls.some(
|
state.listUrls.some(
|
||||||
(url) => new URL(url).searchParams.get("companies[0]") === "Gateway Plumbing",
|
(url) => new URL(url).searchParams.get("companies[0]") === "Gateway Plumbing",
|
||||||
|
|
@ -451,7 +546,7 @@ test.describe("Vendor directory prototype parity", () => {
|
||||||
).toBe(true);
|
).toBe(true);
|
||||||
|
|
||||||
await page.getByRole("tab", { name: "Inactive (1)" }).click();
|
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 page.getByRole("button", { name: "Clear all" }).click();
|
||||||
await expect(page.getByText("Drain Cleaning Bros")).toBeVisible();
|
await expect(page.getByText("Drain Cleaning Bros")).toBeVisible();
|
||||||
await expect(page.getByRole("columnheader", { name: "Status" })).toBeVisible();
|
await expect(page.getByRole("columnheader", { name: "Status" })).toBeVisible();
|
||||||
|
|
@ -466,10 +561,10 @@ test.describe("Vendor directory prototype parity", () => {
|
||||||
const row = page.locator("tbody tr").first();
|
const row = page.locator("tbody tr").first();
|
||||||
const fields = [
|
const fields = [
|
||||||
{ cellIndex: 0, testId: "vendor-text-company", value: LONG_TEXT_VENDOR.CompanyName },
|
{ 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-company-email", value: LONG_TEXT_VENDOR.Email },
|
||||||
{ cellIndex: 2, testId: "vendor-text-location", value: LONG_TEXT_VENDOR.Address },
|
{ cellIndex: 3, testId: "vendor-text-street-address", value: LONG_TEXT_VENDOR.Address },
|
||||||
{ cellIndex: 4, testId: "vendor-text-phone", value: LONG_TEXT_VENDOR.Phone },
|
{ cellIndex: 8, testId: "vendor-text-technician", value: LONG_TEXT_VENDOR.ContactName },
|
||||||
{ cellIndex: 5, testId: "vendor-text-email", value: LONG_TEXT_VENDOR.Email },
|
{ cellIndex: 9, testId: "vendor-text-technician-phone", value: LONG_TEXT_VENDOR.Phone },
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const expected of fields) {
|
for (const expected of fields) {
|
||||||
|
|
@ -603,7 +698,8 @@ test.describe("Vendor directory prototype parity", () => {
|
||||||
"1 Market St",
|
"1 Market St",
|
||||||
);
|
);
|
||||||
await expect(page.getByLabel("City (required)")).toHaveValue("St. Louis");
|
await expect(page.getByLabel("City (required)")).toHaveValue("St. Louis");
|
||||||
await expect(page.getByLabel("State (required)")).toHaveValue("MO");
|
await expect(page.getByLabel("State (required)")).toHaveValue("Missouri (MO)");
|
||||||
|
await expect(page.getByLabel("Service Area (optional)")).toHaveValue("East");
|
||||||
await expect(page.getByLabel("Google Maps URL (optional)")).toHaveCount(0);
|
await expect(page.getByLabel("Google Maps URL (optional)")).toHaveCount(0);
|
||||||
await expect(page.getByLabel("Address (optional)")).toHaveCount(0);
|
await expect(page.getByLabel("Address (optional)")).toHaveCount(0);
|
||||||
await expect(page.getByLabel("Preferred Contact")).toHaveCount(0);
|
await expect(page.getByLabel("Preferred Contact")).toHaveCount(0);
|
||||||
|
|
@ -676,6 +772,55 @@ test.describe("Vendor directory prototype parity", () => {
|
||||||
await expect.poll(() => state.updatedBody?.notes).toBe("Updated in browser E2E");
|
await expect.poll(() => state.updatedBody?.notes).toBe("Updated in browser E2E");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("filters by Service Area and lets an admin assign one", async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||||
|
const state = await mockVendorApi(page);
|
||||||
|
await page.goto("/vendors");
|
||||||
|
|
||||||
|
const gatewayRow = page.getByRole("button", {
|
||||||
|
name: "Open vendor details for Gateway Plumbing",
|
||||||
|
});
|
||||||
|
const metroRow = page.getByRole("button", { name: "Open vendor details for Metro HVAC" });
|
||||||
|
await expect(gatewayRow.getByTestId("vendor-text-service-area")).toHaveText("East");
|
||||||
|
await expect(metroRow.getByTestId("vendor-text-service-area")).toHaveText("Unassigned");
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: "Open vendor filters" }).click();
|
||||||
|
await page.getByRole("button", { name: "Service Area" }).click();
|
||||||
|
await page.getByPlaceholder("All areas").click();
|
||||||
|
await expect(page.getByRole("option")).toHaveText(["Unassigned", "Central", "East"]);
|
||||||
|
await page.getByRole("option", { name: "East" }).click();
|
||||||
|
await page.getByRole("button", { name: "Apply filters" }).click();
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
page.getByRole("button", { name: "Remove filter Service Area: East" }),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(gatewayRow).toBeVisible();
|
||||||
|
await expect(metroRow).toHaveCount(0);
|
||||||
|
expect(state.listUrls.some((url) => new URL(url).searchParams.get("areas[0]") === "1")).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: "Open vendor filters" }).click();
|
||||||
|
await page.getByRole("button", { name: "Service Area" }).click();
|
||||||
|
await page.getByRole("button", { name: "Clear all" }).last().click();
|
||||||
|
await page.getByPlaceholder("All areas").click();
|
||||||
|
await page.getByRole("option", { name: "Unassigned" }).click();
|
||||||
|
await page.getByRole("button", { name: "Apply filters" }).click();
|
||||||
|
await expect(page.getByText("Service Area: Unassigned")).toBeVisible();
|
||||||
|
await expect(metroRow).toBeVisible();
|
||||||
|
await expect(gatewayRow).toHaveCount(0);
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: "Edit vendor Metro HVAC" }).click();
|
||||||
|
const detailDrawer = page.locator(".MuiDrawer-paper").last();
|
||||||
|
const areaField = detailDrawer.getByRole("combobox", { name: "Service Area (optional)" });
|
||||||
|
await expect(areaField).toBeEnabled();
|
||||||
|
await areaField.click();
|
||||||
|
await page.getByRole("option", { name: "Central" }).click();
|
||||||
|
await detailDrawer.getByRole("button", { name: "Save changes" }).click();
|
||||||
|
await expect.poll(() => state.updatedBody?.areaId).toBe(2);
|
||||||
|
expect(state.updatedBody?.state).toBe("MO");
|
||||||
|
});
|
||||||
|
|
||||||
test("reactivates a legacy inactive vendor with an exact sparse update", async ({ page }) => {
|
test("reactivates a legacy inactive vendor with an exact sparse update", async ({ page }) => {
|
||||||
const state = await mockVendorApi(page, { legacyGateway: true });
|
const state = await mockVendorApi(page, { legacyGateway: true });
|
||||||
await page.goto("/vendors");
|
await page.goto("/vendors");
|
||||||
|
|
@ -719,11 +864,14 @@ test.describe("Vendor directory prototype parity", () => {
|
||||||
// leave those as the only things it is exercising.
|
// leave those as the only things it is exercising.
|
||||||
await page.getByRole("combobox", { name: "Street Address (required)" }).fill("1 Market St");
|
await page.getByRole("combobox", { name: "Street Address (required)" }).fill("1 Market St");
|
||||||
await page.getByLabel("City (required)").fill("St. Louis");
|
await page.getByLabel("City (required)").fill("St. Louis");
|
||||||
await page.getByLabel("State (required)").fill("MO");
|
await page.getByLabel("State (required)").fill("Missouri");
|
||||||
|
await page.getByRole("option", { name: "Missouri (MO)" }).click();
|
||||||
await page.getByRole("button", { name: "Add Vendor", exact: true }).last().click();
|
await page.getByRole("button", { name: "Add Vendor", exact: true }).last().click();
|
||||||
|
|
||||||
await expect.poll(() => state.createdBody?.name).toBe("Independent Vendor LLC");
|
await expect.poll(() => state.createdBody?.name).toBe("Independent Vendor LLC");
|
||||||
expect(state.createdBody?.technicians).toEqual([]);
|
expect(state.createdBody?.technicians).toEqual([]);
|
||||||
|
expect(state.createdBody?.state).toBe("MO");
|
||||||
|
expect(state.createdBody?.areaId).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("closes vendor details with Escape and keeps only Edit in the footer", async ({ page }) => {
|
test("closes vendor details with Escape and keeps only Edit in the footer", async ({ page }) => {
|
||||||
|
|
|
||||||
8
e2e/vendors/vendors.visual.spec.ts
vendored
|
|
@ -119,7 +119,7 @@ async function mockVendorApi(page: Page, mode: "default" | "empty" | "error" = "
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (url.pathname.endsWith("/api/Vendor/GetVendorList")) {
|
if (url.pathname.endsWith("/api/Vendor/GetVendorDirectoryList")) {
|
||||||
const isCount = url.searchParams.get("pageSize") === "1";
|
const isCount = url.searchParams.get("pageSize") === "1";
|
||||||
if (mode === "error" && !isCount) {
|
if (mode === "error" && !isCount) {
|
||||||
await fulfillJson(route, { message: "Vendor directory unavailable" }, 500);
|
await fulfillJson(route, { message: "Vendor directory unavailable" }, 500);
|
||||||
|
|
@ -243,8 +243,12 @@ test.describe("Vendor deterministic pixel regression", () => {
|
||||||
|
|
||||||
test("empty", async ({ page }) => {
|
test("empty", async ({ page }) => {
|
||||||
await openVendorPage(page, "empty");
|
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 expectStableScreenshot(page, "vendor-empty.png");
|
||||||
|
|
||||||
|
await page.setViewportSize({ width: 390, height: 844 });
|
||||||
|
await expect(emptyState).toBeInViewport();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("error", async ({ page }) => {
|
test("error", async ({ page }) => {
|
||||||
|
|
|
||||||
80
e2e/work-orders/due-date-schedule-floor.spec.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
||||||
|
import { expect, test, type Route } from "@playwright/test";
|
||||||
|
|
||||||
|
const FROZEN_NOW = "2026-08-19T15:00:00.000Z";
|
||||||
|
|
||||||
|
const TEST_USER = {
|
||||||
|
token: "due-date-floor-e2e-token",
|
||||||
|
expiration: "2030-01-01T00:00:00.000Z",
|
||||||
|
email: "admin@seahavenind.com",
|
||||||
|
userRoles: "Admin",
|
||||||
|
phoneNumber: "5551234567",
|
||||||
|
fullname: "Work Order E2E Admin",
|
||||||
|
id: "1",
|
||||||
|
};
|
||||||
|
|
||||||
|
async function fulfillJson(route: Route, body: unknown, status = 200) {
|
||||||
|
await route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
|
||||||
|
}
|
||||||
|
|
||||||
|
test.describe("Due Date floor in the Create WO wizard (SH-356)", () => {
|
||||||
|
test.setTimeout(60_000);
|
||||||
|
|
||||||
|
test("disables days before Schedule On and clears Due Date when Schedule On passes it", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.clock.install({ time: new Date(FROZEN_NOW) });
|
||||||
|
await page.clock.resume();
|
||||||
|
await page.addInitScript((user) => {
|
||||||
|
localStorage.setItem("auth", JSON.stringify(user));
|
||||||
|
const style = document.createElement("style");
|
||||||
|
style.textContent = ".tsqd-parent-container { display: none !important; }";
|
||||||
|
document.documentElement.appendChild(style);
|
||||||
|
}, TEST_USER);
|
||||||
|
await page.route(
|
||||||
|
(url) => url.pathname.startsWith("/api/"),
|
||||||
|
async (route) => {
|
||||||
|
if (route.request().method() !== "GET") {
|
||||||
|
await fulfillJson(route, {}, 500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await fulfillJson(route, {
|
||||||
|
data: [],
|
||||||
|
items: [],
|
||||||
|
weekStart: "2026-08-17",
|
||||||
|
weekEnd: "2026-08-21",
|
||||||
|
counts: { returned: 0, total: 0 },
|
||||||
|
unscheduled: [],
|
||||||
|
scheduled: [],
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
await page.goto("/workorders");
|
||||||
|
await page.getByRole("button", { name: "New WO" }).click();
|
||||||
|
await expect(page.getByRole("heading", { name: "Type & schedule" })).toBeVisible({
|
||||||
|
timeout: 20_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: /Pick a date/ }).click();
|
||||||
|
const dateTab = page.getByRole("button", { name: "Date", exact: true });
|
||||||
|
if (await dateTab.isVisible()) {
|
||||||
|
await dateTab.click();
|
||||||
|
}
|
||||||
|
await page.getByRole("button", { name: "20", exact: true }).click();
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: /No due date/ }).click();
|
||||||
|
await expect(page.getByRole("button", { name: "19", exact: true })).toBeDisabled();
|
||||||
|
await expect(page.getByRole("button", { name: "20", exact: true })).toBeEnabled();
|
||||||
|
await page.getByRole("button", { name: "21", exact: true }).click();
|
||||||
|
await expect(page.getByRole("button", { name: /No due date/ })).toHaveCount(0);
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: /Aug 20/ }).click();
|
||||||
|
const dateTabAgain = page.getByRole("button", { name: "Date", exact: true });
|
||||||
|
if (await dateTabAgain.isVisible()) {
|
||||||
|
await dateTabAgain.click();
|
||||||
|
}
|
||||||
|
await page.getByRole("button", { name: "25", exact: true }).click();
|
||||||
|
|
||||||
|
await expect(page.getByRole("button", { name: /No due date/ })).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
121
e2e/work-orders/wo-number-sh-placeholder.spec.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
||||||
|
import { expect, test, type Page, type Route } from "@playwright/test";
|
||||||
|
|
||||||
|
const FROZEN_NOW = "2026-08-19T15:00:00.000Z";
|
||||||
|
|
||||||
|
const TEST_USER = {
|
||||||
|
token: "wo-number-sh-placeholder-e2e-token",
|
||||||
|
expiration: "2030-01-01T00:00:00.000Z",
|
||||||
|
email: "admin@seahavenind.com",
|
||||||
|
userRoles: "Admin",
|
||||||
|
phoneNumber: "5551234567",
|
||||||
|
fullname: "Work Order E2E Admin",
|
||||||
|
id: "1",
|
||||||
|
};
|
||||||
|
|
||||||
|
async function fulfillJson(route: Route, body: unknown, status = 200) {
|
||||||
|
await route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function hideQueryDevtools(page: Page) {
|
||||||
|
await page.addStyleTag({
|
||||||
|
content:
|
||||||
|
".tsqd-parent-container { display: none !important; pointer-events: none !important; }",
|
||||||
|
});
|
||||||
|
await page.locator(".tsqd-parent-container").evaluateAll((nodes) => {
|
||||||
|
for (const node of nodes) {
|
||||||
|
node.remove();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const REAL_ROW = {
|
||||||
|
id: 1000,
|
||||||
|
woNumber: "12345678901",
|
||||||
|
workOrderType: 2,
|
||||||
|
siteCode: "DAL1",
|
||||||
|
lifecycleStatusLabel: "Scheduled",
|
||||||
|
scheduledDate: "2026-08-19",
|
||||||
|
dispatcherId: "1",
|
||||||
|
dispatcherName: "Pat Dispatcher",
|
||||||
|
pm: "HVAC",
|
||||||
|
};
|
||||||
|
|
||||||
|
async function mockBoard(page: Page, patches: unknown[]) {
|
||||||
|
await page.route(
|
||||||
|
(url) => url.pathname.startsWith("/api/"),
|
||||||
|
async (route) => {
|
||||||
|
const request = route.request();
|
||||||
|
const url = request.url();
|
||||||
|
if (request.method() !== "GET") {
|
||||||
|
patches.push({ url, body: request.postDataJSON() });
|
||||||
|
await fulfillJson(route, {}, 500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (url.includes("workorders/board/search")) {
|
||||||
|
await fulfillJson(route, { items: [REAL_ROW], totalCount: 1, page: 0, pageSize: 50 });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (url.includes("workorders/board")) {
|
||||||
|
await fulfillJson(route, {
|
||||||
|
weekStart: "2026-08-17",
|
||||||
|
weekEnd: "2026-08-21",
|
||||||
|
counts: { returned: 1, total: 1 },
|
||||||
|
unscheduled: [],
|
||||||
|
scheduled: [REAL_ROW],
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await fulfillJson(route, { data: [], items: [] });
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
test.describe("inline WO number SH placeholder", () => {
|
||||||
|
test.setTimeout(60_000);
|
||||||
|
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await page.clock.install({ time: new Date(FROZEN_NOW) });
|
||||||
|
await page.clock.resume();
|
||||||
|
await page.addInitScript((user) => {
|
||||||
|
localStorage.setItem("auth", JSON.stringify(user));
|
||||||
|
}, TEST_USER);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps a typed SH number on a new inline row and blocks downgrading a saved real number", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const mutations: unknown[] = [];
|
||||||
|
await mockBoard(page, mutations);
|
||||||
|
await page.goto("/workorders");
|
||||||
|
await hideQueryDevtools(page);
|
||||||
|
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible({
|
||||||
|
timeout: 20_000,
|
||||||
|
});
|
||||||
|
await expect(page.getByText("12345678901").first()).toBeVisible();
|
||||||
|
|
||||||
|
await page
|
||||||
|
.getByRole("button", { name: /Add WO/ })
|
||||||
|
.first()
|
||||||
|
.click();
|
||||||
|
await page
|
||||||
|
.getByText(/^Insert WO #/)
|
||||||
|
.first()
|
||||||
|
.click();
|
||||||
|
const draftInput = page.getByLabel("Work order number");
|
||||||
|
await draftInput.fill("SH00001");
|
||||||
|
await draftInput.press("Enter");
|
||||||
|
await expect(draftInput).toHaveCount(0);
|
||||||
|
await expect(page.getByText("SH00001", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByText(/must be 11 digits/)).toHaveCount(0);
|
||||||
|
|
||||||
|
await page.getByText("12345678901", { exact: true }).first().click();
|
||||||
|
const savedInput = page.getByLabel("Work order number");
|
||||||
|
await savedInput.fill("SH00009");
|
||||||
|
await savedInput.press("Enter");
|
||||||
|
await expect(
|
||||||
|
page.getByText("Cannot replace an APM work order number with an internal number"),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(page.getByText("12345678901", { exact: true }).first()).toBeVisible();
|
||||||
|
expect(mutations).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -204,6 +204,12 @@ async function openWorkOrderPage(page: Page, mode: "default" | "empty" | "error"
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function expectWorkOrderPageReady(page: Page) {
|
||||||
|
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible({
|
||||||
|
timeout: 90_000,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async function expectStableScreenshot(page: Page, name: string) {
|
async function expectStableScreenshot(page: Page, name: string) {
|
||||||
await page.waitForTimeout(250);
|
await page.waitForTimeout(250);
|
||||||
await page.evaluate(
|
await page.evaluate(
|
||||||
|
|
@ -217,15 +223,18 @@ async function expectStableScreenshot(page: Page, name: string) {
|
||||||
}
|
}
|
||||||
|
|
||||||
test.describe("Work Orders deterministic pixel regression", () => {
|
test.describe("Work Orders deterministic pixel regression", () => {
|
||||||
|
test.setTimeout(120_000);
|
||||||
|
|
||||||
test("list", async ({ page }) => {
|
test("list", async ({ page }) => {
|
||||||
await openWorkOrderPage(page);
|
await openWorkOrderPage(page);
|
||||||
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible();
|
await expectWorkOrderPageReady(page);
|
||||||
await expect(page.getByText("WO-501").first()).toBeVisible();
|
await expect(page.getByText("WO-501").first()).toBeVisible();
|
||||||
await expectStableScreenshot(page, "wo-list.png");
|
await expectStableScreenshot(page, "wo-list.png");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("filters", async ({ page }) => {
|
test("filters", async ({ page }) => {
|
||||||
await openWorkOrderPage(page);
|
await openWorkOrderPage(page);
|
||||||
|
await expectWorkOrderPageReady(page);
|
||||||
await page.getByRole("button", { name: "Advanced Filters" }).click();
|
await page.getByRole("button", { name: "Advanced Filters" }).click();
|
||||||
await expect(page.getByRole("dialog", { name: "Advanced Filters" })).toBeVisible();
|
await expect(page.getByRole("dialog", { name: "Advanced Filters" })).toBeVisible();
|
||||||
await expectStableScreenshot(page, "wo-filters.png");
|
await expectStableScreenshot(page, "wo-filters.png");
|
||||||
|
|
@ -233,6 +242,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
|
||||||
|
|
||||||
test("new", async ({ page }) => {
|
test("new", async ({ page }) => {
|
||||||
await openWorkOrderPage(page);
|
await openWorkOrderPage(page);
|
||||||
|
await expectWorkOrderPageReady(page);
|
||||||
await page.getByRole("button", { name: "New WO" }).click();
|
await page.getByRole("button", { name: "New WO" }).click();
|
||||||
await expect(page.getByRole("heading", { name: "Type & schedule" })).toBeVisible();
|
await expect(page.getByRole("heading", { name: "Type & schedule" })).toBeVisible();
|
||||||
await expectStableScreenshot(page, "wo-new.png");
|
await expectStableScreenshot(page, "wo-new.png");
|
||||||
|
|
@ -240,6 +250,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
|
||||||
|
|
||||||
test("detail", async ({ page }) => {
|
test("detail", async ({ page }) => {
|
||||||
await openWorkOrderPage(page);
|
await openWorkOrderPage(page);
|
||||||
|
await expectWorkOrderPageReady(page);
|
||||||
const row = page.locator("#wo-row-1");
|
const row = page.locator("#wo-row-1");
|
||||||
await row.hover();
|
await row.hover();
|
||||||
await row.getByRole("button", { name: "View details" }).click();
|
await row.getByRole("button", { name: "View details" }).click();
|
||||||
|
|
@ -249,7 +260,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
|
||||||
|
|
||||||
test("empty", async ({ page }) => {
|
test("empty", async ({ page }) => {
|
||||||
await openWorkOrderPage(page, "empty");
|
await openWorkOrderPage(page, "empty");
|
||||||
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible();
|
await expectWorkOrderPageReady(page);
|
||||||
await page.getByLabel("Search work orders").fill("zz");
|
await page.getByLabel("Search work orders").fill("zz");
|
||||||
await expect(page.getByText("No work orders match your search")).toBeVisible();
|
await expect(page.getByText("No work orders match your search")).toBeVisible();
|
||||||
await expectStableScreenshot(page, "wo-empty.png");
|
await expectStableScreenshot(page, "wo-empty.png");
|
||||||
|
|
@ -257,7 +268,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
|
||||||
|
|
||||||
test("error", async ({ page }) => {
|
test("error", async ({ page }) => {
|
||||||
await openWorkOrderPage(page, "error");
|
await openWorkOrderPage(page, "error");
|
||||||
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible();
|
await expectWorkOrderPageReady(page);
|
||||||
const alert = page.getByRole("main").getByRole("alert");
|
const alert = page.getByRole("main").getByRole("alert");
|
||||||
await expect(alert).toBeVisible();
|
await expect(alert).toBeVisible();
|
||||||
await expect(alert).toContainText(/server error/i);
|
await expect(alert).toContainText(/server error/i);
|
||||||
|
|
@ -267,6 +278,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
|
||||||
test("mobile", async ({ page }) => {
|
test("mobile", async ({ page }) => {
|
||||||
await page.setViewportSize({ width: 390, height: 844 });
|
await page.setViewportSize({ width: 390, height: 844 });
|
||||||
await openWorkOrderPage(page);
|
await openWorkOrderPage(page);
|
||||||
|
await expectWorkOrderPageReady(page);
|
||||||
await expect(page.getByText("WO-501").first()).toBeVisible();
|
await expect(page.getByText("WO-501").first()).toBeVisible();
|
||||||
await expectStableScreenshot(page, "wo-mobile.png");
|
await expectStableScreenshot(page, "wo-mobile.png");
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -77,6 +77,9 @@ export const API_PATHS = {
|
||||||
deleteEmployees: "Employee/DeleteEmployees",
|
deleteEmployees: "Employee/DeleteEmployees",
|
||||||
dropdown: "Employee/Dropdown",
|
dropdown: "Employee/Dropdown",
|
||||||
},
|
},
|
||||||
|
teamMember: {
|
||||||
|
getList: "User",
|
||||||
|
},
|
||||||
contact: {
|
contact: {
|
||||||
getList: "Contact/GetContactList",
|
getList: "Contact/GetContactList",
|
||||||
getContacts: "Contact/GetContacts",
|
getContacts: "Contact/GetContacts",
|
||||||
|
|
@ -125,6 +128,7 @@ export const API_PATHS = {
|
||||||
},
|
},
|
||||||
vendor: {
|
vendor: {
|
||||||
getList: "Vendor/GetVendorList",
|
getList: "Vendor/GetVendorList",
|
||||||
|
getDirectoryList: "Vendor/GetVendorDirectoryList",
|
||||||
getById: "Vendor/GetById",
|
getById: "Vendor/GetById",
|
||||||
create: "Vendor/Create",
|
create: "Vendor/Create",
|
||||||
update: "Vendor/Update",
|
update: "Vendor/Update",
|
||||||
|
|
@ -154,6 +158,9 @@ export const API_PATHS = {
|
||||||
update: "DropdownOptions/Update",
|
update: "DropdownOptions/Update",
|
||||||
delete: "DropdownOptions",
|
delete: "DropdownOptions",
|
||||||
},
|
},
|
||||||
|
services: {
|
||||||
|
list: "services",
|
||||||
|
},
|
||||||
user: {
|
user: {
|
||||||
list: "User",
|
list: "User",
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -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 { AccountListItem } from "@/domain/accounts/types/account";
|
||||||
import type { LocationFormValues } from "@/domain/locations/schemas/location-schema";
|
import type { LocationFormValues } from "@/domain/locations/schemas/location-schema";
|
||||||
import { LOCATION_STATUS_OPTIONS } from "@/domain/locations/types/location";
|
import { LOCATION_STATUS_OPTIONS } from "@/domain/locations/types/location";
|
||||||
|
import { LocationContactsFieldArray } from "./location-contacts-field-array";
|
||||||
import { StateSelect } from "./state-select";
|
import { StateSelect } from "./state-select";
|
||||||
|
|
||||||
interface SharedFieldsProps {
|
interface SharedFieldsProps {
|
||||||
|
|
@ -109,24 +110,7 @@ export function LocationContactFields({ control, errors, register }: SharedField
|
||||||
<Typography variant="subtitle1" className="font-semibold">
|
<Typography variant="subtitle1" className="font-semibold">
|
||||||
Contact Information
|
Contact Information
|
||||||
</Typography>
|
</Typography>
|
||||||
<Stack direction={{ xs: "column", md: "row" }} spacing={2}>
|
<LocationContactsFieldArray control={control} errors={errors} register={register} />
|
||||||
<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>
|
|
||||||
<Stack direction={{ xs: "column", md: "row" }} spacing={2}>
|
<Stack direction={{ xs: "column", md: "row" }} spacing={2}>
|
||||||
<TextField
|
<TextField
|
||||||
{...register("contactEmail")}
|
{...register("contactEmail")}
|
||||||
|
|
|
||||||
|
|
@ -55,8 +55,10 @@ export default function LocationFormPage() {
|
||||||
city: location.city ?? "",
|
city: location.city ?? "",
|
||||||
state: normalizeStateCode(location.state) ?? "",
|
state: normalizeStateCode(location.state) ?? "",
|
||||||
zipCode: location.zipCode ?? "",
|
zipCode: location.zipCode ?? "",
|
||||||
phone: location.phone ?? "",
|
contacts:
|
||||||
contact: location.contact ?? "",
|
location.contacts && location.contacts.length > 0
|
||||||
|
? location.contacts
|
||||||
|
: [{ name: location.contact ?? "", phone: location.phone ?? "" }],
|
||||||
contactEmail: location.contactEmail ?? "",
|
contactEmail: location.contactEmail ?? "",
|
||||||
status: (location.status as LocationFormValues["status"]) || "Active",
|
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,
|
Typography,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import type { LocationListItem } from "@/domain/locations/types/location";
|
import type { LocationListItem } from "@/domain/locations/types/location";
|
||||||
|
import { LocationsContactsCell } from "./locations-contacts-cell";
|
||||||
import { StateAreaCell } from "./state-area-cell";
|
import { StateAreaCell } from "./state-area-cell";
|
||||||
|
|
||||||
interface LocationsTableProps {
|
interface LocationsTableProps {
|
||||||
|
|
@ -74,7 +75,9 @@ export function LocationsTable({ isLoading, onDelete, onEdit, rows }: LocationsT
|
||||||
<StateAreaCell state={row.state} />
|
<StateAreaCell state={row.state} />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>{row.phone || "—"}</TableCell>
|
<TableCell>{row.phone || "—"}</TableCell>
|
||||||
<TableCell>{row.contact || "—"}</TableCell>
|
<TableCell>
|
||||||
|
<LocationsContactsCell row={row} />
|
||||||
|
</TableCell>
|
||||||
<TableCell>{row.status || "—"}</TableCell>
|
<TableCell>{row.status || "—"}</TableCell>
|
||||||
<TableCell align="right">
|
<TableCell align="right">
|
||||||
<Tooltip title="Edit">
|
<Tooltip title="Edit">
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,110 @@
|
||||||
|
import {
|
||||||
|
Avatar,
|
||||||
|
Button,
|
||||||
|
CircularProgress,
|
||||||
|
Paper,
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableContainer,
|
||||||
|
TableHead,
|
||||||
|
TableRow,
|
||||||
|
Typography,
|
||||||
|
} from "@mui/material";
|
||||||
|
import type { TeamMemberListItem } from "@/domain/team-members/types/team-member";
|
||||||
|
|
||||||
|
const HEADINGS = ["Team Member", "Role", "Service Area", "Phone", "Email", "Color", "Status"];
|
||||||
|
|
||||||
|
function memberStatusLabel(status: TeamMemberListItem["status"]) {
|
||||||
|
return status === "Active" ? "Active" : "Inactive";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TeamMembersTable({
|
||||||
|
rows,
|
||||||
|
isLoading,
|
||||||
|
hasError,
|
||||||
|
tab,
|
||||||
|
onOpen,
|
||||||
|
}: {
|
||||||
|
rows: TeamMemberListItem[];
|
||||||
|
isLoading: boolean;
|
||||||
|
hasError: boolean;
|
||||||
|
tab: "active" | "inactive";
|
||||||
|
onOpen: (member: TeamMemberListItem) => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<TableContainer component={Paper} variant="outlined">
|
||||||
|
<Table stickyHeader size="small" sx={{ minWidth: 900 }}>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
{HEADINGS.map((heading) => (
|
||||||
|
<TableCell key={heading} className="font-semibold">
|
||||||
|
{heading}
|
||||||
|
</TableCell>
|
||||||
|
))}
|
||||||
|
<TableCell align="right" className="font-semibold">
|
||||||
|
Actions
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{isLoading ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={8} align="center" sx={{ py: 8 }}>
|
||||||
|
<CircularProgress size={28} />
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : hasError ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={8} align="center" sx={{ py: 8 }}>
|
||||||
|
<Typography sx={{ fontWeight: 600 }}>Unable to load team members</Typography>
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
Check your connection and try again.
|
||||||
|
</Typography>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : rows.length === 0 ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={8} align="center" sx={{ py: 8 }}>
|
||||||
|
<Typography sx={{ fontWeight: 600 }}>No {tab} team members found</Typography>
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
Try a different search, or add a new team member.
|
||||||
|
</Typography>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : (
|
||||||
|
rows.map((member) => (
|
||||||
|
<TableRow
|
||||||
|
key={String(member.id)}
|
||||||
|
hover
|
||||||
|
onClick={() => onOpen(member)}
|
||||||
|
sx={{ cursor: "pointer" }}
|
||||||
|
>
|
||||||
|
<TableCell>{member.name || "—"}</TableCell>
|
||||||
|
<TableCell>{member.role || "—"}</TableCell>
|
||||||
|
<TableCell>{member.serviceArea || "—"}</TableCell>
|
||||||
|
<TableCell>{member.phone || "—"}</TableCell>
|
||||||
|
<TableCell>{member.email || "—"}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Avatar sx={{ width: 22, height: 22, bgcolor: member.color || "primary.main" }} />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{memberStatusLabel(member.status)}</TableCell>
|
||||||
|
<TableCell align="right">
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
onClick={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
onOpen(member);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
View
|
||||||
|
</Button>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</TableContainer>
|
||||||
|
);
|
||||||
|
}
|
||||||
193
src/app/(protected)/team-members/index.tsx
Normal file
|
|
@ -0,0 +1,193 @@
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useDebounce } from "@/hooks/use-debounce";
|
||||||
|
import { useTeamMembersList } from "@/domain/team-members/use-cases/use-team-members-list";
|
||||||
|
import type { TeamMemberListItem } from "@/domain/team-members/types/team-member";
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Avatar,
|
||||||
|
Box,
|
||||||
|
Button,
|
||||||
|
Chip,
|
||||||
|
Dialog,
|
||||||
|
DialogActions,
|
||||||
|
DialogContent,
|
||||||
|
DialogTitle,
|
||||||
|
Drawer,
|
||||||
|
IconButton,
|
||||||
|
Stack,
|
||||||
|
Tab,
|
||||||
|
Tabs,
|
||||||
|
TextField,
|
||||||
|
Typography,
|
||||||
|
} from "@mui/material";
|
||||||
|
import CloseIcon from "@mui/icons-material/Close";
|
||||||
|
import { TeamMembersTable } from "./_components/team-members-table";
|
||||||
|
|
||||||
|
type StatusTab = "active" | "inactive";
|
||||||
|
|
||||||
|
const STATUS_LABELS: Record<StatusTab, "Active" | "Inactive"> = {
|
||||||
|
active: "Active",
|
||||||
|
inactive: "Inactive",
|
||||||
|
};
|
||||||
|
|
||||||
|
function MemberStatus({ status }: { status: TeamMemberListItem["status"] }) {
|
||||||
|
return <Chip size="small" label={status} color={status === "Active" ? "success" : "default"} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function TeamMemberDrawer({
|
||||||
|
member,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
member: TeamMemberListItem | null;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<Drawer anchor="right" open={Boolean(member)} onClose={onClose}>
|
||||||
|
<Box sx={{ width: { xs: "100vw", sm: 380 }, p: 3 }}>
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
sx={{ alignItems: "center", justifyContent: "space-between", mb: 3 }}
|
||||||
|
>
|
||||||
|
<Typography variant="h6">Team Member</Typography>
|
||||||
|
<IconButton aria-label="Close team member details" onClick={onClose}>
|
||||||
|
<CloseIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Stack>
|
||||||
|
{member !== null && (
|
||||||
|
<Stack spacing={2}>
|
||||||
|
<Stack direction="row" spacing={2} sx={{ alignItems: "center" }}>
|
||||||
|
<Avatar sx={{ bgcolor: member.color || "primary.main" }}>
|
||||||
|
{member.name.slice(0, 1).toUpperCase() || "?"}
|
||||||
|
</Avatar>
|
||||||
|
<Box>
|
||||||
|
<Typography variant="h6">{member.name || "—"}</Typography>
|
||||||
|
<Typography color="text.secondary">{member.role || "—"}</Typography>
|
||||||
|
</Box>
|
||||||
|
</Stack>
|
||||||
|
<MemberStatus status={member.status} />
|
||||||
|
<Typography>
|
||||||
|
<strong>Service Area:</strong> {member.serviceArea || "—"}
|
||||||
|
</Typography>
|
||||||
|
<Typography>
|
||||||
|
<strong>Phone:</strong> {member.phone || "—"}
|
||||||
|
</Typography>
|
||||||
|
<Typography>
|
||||||
|
<strong>Email:</strong> {member.email || "—"}
|
||||||
|
</Typography>
|
||||||
|
</Stack>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Drawer>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function TeamMembersListPage() {
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
|
const [tab, setTab] = useState<StatusTab>("active");
|
||||||
|
const [selectedMember, setSelectedMember] = useState<TeamMemberListItem | null>(null);
|
||||||
|
const [addMemberOpen, setAddMemberOpen] = useState(false);
|
||||||
|
const debouncedSearch = useDebounce(search, 300).trim().toLowerCase();
|
||||||
|
const { data, isLoading, error } = useTeamMembersList();
|
||||||
|
const allMembers = data?.items ?? [];
|
||||||
|
|
||||||
|
const activeCount = allMembers.filter((member) => member.status === "Active").length;
|
||||||
|
const inactiveCount = allMembers.length - activeCount;
|
||||||
|
const rows = allMembers
|
||||||
|
.filter((member) => member.status === STATUS_LABELS[tab])
|
||||||
|
.filter((member) => !debouncedSearch || member.name.toLowerCase().includes(debouncedSearch));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
className="flex h-full flex-col overflow-hidden"
|
||||||
|
sx={{ backgroundColor: "var(--color-bg-page)" }}
|
||||||
|
>
|
||||||
|
<Stack
|
||||||
|
direction={{ xs: "column", sm: "row" }}
|
||||||
|
spacing={2}
|
||||||
|
sx={{
|
||||||
|
alignItems: { xs: "stretch", sm: "center" },
|
||||||
|
justifyContent: "space-between",
|
||||||
|
p: 2.5,
|
||||||
|
backgroundColor: "var(--color-bg-surface)",
|
||||||
|
borderBottom: "1px solid var(--color-border)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box>
|
||||||
|
<Typography variant="h4" component="h1">
|
||||||
|
Team Members
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.75 }}>
|
||||||
|
{allMembers.length} team member{allMembers.length === 1 ? "" : "s"} · {activeCount}{" "}
|
||||||
|
active
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
<Stack direction="row" spacing={1} sx={{ alignItems: "center" }}>
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
value={search}
|
||||||
|
onChange={(event) => setSearch(event.target.value)}
|
||||||
|
placeholder="Search team member…"
|
||||||
|
aria-label="Search team member"
|
||||||
|
sx={{ width: 224 }}
|
||||||
|
/>
|
||||||
|
<Button variant="contained" size="small" onClick={() => setAddMemberOpen(true)}>
|
||||||
|
Add Member
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<Tabs
|
||||||
|
value={tab}
|
||||||
|
onChange={(_event, value: StatusTab) => setTab(value)}
|
||||||
|
aria-label="Team member status"
|
||||||
|
>
|
||||||
|
<Tab value="active" label={`Active ${activeCount}`} />
|
||||||
|
<Tab value="inactive" label={`Inactive ${inactiveCount}`} />
|
||||||
|
</Tabs>
|
||||||
|
|
||||||
|
{Boolean(error) && (
|
||||||
|
<Alert severity="error">
|
||||||
|
{error instanceof Error ? error.message : "Failed to load team members"}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Box sx={{ flex: 1, overflow: "auto", p: 2 }}>
|
||||||
|
<TeamMembersTable
|
||||||
|
rows={rows}
|
||||||
|
isLoading={isLoading}
|
||||||
|
hasError={Boolean(error)}
|
||||||
|
tab={tab}
|
||||||
|
onOpen={setSelectedMember}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
sx={{
|
||||||
|
justifyContent: "space-between",
|
||||||
|
px: 2,
|
||||||
|
py: 1,
|
||||||
|
borderTop: "1px solid var(--color-border)",
|
||||||
|
backgroundColor: "var(--color-bg-surface)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{rows.length} {tab} team member{rows.length === 1 ? "" : "s"}
|
||||||
|
{debouncedSearch ? " · filtered" : ""}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{activeCount} active · {inactiveCount} inactive
|
||||||
|
</Typography>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<TeamMemberDrawer member={selectedMember} onClose={() => setSelectedMember(null)} />
|
||||||
|
<Dialog open={addMemberOpen} onClose={() => setAddMemberOpen(false)}>
|
||||||
|
<DialogTitle>Add Member</DialogTitle>
|
||||||
|
<DialogContent>Member details will be added here.</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button onClick={() => setAddMemberOpen(false)}>Close</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -16,6 +16,7 @@ export interface VendorListState {
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
companies: string[];
|
companies: string[];
|
||||||
trades: string[];
|
trades: string[];
|
||||||
|
areas: string[];
|
||||||
locations: string[];
|
locations: string[];
|
||||||
jobBuckets: string[];
|
jobBuckets: string[];
|
||||||
};
|
};
|
||||||
|
|
@ -45,6 +46,7 @@ export function useVendorListState(): VendorListState {
|
||||||
isActive,
|
isActive,
|
||||||
companies: appliedFilters.companies,
|
companies: appliedFilters.companies,
|
||||||
trades: appliedFilters.trades,
|
trades: appliedFilters.trades,
|
||||||
|
areas: appliedFilters.areas,
|
||||||
locations: appliedFilters.locations,
|
locations: appliedFilters.locations,
|
||||||
jobBuckets: appliedFilters.jobBuckets,
|
jobBuckets: appliedFilters.jobBuckets,
|
||||||
}),
|
}),
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useCallback, useMemo, useState } from "react";
|
import { useCallback, useContext, useMemo, useState } from "react";
|
||||||
import { toast } from "react-toastify";
|
import { toast } from "react-toastify";
|
||||||
import { useForm, useWatch, type FieldErrors } from "react-hook-form";
|
import { useForm, useWatch, type FieldErrors } from "react-hook-form";
|
||||||
import {
|
import {
|
||||||
|
|
@ -15,6 +15,8 @@ import {
|
||||||
type EditedCompanyFields,
|
type EditedCompanyFields,
|
||||||
} from "@/domain/vendors/use-cases/use-save-vendor-company-roster";
|
} from "@/domain/vendors/use-cases/use-save-vendor-company-roster";
|
||||||
import { useVendorRosterResolver } from "./use-vendor-roster-resolver";
|
import { useVendorRosterResolver } from "./use-vendor-roster-resolver";
|
||||||
|
import { AuthContext } from "@/providers/auth-context";
|
||||||
|
import { isAdminUser } from "@/lib/auth/user-utils";
|
||||||
|
|
||||||
const VENDOR_ROSTER_NO_CHANGES_MESSAGE =
|
const VENDOR_ROSTER_NO_CHANGES_MESSAGE =
|
||||||
"No changes to save. Enter technician details or update a company field.";
|
"No changes to save. Enter technician details or update a company field.";
|
||||||
|
|
@ -28,6 +30,7 @@ const EDITABLE_COMPANY_FIELDS = [
|
||||||
"state",
|
"state",
|
||||||
"zip",
|
"zip",
|
||||||
"notes",
|
"notes",
|
||||||
|
"areaId",
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -48,10 +51,21 @@ import { useVendorFacets } from "@/domain/vendors/use-cases/use-vendor-facets";
|
||||||
import { isVendorRosterConflictError } from "@/domain/vendors/lib/vendor-roster-conflict";
|
import { isVendorRosterConflictError } from "@/domain/vendors/lib/vendor-roster-conflict";
|
||||||
import type {
|
import type {
|
||||||
VendorCompanyRoster,
|
VendorCompanyRoster,
|
||||||
|
VendorFacetArea,
|
||||||
VendorFacetCompany,
|
VendorFacetCompany,
|
||||||
VendorRosterConflict,
|
VendorRosterConflict,
|
||||||
} from "@/domain/vendors/types/vendor";
|
} from "@/domain/vendors/types/vendor";
|
||||||
|
|
||||||
|
export interface VendorRosterAreaFieldProps {
|
||||||
|
areaOptions: VendorFacetArea[];
|
||||||
|
currentArea: VendorFacetArea | null;
|
||||||
|
canAssignArea: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toCurrentArea(roster: VendorCompanyRoster | null | undefined): VendorFacetArea | null {
|
||||||
|
return roster && roster.areaId !== "" ? { id: roster.areaId, name: roster.areaName } : null;
|
||||||
|
}
|
||||||
|
|
||||||
function withoutBlankNewTechnicians(
|
function withoutBlankNewTechnicians(
|
||||||
values: VendorCompanyRosterFormValues,
|
values: VendorCompanyRosterFormValues,
|
||||||
): VendorCompanyRosterFormValues {
|
): VendorCompanyRosterFormValues {
|
||||||
|
|
@ -96,6 +110,7 @@ export interface VendorRosterForm {
|
||||||
companies: VendorFacetCompany[];
|
companies: VendorFacetCompany[];
|
||||||
trades: string[];
|
trades: string[];
|
||||||
tradesLoading: boolean;
|
tradesLoading: boolean;
|
||||||
|
areaField: VendorRosterAreaFieldProps;
|
||||||
selectedCompanyId: string | number | null;
|
selectedCompanyId: string | number | null;
|
||||||
selectCompany: (company: VendorFacetCompany | null) => Promise<void>;
|
selectCompany: (company: VendorFacetCompany | null) => Promise<void>;
|
||||||
clearSelectedCompany: (nextName?: string) => void;
|
clearSelectedCompany: (nextName?: string) => void;
|
||||||
|
|
@ -116,6 +131,8 @@ export function useVendorRosterForm({
|
||||||
);
|
);
|
||||||
const { data: facets, isLoading: facetsLoading } = useVendorFacets();
|
const { data: facets, isLoading: facetsLoading } = useVendorFacets();
|
||||||
const save = useSaveVendorCompanyRoster();
|
const save = useSaveVendorCompanyRoster();
|
||||||
|
// Area assignment is Admin-only; the API enforces it and the field mirrors it.
|
||||||
|
const canAssignArea = isAdminUser(useContext(AuthContext)?.user?.userRoles);
|
||||||
const [conflict, setConflict] = useState<VendorRosterConflict | null>(null);
|
const [conflict, setConflict] = useState<VendorRosterConflict | null>(null);
|
||||||
|
|
||||||
const routeRoster = mode === "update" ? query.data : undefined;
|
const routeRoster = mode === "update" ? query.data : undefined;
|
||||||
|
|
@ -151,6 +168,14 @@ export function useVendorRosterForm({
|
||||||
clearConflict,
|
clearConflict,
|
||||||
});
|
});
|
||||||
const { resetSelection } = selection;
|
const { resetSelection } = selection;
|
||||||
|
const areaField = useMemo<VendorRosterAreaFieldProps>(
|
||||||
|
() => ({
|
||||||
|
areaOptions: facets?.areas ?? [],
|
||||||
|
currentArea: toCurrentArea(routeRoster ?? selection.selectedRoster),
|
||||||
|
canAssignArea,
|
||||||
|
}),
|
||||||
|
[canAssignArea, facets, routeRoster, selection.selectedRoster],
|
||||||
|
);
|
||||||
|
|
||||||
const isValid = useMemo(() => {
|
const isValid = useMemo(() => {
|
||||||
if (vendorCompanyRosterSchema.safeParse(watched).success) return true;
|
if (vendorCompanyRosterSchema.safeParse(watched).success) return true;
|
||||||
|
|
@ -238,6 +263,7 @@ export function useVendorRosterForm({
|
||||||
companies,
|
companies,
|
||||||
trades,
|
trades,
|
||||||
tradesLoading: facetsLoading,
|
tradesLoading: facetsLoading,
|
||||||
|
areaField,
|
||||||
selectedCompanyId: selection.selectedCompanyId,
|
selectedCompanyId: selection.selectedCompanyId,
|
||||||
selectCompany: selection.selectCompany,
|
selectCompany: selection.selectCompany,
|
||||||
clearSelectedCompany: selection.clearSelectedCompany,
|
clearSelectedCompany: selection.clearSelectedCompany,
|
||||||
|
|
|
||||||
|
|
@ -43,6 +43,7 @@ export function toFormValues(roster: VendorCompanyRoster): VendorCompanyRosterFo
|
||||||
// The deprecated stored Maps URL is intentionally not seeded: the form has
|
// The deprecated stored Maps URL is intentionally not seeded: the form has
|
||||||
// no input for it, and carrying it would re-emit a legacy value on write.
|
// no input for it, and carrying it would re-emit a legacy value on write.
|
||||||
notes: roster.notes,
|
notes: roster.notes,
|
||||||
|
areaId: roster.areaId,
|
||||||
technicians: roster.technicians.map((technician) => ({
|
technicians: roster.technicians.map((technician) => ({
|
||||||
id: technician.id,
|
id: technician.id,
|
||||||
contactName: technician.contactName,
|
contactName: technician.contactName,
|
||||||
|
|
|
||||||
|
|
@ -77,6 +77,7 @@ export function VendorCreateModal({ open, onClose }: VendorCreateModalProps) {
|
||||||
selectedCompanyId={form.selectedCompanyId}
|
selectedCompanyId={form.selectedCompanyId}
|
||||||
onSelectCompany={form.selectCompany}
|
onSelectCompany={form.selectCompany}
|
||||||
onClearSelectedCompany={form.clearSelectedCompany}
|
onClearSelectedCompany={form.clearSelectedCompany}
|
||||||
|
{...form.areaField}
|
||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
|
||||||
|
|
@ -155,6 +155,7 @@ function CompanySection({ roster }: { roster: VendorCompanyRoster }) {
|
||||||
<Field label="State" value={roster.state} />
|
<Field label="State" value={roster.state} />
|
||||||
</Box>
|
</Box>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
<Field label="Service Area" value={roster.areaName || "Unassigned"} />
|
||||||
<AddressMapPreview address={address} />
|
<AddressMapPreview address={address} />
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
|
|
@ -336,6 +337,7 @@ function DrawerEditor({
|
||||||
tradeOptions={form.trades}
|
tradeOptions={form.trades}
|
||||||
tradeOptionsLoading={form.tradesLoading}
|
tradeOptionsLoading={form.tradesLoading}
|
||||||
showTechnicianStatus={false}
|
showTechnicianStatus={false}
|
||||||
|
{...form.areaField}
|
||||||
/>
|
/>
|
||||||
{selectedIndex >= 0 && (
|
{selectedIndex >= 0 && (
|
||||||
<>
|
<>
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import BusinessOutlinedIcon from "@mui/icons-material/BusinessOutlined";
|
||||||
import BuildOutlinedIcon from "@mui/icons-material/BuildOutlined";
|
import BuildOutlinedIcon from "@mui/icons-material/BuildOutlined";
|
||||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||||
import LocationOnOutlinedIcon from "@mui/icons-material/LocationOnOutlined";
|
import LocationOnOutlinedIcon from "@mui/icons-material/LocationOnOutlined";
|
||||||
|
import MapOutlinedIcon from "@mui/icons-material/MapOutlined";
|
||||||
import TagOutlinedIcon from "@mui/icons-material/TagOutlined";
|
import TagOutlinedIcon from "@mui/icons-material/TagOutlined";
|
||||||
import {
|
import {
|
||||||
Accordion,
|
Accordion,
|
||||||
|
|
@ -17,13 +18,14 @@ import {
|
||||||
TextField,
|
TextField,
|
||||||
Typography,
|
Typography,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import type {
|
import {
|
||||||
VendorFacets,
|
type VendorFacetArea,
|
||||||
VendorFacetCompany,
|
type VendorFacets,
|
||||||
VendorFacetJobBucket,
|
type VendorFacetCompany,
|
||||||
VendorFacetLocation,
|
type VendorFacetJobBucket,
|
||||||
|
type VendorFacetLocation,
|
||||||
} from "@/domain/vendors/types/vendor";
|
} from "@/domain/vendors/types/vendor";
|
||||||
import type { VendorFilters } from "./vendor-filters";
|
import { serviceAreaFilterOptions, type VendorFilters } from "./vendor-filters";
|
||||||
|
|
||||||
type DraftSetter = Dispatch<SetStateAction<VendorFilters>>;
|
type DraftSetter = Dispatch<SetStateAction<VendorFilters>>;
|
||||||
|
|
||||||
|
|
@ -156,6 +158,33 @@ interface FilterProps<T> {
|
||||||
setDraft: DraftSetter;
|
setDraft: DraftSetter;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function ServiceAreaFilter({ options, draft, setDraft }: FilterProps<VendorFacetArea>) {
|
||||||
|
return (
|
||||||
|
<FilterSection title="Service Area" icon={<MapOutlinedIcon />}>
|
||||||
|
<Autocomplete
|
||||||
|
multiple
|
||||||
|
size="small"
|
||||||
|
options={options}
|
||||||
|
getOptionLabel={(option) => option.name}
|
||||||
|
isOptionEqualToValue={(option, value) => option.id === value.id}
|
||||||
|
value={options.filter((option) => draft.areas.includes(option.id))}
|
||||||
|
onChange={(_event, value) =>
|
||||||
|
setDraft((current) => ({ ...current, areas: value.map((entry) => entry.id) }))
|
||||||
|
}
|
||||||
|
renderValue={(value, getItemProps) =>
|
||||||
|
value.map((option, index) => {
|
||||||
|
const { key, ...chipProps } = getItemProps({ index });
|
||||||
|
return <Chip key={key} size="small" label={option.name} {...chipProps} />;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
renderInput={(params) => (
|
||||||
|
<TextField {...params} placeholder={draft.areas.length === 0 ? "All areas" : ""} />
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</FilterSection>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function LocationFilter({ options, draft, setDraft }: FilterProps<VendorFacetLocation>) {
|
function LocationFilter({ options, draft, setDraft }: FilterProps<VendorFacetLocation>) {
|
||||||
return (
|
return (
|
||||||
<FilterSection title="Location" icon={<LocationOnOutlinedIcon />}>
|
<FilterSection title="Location" icon={<LocationOnOutlinedIcon />}>
|
||||||
|
|
@ -245,6 +274,11 @@ export function VendorFilterOptions({
|
||||||
<>
|
<>
|
||||||
<CompanyFilter options={facets?.companies ?? []} draft={draft} setDraft={setDraft} />
|
<CompanyFilter options={facets?.companies ?? []} draft={draft} setDraft={setDraft} />
|
||||||
<TradeFilter options={facets?.trades ?? []} draft={draft} setDraft={setDraft} />
|
<TradeFilter options={facets?.trades ?? []} draft={draft} setDraft={setDraft} />
|
||||||
|
<ServiceAreaFilter
|
||||||
|
options={serviceAreaFilterOptions(facets?.areas ?? [])}
|
||||||
|
draft={draft}
|
||||||
|
setDraft={setDraft}
|
||||||
|
/>
|
||||||
<LocationFilter options={facets?.locations ?? []} draft={draft} setDraft={setDraft} />
|
<LocationFilter options={facets?.locations ?? []} draft={draft} setDraft={setDraft} />
|
||||||
<JobCountFilter options={facets?.jobBuckets ?? []} draft={draft} setDraft={setDraft} />
|
<JobCountFilter options={facets?.jobBuckets ?? []} draft={draft} setDraft={setDraft} />
|
||||||
</>
|
</>
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,11 @@ export function VendorFiltersDrawer({
|
||||||
}, [open, appliedFilters]);
|
}, [open, appliedFilters]);
|
||||||
|
|
||||||
const activeCount =
|
const activeCount =
|
||||||
draft.companies.length + draft.trades.length + draft.locations.length + draft.jobBuckets.length;
|
draft.companies.length +
|
||||||
|
draft.trades.length +
|
||||||
|
draft.areas.length +
|
||||||
|
draft.locations.length +
|
||||||
|
draft.jobBuckets.length;
|
||||||
|
|
||||||
const handleClear = () => {
|
const handleClear = () => {
|
||||||
setDraft(emptyVendorFilters);
|
setDraft(emptyVendorFilters);
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,10 @@
|
||||||
|
import { VENDOR_AREA_UNASSIGNED, type VendorFacetArea } from "@/domain/vendors/types/vendor";
|
||||||
|
|
||||||
export interface VendorFilters {
|
export interface VendorFilters {
|
||||||
companies: string[];
|
companies: string[];
|
||||||
trades: string[];
|
trades: string[];
|
||||||
|
/** Stable Area ids or VENDOR_AREA_UNASSIGNED; OR within the facet. */
|
||||||
|
areas: string[];
|
||||||
locations: string[];
|
locations: string[];
|
||||||
jobBuckets: string[];
|
jobBuckets: string[];
|
||||||
}
|
}
|
||||||
|
|
@ -8,6 +12,17 @@ export interface VendorFilters {
|
||||||
export const emptyVendorFilters: VendorFilters = {
|
export const emptyVendorFilters: VendorFilters = {
|
||||||
companies: [],
|
companies: [],
|
||||||
trades: [],
|
trades: [],
|
||||||
|
areas: [],
|
||||||
locations: [],
|
locations: [],
|
||||||
jobBuckets: [],
|
jobBuckets: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const UNASSIGNED_AREA_OPTION: VendorFacetArea = { id: VENDOR_AREA_UNASSIGNED, name: "Unassigned" };
|
||||||
|
|
||||||
|
/** Unassigned first, then the active Area catalogue A–Z (case-insensitive). */
|
||||||
|
export function serviceAreaFilterOptions(areas: VendorFacetArea[]): VendorFacetArea[] {
|
||||||
|
const sorted = [...areas].sort((a, b) =>
|
||||||
|
a.name.localeCompare(b.name, undefined, { sensitivity: "base" }),
|
||||||
|
);
|
||||||
|
return [UNASSIGNED_AREA_OPTION, ...sorted];
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -30,8 +30,11 @@ import {
|
||||||
type RosterTechnicianValues,
|
type RosterTechnicianValues,
|
||||||
type VendorCompanyRosterFormValues,
|
type VendorCompanyRosterFormValues,
|
||||||
} from "@/domain/vendors/schemas/vendor-roster-schema";
|
} from "@/domain/vendors/schemas/vendor-roster-schema";
|
||||||
import type { VendorFacetCompany } from "@/domain/vendors/types/vendor";
|
import type { VendorFacetArea, VendorFacetCompany } from "@/domain/vendors/types/vendor";
|
||||||
|
import { normalizeStateCode } from "@/data/areas";
|
||||||
import { VendorCompanyContactFields } from "./vendor-company-contact-fields";
|
import { VendorCompanyContactFields } from "./vendor-company-contact-fields";
|
||||||
|
import { VendorServiceAreaField } from "./vendor-service-area-field";
|
||||||
|
import { VendorStateSelectField } from "./vendor-state-select-field";
|
||||||
|
|
||||||
interface VendorRosterFormFieldsProps {
|
interface VendorRosterFormFieldsProps {
|
||||||
control: Control<VendorCompanyRosterFormValues>;
|
control: Control<VendorCompanyRosterFormValues>;
|
||||||
|
|
@ -43,6 +46,9 @@ interface VendorRosterFormFieldsProps {
|
||||||
onSelectCompany?: (company: VendorFacetCompany | null) => Promise<void>;
|
onSelectCompany?: (company: VendorFacetCompany | null) => Promise<void>;
|
||||||
onClearSelectedCompany?: (nextName?: string) => void;
|
onClearSelectedCompany?: (nextName?: string) => void;
|
||||||
showTechnicianStatus?: boolean;
|
showTechnicianStatus?: boolean;
|
||||||
|
areaOptions?: VendorFacetArea[];
|
||||||
|
currentArea?: VendorFacetArea | null;
|
||||||
|
canAssignArea?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function CompanyNameField({
|
function CompanyNameField({
|
||||||
|
|
@ -136,6 +142,9 @@ function CompanyFields({
|
||||||
selectedCompanyId,
|
selectedCompanyId,
|
||||||
onSelectCompany,
|
onSelectCompany,
|
||||||
onClearSelectedCompany,
|
onClearSelectedCompany,
|
||||||
|
areaOptions = [],
|
||||||
|
currentArea = null,
|
||||||
|
canAssignArea = false,
|
||||||
}: VendorRosterFormFieldsProps) {
|
}: VendorRosterFormFieldsProps) {
|
||||||
const notes = useWatch({ control, name: "notes" }) ?? "";
|
const notes = useWatch({ control, name: "notes" }) ?? "";
|
||||||
const { field: streetField } = useController({ control, name: "address" });
|
const { field: streetField } = useController({ control, name: "address" });
|
||||||
|
|
@ -163,7 +172,7 @@ function CompanyFields({
|
||||||
// revalidates — a plain assignment would be discarded on save.
|
// revalidates — a plain assignment would be discarded on save.
|
||||||
streetField.onChange(parts.street);
|
streetField.onChange(parts.street);
|
||||||
cityField.onChange(parts.city);
|
cityField.onChange(parts.city);
|
||||||
stateField.onChange(parts.state);
|
stateField.onChange(normalizeStateCode(parts.state) ?? parts.state);
|
||||||
}}
|
}}
|
||||||
label="Street Address (required)"
|
label="Street Address (required)"
|
||||||
required
|
required
|
||||||
|
|
@ -183,15 +192,13 @@ function CompanyFields({
|
||||||
fullWidth
|
fullWidth
|
||||||
slotProps={{ htmlInput: { required: true } }}
|
slotProps={{ htmlInput: { required: true } }}
|
||||||
/>
|
/>
|
||||||
<TextField
|
<VendorStateSelectField
|
||||||
{...stateField}
|
|
||||||
value={stateField.value ?? ""}
|
value={stateField.value ?? ""}
|
||||||
label="State (required)"
|
onChange={stateField.onChange}
|
||||||
placeholder="e.g., MO"
|
onBlur={stateField.onBlur}
|
||||||
|
inputRef={stateField.ref}
|
||||||
error={Boolean(errors.state)}
|
error={Boolean(errors.state)}
|
||||||
helperText={errors.state?.message}
|
helperText={errors.state?.message}
|
||||||
fullWidth
|
|
||||||
slotProps={{ htmlInput: { required: true } }}
|
|
||||||
/>
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
<Controller
|
<Controller
|
||||||
|
|
@ -234,6 +241,12 @@ function CompanyFields({
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
<VendorServiceAreaField
|
||||||
|
control={control}
|
||||||
|
areaOptions={areaOptions}
|
||||||
|
currentArea={currentArea}
|
||||||
|
canAssign={canAssignArea}
|
||||||
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
58
src/app/(protected)/vendors/_components/vendor-service-area-field.tsx
vendored
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
import { Controller, type Control } from "react-hook-form";
|
||||||
|
import { Autocomplete, TextField } from "@mui/material";
|
||||||
|
import type { VendorCompanyRosterFormValues } from "@/domain/vendors/schemas/vendor-roster-schema";
|
||||||
|
import type { VendorFacetArea } from "@/domain/vendors/types/vendor";
|
||||||
|
|
||||||
|
interface VendorServiceAreaFieldProps {
|
||||||
|
control: Control<VendorCompanyRosterFormValues>;
|
||||||
|
areaOptions: VendorFacetArea[];
|
||||||
|
currentArea?: VendorFacetArea | null;
|
||||||
|
canAssign: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const SERVICE_AREA_ADMIN_ONLY_MESSAGE = "Only administrators can assign a Service Area.";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Zero or one Service Area per vendor company, chosen from the Area
|
||||||
|
* catalogue by stable id. Clearing the selection leaves the company Unassigned.
|
||||||
|
* The saved Area stays visible when it is no longer in the active catalogue.
|
||||||
|
*/
|
||||||
|
export function VendorServiceAreaField({
|
||||||
|
control,
|
||||||
|
areaOptions,
|
||||||
|
currentArea,
|
||||||
|
canAssign,
|
||||||
|
}: VendorServiceAreaFieldProps) {
|
||||||
|
const options =
|
||||||
|
currentArea && !areaOptions.some((area) => area.id === currentArea.id)
|
||||||
|
? [...areaOptions, currentArea]
|
||||||
|
: areaOptions;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="areaId"
|
||||||
|
render={({ field }) => (
|
||||||
|
<Autocomplete<VendorFacetArea>
|
||||||
|
options={options}
|
||||||
|
value={options.find((area) => area.id === field.value) ?? null}
|
||||||
|
onChange={(_event, option) => field.onChange(option?.id ?? "")}
|
||||||
|
onBlur={field.onBlur}
|
||||||
|
getOptionLabel={(option) => option.name}
|
||||||
|
isOptionEqualToValue={(option, value) => option.id === value.id}
|
||||||
|
disabled={!canAssign}
|
||||||
|
fullWidth
|
||||||
|
renderInput={(params) => (
|
||||||
|
<TextField
|
||||||
|
{...params}
|
||||||
|
label="Service Area (optional)"
|
||||||
|
placeholder="Unassigned"
|
||||||
|
inputRef={field.ref}
|
||||||
|
helperText={canAssign ? undefined : SERVICE_AREA_ADMIN_ONLY_MESSAGE}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
57
src/app/(protected)/vendors/_components/vendor-state-select-field.tsx
vendored
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
import type { Ref } from "react";
|
||||||
|
import { Autocomplete, TextField } from "@mui/material";
|
||||||
|
import {
|
||||||
|
US_STATE_CODES,
|
||||||
|
formatStateOptionLabel,
|
||||||
|
normalizeStateCode,
|
||||||
|
type StateCode,
|
||||||
|
} from "@/data/areas";
|
||||||
|
|
||||||
|
interface VendorStateSelectFieldProps {
|
||||||
|
value: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
onBlur?: () => void;
|
||||||
|
inputRef?: Ref<HTMLInputElement>;
|
||||||
|
error?: boolean;
|
||||||
|
helperText?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Closed, searchable list of the 50 US states for the vendor company.
|
||||||
|
* Legacy full names are shown as their canonical code. Service Area is chosen
|
||||||
|
* independently, so no Area is derived from the selected State here.
|
||||||
|
*/
|
||||||
|
export function VendorStateSelectField({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
onBlur,
|
||||||
|
inputRef,
|
||||||
|
error,
|
||||||
|
helperText,
|
||||||
|
}: VendorStateSelectFieldProps) {
|
||||||
|
const selected: StateCode | null = normalizeStateCode(value);
|
||||||
|
return (
|
||||||
|
<Autocomplete<StateCode>
|
||||||
|
options={US_STATE_CODES}
|
||||||
|
value={selected}
|
||||||
|
onChange={(_event, option) => onChange(option ?? "")}
|
||||||
|
onBlur={onBlur}
|
||||||
|
getOptionLabel={formatStateOptionLabel}
|
||||||
|
fullWidth
|
||||||
|
renderInput={(params) => (
|
||||||
|
<TextField
|
||||||
|
{...params}
|
||||||
|
label="State (required)"
|
||||||
|
placeholder="Select a state"
|
||||||
|
inputRef={inputRef}
|
||||||
|
error={error}
|
||||||
|
helperText={helperText}
|
||||||
|
slotProps={{
|
||||||
|
...params.slotProps,
|
||||||
|
htmlInput: { ...params.slotProps?.htmlInput, required: true },
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
340
src/app/(protected)/vendors/_components/vendor-table-row.tsx
vendored
Normal file
|
|
@ -0,0 +1,340 @@
|
||||||
|
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 />
|
||||||
|
<CellText value={row.areaName || "Unassigned"} testId="vendor-text-service-area" 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";
|
import { ToolbarButton } from "@/components/ui/toolbar-button";
|
||||||
|
|
||||||
interface VendorsListToolbarProps {
|
interface VendorsListToolbarProps {
|
||||||
globalCount: number;
|
|
||||||
activeCount: number;
|
activeCount: number;
|
||||||
isFetching: boolean;
|
isFetching: boolean;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
|
|
@ -18,7 +17,6 @@ interface VendorsListToolbarProps {
|
||||||
}
|
}
|
||||||
|
|
||||||
export function VendorsListToolbar({
|
export function VendorsListToolbar({
|
||||||
globalCount,
|
|
||||||
activeCount,
|
activeCount,
|
||||||
isFetching,
|
isFetching,
|
||||||
isLoading,
|
isLoading,
|
||||||
|
|
@ -33,7 +31,7 @@ export function VendorsListToolbar({
|
||||||
surface
|
surface
|
||||||
className="-mx-4 -mt-4"
|
className="-mx-4 -mt-4"
|
||||||
title="Vendors / Technicians"
|
title="Vendors / Technicians"
|
||||||
subtitle={`${globalCount} technicians · ${activeCount} active`}
|
subtitle={`${activeCount} active ${activeCount === 1 ? "company" : "companies"}`}
|
||||||
actions={
|
actions={
|
||||||
<>
|
<>
|
||||||
<SearchInput
|
<SearchInput
|
||||||
|
|
@ -93,7 +91,7 @@ export function VendorAppliedFiltersBar({
|
||||||
return (
|
return (
|
||||||
<Stack direction="row" spacing={1} className="flex flex-wrap items-center">
|
<Stack direction="row" spacing={1} className="flex flex-wrap items-center">
|
||||||
<Text variant="caption" tone="muted">
|
<Text variant="caption" tone="muted">
|
||||||
{resultCount} {resultCount === 1 ? "technician" : "technicians"} · filtered by
|
{resultCount} {resultCount === 1 ? "company" : "companies"} · filtered by
|
||||||
</Text>
|
</Text>
|
||||||
{chips.map((chip) => (
|
{chips.map((chip) => (
|
||||||
<Chip
|
<Chip
|
||||||
|
|
@ -148,8 +146,7 @@ export function VendorsListFooter({
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Text variant="caption" as="span" sx={{ color: "#6b7a96", fontSize: 11, lineHeight: 1.5 }}>
|
<Text variant="caption" as="span" sx={{ color: "#6b7a96", fontSize: 11, lineHeight: 1.5 }}>
|
||||||
{totalCount} {isActive ? "active" : "inactive"}{" "}
|
{totalCount} {isActive ? "active" : "inactive"} {totalCount === 1 ? "company" : "companies"}
|
||||||
{totalCount === 1 ? "technician" : "technicians"}
|
|
||||||
{isFiltered && " · filtered"}
|
{isFiltered && " · filtered"}
|
||||||
</Text>
|
</Text>
|
||||||
<Text variant="caption" as="span" sx={{ color: "#6b7a96", fontSize: 11, lineHeight: 1.5 }}>
|
<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 SearchOffOutlinedIcon from "@mui/icons-material/SearchOffOutlined";
|
||||||
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
|
|
||||||
import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
|
|
||||||
import {
|
import {
|
||||||
Avatar,
|
|
||||||
Box,
|
|
||||||
CircularProgress,
|
CircularProgress,
|
||||||
IconButton,
|
|
||||||
Link,
|
|
||||||
Paper,
|
Paper,
|
||||||
Stack,
|
Stack,
|
||||||
Table,
|
Table,
|
||||||
|
|
@ -16,297 +9,25 @@ import {
|
||||||
TableContainer,
|
TableContainer,
|
||||||
TableHead,
|
TableHead,
|
||||||
TableRow,
|
TableRow,
|
||||||
Tooltip,
|
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import { VendorStatusBadge } from "./vendor-status-badge";
|
import { VendorTableRow } from "./vendor-table-row";
|
||||||
import { Text } from "@/components/ui/text";
|
import { Text } from "@/components/ui/text";
|
||||||
import type { VendorListItem } from "@/domain/vendors/types/vendor";
|
import type { VendorListItem } from "@/domain/vendors/types/vendor";
|
||||||
|
|
||||||
const TABLE_COLUMNS = [
|
const TABLE_COLUMNS = [
|
||||||
"Company",
|
"Company",
|
||||||
"Technician",
|
"Company Phone",
|
||||||
"Location",
|
"Company Email",
|
||||||
|
"Street Address",
|
||||||
|
"City",
|
||||||
|
"State",
|
||||||
|
"Service Area",
|
||||||
"Trade",
|
"Trade",
|
||||||
"Phone",
|
"Technician",
|
||||||
"Email",
|
"Technician Phone",
|
||||||
"Total Jobs",
|
"Total Jobs",
|
||||||
] as const;
|
] 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 {
|
interface VendorsTableProps {
|
||||||
rows: VendorListItem[];
|
rows: VendorListItem[];
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
|
|
@ -328,7 +49,6 @@ export function VendorsTable({
|
||||||
}: VendorsTableProps) {
|
}: VendorsTableProps) {
|
||||||
const showEmptyRow = !isLoading && !showError && rows.length === 0;
|
const showEmptyRow = !isLoading && !showError && rows.length === 0;
|
||||||
const columnCount = TABLE_COLUMNS.length + 2;
|
const columnCount = TABLE_COLUMNS.length + 2;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TableContainer
|
<TableContainer
|
||||||
component={Paper}
|
component={Paper}
|
||||||
|
|
@ -340,13 +60,14 @@ export function VendorsTable({
|
||||||
overflow: "auto",
|
overflow: "auto",
|
||||||
borderRadius: 1.5,
|
borderRadius: 1.5,
|
||||||
fontSize: 13,
|
fontSize: 13,
|
||||||
|
containerType: "inline-size",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Table
|
<Table
|
||||||
size="small"
|
size="small"
|
||||||
stickyHeader
|
stickyHeader
|
||||||
sx={{
|
sx={{
|
||||||
minWidth: 1550,
|
minWidth: 2200,
|
||||||
tableLayout: "fixed",
|
tableLayout: "fixed",
|
||||||
"& .MuiTableCell-head": {
|
"& .MuiTableCell-head": {
|
||||||
backgroundColor: "var(--color-bg-muted)",
|
backgroundColor: "var(--color-bg-muted)",
|
||||||
|
|
@ -368,26 +89,15 @@ export function VendorsTable({
|
||||||
lineHeight: 1.43,
|
lineHeight: 1.43,
|
||||||
whiteSpace: "nowrap",
|
whiteSpace: "nowrap",
|
||||||
},
|
},
|
||||||
"& .vendor-row-actions": {
|
"& .vendor-row-actions": { opacity: { xs: 1, md: 0 }, transition: "opacity 120ms ease" },
|
||||||
opacity: { xs: 1, md: 0 },
|
|
||||||
transition: "opacity 120ms ease",
|
|
||||||
},
|
|
||||||
"& .MuiTableRow-root:hover .vendor-row-actions, & .MuiTableRow-root:focus-within .vendor-row-actions":
|
"& .MuiTableRow-root:hover .vendor-row-actions, & .MuiTableRow-root:focus-within .vendor-row-actions":
|
||||||
{
|
{ opacity: 1 },
|
||||||
opacity: 1,
|
|
||||||
},
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<colgroup>
|
<colgroup>
|
||||||
<col style={{ width: 196.34375 }} />
|
{[190, 160, 220, 220, 140, 100, 150, 190, 220, 170, 110, 120, 130].map((width, index) => (
|
||||||
<col style={{ width: 207.25 }} />
|
<col key={`${width}-${index}`} style={{ width }} />
|
||||||
<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 }} />
|
|
||||||
</colgroup>
|
</colgroup>
|
||||||
<TableHead>
|
<TableHead>
|
||||||
<TableRow>
|
<TableRow>
|
||||||
|
|
@ -403,18 +113,21 @@ export function VendorsTable({
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableCell colSpan={columnCount} align="center" className="py-10">
|
<TableCell colSpan={columnCount} className="py-10">
|
||||||
<CircularProgress size={28} />
|
<Stack sx={{ width: "calc(100cqw - 24px)", alignItems: "center" }}>
|
||||||
|
<CircularProgress size={28} />
|
||||||
|
</Stack>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
) : showEmptyRow ? (
|
) : showEmptyRow ? (
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableCell colSpan={columnCount} align="center" className="py-10">
|
<TableCell colSpan={columnCount} className="py-10">
|
||||||
<Stack spacing={1} sx={{ alignItems: "center" }}>
|
<Stack spacing={1} sx={{ width: "calc(100cqw - 24px)", alignItems: "center" }}>
|
||||||
<SearchOffOutlinedIcon sx={{ color: "text.secondary", fontSize: 32 }} />
|
<SearchOffOutlinedIcon sx={{ color: "text.secondary", fontSize: 32 }} />
|
||||||
<Text variant="description" className="font-semibold">
|
<Text
|
||||||
{`No ${isActive ? "active" : "inactive"} technicians found`}
|
variant="description"
|
||||||
</Text>
|
className="font-semibold"
|
||||||
|
>{`No ${isActive ? "active" : "inactive"} companies found`}</Text>
|
||||||
<Text variant="caption" tone="muted">
|
<Text variant="caption" tone="muted">
|
||||||
{isFiltered
|
{isFiltered
|
||||||
? "Try a different search, or add a new vendor."
|
? "Try a different search, or add a new vendor."
|
||||||
|
|
|
||||||
37
src/app/(protected)/vendors/index.tsx
vendored
|
|
@ -13,9 +13,9 @@ import { VendorsTable } from "./_components/vendors-table";
|
||||||
import { useVendorDeactivation } from "./_components/use-vendor-deactivation";
|
import { useVendorDeactivation } from "./_components/use-vendor-deactivation";
|
||||||
import { useVendorListState } from "./_components/use-vendor-list-state";
|
import { useVendorListState } from "./_components/use-vendor-list-state";
|
||||||
import type { VendorFilters } from "./_components/vendor-filters";
|
import type { VendorFilters } from "./_components/vendor-filters";
|
||||||
import type { VendorListItem } from "@/domain/vendors/types/vendor";
|
import { VENDOR_AREA_UNASSIGNED, type VendorListItem } from "@/domain/vendors/types/vendor";
|
||||||
import { useVendorFacets } from "@/domain/vendors/use-cases/use-vendor-facets";
|
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 {
|
interface AppliedChip {
|
||||||
category: keyof VendorFilters;
|
category: keyof VendorFilters;
|
||||||
|
|
@ -91,6 +91,7 @@ function VendorStatusTabs({
|
||||||
function describeChips(
|
function describeChips(
|
||||||
filters: VendorFilters,
|
filters: VendorFilters,
|
||||||
jobBucketLabels: Map<string, string>,
|
jobBucketLabels: Map<string, string>,
|
||||||
|
areaLabels: Map<string, string>,
|
||||||
): AppliedChip[] {
|
): AppliedChip[] {
|
||||||
const chips: AppliedChip[] = [];
|
const chips: AppliedChip[] = [];
|
||||||
filters.companies.forEach((value) =>
|
filters.companies.forEach((value) =>
|
||||||
|
|
@ -99,6 +100,13 @@ function describeChips(
|
||||||
filters.trades.forEach((value) =>
|
filters.trades.forEach((value) =>
|
||||||
chips.push({ category: "trades", value, label: `Trade: ${value}` }),
|
chips.push({ category: "trades", value, label: `Trade: ${value}` }),
|
||||||
);
|
);
|
||||||
|
filters.areas.forEach((value) =>
|
||||||
|
chips.push({
|
||||||
|
category: "areas",
|
||||||
|
value,
|
||||||
|
label: `Service Area: ${areaLabels.get(value) ?? value}`,
|
||||||
|
}),
|
||||||
|
);
|
||||||
filters.locations.forEach((value) =>
|
filters.locations.forEach((value) =>
|
||||||
chips.push({ category: "locations", value, label: `Location: ${value}` }),
|
chips.push({ category: "locations", value, label: `Location: ${value}` }),
|
||||||
);
|
);
|
||||||
|
|
@ -125,9 +133,17 @@ export default function VendorsListPage() {
|
||||||
const deactivation = useVendorDeactivation(closeDetail);
|
const deactivation = useVendorDeactivation(closeDetail);
|
||||||
|
|
||||||
const { data: facets } = useVendorFacets(filters.isActive);
|
const { data: facets } = useVendorFacets(filters.isActive);
|
||||||
const { data, isLoading, isFetching, error } = useVendorsList(filters.listParams);
|
const { data, isLoading, isFetching, error } = useVendorDirectoryList(filters.listParams);
|
||||||
const { data: activeCountData } = useVendorsList({ isActive: true, page: 1, pageSize: 1 });
|
const { data: activeCountData } = useVendorDirectoryList({
|
||||||
const { data: inactiveCountData } = useVendorsList({ isActive: false, page: 1, pageSize: 1 });
|
isActive: true,
|
||||||
|
page: 1,
|
||||||
|
pageSize: 1,
|
||||||
|
});
|
||||||
|
const { data: inactiveCountData } = useVendorDirectoryList({
|
||||||
|
isActive: false,
|
||||||
|
page: 1,
|
||||||
|
pageSize: 1,
|
||||||
|
});
|
||||||
|
|
||||||
const rows = data?.items ?? [];
|
const rows = data?.items ?? [];
|
||||||
const totalCount = data?.totalCount ?? 0;
|
const totalCount = data?.totalCount ?? 0;
|
||||||
|
|
@ -138,12 +154,19 @@ export default function VendorsListPage() {
|
||||||
() => new Map((facets?.jobBuckets ?? []).map((bucket) => [bucket.id, bucket.label])),
|
() => new Map((facets?.jobBuckets ?? []).map((bucket) => [bucket.id, bucket.label])),
|
||||||
[facets],
|
[facets],
|
||||||
);
|
);
|
||||||
const appliedChips = describeChips(filters.appliedFilters, jobBucketLabels);
|
const areaLabels = useMemo(
|
||||||
|
() =>
|
||||||
|
new Map([
|
||||||
|
[VENDOR_AREA_UNASSIGNED, "Unassigned"],
|
||||||
|
...(facets?.areas ?? []).map((area): [string, string] => [area.id, area.name]),
|
||||||
|
]),
|
||||||
|
[facets],
|
||||||
|
);
|
||||||
|
const appliedChips = describeChips(filters.appliedFilters, jobBucketLabels, areaLabels);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box className="flex h-full flex-col overflow-hidden px-4 pt-4 pb-0">
|
<Box className="flex h-full flex-col overflow-hidden px-4 pt-4 pb-0">
|
||||||
<VendorsListToolbar
|
<VendorsListToolbar
|
||||||
globalCount={activeCount + inactiveCount}
|
|
||||||
activeCount={activeCount}
|
activeCount={activeCount}
|
||||||
isFetching={isFetching}
|
isFetching={isFetching}
|
||||||
isLoading={isLoading}
|
isLoading={isLoading}
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import {
|
||||||
getDispatcherAvatarColor,
|
getDispatcherAvatarColor,
|
||||||
getInitialsFromName,
|
getInitialsFromName,
|
||||||
} from "@/domain/work-orders/utils/dispatcher-avatar-color";
|
} from "@/domain/work-orders/utils/dispatcher-avatar-color";
|
||||||
|
import { formatAuditTimestamp } from "@/domain/work-orders/utils/format-audit-timestamp";
|
||||||
import { formatBoardAuditAction } from "@/domain/work-orders/utils/format-board-audit-action";
|
import { formatBoardAuditAction } from "@/domain/work-orders/utils/format-board-audit-action";
|
||||||
|
|
||||||
function isSystemEntry(entry: WorkOrderAuditEntry): boolean {
|
function isSystemEntry(entry: WorkOrderAuditEntry): boolean {
|
||||||
|
|
@ -15,36 +16,6 @@ function isSystemEntry(entry: WorkOrderAuditEntry): boolean {
|
||||||
return !name || name.toLowerCase() === "system";
|
return !name || name.toLowerCase() === "system";
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatClock(date: Date): string {
|
|
||||||
return date.toLocaleTimeString("en-US", {
|
|
||||||
hour: "numeric",
|
|
||||||
minute: "2-digit",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Manual (image): `· 9:48 AM`
|
|
||||||
* System (image): `05/13 · 8:00 AM`
|
|
||||||
* Prefer API display strings that already include · / AM|PM.
|
|
||||||
*/
|
|
||||||
function formatAuditTime(value: string, isSystem: boolean): string {
|
|
||||||
if (!value) return "";
|
|
||||||
if (/[·•]/.test(value) || /\b(AM|PM)\b/i.test(value)) return value;
|
|
||||||
|
|
||||||
const date = new Date(value);
|
|
||||||
if (Number.isNaN(date.getTime())) return value;
|
|
||||||
|
|
||||||
const timePart = formatClock(date);
|
|
||||||
if (isSystem) {
|
|
||||||
const datePart = date.toLocaleDateString("en-US", {
|
|
||||||
month: "2-digit",
|
|
||||||
day: "2-digit",
|
|
||||||
});
|
|
||||||
return `${datePart} · ${timePart}`;
|
|
||||||
}
|
|
||||||
return `· ${timePart}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
type SlideOverAuditListProps = {
|
type SlideOverAuditListProps = {
|
||||||
entries: WorkOrderAuditEntry[];
|
entries: WorkOrderAuditEntry[];
|
||||||
users?: WorkOrderUser[];
|
users?: WorkOrderUser[];
|
||||||
|
|
@ -151,7 +122,7 @@ export function SlideOverAuditList({ entries, users = [] }: SlideOverAuditListPr
|
||||||
color: "#9CA3AF",
|
color: "#9CA3AF",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{formatAuditTime(entry.createdAt, isSys)}
|
{formatAuditTimestamp(entry.createdAt)}
|
||||||
</Text>
|
</Text>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -8,13 +8,29 @@ type SlideOverCompletionActionsProps = {
|
||||||
docStatus: CompletionDocStatus;
|
docStatus: CompletionDocStatus;
|
||||||
rowVersion?: string | number | null;
|
rowVersion?: string | number | null;
|
||||||
completionPending: boolean;
|
completionPending: boolean;
|
||||||
|
/** Completion documents require a selected primary service. */
|
||||||
|
hasService: boolean;
|
||||||
hasUploadHandler: boolean;
|
hasUploadHandler: boolean;
|
||||||
pdfInputRef: RefObject<HTMLInputElement | null>;
|
pdfInputRef: RefObject<HTMLInputElement | null>;
|
||||||
onPdfSelected: (files: FileList | null) => void;
|
onPdfSelected: (files: FileList | null) => void;
|
||||||
onOpenCompletionDoc: () => void;
|
onOpenCompletionDoc: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
function DocStatusButtonContent({ docStatus }: { docStatus: CompletionDocStatus }) {
|
function DocStatusButtonContent({
|
||||||
|
docStatus,
|
||||||
|
hasService,
|
||||||
|
}: {
|
||||||
|
docStatus: CompletionDocStatus;
|
||||||
|
hasService: boolean;
|
||||||
|
}) {
|
||||||
|
if (!hasService) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<FileText size={13} />
|
||||||
|
Select service
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
if (docStatus === "Yes") {
|
if (docStatus === "Yes") {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|
@ -43,6 +59,7 @@ export function SlideOverCompletionActions({
|
||||||
docStatus,
|
docStatus,
|
||||||
rowVersion,
|
rowVersion,
|
||||||
completionPending,
|
completionPending,
|
||||||
|
hasService,
|
||||||
hasUploadHandler,
|
hasUploadHandler,
|
||||||
pdfInputRef,
|
pdfInputRef,
|
||||||
onPdfSelected,
|
onPdfSelected,
|
||||||
|
|
@ -83,10 +100,17 @@ export function SlideOverCompletionActions({
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="w-full gap-1.5 text-[12px]"
|
className="w-full gap-1.5 text-[12px]"
|
||||||
|
disabled={!hasService}
|
||||||
|
title={hasService ? undefined : "Select a service before opening the completion document"}
|
||||||
onClick={onOpenCompletionDoc}
|
onClick={onOpenCompletionDoc}
|
||||||
>
|
>
|
||||||
<DocStatusButtonContent docStatus={docStatus} />
|
<DocStatusButtonContent docStatus={docStatus} hasService={hasService} />
|
||||||
</Button>
|
</Button>
|
||||||
|
{!hasService && (
|
||||||
|
<Text as="p" style={{ fontSize: 11, color: "var(--color-text-muted)" }}>
|
||||||
|
Select a service before opening the completion document.
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,8 @@ import type { UploadableMediaCategory } from "@/domain/work-orders/mappers/work-
|
||||||
import type { WorkOrderBoardCompletion } from "@/domain/work-orders/types/work-order-board-detail";
|
import type { WorkOrderBoardCompletion } from "@/domain/work-orders/types/work-order-board-detail";
|
||||||
import type { MediaFile } from "@/domain/work-orders/types/work-order-media";
|
import type { MediaFile } from "@/domain/work-orders/types/work-order-media";
|
||||||
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
||||||
import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
|
import { hasCompletionDocService } from "@/domain/work-orders/utils/completion-doc-service-gate";
|
||||||
|
import { hasCompletionMediaGallery } from "@/domain/work-orders/utils/partition-slide-over-media";
|
||||||
import {
|
import {
|
||||||
formatMediaSizeLimit,
|
formatMediaSizeLimit,
|
||||||
isWorkOrderFileTooLarge,
|
isWorkOrderFileTooLarge,
|
||||||
|
|
@ -16,10 +17,6 @@ import { SlideOverCompletionMedia } from "./slide-over-completion-media";
|
||||||
import { SlideOverCompletionReadonlyStatus } from "./slide-over-completion-readonly-status";
|
import { SlideOverCompletionReadonlyStatus } from "./slide-over-completion-readonly-status";
|
||||||
import { SlideOverCompletionSignoffs } from "./slide-over-completion-signoffs";
|
import { SlideOverCompletionSignoffs } from "./slide-over-completion-signoffs";
|
||||||
|
|
||||||
function isMediaWO(type: WOType | ""): boolean {
|
|
||||||
return type === "Emergency" || type === "Reactive";
|
|
||||||
}
|
|
||||||
|
|
||||||
type SlideOverCompletionTabProps = {
|
type SlideOverCompletionTabProps = {
|
||||||
row: WorkOrderTableRow;
|
row: WorkOrderTableRow;
|
||||||
isReadOnly: boolean;
|
isReadOnly: boolean;
|
||||||
|
|
@ -56,7 +53,7 @@ export function SlideOverCompletionTab({
|
||||||
const templateUrl = completion?.template?.templateUrl;
|
const templateUrl = completion?.template?.templateUrl;
|
||||||
const signOffAttachment = completion?.signOffAttachment;
|
const signOffAttachment = completion?.signOffAttachment;
|
||||||
|
|
||||||
if (isMediaWO(row.type)) {
|
if (hasCompletionMediaGallery(row.type)) {
|
||||||
return (
|
return (
|
||||||
<SlideOverCompletionMedia
|
<SlideOverCompletionMedia
|
||||||
isReadOnly={isReadOnly}
|
isReadOnly={isReadOnly}
|
||||||
|
|
@ -130,6 +127,7 @@ export function SlideOverCompletionTab({
|
||||||
docStatus={docStatus}
|
docStatus={docStatus}
|
||||||
rowVersion={row.rowVersion}
|
rowVersion={row.rowVersion}
|
||||||
completionPending={completionPending}
|
completionPending={completionPending}
|
||||||
|
hasService={hasCompletionDocService(row.pm)}
|
||||||
hasUploadHandler={Boolean(onUploadCompletionPdf)}
|
hasUploadHandler={Boolean(onUploadCompletionPdf)}
|
||||||
pdfInputRef={pdfInputRef}
|
pdfInputRef={pdfInputRef}
|
||||||
onPdfSelected={handlePdfSelected}
|
onPdfSelected={handlePdfSelected}
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,14 @@ const FILETYPE_ICON: Record<FileCategory, typeof ImageIcon> = {
|
||||||
other: Paperclip,
|
other: Paperclip,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const FILETYPE_LABEL: Record<FileCategory, string> = {
|
||||||
|
image: "Photo",
|
||||||
|
video: "Video",
|
||||||
|
pdf: "PDF",
|
||||||
|
doc: "Document",
|
||||||
|
other: "File",
|
||||||
|
};
|
||||||
|
|
||||||
const EXTRA_DOC_PURPOSES: Array<Extract<UploadableMediaCategory, "Extra" | "Aveta">> = [
|
const EXTRA_DOC_PURPOSES: Array<Extract<UploadableMediaCategory, "Extra" | "Aveta">> = [
|
||||||
"Extra",
|
"Extra",
|
||||||
"Aveta",
|
"Aveta",
|
||||||
|
|
@ -92,8 +100,13 @@ function ExtraDocRow({
|
||||||
const purpose = file.purpose === "Aveta" || isAveta ? "Aveta" : "Extra";
|
const purpose = file.purpose === "Aveta" || isAveta ? "Aveta" : "Extra";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2 py-1">
|
<div
|
||||||
|
role="group"
|
||||||
|
aria-label={`${FILETYPE_LABEL[file.fileType]}, ${purpose}: ${file.name}`}
|
||||||
|
className="flex items-center gap-2 py-1"
|
||||||
|
>
|
||||||
<ItemIcon
|
<ItemIcon
|
||||||
|
aria-hidden
|
||||||
size={12}
|
size={12}
|
||||||
className="shrink-0"
|
className="shrink-0"
|
||||||
style={{ color: isAveta ? "var(--warning)" : "var(--color-text-muted)" }}
|
style={{ color: isAveta ? "var(--warning)" : "var(--color-text-muted)" }}
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,10 @@ import type { WizardWOStatus } from "@/domain/work-orders/types/work-order-wizar
|
||||||
import { deriveDayFields } from "@/domain/work-orders/utils/table-day-utils";
|
import { deriveDayFields } from "@/domain/work-orders/utils/table-day-utils";
|
||||||
import { toVendorTablePatch } from "@/domain/work-orders/utils/vendor-assignment-patch";
|
import { toVendorTablePatch } from "@/domain/work-orders/utils/vendor-assignment-patch";
|
||||||
import { DocBadge } from "./slide-over-doc-badge";
|
import { DocBadge } from "./slide-over-doc-badge";
|
||||||
|
import {
|
||||||
|
clearDueDateBeforeSchedule,
|
||||||
|
resolveDueDateFloor,
|
||||||
|
} from "@/domain/work-orders/utils/due-date-floor";
|
||||||
|
|
||||||
type SlideOverInfoTabEditViewProps = {
|
type SlideOverInfoTabEditViewProps = {
|
||||||
draft: WorkOrderTableRow;
|
draft: WorkOrderTableRow;
|
||||||
|
|
@ -52,6 +56,7 @@ function SlideOverScheduleOnField({
|
||||||
schedMode={draft.schedMode}
|
schedMode={draft.schedMode}
|
||||||
onSave={(scheduledOn) =>
|
onSave={(scheduledOn) =>
|
||||||
onDraftChange({
|
onDraftChange({
|
||||||
|
...clearDueDateBeforeSchedule(draft.dueDate, scheduledOn),
|
||||||
scheduledOn,
|
scheduledOn,
|
||||||
scheduleWeekOnly: false,
|
scheduleWeekOnly: false,
|
||||||
targetWeek: scheduledOn ? "" : draft.targetWeek,
|
targetWeek: scheduledOn ? "" : draft.targetWeek,
|
||||||
|
|
@ -63,6 +68,7 @@ function SlideOverScheduleOnField({
|
||||||
}
|
}
|
||||||
onSaveWeek={(weekStart) =>
|
onSaveWeek={(weekStart) =>
|
||||||
onDraftChange({
|
onDraftChange({
|
||||||
|
...clearDueDateBeforeSchedule(draft.dueDate, weekStart),
|
||||||
scheduledOn: "",
|
scheduledOn: "",
|
||||||
targetWeek: weekStart,
|
targetWeek: weekStart,
|
||||||
scheduleWeekOnly: true,
|
scheduleWeekOnly: true,
|
||||||
|
|
@ -74,6 +80,7 @@ function SlideOverScheduleOnField({
|
||||||
}
|
}
|
||||||
onSaveRange={(start, end) =>
|
onSaveRange={(start, end) =>
|
||||||
onDraftChange({
|
onDraftChange({
|
||||||
|
...clearDueDateBeforeSchedule(draft.dueDate, start),
|
||||||
scheduledOn: start,
|
scheduledOn: start,
|
||||||
scheduleEnd: end,
|
scheduleEnd: end,
|
||||||
schedMode: "range",
|
schedMode: "range",
|
||||||
|
|
@ -175,6 +182,7 @@ export function SlideOverInfoTabEditView({
|
||||||
<DueDateCell
|
<DueDateCell
|
||||||
type={draft.type}
|
type={draft.type}
|
||||||
value={draft.dueDate}
|
value={draft.dueDate}
|
||||||
|
minDate={resolveDueDateFloor(draft)}
|
||||||
onSave={(dueDate) => onDraftChange({ dueDate })}
|
onSave={(dueDate) => onDraftChange({ dueDate })}
|
||||||
/>
|
/>
|
||||||
</SlideOverInfoRow>
|
</SlideOverInfoRow>
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ import type {
|
||||||
UploadWorkOrderMediaInput,
|
UploadWorkOrderMediaInput,
|
||||||
} from "@/domain/work-orders/use-cases/use-work-order-mutations";
|
} from "@/domain/work-orders/use-cases/use-work-order-mutations";
|
||||||
import {
|
import {
|
||||||
|
hasCompletionMediaGallery,
|
||||||
isCompletionSurfaceMedia,
|
isCompletionSurfaceMedia,
|
||||||
isExtrasSurfaceMedia,
|
isExtrasSurfaceMedia,
|
||||||
type MediaSurfaceOwnership,
|
type MediaSurfaceOwnership,
|
||||||
|
|
@ -80,6 +81,7 @@ export function useSlideOverMediaState({
|
||||||
categorizeMediaMutation,
|
categorizeMediaMutation,
|
||||||
}: UseSlideOverMediaStateArgs) {
|
}: UseSlideOverMediaStateArgs) {
|
||||||
const workOrderId = detailForRow?.info.id;
|
const workOrderId = detailForRow?.info.id;
|
||||||
|
const completionHasGallery = hasCompletionMediaGallery(detailForRow?.info.type);
|
||||||
const [mediaBatchPending, setMediaBatchPending] = useState(false);
|
const [mediaBatchPending, setMediaBatchPending] = useState(false);
|
||||||
const [ownership, setOwnershipState] = useState<MediaSurfaceOwnership>(() =>
|
const [ownership, setOwnershipState] = useState<MediaSurfaceOwnership>(() =>
|
||||||
loadOwnership(workOrderId),
|
loadOwnership(workOrderId),
|
||||||
|
|
@ -116,16 +118,16 @@ export function useSlideOverMediaState({
|
||||||
useMediaUploadSession(detailForRow, persistCompletionUpload);
|
useMediaUploadSession(detailForRow, persistCompletionUpload);
|
||||||
|
|
||||||
const completionMedia = useMemo(
|
const completionMedia = useMemo(
|
||||||
() => uploads.filter((item) => isCompletionSurfaceMedia(item, ownership)),
|
() => uploads.filter((item) => isCompletionSurfaceMedia(item, ownership, completionHasGallery)),
|
||||||
[uploads, ownership],
|
[uploads, ownership, completionHasGallery],
|
||||||
);
|
);
|
||||||
|
|
||||||
const extrasUploads = useMemo(
|
const extrasUploads = useMemo(
|
||||||
() =>
|
() =>
|
||||||
boardMediaItemsToMediaFiles(detailForRow?.media ?? []).filter((item) =>
|
boardMediaItemsToMediaFiles(detailForRow?.media ?? []).filter((item) =>
|
||||||
isExtrasSurfaceMedia(item, ownership),
|
isExtrasSurfaceMedia(item, ownership, completionHasGallery),
|
||||||
),
|
),
|
||||||
[detailForRow?.media, ownership],
|
[detailForRow?.media, ownership, completionHasGallery],
|
||||||
);
|
);
|
||||||
|
|
||||||
const hasLocalUploading = uploads.some((item) => item.uploadStatus === "uploading");
|
const hasLocalUploading = uploads.some((item) => item.uploadStatus === "uploading");
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,7 @@ export function buildInlineDraftCreateInput(
|
||||||
scheduledOn: draft.scheduledOn,
|
scheduledOn: draft.scheduledOn,
|
||||||
dueDate: draft.dueDate,
|
dueDate: draft.dueDate,
|
||||||
pm: draft.pm,
|
pm: draft.pm,
|
||||||
|
serviceId: null,
|
||||||
extraServices: draft.extraServices ?? [],
|
extraServices: draft.extraServices ?? [],
|
||||||
avetaRequired: Boolean(draft.avetaRequired),
|
avetaRequired: Boolean(draft.avetaRequired),
|
||||||
pmNote: draft.serviceNotes ?? "",
|
pmNote: draft.serviceNotes ?? "",
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,8 @@ type DateCellProps = {
|
||||||
onClear?: () => void;
|
onClear?: () => void;
|
||||||
/** Screen-reader-only status appended inside the button so the accessible name keeps the visible date and adds durable state. */
|
/** Screen-reader-only status appended inside the button so the accessible name keeps the visible date and adds durable state. */
|
||||||
srStatusSuffix?: string;
|
srStatusSuffix?: string;
|
||||||
|
/** Earliest selectable day in the date calendar (SH-356). */
|
||||||
|
minDate?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function DateCell({
|
export function DateCell({
|
||||||
|
|
@ -41,6 +43,7 @@ export function DateCell({
|
||||||
onSaveRange,
|
onSaveRange,
|
||||||
onClear,
|
onClear,
|
||||||
srStatusSuffix,
|
srStatusSuffix,
|
||||||
|
minDate,
|
||||||
}: DateCellProps) {
|
}: DateCellProps) {
|
||||||
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
|
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
|
||||||
const open = Boolean(anchorEl);
|
const open = Boolean(anchorEl);
|
||||||
|
|
@ -154,6 +157,7 @@ export function DateCell({
|
||||||
) : (
|
) : (
|
||||||
<MiniCalendar
|
<MiniCalendar
|
||||||
value={value}
|
value={value}
|
||||||
|
minDate={minDate}
|
||||||
onChange={(d) => {
|
onChange={(d) => {
|
||||||
onSave(d);
|
onSave(d);
|
||||||
setAnchorEl(null);
|
setAnchorEl(null);
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ type DueDateCalendarDialogProps = {
|
||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
value: string;
|
value: string;
|
||||||
onSave: (iso: string) => void;
|
onSave: (iso: string) => void;
|
||||||
|
minDate?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -19,6 +20,7 @@ export function DueDateCalendarDialog({
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
value,
|
value,
|
||||||
onSave,
|
onSave,
|
||||||
|
minDate,
|
||||||
}: DueDateCalendarDialogProps) {
|
}: DueDateCalendarDialogProps) {
|
||||||
return (
|
return (
|
||||||
<Dialog
|
<Dialog
|
||||||
|
|
@ -44,6 +46,7 @@ export function DueDateCalendarDialog({
|
||||||
<div className="flex justify-center">
|
<div className="flex justify-center">
|
||||||
<MiniCalendar
|
<MiniCalendar
|
||||||
value={value}
|
value={value}
|
||||||
|
minDate={minDate}
|
||||||
onChange={(iso) => {
|
onChange={(iso) => {
|
||||||
onSave(iso);
|
onSave(iso);
|
||||||
onOpenChange(false);
|
onOpenChange(false);
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,8 @@ type DueDateCellProps = {
|
||||||
* read by colour alone.
|
* read by colour alone.
|
||||||
*/
|
*/
|
||||||
pastDue?: boolean;
|
pastDue?: boolean;
|
||||||
|
/** Schedule On floor: earlier days are not selectable (SH-356). */
|
||||||
|
minDate?: string;
|
||||||
onSave: (date: string) => void;
|
onSave: (date: string) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -29,6 +31,7 @@ export function DueDateCell({
|
||||||
q,
|
q,
|
||||||
highlight,
|
highlight,
|
||||||
pastDue = false,
|
pastDue = false,
|
||||||
|
minDate,
|
||||||
onSave,
|
onSave,
|
||||||
}: DueDateCellProps) {
|
}: DueDateCellProps) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
|
@ -40,6 +43,7 @@ export function DueDateCell({
|
||||||
q={q}
|
q={q}
|
||||||
highlight={highlight}
|
highlight={highlight}
|
||||||
onSave={onSave}
|
onSave={onSave}
|
||||||
|
minDate={minDate}
|
||||||
srStatusSuffix={pastDue ? "Past due" : undefined}
|
srStatusSuffix={pastDue ? "Past due" : undefined}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
@ -87,7 +91,13 @@ export function DueDateCell({
|
||||||
style={{ color: "var(--muted-foreground)" }}
|
style={{ color: "var(--muted-foreground)" }}
|
||||||
/>
|
/>
|
||||||
</button>
|
</button>
|
||||||
<DueDateCalendarDialog open={open} onOpenChange={setOpen} value={value} onSave={onSave} />
|
<DueDateCalendarDialog
|
||||||
|
minDate={minDate}
|
||||||
|
open={open}
|
||||||
|
onOpenChange={setOpen}
|
||||||
|
value={value}
|
||||||
|
onSave={onSave}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,12 @@ import { toast } from "react-toastify";
|
||||||
import { workOrdersApi } from "@/domain/work-orders/api/work-orders-api";
|
import { workOrdersApi } from "@/domain/work-orders/api/work-orders-api";
|
||||||
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
||||||
import { findDuplicateWoNumberRow } from "@/domain/work-orders/utils/find-duplicate-wo-number-row";
|
import { findDuplicateWoNumberRow } from "@/domain/work-orders/utils/find-duplicate-wo-number-row";
|
||||||
|
import {
|
||||||
|
WO_NUMBER_DOWNGRADE_MESSAGE,
|
||||||
|
WO_NUMBER_FORMAT_MESSAGE,
|
||||||
|
isValidBoardWoNumber,
|
||||||
|
isWoNumberDowngrade,
|
||||||
|
} from "@/domain/work-orders/utils/wo-number-input";
|
||||||
import { EditableWONumberInput } from "./editable-wo-number-input";
|
import { EditableWONumberInput } from "./editable-wo-number-input";
|
||||||
import { HighlightText } from "./highlight-text";
|
import { HighlightText } from "./highlight-text";
|
||||||
import { AddOnPill, CarriedOverCounterPill, RescheduleCounterPill } from "./wo-counter-pills";
|
import { AddOnPill, CarriedOverCounterPill, RescheduleCounterPill } from "./wo-counter-pills";
|
||||||
|
|
@ -22,8 +28,13 @@ type EditableWONumberCellProps = {
|
||||||
onSave: (v: string) => void;
|
onSave: (v: string) => void;
|
||||||
onDuplicateFound?: (existing: WorkOrderTableRow) => void;
|
onDuplicateFound?: (existing: WorkOrderTableRow) => void;
|
||||||
locked?: boolean;
|
locked?: boolean;
|
||||||
|
/** Empty-state label for create flows; renders with a persistent required asterisk. */
|
||||||
|
requiredPlaceholder?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Inline-create rows pass this id; their number is draft state, never a saved WO number. */
|
||||||
|
const UNSAVED_DRAFT_ID = "draft";
|
||||||
|
|
||||||
async function resolveDuplicateWoNumber(
|
async function resolveDuplicateWoNumber(
|
||||||
draft: string,
|
draft: string,
|
||||||
allOrders: WorkOrderTableRow[],
|
allOrders: WorkOrderTableRow[],
|
||||||
|
|
@ -34,6 +45,28 @@ async function resolveDuplicateWoNumber(
|
||||||
return remote && String(remote.id) !== String(currentId) ? remote : undefined;
|
return remote && String(remote.id) !== String(currentId) ? remote : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function EmptyWoNumberLabel({
|
||||||
|
value,
|
||||||
|
q,
|
||||||
|
requiredPlaceholder,
|
||||||
|
}: {
|
||||||
|
value: string;
|
||||||
|
q?: string;
|
||||||
|
requiredPlaceholder?: string;
|
||||||
|
}) {
|
||||||
|
if (value) {
|
||||||
|
return <HighlightText text={value} q={q} />;
|
||||||
|
}
|
||||||
|
if (!requiredPlaceholder) {
|
||||||
|
return "-";
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<span className="font-sans text-[13px] font-normal">
|
||||||
|
{requiredPlaceholder} <span style={{ color: "var(--destructive)" }}>*</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function EditableWONumberCell({
|
export function EditableWONumberCell({
|
||||||
value,
|
value,
|
||||||
rescheduleCount,
|
rescheduleCount,
|
||||||
|
|
@ -49,6 +82,7 @@ export function EditableWONumberCell({
|
||||||
onSave,
|
onSave,
|
||||||
onDuplicateFound,
|
onDuplicateFound,
|
||||||
locked = false,
|
locked = false,
|
||||||
|
requiredPlaceholder,
|
||||||
}: EditableWONumberCellProps) {
|
}: EditableWONumberCellProps) {
|
||||||
const [editing, setEditing] = useState(false);
|
const [editing, setEditing] = useState(false);
|
||||||
const [draft, setDraft] = useState(value);
|
const [draft, setDraft] = useState(value);
|
||||||
|
|
@ -63,8 +97,14 @@ export function EditableWONumberCell({
|
||||||
setEditing(false);
|
setEditing(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (draft.length !== 11) {
|
if (!isValidBoardWoNumber(draft)) {
|
||||||
toast("Work order number must be exactly 11 digits");
|
toast(WO_NUMBER_FORMAT_MESSAGE);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (String(currentId) !== UNSAVED_DRAFT_ID && isWoNumberDowngrade(value, draft)) {
|
||||||
|
toast.error(WO_NUMBER_DOWNGRADE_MESSAGE);
|
||||||
|
setDraft(value);
|
||||||
|
setEditing(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setIsChecking(true);
|
setIsChecking(true);
|
||||||
|
|
@ -97,14 +137,14 @@ export function EditableWONumberCell({
|
||||||
|
|
||||||
const handleBlur = () => {
|
const handleBlur = () => {
|
||||||
if (isChecking) return;
|
if (isChecking) return;
|
||||||
if (draft !== value && draft.length === 11) {
|
if (draft !== value && isValidBoardWoNumber(draft)) {
|
||||||
commit();
|
commit();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setEditing(false);
|
setEditing(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const invalid = editing && draft.length > 0 && draft.length !== 11;
|
const invalid = editing && draft.length > 0 && !isValidBoardWoNumber(draft);
|
||||||
|
|
||||||
if (locked) {
|
if (locked) {
|
||||||
return (
|
return (
|
||||||
|
|
@ -162,7 +202,7 @@ export function EditableWONumberCell({
|
||||||
padding: "2px 4px",
|
padding: "2px 4px",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{value ? <HighlightText text={value} q={q} /> : "-"}
|
<EmptyWoNumberLabel value={value} q={q} requiredPlaceholder={requiredPlaceholder} />
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
<AddOnPill when={isAddOn} />
|
<AddOnPill when={isAddOn} />
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
|
import { sanitizeBoardWoNumberInput } from "@/domain/work-orders/utils/wo-number-input";
|
||||||
|
|
||||||
type EditableWONumberInputProps = {
|
type EditableWONumberInputProps = {
|
||||||
draft: string;
|
draft: string;
|
||||||
invalid: boolean;
|
invalid: boolean;
|
||||||
|
|
@ -21,9 +23,8 @@ export function EditableWONumberInput({
|
||||||
<input
|
<input
|
||||||
autoFocus
|
autoFocus
|
||||||
disabled={isChecking}
|
disabled={isChecking}
|
||||||
inputMode="numeric"
|
|
||||||
value={draft}
|
value={draft}
|
||||||
onChange={(event) => onChange(event.target.value.replace(/\D/g, "").slice(0, 11))}
|
onChange={(event) => onChange(sanitizeBoardWoNumberInput(event.target.value))}
|
||||||
onFocus={(event) => event.target.select()}
|
onFocus={(event) => event.target.select()}
|
||||||
onClick={(event) => event.stopPropagation()}
|
onClick={(event) => event.stopPropagation()}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
|
|
@ -36,7 +37,7 @@ export function EditableWONumberInput({
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
onBlur={onBlur ?? onCommit}
|
onBlur={onBlur ?? onCommit}
|
||||||
placeholder="12345678901"
|
placeholder="e.g. 12345678901 or SH00001"
|
||||||
aria-label="Work order number"
|
aria-label="Work order number"
|
||||||
aria-invalid={invalid}
|
aria-invalid={invalid}
|
||||||
className="font-mono focus:outline-none"
|
className="font-mono focus:outline-none"
|
||||||
|
|
|
||||||
|
|
@ -39,7 +39,7 @@ export function PmTypePickerPopover({
|
||||||
autoFocus
|
autoFocus
|
||||||
value={search}
|
value={search}
|
||||||
onChange={(e) => onSearchChange(e.target.value)}
|
onChange={(e) => onSearchChange(e.target.value)}
|
||||||
placeholder="Search PM type…"
|
placeholder="Search service…"
|
||||||
className="w-full rounded border border-border bg-[var(--color-bg-surface)] px-2 py-1 text-xs text-[var(--color-text-primary)] focus:outline-none"
|
className="w-full rounded border border-border bg-[var(--color-bg-surface)] px-2 py-1 text-xs text-[var(--color-text-primary)] focus:outline-none"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ type SiteDialogPocSectionProps = {
|
||||||
pocNotes: string;
|
pocNotes: string;
|
||||||
additionalContacts: WorkOrderAdditionalContact[];
|
additionalContacts: WorkOrderAdditionalContact[];
|
||||||
showPrimaryErrors?: boolean;
|
showPrimaryErrors?: boolean;
|
||||||
|
primaryRequired?: boolean;
|
||||||
onPocNameChange: (value: string) => void;
|
onPocNameChange: (value: string) => void;
|
||||||
onPocPhoneChange: (value: string) => void;
|
onPocPhoneChange: (value: string) => void;
|
||||||
onPocNotesChange: (value: string) => void;
|
onPocNotesChange: (value: string) => void;
|
||||||
|
|
@ -19,6 +20,7 @@ export function SiteDialogPocSection({
|
||||||
pocNotes,
|
pocNotes,
|
||||||
additionalContacts,
|
additionalContacts,
|
||||||
showPrimaryErrors = false,
|
showPrimaryErrors = false,
|
||||||
|
primaryRequired = false,
|
||||||
onPocNameChange,
|
onPocNameChange,
|
||||||
onPocPhoneChange,
|
onPocPhoneChange,
|
||||||
onPocNotesChange,
|
onPocNotesChange,
|
||||||
|
|
@ -31,6 +33,7 @@ export function SiteDialogPocSection({
|
||||||
pocNotes={pocNotes}
|
pocNotes={pocNotes}
|
||||||
additionalContacts={additionalContacts}
|
additionalContacts={additionalContacts}
|
||||||
showPrimaryErrors={showPrimaryErrors}
|
showPrimaryErrors={showPrimaryErrors}
|
||||||
|
primaryRequired={primaryRequired}
|
||||||
onPocNameChange={onPocNameChange}
|
onPocNameChange={onPocNameChange}
|
||||||
onPocPhoneChange={onPocPhoneChange}
|
onPocPhoneChange={onPocPhoneChange}
|
||||||
onPocNotesChange={onPocNotesChange}
|
onPocNotesChange={onPocNotesChange}
|
||||||
|
|
|
||||||
|
|
@ -86,7 +86,7 @@ export function SiteDialog({
|
||||||
|
|
||||||
<fieldset disabled={viewOnly} className="mt-3 space-y-3 border-0 p-0">
|
<fieldset disabled={viewOnly} className="mt-3 space-y-3 border-0 p-0">
|
||||||
<div>
|
<div>
|
||||||
<FieldLabel>Site</FieldLabel>
|
<FieldLabel required={createMode}>Site</FieldLabel>
|
||||||
<WizardFieldSelect
|
<WizardFieldSelect
|
||||||
value={s.locId}
|
value={s.locId}
|
||||||
placeholder="Select site …"
|
placeholder="Select site …"
|
||||||
|
|
@ -130,6 +130,7 @@ export function SiteDialog({
|
||||||
pocNotes={s.notes}
|
pocNotes={s.notes}
|
||||||
additionalContacts={s.extraContacts}
|
additionalContacts={s.extraContacts}
|
||||||
showPrimaryErrors={createMode && s.showErrors}
|
showPrimaryErrors={createMode && s.showErrors}
|
||||||
|
primaryRequired={createMode}
|
||||||
onPocNameChange={s.setPn}
|
onPocNameChange={s.setPn}
|
||||||
onPocPhoneChange={s.setPp}
|
onPocPhoneChange={s.setPp}
|
||||||
onPocNotesChange={s.setNotes}
|
onPocNotesChange={s.setNotes}
|
||||||
|
|
|
||||||
|
|
@ -9,10 +9,10 @@ import {
|
||||||
tableRowToClosabilityInput,
|
tableRowToClosabilityInput,
|
||||||
} from "@/domain/work-orders/utils/wo-closability";
|
} from "@/domain/work-orders/utils/wo-closability";
|
||||||
import {
|
import {
|
||||||
BOARD_INLINE_STATUSES,
|
|
||||||
PAST_DUE_BADGE_TOOLTIP,
|
PAST_DUE_BADGE_TOOLTIP,
|
||||||
PAST_DUE_POPOVER_BODY,
|
PAST_DUE_POPOVER_BODY,
|
||||||
PAST_DUE_RESCHEDULE_CTA,
|
PAST_DUE_RESCHEDULE_CTA,
|
||||||
|
getInlineStatusTransitions,
|
||||||
getStatusOptionState,
|
getStatusOptionState,
|
||||||
} from "@/domain/work-orders/utils/wo-lifecycle-transitions";
|
} from "@/domain/work-orders/utils/wo-lifecycle-transitions";
|
||||||
import { HoverChevron } from "./hover-chevron";
|
import { HoverChevron } from "./hover-chevron";
|
||||||
|
|
@ -27,6 +27,7 @@ type StatusCellProps = {
|
||||||
onPastDueAttempt?: () => void;
|
onPastDueAttempt?: () => void;
|
||||||
onRequestComplete?: () => void;
|
onRequestComplete?: () => void;
|
||||||
readOnly?: boolean;
|
readOnly?: boolean;
|
||||||
|
/** Explicit list for inline create; existing WOs derive valid transitions from `wo.status`. */
|
||||||
statusOptions?: readonly WizardWOStatus[];
|
statusOptions?: readonly WizardWOStatus[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -128,10 +129,11 @@ export function StatusCell({
|
||||||
onPastDueAttempt,
|
onPastDueAttempt,
|
||||||
onRequestComplete,
|
onRequestComplete,
|
||||||
readOnly = false,
|
readOnly = false,
|
||||||
statusOptions = BOARD_INLINE_STATUSES,
|
statusOptions,
|
||||||
}: StatusCellProps) {
|
}: StatusCellProps) {
|
||||||
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
|
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
|
||||||
const closabilityGaps = rowClosabilityGaps(wo);
|
const closabilityGaps = rowClosabilityGaps(wo);
|
||||||
|
const options = statusOptions ?? getInlineStatusTransitions(wo.status);
|
||||||
|
|
||||||
if (readOnly) {
|
if (readOnly) {
|
||||||
return <ReadOnlyStatusLabel status={wo.status} />;
|
return <ReadOnlyStatusLabel status={wo.status} />;
|
||||||
|
|
@ -169,7 +171,7 @@ export function StatusCell({
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
slotProps={{ paper: { className: "min-w-[190px] rounded-lg border border-border p-1" } }}
|
slotProps={{ paper: { className: "min-w-[190px] rounded-lg border border-border p-1" } }}
|
||||||
>
|
>
|
||||||
{statusOptions.map((status) => {
|
{options.map((status) => {
|
||||||
const option = getStatusOptionState(wo, status, closabilityGaps);
|
const option = getStatusOptionState(wo, status, closabilityGaps);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ import { shouldNotifyCrossWeek } from "@/domain/work-orders/utils/should-notify-
|
||||||
import type { ReturnTypeOfUseWorkOrdersTableData } from "./wo-table-types";
|
import type { ReturnTypeOfUseWorkOrdersTableData } from "./wo-table-types";
|
||||||
import { rescheduleNotify, weekMoveNotify } from "./reschedule-notify";
|
import { rescheduleNotify, weekMoveNotify } from "./reschedule-notify";
|
||||||
import type { WoTableRowHandlers } from "./wo-table-row";
|
import type { WoTableRowHandlers } from "./wo-table-row";
|
||||||
|
import { clearDueDateBeforeSchedule } from "@/domain/work-orders/utils/due-date-floor";
|
||||||
|
|
||||||
function revealOrNotifyScheduledDay(args: {
|
function revealOrNotifyScheduledDay(args: {
|
||||||
id: string | number;
|
id: string | number;
|
||||||
|
|
@ -31,6 +32,35 @@ function revealOrNotifyScheduledDay(args: {
|
||||||
revealScheduledRow(id);
|
revealScheduledRow(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type DragHandlersArgs = Pick<
|
||||||
|
ReturnTypeOfUseWorkOrdersTableData,
|
||||||
|
"dragState" | "setDragViz" | "reorderRows" | "endDrag"
|
||||||
|
>;
|
||||||
|
|
||||||
|
function createDragHandlers({ dragState, setDragViz, reorderRows, endDrag }: DragHandlersArgs) {
|
||||||
|
return {
|
||||||
|
onDragStart: (id: string | number) => {
|
||||||
|
dragState.current = { dragId: id, overId: null };
|
||||||
|
setDragViz({ dragId: id, overId: null });
|
||||||
|
},
|
||||||
|
onDragOver: (id: string | number) => {
|
||||||
|
const did = dragState.current.dragId;
|
||||||
|
if (did && did !== id && dragState.current.overId !== id) {
|
||||||
|
dragState.current.overId = id;
|
||||||
|
setDragViz((v) => ({ ...v, overId: id }));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onDrop: () => {
|
||||||
|
const { dragId, overId } = dragState.current;
|
||||||
|
if (dragId && overId) {
|
||||||
|
reorderRows(dragId, overId);
|
||||||
|
}
|
||||||
|
endDrag();
|
||||||
|
},
|
||||||
|
onDragEnd: endDrag,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
type UseWoTableRowHandlersOptions = {
|
type UseWoTableRowHandlersOptions = {
|
||||||
tableData: ReturnTypeOfUseWorkOrdersTableData;
|
tableData: ReturnTypeOfUseWorkOrdersTableData;
|
||||||
weekMonday: string;
|
weekMonday: string;
|
||||||
|
|
@ -101,8 +131,11 @@ export function useWoTableRowHandlers({
|
||||||
onPatch: (id, patch, options) => {
|
onPatch: (id, patch, options) => {
|
||||||
onPatch(id, patch, options);
|
onPatch(id, patch, options);
|
||||||
},
|
},
|
||||||
onScheduleDate: (id: string | number, date: string) => {
|
onScheduleDate: (id: string | number, date: string, dueDate?: string) => {
|
||||||
onPatch(id, applySchedulePatch(date, false));
|
onPatch(id, {
|
||||||
|
...applySchedulePatch(date, false),
|
||||||
|
...clearDueDateBeforeSchedule(dueDate, date),
|
||||||
|
});
|
||||||
revealOrNotifyScheduledDay({
|
revealOrNotifyScheduledDay({
|
||||||
id,
|
id,
|
||||||
date,
|
date,
|
||||||
|
|
@ -111,8 +144,11 @@ export function useWoTableRowHandlers({
|
||||||
revealScheduledRow,
|
revealScheduledRow,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
onScheduleRange: (id: string | number, start: string, end: string) => {
|
onScheduleRange: (id: string | number, start: string, end: string, dueDate?: string) => {
|
||||||
onPatch(id, applyScheduleRangePatch(start, end));
|
onPatch(id, {
|
||||||
|
...applyScheduleRangePatch(start, end),
|
||||||
|
...clearDueDateBeforeSchedule(dueDate, start),
|
||||||
|
});
|
||||||
revealOrNotifyScheduledDay({
|
revealOrNotifyScheduledDay({
|
||||||
id,
|
id,
|
||||||
date: start,
|
date: start,
|
||||||
|
|
@ -121,7 +157,7 @@ export function useWoTableRowHandlers({
|
||||||
revealScheduledRow,
|
revealScheduledRow,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
onScheduleWeek: (id: string | number, week: string) => {
|
onScheduleWeek: (id: string | number, week: string, dueDate?: string) => {
|
||||||
const isClear = week === "";
|
const isClear = week === "";
|
||||||
onPatch(
|
onPatch(
|
||||||
id,
|
id,
|
||||||
|
|
@ -135,6 +171,7 @@ export function useWoTableRowHandlers({
|
||||||
schedMode: "week",
|
schedMode: "week",
|
||||||
dayGroup: "",
|
dayGroup: "",
|
||||||
dayLabel: "",
|
dayLabel: "",
|
||||||
|
...clearDueDateBeforeSchedule(dueDate, week),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
weekMoveNotify(week, {
|
weekMoveNotify(week, {
|
||||||
|
|
@ -153,25 +190,12 @@ export function useWoTableRowHandlers({
|
||||||
onRequestComplete,
|
onRequestComplete,
|
||||||
onPastDueAttempt: (id: string | number) => onScheduleHighlight(id),
|
onPastDueAttempt: (id: string | number) => onScheduleHighlight(id),
|
||||||
onReorder: reorderRows,
|
onReorder: reorderRows,
|
||||||
onDragStart: (id: string | number) => {
|
...createDragHandlers({
|
||||||
dragStateRef.current = { dragId: id, overId: null };
|
dragState: dragStateRef,
|
||||||
setDragViz({ dragId: id, overId: null });
|
setDragViz,
|
||||||
},
|
reorderRows,
|
||||||
onDragOver: (id: string | number) => {
|
endDrag,
|
||||||
const did = dragStateRef.current.dragId;
|
}),
|
||||||
if (did && did !== id && dragStateRef.current.overId !== id) {
|
|
||||||
dragStateRef.current.overId = id;
|
|
||||||
setDragViz((v) => ({ ...v, overId: id }));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onDrop: () => {
|
|
||||||
const { dragId, overId } = dragStateRef.current;
|
|
||||||
if (dragId && overId) {
|
|
||||||
reorderRows(dragId, overId);
|
|
||||||
}
|
|
||||||
endDrag();
|
|
||||||
},
|
|
||||||
onDragEnd: endDrag,
|
|
||||||
}),
|
}),
|
||||||
[
|
[
|
||||||
tableData,
|
tableData,
|
||||||
|
|
|
||||||
|
|
@ -11,9 +11,10 @@ export const WO_TABLE_COLS = [
|
||||||
{ key: "vendor", label: "VENDOR", w: 184 },
|
{ key: "vendor", label: "VENDOR", w: 184 },
|
||||||
{ key: "appt", label: "APPT TIME", w: 128 },
|
{ key: "appt", label: "APPT TIME", w: 128 },
|
||||||
{ key: "status", label: "STATUS", w: 148 },
|
{ key: "status", label: "STATUS", w: 148 },
|
||||||
|
// Completed Date gates the Completion Document, so it sits between Status and Comp Doc.
|
||||||
|
{ key: "completed", label: "COMPLETED DATE", w: 130 },
|
||||||
{ key: "doc", label: "COMP DOC", w: 84 },
|
{ key: "doc", label: "COMP DOC", w: 84 },
|
||||||
{ key: "uplift", label: "UPLIFT", w: 108 },
|
{ key: "uplift", label: "UPLIFT", w: 108 },
|
||||||
{ key: "completed", label: "COMPLETED DATE", w: 130 },
|
|
||||||
{ key: "actions", label: "", w: 100 },
|
{ key: "actions", label: "", w: 100 },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import { WO_TABLE_COLS } from "./wo-table-cols";
|
import { WO_TABLE_COLS } from "./wo-table-cols";
|
||||||
|
import { WoTableHeaderLabel } from "./wo-table-header-label";
|
||||||
|
|
||||||
export function WoTableHead() {
|
export function WoTableHead() {
|
||||||
return (
|
return (
|
||||||
|
|
@ -25,7 +26,7 @@ export function WoTableHead() {
|
||||||
borderBottom: "1px solid var(--border)",
|
borderBottom: "1px solid var(--border)",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{col.label}
|
<WoTableHeaderLabel colKey={col.key} label={col.label} />
|
||||||
{Boolean(srLabel) && <span className="sr-only">{srLabel}</span>}
|
{Boolean(srLabel) && <span className="sr-only">{srLabel}</span>}
|
||||||
</th>
|
</th>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
import { Tooltip } from "@mui/material";
|
||||||
|
import { CircleQuestionMark } from "lucide-react";
|
||||||
|
|
||||||
|
import { getWoTableHeaderTooltip } from "@/domain/work-orders/constants/wo-table-header-tooltips";
|
||||||
|
|
||||||
|
type WoTableHeaderLabelProps = {
|
||||||
|
colKey: string;
|
||||||
|
label: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function WoTableHeaderLabel({ colKey, label }: WoTableHeaderLabelProps) {
|
||||||
|
const tooltip = getWoTableHeaderTooltip(colKey);
|
||||||
|
|
||||||
|
if (!tooltip) {
|
||||||
|
return <>{label}</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
|
||||||
|
{label}
|
||||||
|
<Tooltip title={tooltip} arrow placement="top">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={`${label} column help`}
|
||||||
|
style={{
|
||||||
|
display: "inline-flex",
|
||||||
|
cursor: "help",
|
||||||
|
color: "var(--color-text-muted)",
|
||||||
|
padding: 0,
|
||||||
|
border: 0,
|
||||||
|
background: "transparent",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CircleQuestionMark size={13} aria-hidden="true" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -89,6 +89,7 @@ export function WoTableInlineIdentityCells({
|
||||||
allOrders={allRows as never[]}
|
allOrders={allRows as never[]}
|
||||||
onSave={(v) => onPatch({ woNumber: v })}
|
onSave={(v) => onPatch({ woNumber: v })}
|
||||||
onDuplicateFound={onDuplicateFound}
|
onDuplicateFound={onDuplicateFound}
|
||||||
|
requiredPlaceholder="Insert WO #"
|
||||||
/>
|
/>
|
||||||
<AddOnOverrideToggle
|
<AddOnOverrideToggle
|
||||||
checked={draft.isAddOnOverride}
|
checked={draft.isAddOnOverride}
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ export function WoTableInlineRowActions({
|
||||||
onCancel,
|
onCancel,
|
||||||
}: WoTableInlineRowActionsProps) {
|
}: WoTableInlineRowActionsProps) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-0.5">
|
<div className="flex items-center gap-0.5" style={{ minHeight: 34 }}>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onSave}
|
onClick={onSave}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import type { RefObject } from "react";
|
import type { ReactNode, RefObject } from "react";
|
||||||
import type {
|
import type {
|
||||||
LocationOption,
|
LocationOption,
|
||||||
VendorDropdownItem,
|
VendorDropdownItem,
|
||||||
|
|
@ -21,8 +21,13 @@ import { StatusCell } from "./cells/status-cell";
|
||||||
import { TypeCell } from "./cells/type-cell";
|
import { TypeCell } from "./cells/type-cell";
|
||||||
import { VendorCell } from "./cells/vendor-cell";
|
import { VendorCell } from "./cells/vendor-cell";
|
||||||
import { toVendorTablePatch } from "@/domain/work-orders/utils/vendor-assignment-patch";
|
import { toVendorTablePatch } from "@/domain/work-orders/utils/vendor-assignment-patch";
|
||||||
|
import { InlineCreateField } from "./inline-create-field";
|
||||||
import { toInlineDraftRow } from "./to-inline-draft-row";
|
import { toInlineDraftRow } from "./to-inline-draft-row";
|
||||||
import { WoTableInlineIdentityCells } from "./wo-table-inline-identity-cells";
|
import { WoTableInlineIdentityCells } from "./wo-table-inline-identity-cells";
|
||||||
|
import {
|
||||||
|
clearDueDateBeforeSchedule,
|
||||||
|
resolveDueDateFloor,
|
||||||
|
} from "@/domain/work-orders/utils/due-date-floor";
|
||||||
|
|
||||||
type WoTableInlineRowCellsProps = {
|
type WoTableInlineRowCellsProps = {
|
||||||
draft: WorkOrderTableDraft;
|
draft: WorkOrderTableDraft;
|
||||||
|
|
@ -43,6 +48,17 @@ type WoTableInlineRowCellsProps = {
|
||||||
onRequestComplete?: () => void;
|
onRequestComplete?: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Matches the identity cells: top-aligned so field boxes and error helpers line up. */
|
||||||
|
const INLINE_FIELD_TD_STYLE = { padding: "8px 6px 0", verticalAlign: "top" } as const;
|
||||||
|
|
||||||
|
function InlineFieldCell({ children }: { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<td className="group/cell" style={INLINE_FIELD_TD_STYLE}>
|
||||||
|
<InlineCreateField>{children}</InlineCreateField>
|
||||||
|
</td>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function InlineTypeSeverityCell({
|
function InlineTypeSeverityCell({
|
||||||
draft,
|
draft,
|
||||||
onPatch,
|
onPatch,
|
||||||
|
|
@ -51,20 +67,22 @@ function InlineTypeSeverityCell({
|
||||||
onPatch: (patch: Partial<WorkOrderTableDraft>) => void;
|
onPatch: (patch: Partial<WorkOrderTableDraft>) => void;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<td className="group/cell" style={{ padding: "0 14px" }}>
|
<InlineFieldCell>
|
||||||
<TypeCell
|
<TypeCell
|
||||||
value={draft.type}
|
value={draft.type}
|
||||||
severity={draft.severity}
|
severity={draft.severity}
|
||||||
onSave={(t, sev) => onPatch({ type: t, severity: sev })}
|
onSave={(t, sev) => onPatch({ type: t, severity: sev })}
|
||||||
/>
|
/>
|
||||||
</td>
|
</InlineFieldCell>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function InlineMutedDashCell() {
|
function InlineMutedDashCell() {
|
||||||
return (
|
return (
|
||||||
<td style={{ padding: "0 14px" }}>
|
<td style={INLINE_FIELD_TD_STYLE}>
|
||||||
<span style={{ fontSize: 11, color: "var(--color-text-muted)" }}>—</span>
|
<div className="flex items-center" style={{ minHeight: 34 }}>
|
||||||
|
<span style={{ fontSize: 11, color: "var(--color-text-muted)" }}>—</span>
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -81,18 +99,18 @@ function InlineScheduleOnCell({
|
||||||
const hasSchedule =
|
const hasSchedule =
|
||||||
Boolean(draft.scheduledOn) || Boolean(draft.targetWeek) || Boolean(draft.scheduleEnd);
|
Boolean(draft.scheduledOn) || Boolean(draft.targetWeek) || Boolean(draft.scheduleEnd);
|
||||||
return (
|
return (
|
||||||
<td className="group/cell" style={{ padding: "0 14px" }}>
|
<InlineFieldCell>
|
||||||
<DateCell
|
<DateCell
|
||||||
value={draft.scheduledOn}
|
value={draft.scheduledOn}
|
||||||
allowWeekMode
|
allowWeekMode
|
||||||
targetWeek={draft.targetWeek}
|
targetWeek={draft.targetWeek}
|
||||||
defaultMode={weekDefault ? "week" : "date"}
|
defaultMode={weekDefault ? "week" : "date"}
|
||||||
highlight={!draft.scheduledOn && !draft.targetWeek}
|
|
||||||
scheduleEnd={draft.scheduleEnd}
|
scheduleEnd={draft.scheduleEnd}
|
||||||
schedMode={draft.schedMode}
|
schedMode={draft.schedMode}
|
||||||
onSave={(date) =>
|
onSave={(date) =>
|
||||||
onPatch(
|
onPatch(
|
||||||
withAutoScheduleStatus(draft, {
|
withAutoScheduleStatus(draft, {
|
||||||
|
...clearDueDateBeforeSchedule(draft.dueDate, date),
|
||||||
scheduledOn: date,
|
scheduledOn: date,
|
||||||
scheduleWeekOnly: false,
|
scheduleWeekOnly: false,
|
||||||
targetWeek: "",
|
targetWeek: "",
|
||||||
|
|
@ -105,6 +123,7 @@ function InlineScheduleOnCell({
|
||||||
onSaveWeek={(week) =>
|
onSaveWeek={(week) =>
|
||||||
onPatch(
|
onPatch(
|
||||||
withAutoScheduleStatus(draft, {
|
withAutoScheduleStatus(draft, {
|
||||||
|
...clearDueDateBeforeSchedule(draft.dueDate, week),
|
||||||
scheduledOn: "",
|
scheduledOn: "",
|
||||||
targetWeek: week,
|
targetWeek: week,
|
||||||
scheduleWeekOnly: true,
|
scheduleWeekOnly: true,
|
||||||
|
|
@ -117,6 +136,7 @@ function InlineScheduleOnCell({
|
||||||
onSaveRange={(start, end) =>
|
onSaveRange={(start, end) =>
|
||||||
onPatch(
|
onPatch(
|
||||||
withAutoScheduleStatus(draft, {
|
withAutoScheduleStatus(draft, {
|
||||||
|
...clearDueDateBeforeSchedule(draft.dueDate, start),
|
||||||
scheduledOn: start,
|
scheduledOn: start,
|
||||||
scheduleEnd: end,
|
scheduleEnd: end,
|
||||||
schedMode: "range",
|
schedMode: "range",
|
||||||
|
|
@ -142,7 +162,7 @@ function InlineScheduleOnCell({
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</td>
|
</InlineFieldCell>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -184,26 +204,26 @@ export function WoTableInlineRowCells({
|
||||||
|
|
||||||
<InlineTypeSeverityCell draft={draft} onPatch={onPatch} />
|
<InlineTypeSeverityCell draft={draft} onPatch={onPatch} />
|
||||||
|
|
||||||
<td className="group/cell" style={{ padding: "0 14px" }}>
|
<InlineFieldCell>
|
||||||
<AssignedToCell
|
<AssignedToCell
|
||||||
dispatcherId={draft.dispatcherId}
|
dispatcherId={draft.dispatcherId}
|
||||||
users={users}
|
users={users}
|
||||||
highlight={!draft.dispatcherId}
|
|
||||||
onSave={(id) => {
|
onSave={(id) => {
|
||||||
onPatch({ dispatcherId: id, status: draft.status || "Incomplete" });
|
onPatch({ dispatcherId: id, status: draft.status || "Incomplete" });
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</td>
|
</InlineFieldCell>
|
||||||
<InlineScheduleOnCell draft={draft} weekDefault={weekDefault} onPatch={onPatch} />
|
<InlineScheduleOnCell draft={draft} weekDefault={weekDefault} onPatch={onPatch} />
|
||||||
|
|
||||||
<td className="group/cell" style={{ padding: "0 14px" }}>
|
<InlineFieldCell>
|
||||||
<DueDateCell
|
<DueDateCell
|
||||||
type={draft.type}
|
type={draft.type}
|
||||||
value={draft.dueDate}
|
value={draft.dueDate}
|
||||||
|
minDate={resolveDueDateFloor(draft)}
|
||||||
onSave={(date) => onPatch({ dueDate: date })}
|
onSave={(date) => onPatch({ dueDate: date })}
|
||||||
/>
|
/>
|
||||||
</td>
|
</InlineFieldCell>
|
||||||
<td className="group/cell" style={{ padding: "0 14px" }}>
|
<InlineFieldCell>
|
||||||
<PMTypeCell
|
<PMTypeCell
|
||||||
value={draft.pm}
|
value={draft.pm}
|
||||||
pmTypes={pmTypes}
|
pmTypes={pmTypes}
|
||||||
|
|
@ -221,8 +241,8 @@ export function WoTableInlineRowCells({
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</td>
|
</InlineFieldCell>
|
||||||
<td className="group/cell" style={{ padding: "0 14px" }}>
|
<InlineFieldCell>
|
||||||
<VendorCell
|
<VendorCell
|
||||||
vendorId={draft.vendorId}
|
vendorId={draft.vendorId}
|
||||||
company={draft.company}
|
company={draft.company}
|
||||||
|
|
@ -231,8 +251,8 @@ export function WoTableInlineRowCells({
|
||||||
vendors={vendors}
|
vendors={vendors}
|
||||||
onSave={(p) => onPatch(toVendorTablePatch(p))}
|
onSave={(p) => onPatch(toVendorTablePatch(p))}
|
||||||
/>
|
/>
|
||||||
</td>
|
</InlineFieldCell>
|
||||||
<td className="group/cell" style={{ padding: "0 14px" }}>
|
<InlineFieldCell>
|
||||||
<ApptTimeCell
|
<ApptTimeCell
|
||||||
apptTime={
|
apptTime={
|
||||||
draft.apptStart ? `${draft.apptStart}${draft.apptEnd ? ` – ${draft.apptEnd}` : ""}` : ""
|
draft.apptStart ? `${draft.apptStart}${draft.apptEnd ? ` – ${draft.apptEnd}` : ""}` : ""
|
||||||
|
|
@ -242,8 +262,8 @@ export function WoTableInlineRowCells({
|
||||||
onPatch({ apptStart: start ?? "", apptEnd: end ?? "" });
|
onPatch({ apptStart: start ?? "", apptEnd: end ?? "" });
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</td>
|
</InlineFieldCell>
|
||||||
<td className="group/cell" style={{ padding: "0 14px" }}>
|
<InlineFieldCell>
|
||||||
<StatusCell
|
<StatusCell
|
||||||
wo={draftRow as never}
|
wo={draftRow as never}
|
||||||
statusOptions={CREATION_INLINE_STATUSES}
|
statusOptions={CREATION_INLINE_STATUSES}
|
||||||
|
|
@ -251,7 +271,7 @@ export function WoTableInlineRowCells({
|
||||||
onOpenSlideOver={() => {}}
|
onOpenSlideOver={() => {}}
|
||||||
onRequestComplete={onRequestComplete}
|
onRequestComplete={onRequestComplete}
|
||||||
/>
|
/>
|
||||||
</td>
|
</InlineFieldCell>
|
||||||
|
|
||||||
<InlineMutedDashCell />
|
<InlineMutedDashCell />
|
||||||
<InlineMutedDashCell />
|
<InlineMutedDashCell />
|
||||||
|
|
|
||||||
|
|
@ -115,15 +115,17 @@ export function WoTableInlineRow({
|
||||||
pointerEvents: saving ? "none" : undefined,
|
pointerEvents: saving ? "none" : undefined,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<td style={{ padding: "0 0 0 6px" }} />
|
<td style={{ padding: "8px 0 0 6px", verticalAlign: "top" }} />
|
||||||
|
|
||||||
<td style={{ padding: "0 2px 0 8px" }}>
|
<td style={{ padding: "8px 2px 0 8px", verticalAlign: "top" }}>
|
||||||
<Flag
|
<div className="flex items-center" style={{ minHeight: 34 }}>
|
||||||
size={14}
|
<Flag
|
||||||
strokeWidth={1.75}
|
size={14}
|
||||||
aria-hidden="true"
|
strokeWidth={1.75}
|
||||||
style={{ color: "var(--color-border)" }}
|
aria-hidden="true"
|
||||||
/>
|
style={{ color: "var(--color-border)" }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
<WoTableInlineRowCells
|
<WoTableInlineRowCells
|
||||||
|
|
@ -145,7 +147,7 @@ export function WoTableInlineRow({
|
||||||
onRequestComplete={() => setConfirmComplete(true)}
|
onRequestComplete={() => setConfirmComplete(true)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<td style={{ padding: "0 4px" }}>
|
<td style={{ padding: "8px 4px 0", verticalAlign: "top" }}>
|
||||||
<WoTableInlineRowActions
|
<WoTableInlineRowActions
|
||||||
canSave={canSave}
|
canSave={canSave}
|
||||||
saving={saving}
|
saving={saving}
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ import { EditableWONumberCell } from "./cells/editable-wo-number-cell";
|
||||||
import { SiteCell } from "./cells/site-cell";
|
import { SiteCell } from "./cells/site-cell";
|
||||||
import { TypeCell } from "./cells/type-cell";
|
import { TypeCell } from "./cells/type-cell";
|
||||||
import type { WoTableRowHandlers } from "./wo-table-row";
|
import type { WoTableRowHandlers } from "./wo-table-row";
|
||||||
|
import { resolveDueDateFloor } from "@/domain/work-orders/utils/due-date-floor";
|
||||||
|
|
||||||
type WoTableRowCellsProps = {
|
type WoTableRowCellsProps = {
|
||||||
row: WorkOrderTableRow;
|
row: WorkOrderTableRow;
|
||||||
|
|
@ -146,9 +147,9 @@ export function WoTableRowCells({
|
||||||
targetWeek={row.targetWeek}
|
targetWeek={row.targetWeek}
|
||||||
scheduleEnd={row.scheduleEnd}
|
scheduleEnd={row.scheduleEnd}
|
||||||
schedMode={row.schedMode}
|
schedMode={row.schedMode}
|
||||||
onSave={(date) => handlers.onScheduleDate(row.id, date)}
|
onSave={(date) => handlers.onScheduleDate(row.id, date, row.dueDate)}
|
||||||
onSaveWeek={(week) => handlers.onScheduleWeek(row.id, week)}
|
onSaveWeek={(week) => handlers.onScheduleWeek(row.id, week, row.dueDate)}
|
||||||
onSaveRange={(start, end) => handlers.onScheduleRange(row.id, start, end)}
|
onSaveRange={(start, end) => handlers.onScheduleRange(row.id, start, end, row.dueDate)}
|
||||||
onClear={hasSchedule && !viewOnly ? () => handlers.onScheduleWeek(row.id, "") : undefined}
|
onClear={hasSchedule && !viewOnly ? () => handlers.onScheduleWeek(row.id, "") : undefined}
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
|
|
@ -163,6 +164,7 @@ export function WoTableRowCells({
|
||||||
q={search}
|
q={search}
|
||||||
highlight={forceDueDateHighlight || row.isPastDue}
|
highlight={forceDueDateHighlight || row.isPastDue}
|
||||||
pastDue={row.isPastDue}
|
pastDue={row.isPastDue}
|
||||||
|
minDate={resolveDueDateFloor(row)}
|
||||||
onSave={(date) => onPatchRow({ dueDate: date })}
|
onSave={(date) => onPatchRow({ dueDate: date })}
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
|
|
|
||||||
|
|
@ -105,6 +105,17 @@ export function WoTableRowServiceCells({
|
||||||
onRequestComplete={() => handlers.onRequestComplete?.(row)}
|
onRequestComplete={() => handlers.onRequestComplete?.(row)}
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
|
<td
|
||||||
|
className="group/cell"
|
||||||
|
style={{ padding: "0 14px", ...mutationCellStyle }}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<DateCell
|
||||||
|
value={row.completedDate}
|
||||||
|
q={search}
|
||||||
|
onSave={(date) => onPatchRow({ completedDate: date })}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
<td style={{ padding: "0 14px" }} onClick={(e) => e.stopPropagation()}>
|
<td style={{ padding: "0 14px" }} onClick={(e) => e.stopPropagation()}>
|
||||||
<CompDocCell
|
<CompDocCell
|
||||||
status={row.docStatus}
|
status={row.docStatus}
|
||||||
|
|
@ -126,17 +137,6 @@ export function WoTableRowServiceCells({
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
<td
|
|
||||||
className="group/cell"
|
|
||||||
style={{ padding: "0 14px", ...mutationCellStyle }}
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
|
||||||
<DateCell
|
|
||||||
value={row.completedDate}
|
|
||||||
q={search}
|
|
||||||
onSave={(date) => onPatchRow({ completedDate: date })}
|
|
||||||
/>
|
|
||||||
</td>
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -36,9 +36,10 @@ export type WoTableRowHandlers = {
|
||||||
patch: Partial<WorkOrderTableRow>,
|
patch: Partial<WorkOrderTableRow>,
|
||||||
options?: WorkOrderTablePatchOptions,
|
options?: WorkOrderTablePatchOptions,
|
||||||
) => void;
|
) => void;
|
||||||
onScheduleDate: (id: string | number, date: string) => void;
|
/** `dueDate` is the row's current Due Date, cleared when the new schedule passes it (SH-356). */
|
||||||
onScheduleWeek: (id: string | number, week: string) => void;
|
onScheduleDate: (id: string | number, date: string, dueDate?: string) => void;
|
||||||
onScheduleRange: (id: string | number, start: string, end: string) => void;
|
onScheduleWeek: (id: string | number, week: string, dueDate?: string) => void;
|
||||||
|
onScheduleRange: (id: string | number, start: string, end: string, dueDate?: string) => void;
|
||||||
onDuplicateFound?: (existing: WorkOrderTableRow) => void;
|
onDuplicateFound?: (existing: WorkOrderTableRow) => void;
|
||||||
onOpenSlideOver: (row: WorkOrderTableRow) => void;
|
onOpenSlideOver: (row: WorkOrderTableRow) => void;
|
||||||
onRequestComplete?: (row: WorkOrderTableRow) => void;
|
onRequestComplete?: (row: WorkOrderTableRow) => void;
|
||||||
|
|
@ -77,17 +78,17 @@ function guardScheduleHandlers(
|
||||||
if (!canApplyWorkOrderTablePatch(row.status, patch)) return;
|
if (!canApplyWorkOrderTablePatch(row.status, patch)) return;
|
||||||
handlers.onPatch(id, patch, options);
|
handlers.onPatch(id, patch, options);
|
||||||
},
|
},
|
||||||
onScheduleDate: (id, date) => {
|
onScheduleDate: (id, date, dueDate) => {
|
||||||
if (!canApplyWorkOrderTablePatch(row.status, { scheduledOn: date })) return;
|
if (!canApplyWorkOrderTablePatch(row.status, { scheduledOn: date })) return;
|
||||||
handlers.onScheduleDate(id, date);
|
handlers.onScheduleDate(id, date, dueDate);
|
||||||
},
|
},
|
||||||
onScheduleWeek: (id, week) => {
|
onScheduleWeek: (id, week, dueDate) => {
|
||||||
if (!canApplyWorkOrderTablePatch(row.status, { targetWeek: week })) return;
|
if (!canApplyWorkOrderTablePatch(row.status, { targetWeek: week })) return;
|
||||||
handlers.onScheduleWeek(id, week);
|
handlers.onScheduleWeek(id, week, dueDate);
|
||||||
},
|
},
|
||||||
onScheduleRange: (id, start, end) => {
|
onScheduleRange: (id, start, end, dueDate) => {
|
||||||
if (!canApplyWorkOrderTablePatch(row.status, { scheduledOn: start })) return;
|
if (!canApplyWorkOrderTablePatch(row.status, { scheduledOn: start })) return;
|
||||||
handlers.onScheduleRange(id, start, end);
|
handlers.onScheduleRange(id, start, end, dueDate);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,31 +5,49 @@ import { ToolbarButton } from "@/components/ui/toolbar-button";
|
||||||
|
|
||||||
type WorkOrdersListHeaderProps = {
|
type WorkOrdersListHeaderProps = {
|
||||||
search: string;
|
search: string;
|
||||||
|
/** Compact label of the active board week (e.g. "5/4–5/8"). */
|
||||||
|
weekLabel: string;
|
||||||
onSearchChange: (value: string) => void;
|
onSearchChange: (value: string) => void;
|
||||||
/** Omit until Advanced Search slice mounts the sheet. */
|
/** Omit until Advanced Search slice mounts the sheet. */
|
||||||
onOpenAdvancedFilters?: () => void;
|
onOpenAdvancedFilters?: () => void;
|
||||||
/** Omit until wizard shell slice mounts New WO. */
|
/** Omit until wizard shell slice mounts New WO. */
|
||||||
onNewWorkOrder?: () => void;
|
onNewWorkOrder?: () => void;
|
||||||
activeFilterCount: number;
|
activeFilterCount: number;
|
||||||
|
/** True while Advanced Filters are applied; results are global and the keyword box is inert. */
|
||||||
|
advancedFiltersActive?: boolean;
|
||||||
isFetching?: boolean;
|
isFetching?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function WorkOrdersListHeader({
|
export function WorkOrdersListHeader({
|
||||||
search,
|
search,
|
||||||
|
weekLabel,
|
||||||
onSearchChange,
|
onSearchChange,
|
||||||
onOpenAdvancedFilters,
|
onOpenAdvancedFilters,
|
||||||
onNewWorkOrder,
|
onNewWorkOrder,
|
||||||
activeFilterCount,
|
activeFilterCount,
|
||||||
|
advancedFiltersActive = false,
|
||||||
isFetching = false,
|
isFetching = false,
|
||||||
}: WorkOrdersListHeaderProps) {
|
}: WorkOrdersListHeaderProps) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SearchInput
|
<div className="relative">
|
||||||
value={search}
|
<SearchInput
|
||||||
onChange={onSearchChange}
|
value={search}
|
||||||
placeholder="Search this week…"
|
onChange={onSearchChange}
|
||||||
aria-label="Search work orders"
|
placeholder="Search this week…"
|
||||||
/>
|
aria-label="Search work orders"
|
||||||
|
/>
|
||||||
|
{/* Keyword search is scoped to the active week; make that scope visible. */}
|
||||||
|
{!advancedFiltersActive && search.trim() !== "" && Boolean(weekLabel) && (
|
||||||
|
<span
|
||||||
|
role="status"
|
||||||
|
className="absolute left-0 whitespace-nowrap text-(length:--text-xs) text-muted-foreground"
|
||||||
|
style={{ top: "calc(100% + 4px)" }}
|
||||||
|
>
|
||||||
|
Searching within {weekLabel}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{Boolean(onOpenAdvancedFilters) && (
|
{Boolean(onOpenAdvancedFilters) && (
|
||||||
<ToolbarButton
|
<ToolbarButton
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
import { useId } from "react";
|
||||||
import { Plus, Trash2 } from "lucide-react";
|
import { Plus, Trash2 } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Text } from "@/components/ui/text";
|
import { Text } from "@/components/ui/text";
|
||||||
|
|
@ -23,6 +24,8 @@ type PocContactFieldsProps = {
|
||||||
onAdditionalContactsChange: (contacts: WorkOrderAdditionalContact[]) => void;
|
onAdditionalContactsChange: (contacts: WorkOrderAdditionalContact[]) => void;
|
||||||
helperText?: string;
|
helperText?: string;
|
||||||
showPrimaryErrors?: boolean;
|
showPrimaryErrors?: boolean;
|
||||||
|
/** Labels the primary name/phone inputs with a persistent required asterisk. */
|
||||||
|
primaryRequired?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
function extraNameMissing(contact: WorkOrderAdditionalContact): boolean {
|
function extraNameMissing(contact: WorkOrderAdditionalContact): boolean {
|
||||||
|
|
@ -135,7 +138,9 @@ export function PocContactFields({
|
||||||
onAdditionalContactsChange,
|
onAdditionalContactsChange,
|
||||||
helperText,
|
helperText,
|
||||||
showPrimaryErrors = false,
|
showPrimaryErrors = false,
|
||||||
|
primaryRequired = false,
|
||||||
}: PocContactFieldsProps) {
|
}: PocContactFieldsProps) {
|
||||||
|
const fieldId = useId();
|
||||||
const nameMissing = showPrimaryErrors && !pocName.trim();
|
const nameMissing = showPrimaryErrors && !pocName.trim();
|
||||||
const phoneMissing = showPrimaryErrors && !pocPhone.trim();
|
const phoneMissing = showPrimaryErrors && !pocPhone.trim();
|
||||||
|
|
||||||
|
|
@ -153,7 +158,13 @@ export function PocContactFields({
|
||||||
)}
|
)}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div>
|
<div>
|
||||||
|
{primaryRequired && (
|
||||||
|
<FieldLabel required htmlFor={`${fieldId}-name`}>
|
||||||
|
POC name
|
||||||
|
</FieldLabel>
|
||||||
|
)}
|
||||||
<input
|
<input
|
||||||
|
id={`${fieldId}-name`}
|
||||||
value={pocName}
|
value={pocName}
|
||||||
onChange={(event) => onPocNameChange(event.target.value)}
|
onChange={(event) => onPocNameChange(event.target.value)}
|
||||||
placeholder="POC name"
|
placeholder="POC name"
|
||||||
|
|
@ -168,7 +179,13 @@ export function PocContactFields({
|
||||||
</Text>
|
</Text>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
|
{primaryRequired && (
|
||||||
|
<FieldLabel required htmlFor={`${fieldId}-phone`}>
|
||||||
|
POC phone
|
||||||
|
</FieldLabel>
|
||||||
|
)}
|
||||||
<input
|
<input
|
||||||
|
id={`${fieldId}-phone`}
|
||||||
value={pocPhone}
|
value={pocPhone}
|
||||||
onChange={(event) => onPocPhoneChange(event.target.value)}
|
onChange={(event) => onPocPhoneChange(event.target.value)}
|
||||||
placeholder="POC phone"
|
placeholder="POC phone"
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,8 @@ type MiniCalendarProps = {
|
||||||
range?: boolean;
|
range?: boolean;
|
||||||
rangeStart?: string;
|
rangeStart?: string;
|
||||||
rangeEnd?: string;
|
rangeEnd?: string;
|
||||||
|
/** Days before this ISO date are disabled (SH-356 Due Date floor). */
|
||||||
|
minDate?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function MiniCalendar({
|
export function MiniCalendar({
|
||||||
|
|
@ -20,9 +22,11 @@ export function MiniCalendar({
|
||||||
range,
|
range,
|
||||||
rangeStart = "",
|
rangeStart = "",
|
||||||
rangeEnd = "",
|
rangeEnd = "",
|
||||||
|
minDate = "",
|
||||||
}: MiniCalendarProps) {
|
}: MiniCalendarProps) {
|
||||||
const initRaw = range ? rangeStart || value : value;
|
const initRaw = range ? rangeStart || value : value;
|
||||||
const init = /^\d{4}-\d{2}-\d{2}$/.test(initRaw) ? initRaw : todayIso();
|
const fallback = minDate > todayIso() ? minDate : todayIso();
|
||||||
|
const init = /^\d{4}-\d{2}-\d{2}$/.test(initRaw) ? initRaw : fallback;
|
||||||
const [iy, im] = init.split("-").map(Number);
|
const [iy, im] = init.split("-").map(Number);
|
||||||
const [viewY, setViewY] = useState(iy);
|
const [viewY, setViewY] = useState(iy);
|
||||||
const [viewM, setViewM] = useState(im);
|
const [viewM, setViewM] = useState(im);
|
||||||
|
|
@ -94,6 +98,7 @@ export function MiniCalendar({
|
||||||
}
|
}
|
||||||
const iso = `${viewY}-${pad2(viewM)}-${pad2(day)}`;
|
const iso = `${viewY}-${pad2(viewM)}-${pad2(day)}`;
|
||||||
const isToday = iso === today;
|
const isToday = iso === today;
|
||||||
|
const beforeMin = Boolean(minDate) && iso < minDate;
|
||||||
const { bg, fg, radius, filled } = getMiniCalendarCellStyle({
|
const { bg, fg, radius, filled } = getMiniCalendarCellStyle({
|
||||||
iso,
|
iso,
|
||||||
value,
|
value,
|
||||||
|
|
@ -107,8 +112,9 @@ export function MiniCalendar({
|
||||||
<button
|
<button
|
||||||
key={i}
|
key={i}
|
||||||
type="button"
|
type="button"
|
||||||
|
disabled={beforeMin}
|
||||||
onClick={() => onChange(iso)}
|
onClick={() => onChange(iso)}
|
||||||
className="text-center text-[12px] transition-colors hover:bg-[var(--color-primary-tint)]"
|
className="text-center text-[12px] transition-colors hover:bg-[var(--color-primary-tint)] disabled:cursor-not-allowed disabled:bg-transparent disabled:opacity-40"
|
||||||
style={{
|
style={{
|
||||||
height: 26,
|
height: 26,
|
||||||
borderRadius: radius,
|
borderRadius: radius,
|
||||||
|
|
|
||||||
|
|
@ -82,7 +82,10 @@ export function NewWoWizard({
|
||||||
locationDetail={wizard.locationDetail}
|
locationDetail={wizard.locationDetail}
|
||||||
locationDetailLoading={wizard.locationDetailLoading}
|
locationDetailLoading={wizard.locationDetailLoading}
|
||||||
locationDetailError={wizard.locationDetailError}
|
locationDetailError={wizard.locationDetailError}
|
||||||
services={wizard.problems.map((p) => ({ id: p.id, value: p.value }))}
|
services={wizard.services.map((service) => ({
|
||||||
|
id: service.id,
|
||||||
|
value: service.name,
|
||||||
|
}))}
|
||||||
showErrors={wizard.showErrors}
|
showErrors={wizard.showErrors}
|
||||||
svcOpen={wizard.svcOpen}
|
svcOpen={wizard.svcOpen}
|
||||||
onSvcOpenChange={wizard.setSvcOpen}
|
onSvcOpenChange={wizard.setSvcOpen}
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,6 @@ import { useEffect } from "react";
|
||||||
|
|
||||||
import { guardDialogClose } from "@/lib/dialog-guard";
|
import { guardDialogClose } from "@/lib/dialog-guard";
|
||||||
|
|
||||||
import { useDropdownOptionsByCategory } from "@/domain/settings/dropdown-options/use-cases/use-dropdown-options-by-category";
|
|
||||||
|
|
||||||
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
||||||
import type { WorkOrderWizardDraft } from "@/domain/work-orders/types/work-order-wizard";
|
import type { WorkOrderWizardDraft } from "@/domain/work-orders/types/work-order-wizard";
|
||||||
|
|
||||||
|
|
@ -16,6 +14,7 @@ import { useCreateWorkOrderFromWizard } from "@/domain/work-orders/use-cases/use
|
||||||
import { useNewWoWizardDraft } from "@/app/(protected)/workorders/_components/wizard/use-new-wo-wizard-draft";
|
import { useNewWoWizardDraft } from "@/app/(protected)/workorders/_components/wizard/use-new-wo-wizard-draft";
|
||||||
import { useWizardDuplicateActions } from "@/app/(protected)/workorders/_components/wizard/use-wizard-duplicate-actions";
|
import { useWizardDuplicateActions } from "@/app/(protected)/workorders/_components/wizard/use-wizard-duplicate-actions";
|
||||||
import { useWizardPocAutofill } from "@/app/(protected)/workorders/_components/wizard/use-wizard-poc-autofill";
|
import { useWizardPocAutofill } from "@/app/(protected)/workorders/_components/wizard/use-wizard-poc-autofill";
|
||||||
|
import { useServicesForWorkOrderType } from "@/domain/services/use-cases/use-services-for-work-order-type";
|
||||||
|
|
||||||
type UseNewWoWizardControllerArgs = {
|
type UseNewWoWizardControllerArgs = {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
|
|
@ -32,7 +31,7 @@ export function useNewWoWizardController({
|
||||||
const draftState = useNewWoWizardDraft(open);
|
const draftState = useNewWoWizardDraft(open);
|
||||||
|
|
||||||
const { data: locations = [] } = useLocationSites();
|
const { data: locations = [] } = useLocationSites();
|
||||||
const { data: problems = [] } = useDropdownOptionsByCategory("Problem");
|
const { data: registryServices = [] } = useServicesForWorkOrderType(draftState.draft.type);
|
||||||
const {
|
const {
|
||||||
data: locationDetail,
|
data: locationDetail,
|
||||||
isLoading: locationDetailLoading,
|
isLoading: locationDetailLoading,
|
||||||
|
|
@ -78,7 +77,7 @@ export function useNewWoWizardController({
|
||||||
...draftState,
|
...draftState,
|
||||||
patchDraft,
|
patchDraft,
|
||||||
locations,
|
locations,
|
||||||
problems,
|
services: registryServices,
|
||||||
locationDetail,
|
locationDetail,
|
||||||
locationDetailLoading,
|
locationDetailLoading,
|
||||||
locationDetailError,
|
locationDetailError,
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,8 @@ type WizardDateFieldProps = {
|
||||||
scheduleEnd?: string;
|
scheduleEnd?: string;
|
||||||
schedMode?: WizardSchedMode;
|
schedMode?: WizardSchedMode;
|
||||||
onChangeRange?: (start: string, end: string) => void;
|
onChangeRange?: (start: string, end: string) => void;
|
||||||
|
/** Earliest selectable day in the date calendar (SH-356). */
|
||||||
|
minDate?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
function fieldLabel(args: {
|
function fieldLabel(args: {
|
||||||
|
|
@ -49,6 +51,7 @@ export function WizardDateField({
|
||||||
scheduleEnd = "",
|
scheduleEnd = "",
|
||||||
schedMode,
|
schedMode,
|
||||||
onChangeRange,
|
onChangeRange,
|
||||||
|
minDate,
|
||||||
}: WizardDateFieldProps) {
|
}: WizardDateFieldProps) {
|
||||||
const { anchorEl, open, setAnchor, close } = useMenuAnchor();
|
const { anchorEl, open, setAnchor, close } = useMenuAnchor();
|
||||||
const allowRange = Boolean(allowWeekMode && onChangeRange);
|
const allowRange = Boolean(allowWeekMode && onChangeRange);
|
||||||
|
|
@ -127,6 +130,7 @@ export function WizardDateField({
|
||||||
) : (
|
) : (
|
||||||
<MiniCalendar
|
<MiniCalendar
|
||||||
value={value}
|
value={value}
|
||||||
|
minDate={minDate}
|
||||||
onChange={(iso) => {
|
onChange={(iso) => {
|
||||||
onChange(iso);
|
onChange(iso);
|
||||||
close();
|
close();
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,8 @@ type WizardDueDateFieldProps = {
|
||||||
value: string;
|
value: string;
|
||||||
placeholder: string;
|
placeholder: string;
|
||||||
onChange: (iso: string) => void;
|
onChange: (iso: string) => void;
|
||||||
|
/** Schedule On floor: earlier days are not selectable (SH-356). */
|
||||||
|
minDate?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -21,11 +23,19 @@ export function WizardDueDateField({
|
||||||
value,
|
value,
|
||||||
placeholder,
|
placeholder,
|
||||||
onChange,
|
onChange,
|
||||||
|
minDate,
|
||||||
}: WizardDueDateFieldProps) {
|
}: WizardDueDateFieldProps) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
if (type !== "Emergency") {
|
if (type !== "Emergency") {
|
||||||
return <WizardDateField value={value} placeholder={placeholder} onChange={onChange} />;
|
return (
|
||||||
|
<WizardDateField
|
||||||
|
value={value}
|
||||||
|
placeholder={placeholder}
|
||||||
|
onChange={onChange}
|
||||||
|
minDate={minDate}
|
||||||
|
/>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
@ -63,7 +73,13 @@ export function WizardDueDateField({
|
||||||
</span>
|
</span>
|
||||||
<ChevronDown size={13} className="shrink-0" style={{ color: "var(--muted-foreground)" }} />
|
<ChevronDown size={13} className="shrink-0" style={{ color: "var(--muted-foreground)" }} />
|
||||||
</button>
|
</button>
|
||||||
<DueDateCalendarDialog open={open} onOpenChange={setOpen} value={value} onSave={onChange} />
|
<DueDateCalendarDialog
|
||||||
|
open={open}
|
||||||
|
onOpenChange={setOpen}
|
||||||
|
value={value}
|
||||||
|
onSave={onChange}
|
||||||
|
minDate={minDate}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,7 @@ export function WizardStepLocationPocFields({
|
||||||
onAdditionalContactsChange={(contacts) => onUpdate("additionalContacts", contacts)}
|
onAdditionalContactsChange={(contacts) => onUpdate("additionalContacts", contacts)}
|
||||||
helperText="Auto-filled from records — edit if outdated"
|
helperText="Auto-filled from records — edit if outdated"
|
||||||
showPrimaryErrors={showErrors && pocIncomplete}
|
showPrimaryErrors={showErrors && pocIncomplete}
|
||||||
|
primaryRequired
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -32,8 +32,10 @@ export function WizardStepLocationServiceSelect({
|
||||||
nextPm !== draft.pm ? { vendorId: "", vendorName: "", techPhone: "" } : {};
|
nextPm !== draft.pm ? { vendorId: "", vendorName: "", techPhone: "" } : {};
|
||||||
|
|
||||||
const selectSvc = (p: string) => {
|
const selectSvc = (p: string) => {
|
||||||
|
const selected = services.find((service) => service.value === p);
|
||||||
onPatch({
|
onPatch({
|
||||||
pm: p,
|
pm: p,
|
||||||
|
serviceId: selected?.id ?? null,
|
||||||
extraServices: [],
|
extraServices: [],
|
||||||
...clearVendorIfPrimaryChanged(p),
|
...clearVendorIfPrimaryChanged(p),
|
||||||
});
|
});
|
||||||
|
|
@ -48,7 +50,7 @@ export function WizardStepLocationServiceSelect({
|
||||||
icon={
|
icon={
|
||||||
<Droplets size={16} className="shrink-0" style={{ color: "var(--muted-foreground)" }} />
|
<Droplets size={16} className="shrink-0" style={{ color: "var(--muted-foreground)" }} />
|
||||||
}
|
}
|
||||||
searchPlaceholder="Search PM type…"
|
searchPlaceholder="Search services…"
|
||||||
options={services.map((s) => {
|
options={services.map((s) => {
|
||||||
const Icon = getPmTypeIcon(s.value);
|
const Icon = getPmTypeIcon(s.value);
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,10 @@ import {
|
||||||
import { WizardSeverityPicker } from "@/app/(protected)/workorders/_components/wizard/wizard-severity-picker";
|
import { WizardSeverityPicker } from "@/app/(protected)/workorders/_components/wizard/wizard-severity-picker";
|
||||||
import { CheckCircle2, Clock, Flame, Users, Wrench, Zap } from "lucide-react";
|
import { CheckCircle2, Clock, Flame, Users, Wrench, Zap } from "lucide-react";
|
||||||
import type { ElementType } from "react";
|
import type { ElementType } from "react";
|
||||||
|
import {
|
||||||
|
clearDueDateBeforeSchedule,
|
||||||
|
resolveDueDateFloor,
|
||||||
|
} from "@/domain/work-orders/utils/due-date-floor";
|
||||||
|
|
||||||
const WO_TYPE_ICONS: Record<WOType, ElementType> = {
|
const WO_TYPE_ICONS: Record<WOType, ElementType> = {
|
||||||
PM: Wrench,
|
PM: Wrench,
|
||||||
|
|
@ -165,6 +169,7 @@ function WizardTypeScheduleDates({ draft, onUpdate, onPatch }: WizardTypeSchedul
|
||||||
onChange={(iso) =>
|
onChange={(iso) =>
|
||||||
onPatch(
|
onPatch(
|
||||||
withAutoScheduleStatus(draft, {
|
withAutoScheduleStatus(draft, {
|
||||||
|
...clearDueDateBeforeSchedule(draft.dueDate, iso),
|
||||||
scheduledOn: iso,
|
scheduledOn: iso,
|
||||||
scheduleWeekOnly: false,
|
scheduleWeekOnly: false,
|
||||||
scheduleEnd: "",
|
scheduleEnd: "",
|
||||||
|
|
@ -177,6 +182,7 @@ function WizardTypeScheduleDates({ draft, onUpdate, onPatch }: WizardTypeSchedul
|
||||||
onChangeWeek={(w) =>
|
onChangeWeek={(w) =>
|
||||||
onPatch(
|
onPatch(
|
||||||
withAutoScheduleStatus(draft, {
|
withAutoScheduleStatus(draft, {
|
||||||
|
...clearDueDateBeforeSchedule(draft.dueDate, w),
|
||||||
scheduledOn: w,
|
scheduledOn: w,
|
||||||
scheduleWeekOnly: Boolean(w),
|
scheduleWeekOnly: Boolean(w),
|
||||||
scheduleEnd: "",
|
scheduleEnd: "",
|
||||||
|
|
@ -189,6 +195,7 @@ function WizardTypeScheduleDates({ draft, onUpdate, onPatch }: WizardTypeSchedul
|
||||||
onChangeRange={(s, e) =>
|
onChangeRange={(s, e) =>
|
||||||
onPatch(
|
onPatch(
|
||||||
withAutoScheduleStatus(draft, {
|
withAutoScheduleStatus(draft, {
|
||||||
|
...clearDueDateBeforeSchedule(draft.dueDate, s),
|
||||||
scheduledOn: s,
|
scheduledOn: s,
|
||||||
scheduleEnd: e,
|
scheduleEnd: e,
|
||||||
schedMode: "range",
|
schedMode: "range",
|
||||||
|
|
@ -211,6 +218,7 @@ function WizardTypeScheduleDates({ draft, onUpdate, onPatch }: WizardTypeSchedul
|
||||||
<WizardDueDateField
|
<WizardDueDateField
|
||||||
type={draft.type}
|
type={draft.type}
|
||||||
value={draft.dueDate}
|
value={draft.dueDate}
|
||||||
|
minDate={resolveDueDateFloor(draft)}
|
||||||
placeholder="No due date"
|
placeholder="No due date"
|
||||||
onChange={(iso) => onUpdate("dueDate", iso)}
|
onChange={(iso) => onUpdate("dueDate", iso)}
|
||||||
/>
|
/>
|
||||||
|
|
@ -262,9 +270,23 @@ export function WizardStepTypeSchedule({
|
||||||
<WoTypePicker
|
<WoTypePicker
|
||||||
selected={draft.type}
|
selected={draft.type}
|
||||||
onSelect={(t) => {
|
onSelect={(t) => {
|
||||||
|
const typeChanged = t !== draft.type;
|
||||||
onPatch({
|
onPatch({
|
||||||
type: t,
|
type: t,
|
||||||
severity: nextSeverityForType(draft.type, t, draft.severity),
|
severity: nextSeverityForType(draft.type, t, draft.severity),
|
||||||
|
// A registry service is scoped to its work-order type, so a service picked
|
||||||
|
// under the previous type fails backend ResolveServiceAsync (SH-187/#131).
|
||||||
|
// Clear the service (and its vendor, filtered by the service) on a type change.
|
||||||
|
...(typeChanged
|
||||||
|
? {
|
||||||
|
pm: "",
|
||||||
|
serviceId: null,
|
||||||
|
extraServices: [],
|
||||||
|
vendorId: "",
|
||||||
|
vendorName: "",
|
||||||
|
techPhone: "",
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
|
||||||
|
|
@ -33,7 +33,8 @@ export function useWorkOrdersBoardSource(filters: FiltersReturn): WorkOrdersBoar
|
||||||
() =>
|
() =>
|
||||||
buildResolvedBoardSearchParams({
|
buildResolvedBoardSearchParams({
|
||||||
advApplied: filters.advApplied,
|
advApplied: filters.advApplied,
|
||||||
search: filters.search,
|
// Advanced Filters are global by design; the week-scoped keyword box has no effect.
|
||||||
|
search: "",
|
||||||
page: filters.page,
|
page: filters.page,
|
||||||
pageSize: filters.pageSize,
|
pageSize: filters.pageSize,
|
||||||
sortBy: filters.sortBy,
|
sortBy: filters.sortBy,
|
||||||
|
|
@ -43,7 +44,6 @@ export function useWorkOrdersBoardSource(filters: FiltersReturn): WorkOrdersBoar
|
||||||
}),
|
}),
|
||||||
[
|
[
|
||||||
filters.advApplied,
|
filters.advApplied,
|
||||||
filters.search,
|
|
||||||
filters.page,
|
filters.page,
|
||||||
filters.pageSize,
|
filters.pageSize,
|
||||||
filters.sortBy,
|
filters.sortBy,
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import {
|
||||||
} from "@/domain/work-orders/use-cases/use-work-order-detail";
|
} from "@/domain/work-orders/use-cases/use-work-order-detail";
|
||||||
import { useWorkOrderUsers } from "@/domain/work-orders/use-cases/use-work-orders-list";
|
import { useWorkOrderUsers } from "@/domain/work-orders/use-cases/use-work-orders-list";
|
||||||
import { useWorkOrderTableMutations } from "@/domain/work-orders/use-cases/use-work-order-table-mutations";
|
import { useWorkOrderTableMutations } from "@/domain/work-orders/use-cases/use-work-order-table-mutations";
|
||||||
|
import { shouldCompleteAfterCompletionDoc } from "@/domain/work-orders/utils/completion-doc-auto-complete";
|
||||||
import {
|
import {
|
||||||
patchWorkOrderAsCanceled,
|
patchWorkOrderAsCanceled,
|
||||||
patchWorkOrderAsCompleted,
|
patchWorkOrderAsCompleted,
|
||||||
|
|
@ -112,7 +113,17 @@ export function useWorkOrdersListPage() {
|
||||||
generatedAt: data.generatedAt,
|
generatedAt: data.generatedAt,
|
||||||
};
|
};
|
||||||
setCompletionDocs((prev) => ({ ...prev, [String(row.id)]: nextData }));
|
setCompletionDocs((prev) => ({ ...prev, [String(row.id)]: nextData }));
|
||||||
await patchFieldAsync(row.id, { docStatus: status });
|
const saved = await patchFieldAsync(row.id, { docStatus: status });
|
||||||
|
if (saved.kind !== "board" || !shouldCompleteAfterCompletionDoc(status, saved.row)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// Generation is the one automatic completion — no confirmation dialog.
|
||||||
|
await patchFieldAsync(row.id, { status: "Completed" }, saved.row);
|
||||||
|
} catch {
|
||||||
|
// The document is saved; the table mutation already surfaced the status error and
|
||||||
|
// refetched, so the WO stays in its prior status for a manual retry.
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -43,10 +43,12 @@ export default function WorkOrdersListPage() {
|
||||||
actions={
|
actions={
|
||||||
<WorkOrdersListHeader
|
<WorkOrdersListHeader
|
||||||
search={filters.search}
|
search={filters.search}
|
||||||
|
weekLabel={filters.weekLabel}
|
||||||
onSearchChange={filters.handleSearchChange}
|
onSearchChange={filters.handleSearchChange}
|
||||||
onOpenAdvancedFilters={() => filters.setAdvOpen(true)}
|
onOpenAdvancedFilters={() => filters.setAdvOpen(true)}
|
||||||
onNewWorkOrder={() => page.setWizardOpen(true)}
|
onNewWorkOrder={() => page.setWizardOpen(true)}
|
||||||
activeFilterCount={filters.activeFilterCount}
|
activeFilterCount={filters.activeFilterCount}
|
||||||
|
advancedFiltersActive={filters.advApplied != null}
|
||||||
isFetching={tableData.isFetching && !tableData.isLoading}
|
isFetching={tableData.isFetching && !tableData.isLoading}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ import {
|
||||||
Bell,
|
Bell,
|
||||||
BarChart3,
|
BarChart3,
|
||||||
Star,
|
Star,
|
||||||
|
Users,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
|
||||||
export type NavItemDef = {
|
export type NavItemDef = {
|
||||||
|
|
@ -58,6 +59,10 @@ export const navGroups: NavGroup[] = [
|
||||||
{ label: "Sites", icon: MapPin, path: "/locations" },
|
{ label: "Sites", icon: MapPin, path: "/locations" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: "TEAM",
|
||||||
|
items: [{ label: "Team Members", icon: Users, path: "/team-members" }],
|
||||||
|
},
|
||||||
// {
|
// {
|
||||||
// title: "INTERNAL",
|
// title: "INTERNAL",
|
||||||
// items: [{ label: "Documents", icon: FileText, path: "/documents" }],
|
// items: [{ label: "Documents", icon: FileText, path: "/documents" }],
|
||||||
|
|
|
||||||
|
|
@ -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 {
|
function readString(record: Record<string, unknown>, ...keys: string[]): string {
|
||||||
for (const key of keys) {
|
for (const key of keys) {
|
||||||
|
|
@ -90,9 +95,31 @@ export function mapLocationSites(rawItems: unknown[]): LocationSite[] {
|
||||||
return rawItems.map(mapLocationSite);
|
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 {
|
export function mapLocationListItem(raw: unknown): LocationListItem {
|
||||||
const item = (typeof raw === "object" && raw !== null ? raw : {}) as Record<string, unknown>;
|
const item = (typeof raw === "object" && raw !== null ? raw : {}) as Record<string, unknown>;
|
||||||
|
|
||||||
|
const contacts = mapLocationContacts(item.contacts ?? item.Contacts);
|
||||||
|
const mainContact = contacts[0];
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: readId(item),
|
id: readId(item),
|
||||||
name: readString(item, "name", "Name"),
|
name: readString(item, "name", "Name"),
|
||||||
|
|
@ -100,11 +127,14 @@ export function mapLocationListItem(raw: unknown): LocationListItem {
|
||||||
city: readString(item, "city", "City"),
|
city: readString(item, "city", "City"),
|
||||||
state: readString(item, "state", "State"),
|
state: readString(item, "state", "State"),
|
||||||
zipCode: readString(item, "zipCode", "ZipCode", "Zip"),
|
zipCode: readString(item, "zipCode", "ZipCode", "Zip"),
|
||||||
phone: readString(item, "phone", "Phone"),
|
phone: mainContact ? mainContact.phone : readString(item, "phone", "Phone"),
|
||||||
contact: readString(item, "contact", "Contact", "contactPerson", "ContactPerson"),
|
contact: mainContact
|
||||||
|
? mainContact.name
|
||||||
|
: readString(item, "contact", "Contact", "contactPerson", "ContactPerson"),
|
||||||
contactEmail: readString(item, "contactEmail", "ContactEmail"),
|
contactEmail: readString(item, "contactEmail", "ContactEmail"),
|
||||||
status: readString(item, "status", "Status"),
|
status: readString(item, "status", "Status"),
|
||||||
accountId: readOptionalId(item),
|
accountId: readOptionalId(item),
|
||||||
|
contacts: contacts.length > 0 ? contacts : undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -122,6 +152,12 @@ export function mapLocation(raw: unknown): Location {
|
||||||
.join(", ") ||
|
.join(", ") ||
|
||||||
undefined;
|
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 {
|
return {
|
||||||
id: readId(item) || undefined,
|
id: readId(item) || undefined,
|
||||||
name: readString(item, "name", "Name") || undefined,
|
name: readString(item, "name", "Name") || undefined,
|
||||||
|
|
@ -129,31 +165,58 @@ export function mapLocation(raw: unknown): Location {
|
||||||
city: readString(item, "city", "City") || undefined,
|
city: readString(item, "city", "City") || undefined,
|
||||||
state: readString(item, "state", "State") || undefined,
|
state: readString(item, "state", "State") || undefined,
|
||||||
zipCode: readString(item, "zipCode", "ZipCode", "Zip") || undefined,
|
zipCode: readString(item, "zipCode", "ZipCode", "Zip") || undefined,
|
||||||
phone: readString(item, "phone", "Phone") || undefined,
|
phone: mainContact ? mainContact.phone : legacyPhone,
|
||||||
contact: readString(item, "contact", "Contact") || undefined,
|
contact: mainContact ? mainContact.name : legacyContact,
|
||||||
contactEmail: readString(item, "contactEmail", "ContactEmail") || undefined,
|
contactEmail: readString(item, "contactEmail", "ContactEmail") || undefined,
|
||||||
status: readString(item, "status", "Status") || undefined,
|
status: readString(item, "status", "Status") || undefined,
|
||||||
accountId: readOptionalId(item) || 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> {
|
export function mapLocationToBackend(location: unknown): Record<string, unknown> {
|
||||||
const item = (typeof location === "object" && location !== null ? location : {}) as Record<
|
const item = (typeof location === "object" && location !== null ? location : {}) as Record<
|
||||||
string,
|
string,
|
||||||
unknown
|
unknown
|
||||||
>;
|
>;
|
||||||
|
|
||||||
|
const contacts = mapContactsToBackend(item.contacts ?? item.Contacts);
|
||||||
|
const mainContact = contacts[0];
|
||||||
|
|
||||||
const payload: Record<string, unknown> = {
|
const payload: Record<string, unknown> = {
|
||||||
name: item.name ?? "",
|
name: item.name ?? "",
|
||||||
address: item.address ?? "",
|
address: item.address ?? "",
|
||||||
city: item.city ?? "",
|
city: item.city ?? "",
|
||||||
state: item.state ?? "",
|
state: item.state ?? "",
|
||||||
zipCode: item.zipCode ?? "",
|
zipCode: item.zipCode ?? "",
|
||||||
phone: item.phone ?? "",
|
phone: mainContact ? mainContact.phone : (item.phone ?? ""),
|
||||||
contact: item.contact ?? "",
|
contact: mainContact ? mainContact.name : (item.contact ?? ""),
|
||||||
contactEmail: item.contactEmail ?? "",
|
contactEmail: item.contactEmail ?? "",
|
||||||
status: item.status ?? "Active",
|
status: item.status ?? "Active",
|
||||||
accountId: item.accountId ?? "",
|
accountId: item.accountId ?? "",
|
||||||
|
contacts,
|
||||||
};
|
};
|
||||||
|
|
||||||
const id = item.id ?? item.Id;
|
const id = item.id ?? item.Id;
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,16 @@ import { z } from "zod";
|
||||||
import { US_STATE_CODES } from "@/data/areas";
|
import { US_STATE_CODES } from "@/data/areas";
|
||||||
import { LOCATION_STATUS_OPTIONS } from "@/domain/locations/types/location";
|
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({
|
export const locationSchema = z.object({
|
||||||
name: z.string().min(1, "Name is required"),
|
name: z.string().min(1, "Name is required"),
|
||||||
accountId: z.string().optional(),
|
accountId: z.string().optional(),
|
||||||
|
|
@ -11,13 +21,13 @@ export const locationSchema = z.object({
|
||||||
.union([z.enum(US_STATE_CODES), z.literal("")])
|
.union([z.enum(US_STATE_CODES), z.literal("")])
|
||||||
.refine((state): boolean => state !== "", { message: "State is required" }),
|
.refine((state): boolean => state !== "", { message: "State is required" }),
|
||||||
zipCode: z.string().min(1, "Zip code is required"),
|
zipCode: z.string().min(1, "Zip code is required"),
|
||||||
phone: z.string().min(1, "Phone is required"),
|
contacts: z.array(locationContactSchema).min(1, "At least one contact is required"),
|
||||||
contact: z.string().min(1, "Contact person is required"),
|
|
||||||
contactEmail: z.string().min(1, "Contact email is required").email("Invalid email address"),
|
contactEmail: z.string().min(1, "Contact email is required").email("Invalid email address"),
|
||||||
status: z.enum(LOCATION_STATUS_OPTIONS, { message: "Status is required" }),
|
status: z.enum(LOCATION_STATUS_OPTIONS, { message: "Status is required" }),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type LocationFormValues = z.infer<typeof locationSchema>;
|
export type LocationFormValues = z.infer<typeof locationSchema>;
|
||||||
|
export type LocationContactFormValues = z.infer<typeof locationContactSchema>;
|
||||||
|
|
||||||
export const locationDefaultValues: LocationFormValues = {
|
export const locationDefaultValues: LocationFormValues = {
|
||||||
name: "",
|
name: "",
|
||||||
|
|
@ -26,8 +36,7 @@ export const locationDefaultValues: LocationFormValues = {
|
||||||
city: "",
|
city: "",
|
||||||
state: "",
|
state: "",
|
||||||
zipCode: "",
|
zipCode: "",
|
||||||
phone: "",
|
contacts: [{ name: "", phone: "" }],
|
||||||
contact: "",
|
|
||||||
contactEmail: "",
|
contactEmail: "",
|
||||||
status: "Active",
|
status: "Active",
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,12 @@
|
||||||
import type { StateCode } from "@/data/areas";
|
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 {
|
export interface LocationListItem {
|
||||||
id: string | number;
|
id: string | number;
|
||||||
name: string;
|
name: string;
|
||||||
|
|
@ -12,6 +19,8 @@ export interface LocationListItem {
|
||||||
contactEmail: string;
|
contactEmail: string;
|
||||||
status: string;
|
status: string;
|
||||||
accountId: string | number;
|
accountId: string | number;
|
||||||
|
/** Additive contacts payload; `contact`/`phone` mirror the first entry. */
|
||||||
|
contacts?: LocationContact[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Location {
|
export interface Location {
|
||||||
|
|
@ -26,6 +35,8 @@ export interface Location {
|
||||||
contactEmail?: string;
|
contactEmail?: string;
|
||||||
status?: string;
|
status?: string;
|
||||||
accountId?: string | number;
|
accountId?: string | number;
|
||||||
|
/** Additive contacts payload; the first entry is the Main contact. */
|
||||||
|
contacts?: LocationContact[];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Site option from GET locations/sites (wizard / board create). */
|
/** Site option from GET locations/sites (wizard / board create). */
|
||||||
|
|
|
||||||
30
src/domain/services/api/services-api.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
import { apiGet } from "@/api/api";
|
||||||
|
import { API_PATHS } from "@/api/api-paths";
|
||||||
|
import { handleApiResponse } from "@/api/handle-api-response";
|
||||||
|
import { mapServices } from "@/domain/services/mappers/service-mapper";
|
||||||
|
import type { Service } from "@/domain/services/types/service";
|
||||||
|
import { WORK_ORDER_TYPE_API } from "@/domain/work-orders/types/work-order-board";
|
||||||
|
import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
|
||||||
|
|
||||||
|
const TYPE_TO_API: Record<Exclude<WOType, "Overdue">, number> = {
|
||||||
|
PM: WORK_ORDER_TYPE_API.PM,
|
||||||
|
Reactive: WORK_ORDER_TYPE_API.Reactive,
|
||||||
|
Emergency: WORK_ORDER_TYPE_API.Emergency,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const servicesApi = {
|
||||||
|
getActive: async (): Promise<Service[]> => {
|
||||||
|
const data = await apiGet<unknown>(API_PATHS.services.list, {
|
||||||
|
searchParams: { isActive: true },
|
||||||
|
});
|
||||||
|
return mapServices(handleApiResponse(data));
|
||||||
|
},
|
||||||
|
|
||||||
|
getActiveForWorkOrderType: async (workOrderType: WOType): Promise<Service[]> => {
|
||||||
|
if (workOrderType === "Overdue") return [];
|
||||||
|
const data = await apiGet<unknown>(API_PATHS.services.list, {
|
||||||
|
searchParams: { isActive: true, workOrderType: TYPE_TO_API[workOrderType] },
|
||||||
|
});
|
||||||
|
return mapServices(handleApiResponse(data));
|
||||||
|
},
|
||||||
|
};
|
||||||
71
src/domain/services/mappers/service-mapper.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
||||||
|
import type { Service } from "@/domain/services/types/service";
|
||||||
|
import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
|
||||||
|
|
||||||
|
function asRecord(raw: unknown): Record<string, unknown> {
|
||||||
|
return typeof raw === "object" && raw !== null ? (raw as Record<string, unknown>) : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
function readId(item: Record<string, unknown>): string | number {
|
||||||
|
const value = item.id ?? item.Id;
|
||||||
|
return typeof value === "string" || typeof value === "number" ? value : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function readString(item: Record<string, unknown>, ...keys: string[]): string {
|
||||||
|
for (const key of keys) {
|
||||||
|
const value = item[key];
|
||||||
|
if (typeof value === "string") return value.trim();
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function readBool(item: Record<string, unknown>, ...keys: string[]): boolean {
|
||||||
|
for (const key of keys) {
|
||||||
|
const value = item[key];
|
||||||
|
if (typeof value === "boolean") return value;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapWorkOrderType(value: unknown): WOType | null {
|
||||||
|
if (typeof value === "number") {
|
||||||
|
return value === 2 ? "PM" : value === 3 ? "Emergency" : value === 6 ? "Reactive" : null;
|
||||||
|
}
|
||||||
|
if (typeof value === "string") {
|
||||||
|
const normalized = value.trim().toLowerCase();
|
||||||
|
return normalized === "pm" || normalized === "preventivemaintenance"
|
||||||
|
? "PM"
|
||||||
|
: normalized === "emergency"
|
||||||
|
? "Emergency"
|
||||||
|
: normalized === "reactive"
|
||||||
|
? "Reactive"
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapService(raw: unknown): Service {
|
||||||
|
const item = asRecord(raw);
|
||||||
|
const types = item.supportedWorkOrderTypes ?? item.SupportedWorkOrderTypes;
|
||||||
|
return {
|
||||||
|
id: readId(item),
|
||||||
|
name: readString(item, "name", "Name"),
|
||||||
|
trade: readString(item, "trade", "Trade"),
|
||||||
|
iconKey: readString(item, "iconKey", "IconKey"),
|
||||||
|
requiresCompletionDocument: readBool(
|
||||||
|
item,
|
||||||
|
"requiresCompletionDocument",
|
||||||
|
"RequiresCompletionDocument",
|
||||||
|
),
|
||||||
|
isActive: readBool(item, "isActive", "IsActive"),
|
||||||
|
supportedWorkOrderTypes: Array.isArray(types)
|
||||||
|
? types.flatMap((value) => {
|
||||||
|
const mapped = mapWorkOrderType(value);
|
||||||
|
return mapped ? [mapped] : [];
|
||||||
|
})
|
||||||
|
: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapServices(raw: unknown): Service[] {
|
||||||
|
return Array.isArray(raw) ? raw.map(mapService).filter((service) => service.id !== "") : [];
|
||||||
|
}
|
||||||
11
src/domain/services/types/service.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
|
||||||
|
|
||||||
|
export interface Service {
|
||||||
|
id: string | number;
|
||||||
|
name: string;
|
||||||
|
trade: string;
|
||||||
|
iconKey: string;
|
||||||
|
requiresCompletionDocument: boolean;
|
||||||
|
isActive: boolean;
|
||||||
|
supportedWorkOrderTypes: WOType[];
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
|
||||||
|
import { servicesApi } from "@/domain/services/api/services-api";
|
||||||
|
import type { Service } from "@/domain/services/types/service";
|
||||||
|
import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
|
||||||
|
import { queryKeys } from "@/infra/query-key/query-key";
|
||||||
|
|
||||||
|
export function useServicesForWorkOrderType(
|
||||||
|
workOrderType: WOType | "",
|
||||||
|
): UseQueryResult<Service[], Error> {
|
||||||
|
const effectiveType = workOrderType || "PM";
|
||||||
|
return useQuery({
|
||||||
|
queryKey: queryKeys.services.byWorkOrderType(effectiveType),
|
||||||
|
queryFn: () => servicesApi.getActiveForWorkOrderType(effectiveType),
|
||||||
|
enabled: effectiveType !== "Overdue",
|
||||||
|
staleTime: 60 * 1000,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useActiveServices(): UseQueryResult<Service[], Error> {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: queryKeys.services.active(),
|
||||||
|
queryFn: () => servicesApi.getActive(),
|
||||||
|
staleTime: 60 * 1000,
|
||||||
|
});
|
||||||
|
}
|
||||||
13
src/domain/team-members/api/team-members-api.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
import { apiGet } from "@/api/api";
|
||||||
|
import { API_PATHS } from "@/api/api-paths";
|
||||||
|
import { handleApiResponse } from "@/api/handle-api-response";
|
||||||
|
import { mapTeamMemberListItems } from "@/domain/team-members/mappers/team-member-mapper";
|
||||||
|
import type { TeamMemberListResult } from "@/domain/team-members/types/team-member";
|
||||||
|
|
||||||
|
export const teamMembersApi = {
|
||||||
|
getList: async (): Promise<TeamMemberListResult> => {
|
||||||
|
const data = await apiGet<unknown>(API_PATHS.teamMember.getList);
|
||||||
|
const items = handleApiResponse<unknown[]>(data);
|
||||||
|
return { items: mapTeamMemberListItems(Array.isArray(items) ? items : []) };
|
||||||
|
},
|
||||||
|
};
|
||||||
45
src/domain/team-members/mappers/team-member-mapper.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
import type { TeamMemberListItem } from "@/domain/team-members/types/team-member";
|
||||||
|
|
||||||
|
function readString(record: Record<string, unknown>, ...keys: string[]): string {
|
||||||
|
for (const key of keys) {
|
||||||
|
const value = record[key];
|
||||||
|
if (typeof value === "string") return value;
|
||||||
|
if (typeof value === "number") return String(value);
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function readBoolean(record: Record<string, unknown>, ...keys: string[]): boolean {
|
||||||
|
for (const key of keys) {
|
||||||
|
const value = record[key];
|
||||||
|
if (typeof value === "boolean") return value;
|
||||||
|
if (typeof value === "string") return value.toLowerCase() === "true";
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapTeamMemberListItem(raw: unknown): TeamMemberListItem {
|
||||||
|
const record = (typeof raw === "object" && raw !== null ? raw : {}) as Record<string, unknown>;
|
||||||
|
const id = record.id ?? record.Id;
|
||||||
|
const status =
|
||||||
|
readString(record, "status", "Status").toLowerCase() === "inactive" ||
|
||||||
|
readBoolean(record, "isDeleted", "IsDeleted")
|
||||||
|
? "Inactive"
|
||||||
|
: "Active";
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: typeof id === "string" || typeof id === "number" ? id : "",
|
||||||
|
name: readString(record, "name", "Name"),
|
||||||
|
role: readString(record, "role", "Role", "roleName", "RoleName"),
|
||||||
|
serviceArea: readString(record, "serviceArea", "ServiceArea", "locations", "Locations"),
|
||||||
|
phone: readString(record, "phone", "Phone"),
|
||||||
|
email: readString(record, "email", "Email"),
|
||||||
|
color: readString(record, "color", "Color"),
|
||||||
|
status,
|
||||||
|
isAccountOwner: readBoolean(record, "isAccountOwner", "IsAccountOwner"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapTeamMemberListItems(rawItems: unknown[]): TeamMemberListItem[] {
|
||||||
|
return rawItems.map(mapTeamMemberListItem);
|
||||||
|
}
|
||||||
15
src/domain/team-members/types/team-member.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
export interface TeamMemberListItem {
|
||||||
|
id: string | number;
|
||||||
|
name: string;
|
||||||
|
role: string;
|
||||||
|
serviceArea: string;
|
||||||
|
phone: string;
|
||||||
|
email: string;
|
||||||
|
color: string;
|
||||||
|
status: "Active" | "Inactive";
|
||||||
|
isAccountOwner: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TeamMemberListResult {
|
||||||
|
items: TeamMemberListItem[];
|
||||||
|
}
|
||||||
11
src/domain/team-members/use-cases/use-team-members-list.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
|
||||||
|
import { teamMembersApi } from "@/domain/team-members/api/team-members-api";
|
||||||
|
import type { TeamMemberListResult } from "@/domain/team-members/types/team-member";
|
||||||
|
import { queryKeys } from "@/infra/query-key/query-key";
|
||||||
|
|
||||||
|
export function useTeamMembersList(): UseQueryResult<TeamMemberListResult, Error> {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: queryKeys.teamMembers.list(),
|
||||||
|
queryFn: teamMembersApi.getList,
|
||||||
|
});
|
||||||
|
}
|
||||||
19
src/domain/vendors/api/vendors-api.ts
vendored
|
|
@ -56,6 +56,7 @@ function buildListParams(params: VendorsListParams): Record<string, string | num
|
||||||
pushRepeated(searchParams, "trades", params.trades);
|
pushRepeated(searchParams, "trades", params.trades);
|
||||||
pushRepeated(searchParams, "locations", params.locations);
|
pushRepeated(searchParams, "locations", params.locations);
|
||||||
pushRepeated(searchParams, "jobBuckets", params.jobBuckets);
|
pushRepeated(searchParams, "jobBuckets", params.jobBuckets);
|
||||||
|
pushRepeated(searchParams, "areas", params.areas);
|
||||||
return searchParams;
|
return searchParams;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -76,6 +77,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> => {
|
getFacets: async (params?: VendorFacetsParams): Promise<VendorFacets> => {
|
||||||
const data = await apiGet<unknown>(API_PATHS.vendor.facets, {
|
const data = await apiGet<unknown>(API_PATHS.vendor.facets, {
|
||||||
searchParams: buildFacetsParams(params),
|
searchParams: buildFacetsParams(params),
|
||||||
|
|
|
||||||
52
src/domain/vendors/mappers/vendor-mapper.ts
vendored
|
|
@ -1,6 +1,8 @@
|
||||||
import type {
|
import type {
|
||||||
Vendor,
|
Vendor,
|
||||||
VendorDeactivationImpact,
|
VendorDeactivationImpact,
|
||||||
|
VendorDirectoryTechnician,
|
||||||
|
VendorFacetArea,
|
||||||
VendorFacetCompany,
|
VendorFacetCompany,
|
||||||
VendorFacetJobBucket,
|
VendorFacetJobBucket,
|
||||||
VendorFacetLocation,
|
VendorFacetLocation,
|
||||||
|
|
@ -108,7 +110,7 @@ function readBool(record: Record<string, unknown>, ...keys: string[]): boolean {
|
||||||
|
|
||||||
export function mapVendorListItem(raw: unknown): VendorListItem {
|
export function mapVendorListItem(raw: unknown): VendorListItem {
|
||||||
const item = asRecord(raw);
|
const item = asRecord(raw);
|
||||||
return {
|
const mapped = {
|
||||||
id: readId(item),
|
id: readId(item),
|
||||||
companyId: readCompanyId(item),
|
companyId: readCompanyId(item),
|
||||||
companyName: readString(item, "companyName", "CompanyName"),
|
companyName: readString(item, "companyName", "CompanyName"),
|
||||||
|
|
@ -125,6 +127,42 @@ export function mapVendorListItem(raw: unknown): VendorListItem {
|
||||||
tradeSpecialties: readString(item, "tradeSpecialties", "TradeSpecialties"),
|
tradeSpecialties: readString(item, "tradeSpecialties", "TradeSpecialties"),
|
||||||
isActive: readBool(item, "isActive", "IsActive"),
|
isActive: readBool(item, "isActive", "IsActive"),
|
||||||
preferredContact: readPreferredContact(item, "preferredContact", "PreferredContact"),
|
preferredContact: readPreferredContact(item, "preferredContact", "PreferredContact"),
|
||||||
|
areaId: readString(item, "areaId", "AreaId"),
|
||||||
|
areaName: readString(item, "areaName", "AreaName"),
|
||||||
|
};
|
||||||
|
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"),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -255,6 +293,14 @@ function mapFacetLocation(raw: unknown): VendorFacetLocation {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function mapFacetArea(raw: unknown): VendorFacetArea {
|
||||||
|
const item = asRecord(raw);
|
||||||
|
return {
|
||||||
|
id: readString(item, "id", "Id"),
|
||||||
|
name: readString(item, "name", "Name"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function mapFacetJobBucket(raw: unknown): VendorFacetJobBucket {
|
function mapFacetJobBucket(raw: unknown): VendorFacetJobBucket {
|
||||||
const item = asRecord(raw);
|
const item = asRecord(raw);
|
||||||
return {
|
return {
|
||||||
|
|
@ -269,6 +315,7 @@ export function mapVendorFacets(raw: unknown): VendorFacets {
|
||||||
const tradesRaw = item.trades ?? item.Trades;
|
const tradesRaw = item.trades ?? item.Trades;
|
||||||
const locationsRaw = item.locations ?? item.Locations;
|
const locationsRaw = item.locations ?? item.Locations;
|
||||||
const jobBucketsRaw = item.jobBuckets ?? item.JobBuckets;
|
const jobBucketsRaw = item.jobBuckets ?? item.JobBuckets;
|
||||||
|
const areasRaw = item.areas ?? item.Areas;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
companies: Array.isArray(companiesRaw) ? companiesRaw.map(mapFacetCompany) : [],
|
companies: Array.isArray(companiesRaw) ? companiesRaw.map(mapFacetCompany) : [],
|
||||||
|
|
@ -280,6 +327,9 @@ export function mapVendorFacets(raw: unknown): VendorFacets {
|
||||||
})
|
})
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
: [],
|
: [],
|
||||||
|
areas: Array.isArray(areasRaw)
|
||||||
|
? areasRaw.map(mapFacetArea).filter((area) => area.id !== "" && area.name !== "")
|
||||||
|
: [],
|
||||||
locations: Array.isArray(locationsRaw) ? locationsRaw.map(mapFacetLocation) : [],
|
locations: Array.isArray(locationsRaw) ? locationsRaw.map(mapFacetLocation) : [],
|
||||||
jobBuckets: Array.isArray(jobBucketsRaw) ? jobBucketsRaw.map(mapFacetJobBucket) : [],
|
jobBuckets: Array.isArray(jobBucketsRaw) ? jobBucketsRaw.map(mapFacetJobBucket) : [],
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -92,10 +92,18 @@ export function mapVendorCompanyRoster(raw: unknown): VendorCompanyRoster {
|
||||||
zip: readString(item, "zip", "Zip", "zipCode", "ZipCode"),
|
zip: readString(item, "zip", "Zip", "zipCode", "ZipCode"),
|
||||||
googleMapsUrl: readString(item, "googleMapsUrl", "GoogleMapsUrl"),
|
googleMapsUrl: readString(item, "googleMapsUrl", "GoogleMapsUrl"),
|
||||||
notes: readString(item, "notes", "Notes"),
|
notes: readString(item, "notes", "Notes"),
|
||||||
|
areaId: readString(item, "areaId", "AreaId"),
|
||||||
|
areaName: readString(item, "areaName", "AreaName"),
|
||||||
technicians: mapRosterTechnicians(item.technicians ?? item.Technicians),
|
technicians: mapRosterTechnicians(item.technicians ?? item.Technicians),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Form Area ids are strings; the API takes a positive integer id or null (Unassigned). */
|
||||||
|
export function toBackendAreaId(value: unknown): number | null {
|
||||||
|
const parsed = Number(typeof value === "string" ? value.trim() : value);
|
||||||
|
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
||||||
|
}
|
||||||
|
|
||||||
export function mapRosterTechnicianToBackend(technician: unknown): Record<string, unknown> {
|
export function mapRosterTechnicianToBackend(technician: unknown): Record<string, unknown> {
|
||||||
const item = asRecord(technician);
|
const item = asRecord(technician);
|
||||||
const payload: Record<string, unknown> = {
|
const payload: Record<string, unknown> = {
|
||||||
|
|
@ -130,6 +138,11 @@ export function mapVendorRosterToBackend(values: unknown): Record<string, unknow
|
||||||
? techniciansRaw.map(mapRosterTechnicianToBackend)
|
? techniciansRaw.map(mapRosterTechnicianToBackend)
|
||||||
: [],
|
: [],
|
||||||
};
|
};
|
||||||
|
// The form always round-trips its Area (id or null = Unassigned). Callers
|
||||||
|
// without an Area value omit it, which the API treats as "leave unchanged".
|
||||||
|
if ("areaId" in item || "AreaId" in item) {
|
||||||
|
payload.areaId = toBackendAreaId(item.areaId ?? item.AreaId);
|
||||||
|
}
|
||||||
const rowVersion = readString(item, "rowVersion", "RowVersion");
|
const rowVersion = readString(item, "rowVersion", "RowVersion");
|
||||||
if (rowVersion) payload.rowVersion = rowVersion;
|
if (rowVersion) payload.rowVersion = rowVersion;
|
||||||
return payload;
|
return payload;
|
||||||
|
|
@ -157,9 +170,12 @@ export function mapVendorRosterAdditivePatchToBackend(
|
||||||
// SH-250: match the reconcile write path, which canonicalizes companyPhone.
|
// SH-250: match the reconcile write path, which canonicalizes companyPhone.
|
||||||
// Copying companyFields verbatim let additive patches send a different phone
|
// Copying companyFields verbatim let additive patches send a different phone
|
||||||
// shape than PUT for the same user input.
|
// shape than PUT for the same user input.
|
||||||
const companyFields = { ...patch.companyFields };
|
const companyFields: Record<string, unknown> = { ...patch.companyFields };
|
||||||
if (companyFields.companyPhone !== undefined)
|
if (companyFields.companyPhone !== undefined)
|
||||||
companyFields.companyPhone = toCanonicalPhone(companyFields.companyPhone);
|
companyFields.companyPhone = toCanonicalPhone(companyFields.companyPhone);
|
||||||
|
// An edited Area is sent as an id or an explicit null (Unassigned).
|
||||||
|
if (companyFields.areaId !== undefined)
|
||||||
|
companyFields.areaId = toBackendAreaId(companyFields.areaId);
|
||||||
payload.companyFields = companyFields;
|
payload.companyFields = companyFields;
|
||||||
}
|
}
|
||||||
return payload;
|
return payload;
|
||||||
|
|
|
||||||