Compare commits
16 commits
6e7363472b
...
24cf73e217
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
24cf73e217 | ||
|
|
ced5405746 | ||
|
|
47272a0afc | ||
|
|
bd12351c87 | ||
|
|
1cba10b9a8 | ||
|
|
bc5659eb2a | ||
|
|
3f4d64d7b6 | ||
|
|
4d2ee40d60 | ||
|
|
cc0df8f569 | ||
|
|
78ed8571a0 | ||
|
|
e9d556cf9a | ||
|
|
88216520d8 | ||
|
|
fca5487f6d | ||
|
|
ec203e1f5b | ||
|
|
ff2e04b30e | ||
|
|
b61d46ce4b |
22
.github/workflows/ci.yaml
vendored
|
|
@ -41,3 +41,25 @@ jobs:
|
|||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run verify
|
||||
|
||||
vendor-visual-regression:
|
||||
runs-on: ubuntu-latest
|
||||
container: mcr.microsoft.com/playwright:v1.61.1-noble
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24"
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run test:e2e:visual
|
||||
- name: Upload visual diff artifacts
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: vendor-visual-regression-diffs
|
||||
path: |
|
||||
test-results/visual
|
||||
playwright-report-visual
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
|
|
|||
1
.gitignore
vendored
|
|
@ -10,6 +10,7 @@
|
|||
/coverage
|
||||
/test-results
|
||||
/playwright-report
|
||||
/playwright-report-visual
|
||||
/blob-report
|
||||
/playwright/.cache
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ dist
|
|||
build
|
||||
node_modules
|
||||
coverage
|
||||
playwright-report-visual
|
||||
package-lock.json
|
||||
*.tsbuildinfo
|
||||
|
||||
|
|
@ -10,4 +11,4 @@ src/pages/**
|
|||
src/**/*.js
|
||||
src/**/*.jsx
|
||||
src/**/*.css
|
||||
!src/styles/globals.css
|
||||
!src/styles/globals.css
|
||||
|
|
|
|||
58
docs/work-orders/pending-be-contract.md
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
# Pending BE contract (WO design parity gaps)
|
||||
|
||||
Local checklist for FE branches off `dev`. Confirm with backend before shipping PR3/PR5 to production. Until confirmed, FE may use typed clients + mocks.
|
||||
|
||||
## Board row / PATCH
|
||||
|
||||
| Field | Needed by | Notes |
|
||||
| -------------------------------------------------------- | ------------- | ---------------------------------------------------------------------- |
|
||||
| `completedDate` on GET `/board` and `/board/search` rows | PR1, PR4 | PATCH `field: "completedDate"` expected; confirm GET includes ISO date |
|
||||
| `severity` (`1`–`5` \| `null`) on row, create, PATCH | PR2, PR5 | Required for Emergency/Reactive; PATCH `field: "severity"` |
|
||||
| `upliftSummary` on row | PR3, PR4, PR5 | `{ hasUplift, pendingCount, primaryStatus? }` |
|
||||
| `hasPendingUplift` on row/detail | PR4 | Prefer server 422 on Completed / completion-doc when pending |
|
||||
| `additionalContacts[]` | PR6 | `{ name, phone, notes? }[]` on create/detail/PATCH |
|
||||
| `isAddOn` | PR5 (filter) | Indicator, not a WO type (SH-126) |
|
||||
|
||||
## Proposed WO-scoped uplift endpoints (confirm vs NTE `uplifts` queue)
|
||||
|
||||
| Method | Path | Body |
|
||||
| ------ | ------------------------------------------- | --------------------------------- |
|
||||
| GET | `workorders/{id}/uplifts` | — |
|
||||
| POST | `workorders/{id}/uplifts` | `{ amount, notes, attachments? }` |
|
||||
| POST | `workorders/{id}/uplifts/{upliftId}/cancel` | — |
|
||||
| POST | `workorders/{id}/uplifts/{upliftId}/revoke` | `{ reason? }` |
|
||||
|
||||
Statuses (design): `pending` \| `approved` \| `auto_approved` \| `rejected` \| `cancelled` \| `revoked`.
|
||||
|
||||
## Search query params (`GET workorders/board/search`)
|
||||
|
||||
| Param | Meaning |
|
||||
| ------------------------------ | ------------------------- |
|
||||
| `severities` | multi `1`–`5` |
|
||||
| `rescheduled` / `carriedOver` | boolean (≥2 counters) |
|
||||
| `addOn` | boolean (`isAddOn`) |
|
||||
| `flagColors` | multi `#RRGGBB` |
|
||||
| `internalOnly` | WO# starts with `SH` |
|
||||
| `avetaOnly` | if `avetaRequired` exists |
|
||||
| `hasUplift` + `upliftStatuses` | uplift filters |
|
||||
|
||||
Already documented in `board-search-api.md`: datePreset, sites, types, overdue, dispatchers, statuses, pmTypes, vendorIds, docStatuses.
|
||||
|
||||
## Comments
|
||||
|
||||
| Field | Needed by |
|
||||
| ---------------------------------------- | --------- |
|
||||
| POST `{ text, mentions?: string[] }` | PR9 |
|
||||
| Response includes mentions for highlight | PR9 |
|
||||
|
||||
## Vendor
|
||||
|
||||
| Item | Needed by |
|
||||
| -------------------------------------------------------------- | --------- |
|
||||
| Create technician under company (confirm existing vendors API) | PR7 |
|
||||
|
||||
## Optional
|
||||
|
||||
| Item | Needed by |
|
||||
| ----------------------------------- | -------------------------------- |
|
||||
| 422 on duplicate WO number (global) | PR8 (FE dialog works without it) |
|
||||
BIN
e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-add.png
vendored
Normal file
|
After Width: | Height: | Size: 130 KiB |
BIN
e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-detail.png
vendored
Normal file
|
After Width: | Height: | Size: 116 KiB |
BIN
e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-edit.png
vendored
Normal file
|
After Width: | Height: | Size: 142 KiB |
BIN
e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-empty.png
vendored
Normal file
|
After Width: | Height: | Size: 98 KiB |
BIN
e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-error.png
vendored
Normal file
|
After Width: | Height: | Size: 96 KiB |
BIN
e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-filter.png
vendored
Normal file
|
After Width: | Height: | Size: 97 KiB |
BIN
e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-inactive.png
vendored
Normal file
|
After Width: | Height: | Size: 102 KiB |
BIN
e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-list.png
vendored
Normal file
|
After Width: | Height: | Size: 111 KiB |
BIN
e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-mobile-navigation.png
vendored
Normal file
|
After Width: | Height: | Size: 40 KiB |
BIN
e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-mobile.png
vendored
Normal file
|
After Width: | Height: | Size: 46 KiB |
221
e2e/vendor-portal/portal-lifecycle.spec.ts
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
import { expect, test, type Page, type Route } from "@playwright/test";
|
||||
|
||||
const PORTAL_TOKEN = "portal-e2e-token";
|
||||
|
||||
const futureDate = new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString();
|
||||
const pastDate = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString();
|
||||
|
||||
interface DispatchDetail {
|
||||
id: number;
|
||||
dispatchNumber: string;
|
||||
workOrderTitle?: string;
|
||||
internalWONumber?: string;
|
||||
status: string;
|
||||
nteAmount?: number;
|
||||
scheduledDate?: string;
|
||||
poNumber?: string;
|
||||
dispatchedAt?: string;
|
||||
completedDate?: string;
|
||||
refusedAt?: string;
|
||||
statusUpdatedAt?: string;
|
||||
description?: string;
|
||||
workOrder?: Record<string, unknown>;
|
||||
location?: Record<string, unknown>;
|
||||
dispatcherContact?: { name?: string; email?: string; phone?: string };
|
||||
checklist: never[];
|
||||
comments: never[];
|
||||
upliftRequests: never[];
|
||||
signoffs: never[];
|
||||
documents: never[];
|
||||
}
|
||||
|
||||
const sentDetail: DispatchDetail = {
|
||||
id: 101,
|
||||
dispatchNumber: "DSP-101",
|
||||
workOrderTitle: "Emergency boiler repair",
|
||||
internalWONumber: "WO-8842",
|
||||
status: "Sent",
|
||||
nteAmount: 1250,
|
||||
scheduledDate: futureDate,
|
||||
poNumber: "PO-555",
|
||||
statusUpdatedAt: "2026-08-09T16:30:00Z",
|
||||
description: "Boiler is leaking; vendor visit required.",
|
||||
workOrder: {
|
||||
workerOrderTitle: "Emergency boiler repair",
|
||||
internalWONumber: "WO-8842",
|
||||
trade: "Plumbing",
|
||||
subTrade: "Backflow Preventers",
|
||||
siteCode: "STL-01",
|
||||
service: "Boiler Repair",
|
||||
},
|
||||
location: {
|
||||
name: "Central Distribution Center",
|
||||
address: "100 Industrial Pkwy",
|
||||
city: "St. Louis",
|
||||
state: "MO",
|
||||
zipCode: "63101",
|
||||
},
|
||||
dispatcherContact: {
|
||||
name: "Dana Field",
|
||||
email: "dana@seahavenind.com",
|
||||
phone: "314-555-0142",
|
||||
},
|
||||
checklist: [],
|
||||
comments: [],
|
||||
upliftRequests: [],
|
||||
signoffs: [],
|
||||
documents: [],
|
||||
};
|
||||
|
||||
const listDispatches = [
|
||||
{
|
||||
id: 101,
|
||||
dispatchNumber: "DSP-101",
|
||||
workOrderTitle: "Emergency boiler repair",
|
||||
internalWONumber: "WO-8842",
|
||||
locationName: "Central Distribution Center",
|
||||
locationCity: "St. Louis",
|
||||
locationState: "MO",
|
||||
status: "Sent",
|
||||
nteAmount: 1250,
|
||||
scheduledDate: futureDate,
|
||||
},
|
||||
{
|
||||
id: 102,
|
||||
dispatchNumber: "DSP-102",
|
||||
workOrderTitle: "HVAC quarterly service",
|
||||
status: "Refused",
|
||||
refusedAt: "2026-08-08T10:00:00Z",
|
||||
},
|
||||
{
|
||||
id: 103,
|
||||
dispatchNumber: "DSP-103",
|
||||
workOrderTitle: "PastAcknowledged job",
|
||||
status: "Acknowledged",
|
||||
scheduledDate: pastDate,
|
||||
},
|
||||
];
|
||||
|
||||
async function fulfill(route: Route, body: unknown, status = 200) {
|
||||
await route.fulfill({
|
||||
status,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
async function mockPortalApi(page: Page, options: { sessionError?: boolean } = {}) {
|
||||
const detailState: { current: DispatchDetail } = { current: { ...sentDetail } };
|
||||
|
||||
await page.route("**/api/vendor-portal/session", (route) => {
|
||||
if (options.sessionError) {
|
||||
fulfill(route, { message: "Invalid or expired token" }, 401);
|
||||
return;
|
||||
}
|
||||
fulfill(route, { data: { companyName: "Gateway Plumbing", vendorId: 101 } });
|
||||
});
|
||||
|
||||
await page.route(/\/api\/vendor-portal\/dispatches\/\d+\/refuse$/, async (route) => {
|
||||
const body = route.request().postDataJSON() as { reason?: string };
|
||||
detailState.current = {
|
||||
...detailState.current,
|
||||
status: "Refused",
|
||||
refusedAt: new Date().toISOString(),
|
||||
};
|
||||
fulfill(route, {
|
||||
data: {
|
||||
id: detailState.current.id,
|
||||
status: "Refused",
|
||||
refusedAt: detailState.current.refusedAt,
|
||||
reason: body?.reason,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await page.route(/\/api\/vendor-portal\/dispatches\/\d+$/, (route) =>
|
||||
fulfill(route, { data: detailState.current }),
|
||||
);
|
||||
|
||||
await page.route(/\/api\/vendor-portal\/dispatches(?:\?.*)?$/, (route) =>
|
||||
fulfill(route, { data: listDispatches }),
|
||||
);
|
||||
|
||||
return detailState;
|
||||
}
|
||||
|
||||
test.describe("Vendor portal lifecycle", () => {
|
||||
test("upcoming filter, detail snapshot, refuse dialog, and locked Refused state", async ({
|
||||
page,
|
||||
}) => {
|
||||
await mockPortalApi(page);
|
||||
await page.goto(`/v/${PORTAL_TOKEN}/dashboard`);
|
||||
|
||||
await expect(page.getByRole("heading", { name: "Your Work" })).toBeVisible();
|
||||
|
||||
await expect(page.getByRole("button", { name: /^Upcoming/ })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: /^Refused/ })).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: /^Upcoming/ }).click();
|
||||
await expect(page.getByText("DSP-101 — Emergency boiler repair")).toBeVisible();
|
||||
await expect(page.getByText("DSP-103")).toHaveCount(0);
|
||||
|
||||
await page.getByText("DSP-101 — Emergency boiler repair").click();
|
||||
await expect(page).toHaveURL(/\/dispatch\/101$/);
|
||||
|
||||
await expect(page.getByRole("heading", { name: "DSP-101" })).toBeVisible();
|
||||
await expect(page.getByText("Boiler Repair", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("STL-01")).toBeVisible();
|
||||
await expect(page.getByText("$1250.00").first()).toBeVisible();
|
||||
await expect(page.getByRole("link", { name: "dana@seahavenind.com" })).toBeVisible();
|
||||
await expect(page.getByText("Dana Field")).toBeVisible();
|
||||
await expect(page.getByText("314-555-0142")).toBeVisible();
|
||||
await expect(page.getByText(/Status updated/i)).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Refuse Dispatch" }).click();
|
||||
const dialog = page.getByRole("dialog", { name: "Refuse dispatch" });
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByLabel(/Reason/i).fill("Equipment unavailable this week.");
|
||||
await expect(dialog.getByText(/\d+\/500/)).toBeVisible();
|
||||
await dialog.getByRole("button", { name: "Refuse dispatch" }).click();
|
||||
|
||||
await expect(dialog).toHaveCount(0);
|
||||
await expect(page.getByText("Refused", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText(/refused and locked/i)).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Accept Dispatch" })).toHaveCount(0);
|
||||
await expect(page.getByRole("button", { name: "Refuse Dispatch" })).toHaveCount(0);
|
||||
await expect(page.getByRole("button", { name: "Submit Signoff" })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("covers the refuse dialog at a mobile viewport", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await mockPortalApi(page);
|
||||
await page.goto(`/v/${PORTAL_TOKEN}/dashboard`);
|
||||
|
||||
await page.getByText("DSP-101 — Emergency boiler repair").click();
|
||||
await expect(page).toHaveURL(/\/dispatch\/101$/);
|
||||
|
||||
await page.getByRole("button", { name: "Refuse Dispatch" }).click();
|
||||
const dialog = page.getByRole("dialog", { name: "Refuse dispatch" });
|
||||
await expect(dialog).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(dialog).toHaveCount(0);
|
||||
|
||||
await page.getByRole("button", { name: "Refuse Dispatch" }).click();
|
||||
await page
|
||||
.getByRole("dialog", { name: "Refuse dispatch" })
|
||||
.getByRole("button", {
|
||||
name: "Refuse dispatch",
|
||||
})
|
||||
.click();
|
||||
await expect(page.getByText("Refused", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText(/refused and locked/i)).toBeVisible();
|
||||
});
|
||||
|
||||
test("shows an expired-token state when the session is rejected", async ({ page }) => {
|
||||
await mockPortalApi(page, { sessionError: true });
|
||||
await page.goto(`/v/${PORTAL_TOKEN}/dashboard`);
|
||||
|
||||
await expect(page.getByRole("heading", { name: "Access Denied" })).toBeVisible();
|
||||
await expect(page.getByRole("alert")).toContainText(/invalid or expired/i);
|
||||
});
|
||||
});
|
||||
147
e2e/vendors/vendors.spec.ts
vendored
|
|
@ -306,11 +306,18 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
test("covers status tabs, global counts, search, facets, table fields, and filtered footer", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
const state = await mockVendorApi(page);
|
||||
await page.goto("/vendors");
|
||||
|
||||
await expect(page.getByRole("heading", { name: "Vendors / Technicians" })).toBeVisible();
|
||||
await expect(page.getByText("3 vendor entries · 2 active")).toBeVisible();
|
||||
const heading = page.getByRole("heading", { name: "Vendors / Technicians" });
|
||||
await expect(heading).toBeVisible();
|
||||
await expect(heading).toHaveCSS("font-family", /Montserrat/);
|
||||
await expect(heading).toHaveCSS("font-size", "30px");
|
||||
await expect(heading).toHaveCSS("font-weight", "800");
|
||||
await expect(heading).toHaveCSS("line-height", "33px");
|
||||
await expect(heading).toHaveCSS("letter-spacing", "-0.6px");
|
||||
await expect(page.getByText("3 technicians · 2 active")).toBeVisible();
|
||||
await expect(page.getByRole("tab", { name: "Active (2)" })).toHaveAttribute(
|
||||
"aria-selected",
|
||||
"true",
|
||||
|
|
@ -323,52 +330,58 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
"Phone",
|
||||
"Email",
|
||||
"Total Jobs",
|
||||
"Status",
|
||||
]) {
|
||||
await expect(page.getByRole("columnheader", { name: heading })).toBeVisible();
|
||||
}
|
||||
await expect(page.getByRole("columnheader", { name: "Status" })).toBeVisible();
|
||||
const activeTabBox = await page.getByRole("tab", { name: "Active (2)" }).boundingBox();
|
||||
expect(activeTabBox).toMatchObject({ x: 256, y: 159.5, height: 36 });
|
||||
const tableContainerBox = await page.locator("table").locator("..").boundingBox();
|
||||
expect(tableContainerBox).toMatchObject({ x: 260, y: 212.5, width: 1164 });
|
||||
expect(tableContainerBox?.height).toBeCloseTo(738, 0);
|
||||
expect((await page.locator("table").boundingBox())?.width).toBe(1550);
|
||||
expect((await page.getByRole("columnheader", { name: "Company" }).boundingBox())?.height).toBe(
|
||||
47,
|
||||
);
|
||||
expect((await page.locator("tbody tr").first().boundingBox())?.height).toBe(52);
|
||||
await expect(page.getByText("Gateway Plumbing")).toBeVisible();
|
||||
await expect(page.getByText("+1")).toBeVisible();
|
||||
await expect(page.getByText("2 active vendor entries · 2 active · 1 inactive")).toBeVisible();
|
||||
await expect(page.getByText("2 active technicians")).toBeVisible();
|
||||
await expect(page.getByText("2 active · 1 inactive")).toBeVisible();
|
||||
await captureVisual(page, "/tmp/seahaven-vendor-implemented-list.png");
|
||||
|
||||
await page.getByPlaceholder("Search name, company, trade...").fill("metro");
|
||||
await page.getByPlaceholder("Search name, company, trade…").fill("metro");
|
||||
await expect(page.getByText("Metro HVAC")).toBeVisible();
|
||||
await expect(page.getByText(/1 active vendor entry · filtered/)).toBeVisible();
|
||||
await expect(page.getByText(/1 active technician · filtered/)).toBeVisible();
|
||||
expect(state.listUrls.some((url) => new URL(url).searchParams.get("search") === "metro")).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
await page.getByPlaceholder("Search name, company, trade...").fill("clayton");
|
||||
await page.getByPlaceholder("Search name, company, trade…").fill("clayton");
|
||||
await expect(page.getByText("Metro HVAC")).toBeVisible();
|
||||
|
||||
await page.getByPlaceholder("Search name, company, trade...").clear();
|
||||
await page.getByPlaceholder("Search name, company, trade…").clear();
|
||||
await page.getByRole("button", { name: "Open vendor filters" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Filters" })).toBeVisible();
|
||||
await captureVisual(page, "/tmp/seahaven-vendor-implemented-filters.png");
|
||||
await page.getByRole("button", { name: /Company/ }).click();
|
||||
await page.getByPlaceholder("All companies").click();
|
||||
await page.getByRole("option", { name: /Gateway Plumbing/ }).click();
|
||||
await page.getByRole("button", { name: "Apply" }).click();
|
||||
await page.getByRole("button", { name: "Apply filters" }).click();
|
||||
await expect(page.getByText("Gateway Plumbing").first()).toBeVisible();
|
||||
await expect(page.getByText(/1 active vendor entry · filtered/)).toBeVisible();
|
||||
await expect(page.getByText("1 technician · filtered by")).toBeVisible();
|
||||
await expect(page.getByText(/1 active technician · filtered/)).toBeVisible();
|
||||
expect(
|
||||
state.listUrls.some(
|
||||
(url) => new URL(url).searchParams.get("companies[0]") === "Gateway Plumbing",
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
await page.getByRole("button", { name: "Deactivate vendor" }).first().click();
|
||||
await expect(page.getByRole("dialog", { name: "Deactivate Vendor" })).toContainText(
|
||||
"history will be preserved",
|
||||
);
|
||||
await page.getByRole("button", { name: "Deactivate", exact: true }).click();
|
||||
await expect.poll(() => state.deletedId).toBe("1");
|
||||
|
||||
await page.getByRole("tab", { name: "Inactive (1)" }).click();
|
||||
await expect(page.getByText("No vendors match the current filters.")).toBeVisible();
|
||||
await expect(page.getByText("No inactive technicians found")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Clear all" }).click();
|
||||
await expect(page.getByText("Drain Cleaning Bros")).toBeVisible();
|
||||
await expect(page.getByRole("columnheader", { name: "Status" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Deactivate vendor" })).toHaveCount(0);
|
||||
});
|
||||
|
||||
|
|
@ -378,33 +391,35 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
const state = await mockVendorApi(page);
|
||||
await page.goto("/vendors");
|
||||
|
||||
await page.getByRole("button", { name: "+ Add Vendor" }).click();
|
||||
await expect(
|
||||
page.getByText("Register a company and add zero, one, or multiple technicians."),
|
||||
).toBeVisible();
|
||||
await page.getByRole("button", { name: "Add Vendor", exact: true }).click();
|
||||
await expect(page.getByText("Register a vendor company and its technicians.")).toBeVisible();
|
||||
await captureVisual(page, "/tmp/seahaven-vendor-implemented-add.png");
|
||||
await expect(page.getByRole("button", { name: "Add Vendor Company" }).last()).toBeDisabled();
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Add Vendor", exact: true }).last(),
|
||||
).toBeEnabled();
|
||||
|
||||
await page.getByRole("combobox", { name: "Company" }).click();
|
||||
await page.getByRole("option", { name: "Gateway Plumbing" }).click();
|
||||
await expect(page.getByLabel("Company Phone")).toHaveValue("314-555-0100");
|
||||
await expect(page.getByRole("textbox", { name: "Email", exact: true })).toHaveValue(
|
||||
await expect(page.getByLabel("Company Phone (optional)")).toHaveValue("314-555-0100");
|
||||
await expect(page.getByRole("textbox", { name: "Email (optional)", exact: true })).toHaveValue(
|
||||
"dispatch@gateway.test",
|
||||
);
|
||||
await expect(page.getByLabel("Address")).toHaveValue("1 Market St");
|
||||
await expect(page.getByLabel("Google Maps URL")).toHaveValue("https://maps.google.com/gateway");
|
||||
await expect(page.getByLabel("Address (optional)")).toHaveValue("1 Market St");
|
||||
await expect(page.getByLabel("Google Maps URL (optional)")).toHaveValue(
|
||||
"https://maps.google.com/gateway",
|
||||
);
|
||||
await expect(page.getByLabel("Preferred Contact")).toHaveCount(0);
|
||||
await page.getByRole("button", { name: "Add technician" }).click();
|
||||
await page.getByLabel("Technician Name").last().fill("New Technician");
|
||||
await page.getByLabel("Technician name (optional)").last().fill("New Technician");
|
||||
const tradeInput = page.getByRole("combobox", { name: "Add Trade" }).last();
|
||||
await tradeInput.fill("HVAC");
|
||||
await tradeInput.press("Enter");
|
||||
await tradeInput.fill("Plumbing");
|
||||
await tradeInput.press("Enter");
|
||||
await page.getByRole("button", { name: "Move Plumbing up" }).click();
|
||||
await page.getByLabel("Notes").fill("Created in browser E2E");
|
||||
await page.getByRole("button", { name: "Add Vendor Company" }).last().click();
|
||||
await expect(page.getByRole("dialog", { name: "Add Vendor Company" })).toHaveCount(0);
|
||||
await page.getByLabel("Notes (optional)").fill("Created in browser E2E");
|
||||
await page.getByRole("button", { name: "Add Vendor", exact: true }).last().click();
|
||||
await expect(page.getByRole("dialog", { name: /Add Vendor/ })).toHaveCount(0);
|
||||
expect(state.updatedBody).toMatchObject({
|
||||
name: "Gateway Plumbing",
|
||||
companyPhone: "(314) 555-0100",
|
||||
|
|
@ -429,7 +444,7 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
|
||||
await page.getByRole("button", { name: "View vendor Gateway Plumbing" }).click();
|
||||
const detailDrawer = page.locator(".MuiDrawer-paper").last();
|
||||
await expect(detailDrawer.getByRole("heading", { name: "Gateway Plumbing" })).toBeVisible();
|
||||
await expect(detailDrawer.getByRole("heading", { name: "Adam Whyte" })).toBeVisible();
|
||||
await expect(detailDrawer.getByText("Adam Whyte")).toBeVisible();
|
||||
await expect(detailDrawer.getByText("72")).toBeVisible();
|
||||
await expect(
|
||||
|
|
@ -438,9 +453,9 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
await captureVisual(page, "/tmp/seahaven-vendor-implemented-detail.png");
|
||||
|
||||
await detailDrawer.getByRole("button", { name: "Edit" }).click();
|
||||
await expect(page).toHaveURL(/\/vendors\/edit\/1$/);
|
||||
await page.getByLabel("Notes").fill("Updated in browser E2E");
|
||||
await page.getByRole("button", { name: "Save" }).click();
|
||||
await expect(page).toHaveURL(/\/vendors$/);
|
||||
await detailDrawer.getByLabel("Notes (optional)").fill("Updated in browser E2E");
|
||||
await detailDrawer.getByRole("button", { name: "Save changes" }).click();
|
||||
await expect.poll(() => state.updatedBody?.notes).toBe("Updated in browser E2E");
|
||||
});
|
||||
|
||||
|
|
@ -448,18 +463,18 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
const state = await mockVendorApi(page, { legacyGateway: true });
|
||||
await page.goto("/vendors");
|
||||
|
||||
await page.getByRole("button", { name: "Deactivate vendor" }).first().click();
|
||||
await page.getByRole("button", { name: "Edit vendor Gateway Plumbing" }).click();
|
||||
await page.getByRole("switch", { name: "Active status" }).click();
|
||||
await page.getByRole("button", { name: "Deactivate", exact: true }).click();
|
||||
await expect.poll(() => state.deletedId).toBe("1");
|
||||
|
||||
await page.getByRole("tab", { name: "Inactive (2)" }).click();
|
||||
await page.getByRole("button", { name: "View vendor Gateway Plumbing" }).click();
|
||||
await page.getByRole("button", { name: "Edit vendor Gateway Plumbing" }).click();
|
||||
const detailDrawer = page.locator(".MuiDrawer-paper").last();
|
||||
await detailDrawer.getByRole("button", { name: "Edit" }).click();
|
||||
await expect(page).toHaveURL(/\/vendors\/edit\/1$/);
|
||||
await page.getByRole("switch", { name: "Inactive" }).first().click();
|
||||
await page.getByRole("button", { name: "Save" }).click();
|
||||
await detailDrawer.getByRole("switch", { name: "Active status" }).click();
|
||||
await detailDrawer.getByRole("button", { name: "Save changes" }).click();
|
||||
await expect.poll(() => state.updatedBody).toEqual({ isActive: true });
|
||||
await detailDrawer.getByRole("button", { name: "Close drawer" }).click();
|
||||
await page.getByRole("tab", { name: "Active (2)", exact: true }).click();
|
||||
await expect(page.getByText("Gateway Plumbing").first()).toBeVisible();
|
||||
});
|
||||
|
|
@ -468,7 +483,7 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
const state = await mockVendorApi(page);
|
||||
await page.goto("/vendors");
|
||||
|
||||
const addButton = page.getByRole("button", { name: "+ Add Vendor" });
|
||||
const addButton = page.getByRole("button", { name: "Add Vendor", exact: true });
|
||||
await addButton.focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByRole("dialog", { name: /Add Vendor/ })).toBeVisible();
|
||||
|
|
@ -477,10 +492,12 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
await expect(addButton).toBeFocused();
|
||||
|
||||
await addButton.click();
|
||||
await expect(page.getByRole("button", { name: "Add Vendor Company" }).last()).toBeDisabled();
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Add Vendor", exact: true }).last(),
|
||||
).toBeEnabled();
|
||||
await page.getByRole("combobox", { name: "Company" }).fill("Independent Vendor LLC");
|
||||
await page.getByLabel("Company Phone").fill("3145550199");
|
||||
await page.getByRole("button", { name: "Add Vendor Company" }).last().click();
|
||||
await page.getByLabel("Company Phone (optional)").fill("3145550199");
|
||||
await page.getByRole("button", { name: "Add Vendor", exact: true }).last().click();
|
||||
|
||||
await expect.poll(() => state.createdBody?.name).toBe("Independent Vendor LLC");
|
||||
expect(state.createdBody?.technicians).toEqual([]);
|
||||
|
|
@ -506,7 +523,8 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
const blockedState = await mockVendorApi(page, { deactivationBlocked: true });
|
||||
await page.goto("/vendors");
|
||||
|
||||
await page.getByRole("button", { name: "Deactivate vendor" }).first().click();
|
||||
await page.getByRole("button", { name: "Edit vendor Gateway Plumbing" }).click();
|
||||
await page.getByRole("switch", { name: "Active status" }).click();
|
||||
const blockedDialog = page.getByRole("dialog", { name: "Deactivate Vendor" });
|
||||
await expect(blockedDialog).toContainText("WO-501 — Emergency boiler repair");
|
||||
await expect(blockedDialog.getByRole("button", { name: /^Deactivate$/ })).toBeDisabled();
|
||||
|
|
@ -517,7 +535,8 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
|
||||
const racedState = await mockVendorApi(page, { deleteConflict: true });
|
||||
await page.reload();
|
||||
await page.getByRole("button", { name: "Deactivate vendor" }).first().click();
|
||||
await page.getByRole("button", { name: "Edit vendor Gateway Plumbing" }).click();
|
||||
await page.getByRole("switch", { name: "Active status" }).click();
|
||||
await page
|
||||
.getByRole("dialog", { name: "Deactivate Vendor" })
|
||||
.getByRole("button", {
|
||||
|
|
@ -537,10 +556,25 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
await mockVendorApi(page, { listError: true });
|
||||
await page.goto("/vendors");
|
||||
|
||||
const mainBox = await page.getByRole("main").boundingBox();
|
||||
expect(mainBox).toMatchObject({ x: 0, width: 390 });
|
||||
const navigation = page.getByRole("navigation", { name: "Primary navigation" });
|
||||
await expect(navigation).not.toBeVisible();
|
||||
|
||||
const openNavigation = page.getByRole("button", { name: "Toggle navigation" });
|
||||
await openNavigation.focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(navigation).toBeVisible();
|
||||
await expect(page.getByRole("link", { name: "Sites" })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(navigation).not.toBeVisible();
|
||||
await expect(openNavigation).toBeFocused();
|
||||
|
||||
await expect(page.getByRole("main").getByRole("alert")).toContainText(
|
||||
/Vendor directory unavailable|failed|server error/i,
|
||||
{ timeout: 15_000 },
|
||||
);
|
||||
await captureVisual(page, "/tmp/seahaven-vendor-implemented-mobile-list.png");
|
||||
await page.getByRole("button", { name: "Open vendor filters" }).click();
|
||||
const filterDrawer = page.locator(".MuiDrawer-paper").filter({ hasText: "Total Jobs" });
|
||||
await expect(filterDrawer).toBeVisible();
|
||||
|
|
@ -549,4 +583,23 @@ test.describe("Vendor directory prototype parity", () => {
|
|||
await captureVisual(page, "/tmp/seahaven-vendor-implemented-mobile.png");
|
||||
await page.getByRole("button", { name: "Close filters" }).click();
|
||||
});
|
||||
|
||||
test("keeps protected shell destinations available and marks their selected state", async ({
|
||||
page,
|
||||
}) => {
|
||||
await mockVendorApi(page);
|
||||
|
||||
for (const destination of [
|
||||
{ path: "/workorders", label: "Work Orders" },
|
||||
{ path: "/accounts", label: "Accounts" },
|
||||
{ path: "/locations", label: "Sites" },
|
||||
{ path: "/notifications", label: "Notifications" },
|
||||
]) {
|
||||
await page.goto(destination.path);
|
||||
await expect(page.getByRole("link", { name: destination.label })).toHaveAttribute(
|
||||
"aria-current",
|
||||
"page",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
261
e2e/vendors/vendors.visual.spec.ts
vendored
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
import { expect, test, type Page, type Route } from "@playwright/test";
|
||||
|
||||
const TEST_USER = {
|
||||
token: "vendor-visual-token",
|
||||
expiration: "2030-01-01T00:00:00.000Z",
|
||||
email: "admin@seahavenind.com",
|
||||
userRoles: "Admin",
|
||||
phoneNumber: "5551234567",
|
||||
fullname: "Vendor Visual Admin",
|
||||
id: "1",
|
||||
};
|
||||
|
||||
const activeVendors = [
|
||||
{
|
||||
Id: 1,
|
||||
CompanyId: 101,
|
||||
CompanyName: "Gateway Plumbing",
|
||||
ContactName: "Adam Whyte",
|
||||
Email: "dispatch@gateway.test",
|
||||
Phone: "314-555-0198",
|
||||
CompanyPhone: "314-555-0100",
|
||||
Address: "1 Market St",
|
||||
City: "St. Louis",
|
||||
State: "MO",
|
||||
Zip: "63101",
|
||||
TradeSpecialties: "Plumbing, Backflow Preventers",
|
||||
GoogleMapsUrl: "https://maps.google.com/gateway",
|
||||
Notes: "Preferred after-hours vendor",
|
||||
TotalJobs: 72,
|
||||
IsActive: true,
|
||||
PreferredContact: "Email",
|
||||
},
|
||||
{
|
||||
Id: 2,
|
||||
CompanyId: 102,
|
||||
CompanyName: "Metro HVAC",
|
||||
ContactName: "Maya Chen",
|
||||
Email: "maya@metro.test",
|
||||
Phone: "314-555-0112",
|
||||
CompanyPhone: "314-555-0110",
|
||||
Address: "2 Pine St",
|
||||
City: "Clayton",
|
||||
State: "MO",
|
||||
Zip: "63105",
|
||||
TradeSpecialties: "HVAC",
|
||||
GoogleMapsUrl: "",
|
||||
Notes: "",
|
||||
TotalJobs: 18,
|
||||
IsActive: true,
|
||||
},
|
||||
];
|
||||
|
||||
const inactiveVendors = [
|
||||
{
|
||||
...activeVendors[0],
|
||||
Id: 3,
|
||||
CompanyId: 103,
|
||||
CompanyName: "Drain Cleaning Bros",
|
||||
ContactName: "Drew Banks",
|
||||
TotalJobs: 151,
|
||||
IsActive: false,
|
||||
},
|
||||
];
|
||||
|
||||
async function fulfillJson(route: Route, body: unknown, status = 200) {
|
||||
await route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
|
||||
}
|
||||
|
||||
async function mockVendorApi(page: Page, mode: "default" | "empty" | "error" = "default") {
|
||||
await page.clock.setFixedTime(new Date("2026-08-10T12:00:00.000Z"));
|
||||
await page.addInitScript((user) => localStorage.setItem("auth", JSON.stringify(user)), TEST_USER);
|
||||
|
||||
await page.route("**/api/**", async (route) => {
|
||||
const request = route.request();
|
||||
const url = new URL(request.url());
|
||||
|
||||
if (!url.pathname.startsWith("/api/")) {
|
||||
await route.continue();
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.includes("/DropdownOptions/ByCategory/Trade")) {
|
||||
await fulfillJson(route, {
|
||||
data: [
|
||||
{ id: 1, value: "Plumbing" },
|
||||
{ id: 2, value: "HVAC" },
|
||||
],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.endsWith("/api/Vendor/facets")) {
|
||||
await fulfillJson(route, {
|
||||
data: {
|
||||
companies: activeVendors.map((vendor) => ({
|
||||
companyId: vendor.CompanyId,
|
||||
name: vendor.CompanyName,
|
||||
})),
|
||||
trades: ["Plumbing", "Backflow Preventers", "HVAC"],
|
||||
locations: [
|
||||
{ city: "St. Louis", state: "MO", label: "St. Louis, MO" },
|
||||
{ city: "Clayton", state: "MO", label: "Clayton, MO" },
|
||||
],
|
||||
jobBuckets: [
|
||||
{ id: "under-50", label: "Under 50" },
|
||||
{ id: "50-99", label: "50–99" },
|
||||
{ id: "100-149", label: "100–149" },
|
||||
{ id: "150-plus", label: "150+" },
|
||||
],
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.endsWith("/api/Vendor/GetVendorList")) {
|
||||
const isCount = url.searchParams.get("pageSize") === "1";
|
||||
if (mode === "error" && !isCount) {
|
||||
await fulfillJson(route, { message: "Vendor directory unavailable" }, 500);
|
||||
return;
|
||||
}
|
||||
const source =
|
||||
mode === "empty"
|
||||
? []
|
||||
: url.searchParams.get("isActive") === "false"
|
||||
? inactiveVendors
|
||||
: activeVendors;
|
||||
await fulfillJson(route, {
|
||||
Data: isCount ? source.slice(0, 1) : source,
|
||||
TotalCount: source.length,
|
||||
PageNumber: 1,
|
||||
PageSize: Number(url.searchParams.get("pageSize") ?? 12),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith("/api/vendor-company-roster")) {
|
||||
await fulfillJson(route, {
|
||||
companyId: 101,
|
||||
rowVersion: "rv-visual",
|
||||
name: "Gateway Plumbing",
|
||||
companyPhone: "314-555-0100",
|
||||
email: "dispatch@gateway.test",
|
||||
address: "1 Market St",
|
||||
city: "St. Louis",
|
||||
state: "MO",
|
||||
zip: "63101",
|
||||
googleMapsUrl: "https://maps.google.com/gateway",
|
||||
notes: "Preferred after-hours vendor",
|
||||
technicians: [
|
||||
{
|
||||
id: 1,
|
||||
contactName: "Adam Whyte",
|
||||
phone: "314-555-0198",
|
||||
email: "dispatch@gateway.test",
|
||||
preferredContact: "Email",
|
||||
tradeSpecialties: "Plumbing, Backflow Preventers",
|
||||
isActive: true,
|
||||
totalJobs: 72,
|
||||
},
|
||||
],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await fulfillJson(route, { data: {} });
|
||||
});
|
||||
}
|
||||
|
||||
async function openVendorPage(page: Page, mode: "default" | "empty" | "error" = "default") {
|
||||
await mockVendorApi(page, mode);
|
||||
await page.goto("/vendors");
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
await page.addStyleTag({
|
||||
content: `
|
||||
*, *::before, *::after { transition: none !important; animation: none !important; }
|
||||
.MuiDrawer-paper { transform: none !important; }
|
||||
.Toastify__toast-container { display: none !important; }
|
||||
.tsqd-parent-container { display: none !important; }
|
||||
`,
|
||||
});
|
||||
}
|
||||
|
||||
async function expectStableScreenshot(page: Page, name: string) {
|
||||
await page.waitForTimeout(250);
|
||||
await page.evaluate(
|
||||
() =>
|
||||
new Promise<void>((resolve) =>
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
|
||||
),
|
||||
);
|
||||
await page.screenshot({ animations: "disabled", caret: "hide" });
|
||||
await expect(page).toHaveScreenshot(name);
|
||||
}
|
||||
|
||||
test.describe("Vendor deterministic pixel regression", () => {
|
||||
test("list", async ({ page }) => {
|
||||
await openVendorPage(page);
|
||||
await expect(page.getByText("Gateway Plumbing")).toBeVisible();
|
||||
await expectStableScreenshot(page, "vendor-list.png");
|
||||
});
|
||||
|
||||
test("filter", async ({ page }) => {
|
||||
await openVendorPage(page);
|
||||
await page.getByRole("button", { name: "Open vendor filters" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Filters" })).toBeVisible();
|
||||
await expectStableScreenshot(page, "vendor-filter.png");
|
||||
});
|
||||
|
||||
test("add", async ({ page }) => {
|
||||
await openVendorPage(page);
|
||||
await page.getByRole("button", { name: "Add Vendor", exact: true }).click();
|
||||
await expect(page.getByRole("dialog", { name: /Add Vendor/ })).toBeVisible();
|
||||
await expectStableScreenshot(page, "vendor-add.png");
|
||||
});
|
||||
|
||||
test("detail", async ({ page }) => {
|
||||
await openVendorPage(page);
|
||||
await page.getByRole("button", { name: "View vendor Gateway Plumbing" }).click();
|
||||
await expect(page.getByRole("button", { name: "Close drawer" })).toBeVisible();
|
||||
await expectStableScreenshot(page, "vendor-detail.png");
|
||||
});
|
||||
|
||||
test("edit", async ({ page }) => {
|
||||
await openVendorPage(page);
|
||||
await page.getByRole("button", { name: "Edit vendor Gateway Plumbing" }).click();
|
||||
await expect(page.getByRole("button", { name: "Save changes" })).toBeVisible();
|
||||
await expectStableScreenshot(page, "vendor-edit.png");
|
||||
});
|
||||
|
||||
test("inactive", async ({ page }) => {
|
||||
await openVendorPage(page);
|
||||
await page.getByRole("tab", { name: "Inactive (1)" }).click();
|
||||
await expect(page.getByText("Drain Cleaning Bros")).toBeVisible();
|
||||
await expectStableScreenshot(page, "vendor-inactive.png");
|
||||
});
|
||||
|
||||
test("empty", async ({ page }) => {
|
||||
await openVendorPage(page, "empty");
|
||||
await expect(page.getByText("No active technicians found")).toBeVisible();
|
||||
await expectStableScreenshot(page, "vendor-empty.png");
|
||||
});
|
||||
|
||||
test("error", async ({ page }) => {
|
||||
await openVendorPage(page, "error");
|
||||
await expect(page.getByRole("main").getByRole("alert")).toContainText(
|
||||
/server error|vendor directory unavailable/i,
|
||||
);
|
||||
await expectStableScreenshot(page, "vendor-error.png");
|
||||
});
|
||||
|
||||
test("mobile", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await openVendorPage(page);
|
||||
await expect(page.getByText("Gateway Plumbing")).toBeVisible();
|
||||
await expectStableScreenshot(page, "vendor-mobile.png");
|
||||
|
||||
await page.getByRole("button", { name: "Toggle navigation" }).click();
|
||||
await expect(page.getByRole("navigation", { name: "Primary navigation" })).toBeVisible();
|
||||
await expectStableScreenshot(page, "vendor-mobile-navigation.png");
|
||||
});
|
||||
});
|
||||
26
package-lock.json
generated
|
|
@ -4048,9 +4048,9 @@
|
|||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-uri": {
|
||||
"version": "3.1.4",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.4.tgz",
|
||||
"integrity": "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==",
|
||||
"version": "3.1.5",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",
|
||||
"integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
|
|
@ -4578,9 +4578,9 @@
|
|||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
|
||||
"integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
|
||||
"version": "4.3.1",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",
|
||||
"integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
|
|
@ -5302,9 +5302,9 @@
|
|||
"license": "MIT"
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.16",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
|
||||
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
|
||||
"version": "3.3.18",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
|
||||
"integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
|
|
@ -5561,9 +5561,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.18",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.18.tgz",
|
||||
"integrity": "sha512-xdB1oSLHbz1vRWgCDalrCqEFTWzFlhqFC5tIHLMOSUIjhm3XXQ1qrFy8S/ESr1JYRRXqM3c1QFiMZUJdUTqyMQ==",
|
||||
"version": "8.5.26",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
|
||||
"integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "opencollective",
|
||||
|
|
@ -5580,7 +5580,7 @@
|
|||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.12",
|
||||
"nanoid": "^3.3.17",
|
||||
"picocolors": "^1.1.1",
|
||||
"source-map-js": "^1.2.1"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@
|
|||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:e2e": "playwright test",
|
||||
"test:e2e:visual": "playwright test --config playwright.visual.config.ts",
|
||||
"test:e2e:ui": "playwright test --ui",
|
||||
"lint": "eslint . --max-warnings=0",
|
||||
"lint:fix": "eslint . --fix --max-warnings=0",
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { defineConfig, devices } from "@playwright/test";
|
|||
|
||||
export default defineConfig({
|
||||
testDir: "./e2e",
|
||||
testIgnore: "**/*.visual.spec.ts",
|
||||
fullyParallel: true,
|
||||
forbidOnly: Boolean(process.env.CI),
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
|
|
|
|||
43
playwright.visual.config.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { defineConfig, devices } from "@playwright/test";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "./e2e",
|
||||
testMatch: "**/*.visual.spec.ts",
|
||||
fullyParallel: false,
|
||||
forbidOnly: true,
|
||||
retries: 0,
|
||||
workers: 1,
|
||||
reporter: [["list"], ["html", { outputFolder: "playwright-report-visual", open: "never" }]],
|
||||
outputDir: "test-results/visual",
|
||||
snapshotPathTemplate: "{testDir}/__screenshots__/{testFilePath}/{arg}{ext}",
|
||||
expect: {
|
||||
toHaveScreenshot: {
|
||||
animations: "disabled",
|
||||
caret: "hide",
|
||||
// Keep the changed-pixel budget strict while ignoring sub-perceptual
|
||||
// antialiasing differences between local and hosted container runtimes.
|
||||
maxDiffPixels: 5,
|
||||
threshold: 0.1,
|
||||
},
|
||||
},
|
||||
use: {
|
||||
...devices["Desktop Chrome"],
|
||||
baseURL: "http://localhost:4174",
|
||||
colorScheme: "light",
|
||||
deviceScaleFactor: 1,
|
||||
locale: "en-US",
|
||||
launchOptions: {
|
||||
args: ["--disable-gpu", "--font-render-hinting=none"],
|
||||
},
|
||||
reducedMotion: "reduce",
|
||||
timezoneId: "UTC",
|
||||
trace: "retain-on-failure",
|
||||
viewport: { width: 1440, height: 1000 },
|
||||
},
|
||||
webServer: {
|
||||
command: "npm run dev -- --port 4174 --strictPort",
|
||||
url: "http://localhost:4174",
|
||||
reuseExistingServer: false,
|
||||
timeout: 120_000,
|
||||
},
|
||||
});
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { useState } from "react";
|
||||
import { Outlet } from "react-router";
|
||||
import { Box } from "@mui/material";
|
||||
import { Box, useMediaQuery, useTheme } from "@mui/material";
|
||||
|
||||
import { ProtectedRoute } from "@/components/auth/protected-route";
|
||||
import { AppSidebar } from "@/components/layout/app-sidebar";
|
||||
|
|
@ -8,19 +8,36 @@ import { getSidebarWidth } from "@/config/menu";
|
|||
import { AppTopbar } from "@/components/layout/app-topbar";
|
||||
|
||||
export default function AdminShellLayout() {
|
||||
const theme = useTheme();
|
||||
const isDesktop = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const [navCollapsed, setNavCollapsed] = useState(false);
|
||||
const sidebarWidth = getSidebarWidth(navCollapsed);
|
||||
const [mobileNavOpen, setMobileNavOpen] = useState(false);
|
||||
const sidebarWidth = isDesktop ? getSidebarWidth(navCollapsed) : 0;
|
||||
|
||||
const handleToggleNav = () => {
|
||||
if (isDesktop) {
|
||||
setNavCollapsed((value) => !value);
|
||||
return;
|
||||
}
|
||||
|
||||
setMobileNavOpen((value) => !value);
|
||||
};
|
||||
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<Box className="flex h-screen w-full overflow-hidden bg-background">
|
||||
<AppSidebar collapsed={navCollapsed} />
|
||||
<AppSidebar
|
||||
collapsed={isDesktop ? navCollapsed : false}
|
||||
mobile={!isDesktop}
|
||||
open={isDesktop || mobileNavOpen}
|
||||
onClose={() => setMobileNavOpen(false)}
|
||||
/>
|
||||
|
||||
<Box
|
||||
className="flex h-screen min-w-0 flex-1 flex-col overflow-hidden"
|
||||
sx={{ width: `calc(100% - ${sidebarWidth}px)` }}
|
||||
>
|
||||
<AppTopbar onToggleNav={() => setNavCollapsed((value) => !value)} />
|
||||
<AppTopbar onToggleNav={handleToggleNav} />
|
||||
|
||||
<Box
|
||||
component="main"
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ export interface VendorDeactivationState {
|
|||
confirm: () => void;
|
||||
}
|
||||
|
||||
export function useVendorDeactivation(): VendorDeactivationState {
|
||||
export function useVendorDeactivation(onSuccess?: () => void): VendorDeactivationState {
|
||||
const [target, setTarget] = useState<VendorListItem | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const deleteVendor = useDeleteVendor();
|
||||
|
|
@ -39,7 +39,10 @@ export function useVendorDeactivation(): VendorDeactivationState {
|
|||
if (!target || target.id == null) return;
|
||||
setError(null);
|
||||
deleteVendor.mutate(target.id, {
|
||||
onSuccess: () => setTarget(null),
|
||||
onSuccess: () => {
|
||||
setTarget(null);
|
||||
onSuccess?.();
|
||||
},
|
||||
onError: (err: Error) => setError(err.message || "Failed to deactivate vendor"),
|
||||
});
|
||||
};
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ export interface VendorListState {
|
|||
export function useVendorListState(): VendorListState {
|
||||
const [search, setSearch] = useState("");
|
||||
const [page, setPage] = useState(0);
|
||||
const [pageSize, setPageSize] = useState(12);
|
||||
const [pageSize, setPageSize] = useState(48);
|
||||
const [isActive, setIsActive] = useState(true);
|
||||
const [appliedFilters, setAppliedFilters] = useState<VendorFilters>(emptyVendorFilters);
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { useCallback, useMemo, useState } from "react";
|
|||
import { useForm, useWatch, type FieldErrors } from "react-hook-form";
|
||||
import {
|
||||
emptyVendorCompanyRosterForm,
|
||||
emptyRosterTechnician,
|
||||
vendorCompanyRosterSchema,
|
||||
type VendorCompanyRosterFormValues,
|
||||
} from "@/domain/vendors/schemas/vendor-roster-schema";
|
||||
|
|
@ -20,11 +21,30 @@ import type {
|
|||
VendorRosterConflict,
|
||||
} from "@/domain/vendors/types/vendor";
|
||||
|
||||
function withoutBlankNewTechnicians(
|
||||
values: VendorCompanyRosterFormValues,
|
||||
): VendorCompanyRosterFormValues {
|
||||
return {
|
||||
...values,
|
||||
technicians: values.technicians.filter(
|
||||
(technician) =>
|
||||
technician.id != null ||
|
||||
Boolean(
|
||||
technician.contactName.trim() ||
|
||||
technician.phone.trim() ||
|
||||
technician.email.trim() ||
|
||||
technician.tradeSpecialties.trim(),
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export interface VendorRosterFormProps {
|
||||
mode: "create" | "update";
|
||||
vendorId?: string | number;
|
||||
companyId?: string | number;
|
||||
onSuccess?: (roster: VendorCompanyRoster) => void;
|
||||
startWithTechnician?: boolean;
|
||||
}
|
||||
|
||||
export interface VendorRosterForm {
|
||||
|
|
@ -55,6 +75,7 @@ export function useVendorRosterForm({
|
|||
vendorId,
|
||||
companyId,
|
||||
onSuccess,
|
||||
startWithTechnician = false,
|
||||
}: VendorRosterFormProps): VendorRosterForm {
|
||||
const query = useVendorCompanyRoster(
|
||||
mode === "update" ? vendorId : undefined,
|
||||
|
|
@ -69,9 +90,16 @@ export function useVendorRosterForm({
|
|||
const trades = useMemo(() => facets?.trades ?? [], [facets]);
|
||||
const resolver = useVendorRosterResolver(routeRoster);
|
||||
|
||||
const createDefaults = useMemo(
|
||||
() => ({
|
||||
...emptyVendorCompanyRosterForm,
|
||||
technicians: startWithTechnician ? [{ ...emptyRosterTechnician }] : [],
|
||||
}),
|
||||
[startWithTechnician],
|
||||
);
|
||||
const form = useForm<VendorCompanyRosterFormValues>({
|
||||
resolver,
|
||||
defaultValues: emptyVendorCompanyRosterForm,
|
||||
defaultValues: createDefaults,
|
||||
values: mode === "update" && routeRoster ? toFormValues(routeRoster) : undefined,
|
||||
mode: "onChange",
|
||||
});
|
||||
|
|
@ -96,10 +124,10 @@ export function useVendorRosterForm({
|
|||
}, [routeRoster, watched]);
|
||||
|
||||
const resetForm = useCallback(() => {
|
||||
reset(emptyVendorCompanyRosterForm);
|
||||
reset(createDefaults);
|
||||
resetSelection();
|
||||
clearConflict();
|
||||
}, [clearConflict, reset, resetSelection]);
|
||||
}, [clearConflict, createDefaults, reset, resetSelection]);
|
||||
|
||||
const committedRoster = mode === "update" ? routeRoster : selection.selectedRoster;
|
||||
const isUpdate = mode === "update" || selection.selectedRoster != null;
|
||||
|
|
@ -109,7 +137,7 @@ export function useVendorRosterForm({
|
|||
save.mutate(
|
||||
{
|
||||
mode: isUpdate ? "update" : "create",
|
||||
values: formValues,
|
||||
values: withoutBlankNewTechnicians(formValues),
|
||||
companyId: isUpdate ? (committedRoster?.companyId ?? companyId) : undefined,
|
||||
rowVersion: isUpdate ? committedRoster?.rowVersion : undefined,
|
||||
originalRoster: mode === "update" ? routeRoster : undefined,
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ import {
|
|||
DialogContent,
|
||||
DialogTitle,
|
||||
Stack,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import { VendorRosterConflictAlert } from "./vendor-roster-conflict-alert";
|
||||
import { VendorRosterFormFields } from "./vendor-roster-form-fields";
|
||||
import { VendorRosterLoadErrorAlert } from "./vendor-roster-load-error";
|
||||
|
|
@ -21,7 +21,11 @@ interface VendorCreateModalProps {
|
|||
}
|
||||
|
||||
export function VendorCreateModal({ open, onClose }: VendorCreateModalProps) {
|
||||
const form = useVendorRosterForm({ mode: "create", onSuccess: onClose });
|
||||
const form = useVendorRosterForm({
|
||||
mode: "create",
|
||||
onSuccess: onClose,
|
||||
startWithTechnician: true,
|
||||
});
|
||||
const { resetForm } = form;
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -33,17 +37,24 @@ export function VendorCreateModal({ open, onClose }: VendorCreateModalProps) {
|
|||
open={open}
|
||||
onClose={form.isSaving ? undefined : onClose}
|
||||
fullWidth
|
||||
maxWidth="md"
|
||||
maxWidth="sm"
|
||||
aria-labelledby="vendor-create-dialog-title"
|
||||
slotProps={{ paper: { role: "dialog" } }}
|
||||
slotProps={{
|
||||
paper: {
|
||||
role: "dialog",
|
||||
sx: { maxHeight: "88vh", borderRadius: 2 },
|
||||
},
|
||||
}}
|
||||
>
|
||||
<DialogTitle id="vendor-create-dialog-title">
|
||||
Add Vendor Company
|
||||
<Typography variant="body2" sx={{ color: "text.secondary", mt: 0.5 }}>
|
||||
Register a company and add zero, one, or multiple technicians.
|
||||
</Typography>
|
||||
<Text variant="title" as="span">
|
||||
Add Vendor
|
||||
</Text>
|
||||
<Text variant="description" tone="muted" sx={{ mt: 0.5 }}>
|
||||
Register a vendor company and its technicians.
|
||||
</Text>
|
||||
</DialogTitle>
|
||||
<DialogContent>
|
||||
<DialogContent sx={{ maxHeight: "55vh" }}>
|
||||
<Stack spacing={2} className="mt-1">
|
||||
{form.loadErrorMessage !== null && (
|
||||
<VendorRosterLoadErrorAlert message={form.loadErrorMessage} onRetry={form.retryLoad} />
|
||||
|
|
@ -73,9 +84,9 @@ export function VendorCreateModal({ open, onClose }: VendorCreateModalProps) {
|
|||
variant="contained"
|
||||
type="submit"
|
||||
form="vendor-create-form"
|
||||
disabled={form.isSaving || !form.isValid}
|
||||
disabled={form.isSaving}
|
||||
>
|
||||
{form.isSaving ? <CircularProgress size={20} color="inherit" /> : "Add Vendor Company"}
|
||||
{form.isSaving ? <CircularProgress size={20} color="inherit" /> : "Add Vendor"}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useEffect, type ReactNode } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { Controller, useWatch } from "react-hook-form";
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
|
||||
import LaunchIcon from "@mui/icons-material/Launch";
|
||||
|
|
@ -13,15 +13,22 @@ import {
|
|||
Drawer,
|
||||
IconButton,
|
||||
Link,
|
||||
List,
|
||||
ListItem,
|
||||
Stack,
|
||||
Typography,
|
||||
Switch,
|
||||
} from "@mui/material";
|
||||
import { VendorRosterConflictAlert } from "./vendor-roster-conflict-alert";
|
||||
import { VendorRosterFormFields } from "./vendor-roster-form-fields";
|
||||
import { VendorRosterLoadErrorAlert } from "./vendor-roster-load-error";
|
||||
import { useVendorRosterForm } from "./use-vendor-roster-form";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import type {
|
||||
VendorCompanyRoster,
|
||||
VendorListItem,
|
||||
VendorRosterTechnician,
|
||||
} from "@/domain/vendors/types/vendor";
|
||||
import { useVendorCompanyRoster } from "@/domain/vendors/use-cases/use-vendor-company-roster";
|
||||
import type { VendorCompanyRoster, VendorListItem } from "@/domain/vendors/types/vendor";
|
||||
|
||||
const DRAWER_WIDTH = 440;
|
||||
const DRAWER_WIDTH = 420;
|
||||
|
||||
function splitTrades(value: string | undefined): string[] {
|
||||
return (value ?? "")
|
||||
|
|
@ -33,106 +40,45 @@ function splitTrades(value: string | undefined): string[] {
|
|||
interface VendorDetailDrawerProps {
|
||||
open: boolean;
|
||||
vendor: VendorListItem | null;
|
||||
startInEdit?: boolean;
|
||||
onRequestDeactivation?: (vendor: VendorListItem) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
function SectionTitle({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<Typography
|
||||
variant="subtitle2"
|
||||
className="font-semibold uppercase"
|
||||
sx={{ color: "text.secondary", mb: 1 }}
|
||||
<Text
|
||||
variant="label"
|
||||
tone="muted"
|
||||
className="font-semibold tracking-[0.06em] uppercase"
|
||||
sx={{ mb: 1 }}
|
||||
>
|
||||
{children}
|
||||
</Typography>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({ label, value }: { label: string; value: string }) {
|
||||
const display = value && value.trim() !== "" ? value : "—";
|
||||
function Field({ label, value }: { label: string; value?: string }) {
|
||||
const display = !value || value.trim() === "" ? "—" : value;
|
||||
return (
|
||||
<Box>
|
||||
<Typography variant="caption" sx={{ color: "text.secondary", display: "block" }}>
|
||||
<Text variant="caption" tone="muted" sx={{ display: "block" }}>
|
||||
{label}
|
||||
</Typography>
|
||||
<Typography variant="body2">{display}</Typography>
|
||||
</Text>
|
||||
<Text variant="description">{display}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function TechnicianEntry({
|
||||
contactName,
|
||||
phone,
|
||||
email,
|
||||
preferredContact,
|
||||
tradeSpecialties,
|
||||
isActive,
|
||||
totalJobs,
|
||||
}: {
|
||||
contactName: string;
|
||||
phone: string;
|
||||
email: string;
|
||||
preferredContact?: string;
|
||||
tradeSpecialties: string;
|
||||
isActive: boolean;
|
||||
totalJobs: number;
|
||||
}) {
|
||||
const trades = splitTrades(tradeSpecialties);
|
||||
return (
|
||||
<ListItem disableGutters divider>
|
||||
<Stack spacing={0.5} className="w-full">
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: "center" }}>
|
||||
<Typography variant="body2" className="font-semibold">
|
||||
{contactName || "—"}
|
||||
</Typography>
|
||||
<Chip
|
||||
size="small"
|
||||
label={isActive ? "Active" : "Inactive"}
|
||||
color={isActive ? "success" : "default"}
|
||||
/>
|
||||
<Typography variant="caption" sx={{ color: "text.secondary" }}>
|
||||
{totalJobs} jobs
|
||||
</Typography>
|
||||
</Stack>
|
||||
<Stack direction="row" spacing={2} className="flex flex-wrap">
|
||||
{Boolean(phone) && (
|
||||
<Link href={`tel:${phone}`} underline="hover">
|
||||
{phone}
|
||||
</Link>
|
||||
)}
|
||||
{Boolean(email) && (
|
||||
<Link href={`mailto:${email}`} underline="hover">
|
||||
{email}
|
||||
</Link>
|
||||
)}
|
||||
</Stack>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: "center", flexWrap: "wrap" }}>
|
||||
{Boolean(preferredContact) && (
|
||||
<Typography variant="caption" sx={{ color: "text.secondary" }}>
|
||||
Prefers {preferredContact}
|
||||
</Typography>
|
||||
)}
|
||||
{trades.map((trade, index) => (
|
||||
<Chip
|
||||
key={`${trade}-${index}`}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
label={index === 0 ? `${trade} (primary)` : trade}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
</Stack>
|
||||
</ListItem>
|
||||
);
|
||||
}
|
||||
|
||||
function DrawerHeader({
|
||||
roster,
|
||||
vendor,
|
||||
technician,
|
||||
onClose,
|
||||
}: {
|
||||
roster?: VendorCompanyRoster;
|
||||
vendor: VendorListItem | null;
|
||||
technician?: VendorRosterTechnician;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
return (
|
||||
|
|
@ -141,23 +87,18 @@ function DrawerHeader({
|
|||
sx={{
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
px: 3,
|
||||
px: 2.5,
|
||||
py: 2,
|
||||
borderBottom: (theme) => `1px solid ${theme.palette.divider}`,
|
||||
}}
|
||||
>
|
||||
<Box>
|
||||
<Typography
|
||||
id="vendor-detail-drawer-title"
|
||||
variant="subtitle1"
|
||||
component="h2"
|
||||
className="font-semibold"
|
||||
>
|
||||
{roster?.name || vendor?.companyName || "Vendor company"}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ color: "text.secondary" }}>
|
||||
{roster ? `${roster.technicians.length} technician(s)` : "Vendor details"}
|
||||
</Typography>
|
||||
<Text id="vendor-detail-drawer-title" variant="title" as="h2" className="font-semibold">
|
||||
{technician?.contactName || vendor?.contactName || roster?.name || "Vendor company"}
|
||||
</Text>
|
||||
<Text variant="description" tone="muted">
|
||||
{roster?.name || vendor?.companyName || "Vendor details"}
|
||||
</Text>
|
||||
</Box>
|
||||
<IconButton aria-label="Close drawer" onClick={onClose} size="small">
|
||||
<CloseIcon fontSize="small" />
|
||||
|
|
@ -167,18 +108,19 @@ function DrawerHeader({
|
|||
}
|
||||
|
||||
function CompanySection({ roster }: { roster: VendorCompanyRoster }) {
|
||||
const mapsUrl = roster.googleMapsUrl;
|
||||
const address = [roster.address, roster.city, roster.state, roster.zip]
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
|
||||
return (
|
||||
<Stack spacing={1.5}>
|
||||
<Field label="Company" value={roster.name} />
|
||||
<Field label="Company Phone" value={roster.companyPhone} />
|
||||
<Field label="Email" value={roster.email} />
|
||||
<Field
|
||||
label="Address"
|
||||
value={[roster.address, roster.city, roster.state, roster.zip].filter(Boolean).join(", ")}
|
||||
/>
|
||||
{Boolean(mapsUrl) && (
|
||||
<Field label="Company Email" value={roster.email} />
|
||||
<Field label="Address" value={address} />
|
||||
{Boolean(roster.googleMapsUrl) && (
|
||||
<Link
|
||||
href={mapsUrl}
|
||||
href={roster.googleMapsUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1"
|
||||
|
|
@ -191,49 +133,79 @@ function CompanySection({ roster }: { roster: VendorCompanyRoster }) {
|
|||
);
|
||||
}
|
||||
|
||||
function TechniciansSection({ roster }: { roster: VendorCompanyRoster }) {
|
||||
function TechnicianSection({ technician }: { technician: VendorRosterTechnician }) {
|
||||
const trades = splitTrades(technician.tradeSpecialties);
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<SectionTitle>Technicians</SectionTitle>
|
||||
{roster.technicians.length === 0 ? (
|
||||
<Typography variant="body2" sx={{ color: "text.secondary" }}>
|
||||
No technicians assigned to this company.
|
||||
</Typography>
|
||||
) : (
|
||||
<List disablePadding>
|
||||
{roster.technicians.map((technician) => (
|
||||
<TechnicianEntry
|
||||
key={String(technician.id ?? technician.contactName)}
|
||||
contactName={technician.contactName}
|
||||
phone={technician.phone}
|
||||
email={technician.email}
|
||||
preferredContact={technician.preferredContact}
|
||||
tradeSpecialties={technician.tradeSpecialties}
|
||||
isActive={technician.isActive}
|
||||
totalJobs={technician.totalJobs}
|
||||
<Stack spacing={1.5}>
|
||||
<Field label="Phone" value={technician.phone} />
|
||||
<Box>
|
||||
<Text variant="caption" tone="muted" sx={{ display: "block", mb: 0.75 }}>
|
||||
Trade
|
||||
</Text>
|
||||
<Stack direction="row" spacing={0.75} sx={{ flexWrap: "wrap" }}>
|
||||
{trades.length > 0 ? (
|
||||
trades.map((trade, index) => (
|
||||
<Chip key={`${trade}-${index}`} size="small" variant="outlined" label={trade} />
|
||||
))
|
||||
) : (
|
||||
<Text variant="description">—</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</Box>
|
||||
<Stack direction="row" spacing={4} sx={{ alignItems: "flex-end" }}>
|
||||
<Box>
|
||||
<Text variant="title">{technician.totalJobs ?? 0}</Text>
|
||||
<Text variant="caption" tone="muted" sx={{ display: "block" }}>
|
||||
Total Jobs
|
||||
</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text variant="caption" tone="muted" sx={{ display: "block", mb: 0.5 }}>
|
||||
Status
|
||||
</Text>
|
||||
<Chip
|
||||
size="small"
|
||||
label={technician.isActive ? "Active" : "Inactive"}
|
||||
color={technician.isActive ? "success" : "default"}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
)}
|
||||
</Box>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function DrawerBody({ roster }: { roster: VendorCompanyRoster }) {
|
||||
function DrawerBody({
|
||||
roster,
|
||||
technician,
|
||||
}: {
|
||||
roster: VendorCompanyRoster;
|
||||
technician?: VendorRosterTechnician;
|
||||
}) {
|
||||
return (
|
||||
<Stack spacing={3} className="flex-1 overflow-y-auto" sx={{ px: 3, py: 3 }}>
|
||||
<SectionTitle>Company</SectionTitle>
|
||||
<CompanySection roster={roster} />
|
||||
<Stack spacing={3} className="flex-1 overflow-y-auto" sx={{ p: 2.5 }}>
|
||||
<Box>
|
||||
<SectionTitle>Company</SectionTitle>
|
||||
<CompanySection roster={roster} />
|
||||
</Box>
|
||||
<Divider />
|
||||
<TechniciansSection roster={roster} />
|
||||
{technician ? (
|
||||
<TechnicianSection technician={technician} />
|
||||
) : (
|
||||
<Text variant="description" tone="muted">
|
||||
No technicians assigned to this company.
|
||||
</Text>
|
||||
)}
|
||||
{Boolean(roster.notes) && (
|
||||
<>
|
||||
<Divider />
|
||||
<Box>
|
||||
<SectionTitle>Notes</SectionTitle>
|
||||
<Typography variant="body2" sx={{ whiteSpace: "pre-wrap" }}>
|
||||
<Text variant="description" sx={{ whiteSpace: "pre-wrap" }}>
|
||||
{roster.notes}
|
||||
</Typography>
|
||||
</Text>
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
|
|
@ -246,8 +218,8 @@ function DrawerActions({ onEdit }: { onEdit: () => void }) {
|
|||
<Stack
|
||||
direction="row"
|
||||
sx={{
|
||||
px: 3,
|
||||
py: 2,
|
||||
px: 2.5,
|
||||
py: 1.5,
|
||||
borderTop: (theme) => `1px solid ${theme.palette.divider}`,
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-end",
|
||||
|
|
@ -260,8 +232,143 @@ function DrawerActions({ onEdit }: { onEdit: () => void }) {
|
|||
);
|
||||
}
|
||||
|
||||
export function VendorDetailDrawer({ open, vendor, onClose }: VendorDetailDrawerProps) {
|
||||
const navigate = useNavigate();
|
||||
function DrawerEditor({
|
||||
vendor,
|
||||
onClose,
|
||||
onSaved,
|
||||
onRequestDeactivation = () => undefined,
|
||||
}: {
|
||||
vendor: VendorListItem;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
onRequestDeactivation: (vendor: VendorListItem) => void;
|
||||
}) {
|
||||
const form = useVendorRosterForm({
|
||||
mode: "update",
|
||||
vendorId: vendor.id ?? undefined,
|
||||
companyId: vendor.id == null ? (vendor.companyId ?? undefined) : undefined,
|
||||
onSuccess: onSaved,
|
||||
});
|
||||
const roster = form.roster;
|
||||
const technicians = useWatch({ control: form.control, name: "technicians" }) ?? [];
|
||||
const selectedIndex = technicians.findIndex(
|
||||
(technician) => technician.id != null && String(technician.id) === String(vendor.id),
|
||||
);
|
||||
const selectedTotalJobs =
|
||||
roster?.technicians.find(
|
||||
(technician) => technician.id != null && String(technician.id) === String(vendor.id),
|
||||
)?.totalJobs ?? vendor.totalJobs;
|
||||
|
||||
if (form.isLoading) {
|
||||
return <CircularProgress size={28} sx={{ m: "auto" }} />;
|
||||
}
|
||||
if (form.isError || !roster) {
|
||||
return (
|
||||
<Alert severity="error" sx={{ m: 2 }}>
|
||||
Failed to load vendor company. Try again.
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box
|
||||
component="form"
|
||||
id="vendor-drawer-edit-form"
|
||||
onSubmit={form.handleSubmit(form.submit)}
|
||||
className="flex min-h-0 flex-1 flex-col"
|
||||
>
|
||||
<Stack spacing={2} className="flex-1 overflow-y-auto" sx={{ p: 2.5 }}>
|
||||
{form.loadErrorMessage !== null && (
|
||||
<VendorRosterLoadErrorAlert message={form.loadErrorMessage} onRetry={form.retryLoad} />
|
||||
)}
|
||||
{form.conflict !== null && (
|
||||
<VendorRosterConflictAlert conflict={form.conflict} onReload={form.reload} />
|
||||
)}
|
||||
<VendorRosterFormFields
|
||||
control={form.control}
|
||||
errors={form.errors}
|
||||
tradeOptions={form.trades}
|
||||
showTechnicianStatus={false}
|
||||
/>
|
||||
{selectedIndex >= 0 && (
|
||||
<>
|
||||
<Divider />
|
||||
<Stack direction="row" sx={{ alignItems: "center", justifyContent: "space-between" }}>
|
||||
<Box>
|
||||
<Text variant="title">{selectedTotalJobs}</Text>
|
||||
<Text variant="caption" tone="muted">
|
||||
Total Jobs
|
||||
</Text>
|
||||
</Box>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name={`technicians.${selectedIndex}.isActive`}
|
||||
render={({ field }) => (
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: "center" }}>
|
||||
<Text variant="description">{field.value ? "Active" : "Inactive"}</Text>
|
||||
<Switch
|
||||
checked={Boolean(field.value)}
|
||||
slotProps={{ input: { "aria-label": "Active status" } }}
|
||||
onChange={(_event, checked) => {
|
||||
if (field.value && !checked) onRequestDeactivation(vendor);
|
||||
else field.onChange(checked);
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
)}
|
||||
/>
|
||||
</Stack>
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={1.5}
|
||||
sx={{ p: 2, borderTop: 1, borderColor: "divider", justifyContent: "flex-end" }}
|
||||
>
|
||||
<Button onClick={onClose} disabled={form.isSaving}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" variant="contained" disabled={form.isSaving || !form.isValid}>
|
||||
{form.isSaving ? "Saving..." : "Save changes"}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function resolveTechnician(
|
||||
roster: VendorCompanyRoster | undefined,
|
||||
vendor: VendorListItem | null,
|
||||
): VendorRosterTechnician | undefined {
|
||||
if (!roster || !vendor) return undefined;
|
||||
|
||||
const match = roster.technicians.find(
|
||||
(technician) =>
|
||||
vendor.id != null && technician.id != null && String(technician.id) === String(vendor.id),
|
||||
);
|
||||
if (match) return match;
|
||||
if (!vendor.contactName) return undefined;
|
||||
|
||||
return {
|
||||
id: vendor.id ?? undefined,
|
||||
contactName: vendor.contactName,
|
||||
phone: vendor.phone,
|
||||
email: vendor.email,
|
||||
tradeSpecialties: vendor.tradeSpecialties,
|
||||
isActive: vendor.isActive,
|
||||
totalJobs: vendor.totalJobs,
|
||||
};
|
||||
}
|
||||
|
||||
export function VendorDetailDrawer({
|
||||
open,
|
||||
vendor,
|
||||
startInEdit = false,
|
||||
onRequestDeactivation = () => undefined,
|
||||
onClose,
|
||||
}: VendorDetailDrawerProps) {
|
||||
const [isEditing, setIsEditing] = useState(startInEdit);
|
||||
const vendorId = vendor?.id;
|
||||
const companyId = vendor?.companyId;
|
||||
const hasVendorId = vendorId != null;
|
||||
|
|
@ -274,25 +381,30 @@ export function VendorDetailDrawer({ open, vendor, onClose }: VendorDetailDrawer
|
|||
!hasVendorId ? (companyId ?? undefined) : undefined,
|
||||
);
|
||||
|
||||
const editHref = hasVendorId
|
||||
? `/vendors/edit/${vendorId}`
|
||||
: `/vendors/company/${companyId ?? ""}`;
|
||||
const selectedTechnician = resolveTechnician(roster, vendor);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) setIsEditing(startInEdit);
|
||||
}, [open, startInEdit, vendor]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
const closeOnEscape = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") onClose();
|
||||
if (event.key === "Escape" && !isEditing) onClose();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", closeOnEscape);
|
||||
return () => window.removeEventListener("keydown", closeOnEscape);
|
||||
}, [onClose, open]);
|
||||
}, [isEditing, onClose, open]);
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
onClose={(_event, reason) => {
|
||||
if (reason === "escapeKeyDown" && isEditing) return;
|
||||
onClose();
|
||||
}}
|
||||
anchor="right"
|
||||
aria-labelledby="vendor-detail-drawer-title"
|
||||
ModalProps={{ keepMounted: false }}
|
||||
|
|
@ -304,9 +416,21 @@ export function VendorDetailDrawer({ open, vendor, onClose }: VendorDetailDrawer
|
|||
}}
|
||||
>
|
||||
<Stack className="flex h-full flex-col">
|
||||
<DrawerHeader roster={roster} vendor={vendor} onClose={onClose} />
|
||||
<DrawerHeader
|
||||
roster={roster}
|
||||
vendor={vendor}
|
||||
technician={selectedTechnician}
|
||||
onClose={onClose}
|
||||
/>
|
||||
|
||||
{isLoading ? (
|
||||
{isEditing && vendor ? (
|
||||
<DrawerEditor
|
||||
vendor={vendor}
|
||||
onClose={onClose}
|
||||
onSaved={() => setIsEditing(false)}
|
||||
onRequestDeactivation={onRequestDeactivation}
|
||||
/>
|
||||
) : isLoading ? (
|
||||
<Box className="flex flex-1 items-center justify-center">
|
||||
<CircularProgress size={28} />
|
||||
</Box>
|
||||
|
|
@ -316,14 +440,14 @@ export function VendorDetailDrawer({ open, vendor, onClose }: VendorDetailDrawer
|
|||
</Alert>
|
||||
) : roster ? (
|
||||
<>
|
||||
<DrawerBody roster={roster} />
|
||||
<DrawerActions onEdit={() => navigate(editHref)} />
|
||||
<DrawerBody roster={roster} technician={selectedTechnician} />
|
||||
<DrawerActions onEdit={() => setIsEditing(true)} />
|
||||
</>
|
||||
) : (
|
||||
<Box className="flex flex-1 items-center justify-center">
|
||||
<Typography variant="body2" sx={{ color: "text.secondary" }}>
|
||||
<Text variant="description" tone="muted">
|
||||
No vendor selected.
|
||||
</Typography>
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Stack>
|
||||
|
|
|
|||
252
src/app/(protected)/vendors/_components/vendor-filter-options.tsx
vendored
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
import type { Dispatch, ReactNode, SetStateAction } from "react";
|
||||
import BusinessOutlinedIcon from "@mui/icons-material/BusinessOutlined";
|
||||
import BuildOutlinedIcon from "@mui/icons-material/BuildOutlined";
|
||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||
import LocationOnOutlinedIcon from "@mui/icons-material/LocationOnOutlined";
|
||||
import TagOutlinedIcon from "@mui/icons-material/TagOutlined";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionDetails,
|
||||
AccordionSummary,
|
||||
Autocomplete,
|
||||
Box,
|
||||
Button,
|
||||
Checkbox,
|
||||
Chip,
|
||||
Stack,
|
||||
TextField,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import type {
|
||||
VendorFacets,
|
||||
VendorFacetCompany,
|
||||
VendorFacetJobBucket,
|
||||
VendorFacetLocation,
|
||||
} from "@/domain/vendors/types/vendor";
|
||||
import type { VendorFilters } from "./vendor-filters";
|
||||
|
||||
type DraftSetter = Dispatch<SetStateAction<VendorFilters>>;
|
||||
|
||||
function FilterSection({
|
||||
title,
|
||||
icon,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
icon: ReactNode;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<Accordion disableGutters elevation={0} square sx={{ borderBottom: 1, borderColor: "divider" }}>
|
||||
<AccordionSummary expandIcon={<ExpandMoreIcon />} aria-controls={`${title}-filters-content`}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: "center" }}>
|
||||
<Box sx={{ color: "primary.main", display: "flex" }}>{icon}</Box>
|
||||
<Typography variant="subtitle1" className="font-semibold">
|
||||
{title}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</AccordionSummary>
|
||||
<AccordionDetails id={`${title}-filters-content`} sx={{ pt: 0, pb: 2.5 }}>
|
||||
{children}
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
);
|
||||
}
|
||||
|
||||
function CompanyFilter({
|
||||
options,
|
||||
draft,
|
||||
setDraft,
|
||||
}: {
|
||||
options: VendorFacetCompany[];
|
||||
draft: VendorFilters;
|
||||
setDraft: DraftSetter;
|
||||
}) {
|
||||
const allSelected = draft.companies.length === options.length && options.length > 0;
|
||||
return (
|
||||
<FilterSection title="Company" icon={<BusinessOutlinedIcon />}>
|
||||
<Stack direction="row" sx={{ alignItems: "center", justifyContent: "space-between" }}>
|
||||
<Typography variant="caption" sx={{ color: "text.secondary" }}>
|
||||
Select vendor companies
|
||||
</Typography>
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() =>
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
companies: allSelected ? [] : options.map((company) => company.name),
|
||||
}))
|
||||
}
|
||||
>
|
||||
{allSelected ? "Clear all" : "Select all"}
|
||||
</Button>
|
||||
</Stack>
|
||||
<Autocomplete
|
||||
multiple
|
||||
size="small"
|
||||
options={options}
|
||||
getOptionLabel={(option) => (typeof option === "string" ? option : option.name)}
|
||||
isOptionEqualToValue={(option, value) =>
|
||||
typeof option === "string" || typeof value === "string"
|
||||
? option === value
|
||||
: option.name === value.name
|
||||
}
|
||||
value={options.filter((option) => draft.companies.includes(option.name))}
|
||||
onChange={(_event, value) => {
|
||||
const next = (value as (string | VendorFacetCompany)[]).map((entry) =>
|
||||
typeof entry === "string" ? entry : entry.name,
|
||||
);
|
||||
setDraft((current) => ({ ...current, companies: next }));
|
||||
}}
|
||||
renderOption={(props, option, { selected }) => {
|
||||
const { key, ...optionProps } = props;
|
||||
return (
|
||||
<li key={key} {...optionProps}>
|
||||
<Checkbox checked={selected} size="small" sx={{ mr: 1 }} />
|
||||
{option.name}
|
||||
</li>
|
||||
);
|
||||
}}
|
||||
renderValue={(value, getItemProps) =>
|
||||
value.map((option, index) => {
|
||||
const label = typeof option === "string" ? option : option.name;
|
||||
const { key, ...chipProps } = getItemProps({ index });
|
||||
return <Chip key={key} size="small" label={label} {...chipProps} />;
|
||||
})
|
||||
}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
placeholder={draft.companies.length === 0 ? "All companies" : ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FilterSection>
|
||||
);
|
||||
}
|
||||
|
||||
function TradeFilter({ options, draft, setDraft }: FilterProps<string>) {
|
||||
return (
|
||||
<FilterSection title="Trade" icon={<BuildOutlinedIcon />}>
|
||||
<Autocomplete
|
||||
multiple
|
||||
size="small"
|
||||
options={options}
|
||||
value={draft.trades}
|
||||
onChange={(_event, value) =>
|
||||
setDraft((current) => ({ ...current, trades: value as string[] }))
|
||||
}
|
||||
renderValue={(value, getItemProps) =>
|
||||
value.map((option, index) => {
|
||||
const { key, ...chipProps } = getItemProps({ index });
|
||||
return <Chip key={key} size="small" label={option} {...chipProps} />;
|
||||
})
|
||||
}
|
||||
renderInput={(params) => (
|
||||
<TextField {...params} placeholder={draft.trades.length === 0 ? "All trades" : ""} />
|
||||
)}
|
||||
/>
|
||||
</FilterSection>
|
||||
);
|
||||
}
|
||||
|
||||
interface FilterProps<T> {
|
||||
options: T[];
|
||||
draft: VendorFilters;
|
||||
setDraft: DraftSetter;
|
||||
}
|
||||
|
||||
function LocationFilter({ options, draft, setDraft }: FilterProps<VendorFacetLocation>) {
|
||||
return (
|
||||
<FilterSection title="Location" icon={<LocationOnOutlinedIcon />}>
|
||||
<Autocomplete
|
||||
multiple
|
||||
size="small"
|
||||
options={options}
|
||||
getOptionLabel={(option) => (typeof option === "string" ? option : option.label)}
|
||||
isOptionEqualToValue={(option, value) =>
|
||||
typeof option === "string" || typeof value === "string"
|
||||
? option === value
|
||||
: option.label === value.label
|
||||
}
|
||||
value={options.filter((option) => draft.locations.includes(option.label))}
|
||||
onChange={(_event, value) => {
|
||||
const next = (value as (string | VendorFacetLocation)[]).map((entry) =>
|
||||
typeof entry === "string" ? entry : entry.label,
|
||||
);
|
||||
setDraft((current) => ({ ...current, locations: next }));
|
||||
}}
|
||||
renderValue={(value, getItemProps) =>
|
||||
value.map((option, index) => {
|
||||
const label = typeof option === "string" ? option : option.label;
|
||||
const { key, ...chipProps } = getItemProps({ index });
|
||||
return <Chip key={key} size="small" label={label} {...chipProps} />;
|
||||
})
|
||||
}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
placeholder={draft.locations.length === 0 ? "All locations" : ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FilterSection>
|
||||
);
|
||||
}
|
||||
|
||||
function JobCountFilter({ options, draft, setDraft }: FilterProps<VendorFacetJobBucket>) {
|
||||
return (
|
||||
<FilterSection title="Total Jobs" icon={<TagOutlinedIcon />}>
|
||||
<Autocomplete
|
||||
multiple
|
||||
size="small"
|
||||
options={options}
|
||||
getOptionLabel={(option) => (typeof option === "string" ? option : option.label)}
|
||||
isOptionEqualToValue={(option, value) =>
|
||||
typeof option === "string" || typeof value === "string"
|
||||
? option === value
|
||||
: option.id === value.id
|
||||
}
|
||||
value={options.filter((option) => draft.jobBuckets.includes(option.id))}
|
||||
onChange={(_event, value) => {
|
||||
const next = (value as (string | VendorFacetJobBucket)[]).map((entry) =>
|
||||
typeof entry === "string" ? entry : entry.id,
|
||||
);
|
||||
setDraft((current) => ({ ...current, jobBuckets: next }));
|
||||
}}
|
||||
renderValue={(value, getItemProps) =>
|
||||
value.map((option, index) => {
|
||||
const label = typeof option === "string" ? option : option.label;
|
||||
const { key, ...chipProps } = getItemProps({ index });
|
||||
return <Chip key={key} size="small" label={label} {...chipProps} />;
|
||||
})
|
||||
}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
placeholder={draft.jobBuckets.length === 0 ? "All job counts" : ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FilterSection>
|
||||
);
|
||||
}
|
||||
|
||||
export function VendorFilterOptions({
|
||||
facets,
|
||||
draft,
|
||||
setDraft,
|
||||
}: {
|
||||
facets: VendorFacets | undefined;
|
||||
draft: VendorFilters;
|
||||
setDraft: DraftSetter;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<CompanyFilter options={facets?.companies ?? []} draft={draft} setDraft={setDraft} />
|
||||
<TradeFilter options={facets?.trades ?? []} draft={draft} setDraft={setDraft} />
|
||||
<LocationFilter options={facets?.locations ?? []} draft={draft} setDraft={setDraft} />
|
||||
<JobCountFilter options={facets?.jobBuckets ?? []} draft={draft} setDraft={setDraft} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,32 +1,9 @@
|
|||
import { useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import BusinessOutlinedIcon from "@mui/icons-material/BusinessOutlined";
|
||||
import BuildOutlinedIcon from "@mui/icons-material/BuildOutlined";
|
||||
import { useEffect, useState } from "react";
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||
import LocationOnOutlinedIcon from "@mui/icons-material/LocationOnOutlined";
|
||||
import TagOutlinedIcon from "@mui/icons-material/TagOutlined";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionDetails,
|
||||
AccordionSummary,
|
||||
Autocomplete,
|
||||
Box,
|
||||
Button,
|
||||
Checkbox,
|
||||
Chip,
|
||||
Drawer,
|
||||
IconButton,
|
||||
Stack,
|
||||
TextField,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import type {
|
||||
VendorFacets,
|
||||
VendorFacetCompany,
|
||||
VendorFacetJobBucket,
|
||||
VendorFacetLocation,
|
||||
} from "@/domain/vendors/types/vendor";
|
||||
import { Box, Button, Chip, Drawer, IconButton, Stack, Typography } from "@mui/material";
|
||||
import { VendorFilterOptions } from "./vendor-filter-options";
|
||||
import { emptyVendorFilters, type VendorFilters } from "./vendor-filters";
|
||||
import type { VendorFacets } from "@/domain/vendors/types/vendor";
|
||||
|
||||
interface VendorFiltersDrawerProps {
|
||||
open: boolean;
|
||||
|
|
@ -38,32 +15,6 @@ interface VendorFiltersDrawerProps {
|
|||
|
||||
const DRAWER_WIDTH = 360;
|
||||
|
||||
function FilterSection({
|
||||
title,
|
||||
icon,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
icon: ReactNode;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<Accordion disableGutters elevation={0} square sx={{ borderBottom: 1, borderColor: "divider" }}>
|
||||
<AccordionSummary expandIcon={<ExpandMoreIcon />} aria-controls={`${title}-filters-content`}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: "center" }}>
|
||||
<Box sx={{ color: "primary.main", display: "flex" }}>{icon}</Box>
|
||||
<Typography variant="subtitle1" className="font-semibold">
|
||||
{title}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</AccordionSummary>
|
||||
<AccordionDetails id={`${title}-filters-content`} sx={{ pt: 0, pb: 2.5 }}>
|
||||
{children}
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
);
|
||||
}
|
||||
|
||||
export function VendorFiltersDrawer({
|
||||
open,
|
||||
onClose,
|
||||
|
|
@ -74,23 +25,12 @@ export function VendorFiltersDrawer({
|
|||
const [draft, setDraft] = useState<VendorFilters>(appliedFilters);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setDraft(appliedFilters);
|
||||
}
|
||||
if (open) setDraft(appliedFilters);
|
||||
}, [open, appliedFilters]);
|
||||
|
||||
const companyOptions = useMemo(() => facets?.companies ?? [], [facets]);
|
||||
const tradeOptions = useMemo(() => facets?.trades ?? [], [facets]);
|
||||
const locationOptions = useMemo(() => facets?.locations ?? [], [facets]);
|
||||
const jobBucketOptions = useMemo(() => facets?.jobBuckets ?? [], [facets]);
|
||||
|
||||
const activeCount =
|
||||
draft.companies.length + draft.trades.length + draft.locations.length + draft.jobBuckets.length;
|
||||
|
||||
const handleClear = () => {
|
||||
setDraft(emptyVendorFilters);
|
||||
};
|
||||
|
||||
const handleApply = () => {
|
||||
onApply(draft);
|
||||
onClose();
|
||||
|
|
@ -133,165 +73,7 @@ export function VendorFiltersDrawer({
|
|||
</Stack>
|
||||
|
||||
<Box className="flex-1 overflow-y-auto" sx={{ px: 2.5 }}>
|
||||
<FilterSection title="Company" icon={<BusinessOutlinedIcon />}>
|
||||
<Stack direction="row" sx={{ alignItems: "center", justifyContent: "space-between" }}>
|
||||
<Typography variant="caption" sx={{ color: "text.secondary" }}>
|
||||
Select vendor companies
|
||||
</Typography>
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() =>
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
companies:
|
||||
current.companies.length === companyOptions.length
|
||||
? []
|
||||
: companyOptions.map((company) => company.name),
|
||||
}))
|
||||
}
|
||||
>
|
||||
{draft.companies.length === companyOptions.length && companyOptions.length > 0
|
||||
? "Clear all"
|
||||
: "Select all"}
|
||||
</Button>
|
||||
</Stack>
|
||||
<Autocomplete
|
||||
multiple
|
||||
size="small"
|
||||
options={companyOptions}
|
||||
getOptionLabel={(option) => (typeof option === "string" ? option : option.name)}
|
||||
isOptionEqualToValue={(option, value) =>
|
||||
typeof option === "string" || typeof value === "string"
|
||||
? option === value
|
||||
: option.name === value.name
|
||||
}
|
||||
value={companyOptions.filter((option) => draft.companies.includes(option.name))}
|
||||
onChange={(_event, value) => {
|
||||
const next = (value as (string | VendorFacetCompany)[]).map((entry) =>
|
||||
typeof entry === "string" ? entry : entry.name,
|
||||
);
|
||||
setDraft((current) => ({ ...current, companies: next }));
|
||||
}}
|
||||
renderOption={(props, option, { selected }) => {
|
||||
const { key, ...optionProps } = props;
|
||||
return (
|
||||
<li key={key} {...optionProps}>
|
||||
<Checkbox checked={selected} size="small" sx={{ mr: 1 }} />
|
||||
{option.name}
|
||||
</li>
|
||||
);
|
||||
}}
|
||||
renderValue={(value, getItemProps) =>
|
||||
value.map((option, index) => {
|
||||
const label = typeof option === "string" ? option : option.name;
|
||||
const tagProps = getItemProps({ index });
|
||||
const { key, ...chipProps } = tagProps;
|
||||
return <Chip key={key} size="small" label={label} {...chipProps} />;
|
||||
})
|
||||
}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
placeholder={draft.companies.length === 0 ? "All companies" : ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FilterSection>
|
||||
|
||||
<FilterSection title="Trade" icon={<BuildOutlinedIcon />}>
|
||||
<Autocomplete
|
||||
multiple
|
||||
size="small"
|
||||
options={tradeOptions}
|
||||
value={draft.trades}
|
||||
onChange={(_event, value) =>
|
||||
setDraft((current) => ({ ...current, trades: value as string[] }))
|
||||
}
|
||||
renderValue={(value, getItemProps) =>
|
||||
value.map((option, index) => {
|
||||
const tagProps = getItemProps({ index });
|
||||
const { key, ...chipProps } = tagProps;
|
||||
return <Chip key={key} size="small" label={option} {...chipProps} />;
|
||||
})
|
||||
}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
placeholder={draft.trades.length === 0 ? "All trades" : ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FilterSection>
|
||||
|
||||
<FilterSection title="Location" icon={<LocationOnOutlinedIcon />}>
|
||||
<Autocomplete
|
||||
multiple
|
||||
size="small"
|
||||
options={locationOptions}
|
||||
getOptionLabel={(option) => (typeof option === "string" ? option : option.label)}
|
||||
isOptionEqualToValue={(option, value) =>
|
||||
typeof option === "string" || typeof value === "string"
|
||||
? option === value
|
||||
: option.label === value.label
|
||||
}
|
||||
value={locationOptions.filter((option) => draft.locations.includes(option.label))}
|
||||
onChange={(_event, value) => {
|
||||
const next = (value as (string | VendorFacetLocation)[]).map((entry) =>
|
||||
typeof entry === "string" ? entry : entry.label,
|
||||
);
|
||||
setDraft((current) => ({ ...current, locations: next }));
|
||||
}}
|
||||
renderValue={(value, getItemProps) =>
|
||||
value.map((option, index) => {
|
||||
const label = typeof option === "string" ? option : option.label;
|
||||
const tagProps = getItemProps({ index });
|
||||
const { key, ...chipProps } = tagProps;
|
||||
return <Chip key={key} size="small" label={label} {...chipProps} />;
|
||||
})
|
||||
}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
placeholder={draft.locations.length === 0 ? "All locations" : ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FilterSection>
|
||||
|
||||
<FilterSection title="Total Jobs" icon={<TagOutlinedIcon />}>
|
||||
<Autocomplete
|
||||
multiple
|
||||
size="small"
|
||||
options={jobBucketOptions}
|
||||
getOptionLabel={(option) => (typeof option === "string" ? option : option.label)}
|
||||
isOptionEqualToValue={(option, value) =>
|
||||
typeof option === "string" || typeof value === "string"
|
||||
? option === value
|
||||
: option.id === value.id
|
||||
}
|
||||
value={jobBucketOptions.filter((option) => draft.jobBuckets.includes(option.id))}
|
||||
onChange={(_event, value) => {
|
||||
const next = (value as (string | VendorFacetJobBucket)[]).map((entry) =>
|
||||
typeof entry === "string" ? entry : entry.id,
|
||||
);
|
||||
setDraft((current) => ({ ...current, jobBuckets: next }));
|
||||
}}
|
||||
renderValue={(value, getItemProps) =>
|
||||
value.map((option, index) => {
|
||||
const label = typeof option === "string" ? option : option.label;
|
||||
const tagProps = getItemProps({ index });
|
||||
const { key, ...chipProps } = tagProps;
|
||||
return <Chip key={key} size="small" label={label} {...chipProps} />;
|
||||
})
|
||||
}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
placeholder={draft.jobBuckets.length === 0 ? "All job counts" : ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FilterSection>
|
||||
<VendorFilterOptions facets={facets} draft={draft} setDraft={setDraft} />
|
||||
</Box>
|
||||
|
||||
<Stack
|
||||
|
|
@ -303,11 +85,16 @@ export function VendorFiltersDrawer({
|
|||
borderTop: (theme) => `1px solid ${theme.palette.divider}`,
|
||||
}}
|
||||
>
|
||||
<Button variant="outlined" onClick={handleClear} disabled={activeCount === 0} fullWidth>
|
||||
<Button
|
||||
variant="outlined"
|
||||
onClick={() => setDraft(emptyVendorFilters)}
|
||||
disabled={activeCount === 0}
|
||||
fullWidth
|
||||
>
|
||||
Clear all
|
||||
</Button>
|
||||
<Button variant="contained" onClick={handleApply} fullWidth>
|
||||
Apply
|
||||
Apply filters
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ interface VendorRosterFormFieldsProps {
|
|||
selectedCompanyId?: string | number | null;
|
||||
onSelectCompany?: (company: VendorFacetCompany | null) => Promise<void>;
|
||||
onClearSelectedCompany?: (nextName?: string) => void;
|
||||
showTechnicianStatus?: boolean;
|
||||
}
|
||||
|
||||
function CompanyNameField({
|
||||
|
|
@ -54,6 +55,7 @@ function CompanyNameField({
|
|||
<TextField
|
||||
{...field}
|
||||
label="Company"
|
||||
placeholder="Start typing a company…"
|
||||
required
|
||||
error={Boolean(errors.name)}
|
||||
helperText={errors.name?.message}
|
||||
|
|
@ -98,8 +100,9 @@ function CompanyNameField({
|
|||
{...params}
|
||||
label="Company"
|
||||
required
|
||||
placeholder="Start typing a company…"
|
||||
error={Boolean(errors.name)}
|
||||
helperText={errors.name?.message ?? "Choose an existing company or enter a new one"}
|
||||
helperText={errors.name?.message}
|
||||
inputRef={field.ref}
|
||||
/>
|
||||
)}
|
||||
|
|
@ -119,10 +122,7 @@ function CompanyFields({
|
|||
}: VendorRosterFormFieldsProps) {
|
||||
return (
|
||||
<Box>
|
||||
<Typography variant="subtitle2" className="font-semibold uppercase">
|
||||
Company
|
||||
</Typography>
|
||||
<Stack spacing={2} className="mt-2">
|
||||
<Stack spacing={2}>
|
||||
<CompanyNameField
|
||||
control={control}
|
||||
errors={errors}
|
||||
|
|
@ -138,13 +138,13 @@ function CompanyFields({
|
|||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
label="Company Phone"
|
||||
placeholder="(XXX) XXX-XXXX"
|
||||
label="Company Phone (optional)"
|
||||
placeholder="(214) 555-0100"
|
||||
inputMode="tel"
|
||||
value={field.value ?? ""}
|
||||
onChange={(event) => field.onChange(formatNorthAmericanPhone(event.target.value))}
|
||||
error={Boolean(errors.companyPhone)}
|
||||
helperText={errors.companyPhone?.message ?? "Phone or email required"}
|
||||
helperText={errors.companyPhone?.message}
|
||||
fullWidth
|
||||
/>
|
||||
)}
|
||||
|
|
@ -155,7 +155,8 @@ function CompanyFields({
|
|||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
label="Email"
|
||||
label="Email (optional)"
|
||||
placeholder="dispatch@vendor.com"
|
||||
type="email"
|
||||
error={Boolean(errors.email)}
|
||||
helperText={errors.email?.message}
|
||||
|
|
@ -167,9 +168,16 @@ function CompanyFields({
|
|||
<Controller
|
||||
control={control}
|
||||
name="address"
|
||||
render={({ field }) => <TextField {...field} label="Address" fullWidth />}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
label="Address (optional)"
|
||||
placeholder="123 Industrial Pkwy, Dallas, TX 75201"
|
||||
fullWidth
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Stack direction={{ xs: "column", sm: "row" }} spacing={2}>
|
||||
<Stack direction={{ xs: "column", sm: "row" }} spacing={2} sx={{ display: "none" }}>
|
||||
<Controller
|
||||
control={control}
|
||||
name="city"
|
||||
|
|
@ -194,10 +202,10 @@ function CompanyFields({
|
|||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
label="Google Maps URL"
|
||||
placeholder="https://maps.google.com/..."
|
||||
label="Google Maps URL (optional)"
|
||||
placeholder="https://maps.google.com/…"
|
||||
error={Boolean(errors.googleMapsUrl)}
|
||||
helperText={errors.googleMapsUrl?.message ?? "Must be an HTTPS link"}
|
||||
helperText={errors.googleMapsUrl?.message}
|
||||
fullWidth
|
||||
/>
|
||||
)}
|
||||
|
|
@ -206,7 +214,14 @@ function CompanyFields({
|
|||
control={control}
|
||||
name="notes"
|
||||
render={({ field }) => (
|
||||
<TextField {...field} label="Notes" multiline minRows={2} fullWidth />
|
||||
<TextField
|
||||
{...field}
|
||||
label="Notes (optional)"
|
||||
placeholder="Internal notes, scheduling preferences, certifications…"
|
||||
multiline
|
||||
minRows={2}
|
||||
fullWidth
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Stack>
|
||||
|
|
@ -221,6 +236,7 @@ interface TechnicianRowProps {
|
|||
onRemove: () => void;
|
||||
canRemove: boolean;
|
||||
tradeOptions: string[];
|
||||
showStatus: boolean;
|
||||
}
|
||||
|
||||
function TechnicianRow({
|
||||
|
|
@ -230,12 +246,13 @@ function TechnicianRow({
|
|||
onRemove,
|
||||
canRemove,
|
||||
tradeOptions,
|
||||
showStatus,
|
||||
}: TechnicianRowProps) {
|
||||
return (
|
||||
<Stack spacing={2} className="rounded-md border border-solid border-gray-200 p-3">
|
||||
<Stack direction="row" sx={{ alignItems: "center", justifyContent: "space-between" }}>
|
||||
<Typography variant="subtitle2" className="font-semibold">
|
||||
Technician {index + 1}
|
||||
{index + 1} - TECHNICIAN
|
||||
</Typography>
|
||||
<Tooltip title="Remove technician">
|
||||
<span>
|
||||
|
|
@ -256,7 +273,8 @@ function TechnicianRow({
|
|||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
label="Technician Name"
|
||||
label="Technician name (optional)"
|
||||
placeholder="Technician name"
|
||||
error={Boolean(error?.contactName)}
|
||||
helperText={error?.contactName?.message}
|
||||
fullWidth
|
||||
|
|
@ -270,8 +288,8 @@ function TechnicianRow({
|
|||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
label="Technician Phone"
|
||||
placeholder="(XXX) XXX-XXXX"
|
||||
label="Technician phone (optional)"
|
||||
placeholder="(000) 000-0000"
|
||||
inputMode="tel"
|
||||
value={field.value ?? ""}
|
||||
onChange={(event) => field.onChange(formatNorthAmericanPhone(event.target.value))}
|
||||
|
|
@ -292,26 +310,29 @@ function TechnicianRow({
|
|||
error={Boolean(error?.email)}
|
||||
helperText={error?.email?.message}
|
||||
fullWidth
|
||||
sx={{ display: "none" }}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Stack>
|
||||
<VendorTradeSpecialtiesField control={control} index={index} tradeOptions={tradeOptions} />
|
||||
<Controller
|
||||
control={control}
|
||||
name={`technicians.${index}.isActive`}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onChange={(_event, checked) => field.onChange(checked)}
|
||||
/>
|
||||
}
|
||||
label={field.value ? "Active" : "Inactive"}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{showStatus && (
|
||||
<Controller
|
||||
control={control}
|
||||
name={`technicians.${index}.isActive`}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onChange={(_event, checked) => field.onChange(checked)}
|
||||
/>
|
||||
}
|
||||
label={field.value ? "Active" : "Inactive"}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
|
@ -320,10 +341,12 @@ function TechniciansFieldArray({
|
|||
control,
|
||||
errors,
|
||||
tradeOptions,
|
||||
showStatus,
|
||||
}: {
|
||||
control: Control<VendorCompanyRosterFormValues>;
|
||||
errors: FieldErrors<VendorCompanyRosterFormValues>;
|
||||
tradeOptions: string[];
|
||||
showStatus: boolean;
|
||||
}) {
|
||||
const { fields, append, remove } = useFieldArray({ control, name: "technicians" });
|
||||
|
||||
|
|
@ -366,6 +389,7 @@ function TechniciansFieldArray({
|
|||
onRemove={() => remove(index)}
|
||||
canRemove
|
||||
tradeOptions={tradeOptions}
|
||||
showStatus={showStatus}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
|
|
@ -375,12 +399,17 @@ function TechniciansFieldArray({
|
|||
}
|
||||
|
||||
export function VendorRosterFormFields(props: VendorRosterFormFieldsProps) {
|
||||
const { control, errors, tradeOptions = [] } = props;
|
||||
const { control, errors, tradeOptions = [], showTechnicianStatus = true } = props;
|
||||
return (
|
||||
<Stack spacing={3}>
|
||||
<CompanyFields {...props} />
|
||||
<Divider />
|
||||
<TechniciansFieldArray control={control} errors={errors} tradeOptions={tradeOptions} />
|
||||
<TechniciansFieldArray
|
||||
control={control}
|
||||
errors={errors}
|
||||
tradeOptions={tradeOptions}
|
||||
showStatus={showTechnicianStatus}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,9 @@
|
|||
import FilterListIcon from "@mui/icons-material/FilterList";
|
||||
import {
|
||||
Button,
|
||||
Chip,
|
||||
CircularProgress,
|
||||
Stack,
|
||||
TablePagination,
|
||||
TextField,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { Button, Chip, CircularProgress, Stack, TablePagination } from "@mui/material";
|
||||
import { Plus, SlidersHorizontal } from "lucide-react";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { SearchInput } from "@/components/ui/search-input";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import { ToolbarButton } from "@/components/ui/toolbar-button";
|
||||
|
||||
interface VendorsListToolbarProps {
|
||||
globalCount: number;
|
||||
|
|
@ -33,52 +29,46 @@ export function VendorsListToolbar({
|
|||
onAddVendor,
|
||||
}: VendorsListToolbarProps) {
|
||||
return (
|
||||
<Stack
|
||||
direction={{ xs: "column", md: "row" }}
|
||||
spacing={2}
|
||||
sx={{
|
||||
alignItems: { xs: "stretch", md: "center" },
|
||||
justifyContent: "space-between",
|
||||
}}
|
||||
>
|
||||
<Stack direction="row" spacing={2} sx={{ alignItems: "baseline" }}>
|
||||
<Typography variant="h5" component="h1">
|
||||
Vendors / Technicians
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ color: "text.secondary" }}>
|
||||
{globalCount} vendor entries · {activeCount} active
|
||||
</Typography>
|
||||
{isFetching && !isLoading && <CircularProgress size={16} />}
|
||||
</Stack>
|
||||
|
||||
<Stack
|
||||
direction={{ xs: "column", sm: "row" }}
|
||||
spacing={2}
|
||||
sx={{ alignItems: { xs: "stretch", sm: "center" } }}
|
||||
>
|
||||
<TextField
|
||||
size="small"
|
||||
value={search}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
placeholder="Search name, company, trade..."
|
||||
className="min-w-[260px]"
|
||||
/>
|
||||
<Button
|
||||
variant="outlined"
|
||||
onClick={onOpenFilters}
|
||||
startIcon={<FilterListIcon />}
|
||||
aria-label="Open vendor filters"
|
||||
>
|
||||
Filters
|
||||
{appliedFilterCount > 0 && (
|
||||
<Chip size="small" color="primary" label={appliedFilterCount} sx={{ ml: 1 }} />
|
||||
<PageHeader
|
||||
surface
|
||||
className="-mx-4 -mt-4"
|
||||
title="Vendors / Technicians"
|
||||
subtitle={`${globalCount} technicians · ${activeCount} active`}
|
||||
actions={
|
||||
<>
|
||||
<SearchInput
|
||||
value={search}
|
||||
onChange={onSearchChange}
|
||||
placeholder="Search name, company, trade…"
|
||||
aria-label="Search vendors"
|
||||
fullWidth
|
||||
className="w-full md:w-56"
|
||||
inputClassName="h-8 py-0 text-[13px]"
|
||||
/>
|
||||
<ToolbarButton
|
||||
variant="outline"
|
||||
icon={<SlidersHorizontal size={16} />}
|
||||
onClick={onOpenFilters}
|
||||
aria-label="Open vendor filters"
|
||||
badge={appliedFilterCount}
|
||||
className="min-w-[88.609375px] flex-1 text-[13px] md:w-[88.609375px] md:flex-none"
|
||||
>
|
||||
Filters
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
variant="primary"
|
||||
icon={<Plus size={16} />}
|
||||
onClick={onAddVendor}
|
||||
className="min-w-[115.546875px] flex-1 border-0 px-3 text-[13px] md:w-[115.546875px] md:flex-none"
|
||||
>
|
||||
Add Vendor
|
||||
</ToolbarButton>
|
||||
{isFetching && !isLoading && (
|
||||
<CircularProgress size={14} aria-label="Refreshing vendors" role="status" />
|
||||
)}
|
||||
</Button>
|
||||
<Button variant="contained" onClick={onAddVendor}>
|
||||
+ Add Vendor
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -90,16 +80,21 @@ interface AppliedChipEntry {
|
|||
|
||||
interface VendorAppliedFiltersBarProps {
|
||||
chips: AppliedChipEntry[];
|
||||
resultCount: number;
|
||||
onClearAll: () => void;
|
||||
}
|
||||
|
||||
export function VendorAppliedFiltersBar({ chips, onClearAll }: VendorAppliedFiltersBarProps) {
|
||||
export function VendorAppliedFiltersBar({
|
||||
chips,
|
||||
resultCount,
|
||||
onClearAll,
|
||||
}: VendorAppliedFiltersBarProps) {
|
||||
if (chips.length === 0) return null;
|
||||
return (
|
||||
<Stack direction="row" spacing={1} className="flex flex-wrap items-center">
|
||||
<Typography variant="caption" sx={{ color: "text.secondary" }}>
|
||||
Applied:
|
||||
</Typography>
|
||||
<Text variant="caption" tone="muted">
|
||||
{resultCount} {resultCount === 1 ? "technician" : "technicians"} · filtered by
|
||||
</Text>
|
||||
{chips.map((chip) => (
|
||||
<Chip
|
||||
key={chip.key}
|
||||
|
|
@ -146,23 +141,31 @@ export function VendorsListFooter({
|
|||
sx={{
|
||||
alignItems: { xs: "stretch", sm: "center" },
|
||||
justifyContent: "space-between",
|
||||
minHeight: 33.5,
|
||||
mx: -2,
|
||||
px: 2,
|
||||
backgroundColor: "var(--color-bg-surface)",
|
||||
}}
|
||||
>
|
||||
<Typography variant="body2" sx={{ color: "text.secondary" }}>
|
||||
<Text variant="caption" as="span" sx={{ color: "#6b7a96", fontSize: 11, lineHeight: 1.5 }}>
|
||||
{totalCount} {isActive ? "active" : "inactive"}{" "}
|
||||
{totalCount === 1 ? "vendor entry" : "vendor entries"}
|
||||
{totalCount === 1 ? "technician" : "technicians"}
|
||||
{isFiltered && " · filtered"}
|
||||
{` · ${activeCount} active · ${inactiveCount} inactive`}
|
||||
</Typography>
|
||||
<TablePagination
|
||||
component="div"
|
||||
count={totalCount}
|
||||
page={page}
|
||||
onPageChange={(_e, nextPage) => onPageChange(nextPage)}
|
||||
rowsPerPage={pageSize}
|
||||
onRowsPerPageChange={(e) => onPageSizeChange(Number(e.target.value))}
|
||||
rowsPerPageOptions={[12, 24, 48]}
|
||||
/>
|
||||
</Text>
|
||||
<Text variant="caption" as="span" sx={{ color: "#6b7a96", fontSize: 11, lineHeight: 1.5 }}>
|
||||
{activeCount} active · {inactiveCount} inactive
|
||||
</Text>
|
||||
{totalCount > pageSize && (
|
||||
<TablePagination
|
||||
component="div"
|
||||
count={totalCount}
|
||||
page={page}
|
||||
onPageChange={(_e, nextPage) => onPageChange(nextPage)}
|
||||
rowsPerPage={pageSize}
|
||||
onRowsPerPageChange={(e) => onPageSizeChange(Number(e.target.value))}
|
||||
rowsPerPageOptions={[24, 48, 96]}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
import { type KeyboardEvent, type MouseEvent } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutlined";
|
||||
import SearchOffOutlinedIcon from "@mui/icons-material/SearchOffOutlined";
|
||||
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
|
||||
import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
|
||||
import {
|
||||
Avatar,
|
||||
Chip,
|
||||
Box,
|
||||
CircularProgress,
|
||||
IconButton,
|
||||
Link,
|
||||
|
|
@ -18,8 +17,8 @@ import {
|
|||
TableHead,
|
||||
TableRow,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import type { VendorListItem } from "@/domain/vendors/types/vendor";
|
||||
|
||||
const TABLE_COLUMNS = [
|
||||
|
|
@ -30,9 +29,6 @@ const TABLE_COLUMNS = [
|
|||
"Phone",
|
||||
"Email",
|
||||
"Total Jobs",
|
||||
"Status",
|
||||
"View",
|
||||
"Edit",
|
||||
] as const;
|
||||
|
||||
function getInitials(name: string): string {
|
||||
|
|
@ -54,19 +50,34 @@ function stopPropagation(event: MouseEvent): void {
|
|||
event.stopPropagation();
|
||||
}
|
||||
|
||||
function VendorStatus({ isActive }: { isActive: boolean }) {
|
||||
return (
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: "center", pl: 1 }}>
|
||||
<Box
|
||||
component="span"
|
||||
sx={{
|
||||
width: 6,
|
||||
height: 6,
|
||||
borderRadius: "9999px",
|
||||
backgroundColor: isActive ? "success.main" : "text.secondary",
|
||||
}}
|
||||
/>
|
||||
<Text variant="description">{isActive ? "Active" : "Inactive"}</Text>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
interface VendorTableRowProps {
|
||||
row: VendorListItem;
|
||||
onOpenDetail: (row: VendorListItem) => void;
|
||||
onOpenDeactivation: (row: VendorListItem) => void;
|
||||
onOpenEdit: (row: VendorListItem) => void;
|
||||
}
|
||||
|
||||
function VendorTableRow({ row, onOpenDetail, onOpenDeactivation }: VendorTableRowProps) {
|
||||
const navigate = useNavigate();
|
||||
function VendorTableRow({ row, onOpenDetail, onOpenEdit }: VendorTableRowProps) {
|
||||
const trades = splitTrades(row.tradeSpecialties);
|
||||
const primaryTrade = trades[0] ?? "—";
|
||||
const extraTrades = trades.length > 1 ? trades.length - 1 : 0;
|
||||
const locationText = [row.city, row.state].filter(Boolean).join(", ") || "—";
|
||||
const hasVendorId = row.id != null;
|
||||
const rowKey = String(row.id ?? `company-${row.companyId ?? ""}`);
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
|
|
@ -88,37 +99,62 @@ function VendorTableRow({ row, onOpenDetail, onOpenDeactivation }: VendorTableRo
|
|||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
<TableCell>
|
||||
<Typography className="font-semibold">{row.companyName || "—"}</Typography>
|
||||
<Text variant="description" sx={{ color: "var(--color-foreground)" }}>
|
||||
{row.companyName || "—"}
|
||||
</Text>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: "center" }}>
|
||||
<Stack direction="row" spacing={1.25} sx={{ alignItems: "center" }}>
|
||||
<Avatar
|
||||
sx={{
|
||||
width: 28,
|
||||
height: 28,
|
||||
fontSize: 12,
|
||||
backgroundColor: "var(--accent, #1976d2)",
|
||||
backgroundColor: "var(--color-bg-muted)",
|
||||
color: "var(--color-primary)",
|
||||
fontSize: 10.5,
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
{getInitials(row.contactName)}
|
||||
</Avatar>
|
||||
<Typography variant="body2">{row.contactName || "—"}</Typography>
|
||||
<Text variant="description" sx={{ color: "var(--color-foreground)" }}>
|
||||
{row.contactName || "—"}
|
||||
</Text>
|
||||
</Stack>
|
||||
</TableCell>
|
||||
<TableCell>{locationText}</TableCell>
|
||||
<TableCell>
|
||||
<TableCell sx={{ color: "var(--color-muted-foreground)" }}>{locationText}</TableCell>
|
||||
<TableCell sx={{ color: "var(--color-muted-foreground)" }}>
|
||||
{primaryTrade === "—" ? (
|
||||
"—"
|
||||
) : (
|
||||
<Stack direction="row" spacing={0.5} sx={{ alignItems: "center" }}>
|
||||
<span>{primaryTrade}</span>
|
||||
{extraTrades > 0 && <Chip size="small" label={`+${extraTrades}`} />}
|
||||
{extraTrades > 0 && (
|
||||
<Box
|
||||
component="span"
|
||||
sx={{
|
||||
borderRadius: "9999px",
|
||||
backgroundColor: "var(--color-bg-muted)",
|
||||
px: 0.75,
|
||||
py: 0.25,
|
||||
fontSize: 10.5,
|
||||
lineHeight: 1.2,
|
||||
}}
|
||||
>
|
||||
+{extraTrades}
|
||||
</Box>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TableCell sx={{ color: "var(--color-muted-foreground)" }}>
|
||||
{row.phone ? (
|
||||
<Link href={`tel:${row.phone}`} underline="hover" onClick={stopPropagation}>
|
||||
<Link
|
||||
href={`tel:${row.phone}`}
|
||||
underline="hover"
|
||||
color="inherit"
|
||||
onClick={stopPropagation}
|
||||
>
|
||||
{row.phone}
|
||||
</Link>
|
||||
) : (
|
||||
|
|
@ -127,71 +163,53 @@ function VendorTableRow({ row, onOpenDetail, onOpenDeactivation }: VendorTableRo
|
|||
</TableCell>
|
||||
<TableCell>
|
||||
{row.email ? (
|
||||
<Link href={`mailto:${row.email}`} underline="hover" onClick={stopPropagation}>
|
||||
<Link
|
||||
href={`mailto:${row.email}`}
|
||||
underline="hover"
|
||||
sx={{ color: "#6b7a96" }}
|
||||
onClick={stopPropagation}
|
||||
>
|
||||
{row.email}
|
||||
</Link>
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>{row.totalJobs ?? 0}</TableCell>
|
||||
<TableCell align="center">{row.totalJobs ?? 0}</TableCell>
|
||||
<TableCell>
|
||||
<Chip
|
||||
size="small"
|
||||
label={row.isActive ? "Active" : "Inactive"}
|
||||
color={row.isActive ? "success" : "default"}
|
||||
/>
|
||||
<VendorStatus isActive={row.isActive} />
|
||||
</TableCell>
|
||||
<TableCell align="center">
|
||||
<Tooltip title="View details">
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label={`View vendor ${row.companyName}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onOpenDetail(row);
|
||||
}}
|
||||
>
|
||||
<VisibilityOutlinedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</TableCell>
|
||||
<TableCell align="center">
|
||||
<TableCell align="right">
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={0.5}
|
||||
sx={{ alignItems: "center", justifyContent: "center" }}
|
||||
className="vendor-row-actions"
|
||||
sx={{ alignItems: "center", justifyContent: "flex-end" }}
|
||||
>
|
||||
<Tooltip title="View details">
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label={`View vendor ${row.companyName}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onOpenDetail(row);
|
||||
}}
|
||||
>
|
||||
<VisibilityOutlinedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Tooltip title="Edit">
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label={`Edit vendor ${row.companyName}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
navigate(
|
||||
row.id != null
|
||||
? `/vendors/edit/${row.id}`
|
||||
: `/vendors/company/${row.companyId ?? ""}`,
|
||||
);
|
||||
onOpenEdit(row);
|
||||
}}
|
||||
>
|
||||
<EditOutlinedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
{hasVendorId && row.isActive && (
|
||||
<Tooltip title="Deactivate">
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label="Deactivate vendor"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onOpenDeactivation(row);
|
||||
}}
|
||||
>
|
||||
<DeleteOutlineIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Stack>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
|
@ -200,50 +218,118 @@ function VendorTableRow({ row, onOpenDetail, onOpenDeactivation }: VendorTableRo
|
|||
|
||||
interface VendorsTableProps {
|
||||
rows: VendorListItem[];
|
||||
isActive: boolean;
|
||||
isFiltered: boolean;
|
||||
isLoading: boolean;
|
||||
showError: boolean;
|
||||
onOpenDetail: (row: VendorListItem) => void;
|
||||
onOpenDeactivation: (row: VendorListItem) => void;
|
||||
onOpenEdit: (row: VendorListItem) => void;
|
||||
}
|
||||
|
||||
export function VendorsTable({
|
||||
rows,
|
||||
isActive,
|
||||
isFiltered,
|
||||
isLoading,
|
||||
showError,
|
||||
onOpenDetail,
|
||||
onOpenDeactivation,
|
||||
onOpenEdit,
|
||||
}: VendorsTableProps) {
|
||||
const showEmptyRow = !isLoading && !showError && rows.length === 0;
|
||||
const columnCount = TABLE_COLUMNS.length + 2;
|
||||
|
||||
return (
|
||||
<TableContainer component={Paper} variant="outlined" sx={{ overflowX: "auto" }}>
|
||||
<Table size="small" sx={{ minWidth: 960 }}>
|
||||
<TableContainer
|
||||
component={Paper}
|
||||
variant="outlined"
|
||||
sx={{
|
||||
mt: 2,
|
||||
mb: 2,
|
||||
flex: "1 1 auto",
|
||||
overflow: "auto",
|
||||
borderRadius: 1.5,
|
||||
fontSize: 13,
|
||||
}}
|
||||
>
|
||||
<Table
|
||||
size="small"
|
||||
stickyHeader
|
||||
sx={{
|
||||
minWidth: 1550,
|
||||
tableLayout: "fixed",
|
||||
"& .MuiTableCell-head": {
|
||||
backgroundColor: "var(--color-bg-muted)",
|
||||
color: "var(--color-foreground)",
|
||||
fontSize: 10.5,
|
||||
fontWeight: 700,
|
||||
letterSpacing: "0.06em",
|
||||
lineHeight: "24px",
|
||||
px: 1.75,
|
||||
py: 1.375,
|
||||
textTransform: "uppercase",
|
||||
whiteSpace: "nowrap",
|
||||
},
|
||||
"& .MuiTableCell-body": {
|
||||
fontSize: 13,
|
||||
px: 1.5,
|
||||
py: 1,
|
||||
height: 52,
|
||||
lineHeight: 1.43,
|
||||
whiteSpace: "nowrap",
|
||||
},
|
||||
"& .vendor-row-actions": {
|
||||
opacity: { xs: 1, md: 0 },
|
||||
transition: "opacity 120ms ease",
|
||||
},
|
||||
"& .MuiTableRow-root:hover .vendor-row-actions, & .MuiTableRow-root:focus-within .vendor-row-actions":
|
||||
{
|
||||
opacity: 1,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<colgroup>
|
||||
<col style={{ width: 196.34375 }} />
|
||||
<col style={{ width: 207.25 }} />
|
||||
<col style={{ width: 152.703125 }} />
|
||||
<col style={{ width: 218.15625 }} />
|
||||
<col style={{ width: 152.703125 }} />
|
||||
<col style={{ width: 251.90625 }} />
|
||||
<col style={{ width: 109.078125 }} />
|
||||
<col style={{ width: 119.984375 }} />
|
||||
<col style={{ width: 141.875 }} />
|
||||
</colgroup>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
{TABLE_COLUMNS.map((column) => (
|
||||
<TableCell
|
||||
key={column}
|
||||
align={column === "View" || column === "Edit" ? "center" : "left"}
|
||||
className="font-semibold"
|
||||
>
|
||||
<TableCell key={column} align={column === "Total Jobs" ? "center" : "left"}>
|
||||
{column}
|
||||
</TableCell>
|
||||
))}
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell align="right" aria-label="Vendor actions" />
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{isLoading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={TABLE_COLUMNS.length} align="center" className="py-10">
|
||||
<TableCell colSpan={columnCount} align="center" className="py-10">
|
||||
<CircularProgress size={28} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : showEmptyRow ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={TABLE_COLUMNS.length} align="center" className="py-10">
|
||||
<Typography sx={{ color: "text.secondary" }}>
|
||||
No vendors match the current filters.
|
||||
</Typography>
|
||||
<TableCell colSpan={columnCount} align="center" className="py-10">
|
||||
<Stack spacing={1} sx={{ alignItems: "center" }}>
|
||||
<SearchOffOutlinedIcon sx={{ color: "text.secondary", fontSize: 32 }} />
|
||||
<Text variant="description" className="font-semibold">
|
||||
{`No ${isActive ? "active" : "inactive"} technicians found`}
|
||||
</Text>
|
||||
<Text variant="caption" tone="muted">
|
||||
{isFiltered
|
||||
? "Try a different search, or add a new vendor."
|
||||
: "Add a vendor to get started."}
|
||||
</Text>
|
||||
</Stack>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
|
|
@ -252,7 +338,7 @@ export function VendorsTable({
|
|||
key={String(row.id ?? `company-${row.companyId ?? ""}`)}
|
||||
row={row}
|
||||
onOpenDetail={onOpenDetail}
|
||||
onOpenDeactivation={onOpenDeactivation}
|
||||
onOpenEdit={onOpenEdit}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
|
|
|
|||
125
src/app/(protected)/vendors/index.tsx
vendored
|
|
@ -23,16 +23,91 @@ interface AppliedChip {
|
|||
label: string;
|
||||
}
|
||||
|
||||
function statusTabLabel(label: string, count: number) {
|
||||
return (
|
||||
<Box className="flex items-center gap-2">
|
||||
<Box component="span">{label}</Box>
|
||||
<Box
|
||||
component="span"
|
||||
className="min-w-5 rounded-full px-1.5 py-0.5 text-[10px] font-semibold leading-none"
|
||||
sx={{ backgroundColor: "action.hover", color: "text.secondary" }}
|
||||
>
|
||||
{count}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function VendorStatusTabs({
|
||||
isActive,
|
||||
activeCount,
|
||||
inactiveCount,
|
||||
onChange,
|
||||
}: {
|
||||
isActive: boolean;
|
||||
activeCount: number;
|
||||
inactiveCount: number;
|
||||
onChange: (isActive: boolean) => void;
|
||||
}) {
|
||||
return (
|
||||
<Tabs
|
||||
value={isActive ? "active" : "inactive"}
|
||||
onChange={(_event, value: "active" | "inactive") => onChange(value === "active")}
|
||||
aria-label="Vendor status"
|
||||
sx={{
|
||||
minHeight: 36,
|
||||
flexShrink: 0,
|
||||
borderBottom: (theme) => `1px solid ${theme.palette.divider}`,
|
||||
backgroundColor: "var(--color-bg-surface)",
|
||||
mx: -2,
|
||||
px: 1.5,
|
||||
"& .MuiTab-root": {
|
||||
minHeight: 36,
|
||||
px: 2,
|
||||
py: 0,
|
||||
fontSize: 13,
|
||||
fontWeight: 500,
|
||||
textTransform: "none",
|
||||
},
|
||||
"& .MuiTab-root:first-of-type": { width: 102.84375 },
|
||||
"& .Mui-selected": { fontWeight: 600 },
|
||||
"& .MuiTabs-indicator": { height: 2 },
|
||||
}}
|
||||
>
|
||||
<Tab
|
||||
value="active"
|
||||
label={statusTabLabel("Active", activeCount)}
|
||||
aria-label={`Active (${activeCount})`}
|
||||
/>
|
||||
<Tab
|
||||
value="inactive"
|
||||
label={statusTabLabel("Inactive", inactiveCount)}
|
||||
aria-label={`Inactive (${inactiveCount})`}
|
||||
/>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
|
||||
function describeChips(
|
||||
filters: VendorFilters,
|
||||
jobBucketLabels: Map<string, string>,
|
||||
): AppliedChip[] {
|
||||
const chips: AppliedChip[] = [];
|
||||
filters.companies.forEach((value) => chips.push({ category: "companies", value, label: value }));
|
||||
filters.trades.forEach((value) => chips.push({ category: "trades", value, label: value }));
|
||||
filters.locations.forEach((value) => chips.push({ category: "locations", value, label: value }));
|
||||
filters.companies.forEach((value) =>
|
||||
chips.push({ category: "companies", value, label: `Company: ${value}` }),
|
||||
);
|
||||
filters.trades.forEach((value) =>
|
||||
chips.push({ category: "trades", value, label: `Trade: ${value}` }),
|
||||
);
|
||||
filters.locations.forEach((value) =>
|
||||
chips.push({ category: "locations", value, label: `Location: ${value}` }),
|
||||
);
|
||||
filters.jobBuckets.forEach((value) =>
|
||||
chips.push({ category: "jobBuckets", value, label: jobBucketLabels.get(value) ?? value }),
|
||||
chips.push({
|
||||
category: "jobBuckets",
|
||||
value,
|
||||
label: `Total Jobs: ${jobBucketLabels.get(value) ?? value}`,
|
||||
}),
|
||||
);
|
||||
return chips;
|
||||
}
|
||||
|
|
@ -42,7 +117,12 @@ export default function VendorsListPage() {
|
|||
const [filtersOpen, setFiltersOpen] = useState(false);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [detailTarget, setDetailTarget] = useState<VendorListItem | null>(null);
|
||||
const deactivation = useVendorDeactivation();
|
||||
const [detailStartsInEdit, setDetailStartsInEdit] = useState(false);
|
||||
const closeDetail = () => {
|
||||
setDetailTarget(null);
|
||||
setDetailStartsInEdit(false);
|
||||
};
|
||||
const deactivation = useVendorDeactivation(closeDetail);
|
||||
|
||||
const { data: facets } = useVendorFacets(filters.isActive);
|
||||
const { data, isLoading, isFetching, error } = useVendorsList(filters.listParams);
|
||||
|
|
@ -61,7 +141,7 @@ export default function VendorsListPage() {
|
|||
const appliedChips = describeChips(filters.appliedFilters, jobBucketLabels);
|
||||
|
||||
return (
|
||||
<Box className="flex flex-col gap-4 p-4">
|
||||
<Box className="flex h-full flex-col overflow-hidden px-4 pt-4 pb-0">
|
||||
<VendorsListToolbar
|
||||
globalCount={activeCount + inactiveCount}
|
||||
activeCount={activeCount}
|
||||
|
|
@ -74,18 +154,15 @@ export default function VendorsListPage() {
|
|||
onAddVendor={() => setCreateOpen(true)}
|
||||
/>
|
||||
|
||||
<Tabs
|
||||
value={filters.isActive ? "active" : "inactive"}
|
||||
onChange={(_event, value: "active" | "inactive") =>
|
||||
filters.setIsActiveWithReset(value === "active")
|
||||
}
|
||||
aria-label="Vendor status"
|
||||
>
|
||||
<Tab value="active" label={`Active (${activeCount})`} />
|
||||
<Tab value="inactive" label={`Inactive (${inactiveCount})`} />
|
||||
</Tabs>
|
||||
<VendorStatusTabs
|
||||
isActive={filters.isActive}
|
||||
activeCount={activeCount}
|
||||
inactiveCount={inactiveCount}
|
||||
onChange={filters.setIsActiveWithReset}
|
||||
/>
|
||||
|
||||
<VendorAppliedFiltersBar
|
||||
resultCount={totalCount}
|
||||
chips={appliedChips.map((chip) => ({
|
||||
key: `${chip.category}-${chip.value}`,
|
||||
label: chip.label,
|
||||
|
|
@ -102,10 +179,18 @@ export default function VendorsListPage() {
|
|||
|
||||
<VendorsTable
|
||||
rows={rows}
|
||||
isActive={filters.isActive}
|
||||
isFiltered={appliedChips.length > 0 || Boolean(filters.debouncedSearch)}
|
||||
isLoading={isLoading}
|
||||
showError={Boolean(error)}
|
||||
onOpenDetail={setDetailTarget}
|
||||
onOpenDeactivation={deactivation.open}
|
||||
onOpenDetail={(row) => {
|
||||
setDetailStartsInEdit(false);
|
||||
setDetailTarget(row);
|
||||
}}
|
||||
onOpenEdit={(row) => {
|
||||
setDetailStartsInEdit(true);
|
||||
setDetailTarget(row);
|
||||
}}
|
||||
/>
|
||||
|
||||
<VendorsListFooter
|
||||
|
|
@ -133,7 +218,9 @@ export default function VendorsListPage() {
|
|||
<VendorDetailDrawer
|
||||
open={Boolean(detailTarget)}
|
||||
vendor={detailTarget}
|
||||
onClose={() => setDetailTarget(null)}
|
||||
startInEdit={detailStartsInEdit}
|
||||
onRequestDeactivation={deactivation.open}
|
||||
onClose={closeDetail}
|
||||
/>
|
||||
|
||||
<VendorDeactivationDialog
|
||||
|
|
|
|||
|
|
@ -8,36 +8,18 @@ import {
|
|||
formatVendorPortalDateTime,
|
||||
vendorPortalStatusClass,
|
||||
} from "@/domain/vendor-portal/lib/status-helpers";
|
||||
import type { VendorPortalDispatchSummary } from "@/domain/vendor-portal/types/vendor-portal";
|
||||
import {
|
||||
VENDOR_PORTAL_DISPATCH_FILTERS,
|
||||
applyVendorPortalDispatchFilter,
|
||||
getVendorPortalDispatchFilter,
|
||||
type VendorPortalDispatchFilterKey,
|
||||
} from "@/domain/vendor-portal/lib/dispatch-filters";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
|
||||
const FILTERS = [
|
||||
{
|
||||
key: "open",
|
||||
label: "Open",
|
||||
match: (dispatch: VendorPortalDispatchSummary) =>
|
||||
dispatch.status !== "Completed" &&
|
||||
dispatch.status !== "Verified" &&
|
||||
dispatch.status !== "Cancelled",
|
||||
},
|
||||
{
|
||||
key: "completed",
|
||||
label: "Completed",
|
||||
match: (dispatch: VendorPortalDispatchSummary) =>
|
||||
dispatch.status === "Completed" || dispatch.status === "Verified",
|
||||
},
|
||||
{
|
||||
key: "cancelled",
|
||||
label: "Cancelled",
|
||||
match: (dispatch: VendorPortalDispatchSummary) => dispatch.status === "Cancelled",
|
||||
},
|
||||
{ key: "all", label: "All", match: () => true },
|
||||
] as const;
|
||||
|
||||
export default function VendorPortalDashboardPage() {
|
||||
const { token } = useVendorPortal();
|
||||
const navigate = useNavigate();
|
||||
const [filter, setFilter] = useState<(typeof FILTERS)[number]["key"]>("open");
|
||||
const [filter, setFilter] = useState<VendorPortalDispatchFilterKey>("open");
|
||||
|
||||
const {
|
||||
data: dispatches = [],
|
||||
|
|
@ -49,8 +31,11 @@ export default function VendorPortalDashboardPage() {
|
|||
enabled: Boolean(token),
|
||||
});
|
||||
|
||||
const activeFilter = FILTERS.find((item) => item.key === filter) ?? FILTERS[0];
|
||||
const filtered = useMemo(() => dispatches.filter(activeFilter.match), [dispatches, activeFilter]);
|
||||
const activeFilter = getVendorPortalDispatchFilter(filter);
|
||||
const filtered = useMemo(
|
||||
() => applyVendorPortalDispatchFilter(dispatches, activeFilter),
|
||||
[dispatches, activeFilter],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
|
@ -60,7 +45,7 @@ export default function VendorPortalDashboardPage() {
|
|||
Active dispatches and work orders assigned to your company.
|
||||
</div>
|
||||
<div className="vp-actions" style={{ marginTop: 0 }}>
|
||||
{FILTERS.map((item) => (
|
||||
{VENDOR_PORTAL_DISPATCH_FILTERS.map((item) => (
|
||||
<button
|
||||
key={item.key}
|
||||
type="button"
|
||||
|
|
|
|||
|
|
@ -4,8 +4,10 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|||
import { Text } from "@/components/ui/text";
|
||||
import { DispatchDetailSections } from "@/app/v/[token]/dispatch/_components/dispatch-detail-sections";
|
||||
import { DispatchSummaryCard } from "@/app/v/[token]/dispatch/_components/dispatch-summary-card";
|
||||
import { RefuseDispatchDialog } from "@/app/v/[token]/dispatch/_components/refuse-dispatch-dialog";
|
||||
import { useVendorPortal } from "@/app/v/_components/vendor-portal-context";
|
||||
import { vendorPortalApi } from "@/domain/vendor-portal/api/vendor-portal-api";
|
||||
import { isVendorPortalLockedStatus } from "@/domain/vendor-portal/lib/status-helpers";
|
||||
import type { VendorPortalDispatchDetail } from "@/domain/vendor-portal/types/vendor-portal";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
|
||||
|
|
@ -16,6 +18,7 @@ export default function VendorPortalDispatchPage() {
|
|||
const queryClient = useQueryClient();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [actionError, setActionError] = useState("");
|
||||
const [refuseOpen, setRefuseOpen] = useState(false);
|
||||
|
||||
const { data, isLoading, error, refetch } = useQuery({
|
||||
queryKey: queryKeys.vendorPortal.dispatch(token, dispatchId),
|
||||
|
|
@ -74,7 +77,7 @@ export default function VendorPortalDispatchPage() {
|
|||
|
||||
if (!data) return null;
|
||||
|
||||
const locked = data.status === "Verified" || data.status === "Cancelled";
|
||||
const locked = isVendorPortalLockedStatus(data.status);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
|
@ -84,6 +87,7 @@ export default function VendorPortalDispatchPage() {
|
|||
locked={locked}
|
||||
busy={busy}
|
||||
onAccept={() => void runAction(() => vendorPortalApi.accept(token, dispatchId))}
|
||||
onRefuse={() => setRefuseOpen(true)}
|
||||
onStart={() =>
|
||||
void runAction(() => vendorPortalApi.changeStatus(token, dispatchId, "In Progress"))
|
||||
}
|
||||
|
|
@ -107,6 +111,13 @@ export default function VendorPortalDispatchPage() {
|
|||
refresh={refresh}
|
||||
updateLocal={updateLocal}
|
||||
/>
|
||||
|
||||
<RefuseDispatchDialog
|
||||
open={refuseOpen}
|
||||
dispatchId={dispatchId}
|
||||
onClose={() => setRefuseOpen(false)}
|
||||
onRefused={() => setActionError("")}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -76,6 +76,7 @@ export function DispatchDetailSections({
|
|||
existing={data.signoffs ?? []}
|
||||
signoffType="customer"
|
||||
nameLabel="Customer name"
|
||||
submissionLocked={locked}
|
||||
onAdded={() => void refresh()}
|
||||
/>
|
||||
</div>
|
||||
|
|
@ -88,6 +89,7 @@ export function DispatchDetailSections({
|
|||
existing={data.signoffs ?? []}
|
||||
signoffType="vendor"
|
||||
nameLabel="Your name"
|
||||
submissionLocked={locked}
|
||||
onAdded={() => void refresh()}
|
||||
/>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,166 @@
|
|||
import { Text } from "@/components/ui/text";
|
||||
import { formatVendorPortalDateTime } from "@/domain/vendor-portal/lib/status-helpers";
|
||||
import type { VendorPortalDispatchDetail } from "@/domain/vendor-portal/types/vendor-portal";
|
||||
|
||||
type DispatchSnapshotDetailsProps = {
|
||||
data: VendorPortalDispatchDetail;
|
||||
locked: boolean;
|
||||
};
|
||||
|
||||
function resolveCanonicalService(workOrder: VendorPortalDispatchDetail["workOrder"]): string {
|
||||
if (workOrder?.service) {
|
||||
return workOrder.service;
|
||||
}
|
||||
|
||||
return [workOrder?.trade, workOrder?.subTrade].filter(Boolean).join(" · ");
|
||||
}
|
||||
|
||||
function DispatchCommercialDetails({ data }: Pick<DispatchSnapshotDetailsProps, "data">) {
|
||||
const service = resolveCanonicalService(data.workOrder);
|
||||
|
||||
return (
|
||||
<div style={{ marginTop: 12 }}>
|
||||
{data.workOrder != null && Boolean(data.workOrder.internalWONumber) && (
|
||||
<div className="vp-row">
|
||||
<strong>WO #</strong>
|
||||
<span>{data.workOrder.internalWONumber}</span>
|
||||
</div>
|
||||
)}
|
||||
{Boolean(service) && (
|
||||
<div className="vp-row">
|
||||
<strong>Service</strong>
|
||||
<span>{service}</span>
|
||||
</div>
|
||||
)}
|
||||
{Boolean(data.poNumber) && (
|
||||
<div className="vp-row">
|
||||
<strong>PO #</strong>
|
||||
<span>{data.poNumber}</span>
|
||||
</div>
|
||||
)}
|
||||
{data.nteAmount != null && (
|
||||
<div className="vp-row">
|
||||
<strong>NTE</strong>
|
||||
<span>${Number(data.nteAmount).toFixed(2)}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="vp-row">
|
||||
<strong>Invoice</strong>
|
||||
<span>
|
||||
{data.invoiceStatus || "Not Submitted"}
|
||||
{data.invoiceNumber ? ` · ${data.invoiceNumber}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="vp-row">
|
||||
<strong>Payment</strong>
|
||||
<span>{data.paymentStatus || "Unavailable"}</span>
|
||||
</div>
|
||||
{Boolean(data.scheduledDate) && (
|
||||
<div className="vp-row">
|
||||
<strong>Scheduled</strong>
|
||||
<span>{formatVendorPortalDateTime(data.scheduledDate)}</span>
|
||||
</div>
|
||||
)}
|
||||
{Boolean(data.statusUpdatedAt) && (
|
||||
<div className="vp-row">
|
||||
<strong>Status updated</strong>
|
||||
<span>{formatVendorPortalDateTime(data.statusUpdatedAt)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DispatchLocationDetails({ data }: Pick<DispatchSnapshotDetailsProps, "data">) {
|
||||
if (data.location == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const address = [
|
||||
data.location.address,
|
||||
data.location.city,
|
||||
data.location.state,
|
||||
data.location.zipCode,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
|
||||
return (
|
||||
<>
|
||||
<Text variant="heading" sx={{ marginTop: 2 }}>
|
||||
Location
|
||||
</Text>
|
||||
{Boolean(data.workOrder?.siteCode) && (
|
||||
<div className="vp-row">
|
||||
<strong>Site code</strong>
|
||||
<span>{data.workOrder?.siteCode}</span>
|
||||
</div>
|
||||
)}
|
||||
<div>{data.location.name}</div>
|
||||
<div className="vp-muted">{address}</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DispatcherContactDetails({ data }: Pick<DispatchSnapshotDetailsProps, "data">) {
|
||||
const contact = data.dispatcherContact;
|
||||
if (!contact || (!contact.name && !contact.email && !contact.phone)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Text variant="heading" sx={{ marginTop: 2 }}>
|
||||
Dispatcher
|
||||
</Text>
|
||||
{Boolean(contact.name) && (
|
||||
<div className="vp-row">
|
||||
<strong>Name</strong>
|
||||
<span>{contact.name}</span>
|
||||
</div>
|
||||
)}
|
||||
{Boolean(contact.email) && (
|
||||
<div className="vp-row">
|
||||
<strong>Email</strong>
|
||||
<span>
|
||||
<a href={`mailto:${contact.email}`}>{contact.email}</a>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{Boolean(contact.phone) && (
|
||||
<div className="vp-row">
|
||||
<strong>Phone</strong>
|
||||
<span>
|
||||
<a href={`tel:${contact.phone}`}>{contact.phone}</a>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function DispatchSnapshotDetails({ data, locked }: DispatchSnapshotDetailsProps) {
|
||||
const description = data.description || data.workOrder?.description;
|
||||
|
||||
return (
|
||||
<>
|
||||
<DispatchCommercialDetails data={data} />
|
||||
<DispatchLocationDetails data={data} />
|
||||
<DispatcherContactDetails data={data} />
|
||||
{locked && (
|
||||
<Text variant="feedback" className="vp-muted" sx={{ marginTop: 2 }}>
|
||||
This dispatch is {data.status.toLowerCase()} and locked to further changes. Comments
|
||||
remain open.
|
||||
</Text>
|
||||
)}
|
||||
{Boolean(description) && (
|
||||
<>
|
||||
<Text variant="heading" sx={{ marginTop: 2 }}>
|
||||
Description
|
||||
</Text>
|
||||
<div>{description}</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ type DispatchStatusActionsProps = {
|
|||
locked: boolean;
|
||||
busy: boolean;
|
||||
onAccept: () => void;
|
||||
onRefuse: () => void;
|
||||
onStart: () => void;
|
||||
onComplete: () => void;
|
||||
onRequestCancel: () => void;
|
||||
|
|
@ -13,6 +14,7 @@ export function DispatchStatusActions({
|
|||
locked,
|
||||
busy,
|
||||
onAccept,
|
||||
onRefuse,
|
||||
onStart,
|
||||
onComplete,
|
||||
onRequestCancel,
|
||||
|
|
@ -20,9 +22,19 @@ export function DispatchStatusActions({
|
|||
return (
|
||||
<div className="vp-actions">
|
||||
{status === "Sent" && (
|
||||
<button type="button" className="vp-btn vp-btn-success" disabled={busy} onClick={onAccept}>
|
||||
Accept Dispatch
|
||||
</button>
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="vp-btn vp-btn-success"
|
||||
disabled={busy}
|
||||
onClick={onAccept}
|
||||
>
|
||||
Accept Dispatch
|
||||
</button>
|
||||
<button type="button" className="vp-btn vp-btn-warn" disabled={busy} onClick={onRefuse}>
|
||||
Refuse Dispatch
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{status === "Acknowledged" && (
|
||||
<button type="button" className="vp-btn vp-btn-primary" disabled={busy} onClick={onStart}>
|
||||
|
|
|
|||
|
|
@ -1,10 +1,8 @@
|
|||
import { Link } from "react-router";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import {
|
||||
formatVendorPortalDateTime,
|
||||
vendorPortalStatusClass,
|
||||
} from "@/domain/vendor-portal/lib/status-helpers";
|
||||
import { vendorPortalStatusClass } from "@/domain/vendor-portal/lib/status-helpers";
|
||||
import type { VendorPortalDispatchDetail } from "@/domain/vendor-portal/types/vendor-portal";
|
||||
import { DispatchSnapshotDetails } from "@/app/v/[token]/dispatch/_components/dispatch-snapshot-details";
|
||||
import { DispatchStatusActions } from "@/app/v/[token]/dispatch/_components/dispatch-status-actions";
|
||||
|
||||
type DispatchSummaryCardProps = {
|
||||
|
|
@ -13,6 +11,7 @@ type DispatchSummaryCardProps = {
|
|||
locked: boolean;
|
||||
busy: boolean;
|
||||
onAccept: () => void;
|
||||
onRefuse: () => void;
|
||||
onStart: () => void;
|
||||
onComplete: () => void;
|
||||
onRequestCancel: () => void;
|
||||
|
|
@ -24,6 +23,7 @@ export function DispatchSummaryCard({
|
|||
locked,
|
||||
busy,
|
||||
onAccept,
|
||||
onRefuse,
|
||||
onStart,
|
||||
onComplete,
|
||||
onRequestCancel,
|
||||
|
|
@ -43,77 +43,14 @@ export function DispatchSummaryCard({
|
|||
<span className={vendorPortalStatusClass(data.status)}>{data.status}</span>
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: 12 }}>
|
||||
{data.workOrder != null && Boolean(data.workOrder.internalWONumber) && (
|
||||
<div className="vp-row">
|
||||
<strong>WO #</strong>
|
||||
<span>{data.workOrder.internalWONumber}</span>
|
||||
</div>
|
||||
)}
|
||||
{Boolean(data.poNumber) && (
|
||||
<div className="vp-row">
|
||||
<strong>PO #</strong>
|
||||
<span>{data.poNumber}</span>
|
||||
</div>
|
||||
)}
|
||||
{data.nteAmount != null && (
|
||||
<div className="vp-row">
|
||||
<strong>NTE</strong>
|
||||
<span>${Number(data.nteAmount).toFixed(2)}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="vp-row">
|
||||
<strong>Invoice</strong>
|
||||
<span>
|
||||
{data.invoiceStatus || "Not Submitted"}
|
||||
{data.invoiceNumber ? ` · ${data.invoiceNumber}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="vp-row">
|
||||
<strong>Payment</strong>
|
||||
<span>{data.paymentStatus || "Unavailable"}</span>
|
||||
</div>
|
||||
{Boolean(data.scheduledDate) && (
|
||||
<div className="vp-row">
|
||||
<strong>Scheduled</strong>
|
||||
<span>{formatVendorPortalDateTime(data.scheduledDate)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{data.location != null && (
|
||||
<>
|
||||
<Text variant="heading" sx={{ marginTop: 2 }}>
|
||||
Location
|
||||
</Text>
|
||||
<div>{data.location.name}</div>
|
||||
<div className="vp-muted">
|
||||
{[
|
||||
data.location.address,
|
||||
data.location.city,
|
||||
data.location.state,
|
||||
data.location.zipCode,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(", ")}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{Boolean(data.description || data.workOrder?.description) && (
|
||||
<>
|
||||
<Text variant="heading" sx={{ marginTop: 2 }}>
|
||||
Description
|
||||
</Text>
|
||||
<div>{data.description || data.workOrder?.description}</div>
|
||||
</>
|
||||
)}
|
||||
<DispatchSnapshotDetails data={data} locked={locked} />
|
||||
|
||||
<DispatchStatusActions
|
||||
status={data.status}
|
||||
locked={locked}
|
||||
busy={busy}
|
||||
onAccept={onAccept}
|
||||
onRefuse={onRefuse}
|
||||
onStart={onStart}
|
||||
onComplete={onComplete}
|
||||
onRequestCancel={onRequestCancel}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,141 @@
|
|||
import { useEffect } from "react";
|
||||
import { useForm, useWatch } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { Dialog, DialogActions, DialogContent, DialogTitle } from "@mui/material";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import { useVendorPortal } from "@/app/v/_components/vendor-portal-context";
|
||||
import { vendorPortalApi } from "@/domain/vendor-portal/api/vendor-portal-api";
|
||||
import {
|
||||
REFUSE_REASON_MAX_LENGTH,
|
||||
refuseDispatchSchema,
|
||||
type RefuseDispatchValues,
|
||||
} from "@/domain/vendor-portal/schemas/refuse-dispatch-schema";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
import { guardDialogClose } from "@/lib/dialog-guard";
|
||||
|
||||
type RefuseDispatchDialogProps = {
|
||||
open: boolean;
|
||||
dispatchId: number;
|
||||
onClose: () => void;
|
||||
onRefused: () => void;
|
||||
};
|
||||
|
||||
export function RefuseDispatchDialog({
|
||||
open,
|
||||
dispatchId,
|
||||
onClose,
|
||||
onRefused,
|
||||
}: RefuseDispatchDialogProps) {
|
||||
const { token } = useVendorPortal();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
control,
|
||||
reset,
|
||||
formState: { errors },
|
||||
} = useForm<RefuseDispatchValues>({
|
||||
resolver: zodResolver(refuseDispatchSchema),
|
||||
mode: "onChange",
|
||||
defaultValues: { reason: "" },
|
||||
});
|
||||
|
||||
const reasonValue = useWatch({ control, name: "reason" }) ?? "";
|
||||
const isOverLimit = reasonValue.length > REFUSE_REASON_MAX_LENGTH;
|
||||
|
||||
const refuseMutation = useMutation({
|
||||
mutationFn: (values: RefuseDispatchValues) => {
|
||||
const trimmed = values.reason.trim();
|
||||
return vendorPortalApi.refuse(token, dispatchId, trimmed || undefined);
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.vendorPortal.dispatch(token, dispatchId),
|
||||
}),
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.vendorPortal.dispatches(token),
|
||||
}),
|
||||
]);
|
||||
onRefused();
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
|
||||
const { reset: resetMutation } = refuseMutation;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
reset({ reason: "" });
|
||||
resetMutation();
|
||||
}
|
||||
}, [open, reset, resetMutation]);
|
||||
|
||||
const submit = handleSubmit((values) => refuseMutation.mutate(values));
|
||||
const errorMessage = refuseMutation.error
|
||||
? "Unable to refuse this dispatch. Please try again."
|
||||
: "";
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={guardDialogClose(refuseMutation.isPending, onClose)}
|
||||
aria-labelledby="refuse-dispatch-title"
|
||||
>
|
||||
<DialogTitle id="refuse-dispatch-title">Refuse dispatch</DialogTitle>
|
||||
<form onSubmit={(event) => void submit(event)}>
|
||||
<DialogContent>
|
||||
<Text variant="body" className="vp-muted" sx={{ marginBottom: 2 }}>
|
||||
Refusing ends your assignment for this dispatch. A reason is optional but helps your
|
||||
dispatcher reassign the work.
|
||||
</Text>
|
||||
<label htmlFor="refuse-reason" className="vp-muted" style={{ fontSize: 13 }}>
|
||||
Reason (optional)
|
||||
</label>
|
||||
<textarea
|
||||
id="refuse-reason"
|
||||
className="vp-textarea"
|
||||
placeholder="Tell the dispatcher why you are refusing…"
|
||||
aria-invalid={Boolean(errors.reason)}
|
||||
aria-describedby={errors.reason ? "refuse-reason-error" : "refuse-reason-counter"}
|
||||
maxLength={REFUSE_REASON_MAX_LENGTH}
|
||||
{...register("reason")}
|
||||
style={{ marginTop: 6 }}
|
||||
/>
|
||||
<div
|
||||
id="refuse-reason-counter"
|
||||
className="vp-muted"
|
||||
style={{ fontSize: 12, textAlign: "right" }}
|
||||
>
|
||||
{reasonValue.length}/{REFUSE_REASON_MAX_LENGTH}
|
||||
</div>
|
||||
<Text variant="error" when={isOverLimit} id="refuse-reason-error">
|
||||
{errors.reason?.message ?? "Reason must be 500 characters or fewer."}
|
||||
</Text>
|
||||
<Text variant="error" when={Boolean(errorMessage)}>
|
||||
{errorMessage}
|
||||
</Text>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<button
|
||||
type="button"
|
||||
className="vp-btn vp-btn-ghost"
|
||||
onClick={onClose}
|
||||
disabled={refuseMutation.isPending}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="vp-btn vp-btn-warn"
|
||||
disabled={refuseMutation.isPending || isOverLimit}
|
||||
>
|
||||
{refuseMutation.isPending ? "Refusing…" : "Refuse dispatch"}
|
||||
</button>
|
||||
</DialogActions>
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
|
@ -11,6 +11,7 @@ type SignoffSectionProps = {
|
|||
existing: VendorPortalSignoff[];
|
||||
signoffType: string;
|
||||
nameLabel: string;
|
||||
submissionLocked?: boolean;
|
||||
onAdded: () => void;
|
||||
};
|
||||
|
||||
|
|
@ -20,6 +21,7 @@ export function SignoffSection({
|
|||
existing,
|
||||
signoffType,
|
||||
nameLabel,
|
||||
submissionLocked = false,
|
||||
onAdded,
|
||||
}: SignoffSectionProps) {
|
||||
const [name, setName] = useState("");
|
||||
|
|
@ -50,6 +52,10 @@ export function SignoffSection({
|
|||
);
|
||||
}
|
||||
|
||||
if (submissionLocked) {
|
||||
return <Text variant="feedback">Signoff is unavailable for this dispatch.</Text>;
|
||||
}
|
||||
|
||||
const submit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
const signature = method === "drawn" ? drawnSig : typedSig;
|
||||
|
|
|
|||
|
|
@ -8,32 +8,14 @@ import {
|
|||
formatVendorPortalDateTime,
|
||||
vendorPortalStatusClass,
|
||||
} from "@/domain/vendor-portal/lib/status-helpers";
|
||||
import type { VendorPortalDispatchSummary } from "@/domain/vendor-portal/types/vendor-portal";
|
||||
import {
|
||||
VENDOR_PORTAL_DISPATCH_FILTERS,
|
||||
applyVendorPortalDispatchFilter,
|
||||
getVendorPortalDispatchFilter,
|
||||
type VendorPortalDispatchFilterKey,
|
||||
} from "@/domain/vendor-portal/lib/dispatch-filters";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
|
||||
const FILTERS = [
|
||||
{
|
||||
key: "open",
|
||||
label: "Open",
|
||||
match: (dispatch: VendorPortalDispatchSummary) =>
|
||||
dispatch.status !== "Completed" &&
|
||||
dispatch.status !== "Verified" &&
|
||||
dispatch.status !== "Cancelled",
|
||||
},
|
||||
{
|
||||
key: "completed",
|
||||
label: "Completed",
|
||||
match: (dispatch: VendorPortalDispatchSummary) =>
|
||||
dispatch.status === "Completed" || dispatch.status === "Verified",
|
||||
},
|
||||
{
|
||||
key: "cancelled",
|
||||
label: "Cancelled",
|
||||
match: (dispatch: VendorPortalDispatchSummary) => dispatch.status === "Cancelled",
|
||||
},
|
||||
{ key: "all", label: "All", match: () => true },
|
||||
] as const;
|
||||
|
||||
function formatDate(value?: string) {
|
||||
if (!value) return "—";
|
||||
const date = new Date(value);
|
||||
|
|
@ -49,7 +31,7 @@ function formatMoney(value?: number) {
|
|||
export default function VendorPortalPosPage() {
|
||||
const { token } = useVendorPortal();
|
||||
const navigate = useNavigate();
|
||||
const [filter, setFilter] = useState<(typeof FILTERS)[number]["key"]>("open");
|
||||
const [filter, setFilter] = useState<VendorPortalDispatchFilterKey>("open");
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const {
|
||||
|
|
@ -62,12 +44,11 @@ export default function VendorPortalPosPage() {
|
|||
enabled: Boolean(token),
|
||||
});
|
||||
|
||||
const activeFilter = FILTERS.find((item) => item.key === filter) ?? FILTERS[0];
|
||||
const activeFilter = getVendorPortalDispatchFilter(filter);
|
||||
|
||||
const visible = useMemo(() => {
|
||||
const needle = search.trim().toLowerCase();
|
||||
return dispatches.filter((dispatch) => {
|
||||
if (!activeFilter.match(dispatch)) return false;
|
||||
return applyVendorPortalDispatchFilter(dispatches, activeFilter).filter((dispatch) => {
|
||||
if (!needle) return true;
|
||||
return (
|
||||
(dispatch.poNumber || "").toLowerCase().includes(needle) ||
|
||||
|
|
@ -90,7 +71,7 @@ export default function VendorPortalPosPage() {
|
|||
className="vp-actions"
|
||||
style={{ marginTop: 0, gap: 12, alignItems: "center", flexWrap: "wrap" }}
|
||||
>
|
||||
{FILTERS.map((item) => (
|
||||
{VENDOR_PORTAL_DISPATCH_FILTERS.map((item) => (
|
||||
<button
|
||||
key={item.key}
|
||||
type="button"
|
||||
|
|
|
|||
|
|
@ -138,6 +138,10 @@
|
|||
background: var(--doc-no-bg);
|
||||
color: var(--doc-no-text);
|
||||
}
|
||||
.vp-status-refused {
|
||||
background: var(--doc-no-bg);
|
||||
color: var(--doc-no-text);
|
||||
}
|
||||
|
||||
.vp-btn {
|
||||
display: inline-block;
|
||||
|
|
|
|||
|
|
@ -32,9 +32,10 @@ function getNavItemAppearance(isActive: boolean, isHover: boolean) {
|
|||
type NavItemProps = NavItemDef & {
|
||||
collapsed: boolean;
|
||||
active: boolean;
|
||||
onNavigate?: () => void;
|
||||
};
|
||||
|
||||
function NavItem({ label, icon: Icon, path, collapsed, active, badge }: NavItemProps) {
|
||||
function NavItem({ label, icon: Icon, path, collapsed, active, badge, onNavigate }: NavItemProps) {
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const isHover = hovered && !active;
|
||||
const { itemColor, iconColor, itemBg } = getNavItemAppearance(active, isHover);
|
||||
|
|
@ -45,6 +46,7 @@ function NavItem({ label, icon: Icon, path, collapsed, active, badge }: NavItemP
|
|||
aria-current={active ? "page" : undefined}
|
||||
className="no-underline"
|
||||
title={collapsed ? label : undefined}
|
||||
onClick={onNavigate}
|
||||
>
|
||||
<Box
|
||||
onMouseEnter={() => setHovered(true)}
|
||||
|
|
@ -118,18 +120,24 @@ function NavItem({ label, icon: Icon, path, collapsed, active, badge }: NavItemP
|
|||
|
||||
type AppSidebarProps = {
|
||||
collapsed: boolean;
|
||||
mobile?: boolean;
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
};
|
||||
|
||||
export function AppSidebar({ collapsed }: AppSidebarProps) {
|
||||
export function AppSidebar({ collapsed, mobile = false, open = true, onClose }: AppSidebarProps) {
|
||||
const width = getSidebarWidth(collapsed);
|
||||
const { pathname } = useLocation();
|
||||
const activePath = getActiveNavPath(pathname);
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
variant="permanent"
|
||||
variant={mobile ? "temporary" : "permanent"}
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
ModalProps={{ keepMounted: true }}
|
||||
sx={{
|
||||
width,
|
||||
width: mobile ? 0 : width,
|
||||
flexShrink: 0,
|
||||
"& .MuiDrawer-paper": {
|
||||
width,
|
||||
|
|
@ -157,7 +165,13 @@ export function AppSidebar({ collapsed }: AppSidebarProps) {
|
|||
{collapsed ? <BrandMark size="compact" /> : <BrandLockup size="compact" />}
|
||||
</Box>
|
||||
|
||||
<Box component="nav" className="flex-1 overflow-y-auto overflow-x-hidden" sx={{ py: 1 }}>
|
||||
<Box
|
||||
component="nav"
|
||||
id="primary-navigation"
|
||||
aria-label="Primary navigation"
|
||||
className="flex-1 overflow-y-auto overflow-x-hidden"
|
||||
sx={{ py: 1 }}
|
||||
>
|
||||
{navGroups.map((group, groupIndex) => (
|
||||
<Box key={group.title || `group-${groupIndex}`}>
|
||||
{collapsed ? (
|
||||
|
|
@ -198,6 +212,7 @@ export function AppSidebar({ collapsed }: AppSidebarProps) {
|
|||
badge={badge}
|
||||
collapsed={collapsed}
|
||||
active={path === activePath}
|
||||
onNavigate={mobile ? onClose : undefined}
|
||||
/>
|
||||
</Box>
|
||||
))}
|
||||
|
|
|
|||
|
|
@ -24,15 +24,16 @@ export function PageHeader({
|
|||
}: PageHeaderProps) {
|
||||
return (
|
||||
<Stack
|
||||
direction="row"
|
||||
direction={{ xs: "column", md: "row" }}
|
||||
className={cn(
|
||||
surface &&
|
||||
"-mx-2.5 -mt-2.5 shrink-0 border-b border-(--color-border) bg-(--color-bg-surface) px-5 py-4",
|
||||
className,
|
||||
)}
|
||||
sx={{
|
||||
alignItems: "center",
|
||||
alignItems: { xs: "stretch", md: "center" },
|
||||
justifyContent: "space-between",
|
||||
gap: { xs: 2, md: 0 },
|
||||
}}
|
||||
>
|
||||
<Stack spacing={0}>
|
||||
|
|
@ -49,15 +50,31 @@ export function PageHeader({
|
|||
"m-0 font-display mt-1! text-[30px]! font-extrabold leading-[1.1] tracking-[-0.02em] text-foreground",
|
||||
eyebrow && "mt-1",
|
||||
)}
|
||||
sx={{ fontSize: 30, fontWeight: 800, lineHeight: 1.1, letterSpacing: "-0.02em" }}
|
||||
>
|
||||
{title}
|
||||
</Text>
|
||||
<Text variant="description" tone="muted" when={Boolean(subtitle)}>
|
||||
<Text
|
||||
variant="description"
|
||||
as="span"
|
||||
tone="muted"
|
||||
when={Boolean(subtitle)}
|
||||
sx={{ mt: 0.75, fontWeight: 500 }}
|
||||
>
|
||||
{subtitle}
|
||||
</Text>
|
||||
</Stack>
|
||||
{Boolean(actions) && (
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: "center", flexWrap: "nowrap" }}>
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={1}
|
||||
useFlexGap
|
||||
sx={{
|
||||
alignItems: "center",
|
||||
flexWrap: { xs: "wrap", md: "nowrap" },
|
||||
width: { xs: "100%", md: "auto" },
|
||||
}}
|
||||
>
|
||||
{actions}
|
||||
</Stack>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import {
|
|||
ClipboardList,
|
||||
FileText,
|
||||
LayoutDashboard,
|
||||
MapPin,
|
||||
Bell,
|
||||
BarChart3,
|
||||
Star,
|
||||
|
|
@ -52,7 +53,10 @@ export const navGroups: NavGroup[] = [
|
|||
},
|
||||
{
|
||||
title: "CUSTOMERS & SITES",
|
||||
items: [{ label: "Accounts", icon: BriefcaseBusiness, path: "/accounts" }],
|
||||
items: [
|
||||
{ label: "Accounts", icon: BriefcaseBusiness, path: "/accounts" },
|
||||
{ label: "Sites", icon: MapPin, path: "/locations" },
|
||||
],
|
||||
},
|
||||
// {
|
||||
// title: "INTERNAL",
|
||||
|
|
|
|||
|
|
@ -129,6 +129,16 @@ export const vendorPortalApi = {
|
|||
method: "POST",
|
||||
}),
|
||||
|
||||
refuse: (token: string, id: string | number, reason?: string) =>
|
||||
vendorPortalCall<{ id: number; status: string; refusedAt?: string }>(
|
||||
token,
|
||||
`${API_PATHS.vendorPortal.dispatches}/${id}/refuse`,
|
||||
{
|
||||
method: "POST",
|
||||
body: reason ? { reason } : {},
|
||||
},
|
||||
),
|
||||
|
||||
changeStatus: (token: string, id: string | number, status: string) =>
|
||||
vendorPortalCall<void>(token, `${API_PATHS.vendorPortal.dispatches}/${id}/status`, {
|
||||
method: "POST",
|
||||
|
|
|
|||
71
src/domain/vendor-portal/lib/dispatch-filters.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import type { VendorPortalDispatchSummary } from "@/domain/vendor-portal/types/vendor-portal";
|
||||
import {
|
||||
isVendorPortalTerminalStatus,
|
||||
isVendorPortalUpcomingDispatch,
|
||||
} from "@/domain/vendor-portal/lib/status-helpers";
|
||||
|
||||
export interface VendorPortalDispatchFilter {
|
||||
key: VendorPortalDispatchFilterKey;
|
||||
label: string;
|
||||
match: (dispatch: VendorPortalDispatchSummary) => boolean;
|
||||
sort?: (dispatches: VendorPortalDispatchSummary[]) => VendorPortalDispatchSummary[];
|
||||
}
|
||||
|
||||
export type VendorPortalDispatchFilterKey =
|
||||
"open" | "upcoming" | "completed" | "refused" | "cancelled" | "all";
|
||||
|
||||
const sortUpcomingByScheduledDateAscending = (
|
||||
dispatches: VendorPortalDispatchSummary[],
|
||||
): VendorPortalDispatchSummary[] =>
|
||||
[...dispatches].sort((left, right) => {
|
||||
const leftTime = left.scheduledDate ? new Date(left.scheduledDate).getTime() : 0;
|
||||
const rightTime = right.scheduledDate ? new Date(right.scheduledDate).getTime() : 0;
|
||||
return leftTime - rightTime;
|
||||
});
|
||||
|
||||
export const VENDOR_PORTAL_DISPATCH_FILTERS: readonly VendorPortalDispatchFilter[] = [
|
||||
{
|
||||
key: "open",
|
||||
label: "Open",
|
||||
match: (dispatch) => !isVendorPortalTerminalStatus(dispatch.status),
|
||||
},
|
||||
{
|
||||
key: "upcoming",
|
||||
label: "Upcoming",
|
||||
match: (dispatch) => isVendorPortalUpcomingDispatch(dispatch),
|
||||
sort: sortUpcomingByScheduledDateAscending,
|
||||
},
|
||||
{
|
||||
key: "completed",
|
||||
label: "Completed",
|
||||
match: (dispatch) => dispatch.status === "Completed" || dispatch.status === "Verified",
|
||||
},
|
||||
{
|
||||
key: "refused",
|
||||
label: "Refused",
|
||||
match: (dispatch) => dispatch.status === "Refused",
|
||||
},
|
||||
{
|
||||
key: "cancelled",
|
||||
label: "Cancelled",
|
||||
match: (dispatch) => dispatch.status === "Cancelled",
|
||||
},
|
||||
{ key: "all", label: "All", match: () => true },
|
||||
] as const;
|
||||
|
||||
export function getVendorPortalDispatchFilter(
|
||||
key: VendorPortalDispatchFilterKey,
|
||||
): VendorPortalDispatchFilter {
|
||||
return (
|
||||
VENDOR_PORTAL_DISPATCH_FILTERS.find((filter) => filter.key === key) ??
|
||||
VENDOR_PORTAL_DISPATCH_FILTERS[0]
|
||||
);
|
||||
}
|
||||
|
||||
export function applyVendorPortalDispatchFilter(
|
||||
dispatches: VendorPortalDispatchSummary[],
|
||||
filter: VendorPortalDispatchFilter,
|
||||
): VendorPortalDispatchSummary[] {
|
||||
const matched = dispatches.filter(filter.match);
|
||||
return filter.sort ? filter.sort(matched) : matched;
|
||||
}
|
||||
|
|
@ -6,6 +6,7 @@ export function vendorPortalStatusClass(status: string): string {
|
|||
Completed: "vp-status-completed",
|
||||
Verified: "vp-status-verified",
|
||||
Cancelled: "vp-status-cancelled",
|
||||
Refused: "vp-status-refused",
|
||||
};
|
||||
|
||||
return `vp-status-pill ${map[status] ?? ""}`;
|
||||
|
|
@ -23,3 +24,34 @@ export function formatVendorPortalDateTime(value?: string): string {
|
|||
|
||||
return date.toLocaleString();
|
||||
}
|
||||
|
||||
const TERMINAL_STATUSES = new Set(["Completed", "Verified", "Cancelled", "Refused"]);
|
||||
const LOCKED_STATUSES = new Set(["Verified", "Cancelled", "Refused"]);
|
||||
|
||||
export function isVendorPortalTerminalStatus(status: string): boolean {
|
||||
return TERMINAL_STATUSES.has(status);
|
||||
}
|
||||
|
||||
export function isVendorPortalLockedStatus(status: string): boolean {
|
||||
return LOCKED_STATUSES.has(status);
|
||||
}
|
||||
|
||||
export function isVendorPortalUpcomingDispatch(
|
||||
dispatch: { status: string; scheduledDate?: string },
|
||||
now: Date = new Date(),
|
||||
): boolean {
|
||||
if (isVendorPortalTerminalStatus(dispatch.status)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!dispatch.scheduledDate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const scheduled = new Date(dispatch.scheduledDate);
|
||||
if (Number.isNaN(scheduled.getTime())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return scheduled.getTime() >= now.getTime();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,9 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const REFUSE_REASON_MAX_LENGTH = 500;
|
||||
|
||||
export const refuseDispatchSchema = z.object({
|
||||
reason: z.string().max(REFUSE_REASON_MAX_LENGTH, "Reason must be 500 characters or fewer."),
|
||||
});
|
||||
|
||||
export type RefuseDispatchValues = z.infer<typeof refuseDispatchSchema>;
|
||||
|
|
@ -20,6 +20,7 @@ export interface VendorPortalDispatchSummary {
|
|||
nteAmount?: number;
|
||||
dispatchedAt?: string;
|
||||
completedDate?: string;
|
||||
refusedAt?: string;
|
||||
}
|
||||
|
||||
export interface VendorPortalDocument {
|
||||
|
|
@ -73,15 +74,25 @@ export interface VendorPortalSignoff {
|
|||
signedAt?: string;
|
||||
}
|
||||
|
||||
export interface VendorPortalDispatcherContact {
|
||||
name?: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
}
|
||||
|
||||
export interface VendorPortalDispatchDetail extends VendorPortalDispatchSummary {
|
||||
description?: string;
|
||||
acknowledgedAt?: string;
|
||||
statusUpdatedAt?: string;
|
||||
dispatcherContact?: VendorPortalDispatcherContact;
|
||||
workOrder?: {
|
||||
workerOrderTitle?: string;
|
||||
internalWONumber?: string;
|
||||
priority?: string;
|
||||
trade?: string;
|
||||
subTrade?: string;
|
||||
siteCode?: string;
|
||||
service?: string;
|
||||
problem?: string;
|
||||
description?: string;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { useController } from "react-hook-form";
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const rosterGet = vi.fn();
|
||||
const saveMutate = vi.fn();
|
||||
|
||||
vi.mock("@/domain/vendors/api/vendor-company-roster-api", () => ({
|
||||
vendorCompanyRosterApi: { get: (...args: unknown[]) => rosterGet(...args) },
|
||||
|
|
@ -28,7 +29,10 @@ vi.mock("@/domain/vendors/use-cases/use-save-vendor-company-roster", async () =>
|
|||
const actual = await vi.importActual<
|
||||
typeof import("@/domain/vendors/use-cases/use-save-vendor-company-roster")
|
||||
>("@/domain/vendors/use-cases/use-save-vendor-company-roster");
|
||||
return { ...actual, useSaveVendorCompanyRoster: () => ({ mutate: vi.fn(), isPending: false }) };
|
||||
return {
|
||||
...actual,
|
||||
useSaveVendorCompanyRoster: () => ({ mutate: saveMutate, isPending: false }),
|
||||
};
|
||||
});
|
||||
|
||||
import { useVendorRosterForm } from "@/app/(protected)/vendors/_components/use-vendor-roster-form";
|
||||
|
|
@ -101,6 +105,7 @@ function deferRoster(): {
|
|||
describe("useVendorRosterForm load-error handling", () => {
|
||||
beforeEach(() => {
|
||||
rosterGet.mockReset();
|
||||
saveMutate.mockReset();
|
||||
});
|
||||
|
||||
it("shows a safe retryable error when selecting an existing company fetch is rejected", async () => {
|
||||
|
|
@ -196,6 +201,44 @@ describe("useVendorRosterForm load-error handling", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("useVendorRosterForm prototype defaults", () => {
|
||||
it("does not persist the prototype's untouched optional technician card", () => {
|
||||
const { result } = renderHook(
|
||||
() => useVendorRosterForm({ mode: "create", startWithTechnician: true }),
|
||||
{ wrapper: makeWrapper(createClient()) },
|
||||
);
|
||||
|
||||
act(() => {
|
||||
result.current.submit({
|
||||
name: "Independent Vendor LLC",
|
||||
companyPhone: "(314) 555-0199",
|
||||
email: "",
|
||||
address: "",
|
||||
city: "",
|
||||
state: "",
|
||||
zip: "",
|
||||
googleMapsUrl: "",
|
||||
notes: "",
|
||||
technicians: [
|
||||
{
|
||||
contactName: "",
|
||||
phone: "",
|
||||
email: "",
|
||||
preferredContact: "Phone",
|
||||
tradeSpecialties: "",
|
||||
isActive: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
expect(saveMutate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ values: expect.objectContaining({ technicians: [] }) }),
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("useVendorRosterForm stale-selection handling", () => {
|
||||
beforeEach(() => {
|
||||
rosterGet.mockReset();
|
||||
|
|
|
|||
|
|
@ -49,11 +49,11 @@ function rosterWith(technicians: Array<Record<string, unknown>>) {
|
|||
};
|
||||
}
|
||||
|
||||
describe("VendorDetailDrawer preferred-contact display", () => {
|
||||
describe("VendorDetailDrawer selected-technician display", () => {
|
||||
it("renders no preference label when preferredContact is absent", () => {
|
||||
useVendorCompanyRoster.mockReturnValue(
|
||||
rosterWith([
|
||||
{ id: 7, contactName: "Adam", phone: "314-555-0198", isActive: true, totalJobs: 5 },
|
||||
{ id: 1, contactName: "Adam", phone: "314-555-0198", isActive: true, totalJobs: 5 },
|
||||
]),
|
||||
);
|
||||
|
||||
|
|
@ -62,15 +62,15 @@ describe("VendorDetailDrawer preferred-contact display", () => {
|
|||
withAuth: false,
|
||||
});
|
||||
|
||||
expect(screen.getByText("Adam")).toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { level: 2, name: "Adam" })).toBeInTheDocument();
|
||||
expect(screen.queryByText(/^Prefers/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders the preference label when an explicit preferredContact is present", () => {
|
||||
it("keeps the retired preferred-contact value out of the detail view", () => {
|
||||
useVendorCompanyRoster.mockReturnValue(
|
||||
rosterWith([
|
||||
{
|
||||
id: 7,
|
||||
id: 1,
|
||||
contactName: "Adam",
|
||||
phone: "314-555-0198",
|
||||
preferredContact: "Email",
|
||||
|
|
@ -85,6 +85,52 @@ describe("VendorDetailDrawer preferred-contact display", () => {
|
|||
withAuth: false,
|
||||
});
|
||||
|
||||
expect(screen.getByText("Prefers Email")).toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { level: 2, name: "Adam" })).toBeInTheDocument();
|
||||
expect(screen.queryByText(/^Prefers/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("falls back to the clicked row when the roster has no matching stable id", () => {
|
||||
useVendorCompanyRoster.mockReturnValue(
|
||||
rosterWith([
|
||||
{
|
||||
id: 7,
|
||||
contactName: "Adam Whyte",
|
||||
phone: "999-999-9999",
|
||||
isActive: true,
|
||||
totalJobs: 99,
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
renderWithProviders(<VendorDetailDrawer open={true} vendor={vendor} onClose={vi.fn()} />, {
|
||||
route: "/vendors",
|
||||
withAuth: false,
|
||||
});
|
||||
|
||||
expect(screen.getByText("0")).toBeInTheDocument();
|
||||
expect(screen.queryByText("999-999-9999")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not expose a status control for a different technician", () => {
|
||||
useVendorCompanyRoster.mockReturnValue(
|
||||
rosterWith([
|
||||
{
|
||||
id: 7,
|
||||
contactName: "Different Technician",
|
||||
phone: "314-555-0101",
|
||||
email: "",
|
||||
tradeSpecialties: "Plumbing",
|
||||
isActive: true,
|
||||
totalJobs: 10,
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
renderWithProviders(
|
||||
<VendorDetailDrawer open={true} vendor={vendor} startInEdit={true} onClose={vi.fn()} />,
|
||||
{ route: "/vendors", withAuth: false },
|
||||
);
|
||||
|
||||
expect(screen.queryByRole("switch", { name: "Active status" })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,21 +1,14 @@
|
|||
import { screen } from "@testing-library/react";
|
||||
import { screen, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import VendorsListPage from "@/app/(protected)/vendors/index";
|
||||
import type { VendorListItem } from "@/domain/vendors/types/vendor";
|
||||
import type { VendorCompanyRoster, VendorListItem } from "@/domain/vendors/types/vendor";
|
||||
import { renderWithProviders } from "@/test/test-utils";
|
||||
|
||||
const useVendorsList = vi.fn();
|
||||
const useVendorCompanyRoster = vi.fn();
|
||||
const useVendorDeactivationImpact = vi.fn();
|
||||
const mutate = vi.fn();
|
||||
const navigate = vi.fn();
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual("react-router");
|
||||
return { ...actual, useNavigate: () => navigate };
|
||||
});
|
||||
|
||||
vi.mock("@/domain/vendors/use-cases/use-vendors-list", () => ({
|
||||
useVendorsList: (...args: unknown[]) => useVendorsList(...args),
|
||||
}));
|
||||
|
|
@ -61,6 +54,32 @@ const inactiveVendor = {
|
|||
isActive: false,
|
||||
};
|
||||
|
||||
const activeRoster: VendorCompanyRoster = {
|
||||
companyId: "co-1",
|
||||
rowVersion: "rv-1",
|
||||
name: "Gateway Plumbing",
|
||||
companyPhone: "(314) 555-0100",
|
||||
email: "dispatch@gatewayplumbing.com",
|
||||
address: "",
|
||||
city: "St. Louis",
|
||||
state: "MO",
|
||||
zip: "",
|
||||
googleMapsUrl: "",
|
||||
notes: "",
|
||||
technicians: [
|
||||
{
|
||||
id: 1,
|
||||
contactName: "Adam Whyte",
|
||||
phone: "(314) 555-0198",
|
||||
email: "dispatch@gatewayplumbing.com",
|
||||
preferredContact: "Email",
|
||||
tradeSpecialties: "Backflow Preventers",
|
||||
isActive: true,
|
||||
totalJobs: 0,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function result(items: VendorListItem[], totalCount: number) {
|
||||
return {
|
||||
data: { items, totalCount, page: 1, pageSize: 12 },
|
||||
|
|
@ -71,7 +90,13 @@ function result(items: VendorListItem[], totalCount: number) {
|
|||
}
|
||||
|
||||
function setupDefaults() {
|
||||
useVendorCompanyRoster.mockReturnValue({ data: undefined, isLoading: false, error: null });
|
||||
useVendorCompanyRoster.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
useVendorDeactivationImpact.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
|
|
@ -80,7 +105,7 @@ function setupDefaults() {
|
|||
}
|
||||
|
||||
describe("VendorsListPage", () => {
|
||||
it("renders prototype-aligned status tabs and location, then hides deactivation for inactive rows", async () => {
|
||||
it("renders prototype-aligned status and two row actions in both tabs", async () => {
|
||||
setupDefaults();
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], params.isActive ? 1 : 1);
|
||||
|
|
@ -91,11 +116,20 @@ describe("VendorsListPage", () => {
|
|||
|
||||
expect(screen.getByRole("heading", { name: "Vendors / Technicians" })).toBeInTheDocument();
|
||||
expect(screen.getByText("St. Louis, MO")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Deactivate vendor" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("columnheader", { name: "Status" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("cell", { name: "Active" })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: "View vendor Gateway Plumbing" }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Edit vendor Gateway Plumbing" }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Deactivate vendor" })).not.toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole("tab", { name: "Inactive (1)" }));
|
||||
|
||||
expect(screen.getByText("Drain Cleaning Bros")).toBeInTheDocument();
|
||||
expect(screen.getByRole("cell", { name: "Inactive" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Deactivate vendor" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
|
@ -114,39 +148,18 @@ describe("VendorsListPage", () => {
|
|||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
expect(screen.getByText(/25 active vendor entries/)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/3 active vendor entries/)).not.toBeInTheDocument();
|
||||
expect(screen.getByText(/25 active technicians/)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/3 active technicians/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens the detail drawer when a row is clicked or activated by keyboard", async () => {
|
||||
setupDefaults();
|
||||
useVendorCompanyRoster.mockReturnValue({
|
||||
data: {
|
||||
companyId: "co-1",
|
||||
rowVersion: "rv-1",
|
||||
name: "Gateway Plumbing",
|
||||
companyPhone: "(314) 555-0198",
|
||||
email: "dispatch@gatewayplumbing.com",
|
||||
address: "",
|
||||
city: "St. Louis",
|
||||
state: "MO",
|
||||
zip: "",
|
||||
googleMapsUrl: "",
|
||||
notes: "",
|
||||
technicians: [
|
||||
{
|
||||
id: 1,
|
||||
contactName: "Adam Whyte",
|
||||
phone: "(314) 555-0198",
|
||||
email: "dispatch@gatewayplumbing.com",
|
||||
preferredContact: "Email",
|
||||
tradeSpecialties: "Backflow Preventers",
|
||||
isActive: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
data: activeRoster,
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
|
|
@ -161,11 +174,18 @@ describe("VendorsListPage", () => {
|
|||
row.focus();
|
||||
await userEvent.keyboard("{Enter}");
|
||||
|
||||
expect(screen.getByRole("heading", { level: 2, name: "Gateway Plumbing" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { level: 2, name: "Adam Whyte" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("blocks deactivation when the preflight reports open work orders", async () => {
|
||||
setupDefaults();
|
||||
useVendorCompanyRoster.mockReturnValue({
|
||||
data: activeRoster,
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
useVendorDeactivationImpact.mockReturnValue({
|
||||
data: {
|
||||
vendorId: 1,
|
||||
|
|
@ -189,7 +209,8 @@ describe("VendorsListPage", () => {
|
|||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Deactivate vendor" }));
|
||||
await userEvent.click(screen.getByRole("button", { name: "Edit vendor Gateway Plumbing" }));
|
||||
await userEvent.click(screen.getByRole("switch", { name: "Active status" }));
|
||||
|
||||
expect(
|
||||
screen.getByText(/cannot be deactivated because it still has open work orders/),
|
||||
|
|
@ -199,9 +220,51 @@ describe("VendorsListPage", () => {
|
|||
expect(mutate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("navigates to the vendor edit route when the table Edit control is clicked", async () => {
|
||||
it("preserves inline edits when deactivation is cancelled", async () => {
|
||||
setupDefaults();
|
||||
navigate.mockClear();
|
||||
useVendorCompanyRoster.mockReturnValue({
|
||||
data: activeRoster,
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
useVendorDeactivationImpact.mockReturnValue({
|
||||
data: { vendorId: 1, canDeactivate: true, openWorkOrders: [] },
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
});
|
||||
|
||||
renderWithProviders(<VendorsListPage />, { route: "/vendors", withAuth: false });
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Edit vendor Gateway Plumbing" }));
|
||||
const company = screen.getByRole("textbox", { name: "Company" });
|
||||
await userEvent.clear(company);
|
||||
await userEvent.type(company, "Draft Company Name");
|
||||
await userEvent.click(screen.getByRole("switch", { name: "Active status" }));
|
||||
await userEvent.click(
|
||||
within(screen.getByRole("dialog", { name: "Deactivate Vendor" })).getByRole("button", {
|
||||
name: "Cancel",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(company).toBeInTheDocument();
|
||||
expect(company).toHaveValue("Draft Company Name");
|
||||
});
|
||||
|
||||
it("opens inline edit when the table Edit control is clicked", async () => {
|
||||
setupDefaults();
|
||||
useVendorCompanyRoster.mockReturnValue({
|
||||
data: activeRoster,
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([activeVendor], 1) : result([], 0);
|
||||
|
|
@ -211,16 +274,20 @@ describe("VendorsListPage", () => {
|
|||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Edit vendor Gateway Plumbing" }));
|
||||
|
||||
expect(navigate).toHaveBeenCalledWith("/vendors/edit/1");
|
||||
expect(
|
||||
screen.queryByRole("heading", { level: 2, name: "Gateway Plumbing" }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Save changes" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("textbox", { name: "Company" })).toHaveValue("Gateway Plumbing");
|
||||
});
|
||||
|
||||
it("navigates to the company route when editing a vendor without a vendor id", async () => {
|
||||
it("opens inline company edit when the row has no vendor id", async () => {
|
||||
setupDefaults();
|
||||
navigate.mockClear();
|
||||
const companyOnlyVendor = { ...activeVendor, id: null, companyId: "co-9" };
|
||||
useVendorCompanyRoster.mockReturnValue({
|
||||
data: { ...activeRoster, companyId: "co-9", technicians: [] },
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
useVendorsList.mockImplementation((params: { isActive?: boolean; pageSize?: number }) => {
|
||||
if (params.pageSize === 1) return result([], 1);
|
||||
return params.isActive ? result([companyOnlyVendor], 1) : result([], 0);
|
||||
|
|
@ -230,6 +297,7 @@ describe("VendorsListPage", () => {
|
|||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Edit vendor Gateway Plumbing" }));
|
||||
|
||||
expect(navigate).toHaveBeenCalledWith("/vendors/company/co-9");
|
||||
expect(screen.getByRole("button", { name: "Save changes" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("textbox", { name: "Company" })).toHaveValue("Gateway Plumbing");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
99
src/test/app/v/dispatch-detail-sections.test.tsx
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
import { screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { DispatchDetailSections } from "@/app/v/[token]/dispatch/_components/dispatch-detail-sections";
|
||||
import { isVendorPortalLockedStatus } from "@/domain/vendor-portal/lib/status-helpers";
|
||||
import type {
|
||||
VendorPortalDispatchDetail,
|
||||
VendorPortalSignoff,
|
||||
} from "@/domain/vendor-portal/types/vendor-portal";
|
||||
import { renderWithProviders } from "@/test/test-utils";
|
||||
|
||||
vi.mock("@/app/v/[token]/dispatch/_components/checklist-section", () => ({
|
||||
ChecklistSection: () => <div data-testid="checklist-mock" />,
|
||||
}));
|
||||
vi.mock("@/app/v/_components/vendor-portal-documents", () => ({
|
||||
VendorPortalDocuments: () => <div data-testid="documents-mock" />,
|
||||
}));
|
||||
vi.mock("@/app/v/[token]/dispatch/_components/uplift-requests-section", () => ({
|
||||
UpliftRequestsSection: () => <div data-testid="uplift-mock" />,
|
||||
}));
|
||||
vi.mock("@/app/v/[token]/dispatch/_components/comments-section", () => ({
|
||||
CommentsSection: () => <div data-testid="comments-mock" />,
|
||||
}));
|
||||
|
||||
function buildData(
|
||||
overrides: Partial<VendorPortalDispatchDetail> = {},
|
||||
): VendorPortalDispatchDetail {
|
||||
return {
|
||||
id: 9,
|
||||
dispatchNumber: "DSP-9",
|
||||
status: "In Progress",
|
||||
nteAmount: 500,
|
||||
checklist: [],
|
||||
comments: [],
|
||||
upliftRequests: [],
|
||||
signoffs: [],
|
||||
documents: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function renderSections({
|
||||
status,
|
||||
signoffs = [],
|
||||
}: {
|
||||
status: string;
|
||||
signoffs?: VendorPortalSignoff[];
|
||||
}) {
|
||||
const data = buildData({ status, signoffs });
|
||||
const locked = isVendorPortalLockedStatus(status);
|
||||
|
||||
return renderWithProviders(
|
||||
<DispatchDetailSections
|
||||
token="portal-token"
|
||||
dispatchId={9}
|
||||
data={data}
|
||||
locked={locked}
|
||||
refresh={vi.fn()}
|
||||
updateLocal={vi.fn()}
|
||||
/>,
|
||||
{ withAuth: false },
|
||||
);
|
||||
}
|
||||
|
||||
describe("DispatchDetailSections signoff locking", () => {
|
||||
it.each(["Verified", "Cancelled", "Refused"])(
|
||||
"locks both customer and vendor signoff forms when status is %s",
|
||||
(status) => {
|
||||
renderSections({ status });
|
||||
|
||||
expect(screen.getAllByText(/Signoff is unavailable for this dispatch/i)).toHaveLength(2);
|
||||
expect(screen.queryAllByRole("button", { name: "Submit Signoff" })).toHaveLength(0);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["Completed", "In Progress"])(
|
||||
"keeps both signoff forms available when status is %s",
|
||||
(status) => {
|
||||
renderSections({ status });
|
||||
|
||||
expect(screen.getAllByRole("button", { name: "Submit Signoff" })).toHaveLength(2);
|
||||
expect(screen.queryByText(/Signoff is unavailable/i)).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps an existing signoff visible while the dispatch is locked", () => {
|
||||
const customerSignoff: VendorPortalSignoff = {
|
||||
signoffType: "customer",
|
||||
name: "Ada Lovelace",
|
||||
signatureMethod: "drawn",
|
||||
signedAt: "2024-01-02T03:04:05Z",
|
||||
};
|
||||
renderSections({ status: "Refused", signoffs: [customerSignoff] });
|
||||
|
||||
expect(screen.getByText("Ada Lovelace")).toBeInTheDocument();
|
||||
expect(screen.getByText("drawn")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Signoff is unavailable/i)).toBeInTheDocument();
|
||||
expect(screen.queryAllByRole("button", { name: "Submit Signoff" })).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
210
src/test/app/v/refuse-dispatch-dialog.test.tsx
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
import { act, fireEvent, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { RefuseDispatchDialog } from "@/app/v/[token]/dispatch/_components/refuse-dispatch-dialog";
|
||||
import {
|
||||
VendorPortalContext,
|
||||
type VendorPortalContextValue,
|
||||
} from "@/app/v/_components/vendor-portal-context";
|
||||
import { vendorPortalApi } from "@/domain/vendor-portal/api/vendor-portal-api";
|
||||
import { REFUSE_REASON_MAX_LENGTH } from "@/domain/vendor-portal/schemas/refuse-dispatch-schema";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
import { createTestQueryClient, renderWithProviders } from "@/test/test-utils";
|
||||
|
||||
function renderDialog({
|
||||
token = "portal-token",
|
||||
dispatchId = 9,
|
||||
onClose = vi.fn(),
|
||||
onRefused = vi.fn(),
|
||||
}: Partial<{
|
||||
token: string;
|
||||
dispatchId: number;
|
||||
onClose: () => void;
|
||||
onRefused: () => void;
|
||||
}> = {}) {
|
||||
const queryClient = createTestQueryClient();
|
||||
const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");
|
||||
|
||||
const portalValue: VendorPortalContextValue = {
|
||||
token,
|
||||
vendor: { companyName: "Gateway Plumbing", vendorId: 101 },
|
||||
status: "ready",
|
||||
error: null,
|
||||
};
|
||||
|
||||
const utils = renderWithProviders(
|
||||
<VendorPortalContext.Provider value={portalValue}>
|
||||
<RefuseDispatchDialog open dispatchId={dispatchId} onClose={onClose} onRefused={onRefused} />
|
||||
</VendorPortalContext.Provider>,
|
||||
{ withAuth: false, queryClient },
|
||||
);
|
||||
|
||||
return { ...utils, invalidateSpy, queryClient };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(vendorPortalApi, "refuse").mockResolvedValue({ id: 9, status: "Refused" });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("RefuseDispatchDialog", () => {
|
||||
it("submits without a reason when the field is left empty", async () => {
|
||||
renderDialog();
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Refuse dispatch" }));
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(vendorPortalApi.refuse).toHaveBeenCalledWith("portal-token", 9, undefined),
|
||||
);
|
||||
});
|
||||
|
||||
it("trims a supplied reason before sending", async () => {
|
||||
renderDialog();
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/Reason/i), { target: { value: " too busy " } });
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Refuse dispatch" }));
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(vendorPortalApi.refuse).toHaveBeenCalledWith("portal-token", 9, "too busy"),
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks submission when the reason exceeds the length cap", async () => {
|
||||
renderDialog();
|
||||
|
||||
const overLimit = "a".repeat(REFUSE_REASON_MAX_LENGTH + 1);
|
||||
fireEvent.change(screen.getByLabelText(/Reason/i), { target: { value: overLimit } });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Refuse dispatch" })).toBeDisabled(),
|
||||
);
|
||||
expect(vendorPortalApi.refuse).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows a live character counter bounded by the limit", () => {
|
||||
renderDialog();
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/Reason/i), { target: { value: "abc" } });
|
||||
|
||||
expect(screen.getByText(`3/${REFUSE_REASON_MAX_LENGTH}`)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("invalidates the detail and list cache and closes on success", async () => {
|
||||
const onClose = vi.fn();
|
||||
const onRefused = vi.fn();
|
||||
const { invalidateSpy } = renderDialog({ onClose, onRefused });
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Refuse dispatch" }));
|
||||
});
|
||||
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalled());
|
||||
expect(onRefused).toHaveBeenCalled();
|
||||
expect(invalidateSpy).toHaveBeenCalledWith({
|
||||
queryKey: queryKeys.vendorPortal.dispatch("portal-token", 9),
|
||||
});
|
||||
expect(invalidateSpy).toHaveBeenCalledWith({
|
||||
queryKey: queryKeys.vendorPortal.dispatches("portal-token"),
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces a safe inline error and keeps the dialog open on failure", async () => {
|
||||
vi.spyOn(vendorPortalApi, "refuse").mockRejectedValueOnce(new Error("nope"));
|
||||
const onClose = vi.fn();
|
||||
renderDialog({ onClose });
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Refuse dispatch" }));
|
||||
});
|
||||
|
||||
await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent(/Unable to refuse/i));
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("closes without refusing when cancel is pressed", async () => {
|
||||
const onClose = vi.fn();
|
||||
renderDialog({ onClose });
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalled());
|
||||
expect(vendorPortalApi.refuse).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("blocks Escape and backdrop close while a refusal is pending, then closes on success", async () => {
|
||||
let resolveRefusal!: (value: { id: number; status: string }) => void;
|
||||
vi.spyOn(vendorPortalApi, "refuse").mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
resolveRefusal = resolve;
|
||||
}),
|
||||
);
|
||||
const onClose = vi.fn();
|
||||
renderDialog({ onClose });
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Refuse dispatch" }));
|
||||
});
|
||||
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Refusing…" })).toBeDisabled());
|
||||
expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled();
|
||||
|
||||
const backdrop = document.querySelector(".MuiBackdrop-root");
|
||||
expect(backdrop).not.toBeNull();
|
||||
fireEvent.click(backdrop as Element);
|
||||
fireEvent.keyDown(document.body, { key: "Escape" });
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => {
|
||||
resolveRefusal({ id: 9, status: "Refused" });
|
||||
});
|
||||
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it("clears the stale error and reason after closing and reopening", async () => {
|
||||
vi.spyOn(vendorPortalApi, "refuse").mockRejectedValueOnce(new Error("nope"));
|
||||
const onClose = vi.fn();
|
||||
const onRefused = vi.fn();
|
||||
|
||||
const portalValue: VendorPortalContextValue = {
|
||||
token: "portal-token",
|
||||
vendor: { companyName: "Gateway Plumbing", vendorId: 101 },
|
||||
status: "ready",
|
||||
error: null,
|
||||
};
|
||||
const renderEl = (open: boolean) => (
|
||||
<VendorPortalContext.Provider value={portalValue}>
|
||||
<RefuseDispatchDialog open={open} dispatchId={9} onClose={onClose} onRefused={onRefused} />
|
||||
</VendorPortalContext.Provider>
|
||||
);
|
||||
|
||||
const { rerender } = renderWithProviders(renderEl(true), { withAuth: false });
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/Reason/i), { target: { value: "too busy" } });
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Refuse dispatch" }));
|
||||
});
|
||||
await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent(/Unable to refuse/i));
|
||||
expect(screen.getByText(`8/${REFUSE_REASON_MAX_LENGTH}`)).toBeInTheDocument();
|
||||
|
||||
await act(async () => {
|
||||
rerender(renderEl(false));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
rerender(renderEl(true));
|
||||
});
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
|
||||
expect(screen.getByText(`0/${REFUSE_REASON_MAX_LENGTH}`)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
46
src/test/app/v/signoff-section.test.tsx
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { SignoffSection } from "@/app/v/[token]/dispatch/_components/signoff-section";
|
||||
|
||||
function renderSection(overrides: Partial<React.ComponentProps<typeof SignoffSection>> = {}) {
|
||||
return render(
|
||||
<SignoffSection
|
||||
token="portal-token"
|
||||
dispatchId={9}
|
||||
existing={[]}
|
||||
signoffType="customer"
|
||||
nameLabel="Customer name"
|
||||
onAdded={vi.fn()}
|
||||
{...overrides}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("SignoffSection", () => {
|
||||
it("shows status-neutral locked copy when submission is locked", () => {
|
||||
renderSection({ submissionLocked: true });
|
||||
|
||||
expect(screen.getByText(/Signoff is unavailable for this dispatch/i)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/refused/i)).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Submit Signoff" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the submission form when unlocked", () => {
|
||||
renderSection();
|
||||
|
||||
expect(screen.getByRole("button", { name: "Submit Signoff" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows an existing signoff even while locked", () => {
|
||||
renderSection({
|
||||
signoffType: "vendor",
|
||||
nameLabel: "Your name",
|
||||
submissionLocked: true,
|
||||
existing: [{ signoffType: "vendor", name: "Grace Hopper", signatureMethod: "typed" }],
|
||||
});
|
||||
|
||||
expect(screen.getByText("Grace Hopper")).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Signoff is unavailable/i)).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Submit Signoff" })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
90
src/test/domain/vendor-portal/api/vendor-portal-api.test.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { vendorPortalApi } from "@/domain/vendor-portal/api/vendor-portal-api";
|
||||
|
||||
type FetchCall = {
|
||||
url: string;
|
||||
method: string;
|
||||
body: unknown;
|
||||
headers: Record<string, string>;
|
||||
};
|
||||
|
||||
function mockFetch(response: unknown, status = 200) {
|
||||
const calls: FetchCall[] = [];
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (url: string | URL, init?: RequestInit) => {
|
||||
const body = init?.body ? JSON.parse(String(init.body)) : undefined;
|
||||
const headers = (init?.headers ?? {}) as Record<string, string>;
|
||||
calls.push({
|
||||
url: String(url),
|
||||
method: init?.method ?? "GET",
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
json: async () =>
|
||||
response == null
|
||||
? ({} as Record<string, unknown>)
|
||||
: ({ data: response } as Record<string, unknown>),
|
||||
} as Response;
|
||||
}),
|
||||
);
|
||||
return calls;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("VITE_API_BASE_URL", "");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("vendorPortalApi.refuse", () => {
|
||||
it("POSTs to the refuse endpoint with a reason when provided", async () => {
|
||||
const calls = mockFetch({ id: 9, status: "Refused", refusedAt: "2026-08-10T12:00:00Z" });
|
||||
|
||||
await vendorPortalApi.refuse("portal-token", 9, "Too far away");
|
||||
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0].url).toContain("/vendor-portal/dispatches/9/refuse");
|
||||
expect(calls[0].method).toBe("POST");
|
||||
expect(calls[0].headers["X-Vendor-Token"]).toBe("portal-token");
|
||||
expect(calls[0].body).toEqual({ reason: "Too far away" });
|
||||
});
|
||||
|
||||
it("omits the reason from the body when none is supplied", async () => {
|
||||
const calls = mockFetch({ id: 9, status: "Refused" });
|
||||
|
||||
await vendorPortalApi.refuse("portal-token", 9);
|
||||
|
||||
expect(calls[0].body).toEqual({});
|
||||
});
|
||||
|
||||
it("returns the refused payload from the API", async () => {
|
||||
mockFetch({ id: 9, status: "Refused", refusedAt: "2026-08-10T12:00:00Z" });
|
||||
|
||||
const result = await vendorPortalApi.refuse("portal-token", 9);
|
||||
|
||||
expect(result).toEqual({ id: 9, status: "Refused", refusedAt: "2026-08-10T12:00:00Z" });
|
||||
});
|
||||
|
||||
it("throws when the API rejects the refusal", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => ({
|
||||
ok: false,
|
||||
status: 409,
|
||||
json: async () => ({ message: "Dispatch already terminal" }),
|
||||
})) as unknown as typeof fetch,
|
||||
);
|
||||
|
||||
await expect(vendorPortalApi.refuse("portal-token", 9, "nope")).rejects.toThrow(
|
||||
"Dispatch already terminal",
|
||||
);
|
||||
});
|
||||
});
|
||||
45
src/test/domain/vendor-portal/lib/dispatch-filters.test.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
applyVendorPortalDispatchFilter,
|
||||
getVendorPortalDispatchFilter,
|
||||
} from "@/domain/vendor-portal/lib/dispatch-filters";
|
||||
import type { VendorPortalDispatchSummary } from "@/domain/vendor-portal/types/vendor-portal";
|
||||
|
||||
const dispatch = (
|
||||
id: number,
|
||||
status: string,
|
||||
scheduledDate?: string,
|
||||
): VendorPortalDispatchSummary => ({
|
||||
id,
|
||||
dispatchNumber: `DSP-${id}`,
|
||||
status,
|
||||
scheduledDate,
|
||||
});
|
||||
|
||||
describe("vendor portal dispatch filters", () => {
|
||||
it("keeps Refused separate from the Open view", () => {
|
||||
const dispatches = [dispatch(1, "Sent"), dispatch(2, "Refused")];
|
||||
|
||||
expect(
|
||||
applyVendorPortalDispatchFilter(dispatches, getVendorPortalDispatchFilter("open")),
|
||||
).toEqual([dispatches[0]]);
|
||||
expect(
|
||||
applyVendorPortalDispatchFilter(dispatches, getVendorPortalDispatchFilter("refused")),
|
||||
).toEqual([dispatches[1]]);
|
||||
});
|
||||
|
||||
it("sorts Upcoming by schedule without mutating the cached list", () => {
|
||||
const later = dispatch(2, "Acknowledged", "2099-08-12T09:00:00Z");
|
||||
const sooner = dispatch(1, "Sent", "2099-08-11T09:00:00Z");
|
||||
const dispatches = [later, sooner];
|
||||
|
||||
const result = applyVendorPortalDispatchFilter(
|
||||
dispatches,
|
||||
getVendorPortalDispatchFilter("upcoming"),
|
||||
);
|
||||
|
||||
expect(result).toEqual([sooner, later]);
|
||||
expect(dispatches).toEqual([later, sooner]);
|
||||
});
|
||||
});
|
||||
87
src/test/domain/vendor-portal/lib/status-helpers.test.ts
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
formatVendorPortalDateTime,
|
||||
isVendorPortalLockedStatus,
|
||||
isVendorPortalTerminalStatus,
|
||||
isVendorPortalUpcomingDispatch,
|
||||
vendorPortalStatusClass,
|
||||
} from "@/domain/vendor-portal/lib/status-helpers";
|
||||
|
||||
describe("vendorPortalStatusClass", () => {
|
||||
it("applies a distinct class for the Refused status", () => {
|
||||
expect(vendorPortalStatusClass("Refused")).toBe("vp-status-pill vp-status-refused");
|
||||
});
|
||||
|
||||
it("keeps the established class for existing statuses", () => {
|
||||
expect(vendorPortalStatusClass("Sent")).toBe("vp-status-pill vp-status-sent");
|
||||
expect(vendorPortalStatusClass("Cancelled")).toBe("vp-status-pill vp-status-cancelled");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isVendorPortalLockedStatus", () => {
|
||||
it("adds Refused without regressing the established Completed behavior", () => {
|
||||
expect(isVendorPortalLockedStatus("Refused")).toBe(true);
|
||||
expect(isVendorPortalLockedStatus("Verified")).toBe(true);
|
||||
expect(isVendorPortalLockedStatus("Cancelled")).toBe(true);
|
||||
expect(isVendorPortalLockedStatus("Completed")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isVendorPortalTerminalStatus", () => {
|
||||
it("treats Refused, Verified, Cancelled, and Completed as terminal", () => {
|
||||
expect(isVendorPortalTerminalStatus("Refused")).toBe(true);
|
||||
expect(isVendorPortalTerminalStatus("Verified")).toBe(true);
|
||||
expect(isVendorPortalTerminalStatus("Cancelled")).toBe(true);
|
||||
expect(isVendorPortalTerminalStatus("Completed")).toBe(true);
|
||||
});
|
||||
|
||||
it("treats active statuses as non-terminal", () => {
|
||||
expect(isVendorPortalTerminalStatus("Sent")).toBe(false);
|
||||
expect(isVendorPortalTerminalStatus("Acknowledged")).toBe(false);
|
||||
expect(isVendorPortalTerminalStatus("In Progress")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isVendorPortalUpcomingDispatch", () => {
|
||||
const now = new Date("2026-08-10T12:00:00Z");
|
||||
|
||||
it("includes a non-terminal dispatch scheduled in the future", () => {
|
||||
expect(
|
||||
isVendorPortalUpcomingDispatch(
|
||||
{ status: "Acknowledged", scheduledDate: "2026-08-11T09:00:00Z" },
|
||||
now,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("excludes terminal statuses even when scheduled in the future", () => {
|
||||
for (const status of ["Refused", "Verified", "Cancelled", "Completed"]) {
|
||||
expect(
|
||||
isVendorPortalUpcomingDispatch({ status, scheduledDate: "2026-08-11T09:00:00Z" }, now),
|
||||
).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("excludes dispatches without a scheduled date", () => {
|
||||
expect(isVendorPortalUpcomingDispatch({ status: "Sent", scheduledDate: undefined }, now)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("excludes past scheduled dates", () => {
|
||||
expect(
|
||||
isVendorPortalUpcomingDispatch(
|
||||
{ status: "In Progress", scheduledDate: "2026-08-09T09:00:00Z" },
|
||||
now,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatVendorPortalDateTime", () => {
|
||||
it("returns an empty string for missing or invalid values", () => {
|
||||
expect(formatVendorPortalDateTime(undefined)).toBe("");
|
||||
expect(formatVendorPortalDateTime("not-a-date")).toBe("");
|
||||
});
|
||||
});
|
||||