12 Commits

Author SHA1 Message Date
fb26bb7b25 chore(git): ignore n8n-postgres/ and stop tracking it 2025-10-11 11:58:53 +07:00
c55f464f3c feat: Gen package-lock... 2025-10-11 10:30:47 +07:00
aa799edf2c chore(git): stop tracking top-level npm/ (NPM data) and ignore it 2025-10-11 10:13:53 +07:00
cc47c6f5f1 chore(git): stop tracking top-level npm/ (NPM data) and ignore it 2025-10-11 10:09:54 +07:00
admin
15145260f9 feat: backend rebuild 2025-10-11 09:24:40 +07:00
360ab1ac12 251011 start 2025-10-11 08:10:49 +07:00
admin
e58e164e54 update README.md 2025-10-10 16:42:32 +07:00
bbfbc5b910 fix: tailwind v4 postcss, auth-server session, eslint cleanups 2025-10-09 15:47:56 +07:00
670228b76e xxx 2025-10-05 11:57:43 +07:00
admin
754e494e7f fronted แก้ layout build 2 2025-10-05 11:05:03 +07:00
admin
5dec188744 fronted แก้ layout build dev&proc 2025-10-05 10:57:54 +07:00
admin
02e509986b fronted build dev&proc 2025-10-05 10:18:59 +07:00
139 changed files with 48101 additions and 2862 deletions

9
.gitignore vendored
View File

@@ -5,9 +5,12 @@
Documents/
mariadb/data/
n8n*/
n8n-postgres/
npm/
phpmyadmin/
pgadmin/
.tmp.driveupload
.qsync
# =====================================================
# IDE/Editor settings
# =====================================================
@@ -91,4 +94,8 @@ docker-compose.override.*.yml
/frontend/.cache/
.tmp/
.tmp*.*/
.cache/
.cache/
# Ignore Nginx Proxy Manager data
/npm/
/n8n-postgres/

4
.qsync/meta/meta.conf Normal file
View File

@@ -0,0 +1,4 @@
[/dms]
max_log = 510381
number = 3
finish = 1

10989
.qsync/meta/qmeta0 Normal file

File diff suppressed because it is too large Load Diff

11499
.qsync/meta/qmeta1 Normal file

File diff suppressed because it is too large Load Diff

8722
.qsync/meta/qmeta2 Normal file

File diff suppressed because it is too large Load Diff

257
7.conf
View File

@@ -1,257 +0,0 @@
# ------------------------------------------------------------
# lcbp3.np-dms.work
# ------------------------------------------------------------
map $scheme $hsts_header {
https "max-age=63072000; preload";
}
server {
set $forward_scheme http;
set $server "dms_frontend";
set $port 3000;
listen 80;
listen [::]:80;
listen 443 ssl;
listen [::]:443 ssl;
server_name lcbp3.np-dms.work;
http2 on;
# Let's Encrypt SSL
include conf.d/include/letsencrypt-acme-challenge.conf;
include conf.d/include/ssl-cache.conf;
include conf.d/include/ssl-ciphers.conf;
ssl_certificate /etc/letsencrypt/live/npm-7/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/npm-7/privkey.pem;
# HSTS (ngx_http_headers_module is required) (63072000 seconds = 2 years)
add_header Strict-Transport-Security $hsts_header always;
# Force SSL
include conf.d/include/force-ssl.conf;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
proxy_http_version 1.1;
access_log /data/logs/proxy-host-7_access.log proxy;
error_log /data/logs/proxy-host-7_error.log warn;
# ===== ขนาดไฟล์/timeout ระดับ Host =====
client_max_body_size 200m;
client_body_timeout 60s;
send_timeout 60s;
# ===== Proxy headers พื้นฐาน (ส่งให้ backend ทุกตัว) =====
# ที่นี่จะเป็นที่กำหนด header หลักเพียงแห่งเดียว
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# ===== WebSocket/SSE header ระดับ Host =====
# พร้อมสำหรับทุก location ที่อาจต้องใช้ WebSocket
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade"; # ใช้ "upgrade" โดยตรงจะเสถียรกว่า
# ===== สำคัญสำหรับคุกกี้ HttpOnly (ให้ทุก backend) =====
proxy_pass_header Set-Cookie;
# ===== Security headers ระดับ Host (ยอดเยี่ยมมากครับ) =====
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
location /health {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_read_timeout 15s;
proxy_send_timeout 15s;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Scheme $scheme;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://dms_frontend:3000;
# Force SSL
include conf.d/include/force-ssl.conf;
# HSTS (ngx_http_headers_module is required) (63072000 seconds = 2 years)
add_header Strict-Transport-Security $hsts_header always;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
proxy_http_version 1.1;
}
location /_next/static/ {
proxy_set_header Host $host;
add_header Cache-Control "public, max-age=31536000, immutable";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Scheme $scheme;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://dms_frontend:3000;
# Force SSL
include conf.d/include/force-ssl.conf;
# HSTS (ngx_http_headers_module is required) (63072000 seconds = 2 years)
add_header Strict-Transport-Security $hsts_header always;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
proxy_http_version 1.1;
}
location /api/ {
# ===== CORS Configuration =====
set $cors_allow_origin "";
if ($http_origin ~* "^https?://(localhost(:\\d+)?|127\\.0\\.0\\.1(:\\d+)?|np-dms\\.work|www\\.np-dms\\.work|lcbp3\\.np-dms\\.work)$") {
set $cors_allow_origin $http_origin;
}
add_header Vary "Origin" always;
add_header Access-Control-Allow-Credentials "true" always;
add_header Access-Control-Allow-Origin $cors_allow_origin always;
add_header Access-Control-Expose-Headers "Content-Disposition,Content-Length" always;
add_header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers "Authorization, Content-Type, Accept, Origin, Referer, User-Agent, X-Requested-With, Cache-Control, Pragma" always;
# ===== OPTIONS preflight =====
if ($request_method = OPTIONS) {
add_header Content-Length 0;
add_header Content-Type text/plain;
add_header Access-Control-Allow-Origin $cors_allow_origin always;
add_header Access-Control-Allow-Credentials "true" always;
add_header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers "Authorization, Content-Type, Accept, Origin, Referer, User-Agent, X-Requested-With, Cache-Control, Pragma" always;
return 204;
}
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Scheme $scheme;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://dms_backend:3001;
# Force SSL
include conf.d/include/force-ssl.conf;
# HSTS (ngx_http_headers_module is required) (63072000 seconds = 2 years)
add_header Strict-Transport-Security $hsts_header always;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
proxy_http_version 1.1;
}
location / {
# HSTS (ngx_http_headers_module is required) (63072000 seconds = 2 years)
add_header Strict-Transport-Security $hsts_header always;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
proxy_http_version 1.1;
# Proxy!
include conf.d/include/proxy.conf;
}
# Custom
include /data/nginx/custom/server_proxy[.]conf;
}

506
Architech.md Executable file
View File

@@ -0,0 +1,506 @@
# DMS Architecture Deep Dive (Backend + Frontend)
**Project:** Document Management System (DMS) — LCBP3
**Platform:** QNAP TS473A (Container Station)
**Last updated:** 20251007 (UTC+7)
---
## 0) TL;DR (Executive Summary)
* Reverse proxy (Nginx/NPM) เผยแพร่ Frontend (Next.js) และ Backend (Node.js/Express) ผ่าน HTTPS (HSTS)
* Backend เชื่อม MariaDB 10.11 (ข้อมูลหลัก DMS) และแยก n8n + Postgres 16 สำหรับ workflow
* RBAC/ABAC ถูกบังคับใช้งานใน middleware + มีชุด SQL (tables → triggers → procedures → views → seed)
* ไฟล์จริง (PDF/DWG) เก็บนอก webroot ที่ **/share/dmsdata** พร้อมมาตรฐานการตั้งชื่อ+โฟลเดอร์
* Dev/Prod แยกชัดเจนผ่าน Docker multistage + dockercompose + โฟลเดอร์ persist logs/config/certs
---
## 1) Runtime Topology & Trust Boundaries
```
Internet Clients (Browser)
│ HTTPS 443 (HSTS) [QNAP mgmt = 8443]
┌─────────────────────────────────────────────────────┐
│ Reverse Proxy Layer │
│ ├─ Nginx (Alpine) or Nginx Proxy Manager (NPM) │
│ ├─ TLS (LE cert; SAN multisubdomain) │
│ └─ Routes: │
│ • /, /_next/* → Frontend (Next.js :3000) │
│ • /api/* → Backend (Express :3001) │
│ • /pma/* → phpMyAdmin │
│ • /n8n/* → n8n (Workflows) │
└─────────────────────────────────────────────────────┘
│ │
│ └──────────┐
▼ │
Frontend (Next.js) │
│ Cookie-based Auth (HttpOnly) │
▼ ▼
Backend (Node/Express ESM) ─────────► MariaDB 10.11
│ │
└────────────────────────────────────┘
Project data (.pdf/.dwg) @ /share/dms-data
n8n (workflows) ──► Postgres 16 (separate DB for automations)
```
**Trust Boundaries**
* Public zone: Internet ↔ Reverse proxy
* App zone: Reverse proxy ↔ FE/BE containers (internal Docker network)
* Data zone: Backend ↔ Databases (MariaDB, Postgres) + `/share/dms-data`
---
## 2) Frontend Architecture (Next.js / React)
### 2.1 Stack & Key libs
* **Next.js (App Router)**, **React**, ESM
* **Tailwind CSS**, **PostCSS**, **shadcn/ui** (components.json)
* Fetch API (credentials include) → Cookie Auth (HttpOnly)
### 2.2 Directory Layout
```
/frontend/
├─ app/
│ ├─ login/
│ ├─ dashboard/
│ ├─ users/
│ ├─ correspondences/
│ ├─ health/
│ └─ layout.tsx / page.tsx (ตาม App Router)
├─ public/
├─ Dockerfile (multi-stage: dev/prod)
├─ package.json
├─ next.config.js
└─ ...
```
### 2.3 Routing & Layouts
* **Public**: `/login`, `/health`
* **Protected**: `/dashboard`, `/users`, `/correspondences`, ... (client-side guard)
* เก็บ **middleware.ts (ของเดิม)** เพื่อหลีกเลี่ยง regression; ใช้ clientguard + server action อย่างระมัดระวัง
### 2.4 Auth Flow (Cookie-based)
1. ผู้ใช้ submit form `/login``POST /api/auth/login` (Backend)
2. Backend set **HttpOnly** cookie (JWT) + `SameSite=Lax/Strict`, `Secure`
3. หน้า protected เรียก `GET /api/auth/me` เพื่อตรวจสอบสถานะ
4. หาก 401 → redirect → `/login`
> **CORS/Fetch**: เปิด `credentials: 'include'` ทุกครั้ง, ตั้ง `NEXT_PUBLIC_API_BASE` เป็น origin ของ backend ผ่าน proxy (เช่น `https://lcbp3.np-dms.work`)
### 2.5 UI/UX
* Seablue palette, sidebar พับได้, cardbased KPI
* ตารางข้อมูลเตรียมรองรับ **serverside DataTables**
* shadcn/ui: Button, Card, Badge, Tabs, Dropdown, Tooltip, Switch, etc.
### 2.6 Config & ENV
* `NEXT_PUBLIC_API_BASE` (ex: `https://lcbp3.np-dms.work`)
* Build output แยก dev/prod; ระวัง EACCES บน QNAP → ใช้ user `node` + ปรับสิทธิ์โวลุ่ม `.next/*`
### 2.7 Error Handling & Observability (FE)
* Global error boundary (app router) + toast/alert patterns
* Network layer: แยก handler สำหรับ 401/403/500 + retry/backoff ที่จำเป็น
* Metrics (optional): webvitals, UX timing (เก็บฝั่ง n8n หรือ simple logging)
---
## 3) Backend Architecture (Node.js ESM / Express)
### 3.1 Stack & Structure
* Node 20.x, **ESM** modules, **Express**
* `mysql2/promise`, `jsonwebtoken`, `cookie-parser`, `cors`, `helmet`, `winston/morgan`
```tree
/backend/
├─ src/
│ ├─ index.js # bootstrap server, CORS, cookies, health
│ ├─ routes/
│ │ ├─ auth.js # /api/auth/* (login, me, logout)
│ │ ├─ users.js # /api/users/*
│ │ ├─ correspondences.js # /api/correspondences/*
│ │ ├─ drawings.js # /api/drawings/*
│ │ ├─ rfas.js # /api/rfas/*
│ │ └─ transmittals.js # /api/transmittals/*
│ ├─ middleware/
│ │ ├─ authGuard.js # verify JWT from cookie
│ │ ├─ requirePermission.js# RBAC/ABAC enforcement
│ │ ├─ errorHandler.js
│ │ └─ requestLogger.js
│ ├─ db/
│ │ ├─ pool.js # createPool, sane defaults
│ │ └─ models/ # query builders (User, Drawing, ...)
│ ├─ utils/
│ │ ├─ hash.js (bcrypt/argon2)
│ │ ├─ jwt.js
│ │ ├─ pagination.js
│ │ └─ responses.js
│ └─ config/
│ └─ index.js # env, constants
├─ Dockerfile
└─ package.json
```
### 3.2 Request Lifecycle
1. `helmet` + `cors` (allow specific origin; credentials true)
2. `cookie-parser`, `json limit` (e.g., 2MB)
3. `requestLogger` → trace + response time
4. Route handler → `authGuard` (protected) → `requirePermission` (perroute) → Controller
5. Error bubbles → `errorHandler` (JSON shape, status map)
### 3.3 Auth & RBAC/ABAC
* **JWT** ใน HttpOnly cookie; Claims: `sub` (user_id), `roles`, `exp`
* **authGuard**: ตรวจ token → แนบ `req.user`
* **requirePermission**: เช็ค permission ตามเส้นทาง/วิธี; แผนขยาย ABAC (เช่น project scope, owner, doc state)
* Roles/Permissions ถูก seed ใน SQL; มี **view เมทริกซ์** เพื่อ debug (เช่น `v_role_permission_matrix`)
**ตัวอย่าง pseudo** `requirePermission(permission)`
```js
export const requirePermission = (perm) => async (req, res, next) => {
if (!req.user) return res.status(401).json({ error: 'Unauthenticated' });
const ok = await checkPermission(req.user.user_id, perm, req.context);
if (!ok) return res.status(403).json({ error: 'Forbidden' });
return next();
};
```
### 3.4 Database Access & Pooling
* `createPool({ connectionLimit: 10~25, queueLimit: 0, waitForConnections: true })`
* ใช้ parameterized queries เสมอ; ปรับ `sql_mode` ที่จำเป็นใน `my.cnf`
### 3.5 File Storage & Secure Download
* Root: **/share/dmsdata**
* โครงโฟลเดอร์: `{module}/{yyyy}/{mm}/{entityId}/` + ชื่อไฟล์ตามมาตรฐาน (เช่น `DRW-<code>-REV-<rev>.pdf`)
* Endpoint download: ตรวจสิทธิ์ (RBAC/ABAC) → `res.sendFile()`/stream; ป้องกัน path traversal
* MIME allowlist + size limit + virus scan (optional; ภายหลัง)
### 3.6 Health & Readiness
* `GET /api/health``{ ok: true }`
* (optional) `/api/ready` ตรวจ DB ping + disk space (dmsdata)
### 3.7 Config & ENV (BE)
* `DB_HOST, DB_PORT, DB_USER, DB_PASS, DB_NAME`
* `JWT_SECRET, COOKIE_NAME, COOKIE_SAMESITE, COOKIE_SECURE`
* `CORS_ORIGIN, LOG_LEVEL, APP_BASE_URL`
* `FILE_ROOT=/share/dms-data`
### 3.8 Logging
* Access log (morgan) + App log (winston) → `/share/Container/dms/logs/backend/`
* รูปแบบ JSON (timestamp, level, msg, reqId) + daily rotation (logrotate/containerside)
---
## 4) Database (MariaDB 10.11)
### 4.1 Schema Overview (ย่อ)
* **RBAC core**: `users`, `roles`, `permissions`, `user_roles`, `role_permissions`
* **Domain**: `drawings`, `contracts`, `correspondences`, `rfas`, `transmittals`, `organizations`, `projects`, ...
* **Audit**: `audit_logs` (แผนขยาย), `deleted_at` (soft delete, แผนงาน)
```
[users]──<user_roles>──[roles]──<role_permissions>──[permissions]
└── activities/audit_logs (future expansion)
[drawings]──<mapping>──[contracts]
[rfas]──<links>──[drawings]
[correspondences] (internal/external flag)
```
### 4.2 Init SQL Pipeline
1. `01_*_deploy_table_rbac.sql` — สร้างตารางหลักทั้งหมด + RBAC
2. `02_*_triggers.sql` — บังคับ data rules, autoaudit fields
3. `03_*_procedures_handlers.sql` — upsert/bulk handlers (เช่น `sp_bulk_import_contract_dwg`)
4. `04_*_views.sql` — รายงาน/เมทริกซ์สิทธิ์ (`v_role_permission_matrix`, etc.)
5. `05_*_seed_data.sql` — ค่าพื้นฐาน domain (project, categories, statuses)
6. `06_*_seed_users.sql` — บัญชีเริ่มต้น (superadmin, editors, viewers)
7. `07_*_seed_contract_dwg.sql` — ข้อมูลตัวอย่างแบบสัญญา
### 4.3 Indexing & Performance
* Composite indexes ตามคอลัมน์ filter/sort (เช่น `(project_id, updated_at DESC)`)
* Fulltext index (optional) สำหรับ advanced search
* Query plan review (EXPLAIN) + เพิ่ม covering index ตามรายงาน
### 4.4 MySQL/MariaDB Config (my.cnf — แนวทาง)
```
[mysqld]
innodb_buffer_pool_size = 4G # ปรับตาม RAM/QNAP
innodb_log_file_size = 512M
innodb_flush_log_at_trx_commit = 1
max_connections = 200
sql_mode = STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
```
> ปรับค่าให้เหมาะกับ workload จริง + เฝ้าดู IO/CPU ของ QNAP
### 4.5 Backup/Restore
* Logical backup: `mysqldump --routines --triggers --single-transaction`
* Physical (snapshot QNAP) + schedule ผ่าน n8n/cron
* เก็บสำเนา offNAS (encrypted)
---
## 5) Reverse Proxy & TLS
### 5.1 Nginx (Alpine) — ตัวอย่าง server block
> **สำคัญ:** บนสภาพแวดล้อมนี้ ให้ใช้คนละบรรทัด:
> `listen 443 ssl;`
> `http2 on;`
> หลีกเลี่ยง `listen 443 ssl http2;`
```nginx
server {
listen 80;
server_name lcbp3.np-dms.work;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
http2 on;
server_name lcbp3.np-dms.work;
ssl_certificate /etc/nginx/certs/fullchain.pem;
ssl_certificate_key /etc/nginx/certs/privkey.pem;
add_header Strict-Transport-Security "max-age=63072000; preload" always;
# Frontend
location / {
proxy_pass http://frontend:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Next.js static
location /_next/ {
proxy_pass http://frontend:3000;
}
# Backend API
location /api/ {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://backend:3001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
}
# phpMyAdmin (sub-path)
location /pma/ {
proxy_pass http://phpmyadmin:80/;
}
# n8n
location /n8n/ {
proxy_pass http://n8n:5678/;
}
}
```
### 5.2 Nginx Proxy Manager (NPM) — Tips
* ระวังอย่าใส่ `proxy_http_version` ซ้ำซ้อน (duplicate directive) ใน Advanced
* ถ้าต้องแก้ไฟล์ด้านใน NPM → ระวังไฟล์ใน `/data/nginx/proxy_host/*.conf`
* จัดการ certificate / SAN หลาย subdomain ใน UI แต่ mainten ดีเรื่อง symlink/renew
### 5.3 TLS & Certificates
* Lets Encrypt (HTTP01 webroot/standalone) + HSTS
* QNAP mgmt เปลี่ยนเป็น 8443 → พอร์ต 443 public ว่างสำหรับ Nginx/NPM
---
## 6) Docker Compose Topology
### 6.1 Services (สรุป)
* `frontend` (Next.js) :3000
* `backend` (Express) :3001
* `mariadb` (10.11) :3306 (internal)
* `phpmyadmin` :80 (internal)
* `nginx` or `npm` :80/443 (published)
* `n8n` :5678 (internal)
* `postgres_n8n` (16-alpine)
* `pgadmin4`
### 6.2 Volumes & Paths
```
/share/Container/dms/
├─ mariadb/data
├─ mariadb/init/*.sql
├─ backend/ (code)
├─ frontend/ (code)
├─ phpmyadmin/{sessions,tmp,config.user.inc.php}
├─ nginx/{nginx.conf,dms.conf,certs/}
├─ n8n, n8n-postgres, n8n-cache
└─ logs/{backend,frontend,nginx,pgadmin,phpmyadmin,postgres_n8n}
/share/dms-data (pdf/dwg storage)
```
### 6.3 Healthchecks (suggested)
* **backend**: curl `http://localhost:3001/api/health`
* **frontend**: curl `/health` (simple JSON)
* **mariadb**: `mysqladmin ping` with credentials
* **nginx**: `nginx -t` at startup
### 6.4 Security Hardening
* รัน container ด้วย user nonroot (`user: node` สำหรับ FE/BE)
* จำกัด capabilities; readonly FS (ยกเว้นโวลุ่มจำเป็น)
* เฉพาะ backend เมานต์ `/share/dms-data`
---
## 7) Observability, Ops, and Troubleshooting
### 7.1 Logs
* Frontend → `/logs/frontend/*`
* Backend → `/logs/backend/*` (app/access/error)
* Nginx/NPM → `/logs/nginx/*`
* MariaDB → default datadir log + slow query (เปิดใน my.cnf หากต้องการ)
### 7.2 Common Issues & Playbooks
* **401 Unauthenticated**: ตรวจ `authGuard` → JWT cookie มี/หมดอายุ → เวลา server/FE sync → CORS `credentials: true`
* **EACCES Next.js**: สิทธิ์ `.next/*` + run as `node`, โวลุ่ม map ถูก user:group
* **NPM duplicate directive**: ลบซ้ำ `proxy_http_version` ใน Advanced / ตรวจ `proxy_host/*.conf`
* **LE cert path/symlink**: ตรวจ `/etc/letsencrypt/live/npm-*` symlink ชี้ถูก
* **DB field not found**: ตรวจ schema vs code (migration/init SQL) → sync ให้ตรง
### 7.3 Performance Guides
* **Backend**: keepalive, gzip/deflate at proxy, pool 1025, paginate, avoid N+1
* **Frontend**: prefetch critical routes, cache static, image optimization
* **DB**: เพิ่ม index จุด filter, analyze query (EXPLAIN), ปรับ buffer pool
---
## 8) Security & Compliance
* **HTTPS only** + HSTS (preload)
* **CORS**: allow list เฉพาะ FE origin; `Access-Control-Allow-Credentials: true`
* **Cookie**: HttpOnly, Secure, SameSite=Lax/Strict
* **Input Validation**: celebrate/zod (optional) + sanitize
* **Rate limiting**: per IP/route (optional)
* **AuditLog**: วางแผนเพิ่ม ครอบคลุม CRUD + mapping (actor, action, entity, before/after)
* **Backups**: DB + `/share/dms-data` + config (encrypted offNAS)
---
## 9) Backlog → Architecture Mapping
1. **RBAC Enforcement ครบ** → เติม `requirePermission` ทุก route + test matrix ผ่าน view
2. **AuditLog ครบ CRUD/Mapping** → trigger + table `audit_logs` + BE hook
3. **Upload/Download จริงของ Drawing Revisions** → BE endpoints + virus scan (optional)
4. **Dashboard KPI** → BE summary endpoints + FE cards/charts
5. **Serverside DataTables** → paging/sort/filter + indexesรองรับ
6. **รายงาน Export CSV/Excel/PDF** → BE export endpoints + FE buttons
7. **Soft delete** (`deleted_at`) → BE filter default scope + restore endpoint
8. **Validation เข้ม** → celebrate/zod schema + consistent error shape
9. **Indexing/Perf** → slow query log + EXPLAIN review
10. **Job/Cron Deadline Alerts** → n8n schedule + SMTP
---
## 10) Port & ENV Matrix (Quick Ref)
| Component | Ports | Key ENV |
| --------- | --------------- | ------------------------------------------------ |
| Nginx/NPM | 80/443 (public) | SSL paths, HSTS |
| Frontend | 3000 (internal) | `NEXT_PUBLIC_API_BASE` |
| Backend | 3001 (internal) | `DB_*`, `JWT_SECRET`, `CORS_ORIGIN`, `FILE_ROOT` |
| MariaDB | 3306 (internal) | `MY_CNF`, credentials |
| n8n | 5678 (internal) | `N8N_*`, webhook URL under `/n8n/` |
| Postgres | 5432 (internal) | n8n DB |
**QNAP mgmt**: 8443 (already moved)
---
## 11) Sample Snippets
### 11.1 Backend CORS (credentials)
```js
app.use(cors({
origin: ['https://lcbp3.np-dms.work'],
credentials: true,
}));
```
### 11.2 Secure Download (guarded)
```js
router.get('/files/:module/:id/:filename', authGuard, requirePermission('file.read'), async (req, res) => {
const { module, id, filename } = req.params;
// 1) ABAC: verify user can access this module/entity
const ok = await canReadFile(req.user.user_id, module, id);
if (!ok) return res.status(403).json({ error: 'Forbidden' });
const abs = path.join(FILE_ROOT, module, id, filename);
if (!abs.startsWith(FILE_ROOT)) return res.status(400).json({ error: 'Bad path' });
return res.sendFile(abs);
});
```
### 11.3 Healthcheck
```js
router.get('/health', (req, res) => res.json({ ok: true }));
```
---
## 12) Deployment Workflow (Suggested)
1. Git (Gitea) branch strategy `feature/*` → PR → main
2. Build images (dev/prod) via Dockerfile multistage; pin Node/MariaDB versions
3. `docker compose up -d --build` จาก `/share/Container/dms`
4. Validate: `/health`, `/api/health`, login roundtrip
5. Monitor logs + baseline perf; run SQL smoke tests (views/triggers/procs)
---
## 13) Appendix
* **Naming conventions**: snake_case DB, camelCase JS
* **Timezones**: store UTC in DB; display in app TZ (+07:00)
* **Character set**: UTF8 (`utf8mb4_unicode_ci`)
* **Large file policy**: size limit (e.g., 50200MB), allowlist extensions
* **Retention**: archive strategy for old revisions (optional)
---
> หากต้องการ เวอร์ชัน **README.md พร้อมโค้ดตัวอย่าง compose/nginx** จัดรูปแบบให้นำไปวางใน repo ได้ทันที แจ้งได้เลยว่าจะให้แตกไฟล์เป็น `/docs/Architecture.md` + `/nginx/dms.conf` + `/docker-compose.yml` template หรือรูปแบบอื่นที่สะดวกต่อการใช้งานของทีม

View File

@@ -1,483 +0,0 @@
diff --git a/backend/src/middleware/requireBearer.js b/backend/src/middleware/requireBearer.js
new file mode 100644
index 0000000..1111111
--- /dev/null
+++ b/backend/src/middleware/requireBearer.js
@@ -0,0 +1,44 @@
+// backend/src/middleware/requireBearer.js
+import jwt from "jsonwebtoken";
+import { findUserById } from "../db/models/users.js";
+
+export async function requireBearer(req, res, next) {
+ const hdr = req.get("Authorization") || "";
+ const m = hdr.match(/^Bearer\s+(.+)$/i);
+ if (!m) return res.status(401).json({ error: "Unauthenticated" });
+ try {
+ const payload = jwt.verify(m[1], process.env.JWT_ACCESS_SECRET, {
+ issuer: "dms-backend",
+ });
+ const user = await findUserById(payload.user_id);
+ if (!user) return res.status(401).json({ error: "Unauthenticated" });
+ req.user = {
+ user_id: user.user_id,
+ username: user.username,
+ email: user.email,
+ first_name: user.first_name,
+ last_name: user.last_name,
+ };
+ next();
+ } catch {
+ return res.status(401).json({ error: "Unauthenticated" });
+ }
+}
diff --git a/backend/src/routes/auth.js b/backend/src/routes/auth.js
index 2222222..3333333 100644
--- a/backend/src/routes/auth.js
+++ b/backend/src/routes/auth.js
@@ -1,99 +1,109 @@
-// (เดิม) ผูกกับคุกกี้ / ส่ง ok:true ฯลฯ
+// backend/src/routes/auth.js — Bearer Token ล้วน
import { Router } from "express";
import jwt from "jsonwebtoken";
-import { findUserByUsername } from "../db/models/users.js";
+import { findUserByUsername, findUserById } from "../db/models/users.js";
import { verifyPassword } from "../utils/passwords.js";
-// NOTE: ลบการใช้งาน res.cookie(...) ทั้งหมด
+// NOTE: ไม่มีการใช้ res.cookie(...) อีกต่อไป
const router = Router();
function signAccessToken(user) {
return jwt.sign(
{ user_id: user.user_id, username: user.username },
process.env.JWT_ACCESS_SECRET,
- { issuer: "dms-backend", expiresIn: "30m" } // ปรับได้
+ { issuer: "dms-backend", expiresIn: "30m" }
);
}
function signRefreshToken(user) {
return jwt.sign(
- { user_id: user.user_id, username: user.username },
+ { user_id: user.user_id, username: user.username, t: "refresh" },
process.env.JWT_REFRESH_SECRET,
{ issuer: "dms-backend", expiresIn: "30d" }
);
}
router.post("/login", async (req, res) => {
const { username, password } = req.body || {};
const user = await findUserByUsername(username);
if (!user || !(await verifyPassword(password, user.password_hash))) {
return res.status(401).json({ error: "INVALID_CREDENTIALS" });
}
const token = signAccessToken(user);
const refresh_token = signRefreshToken(user);
return res.json({
token,
refresh_token,
user: {
user_id: user.user_id,
username: user.username,
email: user.email,
first_name: user.first_name,
last_name: user.last_name,
},
});
});
+router.post("/refresh", async (req, res) => {
+ const hdr = req.get("Authorization") || "";
+ const m = hdr.match(/^Bearer\s+(.+)$/i);
+ const r = m?.[1];
+ if (!r) return res.status(401).json({ error: "NO_REFRESH_TOKEN" });
+ try {
+ const payload = jwt.verify(r, process.env.JWT_REFRESH_SECRET, {
+ issuer: "dms-backend",
+ });
+ const user = await findUserById(payload.user_id);
+ if (!user) return res.status(401).json({ error: "USER_NOT_FOUND" });
+ const token = signAccessToken(user);
+ return res.json({ token });
+ } catch {
+ return res.status(401).json({ error: "INVALID_REFRESH_TOKEN" });
+ }
+});
+
export default router;
diff --git a/backend/src/index.js b/backend/src/index.js
index 4444444..5555555 100644
--- a/backend/src/index.js
+++ b/backend/src/index.js
@@ -1,60 +1,69 @@
import express from "express";
import cors from "cors";
import authRouter from "./routes/auth.js";
+import { requireBearer } from "./middleware/requireBearer.js";
-// import routers อื่น ๆ ตามจริง เช่น rfasRouter, transmittalsRouter
const app = express();
-// CORS เดิม (อาจมี credentials)
-app.use(cors({
- origin: true,
- credentials: true,
-}));
+// ✅ CORS สำหรับ Bearer: ไม่ต้อง credentials, อนุญาต Authorization header
+app.use(cors({
+ origin: [
+ "https://lcbp3.np-dms.work",
+ "http://localhost:3000"
+ ],
+ methods: ["GET","POST","PUT","PATCH","DELETE","OPTIONS"],
+ allowedHeaders: ["Authorization","Content-Type","Accept","Origin","Referer","User-Agent","X-Requested-With","Cache-Control","Pragma"],
+ exposedHeaders: ["Content-Disposition","Content-Length"]
+}));
app.use(express.json());
-// routes เดิม
-app.use("/api/auth", authRouter);
-// app.use("/api/rfas", rfasRouter);
-// app.use("/api/transmittals", transmittalsRouter);
+// ✅ เส้นทาง auth (ไม่ต้องมี token)
+app.use("/api/auth", authRouter);
+
+// ✅ ตั้ง guard สำหรับเส้นทางที่เหลือต้องล็อกอิน
+app.use("/api", requireBearer);
+// แล้วค่อย mount routers protected ใต้ /api
+// app.use("/api/rfas", rfasRouter);
+// app.use("/api/transmittals", transmittalsRouter);
app.use((err, _req, res, _next) => {
console.error(err);
res.status(500).json({ error: "INTERNAL_SERVER_ERROR" });
});
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`backend listening on :${port}`));
diff --git a/frontend/app/(auth)/login/page.jsx b/frontend/app/(auth)/login/page.jsx
index 6666666..7777777 100644
--- a/frontend/app/(auth)/login/page.jsx
+++ b/frontend/app/(auth)/login/page.jsx
@@ -1,200 +1,236 @@
// File: frontend/app/(auth)/login/page.jsx
"use client";
-// เวอร์ชันเดิม
+// ✅ Bearer-only + Debug toggle (NEXT_PUBLIC_DEBUG_AUTH)
import { useState, useMemo, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import {
Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter,
} from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert";
-const API_BASE = process.env.NEXT_PUBLIC_API_BASE?.replace(/\/$/, "") || "";
+const API_BASE = process.env.NEXT_PUBLIC_API_BASE?.replace(/\/$/, "") || "";
+const DEBUG =
+ String(process.env.NEXT_PUBLIC_DEBUG_AUTH || "").trim() !== "" &&
+ process.env.NEXT_PUBLIC_DEBUG_AUTH !== "0" &&
+ process.env.NEXT_PUBLIC_DEBUG_AUTH !== "false";
+function dlog(...args) {
+ if (DEBUG && typeof window !== "undefined") console.debug("[login]", ...args);
+}
function LoginForm() {
const router = useRouter();
const searchParams = useSearchParams();
const nextPath = useMemo(
() => searchParams.get("next") || "/dashboard",
[searchParams]
);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [showPw, setShowPw] = useState(false);
const [remember, setRemember] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [err, setErr] = useState("");
async function onSubmit(e) {
e.preventDefault();
setErr("");
if (!username.trim() || !password) {
setErr("กรอกชื่อผู้ใช้และรหัสผ่านให้ครบ");
return;
}
try {
setSubmitting(true);
+ dlog("API_BASE =", API_BASE || "(empty → relative)");
+ dlog("nextPath =", nextPath, "remember =", remember);
const res = await fetch(`${API_BASE}/api/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
cache: "no-store",
});
- const data = await res.json().catch(() => ({}));
+ dlog("response.status =", res.status);
+ dlog("response.headers.content-type =", res.headers.get("content-type"));
+ let data = {};
+ try { data = await res.json(); } catch (e) { dlog("response.json() error =", e); }
+ dlog("response.body =", data);
if (!res.ok) {
- setErr(data?.error || "เข้าสู่ระบบไม่สำเร็จ");
+ const msg =
+ data?.error === "INVALID_CREDENTIALS"
+ ? "ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง"
+ : data?.error || `เข้าสู่ระบบไม่สำเร็จ (HTTP ${res.status})`;
+ dlog("login FAILED →", msg);
+ setErr(msg);
return;
}
+ if (!data?.token) {
+ dlog("login FAILED → data.token not found");
+ setErr("รูปแบบข้อมูลตอบกลับไม่ถูกต้อง (ไม่มี token)");
+ return;
+ }
const storage = remember ? window.localStorage : window.sessionStorage;
storage.setItem("dms.token", data.token);
storage.setItem("dms.refresh_token", data.refresh_token);
storage.setItem("dms.user", JSON.stringify(data.user || {}));
+ dlog("token stored in", remember ? "localStorage" : "sessionStorage");
try {
window.dispatchEvent(
new StorageEvent("storage", { key: "dms.auth", newValue: "login" })
);
} catch {}
- router.replace(nextPath);
+ dlog("navigating →", nextPath);
+ router.replace(nextPath);
} catch (e) {
+ dlog("exception =", e);
setErr("เชื่อมต่อเซิร์ฟเวอร์ไม่ได้ กรุณาลองใหม่");
} finally {
setSubmitting(false);
+ dlog("done");
}
}
return (
<div className="grid min-h-[calc(100vh-4rem)] place-items-center p-4">
<Card className="w-full max-w-md border-0 shadow-xl ring-1 ring-black/5 bg-white/90 backdrop-blur">
<CardHeader className="space-y-1">
<CardTitle className="text-2xl font-bold text-sky-800">เข้าสู่ระบบ</CardTitle>
<CardDescription className="text-sky-700">Document Management System • LCBP3</CardDescription>
</CardHeader>
<CardContent>
{err ? (
<Alert className="mb-4"><AlertDescription>{err}</AlertDescription></Alert>
) : null}
<form onSubmit={onSubmit} className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="username">ชื่อผู้ใช้</Label>
<Input id="username" autoFocus autoComplete="username" value={username}
onChange={(e) => setUsername(e.target.value)} placeholder="เช่น superadmin" disabled={submitting}/>
</div>
<div className="grid gap-2">
<Label htmlFor="password">รหัสผ่าน</Label>
<div className="relative">
<Input id="password" type={showPw ? "text" : "password"} autoComplete="current-password"
value={password} onChange={(e) => setPassword(e.target.value)} placeholder="••••••••"
disabled={submitting} className="pr-10"/>
<button type="button" onClick={() => setShowPw((v) => !v)}
className="absolute inset-y-0 px-2 my-auto text-xs bg-white border rounded-md right-2 hover:bg-slate-50"
aria-label={showPw ? "ซ่อนรหัสผ่าน" : "แสดงรหัสผ่าน"} disabled={submitting}>
{showPw ? "Hide" : "Show"}
</button>
</div>
</div>
<div className="flex items-center justify-between pt-1">
<label className="inline-flex items-center gap-2 text-sm text-slate-600">
<input type="checkbox" className="size-4 accent-sky-700"
checked={remember} onChange={(e) => setRemember(e.target.checked)} disabled={submitting}/>
จดจำฉันไว้ในเครื่องนี้
</label>
<a href="/forgot-password" className="text-sm text-sky-700 hover:text-sky-900 hover:underline">ลืมรหัสผ่าน?</a>
</div>
<Button type="submit" disabled={submitting} className="mt-2 bg-sky-700 hover:bg-sky-800">
{submitting ? (<span className="inline-flex items-center gap-2"><Spinner /> กำลังเข้าสู่ระบบ…</span>) : ("เข้าสู่ระบบ")}
</Button>
+ {DEBUG ? (
+ <p className="mt-2 text-xs text-slate-500">
+ DEBUG: NEXT_PUBLIC_API_BASE = <code>{API_BASE || "(empty)"}</code>
+ </p>
+ ) : null}
</form>
</CardContent>
<CardFooter className="text-xs text-center text-slate-500">
&copy; {new Date().getFullYear()} np-dms.work
</CardFooter>
</Card>
</div>
);
}
export default function LoginPage() {
return (
<Suspense fallback={<LoginPageSkeleton />}>
<LoginForm />
</Suspense>
);
}
function LoginPageSkeleton() {
return (
<div className="grid min-h-[calc(100vh-4rem)] place-items-center p-4">
<Card className="w-full max-w-md border-0 shadow-xl ring-1 ring-black/5 bg-white/90 backdrop-blur">
<CardHeader className="space-y-1">
<CardTitle className="text-2xl font-bold text-sky-800">เข้าสู่ระบบ</CardTitle>
<CardDescription className="text-sky-700">Document Management System • LCBP3</CardDescription>
</CardHeader>
<CardContent>
<div className="grid gap-4 animate-pulse">
<div className="h-10 rounded bg-slate-200"></div>
<div className="h-10 rounded bg-slate-200"></div>
<div className="h-10 rounded bg-slate-200"></div>
</div>
</CardContent>
</Card>
</div>
);
}
function Spinner() {
return (
<svg className="animate-spin size-4" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" />
</svg>
);
}
diff --git a/frontend/app/(protected)/layout.jsx b/frontend/app/(protected)/layout.jsx
new file mode 100644
index 0000000..8888888
--- /dev/null
+++ b/frontend/app/(protected)/layout.jsx
@@ -0,0 +1,38 @@
+"use client";
+import { useEffect, useState } from "react";
+import { usePathname, useRouter } from "next/navigation";
+
+export default function ProtectedLayout({ children }) {
+ const router = useRouter();
+ const pathname = usePathname();
+ const [ready, setReady] = useState(false);
+
+ useEffect(() => {
+ try {
+ const token =
+ (typeof window !== "undefined" &&
+ (localStorage.getItem("dms.token") ||
+ sessionStorage.getItem("dms.token"))) ||
+ null;
+ if (!token) {
+ const next = encodeURIComponent(pathname || "/dashboard");
+ router.replace(`/login?next=${next}`);
+ return;
+ }
+ } finally {
+ setReady(true);
+ }
+ }, [pathname, router]);
+
+ if (!ready) {
+ return (
+ <div className="grid min-h-[calc(100vh-4rem)] place-items-center p-6 text-slate-600">
+ กำลังตรวจสิทธิ์…
+ </div>
+ );
+ }
+ return <>{children}</>;
+}
diff --git a/frontend/lib/api.js b/frontend/lib/api.js
new file mode 100644
index 0000000..9999999
--- /dev/null
+++ b/frontend/lib/api.js
@@ -0,0 +1,45 @@
+// frontend/lib/api.js
+const API_BASE = process.env.NEXT_PUBLIC_API_BASE?.replace(/\/$/, "") || "";
+
+function getToken() {
+ if (typeof window === "undefined") return null;
+ return localStorage.getItem("dms.token") || sessionStorage.getItem("dms.token");
+}
+
+export async function apiFetch(path, options = {}) {
+ const token = getToken();
+ const headers = new Headers(options.headers || {});
+ headers.set("Accept", "application/json");
+ if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json");
+ if (token) headers.set("Authorization", `Bearer ${token}`);
+
+ const res = await fetch(`${API_BASE}${path}`, { ...options, headers, cache: "no-store" });
+
+ if (res.status === 401) {
+ const refresh =
+ localStorage.getItem("dms.refresh_token") || sessionStorage.getItem("dms.refresh_token");
+ if (refresh) {
+ const r = await fetch(`${API_BASE}/api/auth/refresh`, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${refresh}` },
+ });
+ if (r.ok) {
+ const { token: newToken } = await r.json();
+ const store = localStorage.getItem("dms.refresh_token") ? localStorage : sessionStorage;
+ store.setItem("dms.token", newToken);
+ const headers2 = new Headers(headers);
+ headers2.set("Authorization", `Bearer ${newToken}`);
+ return fetch(`${API_BASE}${path}`, { ...options, headers: headers2, cache: "no-store" });
+ }
+ }
+ }
+ return res;
+}
diff --git a/frontend/middleware.ts b/frontend/middleware.ts
index aaaaaaa..bbbbbbb 100644
--- a/frontend/middleware.ts
+++ b/frontend/middleware.ts
@@ -1,15 +1,14 @@
-import { NextResponse } from "next/server";
-import type { NextRequest } from "next/server";
-
-// เดิม: ตรวจคุกกี้แล้ว redirect /dashboard
-export function middleware(req: NextRequest) {
- // ... logic เดิมที่ใช้คุกกี้
- return NextResponse.next();
-}
-
-export const config = {
- matcher: ["/(protected/:path*)","/dashboard","/users/:path*","/api/:path*"],
-};
+import { NextResponse } from "next/server";
+// ✅ ไม่บล็อกเพจอีกต่อไป (Bearer อยู่ใน storage ฝั่ง client)
+export function middleware() {
+ return NextResponse.next();
+}
+// จำกัดให้ทำงานเฉพาะ /api ถ้าต้องการใช้ในอนาคต (ตอนนี้ผ่านเฉย ๆ)
+export const config = { matcher: ["/api/:path*"] };
diff --git a/frontend/app/(protected)/dashboard/page.jsx b/frontend/app/(protected)/dashboard/page.jsx
new file mode 100644
index 0000000..ccccccc
--- /dev/null
+++ b/frontend/app/(protected)/dashboard/page.jsx
@@ -0,0 +1,11 @@
+"use client";
+export default function DashboardPage() {
+ return (
+ <main className="p-6">
+ <h1 className="text-2xl font-semibold text-sky-800">Dashboard</h1>
+ <p className="text-slate-600 mt-2">
+ ยินดีต้อนรับสู่ DMS
+ </p>
+ </main>
+ );
+}

683
README.md
View File

@@ -1,6 +1,664 @@
# Document Management Sysytem (dms)
# 📝 0. Project Title: Document Management System (DMS) Web Application for Laem Chabang Port Development Project, Phase 3
## บทบาท; คุณคือ Programmer และ Document Engineer ที่เชี่ยวชาญ
## 0. Project
### 📌 0.1 Project Overview / Description
- ระบบ Document Management System (DMS) เป็นเว็บแอปพลิเคชันที่ออกแบบมาเพื่อจัดการเอกสารภายในโครงการอย่างมีประสิทธิภาพ
- โดยมีฟังก์ชันหลักในการอัปโหลด จัดเก็บ ค้นหา แชร์ และควบคุมสิทธิ์การเข้าถึงเอกสาร
- ระบบนี้จะช่วยลดการใช้เอกสารกระดาษ เพิ่มความปลอดภัยในการจัดเก็บข้อมูล
- เพิ่มความสะดวกในการทำงานร่วมกันระหว่างองกรณ์
### 🎯 0.2 Objectives
- พัฒนาระบบที่สามารถจัดการเอกสารได้อย่างเป็นระบบ
- ลดความซ้ำซ้อนในการจัดเก็บเอกสาร
- เพิ่มความปลอดภัยในการเข้าถึงและจัดการเอกสาร
- รองรับการทำงานร่วมกันแบบออนไลน์
### 📦 0.3 Scope of Work
ระบบจะครอบคลุมฟีเจอร์หลักดังนี้:
- การลงทะเบียนและเข้าสู่ระบบ ของผู้ใช้งาน
- การอัปโหลดและจัดเก็บเอกสารในรูปแบบต่าง ๆ (PDF, DOCX, XLSX ฯลฯ)
- การจัดหมวดหมู่และแท็กเอกสาร
- การค้นหาเอกสารด้วยคำสำคัญหรือฟิลเตอร์
- การกำหนดสิทธิ์การเข้าถึงเอกสาร (เช่น อ่านอย่างเดียว, แก้ไข, ลบ)
- การบันทึกประวัติการใช้งานเอกสาร (Audit Trail)
- การมอบหมายงานให้กับผู้เกี่ยวข้อง และแจ้งเตือนเมื่อมีการมอบหมายงาน
- การแจ้งเตือนเมื่อถึงกำหนดวันที่ต้องส่งเอกสารต่อให้ ผู้เกี่ยวข้องอื่นๆ
- การแจ้งเตือนเมื่อมีการเปลี่ยนแปลงเอกสาร
### 👥 0.4 Target Users
- พนักงานภายใน ขององค์กร
- พนักงานควบคุมเอกสาร (Document Control)/ ผู้ดูแลระบบขององค์กร (admin)
- ผู้จัดการฝ่ายเอกสาร ขององค์กร
- ผู้จัดการโครงการ ขององค์กร
- คณะกรรมการ ของโครงการ
- ผู้ดูแลระบบ IT ของโครงการ (superadmin)
### 📈 0.5 Expected Outcomes
- ลดเวลาในการค้นหาเอกสารลงอย่างน้อย 50%
- ลดเวลาในการจัดทำรายงานเอกสาร ประจำวัน, ประจำสัปดาห์, ประจำเดือน, ประจำปี และ รายงานเอกสารทั้งโครงการ
- ลดการใช้เอกสารกระดาษในองค์กร
- เพิ่มความปลอดภัยในการจัดเก็บข้อมูล
- รองรับการทำงานแบบ Remote Work
### 📘 0.6 Requirements Use Cases
#### 📘 Use Case: Upload Document
Actor: พนักงานควบคุมเอกสาร (Document Control)
Description: พนักงานควบคุมเอกสารสามารถอัปโหลดเอกสารเข้าสู่ระบบเพื่อจัดเก็บและใช้งานในภายหลัง
Preconditions: พนักงานควบคุมเอกสารต้องเข้าสู่ระบบก่อน
Main Flow:
พนักงานควบคุมเอกสารเลือกเมนู “อัปโหลดเอกสาร”
เลือกไฟล์จากเครื่องคอมพิวเตอร์
กรอกข้อมูลประกอบ เช่น ชื่อเอกสาร หมวดหมู่ แท็ก
กดปุ่ม “อัปโหลด”
ระบบบันทึกเอกสารและแสดงผลการอัปโหลดสำเร็จ
Postconditions: เอกสารถูกจัดเก็บในระบบและสามารถค้นหาได้
#### 📘 Use Case: Assign Users to Document
Actor: พนักงานควบคุมเอกสาร (Document Control)
Description: พนักงานควบคุมเอกสารสามารถ มอบหมายงานให้กับ Users
Preconditions: พนักงานควบคุมเอกสารต้องเข้าสู่ระบบก่อน, เอกสารต้องอัปโหลดเรียบร้อยแล้ว
Main Flow:
พนักงานควบคุมเอกสารเลือกเมนู “มอบหมายงาน”
เลือกเอกสารในระบบ
เลือก Users กำหนดวันสิ้นสุดงาน
กดปุ่ม “มอบหมายงาน”
ระบบบันทึกเอกสารและแสดงผลการมอบหมายงานสำเร็จ
Postconditions: งานที่มอยหมาย จัดเก็บในระบบและสามารถค้นหาได้
#### 📘 Use Case: Search Document
Actor: ผู้ใช้งานทั่วไป
Description: ผู้ใช้งานสามารถค้นหาเอกสารจากระบบด้วยคำสำคัญหรือฟิลเตอร์
Preconditions: ผู้ใช้งานต้องเข้าสู่ระบบ
Main Flow:
ผู้ใช้งานกรอกคำค้นหรือเลือกฟิลเตอร์ (หมวดหมู่, วันที่, ผู้สร้าง, ผู้ได้รับมอบหมายงาน, สถานะ, title, subject)
กดปุ่ม “ค้นหา”
ระบบแสดงรายการเอกสารที่ตรงกับเงื่อนไข
Postconditions: ผู้ใช้งานสามารถเปิดดูหรือดาวน์โหลดเอกสารที่ค้นพบได้
#### 📘 Use Case: Manage Access
Actor: ผู้ดูแลระบบโครงการ (superadmin) / ผู้ดูแลระบบขององค์กร (admin)
Description: ผู้ดูแลระบบสามารถกำหนดสิทธิ์การเข้าถึงเอกสารให้กับผู้ใช้งาน
Preconditions: ผู้ดูแลระบบต้องเข้าสู่ระบบ
Main Flow:
ผู้ดูแลระบบเลือกเอกสาร
กด “จัดการสิทธิ์”
เลือกผู้ใช้งานและกำหนดสิทธิ์ (อ่าน, แก้ไข, ลบ)
กด “บันทึก”
Postconditions: สิทธิ์การเข้าถึงเอกสารถูกปรับตามที่กำหนด
#### 📘 Use Case: View Document History
Actor: ผู้ใช้งานทั่วไป / ผู้ดูแลระบบ
Description: ผู้ใช้งานสามารถดูประวัติการใช้งานเอกสาร เช่น การแก้ไข การดาวน์โหลด
Preconditions: ผู้ใช้งานต้องมีสิทธิ์เข้าถึงเอกสาร
Main Flow:
ผู้ใช้งานเปิดเอกสาร
เลือก “ดูประวัติ”
ระบบแสดงรายการกิจกรรมที่เกี่ยวข้องกับเอกสาร
Postconditions: ผู้ใช้งานสามารถตรวจสอบการเปลี่ยนแปลงย้อนหลังได้
### 🔄 0.7 Workflow อัตโนมัติในระบบ DMS
✅ ประโยชน์ของ Workflow อัตโนมัติใน DMS
- ลดภาระงานซ้ำ ๆ ของผู้ใช้งาน
- เพิ่มความปลอดภัยและการควบคุมเอกสาร
- เพิ่มความเร็วในการดำเนินงาน
- ลดข้อผิดพลาดจากการทำงานด้วยมือ
#### 🧩 Workflow: 1. Document treat Workflow
กรณี: เมื่อมีการอัปโหลดเอกสารต้องได้รับการมอบหมายงานให้กับ พนักงานภายในองค์กรณ์
ขั้นตอนอัตโนมัติ:
1. ผู้ใช้งานอัปโหลดเอกสารและเลือก “มอบหมายงาน”
2. ระบบส่งแจ้งเตือนไปยังผู้ได้รับมอบหมายงาน
3. ผู้อนุมัติสามารถตรวจสอบและกด “ตรวจสอบแล้ว”
4. ระบบบันทึกสถานะเอกสารและ ส่งต่อ ไปยัง องกรณือื่น ตามลำดับ เมื่อได้ผลและจัดทำเอกสารตอบแล้ว จึงแจ้งผลกลับไปยังผู้ส่ง
#### 📥 Workflow: 2. Auto Tagging & Categorization
กรณี: เอกสารที่อัปโหลดมีชื่อหรือเนื้อหาที่ตรงกับหมวดหมู่ที่กำหนดไว้
ขั้นตอนอัตโนมัติ:
เมื่ออัปโหลดเอกสาร ระบบวิเคราะห์ชื่อไฟล์หรือเนื้อหา
ระบบกำหนดหมวดหมู่และแท็กให้โดยอัตโนมัติ เช่น “ใบเสนอราคา” → หมวด “การเงิน”
ผู้ใช้งานสามารถแก้ไขได้หากต้องการ
#### 🔐 Workflow: 3. Access Control Workflow
กรณี: เอกสารที่มีความลับสูงต้องจำกัดการเข้าถึง
ขั้นตอนอัตโนมัติ:
เมื่ออัปโหลดเอกสารที่มีคำว่า “ลับ” หรือ “Confidential”
ระบบกำหนดสิทธิ์เริ่มต้นให้เฉพาะผู้ใช้งานระดับผู้จัดการขึ้นไป
ระบบแจ้งเตือนผู้ดูแลระบบให้ตรวจสอบสิทธิ์เพิ่มเติม
#### 📤 Workflow: 4. Expiry & Archiving Workflow
กรณี: เอกสารที่มีอายุการใช้งาน เช่น สัญญา หรือใบอนุญาต
ขั้นตอนอัตโนมัติ:
เมื่ออัปโหลดเอกสาร ผู้ใช้งานระบุวันหมดอายุ
ระบบแจ้งเตือนก่อนหมดอายุล่วงหน้า เช่น 30 วัน
เมื่อถึงวันหมดอายุ ระบบย้ายเอกสารไปยังหมวด “Archive” โดยอัตโนมัติ
#### 📊 Workflow: 5. Audit Trail & Notification Workflow
กรณี: มีการแก้ไขหรือดาวน์โหลดเอกสารสำคัญ
ขั้นตอนอัตโนมัติ:
ทุกการกระทำกับเอกสาร (เปิด, แก้ไข, ลบ) จะถูกบันทึกใน Audit Log
หากเอกสารถูกแก้ไขโดยผู้ใช้งานที่ไม่ใช่เจ้าของ ระบบแจ้งเตือนเจ้าของเอกสารทันที
## 🛠️ 1. DMS Architecture Deep Dive (Backend + Frontend)
### 1.1 Executive Summary
- Reverse proxy (Nginx/NPM) เผยแพร่ Frontend (Next.js) และ Backend (Node.js/Express) ผ่าน HTTPS (HSTS)
- Backend เชื่อม MariaDB 10.11 (ข้อมูลหลัก DMS) และแยก n8n + Postgres 16 สำหรับ workflow
- RBAC/ABAC ถูกบังคับใช้งานใน middleware + มีชุด SQL (tables → triggers → procedures → views → seed)
- ไฟล์จริง (PDF/DWG) เก็บนอก webroot ที่ /share/dmsdata พร้อมมาตรฐานการตั้งชื่อ+โฟลเดอร์
- Dev/Prod แยกชัดเจนผ่าน Docker multistage + dockercompose + โฟลเดอร์ persist logs/config/certs
### 1.2 Runtime Topology & Trust Boundaries
```text
Internet Clients (Browser)
│ HTTPS 443 (HSTS) [QNAP mgmt = 8443]
┌─────────────────────────────────────────────────────┐
│ Reverse Proxy Layer │
│ ├─ Nginx (Alpine) or Nginx Proxy Manager (NPM) │
│ ├─ TLS (LE cert; SAN multisubdomain) │
│ └─ Routes: │
│ • /, /_next/* → Frontend (Next.js :3000) │
│ • /api/* → Backend (Express :3001) │
│ • /pma/* → phpMyAdmin │
│ • /n8n/* → n8n (Workflows) │
└─────────────────────────────────────────────────────┘
│ │
│ └──────────┐
▼ │
Frontend (Next.js) │
│ Cookie-based Auth (HttpOnly) │
▼ ▼
Backend (Node/Express ESM) ─────────► MariaDB 10.11
│ │
└────────────────────────────────────┘
Project data (.pdf/.dwg) @ /share/dms-data
n8n (workflows) ──► Postgres 16 (separate DB for automations)
```
==Trust Boundaries==
- Public zone: Internet ↔ Reverse proxy
- App zone: Reverse proxy ↔ FE/BE containers (internal Docker network)
- # Data zone: Backend ↔ Databases (MariaDB, Postgres) + /share/dms-data
### 1.3 Frontend: Next.js (ESM) / React.js
#### 1.3.1 Stack & Key libs
- Next.js (App Router), React, ESM
- Tailwind CSS, PostCSS, shadcn/ui (components.json)
- Fetch API (credentials include) → Cookie Auth (HttpOnly)
#### 1.3.2 Directory Layout
```text
/frontend/
├─ app/
│ ├─ login/
│ ├─ dashboard/
│ ├─ users/
│ ├─ correspondences/
│ ├─ health/
│ └─ layout.tsx / page.tsx (ตาม App Router)
├─ public/
├─ Dockerfile (multi-stage: dev/prod)
├─ package.json
├─ next.config.js
└─ ...
```
#### 1.3.3 Routing & Layouts
- Public /login, /health
- Protected: /dashboard, /users, /correspondences, ... (client-side guard)
- เก็บ middleware.ts (ของเดิม) เพื่อหลีกเลี่ยง regression; ใช้ clientguard + server action อย่างระมัดระวัง
#### 1.3.4 Auth Flow (Cookie-based)
1. ผู้ใช้ submit form /login → POST /api/auth/login (Backend)
2. Backend set HttpOnly cookie (JWT) + SameSite=Lax/Strict, Secure
3. หน้า protected เรียก GET /api/auth/me เพื่อตรวจสอบสถานะ
4. หาก 401 → redirect → /login
**CORS/Fetch**: เเปิด credentials: 'include' ทุกครั้ง, ตั้ง NEXT_PUBLIC_API_BASE เป็น origin ของ backend ผ่าน proxy (เช่น https://lcbp3.np-dms.work)
#### 1.3.5 UI/UX
- Seablue palette, sidebar พับได้, cardbased KPI
- ตารางข้อมูลเตรียมรองรับ serverside DataTables\*\*
- shadcn/ui: Button, Card, Badge, Tabs, Dropdown, Tooltip, Switch, etc.
#### 1.3.6 Config & ENV
- NEXT_PUBLIC_API_BAS (ex: https://lcbp3.np-dms.work)
- Build output แยก dev/prod; ระวัง EACCES บน QNAP → ใช้ user node + ปรับสิทธิ์โวลุ่ม .next/\*
#### 1.3.7 Error Handling & Observability (FE)
- Global error boundary (app router) + toast/alert patterns
- Network layer: แยก handler สำหรับ 401/403/500 + retry/backoff ที่จำเป็น
- Metrics (optional): webvitals, UX timing (เก็บฝั่ง n8n หรือ simple logging)
---
### 1.4 Backend Architecture (Node.js ESM / Express)
#### 1.4.1 Stack & Structure
- Node 20.x, ESM modules, Express\*\*
- mysql2/promise, jsonwebtoken, cookie-parser, cors, helmet, winston/morgan
```text
/backend/
├─ src/
│ ├─ index.js # bootstrap server, CORS, cookies, health
│ ├─ routes/
│ │ ├─ auth.js # /api/auth/* (login, me, logout)
│ │ ├─ users.js # /api/users/*
│ │ ├─ correspondences.js # /api/correspondences/*
│ │ ├─ drawings.js # /api/drawings/*
│ │ ├─ rfas.js # /api/rfas/*
│ │ └─ transmittals.js # /api/transmittals/*
│ ├─ middleware/
│ │ ├─ authGuard.js # verify JWT from cookie
│ │ ├─ requirePermission.js# RBAC/ABAC enforcement
│ │ ├─ errorHandler.js
│ │ └─ requestLogger.js
│ ├─ db/
│ │ ├─ pool.js # createPool, sane defaults
│ │ └─ models/ # query builders (User, Drawing, ...)
│ ├─ utils/
│ │ ├─ hash.js (bcrypt/argon2)
│ │ ├─ jwt.js
│ │ ├─ pagination.js
│ │ └─ responses.js
│ └─ config/
│ └─ index.js # env, constants
├─ Dockerfile
└─ package.json
```
#### 1.4.2 Request Lifecycle
1. helmet + cors (allow specific origin; credentials true)
2. cookie-parser, json limit (e.g., 2MB)
3. requestLogger → trace + response time
4. Route handler → authGuard (protected) → requirePermission (perroute) → Controller
5. Error bubbles → errorHandler (JSON shape, status map)
#### 1.4.3 Auth & RBAC/ABAC
- JWT ใน HttpOnly cookie; Claims: sub (user_id), roles, exp
- authGuard: ตรวจ token → แนบ req.user
- requirePermission: เช็ค permission ตามเส้นทาง/วิธี; แผนขยาย ABAC (เช่น project scope, owner, doc state)
- Roles/Permissions ถูก seed ใน SQL; มี view เมทริกซ์ เพื่อ debug (เช่น v_role_permission_matrix)
\*\*ตัวอย่าง pseudo requirePermission(permission)
```js
export const requirePermission = (perm) => async (req, res, next) => {
if (!req.user) return res.status(401).json({ error: "Unauthenticated" });
const ok = await checkPermission(req.user.user_id, perm, req.context);
if (!ok) return res.status(403).json({ error: "Forbidden" });
return next();
};
```
#### 1.4.4 Database Access & Pooling
- createPool({ connectionLimit: 10~25, queueLimit: 0, waitForConnections: true })
- ใช้ parameterized queries เสมอ; ปรับ sql_mode ที่จำเป็นใน my.cnf
#### 1.4.5 File Storage & Secure Download
- Root: /share/dmsdata
- โครงโฟลเดอร์: {module}/{yyyy}/{mm}/{entityId}/ + ชื่อไฟล์ตามมาตรฐาน (เช่น DRW-code-REV-rev.pdf)
- Endpoint download: ตรวจสิทธิ์ (RBAC/ABAC) → res.sendFile()/stream; ป้องกัน path traversal
- MIME allowlist + size limit + virus scan (optional; ภายหลัง)
#### 1.4.6 Health & Readiness
- GET /api/health → { ok: true }
- (optional) /api/ready ตรวจ DB ping + disk space (dmsdata)
#### 1.4.7 Config & ENV (BE)
- DB_HOST, DB_PORT, DB_USER, DB_PASS, DB_NAME
- JWT_SECRET, COOKIE_NAME, COOKIE_SAMESITE, COOKIE_SECURE
- CORS_ORIGIN, LOG_LEVEL, APP_BASE_URL
- FILE_ROOT=/share/dms-data
#### 1.4.8 Logging
- Access log (morgan) + App log (winston) → /share/Container/dms/logs/backend/
- รูปแบบ JSON (timestamp, level, msg, reqId) + daily rotation (logrotate/containerside)
### 1.5 Database (MariaDB 10.11)
#### 1.5.1 Schema Overview (ย่อ)
- RBAC core: users, roles, permissions, user_roles, role_permissions
- Domain: drawings, contracts, correspondences, rfas, transmittals, organizations, projects, ...
- Audit: audit_logs (แผนขยาย), deleted_at (soft delete, แผนงาน)
```text
[users]──<user_roles>──[roles]──<role_permissions>──[permissions]
└── activities/audit_logs (future expansion)
[drawings]──<mapping>──[contracts]
[rfas]──<links>──[drawings]
[correspondences] (internal/external flag)
```
#### 1.5.2 Init SQL Pipeline
1. 01\_\*\_deploy_table_rbac.sql — สร้างตารางหลักทั้งหมด + RBAC
2. 02\_\*\_triggers.sql — บังคับ data rules, autoaudit fields
3. 03\_\*\_procedures_handlers.sql — upsert/bulk handlers (เช่น sp_bulk_import_contract_dwg)
4. 04\_\*\_views.sql — รายงาน/เมทริกซ์สิทธิ์ (v_role_permission_matrix, etc.)
5. 05\_\*\_seed_data.sql — ค่าพื้นฐาน domain (project, categories, statuses)
6. 06\_\*\_seed_users.sql — บัญชีเริ่มต้น (superadmin, editors, viewers)
7. 07\_\*\_seed_contract_dwg.sql — ข้อมูลตัวอย่างแบบสัญญา
#### 1.5.3 Indexing & Performance
- Composite indexes ตามคอลัมน์ filter/sort (เช่น (project_id, updated_at DESC))
- Fulltext index (optional) สำหรับ advanced search
- Query plan review (EXPLAIN) + เพิ่ม covering index ตามรายงาน
#### 1.5.4 MySQL/MariaDB Config (my.cnf — แนวทาง)
```conf
[mysqld]
innodb_buffer_pool_size = 4G # ปรับตาม RAM/QNAP
innodb_log_file_size = 512M
innodb_flush_log_at_trx_commit = 1
max_connections = 200
sql_mode = STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
```
> ปรับค่าให้เหมาะกับ workload จริง + เฝ้าดู IO/CPU ของ QNAP
#### 1.5.5 Backup/Restore
- Logical backup: mysqldump --routines --triggers --single-transaction
- Physical (snapshot QNAP) + schedule ผ่าน n8n/cron
- เก็บสำเนา offNAS (encrypted)
### 1.6 Reverse Proxy & TLS
#### 1.6.1 Nginx (Alpine) — ตัวอย่าง server block
> สำคัญ: บนสภาพแวดล้อมนี้ ให้ใช้คนละบรรทัด:
> listen 443 ssl;
> http2 on;
> หลีกเลี่ยง listen 443 ssl http2;
```conf
server {
listen 80;
server_name lcbp3.np-dms.work;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
http2 on;
server_name lcbp3.np-dms.work;
ssl_certificate /etc/nginx/certs/fullchain.pem;
ssl_certificate_key /etc/nginx/certs/privkey.pem;
add_header Strict-Transport-Security "max-age=63072000; preload" always;
# Frontend
location / {
proxy_pass http://frontend:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Next.js static
location /_next/ {
proxy_pass http://frontend:3000;
}
# Backend API
location /api/ {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://backend:3001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
}
# phpMyAdmin (sub-path)
location /pma/ {
proxy_pass http://phpmyadmin:80/;
}
# n8n
location /n8n/ {
proxy_pass http://n8n:5678/;
}
}
```
#### 1.6.2 Nginx Proxy Manager (NPM) — Tips
- ระวังอย่าใส่ proxy_http_version ซ้ำซ้อน (duplicate directive) ใน Advanced
- ถ้าต้องแก้ไฟล์ด้านใน NPM → ระวังไฟล์ใน /data/nginx/proxy_host/\*.conf
- จัดการ certificate / SAN หลาย subdomain ใน UI แต่ mainten ดีเรื่อง symlink/renew
#### 1.6.3 TLS & Certificates
- Lets Encrypt (HTTP01 webroot/standalone) + HSTS
- QNAP mgmt เปลี่ยนเป็น 8443 → พอร์ต 443 public ว่างสำหรับ Nginx/NPM
### 1.7 Docker Compose Topology
#### 1.7.1 Services (สรุป)
- frontend (Next.js) :3000
- backend (Express) :3001
- mariadb (10.11) :3306 (internal)
- phpmyadmin :80 (internal)
- nginx or npm :80/443 (published)
- n8n :5678 (internal)
- postgres_n8n (16-alpine)
- pgadmin4
#### 1.7.2 Volumes & Paths
```text
/share/Container/dms/
├─ mariadb/data
├─ mariadb/init/*.sql
├─ backend/ (code)
├─ frontend/ (code)
├─ phpmyadmin/{sessions,tmp,config.user.inc.php}
├─ nginx/{nginx.conf,dms.conf,certs/}
├─ n8n, n8n-postgres, n8n-cache
└─ logs/{backend,frontend,nginx,pgadmin,phpmyadmin,postgres_n8n}
/share/dms-data (pdf/dwg storage)
```
#### 1.7.3 Healthchecks (suggested)
- backend:
```sh
curl http://localhost:3001/api/health
```
- frontend: curl /health (simple JSON)
- mariadb: mysqladmin ping with credentials
- nginx: nginx -t at startup
#### 1.7.4 Security Hardening
- รัน container ด้วย user nonroot (user: node สำหรับ FE/BE)
- จำกัด capabilities; readonly FS (ยกเว้นโวลุ่มจำเป็น)
- เฉพาะ backend เมานต์ /share/dms-data
### 1.8 Observability, Ops, and Troubleshooting
#### 1.8.1 Logs
- Frontend → /logs/frontend/\*
- Backend → /logs/backend/\* (app/access/error)
- Nginx/NPM → /logs/nginx/\*
- MariaDB → default datadir log + slow query (เปิดใน my.cnf หากต้องการ)
#### 1.8.2 Common Issues & Playbooks
- 401 Unauthenticated: ตรวจ authGuard → JWT cookie มี/หมดอายุ → เวลา server/FE sync → CORS credentials: true
- EACCES Next.js: สิทธิ์ .next/\* + run as`node, โวลุ่ม map ถูก user:group
- NPM duplicate directive: ลบซ้ำ proxy_http_version ใน Advanced / ตรวจ proxy_host/\*.conf
- LE cert path/symlink: ตรวจ /etc/letsencrypt/live/npm-\* symlink ชี้ถูก
- DB field not found: ตรวจ schema vs code (migration/init SQL) → sync ให้ตรง
#### 1.8.3 Performance Guides
- Backend: keepalive, gzip/deflate at proxy, pool 1025, paginate, avoid N+1
- Frontend: prefetch critical routes, cache static, image optimization
- DB: เพิ่ม index จุด filter, analyze query (EXPLAIN), ปรับ buffer pool
### 1.9 Security & Compliance
- HTTPS only + HSTS (preload)
- CORS: allow list เฉพาะ FE origin; Access-Control-Allow-Credentials: true
- Cookie: HttpOnly, Secure, SameSite=Lax/Strict
- Input Validation: celebrate/zod (optional) + sanitize
- Rate limiting: per IP/route (optional)
- AuditLog: วางแผนเพิ่ม ครอบคลุม CRUD + mapping (actor, action, entity, before/after)
- Backups: DB + /share/dms-data + config (encrypted offNAS)
### 1.10 Backlog → Architecture Mapping
1. RBAC Enforcement ครบ → เติม requirePermission ทุก route + test matrix ผ่าน view
2. AuditLog ครบ CRUD/Mapping → trigger + table audit_logs + BE hook
3. Upload/Download จริงของ Drawing Revisions → BE endpoints + virus scan (optional)
4. Dashboard KPI → BE summary endpoints + FE cards/charts
5. Serverside DataTables → paging/sort/filter + indexesรองรับ
6. รายงาน Export CSV/Excel/PDF → BE export endpoints + FE buttons
7. Soft delete (deleted_at) → BE filter default scope + restore endpoint
8. Validation เข้ม → celebrate/zod schema + consistent error shape
9. Indexing/Perf → slow query log + EXPLAIN review
10. Job/Cron Deadline Alerts → n8n schedule + SMTP
### 1.11 Port & ENV Matrix (Quick Ref)
| Component | Ports | Key ENV |
| Nginx/NPM | 80/443 (public) | SSL paths, HSTS |
| Frontend | 3000 (internal) | NEXT*PUBLIC_API_BASE |
| Backend | 3001 (internal) | DB*\*, JWT*SECRET, CORS_ORIGIN, FILE_ROOT |
| MariaDB | 3306 (internal) | MY_CNF, credentials |
| n8n | 5678 (internal) | N8N*, webhook URL under /n8n/ |
| Postgres | 5432 (internal) | n8n DB |
QNAP mgmt: 8443 (already moved)
### 1.12 Sample Snippets
#### 1.12.1 Backend CORS (credentials)
```js
app.use(
cors({
origin: ["https://lcbp3.np-dms.work"],
credentials: true,
})
);
```
#### 1.12.2 Secure Download (guarded)
```js
router.get(
"/files/:module/:id/:filename",
authGuard,
requirePermission("file.read"),
async (req, res) => {
const { module, id, filename } = req.params;
// 1) ABAC: verify user can access this module/entity
const ok = await canReadFile(req.user.user_id, module, id);
if (!ok) return res.status(403).json({ error: "Forbidden" });
const abs = path.join(FILE_ROOT, module, id, filename);
if (!abs.startsWith(FILE_ROOT))
return res.status(400).json({ error: "Bad path" });
return res.sendFile(abs);
}
);
```
#### 1.12.3 Healthcheck
```js
router.get("/health", (req, res) => res.json({ ok: true }));
```
### 13 Deployment Workflow (Suggested)
1. Git (Gitea) branch strategy feature/\* → PR → main
2. Build images (dev/prod) via Dockerfile multistage; pin Node/MariaDB versions
3. docker compose up -d --build จาก /share/Container/dms
4. Validate: /health, /api/health, login roundtrip
5. Monitor logs + baseline perf; run SQL smoke tests (views/triggers/procs)
### 14 Appendix
- Naming conventions: snake_case DB, camelCase JS
- Timezones: store UTC in DB; display in app TZ (+07:00)
- Character set: UTF8 (utf8mb4_unicode_ci)
- Large file policy: size limit (e.g., 50200MB), allowlist extensions
- Retention: archive strategy for old revisions (optional)
## บทบาท: คุณคือ Programmer และ Document Engineer ที่เชี่ยวชาญ
1. การพัฒนาเว็บแอป (Web Application Development)
2. Configuration of Container Station on QNAP
@@ -19,12 +677,11 @@
15. ภาษา SQL
16. RBAC
## 2. ระบบที่ใช้;
## 2. ระบบที่ใช้
## Server
- ใช้ Container Station เป็น SERVER บน QNAP (Model: TS-473A, RAM: 32GB, CPU: AMD Ryzen V1500B 4 cores 8 threads)
**_ เปลี่ยน port 443 ของ QNAP เป็น 8443 แล้ว _**
- ใช้ Container Station เป็น SERVER บน QNAP (Model: TS-473A, RAM: 32GB, CPU: AMD Ryzen V1500B 4 cores 8 threads) **เปลี่ยน port 443 ของ QNAP เป็น 8443 แล้ว**
## การพัฒนาโครงการ
@@ -92,22 +749,6 @@
└─ postgres_n8n/
/share/dms-data # เก็บข้อมมูล .pdf, .dwg แยกตาม correspondences, documents
# ภาษา: ใช้ภาษาไทยในการโต้ตอบ ยกเว้น ศัพท์เทคนิคหรือศัพท์เฉพาะทาง
# ไฟล์ที่ ีupload
- Dockerfile ของ backend
- package.json ของ backend
- docker-compose.yml ชอง Container station
- nginx.conf, dms.conf ของ nginx
- dms_v0_5_0_data_v5_1_sql.zip ประกอบด้วย
- 01_dms_data_v5_1_deploy_table_rbac.sql # Create all data table & RBAC table here!
- 02_dms_data_v5_1_triggers.sql # Create all triggers here!
- 03_dms_data_v5_1_procedures_handlers.sql # Create all procedures here!
- 04_dms_data_v5_1_views.sql # Create all views here!
- 05 dms_data_v5_1_seeก_data.sql # Seed nescesary data here!
- 06_dms_data_v5_1_seed_users.sql # Seed users data here!
# งานที่ต้องการ:
- ไม่ใช้ .env เด็ดขาด Container Station ไม่รองรับ และ docker-compose.yml ได้ทดสอบ รันบน Container station มาแล้ว

96
b.env
View File

@@ -1,96 +0,0 @@
TZ=Asia/Bangkok
GENERIC_TIMEZONE=Asia/Bangkok
PUBLIC_DOMAIN=np-dms.work
PUBLIC_FRONTEND_URL=https://lcbp3.np-dms.work
PUBLIC_BACKEND_URL=https://lcbp3.np-dms.work/api
PUBLIC_N8N_URL=https://lcbp3.np-dms.work/n8n
MARIADB_HOST=mariadb
MARIADB_PORT=3306
MARIADB_ROOT_PASSWORD=Center#2025
MARIADB_DATABASE=dms
MARIADB_USER=center
MARIADB_PASSWORD=Center#2025
# MARIADB_HOST_PORT=7307
# BACKEND_HOST_PORT=7001
# FRONTEND_HOST_PORT=7000
# PHPMYADMIN_HOST_PORT=7070
NGINX_HTTP_HOST_PORT=80
NGINX_HTTPS_HOST_PORT=443
N# 8N_HOST_PORT=7081
NODE_ENV=production
JWT_SECRET=8b0df02e4aee9f9f79a4f2d8ba77b0b82c1ee3446b68cb0bae94ab54d60f8d9e
JWT_EXPIRES_IN=12h
PASSWORD_SALT_ROUNDS=10
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX=200
CORS_ORIGINS=https://lcbp3.np-dms.work,http://localhost:7000,http://192.168.20.248:7000
NEXT_TELEMETRY_DISABLED=1
PMA_HOST=mariadb
PMA_PORT=3306
PMA_ABSOLUTE_URI=https://lcbp3.np-dms.work.com/pma/
UPLOAD_LIMIT=256M
MEMORY_LIMIT=512M
NGINX_SERVER_NAME=np-dms.work.com
NGINX_PROXY_READ_TIMEOUT=300
# QNAP_SSL_CERT_HOST=/etc/qnap-ssl/combine
# QNAP_SSL_KEY_HOST=/etc/qnap-ssl/key
# NGINX_SSL_CERT=/etc/nginx/certs/fullchain.pem
# NGINX_SSL_KEY=/etc/nginx/certs/privkey.pem
# NGINX_SSL_KEY=/etc/nginx/certs
QNAP_SSL_CERT=/etc/config/QcloudSSLCertificate/cert
NGINX_SSL_CERT=/etc/qnap-ssl
N8N_BASIC_AUTH_ACTIVE=true
N8N_BASIC_AUTH_USER=n8n
N8N_BASIC_AUTH_PASSWORD=Center#2025
N8N_PATH=/n8n/
N8N_PROTOCOL=https
N8N_PROXY_HOPS=1
N8N_SECURE_COOKIE=true
N8N_HOST=dcs.mycloudnas.com
N8N_PORT=5678
N8N_EDITOR_BASE_URL=https://lcbp3.np-dms.work/n8n/
WEBHOOK_URL=https://lcbp3.np-dms.work/n8n/
N8N_ENCRYPTION_KEY=9AAIB7Da9DW1qAhJE5/Bz4SnbQjeAngI
# --- n8n → MariaDB ---
# DB_TYPE=mysqldb
# DB_MYSQLDB_HOST=mariadb
# DB_MYSQLDB_PORT=3306
# DB_MYSQLDB_DATABASE=n8n
# DB_MYSQLDB_USER=n8n_user
# DB_MYSQLDB_PASSWORD=Center#2025 # เปลี่ยนเป็นรหัสแข็งแรงของคุณ
# ==== n8n → PostgreSQL (แทน MariaDB/MySQL) ====
DB_TYPE=postgresdb
DB_POSTGRESDB_HOST=postgres_n8n
DB_POSTGRESDB_PORT=5432
DB_POSTGRESDB_DATABASE=n8n
DB_POSTGRESDB_USER=n8n
DB_POSTGRESDB_PASSWORD=Center#2025
# path โฟลเดอร์ n8n เดิม (มี database.sqlite)
# HOST_N8N=/share/Container/dms/n8n
HOST_BASE=/share/Container/dms
HOST_MARIADB=${HOST_BASE}/mariadb
HOST_BACKEND=${HOST_BASE}/backend
HOST_FRONTEND=${HOST_BASE}/frontend
HOST_PHPMYADMIN=${HOST_BASE}/phpmyadmin
HOST_NGINX=${HOST_BASE}/nginx
HOST_LOGS=${HOST_BASE}/logs
HOST_SCRIPTS=${HOST_BASE}/scripts
HOST_N8N=/share/Container/dms/n8n
HOST_N8N_CACHE=${HOST_BASE}/n8n-cache
HOST_DATA=/share/dms-data
# BACKEND_LOG_DIR=${HOST_LOGS}/backend
BACKEND_LOG_DIR=/app/logs

View File

@@ -0,0 +1,29 @@
# Backend build
## วิธีสร้าง package-lock.json ด้วย Docker
### 1. เช็ค uid:gid ของโฟลเดอร์โปรเจกต์บน QNAP
stat -c "%u:%g" .
### 2. ใช้ค่าที่ได้มาแทน UID:GID
```bash
docker run --rm \
-v "/share/Container/dms/frontend:/app" -w /app \
--user UID:GID -e HOME=/tmp \
node:20-alpine sh -lc 'mkdir -p /tmp && npm install --package-lock-only --ignore-scripts'
```
สร้าง package-lock.json โดย ไม่ติดตั้ง node_modules
--user $(id -u):$(id -g) ทำให้ไฟล์ที่ได้เป็นเจ้าของโดยยูสเซอร์ปัจจุบัน (กันปัญหา root-owned)
## ขั้นตอน Build บน QNAP
docker compose -f docker-backend-build.yml build --no-cache 2>&1 | tee backend_build.log
## สำหรับ build local
cd backend
docker build -t dms-backend:dev --target dev .

Binary file not shown.

View File

@@ -1,8 +1,11 @@
.git
.vscode
.backup
node_modules
logs
*.log
Dockerfile*
Dockerfile*.*
*.yml
README*.md
coverage
tmp

15
backend/.eslintrc.json Normal file
View File

@@ -0,0 +1,15 @@
{
"env": {
"node": true,
"es2021": true,
"jest": true
},
"extends": ["eslint:recommended", "plugin:prettier/recommended"],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {
"prettier/prettier": "warn"
}
}

3
backend/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
# Ignore Nginx Proxy Manager data
/npm/

7
backend/.prettierrc.json Normal file
View File

@@ -0,0 +1,7 @@
{
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "always",
"printWidth": 80
}

View File

@@ -66,4 +66,5 @@ USER node
EXPOSE 3001
HEALTHCHECK --interval=30s --timeout=5s --retries=10 \
CMD wget -qO- http://127.0.0.1:3001/health || exit 1
CMD ["node","src/index.js"]
CMD ["node","src/index.js"]

77
backend/docker-compose.yml Executable file
View File

@@ -0,0 +1,77 @@
# File: backend/docker-compose.yml
# DMS Container v0_8_0 แยก service/ lcbp3-backend
x-restart: &restart_policy
restart: unless-stopped
x-logging: &default_logging
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "5"
volumes:
backend_node_modules:
services:
backend:
<<: [*restart_policy, *default_logging]
image: dms-backend:dev
# pull_policy: never # <-- FINAL FIX ADDED HERE
container_name: dms_backend
stdin_open: true
tty: true
#user: "node"
user: "1000:1000"
working_dir: /app
deploy:
resources:
limits:
cpus: "2.0"
memory: 1G
reservations:
cpus: "0.25"
memory: 256M
environment:
TZ: "Asia/Bangkok"
CHOKIDAR_USEPOLLING: "1"
CHOKIDAR_INTERVAL: "300"
WATCHPACK_POLLING: "true"
# NODE_ENV: "production"
NODE_ENV: "development"
PORT: "3001"
DB_HOST: "mariadb"
DB_PORT: "3306"
DB_USER: "center"
DB_PASSWORD: "Center#2025"
DB_NAME: "dms"
JWT_SECRET: "9a6d8705a6695ab9bae4ca1cd46c72a6379aa72404b96e2c5b59af881bb55c639dd583afdce5a885c68e188da55ce6dbc1fb4aa9cd4055ceb51507e56204e4ca"
JWT_ACCESS_SECRET: "9a6d8705a6695ab9bae4ca1cd46c72a6379aa72404b96e2c5b59af881bb55c639dd583afdce5a885c68e188da55ce6dbc1fb4aa9cd4055ceb51507e56204e4ca"
JWT_REFRESH_SECRET: "743e798bb10d6aba168bf68fc3cf8eff103c18bd34f1957a3906dc87987c0df139ab72498f2fe20d6c4c580f044ccba7d7bfa4393ee6035b73ba038f28d7480c"
ACCESS_TTL_MS: "900000"
REFRESH_TTL_MS: "604800000"
JWT_EXPIRES_IN: "12h"
PASSWORD_SALT_ROUNDS: "10"
FRONTEND_ORIGIN: "https://lcbp3.np-dms.work"
CORS_ORIGINS: "https://backend.np-dms.work,http://localhost:3000,http://127.0.0.1:3000,https://lcbp3.np-dms.work"
COOKIE_DOMAIN: ".np-dms.work"
RATE_LIMIT_WINDOW_MS: "900000"
RATE_LIMIT_MAX: "200"
BACKEND_LOG_DIR: "/app/logs"
networks:
lcbp3: {}
volumes:
- "/share/Container/dms/backend/src:/app/src:rw"
# - "/share/Container/dms/backend/package.json:/app/package.json"
# - "/share/Container/dms/backend/package-lock.json:/app/package-lock.json"
- "/share/dms-data:/share/dms-data:rw"
- "/share/Container/dms/logs/backend:/app/logs:rw"
# - "/share/Container/dms/backend/node_modules:/app/node_modules"
- "backend_node_modules:/app/node_modules"
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3001/health"]
interval: 10s
timeout: 5s
retries: 30
networks:
lcbp3:
external: true

6069
backend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "dms-backend",
"version": "0.6.0",
"version": "0.8.0",
"private": true,
"type": "module",
"main": "src/index.js",
@@ -11,7 +11,12 @@
"dev": "nodemon --watch src src/index.js",
"dev:desktop": "node --watch src/index.js",
"start": "node src/index.js",
"lint": "echo 'lint placeholder'",
"lint": "eslint . --ext .js",
"lint:fix": "eslint . --ext .js --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"test:watch:coverage": "jest --watch --coverage",
"health": "node -e \"fetch('http://localhost:'+ (process.env.BACKEND_PORT||3001) +'/health').then(r=>r.text()).then(console.log).catch(e=>{console.error(e);process.exit(1)})\"",
"postinstall": "node -e \"console.log('Installed dms-backend %s','0.6.0')\""
},
@@ -33,6 +38,12 @@
"winston": "^3.13.0"
},
"devDependencies": {
"nodemon": "^3.1.10"
"nodemon": "^3.1.10",
"eslint": "^8.56.0",
"prettier": "^3.1.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"jest": "^29.7.0",
"supertest": "^6.3.4"
}
}

View File

@@ -1,25 +0,0 @@
{
"name": "dms-backend",
"version": "0.5.0",
"private": true,
"type": "module",
"scripts": {
"dev": "node --env-file=../.env src/index.js",
"start": "node src/index.js",
"health": "node -e \"fetch('http://localhost:'+ (process.env.BACKEND_PORT||3001) +'/health').then(r=>r.text()).then(console.log).catch(e=>{console.error(e);process.exit(1)})\""
},
"dependencies": {
"bcrypt": "5.1.1",
"cors": "2.8.5",
"dotenv": "16.4.5",
"express": "4.19.2",
"express-rate-limit": "7.4.0",
"helmet": "7.1.0",
"jsonwebtoken": "9.0.2",
"mariadb": "3.3.1",
"morgan": "1.10.0",
"sequelize": "6.37.3"
}
}

View File

@@ -1,38 +0,0 @@
{
"name": "dms-backend",
"version": "0.6.0",
"private": true,
"type": "module",
"main": "src/index.js",
"engines": {
"node": ">=20.0.0"
},
"scripts": {
"dev": "nodemon --watch src src/index.js",
"start": "node src/index.js",
"lint": "echo 'lint placeholder'",
"health": "node -e \"fetch('http://localhost:'+ (process.env.BACKEND_PORT||3001) +'/health').then(r=>r.text()).then(console.log).catch(e=>{console.error(e);process.exit(1)})\"",
"postinstall": "node -e \"console.log('Installed dms-backend %s','0.6.0')\""
},
"dependencies": {
"bcrypt": "5.1.1",
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.7",
"cors": "2.8.5",
"dotenv": "16.4.5",
"express": "^4.21.2",
"express-rate-limit": "7.4.0",
"helmet": "7.1.0",
"jsonwebtoken": "9.0.2",
"mariadb": "3.3.1",
"morgan": "^1.10.1",
"multer": "^2.0.2",
"mysql2": "^3.11.0",
"sequelize": "6.37.3",
"winston": "^3.13.0"
},
"devDependencies": {
"nodemon": "^3.1.10"
}
}

56
backend/src/db/sequelize.js Normal file → Executable file
View File

@@ -20,76 +20,52 @@ export const sequelize = new Sequelize(
}
);
// --- 1. ประกาศตัวแปรสำหรับ Export Model ทั้งหมด ---
export let User = null;
export let Role = null;
export let Permission = null;
export let UserRole = null;
export let RolePermission = null;
export let Project = null; // <-- เพิ่มเข้ามา
export let UserProjectRole = null; // <-- เพิ่มเข้ามา
if (process.env.ENABLE_SEQUELIZE === "1") {
// --- 2. โหลดโมเดลทั้งหมดแบบ on-demand ---
// โหลดโมเดลแบบ on-demand เพื่อลดความเสี่ยง runtime หากไฟล์โมเดลไม่มี
const mdlUser = await import("./models/User.js").catch(() => null);
const mdlRole = await import("./models/Role.js").catch(() => null);
const mdlPerm = await import("./models/Permission.js").catch(() => null);
const mdlUR = await import("./models/UserRole.js").catch(() => null);
const mdlRP = await import("./models/RolePermission.js").catch(() => null);
const mdlProj = await import("./models/Project.js").catch(() => null); // <-- เพิ่มเข้ามา
const mdlUPR = await import("./models/UserProjectRole.js").catch(() => null); // <-- เพิ่มเข้ามา
// --- 3. Initialize Model ทั้งหมด ---
if (mdlUser?.default) User = mdlUser.default(sequelize);
if (mdlRole?.default) Role = mdlRole.default(sequelize);
if (mdlPerm?.default) Permission = mdlPerm.default(sequelize);
if (mdlUR?.default) UserRole = mdlUR.default(sequelize);
if (mdlRP?.default) RolePermission = mdlRP.default(sequelize);
if (mdlProj?.default) Project = mdlProj.default(sequelize); // <-- เพิ่มเข้ามา
if (mdlUPR?.default) UserProjectRole = mdlUPR.default(sequelize); // <-- เพิ่มเข้ามา
// --- 4. สร้างความสัมพันธ์ (Associations) ทั้งหมด ---
if (User && Role && Permission && UserRole && RolePermission) {
// ความสัมพันธ์ระดับระบบ (System-level)
User.belongsToMany(Role, { through: UserRole, foreignKey: "user_id" });
Role.belongsToMany(User, { through: UserRole, foreignKey: "role_id" });
User.belongsToMany(Role, {
through: UserRole,
foreignKey: "user_id",
otherKey: "role_id",
});
Role.belongsToMany(User, {
through: UserRole,
foreignKey: "role_id",
otherKey: "user_id",
});
Role.belongsToMany(Permission, {
through: RolePermission,
foreignKey: "role_id",
otherKey: "permission_id",
});
Permission.belongsToMany(Role, {
through: RolePermission,
foreignKey: "permission_id",
otherKey: "role_id",
});
}
// ความสัมพันธ์ระดับโปรเจกต์ (Project-level) - ส่วนที่เพิ่มเข้ามา
if (User && Project && Role && UserProjectRole) {
// ทำให้ UserProjectRole เป็นตัวกลางเชื่อม 3 ตาราง
UserProjectRole.belongsTo(User, { foreignKey: "user_id" });
UserProjectRole.belongsTo(Project, { foreignKey: "project_id" });
UserProjectRole.belongsTo(Role, { foreignKey: "role_id" });
// ทำให้สามารถ include ข้อมูลที่เกี่ยวข้องได้ง่ายขึ้น
User.hasMany(UserProjectRole, { foreignKey: "user_id" });
Project.hasMany(UserProjectRole, { foreignKey: "project_id" });
Role.hasMany(UserProjectRole, { foreignKey: "role_id" });
}
}
/**
* ฟังก์ชันสำหรับทดสอบการเชื่อมต่อ Sequelize
*/
export async function dbReady() {
if (process.env.ENABLE_SEQUELIZE !== "1") {
console.log("Sequelize is disabled.");
return Promise.resolve();
}
try {
await sequelize.authenticate();
console.log("Sequelize connection has been established successfully.");
} catch (error) {
console.error("Unable to connect to the database via Sequelize:", error);
return Promise.reject(error);
}
// โหมดเบา ๆ: แค่ทดสอบเชื่อมต่อ
await sequelize.authenticate();
}

View File

@@ -1,8 +1,8 @@
// FILE: backend/src/index.js (ESM) ไฟล์ฉบับ “Bearer-only”
// FILE: src/index.js (ESM)
import fs from "node:fs";
import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser"; // added
import sql from "./db/index.js";
import healthRouter from "./routes/health.js";
@@ -10,9 +10,6 @@ import { authJwt } from "./middleware/authJwt.js";
import { loadPrincipalMw } from "./middleware/loadPrincipal.js";
// ROUTES
import usersRoutes from "./routes/users.js";
import rbacAdminRoutes from "./routes/rbac_admin.js";
import dashboardRoutes from "./routes/dashboard.js";
import authRoutes from "./routes/auth.js";
import lookupRoutes from "./routes/lookup.js";
import organizationsRoutes from "./routes/organizations.js";
@@ -26,6 +23,7 @@ import contractDwgRoutes from "./routes/contract_dwg.js";
import categoriesRoutes from "./routes/categories.js";
import volumesRoutes from "./routes/volumes.js";
import uploadsRoutes from "./routes/uploads.js";
import usersRoutes from "./routes/users.js";
import permissionsRoutes from "./routes/permissions.js";
const PORT = Number(process.env.PORT || 3001);
@@ -39,9 +37,7 @@ const ALLOW_ORIGINS = [
"http://127.0.0.1:3000",
FRONTEND_ORIGIN,
...(process.env.CORS_ALLOWLIST
? process.env.CORS_ALLOWLIST.split(",")
.map((x) => x.trim())
.filter(Boolean)
? process.env.CORS_ALLOWLIST.split(",").map((x) => x.trim()).filter(Boolean)
: []),
].filter(Boolean);
@@ -78,10 +74,6 @@ app.use(
exposedHeaders: ["Content-Disposition", "Content-Length"],
})
);
// parse cookies สำหรับ access_token / refresh_token
app.use(cookieParser()); // added
app.options(
"*",
cors({
@@ -113,12 +105,8 @@ app.get("/health", async (_req, res) => {
});
app.get("/livez", (_req, res) => res.send("ok"));
app.get("/readyz", async (_req, res) => {
try {
await sql.query("SELECT 1");
res.send("ready");
} catch {
res.status(500).send("not-ready");
}
try { await sql.query("SELECT 1"); res.send("ready"); }
catch { res.status(500).send("not-ready"); }
});
app.get("/info", (_req, res) =>
res.json({
@@ -150,8 +138,6 @@ app.use("/api/volumes", volumesRoutes);
app.use("/api/uploads", uploadsRoutes);
app.use("/api/users", usersRoutes);
app.use("/api/permissions", permissionsRoutes);
app.use("/api/rbac", rbacAdminRoutes);
app.use("/api/dashboard", dashboardRoutes);
// 404 / error
app.use((req, res) =>
@@ -173,9 +159,7 @@ async function shutdown(signal) {
try {
console.log(`[SHUTDOWN] ${signal} received`);
await new Promise((resolve) => server.close(resolve));
try {
await sql.end();
} catch {}
try { await sql.end(); } catch {}
console.log("[SHUTDOWN] complete");
process.exit(0);
} catch (e) {

View File

@@ -3,118 +3,41 @@
// - Project-scoped access control base on user_project_roles + permissions
// - Requires req.user.roles and req.user.permissions to be populated (e.g. via auth.js with enrichment)
// - Uses UserProjectRole model to check project membership
// Helper ABAC เสริมบางเคส (ถ้าต้องการฟิลเตอร์/บังคับ project_id ตรง ๆ)
// หมายเหตุ: โดยหลักแล้วคุณควรใช้ requirePerm() ที่บังคับ ABAC อัตโนมัติจาก permissions.scope_level
import { sequelize } from "../db/sequelize.js";
import UPRModel from "../db/models/UserProjectRole.js";
/**
* ดึง project_id ที่ผู้ใช้เข้าถึงได้ (จาก user_project_roles)
*/
export async function getUserProjectIds(user_id) {
const UPR = UPRModel(sequelize);
const rows = await UPR.findAll({ where: { user_id } });
return [...new Set(rows.map((r) => r.project_id))];
}
/**
* projectScopedView(moduleName) -> middleware
* - ต้องมี permission '<module>:view' หรือ
* - เป็นสมาชิกของโปรเจ็กต์ (ผ่าน user_project_roles)
* Behavior:
* - ถ้า query ไม่มี project_id และผู้ใช้ไม่ใช่ Admin:
* จำกัดผลลัพธ์ให้เฉพาะโปรเจ็กต์ที่ผู้ใช้เป็นสมาชิก
* - ถ้ามี project_id: บังคับตรวจสิทธิ์การเป็นสมาชิกของโปรเจ็กต์นั้น (เว้นแต่เป็น Admin)
*/
export function projectScopedView(moduleName) {
export function projectScopedViewFallback(moduleName) {
// ใช้ในเคส legacy เท่านั้น
return async (req, res, next) => {
const roles = req.user?.roles || [];
const isAdmin = roles.includes("Admin");
const permName = `${moduleName}:view`;
const hasViewPerm = (req.user?.permissions || []).includes(permName);
const p = req.principal;
if (!p) return res.status(401).json({ error: "Unauthenticated" });
// Admin ผ่านได้เสมอ
if (isAdmin) return next();
const hasViewPerm = p.can?.(`${moduleName}.view`) || p.permissions?.has?.(`${moduleName}.view`);
if (p.is_superadmin) return next();
const qProjectId = req.query?.project_id
? Number(req.query.project_id)
: null;
const memberProjects = await getUserProjectIds(req.user?.user_id);
const qProjectId = req.query?.project_id ? Number(req.query.project_id) : null;
if (qProjectId) {
// ต้องเป็นสมาชิกโปรเจ็กต์นั้น หรือมี perm view
if (hasViewPerm || memberProjects.includes(qProjectId)) return next();
return res
.status(403)
.json({ error: "Forbidden: not a member of project" });
if (hasViewPerm || p.inProject(qProjectId)) return next();
return res.status(403).json({ error: "FORBIDDEN_PROJECT" });
} else {
// ไม่มี project_id: ถ้ามี perm view → อนุญาตทั้งหมด
// ถ้าไม่มี perm view → จำกัดด้วยรายการโปรเจ็กต์ที่เป็นสมาชิก (บันทึกไว้ใน req.abac.filterProjectIds)
if (hasViewPerm) return next();
if (!memberProjects.length)
return res
.status(403)
.json({ error: "Forbidden: no accessible projects" });
if (!p.project_ids?.length) return res.status(403).json({ error: "FORBIDDEN_PROJECT" });
req.abac = req.abac || {};
req.abac.filterProjectIds = memberProjects;
req.abac.filterProjectIds = p.project_ids;
return next();
}
};
}
/**
* บังคับเป็นสมาชิกโปรเจ็กต์จากค่า project_id ใน body
* ใช้กับ create endpoints
*/
export function requireProjectMembershipFromBody() {
return async (req, res, next) => {
const roles = req.user?.roles || [];
const isAdmin = roles.includes("Admin");
if (isAdmin) return next();
const pid = Number(req.body?.project_id);
if (!pid) return res.status(400).json({ error: "project_id required" });
const memberProjects = await getUserProjectIds(req.user?.user_id);
if (!memberProjects.includes(pid))
return res.status(403).json({ error: "Forbidden: not a project member" });
next();
};
}
/**
* บังคับเป็นสมาชิกโปรเจ็กต์โดยอ้างอิงจากเรคคอร์ด (ใช้กับ update/delete)
* opts: { modelLoader: (sequelize)=>Model, idParam: 'id', projectField: 'project_id' }
*/
export function requireProjectMembershipByRecord(opts) {
const { modelLoader, idParam = "id", projectField = "project_id" } = opts;
return async (req, res, next) => {
const roles = req.user?.roles || [];
const isAdmin = roles.includes("Admin");
if (isAdmin) return next();
const id = Number(req.params[idParam]);
if (!id) return res.status(400).json({ error: "Invalid id" });
const Model = modelLoader(sequelize);
const row = await Model.findByPk(id);
if (!row) return res.status(404).json({ error: "Not found" });
const pid = Number(row[projectField]);
const memberProjects = await getUserProjectIds(req.user?.user_id);
if (!memberProjects.includes(pid))
return res.status(403).json({ error: "Forbidden: not a project member" });
next();
};
}
/**
* บังคับให้ view ทุกอันต้องส่ง project_id (ยกเว้น Admin)
*/
export function requireProjectIdQuery() {
return async (req, res, next) => {
const roles = req.user?.roles || [];
const isAdmin = roles.includes("Admin");
if (isAdmin) return next();
const qProjectId = req.query?.project_id
? Number(req.query.project_id)
: null;
if (!qProjectId)
return res.status(400).json({ error: "project_id query required" });
return (req, res, next) => {
const p = req.principal;
if (!p) return res.status(401).json({ error: "Unauthenticated" });
if (p.is_superadmin) return next();
const qProjectId = req.query?.project_id ? Number(req.query.project_id) : null;
if (!qProjectId) return res.status(400).json({ error: "project_id query required" });
next();
};
}

View File

@@ -0,0 +1,61 @@
// FILE: backend/src/middleware/auth.js
import jwt from "jsonwebtoken";
import { config } from "../config.js";
import { User, Role, UserRole } from "../db/sequelize.js";
export function signAccessToken(payload) {
return jwt.sign(payload, config.JWT.SECRET, {
expiresIn: config.JWT.EXPIRES_IN,
});
}
export function signRefreshToken(payload) {
return jwt.sign(payload, config.JWT.REFRESH_SECRET, {
expiresIn: config.JWT.REFRESH_EXPIRES_IN,
});
}
export function extractToken(req) {
// ให้คุกกี้มาก่อน แล้วค่อย Bearer (รองรับทั้งสองทาง)
const cookieTok = req.cookies?.access_token || null;
if (cookieTok) return cookieTok;
const hdr = req.headers.authorization || "";
return hdr.startsWith("Bearer ") ? hdr.slice(7) : null;
}
export function requireAuth(req, res, next) {
if (req.path === "/health") return next(); // อนุญาต health เสมอ
const token = extractToken(req);
if (!token) return res.status(401).json({ error: "Missing token" });
try {
req.user = jwt.verify(token, config.JWT.SECRET);
next();
} catch {
return res.status(401).json({ error: "Invalid/Expired token" });
}
}
// ใช้กับเส้นทางที่ login แล้วจะ enrich ต่อได้ แต่ไม่บังคับ
export function optionalAuth(req, _res, next) {
const token = extractToken(req);
if (!token) return next();
try {
req.user = jwt.verify(token, config.JWT.SECRET);
} catch {}
next();
}
export async function enrichRoles(req, _res, next) {
if (!req.user?.user_id) return next();
const rows = await UserRole.findAll({
where: { user_id: req.user.user_id },
include: [{ model: Role }],
}).catch(() => []);
req.user.roles = rows.map((r) => r.role?.role_name).filter(Boolean);
next();
}
export function hasPerm(req, perm) {
const set = new Set(req?.user?.permissions || []);
return set.has(perm);
}

63
backend/src/middleware/auth.js Normal file → Executable file
View File

@@ -1,61 +1,30 @@
// FILE: backend/src/middleware/auth.js
// (ถ้ายังใช้อยู่) ปรับให้สอดคล้อง Bearer + principal
import jwt from "jsonwebtoken";
import { config } from "../config.js";
import { User, Role, UserRole } from "../db/sequelize.js";
export function signAccessToken(payload) {
return jwt.sign(payload, config.JWT.SECRET, {
expiresIn: config.JWT.EXPIRES_IN,
});
const { JWT_SECRET = "dev-secret", JWT_EXPIRES_IN = "30m" } = process.env;
return jwt.sign(payload, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN, issuer: "dms-backend" });
}
export function signRefreshToken(payload) {
return jwt.sign(payload, config.JWT.REFRESH_SECRET, {
expiresIn: config.JWT.REFRESH_EXPIRES_IN,
});
}
export function extractToken(req) {
// ให้คุกกี้มาก่อน แล้วค่อย Bearer (รองรับทั้งสองทาง)
const cookieTok = req.cookies?.access_token || null;
if (cookieTok) return cookieTok;
const hdr = req.headers.authorization || "";
return hdr.startsWith("Bearer ") ? hdr.slice(7) : null;
const { JWT_REFRESH_SECRET = "dev-refresh", JWT_REFRESH_EXPIRES_IN = "30d" } = process.env;
return jwt.sign({ ...payload, t: "refresh" }, JWT_REFRESH_SECRET, { expiresIn: JWT_REFRESH_EXPIRES_IN, issuer: "dms-backend" });
}
// ถ้าจะใช้ standalone (ไม่แนะนำถ้ามี authJwt แล้ว)
export function requireAuth(req, res, next) {
if (req.path === "/health") return next(); // อนุญาต health เสมอ
const token = extractToken(req);
if (!token) return res.status(401).json({ error: "Missing token" });
const h = req.headers.authorization || "";
const m = /^Bearer\s+(.+)$/i.exec(h || "");
if (!m) return res.status(401).json({ error: "Missing token" });
try {
req.user = jwt.verify(token, config.JWT.SECRET);
const { JWT_SECRET = "dev-secret" } = process.env;
const payload = jwt.verify(m[1], JWT_SECRET, { issuer: "dms-backend" });
req.auth = { user_id: payload.user_id, username: payload.username };
req.user = req.user || {};
req.user.user_id = payload.user_id;
req.user.username = payload.username;
next();
} catch {
return res.status(401).json({ error: "Invalid/Expired token" });
}
}
// ใช้กับเส้นทางที่ login แล้วจะ enrich ต่อได้ แต่ไม่บังคับ
export function optionalAuth(req, _res, next) {
const token = extractToken(req);
if (!token) return next();
try {
req.user = jwt.verify(token, config.JWT.SECRET);
} catch {}
next();
}
export async function enrichRoles(req, _res, next) {
if (!req.user?.user_id) return next();
const rows = await UserRole.findAll({
where: { user_id: req.user.user_id },
include: [{ model: Role }],
}).catch(() => []);
req.user.roles = rows.map((r) => r.role?.role_name).filter(Boolean);
next();
}
export function hasPerm(req, perm) {
const set = new Set(req?.user?.permissions || []);
return set.has(perm);
}
}

View File

@@ -25,6 +25,10 @@ export function authJwt() {
// แนบข้อมูลขั้นต่ำให้ middleware ถัดไป
req.auth = { user_id: payload.user_id, username: payload.username };
//req.user = { user_id: payload.user_id, username: payload.username };
// เผื่อโค้ดเก่าอ้างอิง req.user
req.user = req.user || {};
req.user.user_id = payload.user_id;
req.user.username = payload.username;
next();
} catch (e) {
return res.status(401).json({ error: "Unauthenticated" });

6
backend/src/middleware/index.js Normal file → Executable file
View File

@@ -1,7 +1,7 @@
// File: backend/src/middleware/index.js
import * as authJwt from "./authJwt.js";
import * as abac from "./abac.js";
import * as auth from "./auth.js";
import * as authJwt from "./authJwt.js";
import * as errorHandler from "./errorHandler.js";
import * as loadPrincipal from "./loadPrincipal.js";
import * as permGuard from "./permGuard.js";
@@ -12,9 +12,9 @@ import * as requirePerm from "./requirePerm.js";
// Export ทุกอย่างออกมาเป็น named exports
// เพื่อให้สามารถ import แบบ `import { authJwt, permGuard } from '../middleware';` ได้
export {
authJwt,
abac,
auth,
authJwt,
errorHandler,
loadPrincipal,
permGuard,
@@ -25,9 +25,9 @@ export {
// (Optional) สร้าง default export สำหรับกรณีที่ต้องการ import ทั้งหมดใน object เดียว
const middleware = {
authJwt,
abac,
auth,
authJwt,
errorHandler,
loadPrincipal,
permGuard,

83
backend/src/middleware/loadPrincipal.js Normal file → Executable file
View File

@@ -5,15 +5,90 @@
// - Uses rbac.js utility to load principal info
// - Attaches to req.principal
// - Requires req.user.user_id to be populated (e.g. via auth.js or authJwt.js)
// โหลด principal จาก DB แล้วแนบไว้ใน req.principal
// NOTE: ตรงนี้สมมุติว่าคุณมี service/query ฝั่ง DB อยู่แล้ว (เช่น sql/Sequelize)
// ถ้าคุณมีฟังก์ชันโหลด principal อยู่ที่อื่น ให้แทน logic DB ตรง FIXME ด้านล่าง
// ใช้ req.auth.user_id และตั้ง req.principal ให้ครบ (RBAC + ABAC)
import { loadPrincipal } from "../utils/rbac.js";
import sql from "../db/index.js";
export function loadPrincipalMw() {
return async (req, res, next) => {
try {
if (!req.user?.user_id)
return res.status(401).json({ error: "Unauthenticated" });
req.principal = await loadPrincipal(req.user.user_id);
const uid = req?.auth?.user_id || req?.user?.user_id;
if (!uid) return res.status(401).json({ error: "Unauthenticated" });
// --- 1) users (รวม org_id)
const [[u]] = await sql.query(
`SELECT user_id, username, email, first_name, last_name, org_id, is_active
FROM users WHERE user_id=? LIMIT 1`,
[uid]
);
if (!u || u.is_active === 0) return res.status(401).json({ error: "Unauthenticated" });
// --- 2) roles (global)
const [roleRows] = await sql.query(
`SELECT r.role_id, r.role_code, r.role_name
FROM user_roles ur
JOIN roles r ON r.role_id = ur.role_id
WHERE ur.user_id=?`,
[uid]
);
const roleCodes = new Set(roleRows.map(r => r.role_code));
const is_superadmin = roleCodes.has("SUPER_ADMIN");
// --- 3) permissions (ผ่าน role_permissions)
const [permRows] = await sql.query(
`SELECT DISTINCT p.perm_code
FROM user_roles ur
JOIN role_permissions rp ON rp.role_id = ur.role_id
JOIN permissions p ON p.permission_id = rp.permission_id AND p.is_active=1
WHERE ur.user_id=?`,
[uid]
);
const permSet = new Set(permRows.map(x => x.perm_code));
// --- 4) project scope (user_project_roles)
const [projRows] = await sql.query(
`SELECT DISTINCT project_id FROM user_project_roles WHERE user_id=?`,
[uid]
);
const project_ids = projRows.map(r => r.project_id);
// --- 5) org scope: users.org_id + orgs จาก project_parties ของโปรเจ็คที่เข้าถึง
const baseOrgIds = u.org_id ? [u.org_id] : [];
let projOrgIds = [];
if (project_ids.length) {
const [rows] = await sql.query(
`SELECT DISTINCT org_id FROM project_parties WHERE project_id IN (?)`,
[project_ids]
);
projOrgIds = rows.map(r => r.org_id);
}
const org_ids = Array.from(new Set([...baseOrgIds, ...projOrgIds]));
req.principal = {
user_id: u.user_id,
username: u.username,
email: u.email,
first_name: u.first_name,
last_name: u.last_name,
org_id: u.org_id || null,
roles: roleRows.map(r => ({ role_id: r.role_id, role_code: r.role_code, role_name: r.role_name })),
permissions: permSet, // Set ของ perm_code
project_ids,
org_ids,
is_superadmin,
// helpers
can: (code) => is_superadmin || permSet.has(code),
canAny: (codes=[]) => is_superadmin || codes.some(c => permSet.has(c)),
canAll: (codes=[]) => is_superadmin || codes.every(c => permSet.has(c)),
inProject: (pid) => is_superadmin || project_ids.includes(Number(pid)),
inOrg: (oid) => is_superadmin || org_ids.includes(Number(oid)),
};
next();
} catch (err) {
console.error("loadPrincipal error", err);

View File

@@ -2,16 +2,14 @@
// Permission guard middleware
// - Checks if user has required permissions
// - Requires req.user.permissions to be populated (e.g. via auth.js or authJwt.js with enrichment)
// เปลี่ยนให้เป็น wrapper ที่เรียก req.principal (ทางเก่ายังใช้ได้)**
/**
* requirePerm('rfa:create') => ตรวจว่ามี permission นี้ใน req.user.permissions
* ต้องแน่ใจว่าเรียก enrichPermissions() มาก่อน หรือคำนวณที่จุดเข้าใช้งาน
*/
export function requirePerm(...allowedPerms) {
return (req, res, next) => {
const perms = req.user?.permissions || [];
const ok = perms.some((p) => allowedPerms.includes(p));
if (!ok) return res.status(403).json({ error: "Forbidden" });
const p = req.principal;
if (!p) return res.status(401).json({ error: "Unauthenticated" });
const ok = p.is_superadmin || allowedPerms.some((code) => p.permissions?.has?.(code));
if (!ok) return res.status(403).json({ error: "FORBIDDEN", need_any_of: allowedPerms });
next();
};
}
}

View File

@@ -2,39 +2,40 @@
// Permission calculation and enrichment middleware
// - Computes effective permissions for a user based on their roles
// - Attaches permissions to req.user.permissions
// ใช้เฉพาะกรณีที่คุณยังมี stack Sequelize เดิมอยู่ และอยาก enrich จาก Role/Permission model
// โดยทั่วไป ถ้าคุณใช้ loadPrincipalMw() อยู่แล้ว สามารถไม่ใช้ไฟล์นี้ได้
import { Role, Permission, UserRole, RolePermission } from "../db/sequelize.js";
import { Permission, UserRole, RolePermission } from "../db/sequelize.js";
/**
* คืนชุด permission (string[]) ของ user_id
*/
export async function computeEffectivePermissions(user_id) {
// ดึง roles ของผู้ใช้
const userRoles = await UserRole.findAll({ where: { user_id } });
const roleIds = userRoles.map((r) => r.role_id);
if (!roleIds.length) return [];
// ดึง permission ผ่าน role_permissions
const rp = await RolePermission.findAll({ where: { role_id: roleIds } });
const permIds = [...new Set(rp.map((x) => x.permission_id))];
if (!permIds.length) return [];
const perms = await Permission.findAll({ where: { permission_id: permIds } });
return [...new Set(perms.map((p) => p.permission_name))];
// ใช้ perm_code ให้สอดคล้อง seed
return [...new Set(perms.map((p) => p.perm_code))];
}
/**
* middleware: เติม permissions ลง req.user.permissions
*/
export function enrichPermissions() {
return async (req, _res, next) => {
if (!req.user?.user_id) return next();
const uid = req?.auth?.user_id || req?.user?.user_id;
if (!uid) return next();
try {
const perms = await computeEffectivePermissions(req.user.user_id);
const perms = await computeEffectivePermissions(uid);
// อัปเดตทั้ง req.principal และ req.user (เผื่อโค้ดเก่า)
req.principal = req.principal || {};
req.principal.permissions = new Set(perms);
req.user = req.user || {};
req.user.permissions = perms;
} catch (e) {
req.user.permissions = [];
} catch {
if (req.principal) req.principal.permissions = new Set();
if (req.user) req.user.permissions = [];
}
next();
};
}
}

View File

@@ -5,18 +5,19 @@
export function requireRole(...allowed) {
return (req, res, next) => {
const roles = req.user?.roles || [];
const ok = roles.some((r) => allowed.includes(r));
if (!ok) return res.status(403).json({ error: "Forbidden" });
const roles = (req.principal?.roles || []).map(r => r.role_code);
const ok = roles.some((r) => allowed.includes(r)) || req.principal?.is_superadmin;
if (!ok) return res.status(403).json({ error: "FORBIDDEN_ROLE", need_any_of: allowed });
next();
};
}
export function requirePermission(...allowedPerms) {
export function requirePermissionCode(...codes) {
return (req, res, next) => {
const perms = req.user?.permissions || [];
const ok = perms.some((p) => allowedPerms.includes(p));
if (!ok) return res.status(403).json({ error: "Forbidden" });
const p = req.principal;
if (!p) return res.status(401).json({ error: "Unauthenticated" });
const ok = p.is_superadmin || codes.some((c) => p.permissions?.has?.(c));
if (!ok) return res.status(403).json({ error: "FORBIDDEN", need_any_of: codes });
next();
};
}

View File

@@ -0,0 +1,18 @@
// FILE: src/middleware/requireBearer.js
import jwt from "jsonwebtoken";
import { findUserById } from "../db/models/users.js";
export async function requireBearer(req, res, next) {
const hdr = req.get("Authorization") || "";
const m = hdr.match(/^Bearer\s+(.+)$/i);
if (!m) return res.status(401).json({ error: "Unauthenticated" });
try {
const payload = jwt.verify(m[1], process.env.JWT_ACCESS_SECRET, { issuer: "dms-backend" });
const user = await findUserById(payload.user_id);
if (!user) return res.status(401).json({ error: "Unauthenticated" });
req.user = { user_id: user.user_id, username: user.username, email: user.email, first_name: user.first_name, last_name: user.last_name };
next();
} catch {
return res.status(401).json({ error: "Unauthenticated" });
}
}

View File

@@ -6,32 +6,59 @@
// - Uses canPerform() utility from rbac.js
// - Supports global, org, and project scopes
// - Requires req.principal to be populated (e.g. via loadPrincipal middleware)
// เช็คตาม perm_code + ABAC อัตโนมัติจาก permissions.scope_level
import sql from "../db/index.js";
import { canPerform } from "../utils/rbac.js";
let _permMap = null;
let _loadedAt = 0;
const TTL_MS = 60_000;
async function getPermRegistry() {
const now = Date.now();
if (_permMap && now - _loadedAt < TTL_MS) return _permMap;
const [rows] = await sql.query(
`SELECT perm_code, scope_level FROM permissions WHERE is_active=1`
);
_permMap = new Map(rows.map(r => [r.perm_code, r.scope_level])); // GLOBAL | ORG | PROJECT
_loadedAt = now;
return _permMap;
}
/**
* requirePerm('correspondence.create', { scope: 'org', getOrgId: req => ... })
* scope: 'global' | 'org' | 'project'
* requirePerm('rfas.view', { projectParam: 'project_id', orgParam: 'org_id' })
* - GLOBAL: แค่มี perm ก็ผ่าน
* - ORG: ต้องมี perm + อยู่ใน org scope (อ่าน org_id จาก param หากระบุ; ไม่ระบุจะใช้ req.principal.org_id)
* - PROJECT:ต้องมี perm + อยู่ใน project scope (อ่าน project_id จาก param)
*/
export function requirePerm(
permCode,
{ scope = "global", getOrgId = null, getProjectId = null } = {}
) {
export function requirePerm(permCode, { projectParam, orgParam } = {}) {
return async (req, res, next) => {
try {
const orgId = getOrgId ? await getOrgId(req) : null;
const projectId = getProjectId ? await getProjectId(req) : null;
const p = req.principal;
if (!p) return res.status(401).json({ error: "Unauthenticated" });
if (canPerform(req.principal, permCode, { scope, orgId, projectId }))
return next();
return res.status(403).json({
error: "FORBIDDEN",
message: `Require ${permCode} (${scope}-scoped)`,
});
} catch (e) {
console.error("requirePerm error", e);
res.status(500).json({ error: "Permission check error" });
if (!(p.is_superadmin || p.permissions?.has?.(permCode))) {
return res.status(403).json({ error: "FORBIDDEN", need: permCode });
}
const registry = await getPermRegistry();
const scope = registry.get(permCode) || "GLOBAL";
const readParam = (name) => req.params?.[name] ?? req.query?.[name] ?? req.body?.[name];
if (scope === "PROJECT") {
const pid = Number(projectParam ? readParam(projectParam) : undefined);
if (!p.is_superadmin) {
if (!pid || !p.inProject(pid)) {
return res.status(403).json({ error: "FORBIDDEN_PROJECT", project_id: pid || null });
}
}
} else if (scope === "ORG") {
const oid = Number(orgParam ? readParam(orgParam) : p.org_id);
if (!p.is_superadmin) {
if (!oid || !p.inOrg(oid)) {
return res.status(403).json({ error: "FORBIDDEN_ORG", org_id: oid || null });
}
}
}
next();
};
}
}

View File

@@ -1,4 +1,6 @@
// FILE: src/routes/categories.js
// อ่าน: ใช้ organizations.view (GLOBAL)
// สร้าง/แก้/ลบ: ใช้ settings.manage (GLOBAL)
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

View File

@@ -1,4 +1,6 @@
// FILE: src/routes/contract_dwg.js
// ใน seed ยังไม่มี contract_dwg.* → ผูกชั่วคราวกับสิทธิ์กลุ่ม drawings:
// read → drawings.view, create/update/delete → drawings.upload/delete (PROJECT scope)
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

View File

@@ -1,4 +1,7 @@
// FILE: src/routes/contracts.js
// ไม่มี contract.* ใน seed → map เป็นงานดูแลองค์กร/โปรเจ็กต์:
// list/get → projects.view (ORG)
// create/update/delete → projects.manage (ORG)
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

74
backend/src/routes/dashboard.js Normal file → Executable file
View File

@@ -1,23 +1,63 @@
import { Router } from "express";
import { User } from "../db/index.js";
import { authJwt } from "../middleware/index.js";
// backend/src/routes/dashboard.js
import { Router } from 'express';
import { Op } from 'sequelize';
// 1. Import Middleware ที่ถูกต้อง
import { authJwt } from '../middleware/authJwt.js';
import { loadPrincipalMw } from '../middleware/loadPrincipal.js';
// 2. Import Sequelize Models จาก `sequelize.js` ไม่ใช่ `index.js`
import { Correspondence, Document, RFA, User } from '../db/sequelize.js';
const router = Router();
router.use(authJwt.verifyToken);
// 3. ใช้ Middleware Chain ที่ถูกต้อง 100%
router.use(authJwt(), loadPrincipalMw());
router.get("/users/summary", async (req, res, next) => {
try {
const totalUsers = await User.count();
const activeUsers = await User.count({ where: { is_active: true } });
res.json({
total: totalUsers,
active: activeUsers,
inactive: totalUsers - activeUsers,
});
} catch (error) {
next(error);
}
// === API สำหรับ User Management Widget ===
router.get('/users/summary', async (req, res, next) => {
try {
// ตรวจสอบว่า Model ถูกโหลดแล้วหรือยัง (จำเป็นสำหรับโหมด lazy-load)
if (!User) {
return res.status(503).json({ message: 'Database models not available. Is ENABLE_SEQUELIZE=1 set?' });
}
const totalUsers = await User.count();
const activeUsers = await User.count({ where: { is_active: true } });
res.json({
total: totalUsers,
active: activeUsers,
inactive: totalUsers - activeUsers,
});
} catch (error) {
next(error);
}
});
export default router;
// === API อื่นๆ สำหรับ Dashboard ที่เราคุยกันไว้ก่อนหน้า ===
router.get('/stats', async (req, res, next) => {
try {
if (!Document || !RFA) {
return res.status(503).json({ message: 'Database models not available. Is ENABLE_SEQUELIZE=1 set?' });
}
const sevenDaysAgo = new Date(new Date().setDate(new Date().getDate() - 7));
const totalDocuments = await Document.count();
const newThisWeek = await Document.count({ where: { createdAt: { [Op.gte]: sevenDaysAgo } } });
const pendingRfas = await RFA.count({ where: { status: 'pending' } }); // สมมติตาม status
res.json({
totalDocuments,
newThisWeek,
pendingRfas
});
} catch (error) {
next(error);
}
});
export default router;

View File

@@ -1,4 +1,5 @@
// FILE: backend/src/routes/mvp.js
// (generic entity maps — ใช้ projects.view อ่าน และ projects.manage เขียน/ลบ)
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

130
backend/src/routes/rbac_admin.js Normal file → Executable file
View File

@@ -1,144 +1,88 @@
// FILE: backend/src/routes/rbac_admin.js
import { Router } from "express";
import { Role, Permission, UserProjectRole, Project } from "../db/sequelize.js";
import { authJwt, permGuard } from "../middleware/index.js";
import { authJwt } from "../middleware/authJwt.js";
import { loadPrincipalMw } from "../middleware/loadPrincipal.js"; // แก้ไข: import ให้ถูกต้อง
import { requirePerm } from "../middleware/requirePerm.js";
const router = Router();
// กำหนดให้ทุก route ในไฟล์นี้ต้องมีสิทธิ์ 'manage_rbac'
router.use(authJwt.verifyToken, permGuard("manage_rbac"));
// Middleware Chain ที่ถูกต้อง 100% ตามสถาปัตยกรรมของคุณ
router.use(authJwt(), loadPrincipalMw());
// == ROLES Management ==
router.get("/roles", async (req, res, next) => {
router.get("/roles", requirePerm("roles.manage"), async (req, res, next) => {
try {
const roles = await Role.findAll({
include: [
{
model: Permission,
attributes: ["id", "name"],
through: { attributes: [] },
},
],
include: [{ model: Permission, attributes: ["id", "name"], through: { attributes: [] } }],
order: [["name", "ASC"]],
});
res.json(roles);
} catch (error) {
next(error);
}
} catch (error) { next(error); }
});
router.post("/roles", async (req, res, next) => {
router.post("/roles", requirePerm("roles.manage"), async (req, res, next) => {
const { name, description } = req.body;
if (!name) return res.status(400).json({ message: "Role name is required." });
try {
const { name, description } = req.body;
if (!name)
return res.status(400).json({ message: "Role name is required." });
const newRole = await Role.create({ name, description });
res.status(201).json(newRole);
} catch (error) {
if (error.name === "SequelizeUniqueConstraintError") {
return res
.status(409)
.json({ message: `Role '${name}' already exists.` });
return res.status(409).json({ message: `Role '${name}' already exists.` });
}
next(error);
}
});
router.put("/roles/:id/permissions", async (req, res, next) => {
try {
router.put("/roles/:id/permissions", requirePerm("roles.manage"), async (req, res, next) => {
const { permissionIds } = req.body;
if (!Array.isArray(permissionIds))
return res
.status(400)
.json({ message: "permissionIds must be an array." });
const role = await Role.findByPk(req.params.id);
if (!role) return res.status(404).json({ message: "Role not found." });
await role.setPermissions(permissionIds);
const updatedRole = await Role.findByPk(req.params.id, {
include: [
{
model: Permission,
attributes: ["id", "name"],
through: { attributes: [] },
},
],
});
res.json(updatedRole);
} catch (error) {
next(error);
}
});
// == PERMISSIONS Management ==
router.get("/permissions", async (req, res, next) => {
try {
const permissions = await Permission.findAll({ order: [["name", "ASC"]] });
res.json(permissions);
} catch (error) {
next(error);
}
if (!Array.isArray(permissionIds)) return res.status(400).json({ message: "permissionIds must be an array." });
try {
const role = await Role.findByPk(req.params.id);
if (!role) return res.status(404).json({ message: "Role not found." });
await role.setPermissions(permissionIds);
const updatedRole = await Role.findByPk(req.params.id, {
include: [{ model: Permission, attributes: ['id', 'name'], through: { attributes: [] } }]
});
res.json(updatedRole);
} catch (error) { next(error); }
});
// == USER-PROJECT-ROLES Management ==
router.get("/user-project-roles", async (req, res, next) => {
router.get("/user-project-roles", requirePerm("users.manage"), async (req, res, next) => {
const { userId } = req.query;
if (!userId)
return res
.status(400)
.json({ message: "userId query parameter is required." });
if (!userId) return res.status(400).json({ message: "userId query parameter is required." });
try {
const assignments = await UserProjectRole.findAll({
where: { user_id: userId },
include: [
{ model: Project, attributes: ["id", "name"] },
{ model: Role, attributes: ["id", "name"] },
],
include: [ { model: Project, attributes: ["id", "name"] }, { model: Role, attributes: ["id", "name"] } ],
});
res.json(assignments);
} catch (error) {
next(error);
}
} catch (error) { next(error); }
});
router.post("/user-project-roles", async (req, res, next) => {
router.post("/user-project-roles", requirePerm("users.manage"), async (req, res, next) => {
const { userId, projectId, roleId } = req.body;
if (!userId || !projectId || !roleId)
return res
.status(400)
.json({ message: "userId, projectId, and roleId are required." });
if (!userId || !projectId || !roleId) return res.status(400).json({ message: "userId, projectId, and roleId are required." });
try {
const [assignment, created] = await UserProjectRole.findOrCreate({
where: { user_id: userId, project_id: projectId, role_id: roleId },
defaults: { user_id: userId, project_id: projectId, role_id: roleId },
});
if (!created)
return res
.status(409)
.json({ message: "This assignment already exists." });
if (!created) return res.status(409).json({ message: "This assignment already exists." });
res.status(201).json(assignment);
} catch (error) {
next(error);
}
} catch (error) { next(error); }
});
router.delete("/user-project-roles", async (req, res, next) => {
router.delete("/user-project-roles", requirePerm("users.manage"), async (req, res, next) => {
const { userId, projectId, roleId } = req.body;
if (!userId || !projectId || !roleId)
return res
.status(400)
.json({ message: "userId, projectId, and roleId are required." });
if (!userId || !projectId || !roleId) return res.status(400).json({ message: "userId, projectId, and roleId are required." });
try {
const deletedCount = await UserProjectRole.destroy({
where: { user_id: userId, project_id: projectId, role_id: roleId },
});
if (deletedCount === 0)
return res.status(404).json({ message: "Assignment not found." });
const deletedCount = await UserProjectRole.destroy({ where: { user_id: userId, project_id: projectId, role_id: roleId } });
if (deletedCount === 0) return res.status(404).json({ message: 'Assignment not found.' });
res.status(204).send();
} catch (error) {
next(error);
}
} catch (error) { next(error); }
});
export default router;
export default router;

173
backend/src/routes/users.js Normal file → Executable file
View File

@@ -1,136 +1,55 @@
// File: backend/src/routes/users.js
// FILE: backend/src/routes/users.js
import { Router } from "express";
import { User, Role } from "../db/sequelize.js";
import { authJwt, permGuard } from "../middleware/index.js";
import { hashPassword } from "../utils/passwords.js";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";
const router = Router();
const r = Router();
// Middleware สำหรับทุก route ในไฟล์นี้
router.use(authJwt.verifyToken);
// ME (ทุกคน)
r.get("/me", async (req, res) => {
const p = req.principal;
const [[u]] = await sql.query(
`SELECT user_id, username, email, first_name, last_name, org_id FROM users WHERE user_id=?`,
[p.user_id]
);
if (!u) return res.status(404).json({ error: "User not found" });
const [roles] = await sql.query(
`SELECT r.role_code, r.role_name, ur.org_id, ur.project_id
FROM user_roles ur JOIN roles r ON r.role_id = ur.role_id
WHERE ur.user_id=?`,
[p.user_id]
);
res.json({
...u,
roles,
role_codes: roles.map((r) => r.role_code),
permissions: [...(p.permissions || [])],
project_ids: p.project_ids,
org_ids: p.org_ids,
is_superadmin: p.is_superadmin,
});
});
// GET /api/users - ดึงรายชื่อผู้ใช้ทั้งหมด
router.get(
// USERS LIST (ORG scope) — admin.access
r.get(
"/",
permGuard("manage_users"), // ตรวจสอบสิทธิ์
async (req, res, next) => {
try {
const users = await User.findAll({
attributes: { exclude: ["password_hash"] }, // **สำคัญมาก: ห้ามส่ง password hash ออกไป**
include: [
{
model: Role,
attributes: ["id", "name"],
through: { attributes: [] }, // ไม่ต้องเอาข้อมูลจากตาราง join (UserRoles) มา
},
],
order: [["username", "ASC"]],
});
res.json(users);
} catch (error) {
next(error);
requirePerm("admin.access", { orgParam: "org_id" }),
async (req, res) => {
const P = req.principal;
let rows = [];
if (P.is_superadmin) {
[rows] = await sql.query(
"SELECT user_id, username, email, org_id FROM users ORDER BY user_id DESC LIMIT 500"
);
} else if (P.org_ids?.length) {
const inSql = P.org_ids.map(() => "?").join(",");
[rows] = await sql.query(
`SELECT user_id, username, email, org_id FROM users WHERE org_id IN (${inSql}) ORDER BY user_id DESC LIMIT 500`,
P.org_ids
);
}
res.json(rows);
}
);
// POST /api/users - สร้างผู้ใช้ใหม่
router.post("/", permGuard("manage_users"), async (req, res, next) => {
const { username, email, password, first_name, last_name, is_active, roles } =
req.body;
if (!username || !email || !password) {
return res
.status(400)
.json({ message: "Username, email, and password are required" });
}
try {
const password_hash = await hashPassword(password);
const newUser = await User.create({
username,
email,
password_hash,
first_name,
last_name,
is_active: is_active !== false,
});
if (roles && roles.length > 0) {
await newUser.setRoles(roles);
}
const userWithRoles = await User.findByPk(newUser.id, {
attributes: { exclude: ["password_hash"] },
include: [
{
model: Role,
attributes: ["id", "name"],
through: { attributes: [] },
},
],
});
res.status(201).json(userWithRoles);
} catch (error) {
if (error.name === "SequelizeUniqueConstraintError") {
return res
.status(409)
.json({ message: "Username or email already exists." });
}
next(error);
}
});
// PUT /api/users/:id - อัปเดตข้อมูลผู้ใช้
router.put("/:id", permGuard("manage_users"), async (req, res, next) => {
const { id } = req.params;
const { email, first_name, last_name, is_active, roles } = req.body;
try {
const user = await User.findByPk(id);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
user.email = email ?? user.email;
user.first_name = first_name ?? user.first_name;
user.last_name = last_name ?? user.last_name;
user.is_active = is_active ?? user.is_active;
await user.save();
if (roles) {
await user.setRoles(roles);
}
const updatedUser = await User.findByPk(id, {
attributes: { exclude: ["password_hash"] },
include: [
{
model: Role,
attributes: ["id", "name"],
through: { attributes: [] },
},
],
});
res.json(updatedUser);
} catch (error) {
next(error);
}
});
// DELETE /api/users/:id - ลบผู้ใช้ (Soft Delete)
router.delete("/:id", permGuard("manage_users"), async (req, res, next) => {
try {
const user = await User.findByPk(req.params.id);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
user.is_active = false; // Soft Delete
await user.save();
res.status(204).send();
} catch (error) {
next(error);
}
});
export default router;
export default r;

View File

@@ -0,0 +1,15 @@
import app from "../src/index.js"; // สมมติว่าคุณ export app จาก src/index.js
import request from "supertest";
// ปิด server หลังจากเทสเสร็จ
afterAll((done) => {
app.server.close(done);
});
describe("GET /health", () => {
it("should respond with 200 OK and a health message", async () => {
const response = await request(app).get("/health");
expect(response.statusCode).toBe(200);
expect(response.text).toContain("Backend is healthy");
});
});

View File

@@ -16,8 +16,8 @@ services:
target: prod
image: dms-backend:prod
command: ["true"]
# docker compose -f docker-backend-build.yml build --no-cache
# docker compose -f docker-backend-build.yml build --no-cache 2>&1 | tee backend_build.log
# ***** สำหรับ build บน server เอา ## ออก *****
# สำหรับ build บน local
# cd backend
# docker build -t dms-backend:dev --target dev .
# docker build -t dms-backend:dev --target dev .

View File

@@ -1,4 +1,4 @@
# DMS Container v0_7_0 251004
# DMS Container v0_7_0
# version: "3.8"
x-restart: &restart_policy
restart: unless-stopped

View File

@@ -24,6 +24,7 @@ services:
command: ["true"]
# docker compose -f docker-frontend-build.yml build --no-cache
# docker compose -f docker-frontend-build.yml build --no-cache 2>&1 | tee frontend_build.log
# สร้าง package-lock.json
# cd frontend

0
frontend/.dockerignore Normal file → Executable file
View File

0
frontend/.editorconfig Normal file → Executable file
View File

0
frontend/.eslintrc.json Normal file → Executable file
View File

0
frontend/.prettierrc.json Normal file → Executable file
View File

4
frontend/Dockerfile Normal file → Executable file
View File

@@ -1,7 +1,7 @@
# syntax=docker/dockerfile:1.6
############ Base ############
FROM node:24-alpine AS base
FROM node:20-alpine AS base
WORKDIR /app
RUN apk add --no-cache bash curl tzdata \
&& ln -snf /usr/share/zoneinfo/Asia/Bangkok /etc/localtime \
@@ -66,6 +66,8 @@ RUN echo "=== Checking components ===" && \
echo "=== Checking .next permissions ===" && \
ls -lad /app/.next
RUN npm ci --no-audit --no-fund --include=dev
RUN npm run build
############ Prod runtime (optimized) ############

0
frontend/api/health/route.js Normal file → Executable file
View File

0
frontend/app/(auth)/layout.jsx Normal file → Executable file
View File

0
frontend/app/(auth)/login/page copy.jsx Normal file → Executable file
View File

0
frontend/app/(auth)/login/page.jsx Normal file → Executable file
View File

View File

View File

@@ -2,7 +2,7 @@
'use client';
import { useState, useEffect } from 'react';
import api from '@/lib/api';
import { api } from '@/lib/api';
import { Button } from '@/components/ui/button';
import {
Dialog,
@@ -26,17 +26,20 @@ export function RoleFormDialog({ role, allPermissions, isOpen, setIsOpen, onSucc
const isEditMode = !!role;
useEffect(() => {
// Reset state ทุกครั้งที่ dialog เปิดขึ้นมาใหม่
if (isOpen) {
if (isEditMode) {
// โหมดแก้ไข: ตั้งค่าฟอร์มด้วยข้อมูล Role ที่มีอยู่
setFormData({ name: role.name, description: role.description || '' });
setSelectedPermissions(new Set(role.Permissions?.map(p => p.id) || []));
} else {
// โหมดสร้างใหม่: เคลียร์ฟอร์ม
setFormData({ name: '', description: '' });
setSelectedPermissions(new Set());
}
setError('');
}
}, [role, isOpen]);
}, [role, isOpen]); // ให้ re-run effect นี้เมื่อ role หรือ isOpen เปลี่ยน
const handleInputChange = (e) => {
const { id, value } = e.target;
@@ -62,15 +65,14 @@ export function RoleFormDialog({ role, allPermissions, isOpen, setIsOpen, onSucc
try {
if (isEditMode) {
// ในโหมดแก้ไข เราจะอัปเดตสิทธิ์เสมอ
// โหมดแก้ไข: อัปเดต Permissions ของ Role ที่มีอยู่
await api.put(`/rbac/roles/${role.id}/permissions`, {
permissionIds: Array.from(selectedPermissions)
});
// (Optional) อาจจะเพิ่มการแก้ไขชื่อ/description ของ role ที่นี่ด้วยก็ได้
// await api.put(`/rbac/roles/${role.id}`, { name: formData.name, description: formData.description });
} else {
// ในโหมดสร้างใหม่
// โหมดสร้างใหม่: สร้าง Role ใหม่ก่อน
const newRoleRes = await api.post('/rbac/roles', formData);
// ถ้าสร้าง Role สำเร็จ และมีการเลือก Permission ไว้ ให้ทำการผูกสิทธิ์ทันที
if (newRoleRes.data && selectedPermissions.size > 0) {
await api.put(`/rbac/roles/${newRoleRes.data.id}/permissions`, {
@@ -78,8 +80,8 @@ export function RoleFormDialog({ role, allPermissions, isOpen, setIsOpen, onSucc
});
}
}
onSuccess();
setIsOpen(false);
onSuccess(); // บอกให้หน้าแม่ (roles/page.jsx) โหลดข้อมูลใหม่
setIsOpen(false); // ปิด Dialog
} catch (err) {
setError(err.response?.data?.message || 'An unexpected error occurred.');
} finally {
@@ -92,13 +94,14 @@ export function RoleFormDialog({ role, allPermissions, isOpen, setIsOpen, onSucc
<DialogContent className="sm:max-w-md">
<form onSubmit={handleSubmit}>
<DialogHeader>
<DialogTitle>{isEditMode ? `Edit Permissions for ${role.name}` : 'Create New Role'}</DialogTitle>
<DialogTitle>{isEditMode ? `Edit Permissions for: ${role.name}` : 'Create New Role'}</DialogTitle>
<DialogDescription>
Select the permissions for this role.
{isEditMode ? 'Select the permissions for this role.' : 'Define a new role and its initial permissions.'}
</DialogDescription>
</DialogHeader>
<div className="py-4 space-y-4">
{/* แสดงฟอร์มสำหรับชื่อและคำอธิบายเฉพาะตอนสร้างใหม่ */}
{!isEditMode && (
<>
<div className="space-y-1">
@@ -123,7 +126,7 @@ export function RoleFormDialog({ role, allPermissions, isOpen, setIsOpen, onSucc
checked={selectedPermissions.has(perm.id)}
onCheckedChange={() => handlePermissionChange(perm.id)}
/>
<label htmlFor={`perm-${perm.id}`} className="text-sm font-medium leading-none">
<label htmlFor={`perm-${perm.id}`} className="text-sm font-medium leading-none cursor-pointer">
{perm.name}
</label>
</div>
@@ -135,6 +138,9 @@ export function RoleFormDialog({ role, allPermissions, isOpen, setIsOpen, onSucc
{error && <p className="text-sm text-red-500 text-center pb-2">{error}</p>}
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setIsOpen(false)} disabled={isLoading}>
Cancel
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? 'Saving...' : 'Save Changes'}
</Button>

View File

@@ -2,9 +2,9 @@
'use client';
import { useState, useEffect } from 'react';
import api from '@/lib/api';
import { api } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
@@ -13,20 +13,27 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Trash2 } from 'lucide-react';
import { ScrollArea } from '@/components/ui/scroll-area';
export function UserFormDialog({ user, isOpen, setIsOpen, onSuccess }) {
// State for form fields
const [formData, setFormData] = useState({});
const [allRoles, setAllRoles] = useState([]);
const [selectedSystemRoles, setSelectedSystemRoles] = useState(new Set());
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState('');
const [allProjects, setAllProjects] = useState([]);
// State for project role assignments
const [projectRoles, setProjectRoles] = useState([]);
const [selectedProjectId, setSelectedProjectId] = useState('');
const [selectedRoleId, setSelectedRoleId] = useState('');
// State for prerequisite data (fetched once)
const [allRoles, setAllRoles] = useState([]);
const [allProjects, setAllProjects] = useState([]);
// UI State
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState('');
const isEditMode = !!user;
// Effect to fetch prerequisite data (all roles and projects) when dialog opens
useEffect(() => {
const fetchPrerequisites = async () => {
try {
@@ -38,6 +45,7 @@ export function UserFormDialog({ user, isOpen, setIsOpen, onSuccess }) {
setAllProjects(projectsRes.data);
} catch (err) {
console.error('Failed to fetch prerequisites', err);
setError('Could not load required data (roles, projects).');
}
};
if (isOpen) {
@@ -45,9 +53,11 @@ export function UserFormDialog({ user, isOpen, setIsOpen, onSuccess }) {
}
}, [isOpen]);
// Effect to set up the form when the user prop changes (for editing) or when opening for creation
useEffect(() => {
const fetchUserData = async () => {
const setupForm = async () => {
if (isEditMode) {
// Edit mode: populate form with user data
setFormData({
username: user.username,
email: user.email,
@@ -57,6 +67,7 @@ export function UserFormDialog({ user, isOpen, setIsOpen, onSuccess }) {
});
setSelectedSystemRoles(new Set(user.Roles?.map(role => role.id) || []));
// Fetch this user's specific project roles
try {
const res = await api.get(`/rbac/user-project-roles?userId=${user.id}`);
setProjectRoles(res.data);
@@ -64,19 +75,20 @@ export function UserFormDialog({ user, isOpen, setIsOpen, onSuccess }) {
console.error("Failed to fetch user's project roles", err);
setProjectRoles([]);
}
} else {
// Create mode: reset all fields
setFormData({ username: '', email: '', password: '', first_name: '', last_name: '', is_active: true });
setSelectedSystemRoles(new Set());
setProjectRoles([]);
}
// Reset local state
setError('');
setSelectedProjectId('');
setSelectedRoleId('');
};
if (isOpen) {
fetchUserData();
setupForm();
}
}, [user, isOpen]);
@@ -107,6 +119,7 @@ export function UserFormDialog({ user, isOpen, setIsOpen, onSuccess }) {
projectId: selectedProjectId,
roleId: selectedRoleId
});
// Refresh the list after adding
const res = await api.get(`/rbac/user-project-roles?userId=${user.id}`);
setProjectRoles(res.data);
setSelectedProjectId('');
@@ -123,12 +136,9 @@ export function UserFormDialog({ user, isOpen, setIsOpen, onSuccess }) {
setError('');
try {
await api.delete('/rbac/user-project-roles', {
data: {
userId: user.id,
projectId: assignment.project_id,
roleId: assignment.role_id
}
data: { userId: user.id, projectId: assignment.project_id, roleId: assignment.role_id }
});
// Refresh list visually without another API call
setProjectRoles(prev => prev.filter(p => p.id !== assignment.id));
} catch(err) {
setError(err.response?.data?.message || 'Failed to remove project role.');
@@ -137,7 +147,8 @@ export function UserFormDialog({ user, isOpen, setIsOpen, onSuccess }) {
}
};
const handleSaveUserDetails = async () => {
const handleSaveUserDetails = async (e) => {
e.preventDefault();
setIsLoading(true);
setError('');
const payload = { ...formData, roles: Array.from(selectedSystemRoles) };
@@ -148,8 +159,8 @@ export function UserFormDialog({ user, isOpen, setIsOpen, onSuccess }) {
} else {
await api.post('/users', payload);
}
onSuccess();
setIsOpen(false);
onSuccess(); // Tell the parent page to refresh its data
setIsOpen(false); // Close the dialog
} catch (err) {
setError(err.response?.data?.message || 'An unexpected error occurred.');
} finally {
@@ -160,107 +171,113 @@ export function UserFormDialog({ user, isOpen, setIsOpen, onSuccess }) {
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogContent className="sm:max-w-3xl">
<DialogHeader>
<DialogTitle>{isEditMode ? `Edit User: ${user.username}` : 'Create New User'}</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[70vh]">
<div className="grid grid-cols-1 p-4 md:grid-cols-2 gap-x-6 gap-y-4">
{/* Section 1: User Details & System Roles */}
<div className="pr-4 space-y-4 border-r-0 md:border-r">
<h3 className="pb-2 font-semibold border-b">User Details & System Roles</h3>
<div className="space-y-2">
<Label htmlFor="username">Username</Label>
<Input id="username" value={formData.username || ''} onChange={handleInputChange} required disabled={isEditMode} />
</div>
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input id="email" type="email" value={formData.email || ''} onChange={handleInputChange} required />
</div>
{!isEditMode && (
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<Input id="password" type="password" value={formData.password || ''} onChange={handleInputChange} required />
</div>
)}
<div className="flex gap-4">
<div className="flex-1 space-y-2">
<Label htmlFor="first_name">First Name</Label>
<Input id="first_name" value={formData.first_name || ''} onChange={handleInputChange} />
</div>
<div className="flex-1 space-y-2">
<Label htmlFor="last_name">Last Name</Label>
<Input id="last_name" value={formData.last_name || ''} onChange={handleInputChange} />
</div>
</div>
<div className="space-y-2">
<Label>System Roles</Label>
<div className="p-2 space-y-2 overflow-y-auto border rounded-md max-h-32">
{allRoles.map(role => (
<div key={role.id} className="flex items-center space-x-2">
<Checkbox id={`role-${role.id}`} checked={selectedSystemRoles.has(role.id)} onCheckedChange={() => handleSystemRoleChange(role.id)} />
<label htmlFor={`role-${role.id}`} className="text-sm font-medium">{role.name}</label>
</div>
))}
</div>
</div>
<div className="flex items-center pt-2 space-x-2">
<Switch id="is_active" checked={formData.is_active || false} onCheckedChange={(checked) => setFormData(prev => ({...prev, is_active: checked}))} />
<Label htmlFor="is_active">User is Active</Label>
</div>
</div>
{/* Section 2: Project Role Assignments */}
<div className="space-y-4">
<h3 className="pb-2 font-semibold border-b">Project Role Assignments</h3>
{isEditMode ? (
<>
<div className="p-4 space-y-3 border rounded-lg bg-muted/50">
<p className="text-sm font-medium">Assign New Project Role</p>
<div className="grid grid-cols-2 gap-2">
<Select onValueChange={setSelectedProjectId} value={selectedProjectId}>
<SelectTrigger><SelectValue placeholder="Select Project" /></SelectTrigger>
<SelectContent>{allProjects.map(p => <SelectItem key={p.id} value={String(p.id)}>{p.name}</SelectItem>)}</SelectContent>
</Select>
<Select onValueChange={setSelectedRoleId} value={selectedRoleId}>
<SelectTrigger><SelectValue placeholder="Select Role" /></SelectTrigger>
<SelectContent>{allRoles.map(r => <SelectItem key={r.id} value={String(r.id)}>{r.name}</SelectItem>)}</SelectContent>
</Select>
</div>
<Button onClick={handleAddProjectRole} disabled={isLoading || !selectedProjectId || !selectedRoleId} size="sm" className="w-full">
{isLoading ? 'Adding...' : 'Add Project Role'}
</Button>
</div>
<form onSubmit={handleSaveUserDetails}>
<DialogHeader>
<DialogTitle>{isEditMode ? `Edit User: ${user.username}` : 'Create New User'}</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[70vh] -mr-6 pr-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4 p-4">
{/* Section 1: User Details & System Roles */}
<div className="space-y-4 border-r-0 md:border-r md:pr-4">
<h3 className="font-semibold border-b pb-2">User Details & System Roles</h3>
<div className="space-y-2">
<p className="text-sm font-medium">Current Assignments</p>
<div className="pr-1 space-y-1 overflow-y-auto max-h-48">
{projectRoles.length > 0 ? projectRoles.map(pr => (
<div key={pr.id} className="flex items-center justify-between p-2 text-sm border rounded-md">
<div>
<span className="font-semibold">{pr.Project.name}</span>
<span className="text-muted-foreground"> as </span>
<span>{pr.Role.name}</span>
</div>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleRemoveProjectRole(pr)} disabled={isLoading}>
<Trash2 className="w-4 h-4 text-red-500" />
</Button>
</div>
)) : <p className="py-2 text-sm italic text-center text-muted-foreground">No project assignments.</p>}
</div>
<Label htmlFor="username">Username</Label>
<Input id="username" value={formData.username || ''} onChange={handleInputChange} required disabled={isEditMode} />
</div>
</>
) : <p className="py-4 text-sm italic text-center text-muted-foreground">Save the user first to assign project roles.</p>}
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input id="email" type="email" value={formData.email || ''} onChange={handleInputChange} required />
</div>
{!isEditMode && (
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<Input id="password" type="password" value={formData.password || ''} onChange={handleInputChange} required />
</div>
)}
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="first_name">First Name</Label>
<Input id="first_name" value={formData.first_name || ''} onChange={handleInputChange} />
</div>
<div className="space-y-2">
<Label htmlFor="last_name">Last Name</Label>
<Input id="last_name" value={formData.last_name || ''} onChange={handleInputChange} />
</div>
</div>
<div className="space-y-2">
<Label>System Roles</Label>
<ScrollArea className="h-24 w-full rounded-md border p-2">
{allRoles.map(role => (
<div key={role.id} className="flex items-center space-x-2">
<Checkbox id={`role-${role.id}`} checked={selectedSystemRoles.has(role.id)} onCheckedChange={() => handleSystemRoleChange(role.id)} />
<label htmlFor={`role-${role.id}`} className="text-sm font-medium leading-none cursor-pointer">{role.name}</label>
</div>
))}
</ScrollArea>
</div>
<div className="flex items-center space-x-2 pt-2">
<Switch id="is_active" checked={formData.is_active || false} onCheckedChange={(checked) => setFormData(prev => ({...prev, is_active: checked}))} />
<Label htmlFor="is_active">User is Active</Label>
</div>
</div>
{/* Section 2: Project Role Assignments */}
<div className="space-y-4">
<h3 className="font-semibold border-b pb-2">Project Role Assignments</h3>
{isEditMode ? (
<>
<div className="p-4 border rounded-lg bg-muted/50 space-y-3">
<p className="text-sm font-medium">Assign New Project Role</p>
<div className="grid grid-cols-2 gap-2">
<Select onValueChange={setSelectedProjectId} value={selectedProjectId}>
<SelectTrigger><SelectValue placeholder="Select Project" /></SelectTrigger>
<SelectContent>{allProjects.map(p => <SelectItem key={p.id} value={String(p.id)}>{p.name}</SelectItem>)}</SelectContent>
</Select>
<Select onValueChange={setSelectedRoleId} value={selectedRoleId}>
<SelectTrigger><SelectValue placeholder="Select Role" /></SelectTrigger>
<SelectContent>{allRoles.map(r => <SelectItem key={r.id} value={String(r.id)}>{r.name}</SelectItem>)}</SelectContent>
</Select>
</div>
<Button type="button" onClick={handleAddProjectRole} disabled={isLoading || !selectedProjectId || !selectedRoleId} size="sm" className="w-full">
{isLoading ? 'Adding...' : 'Add Project Role'}
</Button>
</div>
<div className="space-y-2">
<p className="text-sm font-medium">Current Assignments</p>
<ScrollArea className="h-48 w-full rounded-md border p-1">
<div className="space-y-1 p-1">
{projectRoles.length > 0 ? projectRoles.map(pr => (
<div key={pr.id} className="flex justify-between items-center text-sm p-2 border rounded-md">
<div>
<span className="font-semibold">{pr.Project.name}</span>
<span className="text-muted-foreground"> as </span>
<span>{pr.Role.name}</span>
</div>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleRemoveProjectRole(pr)} disabled={isLoading}>
<Trash2 className="h-4 w-4 text-red-500" />
</Button>
</div>
)) : <p className="text-sm text-muted-foreground italic text-center py-2">No project assignments.</p>}
</div>
</ScrollArea>
</div>
</>
) : <p className="text-sm text-muted-foreground italic text-center py-4">Save the user first to assign project roles.</p>}
</div>
</div>
</div>
</ScrollArea>
{error && <p className="pb-2 text-sm text-center text-red-500">{error}</p>}
<DialogFooter className="pt-4 border-t">
<Button onClick={() => setIsOpen(false)} variant="outline">Close</Button>
<Button onClick={handleSaveUserDetails} disabled={isLoading}>
{isLoading ? 'Saving...' : 'Save User Details'}
</Button>
</DialogFooter>
</ScrollArea>
{error && <p className="text-sm text-red-500 text-center pt-2">{error}</p>}
<DialogFooter className="pt-4 border-t">
<Button type="button" variant="outline" onClick={() => setIsOpen(false)} disabled={isLoading}>
Cancel
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? 'Saving...' : 'Save User Details'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);

0
frontend/app/(protected)/admin/layout.jsx Normal file → Executable file
View File

10
frontend/app/(protected)/admin/roles/page.jsx Normal file → Executable file
View File

@@ -2,7 +2,7 @@
'use client';
import { useState, useEffect } from 'react';
import api from '@/lib/api';
import { api } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
@@ -55,16 +55,16 @@ export default function RolesPage() {
return (
<>
<div className="space-y-4">
<div className="flex justify-between items-center">
<div className="flex items-center justify-between">
<h2 className="text-2xl font-semibold">Roles & Permissions</h2>
<Button onClick={handleCreate}>
<PlusCircle className="mr-2 h-4 w-4" /> Add Role
<PlusCircle className="w-4 h-4 mr-2" /> Add Role
</Button>
</div>
{roles.map(role => (
<Card key={role.id}>
<CardHeader>
<div className="flex justify-between items-start">
<div className="flex items-start justify-between">
<div>
<CardTitle className="flex items-center gap-2">
<ShieldCheck className="text-primary" />
@@ -78,7 +78,7 @@ export default function RolesPage() {
</div>
</CardHeader>
<CardContent>
<p className="text-sm font-medium mb-2">Assigned Permissions:</p>
<p className="mb-2 text-sm font-medium">Assigned Permissions:</p>
<div className="flex flex-wrap gap-2">
{role.Permissions.length > 0 ? (
role.Permissions.map(perm => (

2
frontend/app/(protected)/admin/users/page.jsx Normal file → Executable file
View File

@@ -3,7 +3,7 @@
import { useState, useEffect } from 'react';
import { PlusCircle, MoreHorizontal } from 'lucide-react';
import api from '@/lib/api';
import { api } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';

0
frontend/app/(protected)/contracts-volumes/page.jsx Normal file → Executable file
View File

0
frontend/app/(protected)/correspondences/new/page.jsx Normal file → Executable file
View File

0
frontend/app/(protected)/correspondences/page.jsx Normal file → Executable file
View File

0
frontend/app/(protected)/dashboard/page copy.jsx Normal file → Executable file
View File

2
frontend/app/(protected)/dashboard/page.jsx Normal file → Executable file
View File

@@ -7,7 +7,7 @@ import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/com
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Activity, File, FilePlus, ArrowRight, BellDot, Settings } from 'lucide-react';
import api from '@/lib/api';
import { api } from '@/lib/api';
import { useAuth } from '@/lib/auth';
import { can } from '@/lib/rbac';

8
frontend/app/(protected)/drawings/page.jsx Normal file → Executable file
View File

@@ -1,5 +1,5 @@
import { getSession } from "@/lib/auth";
export default async function Page(){
const { user } = await getSession();
return <div className="rounded-2xl p-5 bg-white">Drawings list/table (อเชอม backend)</div>;
import { requireSession } from '@/lib/auth-server';
export default async function Page() {
const { user } = await requireSession();
return <div className="p-5 bg-white rounded-2xl">Drawings list/table (อเชอม backend)</div>;
}

0
frontend/app/(protected)/drawings/upload/page.jsx Normal file → Executable file
View File

0
frontend/app/(protected)/health/page.jsx Normal file → Executable file
View File

150
frontend/app/(protected)/layout.jsx Normal file → Executable file
View File

@@ -1,85 +1,95 @@
// frontend/app/(protected)/layout.jsx
import Link from "next/link";
import { redirect } from "next/navigation";
import { usePathname } from 'next/navigation';
import { cookies, headers } from "next/headers";
import { can } from "@/lib/rbac";
import { Home, FileText, Users, Settings } from 'lucide-react'; // เพิ่ม Users, Settings หรือไอคอนที่ต้องการ
// File: frontend/app/(protected)/layout.jsx
'use client';
export const metadata = { title: "DMS | Protected" };
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth';
const API_BASE = (process.env.NEXT_PUBLIC_API_BASE || "").replace(/\/$/, "");
import { Bell, LogOut, Users } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
async function fetchSessionFromAPI() {
const cookieStore = await cookies(); // ✅ ต้อง await
const cookieHeader = cookieStore.toString();
// NOTE: ให้ชี้ไปยังไฟล์จริงของคุณ
// เดิมบางโปรเจ็กต์ใช้ "../_components/SideNavigation"
// ที่นี่อ้าง absolute import ตาม tsconfig/baseUrl
import { SideNavigation } from '@/app/_components/SideNavigation';
const hdrs = await headers(); // ✅ ต้อง await
const hostHdr = hdrs.get("host");
const protoHdr = hdrs.get("x-forwarded-proto") || "https";
export default function ProtectedLayout({ children }) {
const { user, isAuthenticated, loading, logout } = useAuth();
const router = useRouter();
const res = await fetch(`${API_BASE}/api/auth/me`, {
method: "GET",
headers: {
Cookie: cookieHeader,
"X-Forwarded-Host": hostHdr || "",
"X-Forwarded-Proto": protoHdr,
Accept: "application/json",
},
cache: "no-store",
});
// Guard ฝั่ง client: ถ้าไม่ได้ล็อกอิน ให้เด้งไป /login
useEffect(() => {
if (!loading && !isAuthenticated) {
router.push('/login');
}
}, [loading, isAuthenticated, router]);
if (!res.ok) return null;
try {
const data = await res.json();
return data?.ok ? data : null;
} catch {
return null;
// ระหว่างรอเช็คสถานะ หรือยังไม่ authenticated -> แสดง loading
if (loading || !isAuthenticated) {
return (
<div className="flex items-center justify-center h-screen">
<div className="text-sm text-muted-foreground">Loading session</div>
</div>
);
}
}
export default async function ProtectedLayout({ children }) {
const session = await fetchSessionFromAPI();
if (!session) {
redirect("/login?next=/dashboard");
}
const { user } = session;
const handleLogout = async () => {
try {
await logout();
} finally {
router.replace('/login');
}
};
return (
<section className="grid grid-cols-12 gap-6 p-4 mx-auto max-w-7xl">
<aside className="col-span-12 lg:col-span-3 xl:col-span-3">
<div className="p-4 border rounded-3xl bg-white/70">
<div className="mb-3 text-sm">RBAC: <b>{user.role}</b></div>
<nav className="space-y-2">
<Link className="block px-4 py-2 rounded-xl bg-white/60 hover:bg-white" href="/dashboard">แดชบอร</Link>
<Link className="block px-4 py-2 rounded-xl bg-white/60 hover:bg-white" href="/drawings">Drawings</Link>
<Link className="block px-4 py-2 rounded-xl bg-white/60 hover:bg-white" href="/rfas">RFAs</Link>
<Link className="block px-4 py-2 rounded-xl bg-white/60 hover:bg-white" href="/transmittals">Transmittals</Link>
<Link className="block px-4 py-2 rounded-xl bg-white/60 hover:bg-white" href="/correspondences">Correspondences</Link>
<Link className="block px-4 py-2 rounded-xl bg-white/60 hover:bg-white" href="/contracts-volumes">Contracts & Volumes</Link>
<Link className="block px-4 py-2 rounded-xl bg-white/60 hover:bg-white" href="/reports">Reports</Link>
{can(user, "workflow:view") && <Link className="block px-4 py-2 rounded-xl bg-white/60 hover:bg-white" href="/workflow">Workflow (n8n)</Link>}
{can(user, "health:view") && <Link className="block px-4 py-2 rounded-xl bg-white/60 hover:bg-white" href="/health">Health</Link>}
{can(user, "users:manage") && <Link className="block px-4 py-2 rounded-xl bg-white/60 hover:bg-white" href="/users">ใช/บทบาท</Link>}
</nav>
</div>
<div className="grid min-h-screen w-full md:grid-cols-[220px_1fr] lg:grid-cols-[280px_1fr]">
{/* Sidebar */}
<aside className="hidden border-r bg-muted/40 md:block">
<SideNavigation user={user} />
</aside>
<main className="col-span-12 space-y-6 lg:col-span-9 xl:col-span-9">
<div className="flex items-center gap-2">
<div className="flex-1 text-lg font-semibold">Document Management System LCBP3 Phase 3</div>
{can(user, "admin:view") && <a className="px-3 py-2 text-white rounded-xl" style={{ background: "#0D5C75" }} href="/admin">Admin</a>}
{can(user, "users:manage") && <a className="px-3 py-2 text-white rounded-xl" style={{ background: "#0D5C75" }} href="/users">ใช/บทบาท</a>}
{can(user, "health:view") && <a className="px-3 py-2 text-white rounded-xl" style={{ background: "#0D5C75" }} href="/health">Health</a>}
{can(user, "workflow:view") && <a className="px-3 py-2 text-white rounded-xl" style={{ background: "#0D5C75" }} href="/workflow">Workflow</a>}
{can(user, "rfa:create") && <a className="px-3 py-2 text-white rounded-xl" style={{ background: "#0D5C75" }} href="/rfas/new">+ RFA</a>}
{can(user, "drawing:upload") && <a className="px-3 py-2 text-white rounded-xl" style={{ background: "#0D5C75" }} href="/drawings/upload">+ Upload Drawing</a>}
{can(user, "transmittal:create") && <a className="px-3 py-2 text-white rounded-xl" style={{ background: "#0D5C75" }} href="/transmittals/new">+ Transmittal</a>}
{can(user, "correspondence:create") && <a className="px-3 py-2 text-white rounded-xl" style={{ background: "#0D5C75" }} href="/correspondences/new">+ หนงสอสอสาร</a>}
</div>
{/* Main */}
<div className="flex flex-col">
<header className="flex h-14 items-center gap-4 border-b bg-muted/40 px-4 lg:h-[60px] lg:px-6">
<div className="flex-1" />
{children}
</main>
</section>
<Button variant="ghost" size="icon" className="relative">
<Bell className="w-5 h-5" />
<span className="absolute inline-flex w-2 h-2 rounded-full right-1 top-1 bg-primary" />
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="secondary" size="icon" className="rounded-full">
<Users className="w-5 h-5" />
<span className="sr-only">Toggle user menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>{user?.username || 'My Account'}</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem>Profile Settings</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleLogout} className="text-red-500 focus:text-red-600">
<LogOut className="w-4 h-4 mr-2" />
<span>Logout</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</header>
<main className="flex flex-col flex-1 gap-4 p-4 lg:gap-6 lg:p-6">
{children}
</main>
</div>
</div>
);
}

0
frontend/app/(protected)/reports/page.jsx Normal file → Executable file
View File

0
frontend/app/(protected)/rfas/new/page.jsx Normal file → Executable file
View File

0
frontend/app/(protected)/rfas/page.jsx Normal file → Executable file
View File

0
frontend/app/(protected)/transmittals/new/page.jsx Normal file → Executable file
View File

0
frontend/app/(protected)/transmittals/page.jsx Normal file → Executable file
View File

0
frontend/app/(protected)/users/page.jsx Normal file → Executable file
View File

0
frontend/app/(protected)/workflow/page.jsx Normal file → Executable file
View File

0
frontend/app/_auth/AuthDriver.js Normal file → Executable file
View File

150
frontend/app/_auth/client.js Executable file
View File

@@ -0,0 +1,150 @@
// frontend/app/page.jsx
'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import {
Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { login as authLogin, logout as authLogout, me as fetchMe, credentials, authHeaders } from '@/app/_auth/client';
export default function HomePage() {
const router = useRouter();
const [me, setMe] = useState(null);
const [loading, setLoading] = useState(true);
// login dialog states
const [open, setOpen] = useState(false);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [submitting, setSubmitting] = useState(false);
const [err, setErr] = useState('');
// โหลดสถานะผู้ใช้แบบไม่ redirect
useEffect(() => {
let cancelled = false;
(async () => {
try {
const user = await fetchMe();
if (!cancelled) setMe(user);
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => { cancelled = true; };
}, []);
async function handleLogin(e) {
e?.preventDefault();
setSubmitting(true);
setErr('');
try {
const user = await authLogin({ username, password });
if (!user) {
setErr('ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง');
return;
}
setMe(user);
setOpen(false);
router.push('/dashboard');
} catch {
setErr('เกิดข้อผิดพลาดในการเชื่อมต่อเซิร์ฟเวอร์');
} finally {
setSubmitting(false);
}
}
async function handleLogout() {
await authLogout().catch(() => {});
setMe(null);
}
if (loading) {
return (
<div className="space-y-6">
<div className="w-56 rounded h-7 bg-muted animate-pulse" />
<div className="grid gap-4 md:grid-cols-3">
{[...Array(3)].map((_, i) => <div key={i} className="rounded h-28 bg-muted animate-pulse" />)}
</div>
</div>
);
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h2 className="text-2xl font-bold">Welcome to DMS</h2>
{/* แถบสถานะล็อกอิน + ปุ่ม */}
<div className="flex items-center gap-2">
{me ? (
<>
<span className="text-sm text-muted-foreground">สวสด, <b>{me.first_name || me.username}</b></span>
<Button variant="secondary" onClick={() => router.push('/dashboard')}>Go to Dashboard</Button>
<Button variant="outline" onClick={handleLogout}>Logout</Button>
</>
) : (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button>Login</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[420px]">
<DialogHeader>
<DialogTitle>เขาสระบบ</DialogTitle>
<DialogDescription>กรอกชอผใชและรหสผานของค</DialogDescription>
</DialogHeader>
<form onSubmit={handleLogin} className="grid gap-3">
<div className="grid gap-1.5">
<Label htmlFor="username">Username</Label>
<Input id="username" value={username} onChange={e => setUsername(e.target.value)} required />
</div>
<div className="grid gap-1.5">
<Label htmlFor="password">Password</Label>
<Input id="password" type="password" value={password} onChange={e => setPassword(e.target.value)} required />
</div>
{err && <p className="text-sm text-red-600">{err}</p>}
<Button type="submit" disabled={submitting}>{submitting ? 'กำลังเข้าสู่ระบบ...' : 'Login'}</Button>
</form>
</DialogContent>
</Dialog>
)}
</div>
</div>
{/* เนื้อหาอื่น ๆ (เหมือนเดิม) */}
<Tabs defaultValue="overview" className="w-full">
<TabsList>
<TabsTrigger value="overview">Overview</TabsTrigger>
<TabsTrigger value="activity">Activity</TabsTrigger>
</TabsList>
<TabsContent value="overview">
<div className="grid gap-4 mt-4 md:grid-cols-3">
<Card><CardHeader><CardTitle>📑 RFAs</CardTitle></CardHeader><CardContent><p className="text-3xl font-bold">24</p></CardContent></Card>
<Card><CardHeader><CardTitle>📐 Drawings</CardTitle></CardHeader><CardContent><p className="text-3xl font-bold">112</p></CardContent></Card>
<Card><CardHeader><CardTitle>📤 Transmittals</CardTitle></CardHeader><CardContent><p className="text-3xl font-bold">8</p></CardContent></Card>
</div>
</TabsContent>
<TabsContent value="activity">
<div className="mt-4 space-y-3">
<p> User <b>editor01</b> uploaded Drawing D-2025-07</p>
<p> Transmittal T-2025-02 issued to Contractor</p>
<p> RFA R-2025-03 marked as Resolved</p>
</div>
</TabsContent>
</Tabs>
<div className="pt-2">
<Button asChild disabled={!me}><Link href="/dashboard">Go to Dashboard</Link></Button>
{!me && <span className="ml-2 text-sm text-muted-foreground">กรณา Login อน</span>}
</div>
</div>
);
}

0
frontend/app/_auth/drivers/bearerDriver.js Normal file → Executable file
View File

0
frontend/app/_auth/drivers/cookieDriver.js Normal file → Executable file
View File

0
frontend/app/_auth/useAuthGuard.jsx Normal file → Executable file
View File

View File

@@ -0,0 +1,84 @@
// File: frontend/app/_components/SideNavigation.jsx
'use client';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Home, FileText, Users, Settings, Package2, Upload, PlusCircle, Workflow, BarChart } from 'lucide-react';
import { can } from "@/lib/rbac";
import { cn } from "@/lib/utils";
// Component นี้จะรับ user object ที่มี roles และ permissions มาจาก Server Component Parent
export function SideNavigation({ user }) {
const pathname = usePathname();
// สร้าง Array ของเมนูหลักตามโครงสร้างเดิมของคุณ
const mainNavLinks = [
{ href: '/dashboard', label: 'Dashboard', icon: Home, perm: null }, // หน้าแรกเข้าได้ทุกคน
{ href: '/correspondences', label: 'Correspondences', icon: FileText, perm: 'correspondence:view' },
{ href: '/drawings', label: 'Drawings', icon: FileText, perm: 'drawing:view' },
{ href: '/rfas', label: 'RFAs', icon: FileText, perm: 'rfa:view' },
{ href: '/transmittals', label: 'Transmittals', icon: FileText, perm: 'transmittal:view' },
{ href: '/reports', label: 'Reports', icon: BarChart, perm: 'report:view' },
];
// สร้าง Array ของเมนู Admin ตามโครงสร้างเดิมของคุณ
const adminNavLinks = [
{ href: '/admin', label: 'Admin', icon: Settings, perm: 'admin:view' },
{ href: '/users', label: 'ผู้ใช้/บทบาท', icon: Users, perm: 'users:manage' },
{ href: '/workflow', label: 'Workflow', icon: Workflow, perm: 'workflow:view' },
];
return (
<div className="flex flex-col h-full max-h-screen gap-2">
<div className="flex h-14 items-center border-b px-4 lg:h-[60px] lg:px-6">
<Link href="/dashboard" className="flex items-center gap-2 font-semibold">
<Package2 className="w-6 h-6" />
<span className="">LCB P3 DMS</span>
</Link>
</div>
<div className="flex-1 overflow-y-auto">
<nav className="grid items-start px-2 text-sm font-medium lg:px-4">
{/* Render เมนูหลัก */}
{mainNavLinks.map(({ href, label, icon: Icon, perm }) =>
(perm === null || can(user, perm)) && (
<Link
key={href}
href={href}
className={cn(
'flex items-center gap-3 rounded-lg px-3 py-2 text-muted-foreground transition-all hover:text-primary',
(pathname === href || (href !== '/dashboard' && pathname.startsWith(href))) ? 'bg-muted text-primary' : ''
)}
>
<Icon className="w-4 h-4" />
{label}
</Link>
)
)}
{/* Render เมนู Admin ถ้ามีสิทธิ์อย่างน้อย 1 เมนู */}
{adminNavLinks.some(link => can(user, link.perm)) && (
<>
<div className="my-2 border-t"></div>
{adminNavLinks.map(({ href, label, icon: Icon, perm }) =>
can(user, perm) && (
<Link
key={href}
href={href}
className={cn(
'flex items-center gap-3 rounded-lg px-3 py-2 text-muted-foreground transition-all hover:text-primary',
pathname.startsWith(href) ? 'bg-muted text-primary' : ''
)}
>
<Icon className="w-4 h-4" />
{label}
</Link>
)
)}
</>
)}
</nav>
</div>
{/* ส่วน Card ด้านล่างสามารถคงไว้ หรือเอาออกได้ตามต้องการ */}
</div>
);
}

View File

@@ -0,0 +1,44 @@
// File: frontend/app/_components/TopBar.jsx <<'JSX'
'use client';
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipProvider, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { Bell } from "lucide-react";
import { useAuth } from "@/lib/auth";
import Link from "next/link";
export default function TopBar() {
const { user, loading, logout } = useAuth();
return (
<header className="flex h-14 items-center gap-4 border-b bg-background px-4 lg:h-[60px] lg:px-6">
<div className="flex-1" />
<TooltipProvider delayDuration={300}>
<Tooltip>
<TooltipTrigger asChild>
<Button variant="ghost" size="icon" className="relative">
<Bell className="h-5 w-5" />
<span className="absolute right-1 top-1 inline-flex h-2 w-2 rounded-full bg-primary" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">Notifications</TooltipContent>
</Tooltip>
</TooltipProvider>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="ml-2">
{loading ? "Loading..." : (user?.first_name || "Account")}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem asChild><Link href="/profile">Profile</Link></DropdownMenuItem>
<DropdownMenuItem asChild><Link href="/settings">Settings</Link></DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={logout}>Logout</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</header>
);
}

View File

@@ -0,0 +1,85 @@
//File: frontend/app/_components/navigation.jsx
'use client'; // <-- 1. กำหนดให้ไฟล์นี้เป็น Client Component
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Home, FileText, Settings, Package2 } from 'lucide-react';
import { can } from "@/lib/rbac";
import { cn } from "@/lib/utils";
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
export function Navigation({ user }) { // 2. รับข้อมูล user มาจาก props
const pathname = usePathname(); // 3. ใช้งาน usePathname ได้แล้ว
const navLinks = [
{ href: '/dashboard', label: 'Dashboard', icon: Home },
{ href: '/correspondences', label: 'Correspondences', icon: FileText },
{ href: '/drawings', label: 'Drawings', icon: FileText },
// ... เพิ่มเมนูอื่นๆ ตามต้องการ
];
const adminLink = {
href: '/admin/users',
label: 'Admin',
icon: Settings,
requiredPermission: 'manage_users'
};
return (
<div className="flex h-full max-h-screen flex-col gap-2">
<div className="flex h-14 items-center border-b px-4 lg:h-[60px] lg:px-6">
<Link href="/dashboard" className="flex items-center gap-2 font-semibold">
<Package2 className="h-6 w-6" />
<span className="">LCB P3 DMS</span>
</Link>
{/* Bell Icon can be here if needed */}
</div>
<div className="flex-1">
<nav className="grid items-start px-2 text-sm font-medium lg:px-4">
{navLinks.map(({ href, label, icon: Icon }) => (
<Link
key={href}
href={href}
className={cn(
'flex items-center gap-3 rounded-lg px-3 py-2 text-muted-foreground transition-all hover:text-primary',
pathname.startsWith(href) ? 'bg-muted text-primary' : ''
)}
>
<Icon className="h-4 w-4" />
{label}
</Link>
))}
{user && can(user, adminLink.requiredPermission) && (
<>
<div className="my-2 border-t"></div>
<Link
href={adminLink.href}
className={cn(
'flex items-center gap-3 rounded-lg px-3 py-2 text-muted-foreground transition-all hover:text-primary',
pathname.startsWith('/admin') ? 'bg-muted text-primary' : ''
)}
>
<adminLink.icon className="h-4 w-4" />
{adminLink.label}
</Link>
</>
)}
</nav>
</div>
<div className="mt-auto p-4">
<Card>
<CardHeader className="p-2 pt-0 md:p-4">
<CardTitle>Need Help?</CardTitle>
<CardDescription>Contact support for any issues or questions.</CardDescription>
</CardHeader>
<CardContent className="p-2 pt-0 md:p-4 md:pt-0">
<Button size="sm" className="w-full">Contact</Button>
</CardContent>
</Card>
</div>
</div>
);
}

146
frontend/app/globals.bak.css Executable file
View File

@@ -0,0 +1,146 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* ====== shadcn/ui theme (light + dark) ====== */
:root {
/* โทน “น้ำทะเล” ตามธีมของคุณ */
--primary: 199 90% 40%;
--primary-foreground: 0 0% 100%;
--secondary: 199 60% 92%;
--secondary-foreground: 220 15% 20%;
--muted: 210 20% 96%;
--muted-foreground: 220 10% 35%;
--accent: 199 95% 48%;
--accent-foreground: 0 0% 100%;
--destructive: 0 84% 60%;
--destructive-foreground: 0 0% 100%;
--card: 0 0% 100%;
--card-foreground: 220 15% 15%;
--popover: 0 0% 100%;
--popover-foreground: 220 15% 15%;
--border: 214 32% 91%;
--input: 214 32% 91%;
--ring: 199 90% 40%;
--radius: 0.8rem; /* โค้งมนตามแนวทาง UI ของโปรเจ็ค */
}
.dark {
--background: 220 18% 10%;
--foreground: 0 0% 100%;
--primary: 199 95% 58%;
--primary-foreground: 220 18% 10%;
--secondary: 218 14% 20%;
--secondary-foreground: 0 0% 100%;
--muted: 220 14% 18%;
--muted-foreground: 220 10% 70%;
--accent: 199 95% 62%;
--accent-foreground: 220 18% 10%;
--destructive: 0 62% 46%;
--destructive-foreground: 0 0% 100%;
--card: 220 18% 12%;
--card-foreground: 0 0% 100%;
--popover: 220 18% 12%;
--popover-foreground: 0 0% 100%;
--border: 220 14% 28%;
--input: 220 14% 28%;
--ring: 199 95% 62%;
}
/* Base styling */
@layer base {
* {
@apply border-border;
}
html,
body {
@apply h-full;
}
body {
@apply bg-background text-foreground antialiased;
}
:root {
--background: 0 0% 100%;
--foreground: 0 0% 3.9%;
--card: 0 0% 100%;
--card-foreground: 0 0% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 0 0% 3.9%;
--primary: 0 0% 9%;
--primary-foreground: 0 0% 98%;
--secondary: 0 0% 96.1%;
--secondary-foreground: 0 0% 9%;
--muted: 0 0% 96.1%;
--muted-foreground: 0 0% 45.1%;
--accent: 0 0% 96.1%;
--accent-foreground: 0 0% 9%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 89.8%;
--input: 0 0% 89.8%;
--ring: 0 0% 3.9%;
--chart-1: 12 76% 61%;
--chart-2: 173 58% 39%;
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;
--radius: 0.5rem;
}
.dark {
--background: 0 0% 3.9%;
--foreground: 0 0% 98%;
--card: 0 0% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 0 0% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 0 0% 9%;
--secondary: 0 0% 14.9%;
--secondary-foreground: 0 0% 98%;
--muted: 0 0% 14.9%;
--muted-foreground: 0 0% 63.9%;
--accent: 0 0% 14.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 14.9%;
--input: 0 0% 14.9%;
--ring: 0 0% 83.1%;
--chart-1: 220 70% 50%;
--chart-2: 160 60% 45%;
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%;
}
}
/* Utility: container max width (ช่วยเรื่อง layout) */
.container {
@apply mx-auto px-4;
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

View File

@@ -1,144 +1,185 @@
/* File: frontend/app/globals.css */
@import "tailwindcss";
@plugin "tailwindcss-animate";
@custom-variant dark (&:is(.dark *));
@tailwind base;
@tailwind components;
@tailwind utilities;
/* ====== shadcn/ui theme (light + dark) ====== */
/* === Base & Theme (shadcn style) === */
@layer base {
:root {
/* Sea palette — light */
--background: 0 0% 100%;
--foreground: 220 15% 15%;
--card: 0 0% 100%;
--card-foreground: 220 15% 15%;
--popover: 0 0% 100%;
--popover-foreground: 220 15% 15%;
/* sea tones */
--primary: 199 90% 40%;
--primary-foreground: 0 0% 100%;
--secondary: 199 60% 92%;
--secondary-foreground: 220 15% 20%;
--muted: 210 20% 96%;
--muted-foreground: 220 10% 35%;
--accent: 199 95% 48%;
--accent-foreground: 0 0% 100%;
--destructive: 0 84% 60%;
--destructive-foreground: 0 0% 100%;
--border: 214 32% 91%;
--input: 214 32% 91%;
--ring: 199 90% 40%;
--radius: 0.8rem;
}
.dark {
/* Sea palette — dark */
--background: 220 18% 10%;
--foreground: 0 0% 100%;
--card: 220 18% 12%;
--card-foreground: 0 0% 100%;
--popover: 220 18% 12%;
--popover-foreground: 0 0% 100%;
--primary: 199 95% 58%;
--primary-foreground: 220 18% 10%;
--secondary: 218 14% 20%;
--secondary-foreground: 0 0% 100%;
--muted: 220 14% 18%;
--muted-foreground: 220 10% 70%;
--accent: 199 95% 62%;
--accent-foreground: 220 18% 10%;
--destructive: 0 62% 46%;
--destructive-foreground: 0 0% 100%;
--border: 220 14% 28%;
--input: 220 14% 28%;
--ring: 199 95% 62%;
}
* { @apply border-border; }
html, body { @apply h-full; }
body { @apply antialiased bg-background text-foreground; }
}
/* Utilities */
.container { @apply px-4 mx-auto; }
@theme inline {
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
:root {
/* โทน “น้ำทะเล” ตามธีมของคุณ */
--primary: 199 90% 40%;
--primary-foreground: 0 0% 100%;
--secondary: 199 60% 92%;
--secondary-foreground: 220 15% 20%;
--muted: 210 20% 96%;
--muted-foreground: 220 10% 35%;
--accent: 199 95% 48%;
--accent-foreground: 0 0% 100%;
--destructive: 0 84% 60%;
--destructive-foreground: 0 0% 100%;
--card: 0 0% 100%;
--card-foreground: 220 15% 15%;
--popover: 0 0% 100%;
--popover-foreground: 220 15% 15%;
--border: 214 32% 91%;
--input: 214 32% 91%;
--ring: 199 90% 40%;
--radius: 0.8rem; /* โค้งมนตามแนวทาง UI ของโปรเจ็ค */
--radius: 0.625rem;
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
}
.dark {
--background: 220 18% 10%;
--foreground: 0 0% 100%;
--primary: 199 95% 58%;
--primary-foreground: 220 18% 10%;
--secondary: 218 14% 20%;
--secondary-foreground: 0 0% 100%;
--muted: 220 14% 18%;
--muted-foreground: 220 10% 70%;
--accent: 199 95% 62%;
--accent-foreground: 220 18% 10%;
--destructive: 0 62% 46%;
--destructive-foreground: 0 0% 100%;
--card: 220 18% 12%;
--card-foreground: 0 0% 100%;
--popover: 220 18% 12%;
--popover-foreground: 0 0% 100%;
--border: 220 14% 28%;
--input: 220 14% 28%;
--ring: 199 95% 62%;
}
/* Base styling */
@layer base {
* {
@apply border-border;
}
html,
body {
@apply h-full;
}
body {
@apply bg-background text-foreground antialiased;
}
:root {
--background: 0 0% 100%;
--foreground: 0 0% 3.9%;
--card: 0 0% 100%;
--card-foreground: 0 0% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 0 0% 3.9%;
--primary: 0 0% 9%;
--primary-foreground: 0 0% 98%;
--secondary: 0 0% 96.1%;
--secondary-foreground: 0 0% 9%;
--muted: 0 0% 96.1%;
--muted-foreground: 0 0% 45.1%;
--accent: 0 0% 96.1%;
--accent-foreground: 0 0% 9%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 89.8%;
--input: 0 0% 89.8%;
--ring: 0 0% 3.9%;
--chart-1: 12 76% 61%;
--chart-2: 173 58% 39%;
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;
--radius: 0.5rem;
}
.dark {
--background: 0 0% 3.9%;
--foreground: 0 0% 98%;
--card: 0 0% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 0 0% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 0 0% 9%;
--secondary: 0 0% 14.9%;
--secondary-foreground: 0 0% 98%;
--muted: 0 0% 14.9%;
--muted-foreground: 0 0% 63.9%;
--accent: 0 0% 14.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 14.9%;
--input: 0 0% 14.9%;
--ring: 0 0% 83.1%;
--chart-1: 220 70% 50%;
--chart-2: 160 60% 45%;
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%;
}
}
/* Utility: container max width (ช่วยเรื่อง layout) */
.container {
@apply mx-auto px-4;
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border;
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;

167
frontend/app/layout.jsx Normal file → Executable file
View File

@@ -1,157 +1,20 @@
// frontend/app/layout.jsx
'use client';
// File: frontend/app/layout.jsx
import './globals.css';
import { Inter } from 'next/font/google';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
Bell,
Home,
Users,
Settings,
Package2,
FileText, // Added for example
LineChart, // Added for example
} from 'lucide-react';
export const metadata = {
title: 'DMS',
description: 'Document Management System',
};
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { cn } from '@/lib/utils';
// **1. Import `useAuth` และ `can` จากไฟล์จริงของคุณ**
import { useAuth } from '@/lib/auth';
import { can } from '@/lib/rbac';
export default function ProtectedLayout({ children }) {
const pathname = usePathname();
// **2. เรียกใช้งาน useAuth hook เพื่อดึงข้อมูล user**
const { user, logout } = useAuth();
const navLinks = [
{ href: '/dashboard', label: 'Dashboard', icon: Home },
{ href: '/correspondences', label: 'Correspondences', icon: FileText },
{ href: '/drawings', label: 'Drawings', icon: FileText },
{ href: '/rfas', label: 'RFAs', icon: FileText },
{ href: '/transmittals', label: 'Transmittals', icon: FileText },
{ href: '/reports', label: 'Reports', icon: LineChart },
];
// **3. สร้าง object สำหรับเมนู Admin โดยเฉพาะ**
const adminLink = {
href: '/admin/users',
label: 'Admin',
icon: Settings,
requiredPermission: 'manage_users'
};
const inter = Inter({ subsets: ['latin'] });
export default function RootLayout({ children }) {
return (
<div className="grid min-h-screen w-full md:grid-cols-[220px_1fr] lg:grid-cols-[280px_1fr]">
<div className="hidden border-r bg-muted/40 md:block">
<div className="flex h-full max-h-screen flex-col gap-2">
<div className="flex h-14 items-center border-b px-4 lg:h-[60px] lg:px-6">
<Link href="/" className="flex items-center gap-2 font-semibold">
<Package2 className="h-6 w-6" />
<span className="">LCB P3 DMS</span>
</Link>
<Button variant="outline" size="icon" className="ml-auto h-8 w-8">
<Bell className="h-4 w-4" />
<span className="sr-only">Toggle notifications</span>
</Button>
</div>
<div className="flex-1">
<nav className="grid items-start px-2 text-sm font-medium lg:px-4">
{navLinks.map(({ href, label, icon: Icon }) => (
<Link
key={href}
href={href}
className={cn(
'flex items-center gap-3 rounded-lg px-3 py-2 text-muted-foreground transition-all hover:text-primary',
pathname.startsWith(href) && 'bg-muted text-primary'
)}
>
<Icon className="h-4 w-4" />
{label}
</Link>
))}
{/* ====== ส่วนที่แก้ไข: ตรวจสอบสิทธิ์ด้วย `can` ====== */}
{user && can(user, adminLink.requiredPermission) && (
<>
<div className="my-2 border-t"></div>
<Link
href={adminLink.href}
className={cn(
'flex items-center gap-3 rounded-lg px-3 py-2 text-muted-foreground transition-all hover:text-primary',
pathname.startsWith('/admin') && 'bg-muted text-primary'
)}
>
<adminLink.icon className="h-4 w-4" />
{adminLink.label}
</Link>
</>
)}
{/* ====== จบส่วนที่แก้ไข ====== */}
</nav>
</div>
<div className="mt-auto p-4">
<Card>
<CardHeader className="p-2 pt-0 md:p-4">
<CardTitle>Need Help?</CardTitle>
<CardDescription>
Contact support for any issues or questions.
</CardDescription>
</CardHeader>
<CardContent className="p-2 pt-0 md:p-4 md:pt-0">
<Button size="sm" className="w-full">
Contact
</Button>
</CardContent>
</Card>
</div>
</div>
</div>
<div className="flex flex-col">
<header className="flex h-14 items-center gap-4 border-b bg-muted/40 px-4 lg:h-[60px] lg:px-6">
{/* Mobile navigation can be added here */}
<div className="w-full flex-1">
{/* Optional: Add a search bar */}
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="secondary" size="icon" className="rounded-full">
<Users className="h-5 w-5" />
<span className="sr-only">Toggle user menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>{user ? user.username : 'My Account'}</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem>Settings</DropdownMenuItem>
<DropdownMenuItem>Support</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={logout}>Logout</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</header>
<main className="flex flex-1 flex-col gap-4 p-4 lg:gap-6 lg:p-6">
{children}
</main>
</div>
</div>
<html lang="th" suppressHydrationWarning>
<body className={`${inter.className} min-h-screen bg-background text-foreground antialiased`}>
{children}
</body>
</html>
);
}
}

186
frontend/app/page.jsx Normal file → Executable file
View File

@@ -1,64 +1,142 @@
// app/page.jsx
"use client";
// frontend/app/page.jsx
'use client';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
// 👉 ใช้ driver เดิมของโปรเจ็กต์ (relative path + credentials: 'include')
import cookieDriver from '@/app/_auth/drivers/cookieDriver';
export default function HomePage() {
const router = useRouter();
const [me, setMe] = useState(null);
const [loading, setLoading] = useState(true);
// dialog/login state
const [open, setOpen] = useState(false);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [submitting, setSubmitting] = useState(false);
const [err, setErr] = useState('');
// โหลดสถานะผู้ใช้แบบไม่ redirect
useEffect(() => {
let cancelled = false;
(async () => {
try {
const res = await cookieDriver.me(); // ภายในยิง /api/auth/me ด้วย credentials: 'include'
if (!cancelled && res && (res.user || res.username)) {
const u = res.user ?? res;
setMe(u);
}
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => { cancelled = true; };
}, []);
async function onSubmit(e) {
e?.preventDefault();
setErr('');
if (!username.trim() || !password) {
setErr('กรอกชื่อผู้ใช้และรหัสผ่านให้ครบ');
return;
}
try {
setSubmitting(true);
const ok = await cookieDriver.login({ username, password }); // ยิง /api/auth/login แบบ relative
if (!ok) {
setErr('ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง');
return;
}
// ตรวจ me อีกรอบให้ชัวร์ว่ามีคุกกี้แล้ว
const res = await cookieDriver.me();
const u = res?.user ?? res ?? { username };
setMe(u);
setOpen(false);
router.push('/dashboard');
} catch {
setErr('เชื่อมต่อเซิร์ฟเวอร์ไม่ได้');
} finally {
setSubmitting(false);
}
}
async function onLogout() {
try { await cookieDriver.logout?.(); } catch {}
setMe(null);
}
if (loading) {
return (
<div className="space-y-6">
<div className="w-56 rounded h-7 bg-muted animate-pulse" />
<div className="grid gap-4 md:grid-cols-3">
{[...Array(3)].map((_, i) => <div key={i} className="h-24 rounded bg-muted animate-pulse" />)}
</div>
</div>
);
}
return (
<div className="space-y-6">
<h2 className="text-2xl font-bold">Welcome to DMS</h2>
{/* header */}
<div className="flex items-center justify-between">
<h2 className="text-2xl font-bold">Welcome to DMS</h2>
<div className="flex items-center gap-2">
{me ? (
<>
<span className="text-sm text-muted-foreground">สวสด, <b>{me.first_name || me.username}</b></span>
<Button variant="secondary" onClick={() => router.push('/dashboard')}>Go to Dashboard</Button>
<Button variant="outline" onClick={onLogout}>Logout</Button>
</>
) : (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild><Button>Login</Button></DialogTrigger>
<DialogContent className="sm:max-w-[420px]">
<DialogHeader>
<DialogTitle>เขาสระบบ</DialogTitle>
<DialogDescription>กรอกชอผใชและรหสผานของค</DialogDescription>
</DialogHeader>
<form onSubmit={onSubmit} className="grid gap-3">
<div className="grid gap-1.5">
<Label htmlFor="username">Username</Label>
<Input id="username" value={username} onChange={(e) => setUsername(e.target.value)} required />
</div>
<div className="grid gap-1.5">
<Label htmlFor="password">Password</Label>
<Input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
</div>
{err && <p className="text-sm text-red-600">{err}</p>}
<Button type="submit" disabled={submitting}>{submitting ? 'กำลังเข้าสู่ระบบ…' : 'Login'}</Button>
</form>
</DialogContent>
</Dialog>
)}
</div>
</div>
<Tabs defaultValue="overview" className="w-full">
<TabsList>
<TabsTrigger value="overview">Overview</TabsTrigger>
<TabsTrigger value="activity">Activity</TabsTrigger>
</TabsList>
{/* เนื้อหาย่อก่อนเข้าดาชบอร์ด */}
<div className="grid gap-4 mt-2 md:grid-cols-3">
<Card><CardHeader><CardTitle>📑 RFAs</CardTitle></CardHeader><CardContent><p className="text-3xl font-bold"></p></CardContent></Card>
<Card><CardHeader><CardTitle>📐 Drawings</CardTitle></CardHeader><CardContent><p className="text-3xl font-bold"></p></CardContent></Card>
<Card><CardHeader><CardTitle>📤 Transmittals</CardTitle></CardHeader><CardContent><p className="text-3xl font-bold"></p></CardContent></Card>
</div>
<TabsContent value="overview">
<div className="grid md:grid-cols-3 gap-4 mt-4">
<Card>
<CardHeader>
<CardTitle>📑 RFAs</CardTitle>
</CardHeader>
<CardContent>
<p className="text-3xl font-bold">24</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>📐 Drawings</CardTitle>
</CardHeader>
<CardContent>
<p className="text-3xl font-bold">112</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>📤 Transmittals</CardTitle>
</CardHeader>
<CardContent>
<p className="text-3xl font-bold">8</p>
</CardContent>
</Card>
</div>
</TabsContent>
<TabsContent value="activity">
<div className="mt-4 space-y-3">
<p>
User <b>editor01</b> uploaded Drawing D-2025-07
</p>
<p> Transmittal T-2025-02 issued to Contractor</p>
<p> RFA R-2025-03 marked as Resolved</p>
</div>
</TabsContent>
</Tabs>
<Button className="mt-6">Go to Dashboard</Button>
<div className="pt-2">
<Button asChild disabled={!me}><Link href="/dashboard">Go to Dashboard</Link></Button>
{!me && <span className="ml-2 text-sm text-muted-foreground">กรณา Login อน</span>}
</div>
</div>
);
}

8
frontend/components.json Normal file → Executable file
View File

@@ -7,16 +7,12 @@
"config": "tailwind.config.js",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
"cssVariables": true
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
"utils": "@/lib/utils"
},
"registries": {}
}

View File

@@ -0,0 +1,99 @@
"use client"
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
const AlertDialog = AlertDialogPrimitive.Root
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
const AlertDialogPortal = AlertDialogPrimitive.Portal
const AlertDialogOverlay = React.forwardRef(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref} />
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
const AlertDialogContent = React.forwardRef(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props} />
</AlertDialogPortal>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
const AlertDialogHeader = ({
className,
...props
}) => (
<div
className={cn("flex flex-col space-y-2 text-center sm:text-left", className)}
{...props} />
)
AlertDialogHeader.displayName = "AlertDialogHeader"
const AlertDialogFooter = ({
className,
...props
}) => (
<div
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
{...props} />
)
AlertDialogFooter.displayName = "AlertDialogFooter"
const AlertDialogTitle = React.forwardRef(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title ref={ref} className={cn("text-lg font-semibold", className)} {...props} />
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
const AlertDialogDescription = React.forwardRef(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props} />
))
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName
const AlertDialogAction = React.forwardRef(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
const AlertDialogCancel = React.forwardRef(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className)}
{...props} />
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}

0
frontend/components/ui/alert.jsx Normal file → Executable file
View File

0
frontend/components/ui/badge.jsx Normal file → Executable file
View File

0
frontend/components/ui/button.jsx Normal file → Executable file
View File

Some files were not shown because too many files have changed in this diff Show More