refactor: modularize road management modules
This commit is contained in:
@@ -28,7 +28,7 @@ import { DetectionDonutChart } from '@/components/dashboard/detection-donut-char
|
|||||||
import { ChainageBarChart } from '@/components/dashboard/chainage-bar-chart';
|
import { ChainageBarChart } from '@/components/dashboard/chainage-bar-chart';
|
||||||
import { DashboardMap } from '@/components/dashboard/dashboard-map';
|
import { DashboardMap } from '@/components/dashboard/dashboard-map';
|
||||||
import { PageHeader } from '@/components/page-header';
|
import { PageHeader } from '@/components/page-header';
|
||||||
import { projectService } from '@/services/api';
|
import { projectService, projectSummaryService } from '@/services/api';
|
||||||
import { Project } from '@/types';
|
import { Project } from '@/types';
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
@@ -282,7 +282,9 @@ export default function DashboardPage() {
|
|||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
|
|
||||||
const summary: ProjectSummary = await projectService.getProjectSummary(selectedProjectId);
|
const summary = await projectSummaryService.getProjectSummary<ProjectSummary>(
|
||||||
|
selectedProjectId,
|
||||||
|
);
|
||||||
setProjectSummary(summary);
|
setProjectSummary(summary);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to load project summary:', err);
|
console.error('Failed to load project summary:', err);
|
||||||
|
|||||||
102
src/app/(modules)/package/components/PackageColumns.tsx
Normal file
102
src/app/(modules)/package/components/PackageColumns.tsx
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
import type { ColumnDef } from '@tanstack/react-table';
|
||||||
|
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||||
|
import type { Package, Project } from '@/types';
|
||||||
|
|
||||||
|
function EmptyValue() {
|
||||||
|
return <span className="text-muted-foreground">-</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function StateBadges({ value }: { value: string | null }) {
|
||||||
|
if (!value) {
|
||||||
|
return <EmptyValue />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const states = value
|
||||||
|
.split(',')
|
||||||
|
.map((state) => state.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
if (!states.length) {
|
||||||
|
return <EmptyValue />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [firstState, ...remainingStates] = states;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<Badge variant="secondary">{firstState}</Badge>
|
||||||
|
{remainingStates.length > 0 ? (
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="flex items-center justify-center rounded-full border border-border/40 bg-muted/50 px-1.5 py-0.5 text-[10px] font-bold text-muted-foreground transition-colors hover:bg-muted"
|
||||||
|
>
|
||||||
|
+{remainingStates.length}
|
||||||
|
</button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-auto p-2" align="start">
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<p className="mb-0.5 px-1 text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
|
||||||
|
Other States
|
||||||
|
</p>
|
||||||
|
{remainingStates.map((state) => (
|
||||||
|
<Badge key={state} variant="secondary">
|
||||||
|
{state}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePackageColumns(projects: Project[]) {
|
||||||
|
return useMemo<ColumnDef<Package>[]>(
|
||||||
|
() => [
|
||||||
|
{
|
||||||
|
accessorKey: 'name',
|
||||||
|
header: 'Package Name',
|
||||||
|
cell: ({ row }) => <div className="font-semibold">{row.original.name}</div>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'project_id',
|
||||||
|
header: 'Project',
|
||||||
|
cell: ({ row }) =>
|
||||||
|
projects.find((project) => project.id === row.original.project_id)?.name ||
|
||||||
|
row.original.project_id,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'project_state',
|
||||||
|
header: 'Project State',
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const project = projects.find((item) => item.id === row.original.project_id);
|
||||||
|
return <StateBadges value={project?.state ?? null} />;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'region',
|
||||||
|
header: 'Region',
|
||||||
|
cell: ({ row }) => row.original.region || <EmptyValue />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'chainage_start_km',
|
||||||
|
header: 'Start (km)',
|
||||||
|
cell: ({ row }) => row.original.chainage_start_km?.toFixed(2) ?? '0.00',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'chainage_end_km',
|
||||||
|
header: 'End (km)',
|
||||||
|
cell: ({ row }) => row.original.chainage_end_km?.toFixed(2) ?? '0.00',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[projects],
|
||||||
|
);
|
||||||
|
}
|
||||||
170
src/app/(modules)/package/components/PackageDialog.tsx
Normal file
170
src/app/(modules)/package/components/PackageDialog.tsx
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import type { ComponentProps } from 'react';
|
||||||
|
import type { FieldErrors, UseFormRegister, UseFormReturn } from 'react-hook-form';
|
||||||
|
import { Globe, Loader2, Package as PackageIcon } from 'lucide-react';
|
||||||
|
|
||||||
|
import { FormField } from '@/components/form';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select';
|
||||||
|
import type { Project } from '@/types';
|
||||||
|
|
||||||
|
import type { PackageFormValues } from '../hooks/usePackageForm';
|
||||||
|
|
||||||
|
interface PackageDialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
packageId?: string;
|
||||||
|
projects: Project[];
|
||||||
|
isProjectsLoading: boolean;
|
||||||
|
projectId: string;
|
||||||
|
onProjectChange: (projectId: string) => void;
|
||||||
|
register: UseFormRegister<PackageFormValues>;
|
||||||
|
errors: FieldErrors<PackageFormValues>;
|
||||||
|
touchedFields: UseFormReturn<PackageFormValues>['formState']['touchedFields'];
|
||||||
|
onSubmit: ComponentProps<'form'>['onSubmit'];
|
||||||
|
canSubmit: boolean;
|
||||||
|
isSaving: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PackageDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
packageId,
|
||||||
|
projects,
|
||||||
|
isProjectsLoading,
|
||||||
|
projectId,
|
||||||
|
onProjectChange,
|
||||||
|
register,
|
||||||
|
errors,
|
||||||
|
touchedFields,
|
||||||
|
onSubmit,
|
||||||
|
canSubmit,
|
||||||
|
isSaving,
|
||||||
|
}: PackageDialogProps) {
|
||||||
|
const projectErrorMessage = touchedFields.project_id ? errors.project_id?.message : undefined;
|
||||||
|
const nameErrorMessage = touchedFields.name ? errors.name?.message : undefined;
|
||||||
|
const startErrorMessage = touchedFields.chainage_start_km
|
||||||
|
? errors.chainage_start_km?.message
|
||||||
|
: undefined;
|
||||||
|
const endErrorMessage = touchedFields.chainage_end_km
|
||||||
|
? errors.chainage_end_km?.message
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="max-w-2xl" onOpenAutoFocus={(event) => event.preventDefault()}>
|
||||||
|
<DialogHeader className="gap-2">
|
||||||
|
<DialogTitle className="flex items-center gap-3 text-xl">
|
||||||
|
<div className="rounded-lg bg-primary p-2 text-primary-foreground shadow-sm">
|
||||||
|
<PackageIcon className="size-5" />
|
||||||
|
</div>
|
||||||
|
{packageId ? 'Edit Package Details' : 'Create New Package'}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-sm">
|
||||||
|
{packageId
|
||||||
|
? 'Update the technical specifications for your road infrastructure package.'
|
||||||
|
: 'Select a project and provide the essential data to establish a new package.'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<form onSubmit={onSubmit} className="space-y-6">
|
||||||
|
{!packageId ? (
|
||||||
|
<FormField label="Project" required error={projectErrorMessage}>
|
||||||
|
<Select value={projectId} onValueChange={onProjectChange}>
|
||||||
|
<SelectTrigger aria-invalid={!!projectErrorMessage}>
|
||||||
|
{isProjectsLoading ? (
|
||||||
|
<span className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
Loading...
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<SelectValue placeholder="Choose a project" />
|
||||||
|
)}
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{projects.map((project) => (
|
||||||
|
<SelectItem key={project.id} value={project.id}>
|
||||||
|
{project.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<input type="hidden" {...register('project_id')} value={projectId} readOnly />
|
||||||
|
</FormField>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="grid gap-5 md:grid-cols-2">
|
||||||
|
<FormField id="package-name" label="Package Name" required error={nameErrorMessage}>
|
||||||
|
<Input
|
||||||
|
id="package-name"
|
||||||
|
placeholder="e.g. Package 01"
|
||||||
|
aria-invalid={!!nameErrorMessage}
|
||||||
|
{...register('name')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
id="package-region"
|
||||||
|
label={
|
||||||
|
<span className="inline-flex items-center gap-2">
|
||||||
|
<Globe className="size-3.5 opacity-60" />
|
||||||
|
Region
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Input id="package-region" placeholder="e.g. North Zone" {...register('region')} />
|
||||||
|
</FormField>
|
||||||
|
|
||||||
|
<FormField id="package-start" label="Segment Start (km)" error={startErrorMessage}>
|
||||||
|
<Input
|
||||||
|
id="package-start"
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
placeholder="0.00"
|
||||||
|
aria-invalid={!!startErrorMessage}
|
||||||
|
{...register('chainage_start_km')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
|
||||||
|
<FormField id="package-end" label="Segment End (km)" error={endErrorMessage}>
|
||||||
|
<Input
|
||||||
|
id="package-end"
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
placeholder="0.00"
|
||||||
|
aria-invalid={!!endErrorMessage}
|
||||||
|
{...register('chainage_end_km')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={isSaving || !canSubmit}>
|
||||||
|
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
|
{packageId ? 'Update Package' : 'Create Package'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
51
src/app/(modules)/package/components/PackageTable.tsx
Normal file
51
src/app/(modules)/package/components/PackageTable.tsx
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import type { ColumnDef } from '@tanstack/react-table';
|
||||||
|
|
||||||
|
import { DataTable } from '@/components/data-table';
|
||||||
|
import type { Package } from '@/types';
|
||||||
|
|
||||||
|
interface PackageTableProps {
|
||||||
|
columns: ColumnDef<Package>[];
|
||||||
|
packages: Package[];
|
||||||
|
isLoading: boolean;
|
||||||
|
skip: number;
|
||||||
|
limit: number;
|
||||||
|
total: number;
|
||||||
|
onPageChange: (skip: number) => void;
|
||||||
|
onLimitChange: (limit: number) => void;
|
||||||
|
onEdit: (pkg: Package) => void;
|
||||||
|
onDelete: (pkg: Package) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PackageTable({
|
||||||
|
columns,
|
||||||
|
packages,
|
||||||
|
isLoading,
|
||||||
|
skip,
|
||||||
|
limit,
|
||||||
|
total,
|
||||||
|
onPageChange,
|
||||||
|
onLimitChange,
|
||||||
|
onEdit,
|
||||||
|
onDelete,
|
||||||
|
}: PackageTableProps) {
|
||||||
|
return (
|
||||||
|
<DataTable
|
||||||
|
title="Packages"
|
||||||
|
data={packages}
|
||||||
|
columns={columns}
|
||||||
|
onEdit={onEdit}
|
||||||
|
onDelete={onDelete}
|
||||||
|
isLoading={isLoading}
|
||||||
|
emptyTitle="No packages found."
|
||||||
|
pagination={{
|
||||||
|
skip,
|
||||||
|
limit,
|
||||||
|
totalItems: total,
|
||||||
|
onPageChange,
|
||||||
|
onLimitChange,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
20
src/app/(modules)/package/hooks/usePackageFilters.ts
Normal file
20
src/app/(modules)/package/hooks/usePackageFilters.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback, useState } from 'react';
|
||||||
|
|
||||||
|
export function usePackageFilters() {
|
||||||
|
const [skip, setSkip] = useState(0);
|
||||||
|
const [limit, setLimitValue] = useState(10);
|
||||||
|
|
||||||
|
const setLimit = useCallback((value: number) => {
|
||||||
|
setLimitValue(value);
|
||||||
|
setSkip(0);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
skip,
|
||||||
|
setSkip,
|
||||||
|
limit,
|
||||||
|
setLimit,
|
||||||
|
};
|
||||||
|
}
|
||||||
151
src/app/(modules)/package/hooks/usePackageForm.ts
Normal file
151
src/app/(modules)/package/hooks/usePackageForm.ts
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { useCallback } from 'react';
|
||||||
|
import { useForm, useWatch } from 'react-hook-form';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import { packageService } from '@/services/api';
|
||||||
|
import type { Package, PackageCreate, PackageUpdate } from '@/types';
|
||||||
|
|
||||||
|
import { packageKeys } from '../queries/packageKeys';
|
||||||
|
|
||||||
|
const optionalNumber = z.string().refine(
|
||||||
|
(value) => {
|
||||||
|
if (!value.trim()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return Number.isFinite(Number(value));
|
||||||
|
},
|
||||||
|
{ message: 'Enter a valid number' },
|
||||||
|
);
|
||||||
|
|
||||||
|
const packageFormSchema = z.object({
|
||||||
|
id: z.string().optional(),
|
||||||
|
project_id: z.string().trim().min(1, 'Project is required'),
|
||||||
|
name: z.string().trim().min(1, 'Package name is required'),
|
||||||
|
region: z.string().optional(),
|
||||||
|
chainage_start_km: optionalNumber,
|
||||||
|
chainage_end_km: optionalNumber,
|
||||||
|
});
|
||||||
|
|
||||||
|
export type PackageFormValues = z.infer<typeof packageFormSchema>;
|
||||||
|
|
||||||
|
const defaultValues: PackageFormValues = {
|
||||||
|
project_id: '',
|
||||||
|
name: '',
|
||||||
|
region: '',
|
||||||
|
chainage_start_km: '',
|
||||||
|
chainage_end_km: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
function trimOptional(value?: string) {
|
||||||
|
return value?.trim() || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toNumberOrZero(value: string) {
|
||||||
|
return value.trim() ? Number(value) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toPackagePayload(values: PackageFormValues): PackageCreate | PackageUpdate {
|
||||||
|
return {
|
||||||
|
project_id: values.project_id,
|
||||||
|
name: values.name.trim(),
|
||||||
|
region: trimOptional(values.region),
|
||||||
|
chainage_start_km: toNumberOrZero(values.chainage_start_km),
|
||||||
|
chainage_end_km: toNumberOrZero(values.chainage_end_km),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePackageForm({ onSaved }: { onSaved: () => void }) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const {
|
||||||
|
register,
|
||||||
|
handleSubmit,
|
||||||
|
reset,
|
||||||
|
setValue,
|
||||||
|
control,
|
||||||
|
formState: { errors, isSubmitting, touchedFields },
|
||||||
|
} = useForm<PackageFormValues>({
|
||||||
|
defaultValues,
|
||||||
|
mode: 'onTouched',
|
||||||
|
reValidateMode: 'onChange',
|
||||||
|
resolver: zodResolver(packageFormSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
const packageId = useWatch({ control, name: 'id' });
|
||||||
|
const projectId = useWatch({ control, name: 'project_id' }) || '';
|
||||||
|
const packageName = useWatch({ control, name: 'name' }) || '';
|
||||||
|
const canSubmit = projectId.trim().length > 0 && packageName.trim().length > 0;
|
||||||
|
|
||||||
|
const saveMutation = useMutation({
|
||||||
|
mutationFn: (values: PackageFormValues) => {
|
||||||
|
const payload = toPackagePayload(values);
|
||||||
|
return values.id
|
||||||
|
? packageService.updatePackage(values.id, payload)
|
||||||
|
: packageService.createPackage(payload as PackageCreate);
|
||||||
|
},
|
||||||
|
onSuccess: (_data, values) => {
|
||||||
|
toast.success(values.id ? 'Package updated' : 'Package created');
|
||||||
|
reset(defaultValues);
|
||||||
|
onSaved();
|
||||||
|
queryClient.invalidateQueries({ queryKey: packageKeys.all });
|
||||||
|
},
|
||||||
|
onError: (_error, values) => {
|
||||||
|
toast.error(values.id ? 'Failed to update package' : 'Failed to create package');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const onSubmit = handleSubmit(
|
||||||
|
(values) => saveMutation.mutate(values),
|
||||||
|
(formErrors) => {
|
||||||
|
if (formErrors.project_id?.message) {
|
||||||
|
toast.error(formErrors.project_id.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (formErrors.name?.message) {
|
||||||
|
toast.error(formErrors.name.message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const openCreate = useCallback(() => {
|
||||||
|
reset(defaultValues);
|
||||||
|
}, [reset]);
|
||||||
|
|
||||||
|
const openEdit = useCallback(
|
||||||
|
(pkg: Package) => {
|
||||||
|
reset({
|
||||||
|
id: pkg.id,
|
||||||
|
project_id: pkg.project_id,
|
||||||
|
name: pkg.name || '',
|
||||||
|
region: pkg.region || '',
|
||||||
|
chainage_start_km: pkg.chainage_start_km?.toString() || '',
|
||||||
|
chainage_end_km: pkg.chainage_end_km?.toString() || '',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[reset],
|
||||||
|
);
|
||||||
|
|
||||||
|
const setProjectId = useCallback(
|
||||||
|
(value: string) => setValue('project_id', value, { shouldDirty: true, shouldValidate: true }),
|
||||||
|
[setValue],
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
register,
|
||||||
|
onSubmit,
|
||||||
|
openCreate,
|
||||||
|
openEdit,
|
||||||
|
resetForm: () => reset(defaultValues),
|
||||||
|
packageId,
|
||||||
|
projectId,
|
||||||
|
setProjectId,
|
||||||
|
errors,
|
||||||
|
touchedFields,
|
||||||
|
canSubmit,
|
||||||
|
isSaving: isSubmitting || saveMutation.isPending,
|
||||||
|
};
|
||||||
|
}
|
||||||
50
src/app/(modules)/package/hooks/usePackageQueries.ts
Normal file
50
src/app/(modules)/package/hooks/usePackageQueries.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
import { packageService, projectService } from '@/services/api';
|
||||||
|
import type { Package, PaginationParams } from '@/types';
|
||||||
|
|
||||||
|
import { packageKeys } from '../queries/packageKeys';
|
||||||
|
|
||||||
|
interface UsePackagesQueryParams {
|
||||||
|
skip: number;
|
||||||
|
limit: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePackagesQuery({ skip, limit }: UsePackagesQueryParams) {
|
||||||
|
const listParams = useMemo<PaginationParams>(() => ({ skip, limit }), [limit, skip]);
|
||||||
|
|
||||||
|
return useQuery({
|
||||||
|
queryKey: packageKeys.list(listParams),
|
||||||
|
queryFn: () => packageService.getPackages(listParams),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useProjectOptionsQuery() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['projects', 'options'],
|
||||||
|
queryFn: () => projectService.getProjects({ skip: 0, limit: 1000 }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeletePackageMutation() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (pkg: Package) => packageService.deletePackage(pkg.id),
|
||||||
|
onSuccess: (_data, pkg) => {
|
||||||
|
toast.success('Package deleted', {
|
||||||
|
description: `${pkg.name} has been removed from the system.`,
|
||||||
|
});
|
||||||
|
queryClient.invalidateQueries({ queryKey: packageKeys.all });
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
toast.error('Deletion failed', {
|
||||||
|
description: 'The package could not be removed. Please try again.',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,513 +1,132 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
import { useCallback, useState } from 'react';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Package as PackageIcon, Plus } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from '@/components/ui/select';
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from '@/components/ui/dialog';
|
|
||||||
import { Loader2, CheckCircle2, Package, FolderKanban, Globe } from 'lucide-react';
|
|
||||||
import { DataTable } from '@/components/data-table';
|
|
||||||
import { PageHeader } from '@/components/page-header';
|
import { PageHeader } from '@/components/page-header';
|
||||||
import { projectService, packageService } from '@/services/api';
|
|
||||||
import { Project, Package as PackageType, PackageCreate, PackageUpdate } from '@/types';
|
|
||||||
import { ColumnDef } from '@tanstack/react-table';
|
|
||||||
import { toast } from 'sonner';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
|
||||||
import { PoweredBy } from '@/components/powered-by';
|
import { PoweredBy } from '@/components/powered-by';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import type { Package } from '@/types';
|
||||||
|
|
||||||
|
import { PackageDialog } from './components/PackageDialog';
|
||||||
|
import { PackageTable } from './components/PackageTable';
|
||||||
|
import { usePackageColumns } from './components/PackageColumns';
|
||||||
|
import { usePackageFilters } from './hooks/usePackageFilters';
|
||||||
|
import { usePackageForm } from './hooks/usePackageForm';
|
||||||
|
import {
|
||||||
|
useDeletePackageMutation,
|
||||||
|
usePackagesQuery,
|
||||||
|
useProjectOptionsQuery,
|
||||||
|
} from './hooks/usePackageQueries';
|
||||||
|
|
||||||
export default function PackagePage() {
|
export default function PackagePage() {
|
||||||
const [packages, setPackages] = useState<PackageType[]>([]);
|
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||||
const [totalItems, setTotalItems] = useState(0);
|
const { skip, setSkip, limit, setLimit } = usePackageFilters();
|
||||||
const [projects, setProjects] = useState<Project[]>([]);
|
const packagesQuery = usePackagesQuery({ skip, limit });
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const projectsQuery = useProjectOptionsQuery();
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
const deletePackageMutation = useDeletePackageMutation();
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
const packageForm = usePackageForm({
|
||||||
const [error, setError] = useState<string | null>(null);
|
onSaved: () => setIsDialogOpen(false),
|
||||||
const [loadingProjects, setLoadingProjects] = useState(false);
|
|
||||||
|
|
||||||
// Pagination state
|
|
||||||
const [skip, setSkip] = useState(0);
|
|
||||||
const [limit, setLimit] = useState(10);
|
|
||||||
|
|
||||||
// Editing state
|
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
|
||||||
const [currentPackage, setCurrentPackage] = useState<PackageType | null>(null);
|
|
||||||
|
|
||||||
// Form fields
|
|
||||||
const [selectedProjectId, setSelectedProjectId] = useState('');
|
|
||||||
const [name, setName] = useState('');
|
|
||||||
const [region, setRegion] = useState('');
|
|
||||||
const [chainageStartKm, setChainageStartKm] = useState<string>('');
|
|
||||||
const [chainageEndKm, setChainageEndKm] = useState<string>('');
|
|
||||||
|
|
||||||
// Load packages and projects
|
|
||||||
const loadPackages = async (currentSkip = skip, currentLimit = limit) => {
|
|
||||||
try {
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
const data = await packageService.getPackages({ skip: currentSkip, limit: currentLimit });
|
|
||||||
setPackages(data.items);
|
|
||||||
setTotalItems(data.totalItems);
|
|
||||||
} catch (err) {
|
|
||||||
setError('Failed to load packages. Please check if the backend is running.');
|
|
||||||
} finally {
|
|
||||||
// Add a small delay for animation stability
|
|
||||||
setTimeout(() => {
|
|
||||||
setIsLoading(false);
|
|
||||||
}, 800);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const loadProjects = async () => {
|
|
||||||
try {
|
|
||||||
setLoadingProjects(true);
|
|
||||||
const data = await projectService.getProjects({ skip: 0, limit: 1000 }); // Load all projects for selector
|
|
||||||
setProjects(data.items);
|
|
||||||
} catch (err) {
|
|
||||||
setError('Failed to load projects.');
|
|
||||||
} finally {
|
|
||||||
setLoadingProjects(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
loadPackages(skip, limit);
|
|
||||||
loadProjects();
|
|
||||||
}, [skip, limit]);
|
|
||||||
|
|
||||||
const resetForm = () => {
|
|
||||||
setSelectedProjectId('');
|
|
||||||
setName('');
|
|
||||||
setRegion('');
|
|
||||||
setChainageStartKm('');
|
|
||||||
setChainageEndKm('');
|
|
||||||
setError(null);
|
|
||||||
setIsEditing(false);
|
|
||||||
setCurrentPackage(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
if (!selectedProjectId) {
|
|
||||||
setError('Please select a project first');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!name.trim()) {
|
|
||||||
setError('Package name is required');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsSubmitting(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (isEditing && currentPackage) {
|
|
||||||
const data: PackageUpdate = {
|
|
||||||
name: name.trim(),
|
|
||||||
region: region.trim() || null,
|
|
||||||
chainage_start_km: chainageStartKm ? parseFloat(chainageStartKm) : 0,
|
|
||||||
chainage_end_km: chainageEndKm ? parseFloat(chainageEndKm) : 0,
|
|
||||||
};
|
|
||||||
await packageService.updatePackage(currentPackage.id, data);
|
|
||||||
toast.success('Package Updated', {
|
|
||||||
description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`,
|
|
||||||
});
|
});
|
||||||
} else {
|
const {
|
||||||
const data: PackageCreate = {
|
register,
|
||||||
project_id: selectedProjectId,
|
onSubmit,
|
||||||
name: name.trim(),
|
openCreate: prepareCreatePackage,
|
||||||
region: region.trim() || null,
|
openEdit: prepareEditPackage,
|
||||||
chainage_start_km: chainageStartKm ? parseFloat(chainageStartKm) : 0,
|
resetForm,
|
||||||
chainage_end_km: chainageEndKm ? parseFloat(chainageEndKm) : 0,
|
packageId,
|
||||||
};
|
projectId,
|
||||||
await packageService.createPackage(data);
|
setProjectId,
|
||||||
toast.success('Package Created', {
|
errors,
|
||||||
description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`,
|
touchedFields,
|
||||||
});
|
canSubmit,
|
||||||
}
|
isSaving,
|
||||||
|
} = packageForm;
|
||||||
|
|
||||||
// Refresh packages list
|
const openCreate = useCallback(() => {
|
||||||
await loadPackages();
|
prepareCreatePackage();
|
||||||
|
setIsDialogOpen(true);
|
||||||
|
}, [prepareCreatePackage]);
|
||||||
|
|
||||||
// Close modal and reset form immediately
|
const openEdit = useCallback(
|
||||||
setIsModalOpen(false);
|
(pkg: Package) => {
|
||||||
resetForm();
|
prepareEditPackage(pkg);
|
||||||
} catch (err) {
|
setIsDialogOpen(true);
|
||||||
const message =
|
|
||||||
err instanceof Error ? err.message : `Failed to ${isEditing ? 'update' : 'create'} package`;
|
|
||||||
setError(message);
|
|
||||||
toast.error('Operation Failed', {
|
|
||||||
description: message,
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsSubmitting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleEdit = (pkg: PackageType) => {
|
|
||||||
setIsEditing(true);
|
|
||||||
setCurrentPackage(pkg);
|
|
||||||
setSelectedProjectId(pkg.project_id);
|
|
||||||
setName(pkg.name || '');
|
|
||||||
setRegion(pkg.region || '');
|
|
||||||
setChainageStartKm(pkg.chainage_start_km?.toString() || '0');
|
|
||||||
setChainageEndKm(pkg.chainage_end_km?.toString() || '0');
|
|
||||||
setIsModalOpen(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDelete = async (pkg: PackageType) => {
|
|
||||||
if (!confirm(`Are you sure you want to delete package "${pkg.name}"?`)) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
setIsLoading(true);
|
|
||||||
await packageService.deletePackage(pkg.id);
|
|
||||||
toast.success('Package Deleted', {
|
|
||||||
description: `${pkg.name} has been removed from the system.`,
|
|
||||||
});
|
|
||||||
await loadPackages();
|
|
||||||
} catch (err) {
|
|
||||||
setError('Failed to delete package');
|
|
||||||
toast.error('Deletion Failed', {
|
|
||||||
description: 'The package could not be removed. Please try again.',
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getProjectName = (projectId: string) => {
|
|
||||||
return projects.find((p) => p.id === projectId)?.name || projectId;
|
|
||||||
};
|
|
||||||
|
|
||||||
const columns: ColumnDef<PackageType>[] = [
|
|
||||||
{
|
|
||||||
accessorKey: 'name',
|
|
||||||
header: 'Package Name',
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="font-semibold text-gray-900 dark:text-gray-100">{row.original.name}</div>
|
|
||||||
),
|
|
||||||
},
|
},
|
||||||
{
|
[prepareEditPackage],
|
||||||
accessorKey: 'project_id',
|
|
||||||
header: 'Project',
|
|
||||||
cell: ({ row }) => getProjectName(row.original.project_id),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'project_state',
|
|
||||||
header: 'Project State',
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const pkg = row.original;
|
|
||||||
const project = projects.find((p) => p.id === pkg.project_id);
|
|
||||||
if (!project?.state) return <span className="text-gray-400">—</span>;
|
|
||||||
|
|
||||||
const states = project.state
|
|
||||||
.split(',')
|
|
||||||
.map((s) => s.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
if (states.length === 0) return <span className="text-gray-400">—</span>;
|
|
||||||
|
|
||||||
const firstState = states[0];
|
|
||||||
const remainingStates = states.slice(1);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex items-center gap-1.5">
|
|
||||||
<Badge variant="secondary">{firstState}</Badge>
|
|
||||||
|
|
||||||
{remainingStates.length > 0 && (
|
|
||||||
<Popover>
|
|
||||||
<PopoverTrigger asChild>
|
|
||||||
<button className="flex items-center justify-center rounded-full bg-muted/50 hover:bg-muted px-1.5 py-0.5 text-[10px] font-bold text-muted-foreground transition-colors border border-border/40">
|
|
||||||
+{remainingStates.length}
|
|
||||||
</button>
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverContent className="w-auto p-2" align="start">
|
|
||||||
<div className="flex flex-col gap-1.5">
|
|
||||||
<p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">
|
|
||||||
Other States
|
|
||||||
</p>
|
|
||||||
{remainingStates.map((item, idx) => (
|
|
||||||
<Badge key={idx} variant="secondary">
|
|
||||||
{item}
|
|
||||||
</Badge>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</PopoverContent>
|
|
||||||
</Popover>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const handleDialogOpenChange = useCallback(
|
||||||
|
(open: boolean) => {
|
||||||
|
setIsDialogOpen(open);
|
||||||
|
if (!open) {
|
||||||
|
resetForm();
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
[resetForm],
|
||||||
|
);
|
||||||
|
|
||||||
|
const deletePackage = useCallback(
|
||||||
|
(pkg: Package) => {
|
||||||
|
if (!confirm(`Are you sure you want to delete package "${pkg.name}"?`)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
deletePackageMutation.mutate(pkg);
|
||||||
},
|
},
|
||||||
{
|
[deletePackageMutation],
|
||||||
accessorKey: 'region',
|
);
|
||||||
header: 'Region',
|
|
||||||
},
|
const projects = projectsQuery.data?.items ?? [];
|
||||||
{
|
const packages = packagesQuery.data?.items ?? [];
|
||||||
accessorKey: 'chainage_start_km',
|
const total = packagesQuery.data?.totalItems ?? 0;
|
||||||
header: 'Start (km)',
|
const columns = usePackageColumns(projects);
|
||||||
cell: ({ row }) => row.original.chainage_start_km?.toFixed(2) ?? '0.00',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'chainage_end_km',
|
|
||||||
header: 'End (km)',
|
|
||||||
cell: ({ row }) => row.original.chainage_end_km?.toFixed(2) ?? '0.00',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<main className="relative z-10">
|
<main className="relative z-10 space-y-5">
|
||||||
{/* Refined Header */}
|
|
||||||
<div className="mb-8">
|
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title="Package Management"
|
title="Package Management"
|
||||||
description="Manage project packages"
|
description="Manage project packages"
|
||||||
icon={Package}
|
icon={PackageIcon}
|
||||||
actions={
|
actions={
|
||||||
<Button
|
<Button onClick={openCreate} size="sm">
|
||||||
onClick={() => {
|
<Plus />
|
||||||
setIsEditing(false);
|
|
||||||
setIsModalOpen(true);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Package className="mr-2 h-4 w-4" />
|
|
||||||
Add New Package
|
Add New Package
|
||||||
</Button>
|
</Button>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Data Table */}
|
<PackageTable
|
||||||
<div>
|
|
||||||
<DataTable
|
|
||||||
title="Packages"
|
|
||||||
data={packages}
|
|
||||||
columns={columns}
|
columns={columns}
|
||||||
onEdit={handleEdit}
|
packages={packages}
|
||||||
onDelete={handleDelete}
|
isLoading={packagesQuery.isLoading || deletePackageMutation.isPending}
|
||||||
isLoading={isLoading}
|
skip={skip}
|
||||||
pagination={{
|
limit={limit}
|
||||||
skip,
|
total={total}
|
||||||
limit,
|
onPageChange={setSkip}
|
||||||
totalItems,
|
onLimitChange={setLimit}
|
||||||
onPageChange: setSkip,
|
onEdit={openEdit}
|
||||||
onLimitChange: (newLimit) => {
|
onDelete={deletePackage}
|
||||||
setLimit(newLimit);
|
|
||||||
setSkip(0); // Reset skip when limit changes
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
<PoweredBy />
|
<PoweredBy />
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{/* Modal Dialog */}
|
<PackageDialog
|
||||||
<Dialog
|
open={isDialogOpen}
|
||||||
open={isModalOpen}
|
onOpenChange={handleDialogOpenChange}
|
||||||
onOpenChange={(open) => {
|
packageId={packageId}
|
||||||
if (!open) {
|
projects={projects}
|
||||||
setIsModalOpen(false);
|
isProjectsLoading={projectsQuery.isLoading}
|
||||||
resetForm();
|
projectId={projectId}
|
||||||
} else {
|
onProjectChange={setProjectId}
|
||||||
setIsModalOpen(true);
|
register={register}
|
||||||
}
|
errors={errors}
|
||||||
}}
|
touchedFields={touchedFields}
|
||||||
>
|
onSubmit={onSubmit}
|
||||||
<DialogContent className="max-w-2xl" onOpenAutoFocus={(e) => e.preventDefault()}>
|
canSubmit={canSubmit}
|
||||||
<DialogHeader className="gap-2">
|
isSaving={isSaving}
|
||||||
<DialogTitle className="flex items-center gap-3 text-xl">
|
|
||||||
<div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm">
|
|
||||||
<Package className="h-5 w-5" />
|
|
||||||
</div>
|
|
||||||
{isEditing ? 'Edit Package Details' : 'Create New Package'}
|
|
||||||
</DialogTitle>
|
|
||||||
<DialogDescription className="text-sm">
|
|
||||||
{isEditing
|
|
||||||
? 'Update the technical specifications for your road infrastructure package.'
|
|
||||||
: 'Select a project and provide the essential data to establish a new package.'}
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-8">
|
|
||||||
{/* Step 1: Select Project */}
|
|
||||||
{!isEditing && (
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="flex items-center gap-2.5">
|
|
||||||
<div className="w-6 h-6 rounded-full bg-primary/10 text-primary flex items-center justify-center text-[10px] font-bold uppercase">
|
|
||||||
01
|
|
||||||
</div>
|
|
||||||
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
|
|
||||||
Select Parent Project
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Select value={selectedProjectId} onValueChange={setSelectedProjectId}>
|
|
||||||
<SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20">
|
|
||||||
{loadingProjects ? (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Loader2 className="h-4 w-4 animate-spin text-primary" />
|
|
||||||
<span className="text-muted-foreground text-sm">Loading...</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<SelectValue placeholder="Choose a project..." />
|
|
||||||
)}
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{projects.map((project) => (
|
|
||||||
<SelectItem key={project.id} value={project.id} className="py-3">
|
|
||||||
<span className="font-semibold">{project.name}</span>
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Step 2: Package Info */}
|
|
||||||
<div
|
|
||||||
className={`space-y-4 ${selectedProjectId || isEditing ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}
|
|
||||||
>
|
|
||||||
{!isEditing && (
|
|
||||||
<div className="flex items-center gap-2.5">
|
|
||||||
<div
|
|
||||||
className={`w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold uppercase ${selectedProjectId ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}`}
|
|
||||||
>
|
|
||||||
02
|
|
||||||
</div>
|
|
||||||
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
|
|
||||||
Package Information
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-5">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="pkg-name"
|
|
||||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
|
|
||||||
>
|
|
||||||
Package Name <span className="text-destructive">*</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="pkg-name"
|
|
||||||
value={name}
|
|
||||||
onChange={(e) => setName(e.target.value)}
|
|
||||||
placeholder="e.g. Package 01"
|
|
||||||
className="h-11 bg-muted/20 border-border/60"
|
|
||||||
required
|
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="region"
|
|
||||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider flex items-center gap-2"
|
|
||||||
>
|
|
||||||
<Globe className="h-3.5 w-3.5 opacity-60" />
|
|
||||||
Region{' '}
|
|
||||||
<span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="region"
|
|
||||||
value={region}
|
|
||||||
onChange={(e) => setRegion(e.target.value)}
|
|
||||||
placeholder="e.g. North Zone"
|
|
||||||
className="h-11 bg-muted/20 border-border/60"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="chainage-start"
|
|
||||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
|
|
||||||
>
|
|
||||||
Segment Start (km)
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="chainage-start"
|
|
||||||
type="number"
|
|
||||||
step="0.01"
|
|
||||||
value={chainageStartKm}
|
|
||||||
onChange={(e) => setChainageStartKm(e.target.value)}
|
|
||||||
placeholder="0.00"
|
|
||||||
className="h-11 bg-muted/20 border-border/60"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="chainage-end"
|
|
||||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
|
|
||||||
>
|
|
||||||
Segment End (km)
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="chainage-end"
|
|
||||||
type="number"
|
|
||||||
step="0.01"
|
|
||||||
value={chainageEndKm}
|
|
||||||
onChange={(e) => setChainageEndKm(e.target.value)}
|
|
||||||
placeholder="0.00"
|
|
||||||
className="h-11 bg-muted/20 border-border/60"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Submit Button */}
|
|
||||||
<div className="flex gap-4 pt-4">
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => {
|
|
||||||
setIsModalOpen(false);
|
|
||||||
resetForm();
|
|
||||||
}}
|
|
||||||
disabled={isSubmitting}
|
|
||||||
className="flex-1"
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
disabled={isSubmitting || !name.trim() || !selectedProjectId}
|
|
||||||
className="flex-1"
|
|
||||||
>
|
|
||||||
{isSubmitting ? (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Loader2 className="h-4 w-4 animate-spin" />
|
|
||||||
<span>{isEditing ? 'Updating...' : 'Creating...'}</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
{isEditing ? (
|
|
||||||
<CheckCircle2 className="h-4 w-4" />
|
|
||||||
) : (
|
|
||||||
<Package className="h-4 w-4" />
|
|
||||||
)}
|
|
||||||
<span>{isEditing ? 'Update Package' : 'Create Package'}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
7
src/app/(modules)/package/queries/packageKeys.ts
Normal file
7
src/app/(modules)/package/queries/packageKeys.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import type { PaginationParams } from '@/types';
|
||||||
|
|
||||||
|
export const packageKeys = {
|
||||||
|
all: ['packages'] as const,
|
||||||
|
lists: () => [...packageKeys.all, 'list'] as const,
|
||||||
|
list: (params: PaginationParams) => [...packageKeys.lists(), params] as const,
|
||||||
|
};
|
||||||
82
src/app/(modules)/project/components/ProjectColumns.tsx
Normal file
82
src/app/(modules)/project/components/ProjectColumns.tsx
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
import type { ColumnDef } from '@tanstack/react-table';
|
||||||
|
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||||
|
import type { Project } from '@/types';
|
||||||
|
|
||||||
|
function EmptyValue() {
|
||||||
|
return <span className="text-muted-foreground">-</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function StateBadges({ value }: { value: string | null }) {
|
||||||
|
if (!value) {
|
||||||
|
return <EmptyValue />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const states = value
|
||||||
|
.split(',')
|
||||||
|
.map((state) => state.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
if (!states.length) {
|
||||||
|
return <EmptyValue />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [firstState, ...remainingStates] = states;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<Badge variant="secondary">{firstState}</Badge>
|
||||||
|
{remainingStates.length > 0 ? (
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="flex items-center justify-center rounded-full border border-border/40 bg-muted/50 px-1.5 py-0.5 text-[10px] font-bold text-muted-foreground transition-colors hover:bg-muted"
|
||||||
|
>
|
||||||
|
+{remainingStates.length}
|
||||||
|
</button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-auto p-2" align="start">
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<p className="mb-0.5 px-1 text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
|
||||||
|
Other States
|
||||||
|
</p>
|
||||||
|
{remainingStates.map((state) => (
|
||||||
|
<Badge key={state} variant="secondary">
|
||||||
|
{state}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useProjectColumns() {
|
||||||
|
return useMemo<ColumnDef<Project>[]>(
|
||||||
|
() => [
|
||||||
|
{
|
||||||
|
accessorKey: 'name',
|
||||||
|
header: 'Project Name',
|
||||||
|
cell: ({ row }) => <div className="font-semibold">{row.original.name}</div>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'state',
|
||||||
|
header: 'State',
|
||||||
|
cell: ({ row }) => <StateBadges value={row.original.state} />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'corridor_name',
|
||||||
|
header: 'Corridor',
|
||||||
|
cell: ({ row }) => row.original.corridor_name || <EmptyValue />,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
}
|
||||||
180
src/app/(modules)/project/components/ProjectDialog.tsx
Normal file
180
src/app/(modules)/project/components/ProjectDialog.tsx
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import type { ComponentProps } from 'react';
|
||||||
|
import type { FieldErrors, UseFormRegister, UseFormReturn } from 'react-hook-form';
|
||||||
|
import { Layers, Loader2, MapPin, Route } from 'lucide-react';
|
||||||
|
|
||||||
|
import { FormField } from '@/components/form';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
|
||||||
|
import type { ProjectFormValues } from '../hooks/useProjectForm';
|
||||||
|
|
||||||
|
interface ProjectDialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
projectId?: string;
|
||||||
|
register: UseFormRegister<ProjectFormValues>;
|
||||||
|
errors: FieldErrors<ProjectFormValues>;
|
||||||
|
touchedFields: UseFormReturn<ProjectFormValues>['formState']['touchedFields'];
|
||||||
|
onSubmit: ComponentProps<'form'>['onSubmit'];
|
||||||
|
canSubmit: boolean;
|
||||||
|
isSaving: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProjectDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
projectId,
|
||||||
|
register,
|
||||||
|
errors,
|
||||||
|
touchedFields,
|
||||||
|
onSubmit,
|
||||||
|
canSubmit,
|
||||||
|
isSaving,
|
||||||
|
}: ProjectDialogProps) {
|
||||||
|
const nameErrorMessage = touchedFields.name ? errors.name?.message : undefined;
|
||||||
|
const startLatErrorMessage = touchedFields.start_lat ? errors.start_lat?.message : undefined;
|
||||||
|
const startLngErrorMessage = touchedFields.start_lng ? errors.start_lng?.message : undefined;
|
||||||
|
const endLatErrorMessage = touchedFields.end_lat ? errors.end_lat?.message : undefined;
|
||||||
|
const endLngErrorMessage = touchedFields.end_lng ? errors.end_lng?.message : undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="max-w-2xl" onOpenAutoFocus={(event) => event.preventDefault()}>
|
||||||
|
<DialogHeader className="gap-2">
|
||||||
|
<DialogTitle className="flex items-center gap-3 text-xl">
|
||||||
|
<div className="rounded-lg bg-primary p-2 text-primary-foreground shadow-sm">
|
||||||
|
<Layers className="size-5" />
|
||||||
|
</div>
|
||||||
|
{projectId ? 'Edit Project Details' : 'Create New Project'}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-sm">
|
||||||
|
{projectId
|
||||||
|
? 'Update the technical specifications for your road infrastructure project.'
|
||||||
|
: 'Provide the essential road data to establish a new analysis project.'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<form onSubmit={onSubmit} className="space-y-6">
|
||||||
|
<FormField id="project-name" label="Project Name" required error={nameErrorMessage}>
|
||||||
|
<Input
|
||||||
|
id="project-name"
|
||||||
|
placeholder="Enter a descriptive project name"
|
||||||
|
aria-invalid={!!nameErrorMessage}
|
||||||
|
{...register('name')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
|
||||||
|
<div className="grid gap-5 md:grid-cols-2">
|
||||||
|
<FormField id="project-state" label="State">
|
||||||
|
<Input id="project-state" placeholder="e.g. Maharashtra" {...register('state')} />
|
||||||
|
</FormField>
|
||||||
|
<FormField
|
||||||
|
id="project-corridor"
|
||||||
|
label={
|
||||||
|
<span className="inline-flex items-center gap-2">
|
||||||
|
<Route className="size-3.5 opacity-60" />
|
||||||
|
Corridor Name
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
id="project-corridor"
|
||||||
|
placeholder="e.g. Mumbai-Goa Highway"
|
||||||
|
{...register('corridor_name')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-8 pt-2 md:grid-cols-2">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<p className="flex items-center gap-2 text-[11px] font-black tracking-widest text-muted-foreground">
|
||||||
|
<MapPin className="size-3.5 opacity-60" />
|
||||||
|
START POINT
|
||||||
|
</p>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<FormField id="project-start-lat" label="Lat" error={startLatErrorMessage}>
|
||||||
|
<Input
|
||||||
|
id="project-start-lat"
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
placeholder="0.0000"
|
||||||
|
className="font-mono text-xs"
|
||||||
|
aria-invalid={!!startLatErrorMessage}
|
||||||
|
{...register('start_lat')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
<FormField id="project-start-lng" label="Lng" error={startLngErrorMessage}>
|
||||||
|
<Input
|
||||||
|
id="project-start-lng"
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
placeholder="0.0000"
|
||||||
|
className="font-mono text-xs"
|
||||||
|
aria-invalid={!!startLngErrorMessage}
|
||||||
|
{...register('start_lng')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<p className="flex items-center gap-2 text-[11px] font-black tracking-widest text-muted-foreground">
|
||||||
|
<MapPin className="size-3.5 opacity-60" />
|
||||||
|
END POINT
|
||||||
|
</p>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<FormField id="project-end-lat" label="Lat" error={endLatErrorMessage}>
|
||||||
|
<Input
|
||||||
|
id="project-end-lat"
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
placeholder="0.0000"
|
||||||
|
className="font-mono text-xs"
|
||||||
|
aria-invalid={!!endLatErrorMessage}
|
||||||
|
{...register('end_lat')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
<FormField id="project-end-lng" label="Lng" error={endLngErrorMessage}>
|
||||||
|
<Input
|
||||||
|
id="project-end-lng"
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
placeholder="0.0000"
|
||||||
|
className="font-mono text-xs"
|
||||||
|
aria-invalid={!!endLngErrorMessage}
|
||||||
|
{...register('end_lng')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
disabled={isSaving}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={isSaving || !canSubmit}>
|
||||||
|
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
|
{projectId ? 'Update Project' : 'Create Project'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
51
src/app/(modules)/project/components/ProjectTable.tsx
Normal file
51
src/app/(modules)/project/components/ProjectTable.tsx
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import type { ColumnDef } from '@tanstack/react-table';
|
||||||
|
|
||||||
|
import { DataTable } from '@/components/data-table';
|
||||||
|
import type { Project } from '@/types';
|
||||||
|
|
||||||
|
interface ProjectTableProps {
|
||||||
|
columns: ColumnDef<Project>[];
|
||||||
|
projects: Project[];
|
||||||
|
isLoading: boolean;
|
||||||
|
skip: number;
|
||||||
|
limit: number;
|
||||||
|
total: number;
|
||||||
|
onPageChange: (skip: number) => void;
|
||||||
|
onLimitChange: (limit: number) => void;
|
||||||
|
onEdit: (project: Project) => void;
|
||||||
|
onDelete: (project: Project) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProjectTable({
|
||||||
|
columns,
|
||||||
|
projects,
|
||||||
|
isLoading,
|
||||||
|
skip,
|
||||||
|
limit,
|
||||||
|
total,
|
||||||
|
onPageChange,
|
||||||
|
onLimitChange,
|
||||||
|
onEdit,
|
||||||
|
onDelete,
|
||||||
|
}: ProjectTableProps) {
|
||||||
|
return (
|
||||||
|
<DataTable
|
||||||
|
title="Projects"
|
||||||
|
data={projects}
|
||||||
|
columns={columns}
|
||||||
|
onEdit={onEdit}
|
||||||
|
onDelete={onDelete}
|
||||||
|
isLoading={isLoading}
|
||||||
|
emptyTitle="No projects found."
|
||||||
|
pagination={{
|
||||||
|
skip,
|
||||||
|
limit,
|
||||||
|
totalItems: total,
|
||||||
|
onPageChange,
|
||||||
|
onLimitChange,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
20
src/app/(modules)/project/hooks/useProjectFilters.ts
Normal file
20
src/app/(modules)/project/hooks/useProjectFilters.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback, useState } from 'react';
|
||||||
|
|
||||||
|
export function useProjectFilters() {
|
||||||
|
const [skip, setSkip] = useState(0);
|
||||||
|
const [limit, setLimitValue] = useState(10);
|
||||||
|
|
||||||
|
const setLimit = useCallback((value: number) => {
|
||||||
|
setLimitValue(value);
|
||||||
|
setSkip(0);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
skip,
|
||||||
|
setSkip,
|
||||||
|
limit,
|
||||||
|
setLimit,
|
||||||
|
};
|
||||||
|
}
|
||||||
146
src/app/(modules)/project/hooks/useProjectForm.ts
Normal file
146
src/app/(modules)/project/hooks/useProjectForm.ts
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { useCallback } from 'react';
|
||||||
|
import { useForm, useWatch } from 'react-hook-form';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import { projectService } from '@/services/api';
|
||||||
|
import type { Project, ProjectCreate, ProjectUpdate } from '@/types';
|
||||||
|
|
||||||
|
import { projectKeys } from '../queries/projectKeys';
|
||||||
|
|
||||||
|
const optionalCoordinate = z.string().refine(
|
||||||
|
(value) => {
|
||||||
|
if (!value.trim()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return Number.isFinite(Number(value));
|
||||||
|
},
|
||||||
|
{ message: 'Enter a valid number' },
|
||||||
|
);
|
||||||
|
|
||||||
|
const projectFormSchema = z.object({
|
||||||
|
id: z.string().optional(),
|
||||||
|
name: z.string().trim().min(1, 'Project name is required'),
|
||||||
|
state: z.string().optional(),
|
||||||
|
corridor_name: z.string().optional(),
|
||||||
|
start_lat: optionalCoordinate,
|
||||||
|
start_lng: optionalCoordinate,
|
||||||
|
end_lat: optionalCoordinate,
|
||||||
|
end_lng: optionalCoordinate,
|
||||||
|
});
|
||||||
|
|
||||||
|
export type ProjectFormValues = z.infer<typeof projectFormSchema>;
|
||||||
|
|
||||||
|
const defaultValues: ProjectFormValues = {
|
||||||
|
name: '',
|
||||||
|
state: '',
|
||||||
|
corridor_name: '',
|
||||||
|
start_lat: '',
|
||||||
|
start_lng: '',
|
||||||
|
end_lat: '',
|
||||||
|
end_lng: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
function trimOptional(value?: string) {
|
||||||
|
return value?.trim() || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toNullableNumber(value: string) {
|
||||||
|
return value.trim() ? Number(value) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toProjectPayload(values: ProjectFormValues): ProjectCreate | ProjectUpdate {
|
||||||
|
return {
|
||||||
|
name: values.name.trim(),
|
||||||
|
state: trimOptional(values.state),
|
||||||
|
corridor_name: trimOptional(values.corridor_name),
|
||||||
|
start_lat: toNullableNumber(values.start_lat),
|
||||||
|
start_lng: toNullableNumber(values.start_lng),
|
||||||
|
end_lat: toNullableNumber(values.end_lat),
|
||||||
|
end_lng: toNullableNumber(values.end_lng),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useProjectForm({ onSaved }: { onSaved: () => void }) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const {
|
||||||
|
register,
|
||||||
|
handleSubmit,
|
||||||
|
reset,
|
||||||
|
control,
|
||||||
|
formState: { errors, isSubmitting, touchedFields },
|
||||||
|
} = useForm<ProjectFormValues>({
|
||||||
|
defaultValues,
|
||||||
|
mode: 'onTouched',
|
||||||
|
reValidateMode: 'onChange',
|
||||||
|
resolver: zodResolver(projectFormSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
const projectId = useWatch({ control, name: 'id' });
|
||||||
|
const projectName = useWatch({ control, name: 'name' }) || '';
|
||||||
|
const canSubmit = projectName.trim().length > 0;
|
||||||
|
|
||||||
|
const saveMutation = useMutation({
|
||||||
|
mutationFn: (values: ProjectFormValues) => {
|
||||||
|
const payload = toProjectPayload(values);
|
||||||
|
return values.id
|
||||||
|
? projectService.updateProject(values.id, payload)
|
||||||
|
: projectService.createProject(payload as ProjectCreate);
|
||||||
|
},
|
||||||
|
onSuccess: (_data, values) => {
|
||||||
|
toast.success(values.id ? 'Project updated' : 'Project created');
|
||||||
|
reset(defaultValues);
|
||||||
|
onSaved();
|
||||||
|
queryClient.invalidateQueries({ queryKey: projectKeys.all });
|
||||||
|
},
|
||||||
|
onError: (_error, values) => {
|
||||||
|
toast.error(values.id ? 'Failed to update project' : 'Failed to create project');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const onSubmit = handleSubmit(
|
||||||
|
(values) => saveMutation.mutate(values),
|
||||||
|
(formErrors) => {
|
||||||
|
if (formErrors.name?.message) {
|
||||||
|
toast.error(formErrors.name.message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const openCreate = useCallback(() => {
|
||||||
|
reset(defaultValues);
|
||||||
|
}, [reset]);
|
||||||
|
|
||||||
|
const openEdit = useCallback(
|
||||||
|
(project: Project) => {
|
||||||
|
reset({
|
||||||
|
id: project.id,
|
||||||
|
name: project.name || '',
|
||||||
|
state: project.state || '',
|
||||||
|
corridor_name: project.corridor_name || '',
|
||||||
|
start_lat: project.start_lat?.toString() ?? '',
|
||||||
|
start_lng: project.start_lng?.toString() ?? '',
|
||||||
|
end_lat: project.end_lat?.toString() ?? '',
|
||||||
|
end_lng: project.end_lng?.toString() ?? '',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[reset],
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
register,
|
||||||
|
onSubmit,
|
||||||
|
openCreate,
|
||||||
|
openEdit,
|
||||||
|
resetForm: () => reset(defaultValues),
|
||||||
|
projectId,
|
||||||
|
errors,
|
||||||
|
touchedFields,
|
||||||
|
canSubmit,
|
||||||
|
isSaving: isSubmitting || saveMutation.isPending,
|
||||||
|
};
|
||||||
|
}
|
||||||
43
src/app/(modules)/project/hooks/useProjectQueries.ts
Normal file
43
src/app/(modules)/project/hooks/useProjectQueries.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
import { projectService } from '@/services/api';
|
||||||
|
import type { PaginationParams, Project } from '@/types';
|
||||||
|
|
||||||
|
import { projectKeys } from '../queries/projectKeys';
|
||||||
|
|
||||||
|
interface UseProjectsQueryParams {
|
||||||
|
skip: number;
|
||||||
|
limit: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useProjectsQuery({ skip, limit }: UseProjectsQueryParams) {
|
||||||
|
const listParams = useMemo<PaginationParams>(() => ({ skip, limit }), [limit, skip]);
|
||||||
|
|
||||||
|
return useQuery({
|
||||||
|
queryKey: projectKeys.list(listParams),
|
||||||
|
queryFn: () => projectService.getProjects(listParams),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeleteProjectMutation() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (project: Project) => projectService.deleteProject(project.id),
|
||||||
|
onSuccess: (_data, project) => {
|
||||||
|
toast.success('Project deleted', {
|
||||||
|
description: `${project.name} has been removed from the system.`,
|
||||||
|
});
|
||||||
|
queryClient.invalidateQueries({ queryKey: projectKeys.all });
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
toast.error('Deletion failed', {
|
||||||
|
description: 'The project could not be removed. Please try again or check your permissions.',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,497 +1,120 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
import { useCallback, useState } from 'react';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Layers, Plus } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from '@/components/ui/dialog';
|
|
||||||
import { Loader2, CheckCircle2, Layers, MapPin, Building2, Route, X } from 'lucide-react';
|
|
||||||
import { DataTable } from '@/components/data-table';
|
|
||||||
import { PageHeader } from '@/components/page-header';
|
import { PageHeader } from '@/components/page-header';
|
||||||
import { projectService } from '@/services/api';
|
|
||||||
import { ProjectCreate, Project, ProjectUpdate } from '@/types';
|
|
||||||
import { ColumnDef } from '@tanstack/react-table';
|
|
||||||
import { toast } from 'sonner';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
|
||||||
import { PoweredBy } from '@/components/powered-by';
|
import { PoweredBy } from '@/components/powered-by';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import type { Project } from '@/types';
|
||||||
|
|
||||||
|
import { ProjectDialog } from './components/ProjectDialog';
|
||||||
|
import { ProjectTable } from './components/ProjectTable';
|
||||||
|
import { useProjectColumns } from './components/ProjectColumns';
|
||||||
|
import { useProjectFilters } from './hooks/useProjectFilters';
|
||||||
|
import { useProjectForm } from './hooks/useProjectForm';
|
||||||
|
import { useDeleteProjectMutation, useProjectsQuery } from './hooks/useProjectQueries';
|
||||||
|
|
||||||
export default function ProjectPage() {
|
export default function ProjectPage() {
|
||||||
const [projects, setProjects] = useState<Project[]>([]);
|
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||||
const [totalItems, setTotalItems] = useState(0);
|
const { skip, setSkip, limit, setLimit } = useProjectFilters();
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const projectsQuery = useProjectsQuery({ skip, limit });
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
const deleteProjectMutation = useDeleteProjectMutation();
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
const projectForm = useProjectForm({
|
||||||
const [error, setError] = useState<string | null>(null);
|
onSaved: () => setIsDialogOpen(false),
|
||||||
|
});
|
||||||
|
const {
|
||||||
|
register,
|
||||||
|
onSubmit,
|
||||||
|
openCreate: prepareCreateProject,
|
||||||
|
openEdit: prepareEditProject,
|
||||||
|
resetForm,
|
||||||
|
projectId,
|
||||||
|
errors,
|
||||||
|
touchedFields,
|
||||||
|
canSubmit,
|
||||||
|
isSaving,
|
||||||
|
} = projectForm;
|
||||||
|
|
||||||
// Pagination state
|
const openCreate = useCallback(() => {
|
||||||
const [skip, setSkip] = useState(0);
|
prepareCreateProject();
|
||||||
const [limit, setLimit] = useState(10);
|
setIsDialogOpen(true);
|
||||||
|
}, [prepareCreateProject]);
|
||||||
|
|
||||||
// Editing state
|
const openEdit = useCallback(
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
(project: Project) => {
|
||||||
const [currentProject, setCurrentProject] = useState<Project | null>(null);
|
prepareEditProject(project);
|
||||||
|
setIsDialogOpen(true);
|
||||||
|
},
|
||||||
|
[prepareEditProject],
|
||||||
|
);
|
||||||
|
|
||||||
// Form fields
|
const handleDialogOpenChange = useCallback(
|
||||||
const [name, setName] = useState('');
|
(open: boolean) => {
|
||||||
const [state, setState] = useState('');
|
setIsDialogOpen(open);
|
||||||
const [corridorName, setCorridorName] = useState('');
|
if (!open) {
|
||||||
const [startLat, setStartLat] = useState('');
|
resetForm();
|
||||||
const [startLng, setStartLng] = useState('');
|
|
||||||
const [endLat, setEndLat] = useState('');
|
|
||||||
const [endLng, setEndLng] = useState('');
|
|
||||||
|
|
||||||
// Load projects
|
|
||||||
const loadProjects = async (currentSkip = skip, currentLimit = limit) => {
|
|
||||||
try {
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
const data = await projectService.getProjects({ skip: currentSkip, limit: currentLimit });
|
|
||||||
setProjects(data.items);
|
|
||||||
setTotalItems(data.totalItems);
|
|
||||||
} catch (err) {
|
|
||||||
setError('Failed to load projects. Please check if the backend is running.');
|
|
||||||
} finally {
|
|
||||||
// Add a small delay for animation stability
|
|
||||||
setTimeout(() => {
|
|
||||||
setIsLoading(false);
|
|
||||||
}, 800);
|
|
||||||
}
|
}
|
||||||
};
|
},
|
||||||
|
[resetForm],
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
const deleteProject = useCallback(
|
||||||
loadProjects(skip, limit);
|
(project: Project) => {
|
||||||
}, [skip, limit]);
|
if (!confirm(`Are you sure you want to delete project "${project.name}"?`)) {
|
||||||
|
|
||||||
const resetForm = () => {
|
|
||||||
setName('');
|
|
||||||
setState('');
|
|
||||||
setCorridorName('');
|
|
||||||
setStartLat('');
|
|
||||||
setStartLng('');
|
|
||||||
setEndLat('');
|
|
||||||
setEndLng('');
|
|
||||||
setError(null);
|
|
||||||
setIsEditing(false);
|
|
||||||
setCurrentProject(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
if (!name.trim()) {
|
|
||||||
setError('Project name is required');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
deleteProjectMutation.mutate(project);
|
||||||
setIsSubmitting(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (isEditing && currentProject) {
|
|
||||||
const data: ProjectUpdate = {
|
|
||||||
name: name.trim(),
|
|
||||||
state: state.trim() || null,
|
|
||||||
corridor_name: corridorName.trim() || null,
|
|
||||||
start_lat: startLat ? parseFloat(startLat) : null,
|
|
||||||
start_lng: startLng ? parseFloat(startLng) : null,
|
|
||||||
end_lat: endLat ? parseFloat(endLat) : null,
|
|
||||||
end_lng: endLng ? parseFloat(endLng) : null,
|
|
||||||
};
|
|
||||||
await projectService.updateProject(currentProject.id, data);
|
|
||||||
toast.success('Project Updated', {
|
|
||||||
description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
const data: ProjectCreate = {
|
|
||||||
name: name.trim(),
|
|
||||||
state: state.trim() || null,
|
|
||||||
corridor_name: corridorName.trim() || null,
|
|
||||||
start_lat: startLat ? parseFloat(startLat) : null,
|
|
||||||
start_lng: startLng ? parseFloat(startLng) : null,
|
|
||||||
end_lat: endLat ? parseFloat(endLat) : null,
|
|
||||||
end_lng: endLng ? parseFloat(endLng) : null,
|
|
||||||
};
|
|
||||||
await projectService.createProject(data);
|
|
||||||
toast.success('Project Created', {
|
|
||||||
description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Refresh projects list
|
|
||||||
await loadProjects();
|
|
||||||
|
|
||||||
// Close modal and reset form immediately
|
|
||||||
setIsModalOpen(false);
|
|
||||||
resetForm();
|
|
||||||
} catch (err) {
|
|
||||||
const message =
|
|
||||||
err instanceof Error ? err.message : `Failed to ${isEditing ? 'update' : 'create'} project`;
|
|
||||||
setError(message);
|
|
||||||
toast.error('Operation Failed', {
|
|
||||||
description: message,
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsSubmitting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleEdit = (project: Project) => {
|
|
||||||
setIsEditing(true);
|
|
||||||
setCurrentProject(project);
|
|
||||||
setName(project.name || '');
|
|
||||||
setState(project.state || '');
|
|
||||||
setCorridorName(project.corridor_name || '');
|
|
||||||
setStartLat(project.start_lat?.toString() || '');
|
|
||||||
setStartLng(project.start_lng?.toString() || '');
|
|
||||||
setEndLat(project.end_lat?.toString() || '');
|
|
||||||
setEndLng(project.end_lng?.toString() || '');
|
|
||||||
setIsModalOpen(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDelete = async (project: Project) => {
|
|
||||||
if (!confirm(`Are you sure you want to delete project "${project.name}"?`)) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
setIsLoading(true);
|
|
||||||
await projectService.deleteProject(project.id);
|
|
||||||
toast.success('Project Deleted', {
|
|
||||||
description: `${project.name} has been removed from the system.`,
|
|
||||||
});
|
|
||||||
await loadProjects();
|
|
||||||
} catch (err) {
|
|
||||||
setError('Failed to delete project');
|
|
||||||
toast.error('Deletion Failed', {
|
|
||||||
description:
|
|
||||||
'The project could not be removed. Please try again or check your permissions.',
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const columns: ColumnDef<Project>[] = [
|
|
||||||
{
|
|
||||||
accessorKey: 'name',
|
|
||||||
header: 'Project Name',
|
|
||||||
cell: ({ row }) => <div className="font-semibold">{row.original.name}</div>,
|
|
||||||
},
|
},
|
||||||
{
|
[deleteProjectMutation],
|
||||||
accessorKey: 'state',
|
|
||||||
header: 'State',
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const project = row.original;
|
|
||||||
if (!project.state) return <span>—</span>;
|
|
||||||
|
|
||||||
const states = project.state
|
|
||||||
.split(',')
|
|
||||||
.map((s) => s.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
if (states.length === 0) return <span>—</span>;
|
|
||||||
|
|
||||||
const firstState = states[0];
|
|
||||||
const remainingStates = states.slice(1);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex items-center gap-1.5">
|
|
||||||
<Badge variant="secondary">{firstState}</Badge>
|
|
||||||
|
|
||||||
{remainingStates.length > 0 && (
|
|
||||||
<Popover>
|
|
||||||
<PopoverTrigger asChild>
|
|
||||||
<button className="flex items-center justify-center rounded-full bg-muted/50 hover:bg-muted px-1.5 py-0.5 text-[10px] font-bold text-muted-foreground transition-colors border border-border/40">
|
|
||||||
+{remainingStates.length}
|
|
||||||
</button>
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverContent className="w-auto p-2" align="start">
|
|
||||||
<div className="flex flex-col gap-1.5">
|
|
||||||
<p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">
|
|
||||||
Other States
|
|
||||||
</p>
|
|
||||||
{remainingStates.map((item, idx) => (
|
|
||||||
<Badge key={idx} variant="secondary">
|
|
||||||
{item}
|
|
||||||
</Badge>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</PopoverContent>
|
|
||||||
</Popover>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
},
|
|
||||||
},
|
const columns = useProjectColumns();
|
||||||
{
|
const projects = projectsQuery.data?.items ?? [];
|
||||||
accessorKey: 'corridor_name',
|
const total = projectsQuery.data?.totalItems ?? 0;
|
||||||
header: 'Corridor',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<main className="relative z-10">
|
<main className="relative z-10 space-y-5">
|
||||||
{/* Refined Header */}
|
|
||||||
<div className="mb-8">
|
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title="Project Management"
|
title="Project Management"
|
||||||
description="Manage road infrastructure projects"
|
description="Manage road infrastructure projects"
|
||||||
icon={Layers}
|
icon={Layers}
|
||||||
actions={
|
actions={
|
||||||
<Button
|
<Button onClick={openCreate} size="sm">
|
||||||
onClick={() => {
|
<Plus />
|
||||||
setIsEditing(false);
|
Add Project
|
||||||
setIsModalOpen(true);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Layers className="mr-2 h-5 w-5" />
|
|
||||||
Add New Project
|
|
||||||
</Button>
|
</Button>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Data Table */}
|
<ProjectTable
|
||||||
<div>
|
|
||||||
<DataTable
|
|
||||||
title="Projects"
|
|
||||||
data={projects}
|
|
||||||
columns={columns}
|
columns={columns}
|
||||||
onEdit={handleEdit}
|
projects={projects}
|
||||||
onDelete={handleDelete}
|
isLoading={projectsQuery.isLoading || deleteProjectMutation.isPending}
|
||||||
isLoading={isLoading}
|
skip={skip}
|
||||||
pagination={{
|
limit={limit}
|
||||||
skip,
|
total={total}
|
||||||
limit,
|
onPageChange={setSkip}
|
||||||
totalItems,
|
onLimitChange={setLimit}
|
||||||
onPageChange: setSkip,
|
onEdit={openEdit}
|
||||||
onLimitChange: (newLimit) => {
|
onDelete={deleteProject}
|
||||||
setLimit(newLimit);
|
|
||||||
setSkip(0); // Reset skip when limit changes
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
<PoweredBy />
|
<PoweredBy />
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{/* Modal Dialog */}
|
<ProjectDialog
|
||||||
<Dialog
|
open={isDialogOpen}
|
||||||
open={isModalOpen}
|
onOpenChange={handleDialogOpenChange}
|
||||||
onOpenChange={(open) => {
|
projectId={projectId}
|
||||||
if (!open) {
|
register={register}
|
||||||
setIsModalOpen(false);
|
errors={errors}
|
||||||
resetForm();
|
touchedFields={touchedFields}
|
||||||
} else {
|
onSubmit={onSubmit}
|
||||||
setIsModalOpen(true);
|
canSubmit={canSubmit}
|
||||||
}
|
isSaving={isSaving}
|
||||||
}}
|
|
||||||
>
|
|
||||||
<DialogContent className="max-w-2xl" onOpenAutoFocus={(e) => e.preventDefault()}>
|
|
||||||
<DialogHeader className="gap-2">
|
|
||||||
<DialogTitle className="flex items-center gap-3 text-xl">
|
|
||||||
<div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm">
|
|
||||||
<Layers className="h-5 w-5" />
|
|
||||||
</div>
|
|
||||||
{isEditing ? 'Edit Project Details' : 'Create New Project'}
|
|
||||||
</DialogTitle>
|
|
||||||
<DialogDescription className="text-sm">
|
|
||||||
{isEditing
|
|
||||||
? 'Update the technical specifications for your road infrastructure project.'
|
|
||||||
: 'Provide the essential road data to establish a new analysis project.'}
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
|
||||||
{/* Project Name */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="name"
|
|
||||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
|
|
||||||
>
|
|
||||||
Project Name <span className="text-destructive">*</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="name"
|
|
||||||
value={name}
|
|
||||||
onChange={(e) => setName(e.target.value)}
|
|
||||||
placeholder="Enter a descriptive project name..."
|
|
||||||
className="h-11 bg-muted/20 border-border/60"
|
|
||||||
required
|
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* State & Corridor Row */}
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-5">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="state"
|
|
||||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
|
|
||||||
>
|
|
||||||
State{' '}
|
|
||||||
<span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="state"
|
|
||||||
value={state}
|
|
||||||
onChange={(e) => setState(e.target.value)}
|
|
||||||
placeholder="e.g. Maharashtra"
|
|
||||||
className="h-11 bg-muted/20 border-border/60"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="corridor"
|
|
||||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider flex items-center gap-2"
|
|
||||||
>
|
|
||||||
<Route className="h-3.5 w-3.5 opacity-60" />
|
|
||||||
Corridor Name{' '}
|
|
||||||
<span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="corridor"
|
|
||||||
value={corridorName}
|
|
||||||
onChange={(e) => setCorridorName(e.target.value)}
|
|
||||||
placeholder="e.g. Mumbai-Goa Highway"
|
|
||||||
className="h-11 bg-muted/20 border-border/60"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* GPS Coordinates Grid */}
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 pt-2">
|
|
||||||
{/* Start Point */}
|
|
||||||
<div className="space-y-4">
|
|
||||||
<p className="text-[11px] font-black text-muted-foreground tracking-widest flex items-center gap-2">
|
|
||||||
<MapPin className="h-3.5 w-3.5 opacity-60" /> START POINT
|
|
||||||
</p>
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="start-lat"
|
|
||||||
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
|
|
||||||
>
|
|
||||||
Lat
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="start-lat"
|
|
||||||
type="number"
|
|
||||||
step="any"
|
|
||||||
value={startLat}
|
|
||||||
onChange={(e) => setStartLat(e.target.value)}
|
|
||||||
placeholder="0.0000"
|
|
||||||
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="start-lng"
|
|
||||||
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
|
|
||||||
>
|
|
||||||
Lng
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="start-lng"
|
|
||||||
type="number"
|
|
||||||
step="any"
|
|
||||||
value={startLng}
|
|
||||||
onChange={(e) => setStartLng(e.target.value)}
|
|
||||||
placeholder="0.0000"
|
|
||||||
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* End Point */}
|
|
||||||
<div className="space-y-4">
|
|
||||||
<p className="text-[11px] font-black text-muted-foreground tracking-widest flex items-center gap-2">
|
|
||||||
<MapPin className="h-3.5 w-3.5 opacity-60" /> END POINT
|
|
||||||
</p>
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="end-lat"
|
|
||||||
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
|
|
||||||
>
|
|
||||||
Lat
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="end-lat"
|
|
||||||
type="number"
|
|
||||||
step="any"
|
|
||||||
value={endLat}
|
|
||||||
onChange={(e) => setEndLat(e.target.value)}
|
|
||||||
placeholder="0.0000"
|
|
||||||
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="end-lng"
|
|
||||||
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
|
|
||||||
>
|
|
||||||
Lng
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="end-lng"
|
|
||||||
type="number"
|
|
||||||
step="any"
|
|
||||||
value={endLng}
|
|
||||||
onChange={(e) => setEndLng(e.target.value)}
|
|
||||||
placeholder="0.0000"
|
|
||||||
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Submit Button */}
|
|
||||||
<div className="flex gap-4 pt-2">
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => {
|
|
||||||
setIsModalOpen(false);
|
|
||||||
resetForm();
|
|
||||||
}}
|
|
||||||
disabled={isSubmitting}
|
|
||||||
className="flex-1 h-12 font-bold uppercase tracking-wider text-xs border-border/80 hover:bg-muted/50"
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
disabled={isSubmitting || !name.trim()}
|
|
||||||
className="flex-1 h-12 font-bold uppercase tracking-wider text-xs shadow-lg shadow-primary/20"
|
|
||||||
>
|
|
||||||
{isSubmitting ? (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Loader2 className="h-4 w-4 animate-spin" />
|
|
||||||
<span>{isEditing ? 'Updating...' : 'Creating...'}</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
{isEditing ? (
|
|
||||||
<CheckCircle2 className="h-4 w-4" />
|
|
||||||
) : (
|
|
||||||
<Layers className="h-4 w-4" />
|
|
||||||
)}
|
|
||||||
<span>{isEditing ? 'Update Project' : 'Create Project'}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
7
src/app/(modules)/project/queries/projectKeys.ts
Normal file
7
src/app/(modules)/project/queries/projectKeys.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import type { PaginationParams } from '@/types';
|
||||||
|
|
||||||
|
export const projectKeys = {
|
||||||
|
all: ['projects'] as const,
|
||||||
|
lists: () => [...projectKeys.all, 'list'] as const,
|
||||||
|
list: (params: PaginationParams) => [...projectKeys.lists(), params] as const,
|
||||||
|
};
|
||||||
150
src/app/(modules)/segment/components/SegmentColumns.tsx
Normal file
150
src/app/(modules)/segment/components/SegmentColumns.tsx
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
import type { ColumnDef } from '@tanstack/react-table';
|
||||||
|
import { ArrowDownCircle, ArrowUpCircle, MapPin, Milestone } from 'lucide-react';
|
||||||
|
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||||
|
import type { Chainage, Package, Project } from '@/types';
|
||||||
|
|
||||||
|
function EmptyValue() {
|
||||||
|
return <span className="text-muted-foreground">-</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function StateBadges({ value }: { value: string | null }) {
|
||||||
|
if (!value) {
|
||||||
|
return <EmptyValue />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const states = value
|
||||||
|
.split(',')
|
||||||
|
.map((state) => state.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
if (!states.length) {
|
||||||
|
return <EmptyValue />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [firstState, ...remainingStates] = states;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<Badge variant="secondary">{firstState}</Badge>
|
||||||
|
{remainingStates.length > 0 ? (
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="flex items-center justify-center rounded-full border border-border/40 bg-muted/50 px-1.5 py-0.5 text-[10px] font-bold text-muted-foreground transition-colors hover:bg-muted"
|
||||||
|
>
|
||||||
|
+{remainingStates.length}
|
||||||
|
</button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-auto p-2" align="start">
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<p className="mb-0.5 px-1 text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
|
||||||
|
Other States
|
||||||
|
</p>
|
||||||
|
{remainingStates.map((state) => (
|
||||||
|
<Badge key={state} variant="secondary">
|
||||||
|
{state}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSegmentColumns(projects: Project[], packages: Package[]) {
|
||||||
|
return useMemo<ColumnDef<Chainage>[]>(
|
||||||
|
() => [
|
||||||
|
{
|
||||||
|
accessorKey: 'segment_name',
|
||||||
|
header: 'Segment Name',
|
||||||
|
cell: ({ row }) => <div className="font-semibold">{row.original.segment_name}</div>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'package_id',
|
||||||
|
header: 'Package',
|
||||||
|
cell: ({ row }) =>
|
||||||
|
packages.find((pkg) => pkg.id === row.original.package_id)?.name ||
|
||||||
|
row.original.package_id,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'project',
|
||||||
|
header: 'Project',
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const pkg = packages.find((item) => item.id === row.original.package_id);
|
||||||
|
const project = projects.find((item) => item.id === pkg?.project_id);
|
||||||
|
return project?.name || <EmptyValue />;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'project_state',
|
||||||
|
header: 'Project State',
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const pkg = packages.find((item) => item.id === row.original.package_id);
|
||||||
|
const project = projects.find((item) => item.id === pkg?.project_id);
|
||||||
|
return <StateBadges value={project?.state ?? null} />;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'chainage',
|
||||||
|
header: 'Segment Range (km)',
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const segment = row.original;
|
||||||
|
return (
|
||||||
|
<div className="flex flex-row gap-2">
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="flex items-center gap-1.5 border-amber-500/50 font-bold text-amber-500"
|
||||||
|
>
|
||||||
|
<Milestone className="size-3" />
|
||||||
|
{segment.chainage_start_km} - {segment.chainage_end_km}
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="secondary" className="gap-1.5">
|
||||||
|
{segment.direction === 'UP' ? (
|
||||||
|
<ArrowUpCircle className="size-3" />
|
||||||
|
) : (
|
||||||
|
<ArrowDownCircle className="size-3" />
|
||||||
|
)}
|
||||||
|
{segment.direction}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'start_gps',
|
||||||
|
header: 'Start GPS',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="flex items-center gap-1.5 border-blue-500/50 font-bold text-blue-500"
|
||||||
|
>
|
||||||
|
<MapPin className="size-3" />
|
||||||
|
{row.original.start_lat.toFixed(4)}, {row.original.start_lng.toFixed(4)}
|
||||||
|
</Badge>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'end_gps',
|
||||||
|
header: 'End GPS',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="flex items-center gap-1.5 border-blue-500/50 font-bold text-blue-500"
|
||||||
|
>
|
||||||
|
<MapPin className="size-3" />
|
||||||
|
{row.original.end_lat.toFixed(4)}, {row.original.end_lng.toFixed(4)}
|
||||||
|
</Badge>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[packages, projects],
|
||||||
|
);
|
||||||
|
}
|
||||||
293
src/app/(modules)/segment/components/SegmentDialog.tsx
Normal file
293
src/app/(modules)/segment/components/SegmentDialog.tsx
Normal file
@@ -0,0 +1,293 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import type { ComponentProps } from 'react';
|
||||||
|
import type { FieldErrors, UseFormRegister, UseFormReturn } from 'react-hook-form';
|
||||||
|
import { Loader2, MapPin, Milestone } from 'lucide-react';
|
||||||
|
|
||||||
|
import { FormField } from '@/components/form';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select';
|
||||||
|
import type { Package, Project } from '@/types';
|
||||||
|
|
||||||
|
import type { SegmentFormValues } from '../hooks/useSegmentForm';
|
||||||
|
|
||||||
|
interface SegmentDialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
segmentId?: string;
|
||||||
|
projects: Project[];
|
||||||
|
packages: Package[];
|
||||||
|
isProjectsLoading: boolean;
|
||||||
|
isPackagesLoading: boolean;
|
||||||
|
projectId: string;
|
||||||
|
onProjectChange: (projectId: string) => void;
|
||||||
|
packageId: string;
|
||||||
|
onPackageChange: (packageId: string) => void;
|
||||||
|
direction: 'UP' | 'DOWN';
|
||||||
|
onDirectionChange: (direction: 'UP' | 'DOWN') => void;
|
||||||
|
register: UseFormRegister<SegmentFormValues>;
|
||||||
|
errors: FieldErrors<SegmentFormValues>;
|
||||||
|
touchedFields: UseFormReturn<SegmentFormValues>['formState']['touchedFields'];
|
||||||
|
onSubmit: ComponentProps<'form'>['onSubmit'];
|
||||||
|
canSubmit: boolean;
|
||||||
|
isSaving: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SegmentDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
segmentId,
|
||||||
|
projects,
|
||||||
|
packages,
|
||||||
|
isProjectsLoading,
|
||||||
|
isPackagesLoading,
|
||||||
|
projectId,
|
||||||
|
onProjectChange,
|
||||||
|
packageId,
|
||||||
|
onPackageChange,
|
||||||
|
direction,
|
||||||
|
onDirectionChange,
|
||||||
|
register,
|
||||||
|
errors,
|
||||||
|
touchedFields,
|
||||||
|
onSubmit,
|
||||||
|
canSubmit,
|
||||||
|
isSaving,
|
||||||
|
}: SegmentDialogProps) {
|
||||||
|
const getError = (field: keyof SegmentFormValues) =>
|
||||||
|
touchedFields[field] ? errors[field]?.message : undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent
|
||||||
|
className="max-h-[calc(100vh-2rem)] overflow-y-auto sm:max-w-2xl"
|
||||||
|
onOpenAutoFocus={(event) => event.preventDefault()}
|
||||||
|
>
|
||||||
|
<DialogHeader className="gap-2">
|
||||||
|
<DialogTitle className="flex items-center gap-3 text-xl">
|
||||||
|
<div className="rounded-lg bg-primary p-2 text-primary-foreground shadow-sm">
|
||||||
|
<Milestone className="size-5" />
|
||||||
|
</div>
|
||||||
|
{segmentId ? 'Edit Segment' : 'Create Segment'}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-sm">
|
||||||
|
{segmentId
|
||||||
|
? 'Update the technical specifications for your road segment.'
|
||||||
|
: 'Select a project and package, then provide the segment data.'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<form onSubmit={onSubmit} className="space-y-6">
|
||||||
|
{!segmentId ? (
|
||||||
|
<div className="grid gap-5 md:grid-cols-2">
|
||||||
|
<FormField label="Project" required error={getError('project_id')}>
|
||||||
|
<Select value={projectId} onValueChange={onProjectChange}>
|
||||||
|
<SelectTrigger aria-invalid={!!getError('project_id')}>
|
||||||
|
{isProjectsLoading ? (
|
||||||
|
<span className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
Loading...
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<SelectValue placeholder="Choose a project" />
|
||||||
|
)}
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{projects.map((project) => (
|
||||||
|
<SelectItem key={project.id} value={project.id}>
|
||||||
|
{project.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<input type="hidden" {...register('project_id')} value={projectId} readOnly />
|
||||||
|
</FormField>
|
||||||
|
|
||||||
|
<FormField label="Package" required error={getError('package_id')}>
|
||||||
|
<Select
|
||||||
|
value={packageId}
|
||||||
|
onValueChange={onPackageChange}
|
||||||
|
disabled={!projectId || isPackagesLoading}
|
||||||
|
>
|
||||||
|
<SelectTrigger aria-invalid={!!getError('package_id')}>
|
||||||
|
{isPackagesLoading ? (
|
||||||
|
<span className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
Loading...
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<SelectValue placeholder={projectId ? 'Choose a package' : 'Select project first'} />
|
||||||
|
)}
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{packages.map((pkg) => (
|
||||||
|
<SelectItem key={pkg.id} value={pkg.id}>
|
||||||
|
{pkg.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<input type="hidden" {...register('package_id')} value={packageId} readOnly />
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="grid gap-5 md:grid-cols-2">
|
||||||
|
<FormField
|
||||||
|
id="segment-name"
|
||||||
|
label="Segment Name"
|
||||||
|
required
|
||||||
|
error={getError('segment_name')}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
id="segment-name"
|
||||||
|
placeholder="e.g. Mumbai to Pune"
|
||||||
|
aria-invalid={!!getError('segment_name')}
|
||||||
|
{...register('segment_name')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
|
||||||
|
<FormField label="Direction" required>
|
||||||
|
<Select value={direction} onValueChange={onDirectionChange}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select direction" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="UP">UP</SelectItem>
|
||||||
|
<SelectItem value="DOWN">DOWN</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</FormField>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
id="segment-start-km"
|
||||||
|
label="Start (km)"
|
||||||
|
required
|
||||||
|
error={getError('chainage_start_km')}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
id="segment-start-km"
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
min="0"
|
||||||
|
placeholder="0.0"
|
||||||
|
aria-invalid={!!getError('chainage_start_km')}
|
||||||
|
{...register('chainage_start_km')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
id="segment-end-km"
|
||||||
|
label="End (km)"
|
||||||
|
required
|
||||||
|
error={getError('chainage_end_km')}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
id="segment-end-km"
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
min="0"
|
||||||
|
placeholder="1.0"
|
||||||
|
aria-invalid={!!getError('chainage_end_km')}
|
||||||
|
{...register('chainage_end_km')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-6 md:grid-cols-2">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<p className="flex items-center gap-2 text-[11px] font-black tracking-widest text-muted-foreground">
|
||||||
|
<MapPin className="size-3.5 opacity-60" />
|
||||||
|
START COORDINATES
|
||||||
|
</p>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<FormField id="start-lat" label="Latitude" required error={getError('start_lat')}>
|
||||||
|
<Input
|
||||||
|
id="start-lat"
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
min="-90"
|
||||||
|
max="90"
|
||||||
|
placeholder="-90 to 90"
|
||||||
|
aria-invalid={!!getError('start_lat')}
|
||||||
|
{...register('start_lat')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
<FormField id="start-lng" label="Longitude" required error={getError('start_lng')}>
|
||||||
|
<Input
|
||||||
|
id="start-lng"
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
min="-180"
|
||||||
|
max="180"
|
||||||
|
placeholder="-180 to 180"
|
||||||
|
aria-invalid={!!getError('start_lng')}
|
||||||
|
{...register('start_lng')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<p className="flex items-center gap-2 text-[11px] font-black tracking-widest text-muted-foreground">
|
||||||
|
<MapPin className="size-3.5 opacity-60" />
|
||||||
|
END COORDINATES
|
||||||
|
</p>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<FormField id="end-lat" label="Latitude" required error={getError('end_lat')}>
|
||||||
|
<Input
|
||||||
|
id="end-lat"
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
min="-90"
|
||||||
|
max="90"
|
||||||
|
placeholder="-90 to 90"
|
||||||
|
aria-invalid={!!getError('end_lat')}
|
||||||
|
{...register('end_lat')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
<FormField id="end-lng" label="Longitude" required error={getError('end_lng')}>
|
||||||
|
<Input
|
||||||
|
id="end-lng"
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
min="-180"
|
||||||
|
max="180"
|
||||||
|
placeholder="-180 to 180"
|
||||||
|
aria-invalid={!!getError('end_lng')}
|
||||||
|
{...register('end_lng')}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={isSaving || !canSubmit}>
|
||||||
|
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
|
{segmentId ? 'Update Segment' : 'Create Segment'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
51
src/app/(modules)/segment/components/SegmentTable.tsx
Normal file
51
src/app/(modules)/segment/components/SegmentTable.tsx
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import type { ColumnDef } from '@tanstack/react-table';
|
||||||
|
|
||||||
|
import { DataTable } from '@/components/data-table';
|
||||||
|
import type { Chainage } from '@/types';
|
||||||
|
|
||||||
|
interface SegmentTableProps {
|
||||||
|
columns: ColumnDef<Chainage>[];
|
||||||
|
segments: Chainage[];
|
||||||
|
isLoading: boolean;
|
||||||
|
skip: number;
|
||||||
|
limit: number;
|
||||||
|
total: number;
|
||||||
|
onPageChange: (skip: number) => void;
|
||||||
|
onLimitChange: (limit: number) => void;
|
||||||
|
onEdit: (segment: Chainage) => void;
|
||||||
|
onDelete: (segment: Chainage) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SegmentTable({
|
||||||
|
columns,
|
||||||
|
segments,
|
||||||
|
isLoading,
|
||||||
|
skip,
|
||||||
|
limit,
|
||||||
|
total,
|
||||||
|
onPageChange,
|
||||||
|
onLimitChange,
|
||||||
|
onEdit,
|
||||||
|
onDelete,
|
||||||
|
}: SegmentTableProps) {
|
||||||
|
return (
|
||||||
|
<DataTable
|
||||||
|
title="Segments"
|
||||||
|
data={segments}
|
||||||
|
columns={columns}
|
||||||
|
onEdit={onEdit}
|
||||||
|
onDelete={onDelete}
|
||||||
|
isLoading={isLoading}
|
||||||
|
emptyTitle="No segments found."
|
||||||
|
pagination={{
|
||||||
|
skip,
|
||||||
|
limit,
|
||||||
|
totalItems: total,
|
||||||
|
onPageChange,
|
||||||
|
onLimitChange,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
20
src/app/(modules)/segment/hooks/useSegmentFilters.ts
Normal file
20
src/app/(modules)/segment/hooks/useSegmentFilters.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback, useState } from 'react';
|
||||||
|
|
||||||
|
export function useSegmentFilters() {
|
||||||
|
const [skip, setSkip] = useState(0);
|
||||||
|
const [limit, setLimitValue] = useState(10);
|
||||||
|
|
||||||
|
const setLimit = useCallback((value: number) => {
|
||||||
|
setLimitValue(value);
|
||||||
|
setSkip(0);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
skip,
|
||||||
|
setSkip,
|
||||||
|
limit,
|
||||||
|
setLimit,
|
||||||
|
};
|
||||||
|
}
|
||||||
207
src/app/(modules)/segment/hooks/useSegmentForm.ts
Normal file
207
src/app/(modules)/segment/hooks/useSegmentForm.ts
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { useCallback } from 'react';
|
||||||
|
import { useForm, useWatch } from 'react-hook-form';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import { chainageService } from '@/services/api';
|
||||||
|
import type { Chainage, ChainageCreate, ChainageUpdate } from '@/types';
|
||||||
|
|
||||||
|
import { segmentKeys } from '../queries/segmentKeys';
|
||||||
|
|
||||||
|
const requiredNumber = (message: string) =>
|
||||||
|
z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(1, message)
|
||||||
|
.refine((value) => Number.isFinite(Number(value)), { message: 'Enter a valid number' });
|
||||||
|
|
||||||
|
const latitude = requiredNumber('Latitude is required').refine(
|
||||||
|
(value) => {
|
||||||
|
const numberValue = Number(value);
|
||||||
|
return numberValue >= -90 && numberValue <= 90;
|
||||||
|
},
|
||||||
|
{ message: 'Latitude must be between -90 and 90' },
|
||||||
|
);
|
||||||
|
|
||||||
|
const longitude = requiredNumber('Longitude is required').refine(
|
||||||
|
(value) => {
|
||||||
|
const numberValue = Number(value);
|
||||||
|
return numberValue >= -180 && numberValue <= 180;
|
||||||
|
},
|
||||||
|
{ message: 'Longitude must be between -180 and 180' },
|
||||||
|
);
|
||||||
|
|
||||||
|
const segmentFormSchema = z.object({
|
||||||
|
id: z.string().optional(),
|
||||||
|
project_id: z.string().trim().min(1, 'Project is required'),
|
||||||
|
package_id: z.string().trim().min(1, 'Package is required'),
|
||||||
|
segment_name: z.string().trim().min(1, 'Segment name is required'),
|
||||||
|
chainage_start_km: requiredNumber('Start km is required'),
|
||||||
|
chainage_end_km: requiredNumber('End km is required'),
|
||||||
|
start_lat: latitude,
|
||||||
|
start_lng: longitude,
|
||||||
|
end_lat: latitude,
|
||||||
|
end_lng: longitude,
|
||||||
|
direction: z.enum(['UP', 'DOWN']),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type SegmentFormValues = z.infer<typeof segmentFormSchema>;
|
||||||
|
|
||||||
|
const defaultValues: SegmentFormValues = {
|
||||||
|
project_id: '',
|
||||||
|
package_id: '',
|
||||||
|
segment_name: '',
|
||||||
|
chainage_start_km: '',
|
||||||
|
chainage_end_km: '',
|
||||||
|
start_lat: '',
|
||||||
|
start_lng: '',
|
||||||
|
end_lat: '',
|
||||||
|
end_lng: '',
|
||||||
|
direction: 'UP',
|
||||||
|
};
|
||||||
|
|
||||||
|
function toSegmentPayload(values: SegmentFormValues): ChainageCreate | ChainageUpdate {
|
||||||
|
return {
|
||||||
|
package_id: values.package_id,
|
||||||
|
segment_name: values.segment_name.trim(),
|
||||||
|
chainage_start_km: Number(values.chainage_start_km),
|
||||||
|
chainage_end_km: Number(values.chainage_end_km),
|
||||||
|
start_lat: Number(values.start_lat),
|
||||||
|
start_lng: Number(values.start_lng),
|
||||||
|
end_lat: Number(values.end_lat),
|
||||||
|
end_lng: Number(values.end_lng),
|
||||||
|
direction: values.direction,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSegmentForm({ onSaved }: { onSaved: () => void }) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const {
|
||||||
|
register,
|
||||||
|
handleSubmit,
|
||||||
|
reset,
|
||||||
|
setValue,
|
||||||
|
control,
|
||||||
|
formState: { errors, isSubmitting, touchedFields },
|
||||||
|
} = useForm<SegmentFormValues>({
|
||||||
|
defaultValues,
|
||||||
|
mode: 'onTouched',
|
||||||
|
reValidateMode: 'onChange',
|
||||||
|
resolver: zodResolver(segmentFormSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
const segmentId = useWatch({ control, name: 'id' });
|
||||||
|
const projectId = useWatch({ control, name: 'project_id' }) || '';
|
||||||
|
const packageId = useWatch({ control, name: 'package_id' }) || '';
|
||||||
|
const direction = useWatch({ control, name: 'direction' }) || 'UP';
|
||||||
|
const segmentName = useWatch({ control, name: 'segment_name' }) || '';
|
||||||
|
const chainageStartKm = useWatch({ control, name: 'chainage_start_km' }) || '';
|
||||||
|
const chainageEndKm = useWatch({ control, name: 'chainage_end_km' }) || '';
|
||||||
|
const startLat = useWatch({ control, name: 'start_lat' }) || '';
|
||||||
|
const startLng = useWatch({ control, name: 'start_lng' }) || '';
|
||||||
|
const endLat = useWatch({ control, name: 'end_lat' }) || '';
|
||||||
|
const endLng = useWatch({ control, name: 'end_lng' }) || '';
|
||||||
|
const canSubmit =
|
||||||
|
projectId.trim().length > 0 &&
|
||||||
|
packageId.trim().length > 0 &&
|
||||||
|
segmentName.trim().length > 0 &&
|
||||||
|
chainageStartKm.trim().length > 0 &&
|
||||||
|
chainageEndKm.trim().length > 0 &&
|
||||||
|
startLat.trim().length > 0 &&
|
||||||
|
startLng.trim().length > 0 &&
|
||||||
|
endLat.trim().length > 0 &&
|
||||||
|
endLng.trim().length > 0;
|
||||||
|
|
||||||
|
const saveMutation = useMutation({
|
||||||
|
mutationFn: (values: SegmentFormValues) => {
|
||||||
|
const payload = toSegmentPayload(values);
|
||||||
|
return values.id
|
||||||
|
? chainageService.updateChainage(values.id, payload)
|
||||||
|
: chainageService.createChainage(payload as ChainageCreate);
|
||||||
|
},
|
||||||
|
onSuccess: (_data, values) => {
|
||||||
|
toast.success(values.id ? 'Segment updated' : 'Segment created');
|
||||||
|
reset(defaultValues);
|
||||||
|
onSaved();
|
||||||
|
queryClient.invalidateQueries({ queryKey: segmentKeys.all });
|
||||||
|
},
|
||||||
|
onError: (_error, values) => {
|
||||||
|
toast.error(values.id ? 'Failed to update segment' : 'Failed to create segment');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const onSubmit = handleSubmit(
|
||||||
|
(values) => saveMutation.mutate(values),
|
||||||
|
(formErrors) => {
|
||||||
|
const firstMessage = Object.values(formErrors).find((error) => error?.message)?.message;
|
||||||
|
if (firstMessage) {
|
||||||
|
toast.error(String(firstMessage));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const openCreate = useCallback(() => {
|
||||||
|
reset(defaultValues);
|
||||||
|
}, [reset]);
|
||||||
|
|
||||||
|
const openEdit = useCallback(
|
||||||
|
(segment: Chainage, projectIdForSegment: string) => {
|
||||||
|
reset({
|
||||||
|
id: segment.id,
|
||||||
|
project_id: projectIdForSegment,
|
||||||
|
package_id: segment.package_id,
|
||||||
|
segment_name: segment.segment_name || '',
|
||||||
|
chainage_start_km: segment.chainage_start_km?.toString() || '',
|
||||||
|
chainage_end_km: segment.chainage_end_km?.toString() || '',
|
||||||
|
start_lat: segment.start_lat?.toString() || '',
|
||||||
|
start_lng: segment.start_lng?.toString() || '',
|
||||||
|
end_lat: segment.end_lat?.toString() || '',
|
||||||
|
end_lng: segment.end_lng?.toString() || '',
|
||||||
|
direction: segment.direction || 'UP',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[reset],
|
||||||
|
);
|
||||||
|
|
||||||
|
const setProjectId = useCallback(
|
||||||
|
(value: string) => {
|
||||||
|
setValue('project_id', value, { shouldDirty: true, shouldValidate: true });
|
||||||
|
setValue('package_id', '', { shouldDirty: true, shouldValidate: true });
|
||||||
|
},
|
||||||
|
[setValue],
|
||||||
|
);
|
||||||
|
|
||||||
|
const setPackageId = useCallback(
|
||||||
|
(value: string) => setValue('package_id', value, { shouldDirty: true, shouldValidate: true }),
|
||||||
|
[setValue],
|
||||||
|
);
|
||||||
|
|
||||||
|
const setDirection = useCallback(
|
||||||
|
(value: 'UP' | 'DOWN') =>
|
||||||
|
setValue('direction', value, { shouldDirty: true, shouldValidate: true }),
|
||||||
|
[setValue],
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
register,
|
||||||
|
onSubmit,
|
||||||
|
openCreate,
|
||||||
|
openEdit,
|
||||||
|
resetForm: () => reset(defaultValues),
|
||||||
|
segmentId,
|
||||||
|
projectId,
|
||||||
|
setProjectId,
|
||||||
|
packageId,
|
||||||
|
setPackageId,
|
||||||
|
direction,
|
||||||
|
setDirection,
|
||||||
|
errors,
|
||||||
|
touchedFields,
|
||||||
|
canSubmit,
|
||||||
|
isSaving: isSubmitting || saveMutation.isPending,
|
||||||
|
};
|
||||||
|
}
|
||||||
65
src/app/(modules)/segment/hooks/useSegmentQueries.ts
Normal file
65
src/app/(modules)/segment/hooks/useSegmentQueries.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
import { chainageService, packageService, projectService } from '@/services/api';
|
||||||
|
import type { Chainage, PaginationParams } from '@/types';
|
||||||
|
|
||||||
|
import { segmentKeys } from '../queries/segmentKeys';
|
||||||
|
|
||||||
|
interface UseSegmentsQueryParams {
|
||||||
|
skip: number;
|
||||||
|
limit: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSegmentsQuery({ skip, limit }: UseSegmentsQueryParams) {
|
||||||
|
const listParams = useMemo<PaginationParams>(() => ({ skip, limit }), [limit, skip]);
|
||||||
|
|
||||||
|
return useQuery({
|
||||||
|
queryKey: segmentKeys.list(listParams),
|
||||||
|
queryFn: () => chainageService.getChainages(listParams),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useProjectOptionsQuery() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['projects', 'options'],
|
||||||
|
queryFn: () => projectService.getProjects({ skip: 0, limit: 1000 }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAllPackageOptionsQuery() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['packages', 'options'],
|
||||||
|
queryFn: () => packageService.getPackages({ skip: 0, limit: 1000 }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePackagesByProjectQuery(projectId: string, enabled: boolean) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['packages', 'by-project', projectId],
|
||||||
|
queryFn: () => packageService.getPackagesByProject(projectId, { skip: 0, limit: 1000 }),
|
||||||
|
enabled: enabled && Boolean(projectId),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeleteSegmentMutation() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (segment: Chainage) => chainageService.deleteChainage(segment.id),
|
||||||
|
onSuccess: (_data, segment) => {
|
||||||
|
toast.success('Segment deleted', {
|
||||||
|
description: `${segment.segment_name} has been removed from the system.`,
|
||||||
|
});
|
||||||
|
queryClient.invalidateQueries({ queryKey: segmentKeys.all });
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
toast.error('Deletion failed', {
|
||||||
|
description: 'The segment could not be removed. Please try again.',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,829 +1,149 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
import { useCallback, useState } from 'react';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Milestone, Plus } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from '@/components/ui/select';
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from '@/components/ui/dialog';
|
|
||||||
import {
|
|
||||||
Loader2,
|
|
||||||
CheckCircle2,
|
|
||||||
MapPin,
|
|
||||||
Navigation,
|
|
||||||
Milestone,
|
|
||||||
ArrowUpCircle,
|
|
||||||
ArrowDownCircle,
|
|
||||||
} from 'lucide-react';
|
|
||||||
import { DataTable } from '@/components/data-table';
|
|
||||||
import { PageHeader } from '@/components/page-header';
|
import { PageHeader } from '@/components/page-header';
|
||||||
import { PoweredBy } from '@/components/powered-by';
|
import { PoweredBy } from '@/components/powered-by';
|
||||||
import { projectService, packageService, chainageService } from '@/services/api';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Project, Package as PackageType, Chainage, ChainageCreate, ChainageUpdate } from '@/types';
|
import type { Chainage } from '@/types';
|
||||||
import { ColumnDef } from '@tanstack/react-table';
|
|
||||||
import { toast } from 'sonner';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
|
||||||
|
|
||||||
export default function ChainagePage() {
|
import { SegmentDialog } from './components/SegmentDialog';
|
||||||
const [chainages, setChainages] = useState<Chainage[]>([]);
|
import { SegmentTable } from './components/SegmentTable';
|
||||||
const [totalItems, setTotalItems] = useState(0);
|
import { useSegmentColumns } from './components/SegmentColumns';
|
||||||
const [projects, setProjects] = useState<Project[]>([]);
|
import { useSegmentFilters } from './hooks/useSegmentFilters';
|
||||||
const [packages, setPackages] = useState<PackageType[]>([]);
|
import { useSegmentForm } from './hooks/useSegmentForm';
|
||||||
const [allPackages, setAllPackages] = useState<PackageType[]>([]);
|
import {
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
useAllPackageOptionsQuery,
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
useDeleteSegmentMutation,
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
usePackagesByProjectQuery,
|
||||||
const [error, setError] = useState<string | null>(null);
|
useProjectOptionsQuery,
|
||||||
const [loadingProjects, setLoadingProjects] = useState(false);
|
useSegmentsQuery,
|
||||||
const [loadingPackages, setLoadingPackages] = useState(false);
|
} from './hooks/useSegmentQueries';
|
||||||
|
|
||||||
// Pagination state
|
export default function SegmentPage() {
|
||||||
const [skip, setSkip] = useState(0);
|
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||||
const [limit, setLimit] = useState(10);
|
const { skip, setSkip, limit, setLimit } = useSegmentFilters();
|
||||||
|
const segmentsQuery = useSegmentsQuery({ skip, limit });
|
||||||
// Editing state
|
const projectsQuery = useProjectOptionsQuery();
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
const allPackagesQuery = useAllPackageOptionsQuery();
|
||||||
const [currentChainage, setCurrentChainage] = useState<Chainage | null>(null);
|
const deleteSegmentMutation = useDeleteSegmentMutation();
|
||||||
|
const segmentForm = useSegmentForm({
|
||||||
// Form fields
|
onSaved: () => setIsDialogOpen(false),
|
||||||
const [selectedProjectId, setSelectedProjectId] = useState('');
|
|
||||||
const [selectedPackageId, setSelectedPackageId] = useState('');
|
|
||||||
const [segmentName, setSegmentName] = useState('');
|
|
||||||
const [chainageStartKm, setChainageStartKm] = useState('');
|
|
||||||
const [chainageEndKm, setChainageEndKm] = useState('');
|
|
||||||
const [startLat, setStartLat] = useState('');
|
|
||||||
const [startLng, setStartLng] = useState('');
|
|
||||||
const [endLat, setEndLat] = useState('');
|
|
||||||
const [endLng, setEndLng] = useState('');
|
|
||||||
const [direction, setDirection] = useState<'UP' | 'DOWN'>('UP');
|
|
||||||
|
|
||||||
// Load chainages and projects
|
|
||||||
const loadChainages = async (currentSkip = skip, currentLimit = limit) => {
|
|
||||||
try {
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
const data = await chainageService.getChainages({ skip: currentSkip, limit: currentLimit });
|
|
||||||
setChainages(data.items);
|
|
||||||
setTotalItems(data.totalItems);
|
|
||||||
} catch (err) {
|
|
||||||
setError('Failed to load segments. Please check if the backend is running.');
|
|
||||||
} finally {
|
|
||||||
// Add a small delay for animation stability
|
|
||||||
setTimeout(() => {
|
|
||||||
setIsLoading(false);
|
|
||||||
}, 800);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const loadProjects = async () => {
|
|
||||||
try {
|
|
||||||
setLoadingProjects(true);
|
|
||||||
const data = await projectService.getProjects({ skip: 0, limit: 1000 });
|
|
||||||
setProjects(data.items);
|
|
||||||
} catch (err) {
|
|
||||||
setError('Failed to load projects.');
|
|
||||||
} finally {
|
|
||||||
setLoadingProjects(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const loadAllPackages = async () => {
|
|
||||||
try {
|
|
||||||
const data = await packageService.getPackages({ skip: 0, limit: 1000 });
|
|
||||||
setAllPackages(data.items);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Failed to load all packages');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
loadChainages(skip, limit);
|
|
||||||
loadProjects();
|
|
||||||
loadAllPackages();
|
|
||||||
}, [skip, limit]);
|
|
||||||
|
|
||||||
// Load packages when project changes
|
|
||||||
useEffect(() => {
|
|
||||||
if (!selectedProjectId) {
|
|
||||||
setPackages([]);
|
|
||||||
if (!isEditing) setSelectedPackageId('');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const loadPackagesForProject = async () => {
|
|
||||||
try {
|
|
||||||
setLoadingPackages(true);
|
|
||||||
if (!isEditing) setSelectedPackageId('');
|
|
||||||
const data = await packageService.getPackagesByProject(selectedProjectId, {
|
|
||||||
skip: 0,
|
|
||||||
limit: 1000,
|
|
||||||
});
|
});
|
||||||
setPackages(data.items);
|
const {
|
||||||
} catch (err) {
|
register,
|
||||||
setError('Failed to load packages for the selected project.');
|
onSubmit,
|
||||||
} finally {
|
openCreate: prepareCreateSegment,
|
||||||
setLoadingPackages(false);
|
openEdit: prepareEditSegment,
|
||||||
}
|
resetForm,
|
||||||
};
|
segmentId,
|
||||||
loadPackagesForProject();
|
projectId,
|
||||||
}, [selectedProjectId, isEditing]);
|
setProjectId,
|
||||||
|
packageId,
|
||||||
|
setPackageId,
|
||||||
|
direction,
|
||||||
|
setDirection,
|
||||||
|
errors,
|
||||||
|
touchedFields,
|
||||||
|
canSubmit,
|
||||||
|
isSaving,
|
||||||
|
} = segmentForm;
|
||||||
|
const projectPackagesQuery = usePackagesByProjectQuery(projectId, isDialogOpen);
|
||||||
|
|
||||||
const resetForm = () => {
|
const openCreate = useCallback(() => {
|
||||||
setSelectedProjectId('');
|
prepareCreateSegment();
|
||||||
setSelectedPackageId('');
|
setIsDialogOpen(true);
|
||||||
setSegmentName('');
|
}, [prepareCreateSegment]);
|
||||||
setChainageStartKm('');
|
|
||||||
setChainageEndKm('');
|
|
||||||
setStartLat('');
|
|
||||||
setStartLng('');
|
|
||||||
setEndLat('');
|
|
||||||
setEndLng('');
|
|
||||||
setDirection('UP');
|
|
||||||
setError(null);
|
|
||||||
setIsEditing(false);
|
|
||||||
setCurrentChainage(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const openEdit = useCallback(
|
||||||
e.preventDefault();
|
(segment: Chainage) => {
|
||||||
if (!selectedPackageId && !isEditing) {
|
const pkg = allPackagesQuery.data?.items.find((item) => item.id === segment.package_id);
|
||||||
setError('Please select a project and package first');
|
prepareEditSegment(segment, pkg?.project_id || '');
|
||||||
return;
|
setIsDialogOpen(true);
|
||||||
}
|
},
|
||||||
if (!segmentName.trim()) {
|
[allPackagesQuery.data?.items, prepareEditSegment],
|
||||||
setError('Segment name is required');
|
);
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!startLat || !startLng || !endLat || !endLng) {
|
|
||||||
setError('All GPS coordinates are required for segments');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const parsedStartLat = parseFloat(startLat);
|
|
||||||
const parsedStartLng = parseFloat(startLng);
|
|
||||||
const parsedEndLat = parseFloat(endLat);
|
|
||||||
const parsedEndLng = parseFloat(endLng);
|
|
||||||
|
|
||||||
if (parsedStartLat < -90 || parsedStartLat > 90 || parsedEndLat < -90 || parsedEndLat > 90) {
|
const handleDialogOpenChange = useCallback(
|
||||||
setError('Latitude values must be between -90 and 90');
|
(open: boolean) => {
|
||||||
return;
|
setIsDialogOpen(open);
|
||||||
}
|
if (!open) {
|
||||||
if (
|
|
||||||
parsedStartLng < -180 ||
|
|
||||||
parsedStartLng > 180 ||
|
|
||||||
parsedEndLng < -180 ||
|
|
||||||
parsedEndLng > 180
|
|
||||||
) {
|
|
||||||
setError('Longitude values must be between -180 and 180');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!chainageStartKm || !chainageEndKm) {
|
|
||||||
setError('Segment start and end values are required');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsSubmitting(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (isEditing && currentChainage) {
|
|
||||||
const data: ChainageUpdate = {
|
|
||||||
segment_name: segmentName.trim(),
|
|
||||||
chainage_start_km: parseFloat(chainageStartKm),
|
|
||||||
chainage_end_km: parseFloat(chainageEndKm),
|
|
||||||
start_lat: parsedStartLat,
|
|
||||||
start_lng: parsedStartLng,
|
|
||||||
end_lat: parsedEndLat,
|
|
||||||
end_lng: parsedEndLng,
|
|
||||||
direction: direction as 'UP' | 'DOWN',
|
|
||||||
};
|
|
||||||
await chainageService.updateChainage(currentChainage.id, data);
|
|
||||||
toast.success('Segment Updated', {
|
|
||||||
description: `${segmentName} has been updated successfully at ${new Date().toLocaleTimeString()}`,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
const data: ChainageCreate = {
|
|
||||||
package_id: selectedPackageId,
|
|
||||||
segment_name: segmentName.trim(),
|
|
||||||
chainage_start_km: parseFloat(chainageStartKm),
|
|
||||||
chainage_end_km: parseFloat(chainageEndKm),
|
|
||||||
start_lat: parsedStartLat,
|
|
||||||
start_lng: parsedStartLng,
|
|
||||||
end_lat: parsedEndLat,
|
|
||||||
end_lng: parsedEndLng,
|
|
||||||
direction: direction,
|
|
||||||
};
|
|
||||||
await chainageService.createChainage(data);
|
|
||||||
toast.success('Segment Created', {
|
|
||||||
description: `${segmentName} has been established successfully at ${new Date().toLocaleTimeString()}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Refresh chainages list
|
|
||||||
await loadChainages();
|
|
||||||
|
|
||||||
// Close modal and reset form immediately
|
|
||||||
setIsModalOpen(false);
|
|
||||||
resetForm();
|
resetForm();
|
||||||
} catch (err) {
|
|
||||||
const message =
|
|
||||||
err instanceof Error
|
|
||||||
? err.message
|
|
||||||
: `Failed to ${isEditing ? 'update' : 'create'} segment`;
|
|
||||||
setError(message);
|
|
||||||
toast.error('Operation Failed', {
|
|
||||||
description: message,
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsSubmitting(false);
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
const handleEdit = (chainage: Chainage) => {
|
|
||||||
setIsEditing(true);
|
|
||||||
setCurrentChainage(chainage);
|
|
||||||
|
|
||||||
// Find project for this package
|
|
||||||
const pkg = allPackages.find((p) => p.id === chainage.package_id);
|
|
||||||
if (pkg) {
|
|
||||||
setSelectedProjectId(pkg.project_id);
|
|
||||||
setSelectedPackageId(chainage.package_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
setSegmentName(chainage.segment_name || '');
|
|
||||||
setChainageStartKm(chainage.chainage_start_km?.toString() || '');
|
|
||||||
setChainageEndKm(chainage.chainage_end_km?.toString() || '');
|
|
||||||
setStartLat(chainage.start_lat.toString());
|
|
||||||
setStartLng(chainage.start_lng.toString());
|
|
||||||
setEndLat(chainage.end_lat.toString());
|
|
||||||
setEndLng(chainage.end_lng.toString());
|
|
||||||
setDirection(chainage.direction);
|
|
||||||
setIsModalOpen(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDelete = async (chainage: Chainage) => {
|
|
||||||
if (!confirm(`Are you sure you want to delete segment "${chainage.segment_name}"?`)) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
setIsLoading(true);
|
|
||||||
await chainageService.deleteChainage(chainage.id);
|
|
||||||
toast.success('Segment Deleted', {
|
|
||||||
description: `${chainage.segment_name} has been removed from the system.`,
|
|
||||||
});
|
|
||||||
await loadChainages();
|
|
||||||
} catch (err) {
|
|
||||||
setError('Failed to delete segment');
|
|
||||||
toast.error('Deletion Failed', {
|
|
||||||
description: 'The segment could not be removed. Please try again.',
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getPackageName = (packageId: string) => {
|
|
||||||
return allPackages.find((p) => p.id === packageId)?.name || packageId;
|
|
||||||
};
|
|
||||||
|
|
||||||
const isFormComplete =
|
|
||||||
selectedPackageId &&
|
|
||||||
segmentName.trim() &&
|
|
||||||
startLat &&
|
|
||||||
startLng &&
|
|
||||||
endLat &&
|
|
||||||
endLng &&
|
|
||||||
chainageStartKm &&
|
|
||||||
chainageEndKm;
|
|
||||||
|
|
||||||
const columns: ColumnDef<Chainage>[] = [
|
|
||||||
{
|
|
||||||
accessorKey: 'segment_name',
|
|
||||||
header: 'Segment Name',
|
|
||||||
cell: ({ row }) => <div className="font-semibold">{row.original.segment_name}</div>,
|
|
||||||
},
|
},
|
||||||
{
|
[resetForm],
|
||||||
accessorKey: 'package_id',
|
|
||||||
header: 'Package',
|
|
||||||
cell: ({ row }) => getPackageName(row.original.package_id),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'project',
|
|
||||||
header: 'Project',
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const chainage = row.original;
|
|
||||||
const pkg = allPackages.find((p) => p.id === chainage.package_id);
|
|
||||||
const project = projects.find((p) => p.id === pkg?.project_id);
|
|
||||||
return project?.name || '—';
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'project_state',
|
|
||||||
header: 'Project State',
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const chainage = row.original;
|
|
||||||
const pkg = allPackages.find((p) => p.id === chainage.package_id);
|
|
||||||
const project = projects.find((p) => p.id === pkg?.project_id);
|
|
||||||
if (!project?.state) return <span className="">—</span>;
|
|
||||||
|
|
||||||
const states = project.state
|
|
||||||
.split(',')
|
|
||||||
.map((s) => s.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
if (states.length === 0) return <span className="">—</span>;
|
|
||||||
|
|
||||||
const firstState = states[0];
|
|
||||||
const remainingStates = states.slice(1);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex items-center gap-1.5">
|
|
||||||
<Badge variant="secondary">{firstState}</Badge>
|
|
||||||
|
|
||||||
{remainingStates.length > 0 && (
|
|
||||||
<Popover>
|
|
||||||
<PopoverTrigger asChild>
|
|
||||||
<button className="flex items-center justify-center rounded-full bg-muted/50 hover:bg-muted px-1.5 py-0.5 text-[10px] font-bold text-muted-foreground transition-colors border border-border/40">
|
|
||||||
+{remainingStates.length}
|
|
||||||
</button>
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverContent className="w-auto p-2" align="start">
|
|
||||||
<div className="flex flex-col gap-1.5">
|
|
||||||
<p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">
|
|
||||||
Other States
|
|
||||||
</p>
|
|
||||||
{remainingStates.map((item, idx) => (
|
|
||||||
<Badge key={idx} variant="secondary">
|
|
||||||
{item}
|
|
||||||
</Badge>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</PopoverContent>
|
|
||||||
</Popover>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const deleteSegment = useCallback(
|
||||||
|
(segment: Chainage) => {
|
||||||
|
if (!confirm(`Are you sure you want to delete segment "${segment.segment_name}"?`)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
deleteSegmentMutation.mutate(segment);
|
||||||
},
|
},
|
||||||
},
|
[deleteSegmentMutation],
|
||||||
{
|
|
||||||
accessorKey: 'chainage',
|
|
||||||
header: 'Segment Range (km)',
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const chainage = row.original;
|
|
||||||
return (
|
|
||||||
<div className="flex flex-row gap-2">
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="flex items-center gap-1.5 border-amber-500/50 text-amber-500 font-bold whitespace-nowrap"
|
|
||||||
>
|
|
||||||
<Milestone className="h-3 w-3" />
|
|
||||||
{chainage.chainage_start_km} - {chainage.chainage_end_km}
|
|
||||||
</Badge>
|
|
||||||
<Badge variant="secondary">
|
|
||||||
{chainage.direction === 'UP' ? (
|
|
||||||
<ArrowUpCircle className="h-3 w-3" />
|
|
||||||
) : (
|
|
||||||
<ArrowDownCircle className="h-3 w-3" />
|
|
||||||
)}
|
|
||||||
{chainage.direction}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
},
|
|
||||||
},
|
const projects = projectsQuery.data?.items ?? [];
|
||||||
{
|
const allPackages = allPackagesQuery.data?.items ?? [];
|
||||||
accessorKey: 'start_gps',
|
const projectPackages = projectPackagesQuery.data?.items ?? [];
|
||||||
header: 'Start GPS',
|
const segments = segmentsQuery.data?.items ?? [];
|
||||||
cell: ({ row }) => (
|
const total = segmentsQuery.data?.totalItems ?? 0;
|
||||||
<Badge
|
const columns = useSegmentColumns(projects, allPackages);
|
||||||
variant="outline"
|
|
||||||
className="flex items-center gap-1.5 border-blue-500/50 text-blue-500 font-bold whitespace-nowrap"
|
|
||||||
>
|
|
||||||
<MapPin className="h-3 w-3" />
|
|
||||||
{row.original.start_lat.toFixed(4)}, {row.original.start_lng.toFixed(4)}
|
|
||||||
</Badge>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'end_gps',
|
|
||||||
header: 'End GPS',
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="flex items-center gap-1.5 border-blue-500/50 text-blue-500 font-bold whitespace-nowrap"
|
|
||||||
>
|
|
||||||
<MapPin className="h-3 w-3" />
|
|
||||||
{row.original.end_lat.toFixed(4)}, {row.original.end_lng.toFixed(4)}
|
|
||||||
</Badge>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<main className="relative z-10">
|
<main className="relative z-10 space-y-5">
|
||||||
{/* Refined Header */}
|
|
||||||
<div className="mb-8">
|
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title="Segment Management"
|
title="Segment Management"
|
||||||
description="Manage road segments"
|
description="Manage road segments"
|
||||||
icon={Milestone}
|
icon={Milestone}
|
||||||
actions={
|
actions={
|
||||||
<Button
|
<Button onClick={openCreate} size="sm">
|
||||||
onClick={() => {
|
<Plus />
|
||||||
setIsEditing(false);
|
|
||||||
setIsModalOpen(true);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Milestone className="mr-2 h-4 w-4" />
|
|
||||||
Add Segment
|
Add Segment
|
||||||
</Button>
|
</Button>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Data Table */}
|
<SegmentTable
|
||||||
<div>
|
|
||||||
<DataTable
|
|
||||||
title="Segments"
|
|
||||||
data={chainages}
|
|
||||||
columns={columns}
|
columns={columns}
|
||||||
onEdit={handleEdit}
|
segments={segments}
|
||||||
onDelete={handleDelete}
|
isLoading={segmentsQuery.isLoading || deleteSegmentMutation.isPending}
|
||||||
isLoading={isLoading}
|
skip={skip}
|
||||||
pagination={{
|
limit={limit}
|
||||||
skip,
|
total={total}
|
||||||
limit,
|
onPageChange={setSkip}
|
||||||
totalItems,
|
onLimitChange={setLimit}
|
||||||
onPageChange: setSkip,
|
onEdit={openEdit}
|
||||||
onLimitChange: (newLimit) => {
|
onDelete={deleteSegment}
|
||||||
setLimit(newLimit);
|
|
||||||
setSkip(0); // Reset skip when limit changes
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
<PoweredBy />
|
<PoweredBy />
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{/* Modal Dialog */}
|
<SegmentDialog
|
||||||
<Dialog
|
open={isDialogOpen}
|
||||||
open={isModalOpen}
|
onOpenChange={handleDialogOpenChange}
|
||||||
onOpenChange={(open) => {
|
segmentId={segmentId}
|
||||||
if (!open) {
|
projects={projects}
|
||||||
setIsModalOpen(false);
|
packages={projectPackages}
|
||||||
resetForm();
|
isProjectsLoading={projectsQuery.isLoading}
|
||||||
} else {
|
isPackagesLoading={projectPackagesQuery.isLoading}
|
||||||
setIsModalOpen(true);
|
projectId={projectId}
|
||||||
}
|
onProjectChange={setProjectId}
|
||||||
}}
|
packageId={packageId}
|
||||||
>
|
onPackageChange={setPackageId}
|
||||||
<DialogContent
|
direction={direction}
|
||||||
className="max-h-[90vh] overflow-y-auto sm:max-w-2xl"
|
onDirectionChange={setDirection}
|
||||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
register={register}
|
||||||
>
|
errors={errors}
|
||||||
<DialogHeader className="gap-2">
|
touchedFields={touchedFields}
|
||||||
<DialogTitle className="flex items-center gap-3 text-xl">
|
onSubmit={onSubmit}
|
||||||
<div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm">
|
canSubmit={canSubmit}
|
||||||
<Milestone className="h-5 w-5" />
|
isSaving={isSaving}
|
||||||
</div>
|
|
||||||
{isEditing ? 'Edit Segment' : 'Create Segment'}
|
|
||||||
</DialogTitle>
|
|
||||||
<DialogDescription className="text-sm">
|
|
||||||
{isEditing
|
|
||||||
? 'Update the technical specifications for your road segment.'
|
|
||||||
: 'Select a project & package, then provide the essential segment data.'}
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
|
||||||
{!isEditing && (
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
|
||||||
{/* Step 1: Select Project */}
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="flex items-center gap-2.5">
|
|
||||||
<div className="w-5 h-5 rounded-full bg-primary/10 text-primary flex items-center justify-center text-[10px] font-bold uppercase">
|
|
||||||
01
|
|
||||||
</div>
|
|
||||||
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
|
|
||||||
Select Project
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Select value={selectedProjectId} onValueChange={setSelectedProjectId}>
|
|
||||||
<SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20">
|
|
||||||
{loadingProjects ? (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Loader2 className="h-4 w-4 animate-spin text-primary" />
|
|
||||||
<span className="text-muted-foreground text-xs">Loading...</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<SelectValue placeholder="Choose a project..." />
|
|
||||||
)}
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{projects.map((project) => (
|
|
||||||
<SelectItem key={project.id} value={project.id} className="py-2.5">
|
|
||||||
<span className="font-semibold">{project.name}</span>
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Step 2: Select Package */}
|
|
||||||
<div
|
|
||||||
className={`space-y-3 ${selectedProjectId ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2.5">
|
|
||||||
<div
|
|
||||||
className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold uppercase ${selectedProjectId ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}`}
|
|
||||||
>
|
|
||||||
02
|
|
||||||
</div>
|
|
||||||
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
|
|
||||||
Select Package
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Select
|
|
||||||
value={selectedPackageId}
|
|
||||||
onValueChange={setSelectedPackageId}
|
|
||||||
disabled={!selectedProjectId}
|
|
||||||
>
|
|
||||||
<SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20">
|
|
||||||
{loadingPackages ? (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Loader2 className="h-4 w-4 animate-spin text-primary" />
|
|
||||||
<span className="text-muted-foreground text-xs">Loading...</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<SelectValue
|
|
||||||
placeholder={
|
|
||||||
selectedProjectId ? 'Choose a package...' : 'Select project first'
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
)}
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{packages.map((pkg) => (
|
|
||||||
<SelectItem key={pkg.id} value={pkg.id} className="py-2.5">
|
|
||||||
<span className="font-semibold">{pkg.name}</span>
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Step 3: Chainage Details */}
|
|
||||||
<div
|
|
||||||
className={`space-y-4 ${selectedPackageId || isEditing ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}
|
|
||||||
>
|
|
||||||
{!isEditing && (
|
|
||||||
<div className="flex items-center gap-2.5">
|
|
||||||
<div
|
|
||||||
className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold uppercase ${selectedPackageId ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}`}
|
|
||||||
>
|
|
||||||
03
|
|
||||||
</div>
|
|
||||||
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
|
|
||||||
Segment Information
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Segment Name & Chainage Row */}
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-5">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="segment"
|
|
||||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
|
|
||||||
>
|
|
||||||
Segment Name <span className="text-destructive">*</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="segment"
|
|
||||||
value={segmentName}
|
|
||||||
onChange={(e) => setSegmentName(e.target.value)}
|
|
||||||
placeholder="e.g. Mumbai to Pune"
|
|
||||||
className="h-11 bg-muted/20 border-border/60"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="ch-start"
|
|
||||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
|
|
||||||
>
|
|
||||||
Start (km) <span className="text-destructive">*</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="ch-start"
|
|
||||||
type="number"
|
|
||||||
step="any"
|
|
||||||
min="0"
|
|
||||||
value={chainageStartKm}
|
|
||||||
onChange={(e) => setChainageStartKm(e.target.value)}
|
|
||||||
placeholder="0.0"
|
|
||||||
className="h-11 bg-muted/20 border-border/60 text-sm font-mono"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="ch-end"
|
|
||||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
|
|
||||||
>
|
|
||||||
End (km) <span className="text-destructive">*</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="ch-end"
|
|
||||||
type="number"
|
|
||||||
step="any"
|
|
||||||
min="0"
|
|
||||||
value={chainageEndKm}
|
|
||||||
onChange={(e) => setChainageEndKm(e.target.value)}
|
|
||||||
placeholder="1.0"
|
|
||||||
className="h-11 bg-muted/20 border-border/60 text-sm font-mono"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Direction Row */}
|
|
||||||
<div className="space-y-3">
|
|
||||||
<Label
|
|
||||||
htmlFor="direction"
|
|
||||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
|
|
||||||
>
|
|
||||||
Direction <span className="text-destructive">*</span>
|
|
||||||
</Label>
|
|
||||||
<Select value={direction} onValueChange={(val: 'UP' | 'DOWN') => setDirection(val)}>
|
|
||||||
<SelectTrigger className="h-11 bg-muted/20 border-border/60 focus:ring-primary/20">
|
|
||||||
<SelectValue placeholder="Select Direction" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="UP" className="py-2.5">
|
|
||||||
<span>UP</span>
|
|
||||||
</SelectItem>
|
|
||||||
<SelectItem value="DOWN" className="py-2.5">
|
|
||||||
<span>DOWN</span>
|
|
||||||
</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* GPS Coordinates Grid */}
|
|
||||||
<div className="space-y-6 pt-4">
|
|
||||||
<div className="space-y-3">
|
|
||||||
<p className="text-[11px] font-black text-muted-foreground tracking-widest flex items-center gap-2">
|
|
||||||
<MapPin className="h-3.5 w-3.5 opacity-60" /> START COORDINATES
|
|
||||||
<span className="text-destructive">*</span>
|
|
||||||
</p>
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="s-lat"
|
|
||||||
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
|
|
||||||
>
|
|
||||||
Latitude
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="s-lat"
|
|
||||||
type="number"
|
|
||||||
step="any"
|
|
||||||
min="-90"
|
|
||||||
max="90"
|
|
||||||
value={startLat}
|
|
||||||
onChange={(e) => setStartLat(e.target.value)}
|
|
||||||
placeholder="-90 to 90"
|
|
||||||
className="h-10 bg-background/70 border-border/40 text-xs font-mono"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="s-lng"
|
|
||||||
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
|
|
||||||
>
|
|
||||||
Longitude
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="s-lng"
|
|
||||||
type="number"
|
|
||||||
step="any"
|
|
||||||
min="-180"
|
|
||||||
max="180"
|
|
||||||
value={startLng}
|
|
||||||
onChange={(e) => setStartLng(e.target.value)}
|
|
||||||
placeholder="-180 to 180"
|
|
||||||
className="h-10 bg-background/70 border-border/40 text-xs font-mono"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-3">
|
|
||||||
<p className="text-[11px] font-black text-muted-foreground tracking-widest flex items-center gap-2">
|
|
||||||
<MapPin className="h-3.5 w-3.5 opacity-60" /> END COORDINATES
|
|
||||||
<span className="text-destructive">*</span>
|
|
||||||
</p>
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="e-lat"
|
|
||||||
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
|
|
||||||
>
|
|
||||||
Latitude
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="e-lat"
|
|
||||||
type="number"
|
|
||||||
step="any"
|
|
||||||
min="-90"
|
|
||||||
max="90"
|
|
||||||
value={endLat}
|
|
||||||
onChange={(e) => setEndLat(e.target.value)}
|
|
||||||
placeholder="-90 to 90"
|
|
||||||
className="h-10 bg-background/70 border-border/40 text-xs font-mono"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label
|
|
||||||
htmlFor="e-lng"
|
|
||||||
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
|
|
||||||
>
|
|
||||||
Longitude
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="e-lng"
|
|
||||||
type="number"
|
|
||||||
step="any"
|
|
||||||
min="-180"
|
|
||||||
max="180"
|
|
||||||
value={endLng}
|
|
||||||
onChange={(e) => setEndLng(e.target.value)}
|
|
||||||
placeholder="-180 to 180"
|
|
||||||
className="h-10 bg-background/70 border-border/40 text-xs font-mono"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Submit Button */}
|
|
||||||
<div className="flex gap-4 pt-4">
|
|
||||||
<Button
|
|
||||||
className="flex-1"
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => {
|
|
||||||
setIsModalOpen(false);
|
|
||||||
resetForm();
|
|
||||||
}}
|
|
||||||
disabled={isSubmitting}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button type="submit" disabled={isSubmitting || !isFormComplete} className="flex-1">
|
|
||||||
{isSubmitting ? (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Loader2 className="h-4 w-4 animate-spin" />
|
|
||||||
<span>{isEditing ? 'Updating...' : 'Creating...'}</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
{isEditing ? (
|
|
||||||
<CheckCircle2 className="h-4 w-4" />
|
|
||||||
) : (
|
|
||||||
<Milestone className="h-4 w-4" />
|
|
||||||
)}
|
|
||||||
<span>{isEditing ? 'Update Segment' : 'Create Segment'}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
7
src/app/(modules)/segment/queries/segmentKeys.ts
Normal file
7
src/app/(modules)/segment/queries/segmentKeys.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import type { PaginationParams } from '@/types';
|
||||||
|
|
||||||
|
export const segmentKeys = {
|
||||||
|
all: ['segments'] as const,
|
||||||
|
lists: () => [...segmentKeys.all, 'list'] as const,
|
||||||
|
list: (params: PaginationParams) => [...segmentKeys.lists(), params] as const,
|
||||||
|
};
|
||||||
@@ -8,7 +8,7 @@ import { ScrollArea } from '@/components/ui/scroll-area';
|
|||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { ChainageSummaryData } from '@/types';
|
import { ChainageSummaryData } from '@/types';
|
||||||
import { projectService } from '@/services/api';
|
import { projectSummaryService } from '@/services/api';
|
||||||
import { getDetectionModeConfig } from '@/constants/detectionModeConfig';
|
import { getDetectionModeConfig } from '@/constants/detectionModeConfig';
|
||||||
|
|
||||||
// Dynamically import MapModal with SSR disabled (Leaflet requires window object)
|
// Dynamically import MapModal with SSR disabled (Leaflet requires window object)
|
||||||
@@ -37,7 +37,10 @@ const DetailedSummarySection = ({
|
|||||||
const fetchSummary = async () => {
|
const fetchSummary = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const data = await projectService.getProjectSummaryByVideo(projectId, videoId);
|
const data = await projectSummaryService.getProjectSummaryByVideo<ChainageSummaryData>(
|
||||||
|
projectId,
|
||||||
|
videoId,
|
||||||
|
);
|
||||||
setSummaryData(data);
|
setSummaryData(data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to fetch summary:', err);
|
console.error('Failed to fetch summary:', err);
|
||||||
|
|||||||
56
src/constants/apiRoutes.ts
Normal file
56
src/constants/apiRoutes.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
export const API_ROUTES = {
|
||||||
|
AUTH: {
|
||||||
|
LOGIN: 'api/auth/login',
|
||||||
|
REFRESH: 'api/auth/refresh',
|
||||||
|
LOGOUT: 'api/auth/logout',
|
||||||
|
ME: 'api/auth/me',
|
||||||
|
},
|
||||||
|
PERMISSIONS: {
|
||||||
|
MY_PERMISSIONS: 'api/permissions/my-permissions',
|
||||||
|
ORGANIZATION_TREE: 'api/permissions/organization-tree',
|
||||||
|
},
|
||||||
|
ROLES: {
|
||||||
|
BASE: 'api/roles',
|
||||||
|
DETAIL: (id: number) => `api/roles/${id}`,
|
||||||
|
STATUS: (id: number) => `api/roles/${id}/status`,
|
||||||
|
},
|
||||||
|
USERS: {
|
||||||
|
BASE: 'api/users',
|
||||||
|
STATUS: (id: number) => `api/users/${id}/status`,
|
||||||
|
},
|
||||||
|
CLIENTS: {
|
||||||
|
BASE: 'api/clients',
|
||||||
|
DETAIL: (id: number) => `api/clients/${id}`,
|
||||||
|
STATUS: (id: number) => `api/clients/${id}/status`,
|
||||||
|
},
|
||||||
|
PLANS: {
|
||||||
|
BASE: 'api/superadmin/plans',
|
||||||
|
DETAIL: (id: number) => `api/superadmin/plans/${id}`,
|
||||||
|
STATUS: (id: number) => `api/superadmin/plans/${id}/status`,
|
||||||
|
},
|
||||||
|
TENANTS: {
|
||||||
|
BASE: 'api/superadmin/tenants',
|
||||||
|
DETAIL: (id: number) => `api/superadmin/tenants/${id}`,
|
||||||
|
},
|
||||||
|
PROJECTS: {
|
||||||
|
BASE: 'biz/api/v1/projects',
|
||||||
|
DETAIL: (id: string) => `biz/api/v1/projects/${id}`,
|
||||||
|
},
|
||||||
|
PACKAGES: {
|
||||||
|
BASE: 'biz/api/v1/packages',
|
||||||
|
DETAIL: (id: string) => `biz/api/v1/packages/${id}`,
|
||||||
|
},
|
||||||
|
CHAINAGES: {
|
||||||
|
BASE: 'biz/api/v1/chainages',
|
||||||
|
DETAIL: (id: string) => `biz/api/v1/chainages/${id}`,
|
||||||
|
},
|
||||||
|
DASHBOARD: {
|
||||||
|
OVERVIEW: 'biz/api/v1/dashboard/overview',
|
||||||
|
},
|
||||||
|
VIDEOS: {
|
||||||
|
LIST: '/videos',
|
||||||
|
UPLOAD: '/upload',
|
||||||
|
STATUS: (id: string) => `/status/${id}`,
|
||||||
|
RESULTS: (id: string) => `/results/${id}`,
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
@@ -1,28 +1,31 @@
|
|||||||
import type { AuthResponseData, LoginPayload, MeResponse, PermissionResponse } from '@/types';
|
import type { AuthResponseData, LoginPayload, MeResponse, PermissionResponse } from '@/types';
|
||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
import axiosClient, { axiosAuth } from '../axios/axios';
|
import axiosClient, { axiosAuth } from '../axios/axios';
|
||||||
|
|
||||||
export const authService = {
|
export const authService = {
|
||||||
login: async (payload: LoginPayload): Promise<AuthResponseData> => {
|
login: async (payload: LoginPayload): Promise<AuthResponseData> => {
|
||||||
const response = await axiosAuth.post<AuthResponseData>('api/auth/login', payload, {
|
const response = await axiosAuth.post<AuthResponseData>(API_ROUTES.AUTH.LOGIN, payload, {
|
||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
});
|
});
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
refresh: async (): Promise<AuthResponseData> => {
|
refresh: async (): Promise<AuthResponseData> => {
|
||||||
const response = await axiosAuth.post<AuthResponseData>('api/auth/refresh', {}, {
|
const response = await axiosAuth.post<AuthResponseData>(API_ROUTES.AUTH.REFRESH, {}, {
|
||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
});
|
});
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
logout: async (): Promise<void> => {
|
logout: async (): Promise<void> => {
|
||||||
await axiosAuth.post('api/auth/logout', {}, { withCredentials: true });
|
await axiosAuth.post(API_ROUTES.AUTH.LOGOUT, {}, { withCredentials: true });
|
||||||
},
|
},
|
||||||
me: async (): Promise<MeResponse> => {
|
me: async (): Promise<MeResponse> => {
|
||||||
const response = await axiosClient.get<MeResponse>('api/auth/me');
|
const response = await axiosClient.get<MeResponse>(API_ROUTES.AUTH.ME);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
permissions: async (): Promise<PermissionResponse> => {
|
permissions: async (): Promise<PermissionResponse> => {
|
||||||
const response = await axiosClient.get<PermissionResponse>('api/permissions/my-permissions');
|
const response = await axiosClient.get<PermissionResponse>(
|
||||||
|
API_ROUTES.PERMISSIONS.MY_PERMISSIONS,
|
||||||
|
);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import axiosClient from '../axios/axios';
|
import axiosClient from '../axios/axios';
|
||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
import {
|
import {
|
||||||
Chainage,
|
Chainage,
|
||||||
ChainageCreate,
|
ChainageCreate,
|
||||||
@@ -7,8 +8,6 @@ import {
|
|||||||
PaginationParams,
|
PaginationParams,
|
||||||
} from '@/types';
|
} from '@/types';
|
||||||
|
|
||||||
const CHAINAGES_ENDPOINT = 'biz/api/v1/chainages';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Chainage Service
|
* Chainage Service
|
||||||
*/
|
*/
|
||||||
@@ -19,7 +18,7 @@ export const chainageService = {
|
|||||||
getChainages: async (params?: PaginationParams): Promise<PaginatedResponse<Chainage>> => {
|
getChainages: async (params?: PaginationParams): Promise<PaginatedResponse<Chainage>> => {
|
||||||
const skip = params?.skip ?? 0;
|
const skip = params?.skip ?? 0;
|
||||||
const limit = params?.limit ?? 100;
|
const limit = params?.limit ?? 100;
|
||||||
const response = await axiosClient.get<PaginatedResponse<Chainage>>(CHAINAGES_ENDPOINT, {
|
const response = await axiosClient.get<PaginatedResponse<Chainage>>(API_ROUTES.CHAINAGES.BASE, {
|
||||||
params: { skip, limit },
|
params: { skip, limit },
|
||||||
});
|
});
|
||||||
return response.data;
|
return response.data;
|
||||||
@@ -34,7 +33,7 @@ export const chainageService = {
|
|||||||
): Promise<PaginatedResponse<Chainage>> => {
|
): Promise<PaginatedResponse<Chainage>> => {
|
||||||
const skip = params?.skip ?? 0;
|
const skip = params?.skip ?? 0;
|
||||||
const limit = params?.limit ?? 100;
|
const limit = params?.limit ?? 100;
|
||||||
const response = await axiosClient.get<PaginatedResponse<Chainage>>(CHAINAGES_ENDPOINT, {
|
const response = await axiosClient.get<PaginatedResponse<Chainage>>(API_ROUTES.CHAINAGES.BASE, {
|
||||||
params: { package_id: packageId, skip, limit },
|
params: { package_id: packageId, skip, limit },
|
||||||
});
|
});
|
||||||
return response.data;
|
return response.data;
|
||||||
@@ -44,7 +43,7 @@ export const chainageService = {
|
|||||||
* Create a new chainage
|
* Create a new chainage
|
||||||
*/
|
*/
|
||||||
createChainage: async (data: ChainageCreate): Promise<Chainage> => {
|
createChainage: async (data: ChainageCreate): Promise<Chainage> => {
|
||||||
const response = await axiosClient.post<Chainage>(CHAINAGES_ENDPOINT, data);
|
const response = await axiosClient.post<Chainage>(API_ROUTES.CHAINAGES.BASE, data);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -52,7 +51,7 @@ export const chainageService = {
|
|||||||
* Update an existing chainage
|
* Update an existing chainage
|
||||||
*/
|
*/
|
||||||
updateChainage: async (chainageId: string, data: ChainageUpdate): Promise<Chainage> => {
|
updateChainage: async (chainageId: string, data: ChainageUpdate): Promise<Chainage> => {
|
||||||
const response = await axiosClient.put<Chainage>(`${CHAINAGES_ENDPOINT}/${chainageId}`, data);
|
const response = await axiosClient.put<Chainage>(API_ROUTES.CHAINAGES.DETAIL(chainageId), data);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -61,7 +60,7 @@ export const chainageService = {
|
|||||||
*/
|
*/
|
||||||
deleteChainage: async (chainageId: string): Promise<{ message: string }> => {
|
deleteChainage: async (chainageId: string): Promise<{ message: string }> => {
|
||||||
const response = await axiosClient.delete<{ message: string }>(
|
const response = await axiosClient.delete<{ message: string }>(
|
||||||
`${CHAINAGES_ENDPOINT}/${chainageId}`,
|
API_ROUTES.CHAINAGES.DETAIL(chainageId),
|
||||||
);
|
);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import axiosClient from '../axios/axios';
|
import axiosClient from '../axios/axios';
|
||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
import type { Client, ClientListParams, ClientListResponse, ClientRequest } from '@/types';
|
import type { Client, ClientListParams, ClientListResponse, ClientRequest } from '@/types';
|
||||||
|
|
||||||
const CLIENTS_ENDPOINT = 'api/clients';
|
|
||||||
|
|
||||||
function toClientPayload(payload: ClientRequest) {
|
function toClientPayload(payload: ClientRequest) {
|
||||||
return {
|
return {
|
||||||
name: payload.name,
|
name: payload.name,
|
||||||
@@ -21,7 +20,7 @@ function toClientPayload(payload: ClientRequest) {
|
|||||||
|
|
||||||
export const clientService = {
|
export const clientService = {
|
||||||
getClients: async (params?: ClientListParams): Promise<ClientListResponse> => {
|
getClients: async (params?: ClientListParams): Promise<ClientListResponse> => {
|
||||||
const response = await axiosClient.get<ClientListResponse>(CLIENTS_ENDPOINT, {
|
const response = await axiosClient.get<ClientListResponse>(API_ROUTES.CLIENTS.BASE, {
|
||||||
params: {
|
params: {
|
||||||
skip: params?.skip ?? 0,
|
skip: params?.skip ?? 0,
|
||||||
limit: params?.limit ?? 10,
|
limit: params?.limit ?? 10,
|
||||||
@@ -38,20 +37,20 @@ export const clientService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
getClientById: async (id: number): Promise<Client> => {
|
getClientById: async (id: number): Promise<Client> => {
|
||||||
const response = await axiosClient.get<Client>(`${CLIENTS_ENDPOINT}/${id}`);
|
const response = await axiosClient.get<Client>(API_ROUTES.CLIENTS.DETAIL(id));
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
saveClient: async (payload: ClientRequest): Promise<Client> => {
|
saveClient: async (payload: ClientRequest): Promise<Client> => {
|
||||||
const requestPayload = toClientPayload(payload);
|
const requestPayload = toClientPayload(payload);
|
||||||
const response = payload.id
|
const response = payload.id
|
||||||
? await axiosClient.put<Client>(`${CLIENTS_ENDPOINT}/${payload.id}`, requestPayload)
|
? await axiosClient.put<Client>(API_ROUTES.CLIENTS.DETAIL(payload.id), requestPayload)
|
||||||
: await axiosClient.post<Client>(CLIENTS_ENDPOINT, requestPayload);
|
: await axiosClient.post<Client>(API_ROUTES.CLIENTS.BASE, requestPayload);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
updateClientStatus: async (id: number, isActive: boolean): Promise<Client> => {
|
updateClientStatus: async (id: number, isActive: boolean): Promise<Client> => {
|
||||||
const response = await axiosClient.patch<Client>(`${CLIENTS_ENDPOINT}/${id}/status`, {
|
const response = await axiosClient.patch<Client>(API_ROUTES.CLIENTS.STATUS(id), {
|
||||||
is_active: isActive,
|
is_active: isActive,
|
||||||
});
|
});
|
||||||
return response.data;
|
return response.data;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import axiosClient from '../axios/axios';
|
import axiosClient from '../axios/axios';
|
||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
import { Detection } from '@/types';
|
import { Detection } from '@/types';
|
||||||
import { projectService } from './project.service';
|
import { projectService } from './project.service';
|
||||||
|
|
||||||
@@ -31,7 +32,7 @@ export const detectionService = {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
}>('biz/api/v1/dashboard/overview', {
|
}>(API_ROUTES.DASHBOARD.OVERVIEW, {
|
||||||
params: { project_id: project.id },
|
params: { project_id: project.id },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
export * from './project.service';
|
export * from './project.service';
|
||||||
|
export * from './project-summary.service';
|
||||||
export * from './package.service';
|
export * from './package.service';
|
||||||
export * from './auth.service';
|
export * from './auth.service';
|
||||||
export { chainageService } from './chainage.service';
|
export { chainageService } from './chainage.service';
|
||||||
export * from './video.service';
|
export * from './video.service';
|
||||||
export * from './detection.service';
|
export * from './detection.service';
|
||||||
export * from './session.service';
|
export * from './session.service';
|
||||||
export { projectDataService } from './project.service';
|
|
||||||
export * from './permission.service';
|
export * from './permission.service';
|
||||||
export * from './role.service';
|
export * from './role.service';
|
||||||
export * from './user.service';
|
export * from './user.service';
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import axiosClient from '../axios/axios';
|
import axiosClient from '../axios/axios';
|
||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
import {
|
import {
|
||||||
Package,
|
Package,
|
||||||
PackageCreate,
|
PackageCreate,
|
||||||
@@ -7,8 +8,6 @@ import {
|
|||||||
PaginationParams,
|
PaginationParams,
|
||||||
} from '@/types';
|
} from '@/types';
|
||||||
|
|
||||||
const PACKAGES_ENDPOINT = 'biz/api/v1/packages';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Package Service
|
* Package Service
|
||||||
*/
|
*/
|
||||||
@@ -19,7 +18,7 @@ export const packageService = {
|
|||||||
getPackages: async (params?: PaginationParams): Promise<PaginatedResponse<Package>> => {
|
getPackages: async (params?: PaginationParams): Promise<PaginatedResponse<Package>> => {
|
||||||
const skip = params?.skip ?? 0;
|
const skip = params?.skip ?? 0;
|
||||||
const limit = params?.limit ?? 100;
|
const limit = params?.limit ?? 100;
|
||||||
const response = await axiosClient.get<PaginatedResponse<Package>>(PACKAGES_ENDPOINT, {
|
const response = await axiosClient.get<PaginatedResponse<Package>>(API_ROUTES.PACKAGES.BASE, {
|
||||||
params: { skip, limit },
|
params: { skip, limit },
|
||||||
});
|
});
|
||||||
return response.data;
|
return response.data;
|
||||||
@@ -34,7 +33,7 @@ export const packageService = {
|
|||||||
): Promise<PaginatedResponse<Package>> => {
|
): Promise<PaginatedResponse<Package>> => {
|
||||||
const skip = params?.skip ?? 0;
|
const skip = params?.skip ?? 0;
|
||||||
const limit = params?.limit ?? 100;
|
const limit = params?.limit ?? 100;
|
||||||
const response = await axiosClient.get<PaginatedResponse<Package>>(PACKAGES_ENDPOINT, {
|
const response = await axiosClient.get<PaginatedResponse<Package>>(API_ROUTES.PACKAGES.BASE, {
|
||||||
params: { project_id: projectId, skip, limit },
|
params: { project_id: projectId, skip, limit },
|
||||||
});
|
});
|
||||||
return response.data;
|
return response.data;
|
||||||
@@ -44,7 +43,7 @@ export const packageService = {
|
|||||||
* Create a new package
|
* Create a new package
|
||||||
*/
|
*/
|
||||||
createPackage: async (data: PackageCreate): Promise<Package> => {
|
createPackage: async (data: PackageCreate): Promise<Package> => {
|
||||||
const response = await axiosClient.post<Package>(PACKAGES_ENDPOINT, data);
|
const response = await axiosClient.post<Package>(API_ROUTES.PACKAGES.BASE, data);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -52,7 +51,7 @@ export const packageService = {
|
|||||||
* Update an existing package
|
* Update an existing package
|
||||||
*/
|
*/
|
||||||
updatePackage: async (packageId: string, data: PackageUpdate): Promise<Package> => {
|
updatePackage: async (packageId: string, data: PackageUpdate): Promise<Package> => {
|
||||||
const response = await axiosClient.put<Package>(`${PACKAGES_ENDPOINT}/${packageId}`, data);
|
const response = await axiosClient.put<Package>(API_ROUTES.PACKAGES.DETAIL(packageId), data);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -61,7 +60,7 @@ export const packageService = {
|
|||||||
*/
|
*/
|
||||||
deletePackage: async (packageId: string): Promise<{ message: string }> => {
|
deletePackage: async (packageId: string): Promise<{ message: string }> => {
|
||||||
const response = await axiosClient.delete<{ message: string }>(
|
const response = await axiosClient.delete<{ message: string }>(
|
||||||
`${PACKAGES_ENDPOINT}/${packageId}`,
|
API_ROUTES.PACKAGES.DETAIL(packageId),
|
||||||
);
|
);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,15 +1,18 @@
|
|||||||
import axiosClient from '../axios/axios';
|
import axiosClient from '../axios/axios';
|
||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
import type { PermissionResponse, PermissionTreeNode } from '@/types';
|
import type { PermissionResponse, PermissionTreeNode } from '@/types';
|
||||||
|
|
||||||
export const permissionService = {
|
export const permissionService = {
|
||||||
getPermissions: async (): Promise<PermissionResponse> => {
|
getPermissions: async (): Promise<PermissionResponse> => {
|
||||||
const response = await axiosClient.get<PermissionResponse>('api/permissions/my-permissions');
|
const response = await axiosClient.get<PermissionResponse>(
|
||||||
|
API_ROUTES.PERMISSIONS.MY_PERMISSIONS,
|
||||||
|
);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
getOrganizationPermissionTree: async (): Promise<PermissionTreeNode[]> => {
|
getOrganizationPermissionTree: async (): Promise<PermissionTreeNode[]> => {
|
||||||
const response = await axiosClient.get<PermissionTreeNode[]>(
|
const response = await axiosClient.get<PermissionTreeNode[]>(
|
||||||
'api/permissions/organization-tree',
|
API_ROUTES.PERMISSIONS.ORGANIZATION_TREE,
|
||||||
);
|
);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import axiosClient from '../axios/axios';
|
import axiosClient from '../axios/axios';
|
||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
import type { Plan, PlanListParams, PlanListResponse, PlanRequest } from '@/types';
|
import type { Plan, PlanListParams, PlanListResponse, PlanRequest } from '@/types';
|
||||||
|
|
||||||
const PLANS_ENDPOINT = 'api/superadmin/plans';
|
|
||||||
|
|
||||||
function toPlanPayload(payload: PlanRequest) {
|
function toPlanPayload(payload: PlanRequest) {
|
||||||
return {
|
return {
|
||||||
name: payload.name,
|
name: payload.name,
|
||||||
@@ -23,7 +22,7 @@ function toPlanPayload(payload: PlanRequest) {
|
|||||||
|
|
||||||
export const planService = {
|
export const planService = {
|
||||||
getPlans: async (params?: PlanListParams): Promise<PlanListResponse> => {
|
getPlans: async (params?: PlanListParams): Promise<PlanListResponse> => {
|
||||||
const response = await axiosClient.get<PlanListResponse>(PLANS_ENDPOINT, {
|
const response = await axiosClient.get<PlanListResponse>(API_ROUTES.PLANS.BASE, {
|
||||||
params: {
|
params: {
|
||||||
skip: params?.skip ?? 0,
|
skip: params?.skip ?? 0,
|
||||||
limit: params?.limit ?? 10,
|
limit: params?.limit ?? 10,
|
||||||
@@ -42,13 +41,13 @@ export const planService = {
|
|||||||
savePlan: async (payload: PlanRequest): Promise<Plan> => {
|
savePlan: async (payload: PlanRequest): Promise<Plan> => {
|
||||||
const requestPayload = toPlanPayload(payload);
|
const requestPayload = toPlanPayload(payload);
|
||||||
const response = payload.id
|
const response = payload.id
|
||||||
? await axiosClient.put<Plan>(`${PLANS_ENDPOINT}/${payload.id}`, requestPayload)
|
? await axiosClient.put<Plan>(API_ROUTES.PLANS.DETAIL(payload.id), requestPayload)
|
||||||
: await axiosClient.post<Plan>(PLANS_ENDPOINT, requestPayload);
|
: await axiosClient.post<Plan>(API_ROUTES.PLANS.BASE, requestPayload);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
updatePlanStatus: async (id: number, isActive: boolean): Promise<Plan> => {
|
updatePlanStatus: async (id: number, isActive: boolean): Promise<Plan> => {
|
||||||
const response = await axiosClient.patch<Plan>(`${PLANS_ENDPOINT}/${id}/status`, {
|
const response = await axiosClient.patch<Plan>(API_ROUTES.PLANS.STATUS(id), {
|
||||||
is_active: isActive,
|
is_active: isActive,
|
||||||
});
|
});
|
||||||
return response.data;
|
return response.data;
|
||||||
|
|||||||
52
src/services/api/project-summary.service.ts
Normal file
52
src/services/api/project-summary.service.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
|
|
||||||
|
import axiosClient from '../axios/axios';
|
||||||
|
|
||||||
|
export const projectSummaryService = {
|
||||||
|
getProjectSummary: async <T = unknown>(projectId: string): Promise<T> => {
|
||||||
|
const response = await axiosClient.get<T>(API_ROUTES.DASHBOARD.OVERVIEW, {
|
||||||
|
params: { project_id: projectId },
|
||||||
|
});
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
getProjectSummaryByVideo: async <T = unknown>(
|
||||||
|
projectId: string,
|
||||||
|
videoId: string,
|
||||||
|
): Promise<T> => {
|
||||||
|
const response = await axiosClient.get<T>(API_ROUTES.DASHBOARD.OVERVIEW, {
|
||||||
|
params: { project_id: projectId, video_id: videoId },
|
||||||
|
});
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const projectDataService = {
|
||||||
|
extractDetections(
|
||||||
|
projectSummary: any,
|
||||||
|
selectedPackageId?: string | null,
|
||||||
|
selectedChainageId?: string | null,
|
||||||
|
): any[] {
|
||||||
|
if (!projectSummary) return [];
|
||||||
|
|
||||||
|
const detections: any[] = [];
|
||||||
|
const packagesToProcess =
|
||||||
|
selectedPackageId && selectedPackageId !== 'all'
|
||||||
|
? { [selectedPackageId]: projectSummary.packages[selectedPackageId] }
|
||||||
|
: projectSummary.packages || {};
|
||||||
|
|
||||||
|
for (const pkg of Object.values(packagesToProcess)) {
|
||||||
|
const chainagesToProcess =
|
||||||
|
selectedChainageId && selectedChainageId !== 'all'
|
||||||
|
? { [selectedChainageId]: (pkg as any).chainages[selectedChainageId] }
|
||||||
|
: (pkg as any).chainages || {};
|
||||||
|
|
||||||
|
for (const chainage of Object.values(chainagesToProcess)) {
|
||||||
|
if (!chainage) continue;
|
||||||
|
detections.push(...((chainage as any).detections || []));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return detections;
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
import axiosClient from '../axios/axios';
|
import axiosClient from '../axios/axios';
|
||||||
import {
|
import {
|
||||||
Project,
|
Project,
|
||||||
@@ -7,9 +8,6 @@ import {
|
|||||||
PaginationParams,
|
PaginationParams,
|
||||||
} from '@/types';
|
} from '@/types';
|
||||||
|
|
||||||
const PROJECTS_ENDPOINT = 'biz/api/v1/projects';
|
|
||||||
const PROJECT_SUMMARY_ENDPOINT = 'biz/api/v1/dashboard/overview';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Project Service
|
* Project Service
|
||||||
*/
|
*/
|
||||||
@@ -20,7 +18,7 @@ export const projectService = {
|
|||||||
getProjects: async (params?: PaginationParams): Promise<PaginatedResponse<Project>> => {
|
getProjects: async (params?: PaginationParams): Promise<PaginatedResponse<Project>> => {
|
||||||
const skip = params?.skip ?? 0;
|
const skip = params?.skip ?? 0;
|
||||||
const limit = params?.limit ?? 100;
|
const limit = params?.limit ?? 100;
|
||||||
const response = await axiosClient.get<PaginatedResponse<Project>>(PROJECTS_ENDPOINT, {
|
const response = await axiosClient.get<PaginatedResponse<Project>>(API_ROUTES.PROJECTS.BASE, {
|
||||||
params: { skip, limit },
|
params: { skip, limit },
|
||||||
});
|
});
|
||||||
return response.data;
|
return response.data;
|
||||||
@@ -30,7 +28,7 @@ export const projectService = {
|
|||||||
* Create a new project
|
* Create a new project
|
||||||
*/
|
*/
|
||||||
createProject: async (data: ProjectCreate): Promise<Project> => {
|
createProject: async (data: ProjectCreate): Promise<Project> => {
|
||||||
const response = await axiosClient.post<Project>(PROJECTS_ENDPOINT, data);
|
const response = await axiosClient.post<Project>(API_ROUTES.PROJECTS.BASE, data);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -38,7 +36,7 @@ export const projectService = {
|
|||||||
* Update an existing project
|
* Update an existing project
|
||||||
*/
|
*/
|
||||||
updateProject: async (projectId: string, data: ProjectUpdate): Promise<Project> => {
|
updateProject: async (projectId: string, data: ProjectUpdate): Promise<Project> => {
|
||||||
const response = await axiosClient.put<Project>(`${PROJECTS_ENDPOINT}/${projectId}`, data);
|
const response = await axiosClient.put<Project>(API_ROUTES.PROJECTS.DETAIL(projectId), data);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -47,66 +45,8 @@ export const projectService = {
|
|||||||
*/
|
*/
|
||||||
deleteProject: async (projectId: string): Promise<{ message: string }> => {
|
deleteProject: async (projectId: string): Promise<{ message: string }> => {
|
||||||
const response = await axiosClient.delete<{ message: string }>(
|
const response = await axiosClient.delete<{ message: string }>(
|
||||||
`${PROJECTS_ENDPOINT}/${projectId}`,
|
API_ROUTES.PROJECTS.DETAIL(projectId),
|
||||||
);
|
);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetch project summary (detections across packages and chainages)
|
|
||||||
*/
|
|
||||||
getProjectSummary: async (projectId: string): Promise<any> => {
|
|
||||||
const response = await axiosClient.get(PROJECT_SUMMARY_ENDPOINT, {
|
|
||||||
params: { project_id: projectId },
|
|
||||||
});
|
|
||||||
return response.data;
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetch project summary filtered by video ID
|
|
||||||
*/
|
|
||||||
getProjectSummaryByVideo: async (projectId: string, videoId: string): Promise<any> => {
|
|
||||||
const response = await axiosClient.get(PROJECT_SUMMARY_ENDPOINT, {
|
|
||||||
params: { project_id: projectId, video_id: videoId },
|
|
||||||
});
|
|
||||||
return response.data;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Service to handle data extraction from project summaries
|
|
||||||
* Moved from legacy project-service.ts
|
|
||||||
*/
|
|
||||||
export const projectDataService = {
|
|
||||||
/**
|
|
||||||
* Extracts all detections from a project summary, optionally filtered by package and chainage
|
|
||||||
*/
|
|
||||||
extractDetections(
|
|
||||||
projectSummary: any,
|
|
||||||
selectedPackageId?: string | null,
|
|
||||||
selectedChainageId?: string | null,
|
|
||||||
): any[] {
|
|
||||||
if (!projectSummary) return [];
|
|
||||||
|
|
||||||
const detections: any[] = [];
|
|
||||||
const packagesToProcess =
|
|
||||||
selectedPackageId && selectedPackageId !== 'all'
|
|
||||||
? { [selectedPackageId]: projectSummary.packages[selectedPackageId] }
|
|
||||||
: projectSummary.packages || {};
|
|
||||||
|
|
||||||
for (const [pkgName, pkg] of Object.entries(packagesToProcess)) {
|
|
||||||
const chainagesToProcess =
|
|
||||||
selectedChainageId && selectedChainageId !== 'all'
|
|
||||||
? { [selectedChainageId]: (pkg as any).chainages[selectedChainageId] }
|
|
||||||
: (pkg as any).chainages || {};
|
|
||||||
|
|
||||||
for (const [chnName, chn] of Object.entries(chainagesToProcess)) {
|
|
||||||
if (!chn) continue;
|
|
||||||
const chainageDetections = (chn as any).detections || [];
|
|
||||||
detections.push(...chainageDetections);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return detections;
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import axiosClient from '../axios/axios';
|
import axiosClient from '../axios/axios';
|
||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
import type { Role, RoleListParams, RoleListResponse, RoleRequest } from '@/types';
|
import type { Role, RoleListParams, RoleListResponse, RoleRequest } from '@/types';
|
||||||
|
|
||||||
const ROLES_ENDPOINT = 'api/roles';
|
|
||||||
|
|
||||||
export const roleService = {
|
export const roleService = {
|
||||||
getRoles: async (params?: RoleListParams): Promise<RoleListResponse> => {
|
getRoles: async (params?: RoleListParams): Promise<RoleListResponse> => {
|
||||||
const response = await axiosClient.get<RoleListResponse>(ROLES_ENDPOINT, {
|
const response = await axiosClient.get<RoleListResponse>(API_ROUTES.ROLES.BASE, {
|
||||||
params: {
|
params: {
|
||||||
skip: params?.skip ?? 0,
|
skip: params?.skip ?? 0,
|
||||||
limit: params?.limit ?? 10,
|
limit: params?.limit ?? 10,
|
||||||
@@ -22,19 +21,19 @@ export const roleService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
getRoleById: async (id: number): Promise<Role> => {
|
getRoleById: async (id: number): Promise<Role> => {
|
||||||
const response = await axiosClient.get<Role>(`${ROLES_ENDPOINT}/${id}`);
|
const response = await axiosClient.get<Role>(API_ROUTES.ROLES.DETAIL(id));
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
saveRole: async (payload: RoleRequest): Promise<Role> => {
|
saveRole: async (payload: RoleRequest): Promise<Role> => {
|
||||||
const response = payload.id
|
const response = payload.id
|
||||||
? await axiosClient.put<Role>(ROLES_ENDPOINT, payload)
|
? await axiosClient.put<Role>(API_ROUTES.ROLES.BASE, payload)
|
||||||
: await axiosClient.post<Role>(ROLES_ENDPOINT, payload);
|
: await axiosClient.post<Role>(API_ROUTES.ROLES.BASE, payload);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
updateRoleStatus: async (id: number, isActive: boolean): Promise<Role> => {
|
updateRoleStatus: async (id: number, isActive: boolean): Promise<Role> => {
|
||||||
const response = await axiosClient.patch<Role>(`${ROLES_ENDPOINT}/${id}/status`, {
|
const response = await axiosClient.patch<Role>(API_ROUTES.ROLES.STATUS(id), {
|
||||||
is_active: isActive,
|
is_active: isActive,
|
||||||
});
|
});
|
||||||
return response.data;
|
return response.data;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import axiosClient from '../axios/axios';
|
import axiosClient from '../axios/axios';
|
||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
import type {
|
import type {
|
||||||
Tenant,
|
Tenant,
|
||||||
TenantCreateRequest,
|
TenantCreateRequest,
|
||||||
@@ -7,8 +8,6 @@ import type {
|
|||||||
TenantUpdateRequest,
|
TenantUpdateRequest,
|
||||||
} from '@/types';
|
} from '@/types';
|
||||||
|
|
||||||
const TENANTS_ENDPOINT = 'api/superadmin/tenants';
|
|
||||||
|
|
||||||
function toCreatePayload(payload: TenantCreateRequest) {
|
function toCreatePayload(payload: TenantCreateRequest) {
|
||||||
return {
|
return {
|
||||||
name: payload.name,
|
name: payload.name,
|
||||||
@@ -39,7 +38,7 @@ function toUpdatePayload(payload: TenantUpdateRequest) {
|
|||||||
|
|
||||||
export const tenantService = {
|
export const tenantService = {
|
||||||
getTenants: async (params?: TenantListParams): Promise<TenantListResponse> => {
|
getTenants: async (params?: TenantListParams): Promise<TenantListResponse> => {
|
||||||
const response = await axiosClient.get<TenantListResponse>(TENANTS_ENDPOINT, {
|
const response = await axiosClient.get<TenantListResponse>(API_ROUTES.TENANTS.BASE, {
|
||||||
params: {
|
params: {
|
||||||
skip: params?.skip ?? 0,
|
skip: params?.skip ?? 0,
|
||||||
limit: params?.limit ?? 10,
|
limit: params?.limit ?? 10,
|
||||||
@@ -53,19 +52,22 @@ export const tenantService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
createTenant: async (payload: TenantCreateRequest): Promise<Tenant> => {
|
createTenant: async (payload: TenantCreateRequest): Promise<Tenant> => {
|
||||||
const response = await axiosClient.post<Tenant>(TENANTS_ENDPOINT, toCreatePayload(payload));
|
const response = await axiosClient.post<Tenant>(
|
||||||
|
API_ROUTES.TENANTS.BASE,
|
||||||
|
toCreatePayload(payload),
|
||||||
|
);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
updateTenant: async (payload: TenantUpdateRequest): Promise<Tenant> => {
|
updateTenant: async (payload: TenantUpdateRequest): Promise<Tenant> => {
|
||||||
const response = await axiosClient.put<Tenant>(
|
const response = await axiosClient.put<Tenant>(
|
||||||
`${TENANTS_ENDPOINT}/${payload.id}`,
|
API_ROUTES.TENANTS.DETAIL(payload.id),
|
||||||
toUpdatePayload(payload),
|
toUpdatePayload(payload),
|
||||||
);
|
);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
deleteTenant: async (id: number): Promise<void> => {
|
deleteTenant: async (id: number): Promise<void> => {
|
||||||
await axiosClient.delete(`${TENANTS_ENDPOINT}/${id}`);
|
await axiosClient.delete(API_ROUTES.TENANTS.DETAIL(id));
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import axiosClient from '../axios/axios';
|
import axiosClient from '../axios/axios';
|
||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
import type { AdministrationUser, UserListParams, UserListResponse, UserRequest } from '@/types';
|
import type { AdministrationUser, UserListParams, UserListResponse, UserRequest } from '@/types';
|
||||||
|
|
||||||
const USERS_ENDPOINT = 'api/users';
|
|
||||||
|
|
||||||
export const userService = {
|
export const userService = {
|
||||||
getUsers: async (params?: UserListParams): Promise<UserListResponse> => {
|
getUsers: async (params?: UserListParams): Promise<UserListResponse> => {
|
||||||
const response = await axiosClient.get<UserListResponse>(USERS_ENDPOINT, {
|
const response = await axiosClient.get<UserListResponse>(API_ROUTES.USERS.BASE, {
|
||||||
params: {
|
params: {
|
||||||
skip: params?.skip ?? 0,
|
skip: params?.skip ?? 0,
|
||||||
limit: params?.limit ?? 10,
|
limit: params?.limit ?? 10,
|
||||||
@@ -24,8 +23,8 @@ export const userService = {
|
|||||||
|
|
||||||
saveUser: async (payload: UserRequest): Promise<AdministrationUser> => {
|
saveUser: async (payload: UserRequest): Promise<AdministrationUser> => {
|
||||||
const response = payload.id
|
const response = payload.id
|
||||||
? await axiosClient.put<AdministrationUser>(USERS_ENDPOINT, payload)
|
? await axiosClient.put<AdministrationUser>(API_ROUTES.USERS.BASE, payload)
|
||||||
: await axiosClient.post<AdministrationUser>(USERS_ENDPOINT, payload);
|
: await axiosClient.post<AdministrationUser>(API_ROUTES.USERS.BASE, payload);
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -33,7 +32,7 @@ export const userService = {
|
|||||||
id: number,
|
id: number,
|
||||||
status: 'active' | 'inactive',
|
status: 'active' | 'inactive',
|
||||||
): Promise<AdministrationUser> => {
|
): Promise<AdministrationUser> => {
|
||||||
const response = await axiosClient.patch<AdministrationUser>(`${USERS_ENDPOINT}/${id}/status`, {
|
const response = await axiosClient.patch<AdministrationUser>(API_ROUTES.USERS.STATUS(id), {
|
||||||
status,
|
status,
|
||||||
});
|
});
|
||||||
return response.data;
|
return response.data;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import axiosClient from '../axios/axios';
|
import axiosClient from '../axios/axios';
|
||||||
|
import { API_ROUTES } from '@/constants/apiRoutes';
|
||||||
import { Video, PaginationParams } from '@/types';
|
import { Video, PaginationParams } from '@/types';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -27,7 +28,7 @@ export const videoService = {
|
|||||||
total_detections?: number;
|
total_detections?: number;
|
||||||
};
|
};
|
||||||
}>;
|
}>;
|
||||||
}>(`/videos`, {
|
}>(API_ROUTES.VIDEOS.LIST, {
|
||||||
params: { skip, limit },
|
params: { skip, limit },
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -53,7 +54,7 @@ export const videoService = {
|
|||||||
* Upload a video for processing
|
* Upload a video for processing
|
||||||
*/
|
*/
|
||||||
uploadVideo: async (formData: FormData): Promise<any> => {
|
uploadVideo: async (formData: FormData): Promise<any> => {
|
||||||
const response = await axiosClient.post('/upload', formData, {
|
const response = await axiosClient.post(API_ROUTES.VIDEOS.UPLOAD, formData, {
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'multipart/form-data',
|
'Content-Type': 'multipart/form-data',
|
||||||
},
|
},
|
||||||
@@ -65,7 +66,7 @@ export const videoService = {
|
|||||||
* Get processing status of a video
|
* Get processing status of a video
|
||||||
*/
|
*/
|
||||||
getVideoStatus: async (videoId: string): Promise<any> => {
|
getVideoStatus: async (videoId: string): Promise<any> => {
|
||||||
const response = await axiosClient.get(`/status/${videoId}`);
|
const response = await axiosClient.get(API_ROUTES.VIDEOS.STATUS(videoId));
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -73,7 +74,7 @@ export const videoService = {
|
|||||||
* Get analysis results for a video
|
* Get analysis results for a video
|
||||||
*/
|
*/
|
||||||
getVideoResults: async (videoId: string): Promise<any> => {
|
getVideoResults: async (videoId: string): Promise<any> => {
|
||||||
const response = await axiosClient.get(`/results/${videoId}`);
|
const response = await axiosClient.get(API_ROUTES.VIDEOS.RESULTS(videoId));
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user