251223:1649 On going update to 1.7.0: Refoctory drawing Module & document number Module
This commit is contained in:
69
frontend/components/numbering/audit-logs-table.tsx
Normal file
69
frontend/components/numbering/audit-logs-table.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { documentNumberingService } from "@/lib/services/document-numbering.service";
|
||||
import { format } from "date-fns";
|
||||
|
||||
export function AuditLogsTable() {
|
||||
const [logs, setLogs] = useState<any[]>([]); // Replace with AuditLog type
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchLogs() {
|
||||
try {
|
||||
const data = await documentNumberingService.getMetrics(); // Using metrics endpoint for now as it contains logs
|
||||
if (data && data.audit) {
|
||||
setLogs(data.audit);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch audit logs", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
fetchLogs();
|
||||
}, []);
|
||||
|
||||
if (loading) return <div>Loading logs...</div>;
|
||||
|
||||
return (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Time</TableHead>
|
||||
<TableHead>Operation</TableHead>
|
||||
<TableHead>Number</TableHead>
|
||||
<TableHead>User</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{logs.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center">No logs found.</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
logs.map((log) => (
|
||||
<TableRow key={log.id}>
|
||||
<TableCell>{format(new Date(log.createdAt), "yyyy-MM-dd HH:mm:ss")}</TableCell>
|
||||
<TableCell>{log.operation}</TableCell>
|
||||
<TableCell>{log.generatedNumber}</TableCell>
|
||||
<TableCell>{log.createdBy || "System"}</TableCell>
|
||||
<TableCell>{log.status}</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
54
frontend/components/numbering/bulk-import-form.tsx
Normal file
54
frontend/components/numbering/bulk-import-form.tsx
Normal file
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { toast } from "sonner";
|
||||
import { documentNumberingService } from "@/lib/services/document-numbering.service";
|
||||
|
||||
export function BulkImportForm({ projectId = 1 }: { projectId?: number }) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (e.target.files) {
|
||||
setFile(e.target.files[0]);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpload = async () => {
|
||||
if (!file) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append("projectId", projectId.toString());
|
||||
|
||||
await documentNumberingService.bulkImport(formData);
|
||||
toast.success("Bulk import initiated. Check audit logs for progress.");
|
||||
setFile(null);
|
||||
} catch (error) {
|
||||
toast.error("Failed to import numbers.");
|
||||
console.error(error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="border p-4 rounded-md space-y-4">
|
||||
<h3 className="text-lg font-medium">Bulk Import Numbers</h3>
|
||||
<p className="text-sm text-gray-500">Import legacy numbers via CSV to reserve them in the system.</p>
|
||||
|
||||
<div className="grid w-full max-w-sm items-center gap-1.5">
|
||||
<Label htmlFor="csv-file">CSV File</Label>
|
||||
<Input id="csv-file" type="file" accept=".csv,.xlsx" onChange={handleFileChange} />
|
||||
</div>
|
||||
|
||||
<Button onClick={handleUpload} disabled={!file || loading}>
|
||||
{loading ? "Importing..." : "Upload & Import"}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
86
frontend/components/numbering/cancel-number-form.tsx
Normal file
86
frontend/components/numbering/cancel-number-form.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
"use client";
|
||||
|
||||
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
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { toast } from "sonner";
|
||||
import { documentNumberingService } from "@/lib/services/document-numbering.service";
|
||||
import { CancelNumberDto } from "@/types/dto/numbering.dto";
|
||||
import { useState } from "react";
|
||||
|
||||
const formSchema = z.object({
|
||||
documentNumber: z.string().min(3, "Document Number is required"),
|
||||
reason: z.string().min(5, "Reason must be at least 5 characters"),
|
||||
});
|
||||
|
||||
type CancelNumberFormData = z.infer<typeof formSchema>;
|
||||
|
||||
export function CancelNumberForm() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const form = useForm<CancelNumberFormData>({
|
||||
resolver: zodResolver(formSchema) as any,
|
||||
defaultValues: {
|
||||
documentNumber: "",
|
||||
reason: "",
|
||||
},
|
||||
});
|
||||
|
||||
async function onSubmit(values: CancelNumberFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
const dto: CancelNumberDto = values;
|
||||
await documentNumberingService.cancelNumber(dto);
|
||||
toast.success("Number cancelled successfully.");
|
||||
form.reset();
|
||||
} catch (error) {
|
||||
toast.error("Failed to cancel number. It may not exist or is already cancelled.");
|
||||
console.error(error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 border p-4 rounded-md">
|
||||
<h3 className="text-lg font-medium">Cancel Number</h3>
|
||||
<p className="text-sm text-gray-500">Permanently cancel a number (e.g. if generated by mistake). It cannot be reused.</p>
|
||||
|
||||
<FormField control={form.control} name="documentNumber" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Document Number</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="e.g. LCB3-COR-GGL-2025-0001" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
|
||||
<FormField control={form.control} name="reason" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Reason</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Reason for cancellation..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
|
||||
<Button type="submit" variant="destructive" disabled={loading}>
|
||||
{loading ? "Cancelling..." : "Cancel Number"}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
133
frontend/components/numbering/manual-override-form.tsx
Normal file
133
frontend/components/numbering/manual-override-form.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
"use client";
|
||||
|
||||
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 { toast } from "sonner";
|
||||
import { documentNumberingService } from "@/lib/services/document-numbering.service";
|
||||
import { ManualOverrideDto } from "@/types/dto/numbering.dto";
|
||||
import { useState } from "react";
|
||||
|
||||
const formSchema = z.object({
|
||||
projectId: z.coerce.number().min(1, "Project is required"),
|
||||
originatorOrganizationId: z.coerce.number().min(1, "Originator is required"),
|
||||
recipientOrganizationId: z.coerce.number().min(1, "Recipient is required"),
|
||||
correspondenceTypeId: z.coerce.number().min(1, "Type is required"),
|
||||
newLastNumber: z.coerce.number().min(1, "New number is required"),
|
||||
reason: z.string().min(5, "Reason must be at least 5 characters"),
|
||||
resetScope: z.string().optional()
|
||||
});
|
||||
|
||||
export function ManualOverrideForm({ projectId = 1 }: { projectId?: number }) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema) as any,
|
||||
defaultValues: {
|
||||
projectId: projectId,
|
||||
originatorOrganizationId: 0,
|
||||
recipientOrganizationId: 0,
|
||||
correspondenceTypeId: 0,
|
||||
newLastNumber: 0,
|
||||
reason: "",
|
||||
resetScope: "YEAR_2025" // Example, should be dynamic or selected
|
||||
},
|
||||
});
|
||||
|
||||
async function onSubmit(values: z.infer<typeof formSchema>) {
|
||||
setLoading(true);
|
||||
try {
|
||||
const dto: ManualOverrideDto = {
|
||||
...values,
|
||||
resetScope: values.resetScope || "YEAR_" + new Date().getFullYear()
|
||||
};
|
||||
await documentNumberingService.manualOverride(dto);
|
||||
toast.success("Manual override applied successfully.");
|
||||
form.reset();
|
||||
} catch (error) {
|
||||
toast.error("Failed to apply override.");
|
||||
console.error(error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 border p-4 rounded-md mt-4">
|
||||
<h3 className="text-lg font-medium">Manual Override Sequence</h3>
|
||||
<p className="text-sm text-gray-500">Careful: This updates the LAST generated number. Next number will receive +1.</p>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* Allow simple text input for IDs for now, ideally Selects from Master Data */}
|
||||
<FormField control={form.control} name="projectId" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Project ID</FormLabel>
|
||||
<FormControl><Input type="number" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="correspondenceTypeId" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Type ID</FormLabel>
|
||||
<FormControl><Input type="number" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="originatorOrganizationId" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Originator Org ID</FormLabel>
|
||||
<FormControl><Input type="number" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="recipientOrganizationId" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Recipient Org ID</FormLabel>
|
||||
<FormControl><Input type="number" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
</div>
|
||||
|
||||
<FormField control={form.control} name="newLastNumber" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Set Last Number To</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
If you set 99, the next auto-generated number will be 100.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
|
||||
<FormField control={form.control} name="reason" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Reason</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Why are you overriding?" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? "Applying..." : "Apply Override"}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
81
frontend/components/numbering/metrics-dashboard.tsx
Normal file
81
frontend/components/numbering/metrics-dashboard.tsx
Normal file
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { documentNumberingService } from "@/lib/services/document-numbering.service";
|
||||
import { NumberingMetrics } from "@/types/dto/numbering.dto";
|
||||
|
||||
export function MetricsDashboard() {
|
||||
const [metrics, setMetrics] = useState<Partial<NumberingMetrics>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchMetrics() {
|
||||
try {
|
||||
const data = await documentNumberingService.getMetrics();
|
||||
setMetrics(data);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch metrics", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
fetchMetrics();
|
||||
const interval = setInterval(fetchMetrics, 30000); // Poll every 30s
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
if (loading) return <div>Loading metrics...</div>;
|
||||
if (!metrics) return <div>No metrics available.</div>;
|
||||
|
||||
// Mock data mapping if real data is missing from backend stub
|
||||
const utilization = metrics.audit ? 45 : 0; // Placeholder until backend returns specific metric
|
||||
const generationRate = 120; // Placeholder
|
||||
const lockWaitP95 = 0.05; // Placeholder
|
||||
|
||||
return (
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Generation Rate</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{generationRate} /Hr</div>
|
||||
<p className="text-xs text-muted-foreground">+20.1% from last hour</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Sequence Utilization</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{utilization}%</div>
|
||||
<Progress value={utilization} className="mt-2" />
|
||||
<p className="text-xs text-muted-foreground mt-1">Average capacity used</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Lock Wait Time (P95)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{lockWaitP95}s</div>
|
||||
<p className="text-xs text-muted-foreground">Redis distributed lock latency</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Recent Errors</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{metrics.errors?.length || 0}</div>
|
||||
<p className="text-xs text-muted-foreground">In the last 24 hours</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { NumberingTemplate } from '@/lib/api/numbering';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
HoverCard,
|
||||
HoverCardContent,
|
||||
@@ -40,8 +39,10 @@ export interface TemplateEditorProps {
|
||||
template?: NumberingTemplate;
|
||||
projectId: number;
|
||||
projectName: string;
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
correspondenceTypes: any[];
|
||||
disciplines: any[];
|
||||
/* eslint-enable @typescript-eslint/no-explicit-any */
|
||||
onSave: (data: Partial<NumberingTemplate>) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
@@ -51,16 +52,14 @@ export function TemplateEditor({
|
||||
projectId,
|
||||
projectName,
|
||||
correspondenceTypes,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
disciplines,
|
||||
onSave,
|
||||
onCancel
|
||||
}: TemplateEditorProps) {
|
||||
const [format, setFormat] = useState(template?.formatTemplate || template?.templateFormat || '');
|
||||
const [format, setFormat] = useState(template?.formatTemplate || '');
|
||||
const [typeId, setTypeId] = useState<string>(template?.correspondenceTypeId?.toString() || '');
|
||||
const [disciplineId, setDisciplineId] = useState<string>(template?.disciplineId?.toString() || '0');
|
||||
const [padding, setPadding] = useState(template?.paddingLength || 4);
|
||||
const [reset, setReset] = useState(template?.resetAnnually ?? true);
|
||||
const [isActive, setIsActive] = useState(template?.isActive ?? true);
|
||||
const [reset, setReset] = useState(template?.resetSequenceYearly ?? true);
|
||||
|
||||
const [preview, setPreview] = useState('');
|
||||
|
||||
@@ -78,18 +77,14 @@ export function TemplateEditor({
|
||||
const t = correspondenceTypes.find(ct => ct.id.toString() === typeId);
|
||||
if (t) replacement = t.typeCode;
|
||||
}
|
||||
if (v.key === '{DISCIPLINE}' && disciplineId !== '0') {
|
||||
const d = disciplines.find(di => di.id.toString() === disciplineId);
|
||||
if (d) replacement = d.disciplineCode;
|
||||
}
|
||||
|
||||
previewText = previewText.replace(new RegExp(v.key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), replacement);
|
||||
});
|
||||
setPreview(previewText);
|
||||
}, [format, typeId, disciplineId, correspondenceTypes, disciplines]);
|
||||
}, [format, typeId, correspondenceTypes]);
|
||||
|
||||
const insertVariable = (variable: string) => {
|
||||
setFormat((prev) => prev + variable);
|
||||
setFormat((prev: string) => prev + variable);
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
@@ -97,13 +92,8 @@ export function TemplateEditor({
|
||||
...template,
|
||||
projectId: projectId,
|
||||
correspondenceTypeId: typeId && typeId !== '__default__' ? Number(typeId) : null,
|
||||
disciplineId: Number(disciplineId),
|
||||
formatTemplate: format,
|
||||
templateFormat: format, // Legacy support
|
||||
paddingLength: padding,
|
||||
resetAnnually: reset,
|
||||
isActive: isActive,
|
||||
exampleNumber: preview
|
||||
resetSequenceYearly: reset,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -115,9 +105,6 @@ export function TemplateEditor({
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h3 className="text-lg font-semibold">{template ? 'Edit Template' : 'New Template'}</h3>
|
||||
<Badge variant={isActive ? "default" : "secondary"}>
|
||||
{isActive ? 'Active' : 'Inactive'}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">Define how document numbers are generated for this project.</p>
|
||||
</div>
|
||||
@@ -125,10 +112,6 @@ export function TemplateEditor({
|
||||
<Badge variant="outline" className="text-base px-3 py-1 bg-slate-50">
|
||||
Project: {projectName}
|
||||
</Badge>
|
||||
<label className="flex items-center gap-2 cursor-pointer text-sm">
|
||||
<Checkbox checked={isActive} onCheckedChange={(c) => setIsActive(!!c)} />
|
||||
Active
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -143,7 +126,8 @@ export function TemplateEditor({
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__default__">Default (All Types)</SelectItem>
|
||||
{correspondenceTypes.map((type) => (
|
||||
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
|
||||
{correspondenceTypes.map((type: any) => (
|
||||
<SelectItem key={type.id} value={type.id.toString()}>
|
||||
{type.typeCode} - {type.typeName}
|
||||
</SelectItem>
|
||||
@@ -155,36 +139,7 @@ export function TemplateEditor({
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Discipline (Optional)</Label>
|
||||
<Select value={disciplineId} onValueChange={setDisciplineId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="All/None" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="0">All Disciplines (Default)</SelectItem>
|
||||
{disciplines.map((d) => (
|
||||
<SelectItem key={d.id} value={d.id.toString()}>
|
||||
{d.disciplineCode} - {d.disciplineName}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Specific discipline templates take precedence over 'All'.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Padding Length</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={padding}
|
||||
onChange={e => setPadding(Number(e.target.value))}
|
||||
min={1} max={10}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Reset Rule</Label>
|
||||
<div className="flex items-center h-10">
|
||||
|
||||
@@ -12,7 +12,28 @@ import { Button } from '@/components/ui/button';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { NumberingTemplate, numberingApi } from '@/lib/api/numbering';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { useOrganizations, useCorrespondenceTypes, useDisciplines, useContracts } from '@/hooks/use-master-data';
|
||||
import { Organization } from '@/types/organization';
|
||||
|
||||
// Local interfaces for Master Data since centralized ones are missing/fragmented
|
||||
interface CorrespondenceType {
|
||||
id: number;
|
||||
typeCode: string;
|
||||
typeName: string;
|
||||
}
|
||||
|
||||
interface Discipline {
|
||||
id: number;
|
||||
disciplineCode: string;
|
||||
}
|
||||
|
||||
|
||||
interface TemplateTesterProps {
|
||||
open: boolean;
|
||||
@@ -22,23 +43,45 @@ interface TemplateTesterProps {
|
||||
|
||||
export function TemplateTester({ open, onOpenChange, template }: TemplateTesterProps) {
|
||||
const [testData, setTestData] = useState({
|
||||
organizationId: "1",
|
||||
disciplineId: "1",
|
||||
originatorId: "",
|
||||
recipientId: "",
|
||||
correspondenceTypeId: "",
|
||||
disciplineId: "",
|
||||
year: new Date().getFullYear(),
|
||||
});
|
||||
const [generatedNumber, setGeneratedNumber] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
// Master Data Hooks
|
||||
const projectId = template?.projectId || 1;
|
||||
const { data: organizations } = useOrganizations({ isActive: true });
|
||||
const { data: correspondenceTypes } = useCorrespondenceTypes();
|
||||
const { data: contracts } = useContracts(projectId);
|
||||
|
||||
// Use first contract ID for disciplines, fallback to 1 or undefined
|
||||
const contractId = contracts?.[0]?.id;
|
||||
const { data: disciplines } = useDisciplines(contractId);
|
||||
|
||||
const handleGenerate = async () => {
|
||||
if (!template) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
// Note: generateTestNumber expects keys: organizationId, disciplineId
|
||||
const result = await numberingApi.generateTestNumber(template.id ?? 0, {
|
||||
organizationId: testData.organizationId,
|
||||
disciplineId: testData.disciplineId
|
||||
const result = await numberingApi.previewNumber({
|
||||
projectId: projectId,
|
||||
originatorId: parseInt(testData.originatorId || "0"),
|
||||
recipientOrganizationId: parseInt(testData.recipientId || "0"),
|
||||
typeId: parseInt(testData.correspondenceTypeId || "0"),
|
||||
disciplineId: parseInt(testData.disciplineId || "0"),
|
||||
});
|
||||
setGeneratedNumber(result.number);
|
||||
setGeneratedNumber(result.previewNumber);
|
||||
} catch (error: any) {
|
||||
console.error("Failed to generate test number", error);
|
||||
setGeneratedNumber("");
|
||||
// Assuming toast is available globally or we can use console for now,
|
||||
// but better to show visible error.
|
||||
// Alert is primitive but effective for 'tester' component debugging if toast not imported.
|
||||
// Actually, let's just set the error string in display if we can, or add a simple red text.
|
||||
setGeneratedNumber(`Error: ${error.response?.data?.message || error.message || "Unknown error"}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -46,7 +89,7 @@ export function TemplateTester({ open, onOpenChange, template }: TemplateTesterP
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Test Number Generation</DialogTitle>
|
||||
</DialogHeader>
|
||||
@@ -58,44 +101,109 @@ export function TemplateTester({ open, onOpenChange, template }: TemplateTesterP
|
||||
<Card className="p-6 mt-6 bg-muted/50 rounded-lg">
|
||||
<h3 className="text-lg font-semibold mb-4">Template Tester</h3>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<div className="md:col-span-2">
|
||||
<h4 className="text-sm font-medium mb-2">Test Parameters</h4>
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* Originator */}
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-medium">Organization</label>
|
||||
<Input
|
||||
value={testData.organizationId}
|
||||
onChange={(e) => setTestData({...testData, organizationId: e.target.value})}
|
||||
placeholder="Org ID"
|
||||
/>
|
||||
<label className="text-xs font-medium">Originator (ORG)</label>
|
||||
<Select
|
||||
value={testData.originatorId}
|
||||
onValueChange={(val) => setTestData({...testData, originatorId: val})}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select Originator" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(organizations as Organization[])?.map((org) => (
|
||||
<SelectItem key={org.id} value={org.id.toString()}>
|
||||
{org.organizationCode} - {org.organizationName}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Recipient */}
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-medium">Discipline</label>
|
||||
<Input
|
||||
<label className="text-xs font-medium">Recipient (REC)</label>
|
||||
<Select
|
||||
value={testData.recipientId}
|
||||
onValueChange={(val) => setTestData({...testData, recipientId: val})}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select Recipient" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(organizations as Organization[])?.map((org) => (
|
||||
<SelectItem key={org.id} value={org.id.toString()}>
|
||||
{org.organizationCode} - {org.organizationName}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Document Type */}
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-medium">Document Type (TYPE)</label>
|
||||
<Select
|
||||
value={testData.correspondenceTypeId}
|
||||
onValueChange={(val) => setTestData({...testData, correspondenceTypeId: val})}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select Type" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="0">Default (All Types)</SelectItem>
|
||||
{(correspondenceTypes as CorrespondenceType[])?.map((type) => (
|
||||
<SelectItem key={type.id} value={type.id.toString()}>
|
||||
{type.typeCode} - {type.typeName}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Discipline */}
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-medium">Discipline (DIS)</label>
|
||||
<Select
|
||||
value={testData.disciplineId}
|
||||
onChange={(e) => setTestData({...testData, disciplineId: e.target.value})}
|
||||
placeholder="Disc ID"
|
||||
/>
|
||||
onValueChange={(val) => setTestData({...testData, disciplineId: val})}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select Discipline" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="0">None</SelectItem>
|
||||
{(disciplines as Discipline[])?.map((disc) => (
|
||||
<SelectItem key={disc.id} value={disc.id.toString()}>
|
||||
{disc.disciplineCode}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Format: {template?.formatTemplate}
|
||||
<p className="text-xs text-muted-foreground mt-4">
|
||||
Format Preview: {template?.formatTemplate}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Button onClick={handleGenerate} className="w-full" disabled={loading || !template}>
|
||||
<Button onClick={handleGenerate} className="w-full mt-4" disabled={loading || !template}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Generate Test Number
|
||||
</Button>
|
||||
|
||||
{generatedNumber && (
|
||||
<Card className="p-4 bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-900 border text-center">
|
||||
<p className="text-sm text-muted-foreground mb-1">Generated Number:</p>
|
||||
<p className="text-2xl font-mono font-bold text-green-700 dark:text-green-400">
|
||||
<Card className={`p-4 mt-4 border text-center ${generatedNumber.startsWith('Error:') ? 'bg-red-50 border-red-200 text-red-700' : 'bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-900'}`}>
|
||||
<p className="text-sm text-muted-foreground mb-1">{generatedNumber.startsWith('Error:') ? 'Generation Failed:' : 'Generated Number:'}</p>
|
||||
<p className={`text-2xl font-mono font-bold ${generatedNumber.startsWith('Error:') ? 'text-red-700' : 'text-green-700 dark:text-green-400'}`}>
|
||||
{generatedNumber}
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
113
frontend/components/numbering/void-replace-form.tsx
Normal file
113
frontend/components/numbering/void-replace-form.tsx
Normal file
@@ -0,0 +1,113 @@
|
||||
"use client";
|
||||
|
||||
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 { Checkbox } from "@/components/ui/checkbox";
|
||||
import { toast } from "sonner";
|
||||
import { documentNumberingService } from "@/lib/services/document-numbering.service";
|
||||
import { VoidReplaceDto } from "@/types/dto/numbering.dto";
|
||||
import { useState } from "react";
|
||||
|
||||
const formSchema = z.object({
|
||||
documentNumber: z.string().min(3, "Document Number is required"),
|
||||
reason: z.string().min(5, "Reason must be at least 5 characters"),
|
||||
replace: z.boolean(),
|
||||
projectId: z.number()
|
||||
});
|
||||
|
||||
type VoidReplaceFormData = z.infer<typeof formSchema>;
|
||||
|
||||
export function VoidReplaceForm({ projectId = 1 }: { projectId?: number }) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const form = useForm<VoidReplaceFormData>({
|
||||
resolver: zodResolver(formSchema) as any,
|
||||
defaultValues: {
|
||||
documentNumber: "",
|
||||
reason: "",
|
||||
replace: false,
|
||||
projectId: projectId
|
||||
},
|
||||
});
|
||||
|
||||
async function onSubmit(values: z.infer<typeof formSchema>) {
|
||||
setLoading(true);
|
||||
try {
|
||||
const dto: VoidReplaceDto = {
|
||||
...values,
|
||||
};
|
||||
await documentNumberingService.voidAndReplace(dto);
|
||||
toast.success("Number voided successfully. " + (values.replace ? "Replacement generated." : ""));
|
||||
form.reset();
|
||||
} catch (error) {
|
||||
toast.error("Failed to void number. Check if it exists.");
|
||||
console.error(error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 border p-4 rounded-md">
|
||||
<h3 className="text-lg font-medium">Void & Replace Number</h3>
|
||||
<p className="text-sm text-gray-500">Void a generated number. Useful for skipped numbers or errors.</p>
|
||||
|
||||
<FormField control={form.control} name="documentNumber" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Document Number</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="e.g. LCB3-COR-GGL-2025-0001" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
|
||||
<FormField control={form.control} name="reason" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Reason</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Reason for voiding..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
|
||||
<FormField control={form.control} name="replace" render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border p-4">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<div className="space-y-1 leading-none">
|
||||
<FormLabel>
|
||||
Generate Replacement?
|
||||
</FormLabel>
|
||||
<FormDescription>
|
||||
If checked, a new number will be reserved immediately.
|
||||
</FormDescription>
|
||||
</div>
|
||||
</FormItem>
|
||||
)} />
|
||||
|
||||
<Button type="submit" variant="destructive" disabled={loading}>
|
||||
{loading ? "Processing..." : "Void Number"}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user