mirror of
https://github.com/Sea-Haven-Industries/shoc-frontend-new.git
synced 2026-10-06 20:32:05 +00:00
* feat(vendors): complete operations roadmap frontend * test(vendors): cover work order assignment flow * fix(vendors): address review feedback * fix(vendors): prevent stale preference saves * fix(vendors): require truthful appointment bounds
254 lines
8.3 KiB
TypeScript
254 lines
8.3 KiB
TypeScript
import { useEffect, useMemo, useState } from "react";
|
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
import {
|
|
Alert,
|
|
Autocomplete,
|
|
Box,
|
|
Button,
|
|
IconButton,
|
|
Paper,
|
|
Stack,
|
|
TextField,
|
|
} from "@mui/material";
|
|
import { ArrowDown, ArrowUp, Trash2 } from "lucide-react";
|
|
import { toast } from "react-toastify";
|
|
import { Text } from "@/components/ui/text";
|
|
import { vendorOperationsApi } from "@/domain/vendor-operations/api/vendor-operations-api";
|
|
import type { SiteVendorPreference } from "@/domain/vendor-operations/types/vendor-operations";
|
|
import {
|
|
useWorkOrderLocations,
|
|
useWorkOrderVendors,
|
|
} from "@/domain/work-orders/use-cases/use-work-order-detail";
|
|
import type { VendorDropdownItem } from "@/domain/work-orders/types/work-order";
|
|
|
|
const EMPTY_PREFERENCES: SiteVendorPreference[] = [];
|
|
|
|
type AddVendorPreferenceControlsProps = {
|
|
trade: string;
|
|
onTradeChange: (value: string) => void;
|
|
vendorOptions: VendorDropdownItem[];
|
|
vendors: VendorDropdownItem[];
|
|
vendorId: number | null;
|
|
onVendorChange: (vendorId: number | null) => void;
|
|
onAdd: () => void;
|
|
};
|
|
|
|
function AddVendorPreferenceControls({
|
|
trade,
|
|
onTradeChange,
|
|
vendorOptions,
|
|
vendors,
|
|
vendorId,
|
|
onVendorChange,
|
|
onAdd,
|
|
}: AddVendorPreferenceControlsProps) {
|
|
return (
|
|
<Paper variant="outlined" className="p-4">
|
|
<Stack direction={{ xs: "column", md: "row" }} spacing={2}>
|
|
<TextField
|
|
label="Trade scope (optional)"
|
|
value={trade}
|
|
onChange={(event) => onTradeChange(event.target.value)}
|
|
/>
|
|
<Autocomplete
|
|
options={vendorOptions}
|
|
getOptionLabel={(option) =>
|
|
`${option.companyName}${option.tradeSpecialties ? ` · ${option.tradeSpecialties}` : ""}`
|
|
}
|
|
value={vendors.find((vendor) => Number(vendor.id) === vendorId) ?? null}
|
|
onChange={(_event, option) => onVendorChange(option ? Number(option.id) : null)}
|
|
renderInput={(params) => <TextField {...params} label="Vendor / technician" />}
|
|
className="flex-1"
|
|
/>
|
|
<Button variant="contained" onClick={onAdd} disabled={vendorId == null}>
|
|
Add
|
|
</Button>
|
|
</Stack>
|
|
</Paper>
|
|
);
|
|
}
|
|
|
|
type PreferenceRowProps = {
|
|
item: SiteVendorPreference;
|
|
index: number;
|
|
total: number;
|
|
onMove: (index: number, offset: number) => void;
|
|
onRemove: (index: number) => void;
|
|
};
|
|
|
|
function PreferenceRow({ item, index, total, onMove, onRemove }: PreferenceRowProps) {
|
|
return (
|
|
<Paper variant="outlined" className="p-3">
|
|
<Stack direction="row" spacing={1} sx={{ alignItems: "center" }}>
|
|
<Text className="flex-1">
|
|
{index + 1}. {item.vendorName} {item.trade ? `· ${item.trade}` : "· All trades"}
|
|
</Text>
|
|
{item.isStale && (
|
|
<Alert severity="warning">
|
|
<Text as="span">Stale preference</Text>
|
|
</Alert>
|
|
)}
|
|
<IconButton
|
|
aria-label={`Move ${item.vendorName} up`}
|
|
onClick={() => onMove(index, -1)}
|
|
disabled={index === 0}
|
|
>
|
|
<ArrowUp size={18} />
|
|
</IconButton>
|
|
<IconButton
|
|
aria-label={`Move ${item.vendorName} down`}
|
|
onClick={() => onMove(index, 1)}
|
|
disabled={index === total - 1}
|
|
>
|
|
<ArrowDown size={18} />
|
|
</IconButton>
|
|
<IconButton aria-label={`Remove ${item.vendorName}`} onClick={() => onRemove(index)}>
|
|
<Trash2 size={18} />
|
|
</IconButton>
|
|
</Stack>
|
|
</Paper>
|
|
);
|
|
}
|
|
|
|
export default function VendorPreferencesPage() {
|
|
const queryClient = useQueryClient();
|
|
const [locationId, setLocationId] = useState<string | number>("");
|
|
const [draft, setDraft] = useState<SiteVendorPreference[]>([]);
|
|
const [isDirty, setIsDirty] = useState(false);
|
|
const [trade, setTrade] = useState("");
|
|
const [vendorId, setVendorId] = useState<number | null>(null);
|
|
const { data: locations = [] } = useWorkOrderLocations();
|
|
const { data: vendors = [] } = useWorkOrderVendors(trade || undefined);
|
|
const queryKey = ["vendor-operations", "site-preferences", locationId];
|
|
const { data: serverPreferences = EMPTY_PREFERENCES, error } = useQuery({
|
|
queryKey,
|
|
queryFn: () => vendorOperationsApi.sitePreferences(locationId),
|
|
enabled: locationId !== "",
|
|
});
|
|
|
|
// A background refetch must not clobber in-flight edits, so only adopt server
|
|
// data while the draft is clean (initial load, site change, or after a save).
|
|
useEffect(() => {
|
|
if (!isDirty) {
|
|
setDraft(serverPreferences);
|
|
}
|
|
}, [isDirty, serverPreferences]);
|
|
|
|
const vendorOptions = useMemo(() => {
|
|
const selectedVendorIds = new Set(draft.map((preference) => preference.vendorId));
|
|
return vendors.filter((vendor) => !selectedVendorIds.has(Number(vendor.id)));
|
|
}, [draft, vendors]);
|
|
|
|
const save = useMutation({
|
|
mutationFn: () =>
|
|
vendorOperationsApi.replaceSitePreferences(
|
|
locationId,
|
|
draft.map((item, sortOrder) => ({ vendorId: item.vendorId, trade: item.trade, sortOrder })),
|
|
),
|
|
onMutate: async () => {
|
|
await queryClient.cancelQueries({ queryKey });
|
|
},
|
|
onSuccess: (savedPreferences) => {
|
|
queryClient.setQueryData(queryKey, savedPreferences);
|
|
setDraft(savedPreferences);
|
|
setIsDirty(false);
|
|
toast.success("Preferred vendors updated");
|
|
},
|
|
onError: () => toast.error("Unable to save preferred vendors. Please try again."),
|
|
});
|
|
|
|
const move = (index: number, offset: number) => {
|
|
setDraft((current) => {
|
|
const target = index + offset;
|
|
if (target < 0 || target >= current.length) return current;
|
|
const next = [...current];
|
|
[next[index], next[target]] = [next[target]!, next[index]!];
|
|
return next.map((item, sortOrder) => ({ ...item, sortOrder }));
|
|
});
|
|
setIsDirty(true);
|
|
};
|
|
|
|
const add = () => {
|
|
const vendor = vendors.find((item) => Number(item.id) === vendorId);
|
|
if (!vendor || locationId === "") return;
|
|
setDraft((current) => [
|
|
...current,
|
|
{
|
|
id: -Date.now(),
|
|
locationId: Number(locationId),
|
|
vendorId: Number(vendor.id),
|
|
vendorName: vendor.companyName,
|
|
trade: trade.trim() || undefined,
|
|
sortOrder: current.length,
|
|
isStale: false,
|
|
},
|
|
]);
|
|
setVendorId(null);
|
|
setIsDirty(true);
|
|
};
|
|
|
|
const remove = (index: number) => {
|
|
setDraft((current) => current.filter((_, row) => row !== index));
|
|
setIsDirty(true);
|
|
};
|
|
|
|
const selectLocation = (nextLocationId: string | number) => {
|
|
setLocationId(nextLocationId);
|
|
setDraft(EMPTY_PREFERENCES);
|
|
setIsDirty(false);
|
|
};
|
|
|
|
return (
|
|
<Box className="flex flex-col gap-4 p-4">
|
|
<Box>
|
|
<Text variant="title" as="h1">
|
|
Preferred vendors by site
|
|
</Text>
|
|
<Text variant="description" tone="muted">
|
|
Preferred vendors rank first, but availability, conflict, trade, active-state, and
|
|
permission checks still apply.
|
|
</Text>
|
|
</Box>
|
|
<Paper variant="outlined" className="p-4">
|
|
<Autocomplete
|
|
options={locations}
|
|
getOptionLabel={(option) => option.name}
|
|
value={locations.find((location) => location.id === locationId) ?? null}
|
|
onChange={(_event, option) => selectLocation(option?.id ?? "")}
|
|
renderInput={(params) => <TextField {...params} label="Site" />}
|
|
/>
|
|
</Paper>
|
|
<Text variant="error" when={Boolean(error)}>
|
|
Unable to load preferred vendors. Please try again.
|
|
</Text>
|
|
{locationId !== "" && (
|
|
<>
|
|
<AddVendorPreferenceControls
|
|
trade={trade}
|
|
onTradeChange={setTrade}
|
|
vendorOptions={vendorOptions}
|
|
vendors={vendors}
|
|
vendorId={vendorId}
|
|
onVendorChange={setVendorId}
|
|
onAdd={add}
|
|
/>
|
|
<Stack spacing={1}>
|
|
{draft.map((item, index) => (
|
|
<PreferenceRow
|
|
key={`${item.vendorId}-${item.trade ?? "all"}`}
|
|
item={item}
|
|
index={index}
|
|
total={draft.length}
|
|
onMove={move}
|
|
onRemove={remove}
|
|
/>
|
|
))}
|
|
</Stack>
|
|
<Button variant="contained" onClick={() => save.mutate()} disabled={save.isPending}>
|
|
{save.isPending ? "Saving…" : "Save preferences"}
|
|
</Button>
|
|
</>
|
|
)}
|
|
</Box>
|
|
);
|
|
}
|