This commit is contained in:
+62
-11
@@ -90,16 +90,16 @@ specs/
|
||||
|
||||
### 📋 หมวดหมู่เอกสาร
|
||||
|
||||
| หมวด | วัตถุประสงค์ | ไฟล์สำคัญ | ผู้ดูแล |
|
||||
|------|---------|---------|--------|
|
||||
| **00-Overview** | ภาพรวม, Product Vision, KPI, Training | Gap 1/5/6/9 | Project Manager / PO |
|
||||
| **01-Requirements** | User Stories, UAT, UI, Edge Cases | Gap 2/3/4/10 | Business Analyst + PO |
|
||||
| **02-Architecture** | สถาปัตยกรรมและการออกแบบ | — | Tech Lead + Architects |
|
||||
| **03-Data-and-Storage** | Schema v1.8.0, Migration Scope | Gap 7 | Backend Lead + DBA |
|
||||
| **04-Infrastructure-OPS** | Deployment, Operations, Release Policy | Gap 8 | DevOps Team |
|
||||
| **05-Engineering-Guidelines** | แผนการพัฒนาและ Implementation | — | Development Team Leads |
|
||||
| **06-Decision-Records** | Architecture Decision Records (17+1) | ADR-018 | Tech Lead + Senior Devs |
|
||||
| **99-archives** | Archived / Tasks | — | All Team Members |
|
||||
| หมวด | วัตถุประสงค์ | ไฟล์สำคัญ | ผู้ดูแล |
|
||||
| ----------------------------- | -------------------------------------- | ------------ | ----------------------- |
|
||||
| **00-Overview** | ภาพรวม, Product Vision, KPI, Training | Gap 1/5/6/9 | Project Manager / PO |
|
||||
| **01-Requirements** | User Stories, UAT, UI, Edge Cases | Gap 2/3/4/10 | Business Analyst + PO |
|
||||
| **02-Architecture** | สถาปัตยกรรมและการออกแบบ | — | Tech Lead + Architects |
|
||||
| **03-Data-and-Storage** | Schema v1.8.0, Migration Scope | Gap 7 | Backend Lead + DBA |
|
||||
| **04-Infrastructure-OPS** | Deployment, Operations, Release Policy | Gap 8 | DevOps Team |
|
||||
| **05-Engineering-Guidelines** | แผนการพัฒนาและ Implementation | — | Development Team Leads |
|
||||
| **06-Decision-Records** | Architecture Decision Records (17+1) | ADR-018 | Tech Lead + Senior Devs |
|
||||
| **99-archives** | Archived / Tasks | — | All Team Members |
|
||||
|
||||
---
|
||||
|
||||
@@ -546,7 +546,58 @@ graph LR
|
||||
**Last Updated**: 2026-02-24
|
||||
```
|
||||
|
||||
### 5. ใช้ Consistent Terminology
|
||||
### 5. UUID Conventions (ADR-019)
|
||||
|
||||
โครงการใช้ **Hybrid Identifier Strategy** — INT PK สำหรับ internal, UUIDv7 สำหรับ public API
|
||||
|
||||
#### Backend Entity Pattern
|
||||
|
||||
```typescript
|
||||
// ❌ ผิด — ส่ง INT id ออก public API
|
||||
@Get(':id')
|
||||
findOne(@Param('id', ParseIntPipe) id: number) { ... }
|
||||
|
||||
// ✅ ถูกต้อง — ใช้ UUID สำหรับ public API
|
||||
@Get(':uuid')
|
||||
findOne(@Param('uuid', ParseUuidPipe) uuid: string) { ... }
|
||||
```
|
||||
|
||||
#### Backend DTO — FK References
|
||||
|
||||
```typescript
|
||||
// ❌ ผิด — frontend ไม่มี INT id (ถูก @Exclude() แล้ว)
|
||||
@IsInt()
|
||||
projectId!: number;
|
||||
|
||||
// ✅ ถูกต้อง — รับ UUID จาก frontend, resolve เป็น INT ใน controller
|
||||
@IsUUID()
|
||||
projectUuid!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
projectId?: number; // resolved internally by controller
|
||||
```
|
||||
|
||||
#### Frontend — Select Components
|
||||
|
||||
```typescript
|
||||
// ❌ ผิด — parseInt บน UUID string จะได้ค่าผิด
|
||||
onValueChange={(v) => setValue("projectId", parseInt(v))}
|
||||
|
||||
// ✅ ถูกต้อง — ส่ง UUID string ตรงๆ
|
||||
onValueChange={(v) => setValue("projectUuid", v)}
|
||||
```
|
||||
|
||||
#### Serialization Behavior
|
||||
|
||||
- `TransformInterceptor` ใช้ `instanceToPlain()` → `@Exclude()` และ `@Expose()` มีผล
|
||||
- Entity ทั้ง 14 ตาราง มี `@Exclude()` บน INT `id` → API response **ไม่มี** `id` เป็นตัวเลข
|
||||
- Project & Contract มี `@Expose({ name: 'id' })` บน `uuid` → API response มี `id` = UUID string
|
||||
- Entity อื่นๆ มี `uuid` field แยก → API response มี `uuid` แต่ไม่มี `id`
|
||||
|
||||
> ดูรายละเอียดเพิ่มเติมที่ [05-07-hybrid-uuid-implementation-plan.md](./specs/05-Engineering-Guidelines/05-07-hybrid-uuid-implementation-plan.md)
|
||||
|
||||
### 6. ใช้ Consistent Terminology
|
||||
|
||||
อ้างอิงจาก [glossary.md](./specs/00-Overview/00-02-glossary.md) เสมอ
|
||||
|
||||
|
||||
@@ -589,6 +589,15 @@ This project is **Internal Use Only** - ลิขสิทธิ์เป็น
|
||||
- ✅ ADR-019 UUID fixes: Drawing admin pages (5), Contracts, Disciplines, Tags, RFA Types
|
||||
- ✅ Fixed contract edit form (UUID mismatch), disciplines dropdown (hardcoded projectId), tags crash (empty Select value)
|
||||
|
||||
### 🔄 ADR-019 Hybrid UUID Migration (Mar 2026)
|
||||
|
||||
- ✅ **Phase 1-4**: Schema, entities, API layer — all 14 tables migrated
|
||||
- ✅ **Phase 5 (Partial)**: Frontend routes, services, hooks migrated to UUID
|
||||
- ✅ Drawing search: `projectUuid` sent to backend, resolved in controller
|
||||
- ✅ Drawing detail page: mock API replaced with real UUID-based services
|
||||
- 🔄 **Phase 5.4 (Pending)**: FK reference UUID migration — `correspondences/form.tsx`, `user-dialog.tsx`, `numbering/template-tester.tsx`, `rfas/page.tsx` still use `parseInt()` on UUID values (see `specs/05-Engineering-Guidelines/05-07-hybrid-uuid-implementation-plan.md`)
|
||||
- 📋 **Phase 6**: Unit + integration tests for UUID-based routes
|
||||
|
||||
### 🔄 Next: Go-Live Preparation
|
||||
|
||||
- 🔄 **UAT**: ทำ User Acceptance Testing ตาม `01-05-acceptance-criteria.md`
|
||||
|
||||
@@ -101,6 +101,7 @@ import { MigrationModule } from './modules/migration/migration.module';
|
||||
username: configService.get<string>('DB_USERNAME'),
|
||||
password: configService.get<string>('DB_PASSWORD'),
|
||||
database: configService.get<string>('DB_DATABASE'),
|
||||
charset: 'utf8mb4',
|
||||
autoLoadEntities: true,
|
||||
synchronize: false, // Production Ready: false
|
||||
}),
|
||||
|
||||
@@ -45,7 +45,9 @@ export class FileStorageService {
|
||||
*/
|
||||
async upload(file: Express.Multer.File, userId: number): Promise<Attachment> {
|
||||
const tempId = uuidv4();
|
||||
const fileExt = path.extname(file.originalname);
|
||||
// Fix: แปลงชื่อไฟล์จาก Latin1 → UTF-8 (Multer/busboy decodes as Latin1 by default)
|
||||
const originalFilename = this.fixMulterFilename(file.originalname);
|
||||
const fileExt = path.extname(originalFilename);
|
||||
const storedFilename = `${uuidv4()}${fileExt}`;
|
||||
const tempPath = path.join(this.tempDir, storedFilename);
|
||||
|
||||
@@ -62,7 +64,7 @@ export class FileStorageService {
|
||||
|
||||
// 3. สร้าง Record ใน Database
|
||||
const attachment = this.attachmentRepository.create({
|
||||
originalFilename: file.originalname,
|
||||
originalFilename,
|
||||
storedFilename: storedFilename,
|
||||
filePath: tempPath, // เก็บ path ปัจจุบันไปก่อน
|
||||
mimeType: file.mimetype,
|
||||
@@ -197,6 +199,22 @@ export class FileStorageService {
|
||||
return { stream, attachment };
|
||||
}
|
||||
|
||||
/**
|
||||
* แก้ปัญหา Multer/busboy ถอดรหัสชื่อไฟล์เป็น Latin1 แทน UTF-8
|
||||
* ทำให้ภาษาไทยกลายเป็น mojibake (เช่น ผรม → 脿赂聹脿赂拢脿赂隆)
|
||||
* วิธีแก้: แปลง latin1 bytes กลับเป็น UTF-8
|
||||
*/
|
||||
private fixMulterFilename(originalname: string): string {
|
||||
try {
|
||||
const decoded = Buffer.from(originalname, 'latin1').toString('utf8');
|
||||
// ตรวจสอบว่า decoded string มี valid UTF-8 characters
|
||||
// ถ้า originalname เป็น ASCII อยู่แล้ว ผลลัพธ์จะเหมือนเดิม
|
||||
return decoded;
|
||||
} catch {
|
||||
return originalname;
|
||||
}
|
||||
}
|
||||
|
||||
private calculateChecksum(buffer: Buffer): string {
|
||||
return crypto.createHash('sha256').update(buffer).digest('hex');
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ export const databaseConfig: TypeOrmModuleOptions = {
|
||||
username: process.env.DB_USERNAME || 'root',
|
||||
password: process.env.DB_PASSWORD || 'Center#2025',
|
||||
database: process.env.DB_DATABASE || 'lcbp3_dev',
|
||||
charset: 'utf8mb4',
|
||||
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
|
||||
migrations: [__dirname + '/../database/migrations/*{.ts,.js}'],
|
||||
synchronize: false,
|
||||
|
||||
@@ -35,13 +35,17 @@ import { RequirePermission } from '../../common/decorators/require-permission.de
|
||||
import { Audit } from '../../common/decorators/audit.decorator';
|
||||
import { ParseUuidPipe } from '../../common/pipes/parse-uuid.pipe';
|
||||
import { User } from '../user/entities/user.entity';
|
||||
import { ProjectService } from '../project/project.service';
|
||||
|
||||
@ApiTags('Drawings - AS Built')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RbacGuard)
|
||||
@Controller('drawings/asbuilt')
|
||||
export class AsBuiltDrawingController {
|
||||
constructor(private readonly asBuiltDrawingService: AsBuiltDrawingService) {}
|
||||
constructor(
|
||||
private readonly asBuiltDrawingService: AsBuiltDrawingService,
|
||||
private readonly projectService: ProjectService
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create new AS Built Drawing' })
|
||||
@@ -74,6 +78,10 @@ export class AsBuiltDrawingController {
|
||||
@ApiResponse({ status: 200, description: 'List of AS Built Drawings' })
|
||||
@RequirePermission('drawing.view')
|
||||
async findAll(@Query() searchDto: SearchAsBuiltDrawingDto) {
|
||||
const project = await this.projectService.findOneByUuid(
|
||||
searchDto.projectUuid
|
||||
);
|
||||
searchDto.projectId = project.id;
|
||||
return this.asBuiltDrawingService.findAll(searchDto);
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import { RequirePermission } from '../../common/decorators/require-permission.de
|
||||
import { ParseUuidPipe } from '../../common/pipes/parse-uuid.pipe';
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
import { User } from '../user/entities/user.entity';
|
||||
import { ProjectService } from '../project/project.service';
|
||||
|
||||
@ApiTags('Contract Drawings')
|
||||
@ApiBearerAuth()
|
||||
@@ -29,7 +30,8 @@ import { User } from '../user/entities/user.entity';
|
||||
@Controller('drawings/contract')
|
||||
export class ContractDrawingController {
|
||||
constructor(
|
||||
private readonly contractDrawingService: ContractDrawingService
|
||||
private readonly contractDrawingService: ContractDrawingService,
|
||||
private readonly projectService: ProjectService
|
||||
) {}
|
||||
|
||||
// Force rebuild for DTO changes
|
||||
@@ -47,7 +49,11 @@ export class ContractDrawingController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Search Contract Drawings' })
|
||||
@RequirePermission('document.view') // สิทธิ์ ID 31: ดูเอกสารทั่วไป
|
||||
findAll(@Query() searchDto: SearchContractDrawingDto) {
|
||||
async findAll(@Query() searchDto: SearchContractDrawingDto) {
|
||||
const project = await this.projectService.findOneByUuid(
|
||||
searchDto.projectUuid
|
||||
);
|
||||
searchDto.projectId = project.id;
|
||||
return this.contractDrawingService.findAll(searchDto);
|
||||
}
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ import { DrawingMasterDataController } from './drawing-master-data.controller';
|
||||
// Modules
|
||||
import { FileStorageModule } from '../../common/file-storage/file-storage.module';
|
||||
import { UserModule } from '../user/user.module';
|
||||
import { ProjectModule } from '../project/project.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -62,6 +63,7 @@ import { UserModule } from '../user/user.module';
|
||||
]),
|
||||
FileStorageModule,
|
||||
UserModule,
|
||||
ProjectModule,
|
||||
],
|
||||
providers: [
|
||||
ShopDrawingService,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { IsNumber, IsOptional, IsString, Min } from 'class-validator';
|
||||
import { IsNumber, IsOptional, IsString, IsUUID, Min } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
@@ -6,10 +6,15 @@ import { Type } from 'class-transformer';
|
||||
* DTO for searching/filtering AS Built Drawings
|
||||
*/
|
||||
export class SearchAsBuiltDrawingDto {
|
||||
@ApiProperty({ description: 'Project ID' })
|
||||
@ApiProperty({ description: 'Project UUID' })
|
||||
@IsUUID()
|
||||
projectUuid!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Project ID (resolved internally)' })
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
projectId!: number;
|
||||
@IsOptional()
|
||||
projectId?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Filter by Main Category ID' })
|
||||
@Type(() => Number)
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { IsInt, IsOptional, IsString, IsNotEmpty } from 'class-validator';
|
||||
import { IsInt, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class SearchContractDrawingDto {
|
||||
@IsUUID()
|
||||
projectUuid!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Type(() => Number)
|
||||
@IsNotEmpty()
|
||||
projectId!: number; // จำเป็น: ใส่ !
|
||||
projectId?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { IsInt, IsOptional, IsString } from 'class-validator';
|
||||
import { IsInt, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class SearchShopDrawingDto {
|
||||
@IsUUID()
|
||||
projectUuid!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Type(() => Number)
|
||||
projectId!: number; // จำเป็น: ใส่ !
|
||||
projectId?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
|
||||
@@ -21,13 +21,17 @@ import { ParseUuidPipe } from '../../common/pipes/parse-uuid.pipe';
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
import { User } from '../user/entities/user.entity';
|
||||
import { Audit } from '../../common/decorators/audit.decorator'; // Import
|
||||
import { ProjectService } from '../project/project.service';
|
||||
|
||||
@ApiTags('Shop Drawings')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RbacGuard)
|
||||
@Controller('drawings/shop')
|
||||
export class ShopDrawingController {
|
||||
constructor(private readonly shopDrawingService: ShopDrawingService) {}
|
||||
constructor(
|
||||
private readonly shopDrawingService: ShopDrawingService,
|
||||
private readonly projectService: ProjectService
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create new Shop Drawing with initial revision' })
|
||||
@@ -40,7 +44,11 @@ export class ShopDrawingController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Search Shop Drawings' })
|
||||
@RequirePermission('drawing.view')
|
||||
findAll(@Query() searchDto: SearchShopDrawingDto) {
|
||||
async findAll(@Query() searchDto: SearchShopDrawingDto) {
|
||||
const project = await this.projectService.findOneByUuid(
|
||||
searchDto.projectUuid
|
||||
);
|
||||
searchDto.projectId = project.id;
|
||||
return this.shopDrawingService.findAll(searchDto);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,33 +1,87 @@
|
||||
"use client";
|
||||
|
||||
import { use } from "react";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ArrowLeft, Download, FileText, GitCompare } from "lucide-react";
|
||||
import { ArrowLeft, Download, FileText, Loader2 } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { RevisionHistory } from "@/components/drawings/revision-history";
|
||||
import { format } from "date-fns";
|
||||
import { drawingApi } from "@/lib/api/drawings";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { contractDrawingService } from "@/lib/services/contract-drawing.service";
|
||||
import { shopDrawingService } from "@/lib/services/shop-drawing.service";
|
||||
import { asBuiltDrawingService } from "@/lib/services/asbuilt-drawing.service";
|
||||
|
||||
export default async function DrawingDetailPage({
|
||||
async function fetchDrawingByUuid(uuid: string) {
|
||||
// Try each drawing type until one succeeds
|
||||
try {
|
||||
const result = await contractDrawingService.getByUuid(uuid);
|
||||
if (result?.data) return { ...result.data, _type: "CONTRACT" };
|
||||
} catch { /* not found in contract drawings */ }
|
||||
|
||||
try {
|
||||
const result = await shopDrawingService.getByUuid(uuid);
|
||||
if (result?.data) return { ...result.data, _type: "SHOP" };
|
||||
} catch { /* not found in shop drawings */ }
|
||||
|
||||
try {
|
||||
const result = await asBuiltDrawingService.getByUuid(uuid);
|
||||
if (result?.data) return { ...result.data, _type: "AS_BUILT" };
|
||||
} catch { /* not found in asbuilt drawings */ }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function DrawingDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ uuid: string }>;
|
||||
}) {
|
||||
const { uuid } = await params;
|
||||
const { uuid } = use(params);
|
||||
|
||||
const { data: drawing, isLoading } = useQuery({
|
||||
queryKey: ["drawing-detail", uuid],
|
||||
queryFn: () => fetchDrawingByUuid(uuid),
|
||||
enabled: !!uuid,
|
||||
});
|
||||
|
||||
if (!uuid) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
// TODO: Replace mock drawingApi with real service call using UUID
|
||||
// For now, keep using the mock API with a numeric fallback
|
||||
const drawingId = parseInt(uuid);
|
||||
const drawing = !isNaN(drawingId) ? await drawingApi.getById(drawingId) : undefined;
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-24">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!drawing) {
|
||||
notFound();
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Link href="/drawings">
|
||||
<Button variant="ghost" size="icon">
|
||||
<ArrowLeft className="h-5 w-5" />
|
||||
</Button>
|
||||
</Link>
|
||||
<h1 className="text-2xl font-bold">Drawing Not Found</h1>
|
||||
</div>
|
||||
<p className="text-muted-foreground">
|
||||
The drawing with UUID <code>{uuid}</code> could not be found.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const drawingNumber = drawing.contractDrawingNo || drawing.drawingNumber || "N/A";
|
||||
const title = drawing.title || drawing.currentRevision?.title || "Untitled";
|
||||
const revisions = drawing.revisions || [];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
@@ -39,10 +93,8 @@ export default async function DrawingDetailPage({
|
||||
</Button>
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">{drawing.drawingNumber}</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{drawing.title}
|
||||
</p>
|
||||
<h1 className="text-2xl font-bold">{drawingNumber}</h1>
|
||||
<p className="text-muted-foreground">{title}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -51,12 +103,6 @@ export default async function DrawingDetailPage({
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Download Current
|
||||
</Button>
|
||||
{(drawing.revisionCount ?? 0) > 1 && (
|
||||
<Button variant="outline">
|
||||
<GitCompare className="mr-2 h-4 w-4" />
|
||||
Compare Revisions
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -67,31 +113,31 @@ export default async function DrawingDetailPage({
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<CardTitle className="text-xl">Drawing Details</CardTitle>
|
||||
<Badge>{drawing.type}</Badge>
|
||||
<Badge>{drawing._type}</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">Discipline</p>
|
||||
<p className="text-sm font-medium text-muted-foreground">Drawing Number</p>
|
||||
<p className="font-medium mt-1">{drawingNumber}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">Type</p>
|
||||
<p className="font-medium mt-1">{drawing._type}</p>
|
||||
</div>
|
||||
{drawing.volumePage && (
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">Volume Page</p>
|
||||
<p className="font-medium mt-1">{drawing.volumePage}</p>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">Created</p>
|
||||
<p className="font-medium mt-1">
|
||||
{typeof drawing.discipline === 'object' && drawing.discipline
|
||||
? `${drawing.discipline.disciplineName} (${drawing.discipline.disciplineCode})`
|
||||
: drawing.discipline || 'N/A'}
|
||||
{drawing.createdAt ? format(new Date(drawing.createdAt), "dd MMM yyyy") : "N/A"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">Sheet Number</p>
|
||||
<p className="font-medium mt-1">{drawing.sheetNumber}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">Scale</p>
|
||||
<p className="font-medium mt-1">{drawing.scale || "N/A"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">Latest Issue Date</p>
|
||||
<p className="font-medium mt-1">{drawing.issueDate ? format(new Date(drawing.issueDate), "dd MMM yyyy") : 'N/A'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
@@ -111,7 +157,7 @@ export default async function DrawingDetailPage({
|
||||
|
||||
{/* Revisions */}
|
||||
<div className="space-y-6">
|
||||
<RevisionHistory revisions={drawing.revisions || []} />
|
||||
<RevisionHistory revisions={revisions} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -16,7 +16,7 @@ import Link from "next/link";
|
||||
import { useProjects } from "@/hooks/use-master-data";
|
||||
|
||||
export default function DrawingsPage() {
|
||||
const [selectedProjectId, setSelectedProjectId] = useState<number | undefined>(undefined);
|
||||
const [selectedProjectUuid, setSelectedProjectUuid] = useState<string | undefined>(undefined);
|
||||
const { data: projects = [], isLoading: isLoadingProjects } = useProjects();
|
||||
|
||||
return (
|
||||
@@ -40,8 +40,8 @@ export default function DrawingsPage() {
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-sm font-medium">Project:</span>
|
||||
<Select
|
||||
value={selectedProjectId?.toString() ?? ""}
|
||||
onValueChange={(v) => setSelectedProjectId(v ? parseInt(v) : undefined)}
|
||||
value={selectedProjectUuid ?? ""}
|
||||
onValueChange={(v) => setSelectedProjectUuid(v || undefined)}
|
||||
>
|
||||
<SelectTrigger className="w-[300px]">
|
||||
{isLoadingProjects ? (
|
||||
@@ -51,8 +51,8 @@ export default function DrawingsPage() {
|
||||
)}
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{projects.map((project: { id: number; projectName: string; projectCode: string }) => (
|
||||
<SelectItem key={project.id} value={String(project.id)}>
|
||||
{projects.map((project: { id: string; projectName: string; projectCode: string }) => (
|
||||
<SelectItem key={project.id} value={project.id}>
|
||||
{project.projectCode} - {project.projectName}
|
||||
</SelectItem>
|
||||
))}
|
||||
@@ -60,18 +60,18 @@ export default function DrawingsPage() {
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{!selectedProjectId ? (
|
||||
{!selectedProjectUuid ? (
|
||||
<div className="text-center py-12 text-muted-foreground border rounded-lg border-dashed">
|
||||
Please select a project to view drawings.
|
||||
</div>
|
||||
) : (
|
||||
<DrawingTabs projectId={selectedProjectId} />
|
||||
<DrawingTabs projectUuid={selectedProjectUuid} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DrawingTabs({ projectId }: { projectId: number }) {
|
||||
function DrawingTabs({ projectUuid }: { projectUuid: string }) {
|
||||
const [search, setSearch] = useState("");
|
||||
// We can add more specific filters here (e.g. category) later
|
||||
|
||||
@@ -98,15 +98,15 @@ function DrawingTabs({ projectId }: { projectId: number }) {
|
||||
</div>
|
||||
|
||||
<TabsContent value="contract" className="mt-0">
|
||||
<DrawingList type="CONTRACT" projectId={projectId} filters={{ search }} />
|
||||
<DrawingList type="CONTRACT" projectUuid={projectUuid} filters={{ search }} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="shop" className="mt-0">
|
||||
<DrawingList type="SHOP" projectId={projectId} filters={{ search }} />
|
||||
<DrawingList type="SHOP" projectUuid={projectUuid} filters={{ search }} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="asbuilt" className="mt-0">
|
||||
<DrawingList type="AS_BUILT" projectId={projectId} filters={{ search }} />
|
||||
<DrawingList type="AS_BUILT" projectUuid={projectUuid} filters={{ search }} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)
|
||||
|
||||
@@ -14,11 +14,11 @@ type DrawingSearchParams = SearchContractDrawingDto | SearchShopDrawingDto | Sea
|
||||
|
||||
interface DrawingListProps {
|
||||
type: 'CONTRACT' | 'SHOP' | 'AS_BUILT';
|
||||
projectId: number;
|
||||
projectUuid: string;
|
||||
filters?: Partial<DrawingSearchParams>;
|
||||
}
|
||||
|
||||
export function DrawingList({ type, projectId, filters }: DrawingListProps) {
|
||||
export function DrawingList({ type, projectUuid, filters }: DrawingListProps) {
|
||||
const [pagination, setPagination] = useState<PaginationState>({
|
||||
pageIndex: 0,
|
||||
pageSize: 20,
|
||||
@@ -30,7 +30,7 @@ export function DrawingList({ type, projectId, filters }: DrawingListProps) {
|
||||
data: response,
|
||||
isLoading,
|
||||
} = useDrawings(type, {
|
||||
projectId,
|
||||
projectUuid,
|
||||
...filters,
|
||||
page: pagination.pageIndex + 1, // API is 1-based
|
||||
limit: pagination.pageSize,
|
||||
|
||||
@@ -32,9 +32,9 @@ export interface CreateAsBuiltDrawingRevisionDto {
|
||||
|
||||
// --- Search ---
|
||||
export interface SearchAsBuiltDrawingDto {
|
||||
projectId: number;
|
||||
projectUuid: string;
|
||||
search?: string;
|
||||
|
||||
page?: number; // Default: 1
|
||||
pageSize?: number; // Default: 20
|
||||
limit?: number; // Default: 20
|
||||
}
|
||||
|
||||
@@ -29,13 +29,13 @@ export type UpdateContractDrawingDto = Partial<CreateContractDrawingDto>;
|
||||
|
||||
// --- Search ---
|
||||
export interface SearchContractDrawingDto {
|
||||
/** จำเป็นต้องระบุ Project ID เสมอ */
|
||||
projectId: number;
|
||||
/** จำเป็นต้องระบุ Project UUID เสมอ */
|
||||
projectUuid: string;
|
||||
|
||||
volumeId?: number;
|
||||
mapCatId?: number;
|
||||
search?: string; // ค้นหาจาก Title หรือ Number
|
||||
|
||||
page?: number; // Default: 1
|
||||
pageSize?: number; // Default: 20
|
||||
limit?: number; // Default: 20
|
||||
}
|
||||
|
||||
@@ -30,11 +30,11 @@ export interface CreateShopDrawingRevisionDto {
|
||||
|
||||
// --- Search ---
|
||||
export interface SearchShopDrawingDto {
|
||||
projectId: number;
|
||||
projectUuid: string;
|
||||
mainCategoryId?: number;
|
||||
subCategoryId?: number;
|
||||
search?: string;
|
||||
|
||||
page?: number; // Default: 1
|
||||
pageSize?: number; // Default: 20
|
||||
limit?: number; // Default: 20
|
||||
}
|
||||
|
||||
+145
-40
File diff suppressed because one or more lines are too long
@@ -26,6 +26,9 @@ services:
|
||||
reservations:
|
||||
cpus: "0.5"
|
||||
memory: 1G
|
||||
command: >-
|
||||
--character-set-server=utf8mb4
|
||||
--collation-server=utf8mb4_general_ci
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: "Center#2025"
|
||||
MYSQL_DATABASE: "lcbp3"
|
||||
|
||||
@@ -14,7 +14,7 @@ This document outlines the step-by-step implementation plan to integrate UUIDv7
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Database Foundation (✅ COMPLETED)
|
||||
## Phase 1: Database Foundation (✅ COMPLETED — 2026-03-16)
|
||||
|
||||
- [x] Create ADR-019 document
|
||||
- [x] Add `uuid UUID` columns (MariaDB native type) to 14 public-facing tables in schema SQL
|
||||
@@ -50,7 +50,7 @@ This document outlines the step-by-step implementation plan to integrate UUIDv7
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Backend — TypeORM Base Entity & UUID Utilities
|
||||
## Phase 2: Backend — TypeORM Base Entity & UUID Utilities (✅ COMPLETED)
|
||||
|
||||
> **Simplified by MariaDB Native UUID Type:** MariaDB 10.7+ stores UUID as `BINARY(16)` internally but auto-converts to/from string format. No manual binary conversion utilities or TypeORM transformers needed.
|
||||
|
||||
@@ -94,7 +94,7 @@ npm install -D @types/uuid
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Backend — Update Existing Entities
|
||||
## Phase 3: Backend — Update Existing Entities (✅ COMPLETED)
|
||||
|
||||
For each of the 14 public-facing entities, extend or mix in the UUID column:
|
||||
|
||||
@@ -135,7 +135,7 @@ export class Correspondence extends UuidBaseEntity {
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Backend — API Layer Changes
|
||||
## Phase 4: Backend — API Layer Changes (✅ COMPLETED)
|
||||
|
||||
### 4.1 UUID Pipe (Parameter Validation)
|
||||
|
||||
@@ -211,25 +211,62 @@ async findByUuidOrId(identifier: string): Promise<Entity> {
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Frontend — UUID Integration
|
||||
## Phase 5: Frontend — UUID Integration (🔄 PARTIAL — see 5.4)
|
||||
|
||||
### 5.1 API Client Updates
|
||||
### 5.1 API Client Updates (✅ COMPLETED)
|
||||
|
||||
- Update all API calls to use UUID in URL paths instead of INT id
|
||||
- Update TanStack Query cache keys to use UUID
|
||||
- Update Zustand stores to key by UUID
|
||||
- [x] Update all API calls to use UUID in URL paths instead of INT id
|
||||
- [x] Update TanStack Query cache keys to use UUID
|
||||
- [x] Service functions renamed `getById` → `getByUuid` (12 services)
|
||||
- [x] Hooks updated with UUID-based cache keys and mutation params
|
||||
|
||||
### 5.2 Route Parameters
|
||||
### 5.2 Route Parameters (✅ COMPLETED)
|
||||
|
||||
```typescript
|
||||
// BEFORE: /correspondences/[id]
|
||||
// AFTER: /correspondences/[uuid]
|
||||
```
|
||||
|
||||
### 5.3 Form Handling
|
||||
- [x] `/correspondences/[uuid]`, `/circulation/[uuid]`, `/drawings/[uuid]` migrated
|
||||
- [ ] `/rfas/[id]` and `/transmittals/[id]` — NOT migrated (separate feature scope)
|
||||
|
||||
- Hidden `uuid` field in forms for edit operations
|
||||
- No changes needed for create operations (UUID generated server-side)
|
||||
### 5.3 Form Handling (✅ PARTIAL)
|
||||
|
||||
- [x] Drawing search: `projectUuid` sent to backend (resolved in controller)
|
||||
- [x] Drawing detail page: UUID-based service calls replace mock API
|
||||
- [ ] Correspondence form: still sends `parseInt(projectId)` — see 5.4
|
||||
- [ ] User dialog: still sends `parseInt(orgId)` — see 5.4
|
||||
|
||||
### 5.4 Remaining: FK Reference UUID Migration (❌ PENDING)
|
||||
|
||||
> **Root Cause:** Backend Create/Update DTOs still accept **integer FK IDs** (e.g., `projectId`, `fromOrganizationId`), but the API **no longer returns integer IDs** in responses (stripped by `@Exclude()` + `instanceToPlain()` in `TransformInterceptor`). Frontend forms that use `parseInt()` on Select values break because the values are either UUID strings or `undefined`.
|
||||
|
||||
#### Pattern: Drawing Search (✅ FIXED — reference implementation)
|
||||
|
||||
- Backend DTO accepts `projectUuid: string` instead of `projectId: number`
|
||||
- Controller resolves: `projectService.findOneByUuid(dto.projectUuid)` → `dto.projectId = project.id`
|
||||
- Frontend sends UUID string directly (no `parseInt`)
|
||||
|
||||
#### Remaining Issues
|
||||
|
||||
| File | Field | Entity | Issue |
|
||||
|------|-------|--------|-------|
|
||||
| `correspondences/form.tsx:212` | `projectId` | Project | `parseInt(p.id)` where `p.id` = UUID string (garbled number) |
|
||||
| `correspondences/form.tsx:326` | `fromOrganizationId` | Organization | `parseInt(String(org.id))` where `org.id` = undefined (NaN) |
|
||||
| `correspondences/form.tsx:349` | `toOrganizationId` | Organization | Same as above |
|
||||
| `admin/users/page.tsx:47` | `primaryOrganizationId` (filter) | Organization | `parseInt(selectedOrgId)` where value = UUID string |
|
||||
| `admin/user-dialog.tsx:226` | `primaryOrganizationId` | Organization | `parseInt(val)` where `org.id` = undefined → `"0"` fallback |
|
||||
| `numbering/template-tester.tsx:71-74` | `originatorOrganizationId`, `recipientOrganizationId` | Organization | `parseInt` on org UUID |
|
||||
| `rfas/page.tsx:17` | `projectId` (URL param) | Project | `parseInt(searchParams.get('projectId'))` — UUID if from URL |
|
||||
|
||||
#### Fix Strategy (same pattern as Drawing Search fix)
|
||||
|
||||
For each affected backend DTO:
|
||||
1. Add `projectUuid?: string` / `organizationUuid?: string` field
|
||||
2. Controller resolves UUID → INT id via respective service's `findOneByUuid()`
|
||||
3. Frontend sends UUID string directly (remove `parseInt`)
|
||||
|
||||
**Estimated Effort:** M (2-3 days) — requires backend DTO changes for Correspondence, User, Numbering modules
|
||||
|
||||
---
|
||||
|
||||
@@ -259,20 +296,21 @@ async findByUuidOrId(identifier: string): Promise<Entity> {
|
||||
|
||||
## Implementation Order (Priority)
|
||||
|
||||
| Order | Task | Effort | Depends On |
|
||||
|-------|------|--------|------------|
|
||||
| 1 | UuidBaseEntity (no transformer needed — MariaDB native UUID) | S | Phase 1 |
|
||||
| 2 | Install `uuid` package | XS | — |
|
||||
| 3 | Update 14 entity files with uuid column | M | Task 1 |
|
||||
| 4 | Create ParseUuidPipe | S | — |
|
||||
| 5 | Update controllers to use UUID params | L | Tasks 3, 4 |
|
||||
| 6 | Update services with findByUuid methods | L | Task 3 |
|
||||
| 7 | Update DTOs to expose uuid, hide id | M | Task 3 |
|
||||
| 8 | Update frontend API calls | L | Tasks 5, 6, 7 |
|
||||
| 9 | Update frontend routes | M | Task 8 |
|
||||
| 10 | Write unit + integration tests | M | Tasks 1-7 |
|
||||
ำ
|
||||
**Estimated Total Effort:** ~3-5 days for backend, ~2-3 days for frontend
|
||||
| Order | Task | Effort | Status |
|
||||
|-------|------|--------|--------|
|
||||
| 1 | UuidBaseEntity (no transformer needed — MariaDB native UUID) | S | ✅ Done |
|
||||
| 2 | Install `uuid` package | XS | ✅ Done |
|
||||
| 3 | Update 14 entity files with uuid column | M | ✅ Done |
|
||||
| 4 | Create ParseUuidPipe | S | ✅ Done |
|
||||
| 5 | Update controllers to use UUID params | L | ✅ Done |
|
||||
| 6 | Update services with findByUuid methods | L | ✅ Done |
|
||||
| 7 | Update DTOs to expose uuid, hide id | M | ✅ Done |
|
||||
| 8 | Update frontend API calls & routes | L | ✅ Done |
|
||||
| 9 | Drawing search: projectUuid migration | S | ✅ Done (2026-03-18) |
|
||||
| 10 | FK reference UUID migration (Correspondence, User, Numbering) | M | ❌ Pending (see Phase 5.4) |
|
||||
| 11 | Write unit + integration tests | M | ❌ Pending |
|
||||
|
||||
**Estimated Remaining Effort:** ~2-3 days for FK migration + ~2 days for tests
|
||||
|
||||
---
|
||||
|
||||
|
||||
Reference in New Issue
Block a user