phase-2: asset register, detail overview, asset picker, attachments
This commit is contained in:
@@ -0,0 +1,433 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { AlertCircle } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ApiError } from "@/api/client";
|
||||
import {
|
||||
assetsApi,
|
||||
type AssetItem,
|
||||
type AssetStatus,
|
||||
type AssetCriticality,
|
||||
} from "@/api/assets";
|
||||
import {
|
||||
departmentsApi,
|
||||
locationsApi,
|
||||
categoriesApi,
|
||||
vendorsApi,
|
||||
} from "@/api/masters";
|
||||
|
||||
const assetSchema = z.object({
|
||||
asset_code: z.string().trim().min(1, "Asset code is required"),
|
||||
serial_no: z.string().trim().min(1, "Serial number is required"),
|
||||
name: z.string().trim().min(1, "Equipment name is required"),
|
||||
category_id: z.coerce.number().int().min(1, "Select a category"),
|
||||
department_id: z.coerce.number().int().min(1, "Select a department"),
|
||||
location_id: z.coerce.number().int().min(1, "Select a location"),
|
||||
supplier_id: z.string().optional(),
|
||||
purchase_value: z.string().optional(),
|
||||
purchase_date: z.string().optional(),
|
||||
installation_date: z.string().optional(),
|
||||
status: z.enum(["in_service", "under_repair", "out_of_service", "condemned"]),
|
||||
criticality: z.enum(["critical", "non_critical"]),
|
||||
requires_calibration: z.boolean(),
|
||||
insurance_applicable: z.boolean(),
|
||||
remarks: z.string().optional(),
|
||||
});
|
||||
|
||||
type AssetFormValues = z.infer<typeof assetSchema>;
|
||||
|
||||
interface AssetFormModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
editing?: AssetItem | null;
|
||||
coordinatorOnly?: boolean;
|
||||
}
|
||||
|
||||
const inputCls =
|
||||
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 disabled:text-gray-500";
|
||||
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
|
||||
const errCls = "text-xs text-red-600 mt-1";
|
||||
|
||||
export function AssetFormModal({
|
||||
open,
|
||||
onClose,
|
||||
editing = null,
|
||||
coordinatorOnly = false,
|
||||
}: AssetFormModalProps) {
|
||||
const qc = useQueryClient();
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
const locsQuery = useQuery({
|
||||
queryKey: ["locations", "active-only"],
|
||||
queryFn: () => locationsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
const catsQuery = useQuery({
|
||||
queryKey: ["categories", "active-only"],
|
||||
queryFn: () => categoriesApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
const allLocations = locsQuery.data?.items ?? [];
|
||||
const categories = catsQuery.data?.items ?? [];
|
||||
const vendors = vendorsQuery.data?.items ?? [];
|
||||
|
||||
const defaultDeptId = editing?.department_id ?? departments[0]?.id ?? 0;
|
||||
const defaultLocId =
|
||||
editing?.location_id ??
|
||||
allLocations.find((l) => l.department_id === defaultDeptId)?.id ??
|
||||
0;
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
reset,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<AssetFormValues>({
|
||||
resolver: zodResolver(assetSchema),
|
||||
defaultValues: {
|
||||
asset_code: "",
|
||||
serial_no: "",
|
||||
name: "",
|
||||
category_id: 0,
|
||||
department_id: 0,
|
||||
location_id: 0,
|
||||
supplier_id: "",
|
||||
purchase_value: "",
|
||||
purchase_date: "",
|
||||
installation_date: "",
|
||||
status: "in_service",
|
||||
criticality: "non_critical",
|
||||
requires_calibration: false,
|
||||
insurance_applicable: false,
|
||||
remarks: "",
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setServerError(null);
|
||||
if (editing) {
|
||||
reset({
|
||||
asset_code: editing.asset_code,
|
||||
serial_no: editing.serial_no ?? "",
|
||||
name: editing.name,
|
||||
category_id: editing.category_id,
|
||||
department_id: editing.department_id,
|
||||
location_id: editing.location_id,
|
||||
supplier_id: editing.supplier_id ? String(editing.supplier_id) : "",
|
||||
purchase_value: editing.purchase_value != null ? String(editing.purchase_value) : "",
|
||||
purchase_date: editing.purchase_date ?? "",
|
||||
installation_date: editing.installation_date ?? "",
|
||||
status: editing.status,
|
||||
criticality: editing.criticality,
|
||||
requires_calibration: editing.requires_calibration,
|
||||
insurance_applicable: editing.insurance_applicable,
|
||||
remarks: editing.remarks ?? "",
|
||||
});
|
||||
} else {
|
||||
reset({
|
||||
asset_code: "",
|
||||
serial_no: "",
|
||||
name: "",
|
||||
category_id: categories[0]?.id ?? 0,
|
||||
department_id: defaultDeptId,
|
||||
location_id: defaultLocId,
|
||||
supplier_id: "",
|
||||
purchase_value: "",
|
||||
purchase_date: "",
|
||||
installation_date: "",
|
||||
status: "in_service",
|
||||
criticality: "non_critical",
|
||||
requires_calibration: false,
|
||||
insurance_applicable: false,
|
||||
remarks: "",
|
||||
});
|
||||
}
|
||||
}, [open, editing, categories.length, defaultDeptId, defaultLocId, reset]);
|
||||
|
||||
const watchedDeptId = Number(watch("department_id"));
|
||||
const filteredLocations = useMemo(
|
||||
() => allLocations.filter((l) => l.department_id === watchedDeptId),
|
||||
[allLocations, watchedDeptId]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || coordinatorOnly) return;
|
||||
const currentLoc = Number(watch("location_id"));
|
||||
if (
|
||||
watchedDeptId > 0 &&
|
||||
filteredLocations.length > 0 &&
|
||||
!filteredLocations.some((l) => l.id === currentLoc)
|
||||
) {
|
||||
setValue("location_id", filteredLocations[0].id);
|
||||
} else if (watchedDeptId > 0 && filteredLocations.length === 0 && currentLoc !== 0) {
|
||||
setValue("location_id", 0);
|
||||
}
|
||||
}, [watchedDeptId, filteredLocations, open, coordinatorOnly, setValue, watch]);
|
||||
|
||||
async function onSubmit(values: AssetFormValues) {
|
||||
setServerError(null);
|
||||
try {
|
||||
if (editing && coordinatorOnly) {
|
||||
await assetsApi.update(editing.id, {
|
||||
requires_calibration: values.requires_calibration,
|
||||
insurance_applicable: values.insurance_applicable,
|
||||
remarks: values.remarks?.trim() || null,
|
||||
});
|
||||
} else {
|
||||
const payload = {
|
||||
asset_code: values.asset_code.trim(),
|
||||
serial_no: values.serial_no.trim(),
|
||||
name: values.name.trim(),
|
||||
category_id: values.category_id,
|
||||
department_id: values.department_id,
|
||||
location_id: values.location_id,
|
||||
supplier_id: values.supplier_id ? Number(values.supplier_id) : null,
|
||||
purchase_value:
|
||||
values.purchase_value && values.purchase_value.trim() !== ""
|
||||
? Number(values.purchase_value)
|
||||
: null,
|
||||
purchase_date: values.purchase_date || null,
|
||||
installation_date: values.installation_date || null,
|
||||
status: values.status as AssetStatus,
|
||||
criticality: values.criticality as AssetCriticality,
|
||||
requires_calibration: values.requires_calibration,
|
||||
insurance_applicable: values.insurance_applicable,
|
||||
remarks: values.remarks?.trim() || null,
|
||||
};
|
||||
if (editing) {
|
||||
await assetsApi.update(editing.id, payload);
|
||||
} else {
|
||||
await assetsApi.create(payload);
|
||||
}
|
||||
}
|
||||
|
||||
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
if (editing) {
|
||||
await qc.invalidateQueries({ queryKey: ["asset-overview", editing.id] });
|
||||
}
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setServerError(err instanceof ApiError ? err.detail : "Failed to save asset.");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={editing ? `Edit Asset — ${editing.asset_code}` : "Add New Asset"}
|
||||
className="max-w-2xl"
|
||||
>
|
||||
{coordinatorOnly && (
|
||||
<div className="mb-3 rounded-md bg-blue-50 border border-blue-200 px-3 py-2 text-xs text-blue-800">
|
||||
Coordinator permissions: only calibration requirement, insurance applicability, and remarks can be edited.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{serverError && (
|
||||
<div className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700">
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{serverError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Asset Code *</label>
|
||||
<input
|
||||
{...register("asset_code")}
|
||||
disabled={coordinatorOnly}
|
||||
placeholder="e.g. PHRC-ICU-0099"
|
||||
className={inputCls}
|
||||
/>
|
||||
{errors.asset_code && <p className={errCls}>{errors.asset_code.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Serial No *</label>
|
||||
<input
|
||||
{...register("serial_no")}
|
||||
disabled={coordinatorOnly}
|
||||
placeholder="Manufacturer serial number"
|
||||
className={inputCls}
|
||||
/>
|
||||
{errors.serial_no && <p className={errCls}>{errors.serial_no.message}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Equipment Name *</label>
|
||||
<input
|
||||
{...register("name")}
|
||||
disabled={coordinatorOnly}
|
||||
placeholder="e.g. Multipara Patient Monitor"
|
||||
className={inputCls}
|
||||
/>
|
||||
{errors.name && <p className={errCls}>{errors.name.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Category *</label>
|
||||
<select {...register("category_id")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value={0}>Select category...</option>
|
||||
{categories.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{errors.category_id && <p className={errCls}>{errors.category_id.message}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Department *</label>
|
||||
<select {...register("department_id")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value={0}>Select department...</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={d.id}>
|
||||
{d.name} ({d.code})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{errors.department_id && <p className={errCls}>{errors.department_id.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Location *</label>
|
||||
<select {...register("location_id")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value={0}>
|
||||
{filteredLocations.length === 0 ? "No locations in department" : "Select location..."}
|
||||
</option>
|
||||
{filteredLocations.map((l) => (
|
||||
<option key={l.id} value={l.id}>
|
||||
{l.name}
|
||||
{l.floor_wing ? ` (${l.floor_wing})` : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{errors.location_id && <p className={errCls}>{errors.location_id.message}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Supplier</label>
|
||||
<select {...register("supplier_id")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value="">None / Not specified</option>
|
||||
{vendors.map((v) => (
|
||||
<option key={v.id} value={String(v.id)}>
|
||||
{v.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Purchase Value (INR)</label>
|
||||
<input
|
||||
type="number"
|
||||
step="1"
|
||||
min="0"
|
||||
{...register("purchase_value")}
|
||||
disabled={coordinatorOnly}
|
||||
placeholder="e.g. 450000"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Purchase Date</label>
|
||||
<input
|
||||
type="date"
|
||||
{...register("purchase_date")}
|
||||
disabled={coordinatorOnly}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Installation Date</label>
|
||||
<input
|
||||
type="date"
|
||||
{...register("installation_date")}
|
||||
disabled={coordinatorOnly}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Status *</label>
|
||||
<select {...register("status")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value="in_service">In Service</option>
|
||||
<option value="under_repair">Under Repair</option>
|
||||
<option value="out_of_service">Out of Service</option>
|
||||
<option value="condemned">Condemned</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Criticality *</label>
|
||||
<select {...register("criticality")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value="critical">Critical</option>
|
||||
<option value="non_critical">Non-Critical</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-6 pt-1">
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
{...register("requires_calibration")}
|
||||
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
Requires Calibration
|
||||
</label>
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
{...register("insurance_applicable")}
|
||||
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
Insurance Applicable
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Remarks</label>
|
||||
<textarea {...register("remarks")} rows={2} className={inputCls} />
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting}>
|
||||
{editing ? "Save Changes" : "Create Asset"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { Search, X, ShieldCheck, Ban } from "lucide-react";
|
||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { CoverageBadge, AssetStatusBadge } from "./StatusBadge";
|
||||
|
||||
interface AssetPickerProps {
|
||||
selectedAsset: AssetLookupItem | null;
|
||||
onSelect: (asset: AssetLookupItem | null) => void;
|
||||
departmentId?: number;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function AssetPicker({
|
||||
selectedAsset,
|
||||
onSelect,
|
||||
departmentId,
|
||||
disabled = false,
|
||||
placeholder = "Search by asset code, equipment name, or serial no...",
|
||||
}: AssetPickerProps) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [debouncedQuery, setDebouncedQuery] = useState("");
|
||||
const [results, setResults] = useState<AssetLookupItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setDebouncedQuery(query);
|
||||
}, 250);
|
||||
return () => clearTimeout(timer);
|
||||
}, [query]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || disabled) return;
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
assetsApi
|
||||
.lookup({ q: debouncedQuery, department_id: departmentId, limit: 25 })
|
||||
.then((res) => {
|
||||
if (!cancelled) setResults(res.items);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setResults([]);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [debouncedQuery, departmentId, open, disabled]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleOutsideClick(e: MouseEvent) {
|
||||
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||
setOpen(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", handleOutsideClick);
|
||||
return () => document.removeEventListener("mousedown", handleOutsideClick);
|
||||
}, []);
|
||||
|
||||
if (selectedAsset) {
|
||||
const isUnderWarranty =
|
||||
selectedAsset.warranty_status === "active" || selectedAsset.warranty_status === "expiring";
|
||||
const isCondemned = selectedAsset.status === "condemned";
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-blue-200 bg-blue-50/40 p-4 space-y-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-mono text-sm font-bold text-[#1e3a8a]">
|
||||
{selectedAsset.asset_code}
|
||||
</span>
|
||||
<span className="font-semibold text-gray-900">{selectedAsset.name}</span>
|
||||
<AssetStatusBadge status={selectedAsset.status} />
|
||||
{isUnderWarranty && (
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-800 border border-emerald-300">
|
||||
<ShieldCheck className="h-3 w-3" />
|
||||
Under Warranty
|
||||
</span>
|
||||
)}
|
||||
{isCondemned && (
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-300">
|
||||
<Ban className="h-3 w-3" />
|
||||
Condemned Asset
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{selectedAsset.serial_no && (
|
||||
<div className="text-xs text-gray-500 mt-0.5">
|
||||
Serial No: <span className="font-mono">{selectedAsset.serial_no}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!disabled && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelect(null);
|
||||
setQuery("");
|
||||
}}
|
||||
aria-label="Clear selected asset"
|
||||
className="inline-flex items-center gap-1 text-xs text-gray-600 hover:text-gray-900 px-2 py-1 rounded border border-gray-200 bg-white"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
Change
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs">
|
||||
<div>
|
||||
<div className="text-gray-500">Category</div>
|
||||
<div className="font-medium text-gray-800">{selectedAsset.category_name || "—"}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Department</div>
|
||||
<div className="font-medium text-gray-800">{selectedAsset.department_name || "—"}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Location</div>
|
||||
<div className="font-medium text-gray-800">{selectedAsset.location_name || "—"}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Warranty</div>
|
||||
<div className="mt-0.5 flex items-center gap-1.5 flex-wrap">
|
||||
<CoverageBadge status={selectedAsset.warranty_status} />
|
||||
{selectedAsset.warranty_end_date && (
|
||||
<span className="text-gray-600">
|
||||
till {formatDate(selectedAsset.warranty_end_date)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Contract</div>
|
||||
<div className="font-medium text-gray-800">
|
||||
{selectedAsset.contract_summary ||
|
||||
(selectedAsset.contract_type
|
||||
? `${selectedAsset.contract_type} (${selectedAsset.contract_status})`
|
||||
: "None")}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Insurance</div>
|
||||
<div className="font-medium text-gray-800">
|
||||
{selectedAsset.insurance_summary || selectedAsset.insurance_status || "None"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="relative">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
disabled={disabled}
|
||||
value={query}
|
||||
onFocus={() => setOpen(true)}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setOpen(true);
|
||||
}}
|
||||
placeholder={placeholder}
|
||||
className="w-full pl-9 pr-4 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white disabled:bg-gray-100"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{open && !disabled && (
|
||||
<div className="absolute left-0 right-0 mt-1 max-h-72 overflow-y-auto bg-white border border-gray-200 rounded-md shadow-lg z-30 divide-y divide-gray-100">
|
||||
{loading ? (
|
||||
<div className="px-4 py-3 text-xs text-gray-500">Searching assets...</div>
|
||||
) : results.length === 0 ? (
|
||||
<div className="px-4 py-3 text-xs text-gray-500">No matching assets found.</div>
|
||||
) : (
|
||||
results.map((item) => {
|
||||
const underWarranty =
|
||||
item.warranty_status === "active" || item.warranty_status === "expiring";
|
||||
const condemned = item.status === "condemned";
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelect(item);
|
||||
setOpen(false);
|
||||
}}
|
||||
className="w-full text-left px-3 py-2.5 hover:bg-blue-50/60 transition-colors flex items-center justify-between gap-2"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium text-gray-900 truncate">
|
||||
<span className="font-mono text-[#1e3a8a]">{item.asset_code}</span> —{" "}
|
||||
{item.name}
|
||||
{item.serial_no ? ` (${item.serial_no})` : ""}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 truncate">
|
||||
{item.department_name || "—"} • {item.location_name || "—"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 shrink-0">
|
||||
{underWarranty && (
|
||||
<span className="px-2 py-0.5 rounded-full text-[11px] font-medium bg-emerald-100 text-emerald-800">
|
||||
Under Warranty
|
||||
</span>
|
||||
)}
|
||||
{condemned && (
|
||||
<span className="px-2 py-0.5 rounded-full text-[11px] font-medium bg-red-100 text-red-800">
|
||||
Condemned
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import { useState, useRef } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Upload,
|
||||
FileText,
|
||||
Image as ImageIcon,
|
||||
Download,
|
||||
Trash2,
|
||||
AlertCircle,
|
||||
ExternalLink,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
attachmentsApi,
|
||||
type AttachmentEntityType,
|
||||
type AttachmentItem,
|
||||
} from "@/api/attachments";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
const MAX_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB
|
||||
const ALLOWED_EXTENSIONS = [".jpg", ".jpeg", ".png", ".pdf"];
|
||||
const ALLOWED_MIME_TYPES = ["image/jpeg", "image/png", "application/pdf"];
|
||||
|
||||
export function validateAttachmentFile(file: File): string | null {
|
||||
const nameLower = file.name.toLowerCase();
|
||||
const hasAllowedExt = ALLOWED_EXTENSIONS.some((ext) => nameLower.endsWith(ext));
|
||||
const hasAllowedMime = !file.type || ALLOWED_MIME_TYPES.includes(file.type);
|
||||
|
||||
if (!hasAllowedExt || !hasAllowedMime) {
|
||||
return "Invalid file type. Only JPG, PNG, and PDF files are allowed.";
|
||||
}
|
||||
if (file.size > MAX_SIZE_BYTES) {
|
||||
return "File is too large. Maximum allowed size is 10 MB.";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
||||
}
|
||||
|
||||
interface AttachmentsProps {
|
||||
entityType: AttachmentEntityType;
|
||||
entityId: number;
|
||||
canUpload: boolean;
|
||||
canDelete: boolean;
|
||||
}
|
||||
|
||||
export function Attachments({
|
||||
entityType,
|
||||
entityId,
|
||||
canUpload,
|
||||
canDelete,
|
||||
}: AttachmentsProps) {
|
||||
const qc = useQueryClient();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [dragActive, setDragActive] = useState(false);
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||
const [confirmDeleteId, setConfirmDeleteId] = useState<number | null>(null);
|
||||
|
||||
const queryKey = ["attachments", entityType, entityId];
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => attachmentsApi.list(entityType, entityId),
|
||||
enabled: Boolean(entityId),
|
||||
});
|
||||
|
||||
const uploadMutation = useMutation({
|
||||
mutationFn: (file: File) => attachmentsApi.upload(entityType, entityId, file),
|
||||
onSuccess: () => {
|
||||
setErrorMsg(null);
|
||||
qc.invalidateQueries({ queryKey });
|
||||
if (entityType === "asset") {
|
||||
qc.invalidateQueries({ queryKey: ["asset-overview", entityId] });
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to upload attachment.");
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => attachmentsApi.remove(id),
|
||||
onSuccess: () => {
|
||||
setConfirmDeleteId(null);
|
||||
setErrorMsg(null);
|
||||
qc.invalidateQueries({ queryKey });
|
||||
if (entityType === "asset") {
|
||||
qc.invalidateQueries({ queryKey: ["asset-overview", entityId] });
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to delete attachment.");
|
||||
},
|
||||
});
|
||||
|
||||
function handleFiles(files: FileList | null) {
|
||||
if (!files || files.length === 0) return;
|
||||
const file = files[0];
|
||||
const validationError = validateAttachmentFile(file);
|
||||
if (validationError) {
|
||||
setErrorMsg(validationError);
|
||||
return;
|
||||
}
|
||||
setErrorMsg(null);
|
||||
uploadMutation.mutate(file);
|
||||
}
|
||||
|
||||
async function handleDownload(att: AttachmentItem, preview = false) {
|
||||
try {
|
||||
setErrorMsg(null);
|
||||
await attachmentsApi.download(att.id, att.original_name, preview);
|
||||
} catch (err) {
|
||||
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to download file.");
|
||||
}
|
||||
}
|
||||
|
||||
const items = data?.items ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{errorMsg && (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{errorMsg}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canUpload && (
|
||||
<div
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setDragActive(true);
|
||||
}}
|
||||
onDragLeave={() => setDragActive(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setDragActive(false);
|
||||
handleFiles(e.dataTransfer.files);
|
||||
}}
|
||||
className={`border-2 border-dashed rounded-lg p-5 text-center transition-colors ${
|
||||
dragActive
|
||||
? "border-[#1e3a8a] bg-blue-50/50"
|
||||
: "border-gray-300 bg-gray-50/50 hover:border-gray-400"
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".jpg,.jpeg,.png,.pdf"
|
||||
aria-label="Upload attachment"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
handleFiles(e.target.files);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
<Upload className="h-6 w-6 text-gray-400 mx-auto mb-2" />
|
||||
<p className="text-sm text-gray-600">
|
||||
Drag and drop a file here, or{" "}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={uploadMutation.isPending}
|
||||
className="text-[#1e3a8a] font-medium hover:underline disabled:opacity-50"
|
||||
>
|
||||
browse
|
||||
</button>
|
||||
</p>
|
||||
<p className="text-xs text-gray-400 mt-1">
|
||||
Allowed: JPG, PNG, PDF • Max size: 10 MB
|
||||
</p>
|
||||
{uploadMutation.isPending && (
|
||||
<p className="text-xs text-blue-600 mt-2">Uploading...</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-2">
|
||||
{[1, 2].map((i) => (
|
||||
<div key={i} className="h-14 bg-gray-100 rounded-md animate-pulse" />
|
||||
))}
|
||||
</div>
|
||||
) : items.length === 0 ? (
|
||||
<div className="text-sm text-gray-400 py-6 text-center border border-gray-200 rounded-lg bg-white">
|
||||
No attachments uploaded yet.
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white border border-gray-200 rounded-lg divide-y divide-gray-100">
|
||||
{items.map((att) => {
|
||||
const isPdf = att.mime_type === "application/pdf";
|
||||
return (
|
||||
<div
|
||||
key={att.id}
|
||||
className="flex items-center justify-between gap-3 px-4 py-3 hover:bg-gray-50/60"
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div className="h-9 w-9 rounded-md bg-blue-50 text-[#1e3a8a] flex items-center justify-center shrink-0">
|
||||
{isPdf ? <FileText className="h-5 w-5" /> : <ImageIcon className="h-5 w-5" />}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium text-gray-900 truncate">
|
||||
{att.original_name}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{formatBytes(att.size_bytes)}
|
||||
{att.uploaded_by_name ? ` • Uploaded by ${att.uploaded_by_name}` : ""}
|
||||
{" • "}
|
||||
{formatDateTime(att.uploaded_at)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5 shrink-0">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleDownload(att, true)}
|
||||
title="Preview in new tab"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5 mr-1" />
|
||||
Preview
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleDownload(att, false)}
|
||||
title="Download file"
|
||||
>
|
||||
<Download className="h-3.5 w-3.5 mr-1" />
|
||||
Download
|
||||
</Button>
|
||||
{canDelete && (
|
||||
confirmDeleteId === att.id ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="danger"
|
||||
size="sm"
|
||||
loading={deleteMutation.isPending}
|
||||
onClick={() => deleteMutation.mutate(att.id)}
|
||||
>
|
||||
Confirm
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setConfirmDeleteId(null)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-red-600 hover:bg-red-50"
|
||||
onClick={() => setConfirmDeleteId(att.id)}
|
||||
aria-label={`Delete ${att.original_name}`}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import {
|
||||
CheckCircle2,
|
||||
Wrench,
|
||||
AlertTriangle,
|
||||
Ban,
|
||||
Clock,
|
||||
ShieldAlert,
|
||||
MinusCircle,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type {
|
||||
AssetStatus,
|
||||
AssetCriticality,
|
||||
CoverageStatus,
|
||||
AlertSeverity,
|
||||
CalibrationStatus,
|
||||
} from "@/api/assets";
|
||||
|
||||
export function AssetStatusBadge({
|
||||
status,
|
||||
className,
|
||||
}: {
|
||||
status: AssetStatus | string;
|
||||
className?: string;
|
||||
}) {
|
||||
const map: Record<string, { label: string; cls: string; dot: string; icon: React.ReactNode }> = {
|
||||
in_service: {
|
||||
label: "In Service",
|
||||
cls: "bg-green-100 text-green-800 border border-green-200",
|
||||
dot: "bg-green-600",
|
||||
icon: <CheckCircle2 className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
under_repair: {
|
||||
label: "Under Repair",
|
||||
cls: "bg-red-100 text-red-800 border border-red-200",
|
||||
dot: "bg-red-600",
|
||||
icon: <Wrench className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
out_of_service: {
|
||||
label: "Out of Service",
|
||||
cls: "bg-amber-100 text-amber-800 border border-amber-200",
|
||||
dot: "bg-amber-600",
|
||||
icon: <AlertTriangle className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
condemned: {
|
||||
label: "Condemned",
|
||||
cls: "bg-gray-100 text-gray-700 border border-gray-300",
|
||||
dot: "bg-gray-500",
|
||||
icon: <Ban className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
};
|
||||
|
||||
const cfg = map[status] ?? {
|
||||
label: status,
|
||||
cls: "bg-gray-100 text-gray-700",
|
||||
dot: "bg-gray-500",
|
||||
icon: <MinusCircle className="h-3 w-3 shrink-0" />,
|
||||
};
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap",
|
||||
cfg.cls,
|
||||
className
|
||||
)}
|
||||
>
|
||||
{cfg.icon}
|
||||
<span>{cfg.label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function CoverageBadge({
|
||||
status,
|
||||
severity,
|
||||
prefix,
|
||||
className,
|
||||
}: {
|
||||
status: CoverageStatus | string;
|
||||
severity?: AlertSeverity | string;
|
||||
prefix?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
let cls = "bg-gray-100 text-gray-600 border border-gray-200";
|
||||
let dot = "bg-gray-400";
|
||||
let label = "None";
|
||||
|
||||
if (status === "active") {
|
||||
cls = "bg-green-100 text-green-800 border border-green-200";
|
||||
dot = "bg-green-600";
|
||||
label = "Active";
|
||||
} else if (status === "expiring") {
|
||||
if (severity === "red") {
|
||||
cls = "bg-red-100 text-red-800 border border-red-200";
|
||||
dot = "bg-red-600";
|
||||
} else {
|
||||
cls = "bg-yellow-100 text-yellow-800 border border-yellow-300";
|
||||
dot = "bg-yellow-500";
|
||||
}
|
||||
label = "Expiring";
|
||||
} else if (status === "expired") {
|
||||
cls = "bg-red-100 text-red-800 border border-red-200";
|
||||
dot = "bg-red-600";
|
||||
label = "Expired";
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap",
|
||||
cls,
|
||||
className
|
||||
)}
|
||||
>
|
||||
<span className={cn("h-1.5 w-1.5 rounded-full shrink-0", dot)} />
|
||||
<span>{prefix ? `${prefix}: ${label}` : label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function CalibrationBadge({
|
||||
status,
|
||||
severity,
|
||||
className,
|
||||
}: {
|
||||
status: CalibrationStatus | string;
|
||||
severity?: AlertSeverity | string;
|
||||
className?: string;
|
||||
}) {
|
||||
let cls = "bg-gray-100 text-gray-600 border border-gray-200";
|
||||
let icon: React.ReactNode = <MinusCircle className="h-3 w-3 shrink-0" />;
|
||||
let label = "None";
|
||||
|
||||
if (status === "completed") {
|
||||
cls = "bg-green-100 text-green-800 border border-green-200";
|
||||
icon = <CheckCircle2 className="h-3 w-3 shrink-0" />;
|
||||
label = "Completed";
|
||||
} else if (status === "upcoming") {
|
||||
cls = "bg-blue-100 text-blue-800 border border-blue-200";
|
||||
icon = <Clock className="h-3 w-3 shrink-0" />;
|
||||
label = "Upcoming";
|
||||
} else if (status === "due") {
|
||||
cls =
|
||||
severity === "red"
|
||||
? "bg-red-100 text-red-800 border border-red-200"
|
||||
: "bg-yellow-100 text-yellow-800 border border-yellow-300";
|
||||
icon = <AlertTriangle className="h-3 w-3 shrink-0" />;
|
||||
label = "Due";
|
||||
} else if (status === "overdue") {
|
||||
cls = "bg-red-100 text-red-800 border border-red-200";
|
||||
icon = <AlertTriangle className="h-3 w-3 shrink-0" />;
|
||||
label = "Overdue";
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap",
|
||||
cls,
|
||||
className
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function CriticalityBadge({
|
||||
criticality,
|
||||
className,
|
||||
}: {
|
||||
criticality: AssetCriticality | string;
|
||||
className?: string;
|
||||
}) {
|
||||
if (criticality === "critical") {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold border border-red-400 text-red-700 bg-red-50 whitespace-nowrap",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<ShieldAlert className="h-3 w-3 shrink-0" />
|
||||
Critical
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-700 border border-slate-200 whitespace-nowrap",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-slate-500 shrink-0" />
|
||||
Non-Critical
|
||||
</span>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user