251119:1200 set backend

This commit is contained in:
2025-11-19 11:57:46 +07:00
parent a3e25d6c52
commit 2b36e5554b
29 changed files with 7719 additions and 204 deletions

View File

@@ -1,5 +1,5 @@
-- ==========================================================
-- DMS v1.4.0 Document Management System Database
-- DMS v1.4.2 Document Management System Database
-- Deploy Script Schema
-- Server: Container Station on QNAPQNAP TS-473A
-- Database service: MariaDB 10.11
@@ -2007,54 +2007,6 @@ CREATE INDEX idx_audit_request_id ON audit_logs(request_id);
-- =====================================================
-- 11. 📊 Views & Procedures (วิว และ โปรซีเดอร์)
-- =====================================================
-- Stored Procedure ดึงเลขที่เอกสารถัดไป
DELIMITER // CREATE PROCEDURE sp_get_next_document_number(
IN p_project_id INT,
IN p_originator_organization_id INT,
IN p_correspondence_type_id INT,
IN p_current_year INT,
OUT p_next_number INT
) BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN -- หากเกิดข้อผิดพลาด ให้ยกเลิก Transaction และส่ง Error กลับไป
ROLLBACK;
END;
START TRANSACTION;
-- ล็อกแถวเพื่อป้องกัน Race Condition
SELECT last_number INTO p_next_number
FROM document_number_counters
WHERE project_id = p_project_id
AND originator_organization_id = p_originator_organization_id
AND correspondence_type_id = p_correspondence_type_id
AND current_year = p_current_year FOR
UPDATE;
-- ถ้าไม่พบ record ให้สร้างใหม่
IF p_next_number IS NULL THEN
SET p_next_number = 1;
INSERT INTO document_number_counters (
project_id,
originator_organization_id,
correspondence_type_id,
current_year,
last_number
)
VALUES (
p_project_id,
p_originator_organization_id,
p_correspondence_type_id,
p_current_year,
p_next_number
);
ELSE -- อัพเดทเลขที่ล่าสุด
SET p_next_number = p_next_number + 1;
UPDATE document_number_counters
SET last_number = p_next_number
WHERE project_id = p_project_id
AND originator_organization_id = p_originator_organization_id
AND correspondence_type_id = p_correspondence_type_id
AND current_year = p_current_year;
END IF;
COMMIT;
END // DELIMITER;
-- View แสดง Revision "ปัจจุบัน" ของ correspondences ทั้งหมด (ที่ไม่ใช่ RFA)
CREATE VIEW v_current_correspondences AS
SELECT c.id AS correspondence_id,

View File

@@ -2,7 +2,7 @@
**สถานะ:** FINAL
**วันที่:** 2025-11-19
**อ้างอิงพื้นฐาน:** v1.4.1 และผลการ Review สถาปัตยกรรม
**อ้างอิงพื้นฐาน:** v1.4.2
**Classification:** Internal Technical Documentation
## 📌 **1. วัตถุประสงค์**
@@ -750,13 +750,13 @@
## **Document Control:**
- **Document:** Application Requirements Specification DMS v1.4.2
- **Version:** 1.4.2
- **Document:** Application Requirements Specification v1.4.2
- **Version:** 1.4
- **Date:** 2025-11-19
- **Author:** System Architecture Team
- **Author:** NAP LCBP3-DMS & Gemini
- **Status:** FINAL
- **Classification:** Internal Technical Documentation
- **Approved By:** System Architect Team
- **Approved By:** Nattanin
---

View File

@@ -3,7 +3,7 @@
**สถานะ:** FINAL GUIDELINE
**วันที่:** 2025-11-19
**อ้างอิง:** Requirements Specification v1.4.2
**ปรับปรุงโดย:** deepseek
**Classification:** Internal Technical Documentation
## 🧠 **1. ปรัชญาทั่วไป (General Philosophy)**
@@ -955,6 +955,16 @@ Views เหล่านี้ทำหน้าที่เป็นแหล
**หมายเหตุ:** แนวทางนี้จะถูกทบทวนและปรับปรุงเป็นระยะตาม feedback จากทีมพัฒนาและความต้องการทางธุรกิจที่เปลี่ยนแปลงไป
## **Document Control:**
* **Document:** FullStackJS v1.4.2
* **Version:** 1.4
* **Date:** 2025-11-19
* **Author:** NAP LCBP3-DMS & Gemini
* **Status:** FINAL
* **Classification:** Internal Technical Documentation
* **Approved By:** Nattanin
---
`End of FullStackJS Guidelines v1.4.2`

View File

@@ -1,7 +1,9 @@
# 📋 **แผนการพัฒนา Backend (NestJS) - LCBP3-DMS v1.4.2 (ฉบับปรับปรุง)**
**สถานะ:** FINAL GUIDELINE
**วันที่:** 2025-11-19
**อ้างอิง:** Requirements v1.4.2 & FullStackJS Guidelines v1.4.2
**จุดเน้นสำคัญ:** Concurrency Control, Data Integrity, Unified Workflow, Idempotency
**Classification:** Internal Technical Documentation
-----
@@ -534,6 +536,16 @@ src/
| Phase 8 | 1 สัปดาห์ | 6 | Documentation & Deploy |
| **รวม** | **15 สัปดาห์** | **39 Tasks** | **Production-Ready Backend v1.4.2** |
## **Document Control:**
- **Document:** Backend Development Plan v1.4.2
- **Version:** 1.4
- **Date:** 2025-11-19
- **Author:** NAP LCBP3-DMS & Gemini
- **Status:** FINAL
- **Classification:** Internal Technical Documentation
- **Approved By:** Nattanin
-----
`End of Backend Development Plan v1.4.2 (ฉบับปรับปรุง)`
`End of Backend Development Plan v1.4.2`

View File

@@ -1,7 +1,9 @@
# 📋 **แผนการพัฒนา Frontend (Next.js) - LCBP3-DMS v1.4.2**
**สถานะ:** FINAL GUIDELINE
**วันที่:** 2025-11-19
**อ้างอิง:** Requirements v1.4.2 & FullStackJS Guidelines v1.4.2
**จุดเน้นสำคัญ:** Responsive Design, Dynamic Forms, Offline Support, Optimistic Updates
**Classification:** Internal Technical Documentation
## 🎯 **ภาพรวมโครงการ**
@@ -977,6 +979,16 @@ F10_3 --> F10_4
5. **User Testing** → ทดสอบกับผู้ใช้จริงระหว่างพัฒนา
6. **Deploy to Production** → Week 15 (พร้อม Backend)
## **Document Control:**
- **Document:** Frontend Development Plan v1.4.2
- **Version:** 1.4
- **Date:** 2025-11-19
- **Author:** NAP LCBP3-DMS & Gemini
- **Status:** FINAL
- **Classification:** Internal Technical Documentation
- **Approved By:** Nattanin
---
`End of Frontend Development Plan v1.4.2 (ฉบับปรับปรุง)`

View File

@@ -1,6 +1,11 @@
# **ตารางฐานข้อมูล (Data Dictionary) - LCBP3-DMS (V1.4.2)**
เอกสารนี้สรุปโครงสร้างตาราง, Foreign Keys (FK), และ Constraints ที่สำคัญทั้งหมดในฐานข้อมูล LCBP3-DMS (v1.4.0) เพื่อใช้เป็นเอกสารอ้างอิงสำหรับทีมพัฒนา Backend (NestJS) และ Frontend (Next.js) โดยอิงจาก Requirements และ SQL Script ล่าสุด [GLM-4.6]
เอกสารนี้สรุปโครงสร้างตาราง, Foreign Keys (FK), และ Constraints ที่สำคัญทั้งหมดในฐานข้อมูล LCBP3-DMS (v1.4.0) เพื่อใช้เป็นเอกสารอ้างอิงสำหรับทีมพัฒนา Backend (NestJS) และ Frontend (Next.js) โดยอิงจาก Requirements และ SQL Script ล่าสุด [GEMINI]
**สถานะ:** FINAL GUIDELINE
**วันที่:** 2025-11-19
**อ้างอิง:** Requirements v1.4.2 & FullStackJS Guidelines v1.4.2
**Classification:** Internal Technical Documentation
---
@@ -1868,7 +1873,6 @@
| version | INT | DEFAULT 0 | ใช้สำหรับ Optimistic Locking (ตรวจสอบค่าก่อน Update) |
| last_number | INT | DEFAULT 0 | Last assigned sequence number |
**Indexes**:
- PRIMARY KEY (project_id, originator_organization_id, correspondence_type_id, current_year)
@@ -1888,7 +1892,7 @@
- Composite primary key ensures unique counters per project/organization/type/year
- Counter resets each year
- Thread-safe increments handled by stored procedure sp_get_next_document_number
- Thread-safe increments handled by DocumentNumberingService in NestJS using Redis Lock and Optimistic Locking on version column
- last_number tracks highest assigned number
- Used with document_number_formats to generate complete document numbers
@@ -2306,51 +2310,6 @@ WHERE user_id = ?
---
### 11.9 sp_get_next_document_number
**Purpose**: Stored procedure to safely generate next sequential document number
**Parameters**:
- IN p_project_id INT
- IN p_originator_organization_id INT
- IN p_correspondence_type_id INT
- IN p_current_year INT
- OUT p_next_number INT
**Logic**:
1. Start transaction
2. SELECT last_number FOR UPDATE (locks row)
3. If record doesn't exist, INSERT with last_number = 1
4. Else UPDATE last_number = last_number + 1
5. Return new number via OUT parameter
6. COMMIT transaction
**Business Rules**:
- Thread-safe counter increment
- FOR UPDATE lock prevents race conditions
- Handles first-time counter initialization
- Rolls back on any error
- Must be called within document creation transaction
- Used in conjunction with document_number_formats template
**Usage Example**:
```sql
CALL sp_get_next_document_number(
1, -- project_id
10, -- organization_id
1, -- type_id (RFA)
2568, -- Buddhist year
@next_number
);
-- @next_number now contains next sequence
```
---
## Database Indexes Summary
### Performance Optimization Indexes
@@ -2753,7 +2712,7 @@ ANALYZE TABLE correspondences;
1. **Document Numbering**:
- Call sp_get_next_document_number
- Call DocumentNumberingService.generateNextNumber() (NestJS) which handles Redis locking and retry logic
- Format with template from document_number_formats
- Store in correspondences.correspondence_number
@@ -2865,14 +2824,15 @@ SELECT * FROM information_schema.INNODB_LOCK_WAITS;
---
**Document Control**:
## **Document Control:**
- Document: Data Dictionary - DMS v1.4.0
- Version: 1.0
- Date: 2025-01-XX
- Author: System Architecture Team
- Status: FINAL
- Classification: Internal Technical Documentation
- **Document:** Data Dictionary v1.4.2
- **Version:** 1.4
- **Date:** 2025-11-19
- **Author:** NAP LCBP3-DMS & Gemini
- **Status:** FINAL
- **Classification:** Internal Technical Documentation
- **Approved By:** Nattanin
---

376
Setting Project.md Normal file
View File

@@ -0,0 +1,376 @@
# **BACKEND DEVELOPMENT**
## **Backend Development Plan (Phase 0)** และ **Requirements** เราจะสร้างโปรเจกต์ชื่อ `lcbp3-backend` โดยใช้ **NestJS** และจัดโครงสร้างแบบ **Domain-Driven Design** ตั้งแต่เริ่มต้นเพื่อให้รองรับการขยายตัวตามแผนงานครับ
นี่คือขั้นตอนและคำสั่งในการสร้างโปรเจกต์ครับ:
### 1. ติดตั้ง Nest CLI และสร้างโปรเจกต์
รันคำสั่งต่อไปนี้ใน Terminal ครับ (แนะนำให้ใช้ `pnpm` ตามแนวทาง FullStackJS Guidelines):
```bash
# 1. ติดตั้ง Nest CLI ทั่วโลก (ถ้ายังไม่ได้ติดตั้ง)
npm install -g @nestjs/cli
# 2. สร้างโปรเจกต์ใหม่ชื่อ lcbp3-backend
nest new backend
# 💡 ระบบจะถามหา Package Manager:
# ให้เลือก "pnpm" (เพื่อให้ตรงกับ Frontend และแผนงาน)
```
### 2. ปรับโครงสร้างโฟลเดอร์ (Domain-Driven Structure)
หลังจากสร้างโปรเจกต์เสร็จแล้ว เราจะปรับโครงสร้าง `src` ให้ตรงกับ **Backend Plan หัวข้อ 3.10** ครับ
รันคำสั่งเหล่านี้ใน Terminal (ภายในโฟลเดอร์ `lcbp3-backend`):
```bash
# เข้าสู่โฟลเดอร์โปรเจกต์
cd backend
# สร้างโครงสร้างโฟลเดอร์หลัก
mkdir -p src/common/auth
mkdir -p src/common/config
mkdir -p src/common/decorators
mkdir -p src/common/entities
mkdir -p src/common/exceptions
mkdir -p src/common/file-storage
mkdir -p src/common/guards
mkdir -p src/common/interceptors
mkdir -p src/common/resilience
mkdir -p src/common/security
mkdir -p src/common/idempotency
mkdir -p src/common/maintenance
# สร้างโฟลเดอร์สำหรับ Modules ตาม Domain
mkdir -p src/modules/user
mkdir -p src/modules/project
mkdir -p src/modules/master
mkdir -p src/modules/correspondence
mkdir -p src/modules/rfa
mkdir -p src/modules/drawing
mkdir -p src/modules/circulation
mkdir -p src/modules/transmittal
mkdir -p src/modules/search
mkdir -p src/modules/monitoring
mkdir -p src/modules/workflow-engine
mkdir -p src/modules/document-numbering
mkdir -p src/modules/notification
mkdir -p src/modules/file-storage
# สร้างโฟลเดอร์ Database
mkdir -p src/database/migrations
mkdir -p src/database/seeds
```
### 3. ตรวจสอบและตั้งค่า TypeScript (Strict Mode)
อ้างอิงจาก **FullStackJS Guidelines ข้อ 2.1**, เราต้องเปิดใช้งาน Strict Mode เพื่อความปลอดภัยของ Type ครับ
เปิดไฟล์ `tsconfig.json` และตรวจสอบค่า config ดังนี้:
```json
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
/* Strict Type-Checking Options */
"strict": true, // บังคับใช้ Strict Mode
"noImplicitAny": true, // ห้ามใช้ Any โดยไม่จำเป็น
"strictNullChecks": true, // ตรวจสอบค่า Null อย่างเคร่งครัด
"strictBindCallApply": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true
}
}
```
### 4. การตั้งค่า Environment (Docker Support)
ตาม **Requirements ข้อ 2.1 และ 2.2**, เราจะไม่ใช้ `.env` ในการ deploy จริงบน QNAP แต่จะใช้ Environment Variables ผ่าน `docker-compose`
อย่างไรก็ตาม สำหรับ **Development** ให้สร้างไฟล์ `.env` ไว้สำหรับการรัน Local (และอย่าลืมใส่ใน `.gitignore`)
สร้างไฟล์ `.env` ที่ root project:
```env
# Database Configuration (สำหรับการ Dev บนเครื่อง Local)
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=root
DB_PASSWORD=password123
DB_DATABASE=lcbp3_dms
# Application
PORT=3000
NODE_ENV=development
# Security
JWT_SECRET=your_super_secret_key_change_it
```
### ขั้นตอนต่อไป (Next Steps)
ตอนนี้โครงสร้างพื้นฐานพร้อมแล้วครับ ขั้นตอนต่อไปตาม **Phase 0** คือ:
1. **Secure Configuration Setup:** ติดตั้ง `@nestjs/config` และ `joi` เพื่อ validate ตัวแปร environment
2. **Database Connection:** ติดตั้ง `typeorm`, `@nestjs/typeorm` และ `mysql2` (สำหรับ MariaDB)
ต้องการให้ผมพาทำส่วน **Configuration Setup (T0.1)** ต่อเลยไหมครับ?
## การติดตั้ง **pnpm**
### 1. ติดตั้งผ่าน npm (วิธีแนะนำ)
เปิด Terminal (หรือ Command Prompt / PowerShell) แล้วรันคำสั่ง:
```bash
npm install -g pnpm
```
> **คำอธิบาย:** `-g` หมายถึง global install คือติดตั้งลงในเครื่องเพื่อให้เรียกใช้คำสั่ง `pnpm` ได้จากทุกโฟลเดอร์ครับ
### 2. ตรวจสอบการติดตั้ง
เมื่อติดตั้งเสร็จแล้ว ให้เช็คเวอร์ชันเพื่อความชัวร์ครับ:
```bash
pnpm --version
```
(ควรจะขึ้นเป็นตัวเลขเวอร์ชัน เช่น `9.x.x`)
-----
### ทางเลือก: ติดตั้งผ่าน Corepack (สำหรับ Node.js เวอร์ชันใหม่)
หากคุณใช้ Node.js เวอร์ชัน 16.13 ขึ้นไป สามารถเปิดใช้งานฟีเจอร์ **Corepack** ที่แถมมากับ Node.js ได้เลย โดยไม่ต้องลงผ่าน npm ครับ:
```bash
corepack enable
corepack prepare pnpm@latest --activate
```
-----
### เมื่อติดตั้งเสร็จแล้ว
คุณสามารถใช้ `pnpm` แทน `npm` ได้เลยครับ เช่น:
* **ติดตั้ง Nest CLI (ถ้ายังไม่ได้ลง):** `pnpm add -g @nestjs/cli`
* **สร้างโปรเจกต์ NestJS:** `nest new lcbp3-backend` (แล้วเลือก pnpm ตอนระบบถาม)
* **รันโปรเจกต์:** `pnpm start:dev`
* **ติดตั้ง Library เพิ่ม:** `pnpm add [package-name]` (เช่น `pnpm add typeorm`)
ติดตั้งเสร็จแล้ว แจ้งผมได้เลยนะครับ จะได้ไปต่อที่ขั้นตอน **Config Database** กันครับ
## การตั้งค่า MariaDB บน `localhost` เพื่อใช้กับ NestJS ตามแผนงาน **Backend Plan T0.3** และ **FullStackJS Guidelines 3.2** เราต้องทำ 2 ส่วนคือ **เตรียม Database Server (Docker)** และ **เชื่อมต่อ NestJS (TypeORM)** ครับ
### 1. ติดตั้ง Libraries ที่จำเป็น
ก่อนอื่นต้องติดตั้ง Module สำหรับ TypeORM, MariaDB Driver และ Config Module (เพื่ออ่านค่าจาก .env) ครับ
รันคำสั่งนี้ใน Terminal:
```bash
pnpm add @nestjs/typeorm typeorm mysql2 @nestjs/config
```
> **หมายเหตุ:** เราใช้ `mysql2` driver เพราะ MariaDB เข้ากันได้กับ MySQL Protocol และ `mysql2` มีประสิทธิภาพสูงครับ
### 2. สร้าง MariaDB Server ด้วย Docker Compose
เพื่อให้มั่นใจว่า Environment ตรงกับ Production (ตามข้อกำหนด \*\* Requirements 2.1\*\* ที่ใช้ Container) เราจะรัน MariaDB ผ่าน Docker ครับ
สร้างไฟล์ `docker-compose.yml` ที่ root ของโปรเจกต์ (ถ้ายังไม่มี):
```yaml
version: '3.8'
services:
mariadb:
image: mariadb:10.11
container_name: lcbp3-db-local
restart: always
environment:
MYSQL_ROOT_PASSWORD: password123
MYSQL_DATABASE: lcbp3_dms
MYSQL_USER: admin
MYSQL_PASSWORD: password123
ports:
- '3306:3306'
volumes:
- db_data:/var/lib/mysql
networks:
- lcbp3-net
# Optional: phpMyAdmin สำหรับจัดการ DB ง่ายๆ
pma:
image: phpmyadmin/phpmyadmin
container_name: lcbp3-pma-local
environment:
PMA_HOST: mariadb
ports:
- '8080:80'
depends_on:
- mariadb
networks:
- lcbp3-net
volumes:
db_data:
networks:
lcbp3-net:
driver: bridge
```
จากนั้นรันคำสั่งเพื่อเริ่ม Database:
```bash
docker-compose up -d
```
### 3. ตั้งค่าการเชื่อมต่อใน `app.module.ts`
เราจะแก้ไขไฟล์ `src/app.module.ts` ให้เชื่อมต่อกับ Database โดยอ่านค่าจาก `.env` ผ่าน `ConfigService` เพื่อความปลอดภัยและยืดหยุ่นครับ
```typescript
// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
// 1. Load Config Module
ConfigModule.forRoot({
isGlobal: true, // ให้เรียกใช้ได้ทุกที่โดยไม่ต้อง import ใหม่
envFilePath: '.env', // อ่านค่าจากไฟล์ .env
}),
// 2. Setup TypeORM Connection (Async เพื่อรออ่าน Config ก่อน)
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
type: 'mariadb', // หรือ 'mysql' ก็ได้เพราะใช้ driver เดียวกัน
host: configService.get<string>('DB_HOST'),
port: configService.get<number>('DB_PORT'),
username: configService.get<string>('DB_USERNAME'),
password: configService.get<string>('DB_PASSWORD'),
database: configService.get<string>('DB_DATABASE'),
// Auto Load Entities: โหลด Entity ทั้งหมดที่อยู่ในโปรเจกต์อัตโนมัติ
autoLoadEntities: true,
// Synchronize: true เฉพาะ Dev environment (ห้ามใช้ใน Prod)
synchronize: configService.get<string>('NODE_ENV') === 'development',
// Logging: เปิดดู Query SQL ตอน Dev
logging: configService.get<string>('NODE_ENV') === 'development',
}),
inject: [ConfigService],
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
```
### 4. ตรวจสอบไฟล์ `.env`
ตรวจสอบไฟล์ `.env` ที่เราสร้างไว้ก่อนหน้านี้ว่าข้อมูลตรงกับ `docker-compose.yml` ไหมครับ
```env
# Database Configuration
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=root
# หรือใช้ user: admin / password: password123 ตามที่ตั้งใน docker-compose ก็ได้
# แต่ถ้า connect จาก host (เครื่องเรา) ใช้ root ก็สะดวกดีครับ
DB_PASSWORD=password123
DB_DATABASE=lcbp3_dms
# App Environment
NODE_ENV=development
PORT=3000
```
### 5. ทดสอบรันโปรเจกต์
ลองรัน NestJS ดูครับว่าเชื่อมต่อได้ไหม:
```bash
pnpm start:dev
```
ถ้า Terminal ขึ้นข้อความสีเขียวๆ ว่า `[NestApplication] Nest application successfully started` และไม่มี Error เกี่ยวกับ TypeORM แสดงว่าเชื่อมต่อ MariaDB บน Localhost สำเร็จแล้วครับ\! 🎉
-----
**ขั้นตอนถัดไป:**
เราควรสร้าง **Base Entity** (T1.1) และ **Users Entity** (T1.3) เพื่อเริ่มทำระบบ Login ไหมครับ?
## การสร้าง `JWT_SECRET` (JSON Web Token Secret) ที่มีความปลอดภัยสูงเป็นสิ่งสำคัญมากสำหรับระบบ Authentication เพราะหาก Secret นี้หลุดหรือเดาง่าย ผู้ไม่หวังดีอาจปลอมแปลง Token เพื่อเข้าสู่ระบบในฐานะใครก็ได้ (เช่น Superadmin)
ในแผนพัฒนา **Backend Plan Phase 0 (T0.1)** และ **FullStackJS Guidelines** ระบุว่าต้องจัดการ Secrets อย่างปลอดภัย นี่คือวิธีสร้าง `JWT_SECRET` ที่มีความซับซ้อนและปลอดภัย (High Entropy) ครับ:
### วิธีที่ 1: ใช้ OpenSSL (แนะนำสำหรับ Production)
วิธีนี้เป็นมาตรฐานและปลอดภัยที่สุด หากคุณใช้ Linux, macOS หรือ Git Bash บน Windows ให้เปิด Terminal แล้วพิมพ์คำสั่ง:
```bash
openssl rand -base64 64
```
*ผลลัพธ์จะได้ String ยาวๆ ที่อ่านไม่รู้เรื่อง เช่น:*
`h78/sT5...xYz==`
### วิธีที่ 2: ใช้ Node.js Crypto (ง่ายสำหรับ Developer)
เนื่องจากเราพัฒนาด้วย Node.js/NestJS คุณสามารถใช้คำสั่ง Node เพื่อสร้าง Key ได้เลย ไม่ต้องติดตั้งอะไรเพิ่มครับ
รันคำสั่งนี้ใน Terminal:
```bash
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```
*ผลลัพธ์จะได้ Hex String ยาว 64 ตัวอักษร*
### วิธีที่ 3: ใช้ Password Manager Generator
หากใช้ 1Password, LastPass หรือ Bitwarden สามารถใช้ฟีเจอร์ "Generate Password" โดยตั้งค่าความยาว 64 ตัวอักษร (รวมตัวเลขและสัญลักษณ์) ก็ใช้ได้เช่นกันครับ
-----
### ⚙️ การนำไปใช้งานในโปรเจกต์
เมื่อได้ Secret Key มาแล้ว ให้นำไปใส่ในไฟล์ `.env` ของคุณ (และ **ห้าม** Commit ไฟล์นี้ขึ้น Git เด็ดขาด ตามข้อกำหนด):
**ไฟล์: `.env`**
```env
# Security
# แทนที่ค่าเดิมด้วยค่าที่ Gen ได้ใหม่
JWT_SECRET=d4a1b2... (ค่าที่คุณเพิ่งสร้าง)
JWT_EXPIRATION=8h
```
**ข้อควรระวัง:**
1. **ความยาว:** ควรยาวอย่างน้อย 32 bytes (256 bits) เพื่อป้องกัน Brute-force
2. **Environment:** ควรแยก Secret ระหว่างเครื่อง `Development` และ `Production` ไม่ควรใช้ Key เดียวกัน
คุณต้องการให้ผมช่วยตั้งค่า `ConfigModule` ใน NestJS เพื่ออ่านค่า `JWT_SECRET` นี้อย่างปลอดภัยพร้อม Validate ว่าห้ามเป็นค่าว่างไหมครับ?

4
backend.bak/.prettierrc Normal file
View File

@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

98
backend.bak/README.md Normal file
View File

@@ -0,0 +1,98 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Project setup
```bash
$ npm install
```
## Compile and run the project
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Run tests
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Deployment
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
```bash
$ npm install -g @nestjs/mau
$ mau deploy
```
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
## Resources
Check out a few resources that may come in handy when working with NestJS:
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).

View File

@@ -0,0 +1,62 @@
# File: docker-compose.yml
# บันทึกการแก้ไข: (สร้างไฟล์)
# (สำคัญ: ไฟล์นี้จะถูก import หรือคัดลอกไปใส่ใน UI ของ QNAP Container Station)
version: '3.8'
services:
# ---------------------------------
# Service 1: Backend (NestJS)
# (Req 2.3)
# ---------------------------------
backend:
build:
context: ./backend # (สมมติว่า Dockerfile อยู่ในโฟลเดอร์ backend)
dockerfile: Dockerfile
image: lcbp3-backend:1.3.0 # (ตั้งชื่อ Image)
container_name: lcbp3-backend
restart: unless-stopped
# (สำคัญ) กำหนด Environment Variables ที่นี่ (ห้ามใช้ .env)
# (Req 6.5, 2.1)
environment:
# --- App Config ---
- PORT=3000
- NODE_ENV=production
# --- Database (Req 2.4) ---
# (ชี้ไปที่ Service 'mariadb' ใน Network 'lcbp3')
- DATABASE_HOST=mariadb
- DATABASE_PORT=3306
- DATABASE_USER=your_db_user # (ต้องเปลี่ยน)
- DATABASE_PASSWORD=your_db_pass # (ต้องเปลี่ยน)
- DATABASE_NAME=lcbp3_dms
# --- Security (JWT) (Req 6.5) ---
- JWT_SECRET=YOUR_VERY_STRONG_JWT_SECRET_KEY # (ต้องเปลี่ยน)
- JWT_EXPIRATION_TIME=3600s # (เช่น 1 ชั่วโมง)
# --- Phase 4 Services ---
- ELASTICSEARCH_URL=http://elasticsearch:9200 # (ชี้ไปที่ Service ES ถ้ามี)
- N8N_WEBHOOK_URL=http://n8n:5678/webhook/your-webhook-id # (ชี้ไปที่ N8N)
# (สำคัญ) เชื่อมต่อ Network กลาง (Req 2.1)
networks:
- lcbp3
# (Deploy) ตั้งค่า Health Check
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/api/v1/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 20s # (รอให้ App เริ่มก่อน)
# ---------------------------------
# Network กลาง (Req 2.1)
# (ต้องสร้าง Network นี้ไว้ก่อนใน QNAP หรือสร้างพร้อมกัน)
# ---------------------------------
networks:
lcbp3:
external: true # (ถ้าสร้างไว้แล้ว)
# name: lcbp3 # (ถ้าต้องการให้ Compose สร้าง)

View File

@@ -0,0 +1,35 @@
// @ts-check
import eslint from '@eslint/js';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{
ignores: ['eslint.config.mjs'],
},
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
eslintPluginPrettierRecommended,
{
languageOptions: {
globals: {
...globals.node,
...globals.jest,
},
sourceType: 'commonjs',
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
{
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
"prettier/prettier": ["error", { endOfLine: "auto" }],
},
},
);

View File

@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

98
backend.bak/package.json Normal file
View File

@@ -0,0 +1,98 @@
{
"name": "backend",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@elastic/elasticsearch": "^9.2.0",
"@nestjs/cache-manager": "^3.0.1",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1",
"@nestjs/elasticsearch": "^11.1.0",
"@nestjs/jwt": "^11.0.1",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.1.9",
"@nestjs/schedule": "^6.0.1",
"@nestjs/swagger": "^11.2.1",
"@nestjs/typeorm": "^11.0.0",
"@types/nodemailer": "^7.0.3",
"@types/uuid": "^10.0.0",
"bcrypt": "^6.0.0",
"cache-manager": "^7.2.4",
"casl": "^0.2.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.2",
"helmet": "^8.1.0",
"multer": "^2.0.2",
"mysql2": "^3.15.3",
"nodemailer": "^7.0.10",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"rate-limiter-flexible": "^8.2.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"typeorm": "^0.3.27",
"uuid": "^13.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.1.9",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/multer": "^2.0.0",
"@types/node": "^22.10.7",
"@types/passport-jwt": "^4.0.1",
"@types/supertest": "^6.0.2",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^16.0.0",
"jest": "^30.2.0",
"prettier": "^3.4.2",
"source-map-support": "^0.5.21",
"supertest": "^7.1.4",
"ts-jest": "^29.2.5",
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

View File

@@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

View File

@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

View File

@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

8
backend.bak/src/main.ts Normal file
View File

@@ -0,0 +1,8 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

View File

@@ -0,0 +1,25 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { App } from 'supertest/types';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication<App>;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

View File

@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

View File

@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

25
backend.bak/tsconfig.json Normal file
View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "nodenext",
"moduleResolution": "nodenext",
"resolvePackageJsonExports": true,
"esModuleInterop": true,
"isolatedModules": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"noFallthroughCasesInSwitch": false
}
}

56
backend/.gitignore vendored Normal file
View File

@@ -0,0 +1,56 @@
# compiled output
/dist
/node_modules
/build
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# temp directory
.temp
.tmp
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

View File

@@ -1,62 +1,38 @@
# File: docker-compose.yml
# บันทึกการแก้ไข: (สร้างไฟล์)
# (สำคัญ: ไฟล์นี้จะถูก import หรือคัดลอกไปใส่ใน UI ของ QNAP Container Station)
version: '3.8'
services:
# ---------------------------------
# Service 1: Backend (NestJS)
# (Req 2.3)
# ---------------------------------
backend:
build:
context: ./backend # (สมมติว่า Dockerfile อยู่ในโฟลเดอร์ backend)
dockerfile: Dockerfile
image: lcbp3-backend:1.3.0 # (ตั้งชื่อ Image)
container_name: lcbp3-backend
restart: unless-stopped
# (สำคัญ) กำหนด Environment Variables ที่นี่ (ห้ามใช้ .env)
# (Req 6.5, 2.1)
mariadb:
image: mariadb:11.8
container_name: lcbp3-db-local
restart: always
environment:
# --- App Config ---
- PORT=3000
- NODE_ENV=production
# --- Database (Req 2.4) ---
# (ชี้ไปที่ Service 'mariadb' ใน Network 'lcbp3')
- DATABASE_HOST=mariadb
- DATABASE_PORT=3306
- DATABASE_USER=your_db_user # (ต้องเปลี่ยน)
- DATABASE_PASSWORD=your_db_pass # (ต้องเปลี่ยน)
- DATABASE_NAME=lcbp3_dms
# --- Security (JWT) (Req 6.5) ---
- JWT_SECRET=YOUR_VERY_STRONG_JWT_SECRET_KEY # (ต้องเปลี่ยน)
- JWT_EXPIRATION_TIME=3600s # (เช่น 1 ชั่วโมง)
# --- Phase 4 Services ---
- ELASTICSEARCH_URL=http://elasticsearch:9200 # (ชี้ไปที่ Service ES ถ้ามี)
- N8N_WEBHOOK_URL=http://n8n:5678/webhook/your-webhook-id # (ชี้ไปที่ N8N)
# (สำคัญ) เชื่อมต่อ Network กลาง (Req 2.1)
MYSQL_ROOT_PASSWORD: Center#2025
MYSQL_DATABASE: lcbp3_dev
MYSQL_USER: admin
MYSQL_PASSWORD: Center2025
ports:
- '3306:3306'
volumes:
- db_data:/var/lib/mysql
networks:
- lcbp3
- lcbp3-net
# (Deploy) ตั้งค่า Health Check
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/api/v1/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 20s # (รอให้ App เริ่มก่อน)
# Optional: phpMyAdmin สำหรับจัดการ DB ง่ายๆ
pma:
image: phpmyadmin/phpmyadmin
container_name: lcbp3-pma-local
environment:
PMA_HOST: mariadb
ports:
- '8080:80'
depends_on:
- mariadb
networks:
- lcbp3-net
volumes:
db_data:
# ---------------------------------
# Network กลาง (Req 2.1)
# (ต้องสร้าง Network นี้ไว้ก่อนใน QNAP หรือสร้างพร้อมกัน)
# ---------------------------------
networks:
lcbp3:
external: true # (ถ้าสร้างไว้แล้ว)
# name: lcbp3 # (ถ้าต้องการให้ Compose สร้าง)
lcbp3-net:
driver: bridge

View File

@@ -20,57 +20,34 @@
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@elastic/elasticsearch": "^9.2.0",
"@nestjs/cache-manager": "^3.0.1",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1",
"@nestjs/elasticsearch": "^11.1.0",
"@nestjs/jwt": "^11.0.1",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.1.9",
"@nestjs/schedule": "^6.0.1",
"@nestjs/swagger": "^11.2.1",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/typeorm": "^11.0.0",
"@types/nodemailer": "^7.0.3",
"@types/uuid": "^10.0.0",
"bcrypt": "^6.0.0",
"cache-manager": "^7.2.4",
"casl": "^0.2.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.2",
"helmet": "^8.1.0",
"multer": "^2.0.2",
"mysql2": "^3.15.3",
"nodemailer": "^7.0.10",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"rate-limiter-flexible": "^8.2.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"typeorm": "^0.3.27",
"uuid": "^13.0.0"
"typeorm": "^0.3.27"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.1.9",
"@nestjs/testing": "^11.0.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/multer": "^2.0.0",
"@types/node": "^22.10.7",
"@types/passport-jwt": "^4.0.1",
"@types/supertest": "^6.0.2",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^16.0.0",
"jest": "^30.2.0",
"jest": "^30.0.0",
"prettier": "^3.4.2",
"source-map-support": "^0.5.21",
"supertest": "^7.1.4",
"supertest": "^7.0.0",
"ts-jest": "^29.2.5",
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",

6725
backend/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,38 @@
// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
imports: [
// 1. Load Config Module
ConfigModule.forRoot({
isGlobal: true, // ให้เรียกใช้ได้ทุกที่โดยไม่ต้อง import ใหม่
envFilePath: '.env', // อ่านค่าจากไฟล์ .env
}),
// 2. Setup TypeORM Connection (Async เพื่อรออ่าน Config ก่อน)
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
type: 'mariadb', // หรือ 'mysql' ก็ได้เพราะใช้ driver เดียวกัน
host: configService.get<string>('DB_HOST'),
port: configService.get<number>('DB_PORT'),
username: configService.get<string>('DB_USERNAME'),
password: configService.get<string>('DB_PASSWORD'),
database: configService.get<string>('DB_DATABASE'),
// Auto Load Entities: โหลด Entity ทั้งหมดที่อยู่ในโปรเจกต์อัตโนมัติ
autoLoadEntities: true,
// Synchronize: true เฉพาะ Dev environment (ห้ามใช้ใน Prod)
synchronize: configService.get<string>('NODE_ENV') === 'development',
// Logging: เปิดดู Query SQL ตอน Dev
logging: configService.get<string>('NODE_ENV') === 'development',
}),
inject: [ConfigService],
}),
],
controllers: [AppController],
providers: [AppService],
})

View File

@@ -1,6 +1,6 @@
{
"compilerOptions": {
"module": "nodenext",
"module": "commonjs",
"moduleResolution": "nodenext",
"resolvePackageJsonExports": true,
"esModuleInterop": true,
@@ -10,16 +10,18 @@
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
/* Strict Type-Checking Options */
"strict": true, // บังคับใช้ Strict Mode
"strictNullChecks": true, // ตรวจสอบค่า Null อย่างเคร่งครัด
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"noFallthroughCasesInSwitch": false
"noImplicitAny": true, // ห้ามใช้ Any โดยไม่จำเป็น
"strictBindCallApply": true,
"noFallthroughCasesInSwitch": true
}
}