Compare commits

..

72 Commits

Author SHA1 Message Date
6e919fde45 check lần 2 2026-11-30 15:38:49 +07:00
1b1012dbed check tên miền 2026-11-30 15:37:55 +07:00
03a481f20d update export 2026-11-11 10:48:31 +07:00
00122e5b4a update export request 2026-11-10 11:01:24 +07:00
63866b14a1 update dasboard ,noti 2026-11-04 09:54:17 +07:00
ea6768f90d Stop tracking docs directory 2026-11-02 15:14:42 +07:00
a41bd9c193 Ignore docs directory 2026-11-02 15:13:17 +07:00
6a872e8c8b bom 2026-11-02 15:09:59 +07:00
c441c809ca fix domain 2026-11-02 10:19:45 +07:00
0dc83be4e7 quản lí robot 2026-10-19 15:21:04 +07:00
2be2e075a0 gititnore 2026-10-14 09:26:57 +07:00
533923076c xuất excel 2026-10-14 09:10:37 +07:00
dff0d32912 update pass 2026-09-30 10:09:08 +07:00
3201a18fd4 update quản lí dự án 2026-09-23 15:54:40 +07:00
bd8ba94301 fix UI 2026-09-23 15:14:54 +07:00
cdaa56febd fix - ASS-OLD 2026-09-23 09:59:41 +07:00
a215b503c6 update file tài sản 2026-09-21 10:06:27 +07:00
2015c6fc16 fix "x" 2026-09-15 10:27:26 +07:00
302d262d33 notification 2026-08-07 08:52:51 +07:00
26094ee4d6 upload tài liệu 2026-08-06 10:44:25 +07:00
92bcb04682 update logo 2026-08-05 10:09:34 +07:00
83bfe98ea7 fix đăng ký 2026-08-03 09:03:27 +07:00
57fc826ebf security + reponsive 2026-07-17 14:16:37 +07:00
00e271fada reponsive all 2026-07-17 10:37:46 +07:00
5c818583dc reponsive moblie 2026-07-17 09:54:41 +07:00
c232fe698f gititore 2026-07-01 16:37:17 +07:00
4b1296c8f8 trả/mượn vtth 2026-06-30 09:51:32 +07:00
f00734deb8 vtth 2026-06-25 09:14:11 +07:00
c36a2e17a7 git commit -m "Stop tracking local env file" 2026-06-22 10:18:01 +07:00
1ff9826056 time 2026-05-15 14:26:30 +07:00
41e523ff35 case hỏng 2026-05-15 10:51:39 +07:00
12c6380ceb fix mươn tài sản đã xuất 2026-05-15 10:17:40 +07:00
cb4d5b9520 done mượn trả 2026-05-15 10:10:25 +07:00
e1b553ba79 fix mượn trả 2026-05-15 10:05:42 +07:00
4aa4ac0d57 fixx v1 2026-05-15 09:56:33 +07:00
927317a87e fix danh mục 2026-05-14 15:41:56 +07:00
57d3d538fa import final 2026-05-08 16:00:28 +07:00
65d6c4f11e fix model validate 2026-05-08 14:21:06 +07:00
f49d5a427c tài sản mượn 2026-05-07 09:44:39 +07:00
395b1f6e85 fixx 01 2026-05-06 16:56:58 +07:00
9f14491562 trạng thái 2026-05-06 16:36:12 +07:00
d88aa39bd6 xuất tài sản 2026-05-06 16:04:56 +07:00
8b2a9d7afe import fix 2026-05-06 11:14:10 +07:00
197186eac8 add dự án 2026-04-25 21:34:17 +07:00
8bd67200ce forgot pass 2026-04-25 11:58:09 +07:00
4fb7f412bf fix mượn trả 2026-04-25 09:24:35 +07:00
bc7a484a01 color
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 16:34:14 +07:00
d4800beb67 request 2026-04-24 16:11:00 +07:00
3961514f6c 24/04/2026 - mã tài sản 2026-04-24 13:56:12 +07:00
9526628334 test 2026-04-22 17:18:31 +07:00
6dc2391858 ok 2026-04-22 17:11:01 +07:00
bcc22b1971 ignore .env 2026-04-22 17:10:23 +07:00
61c4415ff7 push 2026-04-22 16:59:13 +07:00
1408294922 import 2026-04-22 16:57:48 +07:00
5f3e38a3d4 Update README.md 2026-04-20 08:32:13 +00:00
a8933011dd delete 2026-04-20 08:31:37 +00:00
aada849671 update day 2026-04-20 15:30:56 +07:00
3b813a85da sercurity 2026-04-20 15:27:27 +07:00
30e326f92a role 2026-04-20 13:45:29 +07:00
ee10a7e480 sercurity 2026-04-03 09:06:38 +07:00
e59785e06b readme 2026-04-02 15:45:27 +07:00
27c2a4c51e reponsive 2026-04-02 15:41:23 +07:00
a78769cfde Merge branch 'main' of https://git.pnkr.asia/DungTT/ManagerAccount 2026-04-02 15:24:03 +07:00
5a7bf191d0 confirm email 2026-04-02 15:23:32 +07:00
b3c1283694 Update DEPLOYMENT_GUIDE.md 2026-04-02 08:20:53 +00:00
6c2e89dc93 update role 2026-04-02 13:34:11 +07:00
c823549458 readme 2026-04-02 11:26:14 +07:00
d09ba3d2ad done ver1.0.0 2026-04-02 11:16:18 +07:00
58dbefa155 done manager account 2026-03-31 14:14:01 +07:00
900a569c51 fomat 2026-03-31 13:48:10 +07:00
0c1ca1d923 dialog 2026-03-31 10:20:35 +07:00
209b68c3f5 save 2026-03-31 10:20:27 +07:00
81 changed files with 35199 additions and 5170 deletions

9
.dockerignore Normal file
View File

@@ -0,0 +1,9 @@
node_modules
npm-debug.log
.git
.gitignore
.vscode
.idea
.vs
.env
docker-compose.yml

15
.env
View File

@@ -1,15 +0,0 @@
# AccManager Backend Configuration
# Server Port
PORT=3000
# SQL Server Configuration
DB_SERVER=172.20.235.176
DB_USER=sa
DB_PASSWORD=robotics@2020
DB_NAME=AccManager
DB_ENCRYPT=true
DB_TRUST_CERTIFICATE=true
# Application
NODE_ENV=development

48
.env.example Normal file
View File

@@ -0,0 +1,48 @@
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

14
.gitignore vendored
View File

@@ -1 +1,15 @@
node_modules
.env
.env.*
!.env.example
DEPLOYMENT_GUIDE.md
docs-output
scripts
.codex-server.err.log
.codex-server.out.log
tmp
outputs
test/
tools
output
docs

View File

@@ -1,291 +0,0 @@
# AccManager Backend Setup Guide
## 📋 Database Information
**Server:** 172.20.235.176
**Database:** AccManager
**User:** sa
**Password:** robotics@2020
## 📊 Database Structure
### Tables Created
#### 1. **Users** - Quản lý người dùng
- `UserId` (INT) - Primary Key
- `Username` (NVARCHAR) - Unique
- `Password` (NVARCHAR)
- `Email` (NVARCHAR)
- `FullName` (NVARCHAR)
- `Role` (NVARCHAR) - admin, user, viewer
- `Status` (NVARCHAR) - Active/Inactive
- `CreatedDate` (DATETIME)
- `LastLogin` (DATETIME)
- `IsActive` (BIT)
#### 2. **Applications** - Danh sách ứng dụng
- `AppId` (INT) - Primary Key
- `Name` (NVARCHAR)
- `Type` (NVARCHAR) - Cloud, VCS, Collaboration, Infra
- `Status` (NVARCHAR) - online/offline
- `Icon` (NVARCHAR)
- `Description` (NVARCHAR)
- `CreatedDate` (DATETIME)
- `UpdatedDate` (DATETIME)
#### 3. **Accounts** - Tài khoản ứng dụng
- `AccountId` (INT) - Primary Key
- `UserId` (INT) - Foreign Key
- `AppId` (INT) - Foreign Key
- `AccountUsername` (NVARCHAR)
- `AccountPassword` (NVARCHAR)
- `Email` (NVARCHAR)
- `AccessLevel` (NVARCHAR)
- `Status` (NVARCHAR)
- `Notes` (NVARCHAR)
- `CreatedDate` (DATETIME)
- `UpdatedDate` (DATETIME)
#### 4. **AuditLog** - Nhật ký hoạt động
- `LogId` (INT) - Primary Key
- `UserId` (INT) - Foreign Key
- `Action` (NVARCHAR) - INSERT, UPDATE, DELETE
- `TableName` (NVARCHAR)
- `RecordId` (INT)
- `OldValue` (NVARCHAR)
- `NewValue` (NVARCHAR)
- `Timestamp` (DATETIME)
## 🔐 Default Admin Account
**Username:** admin
**Password:** admin
**Role:** admin
**Status:** Active
## 🚀 Installation & Setup
### 1. Install Node.js Dependencies
```bash
npm install
```
### 2. Run Backend Server
```bash
npm start
```
Server sẽ chạy tại: **http://localhost:3000**
### 3. Kiểm tra Database Connection
```bash
curl http://localhost:3000/api/health
```
Response:
```json
{
"status": "OK",
"database": "Connected"
}
```
## 📡 API Endpoints
### Authentication
#### Login
```bash
POST /api/auth/login
Content-Type: application/json
{
"username": "admin",
"password": "admin"
}
```
### Users
#### Get All Users
```bash
GET /api/users
```
#### Get User Details
```bash
GET /api/users/:id
```
#### Create New User
```bash
POST /api/users
Content-Type: application/json
{
"username": "newuser",
"password": "password123",
"email": "user@example.com",
"fullname": "Full Name",
"role": "user"
}
```
### Applications
#### Get All Applications
```bash
GET /api/applications
```
#### Create Application
```bash
POST /api/applications
Content-Type: application/json
{
"name": "New App",
"type": "Cloud",
"status": "online",
"icon": "cloud",
"description": "Application description"
}
```
### Accounts
#### Get User Accounts
```bash
GET /api/accounts/user/:userId
```
#### Create Account
```bash
POST /api/accounts
Content-Type: application/json
{
"userId": 1,
"appId": 1,
"accountUsername": "account_user",
"accountPassword": "account_pass",
"email": "account@example.com",
"accessLevel": "Admin",
"notes": "Account notes"
}
```
### Database Info
#### Get Database Statistics
```bash
GET /api/database/info
```
Response:
```json
{
"success": true,
"database": "AccManager",
"server": "172.20.235.176",
"tables": [
{
"TableName": "Accounts",
"ColumnCount": 11
},
{
"TableName": "Applications",
"ColumnCount": 7
},
{
"TableName": "AuditLog",
"ColumnCount": 8
},
{
"TableName": "Users",
"ColumnCount": 10
}
],
"statistics": {
"users": 1,
"applications": 4,
"accounts": 0
}
}
```
## 🔧 Frontend Integration
Update frontend API calls to use the backend server:
```javascript
// Change from localStorage to API calls
const API_URL = 'http://localhost:3000/api';
// Example: Login
async function login(username, password) {
const response = await fetch(`${API_URL}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
return response.json();
}
// Example: Get user accounts
async function getAccounts(userId) {
const response = await fetch(`${API_URL}/accounts/user/${userId}`);
return response.json();
}
```
## 📝 Initial Data Created
### Users
- **admin** (admin role)
### Applications
- AWS (Cloud) - online
- GitHub (VCS) - online
- Google Workspace (Collaboration) - online
- Nginx Proxy (Infra) - offline
## 🐛 Troubleshooting
### Connection Error
```
Database connection failed: Error
```
**Solution:**
- Kiểm tra SQL Server đang chạy
- Kiểm tra network connectivity đến 172.20.235.176
- Kiểm tra username/password đúng
- Kiểm tra SQL Server Authentication được enable
### Port Already in Use
```
listen EADDRINUSE: address already in use :::3000
```
**Solution:**
```bash
# Change port in .env
PORT=3001
```
### MSSQL Module Not Found
```bash
npm install mssql
```
## 📚 References
- [ExpressJS Documentation](https://expressjs.com/)
- [MSSQL Package](https://github.com/tediousjs/node-mssql)
- [SQL Server Documentation](https://docs.microsoft.com/en-us/sql/)
---
**Status:** ✓ Database created, ✓ Tables created, ✓ Admin user created, ✓ Backend ready

17
Dockerfile Normal file
View File

@@ -0,0 +1,17 @@
FROM node:22-bookworm-slim
WORKDIR /app
ENV NODE_ENV=production
ENV TZ=Asia/Ho_Chi_Minh
ENV APP_TIME_ZONE=Asia/Ho_Chi_Minh
COPY package*.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY backend ./backend
COPY public ./public
EXPOSE 3000
CMD ["node", "backend/server.js"]

166
README.md
View File

@@ -1,166 +0,0 @@
# 🎯 AccManager - SQL Server Backend Setup Complete
## ✅ Database Configuration Complete
SQL Server database **AccManager** has been successfully configured with all necessary tables and initial data.
### 📊 Database Information
```
Server IP: 172.20.235.176
Database: AccManager
User: sa
Password: robotics@2020
Port: 1433 (default)
```
### 👤 Default Admin Account
```
Username: admin
Password: admin
Role: admin
Status: Active
```
## 📋 Database Tables Created
### 1. **Users** - User Management
- Stores login credentials and user roles
- Default admin user: admin/admin
### 2. **Applications** - Service Management
- 4 sample applications pre-loaded:
- AWS (Cloud) - online
- GitHub (VCS) - online
- Google Workspace (Collaboration) - online
- Nginx Proxy (Infra) - offline
### 3. **Accounts** - Credential Storage
- Stores credentials for each user-application combination
- Linked to Users and Applications tables
### 4. **AuditLog** - Activity Tracking
- Logs all INSERT, UPDATE, DELETE operations
- User actions tracked for security
## 🚀 Backend Server Options
### Option 1️⃣: Node.js + Express (Recommended)
**Files:**
- `server.js` - Main server file
- `package.json` - Dependencies
**Quick Start:**
```bash
# 1. Install Node.js from https://nodejs.org/
# 2. Install dependencies
npm install
# 3. Run server
npm start
# Server runs on: http://localhost:3000
```
### Option 2️⃣: Python + Flask
**Files:**
- `server_python.py` - Main server file
- `requirements.txt` - Dependencies
**Quick Start:**
```bash
# 1. Install Python 3.8+ from https://www.python.org/
# 2. Install dependencies
pip install -r requirements.txt
# 3. Run server
python server_python.py
# Server runs on: http://localhost:5000
```
## 📡 API Endpoints
### Health Check
```http
GET /api/health
```
### Authentication
```http
POST /api/auth/login
```
### Users Management
```http
GET /api/users
GET /api/users/:id
POST /api/users
```
### Applications
```http
GET /api/applications
POST /api/applications
```
### Accounts
```http
GET /api/accounts/user/:userId
POST /api/accounts
```
### Database Info
```http
GET /api/database/info
```
## 📚 Documentation Files
- **README.md** (this file) - Overview
- **SETUP_GUIDE.md** - Detailed installation steps
- **DATABASE_SETUP.md** - Schema and API documentation
- **server.js** - Node.js backend source
- **server_python.py** - Python backend source
## 🔐 Default Credentials
```
Username: admin
Password: admin
Role: admin
```
## 🔧 Project Files
```
d:\RoboticsSource\AccManager\
├── server.js (Node.js backend)
├── server_python.py (Python backend)
├── package.json (Node.js dependencies)
├── requirements.txt (Python dependencies)
├── .env (Configuration)
├── database/
│ └── setup.sql (SQL setup script)
├── SETUP_GUIDE.md (Installation guide)
├── DATABASE_SETUP.md (Database documentation)
└── README.md (This file)
```
## ✅ Status
- ✓ Database created (AccManager)
- ✓ 4 tables created (Users, Applications, Accounts, AuditLog)
- ✓ Admin user created (admin/admin)
- ✓ Sample applications added
- ✓ Backend servers ready (Node.js + Python options)
- ✓ API endpoints documented
---
**Version:** 2.0.0 (Backend Ready)
**Database:** SQL Server / AccManager
**Last Updated:** March 27, 2026

View File

@@ -1,220 +0,0 @@
# 🚀 Hướng Dẫn Chạy AccManager - Dành cho Người Dùng Mới
## 📋 Bước 1: Kiểm Tra Node.js
Mở **PowerShell** và chạy:
```powershell
node --version
npm --version
```
**Kết quả mong đợi:**
```
v18.16.0 (hoặc version cao hơn)
9.6.7 (hoặc version khác)
```
Nếu thấy version → **OK, tiếp tục bước 2**
---
## 📋 Bước 2: Vào Thư Mục Dự Án
Copy-paste lệnh này vào PowerShell:
```powershell
cd d:\RoboticsSource\AccManager
```
---
## 📋 Bước 3: Cài Đặt Dependencies
Copy-paste lệnh này vào PowerShell:
```powershell
npm install
```
**Chờ cho tới khi thấy:**
```
added XXX packages in XXs
```
(Sẽ mất 1-3 phút tùy tốc độ mạng)
---
## 📋 Bước 4: Chạy Backend Server
Copy-paste lệnh này vào PowerShell:
```powershell
npm start
```
**Khi thành công, bạn sẽ thấy:**
```
========================================
AccManager Backend Server
========================================
✓ Server running on http://localhost:3000
✓ Database: AccManager
✓ Default admin: admin / admin
API Endpoints:
POST /api/auth/login
GET /api/database/info
GET /api/users
GET /api/applications
GET /api/accounts/user/:userId
========================================
```
**👉 ĐỪNG ĐÓNG TERMINAL NÀY - Server đang chạy!**
---
## 🌐 Bước 5: Mở Ứng Dụng
**Mở trình duyệt** (Chrome, Firefox, Edge...) copy-paste URL này:
```
http://localhost:3000/pages/login.html
```
---
## 🔐 Bước 6: Đăng Nhập
**Nhập thông tin:**
- Username: `admin`
- Password: `admin`
Nhấp **Login**
---
## ✅ Nếu Thành Công
Bạn sẽ thấy:
- ✓ Trang Dashboard
- ✓ Quản lý Accounts
- ✓ Quản lý Applications
- ✓ Thông tin Database
---
## ❌ Nếu Có Lỗi
### Lỗi 1: "npm: The term 'npm' is not recognized"
**Giải pháp:**
- Đóng PowerShell hiện tại
- Mở PowerShell **mới**
- Chạy lại `npm --version`
### Lỗi 2: "Cannot find module 'express'"
**Giải pháp:**
```powershell
npm install
npm start
```
### Lỗi 3: "Port 3000 already in use"
**Giải pháp:** Có chương trình khác dùng port 3000
```powershell
# Dừng server cũ (Ctrl+C)
# Rồi chạy lại: npm start
```
### Lỗi 4: "Cannot connect to database"
**Giải pháp:** Kiểm tra SQL Server
- Đảm bảo SQL Server đang chạy
- IP: 172.20.235.176 có reach được không
```powershell
ping 172.20.235.176
```
---
## 💡 Full Workflow - Copy Toàn Bộ Lệnh
Nếu bạn muốn copy toàn bộ một lần:
```powershell
# Kiểm tra Node.js
node --version
# Vào thư mục
cd d:\RoboticsSource\AccManager
# Cài packages
npm install
# Chạy server
npm start
```
---
## 🎯 Các Lệnh Hữu Ích Khác
### Dừng Server
Nhấp **Ctrl + C** trong PowerShell
### Chạy Server Ở Chế Độ Development (auto-restart)
```powershell
npm run dev
```
### Kiểm Tra API Health
Mở browser khác nhập:
```
http://localhost:3000/api/health
```
### Xem Tất Cả Users
```
http://localhost:3000/api/users
```
### Xem Tất Cả Applications
```
http://localhost:3000/api/applications
```
### Database Info
```
http://localhost:3000/api/database/info
```
---
## 📊 Sơ Đồ Port
| URL | Port | Mục đích |
|-----|------|---------|
| http://localhost:3000/pages/login.html | 3000 | Frontend |
| http://localhost:3000/api/health | 3000 | Backend API |
| 172.20.235.176 | 1433 | SQL Server |
---
## 🎯 Tóm Tắt - 4 Bước Chính
1. **Mở PowerShell**
2. **Chạy:**
```powershell
cd d:\RoboticsSource\AccManager
npm install
npm start
```
3. **Chờ thấy "Server running on http://localhost:3000"**
4. **Mở browser vào: http://localhost:3000/pages/login.html**
5. **Đăng nhập: admin / admin**
---
**Chúc bạn thành công! 🚀**

View File

@@ -1,294 +0,0 @@
# 🚀 AccManager Backend - Complete Setup Guide
## ⚠️ Pre-requisites
### 1. Install Node.js & npm
**Download từ:** https://nodejs.org/
**Khuyến khích:** LTS version (v18 hoặc mới hơn)
#### Kiểm tra installation:
```bash
node --version
npm --version
```
Expected output:
```
v18.* (or newer)
9.* (or newer)
```
### 2. Verify SQL Server Connection
Trước khi chạy backend, kiểm tra SQL Server:
```bash
ping 172.20.235.176
```
Nếu không ping được, kiểm tra:
- SQL Server đang chạy
- Firewall cho phép port 1433
- Network connectivity
---
## 📥 Setup Steps
### Step 1: Install Node Packages
```bash
cd d:\RoboticsSource\AccManager
npm install
```
Wait cho tới khi mô tả xuất hiện `added X packages`
### Step 2: Run Backend Server
```bash
npm start
```
**Expected Output:**
```
========================================
AccManager Backend Server
========================================
✓ Server running on http://localhost:3000
✓ Database: AccManager
✓ Default admin: admin / admin
API Endpoints:
POST /api/auth/login
GET /api/database/info
GET /api/users
GET /api/applications
GET /api/accounts/user/:userId
========================================
```
### Step 3: Test Connection
Mở terminal mới, chạy:
```bash
curl http://localhost:3000/api/health
```
**Response:**
```json
{
"status": "OK",
"database": "Connected"
}
```
### Step 4: Test Database Info
```bash
curl http://localhost:3000/api/database/info
```
---
## 📝 Database Structure
### Database Name: `AccManager`
#### Tables:
1. **Users** (1 admin account)
- Username: admin
- Password: admin
- Role: admin
2. **Applications** (4 sample apps)
- AWS
- GitHub
- Google Workspace
- Nginx Proxy
3. **Accounts** (empty, ready to use)
4. **AuditLog** (empty, for logging)
---
## 🧪 Test API Endpoints
### Test 1: Login
```bash
curl -X POST http://localhost:3000/api/auth/login \
-H "Content-Type: application/json" \
-d "{\"username\":\"admin\",\"password\":\"admin\"}"
```
### Test 2: Get Users
```bash
curl http://localhost:3000/api/users
```
### Test 3: Get Applications
```bash
curl http://localhost:3000/api/applications
```
### Test 4: View Database Info
```bash
curl http://localhost:3000/api/database/info
```
---
## 🔌 Frontend Integration
Update your frontend to connect to the backend:
### Option 1: Update app.js
```javascript
const API_URL = 'http://localhost:3000/api';
// Update login function
async function login(username, password) {
const response = await fetch(`${API_URL}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (data.success) {
localStorage.setItem('currentUser', JSON.stringify(data.user));
window.location.href = './pages/accounts.html';
} else {
alert('Login failed: ' + data.message);
}
}
// Update get accounts function
async function getAccounts(userId) {
const response = await fetch(`${API_URL}/accounts/user/${userId}`);
const data = await response.json();
return data.data || [];
}
```
---
## 📦 Project Structure
```
d:\RoboticsSource\AccManager\
├── server.js # Backend server (Node.js)
├── package.json # Dependencies
├── .env # Configuration
├── DATABASE_SETUP.md # This file
├── database/
│ └── setup.sql # SQL setup script
├── index.html # Frontend entry
├── pages/
│ ├── login.html
│ ├── accounts.html
│ ├── applications.html
│ └── index.html
└── js/
└── app.js # Frontend logic
```
---
## 🔒 Security Notes
⚠️ **For Development Only:**
- Admin password is hardcoded as "admin"
- SQL credentials in code (not recommended for production)
- CORS enabled for all origins
### For Production:
1. Use environment variables
2. Hash passwords with bcrypt
3. Implement JWT authentication
4. Use firewalls and VPNs
5. Enable SSL/TLS
---
## 🐛 Troubleshooting
### Error: "Cannot find module 'express'"
```bash
npm install
```
### Error: "Connection failed"
Check:
- SQL Server running
- IP address correct: 172.20.235.176
- Port 1433 accessible
- Username/password correct
### Error: "Port 3000 already in use"
```bash
# Change port in .env
PORT=3001
# Then restart server
npm start
```
### Error: "CORS error in browser"
This is normal during development. The backend already has CORS enabled.
---
## 📊 Database Credentials
```
Server: 172.20.235.176
Database: AccManager
User: sa
Password: robotics@2020
```
---
## ✅ Verification Checklist
- [ ] Node.js installed
- [ ] npm packages installed (`npm install`)
- [ ] Backend server running (`npm start`)
- [ ] Can access http://localhost:3000/api/health
- [ ] Can login with admin/admin
- [ ] Database shows tables and statistics
- [ ] Frontend connects to backend
---
## 📚 Additional Commands
### Install Development Tools
```bash
npm install -D nodemon
npm run dev # Auto-restart on code changes
```
### Check npm packages
```bash
npm list
```
### Update packages
```bash
npm update
```
### Clear npm cache
```bash
npm cache clean --force
```
---
**For Support:** Check server logs for error messages

86
backend/announcements.js Normal file
View File

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

View File

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

View File

@@ -0,0 +1,10 @@
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 };

View File

@@ -0,0 +1,96 @@
-- 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;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

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

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

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

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

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

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

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

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

317
backend/robots.js Normal file
View File

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

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

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

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

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

9791
backend/server.js Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@@ -1,63 +0,0 @@
# PowerShell Script to Execute SQL Server Setup
# Database: AccManager
# Server: 172.20.235.176
# SQL Server Connection Info
$ServerName = "172.20.235.176"
$Username = "sa"
$Password = "robotics@2020"
$SqlScriptPath = ".\setup.sql"
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "AccManager Database Setup" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
# Check if sqlcmd is available
if (-not (Get-Command sqlcmd -ErrorAction SilentlyContinue)) {
Write-Host "ERROR: sqlcmd is not available on this system." -ForegroundColor Red
Write-Host "Please install SQL Server Command Line Tools (sqlcmd)" -ForegroundColor Yellow
Write-Host "Download from: https://docs.microsoft.com/en-us/sql/tools/sqlcmd-utility" -ForegroundColor Yellow
exit
}
# Check if SQL script file exists
if (-not (Test-Path $SqlScriptPath)) {
Write-Host "ERROR: SQL script file not found: $SqlScriptPath" -ForegroundColor Red
exit
}
Write-Host "Server: $ServerName" -ForegroundColor Green
Write-Host "User: $Username" -ForegroundColor Green
Write-Host "Script: $SqlScriptPath" -ForegroundColor Green
Write-Host ""
# Execute SQL Script
Write-Host "Executing SQL script..." -ForegroundColor Yellow
Write-Host ""
try {
sqlcmd -S $ServerName -U $Username -P $Password -i $SqlScriptPath -o "setup_output.log"
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "SETUP COMPLETED SUCCESSFULLY!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Output saved to: setup_output.log" -ForegroundColor Cyan
Write-Host ""
# Display output
Write-Host "Setup Output:" -ForegroundColor Cyan
Get-Content "setup_output.log"
}
catch {
Write-Host "ERROR executing SQL script:" -ForegroundColor Red
Write-Host $_.Exception.Message -ForegroundColor Red
exit
}
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "Database is ready to use!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green

File diff suppressed because it is too large Load Diff

41
docker-compose.image.yml Normal file
View File

@@ -0,0 +1,41 @@
services:
accmanager:
image: ${DOCKER_IMAGE:-yourdockerhub/accmanager:latest}
container_name: accmanager
restart: unless-stopped
ports:
- "${APP_PORT:-3000}:3000"
environment:
NODE_ENV: ${NODE_ENV:-production}
PORT: 3000
TZ: ${TZ:-Asia/Ho_Chi_Minh}
APP_TIME_ZONE: ${APP_TIME_ZONE:-Asia/Ho_Chi_Minh}
DB_SERVER: ${DB_SERVER:?DB_SERVER is required}
DB_USER: ${DB_USER:?DB_USER is required}
DB_PASSWORD: ${DB_PASSWORD:?DB_PASSWORD is required}
DB_NAME: ${DB_NAME:-AccManager}
DB_ENCRYPT: ${DB_ENCRYPT:-false}
DB_TRUST_CERTIFICATE: ${DB_TRUST_CERTIFICATE:-true}
DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-30000}
BCRYPT_ROUNDS: ${BCRYPT_ROUNDS:-12}
DATA_ENCRYPTION_SECRET: ${DATA_ENCRYPTION_SECRET:?DATA_ENCRYPTION_SECRET is required}
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_PORT: ${SMTP_PORT:-587}
SMTP_SECURE: ${SMTP_SECURE:-false}
SMTP_REQUIRE_TLS: ${SMTP_REQUIRE_TLS:-true}
SMTP_USER: ${SMTP_USER:-}
SMTP_PASS: ${SMTP_PASS:-}
SMTP_FROM: ${SMTP_FROM:-}
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}

43
docker-compose.yml Normal file
View File

@@ -0,0 +1,43 @@
services:
accmanager:
build:
context: .
dockerfile: Dockerfile
container_name: accmanager
restart: unless-stopped
ports:
- "${APP_PORT:-3000}:3000"
environment:
NODE_ENV: production
PORT: 3000
TZ: ${TZ:-Asia/Ho_Chi_Minh}
APP_TIME_ZONE: ${APP_TIME_ZONE:-Asia/Ho_Chi_Minh}
DB_SERVER: ${DB_SERVER:?DB_SERVER is required}
DB_USER: ${DB_USER:?DB_USER is required}
DB_PASSWORD: ${DB_PASSWORD:?DB_PASSWORD is required}
DB_NAME: ${DB_NAME:-AccManager}
DB_ENCRYPT: ${DB_ENCRYPT:-false}
DB_TRUST_CERTIFICATE: ${DB_TRUST_CERTIFICATE:-true}
DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-30000}
BCRYPT_ROUNDS: ${BCRYPT_ROUNDS:-12}
DATA_ENCRYPTION_SECRET: ${DATA_ENCRYPTION_SECRET:?DATA_ENCRYPTION_SECRET is required}
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_PORT: ${SMTP_PORT:-587}
SMTP_SECURE: ${SMTP_SECURE:-false}
SMTP_REQUIRE_TLS: ${SMTP_REQUIRE_TLS:-true}
SMTP_USER: ${SMTP_USER:-}
SMTP_PASS: ${SMTP_PASS:-}
SMTP_FROM: ${SMTP_FROM:-}
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}

View File

@@ -1,134 +0,0 @@
# Robot Account Manager - Project Structure
## Directory Organization
```
AccManager/
├── pages/ # HTML pages
│ ├── login.html # Login page (entry point)
│ ├── index.html # Dashboard
│ ├── accounts.html # Accounts management
│ └── applications.html # Applications management
├── js/ # JavaScript files
│ └── app.js # Main application logic
├── docs/ # Documentation
│ └── README.md # This file
├── index.html # Root redirect to pages/login.html
├── .git/ # Version control
├── .vscode/ # VS Code settings
└── README.md # Project root README
```
## Quick Start
1. **Access the application:**
- Open `index.html` in a browser
- You will be automatically redirected to `pages/login.html`
2. **Login Credentials (Demo):**
- Username: `admin`
- Password: `admin`
3. **Features:**
- Dashboard: Overview of accounts and applications
- Accounts: Manage user accounts for various services
- Applications: Manage connected applications/services
## File Structure Explanation
### /pages/
Contains all HTML pages with updated relative paths for script imports:
- `login.html` - Authentication page
- `index.html` - Main dashboard
- `accounts.html` - Accounts management interface
- `applications.html` - Applications management interface
All pages reference scripts using `../js/app.js` for correct path resolution.
### /js/
Application logic and state management:
- `app.js` - Main AccountManager class with all functionality
### /docs/
Documentation files for reference and development.
## Application Architecture
### AccountManager Class (app.js)
- **Storage**: Uses localStorage for data persistence
- **Pages**: Dynamically renders content based on user navigation
- **Authentication**: Checks for valid session on page load
- **Modals**: Manages adding/editing accounts and applications
### Data Storage
Application stores data in browser's localStorage:
- `currentUser` - Logged-in user information
- `accounts` - List of managed accounts
- `applications` - List of managed applications
- `rememberedUsername` - Optional saved username
## Development Notes
- **Framework**: Tailwind CSS for styling
- **Icons**: Material Design symbols
- **Storage**: Browser localStorage (client-side only)
- **Responsive**: Built with mobile-first approach
- **Modern**: ES6+ JavaScript features
## Navigation Flow
```
index.html (root)
↓
pages/login.html
↓ (after login)
pages/index.html (dashboard)
├→ pages/accounts.html
└→ pages/applications.html
```
## Features
### Authentication
- Username/password login
- Session management
- Remember me functionality
- Logout with confirmation
### Dashboard
- Overview statistics
- Recent account activity
- Quick access to management pages
### Account Management
- Add new accounts
- Edit existing accounts
- Delete accounts
- Filter by service
- View account details
### Application Management
- Add new applications
- Edit application details
- Delete applications
- View application status (online/offline)
- Health monitoring
## Browser Compatibility
- Modern browsers (Chrome, Firefox, Safari, Edge)
- Requires JavaScript enabled
- Uses localStorage API
## Future Improvements
- Server-side authentication
- Database integration
- Advanced filtering and search
- User roles and permissions
- Audit logging
- Dark mode toggle persistence
---
Generated: March 27, 2026
Version: 1.0.0

View File

@@ -1,35 +0,0 @@
# Install Node.js automatically (Run as Administrator)
Write-Host "Installing Node.js LTS..." -ForegroundColor Green
# Check if winget is available
if (Get-Command winget -ErrorAction SilentlyContinue) {
Write-Host "Found winget, installing Node.js..." -ForegroundColor Cyan
winget install OpenJS.NodeJS
}
else {
Write-Host "winget not found. Downloading Node.js installer..." -ForegroundColor Yellow
# Download Node.js LTS
$NodeURL = "https://nodejs.org/dist/v18.16.0/node-v18.16.0-x64.msi"
$InstallerPath = "$env:TEMP\nodejs-installer.msi"
Write-Host "Downloading from: $NodeURL"
Invoke-WebRequest -Uri $NodeURL -OutFile $InstallerPath -UseBasicParsing
Write-Host "Running installer..." -ForegroundColor Cyan
Start-Process -FilePath "msiexec.exe" -ArgumentList "/i $InstallerPath /quiet /norestart" -Wait
Remove-Item $InstallerPath
}
Write-Host "Installation complete! Refreshing environment..." -ForegroundColor Green
# Refresh PATH
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
Write-Host "Checking installation..." -ForegroundColor Cyan
node --version
npm --version
Write-Host "Ready to run npm install!" -ForegroundColor Green

545
js/app.js
View File

@@ -1,545 +0,0 @@
// VaultSentinel - Account Management Application
// Main JavaScript functionality
class AccountManager {
constructor() {
// Check if user is logged in
const currentUser = this.loadFromStorage('currentUser');
if (!currentUser) {
window.location.href = '../pages/login.html';
return;
}
this.currentUser = currentUser;
this.accounts = this.loadFromStorage('accounts') || [];
this.applications = this.loadFromStorage('applications') || [
{ id: 1, name: 'AWS', type: 'Cloud', status: 'online', icon: 'cloud' },
{ id: 2, name: 'GitHub', type: 'VCS', status: 'online', icon: 'code' },
{ id: 3, name: 'Google Workspace', type: 'Collaboration', status: 'online', icon: 'mail' },
{ id: 4, name: 'Nginx Proxy', type: 'Infra', status: 'offline', icon: 'dns' },
];
this.currentPage = 'dashboard';
this.init();
}
init() {
this.setupEventListeners();
// Render dashboard content
const mainContent = document.getElementById('mainContent');
if (mainContent) {
mainContent.innerHTML = this.renderDashboard();
}
}
setupEventListeners() {
// Account modal
const addAccountBtn = document.getElementById('addAccountBtn');
if (addAccountBtn) {
addAccountBtn.addEventListener('click', () => this.openAccountModal());
}
// Application modal
const addAppBtn = document.getElementById('addAppBtn');
if (addAppBtn) {
addAppBtn.addEventListener('click', () => this.openAppModal());
}
// Modal close buttons
document.querySelectorAll('[data-close-modal]').forEach(btn => {
btn.addEventListener('click', () => this.closeModals());
});
// Form submissions
const accountForm = document.getElementById('accountForm');
if (accountForm) {
accountForm.addEventListener('submit', (e) => this.handleAccountSubmit(e));
}
const appForm = document.getElementById('appForm');
if (appForm) {
appForm.addEventListener('submit', (e) => this.handleAppSubmit(e));
}
// Logout button
const logoutBtn = document.getElementById('logoutBtn');
if (logoutBtn) {
logoutBtn.addEventListener('click', () => this.handleLogout());
}
// Update account display
this.updateAccountDisplay();
// Account table row clicks
this.setupAccountRowListeners();
}
updateAccountDisplay() {
// Use the logged-in user from constructor
const usernameEl = document.getElementById('accountUsername');
const roleEl = document.getElementById('accountRole');
if (usernameEl) usernameEl.textContent = this.currentUser?.username || 'User';
if (roleEl) roleEl.textContent = this.currentUser?.role || 'Administrator';
}
handleLogout() {
if (confirm('Are you sure you want to logout?')) {
this.saveToStorage('currentUser', null);
localStorage.clear();
window.location.href = '../pages/login.html';
}
}
renderDashboard() {
return `
<div class="flex-1 flex flex-col p-6 space-y-6 min-h-0 overflow-auto">
<!-- Title and Stats -->
<div class="flex items-end justify-between shrink-0">
<div>
<h1 class="text-2xl font-extrabold text-on-surface tracking-tight leading-none">System Overview</h1>
<p class="text-xs text-on-surface-variant font-medium mt-1">Account & Service Management</p>
</div>
<div class="flex gap-2">
<a href="./accounts.html" class="py-1.5 px-3 bg-primary text-on-primary rounded-lg text-xs font-bold flex items-center gap-1.5 shadow-sm active:scale-95 duration-100">
<span class="material-symbols-outlined text-sm">add</span>
Add Account
</a>
</div>
</div>
<!-- Metric Grid -->
<div class="grid grid-cols-4 gap-4 shrink-0">
<div class="bg-surface-container-lowest p-4 rounded-xl border border-outline-variant/15 flex flex-col">
<span class="text-[10px] font-bold text-on-surface-variant uppercase tracking-wider mb-2">Applications</span>
<div class="flex items-baseline justify-between">
<span class="text-2xl font-black text-on-surface">${this.applications.length}</span>
<span class="text-[10px] font-bold text-on-surface-variant">${this.applications.filter(a => a.status === 'online').length} Active</span>
</div>
</div>
<div class="bg-surface-container-lowest p-4 rounded-xl border border-outline-variant/15 flex flex-col">
<span class="text-[10px] font-bold text-on-surface-variant uppercase tracking-wider mb-2">Total Accounts</span>
<div class="flex items-baseline justify-between">
<span class="text-2xl font-black text-on-surface">${this.accounts.length}</span>
<span class="text-[10px] font-bold text-on-surface-variant/40">Managed</span>
</div>
</div>
<div class="bg-surface-container-lowest p-4 rounded-xl border border-outline-variant/15 flex flex-col">
<span class="text-[10px] font-bold text-on-surface-variant uppercase tracking-wider mb-2">Last Updated</span>
<div class="flex items-baseline justify-between">
<span class="text-sm font-black text-on-surface">${new Date().toLocaleDateString()}</span>
</div>
</div>
<div class="bg-primary-container/10 p-4 rounded-xl border border-primary/20 flex flex-col">
<span class="text-[10px] font-bold text-primary uppercase tracking-wider mb-2">Status</span>
<div class="flex items-baseline justify-between">
<span class="text-lg font-black text-primary">Operational</span>
<span class="material-symbols-outlined text-primary text-sm">check_circle</span>
</div>
</div>
</div>
<!-- Recent Activity -->
<div class="bg-surface-container-lowest rounded-xl p-5 border border-outline-variant/15 flex flex-col flex-1 min-h-0">
<div class="flex items-center justify-between mb-4 shrink-0">
<h3 class="text-sm font-bold text-on-surface flex items-center gap-2">
<span class="material-symbols-outlined text-primary text-base">history</span>
Recent Accounts
</h3>
</div>
${this.accounts.length > 0 ? `
<div class="flex-1 overflow-y-auto space-y-2">
${this.accounts.slice(-5).reverse().map(acc => `
<div class="flex gap-3 p-3 bg-surface-container-low/50 rounded-lg border-l-2 border-primary/50">
<div class="flex-1 min-w-0">
<p class="text-[11px] font-bold text-on-surface truncate">${acc.username}</p>
<p class="text-[9px] text-on-surface-variant">${acc.service} • ${acc.owner}</p>
</div>
</div>
`).join('')}
</div>
` : `
<div class="flex-1 flex items-center justify-center text-center">
<p class="text-sm text-on-surface-variant">No accounts yet. <a href="./accounts.html" class="text-primary font-bold">Create one</a></p>
</div>
`}
</div>
</div>
`;
}
getAccountsContent() {
return `
<div class="p-4 md:p-6 flex flex-col h-full overflow-hidden">
<!-- Page Header -->
<div class="flex items-center justify-between mb-4 shrink-0">
<div>
<h1 class="text-xl font-extrabold text-on-surface tracking-tight">Accounts Management</h1>
<p class="text-[10px] text-on-surface-variant uppercase font-semibold tracking-widest mt-0.5">Administrative Access Control</p>
</div>
<button id="addAccountBtn" class="bg-primary hover:bg-primary-dim text-on-primary px-3 py-1.5 rounded-lg text-xs font-bold shadow-sm flex items-center gap-1.5 transition-all active:scale-95">
<span class="material-symbols-outlined text-base">person_add</span>
Add Account
</button>
</div>
<!-- Filters -->
<div class="flex items-center gap-3 mb-4">
<div class="flex items-center gap-1.5">
<span class="text-[10px] font-bold uppercase text-on-surface-variant">Service</span>
<select id="serviceFilter" class="bg-surface-container-low border-slate-200 rounded-md text-[11px] py-1 px-2 pr-6 focus:ring-1 focus:ring-primary shadow-sm">
<option value="">All Services</option>
${this.applications.map(app => `<option value="${app.name}">${app.name}</option>`).join('')}
</select>
</div>
<div class="flex-1"></div>
</div>
<!-- Accounts Table -->
<div class="flex-1 bg-white rounded-xl border border-slate-200 shadow-sm flex flex-col overflow-hidden min-h-0">
${this.accounts.length > 0 ? `
<div class="overflow-y-auto overflow-x-auto flex-1">
<table class="w-full text-left border-collapse w-full">
<thead class="sticky top-0 z-10">
<tr class="bg-slate-50 border-b border-slate-200">
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Owner</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Username</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Service</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500 text-right">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100">
${this.accounts.map((acc, idx) => `
<tr class="hover:bg-slate-50/80 transition-colors group account-row" data-account-id="${idx}">
<td class="px-4 py-3 text-sm font-medium text-slate-900">${acc.owner}</td>
<td class="px-4 py-3 text-sm text-slate-600">${acc.username}</td>
<td class="px-4 py-3 text-sm">
<span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs font-semibold">${acc.service}</span>
</td>
<td class="px-4 py-3 text-right">
<button class="p-1.5 text-slate-400 hover:text-primary transition-colors edit-account" data-account-id="${idx}">
<span class="material-symbols-outlined text-lg">edit</span>
</button>
<button class="p-1.5 text-slate-400 hover:text-error transition-colors delete-account" data-account-id="${idx}">
<span class="material-symbols-outlined text-lg">delete</span>
</button>
</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
` : `
<div class="flex-1 flex items-center justify-center text-center">
<div>
<p class="text-sm text-on-surface-variant mb-4">No accounts yet. Create one to get started.</p>
<button id="addAccountBtn" class="bg-primary hover:bg-primary-dim text-on-primary px-4 py-2 rounded-lg text-sm font-bold">
<span class="material-symbols-outlined text-base inline mr-2">person_add</span>
Add First Account
</button>
</div>
</div>
`}
</div>
</div>
<!-- Account Modal -->
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm hidden" id="accountModal">
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
<h3 class="text-base font-extrabold text-slate-900">Add New Account</h3>
<button class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400 transition-colors" data-close-modal>
<span class="material-symbols-outlined">close</span>
</button>
</div>
<form id="accountForm" class="p-6 space-y-4">
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Service</label>
<select id="accountService" class="w-full border-slate-200 rounded-lg text-sm py-2.5 px-3" required>
<option value="">Select a service</option>
${this.applications.map(app => `<option value="${app.name}">${app.name}</option>`).join('')}
</select>
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Owner Name</label>
<input type="text" id="accountOwner" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" required placeholder="John Doe">
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Username</label>
<input type="text" id="accountUsername" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" required placeholder="username">
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Password</label>
<input type="password" id="accountPassword" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" required placeholder="••••••••">
</div>
<div class="flex gap-3 pt-4">
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg" data-close-modal>Cancel</button>
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Save Account</button>
</div>
</form>
</div>
</div>
`;
}
getApplicationsContent() {
return `
<div class="flex flex-col p-6 overflow-hidden h-full">
<!-- Header Section -->
<div class="flex items-center justify-between gap-6 mb-6 shrink-0">
<div>
<h1 class="text-2xl font-extrabold text-on-surface tracking-tight">Applications</h1>
<p class="text-sm text-on-surface-variant">Manage and monitor active infrastructure services.</p>
</div>
<button id="addAppBtn" class="bg-primary hover:bg-primary-dim text-on-primary px-4 py-2 rounded-xl font-bold flex items-center gap-2 transition-all active:scale-95 shadow-sm">
<span class="material-symbols-outlined">add</span>
Add New
</button>
</div>
<!-- Dashboard Stats -->
<div class="grid grid-cols-3 gap-4 mb-6 shrink-0">
<div class="bg-surface-container-lowest px-4 py-3 rounded-xl shadow-sm border border-outline-variant/5 flex items-center gap-4">
<div class="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center text-primary">
<span class="material-symbols-outlined text-xl">lan</span>
</div>
<div>
<p class="text-[10px] font-bold text-on-surface-variant uppercase tracking-wider">Active</p>
<p class="text-lg font-black text-on-surface">${this.applications.filter(a => a.status === 'online').length}</p>
</div>
</div>
<div class="bg-surface-container-lowest px-4 py-3 rounded-xl shadow-sm border border-outline-variant/5 flex items-center gap-4">
<div class="w-10 h-10 rounded-lg bg-tertiary/10 flex items-center justify-center text-tertiary">
<span class="material-symbols-outlined text-xl">bolt</span>
</div>
<div>
<p class="text-[10px] font-bold text-on-surface-variant uppercase tracking-wider">Total</p>
<p class="text-lg font-black text-on-surface">${this.applications.length}</p>
</div>
</div>
<div class="bg-surface-container-lowest px-4 py-3 rounded-xl shadow-sm border border-outline-variant/5 flex items-center gap-4">
<div class="w-10 h-10 rounded-lg bg-secondary/10 flex items-center justify-center text-secondary">
<span class="material-symbols-outlined text-xl">database</span>
</div>
<div>
<p class="text-[10px] font-bold text-on-surface-variant uppercase tracking-wider">Health</p>
<p class="text-lg font-black text-on-surface">99.9%</p>
</div>
</div>
</div>
<!-- Applications List -->
<div class="bg-surface-container-lowest rounded-xl shadow-sm border border-outline-variant/10 overflow-hidden flex flex-col flex-1 min-h-0">
<div class="overflow-y-auto flex-1">
<table class="w-full text-left border-collapse">
<thead class="sticky top-0 bg-surface-container-lowest z-10">
<tr class="bg-surface-container-low/30 border-b border-outline-variant/10">
<th class="px-6 py-2.5 text-[10px] font-bold text-on-surface-variant uppercase tracking-widest">Name</th>
<th class="px-6 py-2.5 text-[10px] font-bold text-on-surface-variant uppercase tracking-widest">Type</th>
<th class="px-6 py-2.5 text-[10px] font-bold text-on-surface-variant uppercase tracking-widest">Status</th>
<th class="px-6 py-2.5 text-[10px] font-bold text-on-surface-variant uppercase tracking-widest text-right">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-outline-variant/5">
${this.applications.map((app, idx) => `
<tr class="hover:bg-surface-container-low/30 transition-colors group">
<td class="px-6 py-3">
<div class="flex items-center gap-3">
<div class="w-8 h-8 rounded bg-surface-container-highest flex items-center justify-center text-primary">
<span class="material-symbols-outlined text-sm">${app.icon}</span>
</div>
<span class="font-bold text-sm text-on-surface">${app.name}</span>
</div>
</td>
<td class="px-6 py-3">
<span class="px-2 py-0.5 rounded-full text-[9px] font-black uppercase bg-surface-container-highest text-on-surface-variant">${app.type}</span>
</td>
<td class="px-6 py-3">
<div class="flex items-center gap-1.5">
<div class="w-1.5 h-1.5 rounded-full ${app.status === 'online' ? 'bg-primary' : 'bg-error'} ring-2 ${app.status === 'online' ? 'ring-primary/20' : 'ring-error/20'}"></div>
<span class="text-xs font-medium ${app.status === 'online' ? 'text-on-primary-fixed-variant' : 'text-error'}">${app.status === 'online' ? 'Online' : 'Offline'}</span>
</div>
</td>
<td class="px-6 py-3 text-right">
<div class="flex items-center justify-end gap-1">
<button class="p-1.5 text-on-surface-variant hover:text-primary transition-colors edit-app" data-app-id="${idx}">
<span class="material-symbols-outlined text-lg">edit</span>
</button>
<button class="p-1.5 text-on-surface-variant hover:text-error transition-colors delete-app" data-app-id="${idx}">
<span class="material-symbols-outlined text-lg">delete</span>
</button>
</div>
</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
</div>
</div>
<!-- App Modal -->
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm hidden" id="appModal">
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
<h3 class="text-base font-extrabold text-slate-900">Add New Application</h3>
<button class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400 transition-colors" data-close-modal>
<span class="material-symbols-outlined">close</span>
</button>
</div>
<form id="appForm" class="p-6 space-y-4">
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Application Name</label>
<input type="text" id="appName" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" required placeholder="AWS Services">
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Type</label>
<input type="text" id="appType" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" required placeholder="Cloud">
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Status</label>
<select id="appStatus" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3">
<option value="online">Online</option>
<option value="offline">Offline</option>
</select>
</div>
<div class="flex gap-3 pt-4">
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg" data-close-modal>Cancel</button>
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Save Application</button>
</div>
</form>
</div>
</div>
`;
}
setupAccountRowListeners() {
document.querySelectorAll('.delete-account').forEach(btn => {
btn.addEventListener('click', (e) => {
const accountId = btn.dataset.accountId;
if (confirm('Delete this account?')) {
this.accounts.splice(accountId, 1);
this.saveToStorage('accounts', this.accounts);
location.href = './accounts.html';
}
});
});
document.querySelectorAll('.edit-account').forEach(btn => {
btn.addEventListener('click', (e) => {
const accountId = btn.dataset.accountId;
const account = this.accounts[accountId];
// Populate form with existing data
document.getElementById('accountUsername').value = account.username;
document.getElementById('accountPassword').value = account.password;
document.getElementById('accountOwner').value = account.owner;
document.getElementById('accountService').value = account.service;
this.editingAccountId = accountId;
this.openAccountModal();
});
});
document.querySelectorAll('.delete-app').forEach(btn => {
btn.addEventListener('click', (e) => {
const appId = btn.dataset.appId;
if (confirm('Delete this application?')) {
this.applications.splice(appId, 1);
this.saveToStorage('applications', this.applications);
location.href = './applications.html';
}
});
});
document.querySelectorAll('.edit-app').forEach(btn => {
btn.addEventListener('click', (e) => {
const appId = btn.dataset.appId;
const app = this.applications[appId];
document.getElementById('appName').value = app.name;
document.getElementById('appType').value = app.type;
document.getElementById('appStatus').value = app.status;
this.editingAppId = appId;
this.openAppModal();
});
});
}
handleAccountSubmit(e) {
e.preventDefault();
const newAccount = {
service: document.getElementById('accountService').value,
owner: document.getElementById('accountOwner').value,
username: document.getElementById('accountUsername').value,
password: document.getElementById('accountPassword').value,
dateCreated: new Date().toLocaleDateString()
};
if (this.editingAccountId !== undefined) {
this.accounts[this.editingAccountId] = newAccount;
this.editingAccountId = undefined;
} else {
this.accounts.push(newAccount);
}
this.saveToStorage('accounts', this.accounts);
this.closeModals();
location.href = './accounts.html';
}
handleAppSubmit(e) {
e.preventDefault();
const newApp = {
name: document.getElementById('appName').value,
type: document.getElementById('appType').value,
status: document.getElementById('appStatus').value,
icon: 'cloud'
};
if (this.editingAppId !== undefined) {
this.applications[this.editingAppId] = newApp;
this.editingAppId = undefined;
} else {
this.applications.push(newApp);
}
this.saveToStorage('applications', this.applications);
this.closeModals();
location.href = './applications.html';
}
openAccountModal() {
this.editingAccountId = undefined;
document.getElementById('accountService').value = '';
document.getElementById('accountOwner').value = '';
document.getElementById('accountUsername').value = '';
document.getElementById('accountPassword').value = '';
document.getElementById('accountModal').classList.remove('hidden');
}
openAppModal() {
this.editingAppId = undefined;
document.getElementById('appName').value = '';
document.getElementById('appType').value = '';
document.getElementById('appStatus').value = 'online';
document.getElementById('appModal').classList.remove('hidden');
}
closeModals() {
document.querySelectorAll('.modal-backdrop').forEach(modal => {
modal.classList.add('hidden');
});
}
loadFromStorage(key) {
const data = localStorage.getItem(key);
return data ? JSON.parse(data) : null;
}
saveToStorage(key, data) {
localStorage.setItem(key, JSON.stringify(data));
}
}
// Initialize app when DOM is ready
let app;
document.addEventListener('DOMContentLoaded', () => {
app = new AccountManager();
});

3470
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,21 +2,45 @@
"name": "accmanager-backend",
"version": "1.0.0",
"description": "Backend server for AccManager application",
"main": "server.js",
"main": "backend/server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
"start": "node 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",
"watch:css": "tailwindcss -c tailwind.config.js -i ./public/css/tailwind.css -o ./public/css/main.css --watch"
},
"keywords": ["accmanager", "backend", "express", "mssql"],
"keywords": [
"accmanager",
"backend",
"express",
"mssql"
],
"author": "",
"license": "MIT",
"engines": {
"node": ">=22.0.0"
},
"dependencies": {
"express": "^4.18.2",
"mssql": "^9.1.1",
"bcrypt": "^6.0.0",
"cors": "^2.8.5",
"dotenv": "^16.3.1"
"dotenv": "^16.3.1",
"express": "^5.2.1",
"express-rate-limit": "^8.6.0",
"helmet": "^8.3.0",
"mssql": "^12.7.0",
"multer": "^2.2.0",
"nodemailer": "^9.0.3",
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
},
"devDependencies": {
"nodemon": "^3.0.1"
"@tailwindcss/container-queries": "^0.1.1",
"@tailwindcss/forms": "^0.5.7",
"autoprefixer": "^10.4.19",
"nodemon": "^3.0.1",
"postcss": "^8.4.38",
"tailwindcss": "^3.4.13"
}
}

View File

@@ -1,152 +0,0 @@
<!DOCTYPE html>
<html class="light" lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>VaultSentinel - Accounts Management</title>
<!-- 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"/>
<!-- 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"/>
<script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
<script id="tailwind-config">
tailwind.config = {
darkMode: "class",
theme: {
extend: {
colors: {
"on-secondary-fixed-variant": "#4e5c71",
"on-secondary": "#f8f8ff",
"secondary-fixed-dim": "#c7d5ed",
"surface-variant": "#d9e4ea",
"surface-tint": "#3755c3",
"primary-container": "#dde1ff",
"primary-dim": "#2848b7",
"on-background": "#2a3439",
"surface-container-lowest": "#ffffff",
"tertiary-fixed-dim": "#d4cdee",
"on-tertiary-container": "#514d68",
"error-container": "#fe8983",
"on-secondary-container": "#455367",
"outline": "#717c82",
"on-primary": "#f8f7ff",
"on-primary-container": "#2747b6",
"inverse-primary": "#6d89fa",
"on-surface": "#2a3439",
"primary-fixed": "#dde1ff",
"on-primary-fixed": "#0732a3",
"secondary-dim": "#465468",
"surface-container-high": "#e1e9ee",
"surface-container-highest": "#d9e4ea",
"on-primary-fixed-variant": "#3352c0",
"on-error-container": "#752121",
"secondary": "#526074",
"tertiary-fixed": "#e3dbfd",
"primary": "#3755c3",
"surface-dim": "#cfdce3",
"tertiary": "#605c78",
"on-error": "#fff7f6",
"secondary-fixed": "#d5e3fc",
"error-dim": "#4e0309",
"surface-bright": "#f7f9fb",
"on-surface-variant": "#566166",
"on-tertiary": "#fcf7ff",
"tertiary-container": "#e3dbfd",
"inverse-on-surface": "#9a9d9f",
"on-tertiary-fixed-variant": "#5b5672",
"tertiary-dim": "#54506b",
"outline-variant": "#a9b4b9",
"on-secondary-fixed": "#324053",
"inverse-surface": "#0b0f10",
"on-tertiary-fixed": "#3e3a54",
"primary-fixed-dim": "#cad2ff",
"surface-container": "#e8eff3",
"secondary-container": "#d5e3fc",
"surface-container-low": "#f0f4f7",
"background": "#f7f9fb",
"error": "#9f403d",
"surface": "#f7f9fb"
},
fontFamily: {
"headline": ["Manrope"],
"body": ["Inter"],
"label": ["Inter"]
},
borderRadius: {"DEFAULT": "0.125rem", "lg": "0.25rem", "xl": "0.5rem", "full": "0.75rem"},
},
},
}
</script>
<style>
.material-symbols-outlined { font-family: 'Material Symbols Outlined'; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20; font-size: 1.25rem; line-height: 1; letter-spacing: normal; text-transform: none; display: inline-flex; white-space: nowrap; word-wrap: normal; direction: ltr; }
body { font-family: 'Inter', sans-serif; height: 100vh; overflow: hidden; }
h1, h2, h3, .brand-logo { font-family: 'Manrope', sans-serif; }
.modal-backdrop { opacity: 0; transition: opacity 0.2s ease-in-out; pointer-events: none; }
.modal-backdrop.open { opacity: 1; pointer-events: auto; }
.modal-content { transform: scale(0.95); transition: transform 0.2s ease-in-out; }
.modal-backdrop.open .modal-content { transform: scale(1); }
</style>
</head>
<body class="bg-background text-on-surface antialiased flex h-screen w-screen">
<aside class="h-screen w-56 flex flex-col bg-slate-100 dark:bg-slate-900 font-manrope text-sm font-medium border-r border-outline-variant/10 shrink-0">
<div class="flex flex-col h-full py-6">
<div class="px-6 mb-8">
<div class="text-lg font-black text-slate-900 dark:text-slate-50 tracking-tight leading-none">Robot Account</div>
<div class="text-[10px] uppercase tracking-widest text-on-surface-variant mt-1.5 font-bold">Admin Console</div>
</div>
<nav class="flex-1 px-3 space-y-1">
<a href="./index.html" 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">
<span class="material-symbols-outlined">dashboard</span>
<span>Dashboard</span>
</a>
<a href="./applications.html" 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">
<span class="material-symbols-outlined">apps</span>
<span>Applications</span>
</a>
<a href="./accounts.html" 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">
<span class="material-symbols-outlined">manage_accounts</span>
<span>Accounts</span>
</a>
</nav>
<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>
</div>
</aside>
<main class="flex-1 flex flex-col h-screen min-w-0">
<header class="h-14 flex items-center justify-between px-6 bg-slate-50/80 dark:bg-slate-950/80 backdrop-blur-xl border-b border-outline-variant/10 shrink-0">
<div class="flex items-center gap-4 flex-1">
<div class="flex items-center bg-surface-container-high px-3 py-1.5 rounded-full w-64 group focus-within:ring-2 ring-primary/20 transition-all">
<span class="material-symbols-outlined text-on-surface-variant text-base">search</span>
<input id="searchInput" class="bg-transparent border-none focus:ring-0 text-xs w-full placeholder:text-on-surface-variant/60 py-0" placeholder="Search resources..." type="text"/>
</div>
</div>
<div class="flex items-center gap-4">
<div class="flex items-center gap-2 px-4 py-2 rounded-lg bg-slate-100 dark:bg-slate-800">
<span class="material-symbols-outlined text-slate-600 dark:text-slate-400">account_circle</span>
<div class="flex flex-col">
<span id="accountUsername" class="text-xs font-semibold text-slate-900 dark:text-slate-50">User Account</span>
<span id="accountRole" class="text-[10px] text-slate-500 dark:text-slate-400">Administrator</span>
</div>
</div>
<button id="logoutBtn" class="p-2 rounded-lg text-slate-600 dark:text-slate-300 hover:bg-red-100 dark:hover:bg-red-950 hover:text-red-700 dark:hover:text-red-300 transition-colors" title="Logout">
<span class="material-symbols-outlined">logout</span>
</button>
</div>
</header>
<div id="mainContent" class="flex-1 overflow-hidden"></div>
</main>
<script src="../js/app.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
if (app) {
const mainContent = document.getElementById('mainContent');
if (mainContent) {
mainContent.innerHTML = app.getAccountsContent();
app.setupAccountRowListeners();
}
}
});
</script>
</body>
</html>

View File

@@ -1,152 +0,0 @@
<!DOCTYPE html>
<html class="light" lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>VaultSentinel - Applications Management</title>
<!-- 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"/>
<!-- 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"/>
<script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
<script id="tailwind-config">
tailwind.config = {
darkMode: "class",
theme: {
extend: {
colors: {
"on-secondary-fixed-variant": "#4e5c71",
"on-secondary": "#f8f8ff",
"secondary-fixed-dim": "#c7d5ed",
"surface-variant": "#d9e4ea",
"surface-tint": "#3755c3",
"primary-container": "#dde1ff",
"primary-dim": "#2848b7",
"on-background": "#2a3439",
"surface-container-lowest": "#ffffff",
"tertiary-fixed-dim": "#d4cdee",
"on-tertiary-container": "#514d68",
"error-container": "#fe8983",
"on-secondary-container": "#455367",
"outline": "#717c82",
"on-primary": "#f8f7ff",
"on-primary-container": "#2747b6",
"inverse-primary": "#6d89fa",
"on-surface": "#2a3439",
"primary-fixed": "#dde1ff",
"on-primary-fixed": "#0732a3",
"secondary-dim": "#465468",
"surface-container-high": "#e1e9ee",
"surface-container-highest": "#d9e4ea",
"on-primary-fixed-variant": "#3352c0",
"on-error-container": "#752121",
"secondary": "#526074",
"tertiary-fixed": "#e3dbfd",
"primary": "#3755c3",
"surface-dim": "#cfdce3",
"tertiary": "#605c78",
"on-error": "#fff7f6",
"secondary-fixed": "#d5e3fc",
"error-dim": "#4e0309",
"surface-bright": "#f7f9fb",
"on-surface-variant": "#566166",
"on-tertiary": "#fcf7ff",
"tertiary-container": "#e3dbfd",
"inverse-on-surface": "#9a9d9f",
"on-tertiary-fixed-variant": "#5b5672",
"tertiary-dim": "#54506b",
"outline-variant": "#a9b4b9",
"on-secondary-fixed": "#324053",
"inverse-surface": "#0b0f10",
"on-tertiary-fixed": "#3e3a54",
"primary-fixed-dim": "#cad2ff",
"surface-container": "#e8eff3",
"secondary-container": "#d5e3fc",
"surface-container-low": "#f0f4f7",
"background": "#f7f9fb",
"error": "#9f403d",
"surface": "#f7f9fb"
},
fontFamily: {
"headline": ["Manrope"],
"body": ["Inter"],
"label": ["Inter"]
},
borderRadius: {"DEFAULT": "0.125rem", "lg": "0.25rem", "xl": "0.5rem", "full": "0.75rem"},
},
},
}
</script>
<style>
.material-symbols-outlined { font-family: 'Material Symbols Outlined'; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20; font-size: 1.25rem; line-height: 1; letter-spacing: normal; text-transform: none; display: inline-flex; white-space: nowrap; word-wrap: normal; direction: ltr; }
body { font-family: 'Inter', sans-serif; height: 100vh; overflow: hidden; }
h1, h2, h3, .brand-logo { font-family: 'Manrope', sans-serif; }
.modal-backdrop { opacity: 0; transition: opacity 0.2s ease-in-out; pointer-events: none; }
.modal-backdrop.open { opacity: 1; pointer-events: auto; }
.modal-content { transform: scale(0.95); transition: transform 0.2s ease-in-out; }
.modal-backdrop.open .modal-content { transform: scale(1); }
</style>
</head>
<body class="bg-background text-on-surface antialiased flex h-screen w-screen">
<aside class="h-screen w-56 flex flex-col bg-slate-100 dark:bg-slate-900 font-manrope text-sm font-medium border-r border-outline-variant/10 shrink-0">
<div class="flex flex-col h-full py-6">
<div class="px-6 mb-8">
<div class="text-lg font-black text-slate-900 dark:text-slate-50 tracking-tight leading-none">Robot Account</div>
<div class="text-[10px] uppercase tracking-widest text-on-surface-variant mt-1.5 font-bold">Admin Console</div>
</div>
<nav class="flex-1 px-3 space-y-1">
<a href="./index.html" 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">
<span class="material-symbols-outlined">dashboard</span>
<span>Dashboard</span>
</a>
<a href="./applications.html" 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">
<span class="material-symbols-outlined">apps</span>
<span>Applications</span>
</a>
<a href="./accounts.html" 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">
<span class="material-symbols-outlined">manage_accounts</span>
<span>Accounts</span>
</a>
</nav>
<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>
</div>
</aside>
<main class="flex-1 flex flex-col h-screen min-w-0">
<header class="h-14 flex items-center justify-between px-6 bg-slate-50/80 dark:bg-slate-950/80 backdrop-blur-xl border-b border-outline-variant/10 shrink-0">
<div class="flex items-center gap-4 flex-1">
<div class="flex items-center bg-surface-container-high px-3 py-1.5 rounded-full w-64 group focus-within:ring-2 ring-primary/20 transition-all">
<span class="material-symbols-outlined text-on-surface-variant text-base">search</span>
<input id="searchInput" class="bg-transparent border-none focus:ring-0 text-xs w-full placeholder:text-on-surface-variant/60 py-0" placeholder="Search resources..." type="text"/>
</div>
</div>
<div class="flex items-center gap-4">
<div class="flex items-center gap-2 px-4 py-2 rounded-lg bg-slate-100 dark:bg-slate-800">
<span class="material-symbols-outlined text-slate-600 dark:text-slate-400">account_circle</span>
<div class="flex flex-col">
<span id="accountUsername" class="text-xs font-semibold text-slate-900 dark:text-slate-50">User Account</span>
<span id="accountRole" class="text-[10px] text-slate-500 dark:text-slate-400">Administrator</span>
</div>
</div>
<button id="logoutBtn" class="p-2 rounded-lg text-slate-600 dark:text-slate-300 hover:bg-red-100 dark:hover:bg-red-950 hover:text-red-700 dark:hover:text-red-300 transition-colors" title="Logout">
<span class="material-symbols-outlined">logout</span>
</button>
</div>
</header>
<div id="mainContent" class="flex-1 overflow-hidden"></div>
</main>
<script src="../js/app.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
if (app) {
const mainContent = document.getElementById('mainContent');
if (mainContent) {
mainContent.innerHTML = app.getApplicationsContent();
app.setupAccountRowListeners();
}
}
});
</script>
</body>
</html>

View File

@@ -1,176 +0,0 @@
<!DOCTYPE html>
<html class="light" lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>Robot Manager Account - Account Management System</title>
<!-- 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"/>
<!-- 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"/>
<script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
<script id="tailwind-config">
tailwind.config = {
darkMode: "class",
theme: {
extend: {
colors: {
"on-secondary-fixed-variant": "#4e5c71",
"on-secondary": "#f8f8ff",
"secondary-fixed-dim": "#c7d5ed",
"surface-variant": "#d9e4ea",
"surface-tint": "#3755c3",
"primary-container": "#dde1ff",
"primary-dim": "#2848b7",
"on-background": "#2a3439",
"surface-container-lowest": "#ffffff",
"tertiary-fixed-dim": "#d4cdee",
"on-tertiary-container": "#514d68",
"error-container": "#fe8983",
"on-secondary-container": "#455367",
"outline": "#717c82",
"on-primary": "#f8f7ff",
"on-primary-container": "#2747b6",
"inverse-primary": "#6d89fa",
"on-surface": "#2a3439",
"primary-fixed": "#dde1ff",
"on-primary-fixed": "#0732a3",
"secondary-dim": "#465468",
"surface-container-high": "#e1e9ee",
"surface-container-highest": "#d9e4ea",
"on-primary-fixed-variant": "#3352c0",
"on-error-container": "#752121",
"secondary": "#526074",
"tertiary-fixed": "#e3dbfd",
"primary": "#3755c3",
"surface-dim": "#cfdce3",
"tertiary": "#605c78",
"on-error": "#fff7f6",
"secondary-fixed": "#d5e3fc",
"error-dim": "#4e0309",
"surface-bright": "#f7f9fb",
"on-surface-variant": "#566166",
"on-tertiary": "#fcf7ff",
"tertiary-container": "#e3dbfd",
"inverse-on-surface": "#9a9d9f",
"on-tertiary-fixed-variant": "#5b5672",
"tertiary-dim": "#54506b",
"outline-variant": "#a9b4b9",
"on-secondary-fixed": "#324053",
"inverse-surface": "#0b0f10",
"on-tertiary-fixed": "#3e3a54",
"primary-fixed-dim": "#cad2ff",
"surface-container": "#e8eff3",
"secondary-container": "#d5e3fc",
"surface-container-low": "#f0f4f7",
"background": "#f7f9fb",
"error": "#9f403d",
"surface": "#f7f9fb"
},
fontFamily: {
"headline": ["Manrope"],
"body": ["Inter"],
"label": ["Inter"]
},
borderRadius: {"DEFAULT": "0.125rem", "lg": "0.25rem", "xl": "0.5rem", "full": "0.75rem"},
},
},
}
</script>
<style>
.material-symbols-outlined {
font-family: 'Material Symbols Outlined';
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
font-size: 1.25rem;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-flex;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
}
body { font-family: 'Inter', sans-serif; height: 100vh; overflow: hidden; }
h1, h2, h3, .brand-logo { font-family: 'Manrope', sans-serif; }
.modal-backdrop {
opacity: 0;
transition: opacity 0.2s ease-in-out;
pointer-events: none;
}
.modal-backdrop.open {
opacity: 1;
pointer-events: auto;
}
.modal-content {
transform: scale(0.95);
transition: transform 0.2s ease-in-out;
}
.modal-backdrop.open .modal-content {
transform: scale(1);
}
</style>
</head>
<body class="bg-background text-on-surface antialiased flex h-screen w-screen">
<!-- SideNavBar -->
<aside class="h-screen w-56 flex flex-col bg-slate-100 dark:bg-slate-900 font-manrope text-sm font-medium border-r border-outline-variant/10 shrink-0">
<div class="flex flex-col h-full py-6">
<!-- Header -->
<div class="px-6 mb-8">
<div class="text-lg font-black text-slate-900 dark:text-slate-50 tracking-tight leading-none">Robot Account</div>
<div class="text-[10px] uppercase tracking-widest text-on-surface-variant mt-1.5 font-bold">Admin Console</div>
</div>
<!-- Primary Nav -->
<nav class="flex-1 px-3 space-y-1">
<a href="#" onclick="location.reload(); return false;" 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">
<span class="material-symbols-outlined">dashboard</span>
<span>Dashboard</span>
</a>
<a href="./applications.html" 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">
<span class="material-symbols-outlined">apps</span>
<span>Applications</span>
</a>
<a href="./accounts.html" 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">
<span class="material-symbols-outlined">manage_accounts</span>
<span>Accounts</span>
</a>
</nav>
<!-- Footer -->
<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>
</div>
</aside>
<!-- Main Content -->
<main class="flex-1 flex flex-col h-screen min-w-0">
<!-- TopAppBar -->
<header class="h-14 flex items-center justify-between px-6 bg-slate-50/80 dark:bg-slate-950/80 backdrop-blur-xl border-b border-outline-variant/10 shrink-0">
<div class="flex items-center gap-4 flex-1">
<div class="flex items-center bg-surface-container-high px-3 py-1.5 rounded-full w-64 group focus-within:ring-2 ring-primary/20 transition-all">
<span class="material-symbols-outlined text-on-surface-variant text-base">search</span>
<input id="searchInput" class="bg-transparent border-none focus:ring-0 text-xs w-full placeholder:text-on-surface-variant/60 py-0" placeholder="Search resources..." type="text"/>
</div>
</div>
<div class="flex items-center gap-4">
<div class="flex items-center gap-2 px-4 py-2 rounded-lg bg-slate-100 dark:bg-slate-800">
<span class="material-symbols-outlined text-slate-600 dark:text-slate-400">account_circle</span>
<div class="flex flex-col">
<span id="accountUsername" class="text-xs font-semibold text-slate-900 dark:text-slate-50">User Account</span>
<span id="accountRole" class="text-[10px] text-slate-500 dark:text-slate-400">Administrator</span>
</div>
</div>
<button id="logoutBtn" class="p-2 rounded-lg text-slate-600 dark:text-slate-300 hover:bg-red-100 dark:hover:bg-red-950 hover:text-red-700 dark:hover:text-red-300 transition-colors" title="Logout">
<span class="material-symbols-outlined">logout</span>
</button>
</div>
</header>
<!-- Main Content Area -->
<div id="mainContent" class="flex-1 overflow-hidden">
<!-- Content will be rendered here by JavaScript -->
</div>
</main>
<script src="../js/app.js"></script>
</body>
</html>

View File

@@ -1,254 +0,0 @@
<!DOCTYPE html>
<html class="light" lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>VaultSentinel - Login</title>
<!-- 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"/>
<!-- 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"/>
<script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
<script id="tailwind-config">
tailwind.config = {
darkMode: "class",
theme: {
extend: {
colors: {
"on-secondary-fixed-variant": "#4e5c71",
"on-secondary": "#f8f8ff",
"secondary-fixed-dim": "#c7d5ed",
"surface-variant": "#d9e4ea",
"surface-tint": "#3755c3",
"primary-container": "#dde1ff",
"primary-dim": "#2848b7",
"on-background": "#2a3439",
"surface-container-lowest": "#ffffff",
"tertiary-fixed-dim": "#d4cdee",
"on-tertiary-container": "#514d68",
"error-container": "#fe8983",
"on-secondary-container": "#455367",
"outline": "#717c82",
"on-primary": "#f8f7ff",
"on-primary-container": "#2747b6",
"inverse-primary": "#6d89fa",
"on-surface": "#2a3439",
"primary-fixed": "#dde1ff",
"on-primary-fixed": "#0732a3",
"secondary-dim": "#465468",
"surface-container-high": "#e1e9ee",
"surface-container-highest": "#d9e4ea",
"on-primary-fixed-variant": "#3352c0",
"on-error-container": "#752121",
"secondary": "#526074",
"tertiary-fixed": "#e3dbfd",
"primary": "#3755c3",
"surface-dim": "#cfdce3",
"tertiary": "#605c78",
"on-error": "#fff7f6",
"secondary-fixed": "#d5e3fc",
"error-dim": "#4e0309",
"surface-bright": "#f7f9fb",
"on-surface-variant": "#566166",
"on-tertiary": "#fcf7ff",
"tertiary-container": "#e3dbfd",
"inverse-on-surface": "#9a9d9f",
"on-tertiary-fixed-variant": "#5b5672",
"tertiary-dim": "#54506b",
"outline-variant": "#a9b4b9",
"on-secondary-fixed": "#324053",
"inverse-surface": "#0b0f10",
"on-tertiary-fixed": "#3e3a54",
"primary-fixed-dim": "#cad2ff",
"surface-container": "#e8eff3",
"secondary-container": "#d5e3fc",
"surface-container-low": "#f0f4f7",
"background": "#f7f9fb",
"error": "#9f403d",
"surface": "#f7f9fb"
},
fontFamily: {
"headline": ["Manrope"],
"body": ["Inter"],
"label": ["Inter"]
},
borderRadius: {"DEFAULT": "0.125rem", "lg": "0.25rem", "xl": "0.5rem", "full": "0.75rem"},
},
},
}
</script>
<style>
.material-symbols-outlined {
font-family: 'Material Symbols Outlined';
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
font-size: 1.25rem;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-flex;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
}
body { font-family: 'Inter', sans-serif; min-height: 100vh; }
h1, h2, h3 { font-family: 'Manrope', sans-serif; }
</style>
</head>
<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="min-h-screen flex items-center justify-center px-4">
<div class="w-full max-w-md">
<!-- Login Card -->
<div class="bg-white dark:bg-slate-900 rounded-2xl shadow-lg border border-outline-variant/10 p-8">
<!-- Header -->
<div class="text-center mb-8">
<div class="flex justify-center mb-4">
<div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center">
<span class="material-symbols-outlined text-primary text-4xl">security</span>
</div>
</div>
<h1 class="text-2xl font-black text-slate-900 dark:text-slate-50 tracking-tight">VaultSentinel</h1>
<p class="text-xs uppercase tracking-widest text-on-surface-variant font-bold mt-2">Account Management System</p>
</div>
<!-- Login Form -->
<form id="loginForm" class="space-y-5">
<!-- Username/Email Input -->
<div>
<label for="username" class="block text-xs font-bold text-on-surface-variant uppercase tracking-wider mb-2">Username or 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">person</span>
</span>
<input
type="text"
id="username"
name="username"
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>
<!-- Password Input -->
<div>
<label for="password" class="block text-xs font-bold text-on-surface-variant uppercase tracking-wider mb-2">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</span>
</span>
<input
type="password"
id="password"
name="password"
placeholder="Enter your password"
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>
<!-- Remember Me Checkbox -->
<div class="flex items-center">
<input
type="checkbox"
id="remember"
name="remember"
class="w-4 h-4 rounded border-outline-variant/30 text-primary focus:ring-2 focus:ring-primary/50 cursor-pointer"
/>
<label for="remember" class="ml-2.5 text-xs font-medium text-on-surface-variant cursor-pointer">Remember me</label>
</div>
<!-- Login Button -->
<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-6"
>
<span class="material-symbols-outlined text-sm">login</span>
<span>Sign In</span>
</button>
<!-- Error Message -->
<div id="errorMessage" 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>
<!-- Footer -->
<div class="mt-8 pt-6 border-t border-outline-variant/10 text-center">
<p class="text-[10px] text-on-surface-variant/60">Default credentials for demo: admin / admin</p>
</div>
</div>
<!-- Bottom info -->
<div class="text-center mt-6">
<p class="text-xs text-on-surface-variant/60">v1.0.0</p>
</div>
</div>
</div>
<script>
// Simple login functionality
const loginForm = document.getElementById('loginForm');
const errorMessage = document.getElementById('errorMessage');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const rememberCheckbox = document.getElementById('remember');
// Demo credentials
const validCredentials = {
username: 'admin',
password: 'admin'
};
// Check if already logged in
document.addEventListener('DOMContentLoaded', () => {
const currentUser = localStorage.getItem('currentUser');
if (currentUser) {
window.location.href = './index.html';
}
// Restore remembered username
const rememberedUsername = localStorage.getItem('rememberedUsername');
if (rememberedUsername) {
usernameInput.value = rememberedUsername;
rememberCheckbox.checked = true;
}
});
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
errorMessage.classList.add('hidden');
const username = usernameInput.value.trim();
const password = passwordInput.value;
// Validate credentials
if (username === validCredentials.username && password === validCredentials.password) {
// Store user info
const userData = {
username: username,
role: 'Administrator',
loginTime: new Date().toISOString()
};
localStorage.setItem('currentUser', JSON.stringify(userData));
// Handle remember me
if (rememberCheckbox.checked) {
localStorage.setItem('rememberedUsername', username);
} else {
localStorage.removeItem('rememberedUsername');
}
// Redirect to dashboard
window.location.href = './index.html';
} else {
// Show error
errorMessage.textContent = 'Invalid username or password. Try admin / admin';
errorMessage.classList.remove('hidden');
passwordInput.value = '';
passwordInput.focus();
}
});
</script>
</body>
</html>

6
postcss.config.js Normal file
View File

@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {}
}
};

View File

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

View File

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

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

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

1
public/css/main.css Normal file

File diff suppressed because one or more lines are too long

818
public/css/responsive.css Normal file
View File

@@ -0,0 +1,818 @@
/* 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;
}
}

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

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

3
public/css/tailwind.css Normal file
View File

@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

BIN
public/image/logo_PNKX.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

View File

@@ -1,7 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Redirecting...</title>
<link rel="icon" type="image/png" href="./image/logo_PNKX.png">
<script>
window.location.href = './pages/login.html';
</script>

13626
public/js/app.js Normal file

File diff suppressed because it is too large Load Diff

View File

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

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

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

1232
public/modals.html Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,31 @@
<!DOCTYPE html>
<html class="light" lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>Robot Manager Account - Accounts Management</title>
<link rel="icon" type="image/png" href="../image/logo_PNKX.png"/>
<!-- 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"/>
<!-- Material Symbols -->
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="../css/main.css" />
<!-- Notiflix Notify -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-3.2.7.min.css" />
<script src="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js"></script>
<style>
.material-symbols-outlined { font-family: 'Material Symbols Outlined'; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20; font-size: 1.25rem; line-height: 1; letter-spacing: normal; text-transform: none; display: inline-flex; white-space: nowrap; word-wrap: normal; direction: ltr; }
body { font-family: 'Inter', sans-serif; height: 100vh; overflow: hidden; }
h1, h2, h3, .brand-logo { font-family: 'Manrope', sans-serif; }
.modal-backdrop { opacity: 0; transition: opacity 0.2s ease-in-out; pointer-events: none; }
.modal-backdrop.open { opacity: 1; pointer-events: auto; }
.modal-content { transform: scale(0.95); transition: transform 0.2s ease-in-out; }
.modal-backdrop.open .modal-content { transform: scale(1); }
</style>
</head>
<body>
<script>
window.location.href = './index.html#accounts';
</script>
</body>
</html>

View File

@@ -0,0 +1,31 @@
<!DOCTYPE html>
<html class="light" lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>Robot Manager Account - Applications Management</title>
<link rel="icon" type="image/png" href="../image/logo_PNKX.png"/>
<!-- 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"/>
<!-- Material Symbols -->
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="../css/main.css" />
<!-- Notiflix Notify -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-3.2.7.min.css" />
<script src="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js"></script>
<style>
.material-symbols-outlined { font-family: 'Material Symbols Outlined'; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20; font-size: 1.25rem; line-height: 1; letter-spacing: normal; text-transform: none; display: inline-flex; white-space: nowrap; word-wrap: normal; direction: ltr; }
body { font-family: 'Inter', sans-serif; height: 100vh; overflow: hidden; }
h1, h2, h3, .brand-logo { font-family: 'Manrope', sans-serif; }
.modal-backdrop { opacity: 0; transition: opacity 0.2s ease-in-out; pointer-events: none; }
.modal-backdrop.open { opacity: 1; pointer-events: auto; }
.modal-content { transform: scale(0.95); transition: transform 0.2s ease-in-out; }
.modal-backdrop.open .modal-content { transform: scale(1); }
</style>
</head>
<body>
<script>
window.location.href = './index.html#applications';
</script>
</body>
</html>

455
public/pages/index.html Normal file
View File

@@ -0,0 +1,455 @@
<!DOCTYPE html>
<html class="light" lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>Robot Manager Account - Hệ thống quản lý</title>
<link rel="icon" type="image/png" href="../image/logo_PNKX.png"/>
<!-- 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"/>
<!-- Material Symbols -->
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="../css/main.css?v=20261019-4" />
<link rel="stylesheet" href="../css/robot-bom.css?v=20261102-5" />
<!-- Notiflix Notify -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-3.2.7.min.css" />
<script src="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js"></script>
<script src="https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js"></script>
<style>
.material-symbols-outlined {
font-family: 'Material Symbols Outlined';
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
font-size: 1.25rem;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-flex;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
}
body { font-family: 'Inter', sans-serif; height: 100vh; overflow: hidden; }
h1, h2, h3, .brand-logo { font-family: 'Manrope', sans-serif; }
.modal-backdrop {
opacity: 0;
transition: opacity 0.2s ease-in-out;
pointer-events: none;
}
.modal-backdrop.open {
opacity: 1;
pointer-events: auto;
}
.modal-content {
transform: scale(0.95);
transition: transform 0.2s ease-in-out;
}
.modal-backdrop.open .modal-content {
transform: scale(1);
}
body.app-shell {
overflow: hidden;
}
#mobileMenuBtn,
#sidebarBackdrop {
display: none;
}
.assets-mobile-list,
.consumables-mobile-list {
display: none;
}
@media (max-width: 900px) {
body.app-shell {
width: 100%;
min-height: 100dvh;
height: 100dvh;
overflow: hidden;
position: relative;
}
#mobileMenuBtn {
display: inline-flex;
align-items: center;
justify-content: center;
}
#sidebarBackdrop {
display: block;
position: fixed;
inset: 0;
z-index: 70;
background: rgba(15, 23, 42, 0.45);
opacity: 0;
pointer-events: none;
transition: opacity 0.2s ease-in-out;
}
#appSidebar {
position: fixed;
inset: 0 auto 0 0;
height: 100dvh;
width: min(82vw, 16rem);
z-index: 80;
transform: translateX(-100%);
transition: transform 0.2s ease-in-out;
box-shadow: 0 20px 45px rgba(15, 23, 42, 0.35);
}
body.mobile-nav-open #sidebarBackdrop {
opacity: 1;
pointer-events: auto;
}
body.mobile-nav-open #appSidebar {
transform: translateX(0);
}
#appMain {
width: 100%;
min-width: 0;
height: 100dvh;
}
#appMain > header {
padding-left: 0.75rem;
padding-right: 0.75rem;
gap: 0.5rem;
}
.topbar-actions {
gap: 0.5rem;
}
#profileBtn {
padding: 0.4rem 0.55rem;
}
#profileBtn .profile-meta {
display: none;
}
.dashboard-header,
.page-header,
.page-filters,
.users-controls {
flex-direction: column;
align-items: stretch;
gap: 0.75rem;
}
.page-filters > div,
.users-controls > div,
.users-controls select {
width: 100%;
}
.dashboard-actions,
.page-header button,
.page-header > button {
width: 100%;
}
.dashboard-stats,
.apps-stats {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.table-wrap {
overflow-x: auto;
}
.table-wrap table {
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 {
gap: 0.5rem;
flex-direction: column;
align-items: flex-start;
}
.modal-backdrop {
align-items: flex-end;
}
.modal-backdrop .modal-content {
width: calc(100% - 1rem);
max-height: min(88dvh, 700px);
margin: 0.5rem;
overflow-y: auto;
border-radius: 0.9rem;
}
}
@media (max-width: 560px) {
.dashboard-stats,
.apps-stats {
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>
<link rel="stylesheet" href="../css/responsive.css?v=20261019-3" />
<link rel="stylesheet" href="../css/asset-actions.css?v=20261111-1" />
<link rel="stylesheet" href="../css/dashboard.css?v=20261103-1" />
<link rel="stylesheet" href="../css/announcements.css?v=20261103-2" />
</head>
<body class="app-shell bg-background text-on-surface antialiased flex h-screen w-screen">
<!-- SideNavBar -->
<aside id="appSidebar" class="h-screen w-64 flex flex-col bg-slate-100 dark:bg-slate-900 font-manrope text-sm font-medium border-r border-outline-variant/10 shrink-0">
<div class="flex flex-col h-full min-h-0 py-4">
<!-- Header -->
<div class="px-5 mb-4 shrink-0">
<a href="#dashboard" class="sidebar-brand-link" aria-label="PNKX - Về trang tổng quan">
<img src="../image/logo_PNKX.png" alt="PNKX" class="sidebar-brand-image"/>
</a>
</div>
<!-- Primary Nav -->
<nav id="sidebarNav" class="sidebar-nav flex-1 min-h-0 overflow-y-auto" aria-label="Điều hướng chính">
<ul class="sidebar-menu">
<li>
<a href="#dashboard" data-nav="dashboard" class="sidebar-link" aria-current="page">
<span class="material-symbols-outlined" aria-hidden="true">dashboard</span>
<span class="sidebar-text">Tổng quan</span>
</a>
</li>
<li data-nav-group="accounts">
<button id="sidebarAccountsToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="accounts" aria-expanded="false" aria-controls="sidebarAccounts">
<span class="material-symbols-outlined" aria-hidden="true">manage_accounts</span>
<span class="sidebar-text">Tài khoản</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarAccounts" class="sidebar-children" aria-labelledby="sidebarAccountsToggle" hidden>
<li><a href="#applications" data-nav="applications" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">apps</span>
<span class="sidebar-text">Ứng dụng</span>
</a></li>
<li><a href="#accounts" data-nav="accounts" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">manage_accounts</span>
<span class="sidebar-text">Tài khoản</span>
</a></li>
</ul>
</li>
<li data-nav-group="assets">
<button id="sidebarAssetsToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="assets" aria-expanded="false" aria-controls="sidebarAssets">
<span class="material-symbols-outlined" aria-hidden="true">inventory_2</span>
<span class="sidebar-text">Quản lý tài sản</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarAssets" class="sidebar-children" aria-labelledby="sidebarAssetsToggle" hidden>
<li><a href="#assets" data-nav="assets" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">inventory_2</span>
<span class="sidebar-text">Tài sản</span>
</a></li>
<li><a href="#asset-borrows" data-nav="asset-borrows" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">assignment_returned</span>
<span class="sidebar-text">Mượn/Trả tài sản</span>
</a></li>
<li><a href="#asset-exports" data-nav="asset-exports" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">outbox</span>
<span class="sidebar-text">Xuất vào dự án</span>
</a></li>
<li><a href="#my-borrowed-assets" data-nav="my-borrowed-assets" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">inventory</span>
<span class="sidebar-text">Tài sản đang mượn</span>
</a></li>
<li><a href="#asset-departments" data-nav="asset-departments" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">apartment</span>
<span class="sidebar-text">Phòng ban</span>
</a></li>
<li><a href="#asset-projects" data-nav="asset-projects" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">workspaces</span>
<span class="sidebar-text">Dự án</span>
</a></li>
</ul>
</li>
<li data-nav-group="consumables">
<button id="sidebarConsumablesToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="consumables" aria-expanded="false" aria-controls="sidebarConsumables">
<span class="material-symbols-outlined" aria-hidden="true">category</span>
<span class="sidebar-text">Vật tư tiêu hao</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarConsumables" class="sidebar-children" aria-labelledby="sidebarConsumablesToggle" hidden>
<li><a href="#consumables" data-nav="consumables" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">category</span>
<span class="sidebar-text">Danh sách VTTH</span>
</a></li>
<li><a href="#consumable-exports" data-nav="consumable-exports" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">outbox</span>
<span class="sidebar-text">Lịch sử xuất</span>
</a></li>
</ul>
</li>
<li data-nav-group="robots">
<button id="sidebarRobotsToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="robots" aria-expanded="false" aria-controls="sidebarRobots">
<span class="material-symbols-outlined" aria-hidden="true">smart_toy</span>
<span class="sidebar-text">Quản lý robot</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarRobots" class="sidebar-children" aria-labelledby="sidebarRobotsToggle" hidden>
<li><a href="#robots" data-nav="robots" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">smart_toy</span>
<span class="sidebar-text">Danh sách robot</span>
</a></li>
<li><a href="#robot-types" data-nav="robot-types" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">category</span>
<span class="sidebar-text">Thể loại robot</span>
</a></li>
<li><a href="#robot-bom" data-nav="robot-bom" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">receipt_long</span>
<span class="sidebar-text">BOM robot</span>
</a></li>
</ul>
</li>
<li><a href="#documents" data-nav="documents" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">folder_open</span>
<span class="sidebar-text">Tài liệu</span>
</a></li>
<li id="usersSection" class="sidebar-admin" data-nav-group="administration" style="display: none;">
<button id="sidebarAdministrationToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="administration" aria-expanded="false" aria-controls="sidebarAdministration">
<span class="material-symbols-outlined" aria-hidden="true">admin_panel_settings</span>
<span class="sidebar-text">Quản trị viên</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarAdministration" class="sidebar-children" aria-labelledby="sidebarAdministrationToggle" hidden>
<li><a id="usersNav" href="#users" data-nav="users" class="sidebar-link" style="display: none;">
<span class="material-symbols-outlined" aria-hidden="true">people</span>
<span class="sidebar-text">Quản lý người dùng</span>
</a></li>
<li><a href="#notification-management" data-nav="notification-management" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>
<span class="sidebar-text">Đăng thông báo</span>
</a></li>
</ul>
</li>
</ul>
</nav>
<!-- Footer -->
<div class="px-5 pt-3 mt-3 border-t border-outline-variant/10 shrink-0">
<div class="text-[10px] font-bold text-on-surface-variant/40 uppercase tracking-widest">v1.0.0</div>
</div>
</div>
</aside>
<button id="sidebarBackdrop" type="button" aria-label="Đóng menu điều hướng"></button>
<!-- Main Content -->
<main id="appMain" class="flex-1 flex flex-col h-screen min-w-0">
<!-- TopAppBar -->
<header class="h-14 flex items-center justify-between px-6 bg-slate-50/80 dark:bg-slate-950/80 backdrop-blur-xl border-b border-outline-variant/10 shrink-0">
<div class="flex items-center gap-4 flex-1">
<button id="mobileMenuBtn" type="button" class="p-2 rounded-lg text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors" aria-label="Mở menu điều hướng" aria-controls="appSidebar" aria-expanded="false">
<span class="material-symbols-outlined">menu</span>
</button>
</div>
<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ơ">
<span class="material-symbols-outlined text-slate-600 dark:text-slate-400">account_circle</span>
<div class="profile-meta flex flex-col">
<span id="accountUsername" class="text-xs font-semibold text-slate-900 dark:text-slate-50">Tài khoản người dùng</span>
<span id="accountRole" class="text-[10px] text-slate-500 dark:text-slate-400">Quản trị viên</span>
</div>
</button>
<button id="logoutBtn" class="p-2 rounded-lg text-slate-600 dark:text-slate-300 hover:bg-red-100 dark:hover:bg-red-950 hover:text-red-700 dark:hover:text-red-300 transition-colors" title="Đăng xuất">
<span class="material-symbols-outlined">logout</span>
</button>
</div>
</header>
<!-- Main Content Area -->
<div id="mainContent" class="flex-1 overflow-hidden">
<!-- Content will be rendered here by JavaScript -->
</div>
</main>
<script src="../js/document-formats.js?v=20261019-1"></script>
<script src="../js/robot-bom.js?v=20261102-5"></script>
<script src="../js/app.js?v=20261111-1"></script>
</body>
</html>

740
public/pages/login.html Normal file
View File

@@ -0,0 +1,740 @@
<!DOCTYPE html>
<html class="light" lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>Robotics Account - Login</title>
<link rel="icon" type="image/png" href="../image/logo_PNKX.png"/>
<!-- 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"/>
<!-- Material Symbols -->
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="../css/main.css" />
<style>
.material-symbols-outlined {
font-family: 'Material Symbols Outlined';
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
font-size: 1.25rem;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-flex;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
}
body { font-family: 'Inter', sans-serif; min-height: 100vh; }
h1, h2, h3 { font-family: 'Manrope', sans-serif; }
</style>
<link rel="stylesheet" href="../css/responsive.css?v=20260717-1" />
</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">
<div class="auth-shell min-h-screen flex items-center justify-center px-4">
<div class="w-full max-w-md">
<!-- Login Card -->
<div class="auth-card bg-white dark:bg-slate-900 rounded-2xl shadow-lg border border-outline-variant/10 p-8">
<!-- Header -->
<div class="auth-heading text-center mb-8">
<div class="flex justify-center mb-4">
<img src="../image/logo_PNKX.png" alt="PNKX" class="auth-brand-image"/>
</div>
<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>
</div>
<div id="authTabs" 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="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>
<!-- Login Form -->
<form id="loginForm" class="space-y-5">
<!-- Username/Email Input -->
<div>
<label for="username" class="block text-xs font-bold text-on-surface-variant uppercase tracking-wider mb-2">Username or 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">person</span>
</span>
<input
type="text"
id="username"
name="username"
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>
<!-- Password Input -->
<div>
<label for="password" class="block text-xs font-bold text-on-surface-variant uppercase tracking-wider mb-2">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</span>
</span>
<input
type="password"
id="password"
name="password"
placeholder="Enter your password"
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>
<!-- Remember Me Checkbox -->
<div class="remember-row flex items-center justify-between gap-2">
<div class="flex items-center">
<input
type="checkbox"
id="remember"
name="remember"
class="w-4 h-4 rounded border-outline-variant/30 text-primary focus:ring-2 focus:ring-primary/50 cursor-pointer"
/>
<label for="remember" class="ml-2.5 text-xs font-medium text-on-surface-variant cursor-pointer">Remember me</label>
</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 -->
<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-6"
>
<span class="material-symbols-outlined text-sm">login</span>
<span>Sign In</span>
</button>
<!-- Error Message -->
<div id="errorMessage" 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="verifyNotice" class="hidden bg-amber-50 text-amber-800 border border-amber-200 rounded-lg px-4 py-3 text-xs font-medium space-y-2">
<p id="verifyNoticeText">Please confirm your email before signing in.</p>
<button id="resendVerifyBtn" type="button" class="inline-flex items-center gap-1 px-3 py-1.5 rounded-md bg-amber-100 hover:bg-amber-200 text-amber-900 font-semibold transition-colors">
<span class="material-symbols-outlined text-sm">forward_to_inbox</span>
<span>Resend confirmation email</span>
</button>
</div>
</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 -->
<form id="registerForm" class="space-y-5 hidden">
<div>
<label for="regFullname" class="block text-xs font-bold text-on-surface-variant uppercase tracking-wider mb-2">Full Name</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">badge</span>
</span>
<input
type="text"
id="regFullname"
name="fullname"
placeholder="Enter your full name"
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="regEmail" class="block text-xs font-bold text-on-surface-variant uppercase tracking-wider mb-2">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="regEmail"
name="email"
placeholder="Enter your email"
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="regUsername" 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_add</span>
</span>
<input
type="text"
id="regUsername"
name="username"
placeholder="Choose a 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="regPassword" class="block text-xs font-bold text-on-surface-variant uppercase tracking-wider mb-2">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</span>
</span>
<input
type="password"
id="regPassword"
name="password"
placeholder="Create a 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">how_to_reg</span>
<span>Tạo tài khoản</span>
</button>
<div id="registerErrorMessage" 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="registerSuccessMessage" class="hidden bg-green-50 text-green-800 border border-green-200 rounded-lg px-4 py-3 text-xs font-medium"></div>
</form>
<!-- Footer -->
<!-- <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>
</div> -->
</div>
<!-- Bottom info -->
<div class="text-center mt-6">
<p class="text-xs text-on-surface-variant/60">v1.0.0</p>
</div>
</div>
</div>
<script>
const authTabs = document.getElementById('authTabs');
const loginForm = document.getElementById('loginForm');
const errorMessage = document.getElementById('errorMessage');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
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 registerErrorMessage = document.getElementById('registerErrorMessage');
const registerSuccessMessage = document.getElementById('registerSuccessMessage');
const verifyNotice = document.getElementById('verifyNotice');
const verifyNoticeText = document.getElementById('verifyNoticeText');
const resendVerifyBtn = document.getElementById('resendVerifyBtn');
const regFullnameInput = document.getElementById('regFullname');
const regEmailInput = document.getElementById('regEmail');
const regUsernameInput = document.getElementById('regUsername');
const regPasswordInput = document.getElementById('regPassword');
const loginTab = document.getElementById('loginTab');
const registerTab = document.getElementById('registerTab');
let pendingVerificationIdentifier = '';
let currentMode = 'login';
let resetToken = '';
const setMode = (mode) => {
currentMode = mode;
const isLogin = mode === 'login';
const isRegister = mode === 'register';
const isForgot = mode === 'forgot';
const isReset = mode === 'reset';
loginForm.classList.toggle('hidden', !isLogin);
registerForm.classList.toggle('hidden', !isRegister);
forgotPasswordForm.classList.toggle('hidden', !isForgot);
resetPasswordForm.classList.toggle('hidden', !isReset);
authTabs.classList.toggle('hidden', isReset);
errorMessage.classList.add('hidden');
registerErrorMessage.classList.add('hidden');
registerSuccessMessage.classList.add('hidden');
verifyNotice.classList.add('hidden');
forgotPasswordErrorMessage.classList.add('hidden');
forgotPasswordSuccessMessage.classList.add('hidden');
resetPasswordErrorMessage.classList.add('hidden');
const activate = (btn, active) => {
btn.classList.toggle('bg-primary', active);
btn.classList.toggle('text-on-primary', active);
btn.classList.toggle('shadow-sm', active);
btn.classList.toggle('bg-surface-container-low', !active);
btn.classList.toggle('text-on-surface-variant', !active);
};
activate(loginTab, !isRegister);
activate(registerTab, isRegister);
};
const clearResetQuery = () => {
const cleanUrl = `${window.location.origin}${window.location.pathname}`;
window.history.replaceState({}, document.title, cleanUrl);
};
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') {
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');
}
const rememberedUsername = localStorage.getItem('rememberedUsername');
if (rememberedUsername) {
usernameInput.value = rememberedUsername;
rememberCheckbox.checked = true;
if (!forgotUsernameInput.value) {
forgotUsernameInput.value = rememberedUsername;
}
}
});
loginTab.addEventListener('click', () => {
clearResetQuery();
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) => {
e.preventDefault();
errorMessage.classList.add('hidden');
verifyNotice.classList.add('hidden');
const username = usernameInput.value.trim();
const password = passwordInput.value;
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password, remember: rememberCheckbox.checked })
});
const data = await response.json();
if (data.success && data.user) {
localStorage.setItem('currentUser', JSON.stringify(data.user));
if (rememberCheckbox.checked) {
localStorage.setItem('rememberedUsername', username);
} else {
localStorage.removeItem('rememberedUsername');
}
window.location.href = './index.html';
} else if (data.requiresEmailVerification) {
pendingVerificationIdentifier = data.username || data.email || username;
verifyNoticeText.textContent = data.message || 'Please confirm your email before signing in';
verifyNotice.classList.remove('hidden');
} else {
errorMessage.textContent = data.message || 'Invalid username or password';
errorMessage.classList.remove('hidden');
passwordInput.value = '';
passwordInput.focus();
}
} catch (error) {
errorMessage.textContent = 'Connection error. Try again later.';
errorMessage.classList.remove('hidden');
console.error('Login error:', error);
}
});
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) => {
e.preventDefault();
registerErrorMessage.classList.add('hidden');
registerSuccessMessage.classList.add('hidden');
const payload = {
fullname: regFullnameInput.value.trim(),
email: regEmailInput.value.trim(),
username: regUsernameInput.value.trim(),
password: regPasswordInput.value
};
if (!payload.username || !payload.password || !payload.email) {
registerErrorMessage.textContent = 'Username, password and email are required';
registerErrorMessage.classList.remove('hidden');
return;
}
try {
const response = await fetch('/api/auth/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
const isJson = response.headers.get('content-type')?.includes('application/json');
const data = isJson ? await response.json() : null;
if (response.ok && data?.success) {
const lines = [data.message || 'Registration successful. Please check your email to confirm account.'];
if (data.verificationPreviewUrl) {
lines.push(`Development verification link: ${data.verificationPreviewUrl}`);
}
regPasswordInput.value = '';
setMode('login');
usernameInput.value = payload.username;
passwordInput.value = '';
pendingVerificationIdentifier = payload.email || payload.username;
verifyNoticeText.textContent = lines.join(' ');
verifyNotice.classList.remove('hidden');
} else {
const fallback = isJson ? (data?.message || 'Registration failed') : 'Server error (HTML response)';
registerErrorMessage.textContent = fallback;
registerErrorMessage.classList.remove('hidden');
}
} catch (error) {
registerErrorMessage.textContent = 'Connection error. Please try again.';
registerErrorMessage.classList.remove('hidden');
console.error('Register error:', error);
}
});
resendVerifyBtn.addEventListener('click', async () => {
const identifier = pendingVerificationIdentifier || usernameInput.value.trim();
if (!identifier) {
verifyNoticeText.textContent = 'Enter username/email first, then try resending verification.';
verifyNotice.classList.remove('hidden');
return;
}
try {
const response = await fetch('/api/auth/resend-verification', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ identifier })
});
const data = await response.json();
verifyNoticeText.textContent = data.message || 'Verification email processed.';
verifyNotice.classList.remove('hidden');
if (data.verificationPreviewUrl) {
verifyNoticeText.textContent += ` Development link: ${data.verificationPreviewUrl}`;
}
} catch (error) {
verifyNoticeText.textContent = 'Cannot resend verification email right now.';
verifyNotice.classList.remove('hidden');
console.error('Resend verification error:', error);
}
});
</script>
</body>
</html>

47
public/pages/users.html Normal file
View File

@@ -0,0 +1,47 @@
<!DOCTYPE html>
<html class="light" lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>Robot Manager Account - Users Management</title>
<link rel="icon" type="image/png" href="../image/logo_PNKX.png"/>
<!-- 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"/>
<!-- Material Symbols -->
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="../css/main.css" />
<!-- Notiflix Notify -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-3.2.7.min.css" />
<script src="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js"></script>
<style>
.material-symbols-outlined { font-family: 'Material Symbols Outlined'; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20; font-size: 1.25rem; line-height: 1; letter-spacing: normal; text-transform: none; display: inline-flex; white-space: nowrap; word-wrap: normal; direction: ltr; }
body { font-family: 'Inter', sans-serif; height: 100vh; overflow: hidden; }
h1, h2, h3, .brand-logo { font-family: 'Manrope', sans-serif; }
.modal-backdrop { opacity: 0; transition: opacity 0.2s ease-in-out; pointer-events: none; }
.modal-backdrop.open { opacity: 1; pointer-events: auto; }
.modal-content { transform: scale(0.95); transition: transform 0.2s ease-in-out; }
.modal-backdrop.open .modal-content { transform: scale(1); }
</style>
</head>
<body>
<script>
// Check if user has admin role, if not redirect to dashboard
const currentUser = localStorage.getItem('currentUser');
if (currentUser) {
try {
const user = JSON.parse(currentUser);
if (user.Role !== 'admin') {
window.location.href = './dashboard.html';
}
} catch (e) {
window.location.href = './login.html';
}
} else {
window.location.href = './login.html';
}
</script>
<script>
window.location.href = './index.html#users';
</script>
</body>
</html>

View File

@@ -0,0 +1,73 @@
<!DOCTYPE html>
<html lang="en" class="light">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Confirm Email - AccManager</title>
<link rel="icon" type="image/png" href="../image/logo_PNKX.png" />
<link rel="stylesheet" href="../css/main.css" />
<style>
body { font-family: 'Inter', sans-serif; min-height: 100vh; }
</style>
<link rel="stylesheet" href="../css/responsive.css?v=20260717-1" />
</head>
<body class="verify-page 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">
<section class="verify-card 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>
<p class="text-sm text-slate-600 mb-6">We are confirming your account.</p>
<div id="statusBox" class="rounded-lg border px-4 py-3 text-sm bg-slate-50 border-slate-200 text-slate-700">
Confirming your email, please wait...
</div>
<div class="verify-actions 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 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>
</section>
</main>
<script>
(async () => {
const statusBox = document.getElementById('statusBox');
const signInBtn = document.getElementById('signInBtn');
const params = new URLSearchParams(window.location.search);
const token = params.get('token');
if (!token) {
statusBox.className = 'rounded-lg border px-4 py-3 text-sm bg-red-50 border-red-200 text-red-700';
statusBox.textContent = 'Missing verification token.';
return;
}
try {
const response = await fetch(`/api/auth/verify-email?token=${encodeURIComponent(token)}`);
const data = await response.json();
if (response.ok && data.success) {
statusBox.className = 'rounded-lg border px-4 py-3 text-sm bg-green-50 border-green-200 text-green-700';
if (data.autoLogin && data.user) {
localStorage.setItem('currentUser', JSON.stringify(data.user));
statusBox.textContent = data.message || 'Email confirmed. Redirecting to dashboard...';
setTimeout(() => {
window.location.href = './index.html';
}, 1000);
} else {
statusBox.textContent = data.message || 'Email confirmed successfully.';
signInBtn.classList.remove('hidden');
}
} else {
statusBox.className = 'rounded-lg border px-4 py-3 text-sm bg-red-50 border-red-200 text-red-700';
statusBox.textContent = data.message || 'Email confirmation failed.';
}
} catch (error) {
statusBox.className = 'rounded-lg border px-4 py-3 text-sm bg-red-50 border-red-200 text-red-700';
statusBox.textContent = 'Cannot verify email right now. Please try again later.';
console.error('Verify email page error:', error);
}
})();
</script>
</body>
</html>

View File

@@ -1,4 +0,0 @@
Flask==2.3.2
Flask-CORS==4.0.0
pyodbc==4.0.35
python-dotenv==1.0.0

438
server.js
View File

@@ -1,438 +0,0 @@
// Backend Server for AccManager
// Express.js + mssql
const express = require('express');
const sql = require('mssql');
const cors = require('cors');
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// SQL Server Configuration
const sqlConfig = {
server: '172.20.235.176',
authentication: {
type: 'default',
options: {
userName: 'sa',
password: 'robotics@2020'
}
},
options: {
database: 'AccManager',
trustServerCertificate: true,
enableKeepAlive: true,
connectTimeout: 30000
}
};
// Initialize Database Pool
let pool;
async function initializeDatabase() {
try {
pool = new sql.ConnectionPool(sqlConfig);
await pool.connect();
console.log('✓ Connected to SQL Server');
// Check and create database if not exists
const masterConnection = new sql.ConnectionPool({
server: '172.20.235.176',
authentication: { type: 'default', options: { userName: 'sa', password: 'robotics@2020' } },
options: { connectTimeout: 30000, database: 'master', trustServerCertificate: true }
});
await masterConnection.connect();
const createDbResult = await masterConnection.request()
.query(`IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = 'AccManager')
BEGIN
CREATE DATABASE AccManager;
END`);
await masterConnection.close();
// Now create tables in AccManager
await createTables();
console.log('✓ Database and tables created');
} catch (err) {
console.error('Database connection failed:', err);
process.exit(1);
}
}
async function createTables() {
const queries = [
// Users Table
`IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Users')
BEGIN
CREATE TABLE Users (
UserId INT PRIMARY KEY IDENTITY(1,1),
Username NVARCHAR(50) UNIQUE NOT NULL,
Password NVARCHAR(255) NOT NULL,
Email NVARCHAR(100),
FullName NVARCHAR(100),
Role NVARCHAR(50) NOT NULL,
Status NVARCHAR(20) DEFAULT 'Active',
CreatedDate DATETIME DEFAULT GETDATE(),
LastLogin DATETIME,
IsActive BIT DEFAULT 1
)
END`,
// Applications Table
`IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Applications')
BEGIN
CREATE TABLE Applications (
AppId INT PRIMARY KEY IDENTITY(1,1),
Name NVARCHAR(100) NOT NULL,
Type NVARCHAR(50),
Status NVARCHAR(20) DEFAULT 'online',
Icon NVARCHAR(50),
Description NVARCHAR(500),
CreatedDate DATETIME DEFAULT GETDATE(),
UpdatedDate DATETIME DEFAULT GETDATE()
)
END`,
// Accounts Table
`IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Accounts')
BEGIN
CREATE TABLE Accounts (
AccountId INT PRIMARY KEY IDENTITY(1,1),
UserId INT NOT NULL,
AppId INT NOT NULL,
AccountUsername NVARCHAR(100),
AccountPassword NVARCHAR(255),
Email NVARCHAR(100),
AccessLevel NVARCHAR(50),
Status NVARCHAR(20) DEFAULT 'Active',
Notes NVARCHAR(MAX),
CreatedDate DATETIME DEFAULT GETDATE(),
UpdatedDate DATETIME DEFAULT GETDATE(),
FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE,
FOREIGN KEY (AppId) REFERENCES Applications(AppId) ON DELETE CASCADE
)
END`,
// AuditLog Table
`IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AuditLog')
BEGIN
CREATE TABLE AuditLog (
LogId INT PRIMARY KEY IDENTITY(1,1),
UserId INT,
Action NVARCHAR(50),
TableName NVARCHAR(50),
RecordId INT,
OldValue NVARCHAR(MAX),
NewValue NVARCHAR(MAX),
Timestamp DATETIME DEFAULT GETDATE(),
FOREIGN KEY (UserId) REFERENCES Users(UserId)
)
END`
];
for (let query of queries) {
try {
await pool.request().query(query);
} catch (err) {
console.error('Table creation error:', err.message);
}
}
// Insert initial admin user
try {
await pool.request()
.input('username', sql.NVarChar, 'admin')
.input('password', sql.NVarChar, 'admin')
.input('email', sql.NVarChar, 'admin@accmanager.local')
.input('fullname', sql.NVarChar, 'Administrator')
.input('role', sql.NVarChar, 'admin')
.query(`IF NOT EXISTS (SELECT * FROM Users WHERE Username = @username)
INSERT INTO Users (Username, Password, Email, FullName, Role, IsActive)
VALUES (@username, @password, @email, @fullname, @role, 1)`);
console.log('✓ Admin user created: admin / admin');
} catch (err) {
console.error('Admin user error:', err.message);
}
// Insert sample applications
try {
await pool.request()
.query(`IF (SELECT COUNT(*) FROM Applications) = 0
BEGIN
INSERT INTO Applications (Name, Type, Status, Icon, Description)
VALUES
('AWS', 'Cloud', 'online', 'cloud', 'Amazon Web Services'),
('GitHub', 'VCS', 'online', 'code', 'GitHub - Version Control'),
('Google Workspace', 'Collaboration', 'online', 'mail', 'Google Workspace'),
('Nginx Proxy', 'Infra', 'offline', 'dns', 'Nginx Web Server')
END`);
console.log('✓ Sample applications created');
} catch (err) {
console.error('Applications error:', err.message);
}
}
// ==========================================
// API ROUTES - Authentication
// ==========================================
// Login endpoint
app.post('/api/auth/login', async (req, res) => {
try {
const { username, password } = req.body;
const result = await pool.request()
.input('username', sql.NVarChar, username)
.input('password', sql.NVarChar, password)
.query('SELECT UserId, Username, Email, FullName, Role, Status FROM Users WHERE Username = @username AND Password = @password AND IsActive = 1');
if (result.recordset.length > 0) {
const user = result.recordset[0];
// Update last login
await pool.request()
.input('userId', sql.Int, user.UserId)
.query('UPDATE Users SET LastLogin = GETDATE() WHERE UserId = @userId');
res.json({
success: true,
message: 'Login successful',
user: user
});
} else {
res.status(401).json({
success: false,
message: 'Invalid username or password'
});
}
} catch (err) {
console.error('Login error:', err);
res.status(500).json({ success: false, message: err.message });
}
});
// ==========================================
// API ROUTES - Users
// ==========================================
// Get all users
app.get('/api/users', async (req, res) => {
try {
const result = await pool.request()
.query('SELECT UserId, Username, Email, FullName, Role, Status, CreatedDate FROM Users ORDER BY CreatedDate DESC');
res.json({ success: true, data: result.recordset });
} catch (err) {
res.status(500).json({ success: false, message: err.message });
}
});
// Get user by ID
app.get('/api/users/:id', async (req, res) => {
try {
const result = await pool.request()
.input('userId', sql.Int, req.params.id)
.query('SELECT * FROM Users WHERE UserId = @userId');
if (result.recordset.length > 0) {
res.json({ success: true, data: result.recordset[0] });
} else {
res.status(404).json({ success: false, message: 'User not found' });
}
} catch (err) {
res.status(500).json({ success: false, message: err.message });
}
});
// Create new user
app.post('/api/users', async (req, res) => {
try {
const { username, password, email, fullname, role } = req.body;
const result = await pool.request()
.input('username', sql.NVarChar, username)
.input('password', sql.NVarChar, password)
.input('email', sql.NVarChar, email)
.input('fullname', sql.NVarChar, fullname)
.input('role', sql.NVarChar, role)
.query(`INSERT INTO Users (Username, Password, Email, FullName, Role, IsActive)
VALUES (@username, @password, @email, @fullname, @role, 1);
SELECT SCOPE_IDENTITY() as UserId`);
res.json({ success: true, message: 'User created', userId: result.recordset[0].UserId });
} catch (err) {
res.status(500).json({ success: false, message: err.message });
}
});
// ==========================================
// API ROUTES - Applications
// ==========================================
// Get all applications
app.get('/api/applications', async (req, res) => {
try {
const result = await pool.request()
.query('SELECT * FROM Applications ORDER BY Name');
res.json({ success: true, data: result.recordset });
} catch (err) {
res.status(500).json({ success: false, message: err.message });
}
});
// Create application
app.post('/api/applications', async (req, res) => {
try {
const { name, type, status, icon, description } = req.body;
const result = await pool.request()
.input('name', sql.NVarChar, name)
.input('type', sql.NVarChar, type)
.input('status', sql.NVarChar, status)
.input('icon', sql.NVarChar, icon)
.input('description', sql.NVarChar, description)
.query(`INSERT INTO Applications (Name, Type, Status, Icon, Description)
VALUES (@name, @type, @status, @icon, @description);
SELECT SCOPE_IDENTITY() as AppId`);
res.json({ success: true, message: 'Application created', appId: result.recordset[0].AppId });
} catch (err) {
res.status(500).json({ success: false, message: err.message });
}
});
// ==========================================
// API ROUTES - Accounts
// ==========================================
// Get accounts for a user
app.get('/api/accounts/user/:userId', async (req, res) => {
try {
const result = await pool.request()
.input('userId', sql.Int, req.params.userId)
.query(`SELECT a.*, app.Name as AppName, app.Type as AppType
FROM Accounts a
JOIN Applications app ON a.AppId = app.AppId
WHERE a.UserId = @userId
ORDER BY a.CreatedDate DESC`);
res.json({ success: true, data: result.recordset });
} catch (err) {
res.status(500).json({ success: false, message: err.message });
}
});
// Create account
app.post('/api/accounts', async (req, res) => {
try {
const { userId, appId, accountUsername, accountPassword, email, accessLevel, notes } = req.body;
const result = await pool.request()
.input('userId', sql.Int, userId)
.input('appId', sql.Int, appId)
.input('accountUsername', sql.NVarChar, accountUsername)
.input('accountPassword', sql.NVarChar, accountPassword)
.input('email', sql.NVarChar, email)
.input('accessLevel', sql.NVarChar, accessLevel)
.input('notes', sql.NVarChar, notes)
.query(`INSERT INTO Accounts (UserId, AppId, AccountUsername, AccountPassword, Email, AccessLevel, Notes)
VALUES (@userId, @appId, @accountUsername, @accountPassword, @email, @accessLevel, @notes);
SELECT SCOPE_IDENTITY() as AccountId`);
res.json({ success: true, message: 'Account created', accountId: result.recordset[0].AccountId });
} catch (err) {
res.status(500).json({ success: false, message: err.message });
}
});
// ==========================================
// API ROUTES - Database Info
// ==========================================
// Get database information
app.get('/api/database/info', async (req, res) => {
try {
const tables = await pool.request().query(`
SELECT TABLE_NAME as TableName,
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = t.TABLE_NAME) as ColumnCount
FROM INFORMATION_SCHEMA.TABLES t
WHERE TABLE_SCHEMA = 'dbo'
ORDER BY TABLE_NAME
`);
const users = await pool.request().query('SELECT COUNT(*) as Count FROM Users');
const apps = await pool.request().query('SELECT COUNT(*) as Count FROM Applications');
const accounts = await pool.request().query('SELECT COUNT(*) as Count FROM Accounts');
res.json({
success: true,
database: 'AccManager',
server: '172.20.235.176',
tables: tables.recordset,
statistics: {
users: users.recordset[0].Count,
applications: apps.recordset[0].Count,
accounts: accounts.recordset[0].Count
}
});
} catch (err) {
res.status(500).json({ success: false, message: err.message });
}
});
// Health check
app.get('/api/health', (req, res) => {
res.json({ status: 'OK', database: 'Connected' });
});
// ==========================================
// Error Handling
// ==========================================
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ success: false, message: err.message });
});
// ==========================================
// Server Startup
// ==========================================
const PORT = process.env.PORT || 3000;
async function startServer() {
try {
await initializeDatabase();
app.listen(PORT, () => {
console.log(`\n========================================`);
console.log(`AccManager Backend Server`);
console.log(`========================================`);
console.log(`✓ Server running on http://localhost:${PORT}`);
console.log(`✓ Database: AccManager`);
console.log(`✓ Default admin: admin / admin`);
console.log(`\nAPI Endpoints:`);
console.log(` POST /api/auth/login`);
console.log(` GET /api/database/info`);
console.log(` GET /api/users`);
console.log(` GET /api/applications`);
console.log(` GET /api/accounts/user/:userId`);
console.log(`========================================\n`);
});
} catch (err) {
console.error('Failed to start server:', err);
process.exit(1);
}
}
// Graceful shutdown
process.on('SIGINT', async () => {
console.log('\nShutting down...');
if (pool) {
await pool.close();
}
process.exit(0);
});
startServer();

View File

@@ -1,480 +0,0 @@
# AccManager Backend Server (Python Alternative)
# Requirements: Python 3.8+, Flask, pyodbc
from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
from datetime import datetime
import pyodbc
import json
import os
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
CORS(app)
# SQL Server Connection Settings
DB_SERVER = os.getenv('DB_SERVER', '172.20.235.176')
DB_USER = os.getenv('DB_USER', 'sa')
DB_PASSWORD = os.getenv('DB_PASSWORD', 'robotics@2020')
DB_NAME = os.getenv('DB_NAME', 'AccManager')
# Connection string
CONNECTION_STRING = f'''
Driver={{ODBC Driver 17 for SQL Server}};
Server={DB_SERVER};
Database={DB_NAME};
UID={DB_USER};
PWD={DB_PASSWORD};
TrustServerCertificate=yes;
'''
# Initialize database connection
def get_db_connection():
try:
conn = pyodbc.connect(CONNECTION_STRING)
return conn
except Exception as e:
print(f"Database connection error: {e}")
return None
# Create tables
def create_tables():
conn = get_db_connection()
if not conn:
return False
cursor = conn.cursor()
try:
# Users table
cursor.execute('''
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Users')
BEGIN
CREATE TABLE Users (
UserId INT PRIMARY KEY IDENTITY(1,1),
Username NVARCHAR(50) UNIQUE NOT NULL,
Password NVARCHAR(255) NOT NULL,
Email NVARCHAR(100),
FullName NVARCHAR(100),
Role NVARCHAR(50) NOT NULL,
Status NVARCHAR(20) DEFAULT 'Active',
CreatedDate DATETIME DEFAULT GETDATE(),
LastLogin DATETIME,
IsActive BIT DEFAULT 1
)
END
''')
# Applications table
cursor.execute('''
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Applications')
BEGIN
CREATE TABLE Applications (
AppId INT PRIMARY KEY IDENTITY(1,1),
Name NVARCHAR(100) NOT NULL,
Type NVARCHAR(50),
Status NVARCHAR(20) DEFAULT 'online',
Icon NVARCHAR(50),
Description NVARCHAR(500),
CreatedDate DATETIME DEFAULT GETDATE(),
UpdatedDate DATETIME DEFAULT GETDATE()
)
END
''')
# Accounts table
cursor.execute('''
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Accounts')
BEGIN
CREATE TABLE Accounts (
AccountId INT PRIMARY KEY IDENTITY(1,1),
UserId INT NOT NULL,
AppId INT NOT NULL,
AccountUsername NVARCHAR(100),
AccountPassword NVARCHAR(255),
Email NVARCHAR(100),
AccessLevel NVARCHAR(50),
Status NVARCHAR(20) DEFAULT 'Active',
Notes NVARCHAR(MAX),
CreatedDate DATETIME DEFAULT GETDATE(),
UpdatedDate DATETIME DEFAULT GETDATE(),
FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE,
FOREIGN KEY (AppId) REFERENCES Applications(AppId) ON DELETE CASCADE
)
END
''')
# AuditLog table
cursor.execute('''
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AuditLog')
BEGIN
CREATE TABLE AuditLog (
LogId INT PRIMARY KEY IDENTITY(1,1),
UserId INT,
Action NVARCHAR(50),
TableName NVARCHAR(50),
RecordId INT,
OldValue NVARCHAR(MAX),
NewValue NVARCHAR(MAX),
Timestamp DATETIME DEFAULT GETDATE(),
FOREIGN KEY (UserId) REFERENCES Users(UserId)
)
END
''')
conn.commit()
# Insert admin user
cursor.execute('''
IF NOT EXISTS (SELECT * FROM Users WHERE Username = 'admin')
INSERT INTO Users (Username, Password, Email, FullName, Role, IsActive)
VALUES ('admin', 'admin', 'admin@accmanager.local', 'Administrator', 'admin', 1)
''')
# Insert sample applications
cursor.execute('''
IF (SELECT COUNT(*) FROM Applications) = 0
BEGIN
INSERT INTO Applications (Name, Type, Status, Icon, Description)
VALUES
('AWS', 'Cloud', 'online', 'cloud', 'Amazon Web Services'),
('GitHub', 'VCS', 'online', 'code', 'GitHub - Version Control'),
('Google Workspace', 'Collaboration', 'online', 'mail', 'Google Workspace'),
('Nginx Proxy', 'Infra', 'offline', 'dns', 'Nginx Web Server')
END
''')
conn.commit()
cursor.close()
conn.close()
return True
except Exception as e:
print(f"Table creation error: {e}")
return False
# ==========================================
# Routes: Health Check
# ==========================================
@app.route('/api/health', methods=['GET'])
def health():
conn = get_db_connection()
if conn:
conn.close()
return jsonify({"status": "OK", "database": "Connected"}), 200
else:
return jsonify({"status": "ERROR", "database": "Disconnected"}), 500
# ==========================================
# Routes: Authentication
# ==========================================
@app.route('/api/auth/login', methods=['POST'])
def login():
try:
data = request.get_json()
username = data.get('username')
password = data.get('password')
conn = get_db_connection()
if not conn:
return jsonify({"success": False, "message": "Database connection failed"}), 500
cursor = conn.cursor()
cursor.execute('''
SELECT UserId, Username, Email, FullName, Role, Status
FROM Users
WHERE Username = ? AND Password = ? AND IsActive = 1
''', (username, password))
user = cursor.fetchone()
if user:
cursor.execute('UPDATE Users SET LastLogin = GETDATE() WHERE UserId = ?', user[0])
conn.commit()
return jsonify({
"success": True,
"message": "Login successful",
"user": {
"UserId": user[0],
"username": user[1],
"email": user[2],
"fullname": user[3],
"role": user[4],
"status": user[5]
}
}), 200
else:
return jsonify({
"success": False,
"message": "Invalid username or password"
}), 401
except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500
finally:
if conn:
conn.close()
# ==========================================
# Routes: Users
# ==========================================
@app.route('/api/users', methods=['GET'])
def get_users():
try:
conn = get_db_connection()
if not conn:
return jsonify({"success": False, "message": "Database connection failed"}), 500
cursor = conn.cursor()
cursor.execute('''
SELECT UserId, Username, Email, FullName, Role, Status, CreatedDate
FROM Users
ORDER BY CreatedDate DESC
''')
users = []
for row in cursor.fetchall():
users.append({
"UserId": row[0],
"Username": row[1],
"Email": row[2],
"FullName": row[3],
"Role": row[4],
"Status": row[5],
"CreatedDate": str(row[6])
})
return jsonify({"success": True, "data": users}), 200
except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500
finally:
if conn:
conn.close()
@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
try:
conn = get_db_connection()
if not conn:
return jsonify({"success": False, "message": "Database connection failed"}), 500
cursor = conn.cursor()
cursor.execute('SELECT * FROM Users WHERE UserId = ?', (user_id,))
user = cursor.fetchone()
if user:
return jsonify({
"success": True,
"data": {"UserId": user[0], "Username": user[1]}
}), 200
else:
return jsonify({"success": False, "message": "User not found"}), 404
except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500
finally:
if conn:
conn.close()
@app.route('/api/users', methods=['POST'])
def create_user():
try:
data = request.get_json()
conn = get_db_connection()
if not conn:
return jsonify({"success": False, "message": "Database connection failed"}), 500
cursor = conn.cursor()
cursor.execute('''
INSERT INTO Users (Username, Password, Email, FullName, Role, IsActive)
VALUES (?, ?, ?, ?, ?, 1)
''', (data['username'], data['password'], data['email'],
data['fullname'], data['role']))
conn.commit()
return jsonify({
"success": True,
"message": "User created"
}), 201
except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500
finally:
if conn:
conn.close()
# ==========================================
# Routes: Applications
# ==========================================
@app.route('/api/applications', methods=['GET'])
def get_applications():
try:
conn = get_db_connection()
if not conn:
return jsonify({"success": False, "message": "Database connection failed"}), 500
cursor = conn.cursor()
cursor.execute('SELECT * FROM Applications ORDER BY Name')
apps = []
for row in cursor.fetchall():
apps.append({
"AppId": row[0],
"Name": row[1],
"Type": row[2],
"Status": row[3],
"Icon": row[4],
"Description": row[5]
})
return jsonify({"success": True, "data": apps}), 200
except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500
finally:
if conn:
conn.close()
# ==========================================
# Routes: Accounts
# ==========================================
@app.route('/api/accounts/user/<int:user_id>', methods=['GET'])
def get_accounts(user_id):
try:
conn = get_db_connection()
if not conn:
return jsonify({"success": False, "message": "Database connection failed"}), 500
cursor = conn.cursor()
cursor.execute('''
SELECT a.*, app.Name, app.Type
FROM Accounts a
JOIN Applications app ON a.AppId = app.AppId
WHERE a.UserId = ?
ORDER BY a.CreatedDate DESC
''', (user_id,))
accounts = []
for row in cursor.fetchall():
accounts.append({
"AccountId": row[0],
"UserId": row[1],
"AppId": row[2],
"AccountUsername": row[3],
"AccountPassword": row[4],
"AppName": row[12],
"AppType": row[13]
})
return jsonify({"success": True, "data": accounts}), 200
except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500
finally:
if conn:
conn.close()
# ==========================================
# Routes: Database Info
# ==========================================
@app.route('/api/database/info', methods=['GET'])
def database_info():
try:
conn = get_db_connection()
if not conn:
return jsonify({"success": False, "message": "Database connection failed"}), 500
cursor = conn.cursor()
# Get tables
cursor.execute('''
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
ORDER BY TABLE_NAME
''')
tables = [row[0] for row in cursor.fetchall()]
# Get statistics
cursor.execute('SELECT COUNT(*) FROM Users')
user_count = cursor.fetchone()[0]
cursor.execute('SELECT COUNT(*) FROM Applications')
app_count = cursor.fetchone()[0]
cursor.execute('SELECT COUNT(*) FROM Accounts')
account_count = cursor.fetchone()[0]
return jsonify({
"success": True,
"database": "AccManager",
"server": DB_SERVER,
"tables": tables,
"statistics": {
"users": user_count,
"applications": app_count,
"accounts": account_count
}
}), 200
except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500
finally:
if conn:
conn.close()
# ==========================================
# Error Handlers
# ==========================================
@app.errorhandler(404)
def not_found(error):
return jsonify({"error": "Not found"}), 404
@app.errorhandler(500)
def server_error(error):
return jsonify({"error": "Internal server error"}), 500
# ==========================================
# Startup
# ==========================================
if __name__ == '__main__':
print("\n========================================")
print("AccManager Backend Server (Python)")
print("========================================")
print(f"Server: {DB_SERVER}")
print(f"Database: {DB_NAME}")
print(f"User: {DB_USER}")
# Initialize database
print("\nInitializing database...")
if create_tables():
print("✓ Database tables created/verified")
else:
print("✗ Database initialization failed")
print("\n✓ Server running on http://localhost:5000")
print("\nAPI Endpoints:")
print(" /api/health")
print(" /api/auth/login")
print(" /api/users")
print(" /api/applications")
print(" /api/accounts/user/<id>")
print(" /api/database/info")
print("========================================\n")
app.run(debug=True, host='localhost', port=5000)

79
tailwind.config.js Normal file
View File

@@ -0,0 +1,79 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./public/**/*.{html,js}"
],
darkMode: "class",
theme: {
extend: {
colors: {
"on-secondary-fixed-variant": "#4e5c71",
"on-secondary": "#f8f8ff",
"secondary-fixed-dim": "#c7d5ed",
"surface-variant": "#d9e4ea",
"surface-tint": "#3755c3",
"primary-container": "#dde1ff",
"primary-dim": "#2848b7",
"on-background": "#2a3439",
"surface-container-lowest": "#ffffff",
"tertiary-fixed-dim": "#d4cdee",
"on-tertiary-container": "#514d68",
"error-container": "#fe8983",
"on-secondary-container": "#455367",
"outline": "#717c82",
"on-primary": "#f8f7ff",
"on-primary-container": "#2747b6",
"inverse-primary": "#6d89fa",
"on-surface": "#2a3439",
"primary-fixed": "#dde1ff",
"on-primary-fixed": "#0732a3",
"secondary-dim": "#465468",
"surface-container-high": "#e1e9ee",
"surface-container-highest": "#d9e4ea",
"on-primary-fixed-variant": "#3352c0",
"on-error-container": "#752121",
"secondary": "#526074",
"tertiary-fixed": "#e3dbfd",
"primary": "#3755c3",
"surface-dim": "#cfdce3",
"tertiary": "#605c78",
"on-error": "#fff7f6",
"secondary-fixed": "#d5e3fc",
"error-dim": "#4e0309",
"surface-bright": "#f7f9fb",
"on-surface-variant": "#566166",
"on-tertiary": "#fcf7ff",
"tertiary-container": "#e3dbfd",
"inverse-on-surface": "#9a9d9f",
"on-tertiary-fixed-variant": "#5b5672",
"tertiary-dim": "#54506b",
"outline-variant": "#a9b4b9",
"on-secondary-fixed": "#324053",
"inverse-surface": "#0b0f10",
"on-tertiary-fixed": "#3e3a54",
"primary-fixed-dim": "#cad2ff",
"surface-container": "#e8eff3",
"secondary-container": "#d5e3fc",
"surface-container-low": "#f0f4f7",
"background": "#f7f9fb",
"error": "#9f403d",
"surface": "#f7f9fb"
},
fontFamily: {
headline: ["Manrope", "sans-serif"],
body: ["Inter", "sans-serif"],
label: ["Inter", "sans-serif"]
},
borderRadius: {
DEFAULT: "0.125rem",
lg: "0.25rem",
xl: "0.5rem",
full: "0.75rem"
}
}
},
plugins: [
require("@tailwindcss/forms"),
require("@tailwindcss/container-queries")
]
};

BIN
tmp-import-source.xls Normal file

Binary file not shown.

BIN
tmp-user-import.xls Normal file

Binary file not shown.