377 lines
15 KiB
Plaintext
377 lines
15 KiB
Plaintext
ผมได้ตรวจสอบไฟล์ `FullStackJS_Guidelines01.md` และ `01_lcbp3_v1_1_0.sql` ของคุณแล้ว และได้อัปเดตไฟล์ Guidelines (Markdown) ให้สอดคล้องกับโครงสร้างฐานข้อมูล (SQL) ที่คุณกำหนดไว้อย่างสมบูรณ์ครับ
|
||
|
||
การเปลี่ยนแปลงที่สำคัญคือ:
|
||
|
||
1. **การจัดการ UI (UI Conflict):** แก้ไขความขัดแย้งในไฟล์เดิมที่ระบุทั้ง **Tailwind/Shadcn** และ **Bootstrap** ผมได้รวมศูนย์การพัฒนา UI ไปที่ **Tailwind/Shadcn** ตามที่ระบุไว้ในโปรไฟล์นักพัฒนา (Frontend Developer Profile) และลบส่วนของ Bootstrap ที่ซ้ำซ้อนออกไป
|
||
2. **DMS-Specific Conventions:** อัปเดตส่วนนี้ทั้งหมดเพื่อให้ตรงกับสคีม SQL ของคุณ
|
||
* เปลี่ยนชื่อโปรเจกต์อ้างอิงเป็น **LCBP3-DMS**
|
||
* ปรับปรุงแผนผัง **Domain Modules** ให้สะท้อนโครงสร้างจริง (เช่น `correspondences` เป็นศูนย์กลาง, เพิ่ม `circulations`)
|
||
* อัปเดตตาราง **AuditLog** ให้ตรงกับฟิลด์ใน SQL (เช่น เพิ่ม `entity_type`, `details_json`, `ip_address`)
|
||
* อัปเดตตัวอย่าง **RBAC Permissions** ให้ตรงกับสิทธิ์ที่มีในตาราง `permissions` ของคุณ
|
||
* ชี้แจง
|
||
เรื่อง **File Handling** ว่าตาราง `attachments` จะเชื่อมโยงผ่าน `correspondence_id`
|
||
* อัปเดตส่วน **Reporting** เพื่ออ้างอิงถึง `VIEWS` (เช่น `v_current_rfas`) ที่คุณได้สร้างไว้ใน SQL
|
||
* ย้ายส่วน **"Recommended Enhancements"** (เช่น soft delete, indexes) ที่มีอยู่แล้วใน SQL ไปยังส่วนใหม่ชื่อ **"Implemented Standards"** เพื่อสะท้อนว่างานส่วนนี้เสร็จแล้ว
|
||
|
||
นี่คือไฟล์ `FullStackJS_Guidelines01.md` ฉบับที่อัปเดตแล้วครับ:
|
||
|
||
-----
|
||
|
||
# FullStackJS Development Guidelines
|
||
|
||
## 🧠 General Philosophy
|
||
|
||
Unified best practices for **NestJS Backend**, **NextJS Frontend**, and **Tailwind-based UI/UX** development in TypeScript environments.
|
||
Focus on **clarity**, **maintainability**, **consistency**, and **accessibility** across the entire stack.
|
||
|
||
-----
|
||
|
||
## ⚙️ TypeScript General Guidelines
|
||
|
||
### Basic Principles
|
||
|
||
- Use **English** for all code and documentation.
|
||
- Explicitly type all variables, parameters, and return values.
|
||
- Avoid `any`; create custom types or interfaces.
|
||
- Use **JSDoc** for public classes and methods.
|
||
- Export only **one main symbol** per file.
|
||
- Avoid blank lines within functions.
|
||
|
||
### Naming Conventions
|
||
|
||
| Entity | Convention | Example |
|
||
|:--|:--|:--|
|
||
| Classes | PascalCase | `UserService` |
|
||
| Variables & Functions | camelCase | `getUserInfo` |
|
||
| Files & Folders | kebab-case | `user-service.ts` |
|
||
| Environment Variables | UPPERCASE | `DATABASE_URL` |
|
||
| Booleans | Verb + Noun | `isActive`, `canDelete`, `hasPermission` |
|
||
|
||
Use full words — no abbreviations — except for standard ones (`API`, `URL`, `req`, `res`, `err`, `ctx`).
|
||
|
||
-----
|
||
|
||
## 🧩 Functions
|
||
|
||
- Write short, single-purpose functions (\<20 lines).
|
||
- Use **early returns** to reduce nesting.
|
||
- Use **map**, **filter**, **reduce** instead of loops when suitable.
|
||
- Prefer **arrow functions** for short logic, **named functions** otherwise.
|
||
- Use **default parameters** over null checks.
|
||
- Group multiple parameters into a single object (RO-RO pattern).
|
||
- Return typed objects, not primitives.
|
||
- Maintain a single abstraction level per function.
|
||
|
||
-----
|
||
|
||
## 🧱 Data Handling
|
||
|
||
- Encapsulate data in composite types.
|
||
- Use **immutability** with `readonly` and `as const`.
|
||
- Perform validations in classes or DTOs, not within business functions.
|
||
- Always validate data using typed DTOs.
|
||
|
||
-----
|
||
|
||
## 🧰 Classes
|
||
|
||
- Follow **SOLID** principles.
|
||
- Prefer **composition over inheritance**.
|
||
- Define **interfaces** for contracts.
|
||
- Keep classes focused and small (\<200 lines, \<10 methods, \<10 properties).
|
||
|
||
-----
|
||
|
||
## 🚨 Error Handling
|
||
|
||
- Use exceptions for unexpected errors.
|
||
- Catch only to fix or add context; otherwise, use global error handlers.
|
||
- Always provide meaningful error messages.
|
||
|
||
-----
|
||
|
||
## 🧪 Testing (General)
|
||
|
||
- Use the **Arrange–Act–Assert** pattern.
|
||
- Use descriptive test variable names (`inputData`, `expectedOutput`).
|
||
- Write **unit tests** for all public methods.
|
||
- Mock external dependencies.
|
||
- Add **acceptance tests** per module using Given–When–Then.
|
||
|
||
-----
|
||
|
||
# 🏗️ Backend (NestJS)
|
||
|
||
### Principles
|
||
|
||
- **Modular architecture**:
|
||
- One module per domain.
|
||
- Controller → Service → Repository (Model) structure.
|
||
- DTOs validated with **class-validator**.
|
||
- Use **MikroORM** (or TypeORM/Prisma) for persistence, aligning with the MariaDB schema.
|
||
- Encapsulate reusable code in a **common module** (`@app/common`):
|
||
- Configs, decorators, DTOs, guards, interceptors, notifications, shared services, types, validators.
|
||
|
||
### Core Functionalities
|
||
|
||
- Global **filters** for exception handling.
|
||
- **Middlewares** for request handling.
|
||
- **Guards** for permissions and RBAC.
|
||
- **Interceptors** for response transformation and logging.
|
||
|
||
### Testing
|
||
|
||
- Use **Jest** for testing.
|
||
- Test each controller and service.
|
||
- Add `admin/test` endpoint as a smoke test.
|
||
|
||
-----
|
||
|
||
# 🖥️ Frontend (NextJS / React / UI)
|
||
|
||
### Developer Profile
|
||
|
||
Senior-level TypeScript + React/NextJS engineer.
|
||
Expert in **TailwindCSS**, **Shadcn/UI**, and **Radix** for UI development.
|
||
|
||
### Code Implementation Guidelines
|
||
|
||
- Use **early returns** for clarity.
|
||
- Always style with **TailwindCSS** classes.
|
||
- Prefer `class:` conditional syntax (or `clsx` utility) over ternary operators in class strings.
|
||
- Use **const arrow functions** for components and handlers.
|
||
- Event handlers start with `handle...` (e.g., `handleClick`, `handleSubmit`).
|
||
- Include accessibility attributes:
|
||
`tabIndex="0"`, `aria-label`, `onKeyDown`, etc.
|
||
- Ensure all code is **complete**, **tested**, and **DRY**.
|
||
- Always import required modules explicitly.
|
||
|
||
### UI/UX with React
|
||
|
||
- Use **semantic HTML**.
|
||
- Apply **responsive Tailwind** classes (`sm:`, `md:`, `lg:`).
|
||
- Maintain visual hierarchy with typography and spacing.
|
||
- Use **Shadcn** components (Button, Input, Card, etc.) for consistent UI.
|
||
- Keep components small and focused.
|
||
- Use utility classes for quick styling (spacing, colors, text, etc.).
|
||
- Ensure **ARIA compliance** and semantic markup.
|
||
|
||
### Form Validation & Errors
|
||
|
||
- Use client-side libraries like `zod` and `react-hook-form`.
|
||
- Show errors with **alert components** or inline messages.
|
||
- Include labels, placeholders, and feedback messages.
|
||
|
||
-----
|
||
|
||
# 🔗 Full Stack Integration Guidelines
|
||
|
||
| Aspect | Backend (NestJS) | Frontend (NextJS) | UI Layer (Tailwind/Shadcn) |
|
||
|:--|:--|:--|:--|
|
||
| API | REST / GraphQL Controllers | API hooks via fetch/axios/SWR | Components consuming data |
|
||
| Validation | `class-validator` DTOs | `zod` / `react-hook-form` | Shadcn form/input states |
|
||
| Auth | Guards, JWT | NextAuth / cookies | Auth UI states (loading, signed in) |
|
||
| Errors | Global filters | Toasts / modals | Alerts / feedback text |
|
||
| Testing | Jest (unit/e2e) | Vitest / Playwright | Visual regression |
|
||
| Styles | Scoped modules (if needed) | Tailwind / Shadcn | Tailwind utilities |
|
||
| Accessibility | Guards + filters | ARIA attributes | Semantic HTML |
|
||
|
||
-----
|
||
|
||
# 🗂️ DMS-Specific Conventions (LCBP3-DMS)
|
||
|
||
This section extends the general FullStackJS guidelines for the **LCBP3-DMS** project, focusing on document approval workflows (Correspondence, RFA, Drawing, Contract, Transmittal, Circulation).
|
||
|
||
## 🧱 Backend Domain Modules
|
||
|
||
Use a modular domain structure reflecting the SQL schema. `correspondences` should act as the central hub.
|
||
|
||
```
|
||
src/
|
||
├─ modules/
|
||
│ ├─ correspondences/ (Core: Master documents, Revisions, Attachments)
|
||
│ ├─ rfas/ (RFA logic, Revisions, Workflows, Items)
|
||
│ ├─ drawings/ (ShopDrawings, ContractDrawings, Categories)
|
||
│ ├─ circulations/ (Internal circulation, Templates, Assignees)
|
||
│ ├─ transmittals/ (Transmittal logic, Items)
|
||
│ ├─ projects-contracts/ (Projects, Contracts, Organizations, Parties)
|
||
│ ├─ users-auth/ (Users, Roles, Permissions, Auth)
|
||
│ ├─ audit-log/
|
||
│ └─ common/
|
||
```
|
||
|
||
### Naming Convention
|
||
|
||
| Entity | Example (from SQL) |
|
||
|:--|:--|
|
||
| Table | `correspondences`, `rfa_revisions`, `contract_parties` |
|
||
| Column | `correspondence_id`, `created_by`, `is_current` |
|
||
| DTO | `CreateRfaDto`, `UpdateCorrespondenceDto` |
|
||
| Controller | `rfas.controller.ts` |
|
||
| Service | `correspondences.service.ts` |
|
||
|
||
-----
|
||
|
||
## 🧩 RBAC & Permission Control
|
||
|
||
Use decorators to enforce access rights, referencing permissions from the `permissions` table.
|
||
|
||
```ts
|
||
@RequirePermission('rfas.respond') // Must match a 'permission_code'
|
||
@Put(':id')
|
||
updateRFA(@Param('id') id: string) {
|
||
return this.rfaService.update(id);
|
||
}
|
||
```
|
||
|
||
### Roles
|
||
|
||
- **SUPER\_ADMIN**: Full system access (from `roles` table).
|
||
- **ADMIN**: Organization-level access.
|
||
- **EDITOR**: Module-specific write access.
|
||
- **VIEWER**: Read-only access.
|
||
|
||
### Example Permissions (from `permissions` table)
|
||
|
||
- `rfas.view`, `rfas.create`, `rfas.respond`, `rfas.delete`
|
||
- `drawings.view`, `drawings.upload`, `drawings.delete`
|
||
- `corr.view`, `corr.manage`
|
||
- `transmittals.manage`
|
||
- `cirs.manage`
|
||
- `project_parties.manage`
|
||
|
||
Seed mapping between roles and permissions via seeder scripts (as seen in SQL file).
|
||
|
||
-----
|
||
|
||
## 🧾 AuditLog Standard
|
||
|
||
Log all CRUD and mapping operations to the `audit_logs` table.
|
||
|
||
| Field | Type (from SQL) | Description |
|
||
|:--|:--|:--|
|
||
| `audit_id` | `BIGINT` | Primary Key |
|
||
| `user_id` | `INT` | User performing the action (FK -\> users) |
|
||
| `action` | `VARCHAR(100)` | `rfa.create`, `correspondence.update`, `login.success` |
|
||
| `entity_type`| `VARCHAR(50)` | Table/module name, e.g., 'rfa', 'correspondence' |
|
||
| `entity_id` | `VARCHAR(50)` | Primary ID of the affected record |
|
||
| `details_json`| `JSON` | Contextual data (e.g., changed fields) |
|
||
| `ip_address` | `VARCHAR(45)` | Actor's IP address |
|
||
| `user_agent` | `VARCHAR(255)`| Actor's User Agent |
|
||
| `created_at` | `TIMESTAMP` | UTC timestamp |
|
||
|
||
Example implementation:
|
||
|
||
```ts
|
||
await this.auditLogService.log({
|
||
userId: user.id,
|
||
action: 'rfa.update_status',
|
||
entityType: 'rfa_revisions',
|
||
entityId: rfaRevision.id,
|
||
detailsJson: { from: 'DFT', to: 'FAP' },
|
||
ipAddress: req.ip,
|
||
});
|
||
```
|
||
|
||
-----
|
||
|
||
## 📂 File Handling
|
||
|
||
### File Upload Standard
|
||
|
||
- Centralize all uploads via the `attachments` table.
|
||
- Upload path (convention): `/storage/{year}/{month}/`
|
||
- Stored filename: Use `stored_filename` (e.g., UUID or hash) to prevent conflicts. `original_filename` is for display.
|
||
- Allowed types: `pdf, dwg, docx, xlsx, zip`
|
||
- Max size: **50 MB**
|
||
- Store outside webroot.
|
||
- Serve via secure endpoint `/files/:attachment_id/download`.
|
||
|
||
### Access Control
|
||
|
||
File access is not direct. The `/files/:attachment_id/download` endpoint must:
|
||
|
||
1. Find the `attachment` record.
|
||
2. Get its `correspondence_id`.
|
||
3. Verify the user has permission to view that specific `correspondence` (or its related RFA, Transmittal, etc.).
|
||
|
||
-----
|
||
|
||
## 📊 Reporting & Exports
|
||
|
||
### Reporting Views (from SQL)
|
||
|
||
Reports should be built primarily from the pre-defined database Views:
|
||
|
||
- `v_current_correspondences`: For all current non-RFA document revisions.
|
||
- `v_current_rfas`: For all current RFA revisions and their master data.
|
||
- `v_contract_parties_all`: For auditing project/contract/organization relationships.
|
||
|
||
These views serve as the primary source for server-side reporting and data exports.
|
||
|
||
### Export Rules
|
||
|
||
- Export formats: CSV, Excel, PDF.
|
||
- Provide print view.
|
||
- Include source entity link (e.g., `/rfas/:id`).
|
||
|
||
-----
|
||
|
||
## 🧮 Frontend: DataTable & Form Patterns
|
||
|
||
### DataTable (Server‑Side)
|
||
|
||
- Endpoint: `/api/{module}?page=1&pageSize=20&sort=...&filter=...`
|
||
- Must support: pagination, sorting, search, filters.
|
||
- Always display latest revision inline (for RFA/Drawing).
|
||
|
||
### Form Standards
|
||
|
||
- Dependent dropdowns must be implemented (as supported by schema):
|
||
- Project → Contract Drawing Volumes
|
||
- Contract Drawing Category → Sub-Category
|
||
- RFA (Shop Drawing type) → Linkable Shop Drawing Revisions
|
||
- File upload: preview + validation (via `attachments` logic).
|
||
- Submit via API with toast feedback.
|
||
|
||
-----
|
||
|
||
## 🧭 Dashboard & Activity Feed
|
||
|
||
### Dashboard Cards
|
||
|
||
- Show latest Correspondences, RFAs, Circulations.
|
||
- Include KPI summaries (e.g., "RFAs Pending Approval").
|
||
- Include quick links to modules.
|
||
|
||
### Activity Feed
|
||
|
||
- Display recent `audit_logs` actions (10 latest) relevant to the user.
|
||
|
||
<!-- end list -->
|
||
|
||
```ts
|
||
// Example API response
|
||
[
|
||
{ user: 'editor01', action: 'Updated RFA (LCBP3C1-RFA-001)', time: '2025-11-04T09:30Z' }
|
||
]
|
||
```
|
||
|
||
-----
|
||
|
||
## ✅ Implemented Standards (from SQL v1.1.0)
|
||
|
||
This section confirms that the following best practices are already part of the database design and should be leveraged, not re-implemented.
|
||
|
||
- ✅ **Soft Delete:** Implemented via `deleted_at` columns on key tables (e.g., `correspondences`, `rfas`, `project_parties`). Logic must filter for `deleted_at IS NULL`.
|
||
- ✅ **Database Indexes:** The schema is heavily indexed on foreign keys and common query columns (e.g., `idx_rr_rfa`, `idx_cor_project`, `idx_cr_is_current`) for performance.
|
||
- ✅ **RBAC Structure:** A comprehensive `users`, `roles`, `permissions`, `user_roles`, and `user_project_roles` system is in place.
|
||
- ✅ **Data Seeding:** Master data (roles, permissions, organization\_roles, initial users, project parties) is included in the schema script.
|
||
|
||
## 🧩 Recommended Enhancements (Future)
|
||
|
||
- ✅ Implement Fulltext search on fields like `correspondence_revisions.title` or `details`.
|
||
- ✅ Create a background job (using **n8n** as noted in SQL comments) for RFA deadline reminders based on `due_date`.
|
||
- ✅ Add a periodic cleanup job for `attachments` that are not linked to any `correspondence_id` (orphaned files).
|
||
|
||
----- |