260319:1246 Fix fronend UUID #01
Build and Deploy / deploy (push) Successful in 7m56s

This commit is contained in:
admin
2026-03-19 12:46:33 +07:00
parent e8bdd7d7fc
commit 17afe3e392
19 changed files with 265 additions and 92 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ You value **Data Integrity**, **Security**, and **Clean Architecture**.
| Testing | 🔄 UAT In Progress | Per `01-05-acceptance-criteria.md` | | Testing | 🔄 UAT In Progress | Per `01-05-acceptance-criteria.md` |
| Deployment | 📋 Pending Go-Live | Blue-Green, QNAP Container Station | | Deployment | 📋 Pending Go-Live | Blue-Green, QNAP Container Station |
- **Goal:** Manage construction documents (Correspondence, RFA, Contract Drawings, Shop Drawings) - **Goal:** Manage construction documents (Correspondence, RFA, Circulation, Transmittal, Contract Drawings, Shop Drawings)
with complex multi-level approval workflows. with complex multi-level approval workflows.
- **Infrastructure:** - **Infrastructure:**
- **QNAP NAS:** Container Station — DMS Frontend/Backend, MariaDB, Redis, Elasticsearch, Nginx Proxy Manager, n8n + n8n-db, Tika, Gitea, RocketChat, cAdvisor, exporters - **QNAP NAS:** Container Station — DMS Frontend/Backend, MariaDB, Redis, Elasticsearch, Nginx Proxy Manager, n8n + n8n-db, Tika, Gitea, RocketChat, cAdvisor, exporters
@@ -277,7 +277,7 @@ export class CorrespondenceService {
'correspondence', 'correspondence',
savedCorr.id.toString(), savedCorr.id.toString(),
{ {
projectId: createDto.projectId, projectId: resolvedProjectId,
originatorId: userOrgId, originatorId: userOrgId,
disciplineId: createDto.disciplineId, disciplineId: createDto.disciplineId,
initiatorId: user.user_id, initiatorId: user.user_id,
@@ -297,7 +297,7 @@ export class CorrespondenceService {
title: createDto.subject, title: createDto.subject,
description: createDto.description, description: createDto.description,
status: 'DRAFT', status: 'DRAFT',
projectId: createDto.projectId, projectId: resolvedProjectId,
createdAt: new Date(), createdAt: new Date(),
}); });
@@ -39,6 +39,7 @@ export class DocumentNumberAudit {
'CANCEL', 'CANCEL',
'MANUAL_OVERRIDE', 'MANUAL_OVERRIDE',
'VOID', 'VOID',
'VOID_REPLACE',
'GENERATE', 'GENERATE',
], ],
default: 'CONFIRM', default: 'CONFIRM',
@@ -26,6 +26,7 @@ export class DocumentNumberError {
'SEQUENCE_EXHAUSTED', 'SEQUENCE_EXHAUSTED',
'RESERVATION_EXPIRED', 'RESERVATION_EXPIRED',
'DUPLICATE_NUMBER', 'DUPLICATE_NUMBER',
'GENERATE_ERROR',
], ],
}) })
errorType!: string; errorType!: string;
@@ -475,17 +475,35 @@ export class DocumentNumberingService {
return (await this.auditRepo.save(audit)) as unknown as DocumentNumberAudit; return (await this.auditRepo.save(audit)) as unknown as DocumentNumberAudit;
} }
private async logError(error: any, ctx: any, operation: string) { private mapErrorType(error: Error): string {
const name = error.name || '';
const msg = error.message || '';
if (name === 'ConflictException' || msg.includes('version'))
return 'VERSION_CONFLICT';
if (msg.includes('lock') || msg.includes('timeout')) return 'LOCK_TIMEOUT';
if (msg.includes('Redis') || msg.includes('redis')) return 'REDIS_ERROR';
if (msg.includes('duplicate') || msg.includes('Duplicate'))
return 'DUPLICATE_NUMBER';
if (msg.includes('validation') || msg.includes('Validation'))
return 'VALIDATION_ERROR';
if (msg.includes('exhausted') || msg.includes('maximum'))
return 'SEQUENCE_EXHAUSTED';
if (msg.includes('expired') || msg.includes('reservation'))
return 'RESERVATION_EXPIRED';
if (msg.includes('database') || msg.includes('query')) return 'DB_ERROR';
return 'GENERATE_ERROR';
}
private async logError(error: unknown, ctx: unknown, operation: string) {
try { try {
const err = error instanceof Error ? error : new Error(String(error));
const errEntity = this.errorRepo.create({ const errEntity = this.errorRepo.create({
errorMessage: error.message || 'Unknown Error', errorMessage: err.message || 'Unknown Error',
errorType: error.name || 'GENERATE_ERROR', // Simple mapping errorType: this.mapErrorType(err),
contextData: { contextData: {
// Mapped from context ...(typeof ctx === 'object' && ctx !== null ? ctx : {}),
...ctx,
operation, operation,
inputPayload: JSON.stringify(ctx), } as Record<string, unknown>,
},
}); });
await this.errorRepo.save(errEntity); await this.errorRepo.save(errEntity);
} catch (e) { } catch (e) {
@@ -1,12 +1,15 @@
import { IsInt, IsOptional, IsString, IsUUID } from 'class-validator'; import { IsInt, IsOptional, IsString } from 'class-validator';
import { Type } from 'class-transformer'; import { Type } from 'class-transformer';
export class SearchRfaDto { export class SearchRfaDto {
@IsUUID('all') @IsOptional()
projectUuid!: string; // ADR-019: Public UUID of the project @IsString()
projectId?: number | string; // ADR-019: Accept INT or UUID string
/** @internal Resolved INT ID — set by controller, do NOT expose in API */ @IsOptional()
projectId?: number; @IsInt()
@Type(() => Number)
statusId?: number;
@IsOptional() @IsOptional()
@IsInt() @IsInt()
+20 -5
View File
@@ -54,7 +54,10 @@ export class RfaController {
@Post(':uuid/submit') @Post(':uuid/submit')
@ApiOperation({ summary: 'Submit RFA to Workflow' }) @ApiOperation({ summary: 'Submit RFA to Workflow' })
@ApiParam({ name: 'uuid', description: 'RFA UUID (from correspondences.uuid)' }) @ApiParam({
name: 'uuid',
description: 'RFA UUID (from correspondences.uuid)',
})
@ApiBody({ type: SubmitRfaDto }) @ApiBody({ type: SubmitRfaDto })
@ApiResponse({ status: 200, description: 'RFA submitted successfully' }) @ApiResponse({ status: 200, description: 'RFA submitted successfully' })
@RequirePermission('rfa.create') @RequirePermission('rfa.create')
@@ -71,7 +74,10 @@ export class RfaController {
@Post(':uuid/action') @Post(':uuid/action')
@ApiOperation({ summary: 'Process Workflow Action (Approve/Reject)' }) @ApiOperation({ summary: 'Process Workflow Action (Approve/Reject)' })
@ApiParam({ name: 'uuid', description: 'RFA UUID (from correspondences.uuid)' }) @ApiParam({
name: 'uuid',
description: 'RFA UUID (from correspondences.uuid)',
})
@ApiBody({ type: WorkflowActionDto }) @ApiBody({ type: WorkflowActionDto })
@ApiResponse({ @ApiResponse({
status: 200, status: 200,
@@ -94,15 +100,24 @@ export class RfaController {
@ApiResponse({ status: 200, description: 'List of RFAs' }) @ApiResponse({ status: 200, description: 'List of RFAs' })
@RequirePermission('document.view') @RequirePermission('document.view')
async findAll(@Query() query: SearchRfaDto) { async findAll(@Query() query: SearchRfaDto) {
// ADR-019: resolve projectUuid → internal INT projectId // ADR-019: resolve projectId UUID→INT if provided
const project = await this.projectService.findOneByUuid(query.projectUuid); if (query.projectId) {
const pid = query.projectId;
const num = Number(pid);
if (typeof pid === 'string' && isNaN(num)) {
const project = await this.projectService.findOneByUuid(pid);
query.projectId = project.id; query.projectId = project.id;
}
}
return this.rfaService.findAll(query); return this.rfaService.findAll(query);
} }
@Get(':uuid') @Get(':uuid')
@ApiOperation({ summary: 'Get RFA details with revisions and items' }) @ApiOperation({ summary: 'Get RFA details with revisions and items' })
@ApiParam({ name: 'uuid', description: 'RFA UUID (from correspondences.uuid)' }) @ApiParam({
name: 'uuid',
description: 'RFA UUID (from correspondences.uuid)',
})
@ApiResponse({ status: 200, description: 'RFA details' }) @ApiResponse({ status: 200, description: 'RFA details' })
@RequirePermission('document.view') @RequirePermission('document.view')
findOne(@Param('uuid', ParseUuidPipe) uuid: string) { findOne(@Param('uuid', ParseUuidPipe) uuid: string) {
@@ -38,10 +38,9 @@ export class TransmittalItemDto {
} }
export class CreateTransmittalDto { export class CreateTransmittalDto {
@ApiProperty({ description: 'ID ของโครงการ', example: 1 }) @ApiProperty({ description: 'ID หรือ UUID ของโครงการ (ADR-019)' })
@IsInt()
@IsNotEmpty() @IsNotEmpty()
projectId!: number; projectId!: number | string;
@ApiProperty({ @ApiProperty({
description: 'เรื่อง', description: 'เรื่อง',
@@ -51,10 +50,16 @@ export class CreateTransmittalDto {
@IsNotEmpty() @IsNotEmpty()
subject!: string; subject!: string;
@ApiProperty({ description: 'ผู้รับ (Organization ID)', example: 2 }) @ApiProperty({ description: 'ผู้รับ Organization ID หรือ UUID (ADR-019)' })
@IsInt()
@IsNotEmpty() @IsNotEmpty()
recipientOrganizationId!: number; recipientOrganizationId!: number | string;
@ApiProperty({
description: 'Correspondence ID หรือ UUID (ADR-019)',
required: false,
})
@IsOptional()
correspondenceId?: number | string;
@ApiProperty({ @ApiProperty({
description: 'วัตถุประสงค์', description: 'วัตถุประสงค์',
@@ -65,6 +70,11 @@ export class CreateTransmittalDto {
@IsOptional() @IsOptional()
purpose?: TransmittalPurpose; purpose?: TransmittalPurpose;
@ApiProperty({ description: 'หมายเหตุ', required: false })
@IsString()
@IsOptional()
remarks?: string;
@ApiProperty({ description: 'รายการที่แนบ', type: [TransmittalItemDto] }) @ApiProperty({ description: 'รายการที่แนบ', type: [TransmittalItemDto] })
@IsArray() @IsArray()
@ValidateNested({ each: true }) @ValidateNested({ each: true })
@@ -21,6 +21,8 @@ import { CorrespondenceRevision } from '../correspondence/entities/correspondenc
import { CorrespondenceType } from '../correspondence/entities/correspondence-type.entity'; import { CorrespondenceType } from '../correspondence/entities/correspondence-type.entity';
import { CorrespondenceStatus } from '../correspondence/entities/correspondence-status.entity'; import { CorrespondenceStatus } from '../correspondence/entities/correspondence-status.entity';
import { Project } from '../project/entities/project.entity'; import { Project } from '../project/entities/project.entity';
import { Organization } from '../organization/entities/organization.entity';
import { CorrespondenceRecipient } from '../correspondence/entities/correspondence-recipient.entity';
@Injectable() @Injectable()
export class TransmittalService { export class TransmittalService {
@@ -55,6 +57,22 @@ export class TransmittalService {
return project.id; return project.id;
} }
/**
* ADR-019: Resolve organizationId (INT or UUID string) to internal INT ID
*/
private async resolveOrganizationId(orgId: number | string): Promise<number> {
if (typeof orgId === 'number') return orgId;
const num = Number(orgId);
if (!isNaN(num)) return num;
const org = await this.dataSource.manager.findOne(Organization, {
where: { uuid: orgId },
select: ['id'],
});
if (!org)
throw new NotFoundException(`Organization with UUID ${orgId} not found`);
return org.id;
}
async create(createDto: CreateTransmittalDto, user: User) { async create(createDto: CreateTransmittalDto, user: User) {
// 1. Get Transmittal Type (Assuming Code '901' or 'TRN') // 1. Get Transmittal Type (Assuming Code '901' or 'TRN')
const type = await this.typeRepo.findOne({ const type = await this.typeRepo.findOne({
@@ -119,11 +137,22 @@ export class TransmittalService {
}); });
await queryRunner.manager.save(revision); await queryRunner.manager.save(revision);
// ADR-019: Resolve recipientOrganizationId UUID→INT and create recipient record
const internalRecipientOrgId = await this.resolveOrganizationId(
createDto.recipientOrganizationId
);
const recipient = queryRunner.manager.create(CorrespondenceRecipient, {
correspondenceId: savedCorr.id,
recipientOrganizationId: internalRecipientOrgId,
recipientType: 'TO',
});
await queryRunner.manager.save(recipient);
// 5. Create Transmittal // 5. Create Transmittal
const transmittal = queryRunner.manager.create(Transmittal, { const transmittal = queryRunner.manager.create(Transmittal, {
correspondenceId: savedCorr.id, correspondenceId: savedCorr.id,
purpose: 'FOR_REVIEW', // Default or from DTO purpose: createDto.purpose || 'FOR_REVIEW',
// remarks: createDto.remarks, // Add if in DTO remarks: createDto.remarks,
}); });
const savedTransmittal = await queryRunner.manager.save(transmittal); const savedTransmittal = await queryRunner.manager.save(transmittal);
@@ -169,7 +198,6 @@ export class TransmittalService {
if (!correspondence) { if (!correspondence) {
throw new NotFoundException(`Transmittal with UUID ${uuid} not found`); throw new NotFoundException(`Transmittal with UUID ${uuid} not found`);
} }
return this.findOne(correspondence.id);
} }
async findOne(id: number) { async findOne(id: number) {
+1
View File
@@ -91,6 +91,7 @@ export class UserService {
.leftJoinAndSelect('assignments.role', 'role') .leftJoinAndSelect('assignments.role', 'role')
.select([ .select([
'user.user_id', 'user.user_id',
'user.uuid',
'user.username', 'user.username',
'user.email', 'user.email',
'user.firstName', 'user.firstName',
+4 -10
View File
@@ -23,17 +23,11 @@ function SearchContent() {
statuses: statusParam ? [statusParam] : [], statuses: statusParam ? [statusParam] : [],
}); });
// Construct search DTO // Construct search DTO — only send fields recognized by backend SearchQueryDto
// Backend uses forbidNonWhitelisted: true, so unknown fields (types[], statuses[]) cause 400
const searchDto = { const searchDto = {
q: query, q: query,
// Map internal types to backend expectation if needed, assumes direct mapping for now type: filters.types?.length ? filters.types[0] : undefined,
type: filters.types?.length === 1 ? filters.types[0] : undefined, // Backend might support single type or multiple?
// DTO says 'type?: string', 'status?: string'. If multiple, our backend might need adjustment or we only support single filter for now?
// Spec says "Advanced filters work (type, status)". Let's assume generic loose mapping for now or comma separated.
// Let's assume the hook and backend handle it. If backend expects single value, we pick first or join.
// Backend controller uses `SearchQueryDto`. Let's check DTO if I can view it.
// Actually, I'll pass them and let the service handle serialization if needed.
...filters
}; };
const { data: results, isLoading, isError } = useSearch(searchDto); const { data: results, isLoading, isError } = useSearch(searchDto);
@@ -50,7 +44,7 @@ function SearchContent() {
<p className="text-muted-foreground mt-1"> <p className="text-muted-foreground mt-1">
{isLoading {isLoading
? "Searching..." ? "Searching..."
: `Found ${results?.length || 0} results for "${query}"` : `Found ${results?.meta?.total ?? results?.data?.length ?? 0} results for "${query}"`
} }
</p> </p>
</div> </div>
@@ -70,8 +70,12 @@ export default function TransmittalDetailPage() {
</Button> </Button>
</Link> </Link>
<div> <div>
<h1 className="text-2xl font-bold">{transmittal.transmittalNo}</h1> <h1 className="text-2xl font-bold">
<p className="text-muted-foreground">{transmittal.subject}</p> {transmittal.correspondence?.correspondenceNumber || transmittal.transmittalNo}
</h1>
<p className="text-muted-foreground">
{transmittal.correspondence?.revisions?.find(r => r.isCurrent)?.title || transmittal.subject}
</p>
</div> </div>
</div> </div>
<Button variant="outline" onClick={handlePrint}> <Button variant="outline" onClick={handlePrint}>
@@ -93,7 +97,7 @@ export default function TransmittalDetailPage() {
<div> <div>
<p className="text-sm text-muted-foreground">Date</p> <p className="text-sm text-muted-foreground">Date</p>
<p className="font-medium"> <p className="font-medium">
{format(new Date(transmittal.createdAt), "dd MMM yyyy")} {format(new Date(transmittal.correspondence?.createdAt || transmittal.createdAt), "dd MMM yyyy")}
</p> </p>
</div> </div>
<div> <div>
@@ -103,7 +107,7 @@ export default function TransmittalDetailPage() {
href={`/correspondences/${transmittal.correspondence.uuid}`} href={`/correspondences/${transmittal.correspondence.uuid}`}
className="font-medium text-primary hover:underline" className="font-medium text-primary hover:underline"
> >
{transmittal.correspondence.correspondence_number} {transmittal.correspondence.correspondenceNumber}
</Link> </Link>
) : ( ) : (
<span className="text-muted-foreground">-</span> <span className="text-muted-foreground">-</span>
+16 -3
View File
@@ -3,7 +3,7 @@
import { ColumnDef } from '@tanstack/react-table'; import { ColumnDef } from '@tanstack/react-table';
import { Drawing } from '@/types/drawing'; import { Drawing } from '@/types/drawing';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { ArrowUpDown, MoreHorizontal } from 'lucide-react'; import { ArrowUpDown, MoreHorizontal, Pencil, Upload } from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
import { import {
DropdownMenu, DropdownMenu,
@@ -68,9 +68,22 @@ export const columns: ColumnDef<Drawing>[] = [
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<DropdownMenuItem asChild> <DropdownMenuItem asChild>
<Link href={`/drawings/${drawing.uuid}`}>View Details</Link> <Link href={`/drawings/${drawing.uuid}`}>
View Details
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href={`/drawings/${drawing.uuid}?edit=true`}>
<Pencil className="mr-2 h-4 w-4" />
Edit Detail
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href={`/drawings/${drawing.uuid}?upload=true`}>
<Upload className="mr-2 h-4 w-4" />
Upload Revision
</Link>
</DropdownMenuItem> </DropdownMenuItem>
{/* Add download/view functionality later */}
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
); );
+49 -15
View File
@@ -16,7 +16,7 @@ import {
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useCreateDrawing } from "@/hooks/use-drawing"; import { useCreateDrawing } from "@/hooks/use-drawing";
import { useContractDrawingCategories, useShopMainCategories, useShopSubCategories } from "@/hooks/use-master-data"; import { useContractDrawingCategories, useShopMainCategories, useShopSubCategories, useProjects } from "@/hooks/use-master-data";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { Loader2 } from "lucide-react"; import { Loader2 } from "lucide-react";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
@@ -24,7 +24,7 @@ import { Textarea } from "@/components/ui/textarea";
// Base Schema // Base Schema
const baseSchema = z.object({ const baseSchema = z.object({
drawingType: z.enum(["CONTRACT", "SHOP", "AS_BUILT"]), drawingType: z.enum(["CONTRACT", "SHOP", "AS_BUILT"]),
projectId: z.number().default(1), // Hardcoded for now projectId: z.string().min(1, "Project is required"),
file: z.instanceof(File, { message: "File is required" }), file: z.instanceof(File, { message: "File is required" }),
}); });
@@ -72,19 +72,21 @@ const formSchema = z.discriminatedUnion("drawingType", [
type DrawingFormData = z.infer<typeof formSchema>; type DrawingFormData = z.infer<typeof formSchema>;
interface DrawingUploadFormProps { export function DrawingUploadForm() {
projectId?: number;
}
export function DrawingUploadForm({ projectId = 1 }: DrawingUploadFormProps) {
const router = useRouter(); const router = useRouter();
// Hooks // Project list
const { data: contractCategories } = useContractDrawingCategories(projectId); const { data: projects = [], isLoading: isLoadingProjects } = useProjects();
const { data: shopMainCats } = useShopMainCategories(projectId);
// Selected project for category fetching
const [selectedProjectId, setSelectedProjectId] = useState<number | string | undefined>(undefined);
// Hooks — categories depend on selected project
const { data: contractCategories } = useContractDrawingCategories(selectedProjectId);
const { data: shopMainCats } = useShopMainCategories(selectedProjectId as number);
const [selectedShopMainCat, setSelectedShopMainCat] = useState<number | undefined>(); const [selectedShopMainCat, setSelectedShopMainCat] = useState<number | undefined>();
const { data: shopSubCats } = useShopSubCategories(projectId, selectedShopMainCat); const { data: shopSubCats } = useShopSubCategories(selectedProjectId as number, selectedShopMainCat);
const { const {
register, register,
@@ -95,18 +97,24 @@ export function DrawingUploadForm({ projectId = 1 }: DrawingUploadFormProps) {
} = useForm<DrawingFormData>({ } = useForm<DrawingFormData>({
resolver: zodResolver(formSchema) as any, resolver: zodResolver(formSchema) as any,
defaultValues: { defaultValues: {
projectId,
drawingType: "CONTRACT", drawingType: "CONTRACT",
} }
}); });
const drawingType = watch("drawingType"); const drawingType = watch("drawingType");
const watchedProjectId = watch("projectId");
const createMutation = useCreateDrawing(drawingType); const createMutation = useCreateDrawing(drawingType);
// Reset logic when type changes // When project changes, update selectedProjectId for category hooks
useEffect(() => { useEffect(() => {
// Optional: clear fields or set defaults if (!watchedProjectId) {
}, [drawingType]); setSelectedProjectId(undefined);
return;
}
// Try to resolve UUID→INT from projects list, or pass UUID directly
const project = projects.find((p: { id: string; uuid?: string }) => p.id === watchedProjectId || p.uuid === watchedProjectId) as { id: string; uuid?: string } | undefined;
setSelectedProjectId(project?.id ?? watchedProjectId);
}, [watchedProjectId, projects]);
const onSubmit = (data: DrawingFormData) => { const onSubmit = (data: DrawingFormData) => {
const formData = new FormData(); const formData = new FormData();
@@ -153,6 +161,32 @@ export function DrawingUploadForm({ projectId = 1 }: DrawingUploadFormProps) {
<h3 className="text-lg font-semibold mb-4">Drawing Information</h3> <h3 className="text-lg font-semibold mb-4">Drawing Information</h3>
<div className="space-y-4"> <div className="space-y-4">
{/* Project Selector */}
<div>
<Label>Project *</Label>
<Select
onValueChange={(v) => setValue("projectId", v)}
>
<SelectTrigger>
{isLoadingProjects ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<SelectValue placeholder="Select Project" />
)}
</SelectTrigger>
<SelectContent>
{projects.map((project: { id: string; projectName: string; projectCode: string }) => (
<SelectItem key={project.id} value={project.id}>
{project.projectCode} - {project.projectName}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.projectId && (
<p className="text-sm text-destructive">{errors.projectId.message}</p>
)}
</div>
<div> <div>
<Label>Drawing Type *</Label> <Label>Drawing Type *</Label>
<Select <Select
@@ -53,7 +53,7 @@ import { cn } from "@/lib/utils";
// Schema for items // Schema for items
const itemSchema = z.object({ const itemSchema = z.object({
itemType: z.enum(["DRAWING", "RFA", "CORRESPONDENCE"]), itemType: z.enum(["DRAWING", "RFA", "CORRESPONDENCE"]),
itemId: z.number().min(1, "Document is required"), itemId: z.coerce.number().min(1, "Document ID is required"),
description: z.string().optional(), description: z.string().optional(),
// Virtual fields for UI display // Virtual fields for UI display
documentNumber: z.string().optional(), documentNumber: z.string().optional(),
@@ -77,7 +77,7 @@ export function TransmittalForm() {
const [docOpen, setDocOpen] = useState(false); const [docOpen, setDocOpen] = useState(false);
const form = useForm<FormData>({ const form = useForm<FormData>({
resolver: zodResolver(formSchema), resolver: zodResolver(formSchema) as any,
defaultValues: { defaultValues: {
projectId: "", projectId: "",
recipientOrganizationId: "", recipientOrganizationId: "",
@@ -86,7 +86,7 @@ export function TransmittalForm() {
purpose: "FOR_APPROVAL", purpose: "FOR_APPROVAL",
remarks: "", remarks: "",
items: [ items: [
{ itemType: "DRAWING", itemId: 0, description: "" }, // Initial empty row { itemType: "DRAWING", itemId: 0, description: "" },
], ],
}, },
}); });
@@ -147,7 +147,8 @@ export function TransmittalForm() {
}; };
const selectedDocId = form.watch("correspondenceId"); const selectedDocId = form.watch("correspondenceId");
const selectedDoc = correspondences?.data?.find( const correspondenceList = correspondences?.data || [];
const selectedDoc = correspondenceList.find(
(c: { uuid: string }) => c.uuid === selectedDocId (c: { uuid: string }) => c.uuid === selectedDocId
); );
@@ -200,9 +201,9 @@ export function TransmittalForm() {
</SelectTrigger> </SelectTrigger>
</FormControl> </FormControl>
<SelectContent> <SelectContent>
{(Array.isArray(orgsList) ? orgsList : []).map((o: { uuid: string; organizationName?: string; orgCode?: string }) => ( {(Array.isArray(orgsList) ? orgsList : []).map((o: { uuid: string; organizationName?: string; organizationCode?: string }) => (
<SelectItem key={o.uuid} value={o.uuid}> <SelectItem key={o.uuid} value={o.uuid}>
{o.organizationName || o.orgCode} {o.organizationName || o.organizationCode}
</SelectItem> </SelectItem>
))} ))}
</SelectContent> </SelectContent>
@@ -233,7 +234,7 @@ export function TransmittalForm() {
)} )}
> >
{selectedDoc {selectedDoc
? selectedDoc.correspondence_number ? (selectedDoc as { correspondenceNumber?: string }).correspondenceNumber || 'Selected'
: "Select reference..."} : "Select reference..."}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" /> <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button> </Button>
@@ -245,11 +246,11 @@ export function TransmittalForm() {
<CommandList> <CommandList>
<CommandEmpty>No document found.</CommandEmpty> <CommandEmpty>No document found.</CommandEmpty>
<CommandGroup> <CommandGroup>
{correspondences?.data?.map( {correspondenceList.map(
(doc: { uuid: string; correspondence_number: string }) => ( (doc: { uuid: string; correspondenceNumber?: string }) => (
<CommandItem <CommandItem
key={doc.uuid} key={doc.uuid}
value={doc.correspondence_number} value={doc.correspondenceNumber || doc.uuid}
onSelect={() => { onSelect={() => {
form.setValue("correspondenceId", doc.uuid); form.setValue("correspondenceId", doc.uuid);
setDocOpen(false); setDocOpen(false);
@@ -263,7 +264,7 @@ export function TransmittalForm() {
: "opacity-0" : "opacity-0"
)} )}
/> />
{doc.correspondence_number} {doc.correspondenceNumber || doc.uuid}
</CommandItem> </CommandItem>
) )
)} )}
@@ -18,20 +18,25 @@ export function TransmittalList({ data }: TransmittalListProps) {
const columns: ColumnDef<Transmittal>[] = [ const columns: ColumnDef<Transmittal>[] = [
{ {
accessorKey: "transmittalNo", id: "transmittalNo",
header: "Transmittal No.", header: "Transmittal No.",
cell: ({ row }) => ( cell: ({ row }) => {
<span className="font-medium">{row.getValue("transmittalNo")}</span> const no = row.original.correspondence?.correspondenceNumber || row.original.transmittalNo || '-';
), return <span className="font-medium">{no}</span>;
},
}, },
{ {
accessorKey: "subject", id: "subject",
header: "Subject", header: "Subject",
cell: ({ row }) => ( cell: ({ row }) => {
<div className="max-w-[300px] truncate" title={row.getValue("subject")}> const currentRev = row.original.correspondence?.revisions?.find(r => r.isCurrent);
{row.getValue("subject")} const subject = currentRev?.title || row.original.subject || '-';
return (
<div className="max-w-[300px] truncate" title={subject}>
{subject}
</div> </div>
), );
},
}, },
{ {
accessorKey: "purpose", accessorKey: "purpose",
@@ -49,10 +54,13 @@ export function TransmittalList({ data }: TransmittalListProps) {
}, },
}, },
{ {
accessorKey: "createdAt", id: "createdAt",
header: "Date", header: "Date",
cell: ({ row }) => cell: ({ row }) => {
format(new Date(row.getValue("createdAt")), "dd MMM yyyy"), const dateStr = row.original.correspondence?.createdAt || row.original.createdAt;
if (!dateStr) return '-';
return format(new Date(dateStr), "dd MMM yyyy");
},
}, },
{ {
id: "actions", id: "actions",
+5 -3
View File
@@ -40,9 +40,11 @@ export interface Transmittal {
items?: TransmittalItem[]; items?: TransmittalItem[];
correspondence?: { correspondence?: {
uuid: string; uuid: string;
id?: number; // Excluded from API responses (ADR-019) id?: number;
correspondence_number: string; correspondenceNumber: string;
project_id: number; projectId: number;
createdAt?: string;
revisions?: { title?: string; isCurrent?: boolean }[];
}; };
} }
@@ -0,0 +1,30 @@
-- Delta 03: Fix ENUM mismatches in document_number_audit and document_number_errors
-- Issue: 'GENERATE' operation used by backend but not in DB ENUM → INSERT fails → correspondence creation blocked
-- Date: 2026-03-19
-- Applies to: lcbp3-v1.8.0-schema-02-tables.sql
-- 1. Add 'VOID' and 'GENERATE' to document_number_audit.operation ENUM
ALTER TABLE document_number_audit
MODIFY COLUMN operation ENUM(
'RESERVE',
'CONFIRM',
'MANUAL_OVERRIDE',
'VOID_REPLACE',
'CANCEL',
'VOID',
'GENERATE'
) NOT NULL DEFAULT 'CONFIRM' COMMENT 'ประเภทการดำเนินการ';
-- 2. Add missing error_type values to document_number_errors
ALTER TABLE document_number_errors
MODIFY COLUMN error_type ENUM(
'LOCK_TIMEOUT',
'VERSION_CONFLICT',
'DB_ERROR',
'REDIS_ERROR',
'VALIDATION_ERROR',
'SEQUENCE_EXHAUSTED',
'RESERVATION_EXPIRED',
'DUPLICATE_NUMBER',
'GENERATE_ERROR'
) NOT NULL COMMENT 'ประเภท error (9 types)';
@@ -1013,7 +1013,9 @@ CREATE TABLE document_number_audit (
'CONFIRM', 'CONFIRM',
'MANUAL_OVERRIDE', 'MANUAL_OVERRIDE',
'VOID_REPLACE', 'VOID_REPLACE',
'CANCEL' 'CANCEL',
'VOID',
'GENERATE'
) NOT NULL DEFAULT 'CONFIRM' COMMENT 'ประเภทการดำเนินการ', ) NOT NULL DEFAULT 'CONFIRM' COMMENT 'ประเภทการดำเนินการ',
STATUS ENUM( STATUS ENUM(
'RESERVED', 'RESERVED',
@@ -1074,8 +1076,16 @@ CREATE TABLE document_number_errors (
-- Database connection/query error -- Database connection/query error
'REDIS_ERROR', 'REDIS_ERROR',
-- Redis connection error -- Redis connection error
'VALIDATION_ERROR' -- Template/input validation error 'VALIDATION_ERROR',
) NOT NULL COMMENT 'ประเภท error (5 types)', -- Template/input validation error
'SEQUENCE_EXHAUSTED',
-- Counter reached maximum value
'RESERVATION_EXPIRED',
-- Reservation token expired
'DUPLICATE_NUMBER',
-- Duplicate document number detected
'GENERATE_ERROR' -- General generation error
) NOT NULL COMMENT 'ประเภท error (9 types)',
-- Error Details -- Error Details
error_message TEXT COMMENT 'ข้อความ error (stack top)', error_message TEXT COMMENT 'ข้อความ error (stack top)',
stack_trace TEXT COMMENT 'Stack trace แบบเต็ม (สำหรับ debugging)', stack_trace TEXT COMMENT 'Stack trace แบบเต็ม (สำหรับ debugging)',