fix: tailwind v4 postcss, auth-server session, eslint cleanups

This commit is contained in:
2025-10-09 15:47:56 +07:00
parent 670228b76e
commit bbfbc5b910
117 changed files with 4005 additions and 3414 deletions

View File

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

View File

@@ -1,39 +1,39 @@
/share/CACHEDEV1_DATA/Container/dms
.git/:1759638121:0
mariadb/:1759638121:0
phpmyadmin/:1759638121:0
backend/:1759638121:0
frontend/:1759638121:0
n8n/:1759638121:0
.git/:1759640646:0
mariadb/:1759640620:0
phpmyadmin/:1759640620:0
backend/:1759640620:0
frontend/:1759640620:0
n8n/:1759640620:0
logs/:1757491706:0
.vscode/:1757985732:0
.syncing_db/:1756445267:0
scripts/:1759638121:0
docker-compose.yml:1759638121:11090
scripts/:1759640620:0
docker-compose.yml:1759640620:11090
npm/:1758073592:0
index.html:1759638121:1499
.gitignore:1759638121:2195
pgadmin/:1759638121:0
style.css:1759638121:2208
b.env:1759638121:2689
README.md:1759638121:5487
n8n-postgres/:1759638121:0
index.html:1759640620:1499
.gitignore:1759640620:2195
README.md:1759640620:5487
pgadmin/:1759640620:0
style.css:1759640620:2208
b.env:1759640620:2689
gitea.yml:1759640620:2228
n8n-postgres/:1759640620:0
.editorconfig:1758876690:187
docker-backend-build.yml:1759638121:653
docker-backend-build.yml:1759640620:653
7.conf:1759482888:6539
gitea.yml:1759638121:2228
landing/:1759638121:0
docker-frontend-build.yml:1759638121:917
landing/:1759640620:0
docker-frontend-build.yml:1759640620:917
Documents/:1758647542:0
ng.oonf:1759482888:3220
generate-shadcn-components.yml:1759638121:951
generate-shadcn-components.yml:1759640620:942
build.log:1759638408:11225
lcbp3.code-workspace:1759638121:588
Bearer-Token.patch.diff:1759640620:19143
package-lock.json:1759208202:82
Bearer-Token.patch.diff:1759638121:19143
.github/:1759638121:0
lcbp3.code-workspace:1759640620:588
.github/:1759640620:0
/share/CACHEDEV1_DATA/Container/dms/.github
copilot-instructions.md:1759638121:5519
copilot-instructions.md:1759640620:5519
/share/CACHEDEV1_DATA/Container/dms/Documents
สรุปขั้นตอนการแก้ไขปัญหา n8n.docx:1757496137:18955
ChatGPT_prompt__v5_1.md:1757098209:1674
@@ -89,24 +89,24 @@ package.json:1757746298:411
Dockerfile:1757756549:2332
เช็คลิสต์กู้ frontend (Next.js + Tailwind + shadcn).md:1758336066:4059
/share/CACHEDEV1_DATA/Container/dms/landing
index.html:1759638121:1263
index.html:1759640620:1263
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres
pg_wal/:1759638121:0
base/:1759638121:0
pg_wal/:1759640620:0
base/:1759640620:0
pg_commit_ts/:1757494489:0
pg_dynshmem/:1757494489:0
pg_notify/:1757494489:0
pg_serial/:1757494489:0
pg_snapshots/:1757494489:0
global/:1759638121:0
global/:1759640620:0
pg_twophase/:1757494489:0
pg_xact/:1759638121:0
pg_xact/:1759640620:0
pg_replslot/:1757494489:0
pg_tblspc/:1757494489:0
pg_stat/:1759632264:0
pg_stat_tmp/:1757494489:0
pg_logical/:1759638121:0
postmaster.pid:1759638121:94
pg_logical/:1759640620:0
postmaster.pid:1759640620:94
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/pg_logical
snapshots/:1757494489:0
mappings/:1757494489:0
@@ -118,53 +118,53 @@ pgstat.stat:1759632264:41880
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/pg_tblspc
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/pg_replslot
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/pg_xact
0000:1759638121:8192
0000:1759640620:8192
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/pg_twophase
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/global
pg_control:1759638121:8192
pg_internal.init:1759638121:28676
pg_control:1759640620:8192
pg_internal.init:1759640620:28676
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/pg_snapshots
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/pg_serial
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/pg_notify
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/pg_dynshmem
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/pg_commit_ts
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/base
16384/:1759638121:0
16384/:1759640620:0
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/base/16384
1247:1759638121:147456
1247_vm:1759638121:8192
1249:1759638121:786432
1249_fsm:1759638121:24576
1249_vm:1759638121:8192
1259:1759638121:172032
1259_vm:1759638121:8192
2608:1759638121:188416
2608_vm:1759638121:8192
2619:1759638121:237568
2619_fsm:1759638121:24576
2658:1759638121:262144
2658_fsm:1759638121:24576
2659:1759638121:180224
2659_fsm:1759638121:24576
2662:1759638121:40960
2663:1759638121:65536
2673:1759638121:196608
2673_fsm:1759638121:24576
2674:1759638121:114688
2696:1759638121:40960
2703:1759638121:40960
2704:1759638121:57344
2840:1759638121:32768
2841:1759638121:16384
3455:1759638121:32768
pg_internal.init:1759638121:159700
1247_vm:1759640620:8192
1249:1759640620:786432
1249_fsm:1759640620:24576
1249_vm:1759640620:8192
1259_vm:1759640620:8192
2608:1759640620:188416
2619_fsm:1759640620:24576
2658:1759640620:262144
2659_fsm:1759640620:24576
2662:1759640620:40960
2663:1759640620:65536
2674:1759640620:114688
2841:1759640620:16384
3455:1759640620:32768
1247:1759640620:147456
1259:1759640620:172032
2659:1759640620:180224
2608_vm:1759640620:8192
2703:1759640620:40960
2619:1759640620:237568
2658_fsm:1759640620:24576
2673:1759640620:196608
2673_fsm:1759640620:24576
2696:1759640620:40960
2704:1759640620:57344
2840:1759640620:32768
pg_internal.init:1759640620:159700
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/pg_wal
archive_status/:1757494489:0
000000010000000000000004:1759638121:16777216
000000010000000000000004:1759640620:16777216
000000010000000000000005:1759556297:16777216
/share/CACHEDEV1_DATA/Container/dms/n8n-postgres/pg_wal/archive_status
/share/CACHEDEV1_DATA/Container/dms/pgadmin
sessions/:1759595501:0
sessions/:1759640620:0
storage/:1757868516:0
azurecredentialcache/:1757868516:0
/share/CACHEDEV1_DATA/Container/dms/pgadmin/azurecredentialcache
@@ -186,16 +186,16 @@ d2df0450-77b2-4967-bf87-8f38ce0bb4e8:1759485387:0
0df55aa5-d6f8-4fee-a943-8ac114d46671:1759589589:0
e5583fcf-64a9-40c6-be53-07db7d42a3e8:1759595501:0
/share/CACHEDEV1_DATA/Container/dms/npm
data/:1759638121:0
letsencrypt/:1759638121:0
custom/:1759638121:0
data/:1759640620:0
letsencrypt/:1759640620:0
custom/:1759640620:0
/share/CACHEDEV1_DATA/Container/dms/npm/custom
http.conf:1759595375:70
/share/CACHEDEV1_DATA/Container/dms/npm/letsencrypt
renewal-hooks/:1758077823:0
renewal/:1759638121:0
archive/:1759638121:0
live/:1759638121:0
renewal/:1759640620:0
archive/:1759640620:0
live/:1759640620:0
/share/CACHEDEV1_DATA/Container/dms/npm/letsencrypt/live
npm-12/:1759398744:0
npm-13/:1759463000:0
@@ -235,12 +235,12 @@ post/:1758077823:0
/share/CACHEDEV1_DATA/Container/dms/npm/letsencrypt/renewal-hooks/deploy
/share/CACHEDEV1_DATA/Container/dms/npm/letsencrypt/renewal-hooks/pre
/share/CACHEDEV1_DATA/Container/dms/npm/data
nginx/:1759638121:0
nginx/:1759640620:0
custom_ssl/:1758077299:0
logs/:1759638121:0
logs/:1759640620:0
access/:1758077299:0
letsencrypt-acme-challenge/:1758246982:0
database.sqlite:1759638121:479232
database.sqlite:1759640620:479232
landng/:1758100038:0
landing/:1758103032:0
/share/CACHEDEV1_DATA/Container/dms/npm/data/landing
@@ -278,7 +278,7 @@ proxy-host-9_error.log:1759463001:0
/share/CACHEDEV1_DATA/Container/dms/npm/data/nginx
custom/:1758077294:0
default_www/:1758077299:0
proxy_host/:1759638121:0
proxy_host/:1759640620:0
redirection_host/:1758077299:0
stream/:1758077299:0
dead_host/:1758077299:0
@@ -289,7 +289,7 @@ temp/:1759463000:0
/share/CACHEDEV1_DATA/Container/dms/npm/data/nginx/redirection_host
/share/CACHEDEV1_DATA/Container/dms/npm/data/nginx/proxy_host
6.conf:1759595375:1789
5.conf:1759638121:1725
5.conf:1759640620:1725
7.conf:1759595375:4773
8.conf:1759595375:1295
4.conf.disabled:1759461427:1659
@@ -297,15 +297,15 @@ temp/:1759463000:0
/share/CACHEDEV1_DATA/Container/dms/npm/data/nginx/default_www
/share/CACHEDEV1_DATA/Container/dms/npm/data/nginx/custom
/share/CACHEDEV1_DATA/Container/dms/scripts
backup-mariadb.sh:1759638121:483
healthcheck.sh:1759638121:66
watch-qnap-ssl.sh:1759638121:316
backup_db.sh:1759638121:1968
backup-mariadb.sh:1759640620:483
healthcheck.sh:1759640620:66
watch-qnap-ssl.sh:1759640620:316
backup_db.sh:1759640620:1968
/share/CACHEDEV1_DATA/Container/dms/.syncing_db
/share/CACHEDEV1_DATA/Container/dms/.vscode
settings.json:1757985748:31
/share/CACHEDEV1_DATA/Container/dms/logs
backend/:1759638121:0
backend/:1759640620:0
frontend/:1757320861:0
nginx/:1757931149:0
phpmyadmin/:1757493691:0
@@ -341,42 +341,42 @@ n8nEventLog-3.log:1759541899:0
/share/CACHEDEV1_DATA/Container/dms/n8n/git
/share/CACHEDEV1_DATA/Container/dms/n8n/binaryData
/share/CACHEDEV1_DATA/Container/dms/frontend
app/:1759638121:0
app/:1759640620:0
Dockerfile:1759213359:4313
package.json:1759638121:1143
.dockerignore:1759638121:89
lib/:1759638121:0
package.json:1759640620:1143
.dockerignore:1759640620:89
lib/:1759640620:0
api/:1758331810:0
page.jsx:1759638121:27573
page.jsx:1759640620:27573
public/:1756542229:0
node_modules/:1759631884:0
components.json:1759635683:466
node_modules/:1759638752:0
package-lock.json:1759640727:266527
.next/:1759215523:0
.logs/:1757748438:0
postcss.config.js:1759638121:81
styles/:1759638121:0
tailwind.config.js:1759638121:2330
postcss.config.js:1759640620:81
styles/:1759640620:0
tailwind.config.js:1759640620:2330
components/:1758333756:0
.editorconfig:1759138259:147
.eslintrc.json:1759138259:384
.prettierrc.json:1759138259:207
Dockerfile.bak:1759198743:3846
/share/CACHEDEV1_DATA/Container/dms/frontend/components
ui/:1759638121:0
ui/:1759640620:0
/share/CACHEDEV1_DATA/Container/dms/frontend/components/ui
button.jsx:1759638121:1676
badge.jsx:1759638121:990
card.jsx:1759638121:1440
input.jsx:1759638121:688
tabs.jsx:1759638121:1543
progress.jsx:1759638121:667
dropdown-menu.jsx:1759638121:6359
tooltip.jsx:1759638121:1141
switch.jsx:1759638121:1039
button.jsx:1759640620:1676
badge.jsx:1759640620:990
card.jsx:1759640620:1440
input.jsx:1759640620:688
tabs.jsx:1759640620:1543
progress.jsx:1759640620:667
dropdown-menu.jsx:1759640620:6359
tooltip.jsx:1759640620:1141
switch.jsx:1759640620:1039
label.jsx:1759206357:539
alert.jsx:1759208266:1335
/share/CACHEDEV1_DATA/Container/dms/frontend/styles
global.css:1759638121:58
global.css:1759640620:58
/share/CACHEDEV1_DATA/Container/dms/frontend/.logs
/share/CACHEDEV1_DATA/Container/dms/frontend/.next
/share/CACHEDEV1_DATA/Container/dms/frontend/node_modules
@@ -457,14 +457,14 @@ eastasianwidth/:1759204684:0
is-number/:1759204684:0
strip-bom/:1759204684:0
yaml/:1759204690:0
@radix-ui/:1759634564:0
@radix-ui/:1759638753:0
@types/:1759204681:0
@unrs/:1759631884:0
string-width-cjs/:1759586283:0
tinyglobby/:1759204688:0
eslint-module-utils/:1759586283:0
tailwindcss/:1759586283:0
.package-lock.json:1759635707:279008
.package-lock.json:1759640728:266657
ecdsa-sig-formatter/:1759223641:0
class-variance-authority/:1759204689:0
clsx/:1759586285:0
@@ -559,6 +559,7 @@ glob/:1759204684:0
eslint-import-resolver-node/:1759204687:0
lodash.isinteger/:1759223641:0
jwa/:1759223641:0
js-cookie/:1759638753:0
react-dom/:1759204690:0
autoprefixer/:1759204690:0
eslint/:1759204691:0

View File

@@ -3880,6 +3880,17 @@ react-dom-test-utils.production.min.js:1759204690:12616
react-dom.development.js:1759204690:1029622
react-dom.production.min.js:1759204690:131685
react-dom.profiling.min.js:1759204690:141112
/share/CACHEDEV1_DATA/Container/dms/frontend/node_modules/js-cookie
LICENSE:1759638753:1118
index.js:1759638753:45
dist/:1759638753:0
package.json:1759638753:1785
README.md:1759638753:12387
/share/CACHEDEV1_DATA/Container/dms/frontend/node_modules/js-cookie/dist
js.cookie.js:1759638753:4189
js.cookie.min.js:1759638753:1731
js.cookie.min.mjs:1759638753:1428
js.cookie.mjs:1759638753:3475
/share/CACHEDEV1_DATA/Container/dms/frontend/node_modules/jwa
LICENSE:1759223641:1068
index.js:1759223641:6801

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>
+ );
+}

236
README.md
View File

@@ -1,6 +1,103 @@
# Document Management Sysytem (dms)
## บทบาท; คุณคือ Programmer และ Document Engineer ที่เชี่ยวชาญ
# 📝 Project Title: ocument Management System (DMS) Web Application
## Des
### 📌 1. Project Overview / Description
- ระบบ Document Management System (DMS)
- เป็นเว็บแอปพลิเคชันที่ออกแบบมาเพื่อจัดการเอกสารภายในองค์กรอย่างมีประสิทธิภาพ
- โดยมีฟังก์ชันหลักในการอัปโหลด จัดเก็บ ค้นหา แชร์ และควบคุมสิทธิ์การเข้าถึงเอกสาร
- ระบบนี้จะช่วยลดการใช้เอกสารกระดาษ เพิ่มความปลอดภัยในการจัดเก็บข้อมูล
- และเพิ่มความสะดวกในการทำงานร่วมกันระหว่างทีม
### 🎯 2. Objectives
- พัฒนาระบบที่สามารถจัดการเอกสารได้อย่างเป็นระบบ
- ลดความซ้ำซ้อนในการจัดเก็บเอกสาร
- เพิ่มความปลอดภัยในการเข้าถึงและจัดการเอกสาร
- รองรับการทำงานร่วมกันแบบออนไลน์
### 📦 3. Scope of Work
ระบบจะครอบคลุมฟีเจอร์หลักดังนี้:
- การลงทะเบียนและเข้าสู่ระบบผู้ใช้งาน
- การอัปโหลดและจัดเก็บเอกสารในรูปแบบต่าง ๆ (PDF, DOCX, XLSX ฯลฯ)
- การจัดหมวดหมู่และแท็กเอกสาร
- การค้นหาเอกสารด้วยคำสำคัญหรือฟิลเตอร์
- การกำหนดสิทธิ์การเข้าถึงเอกสาร (เช่น อ่านอย่างเดียว, แก้ไข, ลบ)
- การบันทึกประวัติการใช้งานเอกสาร (Audit Trail)
- การแจ้งเตือนเมื่อมีการเปลี่ยนแปลงเอกสาร
### 🛠️ 4. DMS Architecture Deep Dive (Backend + Frontend)
#### 4.0)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
#### 4.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`
---
- Frontend: Next.js (ESM) / React.js
- Backend: Node.js / Laravel
- Database: Mariadb / PostgreSQL
- Authentication: JWT
- xx
- Cloud Storage: QNAP
### 👥 Target Users
- พนักงานภายในองค์กร
- ผู้จัดการฝ่ายเอกสาร
- ผู้ดูแลระบบ IT
### 📈 Expected Outcomes
- ลดเวลาในการค้นหาเอกสารลงอย่างน้อย 50%
- ลดการใช้เอกสารกระดาษในองค์กร
- เพิ่มความปลอดภัยในการจัดเก็บข้อมูล
- รองรับการทำงานแบบ Remote Work
## บทบาท: คุณคือ Programmer และ Document Engineer ที่เชี่ยวชาญ
1. การพัฒนาเว็บแอป (Web Application Development)
2. Configuration of Container Station on QNAP
@@ -19,7 +116,7 @@
15. ภาษา SQL
16. RBAC
## 2. ระบบที่ใช้;
## 2. ระบบที่ใช้
## Server
@@ -134,3 +231,136 @@ git checkout -b feature/dashboard-update-251004
git add frontend/app/dashboard
git commit -m "feat(dashboard): เพิ่มส่วนจัดการ user"
git push -u origin feature/dashboard-update-251004
📘 Use Case: Upload Document
Actor: ผู้ใช้งานทั่วไป (Employee)
Description: ผู้ใช้งานสามารถอัปโหลดเอกสารเข้าสู่ระบบเพื่อจัดเก็บและใช้งานในภายหลัง
Preconditions: ผู้ใช้งานต้องเข้าสู่ระบบก่อน
Main Flow:
ผู้ใช้งานเลือกเมนู “อัปโหลดเอกสาร”
เลือกไฟล์จากเครื่องคอมพิวเตอร์
กรอกข้อมูลประกอบ เช่น ชื่อเอกสาร หมวดหมู่ แท็ก
กดปุ่ม “อัปโหลด”
ระบบบันทึกเอกสารและแสดงผลการอัปโหลดสำเร็จ
Postconditions: เอกสารถูกจัดเก็บในระบบและสามารถค้นหาได้
## 📘 Use Case:
### Search Document
Actor: ผู้ใช้งานทั่วไป
Description: ผู้ใช้งานสามารถค้นหาเอกสารจากระบบด้วยคำสำคัญหรือฟิลเตอร์
Preconditions: ผู้ใช้งานต้องเข้าสู่ระบบ
Main Flow:
ผู้ใช้งานกรอกคำค้นหรือเลือกฟิลเตอร์ (หมวดหมู่, วันที่, ผู้สร้าง)
กดปุ่ม “ค้นหา”
ระบบแสดงรายการเอกสารที่ตรงกับเงื่อนไข
Postconditions: ผู้ใช้งานสามารถเปิดดูหรือดาวน์โหลดเอกสารที่ค้นพบได้
### Share Document
Actor: ผู้ใช้งานทั่วไป
Description: ผู้ใช้งานสามารถแชร์เอกสารให้กับผู้ใช้งานอื่นในระบบ
Preconditions: ผู้ใช้งานต้องมีสิทธิ์ในการแชร์เอกสาร
Main Flow:
ผู้ใช้งานเลือกเอกสารที่ต้องการแชร์
กดปุ่ม “แชร์”
ระบุผู้รับและสิทธิ์การเข้าถึง (อ่าน/แก้ไข)
กด “ยืนยัน”
ระบบส่งการแจ้งเตือนไปยังผู้รับ
Postconditions: ผู้รับสามารถเข้าถึงเอกสารตามสิทธิ์ที่กำหนด
### Manage Access Rights
Actor: ผู้ดูแลระบบ (Admin)
Description: ผู้ดูแลระบบสามารถกำหนดสิทธิ์การเข้าถึงเอกสารให้กับผู้ใช้งาน
Preconditions: ผู้ดูแลระบบต้องเข้าสู่ระบบ
Main Flow:
ผู้ดูแลระบบเลือกเอกสาร
กด “จัดการสิทธิ์”
เลือกผู้ใช้งานและกำหนดสิทธิ์ (อ่าน, แก้ไข, ลบ)
กด “บันทึก”
Postconditions: สิทธิ์การเข้าถึงเอกสารถูกปรับตามที่กำหนด
### View Document History
Actor: ผู้ใช้งานทั่วไป / ผู้ดูแลระบบ
Description: ผู้ใช้งานสามารถดูประวัติการใช้งานเอกสาร เช่น การแก้ไข การดาวน์โหลด
Preconditions: ผู้ใช้งานต้องมีสิทธิ์เข้าถึงเอกสาร
Main Flow:
ผู้ใช้งานเปิดเอกสาร
เลือก “ดูประวัติ”
ระบบแสดงรายการกิจกรรมที่เกี่ยวข้องกับเอกสาร
Postconditions: ผู้ใช้งานสามารถตรวจสอบการเปลี่ยนแปลงย้อนหลังได้
## 🔄Workflow อัตโนมัติในระบบ DMS
### ✅ ประโยชน์ของ Workflow อัตโนมัติใน DMS
ลดภาระงานซ้ำ ๆ ของผู้ใช้งาน
เพิ่มความปลอดภัยและการควบคุมเอกสาร
เพิ่มความเร็วในการดำเนินงาน
ลดข้อผิดพลาดจากการทำงานด้วยมือ
### 🧩 1.Document Approval Workflow
กรณี: เมื่อมีการอัปโหลดเอกสารที่ต้องได้รับการอนุมัติจากหัวหน้า
ขั้นตอนอัตโนมัติ:
1. ผู้ใช้งานอัปโหลดเอกสารและเลือก “ต้องการอนุมัติ”
2. ระบบส่งแจ้งเตือนไปยังผู้อนุมัติ (เช่น หัวหน้าแผนก)
3. ผู้อนุมัติสามารถตรวจสอบและกด “อนุมัติ” หรือ “ปฏิเสธ”
4. ระบบบันทึกสถานะเอกสารและแจ้งผลกลับไปยังผู้ส่ง
### 📥 2. Auto Tagging & Categorization
กรณี: เอกสารที่อัปโหลดมีชื่อหรือเนื้อหาที่ตรงกับหมวดหมู่ที่กำหนดไว้
ขั้นตอนอัตโนมัติ:
เมื่ออัปโหลดเอกสาร ระบบวิเคราะห์ชื่อไฟล์หรือเนื้อหา
ระบบกำหนดหมวดหมู่และแท็กให้โดยอัตโนมัติ เช่น “ใบเสนอราคา” → หมวด “การเงิน”
ผู้ใช้งานสามารถแก้ไขได้หากต้องการ
### 🔐 3. Access Control Workflow
กรณี: เอกสารที่มีความลับสูงต้องจำกัดการเข้าถึง
ขั้นตอนอัตโนมัติ:
เมื่ออัปโหลดเอกสารที่มีคำว่า “ลับ” หรือ “Confidential”
ระบบกำหนดสิทธิ์เริ่มต้นให้เฉพาะผู้ใช้งานระดับผู้จัดการขึ้นไป
ระบบแจ้งเตือนผู้ดูแลระบบให้ตรวจสอบสิทธิ์เพิ่มเติม
### 📤 4. Expiry & Archiving Workflow
กรณี: เอกสารที่มีอายุการใช้งาน เช่น สัญญา หรือใบอนุญาต
ขั้นตอนอัตโนมัติ:
เมื่ออัปโหลดเอกสาร ผู้ใช้งานระบุวันหมดอายุ
ระบบแจ้งเตือนก่อนหมดอายุล่วงหน้า เช่น 30 วัน
เมื่อถึงวันหมดอายุ ระบบย้ายเอกสารไปยังหมวด “Archive” โดยอัตโนมัติ
### 📊 5. Audit Trail & Notification Workflow
กรณี: มีการแก้ไขหรือดาวน์โหลดเอกสารสำคัญ
ขั้นตอนอัตโนมัติ:
ทุกการกระทำกับเอกสาร (เปิด, แก้ไข, ลบ) จะถูกบันทึกใน Audit Log
หากเอกสารถูกแก้ไขโดยผู้ใช้งานที่ไม่ใช่เจ้าของ ระบบแจ้งเตือนเจ้าของเอกสารทันที

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

BIN
backend/backend_tree.txt Executable file

Binary file not shown.

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://lcbp3.np-dms.work,http://localhost:3000,http://127.0.0.1:3000"
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

View File

@@ -5,7 +5,11 @@
import { Sequelize } from "sequelize";
import { config } from "../config.js";
export const sequelize = new Sequelize(config.DB.NAME, config.DB.USER, config.DB.PASS, {
export const sequelize = new Sequelize(
config.DB.NAME,
config.DB.USER,
config.DB.PASS,
{
host: config.DB.HOST,
port: config.DB.PORT,
dialect: "mariadb",
@@ -13,91 +17,55 @@ export const sequelize = new Sequelize(config.DB.NAME, config.DB.USER, config.DB
dialectOptions: { timezone: "Z" },
define: { freezeTableName: true, underscored: false, timestamps: false },
pool: { max: 10, min: 0, idle: 10000 },
});
}
);
// --- 1. ประกาศตัวแปรสำหรับ Export Model ทั้งหมด ---
export let User, Role, Permission, Organization, Project, UserRole, RolePermission,
UserProjectRole, Correspondence, CorrespondenceVersion, Document, CorrDocumentMap,
Drawing, DrawingRevision, FileObject, RFA, RFARevision, RfaDrawingMap,
Transmittal, TransmittalItem, Volume, ContractDwg, SubCategory;
export let User = null;
export let Role = null;
export let Permission = null;
export let UserRole = null;
export let RolePermission = null;
if (process.env.ENABLE_SEQUELIZE === "1") {
// --- 2. สร้าง Object ของ Models ทั้งหมดที่จะโหลด ---
const modelsToLoad = {
User: await import("./models/User.js").catch(() => null),
Role: await import("./models/Role.js").catch(() => null),
Permission: await import("./models/Permission.js").catch(() => null),
Organization: await import("./models/Organization.js").catch(() => null),
Project: await import("./models/Project.js").catch(() => null),
UserRole: await import("./models/UserRole.js").catch(() => null),
RolePermission: await import("./models/RolePermission.js").catch(() => null),
UserProjectRole: await import("./models/UserProjectRole.js").catch(() => null),
Correspondence: await import("./models/Correspondence.js").catch(() => null),
CorrespondenceVersion: await import("./models/CorrespondenceVersion.js").catch(() => null),
Document: await import("./models/Document.js").catch(() => null),
CorrDocumentMap: await import("./models/CorrDocumentMap.js").catch(() => null),
Drawing: await import("./models/Drawing.js").catch(() => null),
DrawingRevision: await import("./models/DrawingRevision.js").catch(() => null),
FileObject: await import("./models/FileObject.js").catch(() => null),
RFA: await import("./models/RFA.js").catch(() => null),
RFARevision: await import("./models/RFARevision.js").catch(() => null),
RfaDrawingMap: await import("./models/RfaDrawingMap.js").catch(() => null),
Transmittal: await import("./models/Transmittal.js").catch(() => null),
TransmittalItem: await import("./models/TransmittalItem.js").catch(() => null),
Volume: await import("./models/Volume.js").catch(() => null),
ContractDwg: await import("./models/ContractDwg.js").catch(() => null),
SubCategory: await import("./models/SubCategory.js").catch(() => null),
};
// โหลดโมเดลแบบ 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);
// --- 3. Initialize Model ทั้งหมด ---
User = modelsToLoad.User?.default ? modelsToLoad.User.default(sequelize) : null;
Role = modelsToLoad.Role?.default ? modelsToLoad.Role.default(sequelize) : null;
Permission = modelsToLoad.Permission?.default ? modelsToLoad.Permission.default(sequelize) : null;
Organization = modelsToLoad.Organization?.default ? modelsToLoad.Organization.default(sequelize) : null;
Project = modelsToLoad.Project?.default ? modelsToLoad.Project.default(sequelize) : null;
UserRole = modelsToLoad.UserRole?.default ? modelsToLoad.UserRole.default(sequelize) : null;
RolePermission = modelsToLoad.RolePermission?.default ? modelsToLoad.RolePermission.default(sequelize) : null;
UserProjectRole = modelsToLoad.UserProjectRole?.default ? modelsToLoad.UserProjectRole.default(sequelize) : null;
Correspondence = modelsToLoad.Correspondence?.default ? modelsToLoad.Correspondence.default(sequelize) : null;
CorrespondenceVersion = modelsToLoad.CorrespondenceVersion?.default ? modelsToLoad.CorrespondenceVersion.default(sequelize) : null;
Document = modelsToLoad.Document?.default ? modelsToLoad.Document.default(sequelize) : null;
CorrDocumentMap = modelsToLoad.CorrDocumentMap?.default ? modelsToLoad.CorrDocumentMap.default(sequelize) : null;
Drawing = modelsToLoad.Drawing?.default ? modelsToLoad.Drawing.default(sequelize) : null;
DrawingRevision = modelsToLoad.DrawingRevision?.default ? modelsToLoad.DrawingRevision.default(sequelize) : null;
FileObject = modelsToLoad.FileObject?.default ? modelsToLoad.FileObject.default(sequelize) : null;
RFA = modelsToLoad.RFA?.default ? modelsToLoad.RFA.default(sequelize) : null;
RFARevision = modelsToLoad.RFARevision?.default ? modelsToLoad.RFARevision.default(sequelize) : null;
RfaDrawingMap = modelsToLoad.RfaDrawingMap?.default ? modelsToLoad.RfaDrawingMap.default(sequelize) : null;
Transmittal = modelsToLoad.Transmittal?.default ? modelsToLoad.Transmittal.default(sequelize) : null;
TransmittalItem = modelsToLoad.TransmittalItem?.default ? modelsToLoad.TransmittalItem.default(sequelize) : null;
Volume = modelsToLoad.Volume?.default ? modelsToLoad.Volume.default(sequelize) : null;
ContractDwg = modelsToLoad.ContractDwg?.default ? modelsToLoad.ContractDwg.default(sequelize) : null;
SubCategory = modelsToLoad.SubCategory?.default ? modelsToLoad.SubCategory.default(sequelize) : null;
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 (User && Role && Permission && UserRole && RolePermission) {
User.belongsToMany(Role, {
through: UserRole,
foreignKey: "user_id",
otherKey: "role_id",
});
Role.belongsToMany(User, {
through: UserRole,
foreignKey: "role_id",
otherKey: "user_id",
});
// --- 4. สร้างความสัมพันธ์ (Associations) ---
const loadedModels = { User, Role, Permission, Organization, Project, UserRole, RolePermission,
UserProjectRole, Correspondence, CorrespondenceVersion, Document, CorrDocumentMap,
Drawing, DrawingRevision, FileObject, RFA, RFARevision, RfaDrawingMap,
Transmittal, TransmittalItem, Volume, ContractDwg, SubCategory };
for (const modelName in loadedModels) {
if (loadedModels[modelName] && loadedModels[modelName].associate) {
loadedModels[modelName].associate(loadedModels);
}
}
Role.belongsToMany(Permission, {
through: RolePermission,
foreignKey: "role_id",
otherKey: "permission_id",
});
Permission.belongsToMany(Role, {
through: RolePermission,
foreignKey: "permission_id",
otherKey: "role_id",
});
}
}
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

@@ -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" });

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";

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";

View File

@@ -1,99 +1,55 @@
// File: backend/src/routes/users.js
import { Router } from 'express';
import { User, Role } from '../db/sequelize.js';
import { authJwt } from "../middleware/authJwt.js";
import { loadPrincipalMw } from "../middleware/loadPrincipal.js"; // แก้ไข: import ให้ถูกต้อง
import { requirePerm } from '../middleware/requirePerm.js';
import { hashPassword } from '../utils/passwords.js';
// FILE: backend/src/routes/users.js
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";
const router = Router();
const r = Router();
// Middleware Chain ที่ถูกต้อง 100%
router.use(authJwt(), loadPrincipalMw());
// GET /api/users
router.get('/', requirePerm('users.view'), async (req, res, next) => {
try {
const users = await User.findAll({
attributes: { exclude: ['password_hash'] },
include: [{ model: Role, attributes: ['id', 'name'], through: { attributes: [] } }],
order: [['username', 'ASC']]
});
res.json(users);
} catch (error) { next(error); }
// 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,
});
});
// POST /api/users
router.post('/', requirePerm('users.manage'), 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' });
// USERS LIST (ORG scope) — admin.access
r.get(
"/",
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
);
}
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,
created_by: req.principal.user_id,
updated_by: req.principal.user_id,
org_id: req.principal.org_ids[0] || null,
});
res.json(rows);
}
);
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', requirePerm('users.manage'), 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;
user.updated_by = req.principal.user_id;
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
router.delete('/:id', requirePerm('users.manage'), 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;
user.updated_by = req.principal.user_id;
await user.save();
res.status(204).send();
} catch (error) { next(error); }
});
export default router;
export default r;

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

@@ -1,84 +0,0 @@
// File: frontend/app/(protected)/_components/SideNavigation.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 SideNavigation({ 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>
</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',
// ตรวจสอบ Path ปัจจุบันเพื่อ active เมนู
pathname === href || (href !== '/dashboard' && 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.</CardDescription>
</CardHeader>
<CardContent className="p-2 pt-0 md:p-4 md:pt-0">
<Button size="sm" className="w-full">Contact Support</Button>
</CardContent>
</Card>
</div>
</div>
);
}

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

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

@@ -1,54 +1,71 @@
// File: frontend/app/(protected)/layout.jsx
'use client';
import { cookies } from "next/headers"; // 1. ยังคงใช้ฟังก์ชันฝั่ง Server
import { redirect } from "next/navigation";
import { Users } from 'lucide-react';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth';
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';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
// 2. Import SideNavigation Component ที่เราสร้างขึ้นมาใหม่
import { SideNavigation } from "./_components/SideNavigation";
// NOTE: ให้ชี้ไปยังไฟล์จริงของคุณ
// เดิมบางโปรเจ็กต์ใช้ "../_components/SideNavigation"
// ที่นี่อ้าง absolute import ตาม tsconfig/baseUrl
import { SideNavigation } from '@/app/_components/SideNavigation';
// (ฟังก์ชัน fetchSession และตัวแปรอื่นๆ เหมือนเดิม)
const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
export default function ProtectedLayout({ children }) {
const { user, isAuthenticated, loading, logout } = useAuth();
const router = useRouter();
async function fetchSession() {
const cookieStore = cookies();
const token = cookieStore.get("access_token")?.value;
if (!token) return null;
try {
const res = await fetch(`${API_BASE}/api/auth/me`, {
headers: { Authorization: `Bearer ${token}` },
cache: "no-store",
});
if (!res.ok) return null;
return await res.json();
} catch (error) {
console.error("Failed to fetch session:", error);
return null;
// Guard ฝั่ง client: ถ้าไม่ได้ล็อกอิน ให้เด้งไป /login
useEffect(() => {
if (!loading && !isAuthenticated) {
router.push('/login');
}
}, [loading, isAuthenticated, router]);
// ระหว่างรอเช็คสถานะ หรือยังไม่ 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 }) {
// 3. ดึงข้อมูล Session บน Server
const session = await fetchSession();
if (!session?.user) {
redirect("/login");
}
const handleLogout = async () => {
try {
await logout();
} finally {
router.replace('/login');
}
};
return (
<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">
{/* 4. ใช้ SideNavigation Component และส่งข้อมูล user เป็น props */}
<SideNavigation user={session.user} />
<SideNavigation user={user} />
</aside>
{/* 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 w-full">
{/* Optional: Add a search bar */}
</div>
<div className="flex-1" />
<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">
@@ -57,21 +74,22 @@ export default async function ProtectedLayout({ children }) {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>{session.user.username || 'My Account'}</DropdownMenuLabel>
<DropdownMenuLabel>{user?.username || 'My Account'}</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem>Settings</DropdownMenuItem>
<DropdownMenuItem>Profile Settings</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem>
{/* ปุ่ม Logout จริงๆ ควรอยู่ใน Client Component ที่เรียกใช้ useAuth() hook */}
Logout
<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

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

@@ -1,4 +1,4 @@
//File: frontend/app/(protected)/_components/navigation.jsx
//File: frontend/app/_components/navigation.jsx
'use client'; // <-- 1. Client Component
import Link from 'next/link';

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>
);
}
}

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

@@ -17,7 +17,7 @@ export default function HomePage() {
</TabsList>
<TabsContent value="overview">
<div className="grid md:grid-cols-3 gap-4 mt-4">
<div className="grid gap-4 mt-4 md:grid-cols-3">
<Card>
<CardHeader>
<CardTitle>📑 RFAs</CardTitle>

18
frontend/components.json Executable file
View File

@@ -0,0 +1,18 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": false,
"tailwind": {
"config": "tailwind.config.js",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"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

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

View File

@@ -0,0 +1,24 @@
"use client"
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { Check } from "lucide-react"
import { cn } from "@/lib/utils"
const Checkbox = React.forwardRef(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}>
<CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")}>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName
export { Checkbox }

View File

@@ -0,0 +1,96 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
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} />
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.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}>
{children}
<DialogPrimitive.Close
className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}) => (
<div
className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)}
{...props} />
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}) => (
<div
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
{...props} />
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
{...props} />
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props} />
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}

0
frontend/components/ui/dropdown-menu.jsx Normal file → Executable file
View File

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

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

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

View File

@@ -0,0 +1,40 @@
"use client"
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
const ScrollArea = React.forwardRef(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
{...props}>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
const ScrollBar = React.forwardRef(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
className
)}
{...props}>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
export { ScrollArea, ScrollBar }

121
frontend/components/ui/select.jsx Executable file
View File

@@ -0,0 +1,121 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown, ChevronUp } from "lucide-react"
import { cn } from "@/lib/utils"
const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value
const SelectTrigger = React.forwardRef(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
const SelectScrollUpButton = React.forwardRef(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn("flex cursor-default items-center justify-center py-1", className)}
{...props}>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
const SelectScrollDownButton = React.forwardRef(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn("flex cursor-default items-center justify-center py-1", className)}
{...props}>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
))
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName
const SelectContent = React.forwardRef(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover text-popover-foreground shadow-md 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-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-select-content-transform-origin]",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn("p-1", position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]")}>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
const SelectLabel = React.forwardRef(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("px-2 py-1.5 text-sm font-semibold", className)}
{...props} />
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
const SelectItem = React.forwardRef(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}>
<span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
const SelectSeparator = React.forwardRef(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props} />
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
}

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

View File

@@ -0,0 +1,86 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Table = React.forwardRef(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props} />
</div>
))
Table.displayName = "Table"
const TableHeader = React.forwardRef(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
))
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props} />
))
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)}
{...props} />
))
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props} />
))
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props} />
))
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn(
"p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props} />
))
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props} />
))
TableCaption.displayName = "TableCaption"
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

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

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

96
frontend/docker shadcn.yml Executable file
View File

@@ -0,0 +1,96 @@
docker run --rm -it \
-v /share/Container/dms/frontend:/app \
-w /app \
-e CI=1 \
node:20-alpine sh -lc '
set -eu
echo "1) ตรวจและแก้ package.json → next/react/react-dom ต้องอยู่ใน dependencies + scripts ครบ"
test -f package.json || { echo "❌ ไม่พบ package.json ที่ /app"; exit 1; }
node -e "
const fs=require(\"fs\");
const p=JSON.parse(fs.readFileSync(\"package.json\",\"utf8\"));
p.dependencies=p.dependencies||{};
p.devDependencies=p.devDependencies||{};
p.scripts=p.scripts||{};
let changed=false;
for(const k of [\"next\",\"react\",\"react-dom\"]){
if(p.devDependencies[k]){ p.dependencies[k]=p.devDependencies[k]; delete p.devDependencies[k]; changed=true; }
if(!p.dependencies[k]){ p.dependencies[k]=\"latest\"; changed=true; }
}
if(!p.scripts.dev){ p.scripts.dev=\"next dev\"; changed=true; }
if(!p.scripts.build){ p.scripts.build=\"next build\"; changed=true; }
if(!p.scripts.start){ p.scripts.start=\"next start\"; changed=true; }
if(changed){ fs.writeFileSync(\"package.json\",JSON.stringify(p,null,2)); console.log(\"package.json patched\"); }
"
npm i
echo "2) โครง Next.js: app/ หรือ src/app/ + layout.jsx + globals.css"
APPDIR="app"; [ -d src/app ] && APPDIR="src/app"
mkdir -p "$APPDIR"
[ -f "$APPDIR/globals.css" ] || printf "%s\n%s\n%s\n" "@tailwind base;" "@tailwind components;" "@tailwind utilities;" > "$APPDIR/globals.css"
if [ ! -f "$APPDIR/layout.jsx" ] && [ ! -f "$APPDIR/layout.tsx" ]; then
cat > "$APPDIR/layout.jsx" <<EOF
import "./globals.css";
export default function RootLayout({ children }) {
return (<html lang="th"><body>{children}</body></html>);
}
EOF
fi
grep -q "import \"./globals.css\"" "$APPDIR/layout.jsx" 2>/dev/null || sed -i "1i import \"./globals.css\";" "$APPDIR/layout.jsx" 2>/dev/null || true
[ -f "$APPDIR/page.jsx" ] || [ -f "$APPDIR/page.tsx" ] || echo '\''export default function Page(){return <main className="p-6">OK</main>}'\'' > "$APPDIR/page.jsx"
echo "3) สร้าง/อัปเดตไฟล์ config ที่ CLI ต้องมี: jsconfig, postcss, tailwind, next.config"
[ -f jsconfig.json ] || cat > jsconfig.json <<JSON
{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["./*"] } } }
JSON
[ -f postcss.config.cjs ] || echo "module.exports={plugins:{tailwindcss:{},autoprefixer:{}}}" > postcss.config.cjs
[ -f tailwind.config.js ] || npx tailwindcss init -p
grep -q "content:" tailwind.config.js || \
sed -i "s|module.exports = {|module.exports = {\n content: [\"./$APPDIR/**/*.{js,jsx,ts,tsx,mdx}\", \"./components/**/*.{js,jsx,ts,tsx,mdx}\", \"./pages/**/*.{js,jsx,ts,tsx,mdx}\", \"./src/**/*.{js,jsx,ts,tsx,mdx}\"],|g" tailwind.config.js
grep -q "tailwindcss-animate" tailwind.config.js || \
sed -i '\''s|plugins: \[|plugins: [require("tailwindcss-animate"), |; s|plugins: \[\]|plugins: [require("tailwindcss-animate")]|'\'' tailwind.config.js
# next.config (บางเวอร์ชัน CLI เช็คไฟล์นี้ด้วย)
if [ ! -f next.config.js ] && [ ! -f next.config.mjs ]; then
cat > next.config.js <<EOF
/** @type {import('next').NextConfig} */
const nextConfig = { reactStrictMode: true };
module.exports = nextConfig;
EOF
fi
echo "4) components.json (คงของเดิม ถ้าไม่มีค่อยสร้าง)"
if [ ! -f components.json ]; then
TYPESCRIPT=false; [ -f tsconfig.json ] && TYPESCRIPT=true
TAILWIND_FILE="tailwind.config.js"; [ -f tailwind.config.ts ] && TAILWIND_FILE="tailwind.config.ts"
cat > components.json <<EOF
{
"\$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": true,
"tsx": $TYPESCRIPT,
"tailwind": {
"config": "$TAILWIND_FILE",
"css": "$APPDIR/globals.css",
"baseColor": "slate",
"cssVariables": true
},
"aliases": { "components": "@/components", "utils": "@/lib/utils" }
}
EOF
fi
echo "5) ติดตั้ง dev deps tailwind/postcss (idempotent)"
npm i -D tailwindcss postcss autoprefixer tailwindcss-animate >/dev/null 2>&1 || true
echo "6) init (force) — ตอนนี้ควรผ่านการตรวจจับแล้ว"
npx shadcn@latest init -y -f --no-src-dir
echo "✅ เสร็จ — ถ้าต้องการเพิ่มคอมโพเนนต์ต่อ:"
echo "npx shadcn@latest add -y dialog alert-dialog dropdown-menu checkbox scroll-area tabs tooltip switch button label input card badge progress tabs"
'

70
frontend/docker-compose.yml Executable file
View File

@@ -0,0 +1,70 @@
# File: frontend/docker-compose.yml
# DMS Container v0_8_0 แยก service/ lcbp3-frontend
x-restart: &restart_policy
restart: unless-stopped
x-logging: &default_logging
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "5"
volumes:
frontend_node_modules:
frontend_next:
frontend_next_cache:
services:
frontend:
<<: [*restart_policy, *default_logging]
image: dms-frontend:dev
# pull_policy: never # <-- FINAL FIX ADDED HERE
container_name: dms_frontend
stdin_open: true
tty: true
# user: "node"
# user: "1000:1000"
user: "0:0"
# user: "${PUID:-1000}:${PGID:-1000}"
working_dir: /app
deploy:
resources:
limits:
cpus: "2.0"
memory: 2G
environment:
TZ: "Asia/Bangkok"
NODE_ENV: "development"
# NEXT_PUBLIC_API_BASE: "/api"
CHOKIDAR_USEPOLLING: "1"
CHOKIDAR_INTERVAL: "300"
WATCHPACK_POLLING: "true"
NEXT_TELEMETRY_DISABLED: "1"
NEXT_PUBLIC_API_BASE: "https://lcbp3.np-dms.work"
NEXT_PUBLIC_AUTH_MODE: "cookie"
NEXT_PUBLIC_DEBUG_AUTH: "1"
INTERNAL_API_BASE: "http://backend:3001"
JWT_ACCESS_SECRET: "9a6d8705a6695ab9bae4ca1cd46c72a6379aa72404b96e2c5b59af881bb55c639dd583afdce5a885c68e188da55ce6dbc1fb4aa9cd4055ceb51507e56204e4ca"
JWT_REFRESH_SECRET: "743e798bb10d6aba168bf68fc3cf8eff103c18bd34f1957a3906dc87987c0df139ab72498f2fe20d6c4c580f044ccba7d7bfa4393ee6035b73ba038f28d7480c"
expose:
- "3000"
networks:
lcbp3: {}
volumes:
- "/share/Container/dms/frontend:/app:rw"
- "frontend_node_modules:/app/node_modules"
- "frontend_next_cache:/app/.next/cache"
#- "/share/Container/dms/frontend/node_modules:/app/node_modules"
- "frontend_next:/app/.next"
- "/share/Container/dms/logs/frontend:/app/.logs"
healthcheck:
test:
[
"CMD-SHELL",
'wget -qO- http://127.0.0.1:3000/health | grep -q ''"ok":true''',
]
interval: 15s
timeout: 5s
retries: 30
networks:
lcbp3:
external: true

BIN
frontend/frontend_tree.txt Executable file

Binary file not shown.

8
frontend/jsconfig.json Executable file
View File

@@ -0,0 +1,8 @@
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
}
}

58
frontend/lib/AuthContext.jsx Executable file
View File

@@ -0,0 +1,58 @@
// frontend/context/AuthContext.jsx
'use client';
import { createContext, useState, useContext, useEffect } from 'react';
import { api } from '@/lib/api';
import { cookieDriver } from '@/app/_auth/drivers/cookieDriver';
const AuthContext = createContext(null);
const COOKIE_NAME = "access_token";
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const initializeAuth = async () => {
const token = cookieDriver.get(COOKIE_NAME);
if (token) {
try {
api.defaults.headers.Authorization = `Bearer ${token}`;
const response = await api.get('/auth/me');
setUser(response.data.user || response.data);
} catch (error) {
cookieDriver.remove(COOKIE_NAME);
delete api.defaults.headers.Authorization;
}
}
setLoading(false);
};
initializeAuth();
}, []);
const login = async (credentials) => {
const response = await api.post('/auth/login', credentials);
const { token, user } = response.data;
cookieDriver.set(COOKIE_NAME, token, { expires: 7 });
api.defaults.headers.Authorization = `Bearer ${token}`;
setUser(user);
return user;
};
const logout = () => {
cookieDriver.remove(COOKIE_NAME);
delete api.defaults.headers.Authorization;
setUser(null);
window.location.href = '/login';
};
return (
<AuthContext.Provider value={{ user, isAuthenticated: !!user, loading, login, logout }}>
{!loading && children}
</AuthContext.Provider>
);
}
export const useAuth = () => {
return useContext(AuthContext);
};

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

87
frontend/lib/auth copy.js Normal file → Executable file
View File

@@ -1,79 +1,34 @@
<<<<<<< HEAD
// frontend/lib/auth.js
import { cookies } from "next/headers";
const COOKIE_NAME = "access_token";
const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
/**
* Server-side session fetcher (ใช้ใน Server Components/Layouts)
* - อ่านคุกกี้แบบ async: await cookies()
* - ถ้าไม่มี token → return null
* - ถ้ามี → เรียก /api/auth/me ที่ backend เพื่อตรวจสอบ
* Server-side session fetcher
*/
export async function getSession() {
// ✅ ต้อง await
const cookieStore = await cookies();
const cookieStore = cookies();
const token = cookieStore.get(COOKIE_NAME)?.value;
if (!token) return null;
// เรียก backend ตรวจ session (ปรับ endpoint ให้ตรงของคุณ)
const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE}/api/auth/me`, {
// ส่งต่อคุกกี้ไป backend (เลือกอย่างใดอย่างหนึ่ง)
// วิธี A: ส่ง header Cookie โดยตรง
headers: { Cookie: `${COOKIE_NAME}=${token}` },
// วิธี B: ถ้า proxy ผ่าน nginx ในโดเมนเดียวกัน ใช้ credentials รวมคุกกี้อัตโนมัติได้
// credentials: "include",
cache: "no-store",
});
try {
const res = await fetch(`${API_BASE}/api/auth/me`, {
headers: { Authorization: `Bearer ${token}` },
cache: "no-store",
});
if (!res.ok) return null;
const data = await res.json();
// คาดหวังโครงสร้าง { user, permissions } จาก backend
return {
user: data.user,
permissions: data.permissions || [],
token,
};
}
=======
// frontend/lib/auth.js
import { cookies } from "next/headers";
const COOKIE_NAME = "access_token";
/**
* Server-side session fetcher (ใช้ใน Server Components/Layouts)
* - อ่านคุกกี้แบบ async: await cookies()
* - ถ้าไม่มี token → return null
* - ถ้ามี → เรียก /api/auth/me ที่ backend เพื่อตรวจสอบ
*/
export async function getSession() {
// ✅ ต้อง await
const cookieStore = await cookies();
const token = cookieStore.get(COOKIE_NAME)?.value;
if (!token) return null;
// เรียก backend ตรวจ session (ปรับ endpoint ให้ตรงของคุณ)
const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE}/api/auth/me`, {
// ส่งต่อคุกกี้ไป backend (เลือกอย่างใดอย่างหนึ่ง)
// วิธี A: ส่ง header Cookie โดยตรง
headers: { Cookie: `${COOKIE_NAME}=${token}` },
// วิธี B: ถ้า proxy ผ่าน nginx ในโดเมนเดียวกัน ใช้ credentials รวมคุกกี้อัตโนมัติได้
// credentials: "include",
cache: "no-store",
});
if (!res.ok) return null;
const data = await res.json();
// คาดหวังโครงสร้าง { user, permissions } จาก backend
return {
user: data.user,
permissions: data.permissions || [],
token,
};
}
>>>>>>> 71fc7eee (backend: Mod)
if (!res.ok) return null;
const data = await res.json();
return {
user: data.user,
permissions: data.permissions || data.perms || [],
token,
};
} catch (error) {
console.error("Error fetching session:", error);
return null;
}
}

42
frontend/lib/auth-server.js Executable file
View File

@@ -0,0 +1,42 @@
// File: frontend/lib/auth-server.js
// frontend/lib/auth-server.js
import 'server-only';
import { cookies } from 'next/headers';
export function getAccessToken() {
const cookieStore = cookies();
return cookieStore.get('access_token')?.value ?? null;
}
function buildCookieHeader() {
const store = cookies();
return store.getAll().map(c => `${c.name}=${c.value}`).join('; ');
}
export async function getSession() {
const token = getAccessToken();
if (!token) return null;
try {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE}/api/auth/me`, {
method: 'GET',
headers: { cookie: buildCookieHeader(), accept: 'application/json' },
cache: 'no-store',
});
if (!res.ok) return null;
const data = await res.json();
const user = data?.user ?? data; // รองรับทั้ง {user:{...}} หรือส่งตรง
return { user, token };
} catch {
return null;
}
}
export async function requireSession() {
const session = await getSession();
if (!session) {
const { redirect } = await import('next/navigation');
redirect('/login');
}
return session;
}

87
frontend/lib/auth.js Normal file → Executable file
View File

@@ -1,82 +1,41 @@
// frontend/lib/auth.js
// frontend/lib/auth.js
'use client';
import { createContext, useState, useContext, useEffect } from 'react';
import api from './api';
// 1. Import cookieDriver ที่คุณมีอยู่แล้ว ซึ่งเป็นวิธีที่ถูกต้อง
import { cookieDriver } from '@/app/_auth/drivers/cookieDriver';
import { createContext, useContext, useEffect, useState, useCallback } from "react";
const AuthContext = createContext(null);
const COOKIE_NAME = "access_token";
const AuthContext = createContext({
user: null,
isAuthenticated: false,
loading: true,
logout: () => {},
});
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const initializeAuth = async () => {
// 2. อ่าน token จาก cookie ด้วย cookieDriver.get()
const token = cookieDriver.get(COOKIE_NAME);
if (token) {
try {
api.defaults.headers.Authorization = `Bearer ${token}`;
// สมมติว่ามี endpoint /auth/me สำหรับดึงข้อมูลผู้ใช้
const response = await api.get('/auth/me');
setUser(response.data.user || response.data); // รองรับทั้งสองรูปแบบ
} catch (error) {
console.error("Failed to initialize auth from cookie:", error);
cookieDriver.remove(COOKIE_NAME);
delete api.defaults.headers.Authorization;
}
}
setLoading(false);
};
initializeAuth();
fetch("/api/auth/me", { credentials: "include" })
.then((res) => (res.ok ? res.json() : null))
.then((data) => setUser(data?.user ?? null))
.finally(() => setLoading(false));
}, []);
const login = async (credentials) => {
const response = await api.post('/auth/login', credentials);
const { token, user } = response.data;
// 3. ตั้งค่า token ใน cookie ด้วย cookieDriver.set()
cookieDriver.set(COOKIE_NAME, token, { expires: 7, secure: true, sameSite: 'strict' });
api.defaults.headers.Authorization = `Bearer ${token}`;
setUser(user);
return user;
};
const logout = () => {
// 4. ลบ token ออกจาก cookie ด้วย cookieDriver.remove()
cookieDriver.remove(COOKIE_NAME);
delete api.defaults.headers.Authorization;
setUser(null);
window.location.href = '/login';
};
const value = {
user,
isAuthenticated: !!user,
loading,
login,
logout
};
const logout = useCallback(async () => {
try {
await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
} finally {
window.location.href = "/login";
}
}, []);
return (
<AuthContext.Provider value={value}>
{!loading && children}
<AuthContext.Provider value={{ user, isAuthenticated: !!user, loading, logout }}>
{children}
</AuthContext.Provider>
);
}
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
export function useAuth() {
return useContext(AuthContext);
}

0
frontend/lib/rbac.js Normal file → Executable file
View File

31
frontend/lib/session.js Executable file
View File

@@ -0,0 +1,31 @@
// frontend/lib/session.js
import { cookies } from "next/headers";
const COOKIE_NAME = "access_token";
const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
/**
* Server-side function to get the current session from the request cookies.
* This can only be used in Server Components, Server Actions, or Route Handlers.
*/
export async function getSession() {
const cookieStore = cookies();
const token = cookieStore.get(COOKIE_NAME)?.value;
if (!token) return null;
try {
const res = await fetch(`${API_BASE}/api/auth/me`, {
headers: { Authorization: `Bearer ${token}` },
cache: "no-store",
});
if (!res.ok) return null;
const data = await res.json();
return data; // Expects { user, permissions, ... }
} catch (error) {
console.error("Error fetching session:", error);
return null;
}
}

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