690514:2019 204-rfa-approval-refactor #01
CI / CD Pipeline / build (push) Successful in 6m1s
CI / CD Pipeline / deploy (push) Failing after 6m42s

This commit is contained in:
2026-05-14 20:19:21 +07:00
parent 07cc6d47b1
commit 0240d80da5
183 changed files with 20050 additions and 1017 deletions
@@ -0,0 +1,4 @@
// File: app/(dashboard)/delegation/page.tsx
// Change Log
// - 2026-05-13: เพิ่ม route alias สำหรับหน้า Delegation Settings ตาม Phase 5
export { default } from '../settings/delegation/page';
@@ -0,0 +1,214 @@
'use client';
// File: app/(dashboard)/distribution-matrices/page.tsx
// Change Log
// - 2026-05-14: Add admin UI for Distribution Matrix management.
import { useState } from 'react';
import { Network, Plus, Trash2 } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import {
useCreateDistributionMatrix,
useDeleteDistributionMatrix,
useDistributionMatrices,
} from '@/hooks/use-distribution-matrices';
import { useProjectStore } from '@/lib/stores/project-store';
const formSchema = z.object({
name: z.string().min(1, 'Name is required').max(100),
documentTypeId: z.coerce.number().int().positive(),
codes: z.string().optional(),
excludeCodes: z.string().optional(),
});
type DistributionMatrixForm = z.infer<typeof formSchema>;
const splitCodes = (value?: string): string[] | undefined => {
const codes = value
?.split(',')
.map((item) => item.trim())
.filter(Boolean);
return codes && codes.length > 0 ? codes : undefined;
};
export default function DistributionMatricesPage() {
const [createOpen, setCreateOpen] = useState(false);
const selectedProjectId = useProjectStore((state) => state.selectedProjectId);
const { data: matrices = [], isLoading } = useDistributionMatrices(selectedProjectId ?? undefined);
const createMatrix = useCreateDistributionMatrix();
const deleteMatrix = useDeleteDistributionMatrix();
const form = useForm<DistributionMatrixForm>({
resolver: zodResolver(formSchema),
defaultValues: {
name: '',
documentTypeId: 1,
codes: '',
excludeCodes: '3,4',
},
});
const onSubmit = (values: DistributionMatrixForm) => {
createMatrix.mutate(
{
name: values.name,
projectPublicId: selectedProjectId ?? undefined,
documentTypeId: values.documentTypeId,
conditions: {
codes: splitCodes(values.codes),
excludeCodes: splitCodes(values.excludeCodes),
},
},
{
onSuccess: () => {
form.reset();
setCreateOpen(false);
},
}
);
};
return (
<div className="p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold">Distribution Matrix</h1>
<p className="text-muted-foreground text-sm mt-1">
RFA BullMQ Transmittal
</p>
</div>
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
New Matrix
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Create Distribution Matrix</DialogTitle>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input placeholder="Shop Drawing Distribution" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="documentTypeId"
render={({ field }) => (
<FormItem>
<FormLabel>Document Type ID</FormLabel>
<FormControl>
<Input type="number" min={1} {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-2 gap-3">
<FormField
control={form.control}
name="codes"
render={({ field }) => (
<FormItem>
<FormLabel>Included Codes</FormLabel>
<FormControl>
<Input placeholder="1A,1B,2" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="excludeCodes"
render={({ field }) => (
<FormItem>
<FormLabel>Excluded Codes</FormLabel>
<FormControl>
<Input placeholder="3,4" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<Button type="submit" className="w-full" disabled={createMatrix.isPending}>
{createMatrix.isPending ? 'Saving...' : 'Save Matrix'}
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
</div>
{isLoading && <div className="text-center text-muted-foreground py-8">Loading distribution matrices...</div>}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{matrices.map((matrix) => (
<Card key={matrix.publicId}>
<CardHeader className="pb-2">
<div className="flex items-start justify-between gap-3">
<div className="space-y-2">
<div className="flex items-center gap-2">
<Network className="h-4 w-4 text-muted-foreground" />
<CardTitle className="text-base">{matrix.name}</CardTitle>
</div>
<div className="flex flex-wrap gap-1">
<Badge variant="secondary">Type {matrix.documentTypeId}</Badge>
{(matrix.conditions?.codes ?? []).map((code) => (
<Badge key={code} variant="outline">
{code}
</Badge>
))}
{(matrix.conditions?.excludeCodes ?? []).map((code) => (
<Badge key={code} variant="destructive">
Exclude {code}
</Badge>
))}
</div>
</div>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive"
onClick={() => deleteMatrix.mutate(matrix.publicId)}
title="Deactivate matrix"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</CardHeader>
<CardContent>
<div className="text-sm text-muted-foreground">Recipients: {(matrix.recipients ?? []).length}</div>
</CardContent>
</Card>
))}
{!isLoading && matrices.length === 0 && (
<div className="lg:col-span-2 text-center py-12 border-2 border-dashed rounded-lg text-muted-foreground">
<Network className="h-12 w-12 mx-auto mb-3 opacity-20" />
<p>No Distribution Matrix configured.</p>
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,95 @@
'use client';
// File: app/(dashboard)/response-codes/page.tsx
// Master Approval Matrix management UI (T031, FR-022)
import { useState } from 'react';
import { Settings, ShieldCheck, ChevronRight } from 'lucide-react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useResponseCodes } from '@/hooks/use-response-codes';
import { MatrixEditor } from '@/components/response-code/MatrixEditor';
import { ProjectOverrideManager } from '@/components/response-code/ProjectOverrideManager';
import { useProjectStore } from '@/lib/stores/project-store';
export default function ResponseCodesPage() {
const [activeTab, setActiveTab] = useState('global');
const selectedProjectId = useProjectStore((state) => state.selectedProjectId);
// Dummy data for example - in real app, these would come from specialized hooks
const { data: globalRules = [] } = useResponseCodes();
return (
<div className="p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<div className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
<span>Admin</span>
<ChevronRight className="h-3 w-3" />
<span>Master Data</span>
</div>
<h1 className="text-2xl font-bold flex items-center gap-2">
<ShieldCheck className="h-6 w-6 text-primary" />
Approval Matrix & Response Codes
</h1>
<p className="text-muted-foreground text-sm mt-1">
Manage global response codes and document-specific approval rules.
</p>
</div>
</div>
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
<TabsList>
<TabsTrigger value="global" className="gap-2">
Global Matrix
</TabsTrigger>
<TabsTrigger value="project" className="gap-2">
Project Overrides
</TabsTrigger>
<TabsTrigger value="codes" className="gap-2">
Code Definitions
</TabsTrigger>
</TabsList>
<TabsContent value="global" className="space-y-4">
<div className="grid grid-cols-1 gap-4">
<MatrixEditor
documentTypeCode="SDW"
rules={globalRules.map(r => ({
publicId: r.publicId,
responseCode: {
publicId: r.publicId,
code: r.code,
descriptionEn: r.descriptionEn || '',
category: r.category || 'ENGINEERING'
},
isEnabled: true,
requiresComments: false,
triggersNotification: false,
isOverridden: false
}))}
onToggleEnabled={() => {}}
onToggleRequiresComments={() => {}}
onToggleNotification={() => {}}
/>
</div>
</TabsContent>
<TabsContent value="project">
<ProjectOverrideManager
projectPublicId={selectedProjectId ?? ''}
projectName="Selected Project"
overrides={[]}
onDeleteOverride={() => {}}
onAddOverride={() => {}}
/>
</TabsContent>
<TabsContent value="codes">
<div className="bg-muted/30 border rounded-lg p-12 text-center text-muted-foreground">
<Settings className="h-12 w-12 mx-auto mb-4 opacity-20" />
<p>Response Code definition management is coming soon.</p>
</div>
</TabsContent>
</Tabs>
</div>
);
}
@@ -14,13 +14,21 @@ import {
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import { useMyDelegations, useCreateDelegation, useRevokeDelegation, Delegation } from '@/hooks/use-delegation';
import {
useMyDelegations,
useCreateDelegation,
useRevokeDelegation,
Delegation,
} from '@/hooks/use-delegation';
import { useUsers } from '@/hooks/use-users';
import { DelegationForm } from '@/components/delegation/DelegationForm';
import { User } from '@/types/user';
export default function DelegationPage() {
const [createOpen, setCreateOpen] = useState(false);
const { data: delegations = [], isLoading } = useMyDelegations();
const { data: users = [] } = useUsers({ limit: 100 });
const createDelegation = useCreateDelegation();
const revokeDelegation = useRevokeDelegation();
@@ -48,7 +56,11 @@ export default function DelegationPage() {
<DialogTitle>Create Delegation</DialogTitle>
</DialogHeader>
<DelegationForm
availableUsers={[]}
availableUsers={users.map((user: User) => ({
publicId: user.publicId,
fullName: `${user.firstName} ${user.lastName}`.trim(),
email: user.email,
}))}
onSubmit={(dto) =>
createDelegation.mutate(dto, {
onSuccess: () => setCreateOpen(false),
@@ -0,0 +1,207 @@
'use client';
// File: app/(dashboard)/settings/reminder-rules/page.tsx
import { useState } from 'react';
import { Plus, Bell, Trash2, Edit2 } 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 {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
useReminderRules,
useCreateReminderRule,
useUpdateReminderRule,
useDeleteReminderRule,
ReminderRule,
} from '@/hooks/use-reminder';
import { ReminderRuleForm } from '@/components/reminder/ReminderRuleForm';
import { ReminderType } from '@/types/workflow';
export default function ReminderRulesPage() {
const [createOpen, setCreateOpen] = useState(false);
const [editingRule, setEditingRule] = useState<ReminderRule | null>(null);
const { data: rules = [], isLoading } = useReminderRules();
const createRule = useCreateReminderRule();
const updateRule = useUpdateReminderRule();
const deleteRule = useDeleteReminderRule();
const getReminderTypeColor = (type: ReminderType) => {
switch (type) {
case ReminderType.DUE_SOON:
return 'bg-blue-100 text-blue-800 border-blue-200';
case ReminderType.ON_DUE:
return 'bg-yellow-100 text-yellow-800 border-yellow-200';
case ReminderType.OVERDUE:
return 'bg-orange-100 text-orange-800 border-orange-200';
case ReminderType.ESCALATION_L1:
return 'bg-red-100 text-red-800 border-red-200';
case ReminderType.ESCALATION_L2:
return 'bg-purple-100 text-purple-800 border-purple-200';
default:
return 'bg-gray-100 text-gray-800 border-gray-200';
}
};
return (
<div className="p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold">Reminder & Escalation Rules</h1>
<p className="text-muted-foreground text-sm mt-1">
(Escalation)
</p>
</div>
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
New Rule
</Button>
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Create Reminder Rule</DialogTitle>
</DialogHeader>
<ReminderRuleForm
onSubmit={(dto) =>
createRule.mutate(dto, {
onSuccess: () => setCreateOpen(false),
})
}
isLoading={createRule.isPending}
/>
</DialogContent>
</Dialog>
</div>
{isLoading && (
<div className="text-center text-muted-foreground py-8">
Loading rules...
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{rules.map((rule) => (
<Card key={rule.publicId} className={!rule.isActive ? 'opacity-60' : ''}>
<CardHeader className="pb-2">
<div className="flex items-start justify-between">
<div className="space-y-1">
<div className="flex items-center gap-2">
<Bell className="h-4 w-4 text-muted-foreground" />
<CardTitle className="text-base">{rule.name}</CardTitle>
</div>
<div className="flex flex-wrap gap-1 mt-1">
<Badge
variant="outline"
className={`text-[10px] uppercase font-bold ${getReminderTypeColor(
rule.reminderType
)}`}
>
{rule.reminderType}
</Badge>
{rule.escalationLevel > 0 && (
<Badge variant="destructive" className="text-[10px]">
L{rule.escalationLevel}
</Badge>
)}
{rule.documentTypeCode && (
<Badge variant="secondary" className="text-[10px]">
{rule.documentTypeCode}
</Badge>
)}
</div>
</div>
<div className="flex gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => setEditingRule(rule)}
>
<Edit2 className="h-3.5 w-3.5" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive"
onClick={() => {
if (confirm('Delete this rule?')) {
deleteRule.mutate(rule.publicId);
}
}}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="text-sm text-muted-foreground">
<p>
Trigger:{' '}
<span className="font-medium text-foreground">
{rule.daysBeforeDue === 0
? 'On Due Date'
: rule.daysBeforeDue > 0
? `${rule.daysBeforeDue} days before`
: `${Math.abs(rule.daysBeforeDue)} days after`}
</span>
</p>
{rule.messageTemplate && (
<p className="mt-2 text-xs italic line-clamp-2">
"{rule.messageTemplate}"
</p>
)}
</div>
</CardContent>
</Card>
))}
{!isLoading && rules.length === 0 && (
<div className="col-span-full text-center py-12 border-2 border-dashed rounded-lg text-muted-foreground">
<Bell className="h-12 w-12 mx-auto mb-3 opacity-20" />
<p>No reminder rules defined.</p>
<Button
variant="link"
className="mt-2"
onClick={() => setCreateOpen(true)}
>
Create your first rule
</Button>
</div>
)}
</div>
<Dialog
open={!!editingRule}
onOpenChange={(open) => !open && setEditingRule(null)}
>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Edit Reminder Rule</DialogTitle>
</DialogHeader>
{editingRule && (
<ReminderRuleForm
defaultValues={editingRule}
onSubmit={(dto) =>
updateRule.mutate(
{ publicId: editingRule.publicId, data: dto },
{ onSuccess: () => setEditingRule(null) }
)
}
isLoading={updateRule.isPending}
/>
)}
</DialogContent>
</Dialog>
</div>
);
}
@@ -18,17 +18,22 @@ import { useReviewTeams, useCreateReviewTeam, useUpdateReviewTeam } from '@/hook
import { ReviewTeamForm } from '@/components/review-team/ReviewTeamForm';
import { TeamMemberManager } from '@/components/review-team/TeamMemberManager';
import { ReviewTeam } from '@/types/review-team';
// TODO: ดึง projectPublicId จาก context หรือ URL param จริง
const MOCK_PROJECT_ID = 'current-project-public-id';
import { useProjectStore } from '@/lib/stores/project-store';
import { useUsers } from '@/hooks/use-users';
import { useContracts, useDisciplines } from '@/hooks/use-master-data';
export default function ReviewTeamsPage() {
const [expandedTeam, setExpandedTeam] = useState<string | null>(null);
const [createOpen, setCreateOpen] = useState(false);
const [editTeam, setEditTeam] = useState<ReviewTeam | null>(null);
const selectedProjectId = useProjectStore((state) => state.selectedProjectId);
const { data: availableUsers = [] } = useUsers();
const { data: contracts = [] } = useContracts(selectedProjectId ?? undefined);
const primaryContractId = contracts[0]?.publicId;
const { data: availableDisciplines = [] } = useDisciplines(primaryContractId);
const { data: teams = [], isLoading } = useReviewTeams({
projectPublicId: MOCK_PROJECT_ID,
projectPublicId: selectedProjectId ?? undefined,
});
const createTeam = useCreateReviewTeam();
@@ -56,7 +61,7 @@ export default function ReviewTeamsPage() {
<DialogTitle>Create Review Team</DialogTitle>
</DialogHeader>
<ReviewTeamForm
projectPublicId={MOCK_PROJECT_ID}
projectPublicId={selectedProjectId ?? ''}
onSubmit={(values) =>
createTeam.mutate(values, {
onSuccess: () => setCreateOpen(false),
@@ -125,8 +130,8 @@ export default function ReviewTeamsPage() {
<TeamMemberManager
teamPublicId={team.publicId}
members={team.members ?? []}
availableUsers={[]}
availableDisciplines={[]}
availableUsers={availableUsers}
availableDisciplines={availableDisciplines}
/>
</CardContent>
)}
@@ -149,7 +154,7 @@ export default function ReviewTeamsPage() {
</DialogHeader>
{editTeam && (
<ReviewTeamForm
projectPublicId={MOCK_PROJECT_ID}
projectPublicId={selectedProjectId ?? ''}
defaultValues={editTeam}
onSubmit={(values) =>
updateTeam.mutate(
@@ -1,84 +1,81 @@
'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;
}
import { format } from 'date-fns';
import { History, Bell, ShieldAlert, AlertTriangle } from 'lucide-react';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { useReminderHistory } from '@/hooks/use-reminder';
import { ReminderType } from '@/types/workflow';
interface ReminderHistoryProps {
reminders: ReminderEntry[];
isLoading?: boolean;
taskPublicId: string;
}
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 ReminderHistoryViewer({ taskPublicId }: ReminderHistoryProps) {
const { data: history = [], isLoading } = useReminderHistory(taskPublicId);
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>;
}
const getIcon = (type: ReminderType) => {
switch (type) {
case ReminderType.ESCALATION_L1:
return <AlertTriangle className="h-4 w-4 text-orange-500" />;
case ReminderType.ESCALATION_L2:
return <ShieldAlert className="h-4 w-4 text-red-500" />;
default:
return <Bell className="h-4 w-4 text-blue-500" />;
}
};
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>
<Card>
<CardHeader className="pb-3">
<div className="flex items-center gap-2">
<History className="h-4 w-4 text-muted-foreground" />
<CardTitle className="text-sm font-semibold">Reminder History</CardTitle>
</div>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="text-xs text-muted-foreground py-4 text-center">
Loading history...
</div>
);
})}
</div>
) : history.length === 0 ? (
<div className="text-xs text-muted-foreground py-4 text-center border rounded-md border-dashed">
No reminders sent yet.
</div>
) : (
<div className="space-y-4">
{history.map((item) => (
<div
key={item.publicId}
className="flex items-start gap-3 text-xs border-b pb-3 last:border-0 last:pb-0"
>
<div className="mt-0.5">{getIcon(item.reminderType)}</div>
<div className="flex-1 space-y-1">
<div className="flex items-center justify-between">
<span className="font-semibold uppercase tracking-wider">
{item.reminderType.replace('_', ' ')}
</span>
<span className="text-muted-foreground">
{format(new Date(item.sentAt), 'dd MMM yyyy HH:mm')}
</span>
</div>
<p className="text-muted-foreground">
Sent to: <span className="text-foreground">{item.user?.fullName ?? 'Unknown User'}</span>
{item.escalationLevel > 0 && ` (L${item.escalationLevel})`}
</p>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,145 @@
'use client';
// File: components/reminder/ReminderRuleForm.tsx
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Button } from '@/components/ui/button';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, FormDescription } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { ReminderType } from '@/types/workflow';
import { CreateReminderRuleDto } from '@/hooks/use-reminder';
const formSchema = z.object({
name: z.string().min(1, 'Name is required').max(100),
documentTypeCode: z.string().optional(),
reminderType: z.nativeEnum(ReminderType),
daysBeforeDue: z.coerce.number(),
escalationLevel: z.coerce.number().min(0).max(2).default(0),
messageTemplate: z.string().optional(),
});
interface ReminderRuleFormProps {
onSubmit: (data: CreateReminderRuleDto) => void;
isLoading?: boolean;
defaultValues?: Partial<CreateReminderRuleDto>;
}
export function ReminderRuleForm({ onSubmit, isLoading, defaultValues }: ReminderRuleFormProps) {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
name: defaultValues?.name ?? '',
documentTypeCode: defaultValues?.documentTypeCode ?? '',
reminderType: defaultValues?.reminderType ?? ReminderType.DUE_SOON,
daysBeforeDue: defaultValues?.daysBeforeDue ?? 2,
escalationLevel: defaultValues?.escalationLevel ?? 0,
messageTemplate: defaultValues?.messageTemplate ?? '',
},
});
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Rule Name</FormLabel>
<FormControl>
<Input placeholder="e.g. 2 Days Before Reminder" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="reminderType"
render={({ field }) => (
<FormItem>
<FormLabel>Reminder Type</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select type" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value={ReminderType.DUE_SOON}>Due Soon</SelectItem>
<SelectItem value={ReminderType.ON_DUE}>On Due</SelectItem>
<SelectItem value={ReminderType.OVERDUE}>Overdue</SelectItem>
<SelectItem value={ReminderType.ESCALATION_L1}>Escalation L1</SelectItem>
<SelectItem value={ReminderType.ESCALATION_L2}>Escalation L2</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="daysBeforeDue"
render={({ field }) => (
<FormItem>
<FormLabel>Trigger Days</FormLabel>
<FormControl>
<Input type="number" {...field} />
</FormControl>
<FormDescription>+ for before, - for after due</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="escalationLevel"
render={({ field }) => (
<FormItem>
<FormLabel>Escalation Level</FormLabel>
<Select onValueChange={(val) => field.onChange(Number(val))} defaultValue={field.value.toString()}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select level" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="0">0 - Normal Reminder</SelectItem>
<SelectItem value="1">1 - Escalation L1 (Lead)</SelectItem>
<SelectItem value="2">2 - Escalation L2 (PM)</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="messageTemplate"
render={({ field }) => (
<FormItem>
<FormLabel>Message Template (Optional)</FormLabel>
<FormControl>
<Textarea placeholder="Custom message for notification..." {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? 'Saving...' : 'Save Rule'}
</Button>
</form>
</Form>
);
}
@@ -0,0 +1,63 @@
// File: frontend/components/response-code/ResponseCodeSelector.test.tsx
// Unit tests สำหรับ ResponseCodeSelector component (T078)
import { render, screen } from '@testing-library/react';
import { vi } from 'vitest';
import { ResponseCodeSelector } from '@/components/response-code/ResponseCodeSelector';
vi.mock('@/hooks/use-response-codes', () => ({
useResponseCodesByDocType: vi.fn(() => ({
data: [
{
publicId: 'uuid-1',
code: '1A',
category: 'ENGINEERING',
descriptionEn: 'Approved — No Comments',
descriptionTh: 'ผ่าน — ไม่มีเงื่อนไข',
implications: {},
notifyRoles: [],
isActive: true,
isSystem: true,
},
{
publicId: 'uuid-2',
code: '2',
category: 'ENGINEERING',
descriptionEn: 'Approved with Comments',
descriptionTh: 'ผ่าน — มีเงื่อนไข',
implications: { affectsSchedule: true },
notifyRoles: ['CONTRACT_MANAGER'],
isActive: true,
isSystem: true,
},
],
isLoading: false,
})),
}));
describe('ResponseCodeSelector', () => {
it('renders the trigger with placeholder text', () => {
render(
<ResponseCodeSelector
documentTypeId={1}
value={undefined}
onChange={vi.fn()}
/>,
);
expect(screen.getByRole('combobox')).toBeTruthy();
expect(screen.getByText('Select Response Code...')).toBeTruthy();
});
it('renders a custom placeholder when provided', () => {
render(
<ResponseCodeSelector
documentTypeId={1}
value={undefined}
onChange={vi.fn()}
placeholder="Choose a response code"
/>,
);
expect(screen.getByText('Choose a response code')).toBeTruthy();
});
});
@@ -14,6 +14,8 @@ import { Users } from 'lucide-react';
import { useReviewTeams } from '@/hooks/use-review-teams';
import { ReviewTeam } from '@/types/review-team';
const NO_REVIEW_TEAM_VALUE = '__skip_parallel_review__';
interface ReviewTeamSelectorProps {
projectPublicId: string;
rfaTypeCode?: string;
@@ -50,15 +52,17 @@ export function ReviewTeamSelector({
</div>
<Select
value={value ?? ''}
onValueChange={(v: string) => onChange(v || undefined)}
value={value ?? NO_REVIEW_TEAM_VALUE}
onValueChange={(v: string) =>
onChange(v === NO_REVIEW_TEAM_VALUE ? undefined : v)
}
disabled={disabled || isLoading}
>
<SelectTrigger>
<SelectValue placeholder={isLoading ? 'Loading teams...' : 'Skip — no parallel review'} />
</SelectTrigger>
<SelectContent>
<SelectItem value="">Skip no parallel review</SelectItem>
<SelectItem value={NO_REVIEW_TEAM_VALUE}>Skip no parallel review</SelectItem>
{filteredTeams.map((team) => (
<SelectItem key={team.publicId} value={team.publicId}>
<div className="flex items-center gap-2">
@@ -30,7 +30,7 @@ interface User {
}
interface Discipline {
publicId: string;
id?: number;
disciplineCode: string;
codeNameEn?: string;
}
@@ -68,14 +68,16 @@ export function TeamMemberManager({
const removeMember = useRemoveTeamMember();
const handleAdd = () => {
if (!selectedUser || !selectedDiscipline) return;
const disciplineId = Number(selectedDiscipline);
if (!selectedUser || Number.isNaN(disciplineId)) return;
addMember.mutate(
{
teamPublicId,
data: {
userPublicId: selectedUser,
disciplinePublicId: selectedDiscipline,
disciplineId,
role: selectedRole,
},
},
@@ -151,7 +153,7 @@ export function TeamMemberManager({
</SelectTrigger>
<SelectContent>
{availableDisciplines.map((d) => (
<SelectItem key={d.publicId} value={d.publicId}>
<SelectItem key={String(d.id)} value={String(d.id)}>
{d.disciplineCode}
</SelectItem>
))}
+18 -1
View File
@@ -11,6 +11,7 @@ import { useState } from 'react';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { useProcessRFA, useSubmitRFA } from '@/hooks/use-rfa';
import { ReviewTeamSelector } from '@/components/review-team/ReviewTeamSelector';
interface RFADetailProps {
data: RFA;
@@ -20,6 +21,7 @@ export function RFADetail({ data }: RFADetailProps) {
const [actionState, setActionState] = useState<'approve' | 'reject' | 'submit' | null>(null);
const [comments, setComments] = useState('');
const [templateId, setTemplateId] = useState<number>(1);
const [reviewTeamPublicId, setReviewTeamPublicId] = useState<string | undefined>(undefined);
const processMutation = useProcessRFA();
const submitMutation = useSubmitRFA();
const currentRevision = data.revisions.find((revision) => revision.isCurrent) ?? data.revisions[0];
@@ -79,10 +81,17 @@ export function RFADetail({ data }: RFADetailProps) {
const handleSubmit = () => {
submitMutation.mutate(
{ uuid: data.publicId, templateId },
{
uuid: data.publicId,
data: {
templateId,
reviewTeamPublicId,
},
},
{
onSuccess: () => {
setActionState(null);
setReviewTeamPublicId(undefined);
},
}
);
@@ -159,6 +168,14 @@ export function RFADetail({ data }: RFADetailProps) {
/>
<p className="text-xs text-muted-foreground">Enter the routing template ID for this submission.</p>
</div>
{data.correspondence?.project?.publicId && (
<ReviewTeamSelector
projectPublicId={data.correspondence.project.publicId}
value={reviewTeamPublicId}
onChange={setReviewTeamPublicId}
disabled={submitMutation.isPending}
/>
)}
<div className="flex justify-end gap-2">
<Button variant="ghost" onClick={() => setActionState(null)}>Cancel</Button>
<Button onClick={handleSubmit} disabled={submitMutation.isPending}>
+103
View File
@@ -0,0 +1,103 @@
// File: hooks/use-distribution-matrices.ts
// Change Log
// - 2026-05-14: Add TanStack Query hooks for Distribution Matrix admin UI.
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import apiClient from '@/lib/api/client';
import { getApiErrorMessage } from '@/types/api-error';
export type DistributionRecipientType = 'USER' | 'ORGANIZATION' | 'TEAM' | 'ROLE';
export type DistributionDeliveryMethod = 'EMAIL' | 'IN_APP' | 'BOTH';
export interface DistributionConditions {
codes?: string[];
excludeCodes?: string[];
}
export interface DistributionRecipient {
publicId: string;
recipientType: DistributionRecipientType;
recipientPublicId: string;
deliveryMethod: DistributionDeliveryMethod;
sequence?: number;
}
export interface DistributionMatrix {
publicId: string;
name: string;
documentTypeId: number;
conditions?: DistributionConditions;
isActive: boolean;
recipients?: DistributionRecipient[];
responseCode?: {
publicId: string;
code: string;
descriptionEn?: string;
};
}
export interface CreateDistributionMatrixDto {
name: string;
projectPublicId?: string;
documentTypeId: number;
responseCodePublicId?: string;
conditions?: DistributionConditions;
}
const extractArrayData = <T>(value: unknown): T[] => {
if (Array.isArray(value)) return value as T[];
if (value && typeof value === 'object' && 'data' in value) {
const nested = (value as { data?: unknown }).data;
return Array.isArray(nested) ? (nested as T[]) : extractArrayData<T>(nested);
}
return [];
};
export const distributionMatrixKeys = {
all: ['distribution-matrices'] as const,
byProject: (projectPublicId?: string) => [...distributionMatrixKeys.all, { projectPublicId }] as const,
};
export function useDistributionMatrices(projectPublicId?: string) {
return useQuery({
queryKey: distributionMatrixKeys.byProject(projectPublicId),
queryFn: async (): Promise<DistributionMatrix[]> => {
const res = await apiClient.get('/admin/distribution-matrices', {
params: { projectPublicId },
});
return extractArrayData<DistributionMatrix>(res.data);
},
});
}
export function useCreateDistributionMatrix() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: CreateDistributionMatrixDto) => apiClient.post('/admin/distribution-matrices', data),
onSuccess: () => {
toast.success('Distribution Matrix created');
queryClient.invalidateQueries({ queryKey: distributionMatrixKeys.all });
},
onError: (error: unknown) => {
toast.error('Failed to create Distribution Matrix', {
description: getApiErrorMessage(error, 'Something went wrong'),
});
},
});
}
export function useDeleteDistributionMatrix() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (publicId: string) => apiClient.delete(`/admin/distribution-matrices/${publicId}`),
onSuccess: () => {
toast.success('Distribution Matrix deactivated');
queryClient.invalidateQueries({ queryKey: distributionMatrixKeys.all });
},
onError: (error: unknown) => {
toast.error('Failed to deactivate Distribution Matrix', {
description: getApiErrorMessage(error, 'Something went wrong'),
});
},
});
}
+131
View File
@@ -0,0 +1,131 @@
// File: hooks/use-reminder.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import apiClient from '@/lib/api/client';
import { getApiErrorMessage } from '@/types/api-error';
import { ReminderType } from '@/types/workflow';
export interface ReminderRule {
publicId: string;
projectId?: number;
name: string;
documentTypeCode?: string;
reminderType: ReminderType;
daysBeforeDue: number;
escalationLevel: number;
notifyRoles?: string[];
messageTemplate?: string;
isActive: boolean;
}
export interface ReminderHistory {
publicId: string;
taskId: number;
userId: number;
reminderType: ReminderType;
escalationLevel: number;
sentAt: string;
user?: {
fullName: string;
email: string;
};
}
export interface CreateReminderRuleDto {
projectId?: number;
name: string;
documentTypeCode?: string;
reminderType: ReminderType;
daysBeforeDue: number;
escalationLevel?: number;
notifyRoles?: string[];
messageTemplate?: string;
}
export const reminderKeys = {
all: ['reminder-rules'] as const,
byProject: (projectId?: string) => [...reminderKeys.all, { projectId }] as const,
history: (taskPublicId: string) => ['reminder-history', taskPublicId] as const,
};
export function useReminderRules(projectPublicId?: string) {
return useQuery({
queryKey: reminderKeys.byProject(projectPublicId),
queryFn: async (): Promise<ReminderRule[]> => {
const res = await apiClient.get('/admin/reminder-rules', {
params: { projectPublicId },
});
return res.data;
},
});
}
export function useReminderHistory(taskPublicId: string) {
return useQuery({
queryKey: reminderKeys.history(taskPublicId),
queryFn: async (): Promise<ReminderHistory[]> => {
const res = await apiClient.get(`/admin/reminder-rules/history/${taskPublicId}`);
return res.data;
},
enabled: !!taskPublicId,
});
}
export function useCreateReminderRule() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: CreateReminderRuleDto) =>
apiClient.post('/admin/reminder-rules', data),
onSuccess: () => {
toast.success('Reminder rule created successfully');
queryClient.invalidateQueries({ queryKey: reminderKeys.all });
},
onError: (error: unknown) => {
toast.error('Failed to create reminder rule', {
description: getApiErrorMessage(error, 'Something went wrong'),
});
},
});
}
export function useUpdateReminderRule() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
publicId,
data,
}: {
publicId: string;
data: Partial<CreateReminderRuleDto>;
}) => apiClient.patch(`/admin/reminder-rules/${publicId}`, data),
onSuccess: () => {
toast.success('Reminder rule updated');
queryClient.invalidateQueries({ queryKey: reminderKeys.all });
},
onError: (error: unknown) => {
toast.error('Failed to update reminder rule', {
description: getApiErrorMessage(error, 'Something went wrong'),
});
},
});
}
export function useDeleteReminderRule() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (publicId: string) =>
apiClient.delete(`/admin/reminder-rules/${publicId}`),
onSuccess: () => {
toast.success('Reminder rule deleted');
queryClient.invalidateQueries({ queryKey: reminderKeys.all });
},
onError: (error: unknown) => {
toast.error('Failed to delete reminder rule', {
description: getApiErrorMessage(error, 'Something went wrong'),
});
},
});
}
+3 -3
View File
@@ -1,5 +1,5 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { rfaService } from '@/lib/services/rfa.service';
import { rfaService, SubmitRfaDto } from '@/lib/services/rfa.service';
import { SearchRfaDto, CreateRfaDto, UpdateRfaDto } from '@/types/dto/rfa/rfa.dto';
import { WorkflowActionDto } from '@/lib/services/rfa.service';
import { toast } from 'sonner';
@@ -41,8 +41,8 @@ export function useSubmitRFA() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ uuid, templateId }: { uuid: string; templateId: number }) =>
rfaService.submit(uuid, templateId),
mutationFn: ({ uuid, data }: { uuid: string; data: SubmitRfaDto }) =>
rfaService.submit(uuid, data),
onSuccess: (_, { uuid }) => {
toast.success('RFA submitted successfully');
queryClient.invalidateQueries({ queryKey: rfaKeys.detail(uuid) });
+1 -1
View File
@@ -17,7 +17,7 @@ export interface UpdateReviewTeamDto {
export interface AddTeamMemberDto {
userPublicId: string;
disciplinePublicId: string;
disciplineId: number;
role: 'REVIEWER' | 'LEAD' | 'MANAGER';
priorityOrder?: number;
}
+7 -2
View File
@@ -9,6 +9,11 @@ export interface WorkflowActionDto {
stepNumber?: number; // อาจจะไม่จำเป็นถ้า Backend เช็ค state ปัจจุบันได้เอง
}
export interface SubmitRfaDto {
templateId: number;
reviewTeamPublicId?: string;
}
export const rfaService = {
/**
* ดึงรายการ RFA ทั้งหมด (รองรับ Search & Filter)
@@ -40,9 +45,9 @@ export const rfaService = {
/**
* Submit a Draft RFA to workflow
*/
submit: async (uuid: string, templateId: number) => {
submit: async (uuid: string, data: SubmitRfaDto) => {
// POST /rfas/:uuid/submit (ADR-019)
const response = await apiClient.post(`/rfas/${uuid}/submit`, { templateId });
const response = await apiClient.post(`/rfas/${uuid}/submit`, data);
return response.data;
},
+4 -4
View File
@@ -40,13 +40,13 @@
"@radix-ui/react-tabs": "^1.1.13",
"@tanstack/react-query": "^5.91.2",
"@tanstack/react-table": "^8.21.3",
"axios": "1.15.0",
"axios": "1.15.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^4.1.0",
"lucide-react": "^0.577.0",
"next": "16.2.4",
"next": "16.2.6",
"next-auth": "5.0.0-beta.30",
"next-themes": "^0.4.6",
"react": "^19.2.4",
@@ -58,7 +58,7 @@
"sonner": "^2.0.7",
"tailwind-merge": "^3.5.0",
"tailwindcss-animate": "^1.0.7",
"uuid": "^11.0.0",
"uuid": "^11.1.1",
"zod": "4.3.6",
"zustand": "^5.0.12"
},
@@ -83,7 +83,7 @@
"eslint-plugin-react-hooks": "^7.0.1",
"globals": "^17.4.0",
"jsdom": "^29.0.0",
"postcss": "^8.5.8",
"postcss": "^8.5.10",
"tailwindcss": "3.4.3",
"typescript": "^5.9.3",
"vite": "7.3.2",
@@ -1,71 +0,0 @@
// File: frontend/tests/components/ResponseCodeSelector.test.tsx
// Unit tests สำหรับ ResponseCodeSelector component (T078)
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { ResponseCodeSelector } from '@/components/response-code/ResponseCodeSelector';
const mockCodes = [
{
publicId: 'uuid-1',
code: '1A',
category: 'ENGINEERING',
descriptionEn: 'Approved — No Comments',
descriptionTh: 'ผ่าน — ไม่มีเงื่อนไข',
implications: {},
notifyRoles: [],
isSystem: true,
},
{
publicId: 'uuid-2',
code: '2',
category: 'ENGINEERING',
descriptionEn: 'Approved with Comments',
descriptionTh: 'ผ่าน — มีเงื่อนไข',
implications: { affectsSchedule: true },
notifyRoles: ['CONTRACT_MANAGER'],
isSystem: true,
},
{
publicId: 'uuid-3',
code: '3',
category: 'ENGINEERING',
descriptionEn: 'Rejected',
descriptionTh: 'ไม่ผ่าน',
implications: {},
notifyRoles: [],
isSystem: true,
},
];
describe('ResponseCodeSelector', () => {
it('should render code options', () => {
const onSelect = jest.fn();
render(<ResponseCodeSelector codes={mockCodes} onSelect={onSelect} />);
expect(screen.getByText('1A')).toBeInTheDocument();
expect(screen.getByText('2')).toBeInTheDocument();
expect(screen.getByText('3')).toBeInTheDocument();
});
it('should call onSelect when a code is clicked', () => {
const onSelect = jest.fn();
render(<ResponseCodeSelector codes={mockCodes} onSelect={onSelect} />);
fireEvent.click(screen.getByText('1A'));
expect(onSelect).toHaveBeenCalledWith('uuid-1');
});
it('should highlight selected code', () => {
const onSelect = jest.fn();
render(
<ResponseCodeSelector
codes={mockCodes}
onSelect={onSelect}
selectedPublicId="uuid-2"
/>,
);
const selectedButton = screen.getByRole('button', { name: /2/i });
expect(selectedButton).toHaveClass('ring-2');
});
});
+8
View File
@@ -3,6 +3,14 @@ export type WorkflowType = 'CORRESPONDENCE' | 'RFA' | 'DRAWING';
// ADR-021: ระดับความเร่งด่วน (แสดงด้วย Badge สี)
export type WorkflowPriority = 'URGENT' | 'HIGH' | 'MEDIUM' | 'LOW';
export enum ReminderType {
DUE_SOON = 'DUE_SOON',
ON_DUE = 'ON_DUE',
OVERDUE = 'OVERDUE',
ESCALATION_L1 = 'ESCALATION_L1',
ESCALATION_L2 = 'ESCALATION_L2',
}
// ADR-021: ข้อมูลสรุปไฟล์แนบประจำ Step
export interface WorkflowAttachmentSummary {
publicId: string;