This commit is contained in:
@@ -24,7 +24,7 @@ You value **Data Integrity**, **Security**, and **Clean Architecture**.
|
||||
| Testing | 🔄 UAT In Progress | Per `01-05-acceptance-criteria.md` |
|
||||
| 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.
|
||||
- **Infrastructure:**
|
||||
- **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',
|
||||
savedCorr.id.toString(),
|
||||
{
|
||||
projectId: createDto.projectId,
|
||||
projectId: resolvedProjectId,
|
||||
originatorId: userOrgId,
|
||||
disciplineId: createDto.disciplineId,
|
||||
initiatorId: user.user_id,
|
||||
@@ -297,7 +297,7 @@ export class CorrespondenceService {
|
||||
title: createDto.subject,
|
||||
description: createDto.description,
|
||||
status: 'DRAFT',
|
||||
projectId: createDto.projectId,
|
||||
projectId: resolvedProjectId,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ export class DocumentNumberAudit {
|
||||
'CANCEL',
|
||||
'MANUAL_OVERRIDE',
|
||||
'VOID',
|
||||
'VOID_REPLACE',
|
||||
'GENERATE',
|
||||
],
|
||||
default: 'CONFIRM',
|
||||
|
||||
@@ -26,6 +26,7 @@ export class DocumentNumberError {
|
||||
'SEQUENCE_EXHAUSTED',
|
||||
'RESERVATION_EXPIRED',
|
||||
'DUPLICATE_NUMBER',
|
||||
'GENERATE_ERROR',
|
||||
],
|
||||
})
|
||||
errorType!: string;
|
||||
|
||||
@@ -475,17 +475,35 @@ export class DocumentNumberingService {
|
||||
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 {
|
||||
const err = error instanceof Error ? error : new Error(String(error));
|
||||
const errEntity = this.errorRepo.create({
|
||||
errorMessage: error.message || 'Unknown Error',
|
||||
errorType: error.name || 'GENERATE_ERROR', // Simple mapping
|
||||
errorMessage: err.message || 'Unknown Error',
|
||||
errorType: this.mapErrorType(err),
|
||||
contextData: {
|
||||
// Mapped from context
|
||||
...ctx,
|
||||
...(typeof ctx === 'object' && ctx !== null ? ctx : {}),
|
||||
operation,
|
||||
inputPayload: JSON.stringify(ctx),
|
||||
},
|
||||
} as Record<string, unknown>,
|
||||
});
|
||||
await this.errorRepo.save(errEntity);
|
||||
} 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';
|
||||
|
||||
export class SearchRfaDto {
|
||||
@IsUUID('all')
|
||||
projectUuid!: string; // ADR-019: Public UUID of the project
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
projectId?: number | string; // ADR-019: Accept INT or UUID string
|
||||
|
||||
/** @internal Resolved INT ID — set by controller, do NOT expose in API */
|
||||
projectId?: number;
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Type(() => Number)
|
||||
statusId?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
|
||||
@@ -54,7 +54,10 @@ export class RfaController {
|
||||
|
||||
@Post(':uuid/submit')
|
||||
@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 })
|
||||
@ApiResponse({ status: 200, description: 'RFA submitted successfully' })
|
||||
@RequirePermission('rfa.create')
|
||||
@@ -71,7 +74,10 @@ export class RfaController {
|
||||
|
||||
@Post(':uuid/action')
|
||||
@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 })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
@@ -94,15 +100,24 @@ export class RfaController {
|
||||
@ApiResponse({ status: 200, description: 'List of RFAs' })
|
||||
@RequirePermission('document.view')
|
||||
async findAll(@Query() query: SearchRfaDto) {
|
||||
// ADR-019: resolve projectUuid → internal INT projectId
|
||||
const project = await this.projectService.findOneByUuid(query.projectUuid);
|
||||
query.projectId = project.id;
|
||||
// ADR-019: resolve projectId UUID→INT if provided
|
||||
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;
|
||||
}
|
||||
}
|
||||
return this.rfaService.findAll(query);
|
||||
}
|
||||
|
||||
@Get(':uuid')
|
||||
@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' })
|
||||
@RequirePermission('document.view')
|
||||
findOne(@Param('uuid', ParseUuidPipe) uuid: string) {
|
||||
|
||||
@@ -38,10 +38,9 @@ export class TransmittalItemDto {
|
||||
}
|
||||
|
||||
export class CreateTransmittalDto {
|
||||
@ApiProperty({ description: 'ID ของโครงการ', example: 1 })
|
||||
@IsInt()
|
||||
@ApiProperty({ description: 'ID หรือ UUID ของโครงการ (ADR-019)' })
|
||||
@IsNotEmpty()
|
||||
projectId!: number;
|
||||
projectId!: number | string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'เรื่อง',
|
||||
@@ -51,10 +50,16 @@ export class CreateTransmittalDto {
|
||||
@IsNotEmpty()
|
||||
subject!: string;
|
||||
|
||||
@ApiProperty({ description: 'ผู้รับ (Organization ID)', example: 2 })
|
||||
@IsInt()
|
||||
@ApiProperty({ description: 'ผู้รับ Organization ID หรือ UUID (ADR-019)' })
|
||||
@IsNotEmpty()
|
||||
recipientOrganizationId!: number;
|
||||
recipientOrganizationId!: number | string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Correspondence ID หรือ UUID (ADR-019)',
|
||||
required: false,
|
||||
})
|
||||
@IsOptional()
|
||||
correspondenceId?: number | string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'วัตถุประสงค์',
|
||||
@@ -65,6 +70,11 @@ export class CreateTransmittalDto {
|
||||
@IsOptional()
|
||||
purpose?: TransmittalPurpose;
|
||||
|
||||
@ApiProperty({ description: 'หมายเหตุ', required: false })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
remarks?: string;
|
||||
|
||||
@ApiProperty({ description: 'รายการที่แนบ', type: [TransmittalItemDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
|
||||
@@ -21,6 +21,8 @@ import { CorrespondenceRevision } from '../correspondence/entities/correspondenc
|
||||
import { CorrespondenceType } from '../correspondence/entities/correspondence-type.entity';
|
||||
import { CorrespondenceStatus } from '../correspondence/entities/correspondence-status.entity';
|
||||
import { Project } from '../project/entities/project.entity';
|
||||
import { Organization } from '../organization/entities/organization.entity';
|
||||
import { CorrespondenceRecipient } from '../correspondence/entities/correspondence-recipient.entity';
|
||||
|
||||
@Injectable()
|
||||
export class TransmittalService {
|
||||
@@ -55,6 +57,22 @@ export class TransmittalService {
|
||||
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) {
|
||||
// 1. Get Transmittal Type (Assuming Code '901' or 'TRN')
|
||||
const type = await this.typeRepo.findOne({
|
||||
@@ -119,11 +137,22 @@ export class TransmittalService {
|
||||
});
|
||||
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
|
||||
const transmittal = queryRunner.manager.create(Transmittal, {
|
||||
correspondenceId: savedCorr.id,
|
||||
purpose: 'FOR_REVIEW', // Default or from DTO
|
||||
// remarks: createDto.remarks, // Add if in DTO
|
||||
purpose: createDto.purpose || 'FOR_REVIEW',
|
||||
remarks: createDto.remarks,
|
||||
});
|
||||
const savedTransmittal = await queryRunner.manager.save(transmittal);
|
||||
|
||||
@@ -169,7 +198,6 @@ export class TransmittalService {
|
||||
if (!correspondence) {
|
||||
throw new NotFoundException(`Transmittal with UUID ${uuid} not found`);
|
||||
}
|
||||
return this.findOne(correspondence.id);
|
||||
}
|
||||
|
||||
async findOne(id: number) {
|
||||
|
||||
@@ -91,6 +91,7 @@ export class UserService {
|
||||
.leftJoinAndSelect('assignments.role', 'role')
|
||||
.select([
|
||||
'user.user_id',
|
||||
'user.uuid',
|
||||
'user.username',
|
||||
'user.email',
|
||||
'user.firstName',
|
||||
|
||||
@@ -23,17 +23,11 @@ function SearchContent() {
|
||||
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 = {
|
||||
q: query,
|
||||
// Map internal types to backend expectation if needed, assumes direct mapping for now
|
||||
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
|
||||
type: filters.types?.length ? filters.types[0] : undefined,
|
||||
};
|
||||
|
||||
const { data: results, isLoading, isError } = useSearch(searchDto);
|
||||
@@ -50,7 +44,7 @@ function SearchContent() {
|
||||
<p className="text-muted-foreground mt-1">
|
||||
{isLoading
|
||||
? "Searching..."
|
||||
: `Found ${results?.length || 0} results for "${query}"`
|
||||
: `Found ${results?.meta?.total ?? results?.data?.length ?? 0} results for "${query}"`
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -70,8 +70,12 @@ export default function TransmittalDetailPage() {
|
||||
</Button>
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">{transmittal.transmittalNo}</h1>
|
||||
<p className="text-muted-foreground">{transmittal.subject}</p>
|
||||
<h1 className="text-2xl font-bold">
|
||||
{transmittal.correspondence?.correspondenceNumber || transmittal.transmittalNo}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{transmittal.correspondence?.revisions?.find(r => r.isCurrent)?.title || transmittal.subject}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="outline" onClick={handlePrint}>
|
||||
@@ -93,7 +97,7 @@ export default function TransmittalDetailPage() {
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Date</p>
|
||||
<p className="font-medium">
|
||||
{format(new Date(transmittal.createdAt), "dd MMM yyyy")}
|
||||
{format(new Date(transmittal.correspondence?.createdAt || transmittal.createdAt), "dd MMM yyyy")}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
@@ -103,7 +107,7 @@ export default function TransmittalDetailPage() {
|
||||
href={`/correspondences/${transmittal.correspondence.uuid}`}
|
||||
className="font-medium text-primary hover:underline"
|
||||
>
|
||||
{transmittal.correspondence.correspondence_number}
|
||||
{transmittal.correspondence.correspondenceNumber}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { ColumnDef } from '@tanstack/react-table';
|
||||
import { Drawing } from '@/types/drawing';
|
||||
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 {
|
||||
DropdownMenu,
|
||||
@@ -68,9 +68,22 @@ export const columns: ColumnDef<Drawing>[] = [
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<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>
|
||||
{/* Add download/view functionality later */}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { useRouter } from "next/navigation";
|
||||
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 { Loader2 } from "lucide-react";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
@@ -24,7 +24,7 @@ import { Textarea } from "@/components/ui/textarea";
|
||||
// Base Schema
|
||||
const baseSchema = z.object({
|
||||
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" }),
|
||||
});
|
||||
|
||||
@@ -72,19 +72,21 @@ const formSchema = z.discriminatedUnion("drawingType", [
|
||||
|
||||
type DrawingFormData = z.infer<typeof formSchema>;
|
||||
|
||||
interface DrawingUploadFormProps {
|
||||
projectId?: number;
|
||||
}
|
||||
|
||||
export function DrawingUploadForm({ projectId = 1 }: DrawingUploadFormProps) {
|
||||
export function DrawingUploadForm() {
|
||||
const router = useRouter();
|
||||
|
||||
// Hooks
|
||||
const { data: contractCategories } = useContractDrawingCategories(projectId);
|
||||
const { data: shopMainCats } = useShopMainCategories(projectId);
|
||||
// Project list
|
||||
const { data: projects = [], isLoading: isLoadingProjects } = useProjects();
|
||||
|
||||
// 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 { data: shopSubCats } = useShopSubCategories(projectId, selectedShopMainCat);
|
||||
const { data: shopSubCats } = useShopSubCategories(selectedProjectId as number, selectedShopMainCat);
|
||||
|
||||
const {
|
||||
register,
|
||||
@@ -95,18 +97,24 @@ export function DrawingUploadForm({ projectId = 1 }: DrawingUploadFormProps) {
|
||||
} = useForm<DrawingFormData>({
|
||||
resolver: zodResolver(formSchema) as any,
|
||||
defaultValues: {
|
||||
projectId,
|
||||
drawingType: "CONTRACT",
|
||||
}
|
||||
});
|
||||
|
||||
const drawingType = watch("drawingType");
|
||||
const watchedProjectId = watch("projectId");
|
||||
const createMutation = useCreateDrawing(drawingType);
|
||||
|
||||
// Reset logic when type changes
|
||||
// When project changes, update selectedProjectId for category hooks
|
||||
useEffect(() => {
|
||||
// Optional: clear fields or set defaults
|
||||
}, [drawingType]);
|
||||
if (!watchedProjectId) {
|
||||
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 formData = new FormData();
|
||||
@@ -153,6 +161,32 @@ export function DrawingUploadForm({ projectId = 1 }: DrawingUploadFormProps) {
|
||||
<h3 className="text-lg font-semibold mb-4">Drawing Information</h3>
|
||||
|
||||
<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>
|
||||
<Label>Drawing Type *</Label>
|
||||
<Select
|
||||
|
||||
@@ -53,7 +53,7 @@ import { cn } from "@/lib/utils";
|
||||
// Schema for items
|
||||
const itemSchema = z.object({
|
||||
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(),
|
||||
// Virtual fields for UI display
|
||||
documentNumber: z.string().optional(),
|
||||
@@ -77,7 +77,7 @@ export function TransmittalForm() {
|
||||
const [docOpen, setDocOpen] = useState(false);
|
||||
|
||||
const form = useForm<FormData>({
|
||||
resolver: zodResolver(formSchema),
|
||||
resolver: zodResolver(formSchema) as any,
|
||||
defaultValues: {
|
||||
projectId: "",
|
||||
recipientOrganizationId: "",
|
||||
@@ -86,7 +86,7 @@ export function TransmittalForm() {
|
||||
purpose: "FOR_APPROVAL",
|
||||
remarks: "",
|
||||
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 selectedDoc = correspondences?.data?.find(
|
||||
const correspondenceList = correspondences?.data || [];
|
||||
const selectedDoc = correspondenceList.find(
|
||||
(c: { uuid: string }) => c.uuid === selectedDocId
|
||||
);
|
||||
|
||||
@@ -200,9 +201,9 @@ export function TransmittalForm() {
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<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}>
|
||||
{o.organizationName || o.orgCode}
|
||||
{o.organizationName || o.organizationCode}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
@@ -233,7 +234,7 @@ export function TransmittalForm() {
|
||||
)}
|
||||
>
|
||||
{selectedDoc
|
||||
? selectedDoc.correspondence_number
|
||||
? (selectedDoc as { correspondenceNumber?: string }).correspondenceNumber || 'Selected'
|
||||
: "Select reference..."}
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
@@ -245,11 +246,11 @@ export function TransmittalForm() {
|
||||
<CommandList>
|
||||
<CommandEmpty>No document found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{correspondences?.data?.map(
|
||||
(doc: { uuid: string; correspondence_number: string }) => (
|
||||
{correspondenceList.map(
|
||||
(doc: { uuid: string; correspondenceNumber?: string }) => (
|
||||
<CommandItem
|
||||
key={doc.uuid}
|
||||
value={doc.correspondence_number}
|
||||
value={doc.correspondenceNumber || doc.uuid}
|
||||
onSelect={() => {
|
||||
form.setValue("correspondenceId", doc.uuid);
|
||||
setDocOpen(false);
|
||||
@@ -263,7 +264,7 @@ export function TransmittalForm() {
|
||||
: "opacity-0"
|
||||
)}
|
||||
/>
|
||||
{doc.correspondence_number}
|
||||
{doc.correspondenceNumber || doc.uuid}
|
||||
</CommandItem>
|
||||
)
|
||||
)}
|
||||
|
||||
@@ -18,20 +18,25 @@ export function TransmittalList({ data }: TransmittalListProps) {
|
||||
|
||||
const columns: ColumnDef<Transmittal>[] = [
|
||||
{
|
||||
accessorKey: "transmittalNo",
|
||||
id: "transmittalNo",
|
||||
header: "Transmittal No.",
|
||||
cell: ({ row }) => (
|
||||
<span className="font-medium">{row.getValue("transmittalNo")}</span>
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const no = row.original.correspondence?.correspondenceNumber || row.original.transmittalNo || '-';
|
||||
return <span className="font-medium">{no}</span>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "subject",
|
||||
id: "subject",
|
||||
header: "Subject",
|
||||
cell: ({ row }) => (
|
||||
<div className="max-w-[300px] truncate" title={row.getValue("subject")}>
|
||||
{row.getValue("subject")}
|
||||
</div>
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const currentRev = row.original.correspondence?.revisions?.find(r => r.isCurrent);
|
||||
const subject = currentRev?.title || row.original.subject || '-';
|
||||
return (
|
||||
<div className="max-w-[300px] truncate" title={subject}>
|
||||
{subject}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "purpose",
|
||||
@@ -49,10 +54,13 @@ export function TransmittalList({ data }: TransmittalListProps) {
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
id: "createdAt",
|
||||
header: "Date",
|
||||
cell: ({ row }) =>
|
||||
format(new Date(row.getValue("createdAt")), "dd MMM yyyy"),
|
||||
cell: ({ row }) => {
|
||||
const dateStr = row.original.correspondence?.createdAt || row.original.createdAt;
|
||||
if (!dateStr) return '-';
|
||||
return format(new Date(dateStr), "dd MMM yyyy");
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
|
||||
@@ -40,9 +40,11 @@ export interface Transmittal {
|
||||
items?: TransmittalItem[];
|
||||
correspondence?: {
|
||||
uuid: string;
|
||||
id?: number; // Excluded from API responses (ADR-019)
|
||||
correspondence_number: string;
|
||||
project_id: number;
|
||||
id?: number;
|
||||
correspondenceNumber: string;
|
||||
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',
|
||||
'MANUAL_OVERRIDE',
|
||||
'VOID_REPLACE',
|
||||
'CANCEL'
|
||||
'CANCEL',
|
||||
'VOID',
|
||||
'GENERATE'
|
||||
) NOT NULL DEFAULT 'CONFIRM' COMMENT 'ประเภทการดำเนินการ',
|
||||
STATUS ENUM(
|
||||
'RESERVED',
|
||||
@@ -1074,8 +1076,16 @@ CREATE TABLE document_number_errors (
|
||||
-- Database connection/query error
|
||||
'REDIS_ERROR',
|
||||
-- Redis connection error
|
||||
'VALIDATION_ERROR' -- Template/input validation error
|
||||
) NOT NULL COMMENT 'ประเภท error (5 types)',
|
||||
'VALIDATION_ERROR',
|
||||
-- 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_message TEXT COMMENT 'ข้อความ error (stack top)',
|
||||
stack_trace TEXT COMMENT 'Stack trace แบบเต็ม (สำหรับ debugging)',
|
||||
|
||||
Reference in New Issue
Block a user