260324:2133 Refactor correspondence & rfa
CI / CD Pipeline / build (push) Failing after 17m3s
CI / CD Pipeline / deploy (push) Has been skipped

This commit is contained in:
admin
2026-03-24 21:33:59 +07:00
parent 42fc9fa502
commit aa82b890a5
42 changed files with 2617 additions and 233 deletions
@@ -0,0 +1,134 @@
'use client';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Loader2, GitBranch, ChevronRight, CheckCircle2, Clock, XCircle, Circle } from 'lucide-react';
import { useCirculationsByCorrespondence } from '@/hooks/use-circulation';
import { Circulation, CirculationRouting } from '@/types/circulation';
import { format } from 'date-fns';
import Link from 'next/link';
interface CirculationStatusCardProps {
correspondenceUuid: string;
}
const ROUTING_STATUS_META: Record<string, { icon: React.ElementType; color: string; label: string }> = {
PENDING: { icon: Clock, color: 'text-yellow-500', label: 'Pending' },
IN_PROGRESS: { icon: Circle, color: 'text-blue-500', label: 'In Progress' },
COMPLETED: { icon: CheckCircle2, color: 'text-green-500', label: 'Completed' },
REJECTED: { icon: XCircle, color: 'text-red-500', label: 'Rejected' },
};
const CIRC_STATUS_CLASS: Record<string, string> = {
OPEN: 'bg-blue-100 text-blue-700',
COMPLETED: 'bg-green-100 text-green-700',
CANCELLED: 'bg-slate-100 text-slate-500',
};
function RoutingStep({ routing }: { routing: CirculationRouting }) {
const meta = ROUTING_STATUS_META[routing.status] ?? ROUTING_STATUS_META.PENDING;
const Icon = meta.icon;
const assigneeName = routing.assignee
? `${routing.assignee.first_name ?? ''} ${routing.assignee.last_name ?? ''}`.trim() ||
routing.assignee.username
: '—';
return (
<div className="flex items-center gap-2 py-1">
<Icon className={`h-3.5 w-3.5 shrink-0 ${meta.color}`} />
<span className="text-xs flex-1 truncate">{assigneeName}</span>
{routing.completedAt && (
<span className="text-xs text-muted-foreground shrink-0">
{format(new Date(routing.completedAt), 'dd MMM')}
</span>
)}
</div>
);
}
function CirculationItem({ circ }: { circ: Circulation }) {
const statusClass = CIRC_STATUS_CLASS[circ.statusCode] ?? 'bg-gray-100 text-gray-700';
const routings = circ.routings ?? [];
return (
<div className="border rounded-md p-3 space-y-2">
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-xs font-mono text-muted-foreground">{circ.circulationNo}</p>
<p className="text-sm font-medium line-clamp-1">{circ.subject}</p>
</div>
<Badge className={`text-xs px-1.5 py-0 shrink-0 border-0 ${statusClass}`}>
{circ.statusCode}
</Badge>
</div>
{routings.length > 0 && (
<div className="border-t pt-2 space-y-0.5">
{routings.slice(0, 3).map((r) => (
<RoutingStep key={r.id} routing={r} />
))}
{routings.length > 3 && (
<p className="text-xs text-muted-foreground pl-5">
+{routings.length - 3} more assignees
</p>
)}
</div>
)}
<Link href={`/circulation/${circ.uuid}`}>
<Button variant="ghost" size="sm" className="w-full h-7 text-xs mt-1">
View Details
<ChevronRight className="h-3 w-3 ml-1" />
</Button>
</Link>
</div>
);
}
export function CirculationStatusCard({ correspondenceUuid }: CirculationStatusCardProps) {
const { data, isLoading } = useCirculationsByCorrespondence(correspondenceUuid);
const circulations: Circulation[] = Array.isArray(data)
? data
: Array.isArray(data?.data)
? data.data
: [];
return (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center gap-2">
<GitBranch className="h-4 w-4" />
Circulations
{circulations.length > 0 && (
<Badge variant="secondary" className="ml-auto text-xs">
{circulations.length}
</Badge>
)}
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{isLoading ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" />
Loading...
</div>
) : circulations.length === 0 ? (
<p className="text-sm text-muted-foreground">No circulations yet</p>
) : (
circulations.map((circ) => (
<CirculationItem key={circ.uuid} circ={circ} />
))
)}
<Link href={`/circulation/new?correspondenceUuid=${correspondenceUuid}`}>
<Button variant="outline" size="sm" className="w-full h-8 text-xs mt-1">
<GitBranch className="h-3 w-3 mr-1.5" />
New Circulation
</Button>
</Link>
</CardContent>
</Card>
);
}
@@ -3,25 +3,84 @@
import { CorrespondenceList } from '@/components/correspondences/list';
import { Pagination } from '@/components/common/pagination';
import { useCorrespondences } from '@/hooks/use-correspondence';
import { useSearchParams } from 'next/navigation';
import { Loader2 } from 'lucide-react';
import { useSearchParams, useRouter, usePathname } from 'next/navigation';
import { Loader2, Search, X, Download } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import Link from 'next/link';
import { useCallback, useState } from 'react';
import apiClient from '@/lib/api/client';
const STATUS_FILTERS = [
{ value: '', label: 'All Statuses' },
{ value: 'DRAFT', label: 'Draft' },
{ value: 'IN_REVIEW', label: 'In Review' },
{ value: 'APPROVED', label: 'Approved' },
{ value: 'CANCELLED', label: 'Cancelled' },
];
export function CorrespondencesContent() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const page = Number(searchParams.get('page') || '1');
const _status = searchParams.get('status') || undefined;
const statusFilter = searchParams.get('status') || '';
const search = searchParams.get('search') || undefined;
const revisionStatus = (searchParams.get('revisionStatus') as 'CURRENT' | 'ALL' | 'OLD') || 'CURRENT';
const [searchInput, setSearchInput] = useState(search || '');
const [exporting, setExporting] = useState(false);
const handleExportCsv = async () => {
setExporting(true);
try {
const params: Record<string, string> = {};
if (search) params.search = search;
if (statusFilter) params.status = statusFilter;
if (revisionStatus) params.revisionStatus = revisionStatus;
const response = await apiClient.get('/correspondences/export-csv', {
params,
responseType: 'blob',
});
const url = URL.createObjectURL(new Blob([response.data], { type: 'text/csv' }));
const a = document.createElement('a');
a.href = url;
a.download = `correspondences-${new Date().toISOString().split('T')[0]}.csv`;
a.click();
URL.revokeObjectURL(url);
} finally {
setExporting(false);
}
};
const { data, isLoading, isError } = useCorrespondences({
page,
search,
status: statusFilter || undefined,
revisionStatus,
});
const buildUrl = useCallback((updates: Record<string, string>) => {
const params = new URLSearchParams(searchParams.toString());
Object.entries(updates).forEach(([k, v]) => {
if (v) params.set(k, v);
else params.delete(k);
});
params.set('page', '1');
return `${pathname}?${params.toString()}`;
}, [searchParams, pathname]);
const handleSearch = () => {
router.push(buildUrl({ search: searchInput }));
};
const handleClearSearch = () => {
setSearchInput('');
router.push(buildUrl({ search: '' }));
};
if (isLoading) {
return (
<div className="flex justify-center py-8">
@@ -36,20 +95,78 @@ export function CorrespondencesContent() {
return (
<>
<div className="mb-4 flex gap-2">
{/* Filters bar */}
<div className="mb-4 flex flex-wrap items-center gap-3">
{/* Search */}
<div className="flex items-center gap-1 flex-1 min-w-[200px] max-w-sm">
<div className="relative w-full">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
placeholder="Search by number or subject..."
className="pl-8 pr-8 h-9 text-sm"
/>
{searchInput && (
<button
onClick={handleClearSearch}
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
<Button size="sm" onClick={handleSearch} className="h-9">Search</Button>
</div>
{/* Status filter */}
<div className="flex gap-1 bg-muted p-1 rounded-md">
{['ALL', 'CURRENT', 'OLD'].map((status) => (
<Link
key={status}
href={`?${new URLSearchParams({ ...Object.fromEntries(searchParams.entries()), revisionStatus: status, page: '1' }).toString()}`}
>
<Button variant={revisionStatus === status ? 'default' : 'ghost'} size="sm" className="text-xs px-3">
{status === 'CURRENT' ? 'Latest' : status === 'OLD' ? 'Previous' : 'All'}
{STATUS_FILTERS.map(({ value, label }) => (
<Link key={value} href={buildUrl({ status: value })}>
<Button
variant={statusFilter === value ? 'default' : 'ghost'}
size="sm"
className="text-xs px-3 h-7"
>
{label}
</Button>
</Link>
))}
</div>
{/* Revision filter */}
<div className="flex gap-1 bg-muted p-1 rounded-md">
{(['CURRENT', 'ALL', 'OLD'] as const).map((rs) => (
<Link key={rs} href={buildUrl({ revisionStatus: rs })}>
<Button
variant={revisionStatus === rs ? 'default' : 'ghost'}
size="sm"
className="text-xs px-3 h-7"
>
{rs === 'CURRENT' ? 'Latest' : rs === 'OLD' ? 'Previous' : 'All'}
</Button>
</Link>
))}
</div>
{/* Export */}
<Button
variant="outline"
size="sm"
className="h-9 ml-auto gap-1.5"
onClick={handleExportCsv}
disabled={exporting}
>
{exporting ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Download className="h-3.5 w-3.5" />
)}
Export CSV
</Button>
</div>
<CorrespondenceList data={data?.data || []} />
<div className="mt-4">
<Pagination
+205 -66
View File
@@ -5,12 +5,18 @@ import { StatusBadge } from '@/components/common/status-badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { format } from 'date-fns';
import { ArrowLeft, Download, FileText, Loader2, Send, CheckCircle, XCircle, Edit } from 'lucide-react';
import { ArrowLeft, Download, FileText, Loader2, Send, CheckCircle, XCircle, Edit, Ban, AlertTriangle } from 'lucide-react';
import Link from 'next/link';
import { useSubmitCorrespondence, useProcessWorkflow } from '@/hooks/use-correspondence';
import { useSubmitCorrespondence, useProcessWorkflow, useCancelCorrespondence } from '@/hooks/use-correspondence';
import { ReferenceSelector } from '@/components/correspondences/reference-selector';
import { TagManager } from '@/components/correspondences/tag-manager';
import { CirculationStatusCard } from '@/components/correspondences/circulation-status-card';
import { RevisionHistory } from '@/components/correspondences/revision-history';
import { useState } from 'react';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
interface CorrespondenceDetailProps {
data: Correspondence;
@@ -19,53 +25,61 @@ interface CorrespondenceDetailProps {
export function CorrespondenceDetail({ data }: CorrespondenceDetailProps) {
const submitMutation = useSubmitCorrespondence();
const processMutation = useProcessWorkflow();
const [actionState, setActionState] = useState<'approve' | 'reject' | null>(null);
const cancelMutation = useCancelCorrespondence();
const [actionState, setActionState] = useState<'approve' | 'reject' | 'cancel' | null>(null);
const [comments, setComments] = useState('');
const [cancelReason, setCancelReason] = useState('');
if (!data) return <div>No data found</div>;
// Derive Current Revision Data
const currentRevision = data.revisions?.find((r) => r.isCurrent) || data.revisions?.[0];
const subject = currentRevision?.subject || '-';
const description = currentRevision?.description || '-';
const status = currentRevision?.status?.statusCode || 'UNKNOWN'; // e.g. DRAFT
const status = currentRevision?.status?.statusCode || 'UNKNOWN';
const attachments = currentRevision?.attachments || [];
const importance = (currentRevision?.details?.importance as string) || 'NORMAL';
// Note: Importance might be in details
const importance = currentRevision?.details?.importance || 'NORMAL';
const toRecipients = data.recipients?.filter((r) => r.recipientType === 'TO') || [];
const ccRecipients = data.recipients?.filter((r) => r.recipientType === 'CC') || [];
const handleSubmit = () => {
if (confirm('Are you sure you want to submit this correspondence?')) {
submitMutation.mutate({
uuid: data.uuid,
data: {},
});
submitMutation.mutate({ uuid: data.uuid, data: {} });
}
};
const handleProcess = () => {
if (!actionState) return;
if (!actionState || actionState === 'cancel') return;
const action = actionState === 'approve' ? 'APPROVE' : 'REJECT';
processMutation.mutate(
{
uuid: data.uuid,
data: {
action,
comments,
},
},
{
onSuccess: () => {
setActionState(null);
setComments('');
},
}
{ uuid: data.uuid, data: { action, comments } },
{ onSuccess: () => { setActionState(null); setComments(''); } }
);
};
const handleCancel = () => {
if (!cancelReason.trim()) return;
cancelMutation.mutate(
{ uuid: data.uuid, reason: cancelReason },
{ onSuccess: () => { setActionState(null); setCancelReason(''); } }
);
};
return (
<div className="space-y-6">
{/* EC-CORR-002 Warning: Replying to cancelled document */}
{status === 'CANCELLED' && (
<div className="flex items-start gap-3 p-4 bg-amber-50 border border-amber-200 rounded-md">
<AlertTriangle className="h-5 w-5 text-amber-600 mt-0.5 shrink-0" />
<div>
<p className="font-semibold text-amber-800">This correspondence has been cancelled</p>
<p className="text-sm text-amber-700 mt-0.5">
You can still create a new correspondence referencing this document to acknowledge the cancellation.
</p>
</div>
</div>
)}
{/* Header / Actions */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
@@ -82,7 +96,6 @@ export function CorrespondenceDetail({ data }: CorrespondenceDetailProps) {
</div>
</div>
<div className="flex gap-2">
{/* EDIT BUTTON LOGIC: Show if DRAFT */}
{status === 'DRAFT' && (
<Link href={`/correspondences/${data.uuid}/edit`}>
<Button variant="outline">
@@ -91,7 +104,6 @@ export function CorrespondenceDetail({ data }: CorrespondenceDetailProps) {
</Button>
</Link>
)}
{status === 'DRAFT' && (
<Button onClick={handleSubmit} disabled={submitMutation.isPending}>
{submitMutation.isPending ? (
@@ -114,11 +126,21 @@ export function CorrespondenceDetail({ data }: CorrespondenceDetailProps) {
</Button>
</>
)}
{status !== 'CANCELLED' && (
<Button
variant="outline"
className="text-destructive border-destructive hover:bg-destructive/10"
onClick={() => setActionState('cancel')}
>
<Ban className="mr-2 h-4 w-4" />
Cancel
</Button>
)}
</div>
</div>
{/* Action Input Area */}
{actionState && (
{/* Approve / Reject Input Area */}
{(actionState === 'approve' || actionState === 'reject') && (
<Card className="border-primary">
<CardHeader>
<CardTitle className="text-lg">
@@ -136,7 +158,7 @@ export function CorrespondenceDetail({ data }: CorrespondenceDetailProps) {
</div>
<div className="flex justify-end gap-2">
<Button variant="ghost" onClick={() => setActionState(null)}>
Cancel
Back
</Button>
<Button
variant={actionState === 'approve' ? 'default' : 'destructive'}
@@ -152,6 +174,48 @@ export function CorrespondenceDetail({ data }: CorrespondenceDetailProps) {
</Card>
)}
{/* Cancel Confirmation (EC-CORR-001) */}
{actionState === 'cancel' && (
<Card className="border-destructive">
<CardHeader>
<CardTitle className="text-lg text-destructive flex items-center gap-2">
<Ban className="h-5 w-5" />
Cancel Correspondence
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-start gap-3 p-3 bg-amber-50 border border-amber-200 rounded-md text-sm">
<AlertTriangle className="h-4 w-4 text-amber-600 mt-0.5 shrink-0" />
<p className="text-amber-800">
Cancelling will permanently change this document&apos;s status and force-close any active circulations
linked to it. This action cannot be undone.
</p>
</div>
<div className="space-y-2">
<Label>Reason for Cancellation <span className="text-destructive">*</span></Label>
<Input
value={cancelReason}
onChange={(e) => setCancelReason(e.target.value)}
placeholder="Enter reason for cancellation..."
/>
</div>
<div className="flex justify-end gap-2">
<Button variant="ghost" onClick={() => { setActionState(null); setCancelReason(''); }}>
Back
</Button>
<Button
variant="destructive"
onClick={handleCancel}
disabled={cancelMutation.isPending || !cancelReason.trim()}
>
{cancelMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Confirm Cancellation
</Button>
</div>
</CardContent>
</Card>
)}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Main Content */}
<div className="lg:col-span-2 space-y-6">
@@ -163,11 +227,12 @@ export function CorrespondenceDetail({ data }: CorrespondenceDetailProps) {
</div>
</CardHeader>
<CardContent className="space-y-6">
<div>
<h3 className="font-semibold mb-2">Description</h3>
<p className="text-gray-700 whitespace-pre-wrap">{description}</p>
</div>
{description && description !== '-' && (
<div>
<h3 className="font-semibold mb-2">Description</h3>
<p className="text-gray-700 whitespace-pre-wrap">{description}</p>
</div>
)}
{currentRevision?.body && (
<div>
<h3 className="font-semibold mb-2">Content</h3>
@@ -176,7 +241,6 @@ export function CorrespondenceDetail({ data }: CorrespondenceDetailProps) {
</div>
</div>
)}
{currentRevision?.remarks && (
<div>
<h3 className="font-semibold mb-2">Remarks</h3>
@@ -188,11 +252,11 @@ export function CorrespondenceDetail({ data }: CorrespondenceDetailProps) {
<div>
<h3 className="font-semibold mb-3">Attachments</h3>
{attachments && attachments.length > 0 ? (
{attachments.length > 0 ? (
<div className="grid gap-2">
{attachments.map((file, index) => (
<div
key={file.id || index}
key={file.uuid || index}
className="flex items-center justify-between p-3 border rounded-lg bg-muted/20"
>
<div className="flex items-center gap-3">
@@ -215,46 +279,121 @@ export function CorrespondenceDetail({ data }: CorrespondenceDetailProps) {
</Card>
</div>
{/* Sidebar Info */}
{/* Sidebar */}
<div className="space-y-6">
{/* Core Info */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Information</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<CardContent className="space-y-4 text-sm">
<div>
<p className="text-sm font-medium text-muted-foreground">Importance</p>
<div className="mt-1">
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
${
importance === 'URGENT'
? 'bg-red-100 text-red-800'
: importance === 'HIGH'
? 'bg-orange-100 text-orange-800'
: 'bg-blue-100 text-blue-800'
}`}
>
{String(importance)}
</span>
<p className="font-medium text-muted-foreground">Importance</p>
<span
className={`inline-flex items-center mt-1 px-2.5 py-0.5 rounded-full text-xs font-medium
${importance === 'URGENT' ? 'bg-red-100 text-red-800'
: importance === 'HIGH' ? 'bg-orange-100 text-orange-800'
: 'bg-blue-100 text-blue-800'}`}
>
{String(importance)}
</span>
</div>
<div>
<p className="font-medium text-muted-foreground">Document Type</p>
<p className="mt-1">{data.type?.typeName || '-'} <span className="text-xs text-muted-foreground">({data.type?.typeCode || '-'})</span></p>
</div>
<hr />
<div>
<p className="font-medium text-muted-foreground">Originator (From)</p>
<p className="font-semibold mt-1">{data.originator?.organizationName || '-'}</p>
<p className="text-xs text-muted-foreground">{data.originator?.organizationCode}</p>
</div>
<div>
<p className="font-medium text-muted-foreground">To</p>
{toRecipients.length > 0 ? (
<div className="mt-1 space-y-1">
{toRecipients.map((r) => (
<div key={r.recipientOrganizationId}>
<p className="font-semibold">{r.recipientOrganization?.organizationName || '-'}</p>
<p className="text-xs text-muted-foreground">{r.recipientOrganization?.organizationCode}</p>
</div>
))}
</div>
) : (
<p className="mt-1 text-muted-foreground">-</p>
)}
</div>
{ccRecipients.length > 0 && (
<div>
<p className="font-medium text-muted-foreground">CC</p>
<div className="mt-1 flex flex-wrap gap-1">
{ccRecipients.map((r) => (
<Badge key={r.recipientOrganizationId} variant="secondary" className="text-xs">
{r.recipientOrganization?.organizationCode || '-'}
</Badge>
))}
</div>
</div>
</div>
)}
<hr className="my-4 border-t" />
<hr />
<div>
<p className="text-sm font-medium text-muted-foreground">Originator</p>
<p className="font-medium mt-1">{data.originator?.organizationName || '-'}</p>
<p className="text-xs text-muted-foreground">{data.originator?.organizationCode || '-'}</p>
</div>
<div>
<p className="text-sm font-medium text-muted-foreground">Project</p>
<p className="font-medium mt-1">{data.project?.projectName || '-'}</p>
<p className="text-xs text-muted-foreground">{data.project?.projectCode || '-'}</p>
<p className="font-medium text-muted-foreground">Project</p>
<p className="font-semibold mt-1">{data.project?.projectName || '-'}</p>
<p className="text-xs text-muted-foreground">{data.project?.projectCode}</p>
</div>
</CardContent>
</Card>
{/* Dates */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Dates</CardTitle>
</CardHeader>
<CardContent className="space-y-3 text-sm">
{(
[
{ label: 'Document Date', value: currentRevision?.documentDate },
{ label: 'Issued Date', value: currentRevision?.issuedDate },
{ label: 'Received Date', value: currentRevision?.receivedDate },
{ label: 'Due Date', value: currentRevision?.dueDate },
] as { label: string; value?: string }[]
).map(({ label, value }) => (
<div key={label} className="flex justify-between">
<span className="text-muted-foreground">{label}</span>
<span className={`font-medium ${label === 'Due Date' && value && new Date(value) < new Date() && status !== 'CANCELLED' ? 'text-destructive' : ''}`}>
{value ? format(new Date(value), 'dd MMM yyyy') : '-'}
</span>
</div>
))}
</CardContent>
</Card>
{/* Circulations */}
<CirculationStatusCard correspondenceUuid={data.uuid} />
{/* Tags */}
<TagManager
uuid={data.uuid}
canEdit={status !== 'CANCELLED'}
/>
{/* References */}
<ReferenceSelector
uuid={data.uuid}
canEdit={status !== 'CANCELLED'}
/>
{/* Revision History */}
{data.revisions && data.revisions.length > 0 && (
<RevisionHistory revisions={data.revisions} />
)}
</div>
</div>
</div>
+62 -9
View File
@@ -8,6 +8,7 @@ import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { FileUploadZone } from '@/components/custom/file-upload-zone';
import { useRouter } from 'next/navigation';
import { Loader2 } from 'lucide-react';
@@ -18,6 +19,7 @@ import { CreateCorrespondenceDto } from '@/types/dto/correspondence/create-corre
import { useState, useEffect } from 'react';
import { correspondenceService as _correspondenceService } from '@/lib/services/correspondence.service';
import { numberingApi } from '@/lib/api/numbering';
import { filesApi } from '@/lib/api/files';
// Updated Zod Schema with all required fields
const correspondenceSchema = z.object({
@@ -34,6 +36,7 @@ const correspondenceSchema = z.object({
receivedDate: z.string().optional(),
fromOrganizationId: z.string().min(1, 'Please select From Organization'),
toOrganizationId: z.string().min(1, 'Please select To Organization'),
ccOrganizationIds: z.array(z.string()).optional(), // CC organizations support
importance: z.enum(['NORMAL', 'HIGH', 'URGENT']),
attachments: z.array(z.instanceof(File)).optional(),
});
@@ -159,7 +162,30 @@ export function CorrespondenceForm({ initialData, uuid }: { initialData?: Initia
const fromOrgId = watch('fromOrganizationId');
const toOrgId = watch('toOrganizationId');
const onSubmit = (data: FormData) => {
const [isUploading, setIsUploading] = useState(false);
const onSubmit = async (data: FormData) => {
// Build recipients array with TO and CC
const recipients = [
{ organizationId: data.toOrganizationId, type: 'TO' as const },
...(data.ccOrganizationIds?.map(orgId => ({ organizationId: orgId, type: 'CC' as const })) || [])
];
// Phase 1: Upload attachments to temp storage
let attachmentTempIds: string[] | undefined;
const validFiles = (data.attachments || []).filter((f): f is File => f instanceof File && !('validationError' in f && (f as { validationError?: string }).validationError));
if (validFiles.length > 0) {
setIsUploading(true);
try {
const uploaded = await filesApi.uploadMany(validFiles);
attachmentTempIds = uploaded.map((u) => u.tempId);
} catch (_err) {
setIsUploading(false);
return;
}
setIsUploading(false);
}
const payload: CreateCorrespondenceDto = {
projectId: data.projectId,
typeId: data.documentTypeId,
@@ -173,29 +199,26 @@ export function CorrespondenceForm({ initialData, uuid }: { initialData?: Initia
issuedDate: data.issuedDate ? new Date(data.issuedDate).toISOString() : undefined,
receivedDate: data.receivedDate ? new Date(data.receivedDate).toISOString() : undefined,
originatorId: data.fromOrganizationId,
recipients: [{ organizationId: data.toOrganizationId, type: 'TO' }],
attachmentTempIds,
recipients,
details: {
importance: data.importance,
},
};
if (uuid && initialData) {
// UPDATE Mode
updateMutation.mutate(
{ uuid, data: payload },
{
onSuccess: () => router.push(`/correspondences/${uuid}`),
}
{ onSuccess: () => router.push(`/correspondences/${uuid}`) }
);
} else {
// CREATE Mode
createMutation.mutate(payload, {
onSuccess: () => router.push('/correspondences'),
});
}
};
const isPending = createMutation.isPending || updateMutation.isPending;
const isPending = createMutation.isPending || updateMutation.isPending || isUploading;
// -- Preview Logic --
const [preview, setPreview] = useState<{ number: string; isDefaultTemplate: boolean } | null>(null);
@@ -464,6 +487,36 @@ export function CorrespondenceForm({ initialData, uuid }: { initialData?: Initia
</Select>
{errors.toOrganizationId && <p className="text-sm text-destructive">{errors.toOrganizationId.message}</p>}
</div>
<div className="space-y-2">
<Label>CC Organizations (Optional)</Label>
<div className="space-y-2 max-h-32 overflow-y-auto border rounded-md p-3">
{organizationOptions
.filter(org => org.uuid !== toOrgId) // Exclude TO organization
.map((org) => (
<div key={org.uuid} className="flex items-center space-x-2">
<Checkbox
id={`cc-${org.uuid}`}
checked={watch('ccOrganizationIds')?.includes(org.uuid) || false}
onCheckedChange={(checked) => {
const currentCC = watch('ccOrganizationIds') || [];
if (checked) {
setValue('ccOrganizationIds', [...currentCC, org.uuid]);
} else {
setValue('ccOrganizationIds', currentCC.filter(id => id !== org.uuid));
}
}}
/>
<Label htmlFor={`cc-${org.uuid}`} className="text-sm">
{org.organizationName} ({org.organizationCode})
</Label>
</div>
))}
</div>
<p className="text-xs text-muted-foreground">
Select organizations to receive a copy of this correspondence
</p>
</div>
</div>
{/* Importance */}
@@ -504,7 +557,7 @@ export function CorrespondenceForm({ initialData, uuid }: { initialData?: Initia
</Button>
<Button type="submit" disabled={isPending}>
{isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{uuid ? 'Update Correspondence' : 'Create Correspondence'}
{isUploading ? 'Uploading files...' : uuid ? 'Update Correspondence' : 'Create Correspondence'}
</Button>
</div>
</form>
+31 -22
View File
@@ -5,7 +5,7 @@ import { DataTable } from '@/components/common/data-table';
import { ColumnDef } from '@tanstack/react-table';
import { StatusBadge } from '@/components/common/status-badge';
import { Button } from '@/components/ui/button';
import { Eye, Edit, FileText } from 'lucide-react';
import { Eye, Edit } from 'lucide-react';
import Link from 'next/link';
import { format } from 'date-fns';
@@ -36,6 +36,15 @@ export function CorrespondenceList({ data }: CorrespondenceListProps) {
</div>
),
},
{
accessorKey: 'correspondence.type.typeCode',
header: 'Type',
cell: ({ row }) => (
<span className="text-xs font-medium bg-muted px-1.5 py-0.5 rounded">
{row.original.correspondence?.type?.typeCode || '-'}
</span>
),
},
{
accessorKey: 'correspondence.originator.organizationCode',
header: 'From',
@@ -43,6 +52,27 @@ export function CorrespondenceList({ data }: CorrespondenceListProps) {
<span className="font-medium">{row.original.correspondence?.originator?.organizationCode || '-'}</span>
),
},
{
accessorKey: 'correspondence.project.projectCode',
header: 'Project',
cell: ({ row }) => (
<span className="text-sm text-muted-foreground">{row.original.correspondence?.project?.projectCode || '-'}</span>
),
},
{
accessorKey: 'dueDate',
header: 'Due Date',
cell: ({ row }) => {
const due = row.original.dueDate;
if (!due) return <span className="text-muted-foreground">-</span>;
const isOverdue = new Date(due) < new Date() && row.original.status?.statusCode !== 'CANCELLED';
return (
<span className={isOverdue ? 'text-destructive font-medium' : ''}>
{format(new Date(due), 'dd MMM yyyy')}
</span>
);
},
},
{
accessorKey: 'createdAt',
header: 'Created',
@@ -70,27 +100,6 @@ export function CorrespondenceList({ data }: CorrespondenceListProps) {
<Eye className="h-4 w-4" />
</Button>
</Link>
<Button
variant="ghost"
size="icon"
title="View File"
onClick={() => {
const attachments = item.attachments; // Now we are on Revision, so attachments might be here if joined
if (attachments && attachments.length > 0 && attachments[0].url) {
window.open(attachments[0].url, '_blank');
} else {
// Fallback check if attachments are on details json inside revision
// or if we simply didn't join them yet.
// Current Backend join: leftJoinAndSelect('rev.status', 'status') doesn't join attachments explicitly but maybe relation exists?
// Wait, checking Entity... CorrespondenceRevision does NOT have attachments relation in code snippet provided earlier.
// It might be in 'details' JSON or implied.
// Just Alert for now as per previous logic.
alert('ไม่พบไฟล์แนบ (No file attached)');
}
}}
>
<FileText className="h-4 w-4" />
</Button>
{statusCode === 'DRAFT' && (
<Link href={`/correspondences/${docUuid}/edit`}>
<Button variant="ghost" size="icon" title="Edit">
@@ -0,0 +1,215 @@
'use client';
import { useState } from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2, Search, X, Link2, ExternalLink } from 'lucide-react';
import Link from 'next/link';
import {
useReferences,
useAddReference,
useRemoveReference,
useCorrespondences,
} from '@/hooks/use-correspondence';
interface LinkedDoc {
uuid: string;
correspondenceNumber: string;
}
interface RefItem {
source?: LinkedDoc;
target?: LinkedDoc;
}
interface CorrespondenceRevisionItem {
subject: string;
correspondence?: { uuid: string; correspondenceNumber: string };
}
interface ReferenceSelectorProps {
uuid: string;
canEdit: boolean;
}
export function ReferenceSelector({ uuid, canEdit }: ReferenceSelectorProps) {
const [searchQuery, setSearchQuery] = useState('');
const [isSearching, setIsSearching] = useState(false);
const { data: referencesData, isLoading: isLoadingRefs } = useReferences(uuid);
const addMutation = useAddReference();
const removeMutation = useRemoveReference();
const { data: searchResults, isFetching: isSearchFetching } = useCorrespondences(
isSearching && searchQuery.trim().length >= 2
? { search: searchQuery.trim(), limit: 8 }
: { search: '', limit: 0 }
);
const outgoing: RefItem[] = referencesData?.outgoing ?? [];
const incoming: RefItem[] = referencesData?.incoming ?? [];
const totalCount = outgoing.length + incoming.length;
const searchItems = Array.isArray(searchResults?.data)
? searchResults.data
: [];
const existingRefUuids = new Set([
...outgoing.map((r) => r.target?.uuid).filter(Boolean),
...incoming.map((r) => r.source?.uuid).filter(Boolean),
]);
const handleAdd = (targetUuid: string) => {
addMutation.mutate({ uuid, targetUuid });
setIsSearching(false);
setSearchQuery('');
};
const handleRemove = (targetUuid: string) => {
removeMutation.mutate({ uuid, targetUuid });
};
const renderRef = (linked: LinkedDoc, direction: 'out' | 'in') => (
<div
key={linked.uuid}
className="flex items-center justify-between gap-2 p-2 bg-muted/40 rounded-md text-sm"
>
<div className="flex items-center gap-2 min-w-0">
<span className={`text-[10px] font-semibold px-1 py-0.5 rounded shrink-0 ${direction === 'out' ? 'bg-blue-100 text-blue-700' : 'bg-green-100 text-green-700'}`}>
{direction === 'out' ? 'REF' : 'FROM'}
</span>
<Link
href={`/correspondences/${linked.uuid}`}
className="font-mono font-medium hover:underline truncate text-xs"
>
{linked.correspondenceNumber}
</Link>
</div>
<div className="flex items-center gap-1 shrink-0">
<Link href={`/correspondences/${linked.uuid}`} target="_blank">
<Button variant="ghost" size="icon" className="h-6 w-6">
<ExternalLink className="h-3 w-3" />
</Button>
</Link>
{canEdit && direction === 'out' && (
<Button
variant="ghost"
size="icon"
className="h-6 w-6 text-muted-foreground hover:text-destructive"
onClick={() => handleRemove(linked.uuid)}
disabled={removeMutation.isPending}
>
<X className="h-3 w-3" />
</Button>
)}
</div>
</div>
);
return (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center gap-2">
<Link2 className="h-4 w-4" />
Referenced Documents
{totalCount > 0 && (
<Badge variant="secondary" className="ml-auto text-xs">
{totalCount}
</Badge>
)}
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{isLoadingRefs ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" />
Loading references...
</div>
) : totalCount === 0 ? (
<p className="text-sm text-muted-foreground">No referenced documents</p>
) : (
<div className="space-y-2">
{outgoing.map((r) => r.target && renderRef(r.target, 'out'))}
{incoming.map((r) => r.source && renderRef(r.source, 'in'))}
</div>
)}
{canEdit && (
<div className="pt-2 border-t space-y-2">
{isSearching ? (
<>
<div className="flex gap-2">
<div className="relative flex-1">
<Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
<Input
autoFocus
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search by number or subject..."
className="pl-7 h-8 text-sm"
/>
</div>
<Button
variant="ghost"
size="sm"
className="h-8"
onClick={() => { setIsSearching(false); setSearchQuery(''); }}
>
Cancel
</Button>
</div>
{searchQuery.trim().length >= 2 && (
<div className="border rounded-md divide-y max-h-48 overflow-y-auto">
{isSearchFetching ? (
<div className="flex items-center gap-2 p-3 text-sm text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" />
Searching...
</div>
) : searchItems.length === 0 ? (
<p className="p-3 text-sm text-muted-foreground">No results found</p>
) : (
searchItems
.filter((item: CorrespondenceRevisionItem) => {
const itemUuid = item.correspondence?.uuid;
return itemUuid && itemUuid !== uuid && !existingRefUuids.has(itemUuid);
})
.map((item: CorrespondenceRevisionItem) => (
<button
key={item.correspondence?.uuid}
className="w-full flex items-center justify-between gap-2 p-2.5 text-sm hover:bg-muted/60 transition-colors text-left"
onClick={() => handleAdd(item.correspondence!.uuid)}
disabled={addMutation.isPending}
>
<span className="font-mono font-medium text-xs">
{item.correspondence?.correspondenceNumber}
</span>
<span className="text-muted-foreground truncate flex-1 ml-2">
{item.subject}
</span>
</button>
))
)}
</div>
)}
</>
) : (
<Button
variant="outline"
size="sm"
className="w-full h-8 text-xs"
onClick={() => setIsSearching(true)}
>
<Search className="h-3 w-3 mr-1.5" />
Add Reference Document
</Button>
)}
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,99 @@
'use client';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { History, CheckCircle2 } from 'lucide-react';
import { CorrespondenceRevision } from '@/types/correspondence';
import { format } from 'date-fns';
interface RevisionHistoryProps {
revisions: CorrespondenceRevision[];
}
const STATUS_CLASS: Record<string, string> = {
DRAFT: 'bg-gray-100 text-gray-700',
SUBOWN: 'bg-yellow-100 text-yellow-700',
CLBOWN: 'bg-green-100 text-green-700',
CCBOWN: 'bg-red-100 text-red-700',
CANCELLED: 'bg-slate-100 text-slate-500',
};
const STATUS_LABEL: Record<string, string> = {
DRAFT: 'Draft',
SUBOWN: 'Submitted',
CLBOWN: 'Approved',
CCBOWN: 'Rejected',
CANCELLED: 'Cancelled',
};
export function RevisionHistory({ revisions }: RevisionHistoryProps) {
if (!revisions || revisions.length === 0) return null;
const sorted = [...revisions].sort((a, b) => b.revisionNumber - a.revisionNumber);
return (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center gap-2">
<History className="h-4 w-4" />
Revision History
<Badge variant="secondary" className="ml-auto text-xs">
{revisions.length}
</Badge>
</CardTitle>
</CardHeader>
<CardContent>
<div className="relative">
<div className="absolute left-3 top-0 bottom-0 w-px bg-border" />
<div className="space-y-4">
{sorted.map((rev) => {
const statusCode = rev.status?.statusCode ?? '';
const statusLabel = STATUS_LABEL[statusCode] ?? statusCode;
const statusClass = STATUS_CLASS[statusCode] ?? 'bg-gray-100 text-gray-700';
const isCurrent = rev.isCurrent;
return (
<div key={rev.uuid ?? rev.revisionNumber} className="flex gap-3 pl-7 relative">
<div
className={`absolute left-1.5 top-1 w-3 h-3 rounded-full border-2 ${
isCurrent
? 'bg-primary border-primary'
: 'bg-background border-muted-foreground/40'
}`}
/>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-xs font-semibold">
Rev. {rev.revisionLabel ?? String(rev.revisionNumber).padStart(2, '0')}
</span>
{isCurrent && (
<CheckCircle2 className="h-3 w-3 text-primary shrink-0" />
)}
<Badge className={`text-xs px-1.5 py-0 border-0 ${statusClass}`}>
{statusLabel}
</Badge>
</div>
<p className="text-sm mt-0.5 line-clamp-1">{rev.subject}</p>
<p className="text-xs text-muted-foreground mt-0.5">
{format(new Date(rev.createdAt), 'dd MMM yyyy, HH:mm')}
</p>
{rev.remarks && (
<p className="text-xs text-muted-foreground italic mt-0.5 line-clamp-1">
{rev.remarks}
</p>
)}
</div>
</div>
);
})}
</div>
</div>
</CardContent>
</Card>
);
}
@@ -0,0 +1,153 @@
'use client';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2, Tag as TagIcon, X, Plus, ChevronDown } from 'lucide-react';
import { useCorrespondenceTags, useAddTag, useRemoveTag } from '@/hooks/use-correspondence';
import { useQuery } from '@tanstack/react-query';
import { masterDataService } from '@/lib/services/master-data.service';
import { Tag } from '@/types/master-data';
interface TagManagerProps {
uuid: string;
canEdit: boolean;
}
export function TagManager({ uuid, canEdit }: TagManagerProps) {
const [isOpen, setIsOpen] = useState(false);
const { data: assignedRaw, isLoading } = useCorrespondenceTags(uuid);
const { data: allTagsRaw } = useQuery({
queryKey: ['master', 'tags'],
queryFn: () => masterDataService.getTags(),
enabled: isOpen,
});
const addMutation = useAddTag();
const removeMutation = useRemoveTag();
const assigned: Tag[] = Array.isArray(assignedRaw) ? (assignedRaw as Tag[]) : [];
const allTags: Tag[] = Array.isArray(allTagsRaw) ? (allTagsRaw as Tag[]) : [];
const assignedIds = new Set(assigned.map((t) => t.id));
const available = allTags.filter((t) => !assignedIds.has(t.id));
const handleAdd = (tagId: number) => {
addMutation.mutate({ uuid, tagId });
};
const handleRemove = (tagId: number) => {
removeMutation.mutate({ uuid, tagId });
};
const getTagColor = (color?: string) => {
if (!color || color === 'default') return '#e2e8f0';
return color;
};
return (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center gap-2">
<TagIcon className="h-4 w-4" />
Tags
{assigned.length > 0 && (
<Badge variant="secondary" className="ml-auto text-xs">
{assigned.length}
</Badge>
)}
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{isLoading ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" />
Loading tags...
</div>
) : assigned.length === 0 ? (
<p className="text-sm text-muted-foreground">No tags assigned</p>
) : (
<div className="flex flex-wrap gap-1.5">
{assigned.map((tag) => (
<span
key={tag.id}
className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border"
style={{
backgroundColor: `${getTagColor(tag.color_code)}22`,
borderColor: `${getTagColor(tag.color_code)}66`,
color: getTagColor(tag.color_code) === '#e2e8f0' ? 'inherit' : getTagColor(tag.color_code),
}}
>
<span
className="w-1.5 h-1.5 rounded-full shrink-0"
style={{ backgroundColor: getTagColor(tag.color_code) }}
/>
{tag.tag_name}
{canEdit && (
<button
onClick={() => handleRemove(tag.id)}
disabled={removeMutation.isPending}
className="ml-0.5 opacity-60 hover:opacity-100 transition-opacity"
>
<X className="h-2.5 w-2.5" />
</button>
)}
</span>
))}
</div>
)}
{canEdit && (
<div className="pt-2 border-t">
{isOpen ? (
<div className="space-y-2">
<div className="max-h-40 overflow-y-auto border rounded-md divide-y">
{available.length === 0 ? (
<p className="p-2 text-xs text-muted-foreground text-center">
{allTags.length === 0 ? 'Loading...' : 'All tags already assigned'}
</p>
) : (
available.map((tag) => (
<button
key={tag.id}
className="w-full flex items-center gap-2 p-2 text-xs hover:bg-muted/60 transition-colors text-left"
onClick={() => { handleAdd(tag.id); setIsOpen(false); }}
disabled={addMutation.isPending}
>
<span
className="w-2 h-2 rounded-full shrink-0"
style={{ backgroundColor: getTagColor(tag.color_code) }}
/>
{tag.tag_name}
</button>
))
)}
</div>
<Button
variant="ghost"
size="sm"
className="w-full h-7 text-xs"
onClick={() => setIsOpen(false)}
>
<ChevronDown className="h-3 w-3 mr-1" />
Close
</Button>
</div>
) : (
<Button
variant="outline"
size="sm"
className="w-full h-8 text-xs"
onClick={() => setIsOpen(true)}
>
<Plus className="h-3 w-3 mr-1.5" />
Add Tag
</Button>
)}
</div>
)}
</CardContent>
</Card>
);
}