Compare commits

...

16 Commits

Author SHA1 Message Date
6e919fde45 check lần 2 2026-11-30 15:38:49 +07:00
1b1012dbed check tên miền 2026-11-30 15:37:55 +07:00
03a481f20d update export 2026-11-11 10:48:31 +07:00
00122e5b4a update export request 2026-11-10 11:01:24 +07:00
63866b14a1 update dasboard ,noti 2026-11-04 09:54:17 +07:00
ea6768f90d Stop tracking docs directory 2026-11-02 15:14:42 +07:00
a41bd9c193 Ignore docs directory 2026-11-02 15:13:17 +07:00
6a872e8c8b bom 2026-11-02 15:09:59 +07:00
c441c809ca fix domain 2026-11-02 10:19:45 +07:00
0dc83be4e7 quản lí robot 2026-10-19 15:21:04 +07:00
2be2e075a0 gititnore 2026-10-14 09:26:57 +07:00
533923076c xuất excel 2026-10-14 09:10:37 +07:00
dff0d32912 update pass 2026-09-30 10:09:08 +07:00
3201a18fd4 update quản lí dự án 2026-09-23 15:54:40 +07:00
bd8ba94301 fix UI 2026-09-23 15:14:54 +07:00
cdaa56febd fix - ASS-OLD 2026-09-23 09:59:41 +07:00
56 changed files with 7655 additions and 2828 deletions

View File

@@ -20,8 +20,8 @@ DATA_ENCRYPTION_SECRET=replace-with-at-least-32-random-bytes
BCRYPT_ROUNDS=12
# Public HTTPS origin used by email links, CORS and secure cookies.
APP_BASE_URL=https://accmanager.example.internal
CORS_ALLOWED_ORIGINS=https://accmanager.example.internal
APP_BASE_URL=https://robot.dvex.io.vn
CORS_ALLOWED_ORIGINS=https://robot.dvex.io.vn
COOKIE_SECURE=true
TRUST_PROXY_HOPS=1
SESSION_TTL_HOURS=12
@@ -44,5 +44,5 @@ SMTP_FROM=
EMAIL_VERIFY_TOKEN_TTL_MINUTES=30
PASSWORD_RESET_TOKEN_TTL_MINUTES=30
# Maximum size for each uploaded PDF document (1-100 MB).
# Maximum size for each uploaded document (1-100 MB), including robot attachments.
DOCUMENT_MAX_FILE_SIZE_MB=25

6
.gitignore vendored
View File

@@ -7,3 +7,9 @@ docs-output
scripts
.codex-server.err.log
.codex-server.out.log
tmp
outputs
test/
tools
output
docs

View File

@@ -1,34 +0,0 @@
# Thay dữ liệu tài sản, giữ lịch sử mượn trả
Chức năng **Xóa danh mục hiện tại** đưa các tài sản hiện tại vào dữ liệu cũ. Phiếu mượn, phiếu trả, các lần trả một phần, danh sách người đang mượn và lịch sử xuất/hư hỏng/thanh lý vẫn được giữ.
## Các bước thực hiện
1. Sao lưu cơ sở dữ liệu SQL Server trước khi thay dữ liệu. Triển khai bản ứng dụng có chức năng lưu trữ tài sản này trước khi thao tác xóa.
2. Đăng nhập bằng tài khoản **Admin** hoặc **Quản lý tài sản**. Mở **Quản lý tài sản** → **Xóa danh mục hiện tại**, đọc nội dung rồi xác nhận. Thao tác áp dụng cho toàn bộ danh mục hiện tại, kể cả tài sản ở trang khác hoặc đang bị bộ lọc ẩn.
3. Upload file tài sản mới bằng chức năng nhập Excel hiện có. Mã tài sản được phép trùng với mã trong dữ liệu cũ. Bản ghi mới có tồn kho riêng; lịch sử cũ tiếp tục gắn với bản ghi cũ.
4. Mở **Mượn/Trả tài sản**, chọn bộ lọc **Đơn → Còn đang mượn**. Chọn thêm **Tài sản → Tài sản cũ** nếu chỉ muốn xem các phiếu của danh mục đã xóa. Số lượng còn mượn bằng số đã mượn trừ số đã được xác nhận trả. Đơn trả đang chờ duyệt chưa được trừ.
5. Mở **Tài sản cũ còn mượn** để đối chiếu cả người mượn được nhập từ Excel hoặc ghi khi xuất trực tiếp mà chưa có phiếu mượn riêng. Màn hình **Tài sản tôi đang mượn** cũng giữ các tài sản cũ còn đang mượn.
## Xử lý mượn trả sau khi thay dữ liệu
- Phiếu mượn cũ vẫn xem được lịch sử và tạo/duyệt đơn trả theo luồng hiện có. Trả một phần vẫn nằm trong danh sách còn đang mượn.
- Việc trả tài sản cũ cập nhật bản ghi và lịch sử cũ. Muốn đưa số lượng này vào danh mục mới, đối chiếu rồi nhập kho mới riêng; hệ thống không tự ghép chỉ vì trùng mã.
- Tài sản cũ không được sửa hoặc xuất/mượn thêm. Đơn mượn cũ còn chờ xử lý không được duyệt; người quản lý có thể từ chối đơn đó.
- Xóa một tài sản hoặc **Xóa đã chọn** cũng giữ lịch sử theo cùng cơ chế.
Không dùng `DELETE`/`TRUNCATE` bảng tài sản, xóa các bảng mượn trả, hoặc tạo lại database để làm trống danh mục. Chức năng trong giao diện giữ bản ghi cũ để tiếp tục theo dõi số lượng chưa trả. Dữ liệu đã bị xóa bởi phiên bản trước chỉ có thể lấy lại từ bản sao lưu phù hợp.
## Triển khai
Ứng dụng tự chạy migration khi khởi động: thêm trạng thái lưu trữ, cho phép tái sử dụng mã tài sản trong danh mục mới và bảo vệ các liên kết lịch sử khỏi xóa dây chuyền. Migration không tự xóa hoặc lưu trữ tài sản nào. Nếu migration lỗi, ứng dụng dừng khởi động để người triển khai kiểm tra log.
Build/push image mới, cập nhật `DOCKER_IMAGE` trên máy chủ, rồi chạy:
```bash
docker compose --env-file .env -f docker-compose.image.yml pull accmanager
docker compose --env-file .env -f docker-compose.image.yml up -d accmanager
docker compose --env-file .env -f docker-compose.image.yml logs --tail=100 accmanager
```
Kiểm tra ứng dụng khởi động thành công và có nút **Xóa danh mục hiện tại** trước khi thay dữ liệu.

View File

@@ -1,71 +0,0 @@
# Dùng AccManager qua mạng nội bộ khi tên miền hết hạn
Máy chủ hiện tại vẫn chạy tại `172.20.235.176`. Có thể truy cập tạm bằng cách ánh xạ tên `accrobot.pnkr.asia` tới IP này trong file `hosts` của từng máy Windows. Trình duyệt vẫn mở `https://accrobot.pnkr.asia`, nhưng kết nối trực tiếp tới máy chủ trong LAN, không cần DNS công cộng của tên miền.
Ứng dụng, dữ liệu SQL Server, tài khoản và cấu hình Docker hiện tại được giữ nguyên. Máy sử dụng cần kết nối mạng nội bộ hoặc VPN có đường tới `172.20.235.176`.
## Thiết lập trên máy Windows
1. Mở Start, tìm **Notepad**, bấm chuột phải và chọn **Run as administrator**.
2. Trong Notepad chọn **File → Open**, đổi bộ lọc thành **All files**, rồi mở:
```text
C:\Windows\System32\drivers\etc\hosts
```
3. Thêm dòng sau vào cuối file rồi lưu. Nếu đã có dòng đang hoạt động cho đúng tên `accrobot.pnkr.asia`, sửa IP của dòng đó thay vì thêm trùng. Ghi lại IP cũ để hoàn tác; giữ nguyên các dòng của tên khác.
```text
172.20.235.176 accrobot.pnkr.asia # AccManager temporary LAN
```
File phải được lưu đúng tên `hosts`, không thêm đuôi `.txt`.
4. Mở PowerShell hoặc Command Prompt với quyền Administrator và chạy:
```powershell
ipconfig /flushdns
```
5. Đóng rồi mở lại trình duyệt, truy cập **https://accrobot.pnkr.asia** và đăng nhập như bình thường.
Thực hiện trên từng máy cần dùng. Nếu cần áp dụng cho nhiều máy, quản trị mạng có thể tạo bản ghi DNS nội bộ tương đương, với điều kiện các máy sử dụng DNS nội bộ đó.
## Kiểm tra
Sau khi sửa `hosts`, chạy trong PowerShell:
```powershell
curl.exe --noproxy "*" --fail --show-error --connect-timeout 5 --max-time 15 https://accrobot.pnkr.asia/api/health
```
Kết quả mong đợi có `"status":"ok"`. Mở trang đăng nhập và đăng nhập bằng tài khoản hiện có để kiểm tra phiên làm việc.
Nếu chưa truy cập được, kiểm tra máy đang ở đúng LAN/VPN, dòng `hosts` không bị chú thích bằng `#` ở đầu, file không có đuôi `.txt`, rồi xóa cache DNS và mở lại trình duyệt. Nếu máy sử dụng proxy web, cần cho địa chỉ này đi trực tiếp qua LAN.
### Kết quả kiểm tra ngày 10/09/2026
- `https://accrobot.pnkr.asia/api/health` qua IP `172.20.235.176` trả HTTP 200, `status: ok`.
- Trang `/pages/login.html` qua cùng đường kết nối trả HTTP 200.
- Xác minh TLS thành công; chứng chỉ cho `accrobot.pnkr.asia` hết hạn **29/10/2026 lúc 09:56:58 (giờ Việt Nam)**.
- Chưa kiểm tra đăng nhập bằng tài khoản người dùng. Phiên hỗ trợ không có quyền ghi file `hosts`, nên ánh xạ chưa được áp dụng tự động.
Có thể kiểm tra đường kết nối trước khi sửa `hosts` bằng lệnh sau; lệnh chỉ áp dụng ánh xạ cho riêng lần gọi này:
```powershell
curl.exe --noproxy "*" --fail --show-error --connect-timeout 5 --max-time 15 --resolve accrobot.pnkr.asia:443:172.20.235.176 https://accrobot.pnkr.asia/api/health
```
## Vì sao vẫn mở tên web thay vì gõ IP vào trình duyệt?
Ánh xạ `hosts` sử dụng IP nội bộ để kết nối, đồng thời giữ tên HTTPS mà reverse proxy, chứng chỉ và cookie đăng nhập đang dùng. Truy cập bằng `https://172.20.235.176` không khớp tên chứng chỉ. Truy cập `http://172.20.235.176:3000` gặp cấu hình bắt buộc HTTPS và cookie Secure của ứng dụng hiện tại.
Không cần sửa `.env`, chuyển `NODE_ENV` sang development, build image, khởi động lại container hay chuyển cơ sở dữ liệu cho phương án này.
## Hoàn tác sau khi gia hạn tên miền
1. Khi tên miền đã gia hạn và DNS công cộng hoạt động lại, mở file `hosts` với quyền Administrator.
2. Xóa riêng dòng có chú thích `# AccManager temporary LAN`; nếu đã sửa dòng có sẵn, khôi phục nội dung cũ.
3. Chạy `ipconfig /flushdns`, đóng rồi mở lại trình duyệt và truy cập địa chỉ web như trước.
Ánh xạ chỉ giải quyết việc phân giải tên miền. Chứng chỉ HTTPS vẫn cần còn hạn; hoàn tất gia hạn hoặc bố trí chứng chỉ phù hợp trước mốc hết hạn nêu trên.

View File

@@ -1,65 +0,0 @@
# AccManager
AccManager là hệ thống giúp quản lý tập trung tài khoản truy cập cho nhân sự trong tổ chức.
Thay vì lưu rải rác tài khoản ứng dụng ở nhiều nơi, AccManager gom tất cả về một màn hình để dễ tìm, dễ phân quyền và dễ kiểm soát.
## Dự án này dùng để làm gì
- Quản lý danh sách người dùng trong nội bộ.
- Quản lý danh sách ứng dụng đang sử dụng trong công ty.
- Gán tài khoản truy cập ứng dụng cho từng người dùng.
- Theo dõi thông tin tài khoản rõ ràng, tránh thất lạc.
- Lưu trữ, tìm kiếm, xem và tải xuống tài liệu PDF dùng chung.
## Ai sẽ sử dụng
- Quản trị viên: tạo người dùng, tạo ứng dụng, cấp tài khoản, cập nhật thông tin.
- Người dùng thông thường: xem các tài khoản được cấp cho mình.
## Cách sử dụng nhanh
1. Đăng nhập vào hệ thống.
2. Vào mục Người dùng để tạo mới hoặc cập nhật thông tin nhân sự.
3. Vào mục Ứng dụng để thêm các hệ thống cần quản lý.
4. Vào mục Tài khoản để gán tài khoản ứng dụng cho đúng người.
5. Vào mục Tài liệu PDF để tải lên hoặc xem tài liệu dùng chung.
6. Dùng nút Xem chi tiết trong danh sách người dùng để kiểm tra đầy đủ thông tin trước khi chỉnh sửa.
## Quy trình vận hành gợi ý
1. Khi có nhân sự mới:
- Tạo người dùng.
- Gán quyền phù hợp.
- Cấp các tài khoản ứng dụng cần thiết.
2. Khi thay đổi công việc:
- Cập nhật lại danh sách ứng dụng được cấp.
- Thu hồi các tài khoản không còn sử dụng.
3. Khi nhân sự nghỉ việc:
- Khóa hoặc ngừng kích hoạt người dùng.
- Rà soát và thu hồi toàn bộ tài khoản liên quan.
## Lợi ích chính
- Giảm thất lạc thông tin tài khoản.
- Rõ ràng trách nhiệm ai đang dùng tài khoản nào.
- Tiết kiệm thời gian bàn giao và thu hồi quyền truy cập.
- Dễ kiểm tra trước khi cấp quyền mới.
## Tài liệu liên quan
- Hướng dẫn triển khai: [DEPLOYMENT_GUIDE.md](DEPLOYMENT_GUIDE.md)
- Dùng tạm trong mạng nội bộ khi tên miền hết hạn: [LOCAL_ACCESS.md](LOCAL_ACCESS.md)
## Cau hinh email xac thuc dang ky
He thong da ho tro xac thuc email cho:
- Dang ky tai khoan moi.
- Doi email trong phan ho so ca nhan.
Phiên bản tài liệu: 4.0.0
Cập nhật: Tháng 4 năm 2026

View File

@@ -1,765 +0,0 @@
# Portable UI Style Guide - AccManager Inspired
Tài liệu này dùng để mang phong cách UI hiện tại của AccManager sang một dự án khác. Nội dung tập trung vào ngôn ngữ thiết kế, token, layout, component pattern và checklist triển khai, không phụ thuộc chặt vào nghiệp vụ tài khoản/tài sản của AccManager.
## 1. Design DNA
Phong cách UI gốc là một **admin console nội bộ**: gọn, sáng, nhiều dữ liệu, dễ quét bảng, thao tác nhanh và ít trang trí thừa.
Tinh thần chính:
- Ưu tiên hiệu quả vận hành hơn cảm giác marketing.
- Nền sáng, bề mặt trắng/xám nhạt, màu nhấn xanh primary.
- Layout chắc, dày thông tin nhưng vẫn thoáng.
- Component nhỏ gọn: table, filter, modal, form, badge, icon action.
- Button và icon rõ chức năng, phản hồi hover/active nhẹ.
- Typography dùng heading đậm, label nhỏ uppercase, nội dung bảng vừa đủ đọc.
- Phù hợp cho dashboard, CRM, ERP mini, tool nội bộ, quản lý dữ liệu, asset/account/user management.
Không nên biến phong cách này thành landing page, hero lớn, nhiều gradient trang trí, card marketing hoặc layout quá thoáng kiểu portfolio.
## 2. Stack Khuyến Nghị
Để tái tạo đúng style, dự án mới nên dùng:
- Tailwind CSS.
- Font heading: `Manrope`.
- Font body: `Inter`.
- Icon: Google Material Symbols Outlined.
- Toast/notification: Notiflix hoặc thư viện tương đương.
- Table data với sticky header, horizontal scroll trên mobile.
Google Fonts:
```html
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap" rel="stylesheet">
```
Material Symbols base CSS:
```css
.material-symbols-outlined {
font-family: 'Material Symbols Outlined';
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
font-size: 1.25rem;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-flex;
white-space: nowrap;
direction: ltr;
}
```
## 3. Tailwind Design Tokens
Có thể copy phần `theme.extend` này sang `tailwind.config.js` của dự án mới.
```js
theme: {
extend: {
colors: {
"primary": "#3755c3",
"primary-dim": "#2848b7",
"primary-container": "#dde1ff",
"on-primary": "#f8f7ff",
"background": "#f7f9fb",
"surface": "#f7f9fb",
"surface-container-lowest": "#ffffff",
"surface-container-low": "#f0f4f7",
"surface-container": "#e8eff3",
"surface-container-high": "#e1e9ee",
"surface-container-highest": "#d9e4ea",
"on-surface": "#2a3439",
"on-surface-variant": "#566166",
"outline": "#717c82",
"outline-variant": "#a9b4b9",
"error": "#9f403d",
"error-container": "#fe8983"
},
fontFamily: {
headline: ["Manrope", "sans-serif"],
body: ["Inter", "sans-serif"],
label: ["Inter", "sans-serif"]
},
borderRadius: {
DEFAULT: "0.125rem",
lg: "0.25rem",
xl: "0.5rem",
full: "0.75rem"
}
}
}
```
Base body:
```html
<body class="bg-background text-on-surface antialiased">
```
Font rule:
```css
body { font-family: 'Inter', sans-serif; }
h1, h2, h3, .brand-logo { font-family: 'Manrope', sans-serif; }
```
## 4. Color Usage
Màu nền:
- App background: `bg-background`.
- Main card/table: `bg-white` hoặc `bg-surface-container-lowest`.
- Filter bar/input subtle: `bg-surface-container-low`.
- Header/table head: `bg-slate-50`.
Màu chữ:
- Text chính: `text-on-surface`, `text-slate-900`.
- Text phụ: `text-on-surface-variant`, `text-slate-500`, `text-slate-600`.
- Link/action chính: `text-primary`.
Màu hành động:
- Primary: `bg-primary hover:bg-primary-dim text-on-primary`.
- Secondary: border slate, text slate.
- Danger: `bg-red-600 hover:bg-red-700 text-white` hoặc `text-error`.
- Success: emerald/green.
- Pending/warning: amber/yellow.
- Info: blue.
Tránh:
- Dùng quá nhiều gradient.
- Dùng một palette đơn sắc toàn xanh.
- Nền tối toàn trang nếu chưa thiết kế dark mode đầy đủ.
- Màu quá rực trên bảng dữ liệu.
## 5. Typography Scale
Page title:
```html
<h1 class="text-2xl font-extrabold text-on-surface tracking-tight">Page Title</h1>
```
Subtitle:
```html
<p class="text-sm text-on-surface-variant">Short page description.</p>
```
Table header / form label:
```html
<span class="text-[10px] font-bold uppercase tracking-wider text-on-surface-variant">Label</span>
```
Table body:
```html
<td class="px-4 py-3 text-sm text-slate-600">Value</td>
```
Badge text:
```html
<span class="px-2 py-1 rounded text-xs font-semibold">Status</span>
```
Nguyên tắc:
- Heading đậm, ngắn, dễ scan.
- Label nhỏ, uppercase, tracking rộng.
- Nội dung bảng không quá lớn để giữ mật độ dữ liệu.
- Không dùng hero-scale type trong dashboard/tool view.
## 6. App Shell Pattern
Dùng shell này cho các app quản trị/dữ liệu.
```html
<body class="app-shell bg-background text-on-surface antialiased flex h-screen w-screen overflow-hidden">
<aside id="appSidebar" class="h-screen w-56 flex flex-col bg-slate-100 border-r border-outline-variant/10 shrink-0">
<!-- Sidebar content -->
</aside>
<button id="sidebarBackdrop" type="button" aria-label="Close navigation"></button>
<main id="appMain" class="flex-1 flex flex-col h-screen min-w-0">
<header class="h-14 flex items-center justify-between px-6 bg-slate-50/80 backdrop-blur-xl border-b border-outline-variant/10 shrink-0">
<!-- Topbar actions -->
</header>
<div id="mainContent" class="flex-1 overflow-hidden">
<!-- Current page -->
</div>
</main>
</body>
```
Sidebar style:
- Width desktop: `w-56`.
- Background: `bg-slate-100`.
- Border right: `border-outline-variant/10`.
- Group label: uppercase, `text-[10px]`, tracking rộng.
- Active nav: left border xanh, nền slate nhạt, text đậm.
- Nav item: icon + label, height vừa phải, hover nền slate.
Active nav example:
```html
<a class="flex items-center gap-3 px-3 py-2 border-l-4 border-blue-600 bg-slate-200/80 text-slate-900 font-bold rounded-r-lg">
<span class="material-symbols-outlined">dashboard</span>
<span>Tổng quan</span>
</a>
```
Inactive nav:
```html
<a class="flex items-center gap-3 px-3 py-2 text-slate-600 hover:text-slate-900 hover:bg-slate-200/50 transition-all rounded-r-lg">
<span class="material-symbols-outlined">apps</span>
<span>Ứng dụng</span>
</a>
```
## 7. Page Layout Pattern
Mỗi page nên theo cấu trúc:
```html
<div class="page-name flex flex-col p-4 md:p-6 overflow-hidden h-full">
<div class="page-header flex items-center justify-between gap-4 mb-5 shrink-0">
<div>
<h1 class="text-2xl font-extrabold text-on-surface tracking-tight">Page Title</h1>
<p class="text-sm text-on-surface-variant">Short explanation.</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<!-- Action buttons -->
</div>
</div>
<div class="page-filters flex items-center gap-3 mb-4 shrink-0">
<!-- Search/filter controls -->
</div>
<div class="flex-1 bg-white rounded-xl border border-slate-200 shadow-sm flex flex-col overflow-hidden min-h-0">
<!-- Table/list/content -->
</div>
</div>
```
Nguyên tắc:
- Page padding luôn `p-4 md:p-6`.
- Header không quá cao.
- Action chính nằm bên phải.
- Filter nằm ngay trên bảng.
- Content panel chiếm hết phần còn lại.
- Không bọc section bằng quá nhiều card lồng nhau.
## 8. Dashboard Pattern
Dashboard nên có:
- Header ngắn.
- CTA chính.
- Metric grid.
- Recent activity hoặc bảng tóm tắt.
Metric card:
```html
<div class="bg-surface-container-lowest p-4 rounded-xl border border-outline-variant/15 flex flex-col">
<span class="text-[10px] font-bold text-on-surface-variant uppercase tracking-wider mb-2">Applications</span>
<div class="flex items-baseline justify-between">
<span class="text-2xl font-black text-on-surface">24</span>
<span class="text-[10px] font-bold text-on-surface-variant">18 Active</span>
</div>
</div>
```
Grid:
```html
<div class="dashboard-stats grid grid-cols-4 gap-4 shrink-0">
```
Responsive:
- Desktop: 4 cột.
- Tablet/mobile: 2 cột.
- Mobile nhỏ: 1 cột.
## 9. Table Pattern
Đây là component quan trọng nhất của style này.
```html
<div class="flex-1 bg-white rounded-xl border border-slate-200 shadow-sm flex flex-col overflow-hidden min-h-0">
<div class="table-wrap overflow-y-auto overflow-x-auto flex-1">
<table class="w-full text-left border-collapse" style="min-width: 900px;">
<thead class="sticky top-0 z-10 bg-slate-50 border-b border-slate-200">
<tr>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Name</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500 text-right">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100">
<tr class="hover:bg-slate-50/80 transition-colors">
<td class="px-4 py-3 text-sm text-slate-700">Example</td>
<td class="px-4 py-3 text-right">...</td>
</tr>
</tbody>
</table>
</div>
<div class="page-pager flex items-center justify-between px-4 py-2 border-t border-slate-200 bg-slate-50 text-xs text-slate-600">
<span>Showing 1-10 of 50</span>
<div class="flex items-center gap-2">
<button class="px-2 py-1 border border-slate-200 rounded text-xs">Prev</button>
<span class="text-[11px]">Page 1 / 5</span>
<button class="px-2 py-1 border border-slate-200 rounded text-xs">Next</button>
</div>
</div>
</div>
```
Quy ước table:
- Header sticky.
- Row hover nhẹ.
- Cell padding đều.
- Text trong bảng ưu tiên `text-sm`.
- Header dùng `text-[10px] uppercase`.
- Nếu nhiều cột, đặt `min-width` và cho horizontal scroll.
- Nếu có action column quan trọng, có thể sticky bên phải.
Sticky action column:
```html
<td class="sticky right-0 z-10 bg-white group-hover:bg-slate-50/80 px-4 py-3 text-right shadow-[-10px_0_12px_-12px_rgba(15,23,42,0.45)]">
```
## 10. Filter/Search Pattern
Filter bar:
```html
<div class="page-filters flex items-center gap-3 mb-4">
<div class="flex items-center gap-1.5">
<span class="text-[10px] font-bold uppercase text-on-surface-variant">Status</span>
<select class="bg-surface-container-low border-slate-200 rounded-md text-[11px] py-1 px-2 pr-6 focus:ring-1 focus:ring-primary shadow-sm">
<option>All</option>
</select>
</div>
<div class="flex items-center gap-1.5 flex-1">
<span class="text-[10px] font-bold uppercase text-on-surface-variant">Search</span>
<input class="flex-1 bg-surface-container-low border-slate-200 rounded-md text-[11px] py-1 px-2 focus:ring-1 focus:ring-primary shadow-sm" placeholder="Search...">
</div>
</div>
```
Nguyên tắc:
- Filter ngắn, đặt sát bảng.
- Search chiếm phần còn lại.
- Label filter nhỏ và uppercase.
- Trên mobile, filter chuyển thành column/full width.
## 11. Button Pattern
Primary:
```html
<button class="bg-primary hover:bg-primary-dim text-on-primary px-4 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all active:scale-95">
<span class="material-symbols-outlined text-base">add</span>
Add New
</button>
```
Secondary:
```html
<button class="border border-slate-300 hover:bg-slate-100 text-slate-700 px-3 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all active:scale-95">
<span class="material-symbols-outlined text-base">download</span>
Export
</button>
```
Danger:
```html
<button class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg text-xs font-bold">
Delete
</button>
```
Icon action:
```html
<button class="p-1.5 text-slate-400 transition-colors hover:text-primary" title="Edit">
<span class="material-symbols-outlined text-lg">edit</span>
</button>
```
Disabled:
```html
<button class="opacity-50 cursor-not-allowed" disabled>Disabled</button>
```
## 12. Form Pattern
Form field:
```html
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Name</label>
<input class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="Enter name">
</div>
```
Readonly:
```html
<input readonly class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50 text-slate-600">
```
Textarea:
```html
<textarea class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 h-20 resize-none"></textarea>
```
Field with icon:
```html
<div class="relative">
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-on-surface-variant/60">
<span class="material-symbols-outlined text-base">person</span>
</span>
<input class="w-full pl-10 pr-4 py-2.5 bg-surface-container-low border border-outline-variant/30 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent text-sm font-medium">
</div>
```
## 13. Badge/Status Pattern
Online/offline:
```html
<div class="flex items-center gap-1.5">
<div class="w-1.5 h-1.5 rounded-full bg-primary ring-2 ring-primary/20"></div>
<span class="text-xs font-medium text-on-primary-fixed-variant">Online</span>
</div>
```
Status badges:
```html
<span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-emerald-100 text-emerald-700">Trong kho</span>
<span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-blue-100 text-blue-700">Đang sử dụng</span>
<span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-yellow-100 text-yellow-700">Đang chờ</span>
<span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-red-100 text-red-700">Từ chối</span>
```
Role chip:
```html
<span class="px-3 py-1 rounded-full text-xs font-semibold bg-blue-100 text-blue-700">Admin</span>
```
## 14. Modal Pattern
Backdrop + content:
```html
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="exampleModal">
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
<h3 class="text-base font-extrabold text-slate-900">Modal Title</h3>
<button class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400 transition-colors">
<span class="material-symbols-outlined">close</span>
</button>
</div>
<form class="p-6 space-y-4">
<!-- Fields -->
<div class="flex gap-3 pt-4">
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg">Cancel</button>
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Save</button>
</div>
</form>
</div>
</div>
```
Modal CSS:
```css
.modal-backdrop {
opacity: 0;
transition: opacity 0.2s ease-in-out;
pointer-events: none;
}
.modal-backdrop.open {
opacity: 1;
pointer-events: auto;
}
.modal-content {
transform: scale(0.95);
transition: transform 0.2s ease-in-out;
}
.modal-backdrop.open .modal-content {
transform: scale(1);
}
```
Danger confirm modal:
```html
<div class="px-6 py-4 border-b border-slate-100 bg-red-50 flex items-center gap-3">
<span class="material-symbols-outlined text-red-600 text-2xl">warning</span>
<h3 class="text-base font-extrabold text-red-700">Xác nhận xóa</h3>
</div>
```
## 15. Login/Auth Screen Pattern
Auth screen dùng centered card:
```html
<body class="bg-gradient-to-br from-blue-50 via-background to-purple-50 antialiased">
<div class="min-h-screen flex items-center justify-center px-4">
<div class="w-full max-w-md">
<div class="bg-white rounded-2xl shadow-lg border border-outline-variant/10 p-8">
<div class="text-center mb-8">
<div class="flex justify-center mb-4">
<div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center">
<span class="material-symbols-outlined text-primary text-4xl">security</span>
</div>
</div>
<h1 class="text-2xl font-black text-slate-900 tracking-tight">Product Name</h1>
<p class="text-xs uppercase tracking-widest text-on-surface-variant font-bold mt-2">Admin Console</p>
</div>
<!-- Form -->
</div>
</div>
</div>
</body>
```
Auth tabs:
```html
<div class="flex gap-2 mb-6" role="tablist">
<button class="flex-1 py-2.5 rounded-lg text-xs font-bold uppercase tracking-wider border border-outline-variant/30 bg-primary text-on-primary shadow-sm">Đăng nhập</button>
<button class="flex-1 py-2.5 rounded-lg text-xs font-bold uppercase tracking-wider border border-outline-variant/30 bg-surface-container-low text-on-surface-variant">Đăng ký</button>
</div>
```
Alert states:
```html
<div class="bg-error-container/20 text-error/80 border border-error/30 rounded-lg px-4 py-3 text-xs font-medium">Error message</div>
<div class="bg-green-50 text-green-800 border border-green-200 rounded-lg px-4 py-3 text-xs font-medium">Success message</div>
<div class="bg-amber-50 text-amber-800 border border-amber-200 rounded-lg px-4 py-3 text-xs font-medium">Warning message</div>
```
## 16. Responsive Rules
Recommended CSS:
```css
#mobileMenuBtn,
#sidebarBackdrop {
display: none;
}
@media (max-width: 900px) {
body.app-shell {
width: 100%;
min-height: 100dvh;
height: 100dvh;
overflow: hidden;
position: relative;
}
#mobileMenuBtn {
display: inline-flex;
align-items: center;
justify-content: center;
}
#sidebarBackdrop {
display: block;
position: fixed;
inset: 0;
z-index: 70;
background: rgba(15, 23, 42, 0.45);
opacity: 0;
pointer-events: none;
transition: opacity 0.2s ease-in-out;
}
#appSidebar {
position: fixed;
inset: 0 auto 0 0;
height: 100dvh;
width: min(82vw, 16rem);
z-index: 80;
transform: translateX(-100%);
transition: transform 0.2s ease-in-out;
box-shadow: 0 20px 45px rgba(15, 23, 42, 0.35);
}
body.mobile-nav-open #sidebarBackdrop {
opacity: 1;
pointer-events: auto;
}
body.mobile-nav-open #appSidebar {
transform: translateX(0);
}
.page-header,
.page-filters,
.users-controls {
flex-direction: column;
align-items: stretch;
gap: 0.75rem;
}
.table-wrap {
overflow-x: auto;
}
.table-wrap table {
min-width: 700px;
}
.page-pager {
gap: 0.5rem;
flex-direction: column;
align-items: flex-start;
}
.modal-backdrop {
align-items: flex-end;
}
.modal-backdrop .modal-content {
width: calc(100% - 1rem);
max-height: min(88dvh, 700px);
margin: 0.5rem;
overflow-y: auto;
border-radius: 0.9rem;
}
}
@media (max-width: 560px) {
.dashboard-stats {
grid-template-columns: 1fr;
}
}
```
Mobile behavior:
- Sidebar thành off-canvas.
- Topbar gọn lại.
- Profile metadata nên ẩn.
- Header/filter chuyển column.
- Table luôn scroll ngang nếu nhiều cột.
- Modal gần bottom và giới hạn chiều cao.
## 17. UX Rules
Giữ những nguyên tắc này khi áp dụng sang dự án khác:
1. Mỗi màn dữ liệu cần có search hoặc filter nếu danh sách có thể dài.
2. Action chính luôn rõ ràng, nằm ở page header.
3. Action nguy hiểm luôn cần confirm.
4. Action theo quyền nên disabled trực quan, không chỉ báo lỗi sau khi bấm.
5. Table phải có empty state.
6. Table dài cần pagination.
7. Form dài nên chia grid 2 cột trên desktop, 1 cột mobile.
8. Modal dài phải scroll trong content, không làm tràn viewport.
9. Badge trạng thái phải thống nhất màu theo ý nghĩa.
10. Icon-only button phải có `title` hoặc accessible name.
11. Không dùng nhiều card trang trí trong dashboard vận hành.
12. Text không được overlap hoặc tràn button/card.
## 18. Accessibility Checklist
Khi port sang dự án mới, nên bổ sung:
- `aria-label` cho icon-only buttons.
- `role="dialog"` và `aria-modal="true"` cho modal.
- Focus trap trong modal.
- Đóng modal bằng phím `Escape`.
- `aria-expanded` cho mobile menu.
- `aria-selected` cho tabs.
- Label đầy đủ cho form input.
- Không chỉ dùng màu để truyền đạt trạng thái; nên có text status.
- Contrast đủ tốt cho text nhỏ.
## 19. Implementation Checklist
Khi bắt đầu dự án mới:
1. Cài Tailwind và plugin forms nếu cần.
2. Copy design tokens vào `tailwind.config.js`.
3. Thêm Google Fonts và Material Symbols.
4. Tạo app shell: sidebar, topbar, content area.
5. Tạo component base cho button, table, filter, modal, badge.
6. Tạo responsive sidebar theo breakpoint `900px`.
7. Áp dụng page layout pattern cho từng màn hình.
8. Kiểm tra table trên mobile với horizontal scroll.
9. Chuẩn hóa status color map.
10. Thêm empty/loading/error states.
## 20. Mapping Sang Dự Án Khác
Nếu dự án mới không phải quản lý tài khoản/tài sản, vẫn có thể dùng style này bằng cách đổi tên module:
| AccManager concept | Dự án mới có thể thay bằng |
| --- | --- |
| Applications | Products, Services, Modules, Integrations |
| Accounts | Records, Credentials, Customers, Contracts |
| Assets | Inventory, Devices, Documents, Items |
| Users | Members, Staff, Operators |
| Departments | Teams, Groups, Categories |
| Projects | Campaigns, Workspaces, Sites |
| Borrow/Return | Requests, Tickets, Approvals, Workflows |
Điều quan trọng là giữ cùng cấu trúc:
- Sidebar nhóm chức năng.
- Page header + actions.
- Filter/search.
- Table/list.
- Modal CRUD.
- Badge trạng thái.
- Toast feedback.
## 21. Những Gì Nên Tránh Khi Port
- Copy nguyên text nghiệp vụ AccManager nếu dự án mới khác domain.
- Copy table quá nhiều cột khi domain không cần.
- Lạm dụng modal cho mọi thứ nếu workflow mới cần full page editor.
- Dùng gradient nền cho app shell chính.
- Tăng border radius quá lớn làm mất chất admin console.
- Dùng font khác quá mềm hoặc decorative.
- Thêm quá nhiều shadow, glassmorphism, decorative blobs.
- Trộn nhiều style icon khác nhau.

86
backend/announcements.js Normal file
View File

@@ -0,0 +1,86 @@
const express = require('express');
// Every popup and dismissal is evaluated against the authenticated recipient.
const visibleAnnouncement = `n.Source = 'admin' AND n.IsActive = 1
AND (n.ExpiresAt IS NULL OR n.ExpiresAt > DATEADD(HOUR, 7, SYSUTCDATETIME()))
AND EXISTS (
SELECT 1 FROM NotificationAudiences a WHERE a.NotificationId = n.NotificationId
AND (a.AudienceType = 'all'
OR (a.AudienceType = 'user' AND a.AudienceValue = CONVERT(NVARCHAR(100), @userId))
OR (a.AudienceType = 'role' AND LOWER(a.AudienceValue) = LOWER(@userRole)))
)`;
function createAnnouncementRouter({ getPool, sql, requireManage, getUserId, getRole, sendInternalError }) {
const router = express.Router();
const recipientRequest = req => getPool().request()
.input('userId', sql.Int, getUserId(req))
.input('userRole', sql.NVarChar(100), getRole(req));
router.get('/announcements', async (req, res) => {
try {
const result = await recipientRequest(req).query(`
SELECT n.NotificationId, n.Source, n.Severity, n.Title, n.Message, n.ActionUrl,
n.CreatedDate, n.ExpiresAt, n.CreatedBy,
COALESCE(NULLIF(LTRIM(RTRIM(u.FullName)), ''), u.Username) AS CreatedByName,
CAST(CASE WHEN receipts.ReadAt IS NULL THEN 0 ELSE 1 END AS BIT) AS IsRead
FROM Notifications n
LEFT JOIN Users u ON u.UserId = n.CreatedBy
LEFT JOIN NotificationReceipts receipts ON receipts.NotificationId = n.NotificationId AND receipts.UserId = @userId
WHERE ${visibleAnnouncement}
AND NOT EXISTS (SELECT 1 FROM NotificationPopupDismissals d
WHERE d.NotificationId = n.NotificationId AND d.UserId = @userId)
ORDER BY n.CreatedDate DESC, n.NotificationId DESC;
`);
res.json({ success: true, data: result.recordset });
} catch (error) { sendInternalError(res, error); }
});
router.put('/:id/dismiss', async (req, res) => {
const notificationId = Number(req.params.id);
if (!Number.isSafeInteger(notificationId) || notificationId <= 0) {
return res.status(400).json({ success: false, message: 'Thông báo không hợp lệ' });
}
try {
const result = await recipientRequest(req).input('notificationId', sql.BigInt, notificationId).query(`
IF EXISTS (SELECT 1 FROM Notifications n WHERE n.NotificationId = @notificationId AND ${visibleAnnouncement})
BEGIN
MERGE NotificationPopupDismissals WITH (HOLDLOCK) AS target
USING (SELECT @notificationId AS NotificationId, @userId AS UserId) AS source
ON target.NotificationId = source.NotificationId AND target.UserId = source.UserId
WHEN NOT MATCHED THEN INSERT (NotificationId, UserId)
VALUES (source.NotificationId, source.UserId);
SELECT CAST(1 AS BIT) AS Found;
END
ELSE SELECT CAST(0 AS BIT) AS Found;
`);
if (!result.recordset?.[0]?.Found) return res.status(404).json({ success: false, message: 'Thông báo đã kết thúc hoặc không dành cho bạn' });
res.json({ success: true });
} catch (error) { sendInternalError(res, error); }
});
router.get('/manage', requireManage, async (req, res) => {
const page = Math.max(1, Number.parseInt(req.query.page, 10) || 1);
const pageSize = Math.min(50, Math.max(1, Number.parseInt(req.query.pageSize, 10) || 20));
try {
const result = await getPool().request()
.input('offset', sql.Int, (page - 1) * pageSize)
.input('pageSize', sql.Int, pageSize)
.query(`
SET NOCOUNT ON;
SELECT COUNT_BIG(*) AS Total FROM Notifications WHERE Source = 'admin';
SELECT n.NotificationId, n.Source, n.Severity, n.Title, n.Message, n.ActionUrl,
n.CreatedBy, n.CreatedDate, n.ExpiresAt, n.IsActive,
COALESCE(NULLIF(LTRIM(RTRIM(u.FullName)), ''), u.Username) AS CreatedByName
FROM Notifications n LEFT JOIN Users u ON u.UserId = n.CreatedBy
WHERE n.Source = 'admin'
ORDER BY n.CreatedDate DESC, n.NotificationId DESC
OFFSET @offset ROWS FETCH NEXT @pageSize ROWS ONLY;
`);
const total = Number(result.recordsets?.[0]?.[0]?.Total) || 0;
res.json({ success: true, data: result.recordsets?.[1] || [], pagination: { page, pageSize, total, totalPages: Math.max(1, Math.ceil(total / pageSize)) } });
} catch (error) { sendInternalError(res, error); }
});
return router;
}
module.exports = { createAnnouncementRouter };

View File

@@ -0,0 +1,183 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { createRequire } = require('node:module');
const express = require('express');
async function fixture(t) {
const notices = [], audiences = [], reads = new Set(), dismissals = new Set(), queries = [];
const users = { 1: 'admin', 2: 'user', 3: 'user', 4: 'asset' };
const visible = (notice, inputs) => notice.IsActive && (!notice.ExpiresAt || +new Date(notice.ExpiresAt) > Date.now())
&& audiences.some(a => a.id === notice.NotificationId && (a.type === 'all' || a.type === 'user' && +a.value === inputs.userId || a.type === 'role' && a.value === inputs.userRole));
class Request {
constructor() { this.inputs = {}; }
input(name, _type, value) { this.inputs[name] = value; return this; }
async query(query) {
const p = this.inputs;
queries.push({ query, inputs: p });
if (query.includes('INSERT INTO Notifications')) {
const notice = { NotificationId: notices.length + 1, Source: p.source, Title: p.title, Message: p.message,
Severity: p.severity, ActionUrl: p.actionUrl, CreatedBy: p.createdBy, CreatedByName: 'Publisher',
ExpiresAt: p.expiresAt, CreatedDate: new Date(), IsActive: true };
notices.push(notice);
return { recordset: [{ NotificationId: notice.NotificationId }] };
}
if (query.includes('INSERT INTO NotificationAudiences')) {
audiences.push({ id: p.notificationId, type: p.audienceType, value: p.audienceValue });
return { recordset: [] };
}
if (query.includes('INTO #VisibleNotifications')) {
assert.match(query, /receipts\.UserId = @userId/);
assert.match(query, /AudienceType = 'user' AND audiences\.AudienceValue = CONVERT\(NVARCHAR\(100\), @userId\)/);
let rows = notices.filter(n => visible(n, p) && (!p.source || n.Source === p.source))
.map(n => ({ ...n, IsRead: reads.has(`${n.NotificationId}:${p.userId}`) }));
const unread = rows.filter(n => !n.IsRead).length;
if (p.unreadOnly) rows = rows.filter(n => !n.IsRead);
return { recordsets: [[{ Total: rows.length }], [{ UnreadCount: unread }], rows.slice(p.offset, p.offset + p.pageSize)] };
}
if (query.includes('MERGE NotificationPopupDismissals')) {
assert.match(query, /WITH \(HOLDLOCK\)/);
assert.match(query, /n\.Source = 'admin' AND n\.IsActive = 1/);
assert.match(query, /a\.AudienceValue = CONVERT\(NVARCHAR\(100\), @userId\)/);
const found = notices.some(n => n.NotificationId === p.notificationId && n.Source === 'admin' && visible(n, p));
if (found) dismissals.add(`${p.notificationId}:${p.userId}`);
return { recordset: [{ Found: found }] };
}
if (query.includes('FROM NotificationPopupDismissals d')) {
assert.match(query, /d\.UserId = @userId/);
assert.match(query, /n\.ExpiresAt > DATEADD/);
return { recordset: notices.filter(n => n.Source === 'admin' && visible(n, p) && !dismissals.has(`${n.NotificationId}:${p.userId}`))
.map(n => ({ ...n, IsRead: reads.has(`${n.NotificationId}:${p.userId}`) })) };
}
if (query.includes('COUNT_BIG(*) AS Total FROM Notifications')) {
const rows = notices.filter(n => n.Source === 'admin');
return { recordsets: [[{ Total: rows.length }], rows.slice(p.offset, p.offset + p.pageSize)] };
}
if (query.includes('MERGE NotificationReceipts')) {
const found = notices.some(n => n.NotificationId === p.notificationId && visible(n, p));
if (found) reads.add(`${p.notificationId}:${p.userId}`);
return { recordset: [{ Found: found }] };
}
if (query.includes('INSERT INTO NotificationReceipts')) {
notices.filter(n => visible(n, p)).forEach(n => reads.add(`${n.NotificationId}:${p.userId}`));
return { recordset: [] };
}
if (query.includes('UPDATE Notifications')) {
assert.match(query, /@isAdmin = 1 OR CreatedBy = @userId/);
const found = notices.find(n => n.NotificationId === p.notificationId && n.Source === 'admin' && n.IsActive && (p.isAdmin || n.CreatedBy === p.userId));
if (found) found.IsActive = false;
return { recordset: [{ Affected: found ? 1 : 0 }] };
}
if (query.includes('FROM AssetBorrowRequests br WITH')) return { recordset: [{ BorrowId: 11, AssetId: 17, RequestType: 'borrow', RequestStatus: 'pending', CreatedBy: 2, BorrowerName: 'User 2', AssetCode: 'TS-17', AssetName: 'PLC' }] };
if (query.includes('UPDATE AssetBorrowRequests')) return { recordset: [] };
throw new Error(`Unexpected SQL in test: ${query.slice(0, 80)}`);
}
}
class Transaction { async begin() {} async commit() {} async rollback() {} }
const filename = path.join(__dirname, 'server.js');
const localRequire = createRequire(filename);
const sql = { ...localRequire('mssql'), Request, Transaction };
const sandbox = {
require: name => name === 'mssql' ? sql : name === 'dotenv' ? { config() {} } : localRequire(name),
module: { exports: {} }, __dirname, __filename: filename, Buffer, URL, console,
testPool: { request: () => new Request() },
process: { env: { NODE_ENV: 'test', DATA_ENCRYPTION_SECRET: 'announcement-tests-only-secret-more-than-32-characters' }, on() {} }
};
vm.runInNewContext(`${fs.readFileSync(filename, 'utf8')}\npool=testPool; getUserDisplayNameById=async()=> 'Manager';`, sandbox, { filename });
const review = express();
review.use(express.json());
review.use((req, _res, next) => { const id = Number(req.headers['x-test-user'] || 2); req.user = { UserId: id, Role: users[id] }; next(); });
for (const layer of sandbox.module.exports.app.router.stack) {
if (layer.handle?.stack?.some(entry => entry.route?.path === '/announcements')) review.use('/api/notifications', layer.handle);
if (!layer.route || !(layer.route.path.startsWith('/api/notifications') || layer.route.path === '/api/asset-borrows/:id/process')) continue;
for (const method of Object.keys(layer.route.methods)) review[method](layer.route.path, ...layer.route.stack.map(entry => entry.handle));
}
const missingApi = sandbox.module.exports.app.router.stack.find(layer => !layer.route && layer.handle.toString().includes('API_NOT_FOUND'));
if (missingApi) review.use('/api', missingApi.handle);
const server = review.listen(0, '127.0.0.1');
await new Promise(resolve => server.once('listening', resolve));
t.after(() => new Promise(resolve => server.close(resolve)));
const call = async (route, user = 2, method = 'GET', body) => {
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/${route}`, {
method, headers: { 'x-test-user': String(user), 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined
});
return { status: response.status, ...(await response.json()) };
};
const publish = (user = 1, extra = {}) => call('notifications', user, 'POST', {
title: 'Lịch bảo trì', message: 'Hệ thống bảo trì vào cuối tuần.', expiresAt: new Date(Date.now() + 86400000).toISOString(), ...extra
});
return { call, publish, notices, audiences, reads, dismissals, queries };
}
test('Admin and Asset can publish; viewers cannot publish or access management; expiry is required', async t => {
const f = await fixture(t);
assert.equal((await f.publish(1)).status, 201);
assert.equal((await f.publish(4)).status, 201);
assert.equal((await f.publish(2)).status, 403);
for (const expiresAt of [null, 'bad-date', '2020-01-01T00:00:00Z']) assert.equal((await f.publish(4, { expiresAt })).status, 400);
assert.equal((await f.call('notifications/manage', 2)).status, 403);
assert.equal((await f.call('notifications/manage', 4)).data.length, 2);
assert.equal(f.notices[1].CreatedBy, 4);
});
test('reading broadcasts does not suppress popups; dismissal persists per user and per announcement', async t => {
const f = await fixture(t);
await f.publish(); await f.publish();
await f.call('notifications/read-all', 2, 'PUT');
assert.equal((await f.call('notifications/announcements', 2)).data.length, 2);
assert.equal((await f.call('notifications/1/dismiss', 2, 'PUT', { userId: 3 })).status, 200);
assert.equal((await f.call('notifications/1/dismiss', 2, 'PUT')).status, 200);
assert.equal(f.dismissals.size, 1);
assert.deepEqual((await f.call('notifications/announcements', 2)).data.map(n => n.NotificationId), [2]);
assert.equal((await f.call('notifications/announcements', 3)).data.length, 2);
assert.equal((await f.call('notifications', 2)).data.length, 2, 'dismissed announcements remain in the personal inbox');
});
test('expired or withdrawn announcements stop appearing and Asset may withdraw only their own posts', async t => {
const f = await fixture(t);
await f.publish(1); await f.publish(4); await f.publish(1);
f.notices[2].ExpiresAt = new Date(Date.now() - 1000);
assert.equal((await f.call('notifications/1', 4, 'DELETE')).status, 404);
assert.equal((await f.call('notifications/2', 4, 'DELETE')).status, 200);
assert.deepEqual((await f.call('notifications/announcements')).data.map(n => n.NotificationId), [1]);
assert.equal((await f.call('notifications/3/dismiss', 2, 'PUT')).status, 404);
assert.equal((await f.call('notifications/manage', 1)).data.length, 3);
assert.equal((await f.call('notifications/1', 1, 'DELETE')).status, 200);
assert.equal((await f.call('notifications/announcements')).data.length, 0);
});
test('real borrow decision handler notifies only the owner; other users cannot read, dismiss or see it in popups', async t => {
const f = await fixture(t);
const result = await f.call('asset-borrows/11/process', 4, 'POST', { action: 'rejected', rejectReason: 'Chưa đủ thiết bị' });
assert.equal(result.status, 200);
assert.deepEqual(f.audiences, [{ id: 1, type: 'user', value: '2' }]);
assert.equal((await f.call('notifications', 2)).data.length, 1);
assert.equal((await f.call('notifications', 3)).data.length, 0);
assert.equal((await f.call('notifications/1/read', 3, 'PUT')).status, 404);
assert.equal((await f.call('notifications/1/read', 2, 'PUT')).status, 200);
assert.equal((await f.call('notifications/1/dismiss', 2, 'PUT')).status, 404);
assert.equal((await f.call('notifications/announcements', 2)).data.length, 0);
assert.equal((await f.call('notifications', 3)).unreadCount, 0);
});
test('new notification APIs are protected by the production session middleware', async t => {
const { app } = require('./server');
const server = app.listen(0, '127.0.0.1');
await new Promise(resolve => server.once('listening', resolve));
t.after(() => new Promise(resolve => server.close(resolve)));
const base = `http://127.0.0.1:${server.address().port}`;
for (const [route, method] of [['announcements', 'GET'], ['manage', 'GET'], ['1/dismiss', 'PUT']]) {
const response = await fetch(`${base}/api/notifications/${route}`, { method, headers: { 'x-user-id': '1', 'x-user-role': 'admin' } });
assert.equal(response.status, 401);
}
});
test('unknown authenticated API paths return JSON instead of an HTML error page', async t => {
const f = await fixture(t);
const result = await f.call('notifications/missing-endpoint', 1);
assert.equal(result.status, 404);
assert.equal(result.code, 'API_NOT_FOUND');
assert.equal(result.success, false);
});

View File

@@ -0,0 +1,185 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { createExportSqlFixture } = require('./asset-export-sql-fixture');
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
class Browser {
constructor(url) { this.socket = new WebSocket(url); this.nextId = 0; this.pending = new Map(); this.errors = []; }
async open() {
await new Promise((resolve, reject) => { this.socket.addEventListener('open', resolve, { once: true }); this.socket.addEventListener('error', reject, { once: true }); });
this.socket.addEventListener('message', event => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') this.errors.push(message.params.exceptionDetails);
const pending = this.pending.get(message.id); if (!pending) return;
this.pending.delete(message.id); clearTimeout(pending.timer);
if (message.error) pending.reject(new Error(message.error.message)); else pending.resolve(message.result);
});
}
send(method, params = {}) {
return new Promise((resolve, reject) => {
const id = ++this.nextId;
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Browser timeout: ${method}`)); }, 15000);
this.pending.set(id, { resolve, reject, timer }); this.socket.send(JSON.stringify({ id, method, params }));
});
}
async evaluate(expression) {
const result = await this.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description || result.exceptionDetails.text);
return result.result?.value;
}
async until(expression) {
for (let i = 0; i < 100; i++) { if (await this.evaluate(expression)) return; await delay(100); }
throw new Error(`Browser state timeout: ${expression}`);
}
}
test('Chrome preserves project export proposals and supports immediate manager exports for others on desktop/mobile', {
skip: process.env.ACCMANAGER_EXPORT_BROWSER_TEST !== '1' ? 'Set ACCMANAGER_EXPORT_BROWSER_TEST=1 for isolated Chrome and SQL checks' : false,
timeout: 120000
}, async () => {
const f = await createExportSqlFixture();
const root = path.resolve(__dirname, '..');
const output = path.join(root, 'output/asset-exports'); fs.mkdirSync(output, { recursive: true });
f.app.get('/api/auth/session', (req, res) => res.json({ success: true, user: { ...req.user,
FullName: { 1: 'Nguyễn An', 2: 'Trần Bình', 3: 'Quản lý kho' }[req.user.UserId] } }));
f.app.get('/api/asset-projects', (_req, res) => res.json({ success: true, data: [
{ ProjectId: 1, ProjectName: 'Dự án A' }, { ProjectId: 2, ProjectName: 'Dự án B' }
] }));
f.app.get('/api/users', (_req, res) => res.json({ success: true, data: [
{ UserId: 1, FullName: 'Nguyễn An' }, { UserId: 2, FullName: 'Trần Bình' }, { UserId: 3, FullName: 'Quản lý kho' }
] }));
f.app.use('/api', (_req, res) => res.json({ success: true, data: [], unreadCount: 0, pagination: { total: 0, totalPages: 1 } }));
f.app.get('/test-xlsx.js', (_req, res) => res.sendFile(require.resolve('xlsx/dist/xlsx.full.min.js')));
f.app.get('/test-notiflix.js', (_req, res) => res.type('js').send('window.Notiflix={Notify:{init(){},success(){},failure(){},warning(){}}};'));
f.app.get('/pages/index.html', (_req, res) => res.type('html').send(fs.readFileSync(path.join(root, 'public/pages/index.html'), 'utf8')
.replace('https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js', '/test-xlsx.js')
.replace('https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js', '/test-notiflix.js')));
f.app.use(require('express').static(path.join(root, 'public')));
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'accmanager-export-chrome-'));
const chrome = spawn(process.env.ACCMANAGER_TEST_CHROME || 'C:/Program Files/Google/Chrome/Application/chrome.exe', [
'--headless=new', '--remote-debugging-port=0', `--user-data-dir=${profile}`, '--no-first-run', '--no-default-browser-check', '--hide-scrollbars', 'about:blank'
], { stdio: 'ignore', windowsHide: true });
let client;
try {
const portFile = path.join(profile, 'DevToolsActivePort');
for (let i = 0; i < 100 && !fs.existsSync(portFile); i++) await delay(100);
const port = Number(fs.readFileSync(portFile, 'utf8').split('\n')[0]);
const targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json();
client = new Browser(targets.find(target => target.type === 'page').webSocketDebuggerUrl); await client.open();
await client.send('Runtime.enable'); await client.send('Page.enable'); await client.send('Network.enable');
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
await client.send('Page.navigate', { url: `${f.origin}/pages/index.html#assets` });
await client.until('typeof app !== "undefined" && app?.assets?.length === 3 && !!document.getElementById("borrowAssetBtn")');
assert.equal(await client.evaluate('!!document.getElementById("exportAssetForOthersBtn")'), false);
await client.evaluate(`document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.getElementById('borrowAssetBtn').click()`);
await client.until('document.getElementById("borrowAssetModal").classList.contains("open")');
assert.equal(await client.evaluate('document.getElementById("borrowAssetUserInput").value'), 'Nguyễn An');
await client.evaluate('document.getElementById("borrowAssetProjectInput").value="Dự án A"; document.getElementById("borrowQuantityInput").value="2"; document.getElementById("addBorrowProjectBtn").click(); document.querySelector("#borrowAdditionalProjects select").value="Dự án B"; document.querySelector("#borrowAdditionalProjects input").value="1"; document.getElementById("borrowAssetForm").requestSubmit()');
await client.until('app.currentPage === "asset-exports" && !app.assetExportLoading && app.assetExportRequests.length === 1');
assert.equal(await client.evaluate('document.querySelectorAll(".process-asset-export").length'), 0);
assert.equal((await f.pool.request().query('SELECT EndingBalance FROM AssetInventory WHERE AssetId = 1')).recordset[0].EndingBalance, 10);
// Existing batch form remains available to ordinary users.
await client.evaluate('location.hash="#assets"');
await client.until('!!document.getElementById("borrowAssetBtn")');
await client.evaluate(`document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.querySelector('.asset-row-checkbox[data-asset-id="2"]').click(); document.getElementById('borrowAssetBtn').click()`);
await client.until('document.getElementById("batchAssetExportModal").classList.contains("open")');
await client.evaluate('const project=document.getElementById("batchAssetExportCommonProject"); project.value="Dự án A"; project.dispatchEvent(new Event("change")); document.getElementById("batchAssetExportForm").requestSubmit()');
await client.until('app.currentPage === "asset-exports" && !app.assetExportLoading && app.assetExportRequests.length === 2');
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '3', 'x-test-role': 'asset' } });
await client.send('Page.reload');
await client.until('typeof app !== "undefined" && app?.currentUser?.Role === "asset" && !app.assetExportLoading && document.querySelectorAll(".process-asset-export").length === 4');
await client.evaluate('document.querySelector(".process-asset-export[data-action=approved]").click()');
await client.until('document.getElementById("assetExportProcessModal").classList.contains("open")');
await client.evaluate('document.getElementById("assetExportProcessForm").requestSubmit()');
await client.until('!app.assetExportProcessing && app.assetExportRequests.some(row=>row.RequestStatus === "approved")');
assert.equal((await f.pool.request().query('SELECT EndingBalance FROM AssetInventory WHERE AssetId = 1')).recordset[0].EndingBalance, 9);
await client.evaluate('document.querySelector(".process-asset-export[data-action=rejected]").click()');
await client.until('document.getElementById("assetExportProcessModal").classList.contains("open")');
await client.evaluate('document.getElementById("assetExportRejectReason").value="Điều chỉnh số lượng theo dự án"; document.getElementById("assetExportProcessForm").requestSubmit()');
await client.until('!app.assetExportProcessing && app.assetExportRequests.some(row=>row.RequestStatus === "rejected")');
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '1', 'x-test-role': 'user' } });
await client.send('Page.reload');
await client.until('typeof app !== "undefined" && app?.currentUser?.Role === "user" && !app.assetExportLoading && app.assetExportRequests.length === 2');
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'requests.png'), Buffer.from(result.data, 'base64')));
await client.evaluate('document.querySelector(".view-asset-export-document").click()');
await client.until('document.getElementById("assetExportPreviewContent").textContent.includes("Dự án A")');
await client.evaluate('document.querySelector("[data-close-modal=assetExportPreviewModal]").click(); app.downloadBlobFile=(blob,name)=>{window.savedDownload={size:blob.size,name}}; document.querySelector(".download-asset-export-document").click()');
await client.until('window.savedDownload?.size > 1000');
// A failed reload clears stale rows and offers a useful retry.
await client.evaluate('window.originalExportFetch=window.fetch; window.fetch=(url,options)=>String(url).includes("asset-export-requests") ? Promise.resolve({ok:false,json:async()=>({success:false,message:"Không tải được danh sách thử nghiệm"})}) : originalExportFetch(url,options); document.getElementById("refreshAssetExportsBtn").click()');
await client.until('!app.assetExportLoading && !!app.assetExportLoadError');
assert.equal(await client.evaluate('app.assetExportRequests.length'), 0);
await client.evaluate('window.fetch=window.originalExportFetch; document.getElementById("refreshAssetExportsBtn").click()');
await client.until('!app.assetExportLoading && app.assetExportRequests.length === 2');
await client.evaluate('document.getElementById("assetExportHistoryTab").click()');
assert.equal(await client.evaluate('!!document.getElementById("assetExportHistoryModal")'), false);
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'desktop.png'), Buffer.from(result.data, 'base64')));
await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
await delay(250);
assert.equal(await client.evaluate('document.documentElement.scrollWidth <= innerWidth + 1'), true);
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'mobile.png'), Buffer.from(result.data, 'base64')));
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '2', 'x-test-role': 'user' } });
await client.send('Page.reload');
await client.until('typeof app !== "undefined" && app?.currentUser?.UserId === 2 && !app.assetExportLoading && !!document.getElementById("assetExportsTableBody")');
assert.equal(await client.evaluate('app.assetExportRequests.length'), 0);
assert.equal(await client.evaluate('!!document.getElementById("createAssetExportForOthersBtn")'), false);
// The additional manager action exports immediately; the proposal action remains available.
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '3', 'x-test-role': 'admin' } });
await client.send('Page.reload');
await client.until('typeof app !== "undefined" && app?.currentUser?.Role === "admin" && !!document.getElementById("createAssetExportForOthersBtn")');
await client.evaluate('document.getElementById("createAssetExportForOthersBtn").click()');
await client.until('typeof app !== "undefined" && app?.currentUser?.Role === "admin" && app.assets.length === 3 && !!document.getElementById("exportAssetForOthersBtn")');
await client.evaluate(`app.downloadBlobFile=(blob,name)=>{window.savedDownload={size:blob.size,name}}; document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.getElementById('exportAssetForOthersBtn').click()`);
await client.until('document.getElementById("borrowAssetModal").classList.contains("open")');
assert.equal(await client.evaluate('document.getElementById("borrowAssetRecipientInput").required'), true);
assert.equal(await client.evaluate('document.getElementById("borrowAssetRequesterField").hidden'), true);
await client.evaluate('document.getElementById("borrowAssetRecipientInput").value="Trần Bình"; document.getElementById("borrowAssetProjectInput").value="Dự án A"; const quantity=document.getElementById("borrowQuantityInput"); quantity.value="2"; quantity.dispatchEvent(new Event("input",{bubbles:true})); document.querySelector("#borrowAssetForm button[type=submit]").scrollIntoView({block:"nearest"})');
await delay(250);
assert.equal(await client.evaluate('document.querySelector("#borrowAssetForm button[type=submit]").getBoundingClientRect().bottom <= innerHeight'), true);
assert.equal(await client.evaluate('document.documentElement.scrollWidth <= innerWidth + 1'), true);
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'export-for-others-mobile.png'), Buffer.from(result.data, 'base64')));
await client.evaluate('document.getElementById("borrowAssetForm").requestSubmit()');
await client.until('!app.assetExportSubmitting && app.assets.find(row=>row.AssetId===1).EndingBalance===7 && window.savedDownload?.size>1000');
assert.equal((await f.pool.request().query('SELECT COUNT(*) AS total FROM AssetExportRequests')).recordset[0].total, 2);
assert.equal(await client.evaluate('location.hash'), '#assets');
await client.evaluate(`app.closeModals(); document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.getElementById('borrowAssetBtn').click()`);
await client.until('document.getElementById("borrowAssetModal").classList.contains("open")');
assert.equal(await client.evaluate('document.getElementById("borrowAssetForm").dataset.exportForOthers'), 'false');
assert.equal(await client.evaluate('document.getElementById("borrowAssetRecipientInput").disabled'), true);
assert.equal(await client.evaluate('document.querySelector("#borrowAssetForm button[type=submit]").textContent'), 'Gửi đơn chờ duyệt');
// The asset role can export multiple items for a recipient in one saved document.
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '3', 'x-test-role': 'asset' } });
await client.send('Page.reload');
await client.until('typeof app !== "undefined" && app?.currentUser?.Role === "asset" && app.assets.length === 3 && !!document.getElementById("exportAssetForOthersBtn")');
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
await client.evaluate(`app.downloadBlobFile=(blob,name)=>{window.savedDownload={size:blob.size,name}}; document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.querySelector('.asset-row-checkbox[data-asset-id="2"]').click(); document.getElementById('exportAssetForOthersBtn').click()`);
await client.until('document.getElementById("batchAssetExportModal").classList.contains("open")');
await client.evaluate('document.getElementById("batchAssetExportRecipientInput").value="Nguyễn An"; const common=document.getElementById("batchAssetExportCommonProject"); common.value="Dự án B"; common.dispatchEvent(new Event("change"))');
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'batch-export-for-others.png'), Buffer.from(result.data, 'base64')));
await client.evaluate('document.getElementById("batchAssetExportForm").requestSubmit()');
await client.until('!app.assetExportSubmitting && app.assets.find(row=>row.AssetId===1).EndingBalance===6 && window.savedDownload?.size>1000');
assert.equal((await f.pool.request().query('SELECT EndingBalance FROM AssetInventory WHERE AssetId = 2')).recordset[0].EndingBalance, 3);
assert.equal((await f.pool.request().query('SELECT COUNT(*) AS total FROM AssetExportRequests')).recordset[0].total, 2);
const saved = (await f.pool.request().query('SELECT SnapshotJson FROM AssetExportDocuments ORDER BY ExportedDate DESC')).recordset;
assert.equal(JSON.parse(saved[0].SnapshotJson).requesterName, 'Nguyễn An');
assert.equal(JSON.parse(saved[1].SnapshotJson).requesterName, 'Trần Bình');
await client.evaluate(`app.closeModals(); document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.querySelector('.asset-row-checkbox[data-asset-id="2"]').click(); document.getElementById('borrowAssetBtn').click()`);
await client.until('document.getElementById("batchAssetExportModal").classList.contains("open")');
assert.equal(await client.evaluate('document.getElementById("batchAssetExportForm").dataset.exportForOthers'), 'false');
assert.equal(await client.evaluate('document.getElementById("batchAssetExportRecipientInput").disabled'), true);
assert.deepEqual(client.errors, []);
} catch (err) {
if (client) console.error('Browser failure state:', await client.evaluate(`({ url: location.href,
role: typeof app !== 'undefined' && app?.currentUser?.Role, page: typeof app !== 'undefined' && app?.currentPage,
assets: typeof app !== 'undefined' && app?.assets?.length, errors: document.body.innerText.slice(-500) })`), client.errors);
throw err;
} finally {
if (client) client.socket.close();
chrome.kill();
await f.cleanup();
}
});

View File

@@ -0,0 +1,8 @@
const fs = require('node:fs');
const path = require('node:path');
async function ensureAssetExportDocumentSchema(pool) {
await pool.request().batch(fs.readFileSync(path.join(__dirname, 'asset-export-documents.sql'), 'utf8'));
}
module.exports = { ensureAssetExportDocumentSchema };

View File

@@ -0,0 +1,27 @@
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.AssetExportDocuments', 'U') IS NULL
BEGIN
CREATE TABLE dbo.AssetExportDocuments (
ExportDocumentId UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,
FileName NVARCHAR(255) NOT NULL,
MimeType NVARCHAR(150) NOT NULL,
FileContent VARBINARY(MAX) NOT NULL,
SnapshotJson NVARCHAR(MAX) NOT NULL,
CreatedBy INT NULL,
ExportedDate DATETIME NOT NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME()))
);
END;
IF COL_LENGTH('dbo.AssetExportHistory', 'ExportDocumentId') IS NULL
ALTER TABLE dbo.AssetExportHistory ADD ExportDocumentId UNIQUEIDENTIFIER NULL;
IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_AssetExportHistory_Document')
EXEC(N'ALTER TABLE dbo.AssetExportHistory ADD CONSTRAINT FK_AssetExportHistory_Document
FOREIGN KEY (ExportDocumentId) REFERENCES dbo.AssetExportDocuments(ExportDocumentId)');
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;

View File

@@ -0,0 +1,135 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const sql = require('mssql');
const XLSX = require('xlsx');
const { createExportSqlFixture } = require('./asset-export-sql-fixture');
test('managers export for another recipient immediately while pending proposals remain separate', {
skip: process.env.ACCMANAGER_EXPORT_SQL_TEST !== '1' ? 'Set ACCMANAGER_EXPORT_SQL_TEST=1 for a disposable database' : false,
timeout: 120000
}, async () => {
const f = await createExportSqlFixture();
try {
const allocations = [{ projectName: 'Dự án A', quantity: 2 }, { projectName: 'Dự án B', quantity: 1 }];
const stock = async id => (await f.pool.request().input('id', sql.Int, id)
.query('SELECT EndingBalance, Borrower FROM AssetInventory WHERE AssetId = @id')).recordset[0];
const payload = { borrowerName: 'Trần Bình', allocations, note: 'Cấp cho người khác' };
for (const endpoint of ['/assets/1/export', '/assets/export']) {
assert.equal((await f.request(endpoint, { method: 'POST', body: payload })).status, 403);
}
const pending = await f.request('/asset-export-requests', { user: 3, role: 'admin', method: 'POST', body: {
borrowerName: 'Trần Bình', items: [{ assetId: 1, allocations }]
} });
assert.equal(pending.data.RequestStatus, 'pending'); assert.equal(pending.data.RequesterName, 'Quản lý kho');
assert.equal((await stock(1)).EndingBalance, 10);
const single = await f.request('/assets/1/export', { user: 3, role: 'admin', method: 'POST', body: payload });
assert.equal(single.status, 200); assert.equal(single.data.length, 2);
assert.equal((await stock(1)).EndingBalance, 7); assert.equal((await stock(1)).Borrower, null);
const document = await f.request(`/asset-export-documents/${single.document.documentId}`, { user: 3, role: 'admin' });
assert.equal(document.data.snapshot.borrowerName, 'Trần Bình');
assert.equal(document.data.snapshot.exportedByName, 'Quản lý kho');
const download = await f.request(`/asset-export-documents/${single.document.documentId}/download`, { user: 3, role: 'admin' });
assert.deepEqual(download.buffer, Buffer.from(single.document.contentBase64, 'base64'));
assert.ok(XLSX.read(download.buffer).Sheets.ycxvt);
const batch = await f.request('/assets/export', { user: 3, role: 'asset', method: 'POST', body: {
borrowerName: 'Nguyễn An', items: [{ assetId: 1, projectName: 'Dự án B', quantity: 1 },
{ assetId: 2, projectName: 'Dự án A', quantity: 2 }]
} });
assert.equal(batch.status, 200); assert.equal(batch.data.length, 2);
assert.equal((await stock(1)).EndingBalance, 6); assert.equal((await stock(2)).EndingBalance, 3);
const requests = await f.request('/asset-export-requests', { user: 3, role: 'asset' });
assert.equal(requests.data.length, 1); assert.equal(requests.data[0].RequestStatus, 'pending');
const failed = await f.request('/assets/export', { user: 3, role: 'asset', method: 'POST', body: {
borrowerName: 'Trần Bình', items: [{ assetId: 1, projectName: 'A', quantity: 1 },
{ assetId: 2, projectName: 'A', quantity: 100 }]
} });
assert.equal(failed.status, 400);
assert.equal((await stock(1)).EndingBalance, 6); assert.equal((await stock(2)).EndingBalance, 3);
assert.equal((await f.pool.request().query('SELECT COUNT(*) AS total FROM AssetExportDocuments')).recordset[0].total, 2);
} finally { await f.cleanup(); }
});
test('SQL project export approvals preserve stock, ownership, documents, return isolation and concurrent decisions', {
skip: process.env.ACCMANAGER_EXPORT_SQL_TEST !== '1' ? 'Set ACCMANAGER_EXPORT_SQL_TEST=1 for a disposable database' : false,
timeout: 120000
}, async () => {
const f = await createExportSqlFixture();
try {
const items = [{ assetId: 1, allocations: [{ projectName: 'Dự án A', quantity: 2 }, { projectName: 'Dự án B', quantity: 3 }] },
{ assetId: 2, allocations: [{ projectName: 'Dự án A', quantity: 2 }] }];
const stock = async id => (await f.pool.request().query(`SELECT * FROM AssetInventory WHERE AssetId = ${id}`)).recordset[0];
const count = async table => (await f.pool.request().query(`SELECT COUNT(*) AS total FROM ${table}`)).recordset[0].total;
const create = (rows = items, user = 1) => f.request('/asset-export-requests', { user, method: 'POST', body: {
items: rows, note: 'Cấp tài sản vào dự án', createdBy: 2, borrowerName: 'Tên giả mạo', requestStatus: 'approved'
} });
const process = (id, action = 'approved', extra = {}) => f.request(`/asset-export-requests/${id}/process`, {
role: 'asset', user: 3, method: 'POST', body: { action, ...extra }
});
const created = await create();
assert.equal(created.status, 201); assert.equal(created.data.RequestStatus, 'pending');
assert.equal(created.data.CreatedBy, 1); assert.equal(created.data.RequesterName, 'Nguyễn An');
assert.equal((await stock(1)).EndingBalance, 10); assert.equal(await count('AssetExportDocuments'), 0);
const id = created.data.ExportRequestId;
assert.equal((await f.request(`/asset-export-requests/${id}/process`, { method: 'POST', body: { action: 'approved' } })).status, 403);
assert.equal((await f.request('/asset-export-requests', { user: 2 })).data.length, 0);
assert.equal((await f.request('/asset-export-requests', { user: 3, role: 'admin' })).data.length, 1);
// Existing privileged export endpoints remain privileged.
assert.equal((await f.request('/assets/1/export', { method: 'POST', body: items[0] })).status, 403);
const approved = await process(id);
assert.equal(approved.status, 200); assert.equal(approved.data.RequestStatus, 'approved');
assert.equal((await stock(1)).EndingBalance, 5); assert.equal((await stock(1)).ExportInPeriod, 5);
assert.equal((await stock(1)).Borrower, null); assert.equal((await stock(2)).EndingBalance, 3);
assert.equal(await count('AssetBorrowRequests'), 0); assert.equal(await count('AssetExportHistory'), 3);
const allocations = JSON.parse((await stock(1)).ProjectAllocations);
assert.deepEqual(allocations.map(row => [row.projectName, row.quantity, row.allocationType]), [['Dự án A', 2, 'export'], ['Dự án B', 3, 'export']]);
assert.equal((await f.request('/asset-export-history', { user: 2 })).data.length, 0);
assert.equal((await f.request('/asset-export-history')).data.length, 3);
const docId = approved.data.ExportDocumentId;
const preview = await f.request(`/asset-export-documents/${docId}`);
assert.equal(preview.status, 200); assert.equal(preview.data.snapshot.requesterName, 'Nguyễn An');
assert.equal(preview.data.snapshot.exportedByName, 'Quản lý kho');
const downloaded = await f.request(`/asset-export-documents/${docId}/download`);
assert.equal(downloaded.status, 200);
assert.deepEqual(downloaded.buffer, Buffer.from(approved.document.contentBase64, 'base64'));
const workbook = XLSX.read(downloaded.buffer); assert.ok(workbook.Sheets.ycxvt);
assert.equal((await f.request(`/asset-export-documents/${docId}`, { user: 2 })).status, 404);
assert.equal((await f.request(`/asset-export-documents/${docId}/download`, { user: 2 })).status, 404);
assert.equal((await process(id)).status, 409); assert.equal((await stock(1)).EndingBalance, 5);
// A user cannot return the permanent allocation through the loan API.
assert.equal((await f.request('/asset-borrows', { method: 'POST', body: { assetId: 1, requestType: 'return', quantity: 1 } })).status, 400);
// Borrow and return two pieces; the five permanent pieces stay issued.
const borrowed = await f.request('/asset-borrows', { method: 'POST', body: { assetId: 1, requestType: 'borrow', quantity: 2 } });
const borrowId = borrowed.data.borrowId;
assert.equal((await f.request(`/asset-borrows/${borrowId}/process`, { user: 3, role: 'asset', method: 'POST', body: { action: 'approved' } })).status, 200);
assert.equal((await stock(1)).EndingBalance, 3);
const returned = await f.request(`/asset-borrows/${borrowId}/return`, { method: 'POST', body: { quantity: 2 } });
assert.equal((await f.request(`/asset-borrows/${returned.data.borrowId}/process`, { user: 3, role: 'asset', method: 'POST', body: { action: 'approved' } })).status, 200);
assert.equal((await stock(1)).EndingBalance, 5); assert.equal((await stock(1)).ExportInPeriod, 5);
assert.deepEqual(JSON.parse((await stock(1)).ProjectAllocations), allocations);
// Rejection never consumes inventory; approval rechecks current stock.
const rejected = await create([{ assetId: 1, projectName: 'Dự án C', quantity: 1 }], 2);
assert.equal((await process(rejected.data.ExportRequestId, 'rejected')).status, 400);
assert.equal((await process(rejected.data.ExportRequestId, 'rejected', { rejectReason: 'Chưa phù hợp' })).status, 200);
assert.equal((await stock(1)).EndingBalance, 5);
const a = await create([{ assetId: 3, projectName: 'Dự án A', quantity: 3 }]);
const b = await create([{ assetId: 3, projectName: 'Dự án B', quantity: 3 }], 2);
const races = await Promise.all([process(a.data.ExportRequestId), process(b.data.ExportRequestId)]);
assert.deepEqual(races.map(row => row.status).sort(), [200, 400]); assert.equal((await stock(3)).EndingBalance, 1);
const same = await create([{ assetId: 3, projectName: 'Dự án C', quantity: 1 }]);
assert.deepEqual((await Promise.all([process(same.data.ExportRequestId), process(same.data.ExportRequestId)])).map(row => row.status).sort(), [200, 409]);
assert.equal((await stock(3)).EndingBalance, 0);
// Failure in history after file/stock writes rolls the entire approval back.
const failing = await create([{ assetId: 1, projectName: 'FAIL', quantity: 1 }]);
const documentsBefore = await count('AssetExportDocuments');
await f.pool.request().query("ALTER TABLE AssetExportHistory ADD CONSTRAINT CK_ExportTest_Failure CHECK (ProjectName <> 'FAIL')");
assert.equal((await process(failing.data.ExportRequestId)).status, 500);
assert.equal((await stock(1)).EndingBalance, 5); assert.equal(await count('AssetExportDocuments'), documentsBefore);
assert.equal((await f.request('/asset-export-requests')).data.find(row => row.ExportRequestId === failing.data.ExportRequestId).RequestStatus, 'pending');
// An archived line prevents all other lines in that approval from being issued.
const archived = await create([{ assetId: 1, projectName: 'A', quantity: 1 }, { assetId: 2, projectName: 'A', quantity: 1 }]);
await f.pool.request().query('UPDATE AssetInventory SET IsArchived = 1 WHERE AssetId = 2');
assert.equal((await process(archived.data.ExportRequestId)).status, 404);
assert.equal((await stock(1)).EndingBalance, 5); assert.equal(await count('AssetExportDocuments'), documentsBefore);
assert.equal((await f.request(`/asset-export-documents/${docId}/download`)).buffer.equals(downloaded.buffer), true);
} finally { await f.cleanup(); }
});

View File

@@ -0,0 +1,176 @@
const fs = require('node:fs');
const path = require('node:path');
const express = require('express');
const { normalizeExportAllocations } = require('./asset-project-allocations');
async function ensureAssetExportRequestSchema(pool) {
await pool.request().batch(fs.readFileSync(path.join(__dirname, 'asset-export-requests.sql'), 'utf8'));
}
function normalizeExportItems(rawItems) {
if (!Array.isArray(rawItems) || !rawItems.length || rawItems.length > 100) {
throw new Error('Vui lòng chọn từ 1 đến 100 tài sản.');
}
const seen = new Set();
const items = rawItems.map(row => {
const assetId = Number(row?.assetId);
if (!Number.isSafeInteger(assetId) || assetId <= 0 || assetId > 2147483647) throw new Error('Mã tài sản không hợp lệ.');
if (seen.has(assetId)) throw new Error('Mỗi tài sản chỉ được xuất hiện một lần trong phiếu.');
seen.add(assetId);
return { assetId, allocations: normalizeExportAllocations(row) };
});
if (items.reduce((sum, item) => sum + item.allocations.length, 0) > 100) {
throw new Error('Một phiếu chỉ hỗ trợ tối đa 100 dòng tài sản / dự án.');
}
return items;
}
function createAssetExportWorkflow({ getPool, sql, requireManage, getRequesterRole, getUserIdFromRequest,
getUserDisplayNameById, prepareAssetExport, performAssetExport, sendInternalError, notifyProcessed, notifyCreated }) {
const router = express.Router();
const canManage = req => ['admin', 'asset'].includes(getRequesterRole(req));
const serialize = row => ({ ...row, Items: JSON.parse(row.ItemsJson), ItemsJson: undefined });
const fail = (statusCode, message) => { throw Object.assign(new Error(message), { statusCode }); };
async function handleError(transaction, res, err) {
if (transaction) {
try { await transaction.rollback(); } catch { /* Preserve the original failure. */ }
}
if (err.statusCode) return res.status(err.statusCode).json({ success: false, message: err.message });
return sendInternalError(res, err);
}
async function loadPlans(transaction, items, note) {
const assets = new Map();
// Use the same order for overlapping requests so approvals cannot overdraw stock.
for (const { assetId } of [...items].sort((a, b) => a.assetId - b.assetId)) {
const result = await new sql.Request(transaction).input('assetId', sql.Int, assetId).query(`
SELECT TOP 1 AssetId, AssetCode, AssetName, Quantity, ImportInPeriod, ExportInPeriod,
EndingBalance, NewQuantity, UsedQuantity, Custodian, Borrower, ProjectAllocations,
Model, SerialNumber, Unit, Department, Notes
FROM AssetInventory WITH (UPDLOCK, HOLDLOCK)
WHERE AssetId = @assetId AND IsArchived = 0
`);
if (!result.recordset?.[0]) fail(404, `Tài sản #${assetId} không còn trong danh mục hiện tại.`);
assets.set(assetId, result.recordset[0]);
}
return items.map(item => prepareAssetExport(assets.get(item.assetId), item.allocations, note));
}
async function createRequest(req, res, singleAssetId) {
let transaction;
try {
let items;
try {
items = normalizeExportItems(singleAssetId === undefined ? req.body?.items : [{ ...req.body, assetId: singleAssetId }]);
} catch (err) { fail(400, err.message); }
const createdBy = getUserIdFromRequest(req);
const requesterName = String(await getUserDisplayNameById(createdBy) || req.user?.FullName || req.user?.Username || '').trim();
if (!createdBy || !requesterName || requesterName.length > 100) fail(400, 'Không xác định được người đề xuất hợp lệ.');
const note = String(req.body?.note || '').trim() || null;
if (note && note.length > 1000) fail(400, 'Ghi chú xuất tối đa 1000 ký tự.');
transaction = new sql.Transaction(getPool());
await transaction.begin();
const plans = await loadPlans(transaction, items, note);
// Preserve the requested descriptions even if the catalog is later edited or archived.
const snapshot = plans.map(plan => ({ assetId: plan.asset.AssetId, assetCode: plan.asset.AssetCode,
assetName: plan.asset.AssetName, model: plan.asset.Model, unit: plan.asset.Unit, allocations: plan.allocations }));
const result = await new sql.Request(transaction)
.input('requesterName', sql.NVarChar(100), requesterName)
.input('itemsJson', sql.NVarChar(sql.MAX), JSON.stringify(snapshot))
.input('requestNote', sql.NVarChar(1000), note)
.input('createdBy', sql.Int, createdBy)
.query(`INSERT INTO AssetExportRequests (RequesterName, ItemsJson, RequestNote, CreatedBy)
OUTPUT INSERTED.* VALUES (@requesterName, @itemsJson, @requestNote, @createdBy)`);
await transaction.commit();
transaction = undefined;
if (notifyCreated) await notifyCreated(result.recordset[0]);
return res.status(201).json({ success: true, message: 'Đã gửi đơn xuất dự án, chờ admin/asset duyệt.', data: serialize(result.recordset[0]) });
} catch (err) { return handleError(transaction, res, err); }
}
// Keep the existing manager-only export API for integrations. The UI submits
// proposals through this router; approval uses the same atomic stock writer.
async function directExport(req, res, singleAssetId) {
let transaction;
try {
let items;
try { items = normalizeExportItems(singleAssetId === undefined ? req.body?.items : [{ ...req.body, assetId: singleAssetId }]); }
catch (err) { fail(400, err.message); }
const requesterName = String(req.body?.borrowerName || req.body?.custodianName || '').trim();
const exportNote = String(req.body?.note || '').trim() || null;
if (!requesterName || requesterName.length > 100) fail(400, 'Vui lòng chọn người đề nghị xuất, tối đa 100 ký tự.');
if (exportNote && exportNote.length > 1000) fail(400, 'Ghi chú xuất tối đa 1000 ký tự.');
const createdBy = getUserIdFromRequest(req);
const exportedByName = await getUserDisplayNameById(createdBy) || req.user?.FullName || req.user?.Username;
transaction = new sql.Transaction(getPool());
await transaction.begin();
const plans = await loadPlans(transaction, items, exportNote);
const exported = await performAssetExport(transaction, plans, { createdBy, requesterName, exportedByName, exportNote });
await transaction.commit();
res.json({ success: true, message: 'Xuất tài sản vào dự án thành công.',
data: singleAssetId !== undefined && req.body.allocations === undefined ? exported.histories[0] : exported.histories,
document: exported.document });
} catch (err) { return handleError(transaction, res, err); }
}
router.get('/', async (req, res) => {
try {
const result = await getPool().request().input('requesterId', sql.Int, getUserIdFromRequest(req) || -1).query(`
SELECT r.*, d.FileName AS DocumentFileName FROM AssetExportRequests r
LEFT JOIN AssetExportDocuments d ON d.ExportDocumentId = r.ExportDocumentId
${canManage(req) ? '' : 'WHERE r.CreatedBy = @requesterId'}
ORDER BY r.CreatedDate DESC, r.ExportRequestId DESC
`);
res.setHeader('Cache-Control', 'private, no-store');
res.json({ success: true, data: result.recordset.map(serialize) });
} catch (err) { sendInternalError(res, err); }
});
router.post('/', (req, res) => createRequest(req, res));
router.post('/:id/process', requireManage, async (req, res) => {
let transaction;
try {
const requestId = Number(req.params.id);
const action = req.body?.action;
const rejectReason = String(req.body?.rejectReason || '').trim() || null;
if (!Number.isSafeInteger(requestId) || requestId <= 0 || requestId > 2147483647) fail(400, 'Mã đơn không hợp lệ.');
if (!['approved', 'rejected'].includes(action)) fail(400, 'Hành động không hợp lệ.');
if (action === 'rejected' && (!rejectReason || rejectReason.length > 1000)) fail(400, 'Vui lòng nhập lý do từ chối, tối đa 1000 ký tự.');
const processedBy = getUserIdFromRequest(req);
const processedByName = await getUserDisplayNameById(processedBy) || req.user?.FullName || req.user?.Username;
transaction = new sql.Transaction(getPool());
await transaction.begin();
const result = await new sql.Request(transaction).input('requestId', sql.Int, requestId).query(`
SELECT * FROM AssetExportRequests WITH (UPDLOCK, HOLDLOCK) WHERE ExportRequestId = @requestId
`);
const target = result.recordset[0];
if (!target) fail(404, 'Không tìm thấy đơn xuất.');
if (target.RequestStatus !== 'pending') fail(409, 'Đơn xuất đã được xử lý trước đó.');
let exported;
if (action === 'approved') {
const items = normalizeExportItems(JSON.parse(target.ItemsJson));
const plans = await loadPlans(transaction, items, target.RequestNote);
exported = await performAssetExport(transaction, plans, { createdBy: target.CreatedBy,
requesterName: target.RequesterName, exportedByName: processedByName, exportNote: target.RequestNote });
}
const saved = await new sql.Request(transaction)
.input('requestId', sql.Int, requestId)
.input('status', sql.NVarChar(20), action)
.input('rejectReason', sql.NVarChar(1000), action === 'rejected' ? rejectReason : null)
.input('processedBy', sql.Int, processedBy)
.input('processedByName', sql.NVarChar(100), processedByName)
.input('documentId', sql.UniqueIdentifier, exported?.document.documentId || null)
.query(`UPDATE AssetExportRequests SET RequestStatus = @status, RejectReason = @rejectReason,
ProcessedBy = @processedBy, ProcessedByName = @processedByName,
ProcessedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()), ExportDocumentId = @documentId
OUTPUT INSERTED.* WHERE ExportRequestId = @requestId`);
await transaction.commit();
transaction = undefined;
if (notifyProcessed) await notifyProcessed(target, action, rejectReason);
res.json({ success: true, message: action === 'approved' ? 'Đã duyệt và xuất tài sản khỏi kho.' : 'Đã từ chối đơn xuất.',
data: serialize(saved.recordset[0]), document: exported?.document });
} catch (err) { return handleError(transaction, res, err); }
});
return { router, createRequest, directExport };
}
module.exports = { ensureAssetExportRequestSchema, normalizeExportItems, createAssetExportWorkflow };

View File

@@ -0,0 +1,31 @@
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.AssetExportRequests', 'U') IS NULL
BEGIN
CREATE TABLE dbo.AssetExportRequests (
ExportRequestId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
RequesterName NVARCHAR(100) NOT NULL,
ItemsJson NVARCHAR(MAX) NOT NULL,
RequestNote NVARCHAR(1000) NULL,
RequestStatus NVARCHAR(20) NOT NULL DEFAULT 'pending',
CreatedBy INT NOT NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
ProcessedBy INT NULL,
ProcessedByName NVARCHAR(100) NULL,
ProcessedDate DATETIME NULL,
RejectReason NVARCHAR(1000) NULL,
ExportDocumentId UNIQUEIDENTIFIER NULL,
CONSTRAINT CK_AssetExportRequests_Status CHECK (RequestStatus IN ('pending', 'approved', 'rejected')),
CONSTRAINT FK_AssetExportRequests_User FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId),
CONSTRAINT FK_AssetExportRequests_Document FOREIGN KEY (ExportDocumentId) REFERENCES dbo.AssetExportDocuments(ExportDocumentId)
);
CREATE INDEX IX_AssetExportRequests_Creator ON dbo.AssetExportRequests(CreatedBy, CreatedDate DESC);
CREATE INDEX IX_AssetExportRequests_Status ON dbo.AssetExportRequests(RequestStatus, CreatedDate DESC);
END;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;

View File

@@ -0,0 +1,53 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { normalizeExportItems } = require('./asset-export-requests');
const { addProjectExports, releaseAllocations } = require('./asset-project-allocations');
const { createExportTestApp } = require('./asset-export-test-fixture');
test('project export proposals require positive integer quantities, project names and unique inventory IDs', () => {
for (const value of [[], null, [{ assetId: 0, projectName: 'A', quantity: 1 }],
[{ assetId: 1, projectName: '', quantity: 1 }], [{ assetId: 1, projectName: 'A', quantity: 1.5 }],
[{ assetId: 1, projectName: 'A', quantity: -1 }],
[{ assetId: 1, projectName: 'A', quantity: 1 }, { assetId: 1, projectName: 'B', quantity: 1 }],
Array.from({ length: 101 }, (_, i) => ({ assetId: i + 1, projectName: 'A', quantity: 1 }))]) {
assert.throws(() => normalizeExportItems(value));
}
assert.deepEqual(normalizeExportItems([{ assetId: 1, allocations: [
{ projectName: 'Dự án A', quantity: 2 }, { projectName: 'Dự án B', quantity: 3 }
] }])[0].allocations.map(row => row.quantity), [2, 3]);
});
test('permanent project exports consume the existing stock ledger without adding returnable borrowers', () => {
const { prepareAssetExport } = createExportTestApp({});
const asset = { AssetId: 1, AssetCode: 'TS-001', Quantity: 12, ImportInPeriod: 3,
ExportInPeriod: 4, EndingBalance: 11, NewQuantity: 3, UsedQuantity: 8,
Borrower: 'An (2)', ProjectAllocations: JSON.stringify([{ projectName: 'Cũ', borrowerName: '', quantity: 2 }]) };
const plan = prepareAssetExport(asset, [{ projectName: 'Dự án A', quantity: 2 }, { projectName: 'Dự án B', quantity: 3 }], 'Dự án mới');
assert.equal(plan.exportInPeriod, 9);
assert.equal(plan.endingBalance, 6);
assert.equal(plan.newQuantity, 0);
assert.equal(plan.usedQuantity, 6);
assert.equal(plan.borrower, undefined);
assert.equal(asset.Borrower, 'An (2)');
assert.throws(() => prepareAssetExport(asset, [{ projectName: 'A', quantity: 12 }]), /vượt quá/);
assert.throws(() => prepareAssetExport({ ...asset, EndingBalance: 0 }, [{ projectName: 'A', quantity: 1 }]), /hết tồn/);
});
test('returning a loan preserves all quantities permanently issued into projects', () => {
const legacyLoan = [{ projectName: 'Mượn cũ', borrowerName: 'An', quantity: 3 }];
const allocations = addProjectExports(legacyLoan, [{ projectName: 'Dự án A', quantity: 4 }]);
const returned = releaseAllocations(allocations, 'An', 3, 3);
assert.deepEqual(returned, [{ projectName: 'Dự án A', borrowerName: '', quantity: 4, allocationType: 'export' }]);
});
test('production session middleware protects proposal creation, listing and decisions', async t => {
const { productionApp } = createExportTestApp({});
const server = productionApp.listen(0, '127.0.0.1');
await new Promise(resolve => server.once('listening', resolve));
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
for (const [path, method] of [['/api/asset-export-requests', 'GET'], ['/api/asset-export-requests', 'POST'],
['/api/asset-export-requests/1/process', 'POST']]) {
const response = await fetch(`http://127.0.0.1:${server.address().port}${path}`, { method });
assert.equal(response.status, 401);
}
});

View File

@@ -0,0 +1,78 @@
const { randomUUID } = require('node:crypto');
const sql = require('mssql');
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
const { ensureAssetExportRequestSchema } = require('./asset-export-requests');
const { createExportTestApp } = require('./asset-export-test-fixture');
async function createExportSqlFixture() {
require('dotenv').config();
const database = `AccManagerExportTest_${randomUUID().replace(/-/g, '')}`;
const config = { server: process.env.DB_SERVER || 'localhost', user: process.env.DB_USER || 'sa', password: process.env.DB_PASSWORD,
database: 'master', options: { encrypt: /^(true|1)$/i.test(process.env.DB_ENCRYPT || 'false'),
trustServerCertificate: !/^(false|0)$/i.test(process.env.DB_TRUST_CERTIFICATE || 'true'), useUTC: false },
pool: { min: 0, max: 8, idleTimeoutMillis: 1000 }, connectionTimeout: 15000, requestTimeout: 20000 };
if (process.env.DB_PORT) config.port = Number(process.env.DB_PORT);
let admin, pool, server, created = false;
const cleanup = async () => {
if (server) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
if (pool) await pool.close();
if (created) {
if (!/^AccManagerExportTest_[0-9a-f]{32}$/.test(database)) throw new Error('Unsafe test database name');
await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [${database}];`);
}
if (admin) await admin.close();
};
try {
admin = await new sql.ConnectionPool(config).connect();
await admin.request().query(`CREATE DATABASE [${database}]`); created = true;
pool = await new sql.ConnectionPool({ ...config, database }).connect();
await pool.request().batch(`
CREATE TABLE dbo.Users (UserId INT PRIMARY KEY, Username NVARCHAR(100), FullName NVARCHAR(100));
INSERT dbo.Users VALUES (1, 'an', N'Nguyễn An'), (2, 'binh', N'Trần Bình'), (3, 'manager', N'Quản lý kho');
CREATE TABLE dbo.AssetInventory (
AssetId INT PRIMARY KEY, AssetCode NVARCHAR(100), AssetName NVARCHAR(255), Model NVARCHAR(255), SerialNumber NVARCHAR(255),
Quantity INT, ImportInPeriod INT, ExportInPeriod INT, EndingBalance INT, NewQuantity INT, UsedQuantity INT,
Unit NVARCHAR(50), Department NVARCHAR(100), Project NVARCHAR(150), Location NVARCHAR(150), Custodian NVARCHAR(100),
Borrower NVARCHAR(255), ProjectAllocations NVARCHAR(MAX), ExportedBy NVARCHAR(100), Status NVARCHAR(50), Notes NVARCHAR(MAX),
PurchaseDate DATE NULL, PurchasePrice DECIMAL(18,2) NULL, CreatedBy INT NULL,
IsArchived BIT NOT NULL DEFAULT 0, ArchivedDate DATETIME NULL, CreatedDate DATETIME NOT NULL DEFAULT GETDATE(),
UpdatedDate DATETIME NOT NULL DEFAULT GETDATE()
);
INSERT dbo.AssetInventory (AssetId, AssetCode, AssetName, Model, Quantity, ImportInPeriod, ExportInPeriod, EndingBalance, NewQuantity, UsedQuantity, Unit, Custodian, Borrower, ProjectAllocations, Status)
VALUES (1, 'TS-001', N'Máy khoan', 'MK-01', 10, 0, 0, 10, 6, 4, N'cái', N'Quản lý kho', NULL, '[]', 'in_stock'),
(2, 'TS-002', N'Đồng hồ', 'DH-01', 5, 0, 0, 5, 5, 0, N'cái', N'Quản lý kho', NULL, '[]', 'in_stock'),
(3, 'TS-003', N'Động cơ', 'DC-01', 4, 0, 0, 4, 4, 0, N'cái', N'Quản lý kho', NULL, '[]', 'in_stock');
CREATE TABLE dbo.AssetExportHistory (
ExportHistoryId INT IDENTITY PRIMARY KEY, AssetId INT, AssetCode NVARCHAR(100), AssetName NVARCHAR(255),
ExportQuantity INT, ProjectName NVARCHAR(150), CustodianName NVARCHAR(100), ExportedByName NVARCHAR(100),
ExportNote NVARCHAR(1000), CreatedBy INT, ExportedDate DATETIME,
CreatedDate DATETIME NOT NULL DEFAULT GETDATE(), UpdatedDate DATETIME NOT NULL DEFAULT GETDATE()
);
CREATE TABLE dbo.AssetBorrowRequests (
BorrowId INT IDENTITY PRIMARY KEY, AssetId INT, RequestType NVARCHAR(20) DEFAULT 'borrow', RequestStatus NVARCHAR(20) DEFAULT 'pending',
BorrowerName NVARCHAR(100), BorrowQuantity INT, ReturnedQuantity INT DEFAULT 0, Unit NVARCHAR(50), BorrowDate DATE DEFAULT GETDATE(),
RequestNote NVARCHAR(500), RejectReason NVARCHAR(1000), CreatedBy INT, ProcessedBy INT, ProcessedByName NVARCHAR(100),
ProcessedDate DATETIME, CreatedDate DATETIME DEFAULT GETDATE(), UpdatedDate DATETIME DEFAULT GETDATE()
);
CREATE TABLE dbo.AssetBorrowRequestLinks (LinkId INT IDENTITY PRIMARY KEY, BorrowId INT, ReturnId INT, Quantity INT,
CreatedDate DATETIME DEFAULT GETDATE());
`);
await ensureAssetExportDocumentSchema(pool);
await ensureAssetExportRequestSchema(pool);
await ensureAssetExportRequestSchema(pool);
const { app } = createExportTestApp(pool);
server = app.listen(0, '127.0.0.1');
await new Promise(resolve => server.once('listening', resolve));
const origin = `http://127.0.0.1:${server.address().port}`;
const request = async (suffix, { user = 1, role = 'user', method = 'GET', body } = {}) => {
const response = await fetch(`${origin}/api${suffix}`, { method, headers: {
'x-test-user': String(user), 'x-test-role': role, ...(body === undefined ? {} : { 'Content-Type': 'application/json' })
}, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
if (response.headers.get('content-type')?.includes('application/json')) return { status: response.status, ...(await response.json()) };
return { status: response.status, buffer: Buffer.from(await response.arrayBuffer()) };
};
return { pool, app, origin, request, cleanup };
} catch (err) { await cleanup(); throw err; }
}
module.exports = { createExportSqlFixture };

View File

@@ -0,0 +1,48 @@
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { createRequire } = require('node:module');
const express = require('express');
// Exercise production handlers against isolated SQL/test pools, without sessions
// or notifications touching the application's configured database.
function createExportTestApp(pool, { sql, workbookBuilder } = {}) {
const filename = path.join(__dirname, 'server.js');
const localRequire = createRequire(filename);
const sandbox = {
require(name) {
if (name === 'dotenv') return { config() {} };
if (name === 'mssql' && sql) return sql;
if (name === './export-request-workbook' && workbookBuilder) return { buildExportRequestWorkbook: workbookBuilder };
return localRequire(name);
},
module: { exports: {} }, __dirname, __filename: filename, Buffer, URL, Date, console, testPool: pool,
process: { env: { NODE_ENV: 'test', DATA_ENCRYPTION_SECRET: 'project-export-isolated-test-secret-over-32-characters' }, on() {} }
};
vm.runInNewContext(`${fs.readFileSync(filename, 'utf8')}
pool = testPool;
safeCreateSystemNotification = async () => {};
module.exports.workflow = assetExportWorkflow;
module.exports.prepareAssetExport = prepareAssetExport;
`, sandbox, { filename });
const production = sandbox.module.exports;
const app = express();
app.use(express.json());
app.use((req, res, next) => {
const userId = Number(req.headers['x-test-user'] || 1);
if (!userId) return res.status(401).json({ success: false });
req.user = { UserId: userId, Role: req.headers['x-test-role'] || 'user', FullName: `Người dùng ${userId}` };
next();
});
app.use('/api/asset-export-requests', production.workflow.router);
for (const layer of production.app.router.stack) {
if (!layer.route || !/^\/api\/(asset-export-(history|documents)|asset-borrows|assets)/.test(layer.route.path)) continue;
for (const method of Object.keys(layer.route.methods)) {
// The test server provides identity; retain each route's role guards.
app[method](layer.route.path, ...layer.route.stack.map(entry => entry.handle));
}
}
return { app, productionApp: production.app, prepareAssetExport: production.prepareAssetExport };
}
module.exports = { createExportTestApp };

View File

@@ -0,0 +1,156 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
function fixture() {
const nodes = { borrowAssetIdInput: { value: '1' }, borrowAssetUserInput: { value: 'An' },
borrowAssetProjectInput: { value: 'Dự án A' }, borrowQuantityInput: { value: '2' }, borrowAssetNoteInput: { value: '' },
borrowAssetForm: { dataset: {} }, borrowAssetRecipientInput: { value: 'Bình' },
batchAssetExportForm: { dataset: {} }, batchAssetExportUserInput: { value: 'An' },
batchAssetExportRecipientInput: { value: 'Bình' }, batchAssetExportNoteInput: { value: '' } };
const requests = [], messages = [], documents = [], refreshes = [];
const button = { disabled: false };
const sandbox = { document: { addEventListener() {}, getElementById: id => nodes[id], querySelector: () => button, querySelectorAll: () => [] },
window: {}, location: { hash: '#assets' }, console,
fetch: async (url, options) => { requests.push({ url, options }); return { ok: true, json: async () => ({
success: true, data: { RequestStatus: 'pending' }, document: { fileName: 'phieu-xuat.xlsx', contentBase64: 'ZmlsZQ==' }
}) }; } };
sandbox.window.fetch = sandbox.fetch;
vm.runInNewContext(`${fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8')}\napp = Object.create(AccountManager.prototype); globalThis.manager = app;`, sandbox);
const manager = sandbox.manager;
Object.assign(manager, { currentUser: { UserId: 1, Role: 'user', FullName: 'An' }, apiBase: '/api',
selectedAssetIds: new Set([1]), assets: [{ AssetId: 1, AssetCode: 'TS-001', Quantity: 5, ExportInPeriod: 0, EndingBalance: 5 }],
notifySuccess: message => messages.push(message), notifyFailure: message => messages.push(message), notifyWarning: message => messages.push(message),
showExportRequestDocument: file => documents.push(file), refreshAssetsUI: async () => refreshes.push('assets'),
closeModals() {} });
return { manager, sandbox, requests, messages, nodes, button, documents, refreshes };
}
test('ordinary users submit existing project allocations as pending proposals without downloading or changing stock', async () => {
const f = fixture();
await f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
assert.equal(f.requests.length, 1); assert.equal(f.requests[0].url, '/api/asset-export-requests');
assert.deepEqual(JSON.parse(f.requests[0].options.body).items, [{ assetId: 1, allocations: [{ projectName: 'Dự án A', quantity: 2 }] }]);
assert.equal(f.manager.assets[0].EndingBalance, 5); assert.equal(f.manager.lastExportRequestDocument, undefined);
assert.equal(f.sandbox.location.hash, '#asset-exports'); assert.match(f.messages[0], /chờ admin\/asset duyệt/);
assert.equal(f.manager.selectedAssetIds.size, 0); assert.equal(f.button.disabled, false);
});
test('proposal forms block duplicate submissions and retain selection when the server rejects them', async () => {
const f = fixture(); let complete;
f.sandbox.fetch = (url, options) => { f.requests.push({ url, options }); return new Promise(resolve => { complete = resolve; }); };
const first = f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
await f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
assert.equal(f.requests.length, 1); assert.equal(f.button.disabled, true);
complete({ ok: false, json: async () => ({ success: false, message: 'Không đủ tồn' }) });
await first;
assert.equal(f.manager.selectedAssetIds.size, 1); assert.equal(f.button.disabled, false); assert.equal(f.messages[0], 'Không đủ tồn');
});
test('proposal forms reject missing projects, fractional quantities and quantities exceeding stock before submission', async () => {
for (const [field, value] of [['borrowAssetProjectInput', ''], ['borrowQuantityInput', '1.5'], ['borrowQuantityInput', '6']]) {
const f = fixture(); f.nodes[field].value = value;
await f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
assert.equal(f.requests.length, 0); assert.equal(f.messages.length, 1);
}
});
test('export lists filter by creator, status and project, and show processing controls only to managers', () => {
const f = fixture();
const own = { ExportRequestId: 1, CreatedBy: 1, RequesterName: 'An', RequestStatus: 'pending', Items: [
{ assetCode: 'TS-001', assetName: '<Máy khoan>', allocations: [{ projectName: 'Dự án A', quantity: 2 }] }
] };
f.manager.assetExportRequests = [own, { ...own, ExportRequestId: 2, CreatedBy: 2 }];
f.manager.assetExportTab = 'requests';
assert.equal(f.manager.getFilteredAssetExportRows().length, 1);
f.manager.assetExportSearchTerm = 'dự án a'; assert.equal(f.manager.getFilteredAssetExportRows().length, 1);
f.manager.assetExportStatusFilter = 'rejected'; assert.equal(f.manager.getFilteredAssetExportRows().length, 0);
const userRows = f.manager.renderAssetExportRequestsRows([own]);
assert.doesNotMatch(userRows, /process-asset-export|<Máy khoan>/); assert.match(userRows, /&lt;Máy khoan&gt;/);
f.manager.currentUser.Role = 'asset'; assert.match(f.manager.renderAssetExportRequestsRows([own]), /Duyệt xuất/);
});
test('ordinary users cannot invoke the proposal decision UI', async () => {
const f = fixture();
await f.manager.processAssetExportRequest(1, 'approved', '');
assert.equal(f.requests.length, 0);
});
test('admin and asset keep the existing single and batch pending proposal flows', async () => {
for (const role of ['user', 'admin', 'asset']) {
for (const batch of [false, true]) {
const f = fixture(); f.manager.currentUser.Role = role;
f.manager.collectBatchAssetExportItems = () => [{ assetId: 1, allocations: [{ projectName: 'Dự án A', quantity: 2 }] }];
await f.manager[batch ? 'handleBatchAssetExportSubmit' : 'handleBorrowAssetSubmit']({ preventDefault() {} });
assert.equal(f.requests[0].url, '/api/asset-export-requests');
assert.equal(f.documents.length, 0); assert.equal(f.refreshes.length, 0);
assert.match(f.messages[0], /chờ admin\/asset duyệt/);
}
}
});
test('admin and asset can export selected assets to another recipient and download immediately', async () => {
for (const role of ['admin', 'asset']) {
for (const batch of [false, true]) {
const f = fixture(); f.manager.currentUser.Role = role;
f.nodes[batch ? 'batchAssetExportForm' : 'borrowAssetForm'].dataset.exportForOthers = 'true';
f.manager.collectBatchAssetExportItems = () => [{ assetId: 1, allocations: [{ projectName: 'Dự án A', quantity: 2 }] }];
await f.manager[batch ? 'handleBatchAssetExportSubmit' : 'handleBorrowAssetSubmit']({ preventDefault() {} });
assert.equal(f.requests[0].url, batch ? '/api/assets/export' : '/api/assets/1/export');
const body = JSON.parse(f.requests[0].options.body);
assert.equal(body.borrowerName, 'Bình');
assert.deepEqual(batch ? body.items[0].allocations : body.allocations, [{ projectName: 'Dự án A', quantity: 2 }]);
assert.equal(f.documents[0].fileName, 'phieu-xuat.xlsx'); assert.deepEqual(f.refreshes, ['assets']);
assert.equal(f.sandbox.location.hash, '#assets'); assert.equal(f.manager.selectedAssetIds.size, 0);
assert.match(f.messages[0], /Bình/); assert.equal(f.button.disabled, false);
}
}
});
test('exporting for others requires manager permission and a recipient for both forms', async () => {
for (const batch of [false, true]) {
for (const role of ['user', 'admin']) {
const f = fixture(); f.manager.currentUser.Role = role;
f.nodes[batch ? 'batchAssetExportForm' : 'borrowAssetForm'].dataset.exportForOthers = 'true';
f.nodes[batch ? 'batchAssetExportRecipientInput' : 'borrowAssetRecipientInput'].value = '';
f.manager.collectBatchAssetExportItems = () => [{ assetId: 1, allocations: [{ projectName: 'A', quantity: 1 }] }];
await f.manager[batch ? 'handleBatchAssetExportSubmit' : 'handleBorrowAssetSubmit']({ preventDefault() {} });
assert.equal(f.requests.length, 0); assert.equal(f.manager.selectedAssetIds.size, 1);
assert.match(f.messages[0], role === 'user' ? /Asset\/Admin/ : /chọn người nhận/);
}
}
});
test('reopening either form as a proposal clears the direct export mode and recipient validation', () => {
for (const prefix of ['borrowAsset', 'batchAssetExport']) {
const f = fixture();
const form = f.nodes[`${prefix}Form`]; form.querySelector = () => f.button;
for (const suffix of ['RequesterField', 'RecipientField', 'Title', 'Description']) f.nodes[`${prefix}${suffix}`] = {};
f.nodes[`${prefix}RecipientInput`].id = `${prefix}RecipientInput`;
f.manager.populateUserSelectOptions = id => { f.nodes[id].value = ''; };
f.manager.configureAssetExportForm(prefix, true);
assert.equal(form.dataset.exportForOthers, 'true'); assert.equal(f.nodes[`${prefix}RequesterField`].hidden, true);
assert.equal(f.nodes[`${prefix}RecipientInput`].required, true); assert.equal(f.button.textContent, 'Xuất và tải Excel');
f.nodes[`${prefix}RecipientInput`].value = 'Bình';
f.manager.configureAssetExportForm(prefix, false);
assert.equal(form.dataset.exportForOthers, 'false'); assert.equal(f.nodes[`${prefix}RequesterField`].hidden, false);
assert.equal(f.nodes[`${prefix}RecipientField`].hidden, true); assert.equal(f.nodes[`${prefix}RecipientInput`].value, '');
assert.equal(f.nodes[`${prefix}RecipientInput`].disabled, true); assert.equal(f.nodes[`${prefix}RecipientInput`].required, false);
assert.equal(f.button.textContent, 'Gửi đơn chờ duyệt');
}
});
test('direct exports block duplicate submissions and preserve selection on server rejection', async () => {
const f = fixture(); let complete;
f.manager.currentUser.Role = 'asset'; f.nodes.borrowAssetForm.dataset.exportForOthers = 'true';
f.sandbox.fetch = (url, options) => { f.requests.push({ url, options }); return new Promise(resolve => { complete = resolve; }); };
const first = f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
await f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
assert.equal(f.requests.length, 1); assert.equal(f.button.disabled, true);
complete({ ok: false, json: async () => ({ success: false, message: 'Không đủ tồn' }) });
await first;
assert.equal(f.manager.selectedAssetIds.size, 1); assert.equal(f.documents.length, 0);
assert.equal(f.button.disabled, false); assert.equal(f.messages[0], 'Không đủ tồn');
});

View File

@@ -0,0 +1,61 @@
// Current allocations are separate from the immutable export history and the
// legacy Project metadata. Never guess a project for old, unattributed loans.
function parseAllocations(value) {
const rows = typeof value === 'string' ? JSON.parse(value || '[]') : (value || []);
if (!Array.isArray(rows)) throw new Error('Invalid asset project allocations');
return rows.map(row => ({
projectName: String(row.projectName || '').trim(),
borrowerName: String(row.borrowerName || '').trim(),
quantity: Number(row.quantity),
...(row.allocationType === 'export' ? { allocationType: 'export' } : {})
})).filter(row => row.projectName && Number.isSafeInteger(row.quantity) && row.quantity > 0);
}
function normalizeExportAllocations(body = {}) {
const rows = body.allocations === undefined
? [{ projectName: body.projectName, quantity: body.quantity }]
: body.allocations;
if (!Array.isArray(rows) || !rows.length || rows.length > 100) {
throw new Error('Vui lòng chọn từ 1 đến 100 dòng dự án.');
}
const result = [];
for (const row of rows) {
const projectName = String(row?.projectName || '').trim();
const quantity = Number(row?.quantity);
if (!projectName || projectName.length > 150) throw new Error('Tên dự án là bắt buộc, tối đa 150 ký tự.');
if (!['number', 'string'].includes(typeof row?.quantity) || !Number.isSafeInteger(quantity) || quantity <= 0 || quantity > 2147483647) {
throw new Error('Số lượng xuất cho mỗi dự án phải là số nguyên dương.');
}
const existing = result.find(item => item.projectName.toLowerCase() === projectName.toLowerCase());
if (existing) existing.quantity += quantity;
else result.push({ projectName, quantity });
}
if (result.reduce((sum, row) => sum + row.quantity, 0) > 2147483647) throw new Error('Tổng số lượng xuất quá lớn.');
return result;
}
function addAllocations(current, rows, borrowerName) {
// Keep export order so unlinked returns can consume the oldest export first.
return [...parseAllocations(current), ...rows.map(row => ({ ...row, borrowerName }))];
}
function addProjectExports(current, rows) {
return [...parseAllocations(current), ...rows.map(row => ({ ...row, borrowerName: '', allocationType: 'export' }))];
}
function releaseAllocations(current, borrowerName, returnedQuantity, borrowerOutstanding) {
const rows = parseAllocations(current);
const matches = row => row.allocationType !== 'export' && row.borrowerName.toLowerCase() === borrowerName.toLowerCase();
const attributed = rows.filter(matches).reduce((sum, row) => sum + row.quantity, 0);
// Older loans without a project (including request-based loans) are consumed first.
let remaining = Math.max(returnedQuantity - Math.max(borrowerOutstanding - attributed, 0), 0);
for (const row of rows) {
if (!matches(row)) continue;
const taken = Math.min(row.quantity, remaining);
row.quantity -= taken;
remaining -= taken;
}
return rows.filter(row => row.quantity > 0);
}
module.exports = { parseAllocations, normalizeExportAllocations, addAllocations, addProjectExports, releaseAllocations };

131
backend/dashboard.test.js Normal file
View File

@@ -0,0 +1,131 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(require.resolve('../public/js/app.js'), 'utf8');
function fixture(fetch = async () => ({ ok: true, json: async () => ({ success: true, data: [] }) })) {
const context = vm.createContext({
window: { fetch }, fetch, console, AbortSignal,
document: { addEventListener() {}, getElementById: () => null, querySelectorAll: () => [] }
});
vm.runInContext(`${source}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context);
const manager = context.manager;
Object.assign(manager, {
assets: [], consumables: [], robots: [], robotTypes: [], accounts: [], applications: [], documents: [],
assetBorrows: [], consumableBorrowRequests: [], assetProjects: [], assetDepartments: [],
currentUser: { Role: 'admin' }, currentPage: 'assets', apiBase: '/api',
dashboardSourceErrors: {}, dashboardLoading: false, dashboardUpdatedAt: null,
selectedAssetIds: new Set(), updatePendingAssetRequestsBadge() {}, updateConsumableBorrowRequestBadges() {}
});
return manager;
}
test('overview counts catalog codes, excludes archived assets and uses available stock calculations', () => {
const manager = fixture();
manager.assets = [
{ AssetId: 1, Quantity: '20', ImportInPeriod: '5', EndingBalance: '25', ExportInPeriod: '0', Unit: 'cái' },
{ AssetId: 2, Quantity: 10, EndingBalance: 7, ExportInPeriod: 3, Unit: 'bộ' },
{ AssetId: 3, Quantity: 2, EndingBalance: 0, ExportInPeriod: 2 },
// An inflated imported balance cannot make a fully allocated asset available.
{ AssetId: 4, Quantity: 3, EndingBalance: 100, ExportInPeriod: 3 },
{ AssetId: 5, Quantity: 1000, IsArchived: 1 }
];
manager.consumables = [{ EndingBalance: '10' }, { EndingBalance: 0 }, { EndingBalance: '0' }];
manager.assetBorrows = [{ RequestStatus: 'pending' }, { RequestStatus: 'approved' }, { RequestStatus: 'rejected' }];
manager.consumableBorrowRequests = [{ RequestStatus: 'pending' }, { RequestStatus: 'approved' }];
const summary = manager.getDashboardSummary();
assert.equal(summary.assets.length, 4);
assert.deepEqual(JSON.parse(JSON.stringify(summary.assetStock)), { inStock: 1, inUse: 1, exported: 2 });
assert.equal(summary.outOfStock.length, 2);
assert.equal(summary.pendingAssets.length + summary.pendingConsumables.length, 2);
const html = manager.renderDashboard();
assert.match(html, /4<span>mã tài sản/);
assert.match(html, /3<span>mã vật tư/);
assert.doesNotMatch(html, /System Overview|Recent Accounts|Add Account/);
});
test('recent updates combine modules, sort by actual timestamps and escape user content', () => {
const manager = fixture();
manager.assets = [{ AssetName: '<img src=x onerror=alert(1)>', Quantity: 1, CreatedDate: '2026-11-01T01:00:00Z' }];
manager.consumables = [{ ConsumableName: 'Vật tư', UpdatedDate: '2026-11-02T01:00:00Z' }];
manager.robots = [{ Name: 'Robot mới', CreatedDate: '2026-11-03T01:00:00Z' }, { Name: 'Robot không có ngày' }];
manager.documents = [{ Title: 'Tài liệu', UploadedDate: '2026-10-31T01:00:00Z' }, { Title: 'Ngày lỗi', UploadedDate: 'invalid' }];
const originalRobots = [...manager.robots];
const summary = manager.getDashboardSummary();
assert.deepEqual(Array.from(summary.recent, row => row.source), ['Robot', 'Vật tư', 'Tài sản', 'Tài liệu']);
assert.equal(manager.robots[0], originalRobots[0]);
const html = manager.renderDashboard();
assert.match(html, /&lt;img src=x onerror=alert\(1\)&gt;/);
assert.doesNotMatch(html, /<img src=x/);
assert.match(html, /03\/11\/2026/);
assert.doesNotMatch(html, /Invalid Date|NaN/);
});
test('empty data and failed modules have distinct states and a failed module does not expose stale counts', () => {
const manager = fixture();
const empty = manager.renderDashboard();
assert.match(empty, /Chưa có tài sản trong danh mục/);
assert.match(empty, /Không có yêu cầu chờ duyệt hoặc vật tư hết tồn/);
manager.assets = [{ Quantity: 10, AssetName: 'Stale asset', CreatedDate: '2026-11-01' }];
manager.dashboardSourceErrors = { assets: 'Tài sản', assetBorrows: 'Yêu cầu tài sản' };
const html = manager.renderDashboard();
assert.match(html, /role="alert"/);
assert.match(html, /—<span>mã tài sản/);
assert.match(html, /Dữ liệu yêu cầu chưa đầy đủ/);
assert.doesNotMatch(html, /Stale asset|Không có yêu cầu chờ duyệt hoặc vật tư hết tồn/);
assert.equal(manager.assets.length, 1);
});
test('refresh uses existing API routes, tolerates one failed module and recovers on retry', async () => {
const requests = [];
let failRobots = true;
const manager = fixture(async (url, options) => {
requests.push({ url, options });
if (url === '/api/robots' && failRobots) throw new Error('Offline');
return { ok: true, json: async () => ({ success: true, data: url === '/api/assets' ? [{ AssetId: 10, Quantity: 5 }] : [] }) };
});
manager.robots = [{ Name: 'Stale robot' }];
await manager.refreshDashboard();
assert.equal(requests.length, 10);
assert.ok(requests.some(request => request.url === '/api/accounts/all'));
assert.ok(requests.some(request => request.url === '/api/robots/types'));
assert.ok(requests.every(request => request.options.cache === 'no-store' && request.options.signal));
assert.equal(manager.assets[0].EndingBalance, 5);
assert.equal(manager.dashboardSourceErrors.robots, 'Robot');
assert.equal(manager.getDashboardSummary().robots.length, 0);
assert.equal(manager.currentPage, 'assets', 'a completed refresh preserves navigation');
assert.equal(manager.dashboardLoading, false);
assert.ok(manager.dashboardUpdatedAt);
failRobots = false;
await manager.refreshDashboard();
assert.equal(Object.keys(manager.dashboardSourceErrors).length, 0);
});
test('refresh rejects unsuccessful HTTP responses and malformed data rather than treating them as empty', async () => {
const manager = fixture(async url => ({
ok: url !== '/api/assets',
json: async () => url === '/api/consumables' ? { success: true, data: null } : { success: true, data: [] }
}));
await manager.refreshDashboard();
assert.equal(manager.dashboardSourceErrors.assets, 'Tài sản');
assert.equal(manager.dashboardSourceErrors.consumables, 'Vật tư tiêu hao');
});
test('overlapping refreshes share the in-progress work instead of issuing a duplicate batch', async () => {
let release;
let requestCount = 0;
const gate = new Promise(resolve => { release = resolve; });
const manager = fixture(async () => {
requestCount++;
await gate;
return { ok: true, json: async () => ({ success: true, data: [] }) };
});
const pending = manager.refreshDashboard();
await manager.refreshDashboard();
assert.equal(requestCount, 10);
release();
await pending;
assert.equal(manager.dashboardLoading, false);
});

116
backend/document-files.js Normal file
View File

@@ -0,0 +1,116 @@
const path = require('node:path');
const { formats, accept, description } = require('../public/js/document-formats');
function documentError(message) {
return Object.assign(new Error(message), { status: 400, code: 'DOCUMENT_VALIDATION' });
}
function getDocumentFormat(fileName) {
return formats[path.extname(String(fileName || '')).toLowerCase()] || null;
}
function isPdfBuffer(value) {
return Buffer.isBuffer(value) && value.length >= 10
&& value.subarray(0, 5).toString('ascii') === '%PDF-'
&& value.subarray(Math.max(0, value.length - 2048)).includes(Buffer.from('%%EOF'));
}
// Inspect the ZIP directory without inflating any entry, including oversized compressed data.
function zipEntryNames(buffer) {
if (buffer.length < 22) return null;
for (let end = buffer.length - 22; end >= Math.max(0, buffer.length - 65557); end--) {
if (buffer.readUInt32LE(end) !== 0x06054b50 || end + 22 + buffer.readUInt16LE(end + 20) !== buffer.length) continue;
if (buffer.readUInt16LE(end + 4) !== 0 || buffer.readUInt16LE(end + 6) !== 0) return null;
const count = buffer.readUInt16LE(end + 10);
if (count !== buffer.readUInt16LE(end + 8)) return null;
const size = buffer.readUInt32LE(end + 12), offset = buffer.readUInt32LE(end + 16);
if (offset + size !== end) return null;
const names = new Set();
let cursor = offset;
for (let index = 0; index < count; index++) {
if (cursor + 46 > end || buffer.readUInt32LE(cursor) !== 0x02014b50) return null;
const nameSize = buffer.readUInt16LE(cursor + 28), extraSize = buffer.readUInt16LE(cursor + 30), commentSize = buffer.readUInt16LE(cursor + 32);
const next = cursor + 46 + nameSize + extraSize + commentSize;
if (next > end) return null;
const localOffset = buffer.readUInt32LE(cursor + 42);
if (localOffset + 30 > offset || buffer.readUInt32LE(localOffset) !== 0x04034b50) return null;
const dataStart = localOffset + 30 + buffer.readUInt16LE(localOffset + 26) + buffer.readUInt16LE(localOffset + 28);
if (dataStart + buffer.readUInt32LE(cursor + 20) > offset) return null;
names.add(buffer.toString('utf8', cursor + 46, cursor + 46 + nameSize));
cursor = next;
}
return cursor === offset + size ? names : null;
}
return null;
}
function isCompoundFile(buffer) {
return buffer.length >= 512 && buffer.subarray(0, 8).equals(Buffer.from('d0cf11e0a1b11ae1', 'hex'));
}
function hasStream(buffer, name) { return buffer.includes(Buffer.from(`${name}\0`, 'utf16le')); }
function documentContentMatches(buffer, extension) {
if (!Buffer.isBuffer(buffer) || !buffer.length) return false;
const starts = hex => buffer.length >= hex.length / 2 && buffer.subarray(0, hex.length / 2).equals(Buffer.from(hex, 'hex'));
const textStart = buffer.subarray(0, 8192).toString('utf8').trimStart();
switch (extension) {
case '.pdf': return isPdfBuffer(buffer);
case '.png': return buffer.length >= 24 && starts('89504e470d0a1a0a');
case '.jpg': case '.jpeg': return buffer.length >= 12 && starts('ffd8ff');
case '.gif': return buffer.length >= 13 && ['GIF87a', 'GIF89a'].includes(buffer.toString('ascii', 0, 6));
case '.webp': return buffer.length >= 12 && buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP';
case '.bmp': return buffer.length >= 26 && starts('424d');
case '.tif': case '.tiff': return buffer.length >= 8 && (starts('49492a00') || starts('4d4d002a'));
case '.txt': case '.csv':
if (buffer.length >= 4 && (starts('fffe') || starts('feff'))) return buffer.length % 2 === 0;
return !buffer.some(byte => byte < 32 && ![9, 10, 13].includes(byte));
case '.rtf': return textStart.startsWith('{\\rtf');
case '.doc': return (isCompoundFile(buffer) && hasStream(buffer, 'WordDocument')) || textStart.startsWith('{\\rtf');
case '.xls': return (isCompoundFile(buffer) && (hasStream(buffer, 'Workbook') || hasStream(buffer, 'Book')))
|| (buffer.length >= 8 && [0x0009, 0x0209, 0x0409, 0x0809].includes(buffer.readUInt16LE(0)))
|| (textStart.includes('urn:schemas-microsoft-com:office:spreadsheet') && /<Workbook\b/.test(textStart));
case '.ppt': return isCompoundFile(buffer) && hasStream(buffer, 'PowerPoint Document');
case '.docx': case '.xlsx': case '.pptx': {
if (isCompoundFile(buffer) && hasStream(buffer, 'EncryptedPackage') && hasStream(buffer, 'EncryptionInfo')) return true;
const names = zipEntryNames(buffer);
const mainPart = { '.docx': 'word/document.xml', '.xlsx': 'xl/workbook.xml', '.pptx': 'ppt/presentation.xml' }[extension];
return Boolean(names?.has('[Content_Types].xml') && names.has(mainPart));
}
case '.zip': return zipEntryNames(buffer) !== null;
default: return false;
}
}
function validateDocumentFile(file) {
const extension = path.extname(String(file.originalname || '')).toLowerCase();
const format = formats[extension];
if (!format) throw documentError(`Định dạng chưa được hỗ trợ. Chấp nhận: ${description}.`);
if (!documentContentMatches(file.buffer, extension)) throw documentError(`Nội dung file không đúng định dạng ${extension} hoặc file bị hỏng`);
return format;
}
function normalizeUploadedFileName(value) {
const name = String(value || '');
if ([...name].some(character => character.charCodeAt(0) > 255)) return name;
const bytes = Buffer.from(name, 'latin1'), decoded = bytes.toString('utf8');
return Buffer.from(decoded, 'utf8').equals(bytes) ? decoded : name;
}
function sanitizeDocumentFileName(value) {
const cleaned = String(value || 'document.pdf').replace(/[\u0000-\u001f\u007f]/g, '')
.replace(/[\\/:*?"<>|]/g, '_').trim();
const extension = path.extname(cleaned) || '.pdf';
const base = path.extname(cleaned) ? cleaned.slice(0, -extension.length) : cleaned;
return `${(base || 'document').slice(0, Math.max(1, 255 - extension.length))}${extension.slice(0, 254)}`;
}
function getDocumentContentDisposition(fileName, download = false) {
const safeName = sanitizeDocumentFileName(fileName);
const asciiName = safeName.normalize('NFKD').replace(/[^\x20-\x7e]/g, '').replace(/["\\]/g, '_').trim() || 'document';
const encodedName = encodeURIComponent(safeName).replace(/['()*]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
return `${download ? 'attachment' : 'inline'}; filename="${asciiName}"; filename*=UTF-8''${encodedName}`;
}
module.exports = { formats, accept, description, getDocumentFormat, isPdfBuffer, validateDocumentFile,
normalizeUploadedFileName, sanitizeDocumentFileName, getDocumentContentDisposition, zipEntryNames };

166
backend/documents.test.js Normal file
View File

@@ -0,0 +1,166 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { createRequire } = require('node:module');
const express = require('express');
const XLSX = require('xlsx');
const files = require('./document-files');
function officeZip(mainPart) {
const container = XLSX.CFB.utils.cfb_new();
XLSX.CFB.utils.cfb_add(container, '[Content_Types].xml', Buffer.from('<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>'));
XLSX.CFB.utils.cfb_add(container, mainPart, Buffer.from('<document/>'));
return XLSX.CFB.write(container, { type: 'buffer', fileType: 'zip', compression: true });
}
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([['Robot', 'Model'], ['Cộng tác', 'CR10']]), 'Robots');
const examples = {
'manual.pdf': Buffer.from('%PDF-1.4\nmanual\n%%EOF'),
'manual.docx': officeZip('word/document.xml'),
'inventory.xlsx': XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }),
'inventory.xls': XLSX.write(workbook, { type: 'buffer', bookType: 'xls' }),
'slides.pptx': officeZip('ppt/presentation.xml'),
'photo.png': Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aLl8AAAAASUVORK5CYII=', 'base64'),
'notes.txt': Buffer.from('Tài liệu robot tiếng Việt'),
'rows.csv': Buffer.from('name,model\nRobot,CR10'),
'notes.rtf': Buffer.from('{\\rtf1\\ansi Hello}'),
'bundle.zip': officeZip('manual.txt')
};
function productionWithPool(pool) {
const filename = path.join(__dirname, 'server.js');
const localRequire = createRequire(filename);
const sandbox = { require: name => name === 'dotenv' ? { config() {} } : localRequire(name),
module: { exports: {} }, __dirname, __filename: filename, Buffer, URL, console, testPool: pool,
process: { env: { NODE_ENV: 'test', DOCUMENT_MAX_FILE_SIZE_MB: '1', DATA_ENCRYPTION_SECRET: 'documents-test-only-secret-more-than-32-characters' }, on() {} } };
vm.runInNewContext(`${fs.readFileSync(filename, 'utf8')}\npool = testPool;`, sandbox, { filename });
return sandbox.module.exports.app;
}
async function fixture(t) {
const stored = new Map();
let nextId = 1, writes = 0;
const pool = { request() {
const inputs = {};
return { input(name, _type, value) { inputs[name] = value; return this; }, async query(query) {
if (query.includes('INSERT INTO Documents')) {
const document = { DocumentId: nextId++, Title: inputs.title, OriginalFileName: inputs.originalFileName,
MimeType: inputs.mimeType, FileSize: inputs.fileSize, FileData: inputs.fileData,
UploadedBy: 1, UploadedDate: '2026-10-19T10:00:00', CanDelete: true };
stored.set(document.DocumentId, document); writes++;
return { recordset: [document] };
}
if (inputs.documentId) return { recordset: stored.has(inputs.documentId) ? [stored.get(inputs.documentId)] : [] };
return { recordset: [...stored.values()] };
} };
} };
const production = productionWithPool(pool);
const app = express();
app.use(express.json());
app.use((req, res, next) => { req.user = { UserId: 1, Role: 'admin' }; res.setHeader('Cache-Control', 'no-store'); next(); });
// Exercise the actual multipart middleware, validators, SQL parameters and response headers.
for (const layer of production.router.stack) {
if (!layer.route?.path.startsWith('/api/documents')) continue;
for (const method of Object.keys(layer.route.methods)) {
app[method](layer.route.path, ...layer.route.stack.map(entry => entry.handle));
}
}
app.use(production.router.stack.at(-1).handle);
const server = app.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
const base = `http://127.0.0.1:${server.address().port}/api/documents`;
return { stored, writes: () => writes, request: (suffix = '', options) => fetch(`${base}${suffix}`, options) };
}
function upload(name, buffer, type = 'application/octet-stream') {
const body = new FormData(); body.append('file', new Blob([buffer], { type }), name); return { method: 'POST', body };
}
test('document uploads retain actual extensions, canonical MIME types and exact download bytes', async t => {
const f = await fixture(t);
for (const [name, buffer] of Object.entries(examples)) {
const created = await f.request('', upload(name, buffer));
assert.equal(created.status, 201, `${name}: ${await created.clone().text()}`);
const document = (await created.json()).data;
assert.equal(document.OriginalFileName, name);
assert.equal(document.MimeType, files.getDocumentFormat(name).mimeType);
const response = await f.request(`/${document.DocumentId}/file?download=1`);
assert.equal(response.status, 200);
assert.match(response.headers.get('content-disposition'), /^attachment;/);
assert.ok(response.headers.get('content-disposition').includes(name));
assert.deepEqual(Buffer.from(await response.arrayBuffer()), Buffer.from(buffer));
}
assert.equal(f.writes(), Object.keys(examples).length);
});
test('PDF/image/text previews use their correct types; Office and ZIP always download', async t => {
const f = await fixture(t);
for (const name of ['manual.pdf', 'photo.png', 'notes.txt', 'manual.docx', 'inventory.xlsx', 'bundle.zip']) {
const id = (await (await f.request('', upload(name, examples[name]))).json()).data.DocumentId;
const response = await f.request(`/${id}/file`);
const format = files.getDocumentFormat(name);
assert.equal(response.headers.get('content-type').split(';')[0], format.mimeType);
assert.match(response.headers.get('content-disposition'), format.preview ? /^inline;/ : /^attachment;/);
assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
}
});
test('wrong extensions, fake Office packages, damaged PDFs and oversized uploads never write data', async t => {
const f = await fixture(t);
for (const [name, buffer] of [['malware.exe', Buffer.from('MZ')], ['page.html', Buffer.from('<script/>')],
['image.svg', Buffer.from('<svg/>')], ['fake.pdf', Buffer.from('not PDF')], ['fake.docx', examples['bundle.zip']],
['wrong.xlsx', examples['manual.docx']], ['fake.png', examples['manual.pdf']], ['empty.txt', Buffer.alloc(0)],
['oversized.txt', Buffer.alloc(1024 * 1024 + 1, 65)]]) {
assert.equal((await f.request('', upload(name, buffer))).status, 400, name);
}
assert.equal(f.writes(), 0);
});
test('Vietnamese filenames remain readable and long names retain their actual extension', async t => {
const f = await fixture(t);
const name = 'Hướng dẫn vận hành.docx';
const document = (await (await f.request('', upload(name, examples['manual.docx']))).json()).data;
assert.equal(document.OriginalFileName, name);
assert.equal(document.Title, 'Hướng dẫn vận hành');
const response = await f.request(`/${document.DocumentId}/file`);
assert.ok(response.headers.get('content-disposition').includes(encodeURIComponent(name)));
const longName = files.sanitizeDocumentFileName(`${'a'.repeat(300)}.xlsx`);
assert.equal(longName.length, 255); assert.ok(longName.endsWith('.xlsx'));
assert.doesNotMatch(files.getDocumentContentDisposition('report\r\n.xlsx', true), /[\r\n]/);
});
test('ZIP directory validation is bounded and does not accept mismatched Office files', () => {
const damaged = Buffer.from(examples['bundle.zip']);
damaged.writeUInt32LE(0xffffffff, damaged.length - 22 + 16);
assert.equal(files.zipEntryNames(damaged), null);
assert.throws(() => files.validateDocumentFile({ originalname: 'manual.docx', buffer: examples['slides.pptx'] }));
assert.throws(() => files.validateDocumentFile({ originalname: 'data.csv', buffer: Buffer.from([1, 2, 0, 3]) }));
});
test('legacy Word and PowerPoint require their own OLE streams and retain their file types', () => {
for (const [name, stream] of [['manual.doc', 'WordDocument'], ['slides.ppt', 'PowerPoint Document']]) {
const container = XLSX.CFB.utils.cfb_new();
XLSX.CFB.utils.cfb_add(container, stream, Buffer.from('Legacy Office document stream'));
const buffer = XLSX.CFB.write(container, { type: 'buffer', fileType: 'cfb' });
assert.equal(files.validateDocumentFile({ originalname: name, buffer }).mimeType, files.getDocumentFormat(name).mimeType);
}
assert.throws(() => files.validateDocumentFile({ originalname: 'not-word.doc', buffer: examples['inventory.xls'] }));
});
test('document controls show per-format icons/previews and accept the same supported extensions', () => {
const context = vm.createContext({ document: { addEventListener() {} }, window: { fetch() {}, DocumentFormats: require('../public/js/document-formats') }, console });
vm.runInContext(`${fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8')}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context);
const manager = context.manager;
Object.assign(manager, { apiBase: '/api', documentSearchTerm: '', documentMaxFileSizeMb: 25,
documents: Object.keys(examples).map((name, index) => ({ DocumentId: index + 1, OriginalFileName: name, Title: name, FileSize: 123 })),
escapeHtml: value => String(value || '').replace(/</g, '&lt;').replace(/>/g, '&gt;') });
const html = manager.getDocumentsContent();
assert.match(html, /Xem PDF/); assert.match(html, /Xem Ảnh/);
assert.doesNotMatch(html, /Xem Word|Xem Excel/);
for (const name of Object.keys(examples)) assert.equal(manager.isSupportedDocumentName(name), true);
assert.equal(manager.isSupportedDocumentName('bad.exe'), false);
assert.match(html, /\.docx/); assert.match(html, /\.xlsx/); assert.match(html, /\.png/);
});

View File

@@ -0,0 +1,180 @@
const fs = require('node:fs/promises');
const path = require('node:path');
const crypto = require('node:crypto');
const { CFB } = require('xlsx');
const TEMPLATE_PATH = path.join(__dirname, 'templates', 'export-request.xlsx');
const MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
function xmlText(value) {
return String(value ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/g, '')
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function setAttribute(attributes, name, value) {
const pattern = new RegExp(`\\s${name}="[^"]*"`);
return attributes.replace(pattern, '') + ` ${name}="${value}"`;
}
// Edit only the fixed template's XML parts. A read/write through the SheetJS
// worksheet model would discard its logo, print settings and annotations.
function writeCell(xml, address, value, style) {
const pattern = new RegExp(`<c\\b([^>]*\\br="${address}"[^>]*?)(?:/>|>[\\s\\S]*?</c>)`);
let found = false;
const result = xml.replace(pattern, (_cell, originalAttributes) => {
found = true;
let attributes = originalAttributes.replace(/\s+t="[^"]*"/g, '');
if (style !== undefined) attributes = setAttribute(attributes, 's', style);
if (value === null || value === undefined || value === '') return `<c${attributes}/>`;
if (typeof value === 'number') {
if (!Number.isFinite(value)) throw new Error('Invalid export request number');
return `<c${attributes}><v>${value}</v></c>`;
}
// Explicit inline strings also prevent names/notes starting with '='
// from being interpreted as Excel formulas.
return `<c${attributes} t="inlineStr"><is><t xml:space="preserve">${xmlText(value)}</t></is></c>`;
});
if (!found) throw new Error(`Export request template is missing cell ${address}`);
return result;
}
function setRowHeight(xml, row, height) {
height = Math.min(height, 409.5); // Excel's maximum row height in points.
return xml.replace(new RegExp(`<row\\b([^>]*\\br="${row}"[^>]*)>`), (_tag, attrs) => (
`<row${setAttribute(setAttribute(attrs, 'ht', height), 'customHeight', 1)}>`
));
}
function wrapStyle(stylesXml, sourceIndex) {
let styleIndex;
const xml = stylesXml.replace(/<cellXfs\b([^>]*)>([\s\S]*?)<\/cellXfs>/, (_block, attrs, content) => {
const styles = content.match(/<xf\b[^>]*(?:\/>|>[\s\S]*?<\/xf>)/g);
if (!styles?.[sourceIndex]) throw new Error('Export request template styles are invalid');
styleIndex = styles.length;
const newStyle = styles[sourceIndex].replace(/<alignment\b([^>]*?)\/>/, (_alignment, alignmentAttrs) => (
`<alignment${setAttribute(alignmentAttrs, 'wrapText', 1)}/>`
));
return `<cellXfs${setAttribute(attrs, 'count', styles.length + 1)}>${content}${newStyle}</cellXfs>`;
});
if (styleIndex === undefined) throw new Error('Export request template styles are missing');
return { xml, index: styleIndex };
}
function extendRows(xml, extra) {
if (!extra) return xml;
const templateRow = xml.match(/<row\b[^>]*\br="10"[^>]*>[\s\S]*?<\/row>/)?.[0];
if (!templateRow) throw new Error('Export request template is missing its detail row');
// Insert before the last detail row, retaining that row's bottom border.
xml = xml.replace(/<row\b([^>]*\br="(\d+)"[^>]*)>([\s\S]*?)<\/row>/g, (rowXml, attrs, rowNumber, cells) => {
const row = Number(rowNumber);
if (row < 18) return rowXml;
return `<row${setAttribute(attrs, 'r', row + extra)}>${cells.replace(/\br="([A-Z]+)(\d+)"/g,
(_ref, col, number) => `r="${col}${Number(number) + extra}"`)}</row>`;
});
const added = Array.from({ length: extra }, (_, index) => templateRow
.replace(/\br="10"/, `r="${18 + index}"`)
.replace(/\br="([A-Z]+)10"/g, (_ref, col) => `r="${col}${18 + index}"`)).join('');
xml = xml.replace(new RegExp(`<row\\b[^>]*\\br="${18 + extra}"[^>]*>`), match => added + match);
return xml.replace(/\bref="([A-Z]+)(\d+):([A-Z]+)(\d+)"/g, (_ref, left, start, right, end) => (
`ref="${left}${Number(start) >= 18 ? Number(start) + extra : start}:${right}${Number(end) >= 18 ? Number(end) + extra : end}"`
));
}
function wrappedLines(value, width) {
return String(value || '').split('\n').reduce((total, line) => total + Math.max(1, Math.ceil(line.length / width)), 0);
}
async function buildExportRequestWorkbook({ item, rows, availableStock, items, requesterName, recipientName,
exportedByName, note = '', exportedDate = new Date(), kind = 'asset' }, { templatePath = TEMPLATE_PATH } = {}) {
const entries = items ?? [{ item, rows, availableStock }];
if (!Array.isArray(entries) || !entries.length || entries.length > 100) throw new Error('Invalid export request items');
const detailRows = entries.flatMap(entry => {
if (!entry.item || !Array.isArray(entry.rows) || !entry.rows.length) throw new Error('Invalid export request rows');
if (!Number.isSafeInteger(entry.availableStock) || entry.availableStock < 0) throw new Error('Invalid export request stock');
let remaining = entry.availableStock;
return entry.rows.map(row => {
if (!Number.isSafeInteger(row.quantity) || row.quantity <= 0 || row.quantity > remaining) throw new Error('Export request exceeds stock');
const detail = { ...row, item: entry.item, availableStock: remaining };
remaining -= row.quantity;
return detail;
});
});
if (detailRows.length > 100) throw new Error('Invalid export request rows');
const department = [...new Set(entries.map(entry => String(entry.item.Department || '').trim()).filter(Boolean))].join(', ');
const container = CFB.read(await fs.readFile(templatePath), { type: 'buffer' });
const readPart = name => {
const part = CFB.find(container, `Root Entry/${name}`);
if (!part) throw new Error(`Export request template is missing ${name}`);
return Buffer.from(part.content).toString('utf8');
};
const writePart = (name, value) => CFB.utils.cfb_add(container, `Root Entry/${name}`, Buffer.from(value, 'utf8'));
let sheet = readPart('xl/worksheets/sheet1.xml');
let styles = readPart('xl/styles.xml');
const headerStyle = wrapStyle(styles, 37);
const contentStyle = wrapStyle(headerStyle.xml, 4);
styles = contentStyle.xml;
const extra = Math.max(0, detailRows.length - 10);
sheet = extendRows(sheet, extra);
const dateParts = new Intl.DateTimeFormat('en-GB', { timeZone: 'Asia/Ho_Chi_Minh',
year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date(exportedDate));
const datePart = type => dateParts.find(part => part.type === type).value;
const date = `${datePart('day')}/${datePart('month')}/${datePart('year')}`;
sheet = writeCell(sheet, 'G5', `Ngày đề nghị: ${date}`, headerStyle.index);
sheet = writeCell(sheet, 'G6', `Người đề nghị: ${requesterName || ''}`, headerStyle.index);
sheet = writeCell(sheet, 'G7', `Bộ phận sử dụng: ${department}`, headerStyle.index);
const content = [`Nội dung: Xuất ${kind === 'consumable' ? 'vật tư' : 'tài sản'}${recipientName ? ` cho ${recipientName}` : ''}.`,
exportedByName ? `Người xuất: ${exportedByName}.` : '', note].filter(Boolean).join(' ');
sheet = writeCell(sheet, 'A7', content, contentStyle.index);
sheet = sheet.replace(/<mergeCells count="(\d+)">/, (_tag, count) => (
`<mergeCells count="${Number(count) + 1}"><mergeCell ref="A7:F7"/>`
));
sheet = setRowHeight(sheet, 5, 30);
sheet = setRowHeight(sheet, 6, Math.max(30, wrappedLines(`Người đề nghị: ${requesterName || ''}`, 42) * 16 + 8));
sheet = setRowHeight(sheet, 7, Math.max(32, wrappedLines(content, 92) * 16 + 8,
wrappedLines(`Bộ phận sử dụng: ${department}`, 42) * 16 + 8));
const code = entries.length === 1
? String(entries[0].item.AssetCode || entries[0].item.ConsumableCode || '').trim()
: 'NHIEU-TAI-SAN';
detailRows.forEach((row, index) => {
const item = row.item;
const itemCode = String(item.AssetCode || item.ConsumableCode || '').trim();
const description = [item.AssetName || item.ConsumableName || '', itemCode ? `Mã: ${itemCode}` : '',
item.Model ? `Model: ${item.Model}` : '', item.SerialNumber ? `Serial: ${item.SerialNumber}` : ''].filter(Boolean).join('\n');
const number = index + 9;
const purpose = String(row.projectName || recipientName || '').trim();
const values = [index + 1, description, item.Unit || '', row.quantity, row.availableStock, row.quantity, null, purpose];
values.forEach((value, column) => {
sheet = writeCell(sheet, `${String.fromCharCode(65 + column)}${number}`, value,
column === 1 ? 13 : column === 7 ? 12 : undefined);
});
sheet = setRowHeight(sheet, number, Math.max(32, wrappedLines(description, 24) * 16 + 8,
wrappedLines(purpose, 31) * 16 + 8, wrappedLines(item.Unit, 14) * 16 + 8));
});
// Retain all signature labels and placeholders. No signatory names/dates
// are populated. The optional import sheet and drawing parts stay intact.
sheet = sheet.replace(/<pageSetup\b([^>]*?)\/>/, (_tag, attrs) => (
`<pageSetup${setAttribute(setAttribute(attrs.replace(/\s+scale="[^"]*"/, ''), 'fitToWidth', 1), 'fitToHeight', extra ? 0 : 1)}/>`
));
let workbook = readPart('xl/workbook.xml');
const names = `<definedName name="_xlnm.Print_Area" localSheetId="0">'ycxvt'!$A$1:$H$${24 + extra}</definedName>`
+ `<definedName name="_xlnm.Print_Titles" localSheetId="0">'ycxvt'!$8:$8</definedName>`;
workbook = workbook.includes('</definedNames>')
? workbook.replace('</definedNames>', names + '</definedNames>')
: workbook.replace('<calcPr', `<definedNames>${names}</definedNames><calcPr`);
writePart('xl/worksheets/sheet1.xml', sheet);
writePart('xl/styles.xml', styles);
writePart('xl/workbook.xml', workbook);
const buffer = CFB.write(container, { type: 'buffer', fileType: 'zip', compression: true });
const safeCode = code.replace(/[\u0000-\u001f\u007f\\/:*?"<>|]/g, '_').slice(0, 80) || 'vat-tu';
return {
fileName: `DE-NGHI-XUAT-${safeCode}-${datePart('year')}${datePart('month')}${datePart('day')}-${crypto.randomUUID().slice(0, 8)}.xlsx`,
mimeType: MIME_TYPE,
contentBase64: Buffer.from(buffer).toString('base64')
};
}
module.exports = { buildExportRequestWorkbook, TEMPLATE_PATH, MIME_TYPE };

View File

@@ -0,0 +1,75 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(require.resolve('../public/js/app.js'), 'utf8');
function fixture(fetch) {
const context = vm.createContext({
window: { fetch }, fetch, console, URLSearchParams,
document: { addEventListener() {}, getElementById: () => null }
});
vm.runInContext(`${source}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context);
return Object.assign(context.manager, {
apiBase: '/api', currentPage: 'notification-management', currentUser: { Role: 'admin' },
notificationItems: [], notificationPreviewItems: [], notificationPage: 1, notificationPageSize: 20,
notificationFilter: 'all', notificationSourceFilter: '', notificationUnreadCount: 0,
notificationPagination: { page: 1, total: 0, totalPages: 1 },
renderNotificationsPage() {}, notifyFailure() {}
});
}
test('a missing API or HTML fallback produces an actionable message without a JSON parser error', async () => {
for (const status of [200, 404]) {
const manager = fixture(async () => new Response('<!DOCTYPE html><html>Cannot GET /api/notifications/manage</html>', { status, headers: { 'Content-Type': 'text/html' } }));
await assert.rejects(manager.fetchNotificationJson('/manage'), error => {
assert.match(error.message, /khởi động lại backend/);
assert.doesNotMatch(error.message, /Unexpected token|<!DOCTYPE|Cannot GET/);
return true;
});
}
});
test('proxy errors and invalid JSON have readable errors; JSON business errors keep their original message', async () => {
for (const [response, expected] of [
[new Response('<html>Bad Gateway</html>', { status: 502, headers: { 'Content-Type': 'text/html' } }), /HTTP 502/],
[new Response('{broken', { headers: { 'Content-Type': 'application/json' } }), /không hợp lệ/],
[Response.json({ success: false, message: 'Thông báo đã kết thúc' }, { status: 404 }), /Thông báo đã kết thúc/],
[Response.json({ success: false, code: 'API_NOT_FOUND' }, { status: 404 }), /khởi động lại backend/]
]) {
const manager = fixture(async () => response);
await assert.rejects(manager.fetchNotificationJson('/1/dismiss', { method: 'PUT' }), expected);
}
});
test('notification requests preserve JSON headers and never retry a write automatically', async () => {
const calls = [];
const manager = fixture(async (url, options) => {
calls.push({ url, options });
return Response.json({ success: true });
});
await manager.fetchNotificationJson('', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"title":"Notice"}' });
assert.equal(calls.length, 1);
assert.equal(calls[0].url, '/api/notifications');
assert.equal(calls[0].options.headers.Accept, 'application/json');
assert.equal(calls[0].options.headers['Content-Type'], 'application/json');
assert.equal(calls[0].options.method, 'POST');
assert.equal(calls[0].options.cache, 'no-store');
});
test('a failed management load shows an error and retry control, then clears both after recovery', async () => {
let offline = true;
const manager = fixture(async () => offline
? new Response('<html>Not found</html>', { status: 404, headers: { 'Content-Type': 'text/html' } })
: Response.json({ success: true, data: [], pagination: { page: 1, total: 0, totalPages: 1 } }));
await manager.refreshNotificationsPage();
assert.equal(manager.notificationLoading, false);
assert.match(manager.getNotificationsContent(), /role="alert"/);
assert.match(manager.getNotificationsContent(), /id="retryNotificationsBtn"/);
assert.doesNotMatch(manager.getNotificationsContent(), /Không có thông báo phù hợp/);
offline = false;
await manager.refreshNotificationsPage();
assert.equal(manager.notificationLoadError, '');
assert.doesNotMatch(manager.getNotificationsContent(), /retryNotificationsBtn/);
assert.match(manager.getNotificationsContent(), /Không có thông báo phù hợp/);
});

View File

@@ -0,0 +1,358 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { createBomFixture } = require('./robot-bom-test-fixture');
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
class Browser {
constructor(url) { this.socket = new WebSocket(url); this.nextId = 0; this.pending = new Map(); this.errors = []; }
async open() {
await new Promise((resolve, reject) => { this.socket.addEventListener('open', resolve, { once: true }); this.socket.addEventListener('error', reject, { once: true }); });
this.socket.addEventListener('message', event => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') this.errors.push(message.params.exceptionDetails);
const pending = this.pending.get(message.id);
if (!pending) return;
this.pending.delete(message.id); clearTimeout(pending.timer);
if (message.error) pending.reject(new Error(message.error.message)); else pending.resolve(message.result);
});
}
send(method, params = {}) {
return new Promise((resolve, reject) => {
const id = ++this.nextId;
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Browser timeout: ${method}`)); }, 15000);
this.pending.set(id, { resolve, reject, timer }); this.socket.send(JSON.stringify({ id, method, params }));
});
}
async evaluate(expression) {
const result = await this.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description || result.exceptionDetails.text);
return result.result?.value;
}
async until(expression) {
for (let i = 0; i < 100; i++) { if (await this.evaluate(expression)) return; await delay(100); }
throw new Error(`Browser state timeout: ${expression}`);
}
}
test('Chrome checks robot confirmations and BOM forms with independent quantities and supplier sources', {
skip: process.env.ACCMANAGER_BOM_BROWSER_TEST !== '1' ? 'Set ACCMANAGER_BOM_BROWSER_TEST=1 for the isolated Chrome UI check' : false,
timeout: 90000
}, async () => {
const root = path.resolve(__dirname, '..');
const output = path.join(root, 'output/bom-robot'); fs.mkdirSync(output, { recursive: true });
let forceSaveFailure = false;
let forceBomDeleteFailure = false;
let failRobotDelete = false;
const robotDeleteRequests = [];
const fixture = createBomFixture({ failQuery: query => (forceSaveFailure && query.includes('INSERT dbo.RobotBomLines'))
|| (forceBomDeleteFailure && query.includes('DELETE FROM dbo.RobotBomRevisions')) });
const review = fixture.app;
const reviewRobots = fixture.state.models.map(robot => ({ ...robot, Name: 'TESTBOM', DocumentCount: 2 }));
review.get('/api/auth/session', (_req, res) => res.json({ success: true, user: { UserId: 1, Username: 'bom-review', FullName: 'Kiểm tra BOM', Role: 'admin' } }));
review.get('/api/robots/types', (_req, res) => res.json({ success: true, data: [{ TypeId: 1, Name: 'AMR' }] }));
review.get('/api/robots', (_req, res) => res.json({ success: true, data: reviewRobots }));
review.delete('/api/robots/:id', (req, res) => {
robotDeleteRequests.push(Number(req.params.id));
if (failRobotDelete) return res.status(500).json({ success: false, message: 'Không thể xóa robot thử nghiệm. Hãy thử lại.' });
const index = reviewRobots.findIndex(robot => robot.RobotId === Number(req.params.id));
if (index < 0) return res.status(404).json({ success: false, message: 'Robot không tồn tại' });
reviewRobots.splice(index, 1); res.json({ success: true, message: 'Đã xóa robot thử nghiệm' });
});
review.use('/api', (_req, res) => res.json({ success: true, data: [], unreadCount: 0, pagination: { total: 0, totalPages: 1 } }));
review.get('/test-xlsx.js', (_req, res) => res.sendFile(require.resolve('xlsx/dist/xlsx.full.min.js')));
review.get('/test-notiflix.js', (_req, res) => res.type('js').send('window.Notiflix={Notify:{init(){},success(){},failure(){},warning(){}}};'));
review.get('/pages/index.html', (_req, res) => {
const source = fs.readFileSync(path.join(root, 'public/pages/index.html'), 'utf8')
.replace('https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js', '/test-xlsx.js')
.replace('https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js', '/test-notiflix.js');
res.type('html').send(source);
});
review.use(require('express').static(path.join(root, 'public')));
const server = review.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
const origin = `http://127.0.0.1:${server.address().port}`;
const chromePath = process.env.ACCMANAGER_TEST_CHROME || 'C:/Program Files/Google/Chrome/Application/chrome.exe';
// Keep browser-managed extension files outside Node's automatic test discovery.
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'accmanager-bom-chrome-'));
const chrome = spawn(chromePath, ['--headless=new', '--remote-debugging-port=0', `--user-data-dir=${profile}`, '--no-first-run', '--no-default-browser-check', '--hide-scrollbars', 'about:blank'], { stdio: 'ignore', windowsHide: true });
let client;
try {
const portFile = path.join(profile, 'DevToolsActivePort');
for (let i = 0; i < 100 && !fs.existsSync(portFile); i++) await delay(100);
const port = Number(fs.readFileSync(portFile, 'utf8').split('\n')[0]);
const targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json();
client = new Browser(targets.find(target => target.type === 'page').webSocketDebuggerUrl); await client.open();
await client.send('Runtime.enable'); await client.send('Page.enable');
await client.send('Page.addScriptToEvaluateOnNewDocument', { source: 'window.confirm=()=>true;window.alert=()=>{};' });
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
await client.send('Page.navigate', { url: `${origin}/pages/index.html#robot-bom` });
await client.until('typeof app !== "undefined" && app?.robotBom?.models.length === 1 && !app.robotBom.busy');
const prepareNotifications = () => client.evaluate('window.bomMessages=[]; app.notifyFailure=app.notifyWarning=app.notifySuccess=(message)=>bomMessages.push(message); true');
await prepareNotifications();
await client.evaluate('document.querySelector("[data-bom-action=new]").click()');
await client.until('app.robotBom.header?.BomId && !app.robotBom.busy');
const entryGeometry = () => client.evaluate(`(() => {
const dialog=document.querySelector('#bomComponentDialog');
const rect=element=>{const value=element.getBoundingClientRect();return [value.x,value.y,value.width,value.height].map(number=>Math.round(number*100)/100)};
return {dialog:rect(dialog),name:rect(dialog.querySelector('[name=name]')),footer:rect(dialog.querySelector('.bom-dialog-footer')),scroll:dialog.querySelector('.bom-material-layout').scrollTop};
})()`);
const add = async ({ id = null, name, model, unit, quantity, sourceInfo = '', screenshot = false }) => {
await client.evaluate('document.querySelector("[data-bom-action=add]").click()');
const opened = await entryGeometry();
if (id !== null) {
await client.until('document.querySelectorAll("#bomComponentDialog [name=assetChoice]").length>0');
await client.evaluate(`document.querySelector('#bomComponentDialog input[name=assetChoice][value="${id}"]').click()`);
assert.equal(await client.evaluate('document.querySelector("#bomMaterialForm").elements.quantity.value'), '1');
assert.equal(await client.evaluate('document.querySelector("#bomMaterialForm").elements.name.value'), 'Động cơ servo 400W');
assert.equal(await client.evaluate('document.querySelector("#bomMaterialForm").elements.model.value'), 'SV-400');
assert.equal(await client.evaluate('/Tồn|Khả dụng/.test(document.querySelector("#bomAssetResults").innerText)'), false);
} else await client.evaluate('document.querySelector("[data-bom-mode=manual]").click()');
await client.evaluate(`(() => { const form = document.querySelector('#bomMaterialForm'); ${name === undefined ? '' : `form.elements.name.value=${JSON.stringify(name)};`} ${model === undefined ? '' : `form.elements.model.value=${JSON.stringify(model)};`} ${unit === undefined ? '' : `form.elements.unit.value=${JSON.stringify(unit)};`} form.elements.quantity.value=${JSON.stringify(String(quantity))}; form.elements.sourceInfo.value=${JSON.stringify(sourceInfo)}; return true; })()`);
const entered = await client.evaluate('Array.from(document.querySelector("#bomMaterialForm").elements).filter(element=>["name","model","quantity","unit","sourceInfo","notes"].includes(element.name)).map(element=>[element.name,element.value])');
for (const mode of ['manual', 'asset', 'manual', 'asset', id === null ? 'manual' : 'asset']) {
await client.evaluate(`(() => { const button=document.querySelector('[data-bom-mode="${mode}"]');button.focus({preventScroll:true});button.click();return true; })()`);
await client.evaluate('new Promise(resolve=>requestAnimationFrame(()=>resolve(true)))');
assert.deepEqual(await entryGeometry(), opened, 'switching modes must not move or resize the dialog/form/footer');
}
assert.deepEqual(await client.evaluate('Array.from(document.querySelector("#bomMaterialForm").elements).filter(element=>["name","model","quantity","unit","sourceInfo","notes"].includes(element.name)).map(element=>[element.name,element.value])'), entered);
if (screenshot) {
const shot = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-component-picker.png'), Buffer.from(shot.data, 'base64'));
}
if (id === null && name === 'Khung gia công bên ngoài') {
const shot = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-external-entry.png'), Buffer.from(shot.data, 'base64'));
}
await client.evaluate('(() => { const form=document.querySelector("#bomMaterialForm"); form.requestSubmit(form.querySelector("button[value=done]")); return true; })()');
await client.until('!document.querySelector("#bomComponentDialog")');
};
await add({ id: 1, quantity: 200, sourceInfo: 'https://example.com/servo', screenshot: true });
await add({ name: 'Khung gia công bên ngoài', model: 'CUSTOM-01', quantity: 12, sourceInfo: 'Nhà sản xuất: Cơ khí ABC' });
await add({ name: 'Cáp nguồn bên ngoài', model: 'CB-NEW', unit: 'm', quantity: 1.25, sourceInfo: 'https://example.com/cable' });
assert.equal(await client.evaluate('app.robotBom.lines.length'), 3);
assert.equal(await client.evaluate('document.querySelector("#bomRobotCount")===null && document.querySelector("[data-bom-stock]")===null'), true);
assert.equal(await client.evaluate('app.robotBom.sourceHtml("javascript:alert(1)").includes("<a")'), false);
assert.equal(await client.evaluate('document.querySelector(".bom-source-link").getAttribute("href")'), 'https://example.com/servo');
await client.evaluate('document.querySelector("[data-bom-action=save]").click()');
await client.until('!app.robotBom.busy && !app.robotBom.dirty');
await client.evaluate('(() => { const input=document.querySelector("[data-bom-quantity]" );input.value="0.5";input.dispatchEvent(new Event("change",{bubbles:true})); })()');
assert.equal(await client.evaluate('app.robotBom.lines[0].Quantity'), 200);
assert.match(await client.evaluate('bomMessages.at(-1)'), /số lượng nguyên/);
await client.evaluate('window.XLSX.writeFile=(book,name)=>{window.bomExport={book,name}};document.querySelector("[data-bom-action=export]").click()');
assert.equal(await client.evaluate('bomExport.name'), 'BOM-AMR-500-v1.xlsx');
assert.equal(await client.evaluate('XLSX.utils.sheet_to_json(bomExport.book.Sheets.BOM).length'), 3);
await client.evaluate('(async()=>{const bytes=XLSX.write(bomExport.book,{bookType:"xlsx",type:"array"});await app.robotBom.importWorkbook(new File([bytes],"roundtrip.xlsx"));return true})()');
assert.equal(await client.evaluate('app.robotBom.lines[2].Quantity'), 1.25);
assert.equal(await client.evaluate('app.robotBom.lines[1].SourceInfo'), 'Nhà sản xuất: Cơ khí ABC');
await client.evaluate('document.querySelector("[data-bom-action=save]").click()');
await client.until('!app.robotBom.busy && !app.robotBom.dirty');
const screenshot = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-desktop.png'), Buffer.from(screenshot.data, 'base64'));
await client.send('Page.reload'); await delay(300);
await client.until('typeof app !== "undefined" && app?.robotBom?.lines.length===3 && !app.robotBom.busy');
await prepareNotifications();
assert.equal(await client.evaluate('app.robotBom.lines[0].SourceInfo'), 'https://example.com/servo');
fixture.state.catalog = [];
await client.evaluate('window.nativeConfirmCalls=0;window.confirm=()=>{nativeConfirmCalls++;return true};document.querySelector("[data-bom-action=publish]").click()');
await client.until('document.querySelector("#bomPublishDialog")?.open');
assert.equal(await client.evaluate('app.robotBom.header.Status'), 'draft');
await client.evaluate('document.querySelector("#bomPublishDialog .bom-dialog-footer [data-bom-publish-cancel]").click()');
await client.until('!document.querySelector("#bomPublishDialog")');
assert.equal(await client.evaluate('app.robotBom.header.Status'), 'draft');
await client.evaluate('document.querySelector("[data-bom-action=publish]").click()');
await client.until('document.querySelector("#bomPublishDialog")?.open');
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await client.until('!document.querySelector("#bomPublishDialog")');
assert.equal(await client.evaluate('app.robotBom.header.Status'), 'draft');
await client.evaluate('document.querySelector("[data-bom-action=publish]").click();document.querySelector("[data-bom-action=publish]").click()');
await client.until('document.querySelector("#bomPublishDialog")?.open');
assert.equal(await client.evaluate('document.querySelectorAll("#bomPublishDialog").length'), 1);
const confirmation = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-publish-confirmation.png'), Buffer.from(confirmation.data, 'base64'));
await client.evaluate('document.querySelector("[data-bom-publish-confirm]").click()');
await client.until('app.robotBom.header?.Status==="released" && !app.robotBom.busy');
assert.equal(await client.evaluate('nativeConfirmCalls'), 0);
assert.equal(fixture.queries.filter(({ query }) => query.includes("Status = 'released'")).length, 1);
assert.equal(await client.evaluate('document.querySelector("[data-bom-action=add]")===null'), true);
await client.evaluate('document.querySelector("[data-bom-action=copy]").click()');
await client.until('app.robotBom.header?.Revision===2 && !app.robotBom.busy');
assert.equal(await client.evaluate('app.robotBom.lines.length'), 3);
await client.evaluate('(() => { const input=document.querySelector("[data-bom-quantity]");input.value="3";input.dispatchEvent(new Event("change",{bubbles:true}));window.confirm=()=>false;location.hash="#robots"; })()');
await client.until('location.hash==="#robot-bom"');
assert.equal(await client.evaluate('app.robotBom.dirty && app.currentPage==="robot-bom"'), true);
forceSaveFailure = true;
await client.evaluate('window.confirm=()=>true;document.querySelector("[data-bom-action=save]").click()');
await client.until('!app.robotBom.busy');
assert.equal(await client.evaluate('app.robotBom.dirty && app.robotBom.lines[0].Quantity===3'), true);
forceSaveFailure = false;
await client.evaluate('document.querySelector("[data-bom-action=save]").click()');
await client.until('!app.robotBom.busy && !app.robotBom.dirty');
assert.equal(fixture.state.lines.find(line => line.BomId === 1).Quantity, 200);
assert.equal(fixture.state.lines.find(line => line.BomId === 1).SourceId, null);
await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
await delay(200);
assert.equal(await client.evaluate('document.documentElement.scrollWidth<=390'), true);
const mobile = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-mobile.png'), Buffer.from(mobile.data, 'base64'));
await client.evaluate('document.querySelector("[data-bom-action=add]").click()');
assert.equal(await client.evaluate('document.querySelector("#bomComponentDialog").getBoundingClientRect().width<=390'), true);
const mobileGeometry = await entryGeometry();
for (const mode of ['manual', 'asset', 'manual']) {
await client.evaluate(`document.querySelector('[data-bom-mode="${mode}"]').click()`);
assert.deepEqual(await entryGeometry(), mobileGeometry, 'mobile mode switches must retain geometry and scroll');
}
assert.equal(await client.evaluate('document.querySelector("#bomComponentDialog .bom-dialog-footer").getBoundingClientRect().bottom<=844'), true);
const mobileEntry = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-external-mobile.png'), Buffer.from(mobileEntry.data, 'base64'));
await client.evaluate('document.querySelector("[data-bom-close]").click();app.currentUser.Role="user";app.robotBom.render()');
assert.equal(await client.evaluate('document.querySelector("[data-bom-action=save]")===null && document.querySelector("[data-bom-action=add]")===null && document.querySelector("[data-bom-action=delete]")===null'), true);
fixture.state.models.push({ RobotId: 2, Model: 'AMR-500', TypeId: 2, Type: 'AMR khác cấu hình', Name: 'Robot khác' });
await client.evaluate('app.currentUser.Role="admin";app.robotBom.mount(document.getElementById("mainContent"),{Model:"AMR-500",TypeId:2})');
assert.equal(await client.evaluate('app.robotBom.selectedModel().TypeId'), 2);
assert.equal(await client.evaluate('app.robotBom.header===null'), true);
assert.equal(fixture.state.headers.length, 2);
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
await client.evaluate('window.nativeConfirmCalls=0;window.confirm=()=>{nativeConfirmCalls++;return true};location.hash="#robots"');
await client.until('app.currentPage==="robots" && document.querySelector("[data-robot-action=delete]")');
const openRobotDelete = async () => {
await client.evaluate('document.querySelector("[data-robot-action=delete]").click()');
await client.until('document.querySelector("#robotDeleteDialog")?.open');
assert.equal(await client.evaluate('document.querySelector("#robotDeleteDialog .robot-delete-name").textContent'), 'TESTBOM');
assert.equal(await client.evaluate('document.querySelector("#robotDeleteDialog").innerText.includes("AMR-500")'), true);
};
const waitRobotDeleteClosed = () => client.until('!document.querySelector("#robotDeleteDialog") && !app.robotDeletionPending');
await openRobotDelete();
const robotConfirmation = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'robot-delete-confirmation.png'), Buffer.from(robotConfirmation.data, 'base64'));
await client.evaluate('document.querySelector("#robotDeleteDialog .bom-dialog-footer [data-cancel-robot-delete]").click()');
await waitRobotDeleteClosed(); assert.equal(robotDeleteRequests.length, 0);
await openRobotDelete();
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await waitRobotDeleteClosed(); assert.equal(robotDeleteRequests.length, 0);
await openRobotDelete();
await client.evaluate('document.querySelector("#robotDeleteDialog .bom-dialog-header [data-cancel-robot-delete]").click()');
await waitRobotDeleteClosed(); assert.equal(robotDeleteRequests.length, 0);
await openRobotDelete(); await client.evaluate('location.hash="#robot-types"');
await waitRobotDeleteClosed(); assert.equal(robotDeleteRequests.length, 0);
await client.until('app.currentPage==="robot-types"');
await client.evaluate('document.querySelector("[data-robot-type-action=delete]").click()');
await client.until('document.querySelector("#robotDeleteDialog")?.open');
assert.equal(await client.evaluate('document.querySelector("#robotDeleteTitle").textContent'), 'Xóa thể loại robot?');
await client.evaluate('document.querySelector("#robotDeleteDialog [data-cancel-robot-delete]").click()');
await waitRobotDeleteClosed();
await client.evaluate('location.hash="#robots"');
await client.until('app.currentPage==="robots"');
await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
await openRobotDelete();
assert.equal(await client.evaluate('document.querySelector("#robotDeleteDialog").getBoundingClientRect().width<=390 && document.querySelector("#robotDeleteDialog .bom-dialog-footer").getBoundingClientRect().bottom<=844'), true);
const robotMobile = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'robot-delete-mobile.png'), Buffer.from(robotMobile.data, 'base64'));
await client.evaluate('document.querySelector("#robotDeleteDialog [data-cancel-robot-delete]").click()');
await waitRobotDeleteClosed();
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
failRobotDelete = true;
await openRobotDelete(); await client.evaluate('document.querySelector("[data-confirm-robot-delete]").click()');
await waitRobotDeleteClosed();
assert.equal(robotDeleteRequests.length, 1); assert.equal(reviewRobots.length, 1);
assert.match(await client.evaluate('bomMessages.at(-1)'), /Không thể xóa robot thử nghiệm/);
failRobotDelete = false;
await client.evaluate('app.deleteRobot(1);app.deleteRobot(1);true');
await client.until('document.querySelector("#robotDeleteDialog")?.open');
assert.equal(await client.evaluate('document.querySelectorAll("#robotDeleteDialog").length'), 1);
await client.evaluate('document.querySelector("[data-confirm-robot-delete]").click()');
await waitRobotDeleteClosed();
assert.equal(robotDeleteRequests.length, 2); assert.equal(reviewRobots.length, 0);
assert.equal(await client.evaluate('app.robots.length'), 0);
assert.equal(await client.evaluate('nativeConfirmCalls'), 0);
assert.equal(fixture.state.headers.length, 2);
// Delete only the selected revision, with styled confirmation and no implicit save.
await client.evaluate('location.hash="#robot-bom"');
await client.until('app.currentPage==="robot-bom" && !app.robotBom.busy');
await client.evaluate('app.robotBom.mount(document.getElementById("mainContent"),{Model:"AMR-500",TypeId:1})');
await prepareNotifications();
const markBomDirty = () => client.evaluate('(() => { const input=document.querySelector("[data-bom-quantity]");input.value="7";input.dispatchEvent(new Event("change",{bubbles:true}));return true; })()');
const openBomDelete = async () => {
await client.evaluate('document.querySelector("[data-bom-action=delete]").click()');
await client.until('document.querySelector("#bomDeleteDialog")?.open');
};
const bomDeleteCount = () => fixture.queries.filter(({ query }) => query.includes('DELETE FROM dbo.RobotBomRevisions')).length;
await markBomDirty();
await openBomDelete();
assert.equal(await client.evaluate('document.querySelector("#bomDeleteDialog .bom-publish-summary").innerText.includes("AMR-500") && document.querySelector("#bomDeleteTitle").innerText.includes("v2")'), true);
assert.equal(await client.evaluate('document.querySelector("#bomDeleteDialog").innerText.includes("chưa lưu")'), true);
assert.equal(await client.evaluate('document.activeElement.matches(".bom-dialog-footer [data-bom-delete-cancel]")'), true);
await client.evaluate('document.querySelector("#bomDeleteDialog .bom-dialog-footer [data-bom-delete-cancel]").click()');
await client.until('!document.querySelector("#bomDeleteDialog")');
assert.equal(await client.evaluate('app.robotBom.dirty && app.robotBom.lines[0].Quantity===7'), true);
await openBomDelete();
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await client.until('!document.querySelector("#bomDeleteDialog")');
await openBomDelete();
await client.evaluate('document.querySelector("#bomDeleteDialog .bom-dialog-header [data-bom-delete-cancel]").click()');
await client.until('!document.querySelector("#bomDeleteDialog")');
await openBomDelete();
await client.evaluate('app.robotBom.unmount()');
await client.until('!document.querySelector("#bomDeleteDialog")');
assert.equal(bomDeleteCount(), 0); assert.equal(fixture.state.headers.length, 2);
// A stale client cannot delete a newer saved version.
const draft = fixture.state.headers.find(item => item.Revision === 2);
draft.LockVersion++;
await openBomDelete();
await client.evaluate('document.querySelector("[data-bom-delete-confirm]").click()');
await client.until('!app.robotBom.busy && !document.querySelector("#bomDeleteDialog")');
assert.equal(bomDeleteCount(), 0); assert.equal(fixture.state.headers.length, 2);
assert.equal(await client.evaluate('app.robotBom.dirty && app.robotBom.lines[0].Quantity===7'), true);
assert.match(await client.evaluate('bomMessages.at(-1)'), /tải lại trước khi xóa/);
await client.evaluate('app.robotBom.mount(document.getElementById("mainContent"),{Model:"AMR-500",TypeId:1})');
await markBomDirty();
forceBomDeleteFailure = true;
await openBomDelete();
const deleteConfirmation = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-delete-confirmation.png'), Buffer.from(deleteConfirmation.data, 'base64'));
await client.evaluate('document.querySelector("[data-bom-delete-confirm]").click()');
await client.until('!app.robotBom.busy && !document.querySelector("#bomDeleteDialog")');
assert.equal(bomDeleteCount(), 1); assert.equal(fixture.state.headers.length, 2);
assert.equal(fixture.state.lines.filter(line => line.BomId === draft.BomId).length, 3);
assert.equal(await client.evaluate('app.robotBom.dirty && app.robotBom.lines[0].Quantity===7'), true);
forceBomDeleteFailure = false;
await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
await openBomDelete();
await client.evaluate('document.querySelector("[data-bom-action=delete]").click()');
assert.equal(await client.evaluate('document.querySelectorAll("#bomDeleteDialog").length'), 1);
assert.equal(await client.evaluate('document.querySelector("#bomDeleteDialog").getBoundingClientRect().width<=390 && document.querySelector("#bomDeleteDialog .bom-dialog-footer").getBoundingClientRect().bottom<=844'), true);
const deleteMobile = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-delete-mobile.png'), Buffer.from(deleteMobile.data, 'base64'));
await client.evaluate('document.querySelector("[data-bom-delete-confirm]").click();document.querySelector("[data-bom-delete-confirm]")?.click()');
await client.until('!app.robotBom.busy && app.robotBom.header?.Revision===1');
assert.equal(bomDeleteCount(), 2); assert.equal(fixture.state.headers.length, 1);
assert.equal(await client.evaluate('!app.robotBom.dirty && app.robotBom.header.Status==="released" && app.robotBom.revisions.length===1'), true);
assert.equal(fixture.state.lines[0].Quantity, 200);
// Deleting the last historical version refreshes the model picker too.
fixture.state.models = fixture.state.models.filter(item => item.TypeId !== 1);
await openBomDelete();
await client.evaluate('document.querySelector("[data-bom-delete-confirm]").click()');
await client.until('!app.robotBom.busy && app.robotBom.header===null');
assert.equal(bomDeleteCount(), 3); assert.equal(fixture.state.headers.length, 0); assert.equal(fixture.state.lines.length, 0);
assert.equal(await client.evaluate('app.robotBom.models.length===1 && app.robotBom.selectedModel().TypeId===2 && app.robotBom.revisions.length===0'), true);
assert.equal(await client.evaluate('document.querySelector("[data-bom-action=delete]")===null && document.querySelector("#bomRevision").disabled'), true);
assert.equal(await client.evaluate('nativeConfirmCalls'), 0);
assert.equal(fixture.queries.some(({ query }) => /(?:UPDATE|INSERT|DELETE).*Inventory/i.test(query)), false);
assert.deepEqual(client.errors, []);
fs.writeFileSync(path.join(output, 'verification.json'), JSON.stringify({ passed: true, checks: ['BOM draft/released deletion', 'BOM delete cancel/Escape/close/unmount', 'stale BOM deletion rejected', 'BOM deletion rollback and retry', 'BOM dirty state preserved on failure and discarded on success', 'double click deletes one BOM', 'remaining revisions and orphaned models refresh', 'styled robot/type deletion confirmations', 'cancel/Escape/close/navigation send no delete', 'failed robot deletion supports retry', 'double click deletes once', 'mobile deletion confirmation', 'stable entry mode geometry and retained fields', 'desktop/mobile mode switching', 'custom publication confirmation', 'cancel and Escape preserve draft', 'double click publishes once', 'asset name/model picker', 'external components', 'BOM quantity independent of stock', 'supplier URL/text', 'safe source links', 'Excel export/import with sources', 'save/reload', 'publish/copy with no inventory', 'mobile overflow', 'viewer controls'], screenshots: ['bom-delete-confirmation.png', 'bom-delete-mobile.png', 'bom-desktop.png', 'bom-component-picker.png', 'bom-external-entry.png', 'bom-publish-confirmation.png', 'bom-mobile.png', 'bom-external-mobile.png', 'robot-delete-confirmation.png', 'robot-delete-mobile.png'] }, null, 2));
} finally {
if (client) { try { await client.send('Browser.close'); } catch {} client.socket.close(); }
chrome.kill();
if (chrome.exitCode === null) await Promise.race([new Promise(resolve => chrome.once('exit', resolve)), delay(2000)]);
const resolved = path.resolve(profile);
if (path.dirname(resolved) === path.resolve(os.tmpdir()) && path.basename(resolved).startsWith('accmanager-bom-chrome-')) {
fs.rmSync(resolved, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
server.closeAllConnections(); await new Promise(resolve => server.close(resolve));
}
});

View File

@@ -0,0 +1,69 @@
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.RobotBomRevisions', 'U') IS NULL
BEGIN
CREATE TABLE dbo.RobotBomRevisions (
BomId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
RobotModel NVARCHAR(255) NOT NULL,
RobotTypeId INT NOT NULL,
Revision INT NOT NULL,
Status VARCHAR(10) NOT NULL DEFAULT 'draft',
LockVersion INT NOT NULL DEFAULT 1,
CreatedBy INT NULL,
CreatedDate DATETIME2 NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
UpdatedDate DATETIME2 NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
ReleasedDate DATETIME2 NULL,
CONSTRAINT UQ_RobotBomRevisions_ModelRevision UNIQUE (RobotTypeId, RobotModel, Revision),
CONSTRAINT CK_RobotBomRevisions_Status CHECK (Status IN ('draft', 'released')),
CONSTRAINT FK_RobotBomRevisions_Type FOREIGN KEY (RobotTypeId) REFERENCES dbo.RobotTypes(TypeId),
CONSTRAINT FK_RobotBomRevisions_User FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId) ON DELETE SET NULL
);
END;
IF OBJECT_ID('dbo.RobotBomLines', 'U') IS NULL
BEGIN
CREATE TABLE dbo.RobotBomLines (
LineId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
BomId INT NOT NULL,
SourceType VARCHAR(10) NOT NULL DEFAULT 'manual',
SourceId INT NULL,
Code NVARCHAR(100) NOT NULL,
Name NVARCHAR(255) NOT NULL,
Model NVARCHAR(255) NOT NULL,
Unit NVARCHAR(50) NOT NULL,
GroupName NVARCHAR(100) NOT NULL,
Position NVARCHAR(150) NOT NULL DEFAULT '',
Quantity DECIMAL(18,4) NOT NULL,
Notes NVARCHAR(500) NOT NULL DEFAULT '',
SourceInfo NVARCHAR(1000) NOT NULL DEFAULT '',
SortOrder INT NOT NULL,
CONSTRAINT FK_RobotBomLines_Revision FOREIGN KEY (BomId) REFERENCES dbo.RobotBomRevisions(BomId),
CONSTRAINT CK_RobotBomLines_Source CHECK (SourceType = 'manual' AND SourceId IS NULL),
CONSTRAINT CK_RobotBomLines_Quantity CHECK (Quantity > 0 AND Quantity <= 100000)
);
CREATE INDEX IX_RobotBomLines_BomId ON dbo.RobotBomLines(BomId, SortOrder);
END;
IF COL_LENGTH('dbo.RobotBomLines', 'SourceInfo') IS NULL
ALTER TABLE dbo.RobotBomLines ADD SourceInfo NVARCHAR(1000) NOT NULL
CONSTRAINT DF_RobotBomLines_SourceInfo DEFAULT '';
-- Retain existing component descriptions and released versions while detaching
-- the obsolete inventory references. Repeated startup leaves content intact.
IF EXISTS (SELECT 1 FROM sys.check_constraints
WHERE parent_object_id = OBJECT_ID('dbo.RobotBomLines')
AND name = 'CK_RobotBomLines_Source' AND definition LIKE '%asset%')
ALTER TABLE dbo.RobotBomLines DROP CONSTRAINT CK_RobotBomLines_Source;
IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('dbo.RobotBomLines')
AND name = 'SourceId' AND is_nullable = 0)
ALTER TABLE dbo.RobotBomLines ALTER COLUMN SourceId INT NULL;
UPDATE dbo.RobotBomLines SET SourceType = 'manual', SourceId = NULL
WHERE SourceType <> 'manual' OR SourceId IS NOT NULL;
IF NOT EXISTS (SELECT 1 FROM sys.check_constraints WHERE parent_object_id = OBJECT_ID('dbo.RobotBomLines')
AND name = 'CK_RobotBomLines_Source')
ALTER TABLE dbo.RobotBomLines ADD CONSTRAINT CK_RobotBomLines_Source
CHECK (SourceType = 'manual' AND SourceId IS NULL);
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;

View File

@@ -0,0 +1,135 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { randomUUID } = require('node:crypto');
const express = require('express');
const sql = require('mssql');
const { ensureRobotBomSchema, createRobotBomRouter } = require('./robot-bom');
test('SQL Server migrates legacy BOMs, stores external parts and sources, and keeps quantities independent of inventory', {
skip: process.env.ACCMANAGER_BOM_SQL_TEST !== '1' ? 'Set ACCMANAGER_BOM_SQL_TEST=1 to use a disposable database on the configured SQL Server' : false,
timeout: 60000
}, async () => {
require('dotenv').config();
const bool = (key, fallback) => process.env[key] === undefined ? fallback : /^(1|true|yes|on)$/i.test(process.env[key]);
const database = `AccManagerBomTest_${randomUUID().replace(/-/g, '')}`;
const config = { server: process.env.DB_SERVER || 'localhost', user: process.env.DB_USER || 'sa', password: process.env.DB_PASSWORD,
database: 'master', options: { encrypt: bool('DB_ENCRYPT', false), trustServerCertificate: bool('DB_TRUST_CERTIFICATE', true), useUTC: false },
pool: { min: 0, max: 5, idleTimeoutMillis: 1000 }, connectionTimeout: 15000, requestTimeout: 15000 };
let admin, pool, server, created = false;
try {
admin = await new sql.ConnectionPool(config).connect();
await admin.request().query(`CREATE DATABASE [${database}]`); created = true;
pool = await new sql.ConnectionPool({ ...config, database }).connect();
await pool.request().batch(`
CREATE TABLE dbo.Users (UserId INT PRIMARY KEY); INSERT dbo.Users VALUES (1);
CREATE TABLE dbo.RobotTypes (TypeId INT PRIMARY KEY, Name NVARCHAR(100)); INSERT dbo.RobotTypes VALUES (1, N'AMR');
CREATE TABLE dbo.Robots (RobotId INT PRIMARY KEY, Name NVARCHAR(255), Model NVARCHAR(255), TypeId INT);
INSERT dbo.Robots VALUES (1, N'Robot thử nghiệm', 'AMR-500', 1);
CREATE TABLE dbo.AssetInventory (AssetId INT PRIMARY KEY, AssetCode NVARCHAR(100), AssetName NVARCHAR(255),
Model NVARCHAR(255), Unit NVARCHAR(50), EndingBalance INT, Location NVARCHAR(150), IsArchived BIT);
INSERT dbo.AssetInventory VALUES (1, 'LK-001', N'Servo', 'SV-400', N'cái', 8, N'Kho A', 0),
(2, 'OLD', N'Archived', 'SV-400', N'cái', 100, N'Kho A', 1);
CREATE TABLE dbo.ConsumableInventory (ConsumableId INT PRIMARY KEY, ConsumableCode NVARCHAR(100),
ConsumableName NVARCHAR(255), Model NVARCHAR(255), Unit NVARCHAR(50), EndingBalance INT);
INSERT dbo.ConsumableInventory VALUES (1, 'VT-001', N'Cáp', 'CB-2X2.5', 'm', 30);
-- Simulate the earlier inventory-linked installation, including a released BOM.
CREATE TABLE dbo.RobotBomRevisions (
BomId INT IDENTITY PRIMARY KEY, RobotModel NVARCHAR(255) NOT NULL, RobotTypeId INT NOT NULL,
Revision INT NOT NULL, Status VARCHAR(10) NOT NULL DEFAULT 'draft', LockVersion INT NOT NULL DEFAULT 1,
CreatedBy INT NULL, CreatedDate DATETIME2 NOT NULL DEFAULT GETDATE(),
UpdatedDate DATETIME2 NOT NULL DEFAULT GETDATE(), ReleasedDate DATETIME2 NULL,
CONSTRAINT UQ_RobotBomRevisions_ModelRevision UNIQUE (RobotTypeId, RobotModel, Revision)
);
CREATE TABLE dbo.RobotBomLines (
LineId INT IDENTITY PRIMARY KEY, BomId INT NOT NULL, SourceType VARCHAR(10) NOT NULL,
SourceId INT NOT NULL, Code NVARCHAR(100) NOT NULL, Name NVARCHAR(255) NOT NULL,
Model NVARCHAR(255) NOT NULL, Unit NVARCHAR(50) NOT NULL, GroupName NVARCHAR(100) NOT NULL,
Position NVARCHAR(150) NOT NULL DEFAULT '', Quantity DECIMAL(18,4) NOT NULL,
Notes NVARCHAR(500) NOT NULL DEFAULT '', SortOrder INT NOT NULL,
CONSTRAINT CK_RobotBomLines_Source CHECK (SourceType IN ('asset', 'consumable')),
CONSTRAINT FK_RobotBomLines_Revision FOREIGN KEY (BomId) REFERENCES dbo.RobotBomRevisions(BomId)
);
INSERT dbo.RobotBomRevisions (RobotModel, RobotTypeId, Revision, Status) VALUES ('AMR-500', 1, 1, 'released');
INSERT dbo.RobotBomLines (BomId, SourceType, SourceId, Code, Name, Model, Unit, GroupName, Quantity, Notes, SortOrder)
VALUES (1, 'asset', 1, 'LK-001', N'Servo cũ', 'SV-400', N'cái', N'Cơ khí', 2, N'Giữ nguyên mô tả', 0);
`);
await ensureRobotBomSchema(pool); await ensureRobotBomSchema(pool);
const legacy = (await pool.request().query('SELECT * FROM dbo.RobotBomLines WHERE BomId = 1')).recordset[0];
assert.equal(legacy.Name, 'Servo cũ'); assert.equal(legacy.Quantity, 2); assert.equal(legacy.Notes, 'Giữ nguyên mô tả');
assert.equal(legacy.SourceType, 'manual'); assert.equal(legacy.SourceId, null); assert.equal(legacy.SourceInfo, '');
assert.equal((await pool.request().query('SELECT Status FROM dbo.RobotBomRevisions WHERE BomId = 1')).recordset[0].Status, 'released');
const app = express(); app.use(express.json());
app.use((req, _res, next) => { req.user = { UserId: 1 }; next(); });
app.use('/boms', createRobotBomRouter({ getPool: () => pool, sql, requireManage: (_req, _res, next) => next(),
sendInternalError(res, error, message) { console.error('SQL BOM test:', error.message); return res.status(500).json({ success: false, message }); } }));
server = app.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
const request = async (suffix = '', method = 'GET', body) => {
const response = await fetch(`http://127.0.0.1:${server.address().port}/boms${suffix}`, { method,
...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) });
return { status: response.status, ...(await response.json()) };
};
const catalog = await request('/catalog'); assert.equal(catalog.status, 200); assert.equal(catalog.data.length, 1);
assert.deepEqual(Object.keys(catalog.data[0]).sort(), ['Code', 'Id', 'Model', 'Name', 'Unit']);
const id = (await request('', 'POST', { robotId: 1 })).data.BomId;
const lines = [
{ name: 'Servo', model: 'SV-400', unit: 'cái', quantity: 30, sourceInfo: 'https://example.com/servo' },
{ name: 'Khung gia công bên ngoài', model: 'CUSTOM-01', quantity: 2, sourceInfo: 'Nhà sản xuất: Cơ khí ABC' },
{ name: 'Cáp nguồn bên ngoài', model: 'CB-NEW', unit: 'm', quantity: 1.125, notes: 'Tuyến nguồn' }
];
assert.equal((await request(`/${id}`, 'PUT', { lockVersion: 1, lines })).status, 200);
const saved = (await request(`/${id}`)).data.Lines;
assert.equal(saved[0].Quantity, 30); assert.equal(saved[0].SourceInfo, 'https://example.com/servo');
assert.equal(saved[1].Name, 'Khung gia công bên ngoài'); assert.equal(saved[1].SourceInfo, 'Nhà sản xuất: Cơ khí ABC');
assert.equal(saved[2].Quantity, 1.125);
// Two clients with the same version cannot both overwrite the revision.
const saves = await Promise.all([1, 2].map(() => request(`/${id}`, 'PUT', { lockVersion: 2, lines })));
assert.deepEqual(saves.map(result => result.status).sort(), [200, 409]);
// Force a real SQL failure after the DELETE, then verify full rollback.
await pool.request().query('ALTER TABLE dbo.RobotBomLines ADD CONSTRAINT CK_BomTest_Failure CHECK (Quantity < 50)');
assert.equal((await request(`/${id}`, 'PUT', { lockVersion: 3, lines: [{ ...lines[0], quantity: 99 }] })).status, 500);
assert.equal((await request(`/${id}`)).data.Lines.length, 3);
assert.equal((await request(`/${id}`)).data.LockVersion, 3);
assert.equal((await request(`/${id}/publish`, 'POST', { lockVersion: 3 })).status, 200);
assert.equal((await request(`/${id}`, 'PUT', { lockVersion: 4, lines: [] })).status, 409);
const copies = await Promise.all([1, 2].map(() => request('', 'POST', { robotId: 1, copyFromId: id })));
assert.deepEqual(copies.map(result => result.data.Revision).sort(), [3, 4]);
await ensureRobotBomSchema(pool);
assert.equal((await request(`/${copies[0].data.BomId}`)).data.Lines.length, 3);
assert.equal((await request(`/${copies[0].data.BomId}`)).data.Lines[1].SourceInfo, 'Nhà sản xuất: Cơ khí ABC');
assert.deepEqual((await pool.request().query('SELECT EndingBalance FROM dbo.AssetInventory ORDER BY AssetId')).recordset.map(item => item.EndingBalance), [8, 100]);
assert.equal((await pool.request().query('SELECT EndingBalance FROM dbo.ConsumableInventory')).recordset[0].EndingBalance, 30);
// Once descriptions are entered, no inventory tables are needed to save/publish/copy.
await pool.request().query('DROP TABLE dbo.AssetInventory; DROP TABLE dbo.ConsumableInventory;');
await pool.request().query('DELETE FROM dbo.Robots');
const historical = await request('/models');
assert.equal(historical.data[0].RobotId, null); assert.equal(historical.data[0].Model, 'AMR-500');
const detached = await request('', 'POST', { copyFromId: id });
assert.equal(detached.data.Revision, 5);
assert.equal((await request(`/${detached.data.BomId}`, 'PUT', { lockVersion: 1, lines })).status, 200);
assert.equal((await request(`/${detached.data.BomId}/publish`, 'POST', { lockVersion: 2 })).status, 200);
// Deletions respect concurrent versions and remove only their own lines.
const draftId = copies[0].data.BomId;
assert.equal((await request(`/${id}`, 'DELETE', { lockVersion: 3 })).status, 409);
await pool.request().query(`CREATE TABLE dbo.BomDeleteTestReferences (
BomId INT NOT NULL REFERENCES dbo.RobotBomRevisions(BomId));
INSERT dbo.BomDeleteTestReferences VALUES (${draftId})`);
assert.equal((await request(`/${draftId}`, 'DELETE', { lockVersion: 1 })).status, 500);
assert.equal((await request(`/${draftId}`)).data.Lines.length, 3);
await pool.request().query('DROP TABLE dbo.BomDeleteTestReferences');
const deletions = await Promise.all([1, 2].map(() => request(`/${draftId}`, 'DELETE', { lockVersion: 1 })));
assert.deepEqual(deletions.map(result => result.status).sort(), [200, 404]);
assert.equal((await pool.request().input('id', sql.Int, draftId).query('SELECT COUNT(*) AS Total FROM dbo.RobotBomLines WHERE BomId = @id')).recordset[0].Total, 0);
assert.equal((await request(`/${id}`, 'DELETE', { lockVersion: 4 })).status, 200);
assert.equal((await request(`/${id}`)).status, 404);
assert.equal((await request(`/${copies[1].data.BomId}`)).data.Lines.length, 3);
assert.equal((await request(`/${detached.data.BomId}`)).data.Status, 'released');
} finally {
if (server) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
if (pool) await pool.close();
if (admin) {
// Only the explicitly created, randomized test database is eligible for cleanup.
if (created && /^AccManagerBomTest_[a-f0-9]{32}$/.test(database)) await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [${database}]`);
await admin.close();
}
}
});

View File

@@ -0,0 +1,78 @@
const express = require('express');
const { createRobotBomRouter } = require('./robot-bom');
function createBomFixture({ role = 'asset', failQuery } = {}) {
const state = {
models: [{ RobotId: 1, Model: 'AMR-500', TypeId: 1, Type: 'AMR', Name: 'Robot vận chuyển' }],
catalog: [
{ SourceType: 'asset', SourceId: 1, Code: 'LK-001', Name: 'Động cơ servo 400W', Model: 'SV-400', Unit: 'cái', Available: 8, Location: 'Kho A' },
{ SourceType: 'asset', SourceId: 2, Code: 'LK-002', Name: 'Bánh xe chủ động', Model: 'WH-200', Unit: 'cái', Available: 16, Location: 'Kho A' },
{ SourceType: 'asset', SourceId: 3, Code: 'LK-003', Name: 'Bộ pin 48V 40Ah', Model: 'BAT-48-40', Unit: 'bộ', Available: 3, Location: 'Kho A' },
{ SourceType: 'consumable', SourceId: 1, Code: 'VT-001', Name: 'Cáp nguồn', Model: 'CB-2X2.5', Unit: 'm', Available: 30, Location: '' }
],
headers: [], lines: []
};
let nextId = 1;
const queries = [], transactions = [];
class Request {
constructor(transaction) { this.transaction = transaction; this.inputs = {}; }
input(name, _type, value) { this.inputs[name] = value; return this; }
async query(query) {
const inputs = this.inputs; queries.push({ query, inputs, transaction: this.transaction });
if (failQuery?.(query, inputs)) throw new Error('test database failure');
const rows = recordset => ({ recordset: structuredClone(recordset) });
if (query.includes('FROM dbo.AssetInventory')) return rows(state.catalog.filter(item => item.SourceType === 'asset')
.map(item => ({ Id: item.SourceId, Code: item.Code, Name: item.Name, Model: item.Model, Unit: item.Unit })));
if (query.includes('WITH ModelCatalog')) {
const models = [...state.models];
for (const header of state.headers) {
if (!models.some(model => model.Model === header.RobotModel && model.TypeId === header.RobotTypeId)) models.push({
RobotId: null, Model: header.RobotModel, TypeId: header.RobotTypeId, Type: 'AMR', Name: 'BOM đã lưu theo model'
});
}
return rows(models);
}
if (query.includes('SELECT Model, TypeId FROM dbo.Robots')) return rows(state.models.filter(item => item.RobotId === inputs.robotId));
if (query.includes('MAX(Revision)')) return rows([{ NextRevision: Math.max(0, ...state.headers.filter(item => item.RobotModel === inputs.model && item.RobotTypeId === inputs.typeId).map(item => item.Revision)) + 1 }]);
if (query.includes('INSERT dbo.RobotBomRevisions')) {
const now = new Date().toISOString();
const header = { BomId: nextId++, RobotModel: inputs.model, RobotTypeId: inputs.typeId, Revision: inputs.revision, Status: 'draft', LockVersion: 1, CreatedDate: now, UpdatedDate: now, ReleasedDate: null };
state.headers.push(header); return rows([header]);
}
if (query.includes('DELETE FROM dbo.RobotBomRevisions')) { state.headers = state.headers.filter(item => item.BomId !== inputs.id); return rows([]); }
if (query.includes('FROM dbo.RobotBomRevisions') && query.includes('WHERE BomId = @id')) return rows(state.headers.filter(item => item.BomId === inputs.id));
if (query.includes('FROM dbo.RobotBomRevisions b')) return rows(state.headers.filter(item => item.RobotModel === inputs.model && item.RobotTypeId === inputs.typeId).map(item => ({ ...item, LineCount: state.lines.filter(line => line.BomId === item.BomId).length })).sort((a, b) => b.Revision - a.Revision));
if (query.includes('SELECT * FROM dbo.RobotBomLines')) return rows(state.lines.filter(item => item.BomId === inputs.id).sort((a, b) => a.SortOrder - b.SortOrder));
if (query.includes('DELETE FROM dbo.RobotBomLines')) { state.lines = state.lines.filter(item => item.BomId !== inputs.id); return rows([]); }
if (query.includes('INSERT dbo.RobotBomLines')) {
state.lines.push({ BomId: inputs.bomId, SourceType: inputs.sourceType, SourceId: inputs.sourceId,
Code: inputs.code, Name: inputs.name, Model: inputs.model, Unit: inputs.unit,
GroupName: inputs.groupName, Position: inputs.position, Quantity: inputs.quantity,
Notes: inputs.notes, SourceInfo: inputs.sourceInfo, SortOrder: inputs.sortOrder }); return rows([]);
}
if (query.includes('UPDATE dbo.RobotBomRevisions')) {
const header = state.headers.find(item => item.BomId === inputs.id);
header.LockVersion++; header.UpdatedDate = new Date().toISOString();
if (query.includes("Status = 'released'")) { header.Status = 'released'; header.ReleasedDate = header.UpdatedDate; }
return rows([header]);
}
throw new Error(`Unexpected fixture query: ${query}`);
}
}
class Transaction {
constructor() { transactions.push(this); }
async begin() { this.snapshot = structuredClone(state); }
async commit() { this.committed = true; }
async rollback() { Object.assign(state, this.snapshot); this.rolledBack = true; }
}
const app = express();
app.use(express.json());
app.use((req, _res, next) => { req.user = { UserId: 1, Role: role }; next(); });
app.use('/api/robot-boms', createRobotBomRouter({ getPool: () => ({ request: () => new Request() }),
sql: { ...require('mssql'), Request, Transaction },
requireManage(req, res, next) { if (!['asset', 'admin'].includes(req.user.Role)) return res.status(403).json({ success: false }); next(); },
sendInternalError(res, _error, message) { return res.status(500).json({ success: false, message }); }
}));
return { app, state, queries, transactions };
}
module.exports = { createBomFixture };

186
backend/robot-bom.js Normal file
View File

@@ -0,0 +1,186 @@
const express = require('express');
const fs = require('node:fs');
const path = require('node:path');
const MAX_LINES = 500;
const fail = (message, status = 400) => Object.assign(new Error(message), { status });
function positiveId(value) {
if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value)) || Number(value) < 1 || Number(value) > 2147483647) {
throw fail('Mã dữ liệu không hợp lệ');
}
return Number(value);
}
function textField(value, max, label, required = false) {
if (typeof value !== 'string' || value.trim().length > max || (required && !value.trim())) {
throw fail(`${label} ${required ? 'không được trống và ' : ''}tối đa ${max} ký tự`);
}
return value.trim();
}
function quantity(value, unit) {
if (!/^\d+(\.\d{1,4})?$/.test(String(value)) || !Number.isFinite(Number(value)) || Number(value) <= 0 || Number(value) > 100000) {
throw fail('Số lượng phải lớn hơn 0, tối đa 100.000 và không quá 4 chữ số thập phân');
}
const fractional = /^(m|m2|m²|m3|m³|mét|met|kg|g|gam|l|lít|lit|ml|mm|cm|tấn|tan)$/i.test(String(unit).trim());
if (String(unit).trim() && !fractional && !Number.isInteger(Number(value))) throw fail(`Đơn vị ${unit} yêu cầu số lượng nguyên`);
return Number(value);
}
function normalizeLines(input) {
if (!Array.isArray(input) || input.length > MAX_LINES) throw fail(`BOM tối đa ${MAX_LINES} dòng vật tư`);
return input.map((line, index) => {
if (!line || typeof line !== 'object' || Array.isArray(line)) throw fail(`Vật tư dòng ${index + 1} không hợp lệ`);
const unit = textField(line.unit ?? '', 50, 'Đơn vị');
return { SourceType: 'manual', SourceId: null,
Name: textField(line.name, 255, 'Tên vật tư', true),
Code: textField(line.code ?? '', 100, 'Mã vật tư'), Model: textField(line.model ?? '', 255, 'Model vật tư'),
Unit: unit, GroupName: textField(line.groupName ?? '', 100, 'Cụm lắp ráp'),
Position: textField(line.position ?? '', 150, 'Vị trí lắp'), Quantity: quantity(line.quantity ?? 1, unit),
SourceInfo: textField(line.sourceInfo ?? '', 1000, 'Nguồn'),
Notes: textField(line.notes ?? '', 500, 'Ghi chú'), SortOrder: index };
});
}
async function ensureRobotBomSchema(pool) {
await pool.request().batch(fs.readFileSync(path.join(__dirname, 'robot-bom-schema.sql'), 'utf8'));
}
function createRobotBomRouter({ getPool, sql, requireManage, sendInternalError }) {
const router = express.Router();
const handle = fn => async (req, res) => {
try { req.body ??= {}; await fn(req, res); }
catch (error) {
if (error.status) return res.status(error.status).json({ success: false, message: error.message });
if ([2601, 2627, 1205].includes(error.number)) return res.status(409).json({ success: false, message: 'Dữ liệu vừa được thay đổi. Hãy tải lại BOM rồi thử lại.' });
return sendInternalError(res, error, 'Không thể xử lý BOM robot');
}
};
const inTransaction = async fn => {
const transaction = new sql.Transaction(getPool());
await transaction.begin();
try { const result = await fn(() => new sql.Request(transaction)); await transaction.commit(); return result; }
catch (error) { try { await transaction.rollback(); } catch {} throw error; }
};
const loadHeader = async (request, id, lock = false) => {
const result = await request.input('id', sql.Int, positiveId(id)).query(`
SELECT * FROM dbo.RobotBomRevisions ${lock ? 'WITH (UPDLOCK, HOLDLOCK)' : ''} WHERE BomId = @id`);
if (!result.recordset[0]) throw fail('Không tìm thấy phiên bản BOM', 404);
return result.recordset[0];
};
const checkDraft = (header, version) => {
if (header.Status !== 'draft') throw fail('BOM đã phát hành. Hãy sao chép thành phiên bản nháp mới để chỉnh sửa.', 409);
if (header.LockVersion !== positiveId(version)) throw fail('BOM đã được người khác thay đổi. Hãy tải lại trước khi lưu.', 409);
};
const readLines = async (request, id) => (await request.input('id', sql.Int, id)
.query('SELECT * FROM dbo.RobotBomLines WHERE BomId = @id ORDER BY SortOrder, LineId')).recordset;
async function insertLines(request, id, lines) {
for (const line of lines) {
await request().input('bomId', sql.Int, id)
.input('sourceType', sql.VarChar(10), line.SourceType).input('sourceId', sql.Int, line.SourceId)
.input('code', sql.NVarChar(100), line.Code).input('name', sql.NVarChar(255), line.Name)
.input('model', sql.NVarChar(255), line.Model).input('unit', sql.NVarChar(50), line.Unit)
.input('groupName', sql.NVarChar(100), line.GroupName).input('position', sql.NVarChar(150), line.Position)
.input('quantity', sql.Decimal(18, 4), line.Quantity).input('notes', sql.NVarChar(500), line.Notes)
.input('sourceInfo', sql.NVarChar(1000), line.SourceInfo || '')
.input('sortOrder', sql.Int, line.SortOrder).query(`
INSERT dbo.RobotBomLines (BomId, SourceType, SourceId, Code, Name, Model, Unit, GroupName, Position, Quantity, Notes, SourceInfo, SortOrder)
VALUES (@bomId, @sourceType, @sourceId, @code, @name, @model, @unit, @groupName, @position, @quantity, @notes, @sourceInfo, @sortOrder)`);
}
}
router.get('/models', handle(async (_req, res) => {
const result = await getPool().request().query(`
WITH ModelCatalog AS (
SELECT Model, TypeId FROM dbo.Robots
UNION SELECT RobotModel, RobotTypeId FROM dbo.RobotBomRevisions
)
SELECT MIN(r.RobotId) AS RobotId, m.Model, m.TypeId, t.Name AS Type,
COALESCE(MIN(r.Name), N'BOM đã lưu theo model') AS Name
FROM ModelCatalog m JOIN dbo.RobotTypes t ON t.TypeId = m.TypeId
LEFT JOIN dbo.Robots r ON r.Model = m.Model AND r.TypeId = m.TypeId
GROUP BY m.Model, m.TypeId, t.Name ORDER BY m.Model, t.Name`);
res.json({ success: true, data: result.recordset });
}));
router.get('/catalog', handle(async (_req, res) => {
// This picker copies descriptions only. All quantities belong to the BOM.
const result = await getPool().request().query(`
SELECT AssetId AS Id, AssetCode AS Code, AssetName AS Name,
ISNULL(Model, '') AS Model, ISNULL(Unit, '') AS Unit
FROM dbo.AssetInventory WHERE IsArchived = 0 ORDER BY AssetName, AssetCode`);
res.json({ success: true, data: result.recordset });
}));
router.get('/', handle(async (req, res) => {
const model = textField(req.query.model, 255, 'Model robot', true);
const result = await getPool().request().input('model', sql.NVarChar(255), model)
.input('typeId', sql.Int, positiveId(req.query.typeId)).query(`
SELECT b.*, (SELECT COUNT(*) FROM dbo.RobotBomLines l WHERE l.BomId = b.BomId) AS LineCount
FROM dbo.RobotBomRevisions b WHERE RobotModel = @model AND RobotTypeId = @typeId ORDER BY Revision DESC`);
res.json({ success: true, data: result.recordset });
}));
router.get('/:id', handle(async (req, res) => {
const header = await loadHeader(getPool().request(), req.params.id);
res.json({ success: true, data: { ...header, Lines: await readLines(getPool().request(), header.BomId) } });
}));
router.post('/', requireManage, handle(async (req, res) => {
const copyFrom = req.body.copyFromId == null ? null : positiveId(req.body.copyFromId);
const robotId = req.body.robotId == null && copyFrom ? null : positiveId(req.body.robotId);
const header = await inTransaction(async request => {
const source = copyFrom ? await loadHeader(request(), copyFrom, true) : null;
const robot = robotId == null ? { Model: source.RobotModel, TypeId: source.RobotTypeId }
: (await request().input('robotId', sql.Int, robotId)
.query('SELECT Model, TypeId FROM dbo.Robots WITH (HOLDLOCK) WHERE RobotId = @robotId')).recordset[0];
if (!robot) throw fail('Robot không còn trong danh mục. Hãy tải lại danh sách.', 404);
const revision = (await request().input('model', sql.NVarChar(255), robot.Model).input('typeId', sql.Int, robot.TypeId)
.query(`SELECT ISNULL(MAX(Revision), 0) + 1 AS NextRevision FROM dbo.RobotBomRevisions WITH (UPDLOCK, HOLDLOCK)
WHERE RobotModel = @model AND RobotTypeId = @typeId`)).recordset[0].NextRevision;
const inserted = (await request().input('model', sql.NVarChar(255), robot.Model).input('typeId', sql.Int, robot.TypeId)
.input('revision', sql.Int, revision).input('userId', sql.Int, req.user.UserId)
.query(`INSERT dbo.RobotBomRevisions (RobotModel, RobotTypeId, Revision, CreatedBy)
OUTPUT INSERTED.* VALUES (@model, @typeId, @revision, @userId)`)).recordset[0];
if (copyFrom) {
await insertLines(request, inserted.BomId, await readLines(request(), copyFrom));
}
return inserted;
});
res.status(201).json({ success: true, data: header, message: 'Đã tạo phiên bản BOM nháp' });
}));
router.put('/:id', requireManage, handle(async (req, res) => {
const id = positiveId(req.params.id);
if (!Array.isArray(req.body.lines) || req.body.lines.length > MAX_LINES) throw fail(`BOM tối đa ${MAX_LINES} dòng vật tư`);
const saved = await inTransaction(async request => {
const header = await loadHeader(request(), id, true); checkDraft(header, req.body.lockVersion);
const lines = normalizeLines(req.body.lines);
await request().input('id', sql.Int, id).query('DELETE FROM dbo.RobotBomLines WHERE BomId = @id');
await insertLines(request, id, lines);
const updated = (await request().input('id', sql.Int, id).query(`UPDATE dbo.RobotBomRevisions
SET LockVersion = LockVersion + 1, UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
OUTPUT INSERTED.UpdatedDate WHERE BomId = @id`)).recordset[0];
return { BomId: id, LockVersion: header.LockVersion + 1, UpdatedDate: updated.UpdatedDate, Lines: lines };
});
res.json({ success: true, data: saved, message: 'Đã lưu BOM nháp' });
}));
router.delete('/:id', requireManage, handle(async (req, res) => {
const id = positiveId(req.params.id);
await inTransaction(async request => {
const header = await loadHeader(request(), id, true);
if (header.LockVersion !== positiveId(req.body.lockVersion)) {
throw fail('BOM đã được người khác thay đổi. Hãy tải lại trước khi xóa.', 409);
}
await request().input('id', sql.Int, id).query('DELETE FROM dbo.RobotBomLines WHERE BomId = @id');
await request().input('id', sql.Int, id).query('DELETE FROM dbo.RobotBomRevisions WHERE BomId = @id');
});
res.json({ success: true, message: 'Đã xóa phiên bản BOM' });
}));
router.post('/:id/publish', requireManage, handle(async (req, res) => {
const id = positiveId(req.params.id);
await inTransaction(async request => {
const header = await loadHeader(request(), id, true); checkDraft(header, req.body.lockVersion);
const lines = await readLines(request(), id);
if (!lines.length) throw fail('BOM cần có ít nhất một vật tư trước khi phát hành');
normalizeLines(lines.map(line => ({ name: line.Name, unit: line.Unit, quantity: line.Quantity,
code: line.Code, model: line.Model, groupName: line.GroupName, position: line.Position, notes: line.Notes,
sourceInfo: line.SourceInfo || '' })));
await request().input('id', sql.Int, id).query(`UPDATE dbo.RobotBomRevisions SET Status = 'released',
LockVersion = LockVersion + 1, ReleasedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()),
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()) WHERE BomId = @id`);
});
res.json({ success: true, message: 'Đã phát hành BOM. Có thể sao chép thành phiên bản mới khi cần chỉnh sửa.' });
}));
return router;
}
module.exports = { ensureRobotBomSchema, createRobotBomRouter, normalizeLines, quantity };

212
backend/robot-bom.test.js Normal file
View File

@@ -0,0 +1,212 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { normalizeLines, quantity } = require('./robot-bom');
const { createBomFixture } = require('./robot-bom-test-fixture');
const line = extra => ({ name: 'Động cơ servo 400W', model: 'SV-400', unit: 'cái', quantity: 2,
sourceInfo: 'https://example.com/servo', notes: '', ...extra });
async function fixture(t, options) {
const f = createBomFixture(options);
const server = f.app.listen(0, '127.0.0.1');
await new Promise(resolve => server.once('listening', resolve));
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
f.request = async (suffix = '', method = 'GET', body) => {
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/robot-boms${suffix}`, { method,
...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) });
return { status: response.status, ...(response.headers.get('content-type')?.includes('application/json')
? await response.json() : { message: await response.text() }) };
};
return f;
}
test('BOM stores editable names/models, quantities and supplier sources without touching inventory', async t => {
const f = await fixture(t);
const created = await f.request('', 'POST', { robotId: 1 });
assert.equal(created.status, 201);
const id = created.data.BomId;
const saved = await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
assert.equal(saved.status, 200); assert.equal(saved.data.LockVersion, 2);
const reopened = await f.request(`/${id}`);
assert.equal(reopened.data.Lines[0].Name, 'Động cơ servo 400W');
assert.equal(reopened.data.Lines[0].Model, 'SV-400');
assert.equal(reopened.data.Lines[0].SourceInfo, 'https://example.com/servo');
assert.equal(reopened.data.Lines[0].SourceId, null);
assert.equal(reopened.data.Lines[0].SourceType, 'manual');
const revisions = await f.request('?model=AMR-500&typeId=1');
assert.equal(revisions.data[0].LineCount, 1);
assert.equal(f.queries.some(({ query }) => /\b(?:AssetInventory|ConsumableInventory)\b/i.test(query)), false);
});
test('asset picker exposes names/models with no stock quantities, including assets with zero stock', async t => {
const f = await fixture(t);
f.state.catalog[0].Available = 0;
const result = await f.request('/catalog');
assert.equal(result.status, 200); assert.equal(result.data.length, 3);
assert.deepEqual(Object.keys(result.data[0]).sort(), ['Code', 'Id', 'Model', 'Name', 'Unit']);
assert.doesNotMatch(f.queries[0].query, /EndingBalance|Quantity|Available/);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line({ quantity: 2000 })] })).status, 200);
assert.equal(f.state.catalog[0].Available, 0);
});
test('publishing freezes the saved snapshot; copying produces an editable independent revision', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] })).status, 200);
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 2 })).status, 200);
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 3, lines: [] })).status, 409);
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 3 })).status, 409);
f.state.catalog[0].Name = 'New inventory name';
const snapshot = await f.request(`/${id}`);
assert.equal(snapshot.data.Lines[0].Name, 'Động cơ servo 400W');
const copied = await f.request('', 'POST', { robotId: 1, copyFromId: id });
assert.equal(copied.data.Revision, 2); assert.equal(copied.data.Status, 'draft');
await f.request(`/${copied.data.BomId}`, 'PUT', { lockVersion: 1, lines: [line({ quantity: 3 })] });
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
assert.equal((await f.request(`/${copied.data.BomId}`)).data.Lines[0].Quantity, 3);
assert.equal((await f.request(`/${copied.data.BomId}`)).data.Lines[0].SourceInfo, 'https://example.com/servo');
});
test('concurrent stale saves are rejected without overwriting newer quantities', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line({ quantity: 99 })] })).status, 409);
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 1 })).status, 409);
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
});
test('an insert failure rolls back a complete BOM save including deleted old lines', async t => {
let fail = false;
const f = await fixture(t, { failQuery: query => fail && query.includes('INSERT dbo.RobotBomLines') });
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
fail = true;
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 2, lines: [line({ quantity: 3 })] })).status, 500);
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
assert.equal((await f.request(`/${id}`)).data.LockVersion, 2);
assert.equal(f.transactions.at(-1).rolledBack, true);
});
test('external parts and supplier descriptions work without any inventory records', async t => {
const f = await fixture(t);
f.state.catalog = [];
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
const lines = [line({ name: 'Khung gia công bên ngoài', model: 'CUSTOM-01', quantity: 12, sourceInfo: 'Nhà sản xuất: Cơ khí ABC, liên hệ bộ phận kỹ thuật' }), { name: 'Bulong M6' }];
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines })).status, 200);
const saved = (await f.request(`/${id}`)).data.Lines;
assert.equal(saved[0].Quantity, 12); assert.equal(saved[1].Quantity, 1);
assert.equal(saved[0].SourceInfo, lines[0].sourceInfo);
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 2 })).status, 200);
assert.equal((await f.request('/requirements/check', 'POST', {})).status, 404);
assert.equal(f.queries.some(({ query }) => /Inventory/.test(query)), false);
});
test('viewers can read BOMs and descriptive asset choices but cannot create, edit, publish or delete', async t => {
const f = await fixture(t, { role: 'user' });
for (const suffix of ['/models', '/catalog', '?model=AMR-500&typeId=1']) assert.equal((await f.request(suffix)).status, 200);
for (const [suffix, method] of [['', 'POST'], ['/1', 'PUT'], ['/1/publish', 'POST'], ['/1', 'DELETE']]) assert.equal((await f.request(suffix, method, { robotId: 1 })).status, 403);
assert.equal(f.transactions.length, 0);
});
for (const role of ['admin', 'asset']) {
for (const released of [false, true]) {
test(`${role} can delete a ${released ? 'released' : 'draft'} BOM with its lines while preserving copied revisions and inventory`, async t => {
const f = await fixture(t, { role });
const catalog = structuredClone(f.state.catalog);
const models = structuredClone(f.state.models);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
if (released) await f.request(`/${id}/publish`, 'POST', { lockVersion: 2 });
const copiedId = (await f.request('', 'POST', { copyFromId: id })).data.BomId;
const result = await f.request(`/${id}`, 'DELETE', { lockVersion: released ? 3 : 2 });
assert.equal(result.status, 200); assert.equal(result.success, true);
assert.equal((await f.request(`/${id}`)).status, 404);
assert.equal(f.state.lines.some(item => item.BomId === id), false);
assert.deepEqual((await f.request('?model=AMR-500&typeId=1')).data.map(item => item.BomId), [copiedId]);
assert.equal((await f.request(`/${copiedId}`)).data.Lines[0].Quantity, 2);
assert.deepEqual(f.state.catalog, catalog); assert.deepEqual(f.state.models, models);
const deletes = f.queries.filter(({ query }) => query.startsWith('DELETE'));
assert.equal(deletes.at(-1).transaction, deletes.at(-2).transaction);
assert.equal(f.transactions.at(-1).committed, true);
});
}
}
test('deletion rejects stale or invalid versions and invalid or missing BOM identifiers', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 1 })).status, 409);
for (const lockVersion of [undefined, 0, -1, 'invalid']) {
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion })).status, 400);
}
for (const badId of ['abc', '0', '-1', '2147483648']) {
assert.equal((await f.request(`/${badId}`, 'DELETE', { lockVersion: 2 })).status, 400);
}
assert.equal((await f.request('/999', 'DELETE', { lockVersion: 2 })).status, 404);
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
assert.equal(f.queries.some(({ query }) => query.startsWith('DELETE FROM dbo.RobotBomRevisions')), false);
});
test('a header deletion failure rolls back removed BOM lines and allows retry', async t => {
let fail = true;
const f = await fixture(t, { failQuery: query => fail && query.includes('DELETE FROM dbo.RobotBomRevisions') });
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 2 })).status, 500);
assert.equal(f.transactions.at(-1).rolledBack, true);
const retained = (await f.request(`/${id}`)).data;
assert.equal(retained.LockVersion, 2); assert.equal(retained.Lines[0].Quantity, 2);
fail = false;
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 2 })).status, 200);
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 2 })).status, 404);
});
test('deleting the final historical BOM removes its orphaned model and supports an empty BOM', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
f.state.models = [];
assert.equal((await f.request('/models')).data.length, 1);
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 1 })).status, 200);
assert.deepEqual((await f.request('/models')).data, []);
assert.deepEqual((await f.request('?model=AMR-500&typeId=1')).data, []);
});
test('bad identifiers, empty publications, invalid lines and unsafe quantities are rejected', async t => {
const f = await fixture(t);
assert.equal((await f.request('/abc')).status, 400);
assert.equal((await f.request('/999')).status, 404);
assert.equal((await f.request('', 'POST', { robotId: 999 })).status, 404);
assert.equal((await f.request('', 'POST')).status, 400);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 1 })).status, 400);
for (const bad of [null, [null], [line({ name: '' })], [line({ name: ' '.repeat(2) })], [line({ model: 'x'.repeat(256) })], [line({ sourceInfo: 'x'.repeat(1001) })], [line({ quantity: -1 })], [line({ quantity: 0.5 })], Array(501).fill(line())]) {
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: bad })).status, 400);
}
for (const value of [0, -1, 100001, 'NaN', Infinity, '1e4', 0.00001]) assert.throws(() => quantity(value, 'm'));
assert.equal(quantity(0.125, 'm'), 0.125);
});
test('a name alone is sufficient; inventory identity is discarded while descriptive metadata is retained', () => {
const normalized = normalizeLines([{ name: 'Cảm biến ngoài', sourceType: 'asset', sourceId: 999 }])[0];
assert.equal(normalized.Name, 'Cảm biến ngoài'); assert.equal(normalized.Quantity, 1);
assert.equal(normalized.Model, ''); assert.equal(normalized.Unit, '');
assert.equal(normalized.SourceType, 'manual'); assert.equal(normalized.SourceId, null);
assert.equal(normalizeLines([line(), line()]).length, 2);
assert.equal(normalizeLines([line({ unit: '', quantity: 0.125 })])[0].Quantity, 0.125);
assert.deepEqual(normalizeLines([]), []);
});
test('historical models and revisions remain accessible after their last robot is removed', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
f.state.models = [];
const models = await f.request('/models');
assert.equal(models.data[0].Model, 'AMR-500'); assert.equal(models.data[0].RobotId, null);
assert.equal((await f.request('?model=AMR-500&typeId=1')).data.length, 1);
const copied = await f.request('', 'POST', { copyFromId: id });
assert.equal(copied.status, 201); assert.equal(copied.data.Revision, 2);
assert.equal((await f.request(`/${copied.data.BomId}`)).data.Lines.length, 1);
});

71
backend/robot-schema.sql Normal file
View File

@@ -0,0 +1,71 @@
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.RobotTypes', 'U') IS NULL
BEGIN
CREATE TABLE dbo.RobotTypes (
TypeId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
Name NVARCHAR(100) NOT NULL,
Description NVARCHAR(500) NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
CONSTRAINT UQ_RobotTypes_Name UNIQUE (Name)
);
END;
IF OBJECT_ID('dbo.Robots', 'U') IS NULL
BEGIN
CREATE TABLE dbo.Robots (
RobotId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
Name NVARCHAR(255) NOT NULL,
Model NVARCHAR(255) NOT NULL,
Type NVARCHAR(100) NOT NULL,
AvatarData VARBINARY(MAX) NULL,
AvatarMimeType NVARCHAR(100) NULL,
CreatedBy INT NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
CONSTRAINT FK_Robots_CreatedBy FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId) ON DELETE SET NULL
);
CREATE INDEX IX_Robots_Name ON dbo.Robots(Name);
END;
IF COL_LENGTH('dbo.Robots', 'TypeId') IS NULL
ALTER TABLE dbo.Robots ADD TypeId INT NULL;
-- A separate compilation scope is required when TypeId was just added.
-- Only unmigrated rows seed the catalog, so renamed types stay renamed.
EXEC(N'
INSERT INTO dbo.RobotTypes (Name)
SELECT DISTINCT COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
FROM dbo.Robots r
WHERE r.TypeId IS NULL AND NOT EXISTS (
SELECT 1 FROM dbo.RobotTypes t
WHERE t.Name = COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
);
UPDATE r SET TypeId = t.TypeId, Type = t.Name
FROM dbo.Robots r JOIN dbo.RobotTypes t
ON t.Name = COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
WHERE r.TypeId IS NULL;
');
IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('dbo.Robots') AND name = 'TypeId' AND is_nullable = 1)
EXEC(N'ALTER TABLE dbo.Robots ALTER COLUMN TypeId INT NOT NULL;');
IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_Robots_Type')
EXEC(N'ALTER TABLE dbo.Robots ADD CONSTRAINT FK_Robots_Type FOREIGN KEY (TypeId) REFERENCES dbo.RobotTypes(TypeId);');
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.Robots') AND name = 'IX_Robots_TypeId')
EXEC(N'CREATE INDEX IX_Robots_TypeId ON dbo.Robots(TypeId);');
IF OBJECT_ID('dbo.RobotDocuments', 'U') IS NULL
BEGIN
CREATE TABLE dbo.RobotDocuments (
RobotId INT NOT NULL,
DocumentId INT NOT NULL,
CONSTRAINT PK_RobotDocuments PRIMARY KEY (RobotId, DocumentId),
CONSTRAINT FK_RobotDocuments_Robot FOREIGN KEY (RobotId) REFERENCES dbo.Robots(RobotId) ON DELETE CASCADE,
CONSTRAINT FK_RobotDocuments_Document FOREIGN KEY (DocumentId) REFERENCES dbo.Documents(DocumentId)
);
CREATE INDEX IX_RobotDocuments_DocumentId ON dbo.RobotDocuments(DocumentId);
END;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;

171
backend/robots-sql.test.js Normal file
View File

@@ -0,0 +1,171 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { randomBytes } = require('node:crypto');
const express = require('express');
const sql = require('mssql');
const { createRobotRouter, ensureRobotSchema } = require('./robots');
// Explicit opt-in to a disposable loopback SQL Server; never load application credentials.
test('SQL Server preserves shared PDFs, migrates repeatedly, and rolls back an entire failed robot save', {
skip: process.env.ACCMANAGER_ARCHIVE_SQL_TEST === '1' ? false
: 'Set ACCMANAGER_ARCHIVE_SQL_TEST=1 and explicit local SQL test credentials',
timeout: 120000
}, async () => {
const password = process.env.ACCMANAGER_ARCHIVE_TEST_SQL_PASSWORD;
const port = Number(process.env.ACCMANAGER_ARCHIVE_TEST_SQL_PORT || 14339);
assert.ok(password, 'Explicit local test password is required');
assert.ok(Number.isInteger(port) && port > 0 && port < 65536);
const database = `AccManagerRobotsTest_${Date.now()}_${randomBytes(6).toString('hex')}`;
const config = { server: '127.0.0.1', port, user: 'sa', password, database: 'master',
options: { encrypt: false, trustServerCertificate: true, enableArithAbort: true, useUTC: false },
pool: { min: 0, max: 3, idleTimeoutMillis: 1000 }, connectionTimeout: 15000, requestTimeout: 30000 };
const admin = await new sql.ConnectionPool(config).connect();
let pool, server, created = false;
try {
await admin.request().query(`CREATE DATABASE [${database}]`); created = true;
pool = await new sql.ConnectionPool({ ...config, database }).connect();
await pool.request().batch(`
CREATE TABLE dbo.Users (UserId INT IDENTITY PRIMARY KEY, Username NVARCHAR(100));
INSERT dbo.Users (Username) VALUES ('test');
CREATE TABLE dbo.Documents (
DocumentId INT IDENTITY PRIMARY KEY, Title NVARCHAR(255) NOT NULL,
OriginalFileName NVARCHAR(255) NOT NULL, MimeType NVARCHAR(100) NOT NULL DEFAULT 'application/pdf',
FileSize BIGINT NOT NULL, FileData VARBINARY(MAX) NOT NULL, UploadedBy INT NULL,
UploadedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
FOREIGN KEY (UploadedBy) REFERENCES dbo.Users(UserId) ON DELETE SET NULL
);
INSERT dbo.Documents (Title, OriginalFileName, FileSize, FileData, UploadedBy)
VALUES (N'Existing manual', 'existing.pdf', 12, 0x255044462D, 1),
(N'Failure case', 'failure.pdf', 12, 0x255044462D, 1);
CREATE TABLE dbo.Robots (
RobotId INT IDENTITY PRIMARY KEY, Name NVARCHAR(255) NOT NULL, Model NVARCHAR(255) NOT NULL,
Type NVARCHAR(100) NOT NULL, AvatarData VARBINARY(MAX) NULL, AvatarMimeType NVARCHAR(100) NULL,
CreatedBy INT NULL, CreatedDate DATETIME NOT NULL DEFAULT GETDATE(), UpdatedDate DATETIME NOT NULL DEFAULT GETDATE()
);
INSERT dbo.Robots (Name, Model, Type) VALUES (N'Legacy robot', 'LEGACY', N'Robot thử nghiệm');
`);
await ensureRobotSchema(pool); await ensureRobotSchema(pool);
const migrated = (await pool.request().query('SELECT r.TypeId, r.Type, t.Name FROM dbo.Robots r JOIN dbo.RobotTypes t ON t.TypeId = r.TypeId')).recordset;
assert.equal(migrated.length, 1);
assert.equal(migrated[0].Name, 'Robot thử nghiệm');
const typeId = migrated[0].TypeId;
await pool.request().query('DELETE dbo.Robots');
const app = express();
app.use(express.json());
app.use((req, _res, next) => { req.user = { UserId: 1, Role: 'asset' }; next(); });
app.use('/robots', createRobotRouter({ getPool: () => pool, sql, requireManage: (_req, _res, next) => next(),
documentMaxBytes: 1024 * 1024, documentMaxMb: 1,
isPdfBuffer: b => b.subarray(0, 5).toString() === '%PDF-' && b.includes(Buffer.from('%%EOF')),
sanitizeDocumentFileName: name => name,
sendInternalError: (res, _error, message) => res.status(500).json({ success: false, message })
}));
server = app.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
const request = (suffix, options) => fetch(`http://127.0.0.1:${server.address().port}/robots${suffix}`, options);
const pdf = Buffer.from('%PDF-1.4\nNew manual\n%%EOF');
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aLl8AAAAASUVORK5CYII=', 'base64');
const form = (name, documentIds = '[1]') => {
const body = new FormData();
for (const [key, value] of Object.entries({ name, model: 'SQL-TEST', typeId: String(typeId), documentIds })) body.append(key, value);
return body;
};
const snapshot = async () => (await pool.request().query(`
SELECT COUNT(*) AS n FROM dbo.Robots;
SELECT COUNT(*) AS n FROM dbo.Documents;
SELECT COUNT(*) AS n FROM dbo.RobotDocuments;
`)).recordsets.map(rows => rows[0].n);
const body = form('Robot thử SQL');
body.append('avatar', new Blob([png], { type: 'image/png' }), 'robot.png');
body.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'new.pdf');
const create = await request('', { method: 'POST', body });
assert.equal(create.status, 201, await create.clone().text());
const firstId = (await create.json()).data.RobotId;
assert.deepEqual(await snapshot(), [1, 3, 2]);
const avatar = await request(`/${firstId}/avatar`);
assert.deepEqual(Buffer.from(await avatar.arrayBuffer()), png);
let details = await (await request(`/${firstId}`)).json();
assert.equal(details.data.Name, 'Robot thử SQL');
assert.equal(details.data.Documents.length, 2);
const uploadedId = details.data.Documents.find(doc => doc.OriginalFileName === 'new.pdf').DocumentId;
const savedBytes = (await pool.request().input('id', sql.Int, uploadedId)
.query('SELECT FileData FROM dbo.Documents WHERE DocumentId = @id')).recordset[0].FileData;
assert.deepEqual(savedBytes, pdf);
// A second robot shares an existing PDF without duplicating its content.
const second = await request('', { method: 'POST', body: form('Robot thứ hai') });
assert.equal(second.status, 201);
const secondId = (await second.json()).data.RobotId;
assert.deepEqual(await snapshot(), [2, 3, 3]);
await assert.rejects(pool.request().query('DELETE dbo.Documents WHERE DocumentId = 1'), error => error.number === 547);
await ensureRobotSchema(pool);
assert.deepEqual(await snapshot(), [2, 3, 3]);
// An actual SQL constraint failure happens after metadata/PDF insertion.
await pool.request().query('ALTER TABLE dbo.RobotDocuments ADD CONSTRAINT CK_RobotLinks_Test CHECK (DocumentId <> 2)');
const failure = form('Must roll back', '[2]');
failure.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'rollback.pdf');
assert.equal((await request('', { method: 'POST', body: failure })).status, 500);
assert.deepEqual(await snapshot(), [2, 3, 3]);
const failedEdit = form('Must not overwrite existing robot', '[2]');
failedEdit.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'rollback-edit.pdf');
assert.equal((await request(`/${firstId}`, { method: 'PUT', body: failedEdit })).status, 500);
assert.deepEqual(await snapshot(), [2, 3, 3]);
details = await (await request(`/${firstId}`)).json();
assert.equal(details.data.Name, 'Robot thử SQL'); assert.equal(details.data.Documents.length, 2);
await pool.request().query('ALTER TABLE dbo.RobotDocuments DROP CONSTRAINT CK_RobotLinks_Test');
const partial = await request(`/${firstId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Đã sửa', model: 'NEW', typeId }) });
assert.equal(partial.status, 200);
details = await (await request(`/${firstId}`)).json();
assert.equal(details.data.Documents.length, 2); assert.equal(details.data.HasAvatar, true);
const clear = form('Đã gỡ liên kết', '[]'); clear.append('removeAvatar', 'true');
assert.equal((await request(`/${firstId}`, { method: 'PUT', body: clear })).status, 200);
assert.deepEqual(await snapshot(), [2, 3, 1]);
assert.equal((await request(`/${firstId}/avatar`)).status, 404);
await assert.rejects(pool.request().query('DELETE dbo.Documents WHERE DocumentId = 1'), error => error.number === 547);
assert.equal((await request(`/${secondId}`, { method: 'DELETE' })).status, 200);
assert.deepEqual(await snapshot(), [1, 3, 0]);
await pool.request().query('DELETE dbo.Documents WHERE DocumentId = 1');
assert.deepEqual(await snapshot(), [1, 2, 0]);
const json = body => ({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
assert.equal((await request(`/types/${typeId}`, { method: 'DELETE' })).status, 409);
assert.equal((await request('/types', { method: 'POST', ...json({ name: 'Robot thử nghiệm' }) })).status, 409);
const extraType = await request('/types', { method: 'POST', ...json({ name: 'Robot di động', description: 'AMR/AGV' }) });
assert.equal(extraType.status, 201);
const extraId = (await extraType.json()).data.TypeId;
// An in-use type can be renamed without changing its identity or its robots.
assert.equal((await request(`/types/${typeId}`, { method: 'PUT', ...json({ name: 'Thể loại đã đổi tên', description: 'Updated' }) })).status, 200);
await ensureRobotSchema(pool); await ensureRobotSchema(pool);
const catalog = (await (await request('/types')).json()).data;
assert.equal(catalog.length, 2);
assert.equal(catalog.find(type => type.TypeId === typeId).RobotCount, 1);
details = await (await request(`/${firstId}`)).json();
assert.equal(details.data.TypeId, typeId);
assert.equal(details.data.Type, 'Thể loại đã đổi tên');
const duplicateRename = await request(`/types/${typeId}`, { method: 'PUT', ...json({ name: 'Robot di động' }) });
assert.equal(duplicateRename.status, 409);
assert.equal((await (await request(`/${firstId}`)).json()).data.Type, 'Thể loại đã đổi tên');
// Reassignment releases the old type, while the new type becomes protected.
const reassign = form('Chuyển thể loại'); reassign.set('typeId', String(extraId)); reassign.set('documentIds', '[]');
assert.equal((await request(`/${firstId}`, { method: 'PUT', body: reassign })).status, 200);
assert.equal((await request(`/types/${typeId}`, { method: 'DELETE' })).status, 200);
assert.equal((await request(`/types/${extraId}`, { method: 'DELETE' })).status, 409);
assert.equal((await request(`/${firstId}`, { method: 'DELETE' })).status, 200);
assert.equal((await request(`/types/${extraId}`, { method: 'DELETE' })).status, 200);
const stale = form('Must reject stale type'); stale.set('typeId', String(extraId));
assert.equal((await request('', { method: 'POST', body: stale })).status, 400);
assert.deepEqual(await snapshot(), [0, 2, 0]);
} finally {
if (server) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
if (pool) await pool.close();
try {
if (created) {
assert.match(database, /^AccManagerRobotsTest_\d+_[a-f0-9]{12}$/);
await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE`);
await admin.request().query(`DROP DATABASE [${database}]`);
}
} finally { await admin.close(); }
}
});

317
backend/robots.js Normal file
View File

@@ -0,0 +1,317 @@
const express = require('express');
const multer = require('multer');
const fs = require('node:fs');
const path = require('node:path');
const { getDocumentFormat, validateDocumentFile, normalizeUploadedFileName } = require('./document-files');
const AVATAR_MAX_BYTES = 5 * 1024 * 1024;
const MAX_DOCUMENT_UPLOADS = 10;
const MAX_LINKED_DOCUMENTS = 100;
async function ensureRobotSchema(pool) {
await pool.request().batch(fs.readFileSync(path.join(__dirname, 'robot-schema.sql'), 'utf8'));
}
function invalid(message) {
return Object.assign(new Error(message), { status: 400 });
}
function positiveId(value) {
const id = Number(value);
if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(id) || id < 1 || id > 2147483647) {
throw invalid('Mã dữ liệu không hợp lệ');
}
return id;
}
function parseDocumentIds(value) {
if (value === undefined) return undefined;
let ids = value;
if (typeof value === 'string') {
try { ids = JSON.parse(value); } catch { throw invalid('Danh sách tài liệu không hợp lệ'); }
}
if (!Array.isArray(ids) || ids.length > MAX_LINKED_DOCUMENTS) {
throw invalid(`Chỉ được liên kết tối đa ${MAX_LINKED_DOCUMENTS} tài liệu`);
}
return [...new Set(ids.map(positiveId))].sort((a, b) => a - b);
}
function isAvatarBuffer(buffer, mimeType) {
if (!Buffer.isBuffer(buffer) || buffer.length < 12) return false;
if (mimeType === 'image/png') return buffer.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'));
if (mimeType === 'image/jpeg') return buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff;
if (mimeType === 'image/webp') return buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP';
return false;
}
function createRobotRouter({ getPool, sql, requireManage, documentMaxBytes, documentMaxMb,
sanitizeDocumentFileName, sendInternalError }) {
const router = express.Router();
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: Math.max(documentMaxBytes, AVATAR_MAX_BYTES), files: MAX_DOCUMENT_UPLOADS + 1,
fields: 6, parts: MAX_DOCUMENT_UPLOADS + 8, fieldSize: 64 * 1024 },
fileFilter(_req, file, callback) {
const extension = path.extname(file.originalname).toLowerCase();
const avatarTypes = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp' };
const valid = file.fieldname === 'avatar'
? avatarTypes[extension] === file.mimetype
: file.fieldname === 'documents' && Boolean(getDocumentFormat(file.originalname));
callback(valid ? null : invalid('Ảnh đại diện chỉ nhận JPG, PNG, WebP; định dạng tài liệu chưa được hỗ trợ'), valid);
}
}).fields([{ name: 'avatar', maxCount: 1 }, { name: 'documents', maxCount: MAX_DOCUMENT_UPLOADS }]);
const robotColumns = `r.RobotId, r.Name, r.Model, r.TypeId, t.Name AS Type, r.CreatedBy, r.CreatedDate, r.UpdatedDate,
CAST(CASE WHEN r.AvatarData IS NULL THEN 0 ELSE 1 END AS BIT) AS HasAvatar,
(SELECT COUNT(*) FROM dbo.RobotDocuments rd WHERE rd.RobotId = r.RobotId) AS DocumentCount`;
function fail(res, error) {
if (error.status === 400) return res.status(400).json({ success: false, message: error.message });
return sendInternalError(res, error, 'Không thể xử lý thông tin robot');
}
function failType(res, error) {
if ([2601, 2627].includes(error.number)) {
return res.status(409).json({ success: false, message: 'Tên thể loại robot đã tồn tại' });
}
if (error.number === 547) {
return res.status(409).json({ success: false, message: 'Thể loại đang được robot hoặc BOM sử dụng. Không thể xóa để bảo toàn dữ liệu liên quan.' });
}
return fail(res, error);
}
function typeFields(body = {}) {
if (typeof body.name !== 'string' || !body.name.trim() || body.name.trim().length > 100) {
throw invalid('Vui lòng nhập tên thể loại, tối đa 100 ký tự');
}
if (body.description != null && (typeof body.description !== 'string' || body.description.trim().length > 500)) {
throw invalid('Mô tả thể loại tối đa 500 ký tự');
}
return { name: body.name.trim(), description: body.description?.trim() || null };
}
// Declare catalog routes before /:id so "types" cannot be parsed as a robot ID.
router.get('/types', async (_req, res) => {
try {
const result = await getPool().request().query(`SELECT t.TypeId, t.Name, t.Description, t.CreatedDate, t.UpdatedDate,
(SELECT COUNT(*) FROM dbo.Robots r WHERE r.TypeId = t.TypeId) AS RobotCount
FROM dbo.RobotTypes t ORDER BY t.Name, t.TypeId`);
res.json({ success: true, data: result.recordset });
} catch (error) { failType(res, error); }
});
router.post('/types', requireManage, async (req, res) => {
try {
const fields = typeFields(req.body);
const result = await getPool().request().input('name', sql.NVarChar(100), fields.name)
.input('description', sql.NVarChar(500), fields.description).query(`
INSERT INTO dbo.RobotTypes (Name, Description)
OUTPUT INSERTED.TypeId, INSERTED.Name, INSERTED.Description
VALUES (@name, @description)`);
res.status(201).json({ success: true, data: result.recordset[0], message: 'Đã thêm thể loại robot' });
} catch (error) { failType(res, error); }
});
router.put('/types/:id', requireManage, async (req, res) => {
let transaction, begun = false;
try {
const typeId = positiveId(req.params.id);
const fields = typeFields(req.body);
transaction = new sql.Transaction(getPool());
await transaction.begin(); begun = true;
const result = await new sql.Request(transaction).input('typeId', sql.Int, typeId)
.input('name', sql.NVarChar(100), fields.name).input('description', sql.NVarChar(500), fields.description)
.query(`UPDATE dbo.RobotTypes SET Name = @name, Description = @description,
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
OUTPUT INSERTED.TypeId, INSERTED.Name, INSERTED.Description WHERE TypeId = @typeId`);
if (!result.recordset.length) {
await transaction.rollback(); begun = false;
return res.status(404).json({ success: false, message: 'Không tìm thấy thể loại robot' });
}
await new sql.Request(transaction).input('typeId', sql.Int, typeId).input('name', sql.NVarChar(100), fields.name)
.query(`UPDATE dbo.Robots SET Type = @name, UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()) WHERE TypeId = @typeId`);
await transaction.commit(); begun = false;
res.json({ success: true, data: result.recordset[0], message: 'Đã cập nhật thể loại robot' });
} catch (error) {
if (begun) { try { await transaction.rollback(); } catch { /* The driver may have rolled back. */ } }
failType(res, error);
}
});
router.delete('/types/:id', requireManage, async (req, res) => {
try {
const result = await getPool().request().input('typeId', sql.Int, positiveId(req.params.id))
.query('DELETE FROM dbo.RobotTypes OUTPUT DELETED.TypeId WHERE TypeId = @typeId');
if (!result.recordset.length) return res.status(404).json({ success: false, message: 'Không tìm thấy thể loại robot' });
res.json({ success: true, message: 'Đã xóa thể loại robot' });
} catch (error) { failType(res, error); }
});
router.get('/', async (_req, res) => {
try {
const result = await getPool().request().query(`SELECT ${robotColumns} FROM dbo.Robots r
JOIN dbo.RobotTypes t ON t.TypeId = r.TypeId ORDER BY r.CreatedDate DESC, r.RobotId DESC`);
res.json({ success: true, data: result.recordset, maxFileSizeMb: documentMaxMb, avatarMaxFileSizeMb: 5 });
} catch (error) { fail(res, error); }
});
router.get('/:id/avatar', async (req, res) => {
try {
const result = await getPool().request().input('robotId', sql.Int, positiveId(req.params.id))
.query('SELECT AvatarData, AvatarMimeType FROM dbo.Robots WHERE RobotId = @robotId');
const robot = result.recordset[0];
if (!robot?.AvatarData) return res.status(404).json({ success: false, message: 'Robot chưa có ảnh đại diện' });
res.setHeader('Content-Type', robot.AvatarMimeType);
res.setHeader('X-Content-Type-Options', 'nosniff');
res.send(robot.AvatarData);
} catch (error) { fail(res, error); }
});
router.get('/:id', async (req, res) => {
try {
const robotId = positiveId(req.params.id);
const result = await getPool().request().input('robotId', sql.Int, robotId)
.query(`SELECT ${robotColumns} FROM dbo.Robots r JOIN dbo.RobotTypes t ON t.TypeId = r.TypeId WHERE r.RobotId = @robotId`);
if (!result.recordset[0]) return res.status(404).json({ success: false, message: 'Không tìm thấy robot' });
const documents = await getPool().request().input('robotId', sql.Int, robotId).query(`
SELECT d.DocumentId, d.Title, d.OriginalFileName, d.MimeType, d.FileSize, d.UploadedDate
FROM dbo.RobotDocuments rd JOIN dbo.Documents d ON d.DocumentId = rd.DocumentId
WHERE rd.RobotId = @robotId ORDER BY d.Title, d.DocumentId`);
res.json({ success: true, data: { ...result.recordset[0], Documents: documents.recordset } });
} catch (error) { fail(res, error); }
});
async function saveRobot(req, res) {
let transaction;
let begun = false;
try {
req.body ||= {};
const robotId = req.params.id === undefined ? null : positiveId(req.params.id);
const fields = {};
for (const [key, limit] of [['name', 255], ['model', 255]]) {
if (typeof req.body[key] !== 'string' || !req.body[key].trim() || req.body[key].trim().length > limit) {
throw invalid('Vui lòng nhập tên và model robot, tối đa 255 ký tự');
}
fields[key] = req.body[key].trim();
}
const typeId = positiveId(req.body.typeId);
const documentIds = parseDocumentIds(req.body.documentIds);
const avatar = req.files?.avatar?.[0];
const documents = req.files?.documents || [];
if (avatar && (avatar.size > AVATAR_MAX_BYTES || !isAvatarBuffer(avatar.buffer, avatar.mimetype))) {
throw invalid('Ảnh đại diện phải là JPG, PNG hoặc WebP hợp lệ, tối đa 5 MB');
}
for (const file of documents) {
if (file.size > documentMaxBytes) throw invalid(`Tài liệu tối đa ${documentMaxMb} MB mỗi file`);
file.documentFormat = validateDocumentFile(file);
}
if ((documentIds?.length || 0) + documents.length > MAX_LINKED_DOCUMENTS) {
throw invalid(`Chỉ được liên kết tối đa ${MAX_LINKED_DOCUMENTS} tài liệu`);
}
if (req.body.removeAvatar !== undefined && !['true', 'false'].includes(String(req.body.removeAvatar))) {
throw invalid('Yêu cầu xóa ảnh không hợp lệ');
}
transaction = new sql.Transaction(getPool());
await transaction.begin();
begun = true;
const request = () => new sql.Request(transaction);
// Lock the type before the robot, matching the catalog rename lock order.
const selectedType = await request().input('typeId', sql.Int, typeId)
.query('SELECT TypeId, Name FROM dbo.RobotTypes WITH (UPDLOCK, HOLDLOCK) WHERE TypeId = @typeId');
if (!selectedType.recordset.length) throw invalid('Thể loại đã bị xóa hoặc không tồn tại. Vui lòng chọn lại.');
fields.type = selectedType.recordset[0].Name;
if (robotId !== null) {
const existing = await request().input('robotId', sql.Int, robotId)
.query('SELECT RobotId FROM dbo.Robots WITH (UPDLOCK, HOLDLOCK) WHERE RobotId = @robotId');
if (!existing.recordset.length) {
await transaction.rollback(); begun = false;
return res.status(404).json({ success: false, message: 'Không tìm thấy robot' });
}
}
for (const documentId of documentIds || []) {
const existing = await request().input('documentId', sql.Int, documentId).query(`
SELECT DocumentId FROM dbo.Documents WITH (UPDLOCK, HOLDLOCK)
WHERE DocumentId = @documentId`);
if (!existing.recordset.length) throw invalid('Một tài liệu đã bị xóa. Vui lòng chọn lại.');
}
// A partial API update preserves existing links; the form always supplies the full selection.
if (documentIds === undefined && robotId !== null) {
const count = await request().input('robotId', sql.Int, robotId)
.query('SELECT COUNT(*) AS DocumentCount FROM dbo.RobotDocuments WHERE RobotId = @robotId');
if (Number(count.recordset[0].DocumentCount) + documents.length > MAX_LINKED_DOCUMENTS) {
throw invalid(`Chỉ được liên kết tối đa ${MAX_LINKED_DOCUMENTS} tài liệu`);
}
}
const replaceAvatar = Boolean(avatar) || String(req.body.removeAvatar) === 'true';
const write = request().input('name', sql.NVarChar(255), fields.name)
.input('model', sql.NVarChar(255), fields.model).input('type', sql.NVarChar(100), fields.type)
.input('typeId', sql.Int, typeId)
.input('avatarData', sql.VarBinary(sql.MAX), avatar?.buffer || null)
.input('avatarMimeType', sql.NVarChar(100), avatar?.mimetype || null);
let savedId;
if (robotId === null) {
const saved = await write.input('createdBy', sql.Int, req.user.UserId).query(`
INSERT INTO dbo.Robots (Name, Model, Type, TypeId, AvatarData, AvatarMimeType, CreatedBy)
OUTPUT INSERTED.RobotId VALUES (@name, @model, @type, @typeId, @avatarData, @avatarMimeType, @createdBy)`);
savedId = saved.recordset[0].RobotId;
} else {
await write.input('robotId', sql.Int, robotId).input('replaceAvatar', sql.Bit, replaceAvatar).query(`
UPDATE dbo.Robots SET Name = @name, Model = @model, Type = @type, TypeId = @typeId,
AvatarData = CASE WHEN @replaceAvatar = 1 THEN @avatarData ELSE AvatarData END,
AvatarMimeType = CASE WHEN @replaceAvatar = 1 THEN @avatarMimeType ELSE AvatarMimeType END,
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()) WHERE RobotId = @robotId`);
savedId = robotId;
}
if (documentIds !== undefined) {
await request().input('robotId', sql.Int, savedId)
.query('DELETE FROM dbo.RobotDocuments WHERE RobotId = @robotId');
}
const allIds = [...(documentIds || [])];
for (const file of documents) {
const filename = sanitizeDocumentFileName(normalizeUploadedFileName(file.originalname));
const saved = await request().input('title', sql.NVarChar(255), filename.replace(/\.[^.]+$/, '') || 'Tài liệu')
.input('originalFileName', sql.NVarChar(255), filename).input('fileSize', sql.BigInt, file.size)
.input('mimeType', sql.NVarChar(100), file.documentFormat.mimeType)
.input('fileData', sql.VarBinary(sql.MAX), file.buffer).input('uploadedBy', sql.Int, req.user.UserId)
.query(`INSERT INTO dbo.Documents (Title, OriginalFileName, MimeType, FileSize, FileData, UploadedBy)
OUTPUT INSERTED.DocumentId VALUES (@title, @originalFileName, @mimeType, @fileSize, @fileData, @uploadedBy)`);
allIds.push(saved.recordset[0].DocumentId);
}
for (const documentId of allIds) {
await request().input('robotId', sql.Int, savedId).input('documentId', sql.Int, documentId)
.query('INSERT INTO dbo.RobotDocuments (RobotId, DocumentId) VALUES (@robotId, @documentId)');
}
await transaction.commit(); begun = false;
res.status(robotId === null ? 201 : 200).json({ success: true, data: { RobotId: savedId }, message: 'Đã lưu thông tin robot' });
} catch (error) {
if (begun) {
try { await transaction.rollback(); } catch { /* Driver may already have rolled back. */ }
}
fail(res, error);
}
}
router.post('/', requireManage, upload, saveRobot);
router.put('/:id', requireManage, upload, saveRobot);
router.delete('/:id', requireManage, async (req, res) => {
try {
const result = await getPool().request().input('robotId', sql.Int, positiveId(req.params.id))
.query('DELETE FROM dbo.Robots OUTPUT DELETED.RobotId WHERE RobotId = @robotId');
if (!result.recordset.length) return res.status(404).json({ success: false, message: 'Không tìm thấy robot' });
res.json({ success: true, message: 'Đã xóa robot. Tài liệu vẫn được giữ trong kho tài liệu.' });
} catch (error) { fail(res, error); }
});
router.use((error, _req, res, next) => {
if (error instanceof multer.MulterError) {
return res.status(400).json({ success: false, message: error.code === 'LIMIT_FILE_SIZE'
? `Ảnh đại diện tối đa 5 MB; tài liệu tối đa ${documentMaxMb} MB mỗi file`
: `Tối đa 1 ảnh đại diện và ${MAX_DOCUMENT_UPLOADS} tài liệu; vui lòng kiểm tra tệp tải lên` });
}
if (error.status === 400) return fail(res, error);
next(error);
});
return router;
}
module.exports = { ensureRobotSchema, createRobotRouter, parseDocumentIds, isAvatarBuffer };

322
backend/robots.test.js Normal file
View File

@@ -0,0 +1,322 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const express = require('express');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { createRequire } = require('node:module');
const { createRobotRouter, parseDocumentIds } = require('./robots');
const pdf = Buffer.from('%PDF-1.4\nrobot manual\n%%EOF\n');
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aLl8AAAAASUVORK5CYII=', 'base64');
async function fixture(t, { answer, role = 'asset', maxBytes = 1024 * 1024 } = {}) {
const queries = [], transactions = [];
class Request {
constructor(transaction) { this.transaction = transaction; this.inputs = {}; }
input(name, _type, value) { this.inputs[name] = value; return this; }
async query(query) {
const call = { query, inputs: this.inputs, transaction: this.transaction };
queries.push(call);
const result = answer?.(call);
if (result !== undefined) return result;
if (query.includes('SELECT TypeId, Name FROM dbo.RobotTypes')) return { recordset: [{ TypeId: this.inputs.typeId, Name: 'Cộng tác' }] };
if (query.includes('INSERT INTO dbo.Robots')) return { recordset: [{ RobotId: 17 }] };
if (query.includes('INSERT INTO dbo.Documents')) return { recordset: [{ DocumentId: 51 }] };
if (query.includes('SELECT DocumentId FROM dbo.Documents')) return { recordset: [{ DocumentId: this.inputs.documentId }] };
if (query.includes('SELECT RobotId FROM dbo.Robots')) return { recordset: [{ RobotId: 17 }] };
if (query.includes('COUNT(*) AS DocumentCount')) return { recordset: [{ DocumentCount: 2 }] };
return { recordset: [] };
}
}
class Transaction {
constructor() { transactions.push(this); }
async begin() { this.begun = true; }
async commit() { this.committed = true; }
async rollback() { this.rolledBack = true; }
}
const app = express();
app.use(express.json());
app.use((_req, res, next) => {
res.setHeader('Cache-Control', 'no-store'); next();
});
app.use((req, _res, next) => { req.user = { UserId: 1, Role: role }; next(); });
app.use('/api/robots', createRobotRouter({
getPool: () => ({ request: () => new Request() }),
sql: { ...require('mssql'), Request, Transaction },
requireManage(req, res, next) {
if (!['asset', 'admin'].includes(req.user.Role)) return res.status(403).json({ success: false });
next();
},
documentMaxBytes: maxBytes, documentMaxMb: 1,
isPdfBuffer: buffer => buffer.subarray(0, 5).toString() === '%PDF-' && buffer.includes(Buffer.from('%%EOF')),
sanitizeDocumentFileName: name => name.replace(/[\\/\r\n]/g, '_'),
sendInternalError: (res, _error, message) => res.status(500).json({ success: false, message })
}));
const server = app.listen(0, '127.0.0.1');
await new Promise(resolve => server.once('listening', resolve));
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
return { queries, transactions, request: (suffix = '', options) => fetch(`http://127.0.0.1:${server.address().port}/api/robots${suffix}`, options) };
}
function form(extra = {}) {
const body = new FormData();
for (const [key, value] of Object.entries({ name: 'Robot hàn', model: 'CR10', typeId: '1', documentIds: '[3,2,3]', ...extra })) {
if (value !== undefined) body.append(key, value);
}
return body;
}
test('creating a robot saves its avatar, new PDFs and existing links in one transaction', async t => {
const f = await fixture(t);
const body = form();
body.append('avatar', new Blob([png], { type: 'image/png' }), 'robot.png');
body.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'manual.pdf');
const response = await f.request('', { method: 'POST', body });
assert.equal(response.status, 201);
assert.equal((await response.json()).data.RobotId, 17);
assert.equal(f.transactions[0].committed, true);
assert.ok(f.queries.every(query => query.transaction === f.transactions[0]));
const robot = f.queries.find(q => q.query.includes('INSERT INTO dbo.Robots'));
assert.equal(robot.inputs.name, 'Robot hàn');
assert.equal(robot.inputs.typeId, 1);
assert.equal(robot.inputs.type, 'Cộng tác');
assert.deepEqual(robot.inputs.avatarData, png);
const links = f.queries.filter(q => q.query.includes('INSERT INTO dbo.RobotDocuments'));
assert.deepEqual(links.map(q => q.inputs.documentId), [2, 3, 51]);
assert.equal(f.queries.filter(q => q.query.includes('INSERT INTO dbo.Documents')).length, 1);
});
test('a PDF storage failure rolls back robot metadata and every link', async t => {
const f = await fixture(t, { answer({ query }) {
if (query.includes('INSERT INTO dbo.Documents')) throw new Error('Storage failed');
} });
const body = form(); body.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'manual.pdf');
assert.equal((await f.request('', { method: 'POST', body })).status, 500);
assert.equal(f.transactions[0].rolledBack, true);
assert.equal(f.transactions[0].committed, undefined);
assert.equal(f.queries.some(q => q.query.includes('INSERT INTO dbo.RobotDocuments')), false);
});
test('a missing library PDF rejects the whole save before inserting a robot', async t => {
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT DocumentId FROM dbo.Documents') ? { recordset: [] } : undefined });
assert.equal((await f.request('', { method: 'POST', body: form() })).status, 400);
assert.equal(f.transactions[0].rolledBack, true);
assert.equal(f.queries.some(q => q.query.includes('INSERT')), false);
});
test('editing replaces selected links while retaining the avatar unless requested', async t => {
const f = await fixture(t);
assert.equal((await f.request('/17', { method: 'PUT', body: form({ documentIds: '[8]' }) })).status, 200);
const update = f.queries.find(q => q.query.includes('UPDATE dbo.Robots'));
assert.equal(update.inputs.replaceAvatar, false);
assert.match(update.query, /ELSE AvatarData END/);
assert.ok(f.queries.some(q => q.query.includes('DELETE FROM dbo.RobotDocuments')));
assert.deepEqual(f.queries.filter(q => q.query.includes('INSERT INTO dbo.RobotDocuments')).map(q => q.inputs.documentId), [8]);
assert.equal(f.queries.some(q => q.query.includes('DELETE FROM dbo.Documents')), false);
});
test('partial edits preserve document links and can explicitly remove the avatar', async t => {
const f = await fixture(t);
assert.equal((await f.request('/17', { method: 'PUT', body: form({ documentIds: undefined, removeAvatar: 'true' }) })).status, 200);
const update = f.queries.find(q => q.query.includes('UPDATE dbo.Robots'));
assert.equal(update.inputs.replaceAvatar, true);
assert.equal(update.inputs.avatarData, null);
assert.equal(f.queries.some(q => q.query.includes('DELETE FROM dbo.RobotDocuments')), false);
});
test('forged image/PDF contents and oversized avatars are rejected before database access', async t => {
const f = await fixture(t);
for (const [field, type, name, bytes] of [
['avatar', 'image/png', 'bad.png', Buffer.from('not an image')],
['documents', 'application/pdf', 'bad.pdf', Buffer.from('not a PDF')],
['avatar', 'image/png', 'large.png', Buffer.alloc(5 * 1024 * 1024 + 1)]
]) {
const body = form(); body.append(field, new Blob([bytes], { type }), name);
assert.equal((await f.request('', { method: 'POST', body })).status, 400);
}
assert.equal(f.queries.length, 0);
assert.equal(f.transactions.length, 0);
});
test('PDF size configuration, image extensions and upload counts are enforced', async t => {
const f = await fixture(t, { maxBytes: 20 });
const oversizedPdf = form(); oversizedPdf.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'manual.pdf');
const svg = form(); svg.append('avatar', new Blob(['<svg/>'], { type: 'image/svg+xml' }), 'image.svg');
const many = form();
for (let i = 0; i < 11; i++) many.append('documents', new Blob([pdf], { type: 'application/pdf' }), `${i}.pdf`);
for (const body of [oversizedPdf, svg, many]) assert.equal((await f.request('', { method: 'POST', body })).status, 400);
assert.equal(f.transactions.length, 0);
});
test('invalid metadata and document IDs return useful errors without writes', async t => {
const f = await fixture(t);
for (const extra of [{ name: ' ' }, { model: '' }, { typeId: undefined }, { typeId: '0' }, { typeId: '2147483648' }, { documentIds: 'invalid' },
{ documentIds: '[0]' }, { documentIds: '["3 OR 1=1"]' }, { documentIds: '[2147483648]' }]) {
assert.equal((await f.request('', { method: 'POST', body: form(extra) })).status, 400);
}
assert.equal((await f.request('', { method: 'POST' })).status, 400);
assert.equal((await f.request('/17x', { method: 'PUT', body: form() })).status, 400);
assert.equal(f.transactions.length, 0);
assert.throws(() => parseDocumentIds(Array.from({ length: 101 }, (_, i) => i + 1)));
});
test('missing robots cannot be edited or silently recreated', async t => {
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT RobotId FROM dbo.Robots') ? { recordset: [] } : undefined });
assert.equal((await f.request('/17', { method: 'PUT', body: form() })).status, 404);
assert.equal(f.transactions[0].rolledBack, true);
assert.equal(f.queries.some(q => q.query.includes('UPDATE') && !q.query.includes('UPDLOCK')), false);
});
test('ordinary users can read robot data but cannot add, update or delete robots', async t => {
const f = await fixture(t, { role: 'user' });
assert.equal((await f.request()).status, 200);
for (const [method, suffix] of [['POST', ''], ['PUT', '/17'], ['DELETE', '/17']]) {
assert.equal((await f.request(suffix, { method, ...(method === 'DELETE' ? {} : { body: form() }) })).status, 403);
}
assert.equal(f.transactions.length, 0);
assert.equal(f.queries.length, 1);
});
test('avatar endpoints return the stored bytes and safe content type', async t => {
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT AvatarData') ? { recordset: [{ AvatarData: png, AvatarMimeType: 'image/png' }] } : undefined });
const response = await f.request('/17/avatar');
assert.equal(response.status, 200);
assert.equal(response.headers.get('content-type'), 'image/png');
assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
assert.equal(response.headers.get('cache-control'), 'no-store');
assert.deepEqual(Buffer.from(await response.arrayBuffer()), png);
});
test('deleting a robot never deletes shared PDF documents', async t => {
const f = await fixture(t, { answer: ({ query }) => query.startsWith('DELETE FROM dbo.Robots') ? { recordset: [{ RobotId: 17 }] } : undefined });
assert.equal((await f.request('/17', { method: 'DELETE' })).status, 200);
assert.equal(f.queries.length, 1);
assert.match(f.queries[0].query, /^DELETE FROM dbo.Robots/);
assert.doesNotMatch(f.queries[0].query, /DELETE FROM (?:dbo\.)?Documents/);
});
test('robot cards escape user content, search name/model/type, and hide edit actions for viewers', () => {
const source = fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8');
const context = vm.createContext({ document: { addEventListener() {} }, window: { fetch() {} }, console });
vm.runInContext(`${source}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context);
const manager = context.manager;
Object.assign(manager, { robots: [{ RobotId: 17, Name: '<script>Robot</script>', Model: 'CR10', TypeId: 1, Type: 'Cộng tác', DocumentCount: 2 }],
robotTypes: [{ TypeId: 1, Name: 'Cộng tác', RobotCount: 1 }],
apiBase: '/api', currentUser: { Role: 'user' }, robotPage: 1, robotPageSize: 12, robotSearchTerm: '', robotTypeFilter: '',
robotLoadError: '', escapeHtml: value => String(value ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;') });
let html = manager.getRobotsContent();
assert.match(html, /&lt;script&gt;Robot/);
assert.doesNotMatch(html, /<script>Robot/);
assert.match(html, /2 tài liệu/);
assert.doesNotMatch(html, /data-robot-action="edit"|data-robot-action="delete"|id="addRobotBtn"/);
manager.currentUser.Role = 'admin';
assert.match(manager.getRobotsContent(), /data-robot-action="edit"/);
for (const keyword of ['robot', 'cr10', 'cộng tác']) {
manager.robotSearchTerm = keyword; assert.equal(manager.getFilteredRobots().length, 1);
}
manager.robotTypeFilter = 'AMR'; assert.equal(manager.getFilteredRobots().length, 0);
manager.robotTypeFilter = '1'; assert.equal(manager.getFilteredRobots().length, 1);
manager.robotSearchTerm = ''; manager.robotTypeFilter = ''; manager.robotLoadError = 'Server unavailable';
html = manager.getRobotsContent(); assert.match(html, /role="alert"/); assert.match(html, /Server unavailable/);
});
function serverWithPool(pool) {
const serverPath = path.join(__dirname, 'server.js');
const serverRequire = createRequire(serverPath);
const sandbox = {
require: name => name === 'dotenv' ? { config() {} } : serverRequire(name),
module: { exports: {} }, __dirname, __filename: serverPath, Buffer, URL, console,
process: { env: { NODE_ENV: 'test', DATA_ENCRYPTION_SECRET: 'robot-tests-only-key-with-more-than-32-characters' }, on() {} },
robotTestPool: pool
};
vm.runInNewContext(`${fs.readFileSync(serverPath, 'utf8')}\npool = robotTestPool;`, sandbox, { filename: serverPath });
return sandbox.module.exports.app;
}
test('all robot endpoints require an authenticated session in the production application', async t => {
const app = serverWithPool(null);
const server = app.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
const base = `http://127.0.0.1:${server.address().port}/api/robots`;
for (const [method, suffix] of [['GET', ''], ['GET', '/17'], ['GET', '/17/avatar'], ['POST', ''], ['PUT', '/17'], ['DELETE', '/17'],
['GET', '/types'], ['POST', '/types'], ['PUT', '/types/1'], ['DELETE', '/types/1']]) {
const response = await fetch(`${base}${suffix}`, { method, headers: { 'X-User-Id': '1', 'X-User-Role': 'admin' } });
assert.equal(response.status, 401);
}
});
test('a deleted or unknown robot type rejects the save before inserting robot data', async t => {
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT TypeId, Name FROM dbo.RobotTypes') ? { recordset: [] } : undefined });
assert.equal((await f.request('', { method: 'POST', body: form() })).status, 400);
assert.equal(f.transactions[0].rolledBack, true);
assert.equal(f.queries.some(q => q.query.includes('INSERT')), false);
});
test('viewers can read the type catalog but cannot create, rename or delete types', async t => {
const f = await fixture(t, { role: 'user' });
assert.equal((await f.request('/types')).status, 200);
for (const [method, suffix] of [['POST', '/types'], ['PUT', '/types/1'], ['DELETE', '/types/1']]) {
assert.equal((await f.request(suffix, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'AMR' }) })).status, 403);
}
assert.equal(f.queries.length, 1);
assert.equal(f.transactions.length, 0);
});
test('type input is validated and duplicate type names return a conflict', async t => {
const f = await fixture(t, { answer({ query }) {
if (query.includes('INSERT INTO dbo.RobotTypes')) throw Object.assign(new Error('duplicate'), { number: 2627 });
} });
for (const body of [{ name: '' }, { name: ' ' }, { name: 'a'.repeat(101) }, { name: [] }, { name: 'AMR', description: 'a'.repeat(501) }]) {
assert.equal((await f.request('/types', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })).status, 400);
}
assert.equal(f.queries.length, 0);
assert.equal((await f.request('/types', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'AMR' }) })).status, 409);
});
test('renaming a type updates the catalog and robot display values atomically', async t => {
const f = await fixture(t, { answer: ({ query }) => query.includes('UPDATE dbo.RobotTypes') ? { recordset: [{ TypeId: 1, Name: 'Cộng tác mới' }] } : undefined });
const response = await f.request('/types/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Cộng tác mới', description: 'New description' }) });
assert.equal(response.status, 200);
assert.equal(f.transactions[0].committed, true);
assert.ok(f.queries.every(call => call.transaction === f.transactions[0]));
assert.ok(f.queries.some(call => call.query.includes('UPDATE dbo.Robots SET Type = @name') && call.inputs.name === 'Cộng tác mới'));
});
test('rename failures roll back; used types cannot be deleted, and missing types return 404', async t => {
const failed = await fixture(t, { answer({ query }) {
if (query.includes('UPDATE dbo.RobotTypes')) return { recordset: [{ TypeId: 1 }] };
if (query.includes('UPDATE dbo.Robots')) throw new Error('Storage failure');
} });
assert.equal((await failed.request('/types/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Rename' }) })).status, 500);
assert.equal(failed.transactions[0].rolledBack, true);
for (const mode of ['used', 'missing', 'unused']) {
const f = await fixture(t, { answer({ query }) {
if (query.includes('DELETE FROM dbo.RobotTypes')) {
if (mode === 'used') throw Object.assign(new Error('FK conflict'), { number: 547 });
return { recordset: mode === 'unused' ? [{ TypeId: 1 }] : [] };
}
} });
assert.equal((await f.request('/types/1', { method: 'DELETE' })).status, mode === 'used' ? 409 : mode === 'missing' ? 404 : 200);
}
});
test('document deletion blocks robot links and concurrent foreign-key conflicts while retaining owner permissions', async () => {
for (const mode of ['linked', 'unlinked', 'concurrent', 'other-owner']) {
let calls = 0;
const app = serverWithPool({ request() {
return { input() { return this; }, async query(query) {
calls++;
if (query.startsWith('SELECT')) return { recordset: [{ DocumentId: 3, UploadedBy: mode === 'other-owner' ? 2 : 1 }] };
assert.match(query, /NOT EXISTS \(SELECT 1 FROM dbo.RobotDocuments/);
if (mode === 'concurrent') throw Object.assign(new Error('FK conflict'), { number: 547 });
return { recordset: mode === 'unlinked' ? [{ DocumentId: 3 }] : [] };
} };
} });
const route = app.router.stack.find(layer => layer.route?.path === '/api/documents/:id' && layer.route.methods.delete).route;
const response = { statusCode: 200, status(code) { this.statusCode = code; return this; }, json(body) { this.body = body; return this; } };
await route.stack.at(-1).handle({ params: { id: '3' }, user: { UserId: 1, Role: 'user' } }, response);
assert.equal(response.statusCode, mode === 'other-owner' ? 403 : mode === 'unlinked' ? 200 : 409);
assert.equal(calls, mode === 'other-owner' ? 1 : 2);
}
});

18
backend/run-tests.js Normal file
View File

@@ -0,0 +1,18 @@
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
// Restrict discovery to source tests. Browser profiles in tmp/ can contain
// third-party extension *.test.js files and must never enter the project suite.
function discover(directory) {
if (!fs.existsSync(directory)) return [];
return fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
const target = path.join(directory, entry.name);
if (entry.isDirectory() && entry.name !== 'node_modules') return discover(target);
return entry.isFile() && /\.test\.[cm]?js$/.test(entry.name) ? [target] : [];
});
}
const files = [__dirname, path.resolve(__dirname, '../test')].flatMap(discover);
const result = spawnSync(process.execPath, ['--test', ...process.argv.slice(2), ...files], { stdio: 'inherit' });
if (result.error) console.error(result.error.message);
process.exitCode = result.status ?? 1;

View File

@@ -13,6 +13,15 @@ const dotenv = require('dotenv');
const helmet = require('helmet');
const { rateLimit } = require('express-rate-limit');
const { ensureAssetArchiveSchema } = require('./asset-archive-schema');
const { parseAllocations, addProjectExports, releaseAllocations } = require('./asset-project-allocations');
const { buildExportRequestWorkbook } = require('./export-request-workbook');
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
const { ensureAssetExportRequestSchema, createAssetExportWorkflow } = require('./asset-export-requests');
const { ensureRobotSchema, createRobotRouter } = require('./robots');
const { ensureRobotBomSchema, createRobotBomRouter } = require('./robot-bom');
const { createAnnouncementRouter } = require('./announcements');
const { getDocumentFormat, isPdfBuffer, validateDocumentFile, normalizeUploadedFileName,
sanitizeDocumentFileName, getDocumentContentDisposition, accept: documentAccept } = require('./document-files');
dotenv.config();
@@ -2288,47 +2297,13 @@ const documentUpload = multer({
parts: 7
},
fileFilter(req, file, callback) {
const extension = require('path').extname(String(file.originalname || '')).toLowerCase();
const mimeType = String(file.mimetype || '').toLowerCase();
if (extension !== '.pdf' || mimeType !== 'application/pdf') {
return callback(new Error('Chỉ chấp nhận file PDF'));
if (!getDocumentFormat(file.originalname)) {
return callback(Object.assign(new Error('Định dạng tài liệu chưa được hỗ trợ'), { code: 'DOCUMENT_VALIDATION' }));
}
callback(null, true);
}
});
function isPdfBuffer(value) {
if (!Buffer.isBuffer(value) || value.length < 10 || value.subarray(0, 5).toString('ascii') !== '%PDF-') {
return false;
}
const trailerStart = Math.max(0, value.length - 2048);
return value.subarray(trailerStart).includes(Buffer.from('%%EOF', 'ascii'));
}
function sanitizeDocumentFileName(value) {
const cleaned = String(value || 'document.pdf')
.replace(/[\u0000-\u001f\u007f]/g, '')
.replace(/[\\/:*?"<>|]/g, '_')
.trim()
.slice(0, 255);
const baseName = cleaned || 'document.pdf';
return baseName.toLowerCase().endsWith('.pdf')
? baseName
: `${baseName.slice(0, 251)}.pdf`;
}
function getDocumentContentDisposition(fileName, download = false) {
const safeFileName = sanitizeDocumentFileName(fileName);
const asciiFileName = safeFileName
.normalize('NFKD')
.replace(/[^\x20-\x7e]/g, '')
.replace(/["\\]/g, '_')
.trim() || 'document.pdf';
const encodedFileName = encodeURIComponent(safeFileName)
.replace(/['()*]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
return `${download ? 'attachment' : 'inline'}; filename="${asciiFileName}"; filename*=UTF-8''${encodedFileName}`;
}
// Serve static files from /public
const path = require('path');
const publicDir = path.join(__dirname, '..', 'public');
@@ -3098,6 +3073,18 @@ async function createTables() {
)
END`,
`IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'NotificationPopupDismissals')
BEGIN
CREATE TABLE NotificationPopupDismissals (
NotificationId BIGINT NOT NULL,
UserId INT NOT NULL,
DismissedAt DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
PRIMARY KEY (NotificationId, UserId),
FOREIGN KEY (NotificationId) REFERENCES Notifications(NotificationId) ON DELETE CASCADE,
FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE
)
END`,
// AuditLog Table
`IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AuditLog')
BEGIN
@@ -3125,6 +3112,14 @@ async function createTables() {
// Fail startup if history preservation cannot be installed.
await ensureAssetArchiveSchema(pool);
await ensureAssetExportDocumentSchema(pool);
await ensureAssetExportRequestSchema(pool);
await ensureRobotSchema(pool);
await ensureRobotBomSchema(pool);
await pool.request().query(`
IF COL_LENGTH('dbo.AssetInventory', 'ProjectAllocations') IS NULL
ALTER TABLE dbo.AssetInventory ADD ProjectAllocations NVARCHAR(MAX) NULL;
`);
// Ensure notification indexes exist for audience lookup and unread counts.
try {
@@ -3614,8 +3609,8 @@ async function createTables() {
try {
const initialAdminPassword = String(process.env.INITIAL_ADMIN_PASSWORD || '');
if (initialAdminPassword) {
if (initialAdminPassword.length < 12) {
throw new Error('INITIAL_ADMIN_PASSWORD must contain at least 12 characters');
if (initialAdminPassword.length < 6) {
throw new Error('INITIAL_ADMIN_PASSWORD must contain at least 6 characters');
}
const result = await pool.request()
@@ -3779,8 +3774,8 @@ app.post('/api/auth/register', accountRecoveryRateLimit, async (req, res) => {
if (!/^[A-Za-z0-9._-]{3,50}$/.test(safeUsername)) {
return res.status(400).json({ success: false, message: 'Username must be 3-50 characters and contain only letters, numbers, dot, underscore or hyphen' });
}
if (safePassword.length < 12 || safePassword.length > 256) {
return res.status(400).json({ success: false, message: 'Password must be between 12 and 256 characters' });
if (safePassword.length < 6 || safePassword.length > 256) {
return res.status(400).json({ success: false, message: 'Password must be between 6 and 256 characters' });
}
const isEmailFormatValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalizedEmail);
if (!isEmailFormatValid) {
@@ -4115,8 +4110,8 @@ app.post('/api/auth/reset-password', accountRecoveryRateLimit, async (req, res)
return res.status(400).json({ success: false, message: 'Reset token and new password are required' });
}
if (newPassword.length < 12 || newPassword.length > 256) {
return res.status(400).json({ success: false, message: 'New password must be between 12 and 256 characters' });
if (newPassword.length < 6 || newPassword.length > 256) {
return res.status(400).json({ success: false, message: 'New password must be between 6 and 256 characters' });
}
const tokenHash = hashVerificationToken(token);
@@ -4293,6 +4288,11 @@ async function safeCreateSystemNotification(payload) {
// API ROUTES - Notifications
// ==========================================
app.use('/api/notifications', createAnnouncementRouter({
getPool: () => pool, sql, requireManage: requireAssetOrAdmin,
getUserId: getUserIdFromRequest, getRole: getRequesterRole, sendInternalError
}));
app.get('/api/notifications', async (req, res) => {
try {
const userId = getUserIdFromRequest(req);
@@ -4380,7 +4380,7 @@ app.get('/api/notifications', async (req, res) => {
}
});
app.post('/api/notifications', requireAdmin, async (req, res) => {
app.post('/api/notifications', requireAssetOrAdmin, async (req, res) => {
try {
const title = String(req.body?.title || '').trim();
const message = String(req.body?.message || '').trim();
@@ -4399,7 +4399,7 @@ app.post('/api/notifications', requireAdmin, async (req, res) => {
if (rawActionUrl && !actionUrl) {
return res.status(400).json({ success: false, message: 'Liên kết chỉ được dùng đường dẫn nội bộ bắt đầu bằng / hoặc #' });
}
if (expiresAt && (Number.isNaN(expiresAt.getTime()) || expiresAt.getTime() <= Date.now())) {
if (!expiresAt || Number.isNaN(expiresAt.getTime()) || expiresAt.getTime() <= Date.now()) {
return res.status(400).json({ success: false, message: 'Thời gian hết hạn phải ở tương lai' });
}
@@ -4510,7 +4510,7 @@ app.put('/api/notifications/:id/read', async (req, res) => {
}
});
app.delete('/api/notifications/:id', requireAdmin, async (req, res) => {
app.delete('/api/notifications/:id', requireAssetOrAdmin, async (req, res) => {
try {
const notificationId = Number(req.params.id);
if (!Number.isInteger(notificationId) || notificationId <= 0) {
@@ -4519,10 +4519,13 @@ app.delete('/api/notifications/:id', requireAdmin, async (req, res) => {
const result = await pool.request()
.input('notificationId', sql.BigInt, notificationId)
.input('userId', sql.Int, getUserIdFromRequest(req))
.input('isAdmin', sql.Bit, getRequesterRole(req) === 'admin')
.query(`
UPDATE Notifications
SET IsActive = 0
WHERE NotificationId = @notificationId AND Source = 'admin' AND IsActive = 1;
WHERE NotificationId = @notificationId AND Source = 'admin' AND IsActive = 1
AND (@isAdmin = 1 OR CreatedBy = @userId);
SELECT @@ROWCOUNT AS Affected;
`);
@@ -4719,8 +4722,8 @@ app.put('/api/users/me', async (req, res) => {
const emailChanged = String(existingUser.Email || '').toLowerCase() !== incomingEmail;
const shouldChangePassword = newPassword.length > 0;
if (shouldChangePassword && (newPassword.length < 12 || newPassword.length > 256)) {
return res.status(400).json({ success: false, message: 'New password must be between 12 and 256 characters' });
if (shouldChangePassword && (newPassword.length < 6 || newPassword.length > 256)) {
return res.status(400).json({ success: false, message: 'New password must be between 6 and 256 characters' });
}
if (shouldChangePassword || emailChanged) {
@@ -4856,8 +4859,8 @@ app.post('/api/users', requireAdmin, async (req, res) => {
if (!/^[A-Za-z0-9._-]{3,50}$/.test(String(username).trim())) {
return res.status(400).json({ success: false, message: 'Username format is invalid' });
}
if (String(password).length < 12 || String(password).length > 256) {
return res.status(400).json({ success: false, message: 'Password must be between 12 and 256 characters' });
if (String(password).length < 6 || String(password).length > 256) {
return res.status(400).json({ success: false, message: 'Password must be between 6 and 256 characters' });
}
const hashedPassword = await hashPassword(password);
@@ -4904,8 +4907,8 @@ app.put('/api/users/:id', requireAdmin, async (req, res) => {
const { email, fullname, roleId, status, isActive, password } = req.body;
const nextPassword = typeof password === 'string' ? password.trim() : '';
const shouldUpdatePassword = nextPassword.length > 0;
if (shouldUpdatePassword && (nextPassword.length < 12 || nextPassword.length > 256)) {
return res.status(400).json({ success: false, message: 'Password must be between 12 and 256 characters' });
if (shouldUpdatePassword && (nextPassword.length < 6 || nextPassword.length > 256)) {
return res.status(400).json({ success: false, message: 'Password must be between 6 and 256 characters' });
}
// Get role name from Roles table
@@ -6510,6 +6513,7 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
ai.UsedQuantity,
ai.Status,
ai.Borrower,
ai.ProjectAllocations,
ai.Unit AS AssetUnit
FROM AssetBorrowRequests br WITH (UPDLOCK, HOLDLOCK)
INNER JOIN AssetInventory ai WITH (UPDLOCK, HOLDLOCK) ON ai.AssetId = br.AssetId
@@ -6549,7 +6553,9 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
0
);
const baseEndingBalance = parseOptionalNonNegativeInteger(targetRequest.EndingBalance);
const endingBalance = baseEndingBalance !== null ? baseEndingBalance : derivedEndingBalance;
const currentExport = Math.max(currentBorrowed, parseNonNegativeInteger(targetRequest.ExportInPeriod, 0));
const availableFromTotal = Math.max(parseNonNegativeInteger(targetRequest.Quantity, 0) + parseNonNegativeInteger(targetRequest.ImportInPeriod, 0) - currentExport, 0);
const endingBalance = Math.min(baseEndingBalance ?? derivedEndingBalance, availableFromTotal);
const baseNewQuantity = parseOptionalNonNegativeInteger(targetRequest.NewQuantity);
const baseUsedQuantity = parseOptionalNonNegativeInteger(targetRequest.UsedQuantity);
const stockBuckets = normalizeAssetStockBuckets(
@@ -6585,7 +6591,7 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
const nextEndingBalance = Math.max(endingBalance - requestQuantity, 0);
const nextNewQuantity = Math.max(stockBuckets.newQuantity - borrowFromNew, 0);
const nextUsedQuantity = Math.max(stockBuckets.usedQuantity - borrowFromUsed, 0);
const nextBorrowingQuantity = currentBorrowed + requestQuantity;
const nextBorrowingQuantity = currentExport + requestQuantity;
const nextStatus = resolveAssetStatusFromStock(nextEndingBalance, nextBorrowingQuantity);
await new sql.Request(transaction)
@@ -6624,10 +6630,16 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
});
}
const borrowerOutstanding = parseBorrowerEntries(targetRequest.Borrower)
.filter(row => row.name.toLowerCase() === borrowerName.toLowerCase())
.reduce((sum, row) => sum + row.quantity, 0);
const projectAllocations = releaseAllocations(targetRequest.ProjectAllocations, borrowerName, requestQuantity, borrowerOutstanding);
const borrowerSummary = decreased.summary || null;
const remainingBorrowed = decreased.entries.reduce((sum, entry) => (
sum + parseNonNegativeInteger(entry?.quantity, 0)
), 0);
const remainingBorrowed = Math.max(
decreased.entries.reduce((sum, entry) => sum + parseNonNegativeInteger(entry?.quantity, 0), 0),
parseNonNegativeInteger(targetRequest.ExportInPeriod, 0) - requestQuantity,
projectAllocations.reduce((sum, row) => sum + row.quantity, 0)
);
const quantity = parseNonNegativeInteger(targetRequest.Quantity, 0);
const importInPeriod = parseNonNegativeInteger(targetRequest.ImportInPeriod, 0);
const derivedEndingBalance = Math.max(quantity + importInPeriod - parseNonNegativeInteger(targetRequest.ExportInPeriod, 0), 0);
@@ -6650,6 +6662,7 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
await new sql.Request(transaction)
.input('assetId', sql.Int, targetRequest.AssetId)
.input('borrower', sql.NVarChar, borrowerSummary)
.input('projectAllocations', sql.NVarChar(sql.MAX), JSON.stringify(projectAllocations))
.input('exportInPeriod', sql.Int, remainingBorrowed)
.input('endingBalance', sql.Int, nextEndingBalance)
.input('newQuantity', sql.Int, nextBuckets.newQuantity)
@@ -6659,6 +6672,7 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
.query(`
UPDATE AssetInventory
SET Borrower = @borrower,
ProjectAllocations = @projectAllocations,
ExportInPeriod = @exportInPeriod,
EndingBalance = @endingBalance,
NewQuantity = @newQuantity,
@@ -8098,6 +8112,7 @@ app.post('/api/consumables/:id/export', requireAssetOrAdmin, async (req, res) =>
ConsumableId,
ConsumableCode,
ConsumableName,
Model,
Unit,
OpeningBalance,
ImportInPeriod,
@@ -8137,6 +8152,15 @@ app.post('/api/consumables/:id/export', requireAssetOrAdmin, async (req, res) =>
const nextExportInPeriod = previousExportInPeriod + exportQuantity;
const nextEndingBalance = Math.max(previousEndingBalance - exportQuantity, 0);
const document = await buildExportRequestWorkbook({
kind: 'consumable', item: consumable,
rows: [{ projectName: targetType === 'project' ? projectName : '', quantity: exportQuantity }],
availableStock: previousEndingBalance,
requesterName: targetType === 'user' ? recipientName : exportedByName,
recipientName: targetType === 'user' ? recipientName : '',
exportedByName, note: exportNote, exportedDate
});
await new sql.Request(transaction)
.input('consumableId', sql.Int, consumableId)
.input('exportInPeriod', sql.Int, nextExportInPeriod)
@@ -8230,7 +8254,8 @@ app.post('/api/consumables/:id/export', requireAssetOrAdmin, async (req, res) =>
res.json({
success: true,
message: 'Xuat vat tu tieu hao thanh cong',
data: historyResult.recordset?.[0] || null
data: historyResult.recordset?.[0] || null,
document
});
} catch (err) {
if (transaction) {
@@ -8435,7 +8460,7 @@ app.get('/api/assets', async (req, res) => {
SELECT AssetId, IsArchived, ArchivedDate, AssetCode, AssetName, Model, SerialNumber,
Quantity, ImportInPeriod, ExportInPeriod, EndingBalance,
NewQuantity, UsedQuantity,
Unit, Department, Project, Location, Custodian, Borrower, ExportedBy,
Unit, Department, Project, ProjectAllocations, Location, Custodian, Borrower, ExportedBy,
PurchaseDate, PurchasePrice,
CASE
WHEN ISNULL(EndingBalance, 0) <= 0 THEN 'exported'
@@ -8544,7 +8569,7 @@ app.get('/api/assets/:id', async (req, res) => {
SELECT AssetId, AssetCode, AssetName, Model, SerialNumber,
Quantity, ImportInPeriod, ExportInPeriod, EndingBalance,
NewQuantity, UsedQuantity,
Unit, Department, Project, Location, Custodian, Borrower, ExportedBy,
Unit, Department, Project, ProjectAllocations, Location, Custodian, Borrower, ExportedBy,
PurchaseDate, PurchasePrice,
CASE
WHEN ISNULL(EndingBalance, 0) <= 0 THEN 'exported'
@@ -8566,28 +8591,22 @@ app.get('/api/assets/:id', async (req, res) => {
}
});
app.get('/api/asset-export-history', requireAssetOrAdmin, async (req, res) => {
app.get('/api/asset-export-history', async (req, res) => {
try {
const limit = Math.min(parsePositiveInteger(req.query.limit, 300), 2000);
const result = await pool.request()
.input('limit', sql.Int, limit)
.input('requesterId', sql.Int, getUserIdFromRequest(req) || -1)
.query(`
SELECT TOP (@limit)
ExportHistoryId,
AssetId,
AssetCode,
AssetName,
ExportQuantity,
ProjectName,
CustodianName,
ExportedByName,
ExportNote,
CreatedBy,
ExportedDate,
CreatedDate,
UpdatedDate
FROM AssetExportHistory
ORDER BY ExportedDate DESC, ExportHistoryId DESC
h.ExportHistoryId, h.AssetId, h.AssetCode, h.AssetName,
h.ExportQuantity, h.ProjectName, h.CustodianName, h.ExportedByName,
h.ExportNote, h.CreatedBy, h.ExportedDate, h.CreatedDate, h.UpdatedDate,
h.ExportDocumentId, d.FileName AS DocumentFileName
FROM AssetExportHistory h
LEFT JOIN AssetExportDocuments d ON d.ExportDocumentId = h.ExportDocumentId
${['admin', 'asset'].includes(getRequesterRole(req)) ? '' : 'WHERE h.CreatedBy = @requesterId'}
ORDER BY h.ExportedDate DESC, h.ExportHistoryId DESC
`);
res.json({
@@ -8599,6 +8618,41 @@ app.get('/api/asset-export-history', requireAssetOrAdmin, async (req, res) => {
}
});
function isExportDocumentId(value) {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(String(value || ''));
}
app.get('/api/asset-export-documents/:id', async (req, res) => {
if (!isExportDocumentId(req.params.id)) return res.status(400).json({ success: false, message: 'Mã phiếu không hợp lệ.' });
try {
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id)
.input('requesterId', sql.Int, getUserIdFromRequest(req) || -1).query(`
SELECT ExportDocumentId, FileName, SnapshotJson FROM AssetExportDocuments WHERE ExportDocumentId = @documentId
${['admin', 'asset'].includes(getRequesterRole(req)) ? '' : 'AND CreatedBy = @requesterId'}
`);
const document = result.recordset?.[0];
if (!document) return res.status(404).json({ success: false, message: 'Không tìm thấy phiếu xuất đã lưu.' });
res.setHeader('Cache-Control', 'private, no-store');
res.json({ success: true, data: { documentId: document.ExportDocumentId, fileName: document.FileName,
snapshot: JSON.parse(document.SnapshotJson) } });
} catch (err) { sendInternalError(res, err); }
});
app.get('/api/asset-export-documents/:id/download', async (req, res) => {
if (!isExportDocumentId(req.params.id)) return res.status(400).json({ success: false, message: 'Mã phiếu không hợp lệ.' });
try {
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id)
.input('requesterId', sql.Int, getUserIdFromRequest(req) || -1).query(`
SELECT FileName, MimeType, FileContent FROM AssetExportDocuments WHERE ExportDocumentId = @documentId
${['admin', 'asset'].includes(getRequesterRole(req)) ? '' : 'AND CreatedBy = @requesterId'}
`);
const document = result.recordset?.[0];
if (!document) return res.status(404).json({ success: false, message: 'Không tìm thấy file Excel đã lưu.' });
res.setHeader('Cache-Control', 'private, no-store');
res.type(document.MimeType).attachment(document.FileName).send(Buffer.from(document.FileContent));
} catch (err) { sendInternalError(res, err); }
});
app.get('/api/asset-damage-disposal-history', requireAssetOrAdmin, async (req, res) => {
try {
const limit = Math.min(parsePositiveInteger(req.query.limit, 300), 2000);
@@ -8885,209 +8939,121 @@ app.post('/api/assets/:id/damage-disposal', requireAssetOrAdmin, async (req, res
}
});
app.post('/api/assets/:id/export', requireAssetOrAdmin, async (req, res) => {
let transaction;
try {
const assetId = Number(req.params.id);
const exportQuantity = parseNonNegativeInteger(req.body?.quantity, 0);
const borrowerName = String(req.body?.borrowerName || req.body?.custodianName || '').trim();
const projectName = String(req.body?.projectName || '').trim() || null;
const exportNote = String(req.body?.note || '').trim() || null;
const createdBy = getUserIdFromRequest(req);
const exportedByName = await getUserDisplayNameById(createdBy) || req.user?.FullName || req.user?.Username || 'Unknown';
const exportedDate = new Date();
if (!Number.isInteger(assetId) || assetId <= 0) {
return res.status(400).json({ success: false, message: 'Asset id is invalid' });
}
if (exportQuantity <= 0) {
return res.status(400).json({ success: false, message: 'So luong xuat phai lon hon 0' });
}
if (!borrowerName) {
return res.status(400).json({ success: false, message: 'Nguoi muon la bat buoc' });
}
if (!projectName) {
return res.status(400).json({ success: false, message: 'Du an xuat la bat buoc' });
}
transaction = new sql.Transaction(pool);
await transaction.begin();
const assetResult = await new sql.Request(transaction)
.input('assetId', sql.Int, assetId)
.query(`
SELECT TOP 1
AssetId,
AssetCode,
AssetName,
Quantity,
ImportInPeriod,
ExportInPeriod,
EndingBalance,
NewQuantity,
UsedQuantity,
Custodian,
Borrower,
Notes
FROM AssetInventory WITH (UPDLOCK, ROWLOCK)
WHERE AssetId = @assetId AND IsArchived = 0
`);
const asset = assetResult.recordset?.[0];
if (!asset) {
await transaction.rollback();
return res.status(404).json({ success: false, message: 'Asset not found' });
}
const quantity = parseNonNegativeInteger(asset.Quantity, 0);
const importInPeriod = parseNonNegativeInteger(asset.ImportInPeriod, 0);
const existingBorrowerEntries = parseBorrowerEntries(asset.Borrower);
const previousBorrowerExport = existingBorrowerEntries.reduce((sum, entry) => (
sum + parseNonNegativeInteger(entry?.quantity, 0)
), 0);
const storedExportInPeriod = parseOptionalNonNegativeInteger(asset.ExportInPeriod);
const baseExportInPeriod = storedExportInPeriod !== null ? storedExportInPeriod : previousBorrowerExport;
const storedEndingBalance = parseOptionalNonNegativeInteger(asset.EndingBalance);
const baseEndingBalance = storedEndingBalance !== null
? storedEndingBalance
: Math.max(quantity + importInPeriod - baseExportInPeriod, 0);
const baseNewQuantity = parseOptionalNonNegativeInteger(asset.NewQuantity);
const baseUsedQuantity = parseOptionalNonNegativeInteger(asset.UsedQuantity);
const stockBuckets = normalizeAssetStockBuckets(
baseEndingBalance,
baseNewQuantity !== null ? baseNewQuantity : baseEndingBalance,
baseUsedQuantity !== null ? baseUsedQuantity : 0
);
if (baseEndingBalance <= 0) {
await transaction.rollback();
return res.status(400).json({ success: false, message: 'Tai san da het ton cuoi ky, khong the xuat them' });
}
if (exportQuantity > baseEndingBalance) {
await transaction.rollback();
return res.status(400).json({
success: false,
message: `So luong xuat (${exportQuantity}) vuot qua ton cuoi ky (${baseEndingBalance})`
});
}
const borrowerSummary = mergeBorrowerEntries(asset.Borrower, borrowerName, exportQuantity);
const nextBorrowerEntries = parseBorrowerEntries(borrowerSummary);
const nextBorrowerExport = nextBorrowerEntries.reduce((sum, entry) => (
sum + parseNonNegativeInteger(entry?.quantity, 0)
), 0);
const exportDelta = nextBorrowerExport - previousBorrowerExport;
const nextExportInPeriod = Math.max(baseExportInPeriod + exportDelta, 0);
const nextEndingBalance = Math.max(baseEndingBalance - exportDelta, 0);
const borrowFromNew = Math.min(stockBuckets.newQuantity, exportDelta);
const borrowFromUsed = Math.max(exportDelta - borrowFromNew, 0);
const nextNewQuantity = Math.max(stockBuckets.newQuantity - borrowFromNew, 0);
const nextUsedQuantity = Math.max(stockBuckets.usedQuantity - borrowFromUsed, 0);
const nextStatus = resolveAssetStatusFromStock(nextEndingBalance, nextExportInPeriod);
const existingAssetNotes = String(asset.Notes || '').trim();
const cleanExportNote = String(exportNote || '').trim();
const nextAssetNotes = cleanExportNote
? (existingAssetNotes ? `${existingAssetNotes}\n${cleanExportNote}` : cleanExportNote)
: (existingAssetNotes || null);
function prepareAssetExport(asset, allocations, exportNote) {
const fail = message => { throw Object.assign(new Error(message), { statusCode: 400 }); };
const exportQuantity = allocations.reduce((sum, row) => sum + row.quantity, 0);
const quantity = parseNonNegativeInteger(asset.Quantity, 0);
const importInPeriod = parseNonNegativeInteger(asset.ImportInPeriod, 0);
const previousBorrowerExport = parseBorrowerEntries(asset.Borrower)
.reduce((sum, entry) => sum + parseNonNegativeInteger(entry?.quantity, 0), 0);
const allocatedQuantity = parseAllocations(asset.ProjectAllocations).reduce((sum, row) => sum + row.quantity, 0);
const baseExportInPeriod = Math.max(parseOptionalNonNegativeInteger(asset.ExportInPeriod) || 0, previousBorrowerExport, allocatedQuantity);
const totalAvailable = Math.max(quantity + importInPeriod - baseExportInPeriod, 0);
const available = Math.min(parseOptionalNonNegativeInteger(asset.EndingBalance) ?? totalAvailable, totalAvailable);
const label = String(asset.AssetCode || asset.AssetName || asset.AssetId);
if (available <= 0) fail(`${label}: Tài sản đã hết tồn cuối kỳ, không thể xuất thêm.`);
if (exportQuantity > available) fail(`${label}: Số lượng xuất (${exportQuantity}) vượt quá tồn cuối kỳ (${available}).`);
// Permanent project exports never enter the returnable borrower ledger.
const exportDelta = exportQuantity;
const stock = normalizeAssetStockBuckets(available,
parseOptionalNonNegativeInteger(asset.NewQuantity) ?? available,
parseOptionalNonNegativeInteger(asset.UsedQuantity) ?? 0);
const exportFromNew = Math.min(stock.newQuantity, exportDelta);
const endingBalance = Math.max(available - exportDelta, 0);
const exportInPeriod = Math.max(baseExportInPeriod + exportDelta, 0);
const oldNotes = String(asset.Notes || '').trim();
return { asset, allocations, available, endingBalance, exportInPeriod,
newQuantity: Math.max(stock.newQuantity - exportFromNew, 0),
usedQuantity: Math.max(stock.usedQuantity - Math.max(exportDelta - exportFromNew, 0), 0),
status: resolveAssetStatusFromStock(endingBalance, exportInPeriod),
notes: exportNote ? (oldNotes ? `${oldNotes}\n${exportNote}` : exportNote) : (oldNotes || null) };
}
async function performAssetExport(transaction, plans, { createdBy, requesterName, exportedByName, exportNote }) {
const exportedDate = new Date();
const workbookItems = plans.map(plan => ({ item: plan.asset, rows: plan.allocations, availableStock: plan.available }));
const document = await buildExportRequestWorkbook({
...(plans.length === 1 ? workbookItems[0] : { items: workbookItems }),
requesterName, recipientName: requesterName, exportedByName, note: exportNote, exportedDate
});
const documentId = crypto.randomUUID();
const snapshot = { version: 1, exportedDate: exportedDate.toISOString(), borrowerName: requesterName, requesterName, exportedByName, note: exportNote,
items: plans.map(plan => ({ assetId: plan.asset.AssetId, assetCode: plan.asset.AssetCode,
assetName: plan.asset.AssetName, model: plan.asset.Model, serialNumber: plan.asset.SerialNumber,
unit: plan.asset.Unit, department: plan.asset.Department, availableStock: plan.available,
allocations: plan.allocations })) };
await new sql.Request(transaction)
.input('documentId', sql.UniqueIdentifier, documentId)
.input('fileName', sql.NVarChar(255), document.fileName)
.input('mimeType', sql.NVarChar(150), document.mimeType)
.input('fileContent', sql.VarBinary(sql.MAX), Buffer.from(document.contentBase64, 'base64'))
.input('snapshotJson', sql.NVarChar(sql.MAX), JSON.stringify(snapshot))
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.query(`INSERT INTO AssetExportDocuments (ExportDocumentId, FileName, MimeType, FileContent, SnapshotJson, CreatedBy, ExportedDate)
VALUES (@documentId, @fileName, @mimeType, @fileContent, @snapshotJson, @createdBy, @exportedDate)`);
const histories = [];
for (const plan of plans) {
const { asset } = plan;
await new sql.Request(transaction)
.input('assetId', sql.Int, assetId)
.input('project', sql.NVarChar, projectName)
.input('borrower', sql.NVarChar, borrowerSummary)
.input('exportInPeriod', sql.Int, nextExportInPeriod)
.input('endingBalance', sql.Int, nextEndingBalance)
.input('newQuantity', sql.Int, nextNewQuantity)
.input('usedQuantity', sql.Int, nextUsedQuantity)
.input('status', sql.NVarChar, nextStatus)
.input('assetId', sql.Int, asset.AssetId)
// No borrower: returns can release loans while keeping these project exports.
.input('projectAllocations', sql.NVarChar(sql.MAX), JSON.stringify(addProjectExports(asset.ProjectAllocations, plan.allocations)))
.input('exportInPeriod', sql.Int, plan.exportInPeriod)
.input('endingBalance', sql.Int, plan.endingBalance)
.input('newQuantity', sql.Int, plan.newQuantity)
.input('usedQuantity', sql.Int, plan.usedQuantity)
.input('status', sql.NVarChar, plan.status)
.input('exportedBy', sql.NVarChar, exportedByName)
.input('notes', sql.NVarChar, nextAssetNotes)
.query(`
UPDATE AssetInventory
SET Project = @project,
Borrower = @borrower,
ExportInPeriod = @exportInPeriod,
EndingBalance = @endingBalance,
NewQuantity = @newQuantity,
UsedQuantity = @usedQuantity,
Status = @status,
ExportedBy = @exportedBy,
Notes = @notes,
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
WHERE AssetId = @assetId AND IsArchived = 0
`);
const historyCustodianName = String(asset.Custodian || '').trim() || '-';
const historyResult = await new sql.Request(transaction)
.input('assetId', sql.Int, assetId)
.input('assetCode', sql.NVarChar, String(asset.AssetCode || '').trim())
.input('assetName', sql.NVarChar, String(asset.AssetName || '').trim())
.input('exportQuantity', sql.Int, exportQuantity)
.input('projectName', sql.NVarChar, projectName)
.input('custodianName', sql.NVarChar, historyCustodianName)
.input('exportedByName', sql.NVarChar, exportedByName)
.input('exportNote', sql.NVarChar, exportNote)
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.query(`
INSERT INTO AssetExportHistory (
AssetId,
AssetCode,
AssetName,
ExportQuantity,
ProjectName,
CustodianName,
ExportedByName,
ExportNote,
CreatedBy,
ExportedDate
)
OUTPUT
INSERTED.ExportHistoryId,
INSERTED.AssetId,
INSERTED.AssetCode,
INSERTED.AssetName,
INSERTED.ExportQuantity,
INSERTED.ProjectName,
INSERTED.CustodianName,
INSERTED.ExportedByName,
INSERTED.ExportNote,
INSERTED.CreatedBy,
INSERTED.ExportedDate,
INSERTED.CreatedDate,
INSERTED.UpdatedDate
VALUES (
@assetId,
@assetCode,
@assetName,
@exportQuantity,
@projectName,
@custodianName,
@exportedByName,
@exportNote,
@createdBy,
@exportedDate
)
`);
await transaction.commit();
res.json({
success: true,
message: 'Xuat tai san thanh cong',
data: historyResult.recordset?.[0] || null
});
} catch (err) {
if (transaction) {
try {
await transaction.rollback();
} catch (_rollbackErr) {
// Ignore rollback error, respond original error below.
}
.input('notes', sql.NVarChar, plan.notes)
.query(`UPDATE AssetInventory SET ProjectAllocations = @projectAllocations,
ExportInPeriod = @exportInPeriod, EndingBalance = @endingBalance, NewQuantity = @newQuantity,
UsedQuantity = @usedQuantity, Status = @status, ExportedBy = @exportedBy, Notes = @notes,
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
WHERE AssetId = @assetId AND IsArchived = 0`);
for (const allocation of plan.allocations) {
const result = await new sql.Request(transaction)
.input('assetId', sql.Int, asset.AssetId)
.input('assetCode', sql.NVarChar, String(asset.AssetCode || '').trim())
.input('assetName', sql.NVarChar, String(asset.AssetName || '').trim())
.input('exportQuantity', sql.Int, allocation.quantity)
.input('projectName', sql.NVarChar, allocation.projectName)
.input('custodianName', sql.NVarChar, String(asset.Custodian || '').trim() || '-')
.input('exportedByName', sql.NVarChar, exportedByName)
.input('exportNote', sql.NVarChar, exportNote)
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.input('documentId', sql.UniqueIdentifier, documentId)
.query(`INSERT INTO AssetExportHistory (AssetId, AssetCode, AssetName, ExportQuantity, ProjectName,
CustodianName, ExportedByName, ExportNote, CreatedBy, ExportedDate, ExportDocumentId)
OUTPUT INSERTED.*
VALUES (@assetId, @assetCode, @assetName, @exportQuantity, @projectName,
@custodianName, @exportedByName, @exportNote, @createdBy, @exportedDate, @documentId)`);
histories.push(result.recordset?.[0] || null);
}
sendInternalError(res, err);
}
return { document: { ...document, documentId }, histories };
}
const assetExportWorkflow = createAssetExportWorkflow({
getPool: () => pool, sql, requireManage: requireAssetOrAdmin, getRequesterRole, getUserIdFromRequest,
getUserDisplayNameById: id => getUserDisplayNameById(id), prepareAssetExport, performAssetExport, sendInternalError,
notifyCreated: target => safeCreateSystemNotification({
severity: 'info', title: 'Đơn xuất vào dự án mới',
message: `${target.RequesterName} đã gửi đơn xuất #${target.ExportRequestId}, chờ duyệt.`,
actionUrl: '#asset-exports', audiences: [{ type: 'role', value: 'admin' }, { type: 'role', value: 'asset' }]
}),
notifyProcessed: (target, action, rejectReason) => safeCreateSystemNotification({
severity: action === 'approved' ? 'success' : 'error',
title: action === 'approved' ? 'Đơn xuất dự án được duyệt' : 'Đơn xuất dự án bị từ chối',
message: `Đơn xuất #${target.ExportRequestId} đã ${action === 'approved' ? 'được duyệt và trừ kho' : `bị từ chối. Lý do: ${rejectReason}`}.`,
actionUrl: '#asset-exports', audiences: [{ type: 'user', value: Number(target.CreatedBy) }]
})
});
app.use('/api/asset-export-requests', assetExportWorkflow.router);
app.post('/api/assets/export', requireAssetOrAdmin, (req, res) => assetExportWorkflow.directExport(req, res));
app.post('/api/assets/:id/export', requireAssetOrAdmin, (req, res) => assetExportWorkflow.directExport(req, res, req.params.id));
app.post('/api/assets', requireAssetOrAdmin, async (req, res) => {
try {
@@ -9154,6 +9120,7 @@ app.post('/api/assets', requireAssetOrAdmin, async (req, res) => {
});
app.put('/api/assets/:id', requireAssetOrAdmin, async (req, res) => {
const transaction = new sql.Transaction(pool);
try {
const payload = normalizeAssetPayload(req.body);
const updatedBy = getUserIdFromRequest(req);
@@ -9169,7 +9136,30 @@ app.put('/api/assets/:id', requireAssetOrAdmin, async (req, res) => {
await ensureDepartmentExists(payload.department);
const updateResult = await pool.request()
await transaction.begin();
const currentResult = await new sql.Request(transaction)
.input('assetId', sql.Int, req.params.id)
.query('SELECT * FROM AssetInventory WITH (UPDLOCK, HOLDLOCK) WHERE AssetId = @assetId AND IsArchived = 0');
const current = currentResult.recordset?.[0];
if (!current) {
await transaction.rollback();
return res.status(404).json({ success: false, message: 'Asset not found or archived' });
}
// The form may have been opened before another export. Keep the locked ledger.
payload.exportInPeriod = Math.max(parseNonNegativeInteger(current.ExportInPeriod, 0),
parseBorrowerEntries(current.Borrower).reduce((sum, row) => sum + row.quantity, 0),
parseAllocations(current.ProjectAllocations).reduce((sum, row) => sum + row.quantity, 0));
if (payload.quantity + payload.importInPeriod < payload.exportInPeriod) {
await transaction.rollback();
return res.status(400).json({ success: false, message: 'Tổng tài sản không được nhỏ hơn số lượng đang xuất.' });
}
payload.borrower = current.Borrower || null;
payload.endingBalance = payload.quantity + payload.importInPeriod - payload.exportInPeriod;
const buckets = normalizeAssetStockBuckets(payload.endingBalance, Math.max(payload.endingBalance - (current.UsedQuantity || 0), 0), current.UsedQuantity || 0);
payload.newQuantity = buckets.newQuantity;
payload.usedQuantity = buckets.usedQuantity;
payload.status = resolveAssetStatusFromStock(payload.endingBalance, payload.exportInPeriod);
const updateResult = await new sql.Request(transaction)
.input('assetId', sql.Int, req.params.id)
.input('assetCode', sql.NVarChar, payload.assetCode)
.input('assetName', sql.NVarChar, payload.assetName)
@@ -9221,11 +9211,14 @@ app.put('/api/assets/:id', requireAssetOrAdmin, async (req, res) => {
`);
if (!updateResult.recordset?.length) {
await transaction.rollback();
return res.status(404).json({ success: false, message: 'Asset not found or archived' });
}
await transaction.commit();
res.json({ success: true, message: 'Asset updated' });
} catch (err) {
try { await transaction.rollback(); } catch {}
if (String(err.message || '').includes('UNIQUE')) {
return res.status(409).json({ success: false, message: 'Asset code already exists' });
}
@@ -9414,6 +9407,16 @@ app.post('/api/assets/import', requireAssetOrAdmin, upload.single('file'), async
continue;
}
const allocatedAsset = await new sql.Request(transaction)
.input('assetCode', sql.NVarChar, row.assetCode)
.query(`SELECT AssetId FROM AssetInventory WITH (UPDLOCK, HOLDLOCK)
WHERE AssetCode = @assetCode AND IsArchived = 0
AND ProjectAllocations IS NOT NULL AND ProjectAllocations <> '[]'`);
if (allocatedAsset.recordset?.length) {
await transaction.rollback();
return res.status(409).json({ success: false, message: `Tài sản ${row.assetCode} đang xuất cho dự án. Vui lòng cập nhật bằng biểu mẫu tài sản để giữ số lượng đã phân bổ.` });
}
const mergeResult = await new sql.Request(transaction)
.input('assetCode', sql.NVarChar, row.assetCode)
.input('assetName', sql.NVarChar, row.assetName)
@@ -9511,9 +9514,19 @@ app.post('/api/assets/import', requireAssetOrAdmin, upload.single('file'), async
});
// ==========================================
// API ROUTES - PDF Documents
// API ROUTES - Shared Documents
// ==========================================
app.use('/api/robots', createRobotRouter({
getPool: () => pool, sql, requireManage: requireAssetOrAdmin,
documentMaxBytes: DOCUMENT_MAX_FILE_SIZE_BYTES, documentMaxMb: DOCUMENT_MAX_FILE_SIZE_MB,
sanitizeDocumentFileName, sendInternalError
}));
app.use('/api/robot-boms', createRobotBomRouter({
getPool: () => pool, sql, requireManage: requireAssetOrAdmin, sendInternalError
}));
app.get('/api/documents', async (req, res) => {
try {
const search = String(req.query.search || '').trim().slice(0, 255);
@@ -9544,7 +9557,8 @@ app.get('/api/documents', async (req, res) => {
res.json({
success: true,
data: result.recordset,
maxFileSizeMb: DOCUMENT_MAX_FILE_SIZE_MB
maxFileSizeMb: DOCUMENT_MAX_FILE_SIZE_MB,
acceptedExtensions: documentAccept
});
} catch (err) {
sendInternalError(res, err, 'Không thể tải danh sách tài liệu');
@@ -9554,20 +9568,18 @@ app.get('/api/documents', async (req, res) => {
app.post('/api/documents', documentUpload.single('file'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ success: false, message: 'Vui lòng chọn file PDF' });
}
if (!isPdfBuffer(req.file.buffer)) {
return res.status(400).json({ success: false, message: 'Nội dung file không phải là PDF hợp lệ' });
return res.status(400).json({ success: false, message: 'Vui lòng chọn tài liệu' });
}
const format = validateDocumentFile(req.file);
const originalFileName = sanitizeDocumentFileName(req.file.originalname);
const originalFileName = sanitizeDocumentFileName(normalizeUploadedFileName(req.file.originalname));
const requestedTitle = String(req.body.title || '').trim();
const defaultTitle = originalFileName.replace(/\.pdf$/i, '').trim() || 'Tài liệu PDF';
const defaultTitle = originalFileName.replace(/\.[^.]+$/, '').trim() || 'Tài liệu';
const title = (requestedTitle || defaultTitle).slice(0, 255);
const result = await pool.request()
.input('title', sql.NVarChar(255), title)
.input('originalFileName', sql.NVarChar(255), originalFileName)
.input('mimeType', sql.NVarChar(100), 'application/pdf')
.input('mimeType', sql.NVarChar(100), format.mimeType)
.input('fileSize', sql.BigInt, req.file.size)
.input('fileData', sql.VarBinary(sql.MAX), req.file.buffer)
.input('uploadedBy', sql.Int, req.user.UserId)
@@ -9580,10 +9592,11 @@ app.post('/api/documents', documentUpload.single('file'), async (req, res) => {
res.status(201).json({
success: true,
message: 'Đã lưu tài liệu PDF',
message: 'Đã lưu tài liệu',
data: result.recordset[0]
});
} catch (err) {
if (err.code === 'DOCUMENT_VALIDATION') return res.status(400).json({ success: false, message: err.message });
sendInternalError(res, err, 'Không thể lưu tài liệu');
}
});
@@ -9607,8 +9620,10 @@ app.get('/api/documents/:id/file', async (req, res) => {
return res.status(404).json({ success: false, message: 'Không tìm thấy tài liệu' });
}
const shouldDownload = String(req.query.download || '') === '1';
res.setHeader('Content-Type', 'application/pdf');
const format = getDocumentFormat(document.OriginalFileName);
const shouldDownload = String(req.query.download || '') === '1' || !format?.preview;
res.setHeader('Content-Type', format?.mimeType || 'application/octet-stream');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Content-Length', String(document.FileSize));
res.setHeader('Content-Disposition', getDocumentContentDisposition(document.OriginalFileName, shouldDownload));
res.send(document.FileData);
@@ -9638,11 +9653,19 @@ app.delete('/api/documents/:id', async (req, res) => {
return res.status(403).json({ success: false, message: 'Bạn không có quyền xóa tài liệu này' });
}
await pool.request()
const deletedResult = await pool.request()
.input('documentId', sql.Int, documentId)
.query('DELETE FROM Documents WHERE DocumentId = @documentId');
.query(`DELETE FROM Documents OUTPUT DELETED.DocumentId
WHERE DocumentId = @documentId
AND NOT EXISTS (SELECT 1 FROM dbo.RobotDocuments WHERE DocumentId = @documentId)`);
if (!deletedResult.recordset.length) {
return res.status(409).json({ success: false, message: 'Tài liệu đang được gắn với robot. Vui lòng gỡ liên kết trong phần Quản lý robot trước khi xóa.' });
}
res.json({ success: true, message: 'Đã xóa tài liệu' });
} catch (err) {
if (err.number === 547) {
return res.status(409).json({ success: false, message: 'Tài liệu đang được gắn với robot. Vui lòng gỡ liên kết trong phần Quản lý robot trước khi xóa.' });
}
sendInternalError(res, err, 'Không thể xóa tài liệu');
}
});
@@ -9690,6 +9713,10 @@ app.get('/api/database/info', requireAdmin, async (req, res) => {
// Error Handling
// ==========================================
app.use('/api', (req, res) => {
res.status(404).json({ success: false, code: 'API_NOT_FOUND', message: 'API không tồn tại. Vui lòng cập nhật backend rồi thử lại.' });
});
app.use((err, req, res, next) => {
console.error('Unhandled request error:', err.message);
if (err instanceof multer.MulterError) {
@@ -9700,7 +9727,7 @@ app.use((err, req, res, next) => {
: err.message;
return res.status(400).json({ success: false, message });
}
if (err.message === 'Only .xls and .xlsx files are allowed' || err.message === 'Chỉ chấp nhận file PDF') {
if (err.message === 'Only .xls and .xlsx files are allowed' || err.code === 'DOCUMENT_VALIDATION') {
return res.status(400).json({ success: false, message: err.message });
}
res.status(500).json({ success: false, message: 'Internal server error' });

Binary file not shown.

View File

@@ -923,6 +923,19 @@ BEGIN
END
-- ===========================================
-- Popup dismissal is independent of the per-user read receipt.
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'NotificationPopupDismissals')
BEGIN
CREATE TABLE NotificationPopupDismissals (
NotificationId BIGINT NOT NULL,
UserId INT NOT NULL,
DismissedAt DATETIME NOT NULL DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME())),
PRIMARY KEY (NotificationId, UserId),
FOREIGN KEY (NotificationId) REFERENCES Notifications(NotificationId) ON DELETE CASCADE,
FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE
);
END
-- 12. CREATE AUDIT LOG TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AuditLog')
@@ -1286,3 +1299,144 @@ BEGIN CATCH
END CATCH;
GO
-- Persist exact Excel files and their immutable export snapshots.
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.AssetExportDocuments', 'U') IS NULL
BEGIN
CREATE TABLE dbo.AssetExportDocuments (
ExportDocumentId UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,
FileName NVARCHAR(255) NOT NULL,
MimeType NVARCHAR(150) NOT NULL,
FileContent VARBINARY(MAX) NOT NULL,
SnapshotJson NVARCHAR(MAX) NOT NULL,
CreatedBy INT NULL,
ExportedDate DATETIME NOT NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME()))
);
END;
IF COL_LENGTH('dbo.AssetExportHistory', 'ExportDocumentId') IS NULL
ALTER TABLE dbo.AssetExportHistory ADD ExportDocumentId UNIQUEIDENTIFIER NULL;
IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_AssetExportHistory_Document')
EXEC(N'ALTER TABLE dbo.AssetExportHistory ADD CONSTRAINT FK_AssetExportHistory_Document
FOREIGN KEY (ExportDocumentId) REFERENCES dbo.AssetExportDocuments(ExportDocumentId)');
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;
GO
-- Robot catalog and shared PDF document links. Keep in sync with backend/robot-schema.sql.
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.RobotTypes', 'U') IS NULL
BEGIN
CREATE TABLE dbo.RobotTypes (
TypeId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
Name NVARCHAR(100) NOT NULL,
Description NVARCHAR(500) NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
CONSTRAINT UQ_RobotTypes_Name UNIQUE (Name)
);
END;
IF OBJECT_ID('dbo.Robots', 'U') IS NULL
BEGIN
CREATE TABLE dbo.Robots (
RobotId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
Name NVARCHAR(255) NOT NULL,
Model NVARCHAR(255) NOT NULL,
Type NVARCHAR(100) NOT NULL,
AvatarData VARBINARY(MAX) NULL,
AvatarMimeType NVARCHAR(100) NULL,
CreatedBy INT NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
CONSTRAINT FK_Robots_CreatedBy FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId) ON DELETE SET NULL
);
CREATE INDEX IX_Robots_Name ON dbo.Robots(Name);
END;
IF COL_LENGTH('dbo.Robots', 'TypeId') IS NULL
ALTER TABLE dbo.Robots ADD TypeId INT NULL;
-- A separate compilation scope is required when TypeId was just added.
-- Only unmigrated rows seed the catalog, so renamed types stay renamed.
EXEC(N'
INSERT INTO dbo.RobotTypes (Name)
SELECT DISTINCT COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
FROM dbo.Robots r
WHERE r.TypeId IS NULL AND NOT EXISTS (
SELECT 1 FROM dbo.RobotTypes t
WHERE t.Name = COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
);
UPDATE r SET TypeId = t.TypeId, Type = t.Name
FROM dbo.Robots r JOIN dbo.RobotTypes t
ON t.Name = COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
WHERE r.TypeId IS NULL;
');
IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('dbo.Robots') AND name = 'TypeId' AND is_nullable = 1)
EXEC(N'ALTER TABLE dbo.Robots ALTER COLUMN TypeId INT NOT NULL;');
IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_Robots_Type')
EXEC(N'ALTER TABLE dbo.Robots ADD CONSTRAINT FK_Robots_Type FOREIGN KEY (TypeId) REFERENCES dbo.RobotTypes(TypeId);');
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.Robots') AND name = 'IX_Robots_TypeId')
EXEC(N'CREATE INDEX IX_Robots_TypeId ON dbo.Robots(TypeId);');
IF OBJECT_ID('dbo.RobotDocuments', 'U') IS NULL
BEGIN
CREATE TABLE dbo.RobotDocuments (
RobotId INT NOT NULL,
DocumentId INT NOT NULL,
CONSTRAINT PK_RobotDocuments PRIMARY KEY (RobotId, DocumentId),
CONSTRAINT FK_RobotDocuments_Robot FOREIGN KEY (RobotId) REFERENCES dbo.Robots(RobotId) ON DELETE CASCADE,
CONSTRAINT FK_RobotDocuments_Document FOREIGN KEY (DocumentId) REFERENCES dbo.Documents(DocumentId)
);
CREATE INDEX IX_RobotDocuments_DocumentId ON dbo.RobotDocuments(DocumentId);
END;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;
GO
GO
-- Project export approval workflow. Preserves legacy exports.
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.AssetExportRequests', 'U') IS NULL
BEGIN
CREATE TABLE dbo.AssetExportRequests (
ExportRequestId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
RequesterName NVARCHAR(100) NOT NULL,
ItemsJson NVARCHAR(MAX) NOT NULL,
RequestNote NVARCHAR(1000) NULL,
RequestStatus NVARCHAR(20) NOT NULL DEFAULT 'pending',
CreatedBy INT NOT NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
ProcessedBy INT NULL,
ProcessedByName NVARCHAR(100) NULL,
ProcessedDate DATETIME NULL,
RejectReason NVARCHAR(1000) NULL,
ExportDocumentId UNIQUEIDENTIFIER NULL,
CONSTRAINT CK_AssetExportRequests_Status CHECK (RequestStatus IN ('pending', 'approved', 'rejected')),
CONSTRAINT FK_AssetExportRequests_User FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId),
CONSTRAINT FK_AssetExportRequests_Document FOREIGN KEY (ExportDocumentId) REFERENCES dbo.AssetExportDocuments(ExportDocumentId)
);
CREATE INDEX IX_AssetExportRequests_Creator ON dbo.AssetExportRequests(CreatedBy, CreatedDate DESC);
CREATE INDEX IX_AssetExportRequests_Status ON dbo.AssetExportRequests(RequestStatus, CreatedDate DESC);
END;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;
GO

View File

@@ -6,7 +6,8 @@
"scripts": {
"start": "node backend/server.js",
"dev": "nodemon backend/server.js",
"test": "node --test",
"review:export": "node tools/export-review-server.js",
"test": "node backend/run-tests.js",
"check": "node --check backend/server.js && node --check public/js/app.js && npm audit",
"build:css": "tailwindcss -c tailwind.config.js -i ./public/css/tailwind.css -o ./public/css/main.css --minify",
"watch:css": "tailwindcss -c tailwind.config.js -i ./public/css/tailwind.css -o ./public/css/main.css --watch"

View File

@@ -0,0 +1,48 @@
.announcement-dialog {
width: min(560px, calc(100vw - 32px));
max-height: calc(100dvh - 40px);
margin: auto;
padding: 0;
overflow-y: auto;
border: 1px solid #e2e8f0;
border-radius: 16px;
background: white;
color: #243248;
box-shadow: 0 24px 80px #0f172a40;
}
.announcement-dialog::backdrop { background: rgb(15 23 42 / 55%); backdrop-filter: blur(3px); }
.announcement-heading { display: flex; align-items: flex-start; gap: 14px; padding: 24px 24px 20px; border-bottom: 1px solid #edf1f7; }
.announcement-symbol { display: flex; align-items: center; justify-content: center; flex-shrink: 0; width: 44px; height: 44px; border-radius: 12px; background: #edf1ff; color: #3755c3; font-size: 25px; }
.announcement-heading > div { flex: 1; min-width: 0; }
.announcement-heading p { margin: 2px 0 6px; color: #64748b; font-size: 10px; font-weight: 700; letter-spacing: 0.09em; }
.announcement-heading h2 { font-size: 19px; font-weight: 800; line-height: 1.5; overflow-wrap: anywhere; }
.announcement-heading button { display: flex; padding: 5px; border-radius: 7px; color: #64748b; }
.announcement-heading button:hover { background: #f1f5f9; }
.announcement-body { padding: 20px 24px 24px; }
.announcement-author { margin-bottom: 16px; color: #64748b; font-size: 11px; line-height: 1.8; }
#announcementMessage { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 14px; line-height: 1.85; }
.announcement-error { margin-top: 16px; border-radius: 8px; padding: 10px 12px; background: #fff1f2; color: #be123c; font-size: 12px; line-height: 1.6; }
.announcement-footer { padding: 18px 24px 22px; border-top: 1px solid #edf1f7; background: #f8fafc; }
.announcement-footer label { display: flex; align-items: center; gap: 9px; width: fit-content; min-height: 32px; font-size: 13px; font-weight: 600; cursor: pointer; }
.announcement-footer input { width: 16px; height: 16px; border: 1px solid #94a3b8; border-radius: 4px; color: #3755c3; }
.announcement-footer > p { margin: 3px 0 18px; color: #64748b; font-size: 11px; line-height: 1.6; }
.announcement-footer > div { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 10px; }
.announcement-footer button { min-height: 42px; padding: 10px 18px; border: 1px solid #dbe2ef; border-radius: 8px; font-size: 12px; font-weight: 700; }
.announcement-footer .announcement-primary { border-color: #3755c3; background: #3755c3; color: white; }
.announcement-footer .announcement-secondary { background: white; color: #3755c3; }
.announcement-dialog button:disabled { opacity: 0.6; cursor: wait; }
.announcement-dialog :is(button, input):focus-visible { outline: 2px solid #3755c3; outline-offset: 3px; }
.announcement-management-note { margin-top: 20px; border: 1px solid #dce4f6; border-radius: 10px; padding: 14px 16px; background: #f0f4ff; color: #435577; font-size: 12px; line-height: 1.8; }
.announcement-post-status { margin-top: 8px; color: #64748b; font-size: 11px; font-weight: 600; }
.notification-withdraw-dialog .bom-confirm-icon { color: #dc2626; background: #fef2f2; }
.notification-withdraw-dialog .bom-dialog-footer { justify-content: flex-end; }
.notification-withdraw-summary { margin-bottom: 18px; padding: 16px; border: 1px solid #e2e8f0; border-radius: 8px; background: #f8fafc; overflow-wrap: anywhere; }
.notification-withdraw-summary strong { font-size: 14px; font-weight: 700; }
.notification-withdraw-summary p { margin-top: 6px; color: #64748b; font-size: 11px; line-height: 1.6; }
#notificationComposerModal > div { max-height: calc(100dvh - 32px); overflow-y: auto; }
@media (max-width: 480px) {
.announcement-heading { padding: 18px 16px 16px; gap: 10px; }
.announcement-heading h2 { font-size: 17px; }
.announcement-body, .announcement-footer { padding: 16px; }
.announcement-symbol { width: 36px; height: 36px; font-size: 22px; }
}

View File

@@ -0,0 +1,364 @@
/* Asset catalog actions: page utilities and actions on the current selection. */
.assets-page {
--asset-action-surface: #fff;
--asset-action-text: #334155;
--asset-action-muted: #64748b;
--asset-action-border: #e2e8f0;
--asset-action-tint: #f5f7ff;
}
.assets-page .asset-page-heading {
position: relative;
z-index: 120;
}
.asset-page-actions,
.asset-selection-actions {
display: flex;
align-items: center;
gap: 0.5rem;
flex-shrink: 0;
}
.assets-page .asset-action-button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
min-height: 2.5rem;
padding: 0.5625rem 0.875rem;
border: 1px solid var(--asset-action-border);
border-radius: 0.625rem;
background: var(--asset-action-surface);
color: var(--asset-action-text);
font-size: 0.8125rem;
font-weight: 600;
line-height: 1.25;
white-space: nowrap;
cursor: pointer;
touch-action: manipulation;
transition: border-color 0.15s, background-color 0.15s, color 0.15s;
}
.asset-action-button .material-symbols-outlined,
.asset-menu-item .material-symbols-outlined {
flex-shrink: 0;
font-size: 1.125rem;
}
.assets-page .asset-action-button:hover:not(:disabled) {
border-color: #b8c4e8;
background: var(--asset-action-tint);
color: #3755c3;
}
.assets-page .asset-action-primary {
border-color: #3755c3;
background: #3755c3;
color: #fff;
box-shadow: 0 2px 4px rgb(55 85 195 / 0.12);
}
.assets-page .asset-action-primary:hover:not(:disabled) {
border-color: #2848b7;
background: #2848b7;
color: #fff;
}
.asset-action-button:focus-visible,
.asset-menu-item:focus-visible,
.asset-selection-clear:focus-visible {
outline: 2px solid #3755c3;
outline-offset: 3px;
}
.assets-page .asset-action-button:disabled,
.assets-page .asset-menu-item:disabled {
color: #94a3b8;
cursor: not-allowed;
}
.asset-action-menu {
position: relative;
}
.asset-action-menu > summary {
list-style: none;
}
.asset-action-menu > summary::-webkit-details-marker {
display: none;
}
.asset-action-menu[open] > summary {
border-color: #b8c4e8;
color: #3755c3;
background: var(--asset-action-tint);
}
.asset-menu-chevron {
transition: transform 0.15s;
}
.asset-action-menu[open] .asset-menu-chevron {
transform: rotate(180deg);
}
.asset-menu-panel {
position: absolute;
top: calc(100% + 0.5rem);
right: 0;
z-index: 150;
width: 19rem;
max-width: calc(100vw - 2rem);
max-height: min(28rem, calc(100dvh - 12rem));
overflow-y: auto;
padding: 0.375rem;
border: 1px solid var(--asset-action-border);
border-radius: 0.875rem;
background: var(--asset-action-surface);
box-shadow: 0 12px 36px rgb(15 23 42 / 0.12), 0 2px 6px rgb(15 23 42 / 0.04);
text-align: left;
}
.assets-page .asset-menu-label {
margin: 0;
padding: 0.625rem 0.75rem 0.375rem;
color: var(--asset-action-muted);
font-size: 0.6875rem;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.assets-page .asset-menu-item {
display: flex;
align-items: center;
gap: 0.75rem;
width: 100%;
min-height: 2.75rem;
padding: 0.625rem 0.75rem;
border: 0;
border-radius: 0.5rem;
background: transparent;
color: var(--asset-action-text);
font-size: 0.8125rem;
font-weight: 600;
line-height: 1.4;
text-align: left;
cursor: pointer;
}
.asset-menu-item small,
.asset-export-action small {
display: block;
margin-top: 0.1875rem;
color: var(--asset-action-muted);
font-size: 0.6875rem;
font-weight: 400;
line-height: 1.35;
}
.asset-menu-item:hover:not(:disabled) {
background: var(--asset-action-tint);
}
.asset-menu-item:disabled small {
color: inherit;
}
.assets-page .asset-menu-danger {
color: #c2413b;
}
.asset-menu-danger:hover:not(:disabled) {
background: #fff5f4;
}
.asset-menu-divider {
margin-top: 0.375rem !important;
padding-top: 0.375rem;
border-top: 1px solid var(--asset-action-border);
}
.asset-selection-toolbar {
position: relative;
z-index: 110;
display: flex;
align-items: center;
justify-content: space-between;
flex-shrink: 0;
gap: 1rem;
margin-bottom: 0.75rem;
padding: 0.75rem 0.875rem;
border: 1px solid var(--asset-action-border);
border-radius: 0.75rem;
background: var(--asset-action-surface);
transition: background-color 0.15s, border-color 0.15s;
}
.asset-selection-toolbar[data-has-selection="true"] {
border-color: #cdd6f6;
background: var(--asset-action-tint);
}
.asset-selection-info {
display: grid;
grid-template-columns: auto auto;
align-items: center;
justify-content: start;
gap: 0.3125rem 0.75rem;
min-width: 0;
}
.asset-selection-status {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--asset-action-text);
font-size: 0.8125rem;
font-weight: 600;
}
.asset-selection-count {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 1.625rem;
height: 1.625rem;
padding: 0 0.3125rem;
border-radius: 0.4375rem;
background: #f1f5f9;
color: #64748b;
font-variant-numeric: tabular-nums;
}
[data-has-selection="true"] .asset-selection-count {
background: #3755c3;
color: #fff;
}
.asset-selection-hint {
grid-column: 1 / -1;
grid-row: 2;
color: var(--asset-action-muted);
font-size: 0.6875rem;
line-height: 1.4;
}
.asset-selection-clear {
color: #3755c3;
font-size: 0.75rem;
text-underline-offset: 3px;
}
.asset-selection-clear:hover {
text-decoration: underline;
}
.assets-page .asset-export-action {
justify-content: flex-start;
min-height: 3rem;
text-align: left;
}
.assets-page .asset-action-proposal:not(:disabled) {
border-color: #c2cdf1;
color: #3755c3;
}
.assets-page .asset-export-action:disabled small {
color: #94a3b8;
}
@media (max-width: 1200px) {
.asset-selection-toolbar {
flex-wrap: wrap;
}
}
@media (max-width: 900px) {
.assets-page .asset-page-actions {
flex-wrap: wrap;
width: 100%;
gap: 0.5rem;
}
.assets-page .asset-page-actions > button,
.assets-page .asset-page-actions > details {
flex: 1 1 auto;
width: auto;
}
.assets-page .asset-page-actions > details > summary {
width: 100%;
}
.assets-page .asset-page-actions > .asset-action-primary {
flex: 1 0 100%;
order: -1;
}
.assets-page .asset-action-button {
min-height: 2.75rem;
}
.assets-page .asset-page-actions .asset-menu-panel {
right: 0;
}
.assets-page .asset-filter-bar {
grid-template-columns: minmax(7rem, 0.35fr) minmax(0, 1fr);
}
.assets-page .asset-filter-bar .compact-filter-search {
grid-column: auto;
grid-row: auto;
}
.asset-selection-toolbar {
align-items: stretch;
gap: 0.625rem;
padding: 0.75rem;
}
.asset-selection-info {
padding-right: 3rem;
}
.asset-selection-actions {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
width: 100%;
}
.assets-page .asset-export-action {
gap: 0.375rem;
padding: 0.625rem;
font-size: 0.75rem;
white-space: normal;
}
.asset-selection-menu {
position: absolute;
top: 0.75rem;
right: 0.75rem;
}
.assets-page .asset-selection-menu > summary {
min-width: 2.75rem;
padding: 0.5rem;
}
.asset-selection-menu > summary > span:last-child {
display: none;
}
}
.dark .assets-page {
--asset-action-surface: #172033;
--asset-action-text: #e2e8f0;
--asset-action-muted: #94a3b8;
--asset-action-border: #334155;
--asset-action-tint: #1e293b;
}

139
public/css/dashboard.css Normal file
View File

@@ -0,0 +1,139 @@
/* Overview of the existing management modules; all stock totals count catalog codes. */
.dashboard-page {
color: #263449;
background: #f7f9fc;
scrollbar-gutter: stable;
}
.dashboard-shell {
max-width: 1680px;
margin: 0 auto;
padding-bottom: 12px;
}
.dashboard-shell .dashboard-header {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 16px;
margin-bottom: 24px;
}
.dashboard-eyebrow { margin-bottom: 7px; font-size: 10px; font-weight: 800; letter-spacing: 0.12em; color: #62708a; }
.dashboard-header h1 { font-size: 25px; line-height: 1.3; font-weight: 800; letter-spacing: -0.035em; }
.dashboard-header p { margin-top: 6px; font-size: 12px; line-height: 1.6; color: #64748b; }
.dashboard-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
.dashboard-updated { font-size: 11px; color: #64748b; }
.dashboard-refresh { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 9px 13px; border: 1px solid #dce3ee; border-radius: 8px; background: white; font-size: 12px; font-weight: 700; box-shadow: 0 1px 2px #172a4610; }
.dashboard-refresh:hover { background: #eef2ff; border-color: #b9c7f4; }
.dashboard-refresh:disabled { opacity: 0.6; cursor: wait; }
.dashboard-refresh .material-symbols-outlined { font-size: 18px; }
.dashboard-warning { display: flex; align-items: flex-start; gap: 10px; margin-bottom: 18px; border: 1px solid #f4d59c; border-radius: 10px; padding: 12px 16px; background: #fffbeb; color: #92400e; font-size: 12px; line-height: 1.6; }
.dashboard-metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; margin-bottom: 20px; }
.dashboard-metric { display: block; min-width: 0; padding: 19px 20px 16px; background: white; border: 1px solid #e3e9f1; border-radius: 12px; box-shadow: 0 2px 4px #172a4603; transition: border-color 0.15s, box-shadow 0.15s; }
.dashboard-metric:hover { border-color: #b8c6e8; box-shadow: 0 4px 14px #263f7110; }
.dashboard-metric-top { display: flex; align-items: center; gap: 10px; font-size: 12px; font-weight: 700; color: #536176; }
.dashboard-metric-top > .material-symbols-outlined { margin-left: auto; font-size: 16px; color: #94a3b8; }
.dashboard-icon { width: 36px; height: 36px; display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; border-radius: 10px; color: var(--dashboard-accent, #3755c3); background: var(--dashboard-soft, #edf1ff); }
.dashboard-icon .material-symbols-outlined { font-size: 20px; }
.dashboard-tone-blue { --dashboard-accent: #3755c3; --dashboard-soft: #edf1ff; }
.dashboard-tone-green { --dashboard-accent: #087f69; --dashboard-soft: #e8f7f0; }
.dashboard-tone-purple { --dashboard-accent: #7c51c5; --dashboard-soft: #f2edfb; }
.dashboard-tone-amber { --dashboard-accent: #a66313; --dashboard-soft: #fff5e2; }
.dashboard-tone-rose { --dashboard-accent: #be4658; --dashboard-soft: #fff0f2; }
.dashboard-metric-value { display: flex; align-items: baseline; flex-wrap: wrap; column-gap: 8px; margin-top: 16px; font-size: 32px; font-weight: 800; line-height: 1.2; letter-spacing: -0.04em; }
.dashboard-metric-value > span { color: #718096; font-size: 11px; font-weight: 500; letter-spacing: 0; }
.dashboard-metric > p { margin-top: 10px; padding-top: 12px; border-top: 1px solid #f0f3f8; color: #64748b; font-size: 11px; line-height: 1.6; }
.dashboard-layout { display: grid; grid-template-columns: minmax(0, 1.85fr) minmax(300px, 1fr); align-items: start; gap: 20px; }
.dashboard-main-column, .dashboard-side-column { display: grid; min-width: 0; gap: 20px; }
.dashboard-stock-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; }
.dashboard-panel { min-width: 0; padding: 20px; background: white; border: 1px solid #e3e9f1; border-radius: 12px; }
.dashboard-panel-heading { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
.dashboard-panel-heading h2 { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 800; }
.dashboard-panel-heading h2 .material-symbols-outlined { font-size: 18px; color: #6a7eaa; }
.dashboard-panel-heading > a { display: inline-flex; align-items: center; gap: 4px; color: #3755c3; font-size: 11px; font-weight: 700; }
.dashboard-panel-heading > a .material-symbols-outlined { font-size: 15px; }
.dashboard-panel-note { color: #7a8799; font-size: 10px; line-height: 1.6; }
p.dashboard-panel-note { margin-top: 6px; }
.dashboard-stock-row { margin-top: 20px; }
.dashboard-stock-row > div:first-child { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 9px; font-size: 11px; }
.dashboard-stock-row > div:first-child > span { display: inline-flex; align-items: center; gap: 7px; color: #5f6e82; }
.dashboard-stock-row strong { font-size: 13px; white-space: nowrap; }
.dashboard-stock-row small { font-size: 10px; font-weight: 400; color: #7a8799; }
.dashboard-dot { display: inline-block; flex-shrink: 0; width: 7px; height: 7px; border-radius: 50%; }
.dashboard-track { height: 6px; overflow: hidden; background: #f0f3f8; border-radius: 4px; }
.dashboard-track > span { display: block; height: 100%; border-radius: inherit; }
.dashboard-fill-blue { background: #5a79d5; }
.dashboard-fill-purple { background: #a285d5; }
.dashboard-fill-green { background: #43a78d; }
.dashboard-fill-amber { background: #e4b05f; }
.dashboard-fill-rose { background: #dd8190; }
.dashboard-inline-link { display: flex; align-items: center; gap: 6px; margin-top: 19px; color: #3755c3; font-size: 11px; font-weight: 600; }
.dashboard-inline-link .material-symbols-outlined { font-size: 17px; }
.dashboard-inline-link > .material-symbols-outlined:last-child { margin-left: auto; }
.dashboard-empty { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; min-height: 140px; padding: 20px 8px; text-align: center; color: #7a8799; font-size: 12px; line-height: 1.7; }
.dashboard-empty > .material-symbols-outlined { font-size: 28px; color: #c3cddd; }
.dashboard-recent-list { margin-top: 12px; }
.dashboard-recent-row { display: grid; grid-template-columns: 36px minmax(0, 1fr) auto auto 14px; align-items: center; gap: 12px; padding: 12px 0; border-bottom: 1px solid #f0f3f8; }
.dashboard-recent-row:last-child { border-bottom: 0; padding-bottom: 0; }
.dashboard-recent-name { min-width: 0; }
.dashboard-recent-name strong, .dashboard-robot-row strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 600; }
.dashboard-recent-name small, .dashboard-robot-row small { display: block; margin-top: 4px; color: #7a8799; font-size: 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dashboard-recent-row time { color: #7a8799; font-size: 10px; white-space: nowrap; }
.dashboard-recent-row > .material-symbols-outlined, .dashboard-robot-row > .material-symbols-outlined { color: #a5b0c1; font-size: 16px; }
.dashboard-tag { display: inline-flex; align-items: center; justify-content: center; padding: 4px 7px; border-radius: 5px; font-size: 10px; font-weight: 600; color: var(--dashboard-accent); background: var(--dashboard-soft); white-space: nowrap; }
.dashboard-attention-row { display: flex; align-items: center; gap: 10px; width: 100%; margin-top: 14px; text-align: left; }
.dashboard-attention-row > span:nth-child(2) { min-width: 0; flex: 1; }
.dashboard-attention-row strong { display: block; font-size: 11px; font-weight: 600; line-height: 1.5; }
.dashboard-attention-row small { display: block; margin-top: 3px; color: #7a8799; font-size: 10px; line-height: 1.5; }
.dashboard-attention-row > b { font-size: 16px; color: #a66313; }
.dashboard-attention-row > .material-symbols-outlined { font-size: 15px; color: #a5b0c1; }
.dashboard-shortage-list { display: grid; gap: 10px; margin: 14px 0 0 46px; padding-left: 12px; border-left: 2px solid #f0f3f8; }
.dashboard-shortage-list a { display: flex; justify-content: space-between; gap: 12px; min-width: 0; font-size: 11px; }
.dashboard-shortage-list a > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #64748b; }
.dashboard-shortage-list small { flex-shrink: 0; font-size: 10px; color: #be4658; }
.dashboard-shortage-list .dashboard-inline-link { margin-top: 0; }
.dashboard-robot-row { display: flex; align-items: center; gap: 12px; margin-top: 16px; }
.dashboard-robot-row > div:first-child { height: 54px; width: 54px; border-radius: 9px; }
.dashboard-robot-row > span:nth-child(2) { flex: 1; min-width: 0; }
.dashboard-resources { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
.dashboard-resource { display: flex; align-items: center; gap: 10px; min-width: 0; padding: 14px 16px; background: white; border: 1px solid #e3e9f1; border-radius: 10px; font-size: 12px; color: #64748b; }
.dashboard-resource > .material-symbols-outlined { font-size: 19px; color: #8997b2; }
.dashboard-resource strong { margin-left: auto; font-size: 16px; color: #334155; }
.dashboard-resource > .material-symbols-outlined:last-child { font-size: 14px; }
.dashboard-shell a:hover strong, .dashboard-attention-row:hover strong { color: #3755c3; }
.dashboard-shell :is(a, button):focus-visible { outline: 2px solid #3755c3; outline-offset: 4px; border-radius: 6px; }
@media (max-width: 1200px) {
.dashboard-layout { grid-template-columns: minmax(0, 1fr); }
.dashboard-side-column { grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: start; }
.dashboard-metric { padding: 16px; }
.dashboard-metric-top { gap: 7px; font-size: 11px; }
}
@media (max-width: 600px) {
.dashboard-shell .dashboard-header { align-items: flex-start; gap: 12px; margin-bottom: 18px; }
.dashboard-actions { width: 100%; justify-content: space-between; gap: 8px; }
.dashboard-updated { font-size: 10px; }
.dashboard-refresh { min-height: 40px; }
.dashboard-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; margin-bottom: 14px; }
.dashboard-metric { padding: 12px; }
.dashboard-metric-top { flex-wrap: wrap; gap: 7px; font-size: 11px; }
.dashboard-metric-top > .material-symbols-outlined { display: none; }
.dashboard-metric .dashboard-icon { height: 28px; width: 28px; border-radius: 8px; }
.dashboard-metric .dashboard-icon .material-symbols-outlined { font-size: 17px; }
.dashboard-metric-value { font-size: 28px; margin-top: 12px; gap: 5px; }
.dashboard-metric-value > span { font-size: 10px; }
.dashboard-metric > p { min-height: 39px; margin-top: 9px; padding-top: 9px; font-size: 10px; }
.dashboard-stock-grid, .dashboard-side-column { grid-template-columns: minmax(0, 1fr); gap: 14px; }
.dashboard-layout, .dashboard-main-column { gap: 14px; }
.dashboard-panel { padding: 16px; }
.dashboard-recent-row { grid-template-columns: 32px minmax(0, 1fr) auto; gap: 8px; }
.dashboard-recent-row > .dashboard-icon { width: 32px; height: 32px; grid-row: span 2; }
.dashboard-recent-row time { grid-column: 2 / 4; }
.dashboard-recent-row > .material-symbols-outlined { display: none; }
.dashboard-resource { padding: 12px; gap: 7px; font-size: 11px; }
.dashboard-resource > .material-symbols-outlined:last-child { display: none; }
.dashboard-resources { gap: 10px; }
}

File diff suppressed because one or more lines are too long

View File

@@ -18,6 +18,122 @@ textarea {
-webkit-tap-highlight-color: transparent;
}
/* Compact navigation: only one branch is open, with native button keyboard support. */
.sidebar-nav {
padding: 0 0.75rem;
overscroll-behavior: contain;
scrollbar-width: thin;
}
.sidebar-menu,
.sidebar-children {
display: flex;
flex-direction: column;
list-style: none;
margin: 0;
padding: 0;
gap: 0.2rem;
}
.sidebar-link {
display: flex;
align-items: center;
gap: 0.625rem;
width: 100%;
min-height: 2.25rem;
padding: 0.4375rem 0.625rem;
border-radius: 0.375rem;
color: #475569;
font-size: 0.9375rem;
line-height: 1.25rem;
text-align: left;
transition: color 0.15s, background-color 0.15s;
}
.sidebar-link:hover {
background: #e2e8f0;
color: #0f172a;
}
.sidebar-link:focus-visible {
outline: 2px solid #3755c3;
outline-offset: 2px;
}
.sidebar-link .material-symbols-outlined {
flex-shrink: 0;
font-size: 1.125rem;
}
.sidebar-text {
flex: 1;
min-width: 0;
white-space: nowrap;
}
.sidebar-link[aria-current="page"] {
background: #e2e8f0;
color: #0f172a;
font-weight: 700;
}
.sidebar-group-toggle[data-active="true"] {
color: #0f172a;
font-weight: 700;
}
.sidebar-link .sidebar-chevron {
margin-left: auto;
font-size: 1rem;
transition: transform 0.15s;
}
.sidebar-group-toggle[aria-expanded="true"] .sidebar-chevron {
transform: rotate(90deg);
}
.sidebar-children {
margin: 0.25rem 0 0.375rem 1.375rem;
padding-left: 0.375rem;
border-left: 1px dashed #cbd5e1;
gap: 0.125rem;
}
.sidebar-children[hidden] {
display: none;
}
.sidebar-children .sidebar-link {
min-height: 2.125rem;
padding-top: 0.4375rem;
padding-bottom: 0.4375rem;
}
.sidebar-admin {
margin-top: 0.5rem;
padding-top: 0.5rem;
border-top: 1px solid #e2e8f0;
}
.dark .sidebar-link {
color: #94a3b8;
}
.dark .sidebar-link:hover,
.dark .sidebar-link[aria-current="page"] {
background: #1e293b;
color: #f8fafc;
}
.dark .sidebar-group-toggle[data-active="true"] {
color: #f8fafc;
}
.dark .sidebar-children,
.dark .sidebar-admin {
border-color: #334155;
}
.table-wrap,
.overflow-x-auto {
overscroll-behavior-x: contain;
@@ -37,6 +153,50 @@ textarea {
z-index: 0;
}
/* Keep project export decisions and saved files accessible in wide tables. */
.asset-exports-page table {
border-collapse: separate;
border-spacing: 0;
}
.asset-exports-page th,
.asset-exports-page td {
overflow-wrap: anywhere;
}
@media (min-width: 901px) {
.asset-exports-page thead th {
position: sticky;
top: 0;
z-index: 2;
background: #f8fafc;
}
.asset-exports-page tbody td:last-child {
position: sticky;
right: 0;
z-index: 1;
min-width: 190px;
background: #fff;
border-left: 1px solid #e2e8f0;
box-shadow: -6px 0 12px -10px rgb(15 23 42 / 0.3);
}
.asset-exports-page thead th:last-child {
right: 0;
z-index: 3;
}
}
.asset-export-history-file-actions {
flex-wrap: nowrap;
}
.asset-export-history-file-actions > button {
flex: 0 0 auto;
white-space: nowrap;
}
@media (max-width: 900px) {
body.app-shell,
#appMain,

229
public/css/robot-bom.css Normal file
View File

@@ -0,0 +1,229 @@
.bom-page { height:100%; overflow-y:auto; padding:24px; color:#2a3439; background:#f7f9fb; font-size:14px; }
.bom-page h1,.bom-page h2,.bom-page h3,.bom-dialog h2,.bom-dialog h3 { font-family:Manrope,Inter,sans-serif; margin:0; font-weight:800; }
.bom-page h1 { font-size:28px; line-height:1.25; margin-bottom:6px; }
.bom-page h2,.bom-dialog h3 { font-size:17px; }
.bom-page-header { display:flex; align-items:center; justify-content:space-between; gap:20px; margin-bottom:22px; flex-wrap:wrap; }
.bom-eyebrow { font-size:10px; letter-spacing:.1em; font-weight:700; color:#64748b; margin:0 0 5px; }
.bom-muted { color:#64748b; font-size:13px; }
.bom-toolbar,.bom-identity-actions { display:flex; flex-wrap:wrap; gap:8px; }
.bom-btn { display:inline-flex; align-items:center; justify-content:center; gap:6px; border:1px solid #d5deea; border-radius:7px; background:white; color:#334155; padding:9px 12px; font-size:12px; font-weight:700; line-height:1.4; white-space:nowrap; cursor:pointer; }
.bom-btn:hover:not(:disabled) { background:#edf2ff; border-color:#a9b8e9; color:#3755c3; }
.bom-btn:disabled { opacity:.45; cursor:default; }
.bom-btn-primary { color:white; background:#3755c3; border-color:#3755c3; }
.bom-btn-primary:hover:not(:disabled) { color:white; background:#2848b7; }
.bom-btn .material-symbols-outlined { font-size:18px; }
.bom-identity { display:flex; align-items:center; gap:18px; flex-wrap:wrap; padding:18px; background:white; border:1px solid #e2e8f0; border-radius:10px; }
.bom-robot-icon { display:flex; align-items:center; justify-content:center; width:64px; height:64px; border-radius:12px; background:#edf2ff; color:#3755c3; font-size:36px; flex-shrink:0; }
.bom-model-field { flex:1; min-width:180px; }
.bom-model-field label,.bom-version-field label { display:block; color:#64748b; font-size:11px; font-weight:600; margin-bottom:5px; }
.bom-model-field select { width:100%; max-width:360px; font-weight:700; }
.bom-model-field small { display:block; margin-top:5px; color:#64748b; font-size:11px; }
.bom-version-field { min-width:170px; }
.bom-page select,.bom-page input:not([type=file]),.bom-dialog select,.bom-dialog input:not([type=radio]),.bom-dialog textarea { border:1px solid #d7e0eb; border-radius:6px; background:white; font-size:13px; color:#334155; padding:9px 11px; min-height:38px; }
.bom-page input:focus,.bom-page select:focus,.bom-dialog input:focus,.bom-dialog textarea:focus { outline:2px solid #b9c7ff; outline-offset:1px; border-color:#3755c3; }
.bom-badge { display:inline-flex; align-items:center; white-space:nowrap; color:#b45309; background:#fffbeb; border:1px solid #fde68a; border-radius:5px; padding:5px 8px; font-size:11px; font-weight:700; }
.bom-badge-green { color:#15803d; background:#f0fdf4; border-color:#bbf7d0; }
.bom-tabs { display:flex; gap:16px; margin:15px 0 18px; border-bottom:1px solid #e2e8f0; overflow-x:auto; }
.bom-tabs button { padding:13px 8px; color:#64748b; font-size:13px; font-weight:600; white-space:nowrap; border-bottom:2px solid transparent; }
.bom-tabs button[aria-current=page] { color:#3755c3; border-bottom-color:#3755c3; }
.bom-workspace { display:grid; grid-template-columns:minmax(0,1fr) 335px; gap:16px; align-items:start; }
.bom-card { background:white; border:1px solid #e2e8f0; border-radius:9px; min-width:0; overflow:hidden; }
.bom-main-card { padding:18px; }
.bom-card-heading { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:18px; }
.bom-main-card>.bom-card-heading { padding:0 0 14px; }
.bom-count { display:inline-block; font-size:11px; font-weight:500; color:#64748b; background:#f1f5f9; padding:3px 6px; border-radius:5px; vertical-align:middle; }
.bom-filters { display:flex; gap:10px; margin-bottom:14px; }
.bom-search { display:flex; align-items:center; position:relative; flex:1; min-width:100px; }
.bom-search>.material-symbols-outlined { position:absolute; left:11px; color:#94a3b8; font-size:19px; pointer-events:none; }
.bom-search input { width:100%; padding-left:36px!important; }
.bom-filters select { max-width:190px; }
.bom-table-scroll { overflow-x:auto; width:100%; }
.bom-lines-table,.bom-stock-table,.bom-picker-table { width:100%; border-collapse:collapse; font-size:12px; text-align:left; }
.bom-lines-table th,.bom-stock-table th,.bom-picker-table th { font-weight:600; background:#f1f5f9; color:#475569; padding:11px 10px; white-space:nowrap; border:1px solid #e2e8f0; }
.bom-lines-table td,.bom-stock-table td,.bom-picker-table td { padding:12px 10px; border:1px solid #e2e8f0; vertical-align:middle; }
.bom-lines-table strong,.bom-stock-table strong,.bom-picker-table strong { display:block; font-weight:600; }
.bom-lines-table small,.bom-stock-table small,.bom-picker-table small,.bom-selected-summary small { display:block; color:#64748b; font-size:10px; margin-top:3px; line-height:1.45; }
.bom-lines-table td:first-child { min-width:155px; }
.bom-lines-table td:nth-child(2) { min-width:95px; }
.bom-lines-table td:nth-child(5) { min-width:140px; max-width:230px; overflow-wrap:anywhere; }
.bom-group th { background:#eef3f8; font-size:11px; text-transform:uppercase; color:#334155; padding:10px; }
.bom-group .material-symbols-outlined { font-size:17px; margin-right:7px; vertical-align:middle; }
.bom-group small { display:inline; margin-left:10px; font-weight:400; font-size:10px; text-transform:none; color:#64748b; }
.bom-page input.bom-quantity { width:76px; min-height:32px; padding:5px 6px; }
.bom-row-actions { white-space:nowrap; }
.bom-row-actions button { padding:4px; color:#64748b; }
.bom-row-actions button:hover { color:#3755c3; background:#eff6ff; border-radius:4px; }
.bom-row-actions button[data-bom-delete]:hover { color:#dc2626; background:#fef2f2; }
.bom-row-actions .material-symbols-outlined { font-size:17px; }
.bom-stock-card { padding:18px; }
.bom-stock-card>.bom-card-heading { padding:0 0 18px; }
.bom-count-field { display:flex; align-items:center; justify-content:space-between; gap:12px; font-size:12px; }
.bom-count-field input { width:100px; }
.bom-footnote { color:#64748b; font-size:11px; margin:14px 0; line-height:1.6; }
.bom-stock-card>.bom-btn { margin-bottom:14px; }
.bom-stock-table { font-size:11px; }
.bom-stock-table th,.bom-stock-table td { padding:9px 7px; }
.bom-stock-table td:not(:first-child),.bom-stock-table th:not(:first-child) { text-align:right; }
.bom-stock-table td:first-child { max-width:180px; overflow-wrap:anywhere; }
.bom-shortage td { background:#fff7ed; }
.bom-danger { color:#c2410c!important; }
.bom-success { color:#15803d; font-weight:600; }
.bom-stock-result { display:flex; align-items:center; gap:9px; padding:12px; border-radius:7px; margin-top:16px; font-size:12px; }
.bom-stock-result small { display:block; margin-top:3px; font-size:11px; }
.bom-stock-warning { background:#fff7ed; border:1px solid #fed7aa; color:#c2410c; }
.bom-stock-ok { background:#f0fdf4; border:1px solid #bbf7d0; color:#15803d; }
.bom-stock-message { padding:20px 0; }
.bom-empty { display:flex; flex-direction:column; align-items:center; justify-content:center; text-align:center; padding:52px 20px; gap:12px; color:#64748b; }
.bom-empty>.material-symbols-outlined { font-size:36px; color:#94a3b8; }
.bom-empty>strong { color:#334155; font-size:16px; }
.bom-empty p { font-size:13px; margin:0; }
.bom-empty a { color:#3755c3; }
.bom-identity+.bom-empty { margin-top:18px; }
.bom-alert { border:1px solid #fecaca; color:#b91c1c; background:#fef2f2; border-radius:7px; padding:12px; font-size:13px; margin-bottom:16px; }
.bom-sr { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }
.bom-dialog { margin:auto; width:min(1120px,95vw); max-width:none; max-height:92dvh; overflow-y:auto; border:0; border-radius:10px; padding:0; background:white; color:#2a3439; box-shadow:0 24px 80px #0f172a33; }
.bom-dialog::backdrop { background:#0f172a66; }
.bom-dialog-header { display:flex; justify-content:space-between; align-items:flex-start; gap:16px; padding:20px; border-bottom:1px solid #e2e8f0; }
.bom-dialog-header h2 { font-size:20px; }
.bom-dialog-header p { font-size:12px; color:#64748b; margin:5px 0 0; }
.bom-dialog-header>button { padding:3px; color:#64748b; }
.bom-picker-layout { display:grid; grid-template-columns:minmax(0,1.8fr) minmax(280px,1fr); }
.bom-picker-catalog { padding:20px; min-width:0; }
.bom-picker-tools { display:flex; gap:14px; flex-wrap:wrap; }
.bom-source-tabs { display:flex; gap:5px; }
.bom-source-tabs button { padding:9px 12px; border:1px solid #e2e8f0; border-radius:6px; background:white; font-size:12px; font-weight:600; }
.bom-source-tabs button[aria-pressed=true] { background:#3755c3; border-color:#3755c3; color:white; }
.bom-picker-table-wrap { max-height:410px; overflow:auto; }
.bom-picker-table th { position:sticky; top:0; z-index:1; }
.bom-picker-table td { padding:12px 8px; }
.bom-picker-table td:first-child { width:35px; }
.bom-picker-table td:nth-child(2) { min-width:130px; }
.bom-picker-table label { cursor:pointer; }
.bom-picked-row td { background:#edf3ff; }
.bom-picker-pagination { display:flex; align-items:center; justify-content:space-between; gap:10px; color:#64748b; font-size:11px; margin-top:16px; }
.bom-picker-pagination>div { display:flex; gap:5px; }
.bom-picker-settings { border-left:1px solid #e2e8f0; padding:20px; }
.bom-picker-settings>label { display:block; font-size:12px; font-weight:600; margin-top:15px; }
.bom-picker-settings label>input,.bom-picker-settings label>textarea { display:block; width:100%; margin-top:6px; font-weight:400; }
.bom-selected-summary { padding:12px; background:#f1f5f9; border-radius:7px; font-size:13px; margin-top:12px; }
.bom-quantity-unit { display:flex; margin-top:6px; }
.bom-quantity-unit input { width:100%; min-width:0; border-radius:6px 0 0 6px!important; font-weight:400; }
.bom-quantity-unit>span { display:flex; align-items:center; padding:0 12px; background:#f1f5f9; border:1px solid #d7e0eb; border-left:0; border-radius:0 6px 6px 0; font-size:12px; }
.bom-info { display:flex; gap:9px; background:#eff6ff; border-radius:7px; padding:12px; margin-top:20px; font-size:11px; color:#3755c3; }
.bom-info p { color:#64748b; margin:4px 0 0; font-size:11px; }
.bom-dialog-footer { display:flex; align-items:center; justify-content:space-between; gap:14px; padding:18px 20px; border-top:1px solid #e2e8f0; background:#fdfefe; }
.bom-dialog-footer>div { display:flex; flex-wrap:wrap; gap:8px; }
@media(min-width:1700px) { .bom-workspace { grid-template-columns:minmax(0,1fr) 390px; } }
@media(max-width:1250px) { .bom-workspace { grid-template-columns:minmax(0,1fr); } .bom-stock-card { max-width:none; } .bom-identity-actions { width:100%; } }
@media(max-width:760px) { .bom-page { padding:16px; } .bom-page h1 { font-size:24px; } .bom-identity { gap:12px; padding:14px; } .bom-robot-icon { width:45px; height:45px; font-size:28px; } .bom-version-field { min-width:150px; flex:1; } .bom-filters { flex-wrap:wrap; } .bom-filters select { width:100%; max-width:none; } .bom-main-card,.bom-stock-card { padding:14px; } .bom-card-heading h2 { font-size:15px; } .bom-picker-layout { grid-template-columns:minmax(0,1fr); } .bom-picker-settings { border-left:0; border-top:1px solid #e2e8f0; } .bom-picker-table-wrap { max-height:260px; } .bom-picker-pagination { flex-wrap:wrap; } .bom-dialog-footer { flex-wrap:wrap; } .bom-dialog-footer>div { width:100%; justify-content:flex-end; } .bom-tabs { gap:8px; } .bom-tabs button { font-size:12px; } .bom-picker-tools>.bom-search { min-width:100%; } }
.bom-lines-table td:first-child { min-width:0; width:48px; color:#64748b; }
.bom-lines-table td:nth-child(2) { min-width:180px; }
.bom-lines-table td:nth-child(3) { min-width:110px; }
.bom-lines-table td:nth-child(5) { min-width:180px; max-width:300px; }
.bom-lines-table .bom-quantity-unit { margin:0; align-items:center; gap:7px; }
.bom-lines-table .bom-quantity-unit input { width:76px; border-radius:6px!important; }
.bom-lines-table .bom-quantity-unit small { margin:0; white-space:nowrap; }
.bom-notes,.bom-source-cell { overflow-wrap:anywhere; white-space:pre-wrap; }
.bom-source-link { color:#3755c3; text-decoration:underline; text-underline-offset:3px; }
.bom-source-link:hover { color:#2848b7; }
.bom-history-table { width:100%; border-collapse:collapse; font-size:12px; text-align:left; }
.bom-history-table th,.bom-history-table td { border:1px solid #e2e8f0; padding:12px 10px; white-space:nowrap; }
.bom-history-table th { background:#f1f5f9; color:#475569; font-weight:600; }
.bom-dialog { width:min(620px,95vw); }
.bom-entry-tabs { display:flex; flex-wrap:wrap; gap:8px; padding:16px 20px; border-bottom:1px solid #e2e8f0; }
.bom-entry-tabs button { border:1px solid #e2e8f0; padding:9px 12px; border-radius:6px; font-size:12px; font-weight:600; }
.bom-entry-tabs button[aria-pressed=true] { background:#3755c3; color:white; border-color:#3755c3; }
.bom-material-layout { display:grid; grid-template-columns:minmax(0,1fr); }
.bom-asset-picker { padding:20px; border-right:1px solid #e2e8f0; min-width:0; }
.bom-asset-picker[hidden] { display:none; }
.bom-asset-table-wrap { max-height:410px; overflow:auto; }
.bom-asset-table { width:100%; border-collapse:collapse; font-size:12px; text-align:left; }
.bom-asset-table th,.bom-asset-table td { border:1px solid #e2e8f0; padding:11px 9px; }
.bom-asset-table th { background:#f1f5f9; position:sticky; top:0; color:#475569; font-weight:600; }
.bom-asset-table tbody tr { cursor:pointer; }
.bom-asset-table tbody tr:hover { background:#f7f9fb; }
.bom-asset-table strong,.bom-asset-table small { display:block; }
.bom-asset-table small { font-size:10px; color:#64748b; margin-top:4px; }
.bom-material-fields { padding:20px; min-width:0; }
.bom-material-fields label { display:block; font-size:12px; font-weight:600; margin-bottom:16px; }
.bom-material-fields label:last-child { margin-bottom:0; }
.bom-material-fields label>input,.bom-material-fields label>textarea { display:block; width:100%; margin-top:6px; font-weight:400; }
.bom-form-grid { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:16px; }
.bom-optional { font-size:11px; color:#94a3b8; font-weight:400; }
.bom-dialog-footer { justify-content:flex-end; }
/* Both entry modes share one fixed frame and the same form column. */
.bom-entry-dialog { width:min(1100px,95vw); height:min(790px,calc(100dvh - 48px)); max-height:calc(100dvh - 48px); overflow:hidden; }
.bom-entry-dialog[open] { display:flex; }
.bom-entry-dialog>form { display:flex; flex-direction:column; width:100%; height:100%; min-height:0; }
.bom-entry-dialog .bom-dialog-header,.bom-entry-dialog .bom-entry-tabs,.bom-entry-dialog .bom-dialog-footer { flex-shrink:0; }
.bom-entry-dialog .bom-material-layout { flex:1; min-height:0; grid-template-columns:minmax(0,1fr) minmax(360px,1.1fr); overflow:hidden; }
.bom-entry-context { min-width:0; min-height:0; display:grid; grid-template-columns:minmax(0,1fr); border-right:1px solid #e2e8f0; background:#f8fafc; }
.bom-entry-dialog .bom-asset-picker { display:flex; flex-direction:column; min-height:0; border:0; }
.bom-entry-dialog .bom-asset-picker[hidden],.bom-external-guide[hidden] { display:none; }
.bom-entry-dialog .bom-asset-picker>.bom-search { flex:0 0 auto; }
.bom-entry-dialog #bomAssetResults { display:flex; flex:1; flex-direction:column; min-height:0; }
.bom-entry-dialog #bomAssetResults>.bom-footnote { flex-shrink:0; margin-bottom:0; }
.bom-entry-dialog .bom-asset-table-wrap { flex:1; min-height:0; max-height:none; scrollbar-gutter:stable; }
.bom-entry-dialog .bom-material-fields { min-height:0; overflow-y:auto; overscroll-behavior:contain; scrollbar-gutter:stable; padding:22px 24px; }
.bom-entry-dialog .bom-material-fields textarea { min-height:66px; max-height:150px; }
.bom-entry-dialog .bom-dialog-footer { justify-content:space-between; }
.bom-entry-save-hint { max-width:360px; font-size:11px; line-height:1.6; color:#64748b; margin:0; }
.bom-external-guide { padding:28px; overflow-y:auto; scrollbar-gutter:stable; }
.bom-external-icon { display:flex; align-items:center; justify-content:center; width:52px; height:52px; border-radius:12px; color:#3755c3; background:#e8edff; font-size:28px; margin-bottom:18px; }
.bom-external-guide h3 { font-size:19px; margin-bottom:9px; }
.bom-external-guide>p { font-size:13px; line-height:1.7; color:#64748b; margin:0; }
.bom-external-guide ul { display:flex; flex-direction:column; gap:22px; list-style:none; padding:0; margin:28px 0; }
.bom-external-guide li { display:flex; gap:12px; font-size:13px; }
.bom-external-guide li>.material-symbols-outlined { color:#3755c3; font-size:20px; margin-top:1px; }
.bom-external-guide li strong { font-weight:600; }
.bom-external-guide li small { display:block; color:#64748b; margin-top:5px; font-size:12px; line-height:1.6; }
.bom-external-guide p.bom-external-note { border-top:1px solid #e2e8f0; padding-top:18px; font-size:11px; }
.bom-confirm-dialog { width:min(520px,95vw); }
.bom-confirm-heading { display:flex; align-items:center; gap:13px; }
.bom-confirm-heading .bom-eyebrow { margin-bottom:4px; }
.bom-confirm-icon { display:flex; align-items:center; justify-content:center; flex-shrink:0; width:44px; height:44px; border-radius:12px; background:#e8edff; color:#3755c3; font-size:25px; }
.bom-confirm-body { padding:20px 24px 24px; }
.bom-confirm-body>p { font-size:13px; line-height:1.7; color:#64748b; margin:0 0 18px; }
.bom-publish-summary { display:grid; grid-template-columns:2fr 1fr 1.3fr; gap:16px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:16px; margin:0 0 18px; }
.bom-publish-summary div { min-width:0; }
.bom-publish-summary dt { color:#64748b; font-size:11px; margin-bottom:6px; }
.bom-publish-summary dd { margin:0; font-size:13px; font-weight:700; overflow-wrap:anywhere; }
.bom-publish-note { display:flex; gap:9px; color:#3755c3; border-radius:7px; background:#eff3ff; padding:12px; }
.bom-publish-note>.material-symbols-outlined { font-size:18px; flex-shrink:0; margin-top:1px; }
.bom-publish-note p { font-size:12px; line-height:1.7; margin:0; }
.bom-confirm-body>p.bom-footnote { margin:14px 0 0; font-size:11px; }
.bom-btn:focus-visible { outline:2px solid #3755c3; outline-offset:3px; }
.robot-delete-dialog .bom-confirm-icon,.bom-delete-dialog .bom-confirm-icon { color:#dc2626; background:#fef2f2; }
.bom-btn.bom-btn-delete { color:#dc2626; border-color:#fecaca; }
.bom-btn.bom-btn-delete:hover:not(:disabled) { color:#b91c1c; background:#fef2f2; border-color:#fca5a5; }
.robot-delete-card { background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:16px; margin:0 0 18px; }
.robot-delete-name { display:block; font-size:16px; font-weight:700; overflow-wrap:anywhere; }
.robot-delete-details { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:16px; margin:16px 0 0; }
.robot-delete-details dt { color:#64748b; font-size:11px; margin-bottom:5px; }
.robot-delete-details dd { margin:0; font-size:13px; font-weight:600; overflow-wrap:anywhere; }
.bom-btn.bom-btn-danger { color:white; background:#dc2626; border-color:#dc2626; }
.bom-btn.bom-btn-danger:hover:not(:disabled) { color:white; background:#b91c1c; border-color:#b91c1c; }
.bom-btn.bom-btn-danger:focus-visible { outline-color:#dc2626; }
@media(max-width:760px) {
.bom-entry-dialog { width:calc(100vw - 24px); height:calc(100dvh - 32px); max-height:calc(100dvh - 32px); }
.bom-entry-dialog .bom-material-layout { display:flex; flex-direction:column; overflow-y:auto; overscroll-behavior:contain; }
.bom-entry-context { flex:0 0 200px; height:200px; border-right:0; border-bottom:1px solid #e2e8f0; }
.bom-entry-dialog .bom-material-fields { flex-shrink:0; overflow:visible; padding:16px; }
.bom-entry-dialog .bom-asset-picker { padding:14px 16px; overflow:hidden; }
.bom-entry-dialog .bom-asset-picker>.bom-footnote { margin:8px 0; font-size:10px; }
.bom-entry-tabs { padding:12px 16px; }
.bom-entry-tabs button { padding:9px 10px; font-size:11px; }
.bom-external-guide { padding:18px; }
.bom-external-icon { width:36px; height:36px; font-size:22px; margin-bottom:12px; }
.bom-external-guide h3 { font-size:17px; }
.bom-external-guide>p { font-size:12px; }
.bom-external-guide ul,.bom-external-guide .bom-external-note { display:none; }
.bom-entry-save-hint { max-width:none; font-size:10px; }
.bom-entry-dialog .bom-dialog-footer { gap:10px; padding:12px 16px; }
.bom-entry-dialog .bom-dialog-footer>div { width:100%; justify-content:flex-end; gap:6px; }
.bom-entry-dialog .bom-dialog-footer .bom-btn { padding:8px 10px; font-size:11px; }
.bom-confirm-body { padding:18px; }
.bom-publish-summary { gap:10px; padding:12px; }
.bom-confirm-dialog .bom-dialog-header { padding:18px; }
.bom-confirm-dialog .bom-dialog-header h2 { font-size:17px; }
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,26 @@
(function () {
const formats = {
'.pdf': { mimeType: 'application/pdf', label: 'PDF', icon: 'picture_as_pdf', tone: 'red', preview: true },
'.doc': { mimeType: 'application/msword', label: 'Word', icon: 'description', tone: 'blue' },
'.docx': { mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', label: 'Word', icon: 'description', tone: 'blue' },
'.xls': { mimeType: 'application/vnd.ms-excel', label: 'Excel', icon: 'table_chart', tone: 'green' },
'.xlsx': { mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', label: 'Excel', icon: 'table_chart', tone: 'green' },
'.ppt': { mimeType: 'application/vnd.ms-powerpoint', label: 'PowerPoint', icon: 'slideshow', tone: 'orange' },
'.pptx': { mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', label: 'PowerPoint', icon: 'slideshow', tone: 'orange' },
'.jpg': { mimeType: 'image/jpeg', label: 'Ảnh', icon: 'image', tone: 'purple', preview: true },
'.jpeg': { mimeType: 'image/jpeg', label: 'Ảnh', icon: 'image', tone: 'purple', preview: true },
'.png': { mimeType: 'image/png', label: 'Ảnh', icon: 'image', tone: 'purple', preview: true },
'.gif': { mimeType: 'image/gif', label: 'Ảnh', icon: 'image', tone: 'purple', preview: true },
'.webp': { mimeType: 'image/webp', label: 'Ảnh', icon: 'image', tone: 'purple', preview: true },
'.bmp': { mimeType: 'image/bmp', label: 'Ảnh', icon: 'image', tone: 'purple', preview: true },
'.tif': { mimeType: 'image/tiff', label: 'Ảnh TIFF', icon: 'image', tone: 'purple' },
'.tiff': { mimeType: 'image/tiff', label: 'Ảnh TIFF', icon: 'image', tone: 'purple' },
'.txt': { mimeType: 'text/plain', label: 'Văn bản', icon: 'text_snippet', tone: 'slate', preview: true },
'.csv': { mimeType: 'text/csv', label: 'CSV', icon: 'table_chart', tone: 'green' },
'.rtf': { mimeType: 'application/rtf', label: 'RTF', icon: 'description', tone: 'blue' },
'.zip': { mimeType: 'application/zip', label: 'ZIP', icon: 'folder_zip', tone: 'slate' }
};
const config = { formats, accept: Object.keys(formats).join(','), description: 'PDF, Word, Excel, PowerPoint, ảnh, TXT, CSV, RTF, ZIP' };
if (typeof module !== 'undefined' && module.exports) module.exports = config;
if (typeof window !== 'undefined') window.DocumentFormats = config;
}());

288
public/js/robot-bom.js Normal file
View File

@@ -0,0 +1,288 @@
/* Descriptive robot BOM: asset names/models may be copied; BOM quantities are entered independently. */
(() => {
'use strict';
const modelKey = item => JSON.stringify([Number(item.TypeId), item.Model]);
const number = value => Number(value || 0).toLocaleString('vi-VN', { maximumFractionDigits: 4 });
const fractionalUnit = unit => !String(unit).trim() || /^(m|m2|m²|m3|m³|mét|met|kg|g|gam|l|lít|lit|ml|mm|cm|tấn|tan)$/i.test(String(unit).trim());
class RobotBomController {
constructor(app) {
this.app = app; this.models = []; this.revisions = []; this.lines = [];
this.header = null; this.modelId = ''; this.dirty = false; this.busy = false;
this.query = ''; this.tab = 'bom';
this.beforeUnload = event => { if (this.dirty) { event.preventDefault(); event.returnValue = ''; } };
}
escape(value) { return this.app.escapeHtml(String(value ?? '')); }
canManage() { return this.app.canCurrentUserManageAssets(); }
editable() { return this.canManage() && this.header?.Status === 'draft'; }
active() { return this.app.currentPage === 'robot-bom'; }
async api(suffix, options = {}) {
const response = await fetch(`${this.app.apiBase}/robot-boms${suffix}`, { cache: 'no-store', ...options,
headers: { ...(options.body ? { 'Content-Type': 'application/json' } : {}), ...options.headers } });
const result = await response.json();
if (!response.ok || !result.success) throw new Error(result.message || 'Không thể tải dữ liệu BOM');
return result.data;
}
async mount(root, preferredModel) {
this.root = root; this.busy = true; this.error = ''; this.dirty = false;
window.addEventListener('beforeunload', this.beforeUnload); this.render();
try {
this.models = await this.api('/models');
const selected = this.models.find(item => preferredModel && typeof preferredModel === 'object'
? item.Model === preferredModel.Model && item.TypeId === preferredModel.TypeId : item.Model === preferredModel)
|| this.models.find(item => modelKey(item) === this.modelId) || this.models[0];
this.modelId = selected ? modelKey(selected) : ''; await this.loadModel();
} catch (error) { this.error = error.message; }
finally { this.busy = false; this.render(); }
}
unmount() {
window.removeEventListener('beforeunload', this.beforeUnload);
document.getElementById('bomComponentDialog')?.close();
document.getElementById('bomPublishDialog')?.close();
document.getElementById('bomDeleteDialog')?.close();
}
selectedModel() { return this.models.find(item => modelKey(item) === this.modelId); }
async loadModel(preferredId) {
const model = this.selectedModel();
this.header = null; this.lines = []; this.revisions = []; this.dirty = false; this.query = ''; this.error = '';
if (!model) return;
this.revisions = await this.api(`?model=${encodeURIComponent(model.Model)}&typeId=${model.TypeId}`);
const revision = this.revisions.find(item => Number(item.BomId) === Number(preferredId)) || this.revisions[0];
if (revision) await this.loadRevision(revision.BomId);
}
async loadRevision(id) { const data = await this.api(`/${Number(id)}`); this.header = data; this.lines = data.Lines || []; this.dirty = false; }
async run(action) {
if (this.busy) return; this.busy = true; this.render();
try { await action(); } catch (error) { this.app.notifyFailure(error.message); }
finally { this.busy = false; this.render(); }
}
discardChanges() { return !this.dirty || window.confirm('BOM có thay đổi chưa lưu. Bỏ các thay đổi này?'); }
payload() {
return this.lines.map(line => ({ name: line.Name, model: line.Model || '', quantity: line.Quantity ?? 1, unit: line.Unit || '',
sourceInfo: line.SourceInfo || '', notes: line.Notes || '', code: line.Code || '', groupName: line.GroupName || '', position: line.Position || '' }));
}
validateLine(line) {
if (typeof line.Name !== 'string' || !line.Name.trim() || line.Name.trim().length > 255) throw new Error('Nhập tên tài sản / vật tư, tối đa 255 ký tự.');
const value = line.Quantity ?? 1;
if (!/^\d+(\.\d{1,4})?$/.test(String(value)) || Number(value) <= 0 || Number(value) > 100000) throw new Error('Số lượng phải lớn hơn 0, tối đa 100.000 và không quá 4 chữ số thập phân.');
if (!fractionalUnit(line.Unit || '') && !Number.isInteger(Number(value))) throw new Error(`Đơn vị ${line.Unit} yêu cầu số lượng nguyên.`);
if ((line.Model || '').length > 255 || (line.Unit || '').length > 50 || (line.Notes || '').length > 500 || (line.SourceInfo || '').length > 1000) throw new Error('Model tối đa 255, đơn vị 50, ghi chú 500 và nguồn 1.000 ký tự.');
}
validateLines(lines) { if (lines.length > 500) throw new Error('BOM tối đa 500 dòng vật tư.'); lines.forEach(line => this.validateLine(line)); }
async persistDraft() {
this.validateLines(this.lines);
const saved = await this.api(`/${this.header.BomId}`, { method: 'PUT', body: JSON.stringify({ lockVersion: this.header.LockVersion, lines: this.payload() }) });
this.header.LockVersion = saved.LockVersion; this.lines = saved.Lines; this.dirty = false;
this.header.UpdatedDate = saved.UpdatedDate || this.header.UpdatedDate;
const revision = this.revisions.find(item => item.BomId === this.header.BomId);
if (revision) { revision.LineCount = this.lines.length; revision.LockVersion = saved.LockVersion; revision.UpdatedDate = this.header.UpdatedDate; }
}
changed() { this.dirty = true; this.render(); }
button(action, label, icon, primary = false, disabled = false) {
return `<button type="button" data-bom-action="${action}" class="bom-btn ${primary ? 'bom-btn-primary' : ''} ${action === 'delete' ? 'bom-btn-delete' : ''}" ${disabled || this.busy ? 'disabled' : ''}>${icon ? `<span class="material-symbols-outlined" aria-hidden="true">${icon}</span>` : ''}${label}</button>`;
}
sourceHtml(value) {
if (!value) return '<span class="bom-muted">—</span>';
try {
const url = new URL(value);
if (['https:', 'http:'].includes(url.protocol)) return `<a class="bom-source-link" href="${this.escape(url.href)}" target="_blank" rel="noopener noreferrer">${this.escape(value)}</a>`;
} catch {}
return `<span class="bom-source-text">${this.escape(value)}</span>`;
}
tableHtml() {
const keyword = this.query.trim().toLocaleLowerCase('vi');
const rows = this.lines.map((line, index) => ({ line, index })).filter(({ line }) => !keyword || [line.Name, line.Code, line.Model, line.SourceInfo, line.Notes].some(value => String(value || '').toLocaleLowerCase('vi').includes(keyword)));
if (!rows.length) return `<div class="bom-empty"><span class="material-symbols-outlined">view_list</span><strong>${this.lines.length ? 'Không tìm thấy vật tư phù hợp' : 'Chưa có thành phần trong BOM'}</strong><p>${this.lines.length ? 'Thử từ khóa khác.' : 'Thêm tài sản sẵn có hoặc nhập vật tư từ bên ngoài.'}</p></div>`;
const edit = this.editable() && !this.busy;
return `<div class="bom-table-scroll"><table class="bom-lines-table"><thead><tr><th>STT</th><th>Tên tài sản / Vật tư</th><th>Model</th><th>Số lượng</th><th>Nguồn</th><th>Ghi chú</th>${this.canManage() ? '<th><span class="bom-sr">Thao tác</span></th>' : ''}</tr></thead><tbody>${rows.map(({ line, index }) => `<tr><td>${index + 1}</td><td><strong>${this.escape(line.Name)}</strong>${line.Code ? `<small>${this.escape(line.Code)}</small>` : ''}</td><td>${this.escape(line.Model || '—')}</td><td><div class="bom-quantity-unit">${edit ? `<input class="bom-quantity" type="number" data-bom-quantity="${index}" min="${fractionalUnit(line.Unit || '') ? '0.0001' : '1'}" max="100000" step="${fractionalUnit(line.Unit || '') ? '0.0001' : '1'}" value="${Number(line.Quantity ?? 1)}" aria-label="Số lượng ${this.escape(line.Name)}">` : number(line.Quantity ?? 1)}${line.Unit ? `<small>${this.escape(line.Unit)}</small>` : ''}</div></td><td class="bom-source-cell">${this.sourceHtml(line.SourceInfo)}</td><td class="bom-notes">${this.escape(line.Notes || '—')}</td>${this.canManage() ? `<td class="bom-row-actions">${edit ? `<button type="button" data-bom-edit="${index}" aria-label="Sửa ${this.escape(line.Name)}"><span class="material-symbols-outlined">edit</span></button><button type="button" data-bom-delete="${index}" aria-label="Xóa ${this.escape(line.Name)}"><span class="material-symbols-outlined">delete</span></button>` : '—'}</td>` : ''}</tr>`).join('')}</tbody></table></div>`;
}
historyHtml() {
return `<div class="bom-table-scroll"><table class="bom-history-table"><thead><tr><th>Phiên bản</th><th>Trạng thái</th><th>Số dòng</th><th>Cập nhật</th><th>Phát hành</th><th></th></tr></thead><tbody>${this.revisions.map(revision => `<tr><td><strong>v${Number(revision.Revision)}</strong></td><td><span class="bom-badge ${revision.Status === 'released' ? 'bom-badge-green' : ''}">${revision.Status === 'released' ? 'Đã phát hành' : 'Bản nháp'}</span></td><td>${number(revision.LineCount)}</td><td>${this.escape(this.app.formatDateTime(revision.UpdatedDate))}</td><td>${revision.ReleasedDate ? this.escape(this.app.formatDateTime(revision.ReleasedDate)) : '—'}</td><td><button class="bom-btn" data-bom-open="${Number(revision.BomId)}" ${this.busy ? 'disabled' : ''}>Xem BOM</button></td></tr>`).join('')}</tbody></table></div>`;
}
render() {
if (!this.active()) return;
const model = this.selectedModel(); const disabled = this.busy ? 'disabled' : ''; const edit = this.editable();
this.root.innerHTML = `<section class="bom-page" data-bom-page><header class="bom-page-header"><div><p class="bom-eyebrow">THÀNH PHẦN ROBOT</p><h1>BOM robot</h1><p class="bom-muted">Danh sách tài sản và vật tư cấu tạo của robot.</p></div><div class="bom-toolbar">${this.button('refresh', 'Làm mới', 'refresh')}${this.canManage() ? this.button('import', 'Nhập Excel', 'upload', false, !edit) : ''}${this.button('export', 'Xuất Excel', 'download', false, !this.header)}${this.canManage() ? this.button('save', this.dirty ? 'Lưu thay đổi' : 'Lưu BOM', 'save', true, !edit) : ''}</div></header>${this.error ? `<div class="bom-alert" role="alert">${this.escape(this.error)}. Bấm Làm mới để thử lại.</div>` : ''}
<section class="bom-identity"><span class="bom-robot-icon material-symbols-outlined" aria-hidden="true">smart_toy</span><div class="bom-model-field"><label for="bomModel">Model robot</label><select id="bomModel" ${disabled}><option value="" ${this.models.length ? 'hidden' : ''}>${this.busy ? 'Đang tải…' : 'Chưa có robot'}</option>${this.models.map(item => `<option value="${this.escape(modelKey(item))}" ${this.modelId === modelKey(item) ? 'selected' : ''}>${this.escape(item.Model)} · ${this.escape(item.Type)}</option>`).join('')}</select><small>${this.escape(model?.Name || 'Thêm robot trong Danh sách robot để bắt đầu.')}</small></div><div class="bom-version-field"><label for="bomRevision">Phiên bản BOM</label><select id="bomRevision" ${disabled || !this.header ? 'disabled' : ''}>${this.revisions.length ? this.revisions.map(item => `<option value="${Number(item.BomId)}" ${this.header?.BomId === item.BomId ? 'selected' : ''}>v${Number(item.Revision)} · ${item.Status === 'released' ? 'Đã phát hành' : 'Bản nháp'}</option>`).join('') : '<option>Chưa có BOM</option>'}</select></div>${this.header ? `<span class="bom-badge ${this.header.Status === 'released' ? 'bom-badge-green' : ''}">${this.header.Status === 'released' ? 'Đã phát hành' : this.dirty ? 'Chưa lưu thay đổi' : 'Bản nháp'}</span>` : ''}${this.canManage() ? `<div class="bom-identity-actions">${this.button('new', 'BOM mới', 'add', false, !model?.RobotId)}${this.header ? this.button('copy', 'Sao chép BOM', 'content_copy') + this.button('publish', 'Phát hành', 'send', false, !edit || !this.lines.length) + this.button('delete', 'Xóa BOM', 'delete') : ''}</div>` : ''}</section>
${!this.header ? `<div class="bom-card bom-empty"><span class="material-symbols-outlined">inventory_2</span><strong>${this.busy ? 'Đang tải BOM…' : this.models.length ? 'Model robot này chưa có BOM' : 'Chưa có model robot'}</strong><p>${this.models.length ? 'Tạo BOM và thêm các vật tư cấu thành robot.' : '<a href="#robots">Đến Danh sách robot để thêm robot.</a>'}</p>${this.canManage() && model ? this.button('new', 'Tạo BOM đầu tiên', 'add', true) : ''}</div>` : `<nav class="bom-tabs" aria-label="Nội dung BOM">${[['bom', 'Thành phần robot'], ['history', 'Lịch sử phiên bản']].map(([tab, label]) => `<button type="button" data-bom-tab="${tab}" aria-current="${this.tab === tab ? 'page' : 'false'}">${label}</button>`).join('')}</nav><section class="bom-card bom-main-card"><div class="bom-card-heading"><h2>${this.tab === 'history' ? 'Lịch sử phiên bản' : 'Danh sách thành phần'} <span class="bom-count">${this.tab === 'history' ? this.revisions.length + ' phiên bản' : this.lines.length + ' vật tư'}</span></h2>${edit && this.tab === 'bom' ? this.button('add', 'Thêm vật tư', 'add', true) : ''}</div>${this.tab === 'history' ? this.historyHtml() : `<div class="bom-filters"><label class="bom-search"><span class="material-symbols-outlined" aria-hidden="true">search</span><input id="bomSearch" type="search" value="${this.escape(this.query)}" placeholder="Tìm tên, model, nguồn hoặc ghi chú…" aria-label="Tìm vật tư trong BOM"></label></div><div id="bomLineRows">${this.tableHtml()}</div>`}</section>`}<input id="bomImportFile" class="bom-sr" type="file" accept=".xls,.xlsx" aria-label="Chọn file BOM Excel"></section>`;
const page = this.root.querySelector('[data-bom-page]'); page.addEventListener('click', event => this.click(event)); page.addEventListener('change', event => this.change(event));
page.addEventListener('input', event => { if (event.target.id === 'bomSearch') { this.query = event.target.value; this.root.querySelector('#bomLineRows').innerHTML = this.tableHtml(); } });
}
confirmPublication() {
if (this.publishConfirmation) return this.publishConfirmation;
const dialog = document.createElement('dialog');
dialog.id = 'bomPublishDialog'; dialog.className = 'bom-dialog bom-confirm-dialog';
dialog.setAttribute('aria-labelledby', 'bomPublishTitle');
dialog.setAttribute('aria-describedby', 'bomPublishDescription');
dialog.innerHTML = `<header class="bom-dialog-header"><div class="bom-confirm-heading"><span class="bom-confirm-icon material-symbols-outlined" aria-hidden="true">task_alt</span><div><p class="bom-eyebrow">CHỐT PHIÊN BẢN</p><h2 id="bomPublishTitle">Phát hành BOM v${Number(this.header.Revision)}?</h2></div></div><button type="button" data-bom-publish-cancel aria-label="Đóng"><span class="material-symbols-outlined">close</span></button></header>
<div class="bom-confirm-body"><p id="bomPublishDescription">Phiên bản này sẽ được khóa chỉnh sửa sau khi phát hành.</p><dl class="bom-publish-summary"><div><dt>Model robot</dt><dd>${this.escape(this.header.RobotModel)}</dd></div><div><dt>Phiên bản</dt><dd>v${Number(this.header.Revision)}</dd></div><div><dt>Thành phần</dt><dd>${this.lines.length} dòng vật tư</dd></div></dl>
<div class="bom-publish-note"><span class="material-symbols-outlined" aria-hidden="true">info</span><p>Khi cần thay đổi, dùng <strong>Sao chép BOM</strong> để tạo phiên bản nháp mới.</p></div>${this.dirty ? '<p class="bom-footnote">Các thay đổi chưa lưu sẽ được lưu trước khi phát hành.</p>' : ''}</div>
<footer class="bom-dialog-footer"><div><button type="button" data-bom-publish-cancel class="bom-btn">Quay lại</button><button type="button" data-bom-publish-confirm class="bom-btn bom-btn-primary"><span class="material-symbols-outlined" aria-hidden="true">lock</span>Phát hành BOM</button></div></footer>`;
this.publishConfirmation = new Promise(resolve => {
dialog.addEventListener('click', event => {
if (event.target.closest('[data-bom-publish-confirm]')) dialog.close('confirm');
else if (event.target.closest('[data-bom-publish-cancel]')) dialog.close();
else if (event.target === dialog) {
const rect = dialog.getBoundingClientRect();
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) dialog.close();
}
});
dialog.addEventListener('close', () => {
const confirmed = dialog.returnValue === 'confirm';
dialog.remove(); this.publishConfirmation = null; resolve(confirmed);
}, { once: true });
document.body.appendChild(dialog); dialog.showModal();
dialog.querySelector('.bom-dialog-footer [data-bom-publish-cancel]').focus({ preventScroll: true });
});
return this.publishConfirmation;
}
confirmDeletion() {
if (this.deleteConfirmation) return this.deleteConfirmation;
const dialog = document.createElement('dialog');
dialog.id = 'bomDeleteDialog'; dialog.className = 'bom-dialog bom-confirm-dialog bom-delete-dialog';
dialog.setAttribute('aria-labelledby', 'bomDeleteTitle');
dialog.setAttribute('aria-describedby', 'bomDeleteDescription');
const revision = this.revisions.find(item => item.BomId === this.header.BomId);
dialog.innerHTML = `<header class="bom-dialog-header"><div class="bom-confirm-heading"><span class="bom-confirm-icon material-symbols-outlined" aria-hidden="true">delete</span><div><p class="bom-eyebrow">XÓA PHIÊN BẢN</p><h2 id="bomDeleteTitle">Xóa BOM v${Number(this.header.Revision)}?</h2></div></div><button type="button" data-bom-delete-cancel aria-label="Đóng"><span class="material-symbols-outlined">close</span></button></header>
<div class="bom-confirm-body"><p id="bomDeleteDescription">BOM này và toàn bộ vật tư trong phiên bản sẽ bị xóa vĩnh viễn. Thao tác này không thể hoàn tác.</p><dl class="bom-publish-summary"><div><dt>Model robot</dt><dd>${this.escape(this.header.RobotModel)}</dd></div><div><dt>Phiên bản</dt><dd>v${Number(this.header.Revision)}</dd></div><div><dt>Thành phần đã lưu</dt><dd>${number(revision?.LineCount ?? this.lines.length)} dòng vật tư</dd></div></dl><p class="bom-footnote">Chỉ xóa phiên bản đang chọn. Các phiên bản BOM khác, robot và tài sản trong kho vẫn được giữ nguyên.</p>${this.dirty ? '<p class="bom-footnote">Các thay đổi chưa lưu của phiên bản này cũng sẽ bị bỏ.</p>' : ''}</div>
<footer class="bom-dialog-footer"><div><button type="button" data-bom-delete-cancel class="bom-btn">Hủy</button><button type="button" data-bom-delete-confirm class="bom-btn bom-btn-danger"><span class="material-symbols-outlined" aria-hidden="true">delete</span>Xóa BOM</button></div></footer>`;
this.deleteConfirmation = new Promise(resolve => {
dialog.addEventListener('click', event => {
if (event.target.closest('[data-bom-delete-confirm]')) dialog.close('confirm');
else if (event.target.closest('[data-bom-delete-cancel]')) dialog.close();
else if (event.target === dialog) {
const rect = dialog.getBoundingClientRect();
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) dialog.close();
}
});
dialog.addEventListener('close', () => {
const confirmed = dialog.returnValue === 'confirm';
dialog.remove(); this.deleteConfirmation = null; resolve(confirmed);
}, { once: true });
document.body.appendChild(dialog); dialog.showModal();
dialog.querySelector('.bom-dialog-footer [data-bom-delete-cancel]').focus({ preventScroll: true });
});
return this.deleteConfirmation;
}
async click(event) {
const tab = event.target.closest('[data-bom-tab]'); if (tab && !this.busy) { this.tab = tab.dataset.bomTab; this.render(); return; }
const open = event.target.closest('[data-bom-open]'); if (open && !this.busy && this.discardChanges()) { await this.run(async () => { await this.loadRevision(open.dataset.bomOpen); this.tab = 'bom'; }); return; }
const edit = event.target.closest('[data-bom-edit]'); const remove = event.target.closest('[data-bom-delete]');
if ((edit || remove) && this.editable() && !this.busy) { const index = Number((edit || remove).dataset[edit ? 'bomEdit' : 'bomDelete']); if (!this.lines[index]) return; if (edit) this.openMaterialForm(index); else { this.lines.splice(index, 1); this.changed(); } return; }
const button = event.target.closest('[data-bom-action]'); if (!button || button.disabled || this.busy) return;
const action = button.dataset.bomAction;
if (action === 'add' && this.editable()) return this.openMaterialForm();
if (action === 'export') return this.exportWorkbook();
if (action === 'import' && this.editable()) return this.root.querySelector('#bomImportFile').click();
if (action === 'refresh' && this.discardChanges()) return this.mount(this.root, this.selectedModel());
if (!this.canManage()) return;
if (action === 'delete' && this.header) {
const { BomId: bomId, LockVersion: lockVersion, Revision: revision } = this.header;
const selectedModelId = this.modelId;
if (!await this.confirmDeletion() || this.busy || !this.active() || !this.canManage()
|| this.header?.BomId !== bomId || this.header.LockVersion !== lockVersion || this.modelId !== selectedModelId) return;
return this.run(async () => {
await this.api(`/${bomId}`, { method: 'DELETE', body: JSON.stringify({ lockVersion }) });
this.header = null; this.lines = []; this.revisions = []; this.dirty = false;
this.app.notifySuccess(`Đã xóa BOM v${revision}.`);
this.models = await this.api('/models');
this.modelId = this.models.find(item => modelKey(item) === selectedModelId) ? selectedModelId : this.models[0] ? modelKey(this.models[0]) : '';
await this.loadModel(); this.tab = 'bom';
});
}
if (action === 'save' && this.editable()) return this.run(async () => { await this.persistDraft(); this.app.notifySuccess('Đã lưu BOM.'); });
if (['new', 'copy'].includes(action) && this.selectedModel()) {
if (action === 'new' && (!this.selectedModel().RobotId || !this.discardChanges())) return;
return this.run(async () => { if (action === 'copy' && this.dirty) await this.persistDraft(); const created = await this.api('', { method: 'POST', body: JSON.stringify({ robotId: this.selectedModel().RobotId ?? undefined, ...(action === 'copy' ? { copyFromId: this.header.BomId } : {}) }) }); await this.loadModel(created.BomId); this.tab = 'bom'; this.app.notifySuccess('Đã tạo BOM nháp.'); });
}
if (action === 'publish' && this.editable()) {
const bomId = this.header.BomId;
if (!await this.confirmPublication() || this.busy || !this.editable() || this.header.BomId !== bomId) return;
return this.run(async () => {
if (this.dirty) await this.persistDraft();
await this.api(`/${bomId}/publish`, { method: 'POST', body: JSON.stringify({ lockVersion: this.header.LockVersion }) });
this.header.Status = 'released'; this.dirty = false;
this.app.notifySuccess('Đã phát hành BOM.'); await this.loadModel(bomId);
});
}
}
async change(event) {
const target = event.target; if (target.id === 'bomImportFile' && target.files[0]) { await this.importWorkbook(target.files[0]); return; } if (this.busy) return;
if (target.id === 'bomModel') { if (!this.discardChanges()) { target.value = this.modelId; return; } this.modelId = target.value; await this.run(() => this.loadModel()); }
else if (target.id === 'bomRevision') { if (!this.discardChanges()) { target.value = String(this.header.BomId); return; } await this.run(() => this.loadRevision(target.value)); }
else if (target.hasAttribute('data-bom-quantity') && this.editable()) { const line = this.lines[Number(target.dataset.bomQuantity)]; try { this.validateLine({ ...line, Quantity: target.value }); line.Quantity = Number(target.value); this.changed(); } catch (error) { target.value = line.Quantity; this.app.notifyWarning(error.message); } }
}
openMaterialForm(index = null) {
if (!this.editable()) return; if (this.lines.length >= 500 && index === null) { this.app.notifyWarning('BOM tối đa 500 dòng vật tư.'); return; }
const previous = index === null ? null : this.lines[index]; const state = { mode: previous ? 'manual' : 'asset', catalog: null, loading: false, error: '', selected: null, query: '' };
const dialog = document.createElement('dialog'); dialog.id = 'bomComponentDialog'; dialog.className = 'bom-dialog bom-entry-dialog'; dialog.setAttribute('aria-labelledby', 'bomMaterialTitle');
dialog.innerHTML = `<form id="bomMaterialForm"><header class="bom-dialog-header"><div><h2 id="bomMaterialTitle">${previous ? 'Sửa vật tư' : 'Thêm vật tư vào BOM'}</h2><p>Chọn tên/model từ tài sản hoặc nhập vật tư bên ngoài.</p></div><button type="button" data-bom-close aria-label="Đóng"><span class="material-symbols-outlined">close</span></button></header><div class="bom-entry-tabs"><button type="button" data-bom-mode="asset">Chọn tài sản có sẵn</button><button type="button" data-bom-mode="manual">Nhập vật tư bên ngoài</button></div>
<div class="bom-material-layout">
<section class="bom-entry-context"><div class="bom-asset-picker"><label class="bom-search"><span class="material-symbols-outlined">search</span><input id="bomAssetSearch" type="search" placeholder="Tìm tên, mã hoặc model tài sản…" aria-label="Tìm tài sản"></label><p class="bom-footnote">Lấy tên và model từ tài sản. Số lượng BOM tự nhập.</p><div id="bomAssetResults"></div></div>
<div class="bom-external-guide" hidden><span class="bom-external-icon material-symbols-outlined" aria-hidden="true">edit_note</span><h3>Vật tư bên ngoài</h3><p>Thêm trực tiếp thành phần chưa có trong danh sách tài sản.</p><ul><li><span class="material-symbols-outlined" aria-hidden="true">check_circle</span><span><strong>Nhập tên vật tư</strong><small>Bổ sung model hoặc quy cách nếu có.</small></span></li><li><span class="material-symbols-outlined" aria-hidden="true">format_list_numbered</span><span><strong>Tự điền số lượng</strong><small>Theo cấu hình của robot đang lập BOM.</small></span></li><li><span class="material-symbols-outlined" aria-hidden="true">link</span><span><strong>Ghi lại nguồn cung cấp</strong><small>Link mua hàng hoặc thông tin nhà sản xuất.</small></span></li></ul><p class="bom-external-note">Có thể chuyển lại danh sách tài sản; thông tin đang nhập vẫn được giữ.</p></div>
</section>
<section class="bom-material-fields"><label>Tên tài sản / Vật tư <span class="bom-danger">*</span><input name="name" required maxlength="255" value="${this.escape(previous?.Name || '')}" placeholder="VD: Động cơ servo, cảm biến…" autocomplete="off"></label><label>Model <span class="bom-optional">(tùy chọn)</span><input name="model" maxlength="255" value="${this.escape(previous?.Model || '')}" placeholder="Model / quy cách vật tư"></label><div class="bom-form-grid"><label>Số lượng<input name="quantity" type="number" min="0.0001" max="100000" step="0.0001" value="${Number(previous?.Quantity ?? 1)}"></label><label>Đơn vị <span class="bom-optional">(tùy chọn)</span><input name="unit" maxlength="50" value="${this.escape(previous?.Unit || '')}" placeholder="VD: cái, bộ, m"></label></div><label>Nguồn <span class="bom-optional">(tùy chọn)</span><textarea name="sourceInfo" maxlength="1000" rows="2" placeholder="Link mua hàng hoặc thông tin nhà sản xuất / nhà cung cấp…">${this.escape(previous?.SourceInfo || '')}</textarea></label><label>Ghi chú <span class="bom-optional">(tùy chọn)</span><textarea name="notes" maxlength="500" rows="2" placeholder="Thông tin thêm về vật tư…">${this.escape(previous?.Notes || '')}</textarea></label></section>
</div><footer class="bom-dialog-footer"><p class="bom-entry-save-hint">Thêm vật tư, sau đó bấm <strong>Lưu BOM</strong> để lưu danh sách.</p><div><button type="button" data-bom-close class="bom-btn">Hủy</button>${!previous ? '<button type="submit" name="action" value="continue" class="bom-btn">Thêm và tiếp tục</button>' : ''}<button type="submit" name="action" value="done" class="bom-btn bom-btn-primary">${previous ? 'Cập nhật' : 'Thêm vào BOM'}</button></div></footer></form>`;
const form = dialog.querySelector('form');
const renderCatalog = () => {
const host = dialog.querySelector('#bomAssetResults');
if (state.loading) { host.innerHTML = '<p class="bom-muted bom-footnote" role="status">Đang tải danh sách tài sản…</p>'; return; }
if (state.error) { host.innerHTML = `<p class="bom-alert">${this.escape(state.error)}. Có thể chuyển sang Nhập vật tư bên ngoài.</p>`; return; }
const query = state.query.trim().toLocaleLowerCase('vi'); const rows = (state.catalog || []).filter(item => !query || [item.Name, item.Code, item.Model].some(value => String(value || '').toLocaleLowerCase('vi').includes(query)));
host.innerHTML = rows.length ? `<div class="bom-asset-table-wrap"><table class="bom-asset-table"><thead><tr><th></th><th>Tên tài sản</th><th>Model</th></tr></thead><tbody>${rows.slice(0, 50).map(item => `<tr class="${state.selected?.Id === item.Id ? 'bom-picked-row' : ''}"><td><input type="radio" name="assetChoice" value="${Number(item.Id)}" ${state.selected?.Id === item.Id ? 'checked' : ''} aria-label="Chọn ${this.escape(item.Name)}"></td><td><strong>${this.escape(item.Name)}</strong><small>${this.escape(item.Code)}</small></td><td>${this.escape(item.Model || '—')}</td></tr>`).join('')}</tbody></table></div><p class="bom-footnote">${rows.length > 50 ? `Hiển thị 50/${rows.length} tài sản. Tìm kiếm để thu hẹp danh sách.` : `${rows.length} tài sản`}</p>` : '<div class="bom-empty"><strong>Không tìm thấy tài sản</strong><p>Thử tìm kiếm khác hoặc chọn Nhập vật tư bên ngoài.</p></div>';
};
const setMode = async mode => {
state.mode = mode;
dialog.querySelector('.bom-asset-picker').hidden = mode !== 'asset';
dialog.querySelector('.bom-external-guide').hidden = mode !== 'manual';
dialog.querySelectorAll('[data-bom-mode]').forEach(button => button.setAttribute('aria-pressed', String(button.dataset.bomMode === mode)));
if (mode === 'asset' && !state.catalog && !state.loading) { state.loading = true; state.error = ''; renderCatalog(); try { state.catalog = await this.api('/catalog'); } catch (error) { state.error = error.message; } finally { state.loading = false; renderCatalog(); } }
};
dialog.addEventListener('click', event => {
if (event.target.closest('[data-bom-close]')) { dialog.close(); return; }
const mode = event.target.closest('[data-bom-mode]'); if (mode) setMode(mode.dataset.bomMode);
const row = event.target.closest('.bom-asset-table tbody tr'); if (row && !event.target.closest('input')) row.querySelector('input').click();
});
dialog.querySelector('#bomAssetSearch').addEventListener('input', event => { state.query = event.target.value; renderCatalog(); });
dialog.addEventListener('change', event => {
if (event.target.name !== 'assetChoice') return;
state.selected = state.catalog.find(item => item.Id === Number(event.target.value));
if (state.selected) { form.elements.name.value = state.selected.Name; form.elements.model.value = state.selected.Model || ''; form.elements.unit.value = state.selected.Unit || ''; renderCatalog(); }
});
form.addEventListener('submit', event => {
event.preventDefault(); if (!this.editable() || this.busy) return;
const candidate = { ...previous, SourceType: 'manual', SourceId: null, Name: form.elements.name.value.trim(), Model: form.elements.model.value.trim(), Quantity: form.elements.quantity.value === '' ? 1 : Number(form.elements.quantity.value), Unit: form.elements.unit.value.trim(), SourceInfo: form.elements.sourceInfo.value.trim(), Notes: form.elements.notes.value.trim() };
try { this.validateLine(candidate); } catch (error) { this.app.notifyWarning(error.message); return; }
if (index === null) this.lines.push(candidate); else this.lines[index] = candidate; this.query = ''; this.changed();
if (event.submitter?.value === 'continue') { form.reset(); state.selected = null; renderCatalog(); form.elements.name.focus({ preventScroll: true }); } else dialog.close();
});
dialog.addEventListener('close', () => dialog.remove(), { once: true });
document.body.appendChild(dialog); setMode(state.mode); dialog.showModal();
(state.mode === 'manual' ? form.elements.name : dialog.querySelector('#bomAssetSearch')).focus({ preventScroll: true });
}
exportWorkbook() {
if (!window.XLSX || !this.header) { this.app.notifyFailure('Không tìm thấy thư viện Excel hoặc BOM.'); return; }
try {
const rows = this.lines.map(line => ({ 'Tên vật tư': line.Name, 'Model': line.Model || '', 'Số lượng': Number(line.Quantity ?? 1), 'ĐVT': line.Unit || '', 'Nguồn': line.SourceInfo || '', 'Ghi chú': line.Notes || '' }));
for (const [field, label] of [['Code', 'Mã vật tư'], ['GroupName', 'Cụm lắp ráp'], ['Position', 'Vị trí lắp']]) if (this.lines.some(line => line[field])) rows.forEach((row, index) => { row[label] = this.lines[index][field] || ''; });
const book = window.XLSX.utils.book_new(); const sheet = window.XLSX.utils.json_to_sheet(rows, { header: ['Tên vật tư', 'Model', 'Số lượng', 'ĐVT', 'Nguồn', 'Ghi chú'] });
sheet['!cols'] = [36, 24, 14, 12, 55, 40, 20, 24, 24].map(wch => ({ wch })); window.XLSX.utils.book_append_sheet(book, sheet, 'BOM');
window.XLSX.utils.book_append_sheet(book, window.XLSX.utils.json_to_sheet([{ 'Model robot': this.header.RobotModel, 'Thể loại': this.selectedModel()?.Type || '', 'Phiên bản': this.header.Revision, 'Trạng thái': this.dirty ? 'Thay đổi chưa lưu' : this.header.Status === 'released' ? 'Đã phát hành' : 'Bản nháp', 'Ngày xuất': this.app.formatDateTime(new Date()) }]), 'Thong tin');
window.XLSX.writeFile(book, `BOM-${this.header.RobotModel.replace(/[^\p{L}\p{N}._-]/gu, '_').slice(0, 80)}-v${this.header.Revision}.xlsx`);
} catch (error) { this.app.notifyFailure(`Không thể xuất BOM: ${error.message}`); }
}
async importWorkbook(file) {
if (!this.editable() || this.busy) return;
if (!window.XLSX) { this.app.notifyFailure('Không tìm thấy thư viện Excel.'); return; }
if (!/\.xlsx?$/i.test(file.name) || file.size > 10 * 1024 * 1024) { this.app.notifyWarning('Chọn file .xls hoặc .xlsx, tối đa 10 MB.'); return; }
await this.run(async () => {
const book = window.XLSX.read(await file.arrayBuffer(), { type: 'array', sheetRows: 502 }); const sheet = book.Sheets.BOM || book.Sheets[book.SheetNames[0]]; const rows = window.XLSX.utils.sheet_to_json(sheet, { defval: '' });
if (!rows.length || rows.length > 500) throw new Error('File cần có từ 1 đến 500 dòng vật tư. Dùng file Xuất Excel làm mẫu.');
const next = rows.map(row => ({ SourceType: 'manual', SourceId: null, Name: String(row['Tên vật tư'] || row['Tên tài sản'] || row['Tên linh kiện'] || '').trim(), Model: String(row.Model || '').trim(), Quantity: row['Số lượng'] !== undefined && row['Số lượng'] !== '' ? row['Số lượng'] : row['SL / robot'] ?? 1, Unit: String(row['ĐVT'] || '').trim(), SourceInfo: String(row['Nguồn'] || '').trim(), Notes: String(row['Ghi chú'] || '').trim(), Code: String(row['Mã vật tư'] || row['Mã linh kiện'] || '').trim(), GroupName: String(row['Cụm lắp ráp'] || '').trim(), Position: String(row['Vị trí lắp'] || '').trim() }));
this.validateLines(next); if (this.lines.length && !window.confirm(`Thay ${this.lines.length} dòng BOM hiện tại bằng ${next.length} dòng từ Excel? Bấm Lưu thay đổi sau khi kiểm tra danh sách.`)) return;
this.lines = next; this.dirty = true; this.query = ''; this.app.notifySuccess(`Đã đọc ${next.length} vật tư. Bấm Lưu thay đổi để lưu.`);
});
}
}
window.RobotBomController = RobotBomController;
})();

View File

@@ -260,7 +260,7 @@
</select>
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Dự án</label>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Dự án mặc định</label>
<select id="assetProjectInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3">
<option value="">-- Chọn dự án --</option>
</select>
@@ -680,62 +680,128 @@
</div>
<!-- Export Asset Modal -->
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="borrowAssetModal">
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="exportRequestDocumentModal">
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
<h3 class="text-base font-extrabold text-slate-900">Xuất tài sản</h3>
<h3 class="text-base font-extrabold text-slate-900">Phiếu đề nghị xuất Excel</h3>
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400" data-close-modal="exportRequestDocumentModal" aria-label="Đóng">
<span class="material-symbols-outlined">close</span>
</button>
</div>
<div class="p-6 space-y-4">
<p class="text-sm text-slate-700">Đã xuất thành công và tạo phiếu Excel. Nếu file chưa tải xuống, bạn có thể tải lại bên dưới.</p>
<p id="exportRequestDocumentName" class="text-sm font-semibold text-slate-700 break-all"></p>
<p class="text-xs text-slate-500">Phần chữ ký, họ tên và ngày ký để trống để điền sau.</p>
<div class="flex gap-3">
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg" data-close-modal="exportRequestDocumentModal">Đóng</button>
<button type="button" id="downloadExportRequestDocumentBtn" class="flex-1 px-4 py-2 bg-primary text-on-primary rounded-lg text-xs font-bold">Tải lại phiếu Excel</button>
</div>
</div>
</div>
</div>
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="borrowAssetModal">
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4 flex flex-col" style="max-height: calc(100dvh - 2rem);">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50 shrink-0">
<h3 id="borrowAssetTitle" class="text-base font-extrabold text-slate-900">Tạo đơn xuất tài sản vào dự án</h3>
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400 transition-colors" data-close-modal="borrowAssetModal">
<span class="material-symbols-outlined">close</span>
</button>
</div>
<form id="borrowAssetForm" class="p-6 space-y-4">
<form id="borrowAssetForm" class="p-6 space-y-4 overflow-y-auto min-h-0">
<input type="hidden" id="borrowAssetIdInput">
<p id="borrowAssetDescription" class="text-sm text-slate-600">Xuất vào dự án, không hoàn lại kho. Số lượng chỉ trừ khi admin/asset duyệt đơn.</p>
<p id="borrowAssetStockSummary" class="text-sm font-semibold text-slate-700"></p>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Tài sản</label>
<input type="text" id="borrowAssetNameInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Tồn cuối kỳ hiện tại</label>
<label for="borrowCurrentEndingInput" class="text-xs font-bold text-slate-500 block mb-1">Còn có thể xuất</label>
<input type="number" id="borrowCurrentEndingInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Số lượng xuất</label>
<input type="number" id="borrowQuantityInput" min="1" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" value="1" required>
<div id="borrowAssetRequesterField">
<label for="borrowAssetUserInput" class="text-xs font-bold text-slate-500 block mb-1">Người đề xuất</label>
<input type="text" id="borrowAssetUserInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly required>
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Người mượn</label>
<select id="borrowAssetUserInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" required>
<option value="">-- Chọn người mượn --</option>
<div id="borrowAssetRecipientField" hidden>
<label for="borrowAssetRecipientInput" class="text-xs font-bold text-slate-500 block mb-1">Người nhận</label>
<select id="borrowAssetRecipientInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" disabled>
<option value="">-- Chọn người nhận --</option>
</select>
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Xuất cho dự án</label>
<select id="borrowAssetProjectInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" required>
<option value="">-- Chọn dự án --</option>
</select>
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Người xuất</label>
<input type="text" id="borrowByInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
<div class="md:col-span-2 space-y-3">
<div class="flex items-end gap-2">
<label for="borrowAssetProjectInput" class="flex-1 text-xs text-slate-600">Dự án
<select id="borrowAssetProjectInput" class="w-full border border-slate-200 rounded-lg text-sm py-2 px-3" required>
<option value="">-- Chọn dự án --</option>
</select>
</label>
<label for="borrowQuantityInput" class="text-xs text-slate-600" style="width: 100px;">Số lượng
<input type="number" id="borrowQuantityInput" min="1" step="1" class="w-full border border-slate-200 rounded-lg text-sm py-2 px-3" value="1" required>
</label>
</div>
<div id="borrowAdditionalProjects" class="space-y-3"></div>
<button type="button" id="addBorrowProjectBtn" class="mt-2 px-3 py-2 text-xs font-bold text-primary border border-slate-200 rounded-lg">+ Thêm dự án</button>
<p id="borrowAllocationSummary" class="mt-2 text-sm font-semibold" aria-live="polite"></p>
</div>
<div class="md:col-span-2">
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Role người thao tác</label>
<input type="text" id="borrowRoleInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
</div>
<div class="md:col-span-2">
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Ghi chú xuất</label>
<textarea id="borrowAssetNoteInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 h-20 resize-none" placeholder="Nhập ghi chú (nếu có)"></textarea>
<label for="borrowAssetNoteInput" class="text-xs font-bold text-slate-500 block mb-1">Ghi chú xuất</label>
<textarea id="borrowAssetNoteInput" maxlength="1000" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 h-20 resize-none" placeholder="Nhập ghi chú (nếu có)"></textarea>
</div>
</div>
<div class="flex gap-3 pt-2">
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg" data-close-modal="borrowAssetModal">Hủy</button>
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Xác nhận xuất</button>
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Gửi đơn chờ duyệt</button>
</div>
</form>
</div>
</div>
<!-- Batch Asset Export Modal -->
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="batchAssetExportModal">
<div class="modal-content w-full max-w-5xl bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4 flex flex-col" style="max-height: calc(100vh - 2rem);">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
<div><h3 id="batchAssetExportTitle" class="text-base font-extrabold text-slate-900">Tạo đơn xuất nhiều tài sản vào dự án</h3><p id="batchAssetExportDescription" class="mt-1 text-xs text-slate-500">Chọn số lượng và dự án cho từng tài sản. Chỉ trừ kho khi được duyệt; tài sản xuất không hoàn lại kho.</p></div>
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400" data-close-modal="batchAssetExportModal" aria-label="Đóng"><span class="material-symbols-outlined">close</span></button>
</div>
<form id="batchAssetExportForm" class="p-6 space-y-4 overflow-y-auto">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<label id="batchAssetExportRequesterField" class="text-xs font-semibold text-slate-600">Người đề xuất<input id="batchAssetExportUserInput" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm bg-slate-50" readonly required></label>
<label id="batchAssetExportRecipientField" class="text-xs font-semibold text-slate-600" hidden>Người nhận<select id="batchAssetExportRecipientInput" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm" disabled><option value="">-- Chọn người nhận --</option></select></label>
<label class="text-xs font-semibold text-slate-600">Dự án chung (tùy chọn)<select id="batchAssetExportCommonProject" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"><option value="">-- Áp dụng dự án cho tất cả --</option></select></label>
</div>
<p id="batchAssetExportSummary" class="text-sm font-semibold text-slate-700" aria-live="polite"></p>
<div class="overflow-x-auto rounded-lg border border-slate-200">
<table class="w-full text-left text-sm" style="min-width: 760px;">
<thead class="bg-slate-50 text-xs text-slate-500"><tr><th class="px-3 py-3">Tài sản</th><th class="px-3 py-3">Có thể xuất</th><th class="px-3 py-3">Số lượng</th><th class="px-3 py-3">Dự án</th><th class="px-3 py-3"></th></tr></thead>
<tbody id="batchAssetExportTableBody" class="divide-y divide-slate-100"></tbody>
</table>
</div>
<label class="block text-xs font-semibold text-slate-600">Ghi chú xuất<textarea id="batchAssetExportNoteInput" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm h-20 resize-none" maxlength="1000" placeholder="Nhập ghi chú (nếu có)"></textarea></label>
<div class="flex gap-3 pt-2">
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg" data-close-modal="batchAssetExportModal">Hủy</button>
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Gửi đơn chờ duyệt</button>
</div>
</form>
</div>
</div>
<!-- Saved Asset Export Preview -->
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="assetExportPreviewModal" style="z-index: 145;">
<div class="modal-content w-full max-w-5xl bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4 flex flex-col" style="max-height: calc(100vh - 2rem);">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
<div class="min-w-0"><h3 class="text-base font-extrabold text-slate-900">Phiếu xuất tài sản</h3><p id="assetExportPreviewFileName" class="mt-1 truncate text-xs text-slate-500"></p></div>
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400" data-close-modal="assetExportPreviewModal" aria-label="Đóng"><span class="material-symbols-outlined">close</span></button>
</div>
<div id="assetExportPreviewContent" class="p-6 overflow-y-auto"></div>
<div class="px-6 py-4 border-t border-slate-100 flex items-center justify-between gap-3">
<p class="text-xs text-slate-500">Nội dung ghi nhận tại thời điểm xuất.</p>
<button type="button" id="assetExportPreviewDownloadBtn" class="shrink-0 px-4 py-2 bg-primary text-on-primary rounded-lg text-xs font-bold">Tải Excel</button>
</div>
</div>
</div>
<!-- Asset Damage/Disposal Modal -->
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="assetDamageModal">
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
@@ -796,39 +862,24 @@
</div>
</div>
<!-- Asset Export History Modal -->
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="assetExportHistoryModal" style="z-index: 125;">
<div class="modal-content w-full max-w-6xl bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4 flex flex-col" style="max-height: calc(100vh - 2rem);">
<!-- Approve/reject a project export proposal -->
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="assetExportProcessModal">
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
<h3 class="text-base font-extrabold text-slate-900">Lịch sử xuất tài sản</h3>
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400 transition-colors" data-close-modal="assetExportHistoryModal">
<span class="material-symbols-outlined">close</span>
</button>
<h3 id="assetExportProcessTitle" class="text-base font-extrabold text-slate-900">Duyệt xuất dự án</h3>
<button type="button" class="p-1.5 rounded-lg text-slate-500" data-close-modal="assetExportProcessModal" aria-label="Đóng"><span class="material-symbols-outlined">close</span></button>
</div>
<div class="p-6 pt-4 overflow-auto">
<div class="rounded-xl border border-slate-200 overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-left border-collapse" style="min-width: 1100px;">
<thead class="bg-slate-50 border-b border-slate-200">
<tr>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Ngày giờ</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Tài sản</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Số lượng</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Dự án</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Người phụ trách</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Người xuất</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Ghi chú</th>
</tr>
</thead>
<tbody id="assetExportHistoryTableBody" class="divide-y divide-slate-100">
<tr>
<td colspan="7" class="px-4 py-8 text-sm text-center text-slate-500">Chưa có dữ liệu lịch sử xuất.</td>
</tr>
</tbody>
</table>
</div>
<form id="assetExportProcessForm" class="p-6 space-y-4">
<p id="assetExportProcessMessage" class="text-sm text-slate-600"></p>
<div id="assetExportRejectField" hidden>
<label for="assetExportRejectReason" class="block mb-1 text-sm font-bold text-slate-700">Lý do từ chối</label>
<textarea id="assetExportRejectReason" maxlength="1000" class="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm h-24"></textarea>
</div>
</div>
<div class="flex gap-3 pt-2">
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold border border-slate-200 rounded-lg" data-close-modal="assetExportProcessModal">Hủy</button>
<button id="assetExportProcessSubmit" type="submit" class="flex-1 px-4 py-2 bg-primary text-on-primary rounded-lg text-xs font-bold">Duyệt và xuất vào dự án</button>
</div>
</form>
</div>
</div>
@@ -1033,25 +1084,25 @@
</div>
</div>
<!-- Archived asset borrower balances, including imports and direct exports. -->
<!-- All archived asset records, including those with no outstanding borrowers. -->
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="archivedAssetBorrowsModal">
<div class="modal-content bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden flex flex-col m-4" style="width:min(1100px, calc(100vw - 32px));max-height:calc(100vh - 32px);">
<div class="modal-content bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden flex flex-col m-3" style="width:min(1600px, calc(100vw - 24px));max-height:calc(100vh - 24px);">
<div class="px-6 py-4 border-b border-slate-100 bg-slate-50 flex items-center justify-between gap-3">
<h3 class="text-base font-extrabold text-slate-800">Tài sản cũ còn mượn</h3>
<h3 class="text-base font-extrabold text-slate-800">Tài sản cũ</h3>
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-500" data-close-modal="archivedAssetBorrowsModal" aria-label="Đóng">
<span class="material-symbols-outlined">close</span>
</button>
</div>
<div class="px-6 py-4 border-b border-slate-100">
<p class="text-sm text-slate-600">Số dư người mượn của tài sản đã xóa khỏi danh mục, gồm cả dữ liệu nhập Excel và xuất trực tiếp. Các hồ sơ trùng mã được theo dõi riêng.</p>
<p class="mt-2 text-xs text-slate-500">Nếu có đơn mượn gốc, tạo đơn trả tại Mượn/Trả tài sản để ghi nhận vào hồ sơ cũ. Dữ liệu chỉ có số dư người mượn cần đối chiếu riêng, cùng với tồn kho danh mục mới.</p>
<label for="archivedAssetBorrowsSearch" class="mt-3 block text-xs font-bold text-slate-600">Tìm tài sản hoặc người mượn</label>
<input id="archivedAssetBorrowsSearch" class="mt-1 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Mã, tên, serial, người mượn, dự án...">
<p class="text-sm text-slate-600">Toàn bộ tài sản đã xóa khỏi danh mục hiện tại vẫn được lưu trong cơ sở dữ liệu, kể cả tài sản không còn ai mượn. Các hồ sơ trùng mã được theo dõi riêng.</p>
<p class="mt-2 text-xs text-slate-500">Lịch sử mượn/trả được giữ theo từng hồ sơ cũ. Nếu còn đơn mượn, tạo đơn trả tại Mượn/Trả tài sản.</p>
<label for="archivedAssetBorrowsSearch" class="mt-3 block text-xs font-bold text-slate-600">Tìm tài sản cũ</label>
<input id="archivedAssetBorrowsSearch" class="mt-1 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Mã, tên, model, serial, người mượn, dự án...">
</div>
<div class="overflow-auto flex-1">
<table class="w-full text-left border-collapse" style="min-width:780px;">
<table class="w-full text-left border-collapse" style="min-width:1450px;">
<thead class="sticky top-0 bg-slate-50 text-xs font-bold text-slate-500">
<tr><th class="px-4 py-3">Mã</th><th class="px-4 py-3">Tài sản</th><th class="px-4 py-3">Người mượn</th><th class="px-4 py-3">Còn mượn</th><th class="px-4 py-3">Đơn vị</th><th class="px-4 py-3">Dự án / Phòng ban</th></tr>
<tr><th class="px-4 py-3">Mã</th><th class="px-4 py-3">Tài sản</th><th class="px-4 py-3">Ngày xóa</th><th class="px-4 py-3">Tồn đầu</th><th class="px-4 py-3">Nhập</th><th class="px-4 py-3">Xuất</th><th class="px-4 py-3">Tồn cuối</th><th class="px-4 py-3">Còn mượn</th><th class="px-4 py-3">Đơn vị</th><th class="px-4 py-3">Người mượn</th><th class="px-4 py-3">Phòng ban / Dự án</th></tr>
</thead>
<tbody id="archivedAssetBorrowsTableBody"></tbody>
</table>
@@ -1071,7 +1122,7 @@
<h3 class="text-base font-extrabold text-red-700">Xóa tài sản</h3>
</div>
<div class="p-6">
<p class="text-sm text-slate-600 mb-6">Xóa tài sản <strong id="deleteAssetName">-</strong> khỏi danh mục hiện tại? Lịch sử mượn/trả và số lượng còn đang mượn vẫn được giữ trong tài sản cũ.</p>
<p class="text-sm text-slate-600 mb-6">Xóa tài sản <strong id="deleteAssetName">-</strong> khỏi danh mục hiện tại? Toàn bộ hồ sơ, lịch sử mượn/trả và số lượng còn đang mượn vẫn được giữ trong Tài sản cũ.</p>
<div class="flex gap-3">
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg" data-close-modal="deleteAssetModal">Hủy</button>
<button type="button" class="flex-1 px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-xs font-bold confirm-delete-asset">Xóa</button>

View File

@@ -9,7 +9,8 @@
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet"/>
<!-- Material Symbols -->
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="../css/main.css?v=20260806-4" />
<link rel="stylesheet" href="../css/main.css?v=20261019-4" />
<link rel="stylesheet" href="../css/robot-bom.css?v=20261102-5" />
<!-- Notiflix Notify -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-3.2.7.min.css" />
<script src="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js"></script>
@@ -46,25 +47,6 @@
transform: scale(1);
}
.tree-label {
letter-spacing: 0.08em;
text-transform: uppercase;
font-size: 10px;
font-weight: 800;
color: #64748b;
padding: 0 0.75rem;
margin-bottom: 0.35rem;
}
.tree-branch {
margin-left: 0.75rem;
border-left: 1px dashed rgba(100, 116, 139, 0.5);
padding-left: 0.6rem;
display: flex;
flex-direction: column;
gap: 0.2rem;
}
body.app-shell {
overflow: hidden;
}
@@ -268,102 +250,143 @@
}
</style>
<link rel="stylesheet" href="../css/responsive.css?v=20260807-1" />
<link rel="stylesheet" href="../css/responsive.css?v=20261019-3" />
<link rel="stylesheet" href="../css/asset-actions.css?v=20261111-1" />
<link rel="stylesheet" href="../css/dashboard.css?v=20261103-1" />
<link rel="stylesheet" href="../css/announcements.css?v=20261103-2" />
</head>
<body class="app-shell bg-background text-on-surface antialiased flex h-screen w-screen">
<!-- SideNavBar -->
<aside id="appSidebar" class="h-screen w-56 flex flex-col bg-slate-100 dark:bg-slate-900 font-manrope text-sm font-medium border-r border-outline-variant/10 shrink-0">
<div class="flex flex-col h-full py-6">
<aside id="appSidebar" class="h-screen w-64 flex flex-col bg-slate-100 dark:bg-slate-900 font-manrope text-sm font-medium border-r border-outline-variant/10 shrink-0">
<div class="flex flex-col h-full min-h-0 py-4">
<!-- Header -->
<div class="px-6 mb-8">
<div class="px-5 mb-4 shrink-0">
<a href="#dashboard" class="sidebar-brand-link" aria-label="PNKX - Về trang tổng quan">
<img src="../image/logo_PNKX.png" alt="PNKX" class="sidebar-brand-image"/>
</a>
</div>
<!-- Primary Nav -->
<nav class="flex-1 px-3 space-y-4 overflow-y-auto">
<div>
<div class="tree-label">Tài khoản</div>
<div class="tree-branch">
<a href="#dashboard" data-nav="dashboard" class="flex items-center gap-3 px-3 py-2 border-l-4 border-blue-600 bg-slate-200/80 dark:bg-slate-800 text-slate-900 dark:text-slate-50 font-bold group transition-all cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">dashboard</span>
<span>Tổng quan</span>
<nav id="sidebarNav" class="sidebar-nav flex-1 min-h-0 overflow-y-auto" aria-label="Điều hướng chính">
<ul class="sidebar-menu">
<li>
<a href="#dashboard" data-nav="dashboard" class="sidebar-link" aria-current="page">
<span class="material-symbols-outlined" aria-hidden="true">dashboard</span>
<span class="sidebar-text">Tổng quan</span>
</a>
<a href="#applications" data-nav="applications" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">apps</span>
<span>Ứng dụng</span>
</a>
<a href="#accounts" data-nav="accounts" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">manage_accounts</span>
<span>Tài khoản</span>
</a>
<a href="#notifications" data-nav="notifications" class="relative flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">notifications</span>
<span>Thông báo</span>
<span id="notificationNavBadge" class="hidden ml-auto min-w-[20px] h-5 px-1.5 rounded-full bg-red-600 text-white text-[10px] font-extrabold leading-5 text-center">0</span>
</a>
</div>
</div>
<div>
<div class="tree-label">Quản lý tài sản</div>
<div class="tree-branch">
<a href="#assets" data-nav="assets" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">inventory_2</span>
<span>Tài sản</span>
</a>
<a href="#asset-borrows" data-nav="asset-borrows" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">assignment_returned</span>
<span>Mượn/Trả tài sản</span>
</a>
<a href="#my-borrowed-assets" data-nav="my-borrowed-assets" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">inventory</span>
<span>Tài sản đang mượn</span>
</a>
<a href="#asset-departments" data-nav="asset-departments" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">apartment</span>
<span> Phòng Ban</span>
</a>
<a href="#asset-projects" data-nav="asset-projects" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">workspaces</span>
<span>Dự án</span>
</a>
</div>
</div>
<div>
<div class="tree-label">Vật tư tiêu hao</div>
<div class="tree-branch">
<a href="#consumables" data-nav="consumables" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">category</span>
<span>Danh sách VTTH</span>
</a>
<a href="#consumable-exports" data-nav="consumable-exports" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">outbox</span>
<span>Lịch sử xuất</span>
</a>
</div>
</div>
<div>
<div class="tree-label">Tài liệu</div>
<div class="tree-branch">
<a href="#documents" data-nav="documents" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">picture_as_pdf</span>
<span>Tài liệu PDF</span>
</a>
</div>
</div>
<div id="usersSection" class="pt-2 border-t border-outline-variant/10" style="display: none;">
<a id="usersNav" href="#users" data-nav="users" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-lg" style="display: none;">
<span class="material-symbols-outlined">people</span>
<span>Người dùng (Quản trị)</span>
</a>
</div>
</li>
<li data-nav-group="accounts">
<button id="sidebarAccountsToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="accounts" aria-expanded="false" aria-controls="sidebarAccounts">
<span class="material-symbols-outlined" aria-hidden="true">manage_accounts</span>
<span class="sidebar-text">Tài khoản</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarAccounts" class="sidebar-children" aria-labelledby="sidebarAccountsToggle" hidden>
<li><a href="#applications" data-nav="applications" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">apps</span>
<span class="sidebar-text">Ứng dụng</span>
</a></li>
<li><a href="#accounts" data-nav="accounts" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">manage_accounts</span>
<span class="sidebar-text">Tài khoản</span>
</a></li>
</ul>
</li>
<li data-nav-group="assets">
<button id="sidebarAssetsToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="assets" aria-expanded="false" aria-controls="sidebarAssets">
<span class="material-symbols-outlined" aria-hidden="true">inventory_2</span>
<span class="sidebar-text">Quản lý tài sản</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarAssets" class="sidebar-children" aria-labelledby="sidebarAssetsToggle" hidden>
<li><a href="#assets" data-nav="assets" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">inventory_2</span>
<span class="sidebar-text">Tài sản</span>
</a></li>
<li><a href="#asset-borrows" data-nav="asset-borrows" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">assignment_returned</span>
<span class="sidebar-text">Mượn/Trả tài sản</span>
</a></li>
<li><a href="#asset-exports" data-nav="asset-exports" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">outbox</span>
<span class="sidebar-text">Xuất vào dự án</span>
</a></li>
<li><a href="#my-borrowed-assets" data-nav="my-borrowed-assets" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">inventory</span>
<span class="sidebar-text">Tài sản đang mượn</span>
</a></li>
<li><a href="#asset-departments" data-nav="asset-departments" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">apartment</span>
<span class="sidebar-text">Phòng ban</span>
</a></li>
<li><a href="#asset-projects" data-nav="asset-projects" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">workspaces</span>
<span class="sidebar-text">Dự án</span>
</a></li>
</ul>
</li>
<li data-nav-group="consumables">
<button id="sidebarConsumablesToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="consumables" aria-expanded="false" aria-controls="sidebarConsumables">
<span class="material-symbols-outlined" aria-hidden="true">category</span>
<span class="sidebar-text">Vật tư tiêu hao</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarConsumables" class="sidebar-children" aria-labelledby="sidebarConsumablesToggle" hidden>
<li><a href="#consumables" data-nav="consumables" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">category</span>
<span class="sidebar-text">Danh sách VTTH</span>
</a></li>
<li><a href="#consumable-exports" data-nav="consumable-exports" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">outbox</span>
<span class="sidebar-text">Lịch sử xuất</span>
</a></li>
</ul>
</li>
<li data-nav-group="robots">
<button id="sidebarRobotsToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="robots" aria-expanded="false" aria-controls="sidebarRobots">
<span class="material-symbols-outlined" aria-hidden="true">smart_toy</span>
<span class="sidebar-text">Quản lý robot</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarRobots" class="sidebar-children" aria-labelledby="sidebarRobotsToggle" hidden>
<li><a href="#robots" data-nav="robots" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">smart_toy</span>
<span class="sidebar-text">Danh sách robot</span>
</a></li>
<li><a href="#robot-types" data-nav="robot-types" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">category</span>
<span class="sidebar-text">Thể loại robot</span>
</a></li>
<li><a href="#robot-bom" data-nav="robot-bom" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">receipt_long</span>
<span class="sidebar-text">BOM robot</span>
</a></li>
</ul>
</li>
<li><a href="#documents" data-nav="documents" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">folder_open</span>
<span class="sidebar-text">Tài liệu</span>
</a></li>
<li id="usersSection" class="sidebar-admin" data-nav-group="administration" style="display: none;">
<button id="sidebarAdministrationToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="administration" aria-expanded="false" aria-controls="sidebarAdministration">
<span class="material-symbols-outlined" aria-hidden="true">admin_panel_settings</span>
<span class="sidebar-text">Quản trị viên</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarAdministration" class="sidebar-children" aria-labelledby="sidebarAdministrationToggle" hidden>
<li><a id="usersNav" href="#users" data-nav="users" class="sidebar-link" style="display: none;">
<span class="material-symbols-outlined" aria-hidden="true">people</span>
<span class="sidebar-text">Quản lý người dùng</span>
</a></li>
<li><a href="#notification-management" data-nav="notification-management" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>
<span class="sidebar-text">Đăng thông báo</span>
</a></li>
</ul>
</li>
</ul>
</nav>
<!-- Footer -->
<div class="px-6 pt-4 border-t border-outline-variant/10">
<div class="px-5 pt-3 mt-3 border-t border-outline-variant/10 shrink-0">
<div class="text-[10px] font-bold text-on-surface-variant/40 uppercase tracking-widest">v1.0.0</div>
</div>
</div>
@@ -425,6 +448,8 @@
</div>
</main>
<script src="../js/app.js?v=20260915-1"></script>
<script src="../js/document-formats.js?v=20261019-1"></script>
<script src="../js/robot-bom.js?v=20261102-5"></script>
<script src="../js/app.js?v=20261111-1"></script>
</body>
</html>

View File

@@ -193,7 +193,7 @@
id="resetPassword"
name="resetPassword"
placeholder="Enter a new password"
minlength="12"
minlength="6"
maxlength="256"
required
class="w-full pl-10 pr-4 py-2.5 bg-surface-container-low border border-outline-variant/30 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent transition-all text-sm font-medium"
@@ -212,7 +212,7 @@
id="resetConfirmPassword"
name="resetConfirmPassword"
placeholder="Re-enter new password"
minlength="12"
minlength="6"
maxlength="256"
required
class="w-full pl-10 pr-4 py-2.5 bg-surface-container-low border border-outline-variant/30 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent transition-all text-sm font-medium"
@@ -297,7 +297,7 @@
id="regPassword"
name="password"
placeholder="Create a password"
minlength="12"
minlength="6"
maxlength="256"
required
class="w-full pl-10 pr-4 py-2.5 bg-surface-container-low border border-outline-variant/30 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent transition-all text-sm font-medium"
@@ -608,8 +608,8 @@
return;
}
if (!newPassword || newPassword.length < 12 || newPassword.length > 256) {
resetPasswordErrorMessage.textContent = 'New password must be between 12 and 256 characters.';
if (!newPassword || newPassword.length < 6 || newPassword.length > 256) {
resetPasswordErrorMessage.textContent = 'New password must be between 6 and 256 characters.';
resetPasswordErrorMessage.classList.remove('hidden');
return;
}

View File

@@ -1,222 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { createRequire } = require('node:module');
const serverPath = path.resolve(__dirname, '../backend/server.js');
const serverSource = fs.readFileSync(serverPath, 'utf8');
const serverRequire = createRequire(serverPath);
// Run the real route handlers with an isolated pool so these regressions do not
// need credentials or alter a developer's inventory.
function createFixture(answer = () => ({ recordset: [] })) {
const queries = [];
const transactions = [];
class Request {
constructor(transaction) {
this.transaction = transaction;
this.inputs = {};
}
input(name, _type, value) {
this.inputs[name] = value;
return this;
}
async query(query) {
const call = { query, inputs: this.inputs, transaction: this.transaction };
queries.push(call);
return answer(call);
}
}
class Transaction {
constructor() { transactions.push(this); }
async begin() { this.begun = true; }
async commit() { this.committed = true; }
async rollback() { this.rolledBack = true; }
}
const sql = { ...serverRequire('mssql'), Request, Transaction };
const module = { exports: {} };
const context = {
require(name) { return name === 'mssql' ? sql : serverRequire(name); },
module,
exports: module.exports,
__dirname: path.dirname(serverPath),
__filename: serverPath,
Buffer,
URL,
console,
process: {
env: {
...process.env,
NODE_ENV: 'test',
DATA_ENCRYPTION_SECRET: 'test-only-archive-key-with-more-than-32-characters'
},
on() {}
},
testPool: { request: () => new Request() }
};
vm.runInNewContext(`${serverSource}
pool = testPool;
getUserDisplayNameById = async () => 'Borrower A';
safeCreateSystemNotification = async () => {};
ensureDepartmentExists = async () => {};
syncAssetDepartmentsFromInventory = async () => {};
syncAssetProjectsFromInventory = async () => {};
`, context, { filename: serverPath });
async function invoke(method, routePath, overrides = {}) {
const route = module.exports.app.router.stack.find(layer => (
layer.route?.path === routePath && layer.route.methods[method]
)).route;
const handler = route.stack.at(-1).handle;
const req = {
params: {}, query: {}, body: {},
user: { UserId: 1, Role: 'asset', FullName: 'Borrower A' },
...overrides
};
const response = {
statusCode: 200,
status(value) { this.statusCode = value; return this; },
json(value) { this.body = value; return this; }
};
await handler(req, response);
return response;
}
return { invoke, queries, transactions };
}
test('deleting an asset archives it without deleting any history or links', async () => {
const fixture = createFixture(() => ({ recordset: [{ AssetId: 17 }] }));
const response = await fixture.invoke('delete', '/api/assets/:id', { params: { id: '17' } });
assert.equal(response.statusCode, 200);
assert.equal(fixture.queries.length, 1);
assert.match(fixture.queries[0].query, /SET IsArchived = 1/);
assert.match(fixture.queries[0].query, /WHERE AssetId = @assetId AND IsArchived = 0/);
assert.doesNotMatch(fixture.queries[0].query, /DELETE\s/i);
assert.equal(fixture.queries[0].inputs.assetId, 17);
assert.equal(fixture.transactions[0].committed, true);
});
test('bulk archive changes only active inventory and reports the committed count', async () => {
const fixture = createFixture(() => ({ recordset: [{ ArchivedCount: 42 }] }));
const response = await fixture.invoke('post', '/api/assets/archive-all');
assert.equal(response.body.data.archivedCount, 42);
assert.equal(fixture.queries.length, 1);
assert.match(fixture.queries[0].query, /WITH \(UPDLOCK, HOLDLOCK\)/);
assert.match(fixture.queries[0].query, /WHERE IsArchived = 0/);
assert.doesNotMatch(fixture.queries[0].query, /DELETE\s|AssetBorrowRequestLinks/i);
assert.equal(fixture.transactions[0].committed, true);
});
test('current and archived inventory are selected separately', async () => {
const fixture = createFixture();
await fixture.invoke('get', '/api/assets');
await fixture.invoke('get', '/api/assets', { query: { archived: '1' } });
assert.equal(fixture.queries[0].inputs.isArchived, 0);
assert.equal(fixture.queries[1].inputs.isArchived, 1);
for (const call of fixture.queries) {
assert.match(call.query, /WHERE IsArchived = @isArchived/);
assert.match(call.query, /IsArchived, ArchivedDate/);
}
});
test('new borrow requests cannot target an archived asset', async () => {
const fixture = createFixture(() => ({ recordset: [{
AssetId: 17, IsArchived: true, Quantity: 10, EndingBalance: 7,
Borrower: 'Borrower A - so luong: 3'
}] }));
const response = await fixture.invoke('post', '/api/asset-borrows', {
body: { assetId: 17, requestType: 'borrow', quantity: 1 }
});
assert.equal(response.statusCode, 409);
assert.equal(fixture.transactions[0].rolledBack, true);
assert.equal(fixture.queries.length, 1);
assert.match(fixture.queries[0].query, /UPDLOCK, HOLDLOCK/);
});
test('pending borrow approval is blocked after its inventory was archived', async () => {
const fixture = createFixture(() => ({ recordset: [{
BorrowId: 21, AssetId: 17, IsArchived: true,
RequestType: 'borrow', RequestStatus: 'pending', BorrowQuantity: 1
}] }));
const response = await fixture.invoke('post', '/api/asset-borrows/:id/process', {
params: { id: '21' }, body: { action: 'approved' }
});
assert.equal(response.statusCode, 409);
assert.equal(fixture.transactions[0].rolledBack, true);
assert.equal(fixture.queries.length, 1);
});
test('return creation for an archived borrow retains the original asset and link', async () => {
const fixture = createFixture(({ query }) => {
if (query.includes('SELECT TOP 1')) return { recordset: [{
BorrowId: 21, AssetId: 17, IsArchived: true, RequestType: 'borrow',
RequestStatus: 'approved', BorrowerName: 'Borrower A', BorrowQuantity: 3,
ReturnedQuantity: 1, ActiveReturnQuantity: 1, Unit: 'cai', CreatedBy: 1,
Borrower: 'Borrower A - so luong: 2'
}] };
if (query.includes('SCOPE_IDENTITY')) return { recordset: [{ BorrowId: 22 }] };
return { recordset: [] };
});
const response = await fixture.invoke('post', '/api/asset-borrows/:id/return', {
params: { id: '21' }
});
assert.equal(response.statusCode, 200);
const insert = fixture.queries.find(call => call.query.includes('INSERT INTO AssetBorrowRequests'));
assert.equal(insert.inputs.assetId, 17);
assert.equal(insert.inputs.borrowQuantity, 2);
const link = fixture.queries.find(call => call.query.includes('INSERT INTO AssetBorrowRequestLinks'));
assert.equal(link.inputs.borrowId, 21);
assert.equal(link.inputs.returnId, 22);
assert.equal(fixture.transactions[0].committed, true);
});
test('approving an archived return updates only its original inventory and borrow', async () => {
const fixture = createFixture(({ query }) => {
if (query.includes('SELECT TOP 1')) return { recordset: [{
BorrowId: 22, AssetId: 17, IsArchived: true, RequestType: 'return',
RequestStatus: 'pending', BorrowerName: 'Borrower A', BorrowQuantity: 2,
Quantity: 10, ImportInPeriod: 0, ExportInPeriod: 2, EndingBalance: 8,
NewQuantity: 8, UsedQuantity: 0, Borrower: 'Borrower A - so luong: 2', CreatedBy: 1
}] };
if (query.includes('FROM AssetBorrowRequestLinks links')) {
return { recordset: [{ BorrowId: 21, Quantity: 2, BorrowQuantity: 3, ReturnedQuantity: 1 }] };
}
return { recordset: [] };
});
const response = await fixture.invoke('post', '/api/asset-borrows/:id/process', {
params: { id: '22' }, body: { action: 'approved' }
});
assert.equal(response.statusCode, 200);
const inventoryWrites = fixture.queries.filter(call => call.query.includes('UPDATE AssetInventory'));
assert.equal(inventoryWrites.length, 1);
assert.equal(inventoryWrites[0].inputs.assetId, 17);
assert.equal(inventoryWrites[0].inputs.borrower, null);
const borrowWrite = fixture.queries.find(call => call.query.includes('SET ReturnedQuantity'));
assert.equal(borrowWrite.inputs.borrowId, 21);
assert.equal(borrowWrite.inputs.quantity, 2);
assert.equal(fixture.transactions[0].committed, true);
});
test('import matches the active version of a reused asset code only', async () => {
const fixture = createFixture(() => ({ recordset: [{ MergeAction: 'INSERT' }] }));
const response = await fixture.invoke('post', '/api/assets/import', {
body: { rows: [{ assetCode: 'SAME-CODE', assetName: 'Replacement drill', model: 'D2', quantity: 5 }] }
});
assert.equal(response.statusCode, 200);
assert.equal(response.body.data.inserted, 1);
const merge = fixture.queries.find(call => call.query.includes('MERGE AssetInventory'));
assert.match(merge.query, /WITH \(HOLDLOCK\)/);
assert.match(merge.query, /ON target.AssetCode = source.AssetCode AND target.IsArchived = 0/);
assert.equal(merge.inputs.assetCode, 'SAME-CODE');
});
test('editing an archived asset cannot modify the historical inventory', async () => {
const fixture = createFixture();
const response = await fixture.invoke('put', '/api/assets/:id', {
params: { id: '17' }, body: { assetCode: 'SAME-CODE', assetName: 'Modified', model: 'D2' }
});
assert.equal(response.statusCode, 404);
assert.match(fixture.queries[0].query, /WHERE AssetId = @assetId AND IsArchived = 0/);
});

View File

@@ -1,258 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { randomBytes } = require('node:crypto');
const sql = require('mssql');
const { ensureAssetArchiveSchema } = require('../backend/asset-archive-schema');
// Explicit opt-in to a disposable, local SQL Server. Never read .env or reuse the
// application's database configuration. The runner creates its own database.
const integrationEnabled = process.env.ACCMANAGER_ARCHIVE_SQL_TEST === '1';
const integrationOptions = {
skip: integrationEnabled ? false : 'Set ACCMANAGER_ARCHIVE_SQL_TEST=1 to run against disposable local SQL Server',
timeout: 120_000
};
async function withTestDatabase(run) {
const password = process.env.ACCMANAGER_ARCHIVE_TEST_SQL_PASSWORD;
const port = Number(process.env.ACCMANAGER_ARCHIVE_TEST_SQL_PORT || 14339);
assert.ok(password, 'ACCMANAGER_ARCHIVE_TEST_SQL_PASSWORD must be explicitly set');
assert.ok(Number.isInteger(port) && port > 0 && port < 65536, 'Invalid local test SQL port');
const database = `AccManagerArchiveTest_${Date.now()}_${randomBytes(6).toString('hex')}`;
const config = {
server: '127.0.0.1',
port,
user: 'sa',
password,
database: 'master',
options: { encrypt: false, trustServerCertificate: true, enableArithAbort: true },
pool: { min: 0, max: 1, idleTimeoutMillis: 1000 },
connectionTimeout: 15_000,
requestTimeout: 30_000
};
const admin = new sql.ConnectionPool(config);
let created = false;
let pool;
try {
await admin.connect();
await admin.request().query(`CREATE DATABASE [${database}]`);
created = true;
pool = await new sql.ConnectionPool({ ...config, database }).connect();
await run(pool);
} finally {
if (pool) await pool.close();
try {
if (created) {
// This name is generated above, never accepted from the environment.
assert.match(database, /^AccManagerArchiveTest_\d+_[a-f0-9]{12}$/);
await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE`);
await admin.request().query(`DROP DATABASE [${database}]`);
}
} finally {
await admin.close();
}
}
}
const legacySchema = `
CREATE TABLE dbo.AssetInventory (
AssetId INT IDENTITY PRIMARY KEY,
AssetCode NVARCHAR(100) NOT NULL UNIQUE,
AssetName NVARCHAR(255) NOT NULL,
Quantity INT NOT NULL DEFAULT 0,
EndingBalance INT NOT NULL DEFAULT 0
);
-- Exercise removal of both an auto-named constraint and a standalone index.
CREATE UNIQUE INDEX LegacyAssetCodeIndex ON dbo.AssetInventory(AssetCode);
CREATE TABLE dbo.AssetBorrowRequests (
BorrowId INT IDENTITY PRIMARY KEY,
AssetId INT NOT NULL REFERENCES dbo.AssetInventory(AssetId) ON DELETE CASCADE,
RequestType NVARCHAR(20) NOT NULL,
RequestStatus NVARCHAR(20) NOT NULL,
BorrowerName NVARCHAR(100) NOT NULL,
BorrowQuantity INT NOT NULL,
ReturnedQuantity INT NOT NULL DEFAULT 0
);
CREATE TABLE dbo.AssetBorrowRequestLinks (
LinkId INT IDENTITY PRIMARY KEY,
BorrowId INT NOT NULL REFERENCES dbo.AssetBorrowRequests(BorrowId),
ReturnId INT NOT NULL REFERENCES dbo.AssetBorrowRequests(BorrowId),
Quantity INT NOT NULL
);
CREATE TABLE dbo.AssetExportHistory (
ExportHistoryId INT IDENTITY PRIMARY KEY,
AssetId INT NOT NULL REFERENCES dbo.AssetInventory(AssetId) ON DELETE CASCADE,
ExportQuantity INT NOT NULL
);
CREATE TABLE dbo.AssetDamageDisposalHistory (
DamageHistoryId INT IDENTITY PRIMARY KEY,
AssetId INT NOT NULL REFERENCES dbo.AssetInventory(AssetId) ON DELETE CASCADE,
ActionQuantity INT NOT NULL
);
`;
async function historySnapshot(pool) {
return (await pool.request().query(`
SELECT * FROM dbo.AssetBorrowRequests ORDER BY BorrowId;
SELECT * FROM dbo.AssetBorrowRequestLinks ORDER BY LinkId;
SELECT * FROM dbo.AssetExportHistory ORDER BY ExportHistoryId;
SELECT * FROM dbo.AssetDamageDisposalHistory ORDER BY DamageHistoryId;
`)).recordsets;
}
test('SQL Server migration preserves asset history across inventory replacement', integrationOptions, async t => {
await withTestDatabase(async pool => {
await pool.request().batch(legacySchema);
await pool.request().query(`
INSERT dbo.AssetInventory (AssetCode, AssetName, Quantity, EndingBalance) VALUES
('SHARED-CODE', N'Original drill', 10, 6),
('EXPORT-ONLY', N'Exported asset', 4, 3),
('DISPOSAL-ONLY', N'Disposed asset', 3, 2);
INSERT dbo.AssetBorrowRequests
(AssetId, RequestType, RequestStatus, BorrowerName, BorrowQuantity, ReturnedQuantity)
VALUES (1, 'borrow', 'approved', N'Loan owner', 5, 1),
(1, 'return', 'approved', N'Loan owner', 1, 0);
INSERT dbo.AssetBorrowRequestLinks (BorrowId, ReturnId, Quantity) VALUES (1, 2, 1);
INSERT dbo.AssetExportHistory (AssetId, ExportQuantity) VALUES (2, 1);
INSERT dbo.AssetDamageDisposalHistory (AssetId, ActionQuantity) VALUES (3, 1);
`);
const originalHistory = await historySnapshot(pool);
await t.test('legacy migration defaults existing assets to active and preserves every history row', async () => {
await ensureAssetArchiveSchema(pool);
const assets = (await pool.request().query('SELECT IsArchived, ArchivedDate FROM dbo.AssetInventory')).recordset;
assert.equal(assets.length, 3);
assert.ok(assets.every(asset => asset.IsArchived === false && asset.ArchivedDate === null));
assert.deepEqual(await historySnapshot(pool), originalHistory);
const keys = (await pool.request().query(`
SELECT delete_referential_action AS action
FROM sys.foreign_keys
WHERE referenced_object_id = OBJECT_ID('dbo.AssetInventory')
`)).recordset;
assert.equal(keys.length, 3);
assert.ok(keys.every(key => key.action === 0), 'All asset history foreign keys must prevent cascading deletes');
});
await t.test('archiving inventory retains original asset identity and outstanding loan quantity', async () => {
await pool.request().query(`
UPDATE dbo.AssetInventory
SET IsArchived = 1, ArchivedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
WHERE IsArchived = 0;
`);
assert.deepEqual(await historySnapshot(pool), originalHistory);
const result = await pool.request().query(`
SELECT br.BorrowId, ai.AssetCode, ai.AssetName, ai.IsArchived, ai.ArchivedDate,
br.BorrowQuantity - br.ReturnedQuantity AS OutstandingQuantity
FROM dbo.AssetBorrowRequests br
JOIN dbo.AssetInventory ai ON ai.AssetId = br.AssetId
WHERE br.RequestType = 'borrow' AND br.RequestStatus = 'approved'
AND br.BorrowQuantity > br.ReturnedQuantity;
SELECT COUNT(*) AS ActiveCount FROM dbo.AssetInventory WHERE IsArchived = 0;
`);
assert.equal(result.recordsets[1][0].ActiveCount, 0);
assert.equal(result.recordset.length, 1);
assert.equal(result.recordset[0].OutstandingQuantity, 4);
assert.equal(result.recordset[0].AssetName, 'Original drill');
assert.equal(result.recordset[0].IsArchived, true);
assert.ok(result.recordset[0].ArchivedDate instanceof Date);
});
await t.test('same-code replacement receives a new identity without relinking old history', async () => {
const inserted = await pool.request().query(`
INSERT dbo.AssetInventory (AssetCode, AssetName, Quantity, EndingBalance)
OUTPUT INSERTED.AssetId, INSERTED.IsArchived
VALUES ('SHARED-CODE', N'Replacement drill', 20, 20);
`);
assert.notEqual(inserted.recordset[0].AssetId, 1);
assert.equal(inserted.recordset[0].IsArchived, false);
assert.deepEqual(await historySnapshot(pool), originalHistory);
const assets = (await pool.request().query(`
SELECT ai.AssetName, ai.IsArchived, COUNT(br.BorrowId) AS HistoryCount
FROM dbo.AssetInventory ai
LEFT JOIN dbo.AssetBorrowRequests br ON br.AssetId = ai.AssetId
WHERE ai.AssetCode = 'SHARED-CODE'
GROUP BY ai.AssetName, ai.IsArchived ORDER BY ai.IsArchived DESC;
`)).recordset;
assert.deepEqual(assets, [
{ AssetName: 'Original drill', IsArchived: true, HistoryCount: 2 },
{ AssetName: 'Replacement drill', IsArchived: false, HistoryCount: 0 }
]);
});
await t.test('active duplicates remain forbidden while repeated migration accepts archived duplicates', async () => {
await assert.rejects(pool.request().query(`
INSERT dbo.AssetInventory (AssetCode, AssetName) VALUES ('SHARED-CODE', N'Duplicate');
`), error => [2601, 2627].includes(error.number));
await ensureAssetArchiveSchema(pool);
const indexes = (await pool.request().query(`
SELECT name, has_filter AS HasFilter
FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.AssetInventory')
AND is_unique = 1 AND is_primary_key = 0;
`)).recordset;
assert.deepEqual(indexes, [{ name: 'UX_AssetInventory_ActiveAssetCode', HasFilter: true }]);
assert.deepEqual(await historySnapshot(pool), originalHistory);
});
await t.test('physical deletion cannot cascade into loan, export, or disposal history', async () => {
for (const assetId of [1, 2, 3]) {
await assert.rejects(pool.request().input('id', sql.Int, assetId).query(`
DELETE dbo.AssetInventory WHERE AssetId = @id;
`), error => error.number === 547);
}
assert.deepEqual(await historySnapshot(pool), originalHistory);
});
await t.test('returning an old loan updates only its archived asset ledger', async () => {
const transaction = new sql.Transaction(pool);
await transaction.begin();
try {
await new sql.Request(transaction).query(`
UPDATE dbo.AssetInventory SET EndingBalance = EndingBalance + 2
WHERE AssetId = (SELECT AssetId FROM dbo.AssetBorrowRequests WHERE BorrowId = 1);
UPDATE dbo.AssetBorrowRequests SET ReturnedQuantity = ReturnedQuantity + 2 WHERE BorrowId = 1;
INSERT dbo.AssetBorrowRequests
(AssetId, RequestType, RequestStatus, BorrowerName, BorrowQuantity)
VALUES (1, 'return', 'approved', N'Loan owner', 2);
DECLARE @returnId INT = SCOPE_IDENTITY();
INSERT dbo.AssetBorrowRequestLinks (BorrowId, ReturnId, Quantity) VALUES (1, @returnId, 2);
`);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
const result = await pool.request().query(`
SELECT AssetName, EndingBalance FROM dbo.AssetInventory
WHERE AssetCode = 'SHARED-CODE' ORDER BY IsArchived DESC;
SELECT BorrowQuantity - ReturnedQuantity AS OutstandingQuantity
FROM dbo.AssetBorrowRequests WHERE BorrowId = 1;
SELECT SUM(Quantity) AS LinkedReturnedQuantity FROM dbo.AssetBorrowRequestLinks WHERE BorrowId = 1;
`);
assert.deepEqual(result.recordset, [
{ AssetName: 'Original drill', EndingBalance: 8 },
{ AssetName: 'Replacement drill', EndingBalance: 20 }
]);
assert.equal(result.recordsets[1][0].OutstandingQuantity, 2);
assert.equal(result.recordsets[2][0].LinkedReturnedQuantity, 3);
});
});
});
test('SQL Server archive migration rolls back partial DDL if active codes are already duplicated', integrationOptions, async () => {
await withTestDatabase(async pool => {
await pool.request().query(`
CREATE TABLE dbo.AssetInventory (
AssetId INT IDENTITY PRIMARY KEY,
AssetCode NVARCHAR(100) NOT NULL
);
INSERT dbo.AssetInventory (AssetCode) VALUES ('DUPLICATE'), ('DUPLICATE');
`);
await assert.rejects(ensureAssetArchiveSchema(pool));
const result = await pool.request().query(`
SELECT COL_LENGTH('dbo.AssetInventory', 'IsArchived') AS ArchiveColumn,
COL_LENGTH('dbo.AssetInventory', 'ArchivedDate') AS DateColumn;
SELECT COUNT(*) AS AssetCount FROM dbo.AssetInventory;
`);
assert.deepEqual(result.recordset[0], { ArchiveColumn: null, DateColumn: null });
assert.equal(result.recordsets[1][0].AssetCount, 2);
});
});

View File

@@ -1,173 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const source = fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8');
function fixture({ allowed = true, confirmed = true, responseSuccess = true } = {}) {
const requests = [];
const refreshed = [];
const notifications = [];
const button = { disabled: false };
const fetch = async (url, options) => {
requests.push({ url, options });
return { ok: responseSuccess, json: async () => ({ success: responseSuccess, data: { archivedCount: 2 } }) };
};
const document = {
addEventListener() {},
getElementById: id => id === 'archiveAllAssetsBtn' ? button : null
};
const context = vm.createContext({ document, window: { fetch }, fetch, console });
vm.runInContext(`${source}\napp = Object.create(AccountManager.prototype); globalThis.manager = app;`, context);
const manager = context.manager;
Object.assign(manager, {
apiBase: '/api',
assets: [{ AssetId: 1 }, { AssetId: 2 }],
archivedAssets: [],
assetBorrows: [],
selectedAssetIds: new Set([1, 2]),
canCurrentUserManageAssets: () => allowed,
ensureAssetManagePermission: () => allowed,
confirmBulkAssetDelete: async (count, all) => {
assert.equal(count, 2);
assert.equal(all, true);
return confirmed;
},
refreshAssetsUI: async () => { refreshed.push('assets'); manager.assets = []; },
refreshAssetBorrowsUI: async () => { refreshed.push('borrows'); },
notifySuccess: message => notifications.push(message),
notifyFailure: message => notifications.push(message),
notifyWarning: message => notifications.push(message)
});
return { manager, requests, refreshed, notifications, button };
}
function borrow(BorrowId, overrides = {}) {
return {
BorrowId, AssetId: BorrowId, AssetCode: 'SAME-CODE', AssetName: 'Máy đo',
RequestType: 'borrow', RequestStatus: 'approved', BorrowQuantity: 5,
ReturnedQuantity: 0, RemainingQuantity: 5, IsArchived: false,
...overrides
};
}
test('all history retains completed loans and partial loans with related returns', () => {
const { manager } = fixture();
manager.assetBorrows = [
borrow(1),
borrow(2, { RelatedReturnCount: 1, ReturnedQuantity: 2, RemainingQuantity: 3 }),
borrow(3, { RequestStatus: 'returned', ReturnedQuantity: 5, RemainingQuantity: 0 }),
borrow(4, { RequestType: 'return' })
];
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [1, 2, 3, 4]);
});
test('outstanding loans include archived, partial, and pending-return loans, excluding other statuses', () => {
const { manager } = fixture();
manager.assetBorrowTypeFilter = 'outstanding';
manager.assetBorrows = [
borrow(1),
borrow(2, { IsArchived: true, ReturnedQuantity: 2, RemainingQuantity: 3, RelatedReturnCount: 1 }),
borrow(3, { IsArchived: 1, RelatedReturnCount: 1, AvailableReturnQuantity: 0 }),
borrow(4, { RequestStatus: 'pending' }),
borrow(5, { RequestStatus: 'rejected' }),
borrow(6, { RequestStatus: 'returned' }),
borrow(7, { RemainingQuantity: 0 }),
borrow(8, { RequestType: 'return' })
];
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [1, 2, 3]);
manager.assetBorrowCatalogFilter = 'archived';
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [2, 3]);
manager.assetBorrowCatalogFilter = 'current';
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [1]);
manager.assetBorrowSearchTerm = 'missing';
assert.equal(manager.getFilteredAssetBorrows().length, 0);
});
test('partial archived loans permit another return only for quantity not reserved by pending returns', () => {
const { manager } = fixture();
const partial = borrow(1, { IsArchived: true, RelatedReturnCount: 1, ReturnedQuantity: 2, RemainingQuantity: 3, AvailableReturnQuantity: 3 });
assert.equal(manager.canCreateAssetReturnRequestFromBorrow(partial), true);
assert.equal(manager.canCreateAssetReturnRequestFromBorrow({ ...partial, AvailableReturnQuantity: 0 }), false);
assert.equal(manager.canCreateAssetReturnRequestFromBorrow({ ...partial, RequestStatus: 'pending' }), false);
assert.match(manager.getArchivedAssetBadgeHtml(partial), /Tài sản cũ/);
});
test('legacy borrower summaries remain visible without any borrow requests or current assets', () => {
const { manager } = fixture();
manager.assets = [];
manager.archivedAssets = [
{ AssetId: 1, AssetCode: 'REUSED', Borrower: [{ name: 'An', quantity: 2 }], ExportInPeriod: 2, IsArchived: true },
{ AssetId: 2, AssetCode: 'REUSED', Borrower: '', ExportInPeriod: 3, IsArchived: true },
{ AssetId: 3, AssetCode: 'DONE', Borrower: '', ExportInPeriod: 0, IsArchived: true }
];
assert.deepEqual(Array.from(manager.getArchivedOutstandingAssets(), row => row.AssetId), [1, 2]);
manager.archivedAssetSearchTerm = 'An';
assert.deepEqual(Array.from(manager.getArchivedOutstandingAssets(), row => row.AssetId), [1]);
manager.getCurrentUserBorrowerNameKeys = () => ['an'];
assert.deepEqual(Array.from(manager.getCurrentUserBorrowedAssets(), row => [row.AssetId, row.BorrowedQuantityByCurrentUser]), [[1, 2]]);
});
test('same-code current and archived assets remain separate in my borrowed assets', () => {
const { manager } = fixture();
manager.getCurrentUserBorrowerNameKeys = () => ['an'];
manager.assets = [{ AssetId: 2, AssetCode: 'REUSED', Borrower: [{ name: 'An', quantity: 1 }] }];
manager.archivedAssets = [{ AssetId: 1, AssetCode: 'REUSED', Borrower: [{ name: 'An', quantity: 3 }], IsArchived: true }];
assert.deepEqual(Array.from(manager.getCurrentUserBorrowedAssets(), row => [row.AssetId, row.BorrowedQuantityByCurrentUser]), [[2, 1], [1, 3]]);
});
test('archive all requires confirmation, calls archive endpoint once and refreshes both datasets', async () => {
const { manager, requests, refreshed, button } = fixture();
await manager.handleArchiveAllAssets();
assert.equal(requests.length, 1);
assert.equal(requests[0].url, '/api/assets/archive-all');
assert.equal(requests[0].options.method, 'POST');
assert.deepEqual(refreshed, ['assets', 'borrows']);
assert.equal(manager.selectedAssetIds.size, 0);
assert.equal(manager.assetPage, 1);
assert.equal(manager.archivingAssets, false);
assert.equal(button.disabled, true, 'Empty current catalog cannot be archived again');
});
test('cancel or missing permission leaves the catalog untouched', async () => {
for (const options of [{ confirmed: false }, { allowed: false }]) {
const { manager, requests, refreshed } = fixture(options);
await manager.handleArchiveAllAssets();
assert.equal(requests.length, 0);
assert.equal(refreshed.length, 0);
assert.equal(manager.selectedAssetIds.size, 2);
assert.equal(manager.assets.length, 2);
}
});
test('failed archive preserves current selection and supports retry', async () => {
const { manager, requests, refreshed, notifications, button } = fixture({ responseSuccess: false });
await manager.handleArchiveAllAssets();
assert.equal(requests.length, 1);
assert.equal(refreshed.length, 0);
assert.equal(manager.selectedAssetIds.size, 2);
assert.equal(manager.archivingAssets, false);
assert.equal(button.disabled, false);
assert.match(notifications[0], /thất bại/);
});
test('archive double clicks issue one request while confirmation is pending', async () => {
const { manager, requests } = fixture();
let resolveConfirmation;
manager.confirmBulkAssetDelete = () => new Promise(resolve => { resolveConfirmation = resolve; });
const pending = manager.handleArchiveAllAssets();
await manager.handleArchiveAllAssets();
resolveConfirmation(true);
await pending;
assert.equal(requests.length, 1);
});
test('archived pending borrows cannot be approved, while archived returns can', () => {
const { manager } = fixture();
const pending = borrow(1, { RequestStatus: 'pending', IsArchived: true });
assert.doesNotMatch(manager.buildPendingAssetRequestCardHtml(pending), /asset-request-approve-btn/);
assert.match(manager.buildPendingAssetRequestCardHtml(pending), /asset-request-reject-btn/);
assert.match(manager.buildPendingAssetRequestCardHtml({ ...pending, RequestType: 'return' }), /asset-request-approve-btn/);
});

View File

@@ -1,240 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const appSource = fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8');
// A small DOM fixture lets the actual event handler and cleanup methods run
// without starting authentication, network requests, or the application itself.
function createFixture() {
const elements = [];
const listeners = new Map();
class Element {
constructor({ id = '', classes = [], dataset = {}, parent = null } = {}) {
this.id = id;
this.dataset = dataset;
this.parentElement = parent;
this.children = [];
this.value = '';
this.isConnected = true;
const names = new Set(classes);
this.classList = {
contains: name => names.has(name),
add: (...added) => added.forEach(name => names.add(name)),
remove: (...removed) => removed.forEach(name => names.delete(name))
};
if (parent) parent.children.push(this);
elements.push(this);
}
matches(selector) {
if (selector === '[data-close-modal]') return 'closeModal' in this.dataset;
if (selector.startsWith('.')) {
return selector.slice(1).split('.').every(name => this.classList.contains(name));
}
return false;
}
closest(selector) {
return this.matches(selector) ? this : this.parentElement?.closest(selector) || null;
}
getAttribute(name) {
return name === 'data-close-modal' ? this.dataset.closeModal ?? null : null;
}
remove() {
this.isConnected = false;
this.children.forEach(child => child.remove());
}
set innerHTML(value) {
assert.equal(value, '', 'The fixture only supports clearing an existing container');
this.children.forEach(child => child.remove());
this.children = [];
}
get innerHTML() {
return this.children.length ? '<dialog />' : '';
}
}
const document = {
addEventListener(type, handler) {
if (!listeners.has(type)) listeners.set(type, []);
listeners.get(type).push(handler);
},
getElementById: id => elements.find(node => node.id === id && node.isConnected) || null,
querySelectorAll: selector => elements.filter(node => node.isConnected && node.matches(selector)),
contains: node => node.isConnected
};
const context = vm.createContext({
document,
Element,
HTMLElement: Element,
window: { fetch: async () => { throw new Error('Unexpected network request'); } },
console
});
vm.runInContext(`${appSource}\napp = Object.create(AccountManager.prototype); globalThis.manager = app;`, context);
const add = options => new Element(options);
const modal = (id, parent) => add({ id, parent, classes: ['modal-backdrop', 'open'] });
function dispatch(type, target, properties = {}) {
const event = {
target,
defaultPrevented: false,
preventDefault() { this.defaultPrevented = true; },
stopPropagation() {},
...properties
};
(listeners.get(type) || []).forEach(handler => handler(event));
return event;
}
return { manager: context.manager, document, listeners, add, modal, dispatch };
}
test('close buttons work after asynchronous modal insertion, including clicks on the icon', async () => {
const fixture = createFixture();
fixture.manager.setupModalCloseListeners();
await Promise.resolve(); // modals.html is fetched after listeners are installed.
const parent = fixture.modal('accountModal');
const other = fixture.modal('assetModal');
const button = fixture.add({ parent, dataset: { closeModal: 'accountModal' } });
const icon = fixture.add({ parent: button });
const event = fixture.dispatch('click', icon);
assert.equal(parent.classList.contains('open'), false);
assert.equal(other.classList.contains('open'), true);
assert.equal(event.defaultPrevented, true);
parent.classList.add('open');
fixture.dispatch('click', button);
assert.equal(parent.classList.contains('open'), false);
});
test('repeated setup installs one modal close handler', () => {
const fixture = createFixture();
fixture.manager.setupModalCloseListeners();
fixture.manager.setupModalCloseListeners();
const target = fixture.add({ dataset: { closeModal: 'accountModal' } });
const closed = [];
fixture.manager.closeModal = id => closed.push(id);
fixture.dispatch('click', target);
assert.deepEqual(closed, ['accountModal']);
assert.equal(fixture.listeners.get('click').length, 1);
});
test('backdrop clicks close their dialog, while clicks inside the form leave it open', () => {
const fixture = createFixture();
fixture.manager.setupModalCloseListeners();
const modal = fixture.modal('assetModal');
const other = fixture.modal('accountModal');
const content = fixture.add({ parent: modal });
const input = fixture.add({ parent: content });
fixture.dispatch('click', input);
assert.equal(modal.classList.contains('open'), true);
fixture.dispatch('click', modal);
assert.equal(modal.classList.contains('open'), false);
assert.equal(other.classList.contains('open'), true);
});
test('canceling destructive confirmations resolves false exactly once', async () => {
for (const [modalId, resolverField] of [
['assetRequestDeleteConfirmModal', 'pendingAssetRequestDeleteConfirmResolver'],
['bulkDeleteAssetsConfirmModal', 'pendingBulkAssetDeleteConfirmResolver']
]) {
const fixture = createFixture();
fixture.manager.setupModalCloseListeners();
const modal = fixture.modal(modalId);
const button = fixture.add({ parent: modal, dataset: { closeModal: modalId } });
const resolutions = [];
const pending = new Promise(resolve => {
fixture.manager[resolverField] = value => {
resolutions.push(value);
resolve(value);
};
});
fixture.dispatch('click', button);
fixture.dispatch('click', button);
assert.equal(await pending, false);
assert.deepEqual(resolutions, [false]);
assert.equal(fixture.manager[resolverField], undefined);
assert.equal(modal.classList.contains('open'), false);
}
});
test('closing consumable rejection and return dialogs clears pending input state', () => {
const fixture = createFixture();
const rejectModal = fixture.modal('consumableRequestRejectModal');
const idInput = fixture.add({ id: 'consumableRequestRejectIdInput', parent: rejectModal });
const reasonInput = fixture.add({ id: 'consumableRequestRejectReasonInput', parent: rejectModal });
idInput.value = '42';
reasonInput.value = 'Previous reason';
fixture.manager.pendingConsumableRequestRejectId = 42;
fixture.manager.closeModal(rejectModal.id);
assert.equal(rejectModal.classList.contains('open'), false);
assert.equal(idInput.value, '');
assert.equal(reasonInput.value, '');
assert.equal(fixture.manager.pendingConsumableRequestRejectId, undefined);
const returnModal = fixture.modal('consumableReturnModal');
fixture.manager.pendingConsumableReturnHistoryId = 99;
fixture.manager.closeModal(returnModal.id);
assert.equal(returnModal.classList.contains('open'), false);
assert.equal(fixture.manager.pendingConsumableReturnHistoryId, undefined);
});
test('closing dynamic user, role, profile and detail dialogs clears their containers', () => {
for (const modalId of ['userModal', 'roleModal', 'profileModal', 'userDetailsModal']) {
const fixture = createFixture();
fixture.manager.setupModalCloseListeners();
const container = fixture.add({ id: `${modalId}Container` });
const modal = fixture.modal(modalId, container);
const button = fixture.add({ parent: modal, dataset: { closeModal: modalId } });
fixture.dispatch('click', button);
assert.equal(container.innerHTML, '', modalId);
assert.equal(fixture.document.getElementById(modalId), null, modalId);
}
});
test('Escape closes dialogs through their cleanup handlers', () => {
const fixture = createFixture();
for (const method of [
'updateAccountDisplay', 'setupAccountRowListeners', 'setupFilters',
'setupResponsiveShell', 'closeMobileNav', 'closeNotificationPopover'
]) fixture.manager[method] = () => {};
fixture.manager.setupEventListeners();
const confirmation = fixture.modal('bulkDeleteAssetsConfirmModal');
let resolution;
fixture.manager.pendingBulkAssetDeleteConfirmResolver = value => { resolution = value; };
const container = fixture.add({ id: 'profileModalContainer' });
fixture.modal('profileModal', container);
const notification = fixture.modal('notificationComposerModal');
fixture.dispatch('keydown', null, { key: 'Escape' });
assert.equal(confirmation.classList.contains('open'), false);
assert.equal(resolution, false);
assert.equal(container.innerHTML, '');
assert.equal(notification.isConnected, false);
});
test('closing a missing modal is harmless', () => {
const fixture = createFixture();
assert.doesNotThrow(() => fixture.manager.closeModal('alreadyRemovedModal'));
});
test('static and dynamic modal close controls avoid inline scripts and form submission', () => {
for (const relativePath of ['public/modals.html', 'public/pages/index.html', 'public/js/app.js']) {
const source = fs.readFileSync(path.join(__dirname, '..', relativePath), 'utf8');
assert.doesNotMatch(source, /\bonclick\s*=\s*["'][^"']*\bclose\w*Modal\s*\(/i, relativePath);
const closeButtons = [...source.matchAll(/<button\b[^>]*\bdata-close-modal\s*=\s*["'][^"']+["'][^>]*>/g)];
if (relativePath !== 'public/pages/index.html') assert.ok(closeButtons.length > 0, relativePath);
for (const [button] of closeButtons) {
assert.match(button, /\btype\s*=\s*["']button["']/, `${relativePath}: ${button}`);
assert.doesNotMatch(button, /\bonclick\s*=/, `${relativePath}: ${button}`);
}
}
});

View File

@@ -1,149 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
process.env.NODE_ENV = 'test';
process.env.DATA_ENCRYPTION_SECRET = 'test-only-encryption-secret-with-more-than-32-characters';
const {
app,
encryptSensitiveValue,
decryptSensitiveValue,
hashSessionToken,
normalizeOptionalHttpUrl,
isPdfBuffer,
sanitizeDocumentFileName,
getDocumentContentDisposition,
normalizeNotificationActionUrl,
normalizeNotificationAudiences,
normalizeNotificationSeverity
} = require('../backend/server');
async function withTestServer(run) {
const server = app.listen(0, '127.0.0.1');
await new Promise((resolve, reject) => {
server.once('listening', resolve);
server.once('error', reject);
});
try {
const address = server.address();
await run(`http://127.0.0.1:${address.port}`);
} finally {
await new Promise(resolve => server.close(resolve));
}
}
test('stored credentials use authenticated encryption and round-trip safely', () => {
const plainText = 'example-password-value';
const first = encryptSensitiveValue(plainText);
const second = encryptSensitiveValue(plainText);
assert.match(first, /^enc:v2:/);
assert.notEqual(first, second);
assert.equal(first.includes(plainText), false);
assert.equal(decryptSensitiveValue(first), plainText);
assert.equal(decryptSensitiveValue(`${first}tampered`), null);
});
test('session tokens are stored as deterministic SHA-256 hashes', () => {
const token = 'a-private-random-session-token';
const hash = hashSessionToken(token);
assert.match(hash, /^[a-f0-9]{64}$/);
assert.equal(hash, hashSessionToken(token));
assert.equal(hash.includes(token), false);
});
test('application URLs accept only HTTP and HTTPS protocols', () => {
assert.equal(normalizeOptionalHttpUrl(''), '');
assert.equal(normalizeOptionalHttpUrl('javascript:alert(1)'), null);
assert.equal(normalizeOptionalHttpUrl('file:///etc/passwd'), null);
assert.match(normalizeOptionalHttpUrl('https://example.com/path'), /^https:\/\/example\.com\/path/);
});
test('notification links stay inside the application', () => {
assert.equal(normalizeNotificationActionUrl('#asset-borrows'), '#asset-borrows');
assert.equal(normalizeNotificationActionUrl('/pages/index.html#notifications'), '/pages/index.html#notifications');
assert.equal(normalizeNotificationActionUrl('https://attacker.example'), null);
assert.equal(normalizeNotificationActionUrl('//attacker.example/path'), null);
assert.equal(normalizeNotificationActionUrl('/\\attacker.example/path'), null);
assert.equal(normalizeNotificationActionUrl('javascript:alert(1)'), null);
});
test('notification audiences are normalized and deduplicated', () => {
assert.deepEqual(normalizeNotificationAudiences([]), []);
assert.deepEqual(normalizeNotificationAudiences([{ type: 'all' }]), [{ type: 'all', value: null }]);
assert.deepEqual(normalizeNotificationAudiences([
{ type: 'role', value: 'Admin' },
{ type: 'role', value: 'admin' },
{ type: 'user', value: '5' },
{ type: 'user', value: 'invalid' }
]), [
{ type: 'role', value: 'admin' },
{ type: 'user', value: '5' }
]);
assert.equal(normalizeNotificationSeverity('WARNING'), 'warning');
assert.equal(normalizeNotificationSeverity('unknown'), 'info');
});
test('PDF uploads require a PDF header and end-of-file marker', () => {
assert.equal(isPdfBuffer(Buffer.from('%PDF-1.7\nbody\n%%EOF')), true);
assert.equal(isPdfBuffer(Buffer.from('%PDF-1.7\nbody without trailer')), false);
assert.equal(isPdfBuffer(Buffer.from('<html>not a pdf</html>')), false);
});
test('document filenames and response headers cannot inject control characters', () => {
const safeName = sanitizeDocumentFileName('bao/cao\r\nInjected: value');
const longName = sanitizeDocumentFileName('a'.repeat(300));
const disposition = getDocumentContentDisposition('Báo cáo tháng 8.pdf');
assert.equal(safeName, 'bao_caoInjected_ value.pdf');
assert.equal(longName.length, 255);
assert.match(longName, /\.pdf$/);
assert.match(disposition, /^inline; filename="/);
assert.match(disposition, /filename\*=UTF-8''/);
assert.equal(disposition.includes('\r'), false);
assert.equal(disposition.includes('\n'), false);
});
test('forged legacy identity headers cannot bypass protected APIs', async () => {
await withTestServer(async baseUrl => {
const response = await fetch(`${baseUrl}/api/users`, {
headers: {
'x-user-id': '1',
'x-user-role': 'admin'
}
});
const body = await response.json();
assert.equal(response.status, 401);
assert.equal(body.success, false);
});
});
test('security headers and no-store API caching are enabled', async () => {
await withTestServer(async baseUrl => {
const response = await fetch(`${baseUrl}/api/health`);
assert.equal(response.status, 200);
assert.match(response.headers.get('content-security-policy') || '', /default-src 'self'/);
assert.match(response.headers.get('content-security-policy') || '', /script-src-attr 'none'/);
assert.equal(response.headers.get('x-powered-by'), null);
assert.equal(response.headers.get('cache-control'), 'no-store');
});
});
test('state-changing requests from untrusted origins are rejected before route handling', async () => {
await withTestServer(async baseUrl => {
const response = await fetch(`${baseUrl}/api/auth/login`, {
method: 'POST',
headers: {
Origin: 'https://attacker.example',
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: 'test', password: 'not-a-real-password' })
});
assert.equal(response.status, 403);
});
});