Compare commits
4 Commits
main
...
978411c9ec
| Author | SHA1 | Date | |
|---|---|---|---|
| 978411c9ec | |||
| 6dfac52c27 | |||
| 9072477e65 | |||
| ba2e449c88 |
34
.env
Normal file
34
.env
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
# AccManager Backend Configuration
|
||||||
|
|
||||||
|
# Application
|
||||||
|
NODE_ENV=production
|
||||||
|
|
||||||
|
# Host port exposed by docker compose
|
||||||
|
APP_PORT=3000
|
||||||
|
|
||||||
|
# Image used for server pull deployment
|
||||||
|
DOCKER_IMAGE=toiiiiday/accmanager:1.0.3
|
||||||
|
|
||||||
|
# Container app port
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# SQL Server Configuration
|
||||||
|
DB_SERVER=172.20.235.176
|
||||||
|
DB_USER=sa
|
||||||
|
DB_PASSWORD=robotics@2022
|
||||||
|
DB_NAME=AccManager
|
||||||
|
DB_ENCRYPT=false
|
||||||
|
DB_TRUST_CERTIFICATE=true
|
||||||
|
DB_CONNECT_TIMEOUT=30000
|
||||||
|
|
||||||
|
# Security
|
||||||
|
BCRYPT_ROUNDS=12
|
||||||
|
|
||||||
|
# Email Verification (SMTP)
|
||||||
|
APP_BASE_URL=https://accrobot.pnkr.asia/
|
||||||
|
SMTP_HOST=smtp.gmail.com
|
||||||
|
SMTP_PORT=587
|
||||||
|
SMTP_SECURE=false
|
||||||
|
SMTP_USER=robotics.gitlab.2fa@gmail.com
|
||||||
|
SMTP_PASS=jaljalhreomqruqo
|
||||||
|
SMTP_FROM=robotics.gitlab.2fa@gmail.com
|
||||||
48
.env.example
48
.env.example
@@ -1,48 +0,0 @@
|
|||||||
NODE_ENV=production
|
|
||||||
APP_PORT=3000
|
|
||||||
PORT=3000
|
|
||||||
TZ=Asia/Ho_Chi_Minh
|
|
||||||
APP_TIME_ZONE=Asia/Ho_Chi_Minh
|
|
||||||
|
|
||||||
# Database: never commit real credentials.
|
|
||||||
DB_SERVER=sql-server.internal
|
|
||||||
DB_USER=accmanager_app
|
|
||||||
DB_PASSWORD=replace-with-a-strong-database-password
|
|
||||||
DB_NAME=AccManager
|
|
||||||
DB_ENCRYPT=true
|
|
||||||
DB_TRUST_CERTIFICATE=false
|
|
||||||
DB_CONNECT_TIMEOUT=30000
|
|
||||||
|
|
||||||
# Generate a separate random value of at least 32 bytes and keep it stable.
|
|
||||||
# Changing this value without a key-rotation migration will make stored
|
|
||||||
# application credentials unreadable.
|
|
||||||
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://robot.dvex.io.vn
|
|
||||||
CORS_ALLOWED_ORIGINS=https://robot.dvex.io.vn
|
|
||||||
COOKIE_SECURE=true
|
|
||||||
TRUST_PROXY_HOPS=1
|
|
||||||
SESSION_TTL_HOURS=12
|
|
||||||
REMEMBER_SESSION_TTL_DAYS=14
|
|
||||||
ALLOW_SELF_REGISTRATION=true
|
|
||||||
|
|
||||||
# Only needed once when bootstrapping an empty database. Remove the password
|
|
||||||
# from the environment after the first administrator has been created.
|
|
||||||
INITIAL_ADMIN_USERNAME=admin
|
|
||||||
INITIAL_ADMIN_PASSWORD=
|
|
||||||
INITIAL_ADMIN_EMAIL=admin@example.internal
|
|
||||||
|
|
||||||
SMTP_HOST=
|
|
||||||
SMTP_PORT=587
|
|
||||||
SMTP_SECURE=false
|
|
||||||
SMTP_REQUIRE_TLS=true
|
|
||||||
SMTP_USER=
|
|
||||||
SMTP_PASS=
|
|
||||||
SMTP_FROM=
|
|
||||||
EMAIL_VERIFY_TOKEN_TTL_MINUTES=30
|
|
||||||
PASSWORD_RESET_TOKEN_TTL_MINUTES=30
|
|
||||||
|
|
||||||
# Maximum size for each uploaded document (1-100 MB), including robot attachments.
|
|
||||||
DOCUMENT_MAX_FILE_SIZE_MB=25
|
|
||||||
BIN
.gitignore
vendored
BIN
.gitignore
vendored
Binary file not shown.
296
DEPLOYMENT_GUIDE.md
Normal file
296
DEPLOYMENT_GUIDE.md
Normal file
@@ -0,0 +1,296 @@
|
|||||||
|
# 📘 Hướng dẫn Triển khai AccManager
|
||||||
|
|
||||||
|
Tài liệu này hướng dẫn chi tiết cách build Docker image, push lên registry, và triển khai trên server.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 Mục lục
|
||||||
|
|
||||||
|
1. [Chuẩn bị](#chuẩn-bị)
|
||||||
|
2. [Máy DEV: Build & Push Image](#máy-dev-build--push-image)
|
||||||
|
3. [Máy Server: Pull & Deploy](#máy-server-pull--deploy)
|
||||||
|
4. [Kiểm tra & Troubleshoot](#kiểm-tra--troubleshoot)
|
||||||
|
5. [Cập nhật bản mới](#cập-nhật-bản-mới)
|
||||||
|
6. [Public Domain qua Nginx Proxy Manager](#public-domain-qua-nginx-proxy-manager)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Chuẩn bị
|
||||||
|
|
||||||
|
### Tài khoản & Biến môi trường
|
||||||
|
|
||||||
|
1. **Docker Hub Account**: Tạo account tại https://hub.docker.com
|
||||||
|
- Username: `toiiiiday` (dùng username của bạn)
|
||||||
|
- Repository: `accmanager`
|
||||||
|
|
||||||
|
2. **File .env trên máy dev** - Kiểm tra nội dung:
|
||||||
|
```env
|
||||||
|
NODE_ENV=production
|
||||||
|
APP_PORT=3000
|
||||||
|
DOCKER_IMAGE=toiiiiday/accmanager:1.0.1
|
||||||
|
PORT=3000
|
||||||
|
DB_SERVER=172.20.235.176
|
||||||
|
DB_USER=sa
|
||||||
|
DB_PASSWORD=robotics@2022
|
||||||
|
DB_NAME=AccManager
|
||||||
|
DB_ENCRYPT=false
|
||||||
|
DB_TRUST_CERTIFICATE=true
|
||||||
|
DB_CONNECT_TIMEOUT=30000
|
||||||
|
BCRYPT_ROUNDS=12
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Thư mục trên server** - SSH vào server tạo:
|
||||||
|
```bash
|
||||||
|
mkdir -p ~/accmanager
|
||||||
|
cd ~/accmanager
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🖥️ Máy DEV: Build & Push Image
|
||||||
|
|
||||||
|
### Bước 1: Chọn version mới
|
||||||
|
|
||||||
|
Mỗi lần sửa code và muốn deploy, chọn một tag mới theo thứ tự tăng dần.
|
||||||
|
|
||||||
|
Ví dụ:
|
||||||
|
- Bản cũ đang chạy: `1.0.2`
|
||||||
|
- Bản mới sau khi sửa code: `1.0.3`
|
||||||
|
|
||||||
|
### Bước 2: Build image mới (trên máy DEV)
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd D:\RoboticsSource\AccManager
|
||||||
|
docker build -t toiiiiday/accmanager:"version" .
|
||||||
|
```
|
||||||
|
|
||||||
|
### Bước 3: Push image mới lên Docker Hub
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
docker push toiiiiday/accmanager:"version"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Bước 4: Kiểm tra image đã có trên registry
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
docker image ls | findstr toiiiiday/accmanager
|
||||||
|
```
|
||||||
|
|
||||||
|
Hoặc kiểm tra trên Docker Hub:
|
||||||
|
https://hub.docker.com/r/toiiiiday/accmanager/tags
|
||||||
|
|
||||||
|
### Bước 5: Cập nhật .env
|
||||||
|
|
||||||
|
Sửa dòng `DOCKER_IMAGE`:
|
||||||
|
```
|
||||||
|
DOCKER_IMAGE=toiiiiday/accmanager:"version"
|
||||||
|
```
|
||||||
|
|
||||||
|
Mẹo PowerShell (cập nhật nhanh):
|
||||||
|
```powershell
|
||||||
|
(Get-Content .env) -replace '^DOCKER_IMAGE=.*', 'DOCKER_IMAGE=toiiiiday/accmanager:1.0.3' | Set-Content .env
|
||||||
|
```
|
||||||
|
|
||||||
|
### Bước 6: Copy confi lên server
|
||||||
|
|
||||||
|
Từ máy dev:
|
||||||
|
```powershell
|
||||||
|
scp .env robotics@172.20.235.176:~/accmanager/.env
|
||||||
|
scp docker-compose.yml robotics@172.20.235.176:~/accmanager/docker-compose.yml
|
||||||
|
scp docker-compose.image.yml robotics@172.20.235.176:~/accmanager/docker-compose.image.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🐧 Máy Server: Pull & Deploy
|
||||||
|
|
||||||
|
### Bước 1: SSH vào server
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ssh robotics@172.20.235.176
|
||||||
|
```
|
||||||
|
|
||||||
|
### Bước 2: Vào thư mục deploy
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/accmanager
|
||||||
|
```
|
||||||
|
|
||||||
|
### Bước 3: Pull image mới và chạy lại container
|
||||||
|
|
||||||
|
```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
|
||||||
|
```
|
||||||
|
|
||||||
|
Kiểm tra trạng thái:
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.image.yml ps
|
||||||
|
```
|
||||||
|
|
||||||
|
Xem log:
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.image.yml logs -f accmanager
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✅ Kiểm tra & Troubleshoot
|
||||||
|
|
||||||
|
### Kiểm tra app chạy OK
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Kiểm tra container đang running
|
||||||
|
docker compose -f docker-compose.image.yml ps
|
||||||
|
|
||||||
|
# Xem log (tìm "Server running")
|
||||||
|
docker compose -f docker-compose.image.yml logs --tail=50 accmanager
|
||||||
|
|
||||||
|
|
||||||
|
### Nếu gặp lỗi
|
||||||
|
|
||||||
|
**Lỗi: "image not found"**
|
||||||
|
- Kiểm tra: `cat .env | grep DOCKER_IMAGE`
|
||||||
|
- Đảm bảo image đã push lên Docker Hub, kiểm tra: https://hub.docker.com/r/toiiiiday/accmanager
|
||||||
|
|
||||||
|
**Lỗi: "connection refused"**
|
||||||
|
- Kiểm tra DB Server có chạy: `ssh robotics@172.20.235.176`
|
||||||
|
- Kiểm tra DB credentials trong .env
|
||||||
|
|
||||||
|
**Lỗi: Container restart liên tục**
|
||||||
|
- Xem log: `docker compose -f docker-compose.image.yml logs --tail=100 accmanager`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔄 Cập nhật bản mới
|
||||||
|
|
||||||
|
Áp dụng đúng 8 bước sau cho mỗi lần sửa code:
|
||||||
|
|
||||||
|
### Trên máy DEV
|
||||||
|
|
||||||
|
1. Chọn version mới (ví dụ `1.0.3`)
|
||||||
|
2. Build:
|
||||||
|
```powershell
|
||||||
|
docker build -t toiiiiday/accmanager:"version" .
|
||||||
|
```
|
||||||
|
3. Push:
|
||||||
|
```powershell
|
||||||
|
docker push toiiiiday/accmanager:"version"
|
||||||
|
```
|
||||||
|
4. Cập nhật `.env`:
|
||||||
|
```env
|
||||||
|
DOCKER_IMAGE=toiiiiday/accmanager:"version"
|
||||||
|
```
|
||||||
|
5. Copy `.env` lên server:
|
||||||
|
```powershell
|
||||||
|
scp .env robotics@172.20.235.176:~/accmanager/.env
|
||||||
|
```
|
||||||
|
|
||||||
|
### Trên máy SERVER
|
||||||
|
|
||||||
|
6. SSH và vào thư mục deploy:
|
||||||
|
```bash
|
||||||
|
ssh robotics@172.20.235.176
|
||||||
|
cd ~/accmanager
|
||||||
|
```
|
||||||
|
7. Pull + Up:
|
||||||
|
```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
|
||||||
|
```
|
||||||
|
8. Kiểm tra bản mới đã chạy:
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.image.yml ps
|
||||||
|
docker compose -f docker-compose.image.yml logs --tail=50 accmanager
|
||||||
|
```
|
||||||
|
|
||||||
|
### Có cần gắn tag/version cho mỗi phiên bản mới không?
|
||||||
|
|
||||||
|
**Có, nên làm bắt buộc cho production.**
|
||||||
|
|
||||||
|
Lý do:
|
||||||
|
1. Tránh đè image cũ và tránh nhầm lẫn khi deploy.
|
||||||
|
2. Rollback nhanh về bản ổn định trước đó.
|
||||||
|
3. Truy vết được bản code nào đang chạy trên server.
|
||||||
|
4. Tránh rủi ro do dùng `latest` (khó kiểm soát).
|
||||||
|
|
||||||
|
Quy ước khuyến nghị:
|
||||||
|
- `1.0.2` -> fix nhỏ
|
||||||
|
- `1.1.0` -> thêm tính năng
|
||||||
|
- `2.0.0` -> thay đổi lớn/breaking
|
||||||
|
|
||||||
|
Ví dụ rollback về bản cũ `1.0.2`:
|
||||||
|
```env
|
||||||
|
DOCKER_IMAGE=toiiiiday/accmanager:1.0.2
|
||||||
|
```
|
||||||
|
```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
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🌐 Public Domain qua Nginx Proxy Manager
|
||||||
|
|
||||||
|
### Chuẩn bị
|
||||||
|
|
||||||
|
1. **Domain**
|
||||||
|
- Trỏ DNS A record về IP public nơi đặt Nginx Proxy Manager
|
||||||
|
|
||||||
|
2. **Firewall/Router**
|
||||||
|
- Mở inbound port 80, 443 từ Internet
|
||||||
|
- Port 3000 chỉ nội bộ (không public)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📝 Các file liên quan
|
||||||
|
|
||||||
|
- `docker-compose.yml` - Build local
|
||||||
|
- `docker-compose.image.yml` - Pull & run từ registry
|
||||||
|
- `.env` - Biến môi trường
|
||||||
|
- `.dockerignore` - Ignore file khi build
|
||||||
|
- `Dockerfile` - Config image
|
||||||
|
- `deploy-dev.ps1` - Script build & push (Windows)
|
||||||
|
- `deploy-server.sh` - Script pull & deploy (Linux)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 Tóm tắt quy trình
|
||||||
|
|
||||||
|
```
|
||||||
|
Máy DEV
|
||||||
|
├─ Chỉnh sửa code
|
||||||
|
├─ docker build -t toiiiiday/accmanager:X .
|
||||||
|
├─ docker push toiiiiday/accmanager:X
|
||||||
|
├─ sửa DOCKER_IMAGE trong .env
|
||||||
|
└─ scp .env server (copy env)
|
||||||
|
|
||||||
|
Máy Server
|
||||||
|
├─ ssh vào server
|
||||||
|
├─ cd ~/accmanager
|
||||||
|
├─ docker compose pull accmanager
|
||||||
|
└─ docker compose up -d accmanager
|
||||||
|
|
||||||
|
Nginx Proxy Manager
|
||||||
|
└─ Forward từ domain → http://172.20.235.176:3000
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💡 Mẹo
|
||||||
|
|
||||||
|
1. **Luôn tăng version tag**: 1.0.1 → 1.0.2 → 1.0.3
|
||||||
|
2. **Rollback nhanh**: Chỉ cần đổi DOCKER_IMAGE trong .env sang tag cũ rồi deploy lại
|
||||||
|
3. **Giữ log**: `docker compose logs --tail=1000 > backup.log`
|
||||||
|
4. **Restart container**: `docker compose -f docker-compose.image.yml restart accmanager`
|
||||||
|
5. **Xóa container cũ**: `docker compose -f docker-compose.image.yml down`
|
||||||
|
6. **Không dùng `latest` cho production**: luôn deploy bằng tag cụ thể
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Cần giúp? Xem log chi tiết:**
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.image.yml logs --tail=200 accmanager
|
||||||
|
```
|
||||||
@@ -1,10 +1,8 @@
|
|||||||
FROM node:22-bookworm-slim
|
FROM node:20-bookworm-slim
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
ENV TZ=Asia/Ho_Chi_Minh
|
|
||||||
ENV APP_TIME_ZONE=Asia/Ho_Chi_Minh
|
|
||||||
|
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
RUN npm ci --omit=dev && npm cache clean --force
|
RUN npm ci --omit=dev && npm cache clean --force
|
||||||
|
|||||||
62
README.md
Normal file
62
README.md
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
## 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. 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)
|
||||||
|
|
||||||
|
## 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: 3.0.0
|
||||||
|
Cập nhật: Tháng 4 năm 2026
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,183 +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 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);
|
|
||||||
});
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
const fs = require('node:fs');
|
|
||||||
const path = require('node:path');
|
|
||||||
|
|
||||||
async function ensureAssetArchiveSchema(pool) {
|
|
||||||
const migration = fs.readFileSync(path.join(__dirname, 'asset-archive-schema.sql'), 'utf8');
|
|
||||||
// Fail startup if preservation cannot be installed; partial migration rolls back.
|
|
||||||
await pool.request().batch(migration);
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { ensureAssetArchiveSchema };
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
-- Keep archived inventory rows as the identity and stock ledger for old loans.
|
|
||||||
-- Run before serving requests. This migration never archives or deletes data.
|
|
||||||
SET XACT_ABORT ON;
|
|
||||||
SET ANSI_NULLS ON;
|
|
||||||
SET QUOTED_IDENTIFIER ON;
|
|
||||||
SET ANSI_PADDING ON;
|
|
||||||
SET ANSI_WARNINGS ON;
|
|
||||||
SET CONCAT_NULL_YIELDS_NULL ON;
|
|
||||||
SET ARITHABORT ON;
|
|
||||||
SET NUMERIC_ROUNDABORT OFF;
|
|
||||||
|
|
||||||
BEGIN TRY
|
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
IF COL_LENGTH('dbo.AssetInventory', 'IsArchived') IS NULL
|
|
||||||
ALTER TABLE dbo.AssetInventory ADD IsArchived BIT NOT NULL
|
|
||||||
CONSTRAINT DF_AssetInventory_IsArchived DEFAULT(0) WITH VALUES;
|
|
||||||
|
|
||||||
IF COL_LENGTH('dbo.AssetInventory', 'ArchivedDate') IS NULL
|
|
||||||
ALTER TABLE dbo.AssetInventory ADD ArchivedDate DATETIME NULL;
|
|
||||||
|
|
||||||
-- Separate batch: the new column may not exist when this batch is compiled.
|
|
||||||
IF NOT EXISTS (
|
|
||||||
SELECT 1 FROM sys.indexes
|
|
||||||
WHERE object_id = OBJECT_ID('dbo.AssetInventory')
|
|
||||||
AND name = 'UX_AssetInventory_ActiveAssetCode'
|
|
||||||
)
|
|
||||||
EXEC(N'CREATE UNIQUE INDEX UX_AssetInventory_ActiveAssetCode
|
|
||||||
ON dbo.AssetInventory(AssetCode) WHERE IsArchived = 0;');
|
|
||||||
|
|
||||||
-- Replace the former global UNIQUE constraint/index, including generated names.
|
|
||||||
DECLARE @archiveIndexName SYSNAME, @archiveIsConstraint BIT, @archiveDynamicSql NVARCHAR(MAX);
|
|
||||||
DECLARE archive_code_indexes CURSOR LOCAL FAST_FORWARD FOR
|
|
||||||
SELECT i.name, i.is_unique_constraint
|
|
||||||
FROM sys.indexes i
|
|
||||||
WHERE i.object_id = OBJECT_ID('dbo.AssetInventory')
|
|
||||||
AND i.is_unique = 1 AND i.is_primary_key = 0
|
|
||||||
AND i.name <> 'UX_AssetInventory_ActiveAssetCode'
|
|
||||||
AND (SELECT COUNT(*) FROM sys.index_columns ic
|
|
||||||
WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id
|
|
||||||
AND ic.key_ordinal > 0) = 1
|
|
||||||
AND EXISTS (
|
|
||||||
SELECT 1 FROM sys.index_columns ic
|
|
||||||
JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
|
|
||||||
WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id
|
|
||||||
AND ic.key_ordinal = 1 AND c.name = 'AssetCode'
|
|
||||||
);
|
|
||||||
OPEN archive_code_indexes;
|
|
||||||
FETCH NEXT FROM archive_code_indexes INTO @archiveIndexName, @archiveIsConstraint;
|
|
||||||
WHILE @@FETCH_STATUS = 0
|
|
||||||
BEGIN
|
|
||||||
IF @archiveIsConstraint = 1
|
|
||||||
SET @archiveDynamicSql = N'ALTER TABLE dbo.AssetInventory DROP CONSTRAINT ' + QUOTENAME(@archiveIndexName);
|
|
||||||
ELSE
|
|
||||||
SET @archiveDynamicSql = N'DROP INDEX ' + QUOTENAME(@archiveIndexName) + N' ON dbo.AssetInventory';
|
|
||||||
EXEC sys.sp_executesql @archiveDynamicSql;
|
|
||||||
FETCH NEXT FROM archive_code_indexes INTO @archiveIndexName, @archiveIsConstraint;
|
|
||||||
END;
|
|
||||||
CLOSE archive_code_indexes;
|
|
||||||
DEALLOCATE archive_code_indexes;
|
|
||||||
|
|
||||||
-- Also protect history from accidental physical DELETEs outside the application.
|
|
||||||
DECLARE @archiveForeignKey SYSNAME, @archiveTable SYSNAME;
|
|
||||||
DECLARE archive_history_keys CURSOR LOCAL FAST_FORWARD FOR
|
|
||||||
SELECT fk.name, OBJECT_NAME(fk.parent_object_id)
|
|
||||||
FROM sys.foreign_keys fk
|
|
||||||
JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
|
|
||||||
JOIN sys.columns c ON c.object_id = fkc.parent_object_id AND c.column_id = fkc.parent_column_id
|
|
||||||
WHERE fk.referenced_object_id = OBJECT_ID('dbo.AssetInventory')
|
|
||||||
AND fk.parent_object_id IN (
|
|
||||||
OBJECT_ID('dbo.AssetBorrowRequests'), OBJECT_ID('dbo.AssetExportHistory'),
|
|
||||||
OBJECT_ID('dbo.AssetDamageDisposalHistory')
|
|
||||||
)
|
|
||||||
AND c.name = 'AssetId' AND fk.delete_referential_action <> 0;
|
|
||||||
OPEN archive_history_keys;
|
|
||||||
FETCH NEXT FROM archive_history_keys INTO @archiveForeignKey, @archiveTable;
|
|
||||||
WHILE @@FETCH_STATUS = 0
|
|
||||||
BEGIN
|
|
||||||
SET @archiveDynamicSql = N'ALTER TABLE dbo.' + QUOTENAME(@archiveTable)
|
|
||||||
+ N' DROP CONSTRAINT ' + QUOTENAME(@archiveForeignKey);
|
|
||||||
EXEC sys.sp_executesql @archiveDynamicSql;
|
|
||||||
SET @archiveDynamicSql = N'ALTER TABLE dbo.' + QUOTENAME(@archiveTable)
|
|
||||||
+ N' WITH CHECK ADD CONSTRAINT ' + QUOTENAME(@archiveForeignKey)
|
|
||||||
+ N' FOREIGN KEY (AssetId) REFERENCES dbo.AssetInventory(AssetId) ON DELETE NO ACTION;';
|
|
||||||
EXEC sys.sp_executesql @archiveDynamicSql;
|
|
||||||
FETCH NEXT FROM archive_history_keys INTO @archiveForeignKey, @archiveTable;
|
|
||||||
END;
|
|
||||||
CLOSE archive_history_keys;
|
|
||||||
DEALLOCATE archive_history_keys;
|
|
||||||
|
|
||||||
COMMIT TRANSACTION;
|
|
||||||
END TRY
|
|
||||||
BEGIN CATCH
|
|
||||||
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
|
|
||||||
THROW;
|
|
||||||
END CATCH;
|
|
||||||
@@ -1,185 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
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;
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
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(); }
|
|
||||||
});
|
|
||||||
@@ -1,176 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
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;
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,156 +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');
|
|
||||||
|
|
||||||
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, /<Máy khoan>/);
|
|
||||||
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');
|
|
||||||
});
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
// 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 };
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
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, /<img src=x onerror=alert\(1\)>/);
|
|
||||||
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);
|
|
||||||
});
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,166 +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 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, '<').replace(/>/g, '>') });
|
|
||||||
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/);
|
|
||||||
});
|
|
||||||
@@ -1,180 +0,0 @@
|
|||||||
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, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
||||||
}
|
|
||||||
|
|
||||||
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 };
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
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/);
|
|
||||||
});
|
|
||||||
@@ -1,358 +0,0 @@
|
|||||||
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));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
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;
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,186 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,212 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
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;
|
|
||||||
@@ -1,171 +0,0 @@
|
|||||||
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(); }
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,317 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,322 +0,0 @@
|
|||||||
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, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"') });
|
|
||||||
let html = manager.getRobotsContent();
|
|
||||||
assert.match(html, /<script>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);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
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;
|
|
||||||
8661
backend/server.js
8661
backend/server.js
File diff suppressed because it is too large
Load Diff
Binary file not shown.
1247
database/setup.sql
1247
database/setup.sql
File diff suppressed because it is too large
Load Diff
@@ -8,34 +8,19 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
NODE_ENV: ${NODE_ENV:-production}
|
NODE_ENV: ${NODE_ENV:-production}
|
||||||
PORT: 3000
|
PORT: 3000
|
||||||
TZ: ${TZ:-Asia/Ho_Chi_Minh}
|
DB_SERVER: ${DB_SERVER:-172.20.235.176}
|
||||||
APP_TIME_ZONE: ${APP_TIME_ZONE:-Asia/Ho_Chi_Minh}
|
DB_USER: ${DB_USER:-sa}
|
||||||
DB_SERVER: ${DB_SERVER:?DB_SERVER is required}
|
DB_PASSWORD: ${DB_PASSWORD:-changeme}
|
||||||
DB_USER: ${DB_USER:?DB_USER is required}
|
|
||||||
DB_PASSWORD: ${DB_PASSWORD:?DB_PASSWORD is required}
|
|
||||||
DB_NAME: ${DB_NAME:-AccManager}
|
DB_NAME: ${DB_NAME:-AccManager}
|
||||||
DB_ENCRYPT: ${DB_ENCRYPT:-false}
|
DB_ENCRYPT: ${DB_ENCRYPT:-false}
|
||||||
DB_TRUST_CERTIFICATE: ${DB_TRUST_CERTIFICATE:-true}
|
DB_TRUST_CERTIFICATE: ${DB_TRUST_CERTIFICATE:-true}
|
||||||
DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-30000}
|
DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-30000}
|
||||||
BCRYPT_ROUNDS: ${BCRYPT_ROUNDS:-12}
|
BCRYPT_ROUNDS: ${BCRYPT_ROUNDS:-12}
|
||||||
DATA_ENCRYPTION_SECRET: ${DATA_ENCRYPTION_SECRET:?DATA_ENCRYPTION_SECRET is required}
|
APP_BASE_URL: ${APP_BASE_URL:-http://localhost:3000}
|
||||||
APP_BASE_URL: ${APP_BASE_URL:?APP_BASE_URL is required}
|
|
||||||
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-}
|
|
||||||
COOKIE_SECURE: ${COOKIE_SECURE:-true}
|
|
||||||
SESSION_TTL_HOURS: ${SESSION_TTL_HOURS:-12}
|
|
||||||
REMEMBER_SESSION_TTL_DAYS: ${REMEMBER_SESSION_TTL_DAYS:-14}
|
|
||||||
ALLOW_SELF_REGISTRATION: ${ALLOW_SELF_REGISTRATION:-true}
|
|
||||||
TRUST_PROXY_HOPS: ${TRUST_PROXY_HOPS:-1}
|
|
||||||
INITIAL_ADMIN_USERNAME: ${INITIAL_ADMIN_USERNAME:-admin}
|
|
||||||
INITIAL_ADMIN_PASSWORD: ${INITIAL_ADMIN_PASSWORD:-}
|
|
||||||
INITIAL_ADMIN_EMAIL: ${INITIAL_ADMIN_EMAIL:-admin@accmanager.local}
|
|
||||||
SMTP_HOST: ${SMTP_HOST:-}
|
SMTP_HOST: ${SMTP_HOST:-}
|
||||||
SMTP_PORT: ${SMTP_PORT:-587}
|
SMTP_PORT: ${SMTP_PORT:-587}
|
||||||
SMTP_SECURE: ${SMTP_SECURE:-false}
|
SMTP_SECURE: ${SMTP_SECURE:-false}
|
||||||
SMTP_REQUIRE_TLS: ${SMTP_REQUIRE_TLS:-true}
|
|
||||||
SMTP_USER: ${SMTP_USER:-}
|
SMTP_USER: ${SMTP_USER:-}
|
||||||
SMTP_PASS: ${SMTP_PASS:-}
|
SMTP_PASS: ${SMTP_PASS:-}
|
||||||
SMTP_FROM: ${SMTP_FROM:-}
|
SMTP_FROM: ${SMTP_FROM:-}
|
||||||
EMAIL_VERIFY_TOKEN_TTL_MINUTES: ${EMAIL_VERIFY_TOKEN_TTL_MINUTES:-30}
|
EMAIL_VERIFY_TOKEN_TTL_MINUTES: ${EMAIL_VERIFY_TOKEN_TTL_MINUTES:-30}
|
||||||
PASSWORD_RESET_TOKEN_TTL_MINUTES: ${PASSWORD_RESET_TOKEN_TTL_MINUTES:-30}
|
|
||||||
DOCUMENT_MAX_FILE_SIZE_MB: ${DOCUMENT_MAX_FILE_SIZE_MB:-25}
|
|
||||||
|
|||||||
@@ -10,34 +10,19 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
NODE_ENV: production
|
NODE_ENV: production
|
||||||
PORT: 3000
|
PORT: 3000
|
||||||
TZ: ${TZ:-Asia/Ho_Chi_Minh}
|
DB_SERVER: ${DB_SERVER:-172.20.235.176}
|
||||||
APP_TIME_ZONE: ${APP_TIME_ZONE:-Asia/Ho_Chi_Minh}
|
DB_USER: ${DB_USER:-sa}
|
||||||
DB_SERVER: ${DB_SERVER:?DB_SERVER is required}
|
DB_PASSWORD: ${DB_PASSWORD:-changeme}
|
||||||
DB_USER: ${DB_USER:?DB_USER is required}
|
|
||||||
DB_PASSWORD: ${DB_PASSWORD:?DB_PASSWORD is required}
|
|
||||||
DB_NAME: ${DB_NAME:-AccManager}
|
DB_NAME: ${DB_NAME:-AccManager}
|
||||||
DB_ENCRYPT: ${DB_ENCRYPT:-false}
|
DB_ENCRYPT: ${DB_ENCRYPT:-false}
|
||||||
DB_TRUST_CERTIFICATE: ${DB_TRUST_CERTIFICATE:-true}
|
DB_TRUST_CERTIFICATE: ${DB_TRUST_CERTIFICATE:-true}
|
||||||
DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-30000}
|
DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-30000}
|
||||||
BCRYPT_ROUNDS: ${BCRYPT_ROUNDS:-12}
|
BCRYPT_ROUNDS: ${BCRYPT_ROUNDS:-12}
|
||||||
DATA_ENCRYPTION_SECRET: ${DATA_ENCRYPTION_SECRET:?DATA_ENCRYPTION_SECRET is required}
|
APP_BASE_URL: ${APP_BASE_URL:-http://localhost:3000}
|
||||||
APP_BASE_URL: ${APP_BASE_URL:?APP_BASE_URL is required}
|
|
||||||
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-}
|
|
||||||
COOKIE_SECURE: ${COOKIE_SECURE:-true}
|
|
||||||
SESSION_TTL_HOURS: ${SESSION_TTL_HOURS:-12}
|
|
||||||
REMEMBER_SESSION_TTL_DAYS: ${REMEMBER_SESSION_TTL_DAYS:-14}
|
|
||||||
ALLOW_SELF_REGISTRATION: ${ALLOW_SELF_REGISTRATION:-true}
|
|
||||||
TRUST_PROXY_HOPS: ${TRUST_PROXY_HOPS:-1}
|
|
||||||
INITIAL_ADMIN_USERNAME: ${INITIAL_ADMIN_USERNAME:-admin}
|
|
||||||
INITIAL_ADMIN_PASSWORD: ${INITIAL_ADMIN_PASSWORD:-}
|
|
||||||
INITIAL_ADMIN_EMAIL: ${INITIAL_ADMIN_EMAIL:-admin@accmanager.local}
|
|
||||||
SMTP_HOST: ${SMTP_HOST:-}
|
SMTP_HOST: ${SMTP_HOST:-}
|
||||||
SMTP_PORT: ${SMTP_PORT:-587}
|
SMTP_PORT: ${SMTP_PORT:-587}
|
||||||
SMTP_SECURE: ${SMTP_SECURE:-false}
|
SMTP_SECURE: ${SMTP_SECURE:-false}
|
||||||
SMTP_REQUIRE_TLS: ${SMTP_REQUIRE_TLS:-true}
|
|
||||||
SMTP_USER: ${SMTP_USER:-}
|
SMTP_USER: ${SMTP_USER:-}
|
||||||
SMTP_PASS: ${SMTP_PASS:-}
|
SMTP_PASS: ${SMTP_PASS:-}
|
||||||
SMTP_FROM: ${SMTP_FROM:-}
|
SMTP_FROM: ${SMTP_FROM:-}
|
||||||
EMAIL_VERIFY_TOKEN_TTL_MINUTES: ${EMAIL_VERIFY_TOKEN_TTL_MINUTES:-30}
|
EMAIL_VERIFY_TOKEN_TTL_MINUTES: ${EMAIL_VERIFY_TOKEN_TTL_MINUTES:-30}
|
||||||
PASSWORD_RESET_TOKEN_TTL_MINUTES: ${PASSWORD_RESET_TOKEN_TTL_MINUTES:-30}
|
|
||||||
DOCUMENT_MAX_FILE_SIZE_MB: ${DOCUMENT_MAX_FILE_SIZE_MB:-25}
|
|
||||||
|
|||||||
2685
package-lock.json
generated
2685
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
18
package.json
18
package.json
@@ -6,9 +6,6 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node backend/server.js",
|
"start": "node backend/server.js",
|
||||||
"dev": "nodemon backend/server.js",
|
"dev": "nodemon backend/server.js",
|
||||||
"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",
|
"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"
|
"watch:css": "tailwindcss -c tailwind.config.js -i ./public/css/tailwind.css -o ./public/css/main.css --watch"
|
||||||
},
|
},
|
||||||
@@ -20,20 +17,15 @@
|
|||||||
],
|
],
|
||||||
"author": "",
|
"author": "",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
|
||||||
"node": ">=22.0.0"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bcrypt": "^6.0.0",
|
"bcrypt": "^6.0.0",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^16.3.1",
|
"dotenv": "^16.3.1",
|
||||||
"express": "^5.2.1",
|
"express": "^4.18.2",
|
||||||
"express-rate-limit": "^8.6.0",
|
"mssql": "^9.1.1",
|
||||||
"helmet": "^8.3.0",
|
"multer": "^2.1.1",
|
||||||
"mssql": "^12.7.0",
|
"nodemailer": "^8.0.4",
|
||||||
"multer": "^2.2.0",
|
"xlsx": "^0.18.5"
|
||||||
"nodemailer": "^9.0.3",
|
|
||||||
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/container-queries": "^0.1.1",
|
"@tailwindcss/container-queries": "^0.1.1",
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
.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; }
|
|
||||||
}
|
|
||||||
@@ -1,364 +0,0 @@
|
|||||||
/* 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;
|
|
||||||
}
|
|
||||||
@@ -1,139 +0,0 @@
|
|||||||
/* 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
@@ -1,818 +0,0 @@
|
|||||||
/* Mobile-first usability layer for the AccManager application. */
|
|
||||||
|
|
||||||
html {
|
|
||||||
min-width: 320px;
|
|
||||||
overflow-x: hidden;
|
|
||||||
-webkit-text-size-adjust: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
body {
|
|
||||||
min-width: 320px;
|
|
||||||
}
|
|
||||||
|
|
||||||
button,
|
|
||||||
a,
|
|
||||||
input,
|
|
||||||
select,
|
|
||||||
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;
|
|
||||||
-webkit-overflow-scrolling: touch;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Keep every top-bar overlay above sticky table headers. Sticky cells can use
|
|
||||||
large local z-index values, so the content area needs its own lower context. */
|
|
||||||
#appMain > header {
|
|
||||||
position: relative;
|
|
||||||
z-index: 30;
|
|
||||||
overflow: visible;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent {
|
|
||||||
position: relative;
|
|
||||||
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,
|
|
||||||
#mainContent {
|
|
||||||
min-height: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
body.mobile-nav-open {
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
#appSidebar {
|
|
||||||
padding-top: env(safe-area-inset-top);
|
|
||||||
padding-bottom: env(safe-area-inset-bottom);
|
|
||||||
}
|
|
||||||
|
|
||||||
#appSidebar nav {
|
|
||||||
min-height: 0;
|
|
||||||
overflow-y: auto;
|
|
||||||
overscroll-behavior: contain;
|
|
||||||
padding-bottom: 1rem;
|
|
||||||
-webkit-overflow-scrolling: touch;
|
|
||||||
}
|
|
||||||
|
|
||||||
#appMain > header {
|
|
||||||
min-height: 3.5rem;
|
|
||||||
height: auto;
|
|
||||||
padding-top: max(0.35rem, env(safe-area-inset-top));
|
|
||||||
padding-bottom: 0.35rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mobileMenuBtn,
|
|
||||||
#profileBtn,
|
|
||||||
#logoutBtn,
|
|
||||||
#notificationsBellBtn,
|
|
||||||
#pendingAssetRequestsBtn {
|
|
||||||
min-width: 2.75rem;
|
|
||||||
min-height: 2.75rem;
|
|
||||||
touch-action: manipulation;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pendingAssetRequestsBtn {
|
|
||||||
justify-content: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent > [class*="-page"] {
|
|
||||||
width: 100%;
|
|
||||||
min-width: 0;
|
|
||||||
padding: 0.875rem;
|
|
||||||
gap: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-page {
|
|
||||||
padding-bottom: calc(0.875rem + env(safe-area-inset-bottom)) !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-header,
|
|
||||||
.page-header {
|
|
||||||
margin-bottom: 0.875rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-header > div,
|
|
||||||
.page-header > div {
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-header h1,
|
|
||||||
.page-header h1,
|
|
||||||
.users-page h1 {
|
|
||||||
font-size: 1.35rem;
|
|
||||||
line-height: 1.25;
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-header p,
|
|
||||||
.page-header p,
|
|
||||||
.users-page h1 + p {
|
|
||||||
margin-top: 0.25rem;
|
|
||||||
font-size: 0.75rem;
|
|
||||||
line-height: 1.4;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-actions,
|
|
||||||
.asset-header-actions,
|
|
||||||
.consumable-header-actions {
|
|
||||||
max-width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.page-header > button,
|
|
||||||
.dashboard-actions > button,
|
|
||||||
.page-header .asset-header-actions > button,
|
|
||||||
.page-header .consumable-header-actions > button {
|
|
||||||
min-height: 2.75rem;
|
|
||||||
justify-content: center;
|
|
||||||
touch-action: manipulation;
|
|
||||||
}
|
|
||||||
|
|
||||||
.page-filters,
|
|
||||||
.users-controls {
|
|
||||||
margin-bottom: 0.875rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.page-filters > *,
|
|
||||||
.users-controls > * {
|
|
||||||
min-width: 0;
|
|
||||||
max-width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.page-filters > div,
|
|
||||||
.users-controls > div {
|
|
||||||
align-items: stretch;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 0.35rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.page-filters input,
|
|
||||||
.page-filters select,
|
|
||||||
.users-controls input,
|
|
||||||
.users-controls select,
|
|
||||||
.modal-content input,
|
|
||||||
.modal-content select,
|
|
||||||
.modal-content textarea {
|
|
||||||
width: 100%;
|
|
||||||
min-height: 2.75rem;
|
|
||||||
font-size: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Keep the asset and consumable toolbars compact so the data remains
|
|
||||||
visible on tablets and phones. */
|
|
||||||
.asset-borrows-page .compact-page-actions,
|
|
||||||
.consumable-exports-page .compact-page-actions,
|
|
||||||
.assets-page .asset-header-actions,
|
|
||||||
.consumables-page .consumable-header-actions {
|
|
||||||
display: flex;
|
|
||||||
width: 100%;
|
|
||||||
max-width: 100%;
|
|
||||||
flex-flow: row nowrap;
|
|
||||||
gap: 0.5rem;
|
|
||||||
overflow-x: auto;
|
|
||||||
overscroll-behavior-x: contain;
|
|
||||||
padding: 0.125rem 0.125rem 0.375rem;
|
|
||||||
scrollbar-width: thin;
|
|
||||||
-webkit-overflow-scrolling: touch;
|
|
||||||
}
|
|
||||||
|
|
||||||
.asset-borrows-page .compact-page-actions > button,
|
|
||||||
.consumable-exports-page .compact-page-actions > button,
|
|
||||||
.assets-page .asset-header-actions > button,
|
|
||||||
.consumables-page .consumable-header-actions > button {
|
|
||||||
width: auto;
|
|
||||||
min-width: max-content;
|
|
||||||
min-height: 2.5rem;
|
|
||||||
flex: 0 0 auto;
|
|
||||||
padding-top: 0.5rem;
|
|
||||||
padding-bottom: 0.5rem;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters {
|
|
||||||
display: grid !important;
|
|
||||||
align-items: end !important;
|
|
||||||
gap: 0.625rem !important;
|
|
||||||
padding: 0.625rem;
|
|
||||||
border: 1px solid #e2e8f0;
|
|
||||||
border-radius: 0.75rem;
|
|
||||||
background: rgb(248 250 252 / 0.82);
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters.asset-borrow-filter-bar {
|
|
||||||
grid-template-columns: minmax(10rem, 0.35fr) minmax(0, 1fr);
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters.asset-filter-bar {
|
|
||||||
grid-template-columns: minmax(9rem, 0.3fr) minmax(14rem, 1fr) max-content;
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters.consumable-filter-bar {
|
|
||||||
grid-template-columns: minmax(8rem, 0.25fr) minmax(8rem, 0.25fr) minmax(14rem, 1fr);
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters.consumable-export-filter-bar {
|
|
||||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters > div {
|
|
||||||
width: auto;
|
|
||||||
min-width: 0;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: stretch;
|
|
||||||
gap: 0.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters input,
|
|
||||||
.compact-page-filters select {
|
|
||||||
width: 100%;
|
|
||||||
min-width: 0;
|
|
||||||
min-height: 2.5rem;
|
|
||||||
font-size: 0.875rem;
|
|
||||||
line-height: 1.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters .compact-filter-action {
|
|
||||||
width: auto;
|
|
||||||
min-width: max-content;
|
|
||||||
min-height: 2.5rem;
|
|
||||||
align-self: end;
|
|
||||||
justify-content: center;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-stats,
|
|
||||||
.apps-stats {
|
|
||||||
gap: 0.75rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-stats > *,
|
|
||||||
.apps-stats > * {
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.table-wrap {
|
|
||||||
min-width: 0;
|
|
||||||
scrollbar-width: thin;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Tables are progressively enhanced with data labels by app.js. */
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) {
|
|
||||||
display: block;
|
|
||||||
width: 100%;
|
|
||||||
min-width: 0 !important;
|
|
||||||
border-collapse: separate;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > thead {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: minmax(0, 1fr);
|
|
||||||
gap: 0.75rem;
|
|
||||||
padding: 0.75rem;
|
|
||||||
background: rgb(248 250 252 / 0.72);
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody > tr {
|
|
||||||
display: grid;
|
|
||||||
width: 100%;
|
|
||||||
min-width: 0;
|
|
||||||
overflow: hidden;
|
|
||||||
border: 1px solid #e2e8f0;
|
|
||||||
border-radius: 0.75rem;
|
|
||||||
background: #fff;
|
|
||||||
box-shadow: 0 1px 2px rgb(15 23 42 / 0.05);
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody > tr:hover {
|
|
||||||
background: #fff;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody > tr > td {
|
|
||||||
position: static !important;
|
|
||||||
z-index: auto !important;
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: minmax(5.75rem, 36%) minmax(0, 1fr);
|
|
||||||
align-items: start;
|
|
||||||
gap: 0.75rem;
|
|
||||||
width: auto !important;
|
|
||||||
min-width: 0 !important;
|
|
||||||
max-width: none !important;
|
|
||||||
padding: 0.65rem 0.75rem;
|
|
||||||
border: 0;
|
|
||||||
border-bottom: 1px solid #f1f5f9;
|
|
||||||
background: transparent !important;
|
|
||||||
box-shadow: none !important;
|
|
||||||
color: #334155;
|
|
||||||
text-align: left !important;
|
|
||||||
white-space: normal !important;
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody > tr > td:last-child {
|
|
||||||
border-bottom: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody > tr > td::before {
|
|
||||||
content: attr(data-label);
|
|
||||||
color: #64748b;
|
|
||||||
font-size: 0.625rem;
|
|
||||||
font-weight: 800;
|
|
||||||
line-height: 1.35;
|
|
||||||
letter-spacing: 0.06em;
|
|
||||||
text-transform: uppercase;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody > tr > td[colspan] {
|
|
||||||
display: block;
|
|
||||||
padding: 1.5rem 1rem;
|
|
||||||
text-align: center !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody > tr > td[colspan]::before {
|
|
||||||
content: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody > tr > td > * {
|
|
||||||
min-width: 0;
|
|
||||||
max-width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody > tr > td .truncate {
|
|
||||||
white-space: normal;
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody > tr > td .inline-flex {
|
|
||||||
flex-wrap: wrap;
|
|
||||||
justify-content: flex-start;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) button,
|
|
||||||
#mainContent .asset-mobile-card button,
|
|
||||||
#mainContent .consumable-mobile-card button {
|
|
||||||
min-width: 2.5rem;
|
|
||||||
min-height: 2.5rem;
|
|
||||||
touch-action: manipulation;
|
|
||||||
}
|
|
||||||
|
|
||||||
.page-pager {
|
|
||||||
width: 100%;
|
|
||||||
padding: 0.75rem !important;
|
|
||||||
padding-bottom: max(0.75rem, env(safe-area-inset-bottom)) !important;
|
|
||||||
line-height: 1.4;
|
|
||||||
}
|
|
||||||
|
|
||||||
.page-pager > div,
|
|
||||||
.page-pager > span {
|
|
||||||
max-width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.page-pager button {
|
|
||||||
min-width: 2.75rem;
|
|
||||||
min-height: 2.5rem;
|
|
||||||
touch-action: manipulation;
|
|
||||||
}
|
|
||||||
|
|
||||||
.modal-backdrop {
|
|
||||||
padding-top: env(safe-area-inset-top);
|
|
||||||
}
|
|
||||||
|
|
||||||
.modal-backdrop .modal-content {
|
|
||||||
max-width: none !important;
|
|
||||||
max-height: calc(100dvh - 0.75rem - env(safe-area-inset-top)) !important;
|
|
||||||
margin: 0.375rem !important;
|
|
||||||
margin-bottom: 0 !important;
|
|
||||||
border-bottom-right-radius: 0;
|
|
||||||
border-bottom-left-radius: 0;
|
|
||||||
overscroll-behavior: contain;
|
|
||||||
-webkit-overflow-scrolling: touch;
|
|
||||||
}
|
|
||||||
|
|
||||||
.modal-content > .p-6,
|
|
||||||
.modal-content > form.p-6,
|
|
||||||
.modal-content > form > .p-6 {
|
|
||||||
padding: 1rem !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.modal-content > .px-6,
|
|
||||||
.modal-content > form > .px-6 {
|
|
||||||
padding-right: 1rem !important;
|
|
||||||
padding-left: 1rem !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.modal-content .grid-cols-2,
|
|
||||||
.modal-content .grid-cols-4 {
|
|
||||||
grid-template-columns: minmax(0, 1fr);
|
|
||||||
}
|
|
||||||
|
|
||||||
.modal-content h2,
|
|
||||||
.modal-content h3 {
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
|
|
||||||
.modal-content > .flex:last-child,
|
|
||||||
.modal-content > form > .flex:last-child,
|
|
||||||
.modal-content > form > div > .flex:last-child {
|
|
||||||
flex-wrap: wrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.modal-content > .flex:last-child > button,
|
|
||||||
.modal-content > form > .flex:last-child > button,
|
|
||||||
.modal-content > form > div > .flex:last-child > button {
|
|
||||||
min-height: 2.75rem;
|
|
||||||
flex: 1 1 8rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.modal-content .overflow-x-auto table {
|
|
||||||
min-width: 42rem !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
#NotiflixNotifyWrap {
|
|
||||||
right: 0.5rem !important;
|
|
||||||
left: 0.5rem !important;
|
|
||||||
width: auto !important;
|
|
||||||
max-width: none !important;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 560px) {
|
|
||||||
#appMain > header .topbar-actions {
|
|
||||||
gap: 0.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
#notificationPopover {
|
|
||||||
position: fixed;
|
|
||||||
top: calc(3.75rem + env(safe-area-inset-top));
|
|
||||||
right: 0.75rem;
|
|
||||||
left: 0.75rem;
|
|
||||||
width: auto;
|
|
||||||
max-height: calc(100dvh - 4.5rem - env(safe-area-inset-top));
|
|
||||||
}
|
|
||||||
|
|
||||||
#notificationPopoverList {
|
|
||||||
max-height: calc(100dvh - 12rem - env(safe-area-inset-top));
|
|
||||||
}
|
|
||||||
|
|
||||||
#pendingAssetRequestsBtn > span:not(.material-symbols-outlined):not(#pendingAssetRequestsBadge) {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pendingAssetRequestsBtn,
|
|
||||||
#notificationsBellBtn,
|
|
||||||
#profileBtn,
|
|
||||||
#logoutBtn,
|
|
||||||
#mobileMenuBtn {
|
|
||||||
padding-right: 0.625rem;
|
|
||||||
padding-left: 0.625rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent > [class*="-page"] {
|
|
||||||
padding: 0.75rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-stats,
|
|
||||||
.apps-stats {
|
|
||||||
grid-template-columns: minmax(0, 1fr) !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters.asset-borrow-filter-bar {
|
|
||||||
grid-template-columns: minmax(0, 1fr);
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters.asset-filter-bar {
|
|
||||||
grid-template-columns: minmax(0, 1fr) max-content;
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters.asset-filter-bar .compact-filter-search {
|
|
||||||
grid-column: 1 / -1;
|
|
||||||
grid-row: 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters.consumable-filter-bar,
|
|
||||||
.compact-page-filters.consumable-export-filter-bar {
|
|
||||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-page-filters.consumable-filter-bar .compact-filter-search,
|
|
||||||
.compact-page-filters.consumable-export-filter-bar .compact-filter-search {
|
|
||||||
grid-column: 1 / -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody {
|
|
||||||
padding: 0.625rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
#mainContent table.mobile-card-table:not(.keep-table-mobile) > tbody > tr > td {
|
|
||||||
grid-template-columns: minmax(5rem, 34%) minmax(0, 1fr);
|
|
||||||
gap: 0.625rem;
|
|
||||||
padding: 0.625rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.modal-backdrop .modal-content {
|
|
||||||
width: 100% !important;
|
|
||||||
margin-right: 0 !important;
|
|
||||||
margin-left: 0 !important;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Login, registration, password recovery and email verification. */
|
|
||||||
body.auth-page,
|
|
||||||
body.verify-page {
|
|
||||||
min-height: 100dvh;
|
|
||||||
overflow-x: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-shell,
|
|
||||||
.verify-shell {
|
|
||||||
min-height: 100dvh;
|
|
||||||
padding-top: max(1rem, env(safe-area-inset-top));
|
|
||||||
padding-bottom: max(1rem, env(safe-area-inset-bottom));
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 560px) {
|
|
||||||
.auth-shell,
|
|
||||||
.verify-shell {
|
|
||||||
align-items: flex-start;
|
|
||||||
padding-right: 0.75rem;
|
|
||||||
padding-left: 0.75rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card,
|
|
||||||
.verify-card {
|
|
||||||
padding: 1.25rem !important;
|
|
||||||
border-radius: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card .auth-heading {
|
|
||||||
margin-bottom: 1.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card .auth-icon {
|
|
||||||
width: 3.25rem;
|
|
||||||
height: 3.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card h1,
|
|
||||||
.verify-card h1 {
|
|
||||||
font-size: 1.35rem;
|
|
||||||
line-height: 1.25;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card input:not([type="checkbox"]),
|
|
||||||
.auth-card select,
|
|
||||||
.auth-card textarea {
|
|
||||||
min-height: 2.75rem;
|
|
||||||
font-size: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card button,
|
|
||||||
.verify-card a {
|
|
||||||
min-height: 2.75rem;
|
|
||||||
touch-action: manipulation;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card .remember-row,
|
|
||||||
.verify-card .verify-actions {
|
|
||||||
align-items: stretch;
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card .remember-row > div {
|
|
||||||
min-height: 2.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card .remember-row > button {
|
|
||||||
align-self: flex-start;
|
|
||||||
min-height: 2.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.verify-card .verify-actions > a {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
|
||||||
*,
|
|
||||||
*::before,
|
|
||||||
*::after {
|
|
||||||
scroll-behavior: auto !important;
|
|
||||||
transition-duration: 0.01ms !important;
|
|
||||||
animation-duration: 0.01ms !important;
|
|
||||||
animation-iteration-count: 1 !important;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/* Shared brand artwork */
|
|
||||||
.auth-brand-image,
|
|
||||||
.sidebar-brand-image,
|
|
||||||
.verify-brand-image {
|
|
||||||
display: block;
|
|
||||||
width: auto;
|
|
||||||
object-fit: contain;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-brand-image {
|
|
||||||
height: 5rem;
|
|
||||||
max-width: 9rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar-brand-link {
|
|
||||||
display: flex;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: center;
|
|
||||||
min-height: 3.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar-brand-image {
|
|
||||||
height: 3.25rem;
|
|
||||||
max-width: 7rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.verify-brand-image {
|
|
||||||
height: 4rem;
|
|
||||||
max-width: 7rem;
|
|
||||||
margin-left: auto;
|
|
||||||
margin-right: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 560px) {
|
|
||||||
.auth-card .auth-brand-image {
|
|
||||||
height: 4rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.verify-card .verify-brand-image {
|
|
||||||
height: 3.25rem;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,229 +0,0 @@
|
|||||||
.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; }
|
|
||||||
}
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 126 KiB |
@@ -1,10 +1,7 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
||||||
<title>Redirecting...</title>
|
<title>Redirecting...</title>
|
||||||
<link rel="icon" type="image/png" href="./image/logo_PNKX.png">
|
|
||||||
<script>
|
<script>
|
||||||
window.location.href = './pages/login.html';
|
window.location.href = './pages/login.html';
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
9926
public/js/app.js
9926
public/js/app.js
File diff suppressed because it is too large
Load Diff
@@ -1,26 +0,0 @@
|
|||||||
(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;
|
|
||||||
}());
|
|
||||||
@@ -1,288 +0,0 @@
|
|||||||
/* 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;
|
|
||||||
})();
|
|
||||||
1059
public/modals.html
1059
public/modals.html
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,6 @@
|
|||||||
<meta charset="utf-8"/>
|
<meta charset="utf-8"/>
|
||||||
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
||||||
<title>Robot Manager Account - Accounts Management</title>
|
<title>Robot Manager Account - Accounts Management</title>
|
||||||
<link rel="icon" type="image/png" href="../image/logo_PNKX.png"/>
|
|
||||||
<!-- Fonts -->
|
<!-- Fonts -->
|
||||||
<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=Manrope:wght@400;500;600;700;800&family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"/>
|
||||||
<!-- Material Symbols -->
|
<!-- Material Symbols -->
|
||||||
|
|||||||
@@ -4,7 +4,6 @@
|
|||||||
<meta charset="utf-8"/>
|
<meta charset="utf-8"/>
|
||||||
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
||||||
<title>Robot Manager Account - Applications Management</title>
|
<title>Robot Manager Account - Applications Management</title>
|
||||||
<link rel="icon" type="image/png" href="../image/logo_PNKX.png"/>
|
|
||||||
<!-- Fonts -->
|
<!-- Fonts -->
|
||||||
<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"/>
|
<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 -->
|
<!-- Material Symbols -->
|
||||||
|
|||||||
@@ -4,17 +4,15 @@
|
|||||||
<meta charset="utf-8"/>
|
<meta charset="utf-8"/>
|
||||||
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
||||||
<title>Robot Manager Account - Hệ thống quản lý</title>
|
<title>Robot Manager Account - Hệ thống quản lý</title>
|
||||||
<link rel="icon" type="image/png" href="../image/logo_PNKX.png"/>
|
|
||||||
<!-- Fonts -->
|
<!-- Fonts -->
|
||||||
<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"/>
|
<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 -->
|
<!-- 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 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=20261019-4" />
|
<link rel="stylesheet" href="../css/main.css" />
|
||||||
<link rel="stylesheet" href="../css/robot-bom.css?v=20261102-5" />
|
|
||||||
<!-- Notiflix Notify -->
|
<!-- Notiflix Notify -->
|
||||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-3.2.7.min.css" />
|
<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>
|
<script src="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js"></script>
|
||||||
<script src="https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
|
||||||
<style>
|
<style>
|
||||||
.material-symbols-outlined {
|
.material-symbols-outlined {
|
||||||
font-family: 'Material Symbols Outlined';
|
font-family: 'Material Symbols Outlined';
|
||||||
@@ -47,6 +45,25 @@
|
|||||||
transform: scale(1);
|
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 {
|
body.app-shell {
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
@@ -56,11 +73,6 @@
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.assets-mobile-list,
|
|
||||||
.consumables-mobile-list {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 900px) {
|
@media (max-width: 900px) {
|
||||||
body.app-shell {
|
body.app-shell {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@@ -165,54 +177,6 @@
|
|||||||
min-width: 700px;
|
min-width: 700px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.assets-page,
|
|
||||||
.consumables-page {
|
|
||||||
padding: 0.75rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.assets-page .page-header,
|
|
||||||
.consumables-page .page-header {
|
|
||||||
margin-bottom: 0.75rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.assets-page .asset-header-actions,
|
|
||||||
.consumables-page .consumable-header-actions {
|
|
||||||
width: 100%;
|
|
||||||
display: flex;
|
|
||||||
flex-flow: row nowrap;
|
|
||||||
overflow-x: auto;
|
|
||||||
overscroll-behavior-x: contain;
|
|
||||||
-webkit-overflow-scrolling: touch;
|
|
||||||
padding-bottom: 0.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.assets-page .asset-header-actions > button,
|
|
||||||
.consumables-page .consumable-header-actions > button {
|
|
||||||
width: auto;
|
|
||||||
flex: 0 0 auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.assets-page .page-filters,
|
|
||||||
.consumables-page .page-filters {
|
|
||||||
margin-bottom: 0.75rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.assets-page .assets-desktop-table,
|
|
||||||
.consumables-page .consumables-desktop-table {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.assets-page .assets-mobile-list,
|
|
||||||
.consumables-page .consumables-mobile-list {
|
|
||||||
display: flex;
|
|
||||||
min-height: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.assets-page .asset-mobile-card,
|
|
||||||
.consumables-page .consumable-mobile-card {
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
|
|
||||||
.page-pager {
|
.page-pager {
|
||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -237,156 +201,57 @@
|
|||||||
.apps-stats {
|
.apps-stats {
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
}
|
}
|
||||||
|
|
||||||
.assets-page .page-header h1,
|
|
||||||
.consumables-page .page-header h1 {
|
|
||||||
font-size: 1.25rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.assets-page .page-header p,
|
|
||||||
.consumables-page .page-header p {
|
|
||||||
font-size: 0.75rem;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
</style>
|
</style>
|
||||||
<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>
|
</head>
|
||||||
<body class="app-shell bg-background text-on-surface antialiased flex h-screen w-screen">
|
<body class="app-shell bg-background text-on-surface antialiased flex h-screen w-screen">
|
||||||
<!-- SideNavBar -->
|
<!-- SideNavBar -->
|
||||||
<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">
|
<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 min-h-0 py-4">
|
<div class="flex flex-col h-full py-6">
|
||||||
<!-- Header -->
|
<!-- Header -->
|
||||||
<div class="px-5 mb-4 shrink-0">
|
<div class="px-6 mb-8">
|
||||||
<a href="#dashboard" class="sidebar-brand-link" aria-label="PNKX - Về trang tổng quan">
|
<div class="text-lg font-black text-slate-900 dark:text-slate-50 tracking-tight leading-none">Robot Account</div>
|
||||||
<img src="../image/logo_PNKX.png" alt="PNKX" class="sidebar-brand-image"/>
|
<div class="text-[10px] uppercase tracking-widest text-on-surface-variant mt-1.5 font-bold">Admin Console</div>
|
||||||
</a>
|
|
||||||
</div>
|
</div>
|
||||||
<!-- Primary Nav -->
|
<!-- Primary Nav -->
|
||||||
<nav id="sidebarNav" class="sidebar-nav flex-1 min-h-0 overflow-y-auto" aria-label="Điều hướng chính">
|
<nav class="flex-1 px-3 space-y-4">
|
||||||
<ul class="sidebar-menu">
|
<div>
|
||||||
<li>
|
<div class="tree-label">Tài khoản</div>
|
||||||
<a href="#dashboard" data-nav="dashboard" class="sidebar-link" aria-current="page">
|
<div class="tree-branch">
|
||||||
<span class="material-symbols-outlined" aria-hidden="true">dashboard</span>
|
<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="sidebar-text">Tổng quan</span>
|
<span class="material-symbols-outlined">dashboard</span>
|
||||||
|
<span>Tổng quan</span>
|
||||||
</a>
|
</a>
|
||||||
</li>
|
<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">
|
||||||
<li data-nav-group="accounts">
|
<span class="material-symbols-outlined">apps</span>
|
||||||
<button id="sidebarAccountsToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="accounts" aria-expanded="false" aria-controls="sidebarAccounts">
|
<span>Ứng dụng</span>
|
||||||
<span class="material-symbols-outlined" aria-hidden="true">manage_accounts</span>
|
</a>
|
||||||
<span class="sidebar-text">Tài khoản</span>
|
<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 sidebar-chevron" aria-hidden="true">chevron_right</span>
|
<span class="material-symbols-outlined">manage_accounts</span>
|
||||||
</button>
|
<span>Tài khoản</span>
|
||||||
<ul id="sidebarAccounts" class="sidebar-children" aria-labelledby="sidebarAccountsToggle" hidden>
|
</a>
|
||||||
<li><a href="#applications" data-nav="applications" class="sidebar-link">
|
</div>
|
||||||
<span class="material-symbols-outlined" aria-hidden="true">apps</span>
|
</div>
|
||||||
<span class="sidebar-text">Ứng dụng</span>
|
|
||||||
</a></li>
|
<div>
|
||||||
<li><a href="#accounts" data-nav="accounts" class="sidebar-link">
|
<div class="tree-label">Quản lý tài sản</div>
|
||||||
<span class="material-symbols-outlined" aria-hidden="true">manage_accounts</span>
|
<div class="tree-branch">
|
||||||
<span class="sidebar-text">Tài khoản</span>
|
<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">
|
||||||
</a></li>
|
<span class="material-symbols-outlined">inventory_2</span>
|
||||||
</ul>
|
<span>Tài sản</span>
|
||||||
</li>
|
</a>
|
||||||
<li data-nav-group="assets">
|
</div>
|
||||||
<button id="sidebarAssetsToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="assets" aria-expanded="false" aria-controls="sidebarAssets">
|
</div>
|
||||||
<span class="material-symbols-outlined" aria-hidden="true">inventory_2</span>
|
|
||||||
<span class="sidebar-text">Quản lý tài sản</span>
|
<div id="usersSection" class="pt-2 border-t border-outline-variant/10" style="display: none;">
|
||||||
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
|
<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;">
|
||||||
</button>
|
<span class="material-symbols-outlined">people</span>
|
||||||
<ul id="sidebarAssets" class="sidebar-children" aria-labelledby="sidebarAssetsToggle" hidden>
|
<span>Người dùng (Quản trị)</span>
|
||||||
<li><a href="#assets" data-nav="assets" class="sidebar-link">
|
</a>
|
||||||
<span class="material-symbols-outlined" aria-hidden="true">inventory_2</span>
|
</div>
|
||||||
<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>
|
</nav>
|
||||||
<!-- Footer -->
|
<!-- Footer -->
|
||||||
<div class="px-5 pt-3 mt-3 border-t border-outline-variant/10 shrink-0">
|
<div class="px-6 pt-4 border-t border-outline-variant/10">
|
||||||
<div class="text-[10px] font-bold text-on-surface-variant/40 uppercase tracking-widest">v1.0.0</div>
|
<div class="text-[10px] font-bold text-on-surface-variant/40 uppercase tracking-widest">v1.0.0</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -404,31 +269,6 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="topbar-actions flex items-center gap-4">
|
<div class="topbar-actions flex items-center gap-4">
|
||||||
<div id="notificationCenterShell" class="relative">
|
|
||||||
<button id="notificationsBellBtn" type="button" class="relative inline-flex items-center justify-center w-10 h-10 rounded-lg text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors" title="Thông báo" aria-label="Mở thông báo" aria-haspopup="true" aria-expanded="false">
|
|
||||||
<span class="material-symbols-outlined">notifications</span>
|
|
||||||
<span id="notificationBadge" class="hidden absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full bg-red-600 text-white text-[10px] font-extrabold leading-5 text-center ring-2 ring-slate-50 dark:ring-slate-950">0</span>
|
|
||||||
</button>
|
|
||||||
<div id="notificationPopover" class="hidden absolute right-0 top-12 z-50 w-[min(390px,calc(100vw-24px))] overflow-hidden rounded-2xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 shadow-2xl" role="dialog" aria-label="Thông báo gần đây">
|
|
||||||
<div class="flex items-center justify-between gap-3 px-4 py-3 border-b border-slate-100 dark:border-slate-800">
|
|
||||||
<div>
|
|
||||||
<h2 class="text-sm font-bold text-slate-900 dark:text-slate-50">Thông báo</h2>
|
|
||||||
<p id="notificationPopoverSummary" class="text-[11px] text-slate-500">Không có thông báo mới</p>
|
|
||||||
</div>
|
|
||||||
<button id="notificationMarkAllBtn" type="button" class="text-xs font-semibold text-primary hover:underline">Đánh dấu đã đọc</button>
|
|
||||||
</div>
|
|
||||||
<div id="notificationPopoverList" class="max-h-[420px] overflow-y-auto"></div>
|
|
||||||
<a href="#notifications" id="notificationViewAllLink" class="flex items-center justify-center gap-1 px-4 py-3 border-t border-slate-100 dark:border-slate-800 text-xs font-bold text-primary hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors">
|
|
||||||
Xem tất cả
|
|
||||||
<span class="material-symbols-outlined text-base">arrow_forward</span>
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button id="pendingAssetRequestsBtn" type="button" class="hidden relative flex items-center gap-2 px-3 py-2 rounded-lg border border-amber-200 bg-amber-50 hover:bg-amber-100 text-amber-800 transition-colors" title="Đơn chờ xử lý">
|
|
||||||
<span class="material-symbols-outlined text-base">notifications_active</span>
|
|
||||||
<span class="text-xs font-bold">Đơn chờ</span>
|
|
||||||
<span id="pendingAssetRequestsBadge" class="hidden absolute -top-2.5 -right-2.5 min-w-[22px] h-[22px] px-1.5 rounded-[999px] bg-red-600 text-white text-xs font-extrabold leading-[22px] text-center ring-2 ring-white">0</span>
|
|
||||||
</button>
|
|
||||||
<button id="profileBtn" type="button" class="profile-btn flex items-center gap-2 px-4 py-2 rounded-lg bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors" title="Sửa hồ sơ">
|
<button id="profileBtn" type="button" class="profile-btn flex items-center gap-2 px-4 py-2 rounded-lg bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors" title="Sửa hồ sơ">
|
||||||
<span class="material-symbols-outlined text-slate-600 dark:text-slate-400">account_circle</span>
|
<span class="material-symbols-outlined text-slate-600 dark:text-slate-400">account_circle</span>
|
||||||
<div class="profile-meta flex flex-col">
|
<div class="profile-meta flex flex-col">
|
||||||
@@ -448,8 +288,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<script src="../js/document-formats.js?v=20261019-1"></script>
|
<script src="../js/app.js?v=20260421-4"></script>
|
||||||
<script src="../js/robot-bom.js?v=20261102-5"></script>
|
|
||||||
<script src="../js/app.js?v=20261111-1"></script>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -4,7 +4,6 @@
|
|||||||
<meta charset="utf-8"/>
|
<meta charset="utf-8"/>
|
||||||
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
||||||
<title>Robotics Account - Login</title>
|
<title>Robotics Account - Login</title>
|
||||||
<link rel="icon" type="image/png" href="../image/logo_PNKX.png"/>
|
|
||||||
<!-- Fonts -->
|
<!-- Fonts -->
|
||||||
<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"/>
|
<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 -->
|
<!-- Material Symbols -->
|
||||||
@@ -26,23 +25,24 @@
|
|||||||
body { font-family: 'Inter', sans-serif; min-height: 100vh; }
|
body { font-family: 'Inter', sans-serif; min-height: 100vh; }
|
||||||
h1, h2, h3 { font-family: 'Manrope', sans-serif; }
|
h1, h2, h3 { font-family: 'Manrope', sans-serif; }
|
||||||
</style>
|
</style>
|
||||||
<link rel="stylesheet" href="../css/responsive.css?v=20260717-1" />
|
|
||||||
</head>
|
</head>
|
||||||
<body class="auth-page bg-gradient-to-br from-blue-50 via-background to-purple-50 dark:from-slate-950 dark:via-slate-900 dark:to-slate-950 antialiased">
|
<body class="bg-gradient-to-br from-blue-50 via-background to-purple-50 dark:from-slate-950 dark:via-slate-900 dark:to-slate-950 antialiased">
|
||||||
<div class="auth-shell min-h-screen flex items-center justify-center px-4">
|
<div class="min-h-screen flex items-center justify-center px-4">
|
||||||
<div class="w-full max-w-md">
|
<div class="w-full max-w-md">
|
||||||
<!-- Login Card -->
|
<!-- Login Card -->
|
||||||
<div class="auth-card bg-white dark:bg-slate-900 rounded-2xl shadow-lg border border-outline-variant/10 p-8">
|
<div class="bg-white dark:bg-slate-900 rounded-2xl shadow-lg border border-outline-variant/10 p-8">
|
||||||
<!-- Header -->
|
<!-- Header -->
|
||||||
<div class="auth-heading text-center mb-8">
|
<div class="text-center mb-8">
|
||||||
<div class="flex justify-center mb-4">
|
<div class="flex justify-center mb-4">
|
||||||
<img src="../image/logo_PNKX.png" alt="PNKX" class="auth-brand-image"/>
|
<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>
|
</div>
|
||||||
<h1 class="text-2xl font-black text-slate-900 dark:text-slate-50 tracking-tight">Robotics Account Manager</h1>
|
<h1 class="text-2xl font-black text-slate-900 dark:text-slate-50 tracking-tight">Robotics Account Manager</h1>
|
||||||
<p class="text-xs uppercase tracking-widest text-on-surface-variant font-bold mt-2">Account Management System</p>
|
<p class="text-xs uppercase tracking-widest text-on-surface-variant font-bold mt-2">Account Management System</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="authTabs" class="flex gap-2 mb-6" role="tablist" aria-label="Auth switcher">
|
<div class="flex gap-2 mb-6" role="tablist" aria-label="Auth switcher">
|
||||||
<button id="loginTab" type="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 id="loginTab" type="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 id="registerTab" type="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>
|
<button id="registerTab" type="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>
|
</div>
|
||||||
@@ -86,7 +86,6 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Remember Me Checkbox -->
|
<!-- Remember Me Checkbox -->
|
||||||
<div class="remember-row flex items-center justify-between gap-2">
|
|
||||||
<div class="flex items-center">
|
<div class="flex items-center">
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
@@ -96,10 +95,6 @@
|
|||||||
/>
|
/>
|
||||||
<label for="remember" class="ml-2.5 text-xs font-medium text-on-surface-variant cursor-pointer">Remember me</label>
|
<label for="remember" class="ml-2.5 text-xs font-medium text-on-surface-variant cursor-pointer">Remember me</label>
|
||||||
</div>
|
</div>
|
||||||
<button id="forgotPasswordLink" type="button" class="text-xs font-semibold text-primary hover:text-primary-dim transition-colors bg-transparent border-0 p-0">
|
|
||||||
Forgot password?
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Login Button -->
|
<!-- Login Button -->
|
||||||
<button
|
<button
|
||||||
@@ -122,119 +117,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<form id="forgotPasswordForm" class="space-y-5 hidden">
|
|
||||||
<div class="bg-blue-50 border border-blue-100 rounded-lg px-4 py-3 text-xs text-blue-700">
|
|
||||||
Enter your username and registered email to receive a password reset link.
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label for="forgotUsername" class="block text-xs font-bold text-on-surface-variant uppercase tracking-wider mb-2">Username</label>
|
|
||||||
<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
|
|
||||||
type="text"
|
|
||||||
id="forgotUsername"
|
|
||||||
name="forgotUsername"
|
|
||||||
placeholder="Enter your username"
|
|
||||||
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"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label for="forgotEmail" class="block text-xs font-bold text-on-surface-variant uppercase tracking-wider mb-2">Registered Email</label>
|
|
||||||
<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">mail</span>
|
|
||||||
</span>
|
|
||||||
<input
|
|
||||||
type="email"
|
|
||||||
id="forgotEmail"
|
|
||||||
name="forgotEmail"
|
|
||||||
placeholder="Enter your registered email"
|
|
||||||
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"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
class="w-full bg-primary hover:bg-primary-dim text-on-primary font-bold py-2.5 px-4 rounded-lg transition-all active:scale-95 duration-100 flex items-center justify-center gap-2 mt-4"
|
|
||||||
>
|
|
||||||
<span class="material-symbols-outlined text-sm">mark_email_unread</span>
|
|
||||||
<span>Send reset email</span>
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<button id="forgotBackToLoginBtn" type="button" class="w-full bg-surface-container-low hover:bg-slate-200 text-on-surface-variant font-semibold py-2.5 px-4 rounded-lg transition-colors">
|
|
||||||
Back to sign in
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<div id="forgotPasswordErrorMessage" class="hidden bg-error-container/20 text-error/80 border border-error/30 rounded-lg px-4 py-3 text-xs font-medium"></div>
|
|
||||||
<div id="forgotPasswordSuccessMessage" class="hidden bg-green-50 text-green-800 border border-green-200 rounded-lg px-4 py-3 text-xs font-medium"></div>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<form id="resetPasswordForm" class="space-y-5 hidden">
|
|
||||||
<div class="bg-blue-50 border border-blue-100 rounded-lg px-4 py-3 text-xs text-blue-700">
|
|
||||||
Set your new password below.
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label for="resetPassword" class="block text-xs font-bold text-on-surface-variant uppercase tracking-wider mb-2">New Password</label>
|
|
||||||
<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">lock_reset</span>
|
|
||||||
</span>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
id="resetPassword"
|
|
||||||
name="resetPassword"
|
|
||||||
placeholder="Enter a new password"
|
|
||||||
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"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label for="resetConfirmPassword" class="block text-xs font-bold text-on-surface-variant uppercase tracking-wider mb-2">Confirm New Password</label>
|
|
||||||
<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">verified_user</span>
|
|
||||||
</span>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
id="resetConfirmPassword"
|
|
||||||
name="resetConfirmPassword"
|
|
||||||
placeholder="Re-enter new password"
|
|
||||||
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"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
class="w-full bg-primary hover:bg-primary-dim text-on-primary font-bold py-2.5 px-4 rounded-lg transition-all active:scale-95 duration-100 flex items-center justify-center gap-2 mt-4"
|
|
||||||
>
|
|
||||||
<span class="material-symbols-outlined text-sm">password</span>
|
|
||||||
<span>Reset password</span>
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<button id="resetBackToLoginBtn" type="button" class="w-full bg-surface-container-low hover:bg-slate-200 text-on-surface-variant font-semibold py-2.5 px-4 rounded-lg transition-colors">
|
|
||||||
Back to sign in
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<div id="resetPasswordErrorMessage" class="hidden bg-error-container/20 text-error/80 border border-error/30 rounded-lg px-4 py-3 text-xs font-medium"></div>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<!-- Register Form -->
|
<!-- Register Form -->
|
||||||
<form id="registerForm" class="space-y-5 hidden">
|
<form id="registerForm" class="space-y-5 hidden">
|
||||||
<div>
|
<div>
|
||||||
@@ -297,8 +179,6 @@
|
|||||||
id="regPassword"
|
id="regPassword"
|
||||||
name="password"
|
name="password"
|
||||||
placeholder="Create a password"
|
placeholder="Create a password"
|
||||||
minlength="6"
|
|
||||||
maxlength="256"
|
|
||||||
required
|
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"
|
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"
|
||||||
/>
|
/>
|
||||||
@@ -319,7 +199,7 @@
|
|||||||
|
|
||||||
<!-- Footer -->
|
<!-- Footer -->
|
||||||
<!-- <div class="mt-8 pt-6 border-t border-outline-variant/10 text-center">
|
<!-- <div class="mt-8 pt-6 border-t border-outline-variant/10 text-center">
|
||||||
<p class="text-[10px] text-on-surface-variant/60">Use the account provided by your administrator.</p>
|
<p class="text-[10px] text-on-surface-variant/60">Default credentials for demo: admin / admin</p>
|
||||||
</div> -->
|
</div> -->
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -331,27 +211,12 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const authTabs = document.getElementById('authTabs');
|
// Simple login functionality
|
||||||
const loginForm = document.getElementById('loginForm');
|
const loginForm = document.getElementById('loginForm');
|
||||||
const errorMessage = document.getElementById('errorMessage');
|
const errorMessage = document.getElementById('errorMessage');
|
||||||
const usernameInput = document.getElementById('username');
|
const usernameInput = document.getElementById('username');
|
||||||
const passwordInput = document.getElementById('password');
|
const passwordInput = document.getElementById('password');
|
||||||
const rememberCheckbox = document.getElementById('remember');
|
const rememberCheckbox = document.getElementById('remember');
|
||||||
const forgotPasswordLink = document.getElementById('forgotPasswordLink');
|
|
||||||
|
|
||||||
const forgotPasswordForm = document.getElementById('forgotPasswordForm');
|
|
||||||
const forgotUsernameInput = document.getElementById('forgotUsername');
|
|
||||||
const forgotEmailInput = document.getElementById('forgotEmail');
|
|
||||||
const forgotBackToLoginBtn = document.getElementById('forgotBackToLoginBtn');
|
|
||||||
const forgotPasswordErrorMessage = document.getElementById('forgotPasswordErrorMessage');
|
|
||||||
const forgotPasswordSuccessMessage = document.getElementById('forgotPasswordSuccessMessage');
|
|
||||||
|
|
||||||
const resetPasswordForm = document.getElementById('resetPasswordForm');
|
|
||||||
const resetPasswordInput = document.getElementById('resetPassword');
|
|
||||||
const resetConfirmPasswordInput = document.getElementById('resetConfirmPassword');
|
|
||||||
const resetBackToLoginBtn = document.getElementById('resetBackToLoginBtn');
|
|
||||||
const resetPasswordErrorMessage = document.getElementById('resetPasswordErrorMessage');
|
|
||||||
|
|
||||||
const registerForm = document.getElementById('registerForm');
|
const registerForm = document.getElementById('registerForm');
|
||||||
const registerErrorMessage = document.getElementById('registerErrorMessage');
|
const registerErrorMessage = document.getElementById('registerErrorMessage');
|
||||||
const registerSuccessMessage = document.getElementById('registerSuccessMessage');
|
const registerSuccessMessage = document.getElementById('registerSuccessMessage');
|
||||||
@@ -364,31 +229,19 @@
|
|||||||
const regPasswordInput = document.getElementById('regPassword');
|
const regPasswordInput = document.getElementById('regPassword');
|
||||||
const loginTab = document.getElementById('loginTab');
|
const loginTab = document.getElementById('loginTab');
|
||||||
const registerTab = document.getElementById('registerTab');
|
const registerTab = document.getElementById('registerTab');
|
||||||
|
|
||||||
let pendingVerificationIdentifier = '';
|
let pendingVerificationIdentifier = '';
|
||||||
let currentMode = 'login';
|
let currentMode = 'login';
|
||||||
let resetToken = '';
|
|
||||||
|
|
||||||
const setMode = (mode) => {
|
const setMode = (mode) => {
|
||||||
currentMode = mode;
|
currentMode = mode;
|
||||||
const isLogin = mode === 'login';
|
const isLogin = mode === 'login';
|
||||||
const isRegister = mode === 'register';
|
|
||||||
const isForgot = mode === 'forgot';
|
|
||||||
const isReset = mode === 'reset';
|
|
||||||
|
|
||||||
loginForm.classList.toggle('hidden', !isLogin);
|
loginForm.classList.toggle('hidden', !isLogin);
|
||||||
registerForm.classList.toggle('hidden', !isRegister);
|
registerForm.classList.toggle('hidden', isLogin);
|
||||||
forgotPasswordForm.classList.toggle('hidden', !isForgot);
|
|
||||||
resetPasswordForm.classList.toggle('hidden', !isReset);
|
|
||||||
authTabs.classList.toggle('hidden', isReset);
|
|
||||||
|
|
||||||
errorMessage.classList.add('hidden');
|
errorMessage.classList.add('hidden');
|
||||||
registerErrorMessage.classList.add('hidden');
|
registerErrorMessage.classList.add('hidden');
|
||||||
registerSuccessMessage.classList.add('hidden');
|
registerSuccessMessage.classList.add('hidden');
|
||||||
verifyNotice.classList.add('hidden');
|
verifyNotice.classList.add('hidden');
|
||||||
forgotPasswordErrorMessage.classList.add('hidden');
|
|
||||||
forgotPasswordSuccessMessage.classList.add('hidden');
|
|
||||||
resetPasswordErrorMessage.classList.add('hidden');
|
|
||||||
|
|
||||||
const activate = (btn, active) => {
|
const activate = (btn, active) => {
|
||||||
btn.classList.toggle('bg-primary', active);
|
btn.classList.toggle('bg-primary', active);
|
||||||
@@ -398,112 +251,29 @@
|
|||||||
btn.classList.toggle('text-on-surface-variant', !active);
|
btn.classList.toggle('text-on-surface-variant', !active);
|
||||||
};
|
};
|
||||||
|
|
||||||
activate(loginTab, !isRegister);
|
activate(loginTab, isLogin);
|
||||||
activate(registerTab, isRegister);
|
activate(registerTab, !isLogin);
|
||||||
};
|
};
|
||||||
|
|
||||||
const clearResetQuery = () => {
|
// Check if already logged in
|
||||||
const cleanUrl = `${window.location.origin}${window.location.pathname}`;
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
window.history.replaceState({}, document.title, cleanUrl);
|
const currentUser = localStorage.getItem('currentUser');
|
||||||
};
|
if (currentUser) {
|
||||||
|
window.location.href = './index.html';
|
||||||
const getInitialMode = () => {
|
|
||||||
const params = new URLSearchParams(window.location.search);
|
|
||||||
const mode = String(params.get('mode') || '').trim().toLowerCase();
|
|
||||||
const token = String(params.get('token') || '').trim();
|
|
||||||
|
|
||||||
if (mode === 'reset-password') {
|
|
||||||
resetToken = token;
|
|
||||||
return token ? 'reset' : 'forgot';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (mode === 'forgot-password') {
|
setMode('login');
|
||||||
return 'forgot';
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'login';
|
|
||||||
};
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', async () => {
|
|
||||||
let initialMode = getInitialMode();
|
|
||||||
try {
|
|
||||||
const configResponse = await fetch('/api/auth/config', { cache: 'no-store' });
|
|
||||||
const config = await configResponse.json();
|
|
||||||
if (configResponse.ok && config.allowSelfRegistration === false) {
|
|
||||||
registerTab.classList.add('hidden');
|
|
||||||
if (initialMode === 'register') {
|
|
||||||
initialMode = 'login';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
registerTab.classList.add('hidden');
|
|
||||||
if (initialMode === 'register') {
|
|
||||||
initialMode = 'login';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (initialMode !== 'reset') {
|
|
||||||
try {
|
|
||||||
const sessionResponse = await fetch('/api/auth/session', { cache: 'no-store' });
|
|
||||||
const sessionData = await sessionResponse.json();
|
|
||||||
if (sessionResponse.ok && sessionData.success && sessionData.user) {
|
|
||||||
localStorage.setItem('currentUser', JSON.stringify(sessionData.user));
|
|
||||||
window.location.replace('./index.html');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.debug('No active session');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
localStorage.removeItem('currentUser');
|
|
||||||
|
|
||||||
setMode(initialMode);
|
|
||||||
|
|
||||||
if (initialMode === 'forgot') {
|
|
||||||
forgotUsernameInput.value = usernameInput.value.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (initialMode === 'reset' && !resetToken) {
|
|
||||||
setMode('forgot');
|
|
||||||
forgotPasswordErrorMessage.textContent = 'Reset link is invalid. Please request a new password reset email.';
|
|
||||||
forgotPasswordErrorMessage.classList.remove('hidden');
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// Restore remembered username
|
||||||
const rememberedUsername = localStorage.getItem('rememberedUsername');
|
const rememberedUsername = localStorage.getItem('rememberedUsername');
|
||||||
if (rememberedUsername) {
|
if (rememberedUsername) {
|
||||||
usernameInput.value = rememberedUsername;
|
usernameInput.value = rememberedUsername;
|
||||||
rememberCheckbox.checked = true;
|
rememberCheckbox.checked = true;
|
||||||
if (!forgotUsernameInput.value) {
|
|
||||||
forgotUsernameInput.value = rememberedUsername;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
loginTab.addEventListener('click', () => {
|
loginTab.addEventListener('click', () => setMode('login'));
|
||||||
clearResetQuery();
|
registerTab.addEventListener('click', () => setMode('register'));
|
||||||
setMode('login');
|
|
||||||
});
|
|
||||||
|
|
||||||
registerTab.addEventListener('click', () => {
|
|
||||||
clearResetQuery();
|
|
||||||
setMode('register');
|
|
||||||
});
|
|
||||||
|
|
||||||
forgotPasswordLink.addEventListener('click', () => {
|
|
||||||
setMode('forgot');
|
|
||||||
forgotUsernameInput.value = usernameInput.value.trim();
|
|
||||||
forgotEmailInput.focus();
|
|
||||||
});
|
|
||||||
|
|
||||||
forgotBackToLoginBtn.addEventListener('click', () => {
|
|
||||||
clearResetQuery();
|
|
||||||
setMode('login');
|
|
||||||
});
|
|
||||||
|
|
||||||
resetBackToLoginBtn.addEventListener('click', () => {
|
|
||||||
resetToken = '';
|
|
||||||
clearResetQuery();
|
|
||||||
setMode('login');
|
|
||||||
});
|
|
||||||
|
|
||||||
loginForm.addEventListener('submit', async (e) => {
|
loginForm.addEventListener('submit', async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -514,31 +284,36 @@
|
|||||||
const password = passwordInput.value;
|
const password = passwordInput.value;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Call backend login API
|
||||||
const response = await fetch('/api/auth/login', {
|
const response = await fetch('/api/auth/login', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ username, password, remember: rememberCheckbox.checked })
|
body: JSON.stringify({ username, password })
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
if (data.success && data.user) {
|
if (data.success && data.user) {
|
||||||
|
// Store user info from backend
|
||||||
localStorage.setItem('currentUser', JSON.stringify(data.user));
|
localStorage.setItem('currentUser', JSON.stringify(data.user));
|
||||||
|
|
||||||
|
// Handle remember me
|
||||||
if (rememberCheckbox.checked) {
|
if (rememberCheckbox.checked) {
|
||||||
localStorage.setItem('rememberedUsername', username);
|
localStorage.setItem('rememberedUsername', username);
|
||||||
} else {
|
} else {
|
||||||
localStorage.removeItem('rememberedUsername');
|
localStorage.removeItem('rememberedUsername');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Redirect to dashboard
|
||||||
window.location.href = './index.html';
|
window.location.href = './index.html';
|
||||||
} else if (data.requiresEmailVerification) {
|
} else if (data.requiresEmailVerification) {
|
||||||
pendingVerificationIdentifier = data.username || data.email || username;
|
pendingVerificationIdentifier = data.username || data.email || username;
|
||||||
verifyNoticeText.textContent = data.message || 'Please confirm your email before signing in';
|
verifyNoticeText.textContent = data.message || 'Please confirm your email before signing in';
|
||||||
verifyNotice.classList.remove('hidden');
|
verifyNotice.classList.remove('hidden');
|
||||||
} else {
|
} else {
|
||||||
|
// Show error
|
||||||
errorMessage.textContent = data.message || 'Invalid username or password';
|
errorMessage.textContent = data.message || 'Invalid username or password';
|
||||||
errorMessage.classList.remove('hidden');
|
errorMessage.classList.remove('hidden');
|
||||||
passwordInput.value = '';
|
passwordInput.value = '';
|
||||||
@@ -551,108 +326,6 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
forgotPasswordForm.addEventListener('submit', async (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
forgotPasswordErrorMessage.classList.add('hidden');
|
|
||||||
forgotPasswordSuccessMessage.classList.add('hidden');
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
username: forgotUsernameInput.value.trim(),
|
|
||||||
email: forgotEmailInput.value.trim()
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!payload.username || !payload.email) {
|
|
||||||
forgotPasswordErrorMessage.textContent = 'Username and email are required.';
|
|
||||||
forgotPasswordErrorMessage.classList.remove('hidden');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch('/api/auth/forgot-password', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload)
|
|
||||||
});
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (response.ok && data?.success) {
|
|
||||||
const lines = [data.message || 'If the account exists, a password reset email has been sent.'];
|
|
||||||
if (data.resetPreviewUrl) {
|
|
||||||
lines.push(`Development reset link: ${data.resetPreviewUrl}`);
|
|
||||||
}
|
|
||||||
forgotPasswordSuccessMessage.textContent = lines.join(' ');
|
|
||||||
forgotPasswordSuccessMessage.classList.remove('hidden');
|
|
||||||
} else {
|
|
||||||
forgotPasswordErrorMessage.textContent = data?.message || 'Forgot password request failed.';
|
|
||||||
forgotPasswordErrorMessage.classList.remove('hidden');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
forgotPasswordErrorMessage.textContent = 'Connection error. Please try again.';
|
|
||||||
forgotPasswordErrorMessage.classList.remove('hidden');
|
|
||||||
console.error('Forgot password error:', error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
resetPasswordForm.addEventListener('submit', async (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
resetPasswordErrorMessage.classList.add('hidden');
|
|
||||||
|
|
||||||
const newPassword = resetPasswordInput.value;
|
|
||||||
const confirmPassword = resetConfirmPasswordInput.value;
|
|
||||||
|
|
||||||
if (!resetToken) {
|
|
||||||
resetPasswordErrorMessage.textContent = 'Reset link is invalid. Please request a new one.';
|
|
||||||
resetPasswordErrorMessage.classList.remove('hidden');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!newPassword || newPassword.length < 6 || newPassword.length > 256) {
|
|
||||||
resetPasswordErrorMessage.textContent = 'New password must be between 6 and 256 characters.';
|
|
||||||
resetPasswordErrorMessage.classList.remove('hidden');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (newPassword !== confirmPassword) {
|
|
||||||
resetPasswordErrorMessage.textContent = 'Confirm password does not match.';
|
|
||||||
resetPasswordErrorMessage.classList.remove('hidden');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch('/api/auth/reset-password', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
token: resetToken,
|
|
||||||
newPassword
|
|
||||||
})
|
|
||||||
});
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (response.ok && data?.success) {
|
|
||||||
resetToken = '';
|
|
||||||
resetPasswordInput.value = '';
|
|
||||||
resetConfirmPasswordInput.value = '';
|
|
||||||
clearResetQuery();
|
|
||||||
setMode('login');
|
|
||||||
verifyNoticeText.textContent = data.message || 'Password reset successful. Please sign in.';
|
|
||||||
verifyNotice.classList.remove('hidden');
|
|
||||||
passwordInput.focus();
|
|
||||||
} else {
|
|
||||||
resetPasswordErrorMessage.textContent = data?.message || 'Password reset failed.';
|
|
||||||
resetPasswordErrorMessage.classList.remove('hidden');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
resetPasswordErrorMessage.textContent = 'Connection error. Please try again.';
|
|
||||||
resetPasswordErrorMessage.classList.remove('hidden');
|
|
||||||
console.error('Reset password error:', error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
registerForm.addEventListener('submit', async (e) => {
|
registerForm.addEventListener('submit', async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
registerErrorMessage.classList.add('hidden');
|
registerErrorMessage.classList.add('hidden');
|
||||||
|
|||||||
@@ -4,7 +4,6 @@
|
|||||||
<meta charset="utf-8"/>
|
<meta charset="utf-8"/>
|
||||||
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
||||||
<title>Robot Manager Account - Users Management</title>
|
<title>Robot Manager Account - Users Management</title>
|
||||||
<link rel="icon" type="image/png" href="../image/logo_PNKX.png"/>
|
|
||||||
<!-- Fonts -->
|
<!-- Fonts -->
|
||||||
<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"/>
|
<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 -->
|
<!-- Material Symbols -->
|
||||||
|
|||||||
@@ -4,17 +4,14 @@
|
|||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Confirm Email - AccManager</title>
|
<title>Confirm Email - AccManager</title>
|
||||||
<link rel="icon" type="image/png" href="../image/logo_PNKX.png" />
|
|
||||||
<link rel="stylesheet" href="../css/main.css" />
|
<link rel="stylesheet" href="../css/main.css" />
|
||||||
<style>
|
<style>
|
||||||
body { font-family: 'Inter', sans-serif; min-height: 100vh; }
|
body { font-family: 'Inter', sans-serif; min-height: 100vh; }
|
||||||
</style>
|
</style>
|
||||||
<link rel="stylesheet" href="../css/responsive.css?v=20260717-1" />
|
|
||||||
</head>
|
</head>
|
||||||
<body class="verify-page bg-gradient-to-br from-slate-100 via-white to-blue-100 text-slate-900 antialiased">
|
<body class="bg-gradient-to-br from-slate-100 via-white to-blue-100 text-slate-900 antialiased">
|
||||||
<main class="verify-shell min-h-screen flex items-center justify-center px-4">
|
<main class="min-h-screen flex items-center justify-center px-4">
|
||||||
<section class="verify-card w-full max-w-md bg-white rounded-2xl border border-slate-200 shadow-lg p-8">
|
<section class="w-full max-w-md bg-white rounded-2xl border border-slate-200 shadow-lg p-8">
|
||||||
<img src="../image/logo_PNKX.png" alt="PNKX" class="verify-brand-image mb-6" />
|
|
||||||
<h1 class="text-2xl font-black tracking-tight mb-2">Email Confirmation</h1>
|
<h1 class="text-2xl font-black tracking-tight mb-2">Email Confirmation</h1>
|
||||||
<p class="text-sm text-slate-600 mb-6">We are confirming your account.</p>
|
<p class="text-sm text-slate-600 mb-6">We are confirming your account.</p>
|
||||||
|
|
||||||
@@ -22,7 +19,7 @@
|
|||||||
Confirming your email, please wait...
|
Confirming your email, please wait...
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="verify-actions mt-6 flex gap-3">
|
<div class="mt-6 flex gap-3">
|
||||||
<a href="./login.html" class="flex-1 text-center px-4 py-2 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold transition-colors">Back to Login</a>
|
<a href="./login.html" class="flex-1 text-center px-4 py-2 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold transition-colors">Back to Login</a>
|
||||||
<a id="signInBtn" href="./login.html" class="hidden flex-1 text-center px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-semibold transition-colors">Sign In</a>
|
<a id="signInBtn" href="./login.html" class="hidden flex-1 text-center px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-semibold transition-colors">Sign In</a>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user