update file tài sản
This commit is contained in:
@@ -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({
|
||||
|
||||
Reference in New Issue
Block a user