feat(rfa): complete RFA Approval Refactor - all 9 phases (T001-T080)

Phase 1-2: Setup, SQL schema, enums, queue constants, base entities
Phase 3 (US1): ReviewTeam, ReviewTeamMember, ReviewTask, TaskCreationService
Phase 4 (US2): ResponseCode, ResponseCodeRule, ImplicationsService, NotificationTriggerService
Phase 5 (US3): Delegation entity, CircularDetectionService, DelegationService/Controller/Module
Phase 6 (US4): ReminderRule, SchedulerService, EscalationService, ReminderProcessor, ReminderModule
Phase 7 (US5): DistributionMatrix, DistributionRecipient, ApprovalListenerService (Strangler),
               TransmittalCreatorService, DistributionProcessor, DistributionModule
Phase 8 (US6): MatrixManagementService, InheritanceService (global→project override)
Phase 9 (Polish): AggregateStatusService, ConsensusService, VetoOverrideService,
                  ParallelGatewayHandler, review-validators, optimistic locking in completeReview,
                  test stubs (unit/integration/e2e), jest.config.js updated for tests/ directory

Frontend: ReviewTaskInbox, ParallelProgress, VetoOverrideDialog, DelegationForm,
          DelegatedBadge, MatrixEditor, ProjectOverrideManager, DistributionStatus,
          ReminderHistory, ResponseCodeSelector, CodeImplications, CompleteReviewForm,
          ReviewTeamForm, ReviewTeamSelector, TeamMemberManager

Closes #1
This commit is contained in:
Nattanin
2026-05-12 16:17:27 +07:00
parent 3df8707b7f
commit ef20839f99
82 changed files with 7052 additions and 104 deletions
@@ -0,0 +1,178 @@
'use client';
// File: components/delegation/DelegationForm.tsx
// Form สร้าง Delegation พร้อม date range picker (FR-011)
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { CreateDelegationDto } from '@/hooks/use-delegation';
import { DelegationScope } from '@/types/review-team';
const delegationSchema = z
.object({
delegateUserPublicId: z.string().uuid('Select a valid user'),
scope: z.enum(['ALL', 'RFA_ONLY', 'CORRESPONDENCE_ONLY', 'SPECIFIC_TYPES'] as const),
startDate: z.string().min(1, 'Start date is required'),
endDate: z.string().min(1, 'End date is required'),
reason: z.string().max(500).optional(),
})
.refine((d: { startDate: string; endDate: string }) => new Date(d.startDate) < new Date(d.endDate), {
message: 'End date must be after start date',
path: ['endDate'],
});
type DelegationFormValues = z.infer<typeof delegationSchema>;
interface User {
publicId: string;
fullName?: string;
email?: string;
}
interface DelegationFormProps {
availableUsers: User[];
onSubmit: (dto: CreateDelegationDto) => void;
isLoading?: boolean;
}
const SCOPE_LABELS: Record<DelegationScope, string> = {
ALL: 'All Documents',
RFA_ONLY: 'RFA Only',
CORRESPONDENCE_ONLY: 'Correspondence Only',
SPECIFIC_TYPES: 'Specific Document Types',
};
export function DelegationForm({ availableUsers, onSubmit, isLoading }: DelegationFormProps) {
const form = useForm<DelegationFormValues>({
resolver: zodResolver(delegationSchema),
defaultValues: { scope: 'ALL' },
});
const handleSubmit = (values: DelegationFormValues) => {
onSubmit({
...values,
scope: values.scope as DelegationScope,
});
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
<FormField
control={form.control}
name="delegateUserPublicId"
render={({ field }) => (
<FormItem>
<FormLabel>Delegate To</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select user to delegate..." />
</SelectTrigger>
<SelectContent>
{availableUsers.map((u) => (
<SelectItem key={u.publicId} value={u.publicId}>
{u.fullName ?? u.email}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="scope"
render={({ field }) => (
<FormItem>
<FormLabel>Scope</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{(Object.keys(SCOPE_LABELS) as DelegationScope[]).map((s) => (
<SelectItem key={s} value={s}>
{SCOPE_LABELS[s]}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-2 gap-3">
<FormField
control={form.control}
name="startDate"
render={({ field }) => (
<FormItem>
<FormLabel>Start Date</FormLabel>
<FormControl>
<Input type="date" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="endDate"
render={({ field }) => (
<FormItem>
<FormLabel>End Date</FormLabel>
<FormControl>
<Input type="date" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="reason"
render={({ field }) => (
<FormItem>
<FormLabel>Reason (Optional)</FormLabel>
<FormControl>
<Textarea placeholder="e.g. Annual leave 12-18 May" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? 'Creating...' : 'Create Delegation'}
</Button>
</form>
</Form>
);
}
@@ -0,0 +1,87 @@
'use client';
// File: components/distribution/DistributionStatus.tsx
// แสดงสถานะ Distribution ของ RFA หลังอนุมัติ (T060)
import React from 'react';
import { CheckCircle2, Clock, SendHorizonal, Users } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
type DistributionStatus = 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'FAILED';
interface DistributionRecord {
publicId: string;
status: DistributionStatus;
transmittalCount: number;
recipientCount: number;
processedAt?: string;
error?: string;
}
interface DistributionStatusProps {
rfaPublicId: string;
distribution?: DistributionRecord;
isLoading?: boolean;
}
const STATUS_CONFIG: Record<
DistributionStatus,
{ label: string; variant: 'default' | 'secondary' | 'destructive' | 'outline'; icon: React.ElementType }
> = {
PENDING: { label: 'Queued', variant: 'outline', icon: Clock },
PROCESSING: { label: 'Processing', variant: 'secondary', icon: Clock },
COMPLETED: { label: 'Distributed', variant: 'default', icon: CheckCircle2 },
FAILED: { label: 'Failed', variant: 'destructive', icon: Clock },
};
export function DistributionStatus({ rfaPublicId: _rfaPublicId, distribution, isLoading }: DistributionStatusProps) {
if (isLoading) {
return <div className="text-sm text-muted-foreground">Checking distribution status...</div>;
}
if (!distribution) {
return (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Clock className="h-4 w-4" />
<span>Awaiting approval for distribution</span>
</div>
);
}
const config = STATUS_CONFIG[distribution.status];
const Icon = config.icon;
return (
<Card>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<CardTitle className="text-sm font-medium">Distribution Status</CardTitle>
<Badge variant={config.variant} className="gap-1">
<Icon className="h-3 w-3" />
{config.label}
</Badge>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="flex items-center gap-4 text-sm">
<div className="flex items-center gap-1 text-muted-foreground">
<SendHorizonal className="h-3.5 w-3.5" />
<span>{distribution.transmittalCount} Transmittal(s)</span>
</div>
<div className="flex items-center gap-1 text-muted-foreground">
<Users className="h-3.5 w-3.5" />
<span>{distribution.recipientCount} Recipient(s)</span>
</div>
{distribution.processedAt && (
<span className="text-xs text-muted-foreground">
{new Date(distribution.processedAt).toLocaleDateString('th-TH')}
</span>
)}
</div>
{distribution.error && (
<p className="mt-1 text-xs text-destructive">{distribution.error}</p>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,84 @@
'use client';
// File: components/reminder/ReminderHistory.tsx
// แสดงประวัติ Reminder และ Escalation ของ Review Task (T050)
import React from 'react';
import { Badge } from '@/components/ui/badge';
import { Clock, AlertTriangle, Bell } from 'lucide-react';
type ReminderType = 'DUE_SOON' | 'ON_DUE' | 'OVERDUE' | 'ESCALATION_L1' | 'ESCALATION_L2';
interface ReminderEntry {
id: string;
type: ReminderType;
sentAt: string;
recipient?: string;
isDelivered?: boolean;
}
interface ReminderHistoryProps {
reminders: ReminderEntry[];
isLoading?: boolean;
}
const TYPE_CONFIG: Record<
ReminderType,
{ label: string; icon: React.ElementType; variant: 'default' | 'secondary' | 'destructive' | 'outline' }
> = {
DUE_SOON: { label: 'Due Soon', icon: Clock, variant: 'outline' },
ON_DUE: { label: 'Due Today', icon: Bell, variant: 'secondary' },
OVERDUE: { label: 'Overdue', icon: AlertTriangle, variant: 'destructive' },
ESCALATION_L1: { label: 'Escalation L1', icon: AlertTriangle, variant: 'destructive' },
ESCALATION_L2: { label: 'Escalation L2 (PM)', icon: AlertTriangle, variant: 'destructive' },
};
export function ReminderHistory({ reminders, isLoading }: ReminderHistoryProps) {
if (isLoading) {
return <div className="text-sm text-muted-foreground">Loading reminder history...</div>;
}
if (reminders.length === 0) {
return <div className="text-sm text-muted-foreground">No reminders sent yet.</div>;
}
return (
<div className="space-y-2">
{reminders.map((entry) => {
const config = TYPE_CONFIG[entry.type];
const Icon = config.icon;
return (
<div
key={entry.id}
className="flex items-center justify-between py-1.5 border-b last:border-0"
>
<div className="flex items-center gap-2">
<Icon className="h-3.5 w-3.5 text-muted-foreground flex-shrink-0" />
<Badge variant={config.variant} className="text-xs">
{config.label}
</Badge>
{entry.recipient && (
<span className="text-xs text-muted-foreground"> {entry.recipient}</span>
)}
</div>
<div className="flex items-center gap-2">
{entry.isDelivered !== undefined && (
<span className={`text-xs ${entry.isDelivered ? 'text-green-600' : 'text-orange-500'}`}>
{entry.isDelivered ? '✓ Delivered' : '⏳ Pending'}
</span>
)}
<span className="text-xs text-muted-foreground">
{new Date(entry.sentAt).toLocaleDateString('th-TH', {
day: '2-digit',
month: 'short',
hour: '2-digit',
minute: '2-digit',
})}
</span>
</div>
</div>
);
})}
</div>
);
}
@@ -0,0 +1,82 @@
'use client';
// File: components/response-code/CodeImplications.tsx
// แสดงผลกระทบของ Response Code ที่เลือก (FR-007)
import { AlertTriangle, Clock, DollarSign, FileText, Leaf } from 'lucide-react';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { ResponseCode } from '@/types/review-team';
interface CodeImplicationsProps {
responseCode: ResponseCode;
}
const SEVERITY_VARIANTS = {
'3': { variant: 'destructive' as const, label: 'Critical — Document Rejected' },
'1C': { variant: 'default' as const, label: 'High — Contract Implications' },
'1D': { variant: 'default' as const, label: 'High — Alternative Approved' },
'2': { variant: 'default' as const, label: 'Moderate — Revision Required' },
};
export function CodeImplications({ responseCode }: CodeImplicationsProps) {
const impl = responseCode.implications;
const notifyRoles = responseCode.notifyRoles ?? [];
const hasImplications =
impl?.affectsSchedule ||
impl?.affectsCost ||
impl?.requiresContractReview ||
impl?.requiresEiaAmendment ||
notifyRoles.length > 0;
if (!hasImplications) return null;
const severityInfo = SEVERITY_VARIANTS[responseCode.code as keyof typeof SEVERITY_VARIANTS];
return (
<Alert variant={severityInfo?.variant ?? 'default'} className="mt-2">
<AlertTriangle className="h-4 w-4" />
<AlertTitle className="font-semibold">
{severityInfo?.label ?? 'Action Required'}
</AlertTitle>
<AlertDescription>
<div className="space-y-1 mt-1">
{impl?.affectsSchedule && (
<div className="flex items-center gap-2 text-sm">
<Clock className="h-3.5 w-3.5 flex-shrink-0" />
<span>May affect project schedule</span>
</div>
)}
{impl?.affectsCost && (
<div className="flex items-center gap-2 text-sm">
<DollarSign className="h-3.5 w-3.5 flex-shrink-0" />
<span>Cost impact QS assessment required</span>
</div>
)}
{impl?.requiresContractReview && (
<div className="flex items-center gap-2 text-sm">
<FileText className="h-3.5 w-3.5 flex-shrink-0" />
<span>Contract review required</span>
</div>
)}
{impl?.requiresEiaAmendment && (
<div className="flex items-center gap-2 text-sm">
<Leaf className="h-3.5 w-3.5 flex-shrink-0" />
<span>EIA amendment may be required</span>
</div>
)}
{notifyRoles.length > 0 && (
<div className="flex items-center gap-1 flex-wrap mt-1">
<span className="text-xs text-muted-foreground">Will notify:</span>
{notifyRoles.map((role) => (
<Badge key={role} variant="outline" className="text-xs">
{role.replace(/_/g, ' ')}
</Badge>
))}
</div>
)}
</div>
</AlertDescription>
</Alert>
);
}
@@ -0,0 +1,163 @@
'use client';
// File: components/response-code/MatrixEditor.tsx
// Visual editor สำหรับ Master Approval Matrix (T064, FR-022)
import React, { useState } from 'react';
import { Check, X, AlertTriangle, Lock } from 'lucide-react';
import { Switch } from '@/components/ui/switch';
import { Badge } from '@/components/ui/badge';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
interface MatrixRule {
publicId: string;
responseCode: {
publicId: string;
code: string;
descriptionEn: string;
category: string;
};
isEnabled: boolean;
requiresComments: boolean;
triggersNotification: boolean;
isOverridden: boolean;
isSystem?: boolean;
}
interface MatrixEditorProps {
documentTypeCode: string;
rules: MatrixRule[];
isProjectLevel?: boolean;
onToggleEnabled: (rulePublicId: string, enabled: boolean) => void;
onToggleRequiresComments: (rulePublicId: string, value: boolean) => void;
onToggleNotification: (rulePublicId: string, value: boolean) => void;
isLoading?: boolean;
}
const CATEGORY_ORDER = ['ENGINEERING', 'MATERIAL', 'CONTRACT', 'TESTING', 'ESG'];
export function MatrixEditor({
documentTypeCode,
rules,
isProjectLevel = false,
onToggleEnabled,
onToggleRequiresComments,
onToggleNotification,
isLoading,
}: MatrixEditorProps) {
const [filter, setFilter] = useState<string>('ALL');
const grouped = CATEGORY_ORDER.reduce<Record<string, MatrixRule[]>>((acc, cat) => {
const catRules = rules.filter(
(r) => r.responseCode.category === cat && (filter === 'ALL' || r.responseCode.category === filter),
);
if (catRules.length > 0) acc[cat] = catRules;
return acc;
}, {});
return (
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base">
Matrix: {documentTypeCode}
{isProjectLevel && (
<Badge variant="secondary" className="ml-2 text-xs">Project Override</Badge>
)}
</CardTitle>
<select
value={filter}
onChange={(e: React.ChangeEvent<HTMLSelectElement>) => setFilter(e.target.value)}
className="text-sm border rounded px-2 py-1"
>
<option value="ALL">All Categories</option>
{CATEGORY_ORDER.map((c) => (
<option key={c} value={c}>{c}</option>
))}
</select>
</div>
</CardHeader>
<CardContent className="pt-0">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-16">Code</TableHead>
<TableHead>Description</TableHead>
<TableHead className="w-24 text-center">Enabled</TableHead>
<TableHead className="w-28 text-center">Req. Comments</TableHead>
<TableHead className="w-28 text-center">Notify</TableHead>
<TableHead className="w-20 text-center">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{Object.entries(grouped).map(([cat, catRules]) => (
<React.Fragment key={cat}>
<TableRow className="bg-muted/30">
<TableCell colSpan={6} className="py-1 text-xs font-semibold text-muted-foreground uppercase tracking-wide">
{cat}
</TableCell>
</TableRow>
{catRules.map((rule) => (
<TableRow key={rule.publicId} className={!rule.isEnabled ? 'opacity-50' : ''}>
<TableCell>
<span className="font-mono text-sm font-bold">{rule.responseCode.code}</span>
</TableCell>
<TableCell className="text-sm">{rule.responseCode.descriptionEn}</TableCell>
<TableCell className="text-center">
{rule.isSystem ? (
<Lock className="h-4 w-4 mx-auto text-muted-foreground" />
) : (
<Switch
checked={rule.isEnabled}
onCheckedChange={(v: boolean) => onToggleEnabled(rule.publicId, v)}
disabled={isLoading}
/>
)}
</TableCell>
<TableCell className="text-center">
<Switch
checked={rule.requiresComments}
onCheckedChange={(v: boolean) => onToggleRequiresComments(rule.publicId, v)}
disabled={isLoading || !rule.isEnabled}
/>
</TableCell>
<TableCell className="text-center">
<Switch
checked={rule.triggersNotification}
onCheckedChange={(v: boolean) => onToggleNotification(rule.publicId, v)}
disabled={isLoading || !rule.isEnabled}
/>
</TableCell>
<TableCell className="text-center">
{rule.isOverridden ? (
<AlertTriangle className="h-4 w-4 mx-auto text-amber-500" />
) : rule.isEnabled ? (
<Check className="h-4 w-4 mx-auto text-green-500" />
) : (
<X className="h-4 w-4 mx-auto text-muted-foreground" />
)}
</TableCell>
</TableRow>
))}
</React.Fragment>
))}
{Object.keys(grouped).length === 0 && (
<TableRow>
<TableCell colSpan={6} className="text-center text-muted-foreground py-6">
No rules configured for this document type.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</CardContent>
</Card>
);
}
@@ -0,0 +1,156 @@
'use client';
// File: components/response-code/ProjectOverrideManager.tsx
// จัดการ project-specific overrides ของ Master Approval Matrix (T065)
import React, { useState } from 'react';
import { Plus, Trash2, ArrowDownToLine } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
interface OverrideRule {
publicId: string;
responseCode: {
code: string;
descriptionEn: string;
category: string;
};
documentTypeCode: string;
isEnabled: boolean;
requiresComments: boolean;
triggersNotification: boolean;
}
interface ProjectOverrideManagerProps {
projectPublicId: string;
projectName: string;
overrides: OverrideRule[];
onDeleteOverride: (rulePublicId: string) => void;
onAddOverride: () => void;
isLoading?: boolean;
}
export function ProjectOverrideManager({
projectPublicId: _projectPublicId,
projectName,
overrides,
onDeleteOverride,
onAddOverride,
isLoading,
}: ProjectOverrideManagerProps) {
const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
const grouped = overrides.reduce<Record<string, OverrideRule[]>>((acc, rule) => {
const key = rule.documentTypeCode;
if (!acc[key]) acc[key] = [];
acc[key].push(rule);
return acc;
}, {});
return (
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-base">{projectName}</CardTitle>
<p className="text-xs text-muted-foreground mt-0.5">
{overrides.length} project-specific override(s)
</p>
</div>
<Button size="sm" onClick={onAddOverride} disabled={isLoading}>
<Plus className="h-4 w-4 mr-1" />
Add Override
</Button>
</div>
</CardHeader>
<CardContent className="pt-0">
{overrides.length === 0 ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground py-4">
<ArrowDownToLine className="h-4 w-4" />
<span>Inheriting all rules from global defaults</span>
</div>
) : (
<div className="space-y-4">
{Object.entries(grouped).map(([docType, rules]) => (
<div key={docType}>
<p className="text-xs font-semibold text-muted-foreground uppercase mb-2">
{docType}
</p>
<div className="space-y-1.5">
{rules.map((rule) => (
<div
key={rule.publicId}
className="flex items-center justify-between py-1.5 px-2 rounded bg-muted/40"
>
<div className="flex items-center gap-2">
<span className="font-mono text-xs font-bold">
{rule.responseCode.code}
</span>
<span className="text-sm">{rule.responseCode.descriptionEn}</span>
<Badge variant={rule.isEnabled ? 'default' : 'outline'} className="text-xs">
{rule.isEnabled ? 'Enabled' : 'Disabled'}
</Badge>
{rule.requiresComments && (
<Badge variant="secondary" className="text-xs">Req. Comments</Badge>
)}
</div>
<AlertDialog
open={confirmDelete === rule.publicId}
onOpenChange={(open: boolean) => !open && setConfirmDelete(null)}
>
<AlertDialogTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => setConfirmDelete(rule.publicId)}
>
<Trash2 className="h-3.5 w-3.5 text-destructive" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove Override?</AlertDialogTitle>
<AlertDialogDescription>
This will revert code <strong>{rule.responseCode.code}</strong> to the
global default settings for this project.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
onDeleteOverride(rule.publicId);
setConfirmDelete(null);
}}
>
Remove Override
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
))}
</div>
<Separator className="mt-3" />
</div>
))}
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,102 @@
'use client';
// File: components/response-code/ResponseCodeSelector.tsx
// เลือก Response Code ตาม Category ของเอกสาร (FR-006)
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { useResponseCodesByDocType } from '@/hooks/use-response-codes';
import { ResponseCode } from '@/types/review-team';
interface ResponseCodeSelectorProps {
documentTypeId: number;
projectId?: number;
value?: string;
onChange: (publicId: string) => void;
disabled?: boolean;
placeholder?: string;
}
const SEVERITY_COLORS: Record<string, string> = {
'1A': 'bg-green-100 text-green-800',
'1B': 'bg-emerald-100 text-emerald-800',
'1C': 'bg-yellow-100 text-yellow-800',
'1D': 'bg-orange-100 text-orange-800',
'1E': 'bg-blue-100 text-blue-800',
'1F': 'bg-sky-100 text-sky-800',
'1G': 'bg-purple-100 text-purple-800',
'2': 'bg-amber-100 text-amber-800',
'3': 'bg-red-100 text-red-800',
'4': 'bg-gray-100 text-gray-600',
};
function CodeBadge({ code }: { code: string }) {
const colorClass = SEVERITY_COLORS[code] ?? 'bg-gray-100 text-gray-600';
return (
<span className={`inline-flex items-center rounded px-1.5 py-0.5 text-xs font-bold ${colorClass}`}>
{code}
</span>
);
}
export function ResponseCodeSelector({
documentTypeId,
projectId,
value,
onChange,
disabled,
placeholder = 'Select Response Code...',
}: ResponseCodeSelectorProps) {
const { data: codes = [], isLoading } = useResponseCodesByDocType(documentTypeId, projectId);
// กลุ่ม codes ตาม category
const grouped = (codes as ResponseCode[]).reduce<Record<string, ResponseCode[]>>(
(acc, code) => {
const cat = code.category;
if (!acc[cat]) acc[cat] = [];
acc[cat].push(code);
return acc;
},
{},
);
const categories = Object.keys(grouped);
return (
<Select value={value ?? ''} onValueChange={onChange} disabled={disabled || isLoading}>
<SelectTrigger>
<SelectValue placeholder={isLoading ? 'Loading codes...' : placeholder} />
</SelectTrigger>
<SelectContent>
{categories.length === 0 && !isLoading && (
<div className="p-3 text-sm text-muted-foreground">No codes available</div>
)}
{categories.map((cat) => (
<SelectGroup key={cat}>
<SelectLabel className="text-xs text-muted-foreground uppercase tracking-wide">
{cat}
</SelectLabel>
{grouped[cat].map((code) => (
<SelectItem key={code.publicId} value={code.publicId}>
<div className="flex items-center gap-2">
<CodeBadge code={code.code} />
<span className="text-sm">{code.descriptionEn}</span>
{(code.implications?.affectsCost || code.implications?.requiresContractReview) && (
<span className="text-xs text-orange-600 font-medium"> Action Required</span>
)}
</div>
</SelectItem>
))}
</SelectGroup>
))}
</SelectContent>
</Select>
);
}
@@ -0,0 +1,113 @@
'use client';
// File: components/review-task/CompleteReviewForm.tsx
// Form สำหรับบันทึกผล Review Task (FR-009) — Response Code + Comments
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { ResponseCodeSelector } from '@/components/response-code/ResponseCodeSelector';
import { CodeImplications } from '@/components/response-code/CodeImplications';
import { useResponseCodes } from '@/hooks/use-response-codes';
import { ResponseCode } from '@/types/review-team';
import { useState } from 'react';
const completeReviewSchema = z.object({
responseCodePublicId: z.string().uuid('Response Code is required'),
comments: z.string().optional(),
});
type CompleteReviewFormValues = z.infer<typeof completeReviewSchema>;
interface CompleteReviewFormProps {
taskPublicId: string;
documentTypeId: number;
projectId?: number;
onSubmit: (values: CompleteReviewFormValues) => void;
isLoading?: boolean;
}
export function CompleteReviewForm({
taskPublicId: _taskPublicId,
documentTypeId,
projectId,
onSubmit,
isLoading,
}: CompleteReviewFormProps) {
const [selectedCode, setSelectedCode] = useState<ResponseCode | null>(null);
const { data: allCodes = [] } = useResponseCodes();
const form = useForm<CompleteReviewFormValues>({
resolver: zodResolver(completeReviewSchema),
});
const handleCodeChange = (publicId: string) => {
form.setValue('responseCodePublicId', publicId);
const found = (allCodes as ResponseCode[]).find((c) => c.publicId === publicId) ?? null;
setSelectedCode(found);
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="responseCodePublicId"
render={() => (
<FormItem>
<FormLabel>Response Code</FormLabel>
<FormControl>
<ResponseCodeSelector
documentTypeId={documentTypeId}
projectId={projectId}
value={form.watch('responseCodePublicId')}
onChange={handleCodeChange}
disabled={isLoading}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{selectedCode && <CodeImplications responseCode={selectedCode} />}
<FormField
control={form.control}
name="comments"
render={({ field }) => (
<FormItem>
<FormLabel>
Comments
{selectedCode?.code === '2' || selectedCode?.code === '3' ? (
<span className="text-destructive ml-1">*</span>
) : null}
</FormLabel>
<FormControl>
<Textarea
placeholder="Enter review comments..."
className="min-h-[80px]"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? 'Submitting...' : 'Submit Review'}
</Button>
</form>
</Form>
);
}
@@ -0,0 +1,39 @@
'use client';
// File: components/review-task/DelegatedBadge.tsx
// แสดง indicator "Delegated from X" บน Review Task (T041)
import { ArrowRightLeft } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from '@/components/ui/hover-card';
interface DelegatedBadgeProps {
delegatedFromUser?: {
publicId: string;
fullName?: string;
email?: string;
};
}
export function DelegatedBadge({ delegatedFromUser }: DelegatedBadgeProps) {
if (!delegatedFromUser) return null;
const displayName = delegatedFromUser.fullName ?? delegatedFromUser.email ?? 'Unknown';
return (
<HoverCard>
<HoverCardTrigger asChild>
<Badge variant="outline" className="gap-1 text-xs text-muted-foreground border-dashed cursor-pointer">
<ArrowRightLeft className="h-3 w-3" />
Delegated
</Badge>
</HoverCardTrigger>
<HoverCardContent className="w-auto p-2">
<p className="text-sm">Delegated from: <strong>{displayName}</strong></p>
</HoverCardContent>
</HoverCard>
);
}
@@ -0,0 +1,92 @@
'use client';
// File: components/review-task/ParallelProgress.tsx
// Parallel review progress indicator แสดงทุก discipline tracks (T072)
import React from 'react';
import { CheckCircle2, Clock, AlertTriangle } from 'lucide-react';
import { Progress } from '@/components/ui/progress';
import { Badge } from '@/components/ui/badge';
type TaskStatus = 'PENDING' | 'IN_PROGRESS' | 'COMPLETED' | 'DELEGATED' | 'EXPIRED' | 'CANCELLED';
interface DisciplineTrack {
disciplineId: string;
disciplineName: string;
taskStatus: TaskStatus;
responseCode?: string;
dueDate?: string;
assigneeName?: string;
}
interface ParallelProgressProps {
tracks: DisciplineTrack[];
overallPct: number;
isAllComplete: boolean;
}
const TRACK_ICON: Record<TaskStatus, React.ElementType> = {
PENDING: Clock,
IN_PROGRESS: Clock,
COMPLETED: CheckCircle2,
DELEGATED: Clock,
EXPIRED: AlertTriangle,
CANCELLED: AlertTriangle,
};
const TRACK_COLOR: Record<TaskStatus, string> = {
PENDING: 'text-muted-foreground',
IN_PROGRESS: 'text-blue-500',
COMPLETED: 'text-green-500',
DELEGATED: 'text-amber-500',
EXPIRED: 'text-destructive',
CANCELLED: 'text-muted-foreground',
};
export function ParallelProgress({ tracks, overallPct, isAllComplete }: ParallelProgressProps) {
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
<span className="text-sm font-medium">Parallel Review Tracks</span>
<div className="flex items-center gap-2">
<span className="text-sm font-semibold">{overallPct}%</span>
{isAllComplete && (
<Badge variant="default" className="text-xs">All Complete</Badge>
)}
</div>
</div>
<Progress value={overallPct} className="h-1.5" />
<div className="space-y-1.5">
{tracks.map((track) => {
const Icon = TRACK_ICON[track.taskStatus];
const colorClass = TRACK_COLOR[track.taskStatus];
return (
<div
key={track.disciplineId}
className="flex items-center justify-between py-1.5 px-2 rounded bg-muted/30"
>
<div className="flex items-center gap-2">
<Icon className={`h-4 w-4 ${colorClass} flex-shrink-0`} />
<div>
<p className="text-sm font-medium">{track.disciplineName}</p>
{track.assigneeName && (
<p className="text-xs text-muted-foreground">{track.assigneeName}</p>
)}
</div>
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
{track.responseCode && (
<span className="font-mono font-bold text-foreground">{track.responseCode}</span>
)}
{track.dueDate && (
<span>{new Date(track.dueDate).toLocaleDateString('th-TH', { day: '2-digit', month: 'short' })}</span>
)}
</div>
</div>
);
})}
</div>
</div>
);
}
@@ -0,0 +1,186 @@
'use client';
// File: components/review-task/ReviewTaskInbox.tsx
// Review Task inbox พร้อม aggregate status indicator (T071)
import React, { useState } from 'react';
import { Clock, CheckCircle2, AlertTriangle, ArrowRightLeft, Users } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { DelegatedBadge } from '@/components/review-task/DelegatedBadge';
type ReviewTaskStatus = 'PENDING' | 'IN_PROGRESS' | 'COMPLETED' | 'DELEGATED' | 'EXPIRED' | 'CANCELLED';
interface ReviewTaskItem {
publicId: string;
status: ReviewTaskStatus;
discipline?: { name: string };
assignedToUser?: { publicId: string; fullName?: string; email?: string };
delegatedFromUser?: { publicId: string; fullName?: string; email?: string };
dueDate?: string;
rfaNumber?: string;
documentTitle?: string;
}
interface AggregateStatus {
total: number;
completed: number;
pending: number;
completionPct: number;
isAllComplete: boolean;
hasExpired: boolean;
}
interface ReviewTaskInboxProps {
tasks: ReviewTaskItem[];
aggregateStatus?: AggregateStatus;
onStartTask: (taskPublicId: string) => void;
onCompleteTask: (taskPublicId: string) => void;
isLoading?: boolean;
}
const STATUS_CONFIG: Record<ReviewTaskStatus, { label: string; variant: 'default' | 'secondary' | 'destructive' | 'outline' }> = {
PENDING: { label: 'Pending', variant: 'outline' },
IN_PROGRESS: { label: 'In Progress', variant: 'secondary' },
COMPLETED: { label: 'Completed', variant: 'default' },
DELEGATED: { label: 'Delegated', variant: 'secondary' },
EXPIRED: { label: 'Expired', variant: 'destructive' },
CANCELLED: { label: 'Cancelled', variant: 'outline' },
};
export function ReviewTaskInbox({
tasks,
aggregateStatus,
onStartTask,
onCompleteTask,
isLoading,
}: ReviewTaskInboxProps) {
const [filter, setFilter] = useState<ReviewTaskStatus | 'ALL'>('ALL');
const filtered = filter === 'ALL' ? tasks : tasks.filter((t) => t.status === filter);
return (
<div className="space-y-4">
{aggregateStatus && (
<Card>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<CardTitle className="text-sm flex items-center gap-2">
<Users className="h-4 w-4" />
Parallel Review Progress
</CardTitle>
<span className="text-sm font-semibold">{aggregateStatus.completionPct}%</span>
</div>
</CardHeader>
<CardContent className="pt-0 space-y-2">
<Progress value={aggregateStatus.completionPct} className="h-2" />
<div className="flex items-center gap-3 text-xs text-muted-foreground">
<span>{aggregateStatus.completed}/{aggregateStatus.total} tasks complete</span>
{aggregateStatus.isAllComplete && (
<Badge variant="default" className="text-xs gap-1">
<CheckCircle2 className="h-3 w-3" /> All Complete
</Badge>
)}
{aggregateStatus.hasExpired && (
<Badge variant="destructive" className="text-xs gap-1">
<AlertTriangle className="h-3 w-3" /> Has Expired
</Badge>
)}
</div>
</CardContent>
</Card>
)}
<div className="flex items-center gap-2">
{(['ALL', 'PENDING', 'IN_PROGRESS', 'COMPLETED'] as const).map((s) => (
<Button
key={s}
variant={filter === s ? 'default' : 'outline'}
size="sm"
onClick={() => setFilter(s)}
>
{s === 'ALL' ? 'All' : STATUS_CONFIG[s]?.label ?? s}
</Button>
))}
</div>
<div className="space-y-2">
{filtered.map((task) => {
const config = STATUS_CONFIG[task.status];
const isOverdue =
task.dueDate && new Date(task.dueDate) < new Date() && task.status !== 'COMPLETED';
return (
<Card key={task.publicId} className={isOverdue ? 'border-destructive/50' : ''}>
<CardContent className="py-3">
<div className="flex items-start justify-between gap-3">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="text-sm font-medium truncate">{task.rfaNumber ?? task.publicId}</span>
<Badge variant={config.variant} className="text-xs">{config.label}</Badge>
{task.delegatedFromUser && (
<DelegatedBadge delegatedFromUser={task.delegatedFromUser} />
)}
{isOverdue && (
<Badge variant="destructive" className="text-xs gap-1">
<AlertTriangle className="h-3 w-3" /> Overdue
</Badge>
)}
</div>
{task.documentTitle && (
<p className="text-xs text-muted-foreground truncate">{task.documentTitle}</p>
)}
<div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
{task.discipline && <span>{task.discipline.name}</span>}
{task.dueDate && (
<span className="flex items-center gap-1">
<Clock className="h-3 w-3" />
{new Date(task.dueDate).toLocaleDateString('th-TH')}
</span>
)}
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
{task.status === 'PENDING' && (
<Button
size="sm"
variant="outline"
onClick={() => onStartTask(task.publicId)}
disabled={isLoading}
>
Start
</Button>
)}
{task.status === 'IN_PROGRESS' && (
<Button
size="sm"
onClick={() => onCompleteTask(task.publicId)}
disabled={isLoading}
>
Complete
</Button>
)}
{task.status === 'COMPLETED' && (
<CheckCircle2 className="h-5 w-5 text-green-500" />
)}
{task.status === 'DELEGATED' && (
<ArrowRightLeft className="h-4 w-4 text-muted-foreground" />
)}
</div>
</div>
</CardContent>
</Card>
);
})}
{filtered.length === 0 && (
<div className="text-center text-muted-foreground py-8">
No review tasks found.
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,101 @@
'use client';
// File: components/review-task/VetoOverrideDialog.tsx
// PM Veto Override dialog — บังคับผ่าน RFA แม้มี Code 3 (T072.5)
import React, { useState } from 'react';
import { AlertTriangle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
interface VetoOverrideDialogProps {
rfaNumber: string;
onConfirm: (reason: string) => void;
isLoading?: boolean;
}
const MIN_REASON_LENGTH = 10;
export function VetoOverrideDialog({ rfaNumber, onConfirm, isLoading }: VetoOverrideDialogProps) {
const [open, setOpen] = useState(false);
const [reason, setReason] = useState('');
const isValid = reason.trim().length >= MIN_REASON_LENGTH;
const handleConfirm = () => {
if (!isValid) return;
onConfirm(reason.trim());
setOpen(false);
setReason('');
};
const handleOpenChange = (next: boolean) => {
if (!next) setReason('');
setOpen(next);
};
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button variant="destructive" size="sm">
<AlertTriangle className="h-4 w-4 mr-1.5" />
PM Override
</Button>
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
PM Veto Override
</DialogTitle>
<DialogDescription>
Override the Code 3 rejection for <strong>{rfaNumber}</strong> and force-approve.
This action will be permanently logged in the audit trail.
</DialogDescription>
</DialogHeader>
<div className="space-y-3 py-2">
<div>
<label className="text-sm font-medium">Justification Reason *</label>
<Textarea
value={reason}
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setReason(e.target.value)}
placeholder="Provide a detailed reason for overriding the rejection (minimum 10 characters)..."
className="mt-1.5 min-h-[100px]"
/>
<p className={`text-xs mt-1 ${isValid ? 'text-green-600' : 'text-muted-foreground'}`}>
{reason.trim().length}/{MIN_REASON_LENGTH} minimum characters
</p>
</div>
<div className="rounded-md bg-destructive/10 border border-destructive/20 p-3">
<p className="text-xs text-destructive font-medium">
This override is irreversible. All reviewers and stakeholders will be notified.
</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button
variant="destructive"
onClick={handleConfirm}
disabled={!isValid || isLoading}
>
{isLoading ? 'Processing...' : 'Confirm Override'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,145 @@
'use client';
// File: components/review-team/ReviewTeamForm.tsx
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { X } from 'lucide-react';
import { useState } from 'react';
const reviewTeamSchema = z.object({
name: z.string().min(1, 'Name is required').max(100),
description: z.string().max(255).optional(),
defaultForRfaTypes: z.array(z.string()).optional(),
});
type ReviewTeamFormValues = z.infer<typeof reviewTeamSchema>;
interface ReviewTeamFormProps {
projectPublicId: string;
defaultValues?: Partial<ReviewTeamFormValues>;
onSubmit: (values: ReviewTeamFormValues & { projectPublicId: string }) => void;
isLoading?: boolean;
}
const RFA_TYPE_OPTIONS = ['SDW', 'DDW', 'ADW', 'MS', 'MAT', 'BOQ'];
export function ReviewTeamForm({
projectPublicId,
defaultValues,
onSubmit,
isLoading,
}: ReviewTeamFormProps) {
const [typeInput, setTypeInput] = useState('');
const form = useForm<ReviewTeamFormValues>({
resolver: zodResolver(reviewTeamSchema),
defaultValues: {
name: defaultValues?.name ?? '',
description: defaultValues?.description ?? '',
defaultForRfaTypes: defaultValues?.defaultForRfaTypes ?? [],
},
});
const rfaTypes = form.watch('defaultForRfaTypes') ?? [];
const addRfaType = (type: string) => {
if (type && !rfaTypes.includes(type)) {
form.setValue('defaultForRfaTypes', [...rfaTypes, type]);
}
setTypeInput('');
};
const removeRfaType = (type: string) => {
form.setValue(
'defaultForRfaTypes',
rfaTypes.filter((t) => t !== type),
);
};
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit((values) =>
onSubmit({ ...values, projectPublicId }),
)}
className="space-y-4"
>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Team Name</FormLabel>
<FormControl>
<Input placeholder="e.g. Structural Review Team" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea placeholder="Optional description..." {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormItem>
<FormLabel>Default for RFA Types</FormLabel>
<div className="flex flex-wrap gap-2 mb-2">
{rfaTypes.map((type) => (
<Badge key={type} variant="secondary" className="gap-1">
{type}
<button
type="button"
onClick={() => removeRfaType(type)}
className="ml-1 hover:text-destructive"
>
<X className="h-3 w-3" />
</button>
</Badge>
))}
</div>
<div className="flex gap-2">
{RFA_TYPE_OPTIONS.filter((t) => !rfaTypes.includes(t)).map((type) => (
<button
key={type}
type="button"
onClick={() => addRfaType(type)}
className="text-xs px-2 py-1 rounded border border-dashed hover:bg-accent"
>
+ {type}
</button>
))}
</div>
<input type="hidden" value={typeInput} onChange={(e) => setTypeInput(e.target.value)} />
</FormItem>
<Button type="submit" disabled={isLoading}>
{isLoading ? 'Saving...' : 'Save Team'}
</Button>
</form>
</Form>
);
}
@@ -0,0 +1,84 @@
'use client';
// File: components/review-team/ReviewTeamSelector.tsx
// Selector component สำหรับเลือก Review Team ตอน Submit RFA (T023)
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Users } from 'lucide-react';
import { useReviewTeams } from '@/hooks/use-review-teams';
import { ReviewTeam } from '@/types/review-team';
interface ReviewTeamSelectorProps {
projectPublicId: string;
rfaTypeCode?: string;
value?: string;
onChange: (publicId: string | undefined) => void;
disabled?: boolean;
}
export function ReviewTeamSelector({
projectPublicId,
rfaTypeCode,
value,
onChange,
disabled,
}: ReviewTeamSelectorProps) {
const { data: teams = [], isLoading } = useReviewTeams({
projectPublicId,
isActive: true,
});
// กรอง teams ที่ match กับ rfaTypeCode (ถ้ากำหนด)
const filteredTeams = rfaTypeCode
? (teams as ReviewTeam[]).filter(
(t) => !t.defaultForRfaTypes?.length || t.defaultForRfaTypes.includes(rfaTypeCode),
)
: (teams as ReviewTeam[]);
return (
<div className="space-y-2">
<div className="flex items-center gap-2 text-sm font-medium">
<Users className="h-4 w-4" />
<span>Review Team (Parallel Review)</span>
<Badge variant="outline" className="text-xs">Optional</Badge>
</div>
<Select
value={value ?? ''}
onValueChange={(v: string) => onChange(v || undefined)}
disabled={disabled || isLoading}
>
<SelectTrigger>
<SelectValue placeholder={isLoading ? 'Loading teams...' : 'Skip — no parallel review'} />
</SelectTrigger>
<SelectContent>
<SelectItem value="">Skip no parallel review</SelectItem>
{filteredTeams.map((team) => (
<SelectItem key={team.publicId} value={team.publicId}>
<div className="flex items-center gap-2">
<span>{team.name}</span>
{(team.members ?? []).length > 0 && (
<span className="text-xs text-muted-foreground">
({team.members?.length} members)
</span>
)}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
{value && (
<p className="text-xs text-muted-foreground">
Parallel review tasks will be created for each discipline in the selected team.
</p>
)}
</div>
);
}
@@ -0,0 +1,184 @@
'use client';
// File: components/review-team/TeamMemberManager.tsx
// จัดการสมาชิกของ Review Team แยกตาม Discipline (FR-001)
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Trash2, UserPlus } from 'lucide-react';
import { useAddTeamMember, useRemoveTeamMember } from '@/hooks/use-review-teams';
import { ReviewTeamMemberRole } from '@/types/review-team';
interface Member {
publicId: string;
role: ReviewTeamMemberRole;
user?: { publicId: string; fullName?: string; email?: string };
discipline?: { publicId: string; disciplineCode: string; codeNameEn?: string };
}
interface User {
publicId: string;
fullName?: string;
email?: string;
}
interface Discipline {
publicId: string;
disciplineCode: string;
codeNameEn?: string;
}
interface TeamMemberManagerProps {
teamPublicId: string;
members: Member[];
availableUsers: User[];
availableDisciplines: Discipline[];
}
const ROLE_LABELS: Record<ReviewTeamMemberRole, string> = {
REVIEWER: 'Reviewer',
LEAD: 'Lead',
MANAGER: 'Manager',
};
const ROLE_BADGE_VARIANT: Record<ReviewTeamMemberRole, 'default' | 'secondary' | 'outline'> = {
LEAD: 'default',
MANAGER: 'secondary',
REVIEWER: 'outline',
};
export function TeamMemberManager({
teamPublicId,
members,
availableUsers,
availableDisciplines,
}: TeamMemberManagerProps) {
const [selectedUser, setSelectedUser] = useState('');
const [selectedDiscipline, setSelectedDiscipline] = useState('');
const [selectedRole, setSelectedRole] = useState<ReviewTeamMemberRole>('REVIEWER');
const addMember = useAddTeamMember();
const removeMember = useRemoveTeamMember();
const handleAdd = () => {
if (!selectedUser || !selectedDiscipline) return;
addMember.mutate(
{
teamPublicId,
data: {
userPublicId: selectedUser,
disciplinePublicId: selectedDiscipline,
role: selectedRole,
},
},
{
onSuccess: () => {
setSelectedUser('');
setSelectedDiscipline('');
setSelectedRole('REVIEWER');
},
},
);
};
return (
<div className="space-y-4">
{/* Member List */}
<div className="space-y-2">
{members.length === 0 && (
<p className="text-sm text-muted-foreground">No members assigned yet.</p>
)}
{members.map((member) => (
<div
key={member.publicId}
className="flex items-center justify-between p-3 rounded-lg border bg-card"
>
<div className="flex items-center gap-3">
<div>
<p className="text-sm font-medium">
{member.user?.fullName ?? member.user?.email ?? '—'}
</p>
<p className="text-xs text-muted-foreground">
{member.discipline?.disciplineCode} {member.discipline?.codeNameEn}
</p>
</div>
</div>
<div className="flex items-center gap-2">
<Badge variant={ROLE_BADGE_VARIANT[member.role]}>
{ROLE_LABELS[member.role]}
</Badge>
<Button
variant="ghost"
size="icon"
onClick={() =>
removeMember.mutate({ teamPublicId, memberPublicId: member.publicId })
}
disabled={removeMember.isPending}
>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</div>
</div>
))}
</div>
{/* Add Member Form */}
<div className="flex gap-2 pt-2 border-t">
<Select value={selectedUser} onValueChange={setSelectedUser}>
<SelectTrigger className="flex-1">
<SelectValue placeholder="Select user..." />
</SelectTrigger>
<SelectContent>
{availableUsers.map((u) => (
<SelectItem key={u.publicId} value={u.publicId}>
{u.fullName ?? u.email}
</SelectItem>
))}
</SelectContent>
</Select>
<Select value={selectedDiscipline} onValueChange={setSelectedDiscipline}>
<SelectTrigger className="w-36">
<SelectValue placeholder="Discipline..." />
</SelectTrigger>
<SelectContent>
{availableDisciplines.map((d) => (
<SelectItem key={d.publicId} value={d.publicId}>
{d.disciplineCode}
</SelectItem>
))}
</SelectContent>
</Select>
<Select
value={selectedRole}
onValueChange={(v: string) => setSelectedRole(v as ReviewTeamMemberRole)}
>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
{(Object.keys(ROLE_LABELS) as ReviewTeamMemberRole[]).map((role) => (
<SelectItem key={role} value={role}>
{ROLE_LABELS[role]}
</SelectItem>
))}
</SelectContent>
</Select>
<Button onClick={handleAdd} disabled={!selectedUser || !selectedDiscipline || addMember.isPending}>
<UserPlus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
</div>
);
}