Merge remote-tracking branch 'origin/dev' into feat/ab/sh-324-team-members-list
# Conflicts: # e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-add.png # e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-detail.png # e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-edit.png # e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-empty.png # e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-error.png # e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-filter.png # e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-inactive.png # e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-list.png # e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-mobile-navigation.png # e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-detail.png # e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-empty.png # e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-error.png # e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-filters.png # e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-list.png # e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-new.png
|
Before Width: | Height: | Size: 140 KiB After Width: | Height: | Size: 142 KiB |
|
Before Width: | Height: | Size: 113 KiB After Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 145 KiB After Width: | Height: | Size: 146 KiB |
|
Before Width: | Height: | Size: 102 KiB After Width: | Height: | Size: 103 KiB |
|
Before Width: | Height: | Size: 101 KiB After Width: | Height: | Size: 101 KiB |
|
Before Width: | Height: | Size: 99 KiB After Width: | Height: | Size: 101 KiB |
|
Before Width: | Height: | Size: 104 KiB After Width: | Height: | Size: 104 KiB |
|
Before Width: | Height: | Size: 111 KiB After Width: | Height: | Size: 111 KiB |
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 45 KiB After Width: | Height: | Size: 45 KiB |
|
Before Width: | Height: | Size: 144 KiB After Width: | Height: | Size: 144 KiB |
|
Before Width: | Height: | Size: 100 KiB After Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 114 KiB After Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 148 KiB After Width: | Height: | Size: 148 KiB |
|
Before Width: | Height: | Size: 119 KiB After Width: | Height: | Size: 120 KiB |
|
Before Width: | Height: | Size: 189 KiB After Width: | Height: | Size: 189 KiB |
88
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],
|
||||||
|
|
@ -135,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" },
|
||||||
|
|
@ -160,13 +170,20 @@ 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) => {
|
const responseRows = filtered.map((vendor) => {
|
||||||
|
|
@ -244,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)
|
||||||
|
|
@ -307,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) => ({
|
||||||
|
|
@ -410,6 +431,7 @@ test.describe("Vendor directory prototype parity", () => {
|
||||||
"Street Address",
|
"Street Address",
|
||||||
"City",
|
"City",
|
||||||
"State",
|
"State",
|
||||||
|
"Service Area",
|
||||||
"Trade",
|
"Trade",
|
||||||
"Technician",
|
"Technician",
|
||||||
"Technician Phone",
|
"Technician Phone",
|
||||||
|
|
@ -461,6 +483,7 @@ test.describe("Vendor directory prototype parity", () => {
|
||||||
"Street Address",
|
"Street Address",
|
||||||
"City",
|
"City",
|
||||||
"State",
|
"State",
|
||||||
|
"Service Area",
|
||||||
"Trade",
|
"Trade",
|
||||||
"Technician",
|
"Technician",
|
||||||
"Technician Phone",
|
"Technician Phone",
|
||||||
|
|
@ -474,7 +497,7 @@ 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(2050);
|
expect((await page.locator("table").boundingBox())?.width).toBe(2200);
|
||||||
expect(
|
expect(
|
||||||
(await page.getByRole("columnheader", { name: "Company", exact: true }).boundingBox())
|
(await page.getByRole("columnheader", { name: "Company", exact: true }).boundingBox())
|
||||||
?.height,
|
?.height,
|
||||||
|
|
@ -540,8 +563,8 @@ test.describe("Vendor directory prototype parity", () => {
|
||||||
{ cellIndex: 0, testId: "vendor-text-company", value: LONG_TEXT_VENDOR.CompanyName },
|
{ cellIndex: 0, testId: "vendor-text-company", value: LONG_TEXT_VENDOR.CompanyName },
|
||||||
{ cellIndex: 2, testId: "vendor-text-company-email", value: LONG_TEXT_VENDOR.Email },
|
{ cellIndex: 2, testId: "vendor-text-company-email", value: LONG_TEXT_VENDOR.Email },
|
||||||
{ cellIndex: 3, testId: "vendor-text-street-address", value: LONG_TEXT_VENDOR.Address },
|
{ cellIndex: 3, testId: "vendor-text-street-address", value: LONG_TEXT_VENDOR.Address },
|
||||||
{ cellIndex: 7, testId: "vendor-text-technician", value: LONG_TEXT_VENDOR.ContactName },
|
{ cellIndex: 8, testId: "vendor-text-technician", value: LONG_TEXT_VENDOR.ContactName },
|
||||||
{ cellIndex: 8, testId: "vendor-text-technician-phone", value: LONG_TEXT_VENDOR.Phone },
|
{ cellIndex: 9, testId: "vendor-text-technician-phone", value: LONG_TEXT_VENDOR.Phone },
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const expected of fields) {
|
for (const expected of fields) {
|
||||||
|
|
@ -675,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);
|
||||||
|
|
@ -748,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");
|
||||||
|
|
@ -791,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 }) => {
|
||||||
|
|
|
||||||
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -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 },
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -155,6 +155,7 @@ function CompanyCells({ row }: { row: VendorListItem }) {
|
||||||
<CellText value={row.address} testId="vendor-text-street-address" focusable />
|
<CellText value={row.address} testId="vendor-text-street-address" focusable />
|
||||||
<CellText value={row.city} testId="vendor-text-city" focusable />
|
<CellText value={row.city} testId="vendor-text-city" focusable />
|
||||||
<CellText value={row.state} testId="vendor-text-state" focusable />
|
<CellText value={row.state} testId="vendor-text-state" focusable />
|
||||||
|
<CellText value={row.areaName || "Unassigned"} testId="vendor-text-service-area" focusable />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ const TABLE_COLUMNS = [
|
||||||
"Street Address",
|
"Street Address",
|
||||||
"City",
|
"City",
|
||||||
"State",
|
"State",
|
||||||
|
"Service Area",
|
||||||
"Trade",
|
"Trade",
|
||||||
"Technician",
|
"Technician",
|
||||||
"Technician Phone",
|
"Technician Phone",
|
||||||
|
|
@ -66,7 +67,7 @@ export function VendorsTable({
|
||||||
size="small"
|
size="small"
|
||||||
stickyHeader
|
stickyHeader
|
||||||
sx={{
|
sx={{
|
||||||
minWidth: 2050,
|
minWidth: 2200,
|
||||||
tableLayout: "fixed",
|
tableLayout: "fixed",
|
||||||
"& .MuiTableCell-head": {
|
"& .MuiTableCell-head": {
|
||||||
backgroundColor: "var(--color-bg-muted)",
|
backgroundColor: "var(--color-bg-muted)",
|
||||||
|
|
@ -94,7 +95,7 @@ export function VendorsTable({
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<colgroup>
|
<colgroup>
|
||||||
{[190, 160, 220, 220, 140, 100, 190, 220, 170, 110, 120, 130].map((width, index) => (
|
{[190, 160, 220, 220, 140, 100, 150, 190, 220, 170, 110, 120, 130].map((width, index) => (
|
||||||
<col key={`${width}-${index}`} style={{ width }} />
|
<col key={`${width}-${index}`} style={{ width }} />
|
||||||
))}
|
))}
|
||||||
</colgroup>
|
</colgroup>
|
||||||
|
|
|
||||||
20
src/app/(protected)/vendors/index.tsx
vendored
|
|
@ -13,7 +13,7 @@ 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 { useVendorDirectoryList } from "@/domain/vendors/use-cases/use-vendor-directory-list";
|
import { useVendorDirectoryList } from "@/domain/vendors/use-cases/use-vendor-directory-list";
|
||||||
|
|
||||||
|
|
@ -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}` }),
|
||||||
);
|
);
|
||||||
|
|
@ -146,7 +154,15 @@ 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">
|
||||||
|
|
|
||||||
|
|
@ -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");
|
||||||
|
|
|
||||||
|
|
@ -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}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,8 @@ 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;
|
||||||
};
|
};
|
||||||
|
|
||||||
async function resolveDuplicateWoNumber(
|
async function resolveDuplicateWoNumber(
|
||||||
|
|
@ -34,6 +36,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 +73,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);
|
||||||
|
|
@ -162,7 +187,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} />
|
||||||
|
|
|
||||||
|
|
@ -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,
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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)}
|
||||||
/>
|
/>
|
||||||
|
|
|
||||||
|
|
@ -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}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
|
|
|
||||||
1
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
15
src/domain/vendors/mappers/vendor-mapper.ts
vendored
|
|
@ -2,6 +2,7 @@ import type {
|
||||||
Vendor,
|
Vendor,
|
||||||
VendorDeactivationImpact,
|
VendorDeactivationImpact,
|
||||||
VendorDirectoryTechnician,
|
VendorDirectoryTechnician,
|
||||||
|
VendorFacetArea,
|
||||||
VendorFacetCompany,
|
VendorFacetCompany,
|
||||||
VendorFacetJobBucket,
|
VendorFacetJobBucket,
|
||||||
VendorFacetLocation,
|
VendorFacetLocation,
|
||||||
|
|
@ -126,6 +127,8 @@ 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 rawTechnicians = item.technicians ?? item.Technicians;
|
||||||
const technicians = Array.isArray(rawTechnicians)
|
const technicians = Array.isArray(rawTechnicians)
|
||||||
|
|
@ -290,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 {
|
||||||
|
|
@ -304,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) : [],
|
||||||
|
|
@ -315,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;
|
||||||
|
|
|
||||||
|
|
@ -54,6 +54,8 @@ const baseCompanyFields = {
|
||||||
notes: z
|
notes: z
|
||||||
.string()
|
.string()
|
||||||
.max(VENDOR_NOTES_MAX_LENGTH, `Notes must be ${VENDOR_NOTES_MAX_LENGTH} characters or fewer`),
|
.max(VENDOR_NOTES_MAX_LENGTH, `Notes must be ${VENDOR_NOTES_MAX_LENGTH} characters or fewer`),
|
||||||
|
// Optional stable Area id; "" means Unassigned. Admin-only to change.
|
||||||
|
areaId: z.string(),
|
||||||
technicians: z.array(rosterTechnicianSchema),
|
technicians: z.array(rosterTechnicianSchema),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -107,5 +109,6 @@ export const emptyVendorCompanyRosterForm: VendorCompanyRosterFormValues = {
|
||||||
state: "",
|
state: "",
|
||||||
zip: "",
|
zip: "",
|
||||||
notes: "",
|
notes: "",
|
||||||
|
areaId: "",
|
||||||
technicians: [],
|
technicians: [],
|
||||||
};
|
};
|
||||||
|
|
|
||||||
19
src/domain/vendors/types/vendor.ts
vendored
|
|
@ -30,6 +30,10 @@ export interface VendorListItem {
|
||||||
tradeSpecialties: string;
|
tradeSpecialties: string;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
preferredContact: VendorPreferredContact;
|
preferredContact: VendorPreferredContact;
|
||||||
|
/** Stable Area id as a string; "" when the company is Unassigned. */
|
||||||
|
areaId: string;
|
||||||
|
/** Area display name; "" when the company is Unassigned. */
|
||||||
|
areaName: string;
|
||||||
/** Present on company-grouped directory responses; optional for legacy clients/fixtures. */
|
/** Present on company-grouped directory responses; optional for legacy clients/fixtures. */
|
||||||
technicians?: VendorDirectoryTechnician[];
|
technicians?: VendorDirectoryTechnician[];
|
||||||
}
|
}
|
||||||
|
|
@ -63,6 +67,8 @@ export interface VendorsListParams {
|
||||||
trades?: string[];
|
trades?: string[];
|
||||||
locations?: string[];
|
locations?: string[];
|
||||||
jobBuckets?: string[];
|
jobBuckets?: string[];
|
||||||
|
/** Stable Area ids or the "__unassigned__" sentinel. */
|
||||||
|
areas?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface VendorsListResult {
|
export interface VendorsListResult {
|
||||||
|
|
@ -95,9 +101,19 @@ export interface VendorFacetJobBucket {
|
||||||
label: string;
|
label: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Active Area catalogue option. `id` is the stable areas[n] filter value. */
|
||||||
|
export interface VendorFacetArea {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wire value that selects companies without an Area. */
|
||||||
|
export const VENDOR_AREA_UNASSIGNED = "__unassigned__";
|
||||||
|
|
||||||
export interface VendorFacets {
|
export interface VendorFacets {
|
||||||
companies: VendorFacetCompany[];
|
companies: VendorFacetCompany[];
|
||||||
trades: string[];
|
trades: string[];
|
||||||
|
areas: VendorFacetArea[];
|
||||||
locations: VendorFacetLocation[];
|
locations: VendorFacetLocation[];
|
||||||
jobBuckets: VendorFacetJobBucket[];
|
jobBuckets: VendorFacetJobBucket[];
|
||||||
}
|
}
|
||||||
|
|
@ -147,6 +163,9 @@ export interface VendorCompanyRoster {
|
||||||
zip: string;
|
zip: string;
|
||||||
googleMapsUrl: string;
|
googleMapsUrl: string;
|
||||||
notes: string;
|
notes: string;
|
||||||
|
/** Stable Area id as a string; "" when the company is Unassigned. */
|
||||||
|
areaId: string;
|
||||||
|
areaName: string;
|
||||||
technicians: VendorRosterTechnician[];
|
technicians: VendorRosterTechnician[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,7 @@ const COMPANY_FIELDS = [
|
||||||
"state",
|
"state",
|
||||||
"zip",
|
"zip",
|
||||||
"notes",
|
"notes",
|
||||||
|
"areaId",
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
const TECHNICIAN_FIELDS = [
|
const TECHNICIAN_FIELDS = [
|
||||||
|
|
|
||||||
17
src/domain/work-orders/constants/wo-table-header-tooltips.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
/**
|
||||||
|
* Help copy for date-column headers on the work orders board table.
|
||||||
|
* Keyed by the `WO_TABLE_COLS` column key; only columns with copy here show a
|
||||||
|
* header help icon. `appt` (Appt Time) is an intentional open point — do not
|
||||||
|
* add it without a business-rule decision.
|
||||||
|
*/
|
||||||
|
export const WO_TABLE_HEADER_TOOLTIPS = {
|
||||||
|
sched: "The date the work is planned to happen. Setting it moves the work order to Scheduled.",
|
||||||
|
due: "The deadline for the work — when it must be completed by.",
|
||||||
|
completed: "The date the vendor actually finished the work. Required to complete the work order.",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function getWoTableHeaderTooltip(colKey: string): string | undefined {
|
||||||
|
return colKey in WO_TABLE_HEADER_TOOLTIPS
|
||||||
|
? WO_TABLE_HEADER_TOOLTIPS[colKey as keyof typeof WO_TABLE_HEADER_TOOLTIPS]
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
45
src/domain/work-orders/errors/board-create-errors.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
import { isHTTPError, isNetworkError, isTimeoutError } from "ky";
|
||||||
|
import { mapHttpStatusToMessage } from "@/api/api-error";
|
||||||
|
import { DISPATCH_REQUIRED_MESSAGE } from "@/domain/work-orders/errors/board-patch-errors";
|
||||||
|
|
||||||
|
export const BOARD_CREATE_FAILED_MESSAGE = "Unable to create the work order. Please try again.";
|
||||||
|
|
||||||
|
const DUPLICATE_WO_NUMBER_MESSAGE =
|
||||||
|
"This work order number is already assigned to another work order.";
|
||||||
|
|
||||||
|
/** Statuses whose mapped copy is fixed product text, never the response body. */
|
||||||
|
const FIXED_COPY_STATUSES = new Set([401, 403, 404, 500]);
|
||||||
|
|
||||||
|
function readErrorCode(data: unknown): string | undefined {
|
||||||
|
if (typeof data !== "object" || data === null) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const record = data as Record<string, unknown>;
|
||||||
|
const code = record.code ?? record.Code;
|
||||||
|
return typeof code === "string" ? code : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* why: board create returns backend validation text ("siteCode is required.",
|
||||||
|
* "vendorId is required when setting appointment fields.") that must never reach the
|
||||||
|
* screen. Unknown failures fall back to generic copy, not to `error.message`.
|
||||||
|
*/
|
||||||
|
export function boardCreateErrorMessage(error: unknown): string {
|
||||||
|
if (isHTTPError(error)) {
|
||||||
|
const code = readErrorCode(error.data);
|
||||||
|
if (code === "DispatchRequired") {
|
||||||
|
return DISPATCH_REQUIRED_MESSAGE;
|
||||||
|
}
|
||||||
|
if (code === "DuplicateWoNumber") {
|
||||||
|
return DUPLICATE_WO_NUMBER_MESSAGE;
|
||||||
|
}
|
||||||
|
const status = error.response.status;
|
||||||
|
return FIXED_COPY_STATUSES.has(status)
|
||||||
|
? mapHttpStatusToMessage(status)
|
||||||
|
: BOARD_CREATE_FAILED_MESSAGE;
|
||||||
|
}
|
||||||
|
if (isNetworkError(error) || isTimeoutError(error)) {
|
||||||
|
return error.message;
|
||||||
|
}
|
||||||
|
return BOARD_CREATE_FAILED_MESSAGE;
|
||||||
|
}
|
||||||
|
|
@ -22,10 +22,12 @@ export class BoardPatchValidationError extends Error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const DISPATCH_REQUIRED_MESSAGE = "Select a vendor company before saving.";
|
||||||
|
|
||||||
/** why: backend field names must never be exposed through user-facing board toasts. */
|
/** why: backend field names must never be exposed through user-facing board toasts. */
|
||||||
export function boardPatchValidationMessage(error: BoardPatchValidationError): string {
|
export function boardPatchValidationMessage(error: BoardPatchValidationError): string {
|
||||||
if (error.code === "DispatchRequired") {
|
if (error.code === "DispatchRequired") {
|
||||||
return "Select a vendor company before saving.";
|
return DISPATCH_REQUIRED_MESSAGE;
|
||||||
}
|
}
|
||||||
return error.message;
|
return error.message;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@ 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 { boardCreateErrorMessage } from "@/domain/work-orders/errors/board-create-errors";
|
||||||
|
|
||||||
import type { WorkOrderDetail } from "@/domain/work-orders/types/work-order";
|
import type { WorkOrderDetail } from "@/domain/work-orders/types/work-order";
|
||||||
|
|
||||||
import type { WorkOrderWizardDraft } from "@/domain/work-orders/types/work-order-wizard";
|
import type { WorkOrderWizardDraft } from "@/domain/work-orders/types/work-order-wizard";
|
||||||
|
|
@ -27,7 +29,7 @@ export function useCreateWorkOrderFromWizard(
|
||||||
},
|
},
|
||||||
|
|
||||||
onError: (error: Error) => {
|
onError: (error: Error) => {
|
||||||
toast.error(error.message || "Failed to create work order");
|
toast.error(boardCreateErrorMessage(error));
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -134,11 +134,17 @@ export function useWorkOrderTableMutations(
|
||||||
mutationFn: ({
|
mutationFn: ({
|
||||||
id,
|
id,
|
||||||
persistPatch,
|
persistPatch,
|
||||||
|
baseRow,
|
||||||
}: {
|
}: {
|
||||||
id: string | number;
|
id: string | number;
|
||||||
patch: WorkOrderTablePatch;
|
patch: WorkOrderTablePatch;
|
||||||
persistPatch: WorkOrderTablePatch;
|
persistPatch: WorkOrderTablePatch;
|
||||||
}) => enqueuePatch(id, () => runWorkOrderTablePatch(id, persistPatch, getRow)),
|
/** Server row from a just-settled patch; its rowVersion is fresher than the table snapshot. */
|
||||||
|
baseRow?: WorkOrderTableRow;
|
||||||
|
}) =>
|
||||||
|
enqueuePatch(id, () =>
|
||||||
|
runWorkOrderTablePatch(id, persistPatch, baseRow ? () => baseRow : getRow),
|
||||||
|
),
|
||||||
onMutate: async ({ id, persistPatch }) => {
|
onMutate: async ({ id, persistPatch }) => {
|
||||||
onPatch(id, persistPatch);
|
onPatch(id, persistPatch);
|
||||||
},
|
},
|
||||||
|
|
@ -182,9 +188,13 @@ export function useWorkOrderTableMutations(
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const patchFieldAsync = (id: string | number, patch: WorkOrderTablePatch) => {
|
const patchFieldAsync = (
|
||||||
const persistPatch = resolvePatch(id, patch);
|
id: string | number,
|
||||||
return patchMutation.mutateAsync({ id, patch, persistPatch });
|
patch: WorkOrderTablePatch,
|
||||||
|
baseRow?: WorkOrderTableRow,
|
||||||
|
) => {
|
||||||
|
const persistPatch = baseRow ? mergeAutoSchedulePatch(baseRow, patch) : resolvePatch(id, patch);
|
||||||
|
return patchMutation.mutateAsync({ id, patch, persistPatch, baseRow });
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -39,24 +39,53 @@ function formatSeverityAuditLabel(raw: string): string {
|
||||||
return raw;
|
return raw;
|
||||||
}
|
}
|
||||||
|
|
||||||
function tryTypeRule({ fieldKey, actionKey, newValue }: AuditActionRuleContext): string | null {
|
const CLEARED_AUDIT_VALUE: FormattedAuditValue = { text: "—", isQuotedList: false };
|
||||||
|
|
||||||
|
/** `from X to Y` whenever the previous value is known; a cleared value reads as "—". */
|
||||||
|
function formatFieldChangeSentence(
|
||||||
|
label: string,
|
||||||
|
oldValue: FormattedAuditValue,
|
||||||
|
newValue: FormattedAuditValue,
|
||||||
|
): string | null {
|
||||||
|
if (!oldValue.text && !newValue.text) return null;
|
||||||
|
const next = wrapAuditValue(newValue.text ? newValue : CLEARED_AUDIT_VALUE);
|
||||||
|
if (oldValue.text) {
|
||||||
|
return `Changed ${label} from ${wrapAuditValue(oldValue)} to ${next}`;
|
||||||
|
}
|
||||||
|
return `Changed ${label} to ${next}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryTypeRule({
|
||||||
|
fieldKey,
|
||||||
|
actionKey,
|
||||||
|
oldValue,
|
||||||
|
newValue,
|
||||||
|
}: AuditActionRuleContext): string | null {
|
||||||
const matches =
|
const matches =
|
||||||
fieldKey === "type" ||
|
fieldKey === "type" ||
|
||||||
fieldKey === "workordertype" ||
|
fieldKey === "workordertype" ||
|
||||||
fieldKey === "wotype" ||
|
fieldKey === "wotype" ||
|
||||||
actionKey === "typechanged" ||
|
actionKey === "typechanged" ||
|
||||||
actionKey.includes("workordertype");
|
actionKey.includes("workordertype");
|
||||||
if (!matches || !newValue.text) return null;
|
if (!matches) return null;
|
||||||
|
|
||||||
return `Changed Type to ${wrapAuditValue(newValue)}`;
|
return formatFieldChangeSentence("Type", oldValue, newValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
function trySeverityRule({ fieldKey, actionKey, newValue }: AuditActionRuleContext): string | null {
|
function severityValue(value: FormattedAuditValue): FormattedAuditValue {
|
||||||
const matches = fieldKey.includes("severity") || actionKey.includes("severity");
|
return value.text ? { text: formatSeverityAuditLabel(value.text), isQuotedList: false } : value;
|
||||||
if (!matches || !newValue.text) return null;
|
}
|
||||||
|
|
||||||
const labeled = { text: formatSeverityAuditLabel(newValue.text), isQuotedList: false };
|
function trySeverityRule({
|
||||||
return `Changed Severity to ${wrapAuditValue(labeled)}`;
|
fieldKey,
|
||||||
|
actionKey,
|
||||||
|
oldValue,
|
||||||
|
newValue,
|
||||||
|
}: AuditActionRuleContext): string | null {
|
||||||
|
const matches = fieldKey.includes("severity") || actionKey.includes("severity");
|
||||||
|
if (!matches) return null;
|
||||||
|
|
||||||
|
return formatFieldChangeSentence("Severity", severityValue(oldValue), severityValue(newValue));
|
||||||
}
|
}
|
||||||
|
|
||||||
function tryStatusRule({
|
function tryStatusRule({
|
||||||
|
|
|
||||||
25
src/domain/work-orders/utils/completion-doc-auto-complete.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
import type { CompDocSaveStatus } from "@/domain/work-orders/types/completion-doc";
|
||||||
|
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
||||||
|
import {
|
||||||
|
getClosabilityGaps,
|
||||||
|
tableRowToClosabilityInput,
|
||||||
|
} from "@/domain/work-orders/utils/wo-closability";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Completion is manual with confirmation, except that generating the completion document
|
||||||
|
* completes the WO — but only when the closability gate passes on the persisted row.
|
||||||
|
* Not-required (NN) and drafts never complete; Past Due rows must be
|
||||||
|
* rescheduled before any status change, so they are left for the dispatcher.
|
||||||
|
*/
|
||||||
|
export function shouldCompleteAfterCompletionDoc(
|
||||||
|
status: CompDocSaveStatus,
|
||||||
|
row: WorkOrderTableRow,
|
||||||
|
): boolean {
|
||||||
|
if (status !== "Yes" || row.docStatus !== "Yes") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (row.status === "Completed" || row.status === "Canceled" || row.isPastDue) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return getClosabilityGaps(tableRowToClosabilityInput(row)).length === 0;
|
||||||
|
}
|
||||||
27
src/domain/work-orders/utils/due-date-floor.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
/**
|
||||||
|
* SH-356: a Due Date can never be earlier than Schedule On.
|
||||||
|
*
|
||||||
|
* The floor is the concrete Schedule On day, the start of a date range, or — for a
|
||||||
|
* week-only schedule (SH-110) — the first day of the target week.
|
||||||
|
*/
|
||||||
|
export function resolveDueDateFloor(schedule: {
|
||||||
|
scheduledOn?: string | null;
|
||||||
|
targetWeek?: string | null;
|
||||||
|
}): string {
|
||||||
|
return schedule.scheduledOn?.trim() || schedule.targetWeek?.trim() || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDueDateBeforeFloor(dueDate: string | null | undefined, floor: string): boolean {
|
||||||
|
return Boolean(dueDate && floor && dueDate < floor);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Patch fragment for a Schedule On change: clears an existing Due Date that the new
|
||||||
|
* schedule would leave in the past. Never bumps it to a guessed value.
|
||||||
|
*/
|
||||||
|
export function clearDueDateBeforeSchedule(
|
||||||
|
dueDate: string | null | undefined,
|
||||||
|
nextFloor: string,
|
||||||
|
): { dueDate?: string } {
|
||||||
|
return isDueDateBeforeFloor(dueDate, nextFloor) ? { dueDate: "" } : {};
|
||||||
|
}
|
||||||
24
src/domain/work-orders/utils/format-audit-timestamp.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
const AUDIT_DATE_PATTERN = /\b\d{1,2}\/\d{1,2}(\/\d{2,4})?\b/;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every entry, manual or system, shows a complete timestamp — `09/15/2026 · 7:42 PM`.
|
||||||
|
* Pre-formatted API strings are kept only when they already carry a calendar date.
|
||||||
|
*/
|
||||||
|
export function formatAuditTimestamp(value: string): string {
|
||||||
|
if (!value) return "";
|
||||||
|
if (AUDIT_DATE_PATTERN.test(value) && /\b(AM|PM)\b/i.test(value)) return value;
|
||||||
|
|
||||||
|
const date = new Date(value);
|
||||||
|
if (Number.isNaN(date.getTime())) return value;
|
||||||
|
|
||||||
|
const datePart = date.toLocaleDateString("en-US", {
|
||||||
|
month: "2-digit",
|
||||||
|
day: "2-digit",
|
||||||
|
year: "numeric",
|
||||||
|
});
|
||||||
|
const timePart = date.toLocaleTimeString("en-US", {
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
});
|
||||||
|
return `${datePart} · ${timePart}`;
|
||||||
|
}
|
||||||
|
|
@ -127,6 +127,10 @@ function formatGenericAuditFallback(args: {
|
||||||
if (newValue.text) {
|
if (newValue.text) {
|
||||||
return `Changed ${label} to ${wrapAuditValue(newValue)}`;
|
return `Changed ${label} to ${wrapAuditValue(newValue)}`;
|
||||||
}
|
}
|
||||||
if (action) return action;
|
if (oldValue.text) {
|
||||||
|
return `Changed ${label} from ${wrapAuditValue(oldValue)} to "—"`;
|
||||||
|
}
|
||||||
|
// Never surface a raw audit enum such as "FieldChanged" as the sentence.
|
||||||
|
if (fieldName && action) return `Updated ${label}`;
|
||||||
return "Updated work order";
|
return "Updated work order";
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,11 @@ const EMPTY_OWNERSHIP: MediaSurfaceOwnership = {
|
||||||
extraOwnedIds: new Set(),
|
extraOwnedIds: new Set(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Only Reactive and Emergency work orders render a media gallery on the Completion tab. */
|
||||||
|
export function hasCompletionMediaGallery(type: string | null | undefined): boolean {
|
||||||
|
return type === "Emergency" || type === "Reactive";
|
||||||
|
}
|
||||||
|
|
||||||
function isPhotoOrVideo(item: MediaFile): boolean {
|
function isPhotoOrVideo(item: MediaFile): boolean {
|
||||||
return item.fileType === "image" || item.fileType === "video";
|
return item.fileType === "image" || item.fileType === "video";
|
||||||
}
|
}
|
||||||
|
|
@ -24,20 +29,25 @@ function isInFlight(item: MediaFile): boolean {
|
||||||
export function isCompletionSurfaceMedia(
|
export function isCompletionSurfaceMedia(
|
||||||
item: MediaFile,
|
item: MediaFile,
|
||||||
ownership: MediaSurfaceOwnership = EMPTY_OWNERSHIP,
|
ownership: MediaSurfaceOwnership = EMPTY_OWNERSHIP,
|
||||||
|
completionHasGallery = true,
|
||||||
): boolean {
|
): boolean {
|
||||||
if (isInFlight(item)) return true;
|
if (isInFlight(item)) return true;
|
||||||
if (COMPLETION_PURPOSES.has(item.purpose ?? "")) return true;
|
if (COMPLETION_PURPOSES.has(item.purpose ?? "")) return true;
|
||||||
|
if (!completionHasGallery && item.purpose === "Extra") return false;
|
||||||
if (ownership.completionOwnedIds.has(item.id)) return true;
|
if (ownership.completionOwnedIds.has(item.id)) return true;
|
||||||
if (ownership.extraOwnedIds.has(item.id)) return false;
|
if (ownership.extraOwnedIds.has(item.id)) return false;
|
||||||
return item.purpose === "Extra" && isPhotoOrVideo(item);
|
return item.purpose === "Extra" && isPhotoOrVideo(item);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Without a Completion gallery, every Extra item (including photos/videos) belongs to Extras. */
|
||||||
export function isExtrasSurfaceMedia(
|
export function isExtrasSurfaceMedia(
|
||||||
item: MediaFile,
|
item: MediaFile,
|
||||||
ownership: MediaSurfaceOwnership = EMPTY_OWNERSHIP,
|
ownership: MediaSurfaceOwnership = EMPTY_OWNERSHIP,
|
||||||
|
completionHasGallery = true,
|
||||||
): boolean {
|
): boolean {
|
||||||
if (item.purpose === "Aveta") return true;
|
if (item.purpose === "Aveta") return true;
|
||||||
if (item.purpose !== "Extra") return false;
|
if (item.purpose !== "Extra") return false;
|
||||||
|
if (!completionHasGallery) return true;
|
||||||
if (ownership.completionOwnedIds.has(item.id)) return false;
|
if (ownership.completionOwnedIds.has(item.id)) return false;
|
||||||
if (ownership.extraOwnedIds.has(item.id)) return true;
|
if (ownership.extraOwnedIds.has(item.id)) return true;
|
||||||
return !isPhotoOrVideo(item);
|
return !isPhotoOrVideo(item);
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,21 @@ import {
|
||||||
UPLIFT_PENDING_COMPLETED_TITLE,
|
UPLIFT_PENDING_COMPLETED_TITLE,
|
||||||
} from "@/domain/work-orders/utils/wo-closability";
|
} from "@/domain/work-orders/utils/wo-closability";
|
||||||
|
|
||||||
/** AAP `ALL_STATUSES` — Canceled is kebab-only. */
|
/**
|
||||||
export const BOARD_INLINE_STATUSES: readonly WizardWOStatus[] = ALL_WIZARD_STATUSES;
|
* Lifecycle states the server derives (Incomplete from create, Scheduled from Schedule On).
|
||||||
|
* Past Due is an overlay, not a status. None of these may be picked manually on an existing WO.
|
||||||
|
*/
|
||||||
|
export const AUTOMATIC_LIFECYCLE_STATUSES: readonly WizardWOStatus[] = ["Incomplete", "Scheduled"];
|
||||||
|
|
||||||
|
/** Manually selectable statuses for an existing WO — Canceled is kebab-only. */
|
||||||
|
export const BOARD_INLINE_STATUSES: readonly WizardWOStatus[] = ALL_WIZARD_STATUSES.filter(
|
||||||
|
(status) => !AUTOMATIC_LIFECYCLE_STATUSES.includes(status),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Inline options for an existing WO never repeat its current status. */
|
||||||
|
export function getInlineStatusTransitions(currentStatus: string): WizardWOStatus[] {
|
||||||
|
return BOARD_INLINE_STATUSES.filter((status) => status !== currentStatus);
|
||||||
|
}
|
||||||
|
|
||||||
/** AAP `CREATION_STATUSES` — wizard Step 3 and inline create. */
|
/** AAP `CREATION_STATUSES` — wizard Step 3 and inline create. */
|
||||||
export const CREATION_INLINE_STATUSES: readonly WizardWOStatus[] = [
|
export const CREATION_INLINE_STATUSES: readonly WizardWOStatus[] = [
|
||||||
|
|
|
||||||
|
|
@ -68,6 +68,8 @@ const roster: VendorCompanyRoster = {
|
||||||
zip: "63101",
|
zip: "63101",
|
||||||
googleMapsUrl: "",
|
googleMapsUrl: "",
|
||||||
notes: "",
|
notes: "",
|
||||||
|
areaId: "",
|
||||||
|
areaName: "",
|
||||||
technicians: [],
|
technicians: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -134,6 +136,7 @@ function submitValues(
|
||||||
state: "MO",
|
state: "MO",
|
||||||
zip: "63101",
|
zip: "63101",
|
||||||
notes: "",
|
notes: "",
|
||||||
|
areaId: "",
|
||||||
technicians,
|
technicians,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
@ -300,6 +303,7 @@ describe("useVendorRosterForm prototype defaults", () => {
|
||||||
state: "",
|
state: "",
|
||||||
zip: "",
|
zip: "",
|
||||||
notes: "",
|
notes: "",
|
||||||
|
areaId: "",
|
||||||
technicians: [
|
technicians: [
|
||||||
{
|
{
|
||||||
contactName: "",
|
contactName: "",
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,8 @@ import {
|
||||||
type VendorCompanyRosterFormValues,
|
type VendorCompanyRosterFormValues,
|
||||||
} from "@/domain/vendors/schemas/vendor-roster-schema";
|
} from "@/domain/vendors/schemas/vendor-roster-schema";
|
||||||
import { renderWithProviders } from "@/test/test-utils";
|
import { renderWithProviders } from "@/test/test-utils";
|
||||||
|
import type { StateCode } from "@/data/areas";
|
||||||
|
import { pickVendorState } from "./vendor-state-select";
|
||||||
|
|
||||||
vi.mock("@/domain/vendors/use-cases/use-vendor-facets", () => ({
|
vi.mock("@/domain/vendors/use-cases/use-vendor-facets", () => ({
|
||||||
useVendorFacets: () => ({ data: { companies: [], trades: [] }, isLoading: false }),
|
useVendorFacets: () => ({ data: { companies: [], trades: [] }, isLoading: false }),
|
||||||
|
|
@ -58,16 +60,18 @@ async function fillCompanyNameAndSubmit(name = "Gateway Plumbing") {
|
||||||
await userEvent.click(screen.getByRole("button", { name: "Add Vendor" }));
|
await userEvent.click(screen.getByRole("button", { name: "Add Vendor" }));
|
||||||
}
|
}
|
||||||
|
|
||||||
function fillRequiredAddress({ street = "6735 Trippel Rd", city = "Theodore", state = "AL" } = {}) {
|
function fillRequiredAddress({
|
||||||
|
street = "6735 Trippel Rd",
|
||||||
|
city = "Theodore",
|
||||||
|
state = "AL" as StateCode,
|
||||||
|
} = {}) {
|
||||||
fireEvent.change(screen.getByRole("combobox", { name: "Street Address (required)" }), {
|
fireEvent.change(screen.getByRole("combobox", { name: "Street Address (required)" }), {
|
||||||
target: { value: street },
|
target: { value: street },
|
||||||
});
|
});
|
||||||
fireEvent.change(screen.getByRole("textbox", { name: "City (required)" }), {
|
fireEvent.change(screen.getByRole("textbox", { name: "City (required)" }), {
|
||||||
target: { value: city },
|
target: { value: city },
|
||||||
});
|
});
|
||||||
fireEvent.change(screen.getByRole("textbox", { name: "State (required)" }), {
|
pickVendorState(state);
|
||||||
target: { value: state },
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("VendorCreateModal validation", () => {
|
describe("VendorCreateModal validation", () => {
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,8 @@ const vendor: VendorListItem = {
|
||||||
tradeSpecialties: "",
|
tradeSpecialties: "",
|
||||||
isActive: true,
|
isActive: true,
|
||||||
preferredContact: "Phone",
|
preferredContact: "Phone",
|
||||||
|
areaId: "",
|
||||||
|
areaName: "",
|
||||||
};
|
};
|
||||||
|
|
||||||
function rosterWith(technicians: Array<Record<string, unknown>>) {
|
function rosterWith(technicians: Array<Record<string, unknown>>) {
|
||||||
|
|
@ -57,6 +59,8 @@ function rosterWith(technicians: Array<Record<string, unknown>>) {
|
||||||
zip: "",
|
zip: "",
|
||||||
googleMapsUrl: "",
|
googleMapsUrl: "",
|
||||||
notes: "",
|
notes: "",
|
||||||
|
areaId: "",
|
||||||
|
areaName: "",
|
||||||
technicians,
|
technicians,
|
||||||
},
|
},
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
|
|
|
||||||
|
|
@ -11,11 +11,15 @@ import {
|
||||||
} from "@/domain/vendors/schemas/vendor-roster-schema";
|
} from "@/domain/vendors/schemas/vendor-roster-schema";
|
||||||
import { suggestAddresses } from "@/lib/address/vendor-address";
|
import { suggestAddresses } from "@/lib/address/vendor-address";
|
||||||
import { renderWithProviders } from "@/test/test-utils";
|
import { renderWithProviders } from "@/test/test-utils";
|
||||||
|
import { formatStateOptionLabel, normalizeStateCode } from "@/data/areas";
|
||||||
|
import { pickVendorState, stateField } from "./vendor-state-select";
|
||||||
|
|
||||||
const TYPED_STREET = "415 Murphy Rd";
|
const TYPED_STREET = "415 Murphy Rd";
|
||||||
const FIRST_SUGGESTION = suggestAddresses(TYPED_STREET)[0];
|
const FIRST_SUGGESTION = suggestAddresses(TYPED_STREET)[0];
|
||||||
|
|
||||||
if (FIRST_SUGGESTION == null) throw new Error("expected a suggestion for the typed street");
|
if (FIRST_SUGGESTION == null) throw new Error("expected a suggestion for the typed street");
|
||||||
|
const FIRST_SUGGESTION_STATE = normalizeStateCode(FIRST_SUGGESTION.state);
|
||||||
|
if (FIRST_SUGGESTION_STATE == null) throw new Error("expected a canonical suggestion state");
|
||||||
|
|
||||||
function AddressFormHarness({
|
function AddressFormHarness({
|
||||||
onValid,
|
onValid,
|
||||||
|
|
@ -67,9 +71,7 @@ describe("VendorRosterFormFields address autocomplete", () => {
|
||||||
expect(screen.getByRole("textbox", { name: "City (required)" })).toHaveValue(
|
expect(screen.getByRole("textbox", { name: "City (required)" })).toHaveValue(
|
||||||
FIRST_SUGGESTION.city,
|
FIRST_SUGGESTION.city,
|
||||||
);
|
);
|
||||||
expect(screen.getByRole("textbox", { name: "State (required)" })).toHaveValue(
|
expect(stateField()).toHaveValue(formatStateOptionLabel(FIRST_SUGGESTION_STATE));
|
||||||
FIRST_SUGGESTION.state,
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("submits the settled structured parts, not the option label", async () => {
|
it("submits the settled structured parts, not the option label", async () => {
|
||||||
|
|
@ -104,14 +106,12 @@ describe("VendorRosterFormFields address autocomplete", () => {
|
||||||
expect(screen.getByRole("textbox", { name: "City (required)" })).toHaveValue(
|
expect(screen.getByRole("textbox", { name: "City (required)" })).toHaveValue(
|
||||||
FIRST_SUGGESTION.city,
|
FIRST_SUGGESTION.city,
|
||||||
);
|
);
|
||||||
expect(screen.getByRole("textbox", { name: "State (required)" })).toHaveValue(
|
expect(stateField()).toHaveValue(formatStateOptionLabel(FIRST_SUGGESTION_STATE));
|
||||||
FIRST_SUGGESTION.state,
|
|
||||||
);
|
|
||||||
await user.click(screen.getByRole("button", { name: "Clear" }));
|
await user.click(screen.getByRole("button", { name: "Clear" }));
|
||||||
|
|
||||||
expect(street).toHaveValue("");
|
expect(street).toHaveValue("");
|
||||||
expect(screen.getByRole("textbox", { name: "City (required)" })).toHaveValue("");
|
expect(screen.getByRole("textbox", { name: "City (required)" })).toHaveValue("");
|
||||||
expect(screen.getByRole("textbox", { name: "State (required)" })).toHaveValue("");
|
expect(stateField()).toHaveValue("");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -132,9 +132,7 @@ describe("VendorRosterFormFields map preview empty state", () => {
|
||||||
fireEvent.change(screen.getByRole("textbox", { name: "City (required)" }), {
|
fireEvent.change(screen.getByRole("textbox", { name: "City (required)" }), {
|
||||||
target: { value: "Theodore" },
|
target: { value: "Theodore" },
|
||||||
});
|
});
|
||||||
fireEvent.change(screen.getByRole("textbox", { name: "State (required)" }), {
|
pickVendorState("AL");
|
||||||
target: { value: "AL" },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(await screen.findByTitle(`Map of ${TYPED_STREET} Theodore AL`)).toBeInTheDocument();
|
expect(await screen.findByTitle(`Map of ${TYPED_STREET} Theodore AL`)).toBeInTheDocument();
|
||||||
expect(screen.queryByRole("status")).not.toBeInTheDocument();
|
expect(screen.queryByRole("status")).not.toBeInTheDocument();
|
||||||
|
|
|
||||||
197
src/test/app/(protected)/vendors/vendor-service-area.test.tsx
vendored
Normal file
|
|
@ -0,0 +1,197 @@
|
||||||
|
import { fireEvent, screen, waitFor } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { useForm } from "react-hook-form";
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { VendorRosterFormFields } from "@/app/(protected)/vendors/_components/vendor-roster-form-fields";
|
||||||
|
import { SERVICE_AREA_ADMIN_ONLY_MESSAGE } from "@/app/(protected)/vendors/_components/vendor-service-area-field";
|
||||||
|
import { VendorFilterOptions } from "@/app/(protected)/vendors/_components/vendor-filter-options";
|
||||||
|
import {
|
||||||
|
emptyVendorFilters,
|
||||||
|
serviceAreaFilterOptions,
|
||||||
|
} from "@/app/(protected)/vendors/_components/vendor-filters";
|
||||||
|
import {
|
||||||
|
emptyVendorCompanyRosterForm,
|
||||||
|
vendorCompanyRosterSchema,
|
||||||
|
type VendorCompanyRosterFormValues,
|
||||||
|
} from "@/domain/vendors/schemas/vendor-roster-schema";
|
||||||
|
import { VENDOR_AREA_UNASSIGNED, type VendorFacetArea } from "@/domain/vendors/types/vendor";
|
||||||
|
import {
|
||||||
|
mapVendorRosterAdditivePatchToBackend,
|
||||||
|
mapVendorRosterToBackend,
|
||||||
|
} from "@/domain/vendors/mappers/vendor-roster-mapper";
|
||||||
|
import { mapVendorFacets, mapVendorListItem } from "@/domain/vendors/mappers/vendor-mapper";
|
||||||
|
import { renderWithProviders } from "@/test/test-utils";
|
||||||
|
import { pickVendorState, stateField } from "./vendor-state-select";
|
||||||
|
|
||||||
|
const AREAS: VendorFacetArea[] = [
|
||||||
|
{ id: "1", name: "East" },
|
||||||
|
{ id: "2", name: "Central" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function Harness({
|
||||||
|
canAssignArea,
|
||||||
|
currentArea = null,
|
||||||
|
defaults = {},
|
||||||
|
onValid,
|
||||||
|
}: {
|
||||||
|
canAssignArea: boolean;
|
||||||
|
currentArea?: VendorFacetArea | null;
|
||||||
|
defaults?: Partial<VendorCompanyRosterFormValues>;
|
||||||
|
onValid: (values: VendorCompanyRosterFormValues) => void;
|
||||||
|
}) {
|
||||||
|
const { control, handleSubmit, formState } = useForm<VendorCompanyRosterFormValues>({
|
||||||
|
defaultValues: { ...emptyVendorCompanyRosterForm, ...defaults },
|
||||||
|
resolver: zodResolver(vendorCompanyRosterSchema),
|
||||||
|
mode: "onChange",
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
<form onSubmit={handleSubmit(onValid)}>
|
||||||
|
<VendorRosterFormFields
|
||||||
|
control={control}
|
||||||
|
errors={formState.errors}
|
||||||
|
areaOptions={AREAS}
|
||||||
|
currentArea={currentArea}
|
||||||
|
canAssignArea={canAssignArea}
|
||||||
|
/>
|
||||||
|
<button type="submit">Submit</button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const COMPLETE_COMPANY: Partial<VendorCompanyRosterFormValues> = {
|
||||||
|
name: "Gateway Plumbing",
|
||||||
|
companyPhone: "(314) 555-0100",
|
||||||
|
address: "1 Market St",
|
||||||
|
city: "St. Louis",
|
||||||
|
state: "MO",
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("Vendor Service Area field", () => {
|
||||||
|
it("lets an admin assign one Service Area by stable id", async () => {
|
||||||
|
const onValid = vi.fn();
|
||||||
|
renderWithProviders(<Harness canAssignArea onValid={onValid} defaults={COMPLETE_COMPANY} />, {
|
||||||
|
withAuth: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const area = screen.getByRole("combobox", { name: "Service Area (optional)" });
|
||||||
|
expect(area).toBeEnabled();
|
||||||
|
fireEvent.change(area, { target: { value: "Cen" } });
|
||||||
|
fireEvent.click(screen.getByRole("option", { name: "Central" }));
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: "Submit" }));
|
||||||
|
|
||||||
|
await waitFor(() => expect(onValid).toHaveBeenCalledTimes(1));
|
||||||
|
expect((onValid.mock.calls[0]?.[0] as VendorCompanyRosterFormValues).areaId).toBe("2");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows the saved Area read-only to non-admins and keeps it on submit", async () => {
|
||||||
|
const onValid = vi.fn();
|
||||||
|
renderWithProviders(
|
||||||
|
<Harness
|
||||||
|
canAssignArea={false}
|
||||||
|
currentArea={{ id: "9", name: "Archived Zone" }}
|
||||||
|
defaults={{ ...COMPLETE_COMPANY, areaId: "9" }}
|
||||||
|
onValid={onValid}
|
||||||
|
/>,
|
||||||
|
{ withAuth: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
const area = screen.getByRole("combobox", { name: "Service Area (optional)" });
|
||||||
|
expect(area).toBeDisabled();
|
||||||
|
expect(area).toHaveValue("Archived Zone");
|
||||||
|
expect(screen.getByText(SERVICE_AREA_ADMIN_ONLY_MESSAGE)).toBeInTheDocument();
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: "Submit" }));
|
||||||
|
|
||||||
|
await waitFor(() => expect(onValid).toHaveBeenCalledTimes(1));
|
||||||
|
expect((onValid.mock.calls[0]?.[0] as VendorCompanyRosterFormValues).areaId).toBe("9");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not derive the Service Area from the selected State", () => {
|
||||||
|
renderWithProviders(<Harness canAssignArea onValid={vi.fn()} />, { withAuth: false });
|
||||||
|
|
||||||
|
pickVendorState("CA");
|
||||||
|
|
||||||
|
expect(stateField()).toHaveValue("California (CA)");
|
||||||
|
expect(screen.getByRole("combobox", { name: "Service Area (optional)" })).toHaveValue("");
|
||||||
|
expect(screen.queryByText(/Area:/)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Vendor State field", () => {
|
||||||
|
it("is a closed list: free text is not kept and legacy names show as codes", () => {
|
||||||
|
renderWithProviders(
|
||||||
|
<Harness canAssignArea={false} onValid={vi.fn()} defaults={{ state: "missouri" }} />,
|
||||||
|
{ withAuth: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(stateField()).toHaveValue("Missouri (MO)");
|
||||||
|
fireEvent.change(stateField(), { target: { value: "Ontario" } });
|
||||||
|
expect(screen.queryByRole("option", { name: /Ontario/ })).not.toBeInTheDocument();
|
||||||
|
fireEvent.blur(stateField());
|
||||||
|
expect(stateField()).toHaveValue("Missouri (MO)");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Service Area contracts", () => {
|
||||||
|
it("orders filter options Unassigned first, then names A–Z", () => {
|
||||||
|
expect(
|
||||||
|
serviceAreaFilterOptions([
|
||||||
|
{ id: "3", name: "West" },
|
||||||
|
{ id: "4", name: "california" },
|
||||||
|
{ id: "1", name: "East" },
|
||||||
|
]).map((option) => option.id),
|
||||||
|
).toEqual([VENDOR_AREA_UNASSIGNED, "4", "1", "3"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps facet areas and directory Area fields from the API", () => {
|
||||||
|
expect(
|
||||||
|
mapVendorFacets({
|
||||||
|
Areas: [
|
||||||
|
{ Id: 1, Name: "East" },
|
||||||
|
{ Id: 0, Name: "" },
|
||||||
|
],
|
||||||
|
}).areas,
|
||||||
|
).toEqual([{ id: "1", name: "East" }]);
|
||||||
|
const row = mapVendorListItem({ Id: 1, AreaId: 2, AreaName: "Central" });
|
||||||
|
expect(row.areaId).toBe("2");
|
||||||
|
expect(row.areaName).toBe("Central");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("round-trips form Areas, sends explicit null for Unassigned, and omits absent Areas", () => {
|
||||||
|
expect(mapVendorRosterToBackend({ name: "A", areaId: "3" }).areaId).toBe(3);
|
||||||
|
expect(mapVendorRosterToBackend({ name: "A", areaId: "" }).areaId).toBeNull();
|
||||||
|
expect(mapVendorRosterToBackend({ name: "A" })).not.toHaveProperty("areaId");
|
||||||
|
expect(
|
||||||
|
mapVendorRosterAdditivePatchToBackend({
|
||||||
|
rowVersion: "rv",
|
||||||
|
addTechnicians: [],
|
||||||
|
companyFields: { areaId: "" },
|
||||||
|
}).companyFields,
|
||||||
|
).toEqual({ areaId: null });
|
||||||
|
expect(
|
||||||
|
mapVendorRosterAdditivePatchToBackend({ rowVersion: "rv", addTechnicians: [] }),
|
||||||
|
).not.toHaveProperty("companyFields");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Vendor Service Area filter section", () => {
|
||||||
|
it("sits between Trade and Location", () => {
|
||||||
|
const setDraft = vi.fn();
|
||||||
|
renderWithProviders(
|
||||||
|
<VendorFilterOptions
|
||||||
|
facets={{ companies: [], trades: [], areas: AREAS, locations: [], jobBuckets: [] }}
|
||||||
|
draft={emptyVendorFilters}
|
||||||
|
setDraft={setDraft}
|
||||||
|
/>,
|
||||||
|
{ withAuth: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getAllByRole("button").map((button) => button.textContent)).toEqual([
|
||||||
|
"Company",
|
||||||
|
"Trade",
|
||||||
|
"Service Area",
|
||||||
|
"Location",
|
||||||
|
"Total Jobs",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
15
src/test/app/(protected)/vendors/vendor-state-select.ts
vendored
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
import { fireEvent, screen } from "@testing-library/react";
|
||||||
|
import { formatStateOptionLabel, type StateCode } from "@/data/areas";
|
||||||
|
|
||||||
|
export const STATE_FIELD_NAME = "State (required)";
|
||||||
|
|
||||||
|
export function stateField(): HTMLElement {
|
||||||
|
return screen.getByRole("combobox", { name: STATE_FIELD_NAME });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Picks a state from the closed vendor State list by its option label. */
|
||||||
|
export function pickVendorState(code: StateCode): void {
|
||||||
|
const label = formatStateOptionLabel(code);
|
||||||
|
fireEvent.change(stateField(), { target: { value: label } });
|
||||||
|
fireEvent.click(screen.getByRole("option", { name: label }));
|
||||||
|
}
|
||||||
|
|
@ -46,6 +46,8 @@ const activeVendor: VendorListItem = {
|
||||||
tradeSpecialties: "Backflow Preventers",
|
tradeSpecialties: "Backflow Preventers",
|
||||||
isActive: true,
|
isActive: true,
|
||||||
preferredContact: "Email",
|
preferredContact: "Email",
|
||||||
|
areaId: "",
|
||||||
|
areaName: "",
|
||||||
};
|
};
|
||||||
|
|
||||||
const inactiveVendor = {
|
const inactiveVendor = {
|
||||||
|
|
@ -67,6 +69,8 @@ const activeRoster: VendorCompanyRoster = {
|
||||||
zip: "",
|
zip: "",
|
||||||
googleMapsUrl: "",
|
googleMapsUrl: "",
|
||||||
notes: "",
|
notes: "",
|
||||||
|
areaId: "",
|
||||||
|
areaName: "",
|
||||||
technicians: [
|
technicians: [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
|
|
@ -668,4 +672,30 @@ describe("VendorsListPage", () => {
|
||||||
expect(screen.getByRole("tab", { name: "Active (3)" })).toBeInTheDocument();
|
expect(screen.getByRole("tab", { name: "Active (3)" })).toBeInTheDocument();
|
||||||
expect(screen.getByRole("tab", { name: "Inactive (2)" })).toBeInTheDocument();
|
expect(screen.getByRole("tab", { name: "Inactive (2)" })).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("shows the Service Area column after State with Unassigned for companies without an Area", () => {
|
||||||
|
setupDefaults();
|
||||||
|
const assigned: VendorListItem = { ...activeVendor, areaId: "1", areaName: "East" };
|
||||||
|
const unassigned: VendorListItem = {
|
||||||
|
...activeVendor,
|
||||||
|
id: 9,
|
||||||
|
companyId: "co-9",
|
||||||
|
companyName: "No Area Co",
|
||||||
|
};
|
||||||
|
useVendorDirectoryList.mockImplementation(
|
||||||
|
(params: { isActive?: boolean; pageSize?: number }) => {
|
||||||
|
if (params.pageSize === 1) return result([], 2);
|
||||||
|
return params.isActive ? result([assigned, unassigned], 2) : result([], 0);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||||
|
|
||||||
|
const headers = screen.getAllByRole("columnheader").map((header) => header.textContent);
|
||||||
|
expect(headers.indexOf("Service Area")).toBe(headers.indexOf("State") + 1);
|
||||||
|
expect(headers.indexOf("Trade")).toBe(headers.indexOf("Service Area") + 1);
|
||||||
|
expect(
|
||||||
|
screen.getAllByTestId("vendor-text-service-area").map((cell) => cell.textContent),
|
||||||
|
).toEqual(["East", "Unassigned"]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,194 @@
|
||||||
|
import { fireEvent, render, renderHook, screen, within } from "@testing-library/react";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { SlideOverInfoTabEditView } from "@/app/(protected)/workorders/_components/detail/tabs/slide-over-info-tab-edit-view";
|
||||||
|
import { WoTableInlineRow } from "@/app/(protected)/workorders/_components/list/table/wo-table-inline-row";
|
||||||
|
import { useWoTableRowHandlers } from "@/app/(protected)/workorders/_components/list/table/use-wo-table-row-handlers";
|
||||||
|
import { MiniCalendar } from "@/app/(protected)/workorders/_components/wizard/mini-calendar";
|
||||||
|
import { WizardStepTypeSchedule } from "@/app/(protected)/workorders/_components/wizard/wizard-step-type-schedule";
|
||||||
|
import { EMPTY_TABLE_DRAFT } from "@/domain/work-orders/types/work-order-table-row";
|
||||||
|
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
||||||
|
import { EMPTY_WIZARD_DRAFT } from "@/domain/work-orders/types/work-order-wizard";
|
||||||
|
import { pad2, todayIso } from "@/domain/work-orders/utils/wizard-date-utils";
|
||||||
|
import { renderWithProviders } from "@/test/test-utils";
|
||||||
|
|
||||||
|
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/site-cell", () => ({
|
||||||
|
SiteCell: () => null,
|
||||||
|
}));
|
||||||
|
vi.mock(
|
||||||
|
"@/app/(protected)/workorders/_components/list/table/cells/editable-wo-number-cell",
|
||||||
|
() => ({ EditableWONumberCell: () => null }),
|
||||||
|
);
|
||||||
|
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/type-cell", () => ({
|
||||||
|
TypeCell: () => null,
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/assigned-to-cell", () => ({
|
||||||
|
AssignedToCell: () => null,
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/appt-time-cell", () => ({
|
||||||
|
ApptTimeCell: () => null,
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/pm-type-cell", () => ({
|
||||||
|
PMTypeCell: () => null,
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/vendor-cell", () => ({
|
||||||
|
VendorCell: () => null,
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/(protected)/workorders/_components/list/table/cells/status-cell", () => ({
|
||||||
|
StatusCell: () => null,
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/(protected)/workorders/_components/list/table/reschedule-notify", () => ({
|
||||||
|
rescheduleNotify: vi.fn(),
|
||||||
|
weekMoveNotify: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
function day(n: number): string {
|
||||||
|
const [y, m] = todayIso().split("-").map(Number);
|
||||||
|
return `${y}-${pad2(m)}-${pad2(n)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rowByLabel(label: string) {
|
||||||
|
return screen.getByText(label, { selector: "span,label,div" }).closest("div")!;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Due Date cannot be before Schedule On (SH-356)", () => {
|
||||||
|
it("disables calendar days before the floor", () => {
|
||||||
|
render(<MiniCalendar value={day(12)} minDate={day(10)} onChange={vi.fn()} />);
|
||||||
|
|
||||||
|
expect(screen.getByRole("button", { name: "9" })).toBeDisabled();
|
||||||
|
expect(screen.getByRole("button", { name: "10" })).toBeEnabled();
|
||||||
|
expect(screen.getByRole("button", { name: "11" })).toBeEnabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("slide-over edit", () => {
|
||||||
|
const draft = { scheduledOn: day(10), dueDate: day(12) } as Partial<WorkOrderTableRow>;
|
||||||
|
|
||||||
|
function renderSlideOver(onDraftChange = vi.fn()) {
|
||||||
|
renderWithProviders(
|
||||||
|
<SlideOverInfoTabEditView
|
||||||
|
draft={{ ...EMPTY_TABLE_DRAFT, id: 42, targetWeek: "", ...draft } as WorkOrderTableRow}
|
||||||
|
users={[]}
|
||||||
|
sites={[]}
|
||||||
|
vendors={[]}
|
||||||
|
pmTypes={[]}
|
||||||
|
allOrders={[]}
|
||||||
|
onDraftChange={onDraftChange}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
return onDraftChange;
|
||||||
|
}
|
||||||
|
|
||||||
|
it("disables Due Date days before Schedule On", async () => {
|
||||||
|
renderSlideOver();
|
||||||
|
fireEvent.click(within(rowByLabel("Due Date")).getByRole("button"));
|
||||||
|
|
||||||
|
expect(await screen.findByRole("button", { name: "9" })).toBeDisabled();
|
||||||
|
expect(screen.getByRole("button", { name: "10" })).toBeEnabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clears the Due Date when Schedule On moves past it", async () => {
|
||||||
|
const onDraftChange = renderSlideOver();
|
||||||
|
fireEvent.click(within(rowByLabel("Schedule On")).getAllByRole("button")[0]);
|
||||||
|
fireEvent.click(await screen.findByRole("button", { name: "15" }));
|
||||||
|
|
||||||
|
expect(onDraftChange).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ scheduledOn: day(15), dueDate: "" }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("wizard: clears Due Date on a later Schedule On and floors the Due Date picker", async () => {
|
||||||
|
const onPatch = vi.fn();
|
||||||
|
render(
|
||||||
|
<WizardStepTypeSchedule
|
||||||
|
draft={{ ...EMPTY_WIZARD_DRAFT, scheduledOn: day(10), schedMode: "date", dueDate: day(12) }}
|
||||||
|
users={[]}
|
||||||
|
onUpdate={vi.fn()}
|
||||||
|
onPatch={onPatch}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const dueDateButtons = within(rowByLabel("Due Date").parentElement!).getAllByRole("button");
|
||||||
|
fireEvent.click(dueDateButtons[dueDateButtons.length - 1]);
|
||||||
|
expect(await screen.findByRole("button", { name: "9" })).toBeDisabled();
|
||||||
|
fireEvent.keyDown(document.activeElement ?? document.body, { key: "Escape" });
|
||||||
|
|
||||||
|
const scheduleBlock = rowByLabel("Schedule On").parentElement!;
|
||||||
|
const scheduleButtons = within(scheduleBlock).getAllByRole("button");
|
||||||
|
fireEvent.click(scheduleButtons[scheduleButtons.length - 1]);
|
||||||
|
const calendars = await screen.findAllByRole("button", { name: "15" });
|
||||||
|
fireEvent.click(calendars[calendars.length - 1]);
|
||||||
|
|
||||||
|
expect(onPatch).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ scheduledOn: day(15), dueDate: "" }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("inline creation row: clears Due Date on a later Schedule On", async () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
renderWithProviders(
|
||||||
|
<table>
|
||||||
|
<tbody>
|
||||||
|
<WoTableInlineRow
|
||||||
|
draft={{ ...EMPTY_TABLE_DRAFT, scheduledOn: day(10), dueDate: day(12) }}
|
||||||
|
draftDayKey={day(10)}
|
||||||
|
users={[]}
|
||||||
|
sites={[]}
|
||||||
|
vendors={[]}
|
||||||
|
pmTypes={[]}
|
||||||
|
allRows={[]}
|
||||||
|
onChange={onChange}
|
||||||
|
onSave={vi.fn()}
|
||||||
|
onCancel={vi.fn()}
|
||||||
|
/>
|
||||||
|
</tbody>
|
||||||
|
</table>,
|
||||||
|
{ withAuth: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
const cells = screen.getAllByRole("cell");
|
||||||
|
const dateButtons = cells.flatMap((cell) => within(cell).queryAllByRole("button"));
|
||||||
|
const scheduleButton = dateButtons.find(
|
||||||
|
(b) => b.textContent?.includes(day(10).slice(5).replace("-", "/")) ?? false,
|
||||||
|
);
|
||||||
|
fireEvent.click(scheduleButton ?? dateButtons[0]);
|
||||||
|
fireEvent.click(await screen.findByRole("button", { name: "15" }));
|
||||||
|
|
||||||
|
expect(onChange).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ scheduledOn: day(15), dueDate: "" }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("board row: sends the Due Date clear in the same schedule patch", () => {
|
||||||
|
const onPatch = vi.fn();
|
||||||
|
const { result } = renderHook(() =>
|
||||||
|
useWoTableRowHandlers({
|
||||||
|
tableData: {
|
||||||
|
dragState: { current: { dragId: null, overId: null } },
|
||||||
|
setDragViz: vi.fn(),
|
||||||
|
reorderRows: vi.fn(),
|
||||||
|
endDrag: vi.fn(),
|
||||||
|
revealScheduledRow: vi.fn(),
|
||||||
|
setSelectedId: vi.fn(),
|
||||||
|
} as never,
|
||||||
|
weekMonday: "2026-05-18",
|
||||||
|
onNavigateToDay: vi.fn(),
|
||||||
|
onOpenSlideOver: vi.fn(),
|
||||||
|
onOpenMedia: vi.fn(),
|
||||||
|
onPatch,
|
||||||
|
onScheduleHighlight: vi.fn(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
result.current.onScheduleDate("wo-1", "2026-05-21", "2026-05-20");
|
||||||
|
expect(onPatch).toHaveBeenLastCalledWith("wo-1", expect.objectContaining({ dueDate: "" }));
|
||||||
|
|
||||||
|
result.current.onScheduleRange("wo-1", "2026-05-19", "2026-05-22", "2026-05-20");
|
||||||
|
expect(onPatch.mock.lastCall?.[1]).not.toHaveProperty("dueDate");
|
||||||
|
|
||||||
|
result.current.onScheduleWeek("wo-1", "2026-05-25", "2026-05-20");
|
||||||
|
expect(onPatch).toHaveBeenLastCalledWith(
|
||||||
|
"wo-1",
|
||||||
|
expect.objectContaining({ targetWeek: "2026-05-25", dueDate: "" }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -42,6 +42,16 @@ describe("saveExistingRowType", () => {
|
||||||
expect(onPatch.mock.calls[0]![2]).toBeUndefined();
|
expect(onPatch.mock.calls[0]![2]).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("does not warn when moving between SEV 3–5", () => {
|
||||||
|
const onPatch = vi.fn();
|
||||||
|
|
||||||
|
saveExistingRowType(onPatch, { ...row, severity: 5 }, "Reactive", 3);
|
||||||
|
|
||||||
|
expect(toastWarn).not.toHaveBeenCalled();
|
||||||
|
expect(onPatch).toHaveBeenCalledWith(7, { type: "Reactive", severity: 3 });
|
||||||
|
expect(onPatch.mock.calls[0]![2]).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
it("does not warn when clearing severity on a PM correction", () => {
|
it("does not warn when clearing severity on a PM correction", () => {
|
||||||
const onPatch = vi.fn();
|
const onPatch = vi.fn();
|
||||||
|
|
||||||
|
|
|
||||||
47
src/test/app/(protected)/workorders/severity-badge.test.tsx
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
import { render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { SeverityBadge } from "@/app/(protected)/workorders/_components/list/table/cells/severity-badge";
|
||||||
|
|
||||||
|
describe("SeverityBadge", () => {
|
||||||
|
it("shows description, Accept/Respond deadline, and after-hours on hover", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<SeverityBadge severity={1} />);
|
||||||
|
|
||||||
|
await user.hover(screen.getByText("SEV 1"));
|
||||||
|
|
||||||
|
const tooltip = await screen.findByRole("tooltip");
|
||||||
|
expect(tooltip).toHaveTextContent(
|
||||||
|
"Business Critical Function Down · Accept: 15 min · Respond: 2 hrs · After hours: Yes",
|
||||||
|
);
|
||||||
|
expect(tooltip).not.toHaveTextContent(/Quote|Tech Notes|Invoice|Turnaround/i);
|
||||||
|
|
||||||
|
await user.unhover(screen.getByText("SEV 1"));
|
||||||
|
await waitFor(() => expect(screen.queryByRole("tooltip")).not.toBeInTheDocument());
|
||||||
|
});
|
||||||
|
|
||||||
|
it("transcribes the SEV table row for the given severity", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<SeverityBadge severity={3} />);
|
||||||
|
|
||||||
|
await user.hover(screen.getByText("SEV 3"));
|
||||||
|
|
||||||
|
expect(await screen.findByRole("tooltip")).toHaveTextContent(
|
||||||
|
"Group Productivity Impaired · Accept: 2 hrs · Respond: 8 hrs (next day if after hours) · After hours: Approval required",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is a button only when it can reopen the severity control", async () => {
|
||||||
|
const onClick = vi.fn();
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const { rerender } = render(<SeverityBadge severity={2} />);
|
||||||
|
expect(screen.queryByRole("button")).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
rerender(<SeverityBadge severity={2} onClick={onClick} />);
|
||||||
|
const badge = screen.getByRole("button");
|
||||||
|
expect(badge).toHaveTextContent("SEV 2");
|
||||||
|
await user.click(badge);
|
||||||
|
|
||||||
|
expect(onClick).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,54 @@
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { SlideOverAuditList } from "@/app/(protected)/workorders/_components/detail/slide-over-audit-list";
|
||||||
|
import type { WorkOrderAuditEntry } from "@/domain/work-orders/types/work-order";
|
||||||
|
|
||||||
|
function statusEntry(overrides: Partial<WorkOrderAuditEntry> = {}): WorkOrderAuditEntry {
|
||||||
|
return {
|
||||||
|
id: "s1",
|
||||||
|
fieldName: "LifecycleStatus",
|
||||||
|
oldValue: "Pending",
|
||||||
|
newValue: "En Route",
|
||||||
|
action: "StatusChanged",
|
||||||
|
createdAt: "2026-09-15T19:42:00",
|
||||||
|
userName: "Alex Dispatcher",
|
||||||
|
type: "manual",
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("SlideOverAuditList timestamps (SH-361)", () => {
|
||||||
|
it("shows the date as well as the time on a manual status change", () => {
|
||||||
|
render(<SlideOverAuditList entries={[statusEntry()]} />);
|
||||||
|
|
||||||
|
expect(screen.getByText('Changed status from "Pending" to "En Route"')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/^\d{2}\/\d{2}\/2026 · 7:42 PM$/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders a type correction with its previous value (SH-363)", () => {
|
||||||
|
render(
|
||||||
|
<SlideOverAuditList
|
||||||
|
entries={[
|
||||||
|
statusEntry({
|
||||||
|
id: "t1",
|
||||||
|
action: "FieldChanged",
|
||||||
|
fieldName: "WorkOrderType",
|
||||||
|
oldValue: "PM",
|
||||||
|
newValue: "Reactive",
|
||||||
|
}),
|
||||||
|
statusEntry({
|
||||||
|
id: "t2",
|
||||||
|
action: "FieldChanged",
|
||||||
|
fieldName: "Severity",
|
||||||
|
oldValue: "3",
|
||||||
|
newValue: "",
|
||||||
|
}),
|
||||||
|
]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('Changed Type from "PM" to "Reactive"')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('Changed Severity from "SEV 3" to "—"')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText("FieldChanged")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,46 @@
|
||||||
|
import { fireEvent, render, screen } from "@testing-library/react";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { SlideOverCompletionTab } from "@/app/(protected)/workorders/_components/detail/tabs/slide-over-completion-tab";
|
||||||
|
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
||||||
|
|
||||||
|
function renderTab(pm: string, onOpenCompletionDoc = vi.fn()) {
|
||||||
|
const row = { id: "1", type: "PM", pm, docStatus: "No", rowVersion: "1" } as WorkOrderTableRow;
|
||||||
|
render(
|
||||||
|
<SlideOverCompletionTab
|
||||||
|
row={row}
|
||||||
|
isReadOnly={false}
|
||||||
|
media={[]}
|
||||||
|
onOpenCompletionDoc={onOpenCompletionDoc}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
return onOpenCompletionDoc;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("SlideOverCompletionTab service gate", () => {
|
||||||
|
it("disables the completion document button until a service is selected", () => {
|
||||||
|
const onOpen = renderTab(" ");
|
||||||
|
|
||||||
|
const button = screen.getByRole("button", { name: /select service/i });
|
||||||
|
expect(button).toBeDisabled();
|
||||||
|
expect(
|
||||||
|
screen.getByText("Select a service before opening the completion document."),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.queryByRole("button", { name: /open completion document/i }),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(button);
|
||||||
|
expect(onOpen).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("opens the completion document when a service is selected", () => {
|
||||||
|
const onOpen = renderTab("HVAC Inspection");
|
||||||
|
|
||||||
|
const button = screen.getByRole("button", { name: /open completion document/i });
|
||||||
|
expect(button).toBeEnabled();
|
||||||
|
expect(screen.queryByText(/select service/i)).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(button);
|
||||||
|
expect(onOpen).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -161,4 +161,40 @@ describe("SlideOverExtrasTab Aveta", () => {
|
||||||
|
|
||||||
expect(screen.getByRole("button", { name: "safety-form.pdf" })).toBeDisabled();
|
expect(screen.getByRole("button", { name: "safety-form.pdf" })).toBeDisabled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("labels each extra item with its type and category", () => {
|
||||||
|
const sitePhoto: MediaFile = {
|
||||||
|
id: "m3",
|
||||||
|
name: "site.jpg",
|
||||||
|
fileType: "image",
|
||||||
|
url: "blob:3",
|
||||||
|
category: "Photo",
|
||||||
|
purpose: "Extra",
|
||||||
|
};
|
||||||
|
const walkthrough: MediaFile = {
|
||||||
|
id: "m4",
|
||||||
|
name: "walkthrough.mp4",
|
||||||
|
fileType: "video",
|
||||||
|
url: "blob:4",
|
||||||
|
category: "Video",
|
||||||
|
purpose: "Extra",
|
||||||
|
};
|
||||||
|
|
||||||
|
renderWithProviders(
|
||||||
|
<SlideOverExtrasTab
|
||||||
|
uploads={[sitePhoto, walkthrough, avetaDoc]}
|
||||||
|
isReadOnly
|
||||||
|
onUpload={vi.fn()}
|
||||||
|
onRemove={vi.fn()}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByRole("group", { name: "Photo, Extra: site.jpg" })).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.getByRole("group", { name: "Video, Extra: walkthrough.mp4" }),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.getByRole("group", { name: "PDF, Aveta: aveta-clearance.pdf" }),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { fireEvent, render, screen } from "@testing-library/react";
|
import { fireEvent, render, screen } from "@testing-library/react";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
import { StatusCell } from "@/app/(protected)/workorders/_components/list/table/cells/status-cell";
|
import { StatusCell } from "@/app/(protected)/workorders/_components/list/table/cells/status-cell";
|
||||||
|
import type { WizardWOStatus } from "@/domain/work-orders/types/work-order-wizard";
|
||||||
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
||||||
|
|
||||||
const incompleteRow = {
|
const incompleteRow = {
|
||||||
|
|
@ -43,21 +44,62 @@ describe("StatusCell closability gate", () => {
|
||||||
expect(screen.queryByRole("button", { name: /^canceled$/i })).toBeNull();
|
expect(screen.queryByRole("button", { name: /^canceled$/i })).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("disables Scheduled when the row has no concrete date", () => {
|
it.each<WizardWOStatus>([
|
||||||
|
"Pending",
|
||||||
|
"En Route",
|
||||||
|
"On Site",
|
||||||
|
"In Progress",
|
||||||
|
"Rescheduled",
|
||||||
|
"Pending Quote",
|
||||||
|
])("offers only manual transitions away from %s (SH-357, SH-358)", (current) => {
|
||||||
const onChangeStatus = vi.fn();
|
const onChangeStatus = vi.fn();
|
||||||
render(
|
render(
|
||||||
<StatusCell
|
<StatusCell
|
||||||
wo={{ ...incompleteRow, status: "Pending", scheduledOn: "" }}
|
wo={{ ...incompleteRow, status: current, scheduledOn: "2026-06-01" }}
|
||||||
onChangeStatus={onChangeStatus}
|
onChangeStatus={onChangeStatus}
|
||||||
onOpenSlideOver={vi.fn()}
|
onOpenSlideOver={vi.fn()}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
|
||||||
fireEvent.click(screen.getByRole("button", { name: /pending/i }));
|
fireEvent.click(screen.getByRole("button", { name: new RegExp(current, "i") }));
|
||||||
const scheduled = screen.getByRole("button", { name: /^scheduled$/i });
|
const offered = Array.from(document.querySelectorAll(".MuiPopover-paper button")).map(
|
||||||
expect(scheduled).toBeDisabled();
|
(button) => button.textContent?.trim(),
|
||||||
fireEvent.click(scheduled);
|
);
|
||||||
expect(onChangeStatus).not.toHaveBeenCalled();
|
|
||||||
|
expect(offered).not.toContain("Incomplete");
|
||||||
|
expect(offered).not.toContain("Scheduled");
|
||||||
|
expect(offered).not.toContain("Past Due");
|
||||||
|
expect(offered).not.toContain("Canceled");
|
||||||
|
expect(offered).not.toContain(current);
|
||||||
|
expect(offered).toEqual(
|
||||||
|
[
|
||||||
|
"Pending",
|
||||||
|
"En Route",
|
||||||
|
"On Site",
|
||||||
|
"In Progress",
|
||||||
|
"Completed",
|
||||||
|
"Rescheduled",
|
||||||
|
"Pending Quote",
|
||||||
|
].filter((status) => status !== current),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("offers every manual status, and no automatic one, from Incomplete or Scheduled", () => {
|
||||||
|
for (const current of ["Incomplete", "Scheduled"] as const) {
|
||||||
|
const { unmount } = render(
|
||||||
|
<StatusCell
|
||||||
|
wo={{ ...incompleteRow, status: current }}
|
||||||
|
onChangeStatus={vi.fn()}
|
||||||
|
onOpenSlideOver={vi.fn()}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: new RegExp(current, "i") }));
|
||||||
|
expect(screen.getByRole("button", { name: /^pending$/i })).toBeTruthy();
|
||||||
|
expect(screen.queryByRole("button", { name: /^incomplete$/i })).toBeNull();
|
||||||
|
expect(screen.queryByRole("button", { name: /^scheduled$/i })).toBeNull();
|
||||||
|
unmount();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it("limits creation options to Incomplete, Pending, and Scheduled", () => {
|
it("limits creation options to Incomplete, Pending, and Scheduled", () => {
|
||||||
|
|
|
||||||
|
|
@ -278,4 +278,53 @@ describe("useSlideOverMediaState completion filter", () => {
|
||||||
expect(remounted.result.current.completionMedia).toHaveLength(0);
|
expect(remounted.result.current.completionMedia).toHaveLength(0);
|
||||||
expect(remounted.result.current.extrasUploads.map((item) => item.id)).toEqual(["10"]);
|
expect(remounted.result.current.extrasUploads.map((item) => item.id)).toEqual(["10"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("shows Extra photos and videos in Extra Docs on PM work orders", () => {
|
||||||
|
const detail = detailWithMedia(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
id: "10",
|
||||||
|
category: "Extra",
|
||||||
|
url: "https://cdn.example.com/site.jpg",
|
||||||
|
fileName: "site.jpg",
|
||||||
|
uploadedAt: "2026-07-15T18:00:00.0000000Z",
|
||||||
|
isLegacy: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "11",
|
||||||
|
category: "Extra",
|
||||||
|
url: "https://cdn.example.com/walkthrough.mp4",
|
||||||
|
fileName: "walkthrough.mp4",
|
||||||
|
uploadedAt: "2026-07-15T18:00:00.0000000Z",
|
||||||
|
isLegacy: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "4",
|
||||||
|
category: "Extra",
|
||||||
|
url: "https://cdn.example.com/extra.pdf",
|
||||||
|
fileName: "extra.pdf",
|
||||||
|
uploadedAt: "2026-07-15T18:00:00.0000000Z",
|
||||||
|
isLegacy: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{ id: 200, type: "PM" },
|
||||||
|
);
|
||||||
|
|
||||||
|
const { result } = renderHook(() =>
|
||||||
|
useSlideOverMediaState({
|
||||||
|
detailForRow: detail,
|
||||||
|
uploadMediaMutation: idleMutation(),
|
||||||
|
deleteMediaMutation: idleMutation(),
|
||||||
|
categorizeMediaMutation: idleMutation(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.current.completionMedia).toHaveLength(0);
|
||||||
|
expect(result.current.extrasUploads.map((item) => item.id)).toEqual(["10", "11", "4"]);
|
||||||
|
expect(result.current.extrasUploads.map((item) => item.fileType)).toEqual([
|
||||||
|
"image",
|
||||||
|
"video",
|
||||||
|
"pdf",
|
||||||
|
]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,162 @@
|
||||||
|
import { renderHook } from "@testing-library/react";
|
||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { EMPTY_ADVANCED_FILTERS } from "@/domain/work-orders/types/work-order-advanced-filters";
|
||||||
|
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
||||||
|
|
||||||
|
const patchField = vi.hoisted(() => vi.fn());
|
||||||
|
const patchFieldAsync = vi.hoisted(() => vi.fn());
|
||||||
|
|
||||||
|
vi.mock("react-toastify", () => ({
|
||||||
|
toast: {
|
||||||
|
warning: vi.fn(),
|
||||||
|
success: vi.fn(),
|
||||||
|
error: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/app/(protected)/workorders/_hooks/use-work-orders-list-filters", () => ({
|
||||||
|
useWorkOrdersListFilters: () => ({
|
||||||
|
search: "",
|
||||||
|
handleSearchChange: vi.fn(),
|
||||||
|
advOpen: false,
|
||||||
|
setAdvOpen: vi.fn(),
|
||||||
|
advApplied: null,
|
||||||
|
advInitial: EMPTY_ADVANCED_FILTERS,
|
||||||
|
applyAdvancedFilters: vi.fn(),
|
||||||
|
clearAdvancedFilters: vi.fn(),
|
||||||
|
clearAdvancedFilterChip: vi.fn(),
|
||||||
|
activeFilterCount: 0,
|
||||||
|
weekMonday: "2026-07-20",
|
||||||
|
selectedDayIso: "2026-07-20",
|
||||||
|
setWeekMonday: vi.fn(),
|
||||||
|
setSelectedDayIso: vi.fn(),
|
||||||
|
navigateToDay: vi.fn(),
|
||||||
|
dispatcherIds: new Set<string>(),
|
||||||
|
setDispatcherIds: vi.fn(),
|
||||||
|
types: new Set(),
|
||||||
|
setTypes: vi.fn(),
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/app/(protected)/workorders/_hooks/use-work-orders-table-data", () => ({
|
||||||
|
useWorkOrdersTableData: () => ({
|
||||||
|
rows: [],
|
||||||
|
totalCount: 0,
|
||||||
|
scopeTotalCount: 0,
|
||||||
|
isFetching: false,
|
||||||
|
isLoading: false,
|
||||||
|
setSelectedId: vi.fn(),
|
||||||
|
patchRow: vi.fn(),
|
||||||
|
clearRowPatch: vi.fn(),
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/domain/work-orders/use-cases/use-work-order-table-mutations", () => ({
|
||||||
|
useWorkOrderTableMutations: () => ({
|
||||||
|
patchField,
|
||||||
|
patchFieldAsync,
|
||||||
|
isPending: false,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/domain/work-orders/use-cases/use-work-orders-list", () => ({
|
||||||
|
useWorkOrderUsers: () => ({ data: [], isLoading: false }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/domain/work-orders/use-cases/use-work-order-detail", () => ({
|
||||||
|
useWorkOrderLocations: () => ({ data: [] }),
|
||||||
|
useWorkOrderVendors: () => ({ data: [] }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/domain/settings/dropdown-options/use-cases/use-dropdown-options-by-category", () => ({
|
||||||
|
useDropdownOptionsByCategory: () => ({ data: [] }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { useWorkOrdersListPage } from "@/app/(protected)/workorders/_hooks/use-work-orders-list-page";
|
||||||
|
|
||||||
|
function closableRow(overrides: Partial<WorkOrderTableRow> = {}): WorkOrderTableRow {
|
||||||
|
return {
|
||||||
|
id: 77,
|
||||||
|
woNumber: "24866",
|
||||||
|
type: "PM",
|
||||||
|
dispatcherId: "u1",
|
||||||
|
dispatcherName: "Dispatcher",
|
||||||
|
company: "Vendor Co",
|
||||||
|
vendorId: "7",
|
||||||
|
tech: "Tech One",
|
||||||
|
completedDate: "2026-09-15",
|
||||||
|
pm: "HVAC",
|
||||||
|
status: "In Progress",
|
||||||
|
docStatus: "No",
|
||||||
|
mediaCount: 0,
|
||||||
|
isPastDue: false,
|
||||||
|
rowVersion: "v1",
|
||||||
|
upliftSummary: { hasUplift: false, pendingCount: 0 },
|
||||||
|
...overrides,
|
||||||
|
} as WorkOrderTableRow;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("useWorkOrdersListPage completion document (SH-341)", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("completes the WO without confirmation once Generate persists the document", async () => {
|
||||||
|
const saved = closableRow({ docStatus: "Yes", rowVersion: "v2" });
|
||||||
|
patchFieldAsync.mockResolvedValueOnce({ kind: "board", row: saved });
|
||||||
|
patchFieldAsync.mockResolvedValueOnce({
|
||||||
|
kind: "board",
|
||||||
|
row: { ...saved, status: "Completed" },
|
||||||
|
});
|
||||||
|
const { result } = renderHook(() => useWorkOrdersListPage());
|
||||||
|
|
||||||
|
await result.current.saveCompletionDoc(closableRow(), { notes: "", generatedAt: "now" }, "Yes");
|
||||||
|
|
||||||
|
expect(patchFieldAsync).toHaveBeenNthCalledWith(1, 77, { docStatus: "Yes" });
|
||||||
|
expect(patchFieldAsync).toHaveBeenNthCalledWith(2, 77, { status: "Completed" }, saved);
|
||||||
|
expect(patchField).not.toHaveBeenCalled();
|
||||||
|
expect(result.current.confirmComplete).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not complete on Save draft or Not required", async () => {
|
||||||
|
const { result } = renderHook(() => useWorkOrdersListPage());
|
||||||
|
|
||||||
|
patchFieldAsync.mockResolvedValueOnce({ kind: "board", row: closableRow({ docStatus: "No" }) });
|
||||||
|
await result.current.saveCompletionDoc(closableRow(), { notes: "", generatedAt: "" }, "No");
|
||||||
|
patchFieldAsync.mockResolvedValueOnce({ kind: "board", row: closableRow({ docStatus: "NN" }) });
|
||||||
|
await result.current.saveCompletionDoc(closableRow(), { notes: "", generatedAt: "" }, "NN");
|
||||||
|
|
||||||
|
expect(patchFieldAsync).toHaveBeenCalledTimes(2);
|
||||||
|
expect(patchFieldAsync).not.toHaveBeenCalledWith(
|
||||||
|
77,
|
||||||
|
{ status: "Completed" },
|
||||||
|
expect.anything(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the closability gate: a missing service leaves the status unchanged", async () => {
|
||||||
|
patchFieldAsync.mockResolvedValueOnce({
|
||||||
|
kind: "board",
|
||||||
|
row: closableRow({ docStatus: "Yes", pm: "" }),
|
||||||
|
});
|
||||||
|
const { result } = renderHook(() => useWorkOrdersListPage());
|
||||||
|
|
||||||
|
await result.current.saveCompletionDoc(closableRow(), { notes: "", generatedAt: "now" }, "Yes");
|
||||||
|
|
||||||
|
expect(patchFieldAsync).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the generated document when the automatic completion is rejected", async () => {
|
||||||
|
patchFieldAsync.mockResolvedValueOnce({
|
||||||
|
kind: "board",
|
||||||
|
row: closableRow({ docStatus: "Yes" }),
|
||||||
|
});
|
||||||
|
patchFieldAsync.mockRejectedValueOnce(new Error("Work order was modified."));
|
||||||
|
const { result } = renderHook(() => useWorkOrdersListPage());
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
result.current.saveCompletionDoc(closableRow(), { notes: "", generatedAt: "now" }, "Yes"),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
expect(patchFieldAsync).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||