2 Commits

11 changed files with 382 additions and 46 deletions

View File

@@ -0,0 +1,161 @@
'use client';
import { useState, type FormEvent } from 'react';
import { Loader2, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import type { DetectionDiscardReason, DiscardDetectionPayload } from '@/types';
const DISCARD_REASON_OPTIONS: Array<{
value: DetectionDiscardReason;
label: string;
}> = [
{ value: 'not_a_defect', label: 'Not a defect' },
{ value: 'wrong_class', label: 'Wrong classification' },
{ value: 'duplicate', label: 'Duplicate detection' },
{ value: 'poor_image_quality', label: 'Poor image quality' },
{ value: 'incorrect_location', label: 'Incorrect location' },
{ value: 'already_repaired', label: 'Already repaired' },
{ value: 'other', label: 'Other' },
];
interface DetectionDiscardDialogProps {
open: boolean;
detectionLabel: string;
isPending: boolean;
onOpenChange: (open: boolean) => void;
onSubmit: (payload: DiscardDetectionPayload) => Promise<void>;
}
export function DetectionDiscardDialog({
open,
detectionLabel,
isPending,
onOpenChange,
onSubmit,
}: DetectionDiscardDialogProps) {
const [reason, setReason] = useState<DetectionDiscardReason | ''>('');
const [comment, setComment] = useState('');
const resetForm = () => {
setReason('');
setComment('');
};
const handleOpenChange = (nextOpen: boolean) => {
if (isPending) return;
if (!nextOpen) resetForm();
onOpenChange(nextOpen);
};
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!reason || isPending) return;
try {
await onSubmit({
reason,
comment: comment.trim() || undefined,
});
resetForm();
} catch {
// The mutation displays the request error and keeps the dialog open.
}
};
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent showCloseButton={!isPending}>
<form className="flex min-h-0 flex-1 flex-col" onSubmit={handleSubmit}>
<DialogHeader>
<DialogTitle>Discard detection</DialogTitle>
<DialogDescription>
Remove {detectionLabel} from this ticket and record why the AI
result is incorrect.
</DialogDescription>
</DialogHeader>
<DialogBody className="space-y-5">
<div className="space-y-2">
<Label htmlFor="discard-reason">Reason</Label>
<Select
value={reason}
onValueChange={(value) =>
setReason(value as DetectionDiscardReason)
}
disabled={isPending}
>
<SelectTrigger id="discard-reason" className="w-full">
<SelectValue placeholder="Select a reason" />
</SelectTrigger>
<SelectContent>
{DISCARD_REASON_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<Label htmlFor="discard-comment">Comment</Label>
<span className="text-xs text-muted-foreground">
Optional | {comment.length}/500
</span>
</div>
<Textarea
id="discard-comment"
value={comment}
onChange={(event) => setComment(event.target.value)}
placeholder="Add details that can help improve future detections"
rows={4}
maxLength={500}
disabled={isPending}
/>
</div>
</DialogBody>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={isPending}
>
Cancel
</Button>
<Button
type="submit"
variant="destructive"
disabled={!reason || isPending}
>
{isPending ? <Loader2 className="animate-spin" /> : <Trash2 />}
{isPending ? 'Discarding' : 'Discard detection'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,7 +1,7 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
import { AlertTriangle, ChevronLeft, ChevronRight } from 'lucide-react';
import { AlertTriangle, ChevronLeft, ChevronRight, Trash2 } from 'lucide-react';
import DetectionLocationMap from '@/components/map/detectionLocationMap';
import { Badge } from '@/components/ui/badge';
@@ -11,9 +11,14 @@ import AnnotatedDetectionImage from '@/components/video/annotatedDetectionImage'
import { getDefectVisual } from '@/constants/defectVisualConfig';
import { cn } from '@/lib/utils';
import { useTicketClassDetectionsQuery } from '../../hooks/useTicketQueries';
import {
useDiscardDetectionMutation,
useTicketClassDetectionsQuery,
} from '../../hooks/useTicketQueries';
import { DetectionDiscardDialog } from './DetectionDiscardDialog';
interface TicketClassDetectionPreviewProps {
ticketId: string;
videoId?: string | null;
defectClassName: string;
displayName: string;
@@ -89,12 +94,14 @@ function TicketClassDetectionPreviewSkeleton() {
}
export function TicketClassDetectionPreview({
ticketId,
videoId,
defectClassName,
displayName,
totalCount,
}: TicketClassDetectionPreviewProps) {
const [currentIndex, setCurrentIndex] = useState(0);
const [isDiscardDialogOpen, setIsDiscardDialogOpen] = useState(false);
const visual = getDefectVisual(defectClassName);
const IssueIcon = visual.icon;
@@ -116,6 +123,11 @@ export function TicketClassDetectionPreview({
videoId ?? undefined,
queryParams,
);
const discardMutation = useDiscardDetectionMutation(
ticketId,
videoId ?? undefined,
defectClassName,
);
const detectionResult = detectionsQuery.data;
const activeDetection = detectionResult?.items[0];
const detectionCount = detectionResult?.total ?? totalCount ?? 0;
@@ -274,6 +286,31 @@ export function TicketClassDetectionPreview({
},
]}
/>
<div className="flex justify-end">
<Button
type="button"
variant="destructive"
onClick={() => setIsDiscardDialogOpen(true)}
>
<Trash2 />
Discard detection
</Button>
</div>
<DetectionDiscardDialog
open={isDiscardDialogOpen}
detectionLabel={activeDetection.detection.display_name}
isPending={discardMutation.isPending}
onOpenChange={setIsDiscardDialogOpen}
onSubmit={async (payload) => {
await discardMutation.mutateAsync({
detectionId: activeDetection.detection.id,
payload,
});
setIsDiscardDialogOpen(false);
}}
/>
</>
)}
</div>

View File

@@ -150,6 +150,7 @@ export function TicketDefectClassTabs({
<div className="min-w-0 px-5">
<TicketClassDetectionPreview
ticketId={ticketId}
videoId={previewVideoId}
defectClassName={selectedClass}
displayName={previewDisplayName}

View File

@@ -4,10 +4,11 @@ import { useMemo } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { ticketService, videoService } from '@/services/api';
import { detectionService, ticketService, videoService } from '@/services/api';
import type {
AssignTicketPayload,
CloseTicketPayload,
DiscardDetectionPayload,
RequestTicketExtensionPayload,
ReviewTicketExtensionPayload,
ReviewRepairPayload,
@@ -117,6 +118,46 @@ export function useTicketClassDetectionsQuery(
});
}
export function useDiscardDetectionMutation(
ticketId: string,
videoId: string | undefined,
defectClass: string,
) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
detectionId,
payload,
}: {
detectionId: number;
payload: DiscardDetectionPayload;
}) => detectionService.discardDetection(detectionId, payload),
onSuccess: async () => {
toast.success('Detection discarded');
await Promise.all([
videoId
? queryClient.invalidateQueries({
queryKey: ticketKeys.classDetectionLists(videoId),
})
: Promise.resolve(),
queryClient.invalidateQueries({
queryKey: ticketKeys.overview(ticketId),
}),
queryClient.invalidateQueries({
queryKey: ticketKeys.classDetail(ticketId, defectClass),
}),
queryClient.invalidateQueries({
queryKey: ticketKeys.defectClasses(ticketId),
}),
queryClient.invalidateQueries({ queryKey: ticketKeys.lists() }),
]);
},
onError: () => toast.error('Failed to discard detection'),
});
}
export function useTicketExtensionRequestQuery(
ticketId: string | undefined,
assignmentId: number | undefined,

View File

@@ -9,8 +9,10 @@ export const ticketKeys = {
[...ticketKeys.details(), ticketId, 'overview'] as const,
classDetail: (ticketId: string, defectClass: string) =>
[...ticketKeys.details(), ticketId, 'class', defectClass] as const,
classDetectionLists: (videoId: string) =>
[...ticketKeys.details(), 'video', videoId, 'detections'] as const,
classDetections: (videoId: string, params: VideoDetectionsParams) =>
[...ticketKeys.details(), 'video', videoId, 'detections', params] as const,
[...ticketKeys.classDetectionLists(videoId), params] as const,
defectClasses: (ticketId: string) =>
[...ticketKeys.details(), ticketId, 'defect-classes'] as const,
extensionRequest: (ticketId: string, assignmentId: number | undefined) =>

View File

@@ -58,6 +58,9 @@ export const API_ROUTES = {
`/biz/api/v1/results/${id}/annotation-frames`,
DETECTIONS: (id: string) => `/biz/api/v1/results/${id}/detections`,
},
DETECTIONS: {
DISCARD: (id: number) => `/biz/api/v1/detections/${id}/discard`,
},
TICKETS: {
BASE: '/biz/api/v1/tickets',
DETAIL: (id: string) => `/biz/api/v1/tickets/${id}`,

View File

@@ -1,19 +1,20 @@
'use client';
import { Button } from '@/components/ui/button';
import { initializeAuthenticatedApp } from '@/services/initializer.service';
import { useAppStore } from '@/store/app.store';
import { useAuthStore } from '@/store/auth.store';
import type { ReactNode } from 'react';
import { useEffect } from 'react';
import { useEffect, useState } from 'react';
export default function AppInitializer({ children }: { children: ReactNode }) {
const accessToken = useAuthStore((state) => state.accessToken);
const logout = useAuthStore((state) => state.logout);
const user = useAppStore((state) => state.user);
const loadStatus = useAppStore((state) => state.loadStatus);
const setLoading = useAppStore((state) => state.setLoading);
const setLoaded = useAppStore((state) => state.setLoaded);
const setLoadError = useAppStore((state) => state.setLoadError);
const clearApp = useAppStore((state) => state.clear);
const [retryAttempt, setRetryAttempt] = useState(0);
useEffect(() => {
let isActive = true;
@@ -30,8 +31,6 @@ export default function AppInitializer({ children }: { children: ReactNode }) {
await initializeAuthenticatedApp();
} catch {
if (isActive) {
logout();
clearApp();
setLoadError();
}
}
@@ -42,15 +41,32 @@ export default function AppInitializer({ children }: { children: ReactNode }) {
return () => {
isActive = false;
};
}, [
accessToken,
clearApp,
logout,
setLoaded,
setLoadError,
setLoading,
user,
]);
}, [accessToken, retryAttempt, setLoaded, setLoadError, setLoading, user]);
if (accessToken && !user && loadStatus === 'error') {
return (
<main className="flex min-h-screen items-center justify-center bg-background px-6">
<div
className="flex max-w-md flex-col items-center gap-4 text-center"
role="alert"
>
<div className="space-y-2">
<h1 className="text-xl font-semibold">Unable to load workspace</h1>
<p className="text-sm text-muted-foreground">
We could not load your account details. Your session has been
kept, so you can safely try again.
</p>
</div>
<Button
type="button"
onClick={() => setRetryAttempt((value) => value + 1)}
>
Try again
</Button>
</div>
</main>
);
}
return children;
}

View File

@@ -0,0 +1,21 @@
import { API_ROUTES } from '@/constants/apiRoutes';
import type {
DiscardDetectionPayload,
DiscardDetectionResponse,
} from '@/types';
import axiosClient from '../axios/axios';
export const detectionService = {
discardDetection: async (
detectionId: number,
payload: DiscardDetectionPayload,
): Promise<DiscardDetectionResponse> => {
const response = await axiosClient.post<DiscardDetectionResponse>(
API_ROUTES.DETECTIONS.DISCARD(detectionId),
payload,
);
return response.data;
},
};

View File

@@ -3,6 +3,7 @@ export * from './package.service';
export * from './auth.service';
export { chainageService } from './chainage.service';
export * from './video.service';
export * from './detection.service';
export * from './permission.service';
export * from './role.service';
export * from './user.service';

View File

@@ -12,6 +12,62 @@ const axiosClient = axios.create({
},
});
export const axiosAuth = axios.create({
baseURL: BASE_URL,
headers: {
'Content-Type': 'application/json',
},
});
let refreshPromise: Promise<string> | null = null;
const isInvalidSessionResponse = (error: unknown) => {
if (!axios.isAxiosError(error)) return false;
return error.response?.status === 401 || error.response?.status === 403;
};
const refreshAccessToken = () => {
if (!refreshPromise) {
refreshPromise = axiosAuth
.post(
'api/auth/refresh',
{},
{
withCredentials: true,
},
)
.then((response) => {
const accessToken = response.data?.access_token;
if (!accessToken) {
throw new Error('Refresh failed: no access token');
}
useAuthStore.getState().setAccessToken(accessToken);
return accessToken;
})
.catch((error: unknown) => {
if (isInvalidSessionResponse(error)) {
useAuthStore.getState().logout();
useAppStore.getState().clear();
if (typeof window !== 'undefined') {
window.location.href = '/login';
}
}
throw error;
})
.finally(() => {
refreshPromise = null;
});
}
return refreshPromise;
};
axiosClient.interceptors.request.use(
(config) => {
const token = useAuthStore.getState().accessToken;
@@ -49,31 +105,11 @@ axiosClient.interceptors.response.use(
originalRequest._retry = true;
try {
const response = await axiosAuth.post(
'api/auth/refresh',
{},
{
withCredentials: true,
},
);
const accessToken = response.data?.access_token;
if (!accessToken) {
throw new Error('Refresh failed: no access token');
}
useAuthStore.getState().setAccessToken(accessToken);
const accessToken = await refreshAccessToken();
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
return axiosClient(originalRequest);
} catch (refreshError) {
useAuthStore.getState().logout();
useAppStore.getState().clear();
if (typeof window !== 'undefined') {
window.location.href = '/login';
}
return Promise.reject(refreshError);
}
}
@@ -82,11 +118,4 @@ axiosClient.interceptors.response.use(
},
);
export const axiosAuth = axios.create({
baseURL: BASE_URL,
headers: {
'Content-Type': 'application/json',
},
});
export default axiosClient;

View File

@@ -75,6 +75,30 @@ export type VideoDetectionsResponse = {
items: DetectionResultItem[];
};
export type DetectionDiscardReason =
| 'not_a_defect'
| 'wrong_class'
| 'duplicate'
| 'poor_image_quality'
| 'incorrect_location'
| 'already_repaired'
| 'other';
export type DiscardDetectionPayload = {
reason: DetectionDiscardReason;
comment?: string;
};
export type DiscardDetectionResponse = {
detection_id: number;
video_id: string;
status: 'discarded';
feedback_id: number;
action: 'discarded';
ticket_detection_count: number;
created_at: string;
};
export type VideoAnnotationFramesParams = {
start_time_ms: number;
end_time_ms: number;