update file tài sản
This commit is contained in:
34
ASSET_DATA_REPLACEMENT.md
Normal file
34
ASSET_DATA_REPLACEMENT.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Thay dữ liệu tài sản, giữ lịch sử mượn trả
|
||||
|
||||
Chức năng **Xóa danh mục hiện tại** đưa các tài sản hiện tại vào dữ liệu cũ. Phiếu mượn, phiếu trả, các lần trả một phần, danh sách người đang mượn và lịch sử xuất/hư hỏng/thanh lý vẫn được giữ.
|
||||
|
||||
## Các bước thực hiện
|
||||
|
||||
1. Sao lưu cơ sở dữ liệu SQL Server trước khi thay dữ liệu. Triển khai bản ứng dụng có chức năng lưu trữ tài sản này trước khi thao tác xóa.
|
||||
2. Đăng nhập bằng tài khoản **Admin** hoặc **Quản lý tài sản**. Mở **Quản lý tài sản** → **Xóa danh mục hiện tại**, đọc nội dung rồi xác nhận. Thao tác áp dụng cho toàn bộ danh mục hiện tại, kể cả tài sản ở trang khác hoặc đang bị bộ lọc ẩn.
|
||||
3. Upload file tài sản mới bằng chức năng nhập Excel hiện có. Mã tài sản được phép trùng với mã trong dữ liệu cũ. Bản ghi mới có tồn kho riêng; lịch sử cũ tiếp tục gắn với bản ghi cũ.
|
||||
4. Mở **Mượn/Trả tài sản**, chọn bộ lọc **Đơn → Còn đang mượn**. Chọn thêm **Tài sản → Tài sản cũ** nếu chỉ muốn xem các phiếu của danh mục đã xóa. Số lượng còn mượn bằng số đã mượn trừ số đã được xác nhận trả. Đơn trả đang chờ duyệt chưa được trừ.
|
||||
5. Mở **Tài sản cũ còn mượn** để đối chiếu cả người mượn được nhập từ Excel hoặc ghi khi xuất trực tiếp mà chưa có phiếu mượn riêng. Màn hình **Tài sản tôi đang mượn** cũng giữ các tài sản cũ còn đang mượn.
|
||||
|
||||
## Xử lý mượn trả sau khi thay dữ liệu
|
||||
|
||||
- Phiếu mượn cũ vẫn xem được lịch sử và tạo/duyệt đơn trả theo luồng hiện có. Trả một phần vẫn nằm trong danh sách còn đang mượn.
|
||||
- Việc trả tài sản cũ cập nhật bản ghi và lịch sử cũ. Muốn đưa số lượng này vào danh mục mới, đối chiếu rồi nhập kho mới riêng; hệ thống không tự ghép chỉ vì trùng mã.
|
||||
- Tài sản cũ không được sửa hoặc xuất/mượn thêm. Đơn mượn cũ còn chờ xử lý không được duyệt; người quản lý có thể từ chối đơn đó.
|
||||
- Xóa một tài sản hoặc **Xóa đã chọn** cũng giữ lịch sử theo cùng cơ chế.
|
||||
|
||||
Không dùng `DELETE`/`TRUNCATE` bảng tài sản, xóa các bảng mượn trả, hoặc tạo lại database để làm trống danh mục. Chức năng trong giao diện giữ bản ghi cũ để tiếp tục theo dõi số lượng chưa trả. Dữ liệu đã bị xóa bởi phiên bản trước chỉ có thể lấy lại từ bản sao lưu phù hợp.
|
||||
|
||||
## Triển khai
|
||||
|
||||
Ứng dụng tự chạy migration khi khởi động: thêm trạng thái lưu trữ, cho phép tái sử dụng mã tài sản trong danh mục mới và bảo vệ các liên kết lịch sử khỏi xóa dây chuyền. Migration không tự xóa hoặc lưu trữ tài sản nào. Nếu migration lỗi, ứng dụng dừng khởi động để người triển khai kiểm tra log.
|
||||
|
||||
Build/push image mới, cập nhật `DOCKER_IMAGE` trên máy chủ, rồi chạy:
|
||||
|
||||
```bash
|
||||
docker compose --env-file .env -f docker-compose.image.yml pull accmanager
|
||||
docker compose --env-file .env -f docker-compose.image.yml up -d accmanager
|
||||
docker compose --env-file .env -f docker-compose.image.yml logs --tail=100 accmanager
|
||||
```
|
||||
|
||||
Kiểm tra ứng dụng khởi động thành công và có nút **Xóa danh mục hiện tại** trước khi thay dữ liệu.
|
||||
10
backend/asset-archive-schema.js
Normal file
10
backend/asset-archive-schema.js
Normal 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 };
|
||||
96
backend/asset-archive-schema.sql
Normal file
96
backend/asset-archive-schema.sql
Normal 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;
|
||||
@@ -12,6 +12,7 @@ const XLSX = require('xlsx');
|
||||
const dotenv = require('dotenv');
|
||||
const helmet = require('helmet');
|
||||
const { rateLimit } = require('express-rate-limit');
|
||||
const { ensureAssetArchiveSchema } = require('./asset-archive-schema');
|
||||
|
||||
dotenv.config();
|
||||
|
||||
@@ -410,7 +411,7 @@ async function syncAssetDepartmentsFromInventory() {
|
||||
WITH SourceDepartments AS (
|
||||
SELECT DISTINCT LTRIM(RTRIM(Department)) AS DepartmentName
|
||||
FROM AssetInventory
|
||||
WHERE Department IS NOT NULL
|
||||
WHERE IsArchived = 0 AND Department IS NOT NULL
|
||||
AND LTRIM(RTRIM(Department)) <> ''
|
||||
)
|
||||
INSERT INTO AssetDepartments (DepartmentName)
|
||||
@@ -433,7 +434,7 @@ async function syncAssetProjectsFromInventory() {
|
||||
WITH SourceProjects AS (
|
||||
SELECT DISTINCT LTRIM(RTRIM(Project)) AS ProjectName
|
||||
FROM AssetInventory
|
||||
WHERE Project IS NOT NULL
|
||||
WHERE IsArchived = 0 AND Project IS NOT NULL
|
||||
AND LTRIM(RTRIM(Project)) <> ''
|
||||
)
|
||||
INSERT INTO AssetProjects (ProjectName)
|
||||
@@ -1325,7 +1326,7 @@ async function generateUniqueManualAssetCode(payload = {}, maxAttempts = 8) {
|
||||
.query(`
|
||||
SELECT TOP 1 AssetId
|
||||
FROM AssetInventory
|
||||
WHERE AssetCode = @assetCode
|
||||
WHERE AssetCode = @assetCode AND IsArchived = 0
|
||||
`);
|
||||
|
||||
if (existed.recordset.length === 0) {
|
||||
@@ -1677,7 +1678,7 @@ async function ensureUniqueImportAssetCode(transaction, initialCode, maxAttempts
|
||||
.query(`
|
||||
SELECT TOP 1 AssetId
|
||||
FROM AssetInventory
|
||||
WHERE AssetCode = @assetCode
|
||||
WHERE AssetCode = @assetCode AND IsArchived = 0
|
||||
`);
|
||||
|
||||
if (existed.recordset.length === 0) {
|
||||
@@ -2352,6 +2353,7 @@ const sqlConfig = {
|
||||
database: DB_NAME,
|
||||
trustServerCertificate: DB_TRUST_CERTIFICATE,
|
||||
enableKeepAlive: true,
|
||||
enableArithAbort: true,
|
||||
connectTimeout: DB_CONNECT_TIMEOUT,
|
||||
encrypt: DB_ENCRYPT,
|
||||
useUTC: false
|
||||
@@ -3121,6 +3123,9 @@ async function createTables() {
|
||||
}
|
||||
}
|
||||
|
||||
// Fail startup if history preservation cannot be installed.
|
||||
await ensureAssetArchiveSchema(pool);
|
||||
|
||||
// Ensure notification indexes exist for audience lookup and unread counts.
|
||||
try {
|
||||
await pool.request().query(`IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_Notifications_ActiveCreated') CREATE INDEX IX_Notifications_ActiveCreated ON Notifications(IsActive, CreatedDate DESC);`);
|
||||
@@ -3525,15 +3530,16 @@ async function createTables() {
|
||||
WHERE LOWER(LTRIM(RTRIM(ISNULL(borrowRows.RequestType, '')))) = 'borrow';
|
||||
END
|
||||
`);
|
||||
await pool.request().query(`UPDATE AssetInventory SET EndingBalance = ISNULL(EndingBalance, ISNULL(Quantity, 0));`);
|
||||
await pool.request().query(`UPDATE AssetInventory SET Quantity = ISNULL(NULLIF(Quantity, 0), EndingBalance);`);
|
||||
await pool.request().query(`UPDATE AssetInventory SET UsedQuantity = CASE WHEN UsedQuantity < 0 THEN 0 ELSE ISNULL(UsedQuantity, 0) END;`);
|
||||
await pool.request().query(`UPDATE AssetInventory SET EndingBalance = ISNULL(EndingBalance, ISNULL(Quantity, 0)) WHERE IsArchived = 0;`);
|
||||
await pool.request().query(`UPDATE AssetInventory SET Quantity = ISNULL(NULLIF(Quantity, 0), EndingBalance) WHERE IsArchived = 0;`);
|
||||
await pool.request().query(`UPDATE AssetInventory SET UsedQuantity = CASE WHEN UsedQuantity < 0 THEN 0 ELSE ISNULL(UsedQuantity, 0) END WHERE IsArchived = 0;`);
|
||||
await pool.request().query(`
|
||||
UPDATE AssetInventory
|
||||
SET NewQuantity = CASE
|
||||
WHEN ISNULL(NewQuantity, 0) < 0 THEN 0
|
||||
ELSE ISNULL(NewQuantity, 0)
|
||||
END;
|
||||
END
|
||||
WHERE IsArchived = 0;
|
||||
`);
|
||||
await pool.request().query(`
|
||||
UPDATE AssetInventory
|
||||
@@ -3553,14 +3559,15 @@ async function createTables() {
|
||||
AND ISNULL(NewQuantity, 0) < ((ISNULL(NewQuantity, 0) + ISNULL(UsedQuantity, 0)) - ISNULL(EndingBalance, 0))
|
||||
THEN ISNULL(EndingBalance, 0)
|
||||
ELSE ISNULL(UsedQuantity, 0)
|
||||
END;
|
||||
END
|
||||
WHERE IsArchived = 0;
|
||||
`);
|
||||
await pool.request().query(`
|
||||
UPDATE ai
|
||||
SET ai.ExportedBy = COALESCE(NULLIF(LTRIM(RTRIM(u.FullName)), ''), NULLIF(LTRIM(RTRIM(u.Username)), ''))
|
||||
FROM AssetInventory ai
|
||||
LEFT JOIN Users u ON ai.CreatedBy = u.UserId
|
||||
WHERE ai.ExportedBy IS NULL
|
||||
WHERE ai.ExportedBy IS NULL AND ai.IsArchived = 0
|
||||
`);
|
||||
await pool.request().query(`IF COL_LENGTH('dbo.AssetInventory','Category') IS NOT NULL ALTER TABLE AssetInventory DROP COLUMN Category;`);
|
||||
await pool.request().query(`IF COL_LENGTH('dbo.AssetInventory','Brand') IS NOT NULL ALTER TABLE AssetInventory DROP COLUMN Brand;`);
|
||||
@@ -5312,6 +5319,7 @@ app.get('/api/asset-departments', async (req, res) => {
|
||||
FROM AssetDepartments d
|
||||
LEFT JOIN AssetInventory ai
|
||||
ON LOWER(LTRIM(RTRIM(ai.Department))) = LOWER(LTRIM(RTRIM(d.DepartmentName)))
|
||||
AND ai.IsArchived = 0
|
||||
GROUP BY d.DepartmentId, d.DepartmentName, d.CreatedDate, d.UpdatedDate
|
||||
ORDER BY d.DepartmentName ASC
|
||||
`);
|
||||
@@ -5433,7 +5441,7 @@ app.put('/api/asset-departments/:id', requireAssetOrAdmin, async (req, res) => {
|
||||
UPDATE AssetInventory
|
||||
SET Department = @newDepartmentName,
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
WHERE LOWER(LTRIM(RTRIM(Department))) = LOWER(@oldDepartmentName)
|
||||
WHERE LOWER(LTRIM(RTRIM(Department))) = LOWER(@oldDepartmentName) AND IsArchived = 0
|
||||
`);
|
||||
|
||||
await transaction.commit();
|
||||
@@ -5487,7 +5495,7 @@ app.delete('/api/asset-departments/:id', requireAssetOrAdmin, async (req, res) =
|
||||
UPDATE AssetInventory
|
||||
SET Department = NULL,
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
WHERE LOWER(LTRIM(RTRIM(Department))) = LOWER(@departmentName)
|
||||
WHERE LOWER(LTRIM(RTRIM(Department))) = LOWER(@departmentName) AND IsArchived = 0
|
||||
`);
|
||||
|
||||
await new sql.Request(transaction)
|
||||
@@ -5530,6 +5538,7 @@ app.get('/api/asset-projects', async (req, res) => {
|
||||
FROM AssetProjects p
|
||||
LEFT JOIN AssetInventory ai
|
||||
ON LOWER(LTRIM(RTRIM(ai.Project))) = LOWER(LTRIM(RTRIM(p.ProjectName)))
|
||||
AND ai.IsArchived = 0
|
||||
GROUP BY p.ProjectId, p.ProjectName, p.CreatedDate, p.UpdatedDate
|
||||
ORDER BY p.ProjectName ASC
|
||||
`);
|
||||
@@ -5651,7 +5660,7 @@ app.put('/api/asset-projects/:id', requireAssetOrAdmin, async (req, res) => {
|
||||
UPDATE AssetInventory
|
||||
SET Project = @newProjectName,
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
WHERE LOWER(LTRIM(RTRIM(Project))) = LOWER(@oldProjectName)
|
||||
WHERE LOWER(LTRIM(RTRIM(Project))) = LOWER(@oldProjectName) AND IsArchived = 0
|
||||
`);
|
||||
|
||||
await transaction.commit();
|
||||
@@ -5705,7 +5714,7 @@ app.delete('/api/asset-projects/:id', requireAssetOrAdmin, async (req, res) => {
|
||||
UPDATE AssetInventory
|
||||
SET Project = NULL,
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
WHERE LOWER(LTRIM(RTRIM(Project))) = LOWER(@projectName)
|
||||
WHERE LOWER(LTRIM(RTRIM(Project))) = LOWER(@projectName) AND IsArchived = 0
|
||||
`);
|
||||
|
||||
await new sql.Request(transaction)
|
||||
@@ -5751,6 +5760,8 @@ app.get('/api/asset-borrows', async (req, res) => {
|
||||
br.AssetId,
|
||||
ai.AssetCode,
|
||||
ai.AssetName,
|
||||
ai.IsArchived,
|
||||
ai.ArchivedDate,
|
||||
br.RequestType,
|
||||
br.RequestStatus,
|
||||
br.BorrowerName,
|
||||
@@ -5764,6 +5775,22 @@ app.get('/api/asset-borrows', async (req, res) => {
|
||||
END
|
||||
ELSE 0
|
||||
END AS RemainingQuantity,
|
||||
CASE
|
||||
WHEN LOWER(LTRIM(RTRIM(ISNULL(br.RequestType, '')))) = 'borrow'
|
||||
AND LOWER(LTRIM(RTRIM(ISNULL(br.RequestStatus, '')))) = 'approved'
|
||||
THEN CASE
|
||||
WHEN ISNULL(br.BorrowQuantity, 0) >
|
||||
CASE WHEN ISNULL(activeReturns.ActiveReturnQuantity, 0) > ISNULL(br.ReturnedQuantity, 0)
|
||||
THEN ISNULL(activeReturns.ActiveReturnQuantity, 0)
|
||||
ELSE ISNULL(br.ReturnedQuantity, 0) END
|
||||
THEN ISNULL(br.BorrowQuantity, 0) -
|
||||
CASE WHEN ISNULL(activeReturns.ActiveReturnQuantity, 0) > ISNULL(br.ReturnedQuantity, 0)
|
||||
THEN ISNULL(activeReturns.ActiveReturnQuantity, 0)
|
||||
ELSE ISNULL(br.ReturnedQuantity, 0) END
|
||||
ELSE 0
|
||||
END
|
||||
ELSE 0
|
||||
END AS AvailableReturnQuantity,
|
||||
ISNULL(returnSummary.ReturnCount, 0) AS RelatedReturnCount,
|
||||
ISNULL(borrowSummary.BorrowCount, 0) AS RelatedBorrowCount,
|
||||
COALESCE(NULLIF(LTRIM(RTRIM(br.Unit)), ''), ai.Unit) AS Unit,
|
||||
@@ -5777,6 +5804,13 @@ app.get('/api/asset-borrows', async (req, res) => {
|
||||
br.CreatedDate
|
||||
FROM AssetBorrowRequests br
|
||||
LEFT JOIN AssetInventory ai ON ai.AssetId = br.AssetId
|
||||
OUTER APPLY (
|
||||
SELECT SUM(ISNULL(links.Quantity, 0)) AS ActiveReturnQuantity
|
||||
FROM AssetBorrowRequestLinks links
|
||||
INNER JOIN AssetBorrowRequests returnRows ON returnRows.BorrowId = links.ReturnId
|
||||
WHERE links.BorrowId = br.BorrowId
|
||||
AND LOWER(LTRIM(RTRIM(ISNULL(returnRows.RequestStatus, '')))) IN ('pending', 'approved')
|
||||
) activeReturns
|
||||
OUTER APPLY (
|
||||
SELECT COUNT(1) AS ReturnCount
|
||||
FROM AssetBorrowRequests rr
|
||||
@@ -5842,6 +5876,8 @@ app.get('/api/asset-borrows/:id/history', async (req, res) => {
|
||||
br.AssetId,
|
||||
ai.AssetCode,
|
||||
ai.AssetName,
|
||||
ai.IsArchived,
|
||||
ai.ArchivedDate,
|
||||
br.RequestType,
|
||||
br.RequestStatus,
|
||||
br.BorrowerName,
|
||||
@@ -5900,6 +5936,8 @@ app.get('/api/asset-borrows/:id/history', async (req, res) => {
|
||||
br.AssetId,
|
||||
ai.AssetCode,
|
||||
ai.AssetName,
|
||||
ai.IsArchived,
|
||||
ai.ArchivedDate,
|
||||
br.RequestType,
|
||||
br.RequestStatus,
|
||||
br.BorrowerName,
|
||||
@@ -6016,11 +6054,15 @@ app.post('/api/asset-borrows', async (req, res) => {
|
||||
return res.status(400).json({ success: false, message: 'So luong phai lon hon 0' });
|
||||
}
|
||||
|
||||
const assetResult = await pool.request()
|
||||
transaction = new sql.Transaction(pool);
|
||||
await transaction.begin();
|
||||
|
||||
const assetResult = await new sql.Request(transaction)
|
||||
.input('assetId', sql.Int, assetId)
|
||||
.query(`
|
||||
SELECT TOP 1
|
||||
AssetId,
|
||||
IsArchived,
|
||||
AssetCode,
|
||||
AssetName,
|
||||
Quantity,
|
||||
@@ -6029,12 +6071,13 @@ app.post('/api/asset-borrows', async (req, res) => {
|
||||
EndingBalance,
|
||||
Borrower,
|
||||
Unit
|
||||
FROM AssetInventory
|
||||
FROM AssetInventory WITH (UPDLOCK, HOLDLOCK)
|
||||
WHERE AssetId = @assetId
|
||||
`);
|
||||
|
||||
const asset = assetResult.recordset?.[0];
|
||||
if (!asset) {
|
||||
await transaction.rollback();
|
||||
return res.status(404).json({ success: false, message: 'Khong tim thay tai san' });
|
||||
}
|
||||
|
||||
@@ -6052,11 +6095,18 @@ app.post('/api/asset-borrows', async (req, res) => {
|
||||
const unit = String(req.body?.unit || '').trim() || String(asset.Unit || '').trim() || null;
|
||||
|
||||
if (requestType === 'borrow') {
|
||||
if (asset.IsArchived) {
|
||||
await transaction.rollback();
|
||||
return res.status(409).json({ success: false, message: 'Tai san da luu tru, khong the tao don muon moi' });
|
||||
}
|
||||
|
||||
if (endingBalance <= 0) {
|
||||
await transaction.rollback();
|
||||
return res.status(400).json({ success: false, message: 'Tai san da het ton cuoi ky' });
|
||||
}
|
||||
|
||||
if (borrowQuantity > endingBalance) {
|
||||
await transaction.rollback();
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: `So luong muon (${borrowQuantity}) vuot qua ton cuoi ky (${endingBalance})`
|
||||
@@ -6067,6 +6117,7 @@ app.post('/api/asset-borrows', async (req, res) => {
|
||||
const borrowedQuantity = parseNonNegativeInteger(existed?.quantity, 0);
|
||||
|
||||
if (borrowedQuantity <= 0) {
|
||||
await transaction.rollback();
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Ban chua co du lieu muon tai san nay de tao don tra'
|
||||
@@ -6074,6 +6125,7 @@ app.post('/api/asset-borrows', async (req, res) => {
|
||||
}
|
||||
|
||||
if (borrowQuantity > borrowedQuantity) {
|
||||
await transaction.rollback();
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: `So luong tra (${borrowQuantity}) vuot qua so luong dang muon (${borrowedQuantity})`
|
||||
@@ -6081,9 +6133,6 @@ app.post('/api/asset-borrows', async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
transaction = new sql.Transaction(pool);
|
||||
await transaction.begin();
|
||||
|
||||
let returnLinkRows = [];
|
||||
if (requestType === 'return') {
|
||||
const createdByValue = Number.isInteger(Number(createdBy)) ? Number(createdBy) : null;
|
||||
@@ -6450,6 +6499,7 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
|
||||
br.BorrowDate,
|
||||
br.Unit,
|
||||
br.CreatedBy,
|
||||
ai.IsArchived,
|
||||
ai.AssetCode,
|
||||
ai.AssetName,
|
||||
ai.Quantity,
|
||||
@@ -6461,8 +6511,8 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
|
||||
ai.Status,
|
||||
ai.Borrower,
|
||||
ai.Unit AS AssetUnit
|
||||
FROM AssetBorrowRequests br
|
||||
INNER JOIN AssetInventory ai ON ai.AssetId = br.AssetId
|
||||
FROM AssetBorrowRequests br WITH (UPDLOCK, HOLDLOCK)
|
||||
INNER JOIN AssetInventory ai WITH (UPDLOCK, HOLDLOCK) ON ai.AssetId = br.AssetId
|
||||
WHERE br.BorrowId = @borrowId
|
||||
`);
|
||||
|
||||
@@ -6484,6 +6534,11 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
|
||||
const requestQuantity = parseNonNegativeInteger(targetRequest.BorrowQuantity, 0);
|
||||
|
||||
if (requestType === 'borrow') {
|
||||
if (targetRequest.IsArchived) {
|
||||
await transaction.rollback();
|
||||
return res.status(409).json({ success: false, message: 'Tai san da luu tru, khong the duyet don muon. Vui long tu choi don nay.' });
|
||||
}
|
||||
|
||||
const currentBorrowed = parseBorrowerEntries(targetRequest.Borrower).reduce((sum, entry) => (
|
||||
sum + parseNonNegativeInteger(entry?.quantity, 0)
|
||||
), 0);
|
||||
@@ -8373,8 +8428,11 @@ app.post('/api/consumables/import', requireAssetOrAdmin, upload.single('file'),
|
||||
|
||||
app.get('/api/assets', async (req, res) => {
|
||||
try {
|
||||
const result = await pool.request().query(`
|
||||
SELECT AssetId, AssetCode, AssetName, Model, SerialNumber,
|
||||
const archived = ['1', 'true', 'yes'].includes(String(req.query.archived || '').trim().toLowerCase());
|
||||
const result = await pool.request()
|
||||
.input('isArchived', sql.Bit, archived ? 1 : 0)
|
||||
.query(`
|
||||
SELECT AssetId, IsArchived, ArchivedDate, AssetCode, AssetName, Model, SerialNumber,
|
||||
Quantity, ImportInPeriod, ExportInPeriod, EndingBalance,
|
||||
NewQuantity, UsedQuantity,
|
||||
Unit, Department, Project, Location, Custodian, Borrower, ExportedBy,
|
||||
@@ -8386,6 +8444,7 @@ app.get('/api/assets', async (req, res) => {
|
||||
END AS Status,
|
||||
Notes, CreatedBy, CreatedDate, UpdatedDate
|
||||
FROM AssetInventory
|
||||
WHERE IsArchived = @isArchived
|
||||
ORDER BY UpdatedDate DESC, AssetName ASC
|
||||
`);
|
||||
|
||||
@@ -8426,7 +8485,7 @@ app.get('/api/assets/search', async (req, res) => {
|
||||
CASE WHEN @keyword <> '' AND AssetCode LIKE @keywordLike THEN 0 ELSE 1 END AS CodeRank,
|
||||
CASE WHEN @keyword <> '' AND AssetName LIKE @keywordLike THEN 0 ELSE 1 END AS NameRank
|
||||
FROM AssetInventory
|
||||
WHERE (@borrowableOnly = 0 OR ISNULL(EndingBalance, 0) > 0)
|
||||
WHERE IsArchived = 0 AND (@borrowableOnly = 0 OR ISNULL(EndingBalance, 0) > 0)
|
||||
AND (
|
||||
@keyword = ''
|
||||
OR AssetCode LIKE @keywordLike
|
||||
@@ -8458,7 +8517,7 @@ app.get('/api/assets/search', async (req, res) => {
|
||||
|
||||
SELECT COUNT(*) AS TotalCount
|
||||
FROM AssetInventory
|
||||
WHERE (@borrowableOnly = 0 OR ISNULL(EndingBalance, 0) > 0)
|
||||
WHERE IsArchived = 0 AND (@borrowableOnly = 0 OR ISNULL(EndingBalance, 0) > 0)
|
||||
AND (
|
||||
@keyword = ''
|
||||
OR AssetCode LIKE @keywordLike
|
||||
@@ -8494,7 +8553,7 @@ app.get('/api/assets/:id', async (req, res) => {
|
||||
END AS Status,
|
||||
Notes, CreatedBy, CreatedDate, UpdatedDate
|
||||
FROM AssetInventory
|
||||
WHERE AssetId = @assetId
|
||||
WHERE AssetId = @assetId AND IsArchived = 0
|
||||
`);
|
||||
|
||||
if (result.recordset.length === 0) {
|
||||
@@ -8626,7 +8685,7 @@ app.post('/api/assets/:id/damage-disposal', requireAssetOrAdmin, async (req, res
|
||||
UsedQuantity,
|
||||
Unit
|
||||
FROM AssetInventory WITH (UPDLOCK, ROWLOCK)
|
||||
WHERE AssetId = @assetId
|
||||
WHERE AssetId = @assetId AND IsArchived = 0
|
||||
`);
|
||||
|
||||
const asset = assetResult.recordset?.[0];
|
||||
@@ -8700,7 +8759,7 @@ app.post('/api/assets/:id/damage-disposal', requireAssetOrAdmin, async (req, res
|
||||
UsedQuantity = @usedQuantity,
|
||||
Status = @status,
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
WHERE AssetId = @assetId
|
||||
WHERE AssetId = @assetId AND IsArchived = 0
|
||||
`);
|
||||
|
||||
const historyResult = await new sql.Request(transaction)
|
||||
@@ -8871,7 +8930,7 @@ app.post('/api/assets/:id/export', requireAssetOrAdmin, async (req, res) => {
|
||||
Borrower,
|
||||
Notes
|
||||
FROM AssetInventory WITH (UPDLOCK, ROWLOCK)
|
||||
WHERE AssetId = @assetId
|
||||
WHERE AssetId = @assetId AND IsArchived = 0
|
||||
`);
|
||||
|
||||
const asset = assetResult.recordset?.[0];
|
||||
@@ -8955,7 +9014,7 @@ app.post('/api/assets/:id/export', requireAssetOrAdmin, async (req, res) => {
|
||||
ExportedBy = @exportedBy,
|
||||
Notes = @notes,
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
WHERE AssetId = @assetId
|
||||
WHERE AssetId = @assetId AND IsArchived = 0
|
||||
`);
|
||||
|
||||
const historyCustodianName = String(asset.Custodian || '').trim() || '-';
|
||||
@@ -9110,7 +9169,7 @@ app.put('/api/assets/:id', requireAssetOrAdmin, async (req, res) => {
|
||||
|
||||
await ensureDepartmentExists(payload.department);
|
||||
|
||||
await pool.request()
|
||||
const updateResult = await pool.request()
|
||||
.input('assetId', sql.Int, req.params.id)
|
||||
.input('assetCode', sql.NVarChar, payload.assetCode)
|
||||
.input('assetName', sql.NVarChar, payload.assetName)
|
||||
@@ -9157,9 +9216,14 @@ app.put('/api/assets/:id', requireAssetOrAdmin, async (req, res) => {
|
||||
Status = @status,
|
||||
Notes = @notes,
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
WHERE AssetId = @assetId
|
||||
OUTPUT INSERTED.AssetId
|
||||
WHERE AssetId = @assetId AND IsArchived = 0
|
||||
`);
|
||||
|
||||
if (!updateResult.recordset?.length) {
|
||||
return res.status(404).json({ success: false, message: 'Asset not found or archived' });
|
||||
}
|
||||
|
||||
res.json({ success: true, message: 'Asset updated' });
|
||||
} catch (err) {
|
||||
if (String(err.message || '').includes('UNIQUE')) {
|
||||
@@ -9181,20 +9245,16 @@ app.delete('/api/assets/:id', requireAssetOrAdmin, async (req, res) => {
|
||||
|
||||
await transaction.begin();
|
||||
|
||||
await new sql.Request(transaction)
|
||||
.input('assetId', sql.Int, assetId)
|
||||
.query(`
|
||||
DELETE links
|
||||
FROM AssetBorrowRequestLinks links
|
||||
INNER JOIN AssetBorrowRequests requests
|
||||
ON requests.BorrowId = links.BorrowId
|
||||
OR requests.BorrowId = links.ReturnId
|
||||
WHERE requests.AssetId = @assetId
|
||||
`);
|
||||
|
||||
const deleteResult = await new sql.Request(transaction)
|
||||
.input('assetId', sql.Int, assetId)
|
||||
.query('DELETE FROM AssetInventory OUTPUT DELETED.AssetId WHERE AssetId = @assetId');
|
||||
.query(`
|
||||
UPDATE AssetInventory WITH (UPDLOCK, HOLDLOCK)
|
||||
SET IsArchived = 1,
|
||||
ArchivedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()),
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
OUTPUT INSERTED.AssetId
|
||||
WHERE AssetId = @assetId AND IsArchived = 0
|
||||
`);
|
||||
|
||||
if (!deleteResult.recordset?.length) {
|
||||
await transaction.rollback();
|
||||
@@ -9203,7 +9263,7 @@ app.delete('/api/assets/:id', requireAssetOrAdmin, async (req, res) => {
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
res.json({ success: true, message: 'Asset deleted' });
|
||||
res.json({ success: true, message: 'Da xoa tai san khoi danh sach hien tai va giu nguyen lich su muon tra' });
|
||||
} catch (err) {
|
||||
try {
|
||||
await transaction.rollback();
|
||||
@@ -9214,6 +9274,36 @@ app.delete('/api/assets/:id', requireAssetOrAdmin, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/assets/archive-all', requireAssetOrAdmin, async (req, res) => {
|
||||
const transaction = new sql.Transaction(pool);
|
||||
|
||||
try {
|
||||
await transaction.begin();
|
||||
const result = await new sql.Request(transaction).query(`
|
||||
UPDATE AssetInventory WITH (UPDLOCK, HOLDLOCK)
|
||||
SET IsArchived = 1,
|
||||
ArchivedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()),
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
WHERE IsArchived = 0;
|
||||
SELECT @@ROWCOUNT AS ArchivedCount;
|
||||
`);
|
||||
await transaction.commit();
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Da xoa danh sach tai san hien tai va giu nguyen lich su muon tra',
|
||||
data: { archivedCount: Number(result.recordset?.[0]?.ArchivedCount) || 0 }
|
||||
});
|
||||
} catch (err) {
|
||||
try {
|
||||
await transaction.rollback();
|
||||
} catch (_rollbackErr) {
|
||||
// Ignore rollback errors when transaction already finished.
|
||||
}
|
||||
sendInternalError(res, err);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/assets/import', requireAssetOrAdmin, upload.single('file'), async (req, res) => {
|
||||
let incomingRows = [];
|
||||
let source = 'rows';
|
||||
@@ -9348,9 +9438,9 @@ app.post('/api/assets/import', requireAssetOrAdmin, upload.single('file'), async
|
||||
.input('notes', sql.NVarChar, row.notes)
|
||||
.input('createdBy', sql.Int, createdBy)
|
||||
.query(`
|
||||
MERGE AssetInventory AS target
|
||||
MERGE AssetInventory WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @assetCode AS AssetCode) AS source
|
||||
ON target.AssetCode = source.AssetCode
|
||||
ON target.AssetCode = source.AssetCode AND target.IsArchived = 0
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET
|
||||
AssetName = @assetName,
|
||||
@@ -9575,7 +9665,7 @@ app.get('/api/database/info', requireAdmin, async (req, res) => {
|
||||
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');
|
||||
const assets = await pool.request().query('SELECT COUNT(*) as Count FROM AssetInventory');
|
||||
const assets = await pool.request().query('SELECT COUNT(*) as Count FROM AssetInventory WHERE IsArchived = 0');
|
||||
const consumables = await pool.request().query('SELECT COUNT(*) as Count FROM ConsumableInventory');
|
||||
|
||||
res.json({
|
||||
|
||||
@@ -1185,3 +1185,104 @@ PRINT ' Password: admin';
|
||||
PRINT ' Role: admin';
|
||||
PRINT '';
|
||||
PRINT '========================================';
|
||||
|
||||
GO
|
||||
-- Asset archive migration: keep in sync with backend/asset-archive-schema.sql.
|
||||
-- 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;
|
||||
|
||||
GO
|
||||
|
||||
227
public/js/app.js
227
public/js/app.js
@@ -64,6 +64,9 @@ class AccountManager {
|
||||
this.applications = [];
|
||||
this.users = [];
|
||||
this.assets = [];
|
||||
this.archivedAssets = [];
|
||||
this.archivedAssetSearchTerm = '';
|
||||
this.archivingAssets = false;
|
||||
this.consumables = [];
|
||||
this.documents = [];
|
||||
this.roles = [];
|
||||
@@ -114,6 +117,7 @@ class AccountManager {
|
||||
this.assetBorrows = [];
|
||||
this.assetBorrowSearchTerm = '';
|
||||
this.assetBorrowTypeFilter = '';
|
||||
this.assetBorrowCatalogFilter = '';
|
||||
this.myBorrowedAssetSearchTerm = '';
|
||||
this.assetBorrowProductSearchTimer = undefined;
|
||||
this.assetBorrowProductItems = [];
|
||||
@@ -1694,6 +1698,26 @@ class AccountManager {
|
||||
} catch (err) {
|
||||
console.error('Fetch assets error:', err);
|
||||
}
|
||||
await this.fetchArchivedAssets();
|
||||
}
|
||||
|
||||
async fetchArchivedAssets() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/assets?archived=1`, {
|
||||
headers: this.getAuthHeaders(false),
|
||||
cache: 'no-store'
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) {
|
||||
throw new Error(data.message || 'Không tải được tài sản cũ');
|
||||
}
|
||||
this.archivedAssets = (Array.isArray(data.data) ? data.data : [])
|
||||
.map(asset => this.normalizeAssetComputedFields(asset));
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('Fetch archived assets error:', err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async fetchConsumables() {
|
||||
@@ -2786,7 +2810,7 @@ class AccountManager {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.assets
|
||||
return [...this.assets, ...(this.archivedAssets || [])]
|
||||
.map(asset => {
|
||||
const borrowerEntries = this.parseBorrowerEntries(asset?.Borrower);
|
||||
const matchedEntries = borrowerEntries.filter(entry => {
|
||||
@@ -2845,17 +2869,21 @@ class AccountManager {
|
||||
getFilteredAssetBorrows() {
|
||||
const search = String(this.assetBorrowSearchTerm || '').toLowerCase();
|
||||
const typeFilter = String(this.assetBorrowTypeFilter || '').trim().toLowerCase();
|
||||
const catalogFilter = String(this.assetBorrowCatalogFilter || '');
|
||||
const rows = Array.isArray(this.assetBorrows) ? this.assetBorrows : [];
|
||||
|
||||
return rows.filter(item => {
|
||||
const requestType = this.normalizeAssetRequestType(item.RequestType);
|
||||
const requestStatus = this.normalizeAssetRequestStatus(item.RequestStatus);
|
||||
const relatedReturnCount = this.parseNonNegativeInteger(item?.RelatedReturnCount, 0);
|
||||
if (requestType === 'borrow' && (requestStatus === 'returned' || relatedReturnCount > 0 || this.hasActiveReturnForBorrowRequest(item, rows))) {
|
||||
const isArchived = this.isArchivedAsset(item);
|
||||
if ((catalogFilter === 'archived' && !isArchived) || (catalogFilter === 'current' && isArchived)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const matchesType = !typeFilter || requestType === typeFilter;
|
||||
const remainingQuantity = this.parseNonNegativeInteger(item?.RemainingQuantity,
|
||||
Math.max(this.parseNonNegativeInteger(item?.BorrowQuantity, 0) - this.parseNonNegativeInteger(item?.ReturnedQuantity, 0), 0));
|
||||
const matchesType = !typeFilter || requestType === typeFilter
|
||||
|| (typeFilter === 'outstanding' && requestType === 'borrow' && requestStatus === 'approved' && remainingQuantity > 0);
|
||||
if (!matchesType) {
|
||||
return false;
|
||||
}
|
||||
@@ -3403,6 +3431,16 @@ class AccountManager {
|
||||
});
|
||||
}
|
||||
|
||||
isArchivedAsset(item) {
|
||||
return item?.IsArchived === true || Number(item?.IsArchived) === 1;
|
||||
}
|
||||
|
||||
getArchivedAssetBadgeHtml(item) {
|
||||
return this.isArchivedAsset(item)
|
||||
? '<div class="mt-1 text-[11px] font-bold text-amber-700">Tài sản cũ</div>'
|
||||
: '';
|
||||
}
|
||||
|
||||
async handleDocumentUpload(event) {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
@@ -4730,7 +4768,7 @@ class AccountManager {
|
||||
const borrowQuantity = this.parseNonNegativeInteger(item?.BorrowQuantity, 0);
|
||||
const remainingQuantity = this.parseNonNegativeInteger(item?.RemainingQuantity, Math.max(borrowQuantity - returnedQuantity, 0));
|
||||
const canCreateReturn = this.canCreateAssetReturnRequestFromBorrow(item);
|
||||
const returnProgressHtml = requestType === 'borrow' && returnedQuantity > 0 && statusMeta.value !== 'returned'
|
||||
const returnProgressHtml = requestType === 'borrow' && statusMeta.value === 'approved'
|
||||
? `<div class="mt-1 text-[11px] text-slate-500 whitespace-nowrap">Đã trả ${returnedQuantity}/${borrowQuantity}, còn ${remainingQuantity}</div>`
|
||||
: '';
|
||||
const detailActionHtml = `
|
||||
@@ -4763,6 +4801,7 @@ class AccountManager {
|
||||
<td class="px-4 py-3 text-sm text-slate-700">
|
||||
<div>${this.escapeHtml(assetName)}</div>
|
||||
${assetCode}
|
||||
${this.getArchivedAssetBadgeHtml(item)}
|
||||
</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600 whitespace-nowrap">
|
||||
<span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-bold whitespace-nowrap ${typeMeta.className}">${typeMeta.label}</span>
|
||||
@@ -4794,9 +4833,10 @@ class AccountManager {
|
||||
const borrowQuantity = this.parseNonNegativeInteger(item?.BorrowQuantity, 0);
|
||||
const returnedQuantity = this.parseNonNegativeInteger(item?.ReturnedQuantity, 0);
|
||||
const remainingQuantity = this.parseNonNegativeInteger(item?.RemainingQuantity, Math.max(borrowQuantity - returnedQuantity, 0));
|
||||
const relatedReturnCount = this.parseNonNegativeInteger(item?.RelatedReturnCount, 0);
|
||||
const availableReturnQuantity = this.parseNonNegativeInteger(item?.AvailableReturnQuantity,
|
||||
this.parseNonNegativeInteger(item?.RelatedReturnCount, 0) > 0 ? 0 : remainingQuantity);
|
||||
|
||||
return borrowQuantity > 0 && remainingQuantity > 0 && relatedReturnCount <= 0;
|
||||
return borrowQuantity > 0 && remainingQuantity > 0 && availableReturnQuantity > 0;
|
||||
}
|
||||
|
||||
canCurrentUserCancelAssetRequest(item) {
|
||||
@@ -4906,7 +4946,7 @@ class AccountManager {
|
||||
<tr class="hover:bg-slate-50/80 transition-colors">
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${pageInfo.start + index}</td>
|
||||
<td class="px-4 py-3 text-sm font-semibold text-slate-700">${this.escapeHtml(asset.AssetCode || '-')}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-700">${this.escapeHtml(asset.AssetName || '-')}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-700">${this.escapeHtml(asset.AssetName || '-')}${this.getArchivedAssetBadgeHtml(asset)}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-700 font-bold">${Number(asset.BorrowedQuantityByCurrentUser) || 0}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${this.escapeHtml(asset.Unit || '-')}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${this.escapeHtml(asset.Project || '-')}</td>
|
||||
@@ -4960,7 +5000,7 @@ class AccountManager {
|
||||
<tr class="hover:bg-slate-50/80 transition-colors">
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${pageInfo.start + index}</td>
|
||||
<td class="px-4 py-3 text-sm font-semibold text-slate-700">${this.escapeHtml(asset.AssetCode || '-')}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-700">${this.escapeHtml(asset.AssetName || '-')}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-700">${this.escapeHtml(asset.AssetName || '-')}${this.getArchivedAssetBadgeHtml(asset)}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-700 font-bold">${Number(asset.BorrowedQuantityByCurrentUser) || 0}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${this.escapeHtml(asset.Unit || '-')}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${this.escapeHtml(asset.Project || '-')}</td>
|
||||
@@ -5024,9 +5064,16 @@ class AccountManager {
|
||||
<div class="page-header flex items-center justify-between gap-4 mb-5 shrink-0">
|
||||
<div>
|
||||
<h1 class="text-2xl font-extrabold text-on-surface tracking-tight">Mượn/Trả tài sản</h1>
|
||||
<p class="text-sm text-on-surface-variant">Theo dõi trạng thái đơn mượn và đơn trả tài sản.</p>
|
||||
<p class="text-sm text-on-surface-variant">Lịch sử mượn/trả gồm cả tài sản cũ đã xóa khỏi danh mục.</p>
|
||||
</div>
|
||||
<div class="compact-page-actions flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
id="openArchivedAssetBorrowsBtn"
|
||||
class="border border-amber-300 text-amber-700 px-4 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 hover:bg-amber-50"
|
||||
>
|
||||
<span class="material-symbols-outlined text-base">history</span>
|
||||
Tài sản cũ còn mượn
|
||||
</button>
|
||||
<button
|
||||
id="addAssetBorrowRequestBtn"
|
||||
class="bg-primary text-on-primary px-4 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all active:scale-95 hover:bg-primary-dim"
|
||||
@@ -5056,13 +5103,22 @@ class AccountManager {
|
||||
|
||||
<div class="page-filters compact-page-filters asset-borrow-filter-bar flex items-center gap-3 mb-4 shrink-0">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="text-[10px] font-bold uppercase text-on-surface-variant">Danh mục</span>
|
||||
<span class="text-[10px] font-bold uppercase text-on-surface-variant">Đơn</span>
|
||||
<select id="assetBorrowTypeFilter" 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="" ${!this.assetBorrowTypeFilter ? 'selected' : ''}>Tất cả</option>
|
||||
<option value="outstanding" ${this.assetBorrowTypeFilter === 'outstanding' ? 'selected' : ''}>Còn đang mượn</option>
|
||||
<option value="borrow" ${this.assetBorrowTypeFilter === 'borrow' ? 'selected' : ''}>Mượn tài sản</option>
|
||||
<option value="return" ${this.assetBorrowTypeFilter === 'return' ? 'selected' : ''}>Trả tài sản</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<label for="assetBorrowCatalogFilter" class="text-[10px] font-bold uppercase text-on-surface-variant">Tài sản</label>
|
||||
<select id="assetBorrowCatalogFilter" 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="" ${!this.assetBorrowCatalogFilter ? 'selected' : ''}>Tất cả</option>
|
||||
<option value="archived" ${this.assetBorrowCatalogFilter === 'archived' ? 'selected' : ''}>Tài sản cũ</option>
|
||||
<option value="current" ${this.assetBorrowCatalogFilter === 'current' ? 'selected' : ''}>Danh mục hiện tại</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="compact-filter-search flex items-center gap-1.5 flex-1">
|
||||
<span class="text-[10px] font-bold uppercase text-on-surface-variant">Tìm kiếm</span>
|
||||
<input
|
||||
@@ -5216,7 +5272,7 @@ class AccountManager {
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-base font-extrabold text-slate-900">Chi tiết mượn/trả tài sản</h3>
|
||||
<div class="mt-1 flex flex-wrap items-center gap-2 text-xs text-slate-500 min-w-0">
|
||||
<span class="font-bold text-slate-700 break-words min-w-0">${this.escapeHtml(assetName)}</span>
|
||||
<span class="font-bold text-slate-700 break-words min-w-0">${this.escapeHtml(assetName)}${this.getArchivedAssetBadgeHtml(selected)}</span>
|
||||
<span class="inline-flex items-center px-2 py-0.5 rounded ${selectedTypeMeta.className}">${selectedTypeMeta.label}</span>
|
||||
<span class="inline-flex items-center px-2 py-0.5 rounded ${selectedStatusMeta.className}">${selectedStatusMeta.label}</span>
|
||||
</div>
|
||||
@@ -5266,11 +5322,12 @@ class AccountManager {
|
||||
}
|
||||
|
||||
setupAssetBorrowListeners() {
|
||||
this.setupArchivedAssetListeners();
|
||||
const typeFilter = document.getElementById('assetBorrowTypeFilter');
|
||||
if (typeFilter && typeFilter.dataset.boundChange !== 'true') {
|
||||
typeFilter.addEventListener('change', event => {
|
||||
const nextValue = String(event.target.value || '').trim().toLowerCase();
|
||||
this.assetBorrowTypeFilter = (nextValue === 'borrow' || nextValue === 'return')
|
||||
this.assetBorrowTypeFilter = (nextValue === 'borrow' || nextValue === 'return' || nextValue === 'outstanding')
|
||||
? nextValue
|
||||
: '';
|
||||
this.assetBorrowPage = 1;
|
||||
@@ -5279,6 +5336,16 @@ class AccountManager {
|
||||
typeFilter.dataset.boundChange = 'true';
|
||||
}
|
||||
|
||||
const catalogFilter = document.getElementById('assetBorrowCatalogFilter');
|
||||
if (catalogFilter && catalogFilter.dataset.boundChange !== 'true') {
|
||||
catalogFilter.addEventListener('change', event => {
|
||||
this.assetBorrowCatalogFilter = ['current', 'archived'].includes(event.target.value) ? event.target.value : '';
|
||||
this.assetBorrowPage = 1;
|
||||
this.renderAssetBorrowsTableBody();
|
||||
});
|
||||
catalogFilter.dataset.boundChange = 'true';
|
||||
}
|
||||
|
||||
const searchInput = document.getElementById('assetBorrowSearch');
|
||||
if (searchInput && searchInput.dataset.boundInput !== 'true') {
|
||||
searchInput.addEventListener('input', (event) => {
|
||||
@@ -5561,6 +5628,7 @@ class AccountManager {
|
||||
const dateLabel = typeMeta.value === 'return' ? 'Ngày trả' : 'Ngày mượn';
|
||||
const note = String(item?.RequestNote || '').trim();
|
||||
const requestId = Number(item?.BorrowId) || 0;
|
||||
const blockedArchivedBorrow = this.isArchivedAsset(item) && typeMeta.value === 'borrow';
|
||||
|
||||
return `
|
||||
<div class="rounded-lg border border-slate-200 bg-white p-3 space-y-2 shadow-sm">
|
||||
@@ -5571,12 +5639,14 @@ class AccountManager {
|
||||
<div class="text-xs text-slate-700 space-y-1">
|
||||
<div><span class="font-bold">Tên đầy đủ:</span> ${this.escapeHtml(item?.BorrowerName || '-')}</div>
|
||||
<div><span class="font-bold">Tên tài sản:</span> ${this.escapeHtml(item?.AssetCode || '')} ${item?.AssetCode ? '- ' : ''}${this.escapeHtml(item?.AssetName || '-')}</div>
|
||||
${this.getArchivedAssetBadgeHtml(item)}
|
||||
${blockedArchivedBorrow ? '<p class="text-amber-700">Tài sản đã xóa khỏi danh mục. Vui lòng từ chối hoặc hủy đơn mượn này.</p>' : ''}
|
||||
<div><span class="font-bold">Số lượng:</span> ${Number(item?.BorrowQuantity) || 0} ${this.escapeHtml(item?.Unit || '')}</div>
|
||||
<div><span class="font-bold">Ghi chú:</span> ${this.escapeHtml(note || '-')}</div>
|
||||
<div><span class="font-bold">${dateLabel}:</span> ${this.formatDateOnly(item?.BorrowDate)}</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 pt-1">
|
||||
<button class="asset-request-approve-btn flex-1 min-w-0 px-3 py-1.5 rounded-md bg-primary hover:bg-primary-dim text-on-primary text-xs font-bold whitespace-nowrap" data-request-id="${requestId}">Chấp nhận</button>
|
||||
${blockedArchivedBorrow ? '' : `<button class="asset-request-approve-btn flex-1 min-w-0 px-3 py-1.5 rounded-md bg-primary hover:bg-primary-dim text-on-primary text-xs font-bold whitespace-nowrap" data-request-id="${requestId}">Chấp nhận</button>`}
|
||||
<button class="asset-request-reject-btn flex-1 min-w-0 px-3 py-1.5 rounded-md bg-red-600 hover:bg-red-700 text-white text-xs font-bold whitespace-nowrap" data-request-id="${requestId}">Từ chối</button>
|
||||
<button class="asset-request-delete-btn flex-1 min-w-0 px-3 py-1.5 rounded-md bg-slate-700 hover:bg-slate-800 text-white text-xs font-bold whitespace-nowrap" data-request-id="${requestId}">Xóa đơn</button>
|
||||
</div>
|
||||
@@ -5732,17 +5802,22 @@ class AccountManager {
|
||||
}
|
||||
}
|
||||
|
||||
async confirmBulkAssetDelete(selectedCount) {
|
||||
async confirmBulkAssetDelete(selectedCount, archiveAll = false) {
|
||||
const modal = document.getElementById('bulkDeleteAssetsConfirmModal');
|
||||
const messageNode = document.getElementById('bulkDeleteAssetsConfirmMessage');
|
||||
const countNode = document.getElementById('bulkDeleteAssetsConfirmCount');
|
||||
const titleNode = document.getElementById('bulkDeleteAssetsConfirmTitle');
|
||||
const message = archiveAll
|
||||
? 'Xóa toàn bộ danh mục tài sản hiện tại để nhập dữ liệu mới? Lịch sử và số lượng còn đang mượn được giữ trong tài sản cũ. Dữ liệu nhập mới được quản lý riêng, kể cả khi trùng mã tài sản.'
|
||||
: `Xóa ${selectedCount} tài sản đã chọn khỏi danh mục hiện tại? Lịch sử mượn/trả và số lượng còn đang mượn vẫn được giữ trong tài sản cũ.`;
|
||||
|
||||
if (!modal || !messageNode || !countNode) {
|
||||
return window.confirm(`Bạn có chắc muốn xóa ${selectedCount} tài sản đã chọn?`);
|
||||
return window.confirm(message);
|
||||
}
|
||||
|
||||
countNode.textContent = String(selectedCount);
|
||||
messageNode.textContent = `Bạn có chắc muốn xóa ${selectedCount} tài sản đã chọn?`;
|
||||
messageNode.textContent = message;
|
||||
if (titleNode) titleNode.textContent = archiveAll ? 'Xóa danh mục hiện tại' : 'Xóa tài sản đã chọn';
|
||||
|
||||
if (this.pendingBulkAssetDeleteConfirmResolver) {
|
||||
this.resolveBulkAssetDeleteConfirm(false);
|
||||
@@ -6633,6 +6708,14 @@ class AccountManager {
|
||||
<p class="text-sm text-on-surface-variant">Theo dõi tài sản, kho và trạng thái sử dụng.</p>
|
||||
</div>
|
||||
<div class="asset-header-actions flex flex-wrap items-center gap-2">
|
||||
<button id="archiveAllAssetsBtn" class="border border-red-200 text-red-700 px-3 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 ${canManageAssets && this.assets.length ? 'hover:bg-red-50' : 'opacity-50 cursor-not-allowed'}" ${canManageAssets && this.assets.length ? '' : 'disabled'}>
|
||||
<span class="material-symbols-outlined text-base">archive</span>
|
||||
Xóa danh mục hiện tại
|
||||
</button>
|
||||
<button id="openArchivedAssetBorrowsBtn" class="border border-amber-300 text-amber-700 px-3 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 hover:bg-amber-50">
|
||||
<span class="material-symbols-outlined text-base">history</span>
|
||||
Tài sản cũ còn mượn
|
||||
</button>
|
||||
<button id="importAssetBtn" class="border border-slate-300 text-slate-700 px-3 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all active:scale-95 ${canManageAssets ? 'hover:bg-slate-100' : 'opacity-50 cursor-not-allowed'}" ${canManageAssets ? '' : 'disabled'}>
|
||||
<span class="material-symbols-outlined text-base">upload_file</span>
|
||||
Nhập Excel
|
||||
@@ -7069,6 +7152,112 @@ class AccountManager {
|
||||
}
|
||||
|
||||
await this.refreshAssetsUI();
|
||||
await this.refreshAssetBorrowsUI();
|
||||
}
|
||||
|
||||
setupArchivedAssetListeners() {
|
||||
const archiveButton = document.getElementById('archiveAllAssetsBtn');
|
||||
if (archiveButton && !archiveButton.dataset.boundClick) {
|
||||
archiveButton.addEventListener('click', () => this.handleArchiveAllAssets());
|
||||
archiveButton.dataset.boundClick = 'true';
|
||||
}
|
||||
const outstandingButton = document.getElementById('openArchivedAssetBorrowsBtn');
|
||||
if (outstandingButton && !outstandingButton.dataset.boundClick) {
|
||||
outstandingButton.addEventListener('click', () => this.openArchivedAssetBorrowsModal());
|
||||
outstandingButton.dataset.boundClick = 'true';
|
||||
}
|
||||
}
|
||||
|
||||
async handleArchiveAllAssets() {
|
||||
if (this.archivingAssets || !this.ensureAssetManagePermission('xóa danh mục tài sản')) return;
|
||||
this.archivingAssets = true;
|
||||
const button = document.getElementById('archiveAllAssetsBtn');
|
||||
if (button) button.disabled = true;
|
||||
try {
|
||||
const confirmed = await this.confirmBulkAssetDelete(this.assets.length, true);
|
||||
if (!confirmed) return;
|
||||
const response = await fetch(`${this.apiBase}/assets/archive-all`, {
|
||||
method: 'POST',
|
||||
headers: this.getAuthHeaders(false)
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) {
|
||||
this.notifyFailure(data.message || 'Xóa danh mục tài sản thất bại');
|
||||
return;
|
||||
}
|
||||
this.selectedAssetIds.clear();
|
||||
this.assetPage = 1;
|
||||
this.assetBorrowPage = 1;
|
||||
this.notifySuccess(`Đã chuyển ${Number(data.data?.archivedCount) || 0} tài sản sang dữ liệu cũ. Lịch sử mượn/trả được giữ lại.`);
|
||||
await this.refreshAssetsUI();
|
||||
await this.refreshAssetBorrowsUI();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
this.notifyFailure('Xóa danh mục tài sản thất bại');
|
||||
} finally {
|
||||
this.archivingAssets = false;
|
||||
const activeButton = document.getElementById('archiveAllAssetsBtn');
|
||||
if (activeButton) activeButton.disabled = !this.canCurrentUserManageAssets() || !this.assets.length;
|
||||
}
|
||||
}
|
||||
|
||||
getArchivedOutstandingAssets() {
|
||||
const search = String(this.archivedAssetSearchTerm || '').trim().toLowerCase();
|
||||
return (this.archivedAssets || []).map(asset => {
|
||||
const borrowerQuantity = this.parseBorrowerEntries(asset.Borrower)
|
||||
.reduce((sum, entry) => sum + this.parseNonNegativeInteger(entry.quantity, 0), 0);
|
||||
return {
|
||||
...asset,
|
||||
OutstandingQuantity: Math.max(borrowerQuantity, this.parseNonNegativeInteger(asset.ExportInPeriod, 0))
|
||||
};
|
||||
}).filter(asset => asset.OutstandingQuantity > 0 && (!search || [
|
||||
asset.AssetCode, asset.AssetName, asset.Model, asset.SerialNumber,
|
||||
this.formatBorrowerSummaryText(asset.Borrower), asset.Department, asset.Project, asset.Location
|
||||
].some(value => String(value || '').toLowerCase().includes(search))));
|
||||
}
|
||||
|
||||
renderArchivedAssetBorrowsTable() {
|
||||
const tableBody = document.getElementById('archivedAssetBorrowsTableBody');
|
||||
if (!tableBody) return;
|
||||
const rows = this.getArchivedOutstandingAssets();
|
||||
tableBody.innerHTML = rows.length ? rows.map(asset => `
|
||||
<tr class="border-b border-slate-100">
|
||||
<td class="px-4 py-3 text-sm text-slate-700">${this.escapeHtml(asset.AssetCode || '-')}<div class="text-[11px] text-slate-500">Hồ sơ cũ #${Number(asset.AssetId) || 0}</div></td>
|
||||
<td class="px-4 py-3 text-sm text-slate-700">${this.escapeHtml(asset.AssetName || '-')}<div class="text-[11px] text-slate-500">${this.escapeHtml(asset.SerialNumber || '')}</div></td>
|
||||
<td class="px-4 py-3 text-sm text-slate-700 whitespace-pre-line">${this.escapeHtml(this.formatBorrowerSummaryText(asset.Borrower) || 'Chưa có tên người mượn')}</td>
|
||||
<td class="px-4 py-3 text-sm font-bold text-slate-700">${asset.OutstandingQuantity}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-700">${this.escapeHtml(asset.Unit || '-')}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-700">${this.escapeHtml(asset.Project || asset.Department || '-')}</td>
|
||||
</tr>
|
||||
`).join('') : '<tr><td colspan="6" class="px-4 py-8 text-center text-sm text-slate-500">Không có tài sản cũ còn mượn phù hợp.</td></tr>';
|
||||
const count = document.getElementById('archivedAssetBorrowsCount');
|
||||
if (count) count.textContent = `${rows.length} hồ sơ tài sản cũ còn mượn`;
|
||||
}
|
||||
|
||||
async openArchivedAssetBorrowsModal() {
|
||||
const modal = document.getElementById('archivedAssetBorrowsModal');
|
||||
if (!modal) {
|
||||
this.notifyFailure('Không tìm thấy danh sách tài sản cũ');
|
||||
return;
|
||||
}
|
||||
if (!await this.fetchArchivedAssets()) {
|
||||
this.notifyFailure('Không tải được dữ liệu tài sản cũ. Vui lòng thử lại.');
|
||||
return;
|
||||
}
|
||||
this.archivedAssetSearchTerm = '';
|
||||
const search = document.getElementById('archivedAssetBorrowsSearch');
|
||||
if (search) {
|
||||
search.value = '';
|
||||
if (!search.dataset.boundInput) {
|
||||
search.addEventListener('input', event => {
|
||||
this.archivedAssetSearchTerm = event.target.value;
|
||||
this.renderArchivedAssetBorrowsTable();
|
||||
});
|
||||
search.dataset.boundInput = 'true';
|
||||
}
|
||||
}
|
||||
this.renderArchivedAssetBorrowsTable();
|
||||
modal.classList.add('open');
|
||||
}
|
||||
|
||||
setupAssetPagerListeners() {
|
||||
@@ -9030,6 +9219,7 @@ class AccountManager {
|
||||
}
|
||||
|
||||
setupAssetRowListeners() {
|
||||
this.setupArchivedAssetListeners();
|
||||
this.setupAssetSelectionListeners();
|
||||
const canManageAssets = this.canCurrentUserManageAssets();
|
||||
|
||||
@@ -9103,8 +9293,9 @@ class AccountManager {
|
||||
this.pendingDeleteAssetId = undefined;
|
||||
this.selectedAssetIds.delete(targetDeleteId);
|
||||
this.closeModals();
|
||||
this.notifySuccess('Xóa tài sản thành công');
|
||||
this.notifySuccess('Đã xóa khỏi danh mục. Lịch sử mượn/trả được giữ lại.');
|
||||
await this.refreshAssetsUI();
|
||||
await this.refreshAssetBorrowsUI();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
this.notifyFailure('Xóa tài sản thất bại');
|
||||
|
||||
@@ -1033,6 +1033,36 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Archived asset borrower balances, including imports and direct exports. -->
|
||||
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="archivedAssetBorrowsModal">
|
||||
<div class="modal-content bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden flex flex-col m-4" style="width:min(1100px, calc(100vw - 32px));max-height:calc(100vh - 32px);">
|
||||
<div class="px-6 py-4 border-b border-slate-100 bg-slate-50 flex items-center justify-between gap-3">
|
||||
<h3 class="text-base font-extrabold text-slate-800">Tài sản cũ còn mượn</h3>
|
||||
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-500" data-close-modal="archivedAssetBorrowsModal" aria-label="Đóng">
|
||||
<span class="material-symbols-outlined">close</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="px-6 py-4 border-b border-slate-100">
|
||||
<p class="text-sm text-slate-600">Số dư người mượn của tài sản đã xóa khỏi danh mục, gồm cả dữ liệu nhập Excel và xuất trực tiếp. Các hồ sơ trùng mã được theo dõi riêng.</p>
|
||||
<p class="mt-2 text-xs text-slate-500">Nếu có đơn mượn gốc, tạo đơn trả tại Mượn/Trả tài sản để ghi nhận vào hồ sơ cũ. Dữ liệu chỉ có số dư người mượn cần đối chiếu riêng, cùng với tồn kho danh mục mới.</p>
|
||||
<label for="archivedAssetBorrowsSearch" class="mt-3 block text-xs font-bold text-slate-600">Tìm tài sản hoặc người mượn</label>
|
||||
<input id="archivedAssetBorrowsSearch" class="mt-1 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Mã, tên, serial, người mượn, dự án...">
|
||||
</div>
|
||||
<div class="overflow-auto flex-1">
|
||||
<table class="w-full text-left border-collapse" style="min-width:780px;">
|
||||
<thead class="sticky top-0 bg-slate-50 text-xs font-bold text-slate-500">
|
||||
<tr><th class="px-4 py-3">Mã</th><th class="px-4 py-3">Tài sản</th><th class="px-4 py-3">Người mượn</th><th class="px-4 py-3">Còn mượn</th><th class="px-4 py-3">Đơn vị</th><th class="px-4 py-3">Dự án / Phòng ban</th></tr>
|
||||
</thead>
|
||||
<tbody id="archivedAssetBorrowsTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="px-6 py-4 border-t border-slate-100 flex items-center justify-between gap-3">
|
||||
<span id="archivedAssetBorrowsCount" class="text-xs text-slate-500"></span>
|
||||
<button type="button" class="px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg" data-close-modal="archivedAssetBorrowsModal">Đóng</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Delete Asset Modal -->
|
||||
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="deleteAssetModal">
|
||||
<div class="modal-content w-full max-w-md bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
|
||||
@@ -1041,7 +1071,7 @@
|
||||
<h3 class="text-base font-extrabold text-red-700">Xóa tài sản</h3>
|
||||
</div>
|
||||
<div class="p-6">
|
||||
<p class="text-sm text-slate-600 mb-6">Bạn có chắc muốn xóa tài sản <strong id="deleteAssetName">-</strong>? Hành động này không thể hoàn tác.</p>
|
||||
<p class="text-sm text-slate-600 mb-6">Xóa tài sản <strong id="deleteAssetName">-</strong> khỏi danh mục hiện tại? Lịch sử mượn/trả và số lượng còn đang mượn vẫn được giữ trong tài sản cũ.</p>
|
||||
<div class="flex gap-3">
|
||||
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg" data-close-modal="deleteAssetModal">Hủy</button>
|
||||
<button type="button" class="flex-1 px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-xs font-bold confirm-delete-asset">Xóa</button>
|
||||
@@ -1055,10 +1085,11 @@
|
||||
<div class="modal-content w-full max-w-md 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 bg-red-50 flex items-center gap-3">
|
||||
<span class="material-symbols-outlined text-red-600 text-2xl">warning</span>
|
||||
<h3 class="text-base font-extrabold text-red-700">Xóa tài sản đã chọn</h3>
|
||||
<h3 id="bulkDeleteAssetsConfirmTitle" class="text-base font-extrabold text-red-700">Xóa tài sản đã chọn</h3>
|
||||
</div>
|
||||
<div class="p-6">
|
||||
<p id="bulkDeleteAssetsConfirmMessage" class="text-sm text-slate-600 mb-6">Bạn có chắc muốn xóa các tài sản đã chọn?</p>
|
||||
<p class="text-xs text-slate-500 mb-4">Đơn mượn đang chờ của tài sản cũ không thể duyệt sau khi xóa; cần hủy hoặc từ chối. Đơn trả vẫn được xử lý trên hồ sơ cũ. Tồn kho dữ liệu mới cần đối chiếu riêng.</p>
|
||||
<div class="mb-4 rounded-lg border border-red-100 bg-red-50 px-3 py-2 text-xs text-red-700">
|
||||
Số lượng: <strong id="bulkDeleteAssetsConfirmCount">0</strong> tài sản
|
||||
</div>
|
||||
|
||||
222
test/asset-archive-routes.test.js
Normal file
222
test/asset-archive-routes.test.js
Normal file
@@ -0,0 +1,222 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const { createRequire } = require('node:module');
|
||||
|
||||
const serverPath = path.resolve(__dirname, '../backend/server.js');
|
||||
const serverSource = fs.readFileSync(serverPath, 'utf8');
|
||||
const serverRequire = createRequire(serverPath);
|
||||
|
||||
// Run the real route handlers with an isolated pool so these regressions do not
|
||||
// need credentials or alter a developer's inventory.
|
||||
function createFixture(answer = () => ({ recordset: [] })) {
|
||||
const queries = [];
|
||||
const transactions = [];
|
||||
class Request {
|
||||
constructor(transaction) {
|
||||
this.transaction = transaction;
|
||||
this.inputs = {};
|
||||
}
|
||||
input(name, _type, value) {
|
||||
this.inputs[name] = value;
|
||||
return this;
|
||||
}
|
||||
async query(query) {
|
||||
const call = { query, inputs: this.inputs, transaction: this.transaction };
|
||||
queries.push(call);
|
||||
return answer(call);
|
||||
}
|
||||
}
|
||||
class Transaction {
|
||||
constructor() { transactions.push(this); }
|
||||
async begin() { this.begun = true; }
|
||||
async commit() { this.committed = true; }
|
||||
async rollback() { this.rolledBack = true; }
|
||||
}
|
||||
const sql = { ...serverRequire('mssql'), Request, Transaction };
|
||||
const module = { exports: {} };
|
||||
const context = {
|
||||
require(name) { return name === 'mssql' ? sql : serverRequire(name); },
|
||||
module,
|
||||
exports: module.exports,
|
||||
__dirname: path.dirname(serverPath),
|
||||
__filename: serverPath,
|
||||
Buffer,
|
||||
URL,
|
||||
console,
|
||||
process: {
|
||||
env: {
|
||||
...process.env,
|
||||
NODE_ENV: 'test',
|
||||
DATA_ENCRYPTION_SECRET: 'test-only-archive-key-with-more-than-32-characters'
|
||||
},
|
||||
on() {}
|
||||
},
|
||||
testPool: { request: () => new Request() }
|
||||
};
|
||||
vm.runInNewContext(`${serverSource}
|
||||
pool = testPool;
|
||||
getUserDisplayNameById = async () => 'Borrower A';
|
||||
safeCreateSystemNotification = async () => {};
|
||||
ensureDepartmentExists = async () => {};
|
||||
syncAssetDepartmentsFromInventory = async () => {};
|
||||
syncAssetProjectsFromInventory = async () => {};
|
||||
`, context, { filename: serverPath });
|
||||
|
||||
async function invoke(method, routePath, overrides = {}) {
|
||||
const route = module.exports.app.router.stack.find(layer => (
|
||||
layer.route?.path === routePath && layer.route.methods[method]
|
||||
)).route;
|
||||
const handler = route.stack.at(-1).handle;
|
||||
const req = {
|
||||
params: {}, query: {}, body: {},
|
||||
user: { UserId: 1, Role: 'asset', FullName: 'Borrower A' },
|
||||
...overrides
|
||||
};
|
||||
const response = {
|
||||
statusCode: 200,
|
||||
status(value) { this.statusCode = value; return this; },
|
||||
json(value) { this.body = value; return this; }
|
||||
};
|
||||
await handler(req, response);
|
||||
return response;
|
||||
}
|
||||
return { invoke, queries, transactions };
|
||||
}
|
||||
|
||||
test('deleting an asset archives it without deleting any history or links', async () => {
|
||||
const fixture = createFixture(() => ({ recordset: [{ AssetId: 17 }] }));
|
||||
const response = await fixture.invoke('delete', '/api/assets/:id', { params: { id: '17' } });
|
||||
assert.equal(response.statusCode, 200);
|
||||
assert.equal(fixture.queries.length, 1);
|
||||
assert.match(fixture.queries[0].query, /SET IsArchived = 1/);
|
||||
assert.match(fixture.queries[0].query, /WHERE AssetId = @assetId AND IsArchived = 0/);
|
||||
assert.doesNotMatch(fixture.queries[0].query, /DELETE\s/i);
|
||||
assert.equal(fixture.queries[0].inputs.assetId, 17);
|
||||
assert.equal(fixture.transactions[0].committed, true);
|
||||
});
|
||||
|
||||
test('bulk archive changes only active inventory and reports the committed count', async () => {
|
||||
const fixture = createFixture(() => ({ recordset: [{ ArchivedCount: 42 }] }));
|
||||
const response = await fixture.invoke('post', '/api/assets/archive-all');
|
||||
assert.equal(response.body.data.archivedCount, 42);
|
||||
assert.equal(fixture.queries.length, 1);
|
||||
assert.match(fixture.queries[0].query, /WITH \(UPDLOCK, HOLDLOCK\)/);
|
||||
assert.match(fixture.queries[0].query, /WHERE IsArchived = 0/);
|
||||
assert.doesNotMatch(fixture.queries[0].query, /DELETE\s|AssetBorrowRequestLinks/i);
|
||||
assert.equal(fixture.transactions[0].committed, true);
|
||||
});
|
||||
|
||||
test('current and archived inventory are selected separately', async () => {
|
||||
const fixture = createFixture();
|
||||
await fixture.invoke('get', '/api/assets');
|
||||
await fixture.invoke('get', '/api/assets', { query: { archived: '1' } });
|
||||
assert.equal(fixture.queries[0].inputs.isArchived, 0);
|
||||
assert.equal(fixture.queries[1].inputs.isArchived, 1);
|
||||
for (const call of fixture.queries) {
|
||||
assert.match(call.query, /WHERE IsArchived = @isArchived/);
|
||||
assert.match(call.query, /IsArchived, ArchivedDate/);
|
||||
}
|
||||
});
|
||||
|
||||
test('new borrow requests cannot target an archived asset', async () => {
|
||||
const fixture = createFixture(() => ({ recordset: [{
|
||||
AssetId: 17, IsArchived: true, Quantity: 10, EndingBalance: 7,
|
||||
Borrower: 'Borrower A - so luong: 3'
|
||||
}] }));
|
||||
const response = await fixture.invoke('post', '/api/asset-borrows', {
|
||||
body: { assetId: 17, requestType: 'borrow', quantity: 1 }
|
||||
});
|
||||
assert.equal(response.statusCode, 409);
|
||||
assert.equal(fixture.transactions[0].rolledBack, true);
|
||||
assert.equal(fixture.queries.length, 1);
|
||||
assert.match(fixture.queries[0].query, /UPDLOCK, HOLDLOCK/);
|
||||
});
|
||||
|
||||
test('pending borrow approval is blocked after its inventory was archived', async () => {
|
||||
const fixture = createFixture(() => ({ recordset: [{
|
||||
BorrowId: 21, AssetId: 17, IsArchived: true,
|
||||
RequestType: 'borrow', RequestStatus: 'pending', BorrowQuantity: 1
|
||||
}] }));
|
||||
const response = await fixture.invoke('post', '/api/asset-borrows/:id/process', {
|
||||
params: { id: '21' }, body: { action: 'approved' }
|
||||
});
|
||||
assert.equal(response.statusCode, 409);
|
||||
assert.equal(fixture.transactions[0].rolledBack, true);
|
||||
assert.equal(fixture.queries.length, 1);
|
||||
});
|
||||
|
||||
test('return creation for an archived borrow retains the original asset and link', async () => {
|
||||
const fixture = createFixture(({ query }) => {
|
||||
if (query.includes('SELECT TOP 1')) return { recordset: [{
|
||||
BorrowId: 21, AssetId: 17, IsArchived: true, RequestType: 'borrow',
|
||||
RequestStatus: 'approved', BorrowerName: 'Borrower A', BorrowQuantity: 3,
|
||||
ReturnedQuantity: 1, ActiveReturnQuantity: 1, Unit: 'cai', CreatedBy: 1,
|
||||
Borrower: 'Borrower A - so luong: 2'
|
||||
}] };
|
||||
if (query.includes('SCOPE_IDENTITY')) return { recordset: [{ BorrowId: 22 }] };
|
||||
return { recordset: [] };
|
||||
});
|
||||
const response = await fixture.invoke('post', '/api/asset-borrows/:id/return', {
|
||||
params: { id: '21' }
|
||||
});
|
||||
assert.equal(response.statusCode, 200);
|
||||
const insert = fixture.queries.find(call => call.query.includes('INSERT INTO AssetBorrowRequests'));
|
||||
assert.equal(insert.inputs.assetId, 17);
|
||||
assert.equal(insert.inputs.borrowQuantity, 2);
|
||||
const link = fixture.queries.find(call => call.query.includes('INSERT INTO AssetBorrowRequestLinks'));
|
||||
assert.equal(link.inputs.borrowId, 21);
|
||||
assert.equal(link.inputs.returnId, 22);
|
||||
assert.equal(fixture.transactions[0].committed, true);
|
||||
});
|
||||
|
||||
test('approving an archived return updates only its original inventory and borrow', async () => {
|
||||
const fixture = createFixture(({ query }) => {
|
||||
if (query.includes('SELECT TOP 1')) return { recordset: [{
|
||||
BorrowId: 22, AssetId: 17, IsArchived: true, RequestType: 'return',
|
||||
RequestStatus: 'pending', BorrowerName: 'Borrower A', BorrowQuantity: 2,
|
||||
Quantity: 10, ImportInPeriod: 0, ExportInPeriod: 2, EndingBalance: 8,
|
||||
NewQuantity: 8, UsedQuantity: 0, Borrower: 'Borrower A - so luong: 2', CreatedBy: 1
|
||||
}] };
|
||||
if (query.includes('FROM AssetBorrowRequestLinks links')) {
|
||||
return { recordset: [{ BorrowId: 21, Quantity: 2, BorrowQuantity: 3, ReturnedQuantity: 1 }] };
|
||||
}
|
||||
return { recordset: [] };
|
||||
});
|
||||
const response = await fixture.invoke('post', '/api/asset-borrows/:id/process', {
|
||||
params: { id: '22' }, body: { action: 'approved' }
|
||||
});
|
||||
assert.equal(response.statusCode, 200);
|
||||
const inventoryWrites = fixture.queries.filter(call => call.query.includes('UPDATE AssetInventory'));
|
||||
assert.equal(inventoryWrites.length, 1);
|
||||
assert.equal(inventoryWrites[0].inputs.assetId, 17);
|
||||
assert.equal(inventoryWrites[0].inputs.borrower, null);
|
||||
const borrowWrite = fixture.queries.find(call => call.query.includes('SET ReturnedQuantity'));
|
||||
assert.equal(borrowWrite.inputs.borrowId, 21);
|
||||
assert.equal(borrowWrite.inputs.quantity, 2);
|
||||
assert.equal(fixture.transactions[0].committed, true);
|
||||
});
|
||||
|
||||
test('import matches the active version of a reused asset code only', async () => {
|
||||
const fixture = createFixture(() => ({ recordset: [{ MergeAction: 'INSERT' }] }));
|
||||
const response = await fixture.invoke('post', '/api/assets/import', {
|
||||
body: { rows: [{ assetCode: 'SAME-CODE', assetName: 'Replacement drill', model: 'D2', quantity: 5 }] }
|
||||
});
|
||||
assert.equal(response.statusCode, 200);
|
||||
assert.equal(response.body.data.inserted, 1);
|
||||
const merge = fixture.queries.find(call => call.query.includes('MERGE AssetInventory'));
|
||||
assert.match(merge.query, /WITH \(HOLDLOCK\)/);
|
||||
assert.match(merge.query, /ON target.AssetCode = source.AssetCode AND target.IsArchived = 0/);
|
||||
assert.equal(merge.inputs.assetCode, 'SAME-CODE');
|
||||
});
|
||||
|
||||
test('editing an archived asset cannot modify the historical inventory', async () => {
|
||||
const fixture = createFixture();
|
||||
const response = await fixture.invoke('put', '/api/assets/:id', {
|
||||
params: { id: '17' }, body: { assetCode: 'SAME-CODE', assetName: 'Modified', model: 'D2' }
|
||||
});
|
||||
assert.equal(response.statusCode, 404);
|
||||
assert.match(fixture.queries[0].query, /WHERE AssetId = @assetId AND IsArchived = 0/);
|
||||
});
|
||||
258
test/asset-archive-schema.test.js
Normal file
258
test/asset-archive-schema.test.js
Normal file
@@ -0,0 +1,258 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { randomBytes } = require('node:crypto');
|
||||
const sql = require('mssql');
|
||||
const { ensureAssetArchiveSchema } = require('../backend/asset-archive-schema');
|
||||
|
||||
// Explicit opt-in to a disposable, local SQL Server. Never read .env or reuse the
|
||||
// application's database configuration. The runner creates its own database.
|
||||
const integrationEnabled = process.env.ACCMANAGER_ARCHIVE_SQL_TEST === '1';
|
||||
const integrationOptions = {
|
||||
skip: integrationEnabled ? false : 'Set ACCMANAGER_ARCHIVE_SQL_TEST=1 to run against disposable local SQL Server',
|
||||
timeout: 120_000
|
||||
};
|
||||
|
||||
async function withTestDatabase(run) {
|
||||
const password = process.env.ACCMANAGER_ARCHIVE_TEST_SQL_PASSWORD;
|
||||
const port = Number(process.env.ACCMANAGER_ARCHIVE_TEST_SQL_PORT || 14339);
|
||||
assert.ok(password, 'ACCMANAGER_ARCHIVE_TEST_SQL_PASSWORD must be explicitly set');
|
||||
assert.ok(Number.isInteger(port) && port > 0 && port < 65536, 'Invalid local test SQL port');
|
||||
const database = `AccManagerArchiveTest_${Date.now()}_${randomBytes(6).toString('hex')}`;
|
||||
const config = {
|
||||
server: '127.0.0.1',
|
||||
port,
|
||||
user: 'sa',
|
||||
password,
|
||||
database: 'master',
|
||||
options: { encrypt: false, trustServerCertificate: true, enableArithAbort: true },
|
||||
pool: { min: 0, max: 1, idleTimeoutMillis: 1000 },
|
||||
connectionTimeout: 15_000,
|
||||
requestTimeout: 30_000
|
||||
};
|
||||
const admin = new sql.ConnectionPool(config);
|
||||
let created = false;
|
||||
let pool;
|
||||
try {
|
||||
await admin.connect();
|
||||
await admin.request().query(`CREATE DATABASE [${database}]`);
|
||||
created = true;
|
||||
pool = await new sql.ConnectionPool({ ...config, database }).connect();
|
||||
await run(pool);
|
||||
} finally {
|
||||
if (pool) await pool.close();
|
||||
try {
|
||||
if (created) {
|
||||
// This name is generated above, never accepted from the environment.
|
||||
assert.match(database, /^AccManagerArchiveTest_\d+_[a-f0-9]{12}$/);
|
||||
await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE`);
|
||||
await admin.request().query(`DROP DATABASE [${database}]`);
|
||||
}
|
||||
} finally {
|
||||
await admin.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const legacySchema = `
|
||||
CREATE TABLE dbo.AssetInventory (
|
||||
AssetId INT IDENTITY PRIMARY KEY,
|
||||
AssetCode NVARCHAR(100) NOT NULL UNIQUE,
|
||||
AssetName NVARCHAR(255) NOT NULL,
|
||||
Quantity INT NOT NULL DEFAULT 0,
|
||||
EndingBalance INT NOT NULL DEFAULT 0
|
||||
);
|
||||
-- Exercise removal of both an auto-named constraint and a standalone index.
|
||||
CREATE UNIQUE INDEX LegacyAssetCodeIndex ON dbo.AssetInventory(AssetCode);
|
||||
CREATE TABLE dbo.AssetBorrowRequests (
|
||||
BorrowId INT IDENTITY PRIMARY KEY,
|
||||
AssetId INT NOT NULL REFERENCES dbo.AssetInventory(AssetId) ON DELETE CASCADE,
|
||||
RequestType NVARCHAR(20) NOT NULL,
|
||||
RequestStatus NVARCHAR(20) NOT NULL,
|
||||
BorrowerName NVARCHAR(100) NOT NULL,
|
||||
BorrowQuantity INT NOT NULL,
|
||||
ReturnedQuantity INT NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE dbo.AssetBorrowRequestLinks (
|
||||
LinkId INT IDENTITY PRIMARY KEY,
|
||||
BorrowId INT NOT NULL REFERENCES dbo.AssetBorrowRequests(BorrowId),
|
||||
ReturnId INT NOT NULL REFERENCES dbo.AssetBorrowRequests(BorrowId),
|
||||
Quantity INT NOT NULL
|
||||
);
|
||||
CREATE TABLE dbo.AssetExportHistory (
|
||||
ExportHistoryId INT IDENTITY PRIMARY KEY,
|
||||
AssetId INT NOT NULL REFERENCES dbo.AssetInventory(AssetId) ON DELETE CASCADE,
|
||||
ExportQuantity INT NOT NULL
|
||||
);
|
||||
CREATE TABLE dbo.AssetDamageDisposalHistory (
|
||||
DamageHistoryId INT IDENTITY PRIMARY KEY,
|
||||
AssetId INT NOT NULL REFERENCES dbo.AssetInventory(AssetId) ON DELETE CASCADE,
|
||||
ActionQuantity INT NOT NULL
|
||||
);
|
||||
`;
|
||||
|
||||
async function historySnapshot(pool) {
|
||||
return (await pool.request().query(`
|
||||
SELECT * FROM dbo.AssetBorrowRequests ORDER BY BorrowId;
|
||||
SELECT * FROM dbo.AssetBorrowRequestLinks ORDER BY LinkId;
|
||||
SELECT * FROM dbo.AssetExportHistory ORDER BY ExportHistoryId;
|
||||
SELECT * FROM dbo.AssetDamageDisposalHistory ORDER BY DamageHistoryId;
|
||||
`)).recordsets;
|
||||
}
|
||||
|
||||
test('SQL Server migration preserves asset history across inventory replacement', integrationOptions, async t => {
|
||||
await withTestDatabase(async pool => {
|
||||
await pool.request().batch(legacySchema);
|
||||
await pool.request().query(`
|
||||
INSERT dbo.AssetInventory (AssetCode, AssetName, Quantity, EndingBalance) VALUES
|
||||
('SHARED-CODE', N'Original drill', 10, 6),
|
||||
('EXPORT-ONLY', N'Exported asset', 4, 3),
|
||||
('DISPOSAL-ONLY', N'Disposed asset', 3, 2);
|
||||
INSERT dbo.AssetBorrowRequests
|
||||
(AssetId, RequestType, RequestStatus, BorrowerName, BorrowQuantity, ReturnedQuantity)
|
||||
VALUES (1, 'borrow', 'approved', N'Loan owner', 5, 1),
|
||||
(1, 'return', 'approved', N'Loan owner', 1, 0);
|
||||
INSERT dbo.AssetBorrowRequestLinks (BorrowId, ReturnId, Quantity) VALUES (1, 2, 1);
|
||||
INSERT dbo.AssetExportHistory (AssetId, ExportQuantity) VALUES (2, 1);
|
||||
INSERT dbo.AssetDamageDisposalHistory (AssetId, ActionQuantity) VALUES (3, 1);
|
||||
`);
|
||||
const originalHistory = await historySnapshot(pool);
|
||||
|
||||
await t.test('legacy migration defaults existing assets to active and preserves every history row', async () => {
|
||||
await ensureAssetArchiveSchema(pool);
|
||||
const assets = (await pool.request().query('SELECT IsArchived, ArchivedDate FROM dbo.AssetInventory')).recordset;
|
||||
assert.equal(assets.length, 3);
|
||||
assert.ok(assets.every(asset => asset.IsArchived === false && asset.ArchivedDate === null));
|
||||
assert.deepEqual(await historySnapshot(pool), originalHistory);
|
||||
const keys = (await pool.request().query(`
|
||||
SELECT delete_referential_action AS action
|
||||
FROM sys.foreign_keys
|
||||
WHERE referenced_object_id = OBJECT_ID('dbo.AssetInventory')
|
||||
`)).recordset;
|
||||
assert.equal(keys.length, 3);
|
||||
assert.ok(keys.every(key => key.action === 0), 'All asset history foreign keys must prevent cascading deletes');
|
||||
});
|
||||
|
||||
await t.test('archiving inventory retains original asset identity and outstanding loan quantity', async () => {
|
||||
await pool.request().query(`
|
||||
UPDATE dbo.AssetInventory
|
||||
SET IsArchived = 1, ArchivedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
WHERE IsArchived = 0;
|
||||
`);
|
||||
assert.deepEqual(await historySnapshot(pool), originalHistory);
|
||||
const result = await pool.request().query(`
|
||||
SELECT br.BorrowId, ai.AssetCode, ai.AssetName, ai.IsArchived, ai.ArchivedDate,
|
||||
br.BorrowQuantity - br.ReturnedQuantity AS OutstandingQuantity
|
||||
FROM dbo.AssetBorrowRequests br
|
||||
JOIN dbo.AssetInventory ai ON ai.AssetId = br.AssetId
|
||||
WHERE br.RequestType = 'borrow' AND br.RequestStatus = 'approved'
|
||||
AND br.BorrowQuantity > br.ReturnedQuantity;
|
||||
SELECT COUNT(*) AS ActiveCount FROM dbo.AssetInventory WHERE IsArchived = 0;
|
||||
`);
|
||||
assert.equal(result.recordsets[1][0].ActiveCount, 0);
|
||||
assert.equal(result.recordset.length, 1);
|
||||
assert.equal(result.recordset[0].OutstandingQuantity, 4);
|
||||
assert.equal(result.recordset[0].AssetName, 'Original drill');
|
||||
assert.equal(result.recordset[0].IsArchived, true);
|
||||
assert.ok(result.recordset[0].ArchivedDate instanceof Date);
|
||||
});
|
||||
|
||||
await t.test('same-code replacement receives a new identity without relinking old history', async () => {
|
||||
const inserted = await pool.request().query(`
|
||||
INSERT dbo.AssetInventory (AssetCode, AssetName, Quantity, EndingBalance)
|
||||
OUTPUT INSERTED.AssetId, INSERTED.IsArchived
|
||||
VALUES ('SHARED-CODE', N'Replacement drill', 20, 20);
|
||||
`);
|
||||
assert.notEqual(inserted.recordset[0].AssetId, 1);
|
||||
assert.equal(inserted.recordset[0].IsArchived, false);
|
||||
assert.deepEqual(await historySnapshot(pool), originalHistory);
|
||||
const assets = (await pool.request().query(`
|
||||
SELECT ai.AssetName, ai.IsArchived, COUNT(br.BorrowId) AS HistoryCount
|
||||
FROM dbo.AssetInventory ai
|
||||
LEFT JOIN dbo.AssetBorrowRequests br ON br.AssetId = ai.AssetId
|
||||
WHERE ai.AssetCode = 'SHARED-CODE'
|
||||
GROUP BY ai.AssetName, ai.IsArchived ORDER BY ai.IsArchived DESC;
|
||||
`)).recordset;
|
||||
assert.deepEqual(assets, [
|
||||
{ AssetName: 'Original drill', IsArchived: true, HistoryCount: 2 },
|
||||
{ AssetName: 'Replacement drill', IsArchived: false, HistoryCount: 0 }
|
||||
]);
|
||||
});
|
||||
|
||||
await t.test('active duplicates remain forbidden while repeated migration accepts archived duplicates', async () => {
|
||||
await assert.rejects(pool.request().query(`
|
||||
INSERT dbo.AssetInventory (AssetCode, AssetName) VALUES ('SHARED-CODE', N'Duplicate');
|
||||
`), error => [2601, 2627].includes(error.number));
|
||||
await ensureAssetArchiveSchema(pool);
|
||||
const indexes = (await pool.request().query(`
|
||||
SELECT name, has_filter AS HasFilter
|
||||
FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.AssetInventory')
|
||||
AND is_unique = 1 AND is_primary_key = 0;
|
||||
`)).recordset;
|
||||
assert.deepEqual(indexes, [{ name: 'UX_AssetInventory_ActiveAssetCode', HasFilter: true }]);
|
||||
assert.deepEqual(await historySnapshot(pool), originalHistory);
|
||||
});
|
||||
|
||||
await t.test('physical deletion cannot cascade into loan, export, or disposal history', async () => {
|
||||
for (const assetId of [1, 2, 3]) {
|
||||
await assert.rejects(pool.request().input('id', sql.Int, assetId).query(`
|
||||
DELETE dbo.AssetInventory WHERE AssetId = @id;
|
||||
`), error => error.number === 547);
|
||||
}
|
||||
assert.deepEqual(await historySnapshot(pool), originalHistory);
|
||||
});
|
||||
|
||||
await t.test('returning an old loan updates only its archived asset ledger', async () => {
|
||||
const transaction = new sql.Transaction(pool);
|
||||
await transaction.begin();
|
||||
try {
|
||||
await new sql.Request(transaction).query(`
|
||||
UPDATE dbo.AssetInventory SET EndingBalance = EndingBalance + 2
|
||||
WHERE AssetId = (SELECT AssetId FROM dbo.AssetBorrowRequests WHERE BorrowId = 1);
|
||||
UPDATE dbo.AssetBorrowRequests SET ReturnedQuantity = ReturnedQuantity + 2 WHERE BorrowId = 1;
|
||||
INSERT dbo.AssetBorrowRequests
|
||||
(AssetId, RequestType, RequestStatus, BorrowerName, BorrowQuantity)
|
||||
VALUES (1, 'return', 'approved', N'Loan owner', 2);
|
||||
DECLARE @returnId INT = SCOPE_IDENTITY();
|
||||
INSERT dbo.AssetBorrowRequestLinks (BorrowId, ReturnId, Quantity) VALUES (1, @returnId, 2);
|
||||
`);
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
const result = await pool.request().query(`
|
||||
SELECT AssetName, EndingBalance FROM dbo.AssetInventory
|
||||
WHERE AssetCode = 'SHARED-CODE' ORDER BY IsArchived DESC;
|
||||
SELECT BorrowQuantity - ReturnedQuantity AS OutstandingQuantity
|
||||
FROM dbo.AssetBorrowRequests WHERE BorrowId = 1;
|
||||
SELECT SUM(Quantity) AS LinkedReturnedQuantity FROM dbo.AssetBorrowRequestLinks WHERE BorrowId = 1;
|
||||
`);
|
||||
assert.deepEqual(result.recordset, [
|
||||
{ AssetName: 'Original drill', EndingBalance: 8 },
|
||||
{ AssetName: 'Replacement drill', EndingBalance: 20 }
|
||||
]);
|
||||
assert.equal(result.recordsets[1][0].OutstandingQuantity, 2);
|
||||
assert.equal(result.recordsets[2][0].LinkedReturnedQuantity, 3);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('SQL Server archive migration rolls back partial DDL if active codes are already duplicated', integrationOptions, async () => {
|
||||
await withTestDatabase(async pool => {
|
||||
await pool.request().query(`
|
||||
CREATE TABLE dbo.AssetInventory (
|
||||
AssetId INT IDENTITY PRIMARY KEY,
|
||||
AssetCode NVARCHAR(100) NOT NULL
|
||||
);
|
||||
INSERT dbo.AssetInventory (AssetCode) VALUES ('DUPLICATE'), ('DUPLICATE');
|
||||
`);
|
||||
await assert.rejects(ensureAssetArchiveSchema(pool));
|
||||
const result = await pool.request().query(`
|
||||
SELECT COL_LENGTH('dbo.AssetInventory', 'IsArchived') AS ArchiveColumn,
|
||||
COL_LENGTH('dbo.AssetInventory', 'ArchivedDate') AS DateColumn;
|
||||
SELECT COUNT(*) AS AssetCount FROM dbo.AssetInventory;
|
||||
`);
|
||||
assert.deepEqual(result.recordset[0], { ArchiveColumn: null, DateColumn: null });
|
||||
assert.equal(result.recordsets[1][0].AssetCount, 2);
|
||||
});
|
||||
});
|
||||
173
test/asset-archive-ui.test.js
Normal file
173
test/asset-archive-ui.test.js
Normal file
@@ -0,0 +1,173 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const source = fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8');
|
||||
|
||||
function fixture({ allowed = true, confirmed = true, responseSuccess = true } = {}) {
|
||||
const requests = [];
|
||||
const refreshed = [];
|
||||
const notifications = [];
|
||||
const button = { disabled: false };
|
||||
const fetch = async (url, options) => {
|
||||
requests.push({ url, options });
|
||||
return { ok: responseSuccess, json: async () => ({ success: responseSuccess, data: { archivedCount: 2 } }) };
|
||||
};
|
||||
const document = {
|
||||
addEventListener() {},
|
||||
getElementById: id => id === 'archiveAllAssetsBtn' ? button : null
|
||||
};
|
||||
const context = vm.createContext({ document, window: { fetch }, fetch, console });
|
||||
vm.runInContext(`${source}\napp = Object.create(AccountManager.prototype); globalThis.manager = app;`, context);
|
||||
const manager = context.manager;
|
||||
Object.assign(manager, {
|
||||
apiBase: '/api',
|
||||
assets: [{ AssetId: 1 }, { AssetId: 2 }],
|
||||
archivedAssets: [],
|
||||
assetBorrows: [],
|
||||
selectedAssetIds: new Set([1, 2]),
|
||||
canCurrentUserManageAssets: () => allowed,
|
||||
ensureAssetManagePermission: () => allowed,
|
||||
confirmBulkAssetDelete: async (count, all) => {
|
||||
assert.equal(count, 2);
|
||||
assert.equal(all, true);
|
||||
return confirmed;
|
||||
},
|
||||
refreshAssetsUI: async () => { refreshed.push('assets'); manager.assets = []; },
|
||||
refreshAssetBorrowsUI: async () => { refreshed.push('borrows'); },
|
||||
notifySuccess: message => notifications.push(message),
|
||||
notifyFailure: message => notifications.push(message),
|
||||
notifyWarning: message => notifications.push(message)
|
||||
});
|
||||
return { manager, requests, refreshed, notifications, button };
|
||||
}
|
||||
|
||||
function borrow(BorrowId, overrides = {}) {
|
||||
return {
|
||||
BorrowId, AssetId: BorrowId, AssetCode: 'SAME-CODE', AssetName: 'Máy đo',
|
||||
RequestType: 'borrow', RequestStatus: 'approved', BorrowQuantity: 5,
|
||||
ReturnedQuantity: 0, RemainingQuantity: 5, IsArchived: false,
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
test('all history retains completed loans and partial loans with related returns', () => {
|
||||
const { manager } = fixture();
|
||||
manager.assetBorrows = [
|
||||
borrow(1),
|
||||
borrow(2, { RelatedReturnCount: 1, ReturnedQuantity: 2, RemainingQuantity: 3 }),
|
||||
borrow(3, { RequestStatus: 'returned', ReturnedQuantity: 5, RemainingQuantity: 0 }),
|
||||
borrow(4, { RequestType: 'return' })
|
||||
];
|
||||
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
test('outstanding loans include archived, partial, and pending-return loans, excluding other statuses', () => {
|
||||
const { manager } = fixture();
|
||||
manager.assetBorrowTypeFilter = 'outstanding';
|
||||
manager.assetBorrows = [
|
||||
borrow(1),
|
||||
borrow(2, { IsArchived: true, ReturnedQuantity: 2, RemainingQuantity: 3, RelatedReturnCount: 1 }),
|
||||
borrow(3, { IsArchived: 1, RelatedReturnCount: 1, AvailableReturnQuantity: 0 }),
|
||||
borrow(4, { RequestStatus: 'pending' }),
|
||||
borrow(5, { RequestStatus: 'rejected' }),
|
||||
borrow(6, { RequestStatus: 'returned' }),
|
||||
borrow(7, { RemainingQuantity: 0 }),
|
||||
borrow(8, { RequestType: 'return' })
|
||||
];
|
||||
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [1, 2, 3]);
|
||||
manager.assetBorrowCatalogFilter = 'archived';
|
||||
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [2, 3]);
|
||||
manager.assetBorrowCatalogFilter = 'current';
|
||||
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [1]);
|
||||
manager.assetBorrowSearchTerm = 'missing';
|
||||
assert.equal(manager.getFilteredAssetBorrows().length, 0);
|
||||
});
|
||||
|
||||
test('partial archived loans permit another return only for quantity not reserved by pending returns', () => {
|
||||
const { manager } = fixture();
|
||||
const partial = borrow(1, { IsArchived: true, RelatedReturnCount: 1, ReturnedQuantity: 2, RemainingQuantity: 3, AvailableReturnQuantity: 3 });
|
||||
assert.equal(manager.canCreateAssetReturnRequestFromBorrow(partial), true);
|
||||
assert.equal(manager.canCreateAssetReturnRequestFromBorrow({ ...partial, AvailableReturnQuantity: 0 }), false);
|
||||
assert.equal(manager.canCreateAssetReturnRequestFromBorrow({ ...partial, RequestStatus: 'pending' }), false);
|
||||
assert.match(manager.getArchivedAssetBadgeHtml(partial), /Tài sản cũ/);
|
||||
});
|
||||
|
||||
test('legacy borrower summaries remain visible without any borrow requests or current assets', () => {
|
||||
const { manager } = fixture();
|
||||
manager.assets = [];
|
||||
manager.archivedAssets = [
|
||||
{ AssetId: 1, AssetCode: 'REUSED', Borrower: [{ name: 'An', quantity: 2 }], ExportInPeriod: 2, IsArchived: true },
|
||||
{ AssetId: 2, AssetCode: 'REUSED', Borrower: '', ExportInPeriod: 3, IsArchived: true },
|
||||
{ AssetId: 3, AssetCode: 'DONE', Borrower: '', ExportInPeriod: 0, IsArchived: true }
|
||||
];
|
||||
assert.deepEqual(Array.from(manager.getArchivedOutstandingAssets(), row => row.AssetId), [1, 2]);
|
||||
manager.archivedAssetSearchTerm = 'An';
|
||||
assert.deepEqual(Array.from(manager.getArchivedOutstandingAssets(), row => row.AssetId), [1]);
|
||||
manager.getCurrentUserBorrowerNameKeys = () => ['an'];
|
||||
assert.deepEqual(Array.from(manager.getCurrentUserBorrowedAssets(), row => [row.AssetId, row.BorrowedQuantityByCurrentUser]), [[1, 2]]);
|
||||
});
|
||||
|
||||
test('same-code current and archived assets remain separate in my borrowed assets', () => {
|
||||
const { manager } = fixture();
|
||||
manager.getCurrentUserBorrowerNameKeys = () => ['an'];
|
||||
manager.assets = [{ AssetId: 2, AssetCode: 'REUSED', Borrower: [{ name: 'An', quantity: 1 }] }];
|
||||
manager.archivedAssets = [{ AssetId: 1, AssetCode: 'REUSED', Borrower: [{ name: 'An', quantity: 3 }], IsArchived: true }];
|
||||
assert.deepEqual(Array.from(manager.getCurrentUserBorrowedAssets(), row => [row.AssetId, row.BorrowedQuantityByCurrentUser]), [[2, 1], [1, 3]]);
|
||||
});
|
||||
|
||||
test('archive all requires confirmation, calls archive endpoint once and refreshes both datasets', async () => {
|
||||
const { manager, requests, refreshed, button } = fixture();
|
||||
await manager.handleArchiveAllAssets();
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0].url, '/api/assets/archive-all');
|
||||
assert.equal(requests[0].options.method, 'POST');
|
||||
assert.deepEqual(refreshed, ['assets', 'borrows']);
|
||||
assert.equal(manager.selectedAssetIds.size, 0);
|
||||
assert.equal(manager.assetPage, 1);
|
||||
assert.equal(manager.archivingAssets, false);
|
||||
assert.equal(button.disabled, true, 'Empty current catalog cannot be archived again');
|
||||
});
|
||||
|
||||
test('cancel or missing permission leaves the catalog untouched', async () => {
|
||||
for (const options of [{ confirmed: false }, { allowed: false }]) {
|
||||
const { manager, requests, refreshed } = fixture(options);
|
||||
await manager.handleArchiveAllAssets();
|
||||
assert.equal(requests.length, 0);
|
||||
assert.equal(refreshed.length, 0);
|
||||
assert.equal(manager.selectedAssetIds.size, 2);
|
||||
assert.equal(manager.assets.length, 2);
|
||||
}
|
||||
});
|
||||
|
||||
test('failed archive preserves current selection and supports retry', async () => {
|
||||
const { manager, requests, refreshed, notifications, button } = fixture({ responseSuccess: false });
|
||||
await manager.handleArchiveAllAssets();
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(refreshed.length, 0);
|
||||
assert.equal(manager.selectedAssetIds.size, 2);
|
||||
assert.equal(manager.archivingAssets, false);
|
||||
assert.equal(button.disabled, false);
|
||||
assert.match(notifications[0], /thất bại/);
|
||||
});
|
||||
|
||||
test('archive double clicks issue one request while confirmation is pending', async () => {
|
||||
const { manager, requests } = fixture();
|
||||
let resolveConfirmation;
|
||||
manager.confirmBulkAssetDelete = () => new Promise(resolve => { resolveConfirmation = resolve; });
|
||||
const pending = manager.handleArchiveAllAssets();
|
||||
await manager.handleArchiveAllAssets();
|
||||
resolveConfirmation(true);
|
||||
await pending;
|
||||
assert.equal(requests.length, 1);
|
||||
});
|
||||
|
||||
test('archived pending borrows cannot be approved, while archived returns can', () => {
|
||||
const { manager } = fixture();
|
||||
const pending = borrow(1, { RequestStatus: 'pending', IsArchived: true });
|
||||
assert.doesNotMatch(manager.buildPendingAssetRequestCardHtml(pending), /asset-request-approve-btn/);
|
||||
assert.match(manager.buildPendingAssetRequestCardHtml(pending), /asset-request-reject-btn/);
|
||||
assert.match(manager.buildPendingAssetRequestCardHtml({ ...pending, RequestType: 'return' }), /asset-request-approve-btn/);
|
||||
});
|
||||
Reference in New Issue
Block a user