690409:1012 Done Task-FE-AI-03
This commit is contained in:
@@ -1,7 +1,9 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect, useState, useCallback } from 'react';
|
import { useEffect, useState, useCallback } from 'react';
|
||||||
|
import { aiService } from '@/lib/services/ai.service';
|
||||||
import { migrationService } from '@/lib/services/migration.service';
|
import { migrationService } from '@/lib/services/migration.service';
|
||||||
|
import { AiMigrationLog, AiMigrationLogStatus } from '@/types/ai';
|
||||||
import { MigrationReviewQueueItem, MigrationReviewStatus } from '@/types/migration';
|
import { MigrationReviewQueueItem, MigrationReviewStatus } from '@/types/migration';
|
||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||||
import { Checkbox } from '@/components/ui/checkbox';
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
@@ -9,13 +11,348 @@ import { Badge } from '@/components/ui/badge';
|
|||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||||
|
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
|
||||||
import { format } from 'date-fns';
|
import { format } from 'date-fns';
|
||||||
import { EyeIcon, FileXIcon, CheckSquareIcon } from 'lucide-react';
|
import { EyeIcon, FileXIcon, CheckCircleIcon, XCircleIcon, RefreshCwIcon } from 'lucide-react';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { getApiErrorMessage } from '@/types/api-error';
|
import { getApiErrorMessage } from '@/types/api-error';
|
||||||
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
|
|
||||||
export default function MigrationReviewQueuePage() {
|
// --- AI Migration Tab ---
|
||||||
|
|
||||||
|
function AiMigrationTab() {
|
||||||
|
const [items, setItems] = useState<AiMigrationLog[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [statusFilter, setStatusFilter] = useState<string>('PENDING_REVIEW');
|
||||||
|
// ADR-019: ใช้ publicId (string) สำหรับ selection
|
||||||
|
const [selectedPublicIds, setSelectedPublicIds] = useState<string[]>([]);
|
||||||
|
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||||
|
// Sheet สำหรับ inline review
|
||||||
|
const [reviewItem, setReviewItem] = useState<AiMigrationLog | null>(null);
|
||||||
|
const [adminFeedback, setAdminFeedback] = useState('');
|
||||||
|
|
||||||
|
const fetchData = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
setErrorMessage(null);
|
||||||
|
const res = await aiService.getMigrationList({
|
||||||
|
status: statusFilter === 'ALL' ? undefined : (statusFilter as AiMigrationLogStatus),
|
||||||
|
limit: 50,
|
||||||
|
});
|
||||||
|
setItems(Array.isArray(res.items) ? res.items : []);
|
||||||
|
setSelectedPublicIds([]);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
setItems([]);
|
||||||
|
setErrorMessage(getApiErrorMessage(error, 'ไม่สามารถโหลดข้อมูล AI Migration Logs ได้'));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [statusFilter]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchData();
|
||||||
|
}, [fetchData]);
|
||||||
|
|
||||||
|
// ADR-019: toggle โดยใช้ publicId (string) ไม่ใช่ numeric id
|
||||||
|
const handleToggleSelectAll = () => {
|
||||||
|
if (selectedPublicIds.length === items.length) {
|
||||||
|
setSelectedPublicIds([]);
|
||||||
|
} else {
|
||||||
|
setSelectedPublicIds(items.map((i) => i.publicId));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleToggleSelect = (publicId: string) => {
|
||||||
|
setSelectedPublicIds((prev) =>
|
||||||
|
prev.includes(publicId) ? prev.filter((id) => id !== publicId) : [...prev, publicId]
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Bulk verify รายการที่เลือก (ADR-019: ใช้ publicId)
|
||||||
|
const handleBulkVerify = async () => {
|
||||||
|
if (selectedPublicIds.length === 0) return;
|
||||||
|
try {
|
||||||
|
setSubmitting(true);
|
||||||
|
await Promise.all(
|
||||||
|
selectedPublicIds.map((publicId) =>
|
||||||
|
aiService.updateMigration(
|
||||||
|
publicId, // ADR-019: UUID เท่านั้น
|
||||||
|
{ status: AiMigrationLogStatus.VERIFIED },
|
||||||
|
`bulk-verify-${publicId}-${uuidv4()}`
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
toast.success(`ยืนยัน ${selectedPublicIds.length} รายการเรียบร้อย`);
|
||||||
|
await fetchData();
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error('การยืนยันแบบกลุ่มล้มเหลว');
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// อัปเดตสถานะ item เดี่ยว (ADR-019: ใช้ publicId)
|
||||||
|
const handleUpdateStatus = async (status: AiMigrationLogStatus) => {
|
||||||
|
if (!reviewItem) return;
|
||||||
|
try {
|
||||||
|
setSubmitting(true);
|
||||||
|
await aiService.updateMigration(
|
||||||
|
reviewItem.publicId, // ADR-019: UUID เท่านั้น
|
||||||
|
{ status, adminFeedback: adminFeedback || undefined },
|
||||||
|
`review-${reviewItem.publicId}-${uuidv4()}`
|
||||||
|
);
|
||||||
|
const label = status === AiMigrationLogStatus.VERIFIED ? 'ยืนยัน' : 'ปฏิเสธ';
|
||||||
|
toast.success(`${label}เอกสารเรียบร้อย`);
|
||||||
|
setReviewItem(null);
|
||||||
|
setAdminFeedback('');
|
||||||
|
await fetchData();
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error('ไม่สามารถอัปเดตสถานะได้');
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// สีของ confidence badge
|
||||||
|
const getConfidenceVariant = (score?: number): 'default' | 'secondary' | 'destructive' | 'outline' => {
|
||||||
|
if (!score) return 'destructive';
|
||||||
|
if (score >= 0.95) return 'default';
|
||||||
|
if (score >= 0.75) return 'secondary';
|
||||||
|
return 'destructive';
|
||||||
|
};
|
||||||
|
|
||||||
|
// สีของ status badge
|
||||||
|
const getStatusVariant = (status: AiMigrationLogStatus): 'default' | 'secondary' | 'destructive' | 'outline' => {
|
||||||
|
switch (status) {
|
||||||
|
case AiMigrationLogStatus.VERIFIED:
|
||||||
|
case AiMigrationLogStatus.IMPORTED:
|
||||||
|
return 'default';
|
||||||
|
case AiMigrationLogStatus.FAILED:
|
||||||
|
return 'destructive';
|
||||||
|
default:
|
||||||
|
return 'outline';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const statusLabels: Record<string, string> = {
|
||||||
|
PENDING_REVIEW: 'รอตรวจสอบ',
|
||||||
|
VERIFIED: 'ผ่านการตรวจสอบ',
|
||||||
|
IMPORTED: 'นำเข้าแล้ว',
|
||||||
|
FAILED: 'ล้มเหลว',
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex flex-wrap justify-between items-center gap-4">
|
||||||
|
<CardTitle>AI Migration Logs</CardTitle>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
{selectedPublicIds.length > 0 && (
|
||||||
|
<Button variant="default" onClick={handleBulkVerify} disabled={submitting}>
|
||||||
|
<CheckCircleIcon className="mr-2 h-4 w-4" />
|
||||||
|
{submitting ? 'กำลังดำเนินการ...' : `ยืนยัน ${selectedPublicIds.length} รายการ`}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button variant="outline" size="sm" onClick={fetchData} disabled={loading}>
|
||||||
|
<RefreshCwIcon className="h-4 w-4 mr-2" />
|
||||||
|
รีเฟรช
|
||||||
|
</Button>
|
||||||
|
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||||
|
<SelectTrigger className="w-[180px]">
|
||||||
|
<SelectValue placeholder="สถานะ" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="ALL">ทุกสถานะ</SelectItem>
|
||||||
|
<SelectItem value="PENDING_REVIEW">รอตรวจสอบ</SelectItem>
|
||||||
|
<SelectItem value="VERIFIED">ผ่านการตรวจสอบ</SelectItem>
|
||||||
|
<SelectItem value="FAILED">ล้มเหลว</SelectItem>
|
||||||
|
<SelectItem value="IMPORTED">นำเข้าแล้ว</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{errorMessage && (
|
||||||
|
<div className="mb-4 rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive">
|
||||||
|
{errorMessage}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{loading ? (
|
||||||
|
<div className="py-10 text-center text-muted-foreground">กำลังโหลด...</div>
|
||||||
|
) : items.length === 0 ? (
|
||||||
|
<div className="py-10 text-center text-muted-foreground">ไม่มีรายการ</div>
|
||||||
|
) : (
|
||||||
|
<div className="rounded-md border">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead className="w-[50px]">
|
||||||
|
<Checkbox
|
||||||
|
checked={items.length > 0 && selectedPublicIds.length === items.length}
|
||||||
|
onCheckedChange={handleToggleSelectAll}
|
||||||
|
aria-label="เลือกทั้งหมด"
|
||||||
|
/>
|
||||||
|
</TableHead>
|
||||||
|
<TableHead>ไฟล์ต้นทาง</TableHead>
|
||||||
|
<TableHead>ความมั่นใจ AI</TableHead>
|
||||||
|
<TableHead>สถานะ</TableHead>
|
||||||
|
<TableHead>วันที่สร้าง</TableHead>
|
||||||
|
<TableHead className="text-right">การดำเนินการ</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{items.map((item) => (
|
||||||
|
// ADR-019: ใช้ publicId เป็น key
|
||||||
|
<TableRow key={item.publicId}>
|
||||||
|
<TableCell>
|
||||||
|
<Checkbox
|
||||||
|
checked={selectedPublicIds.includes(item.publicId)}
|
||||||
|
onCheckedChange={() => handleToggleSelect(item.publicId)}
|
||||||
|
aria-label={`เลือก ${item.publicId}`}
|
||||||
|
/>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs max-w-[200px] truncate">
|
||||||
|
{item.sourceFile}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={getConfidenceVariant(item.confidenceScore)}>
|
||||||
|
{item.confidenceScore
|
||||||
|
? (item.confidenceScore * 100).toFixed(1) + '%'
|
||||||
|
: 'N/A'}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={getStatusVariant(item.status)}>
|
||||||
|
{statusLabels[item.status] ?? item.status}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm">
|
||||||
|
{format(new Date(item.createdAt), 'dd MMM yyyy, HH:mm')}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => {
|
||||||
|
setReviewItem(item);
|
||||||
|
setAdminFeedback(item.adminFeedback ?? '');
|
||||||
|
}}
|
||||||
|
disabled={item.status === AiMigrationLogStatus.IMPORTED}
|
||||||
|
>
|
||||||
|
<EyeIcon className="h-4 w-4 mr-2" />
|
||||||
|
ตรวจสอบ
|
||||||
|
</Button>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Inline Review Sheet */}
|
||||||
|
<Sheet
|
||||||
|
open={reviewItem !== null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open) {
|
||||||
|
setReviewItem(null);
|
||||||
|
setAdminFeedback('');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SheetContent className="w-full sm:max-w-lg overflow-y-auto">
|
||||||
|
<SheetHeader>
|
||||||
|
<SheetTitle>ตรวจสอบ AI Migration Log</SheetTitle>
|
||||||
|
</SheetHeader>
|
||||||
|
{reviewItem && (
|
||||||
|
<div className="mt-4 space-y-4">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-xs text-muted-foreground">Public ID (ADR-019)</p>
|
||||||
|
<p className="font-mono text-xs break-all">{reviewItem.publicId}</p>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-xs text-muted-foreground">ไฟล์ต้นทาง</p>
|
||||||
|
<p className="text-sm">{reviewItem.sourceFile}</p>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-xs text-muted-foreground">ความมั่นใจ AI</p>
|
||||||
|
<Badge variant={getConfidenceVariant(reviewItem.confidenceScore)}>
|
||||||
|
{reviewItem.confidenceScore
|
||||||
|
? (reviewItem.confidenceScore * 100).toFixed(1) + '%'
|
||||||
|
: 'N/A'}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
{reviewItem.aiExtractedMetadata &&
|
||||||
|
Object.keys(reviewItem.aiExtractedMetadata).length > 0 && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p className="text-xs font-medium text-muted-foreground">
|
||||||
|
ข้อมูลที่ AI สกัดได้
|
||||||
|
</p>
|
||||||
|
<div className="bg-muted/40 rounded p-3 text-xs space-y-1 max-h-48 overflow-y-auto">
|
||||||
|
{Object.entries(reviewItem.aiExtractedMetadata).map(([k, v]) => (
|
||||||
|
<div key={k} className="flex gap-2">
|
||||||
|
<span className="font-medium text-muted-foreground min-w-[100px]">{k}:</span>
|
||||||
|
<span>{String(v)}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="space-y-1">
|
||||||
|
<label className="text-sm font-medium">ความเห็น Admin</label>
|
||||||
|
<Textarea
|
||||||
|
value={adminFeedback}
|
||||||
|
onChange={(e) => setAdminFeedback(e.target.value)}
|
||||||
|
placeholder="ระบุความเห็นหรือเหตุผล (ถ้ามี)"
|
||||||
|
rows={3}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-3 pt-2">
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
className="flex-1"
|
||||||
|
disabled={
|
||||||
|
submitting ||
|
||||||
|
reviewItem.status === AiMigrationLogStatus.IMPORTED ||
|
||||||
|
reviewItem.status === AiMigrationLogStatus.FAILED
|
||||||
|
}
|
||||||
|
onClick={() => handleUpdateStatus(AiMigrationLogStatus.FAILED)}
|
||||||
|
>
|
||||||
|
<XCircleIcon className="h-4 w-4 mr-2" />
|
||||||
|
ปฏิเสธ
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className="flex-1 bg-green-600 hover:bg-green-700 text-white"
|
||||||
|
disabled={
|
||||||
|
submitting ||
|
||||||
|
reviewItem.status === AiMigrationLogStatus.IMPORTED ||
|
||||||
|
reviewItem.status === AiMigrationLogStatus.VERIFIED
|
||||||
|
}
|
||||||
|
onClick={() => handleUpdateStatus(AiMigrationLogStatus.VERIFIED)}
|
||||||
|
>
|
||||||
|
<CheckCircleIcon className="h-4 w-4 mr-2" />
|
||||||
|
{submitting ? 'กำลังดำเนินการ...' : 'ยืนยัน'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Legacy Queue Tab (ระบบ Migration เดิม) ---
|
||||||
|
|
||||||
|
function LegacyQueueTab() {
|
||||||
const [items, setItems] = useState<MigrationReviewQueueItem[]>([]);
|
const [items, setItems] = useState<MigrationReviewQueueItem[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
@@ -32,7 +369,7 @@ export default function MigrationReviewQueuePage() {
|
|||||||
limit: 50,
|
limit: 50,
|
||||||
});
|
});
|
||||||
setItems(Array.isArray(res.items) ? res.items : []);
|
setItems(Array.isArray(res.items) ? res.items : []);
|
||||||
setSelectedIds([]); // reset selection on fetch
|
setSelectedIds([]);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
setItems([]);
|
setItems([]);
|
||||||
setErrorMessage(getApiErrorMessage(error, 'Failed to load queue'));
|
setErrorMessage(getApiErrorMessage(error, 'Failed to load queue'));
|
||||||
@@ -61,7 +398,6 @@ export default function MigrationReviewQueuePage() {
|
|||||||
if (selectedIds.length === 0) return;
|
if (selectedIds.length === 0) return;
|
||||||
try {
|
try {
|
||||||
setSubmitting(true);
|
setSubmitting(true);
|
||||||
|
|
||||||
const batchItems = items
|
const batchItems = items
|
||||||
.filter((i): i is typeof i & { id: number } => i.id !== undefined)
|
.filter((i): i is typeof i & { id: number } => i.id !== undefined)
|
||||||
.filter((i) => selectedIds.includes(i.id))
|
.filter((i) => selectedIds.includes(i.id))
|
||||||
@@ -80,16 +416,12 @@ export default function MigrationReviewQueuePage() {
|
|||||||
received_date: item.receivedDate,
|
received_date: item.receivedDate,
|
||||||
sender_id: item.senderOrganizationId,
|
sender_id: item.senderOrganizationId,
|
||||||
receiver_id: item.receiverOrganizationId,
|
receiver_id: item.receiverOrganizationId,
|
||||||
details: {
|
details: { tags: item.extractedTags },
|
||||||
tags: item.extractedTags,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const batchId = `BATCH_UI_${Date.now()}`;
|
const batchId = `BATCH_UI_${Date.now()}`;
|
||||||
await migrationService.commitBatch({ items: batchItems, batchId }, batchId);
|
await migrationService.commitBatch({ items: batchItems, batchId }, batchId);
|
||||||
|
await fetchData();
|
||||||
fetchData();
|
|
||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
toast.error('Batch commit failed.');
|
toast.error('Batch commit failed.');
|
||||||
} finally {
|
} finally {
|
||||||
@@ -98,22 +430,20 @@ export default function MigrationReviewQueuePage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<Card>
|
||||||
<div className="flex justify-between flex-wrap gap-4 items-center">
|
<CardHeader>
|
||||||
<div>
|
<div className="flex flex-wrap justify-between items-center gap-4">
|
||||||
<h1 className="text-3xl font-bold tracking-tight">Migration Review Queue</h1>
|
<CardTitle>Legacy Review Queue - {statusFilter}</CardTitle>
|
||||||
<p className="text-muted-foreground mt-1">Review and correct documents that AI flagged as low confidence.</p>
|
<div className="flex items-center gap-3">
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
{selectedIds.length > 0 && (
|
{selectedIds.length > 0 && (
|
||||||
<Button variant="default" onClick={handleBatchApprove} disabled={submitting}>
|
<Button variant="default" onClick={handleBatchApprove} disabled={submitting}>
|
||||||
<CheckSquareIcon className="mr-2 h-4 w-4" />
|
<CheckCircleIcon className="mr-2 h-4 w-4" />
|
||||||
{submitting ? 'Processing...' : `Batch Approve (${selectedIds.length})`}
|
{submitting ? 'Processing...' : `Batch Approve (${selectedIds.length})`}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<Link href="/admin/migration/errors">
|
<Link href="/admin/migration/errors">
|
||||||
<Button variant="outline">
|
<Button variant="outline">
|
||||||
<FileXIcon className="mr-2 h-4 w-4" /> View Error Logs
|
<FileXIcon className="mr-2 h-4 w-4" /> View Errors
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||||
@@ -129,10 +459,6 @@ export default function MigrationReviewQueuePage() {
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Queue Items - {statusFilter}</CardTitle>
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{errorMessage && (
|
{errorMessage && (
|
||||||
@@ -166,12 +492,12 @@ export default function MigrationReviewQueuePage() {
|
|||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{items.map((item) => (
|
{items.map((item) => (
|
||||||
<TableRow key={item.id || item.publicId}>
|
<TableRow key={item.id ?? item.publicId}>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={item.id !== undefined && selectedIds.includes(item.id)}
|
checked={item.id !== undefined && selectedIds.includes(item.id)}
|
||||||
onCheckedChange={() => item.id !== undefined && handleToggleSelect(item.id)}
|
onCheckedChange={() => item.id !== undefined && handleToggleSelect(item.id)}
|
||||||
aria-label={`Select item ${item.id || item.publicId}`}
|
aria-label={`Select item ${item.id}`}
|
||||||
/>
|
/>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="font-medium">{item.documentNumber}</TableCell>
|
<TableCell className="font-medium">{item.documentNumber}</TableCell>
|
||||||
@@ -206,11 +532,13 @@ export default function MigrationReviewQueuePage() {
|
|||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>{format(new Date(item.createdAt), 'dd MMM yyyy, HH:mm')}</TableCell>
|
<TableCell>{format(new Date(item.createdAt), 'dd MMM yyyy, HH:mm')}</TableCell>
|
||||||
<TableCell className="text-right">
|
<TableCell className="text-right">
|
||||||
<Link href={`/admin/migration/review/${item.id || item.publicId}`}>
|
{item.id !== undefined && (
|
||||||
|
<Link href={`/admin/migration/review/${item.id}`}>
|
||||||
<Button size="sm" variant="ghost">
|
<Button size="sm" variant="ghost">
|
||||||
<EyeIcon className="h-4 w-4 mr-2" /> Review
|
<EyeIcon className="h-4 w-4 mr-2" /> Review
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
|
)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))}
|
))}
|
||||||
@@ -220,6 +548,30 @@ export default function MigrationReviewQueuePage() {
|
|||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Main Page ---
|
||||||
|
|
||||||
|
export default function MigrationManagementPage() {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold tracking-tight">Migration Management</h1>
|
||||||
|
<p className="text-muted-foreground mt-1">จัดการการนำเข้าเอกสาร — AI Migration Logs และ Legacy Review Queue</p>
|
||||||
|
</div>
|
||||||
|
<Tabs defaultValue="ai">
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value="ai">AI Migration Logs</TabsTrigger>
|
||||||
|
<TabsTrigger value="legacy">Legacy Queue</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent value="ai">
|
||||||
|
<AiMigrationTab />
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent value="legacy">
|
||||||
|
<LegacyQueueTab />
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
// File: components/ai/ai-suggestion-field.tsx
|
||||||
|
// Component แสดง AI Suggestion พร้อม Accept / Reject / Edit actions (ADR-018, ADR-020)
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { Check, X, Edit2, Sparkles } from 'lucide-react';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
// สีตาม confidence score (>= 0.95 สีเขียว, >= 0.85 สีเหลือง, < 0.85 สีแดง)
|
||||||
|
const getConfidenceClass = (confidence: number): string => {
|
||||||
|
if (confidence >= 0.95) return 'text-green-700 bg-green-50 border-green-400';
|
||||||
|
if (confidence >= 0.85) return 'text-yellow-700 bg-yellow-50 border-yellow-400';
|
||||||
|
return 'text-red-700 bg-red-50 border-red-400';
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface AiSuggestionFieldProps {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
suggestion?: string;
|
||||||
|
confidence?: number;
|
||||||
|
onAccept: () => void;
|
||||||
|
onReject: () => void;
|
||||||
|
onEdit: (newValue: string) => void;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AiSuggestionField({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
suggestion,
|
||||||
|
confidence,
|
||||||
|
onAccept,
|
||||||
|
onReject,
|
||||||
|
onEdit,
|
||||||
|
className,
|
||||||
|
}: AiSuggestionFieldProps) {
|
||||||
|
const [isEditing, setIsEditing] = useState(false);
|
||||||
|
const [editValue, setEditValue] = useState(value);
|
||||||
|
|
||||||
|
// มีค่าจาก AI หรือไม่
|
||||||
|
const hasSuggestion = suggestion !== undefined && suggestion !== '';
|
||||||
|
// ค่าปัจจุบันตรงกับที่ AI แนะนำ
|
||||||
|
const isAiValue = hasSuggestion && value === suggestion;
|
||||||
|
|
||||||
|
const handleSave = () => {
|
||||||
|
onEdit(editValue);
|
||||||
|
setIsEditing(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleStartEdit = () => {
|
||||||
|
setEditValue(value);
|
||||||
|
setIsEditing(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn('space-y-1', className)}>
|
||||||
|
{/* Label พร้อม Confidence Badge */}
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<label className="text-sm font-medium">{label}</label>
|
||||||
|
{hasSuggestion && confidence !== undefined && (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className={cn('text-xs gap-1 px-1.5 py-0', getConfidenceClass(confidence))}
|
||||||
|
>
|
||||||
|
<Sparkles className="h-3 w-3" />
|
||||||
|
AI {Math.round(confidence * 100)}%
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Field Content — highlight สีเหลืองเมื่อใช้ค่าจาก AI */}
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'rounded border px-3 py-2 text-sm min-h-[2.25rem]',
|
||||||
|
isAiValue && 'bg-yellow-50 border-l-4 border-yellow-400'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{isEditing ? (
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
value={editValue}
|
||||||
|
onChange={(e) => setEditValue(e.target.value)}
|
||||||
|
className="h-7 text-sm"
|
||||||
|
autoFocus
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') handleSave();
|
||||||
|
if (e.key === 'Escape') setIsEditing(false);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Button type="button" size="sm" variant="outline" onClick={handleSave} className="h-7 px-2">
|
||||||
|
<Check className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setIsEditing(false)}
|
||||||
|
className="h-7 px-2"
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<span>
|
||||||
|
{value !== '' ? value : <span className="text-muted-foreground italic">—</span>}
|
||||||
|
</span>
|
||||||
|
{hasSuggestion && (
|
||||||
|
<div className="flex gap-1 shrink-0">
|
||||||
|
{/* ปุ่ม "รับ" จะแสดงเมื่อค่าปัจจุบันยังไม่ใช่ค่า AI */}
|
||||||
|
{!isAiValue && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={onAccept}
|
||||||
|
className="h-6 px-2 text-xs text-green-700 border-green-300 hover:bg-green-50"
|
||||||
|
title={`รับค่าจาก AI: ${suggestion}`}
|
||||||
|
>
|
||||||
|
<Check className="h-3 w-3 mr-1" />
|
||||||
|
รับ
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{/* ปุ่ม "ปฏิเสธ" จะแสดงเมื่อใช้ค่า AI อยู่ */}
|
||||||
|
{isAiValue && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={onReject}
|
||||||
|
className="h-6 px-2 text-xs text-red-700 border-red-300 hover:bg-red-50"
|
||||||
|
title="ปฏิเสธค่า AI"
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3 mr-1" />
|
||||||
|
ปฏิเสธ
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={handleStartEdit}
|
||||||
|
className="h-6 w-6 p-0"
|
||||||
|
title="แก้ไขค่า"
|
||||||
|
>
|
||||||
|
<Edit2 className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* แสดง AI Suggestion hint เมื่อค่าปัจจุบันต่างจาก AI */}
|
||||||
|
{hasSuggestion && !isAiValue && (
|
||||||
|
<p className="text-xs text-muted-foreground pl-1">
|
||||||
|
AI แนะนำ:{' '}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="font-medium text-yellow-700 hover:underline"
|
||||||
|
onClick={onAccept}
|
||||||
|
>
|
||||||
|
{suggestion}
|
||||||
|
</button>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
// File: components/ai/document-comparison-view.tsx
|
||||||
|
// Side-by-side PDF viewer + Form ที่มี AI Suggestions (ADR-018, ADR-020)
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { Eye, ChevronDown, ChevronUp } from 'lucide-react';
|
||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { AiSuggestionField } from './ai-suggestion-field';
|
||||||
|
import type { ExtractionResult } from '@/types/ai';
|
||||||
|
|
||||||
|
// Labels ภาษาไทยสำหรับ field ต่างๆ
|
||||||
|
const FIELD_LABELS: Record<string, string> = {
|
||||||
|
subject: 'ชื่อเรื่อง',
|
||||||
|
documentDate: 'วันที่เอกสาร',
|
||||||
|
category: 'ประเภทเอกสาร',
|
||||||
|
senderId: 'รหัสองค์กรผู้ส่ง',
|
||||||
|
disciplineId: 'สาขา (Discipline)',
|
||||||
|
issuedDate: 'วันที่ออกเอกสาร',
|
||||||
|
receivedDate: 'วันที่รับเอกสาร',
|
||||||
|
projectCode: 'รหัสโครงการ',
|
||||||
|
documentNumber: 'เลขที่เอกสาร',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Fields ที่แสดงใน comparison view
|
||||||
|
const DISPLAY_FIELDS = ['subject', 'documentDate', 'category', 'disciplineId', 'senderId'];
|
||||||
|
|
||||||
|
export interface DocumentComparisonViewProps {
|
||||||
|
fileUrl: string | null;
|
||||||
|
extractedData: ExtractionResult | null;
|
||||||
|
formData: Record<string, string>;
|
||||||
|
onFieldUpdate: (field: string, value: string) => void;
|
||||||
|
extractedText?: string;
|
||||||
|
reviewReason?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DocumentComparisonView({
|
||||||
|
fileUrl,
|
||||||
|
extractedData,
|
||||||
|
formData,
|
||||||
|
onFieldUpdate,
|
||||||
|
extractedText,
|
||||||
|
reviewReason,
|
||||||
|
}: DocumentComparisonViewProps) {
|
||||||
|
const [showRawText, setShowRawText] = useState(false);
|
||||||
|
|
||||||
|
// แกะ metadata และ confidence จาก ExtractionResult
|
||||||
|
const metadata = (extractedData?.extractedMetadata ?? {}) as Record<string, unknown>;
|
||||||
|
const fieldConfidences = metadata.fieldConfidences as Record<string, number> | undefined;
|
||||||
|
|
||||||
|
const getSuggestion = (field: string): string | undefined => {
|
||||||
|
const val = metadata[field];
|
||||||
|
return val !== undefined ? String(val) : undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getConfidence = (field: string): number | undefined =>
|
||||||
|
fieldConfidences?.[field] ?? extractedData?.confidenceScore;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-1 gap-6 overflow-hidden">
|
||||||
|
{/* Left: PDF Viewer */}
|
||||||
|
<Card className="flex-1 hidden md:flex flex-col overflow-hidden border-2 border-primary/10 shadow-md">
|
||||||
|
<CardContent className="p-0 flex-1 relative bg-slate-100">
|
||||||
|
{fileUrl ? (
|
||||||
|
<iframe
|
||||||
|
src={`${fileUrl}#toolbar=0&navpanes=0`}
|
||||||
|
className="absolute inset-0 w-full h-full"
|
||||||
|
title="Document Viewer"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center text-muted-foreground">
|
||||||
|
<p>ไม่พบไฟล์เอกสาร</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Right: Form + AI Suggestions */}
|
||||||
|
<Card className="w-full md:w-[450px] lg:w-[500px] flex-shrink-0 flex flex-col overflow-hidden border-2 border-primary/10 shadow-md">
|
||||||
|
<div className="p-4 border-b bg-muted/30 shrink-0">
|
||||||
|
<h2 className="font-semibold text-lg">ข้อมูลที่สกัดได้</h2>
|
||||||
|
{extractedData?.confidenceScore !== undefined && (
|
||||||
|
<p className="text-sm text-muted-foreground mt-1">
|
||||||
|
ความมั่นใจรวม:{' '}
|
||||||
|
<span
|
||||||
|
className={
|
||||||
|
extractedData.confidenceScore >= 0.95
|
||||||
|
? 'text-green-600 font-semibold'
|
||||||
|
: extractedData.confidenceScore >= 0.85
|
||||||
|
? 'text-yellow-600 font-semibold'
|
||||||
|
: 'text-red-600 font-semibold'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{(extractedData.confidenceScore * 100).toFixed(1)}%
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{reviewReason && (
|
||||||
|
<p className="text-sm text-red-600 mt-1 bg-red-50 p-2 rounded border border-red-100">
|
||||||
|
เหตุผลตรวจสอบ: {reviewReason}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<CardContent className="flex-1 overflow-y-auto p-4 space-y-4">
|
||||||
|
{/* AI Suggestion Fields */}
|
||||||
|
{DISPLAY_FIELDS.map((field) => {
|
||||||
|
const suggestion = getSuggestion(field);
|
||||||
|
const confidence = getConfidence(field);
|
||||||
|
const currentValue = formData[field] ?? '';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AiSuggestionField
|
||||||
|
key={field}
|
||||||
|
label={FIELD_LABELS[field] ?? field}
|
||||||
|
value={currentValue}
|
||||||
|
suggestion={suggestion}
|
||||||
|
confidence={confidence}
|
||||||
|
onAccept={() => suggestion !== undefined && onFieldUpdate(field, suggestion)}
|
||||||
|
onReject={() => onFieldUpdate(field, '')}
|
||||||
|
onEdit={(val) => onFieldUpdate(field, val)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{/* OCR Raw Text Viewer (toggle) */}
|
||||||
|
{extractedText && (
|
||||||
|
<div className="border-t pt-4">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="text-blue-600 p-0 h-auto hover:bg-transparent gap-1"
|
||||||
|
onClick={() => setShowRawText((prev) => !prev)}
|
||||||
|
>
|
||||||
|
<Eye className="h-4 w-4" />
|
||||||
|
ดูข้อความดิบจาก AI
|
||||||
|
{showRawText ? (
|
||||||
|
<ChevronUp className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<ChevronDown className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
{showRawText && (
|
||||||
|
<Card className="mt-2">
|
||||||
|
<CardContent className="p-4">
|
||||||
|
<pre className="text-xs bg-gray-50 p-3 rounded overflow-auto max-h-48 whitespace-pre-wrap font-mono">
|
||||||
|
{extractedText}
|
||||||
|
</pre>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
// File: components/ai/processing-indicator.tsx
|
||||||
|
// Loading indicator ระหว่าง AI ประมวลผลเอกสาร (ADR-018, ADR-020)
|
||||||
|
|
||||||
|
import { Loader2 } from 'lucide-react';
|
||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
|
||||||
|
export function AiProcessingIndicator() {
|
||||||
|
return (
|
||||||
|
<Card className="border-yellow-200 bg-yellow-50">
|
||||||
|
<CardContent className="flex items-center space-x-3 p-4">
|
||||||
|
<Loader2 className="h-5 w-5 animate-spin text-yellow-600" />
|
||||||
|
<div>
|
||||||
|
<p className="font-medium text-yellow-800">AI กำลังวิเคราะห์เอกสาร...</p>
|
||||||
|
<p className="text-sm text-yellow-600">กรุณารอสักครู่ (ประมาณ 15-30 วินาที)</p>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
// File: lib/services/ai.service.ts
|
||||||
|
// Service สำหรับ AI Gateway API (ADR-018: Frontend → DMS API เท่านั้น ห้ามเรียก n8n/Ollama โดยตรง)
|
||||||
|
|
||||||
|
import api from '../api/client';
|
||||||
|
import type {
|
||||||
|
ExtractionResult,
|
||||||
|
ExtractDocumentDto,
|
||||||
|
AiMigrationLog,
|
||||||
|
AiMigrationLogStatus,
|
||||||
|
AiMigrationUpdateDto,
|
||||||
|
AiFeedbackDto,
|
||||||
|
AiPaginatedResult,
|
||||||
|
} from '@/types/ai';
|
||||||
|
|
||||||
|
// Helper: แกะ nested data wrapper จาก TransformInterceptor
|
||||||
|
const extractData = <T>(value: unknown): T => {
|
||||||
|
if (value && typeof value === 'object' && 'data' in value) {
|
||||||
|
return (value as { data: T }).data;
|
||||||
|
}
|
||||||
|
return value as T;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper: normalize paginated response
|
||||||
|
const normalizePaginated = <T>(value: unknown): AiPaginatedResult<T> => {
|
||||||
|
const inner = extractData<unknown>(value);
|
||||||
|
if (
|
||||||
|
inner &&
|
||||||
|
typeof inner === 'object' &&
|
||||||
|
'items' in inner &&
|
||||||
|
Array.isArray((inner as { items: unknown[] }).items)
|
||||||
|
) {
|
||||||
|
return inner as AiPaginatedResult<T>;
|
||||||
|
}
|
||||||
|
return { items: [], total: 0, page: 1, limit: 10, totalPages: 0 };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const aiService = {
|
||||||
|
// --- Real-time Extraction (ADR-018: ผ่าน /api/ai/extract เท่านั้น ห้ามเรียก n8n/Ollama) ---
|
||||||
|
extract: async (dto: ExtractDocumentDto): Promise<ExtractionResult> => {
|
||||||
|
const { data } = await api.post('/ai/extract', dto);
|
||||||
|
return extractData<ExtractionResult>(data);
|
||||||
|
},
|
||||||
|
|
||||||
|
// --- Admin: รายการ AI Migration Logs ---
|
||||||
|
getMigrationList: async (params: {
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
status?: AiMigrationLogStatus;
|
||||||
|
minConfidence?: number;
|
||||||
|
}): Promise<AiPaginatedResult<AiMigrationLog>> => {
|
||||||
|
const { data } = await api.get('/ai/migration', { params });
|
||||||
|
return normalizePaginated<AiMigrationLog>(data);
|
||||||
|
},
|
||||||
|
|
||||||
|
// --- Admin: อัปเดตสถานะ Migration Log (ADR-019: ใช้ publicId) ---
|
||||||
|
updateMigration: async (
|
||||||
|
publicId: string, // ADR-019: UUID เท่านั้น ห้ามใช้ parseInt
|
||||||
|
dto: AiMigrationUpdateDto,
|
||||||
|
idempotencyKey: string
|
||||||
|
): Promise<AiMigrationLog> => {
|
||||||
|
const { data } = await api.patch(`/ai/migration/${publicId}`, dto, {
|
||||||
|
headers: { 'Idempotency-Key': idempotencyKey },
|
||||||
|
});
|
||||||
|
return extractData<AiMigrationLog>(data);
|
||||||
|
},
|
||||||
|
|
||||||
|
// --- Feedback Collection (สำหรับปรับปรุง AI) ---
|
||||||
|
submitFeedback: async (dto: AiFeedbackDto): Promise<void> => {
|
||||||
|
await api.post('/ai/feedback', dto);
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
// File: types/ai.ts
|
||||||
|
// ประเภทข้อมูลสำหรับ AI Integration (ADR-018, ADR-020)
|
||||||
|
|
||||||
|
// สถานะของ AI Migration Log (ตรงกับ backend MigrationLogStatus)
|
||||||
|
export enum AiMigrationLogStatus {
|
||||||
|
PENDING_REVIEW = 'PENDING_REVIEW',
|
||||||
|
VERIFIED = 'VERIFIED',
|
||||||
|
IMPORTED = 'IMPORTED',
|
||||||
|
FAILED = 'FAILED',
|
||||||
|
}
|
||||||
|
|
||||||
|
// ผลลัพธ์จาก Real-time AI Extraction
|
||||||
|
export interface ExtractionResult {
|
||||||
|
migrationLogPublicId: string; // ADR-019: UUID เท่านั้น
|
||||||
|
status: 'processing' | 'completed' | 'failed';
|
||||||
|
extractedMetadata?: Record<string, unknown>;
|
||||||
|
confidenceScore?: number;
|
||||||
|
action?: string;
|
||||||
|
processingTimeMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ข้อมูล AI Migration Log (ตาราง migration_logs)
|
||||||
|
export interface AiMigrationLog {
|
||||||
|
publicId: string; // ADR-019: UUID เท่านั้น
|
||||||
|
sourceFile: string;
|
||||||
|
sourceMetadata?: Record<string, unknown>;
|
||||||
|
aiExtractedMetadata?: Record<string, unknown>;
|
||||||
|
confidenceScore?: number;
|
||||||
|
status: AiMigrationLogStatus;
|
||||||
|
adminFeedback?: string;
|
||||||
|
reviewedAt?: string;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// DTO สำหรับส่ง Extract Document ไปยัง AI
|
||||||
|
export interface ExtractDocumentDto {
|
||||||
|
publicId: string; // ADR-019: UUID ของไฟล์ใน temp storage
|
||||||
|
context: 'ingestion' | 'migration' | 'review';
|
||||||
|
fileType?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// DTO สำหรับอัปเดตสถานะ Migration Log (Admin)
|
||||||
|
export interface AiMigrationUpdateDto {
|
||||||
|
status?: AiMigrationLogStatus;
|
||||||
|
adminFeedback?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Feedback สำหรับปรับปรุงความแม่นยำ AI
|
||||||
|
export interface AiFeedbackDto {
|
||||||
|
documentPublicId: string; // ADR-019: UUID เท่านั้น
|
||||||
|
field: string;
|
||||||
|
aiSuggestion: string;
|
||||||
|
userCorrection: string;
|
||||||
|
confidence: number;
|
||||||
|
timestamp: string;
|
||||||
|
userAgent: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Metrics สำหรับ Admin Analytics Dashboard
|
||||||
|
export interface PerformanceMetrics {
|
||||||
|
overallAccuracy: number;
|
||||||
|
userCorrectionRate: number;
|
||||||
|
avgProcessingTime: number;
|
||||||
|
fieldAccuracy: Record<string, number>;
|
||||||
|
modelPerformance: Record<string, number>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paginated Result สำหรับ AI endpoints
|
||||||
|
export interface AiPaginatedResult<T> {
|
||||||
|
items: T[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
limit: number;
|
||||||
|
totalPages: number;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user