update export request
This commit is contained in:
131
backend/asset-export-browser.test.js
Normal file
131
backend/asset-export-browser.test.js
Normal file
@@ -0,0 +1,131 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { spawn } = require('node:child_process');
|
||||
const { createExportSqlFixture } = require('./asset-export-sql-fixture');
|
||||
|
||||
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
class Browser {
|
||||
constructor(url) { this.socket = new WebSocket(url); this.nextId = 0; this.pending = new Map(); this.errors = []; }
|
||||
async open() {
|
||||
await new Promise((resolve, reject) => { this.socket.addEventListener('open', resolve, { once: true }); this.socket.addEventListener('error', reject, { once: true }); });
|
||||
this.socket.addEventListener('message', event => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.method === 'Runtime.exceptionThrown') this.errors.push(message.params.exceptionDetails);
|
||||
const pending = this.pending.get(message.id); if (!pending) return;
|
||||
this.pending.delete(message.id); clearTimeout(pending.timer);
|
||||
if (message.error) pending.reject(new Error(message.error.message)); else pending.resolve(message.result);
|
||||
});
|
||||
}
|
||||
send(method, params = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = ++this.nextId;
|
||||
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Browser timeout: ${method}`)); }, 15000);
|
||||
this.pending.set(id, { resolve, reject, timer }); this.socket.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
}
|
||||
async evaluate(expression) {
|
||||
const result = await this.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
|
||||
if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description || result.exceptionDetails.text);
|
||||
return result.result?.value;
|
||||
}
|
||||
async until(expression) {
|
||||
for (let i = 0; i < 100; i++) { if (await this.evaluate(expression)) return; await delay(100); }
|
||||
throw new Error(`Browser state timeout: ${expression}`);
|
||||
}
|
||||
}
|
||||
|
||||
test('Chrome submits project export proposals, approves/rejects, isolates creators and displays saved files on desktop/mobile', {
|
||||
skip: process.env.ACCMANAGER_EXPORT_BROWSER_TEST !== '1' ? 'Set ACCMANAGER_EXPORT_BROWSER_TEST=1 for isolated Chrome and SQL checks' : false,
|
||||
timeout: 120000
|
||||
}, async () => {
|
||||
const f = await createExportSqlFixture();
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const output = path.join(root, 'output/asset-exports'); fs.mkdirSync(output, { recursive: true });
|
||||
f.app.get('/api/auth/session', (req, res) => res.json({ success: true, user: { ...req.user,
|
||||
FullName: { 1: 'Nguyễn An', 2: 'Trần Bình', 3: 'Quản lý kho' }[req.user.UserId] } }));
|
||||
f.app.get('/api/asset-projects', (_req, res) => res.json({ success: true, data: [
|
||||
{ ProjectId: 1, ProjectName: 'Dự án A' }, { ProjectId: 2, ProjectName: 'Dự án B' }
|
||||
] }));
|
||||
f.app.use('/api', (_req, res) => res.json({ success: true, data: [], unreadCount: 0, pagination: { total: 0, totalPages: 1 } }));
|
||||
f.app.get('/test-xlsx.js', (_req, res) => res.sendFile(require.resolve('xlsx/dist/xlsx.full.min.js')));
|
||||
f.app.get('/test-notiflix.js', (_req, res) => res.type('js').send('window.Notiflix={Notify:{init(){},success(){},failure(){},warning(){}}};'));
|
||||
f.app.get('/pages/index.html', (_req, res) => res.type('html').send(fs.readFileSync(path.join(root, 'public/pages/index.html'), 'utf8')
|
||||
.replace('https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js', '/test-xlsx.js')
|
||||
.replace('https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js', '/test-notiflix.js')));
|
||||
f.app.use(require('express').static(path.join(root, 'public')));
|
||||
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'accmanager-export-chrome-'));
|
||||
const chrome = spawn(process.env.ACCMANAGER_TEST_CHROME || 'C:/Program Files/Google/Chrome/Application/chrome.exe', [
|
||||
'--headless=new', '--remote-debugging-port=0', `--user-data-dir=${profile}`, '--no-first-run', '--no-default-browser-check', '--hide-scrollbars', 'about:blank'
|
||||
], { stdio: 'ignore', windowsHide: true });
|
||||
let client;
|
||||
try {
|
||||
const portFile = path.join(profile, 'DevToolsActivePort');
|
||||
for (let i = 0; i < 100 && !fs.existsSync(portFile); i++) await delay(100);
|
||||
const port = Number(fs.readFileSync(portFile, 'utf8').split('\n')[0]);
|
||||
const targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json();
|
||||
client = new Browser(targets.find(target => target.type === 'page').webSocketDebuggerUrl); await client.open();
|
||||
await client.send('Runtime.enable'); await client.send('Page.enable'); await client.send('Network.enable');
|
||||
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
|
||||
await client.send('Page.navigate', { url: `${f.origin}/pages/index.html#assets` });
|
||||
await client.until('typeof app !== "undefined" && app?.assets?.length === 3 && !!document.getElementById("borrowAssetBtn")');
|
||||
await client.evaluate(`document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.getElementById('borrowAssetBtn').click()`);
|
||||
await client.until('document.getElementById("borrowAssetModal").classList.contains("open")');
|
||||
assert.equal(await client.evaluate('document.getElementById("borrowAssetUserInput").value'), 'Nguyễn An');
|
||||
await client.evaluate('document.getElementById("borrowAssetProjectInput").value="Dự án A"; document.getElementById("borrowQuantityInput").value="2"; document.getElementById("addBorrowProjectBtn").click(); document.querySelector("#borrowAdditionalProjects select").value="Dự án B"; document.querySelector("#borrowAdditionalProjects input").value="1"; document.getElementById("borrowAssetForm").requestSubmit()');
|
||||
await client.until('app.currentPage === "asset-exports" && !app.assetExportLoading && app.assetExportRequests.length === 1');
|
||||
assert.equal(await client.evaluate('document.querySelectorAll(".process-asset-export").length'), 0);
|
||||
assert.equal((await f.pool.request().query('SELECT EndingBalance FROM AssetInventory WHERE AssetId = 1')).recordset[0].EndingBalance, 10);
|
||||
// Existing batch form remains available to ordinary users.
|
||||
await client.evaluate('location.hash="#assets"');
|
||||
await client.until('!!document.getElementById("borrowAssetBtn")');
|
||||
await client.evaluate(`document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.querySelector('.asset-row-checkbox[data-asset-id="2"]').click(); document.getElementById('borrowAssetBtn').click()`);
|
||||
await client.until('document.getElementById("batchAssetExportModal").classList.contains("open")');
|
||||
await client.evaluate('const project=document.getElementById("batchAssetExportCommonProject"); project.value="Dự án A"; project.dispatchEvent(new Event("change")); document.getElementById("batchAssetExportForm").requestSubmit()');
|
||||
await client.until('app.currentPage === "asset-exports" && !app.assetExportLoading && app.assetExportRequests.length === 2');
|
||||
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '3', 'x-test-role': 'asset' } });
|
||||
await client.send('Page.reload');
|
||||
await client.until('typeof app !== "undefined" && app?.currentUser?.Role === "asset" && !app.assetExportLoading && document.querySelectorAll(".process-asset-export").length === 4');
|
||||
await client.evaluate('document.querySelector(".process-asset-export[data-action=approved]").click()');
|
||||
await client.until('document.getElementById("assetExportProcessModal").classList.contains("open")');
|
||||
await client.evaluate('document.getElementById("assetExportProcessForm").requestSubmit()');
|
||||
await client.until('!app.assetExportProcessing && app.assetExportRequests.some(row=>row.RequestStatus === "approved")');
|
||||
assert.equal((await f.pool.request().query('SELECT EndingBalance FROM AssetInventory WHERE AssetId = 1')).recordset[0].EndingBalance, 9);
|
||||
await client.evaluate('document.querySelector(".process-asset-export[data-action=rejected]").click()');
|
||||
await client.until('document.getElementById("assetExportProcessModal").classList.contains("open")');
|
||||
await client.evaluate('document.getElementById("assetExportRejectReason").value="Điều chỉnh số lượng theo dự án"; document.getElementById("assetExportProcessForm").requestSubmit()');
|
||||
await client.until('!app.assetExportProcessing && app.assetExportRequests.some(row=>row.RequestStatus === "rejected")');
|
||||
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '1', 'x-test-role': 'user' } });
|
||||
await client.send('Page.reload');
|
||||
await client.until('typeof app !== "undefined" && app?.currentUser?.Role === "user" && !app.assetExportLoading && app.assetExportRequests.length === 2');
|
||||
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'requests.png'), Buffer.from(result.data, 'base64')));
|
||||
await client.evaluate('document.querySelector(".view-asset-export-document").click()');
|
||||
await client.until('document.getElementById("assetExportPreviewContent").textContent.includes("Dự án A")');
|
||||
await client.evaluate('document.querySelector("[data-close-modal=assetExportPreviewModal]").click(); app.downloadBlobFile=(blob,name)=>{window.savedDownload={size:blob.size,name}}; document.querySelector(".download-asset-export-document").click()');
|
||||
await client.until('window.savedDownload?.size > 1000');
|
||||
// A failed reload clears stale rows and offers a useful retry.
|
||||
await client.evaluate('window.originalExportFetch=window.fetch; window.fetch=(url,options)=>String(url).includes("asset-export-requests") ? Promise.resolve({ok:false,json:async()=>({success:false,message:"Không tải được danh sách thử nghiệm"})}) : originalExportFetch(url,options); document.getElementById("refreshAssetExportsBtn").click()');
|
||||
await client.until('!app.assetExportLoading && !!app.assetExportLoadError');
|
||||
assert.equal(await client.evaluate('app.assetExportRequests.length'), 0);
|
||||
await client.evaluate('window.fetch=window.originalExportFetch; document.getElementById("refreshAssetExportsBtn").click()');
|
||||
await client.until('!app.assetExportLoading && app.assetExportRequests.length === 2');
|
||||
await client.evaluate('document.getElementById("assetExportHistoryTab").click()');
|
||||
assert.equal(await client.evaluate('!!document.getElementById("assetExportHistoryModal")'), false);
|
||||
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'desktop.png'), Buffer.from(result.data, 'base64')));
|
||||
await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
|
||||
await delay(250);
|
||||
assert.equal(await client.evaluate('document.documentElement.scrollWidth <= innerWidth + 1'), true);
|
||||
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'mobile.png'), Buffer.from(result.data, 'base64')));
|
||||
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '2', 'x-test-role': 'user' } });
|
||||
await client.send('Page.reload');
|
||||
await client.until('typeof app !== "undefined" && app?.currentUser?.UserId === 2 && !app.assetExportLoading && !!document.getElementById("assetExportsTableBody")');
|
||||
assert.equal(await client.evaluate('app.assetExportRequests.length'), 0);
|
||||
assert.deepEqual(client.errors, []);
|
||||
} finally {
|
||||
if (client) client.socket.close();
|
||||
chrome.kill();
|
||||
await f.cleanup();
|
||||
}
|
||||
});
|
||||
89
backend/asset-export-requests-sql.test.js
Normal file
89
backend/asset-export-requests-sql.test.js
Normal file
@@ -0,0 +1,89 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const XLSX = require('xlsx');
|
||||
const { createExportSqlFixture } = require('./asset-export-sql-fixture');
|
||||
|
||||
test('SQL project export approvals preserve stock, ownership, documents, return isolation and concurrent decisions', {
|
||||
skip: process.env.ACCMANAGER_EXPORT_SQL_TEST !== '1' ? 'Set ACCMANAGER_EXPORT_SQL_TEST=1 for a disposable database' : false,
|
||||
timeout: 120000
|
||||
}, async () => {
|
||||
const f = await createExportSqlFixture();
|
||||
try {
|
||||
const items = [{ assetId: 1, allocations: [{ projectName: 'Dự án A', quantity: 2 }, { projectName: 'Dự án B', quantity: 3 }] },
|
||||
{ assetId: 2, allocations: [{ projectName: 'Dự án A', quantity: 2 }] }];
|
||||
const stock = async id => (await f.pool.request().query(`SELECT * FROM AssetInventory WHERE AssetId = ${id}`)).recordset[0];
|
||||
const count = async table => (await f.pool.request().query(`SELECT COUNT(*) AS total FROM ${table}`)).recordset[0].total;
|
||||
const create = (rows = items, user = 1) => f.request('/asset-export-requests', { user, method: 'POST', body: {
|
||||
items: rows, note: 'Cấp tài sản vào dự án', createdBy: 2, borrowerName: 'Tên giả mạo', requestStatus: 'approved'
|
||||
} });
|
||||
const process = (id, action = 'approved', extra = {}) => f.request(`/asset-export-requests/${id}/process`, {
|
||||
role: 'asset', user: 3, method: 'POST', body: { action, ...extra }
|
||||
});
|
||||
const created = await create();
|
||||
assert.equal(created.status, 201); assert.equal(created.data.RequestStatus, 'pending');
|
||||
assert.equal(created.data.CreatedBy, 1); assert.equal(created.data.RequesterName, 'Nguyễn An');
|
||||
assert.equal((await stock(1)).EndingBalance, 10); assert.equal(await count('AssetExportDocuments'), 0);
|
||||
const id = created.data.ExportRequestId;
|
||||
assert.equal((await f.request(`/asset-export-requests/${id}/process`, { method: 'POST', body: { action: 'approved' } })).status, 403);
|
||||
assert.equal((await f.request('/asset-export-requests', { user: 2 })).data.length, 0);
|
||||
assert.equal((await f.request('/asset-export-requests', { user: 3, role: 'admin' })).data.length, 1);
|
||||
// Existing privileged export endpoints remain privileged.
|
||||
assert.equal((await f.request('/assets/1/export', { method: 'POST', body: items[0] })).status, 403);
|
||||
const approved = await process(id);
|
||||
assert.equal(approved.status, 200); assert.equal(approved.data.RequestStatus, 'approved');
|
||||
assert.equal((await stock(1)).EndingBalance, 5); assert.equal((await stock(1)).ExportInPeriod, 5);
|
||||
assert.equal((await stock(1)).Borrower, null); assert.equal((await stock(2)).EndingBalance, 3);
|
||||
assert.equal(await count('AssetBorrowRequests'), 0); assert.equal(await count('AssetExportHistory'), 3);
|
||||
const allocations = JSON.parse((await stock(1)).ProjectAllocations);
|
||||
assert.deepEqual(allocations.map(row => [row.projectName, row.quantity, row.allocationType]), [['Dự án A', 2, 'export'], ['Dự án B', 3, 'export']]);
|
||||
assert.equal((await f.request('/asset-export-history', { user: 2 })).data.length, 0);
|
||||
assert.equal((await f.request('/asset-export-history')).data.length, 3);
|
||||
const docId = approved.data.ExportDocumentId;
|
||||
const preview = await f.request(`/asset-export-documents/${docId}`);
|
||||
assert.equal(preview.status, 200); assert.equal(preview.data.snapshot.requesterName, 'Nguyễn An');
|
||||
assert.equal(preview.data.snapshot.exportedByName, 'Quản lý kho');
|
||||
const downloaded = await f.request(`/asset-export-documents/${docId}/download`);
|
||||
assert.equal(downloaded.status, 200);
|
||||
assert.deepEqual(downloaded.buffer, Buffer.from(approved.document.contentBase64, 'base64'));
|
||||
const workbook = XLSX.read(downloaded.buffer); assert.ok(workbook.Sheets.ycxvt);
|
||||
assert.equal((await f.request(`/asset-export-documents/${docId}`, { user: 2 })).status, 404);
|
||||
assert.equal((await f.request(`/asset-export-documents/${docId}/download`, { user: 2 })).status, 404);
|
||||
assert.equal((await process(id)).status, 409); assert.equal((await stock(1)).EndingBalance, 5);
|
||||
// A user cannot return the permanent allocation through the loan API.
|
||||
assert.equal((await f.request('/asset-borrows', { method: 'POST', body: { assetId: 1, requestType: 'return', quantity: 1 } })).status, 400);
|
||||
// Borrow and return two pieces; the five permanent pieces stay issued.
|
||||
const borrowed = await f.request('/asset-borrows', { method: 'POST', body: { assetId: 1, requestType: 'borrow', quantity: 2 } });
|
||||
const borrowId = borrowed.data.borrowId;
|
||||
assert.equal((await f.request(`/asset-borrows/${borrowId}/process`, { user: 3, role: 'asset', method: 'POST', body: { action: 'approved' } })).status, 200);
|
||||
assert.equal((await stock(1)).EndingBalance, 3);
|
||||
const returned = await f.request(`/asset-borrows/${borrowId}/return`, { method: 'POST', body: { quantity: 2 } });
|
||||
assert.equal((await f.request(`/asset-borrows/${returned.data.borrowId}/process`, { user: 3, role: 'asset', method: 'POST', body: { action: 'approved' } })).status, 200);
|
||||
assert.equal((await stock(1)).EndingBalance, 5); assert.equal((await stock(1)).ExportInPeriod, 5);
|
||||
assert.deepEqual(JSON.parse((await stock(1)).ProjectAllocations), allocations);
|
||||
// Rejection never consumes inventory; approval rechecks current stock.
|
||||
const rejected = await create([{ assetId: 1, projectName: 'Dự án C', quantity: 1 }], 2);
|
||||
assert.equal((await process(rejected.data.ExportRequestId, 'rejected')).status, 400);
|
||||
assert.equal((await process(rejected.data.ExportRequestId, 'rejected', { rejectReason: 'Chưa phù hợp' })).status, 200);
|
||||
assert.equal((await stock(1)).EndingBalance, 5);
|
||||
const a = await create([{ assetId: 3, projectName: 'Dự án A', quantity: 3 }]);
|
||||
const b = await create([{ assetId: 3, projectName: 'Dự án B', quantity: 3 }], 2);
|
||||
const races = await Promise.all([process(a.data.ExportRequestId), process(b.data.ExportRequestId)]);
|
||||
assert.deepEqual(races.map(row => row.status).sort(), [200, 400]); assert.equal((await stock(3)).EndingBalance, 1);
|
||||
const same = await create([{ assetId: 3, projectName: 'Dự án C', quantity: 1 }]);
|
||||
assert.deepEqual((await Promise.all([process(same.data.ExportRequestId), process(same.data.ExportRequestId)])).map(row => row.status).sort(), [200, 409]);
|
||||
assert.equal((await stock(3)).EndingBalance, 0);
|
||||
// Failure in history after file/stock writes rolls the entire approval back.
|
||||
const failing = await create([{ assetId: 1, projectName: 'FAIL', quantity: 1 }]);
|
||||
const documentsBefore = await count('AssetExportDocuments');
|
||||
await f.pool.request().query("ALTER TABLE AssetExportHistory ADD CONSTRAINT CK_ExportTest_Failure CHECK (ProjectName <> 'FAIL')");
|
||||
assert.equal((await process(failing.data.ExportRequestId)).status, 500);
|
||||
assert.equal((await stock(1)).EndingBalance, 5); assert.equal(await count('AssetExportDocuments'), documentsBefore);
|
||||
assert.equal((await f.request('/asset-export-requests')).data.find(row => row.ExportRequestId === failing.data.ExportRequestId).RequestStatus, 'pending');
|
||||
// An archived line prevents all other lines in that approval from being issued.
|
||||
const archived = await create([{ assetId: 1, projectName: 'A', quantity: 1 }, { assetId: 2, projectName: 'A', quantity: 1 }]);
|
||||
await f.pool.request().query('UPDATE AssetInventory SET IsArchived = 1 WHERE AssetId = 2');
|
||||
assert.equal((await process(archived.data.ExportRequestId)).status, 404);
|
||||
assert.equal((await stock(1)).EndingBalance, 5); assert.equal(await count('AssetExportDocuments'), documentsBefore);
|
||||
assert.equal((await f.request(`/asset-export-documents/${docId}/download`)).buffer.equals(downloaded.buffer), true);
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
176
backend/asset-export-requests.js
Normal file
176
backend/asset-export-requests.js
Normal file
@@ -0,0 +1,176 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const express = require('express');
|
||||
const { normalizeExportAllocations } = require('./asset-project-allocations');
|
||||
|
||||
async function ensureAssetExportRequestSchema(pool) {
|
||||
await pool.request().batch(fs.readFileSync(path.join(__dirname, 'asset-export-requests.sql'), 'utf8'));
|
||||
}
|
||||
|
||||
function normalizeExportItems(rawItems) {
|
||||
if (!Array.isArray(rawItems) || !rawItems.length || rawItems.length > 100) {
|
||||
throw new Error('Vui lòng chọn từ 1 đến 100 tài sản.');
|
||||
}
|
||||
const seen = new Set();
|
||||
const items = rawItems.map(row => {
|
||||
const assetId = Number(row?.assetId);
|
||||
if (!Number.isSafeInteger(assetId) || assetId <= 0 || assetId > 2147483647) throw new Error('Mã tài sản không hợp lệ.');
|
||||
if (seen.has(assetId)) throw new Error('Mỗi tài sản chỉ được xuất hiện một lần trong phiếu.');
|
||||
seen.add(assetId);
|
||||
return { assetId, allocations: normalizeExportAllocations(row) };
|
||||
});
|
||||
if (items.reduce((sum, item) => sum + item.allocations.length, 0) > 100) {
|
||||
throw new Error('Một phiếu chỉ hỗ trợ tối đa 100 dòng tài sản / dự án.');
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
function createAssetExportWorkflow({ getPool, sql, requireManage, getRequesterRole, getUserIdFromRequest,
|
||||
getUserDisplayNameById, prepareAssetExport, performAssetExport, sendInternalError, notifyProcessed, notifyCreated }) {
|
||||
const router = express.Router();
|
||||
const canManage = req => ['admin', 'asset'].includes(getRequesterRole(req));
|
||||
const serialize = row => ({ ...row, Items: JSON.parse(row.ItemsJson), ItemsJson: undefined });
|
||||
const fail = (statusCode, message) => { throw Object.assign(new Error(message), { statusCode }); };
|
||||
async function handleError(transaction, res, err) {
|
||||
if (transaction) {
|
||||
try { await transaction.rollback(); } catch { /* Preserve the original failure. */ }
|
||||
}
|
||||
if (err.statusCode) return res.status(err.statusCode).json({ success: false, message: err.message });
|
||||
return sendInternalError(res, err);
|
||||
}
|
||||
|
||||
async function loadPlans(transaction, items, note) {
|
||||
const assets = new Map();
|
||||
// Use the same order for overlapping requests so approvals cannot overdraw stock.
|
||||
for (const { assetId } of [...items].sort((a, b) => a.assetId - b.assetId)) {
|
||||
const result = await new sql.Request(transaction).input('assetId', sql.Int, assetId).query(`
|
||||
SELECT TOP 1 AssetId, AssetCode, AssetName, Quantity, ImportInPeriod, ExportInPeriod,
|
||||
EndingBalance, NewQuantity, UsedQuantity, Custodian, Borrower, ProjectAllocations,
|
||||
Model, SerialNumber, Unit, Department, Notes
|
||||
FROM AssetInventory WITH (UPDLOCK, HOLDLOCK)
|
||||
WHERE AssetId = @assetId AND IsArchived = 0
|
||||
`);
|
||||
if (!result.recordset?.[0]) fail(404, `Tài sản #${assetId} không còn trong danh mục hiện tại.`);
|
||||
assets.set(assetId, result.recordset[0]);
|
||||
}
|
||||
return items.map(item => prepareAssetExport(assets.get(item.assetId), item.allocations, note));
|
||||
}
|
||||
|
||||
async function createRequest(req, res, singleAssetId) {
|
||||
let transaction;
|
||||
try {
|
||||
let items;
|
||||
try {
|
||||
items = normalizeExportItems(singleAssetId === undefined ? req.body?.items : [{ ...req.body, assetId: singleAssetId }]);
|
||||
} catch (err) { fail(400, err.message); }
|
||||
const createdBy = getUserIdFromRequest(req);
|
||||
const requesterName = String(await getUserDisplayNameById(createdBy) || req.user?.FullName || req.user?.Username || '').trim();
|
||||
if (!createdBy || !requesterName || requesterName.length > 100) fail(400, 'Không xác định được người đề xuất hợp lệ.');
|
||||
const note = String(req.body?.note || '').trim() || null;
|
||||
if (note && note.length > 1000) fail(400, 'Ghi chú xuất tối đa 1000 ký tự.');
|
||||
transaction = new sql.Transaction(getPool());
|
||||
await transaction.begin();
|
||||
const plans = await loadPlans(transaction, items, note);
|
||||
// Preserve the requested descriptions even if the catalog is later edited or archived.
|
||||
const snapshot = plans.map(plan => ({ assetId: plan.asset.AssetId, assetCode: plan.asset.AssetCode,
|
||||
assetName: plan.asset.AssetName, model: plan.asset.Model, unit: plan.asset.Unit, allocations: plan.allocations }));
|
||||
const result = await new sql.Request(transaction)
|
||||
.input('requesterName', sql.NVarChar(100), requesterName)
|
||||
.input('itemsJson', sql.NVarChar(sql.MAX), JSON.stringify(snapshot))
|
||||
.input('requestNote', sql.NVarChar(1000), note)
|
||||
.input('createdBy', sql.Int, createdBy)
|
||||
.query(`INSERT INTO AssetExportRequests (RequesterName, ItemsJson, RequestNote, CreatedBy)
|
||||
OUTPUT INSERTED.* VALUES (@requesterName, @itemsJson, @requestNote, @createdBy)`);
|
||||
await transaction.commit();
|
||||
transaction = undefined;
|
||||
if (notifyCreated) await notifyCreated(result.recordset[0]);
|
||||
return res.status(201).json({ success: true, message: 'Đã gửi đơn xuất dự án, chờ admin/asset duyệt.', data: serialize(result.recordset[0]) });
|
||||
} catch (err) { return handleError(transaction, res, err); }
|
||||
}
|
||||
|
||||
// Keep the existing manager-only export API for integrations. The UI submits
|
||||
// proposals through this router; approval uses the same atomic stock writer.
|
||||
async function directExport(req, res, singleAssetId) {
|
||||
let transaction;
|
||||
try {
|
||||
let items;
|
||||
try { items = normalizeExportItems(singleAssetId === undefined ? req.body?.items : [{ ...req.body, assetId: singleAssetId }]); }
|
||||
catch (err) { fail(400, err.message); }
|
||||
const requesterName = String(req.body?.borrowerName || req.body?.custodianName || '').trim();
|
||||
const exportNote = String(req.body?.note || '').trim() || null;
|
||||
if (!requesterName || requesterName.length > 100) fail(400, 'Vui lòng chọn người đề nghị xuất, tối đa 100 ký tự.');
|
||||
if (exportNote && exportNote.length > 1000) fail(400, 'Ghi chú xuất tối đa 1000 ký tự.');
|
||||
const createdBy = getUserIdFromRequest(req);
|
||||
const exportedByName = await getUserDisplayNameById(createdBy) || req.user?.FullName || req.user?.Username;
|
||||
transaction = new sql.Transaction(getPool());
|
||||
await transaction.begin();
|
||||
const plans = await loadPlans(transaction, items, exportNote);
|
||||
const exported = await performAssetExport(transaction, plans, { createdBy, requesterName, exportedByName, exportNote });
|
||||
await transaction.commit();
|
||||
res.json({ success: true, message: 'Xuất tài sản vào dự án thành công.',
|
||||
data: singleAssetId !== undefined && req.body.allocations === undefined ? exported.histories[0] : exported.histories,
|
||||
document: exported.document });
|
||||
} catch (err) { return handleError(transaction, res, err); }
|
||||
}
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const result = await getPool().request().input('requesterId', sql.Int, getUserIdFromRequest(req) || -1).query(`
|
||||
SELECT r.*, d.FileName AS DocumentFileName FROM AssetExportRequests r
|
||||
LEFT JOIN AssetExportDocuments d ON d.ExportDocumentId = r.ExportDocumentId
|
||||
${canManage(req) ? '' : 'WHERE r.CreatedBy = @requesterId'}
|
||||
ORDER BY r.CreatedDate DESC, r.ExportRequestId DESC
|
||||
`);
|
||||
res.setHeader('Cache-Control', 'private, no-store');
|
||||
res.json({ success: true, data: result.recordset.map(serialize) });
|
||||
} catch (err) { sendInternalError(res, err); }
|
||||
});
|
||||
router.post('/', (req, res) => createRequest(req, res));
|
||||
router.post('/:id/process', requireManage, async (req, res) => {
|
||||
let transaction;
|
||||
try {
|
||||
const requestId = Number(req.params.id);
|
||||
const action = req.body?.action;
|
||||
const rejectReason = String(req.body?.rejectReason || '').trim() || null;
|
||||
if (!Number.isSafeInteger(requestId) || requestId <= 0 || requestId > 2147483647) fail(400, 'Mã đơn không hợp lệ.');
|
||||
if (!['approved', 'rejected'].includes(action)) fail(400, 'Hành động không hợp lệ.');
|
||||
if (action === 'rejected' && (!rejectReason || rejectReason.length > 1000)) fail(400, 'Vui lòng nhập lý do từ chối, tối đa 1000 ký tự.');
|
||||
const processedBy = getUserIdFromRequest(req);
|
||||
const processedByName = await getUserDisplayNameById(processedBy) || req.user?.FullName || req.user?.Username;
|
||||
transaction = new sql.Transaction(getPool());
|
||||
await transaction.begin();
|
||||
const result = await new sql.Request(transaction).input('requestId', sql.Int, requestId).query(`
|
||||
SELECT * FROM AssetExportRequests WITH (UPDLOCK, HOLDLOCK) WHERE ExportRequestId = @requestId
|
||||
`);
|
||||
const target = result.recordset[0];
|
||||
if (!target) fail(404, 'Không tìm thấy đơn xuất.');
|
||||
if (target.RequestStatus !== 'pending') fail(409, 'Đơn xuất đã được xử lý trước đó.');
|
||||
let exported;
|
||||
if (action === 'approved') {
|
||||
const items = normalizeExportItems(JSON.parse(target.ItemsJson));
|
||||
const plans = await loadPlans(transaction, items, target.RequestNote);
|
||||
exported = await performAssetExport(transaction, plans, { createdBy: target.CreatedBy,
|
||||
requesterName: target.RequesterName, exportedByName: processedByName, exportNote: target.RequestNote });
|
||||
}
|
||||
const saved = await new sql.Request(transaction)
|
||||
.input('requestId', sql.Int, requestId)
|
||||
.input('status', sql.NVarChar(20), action)
|
||||
.input('rejectReason', sql.NVarChar(1000), action === 'rejected' ? rejectReason : null)
|
||||
.input('processedBy', sql.Int, processedBy)
|
||||
.input('processedByName', sql.NVarChar(100), processedByName)
|
||||
.input('documentId', sql.UniqueIdentifier, exported?.document.documentId || null)
|
||||
.query(`UPDATE AssetExportRequests SET RequestStatus = @status, RejectReason = @rejectReason,
|
||||
ProcessedBy = @processedBy, ProcessedByName = @processedByName,
|
||||
ProcessedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()), ExportDocumentId = @documentId
|
||||
OUTPUT INSERTED.* WHERE ExportRequestId = @requestId`);
|
||||
await transaction.commit();
|
||||
transaction = undefined;
|
||||
if (notifyProcessed) await notifyProcessed(target, action, rejectReason);
|
||||
res.json({ success: true, message: action === 'approved' ? 'Đã duyệt và xuất tài sản khỏi kho.' : 'Đã từ chối đơn xuất.',
|
||||
data: serialize(saved.recordset[0]), document: exported?.document });
|
||||
} catch (err) { return handleError(transaction, res, err); }
|
||||
});
|
||||
return { router, createRequest, directExport };
|
||||
}
|
||||
|
||||
module.exports = { ensureAssetExportRequestSchema, normalizeExportItems, createAssetExportWorkflow };
|
||||
31
backend/asset-export-requests.sql
Normal file
31
backend/asset-export-requests.sql
Normal file
@@ -0,0 +1,31 @@
|
||||
SET XACT_ABORT ON;
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
IF OBJECT_ID('dbo.AssetExportRequests', 'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.AssetExportRequests (
|
||||
ExportRequestId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
|
||||
RequesterName NVARCHAR(100) NOT NULL,
|
||||
ItemsJson NVARCHAR(MAX) NOT NULL,
|
||||
RequestNote NVARCHAR(1000) NULL,
|
||||
RequestStatus NVARCHAR(20) NOT NULL DEFAULT 'pending',
|
||||
CreatedBy INT NOT NULL,
|
||||
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
|
||||
ProcessedBy INT NULL,
|
||||
ProcessedByName NVARCHAR(100) NULL,
|
||||
ProcessedDate DATETIME NULL,
|
||||
RejectReason NVARCHAR(1000) NULL,
|
||||
ExportDocumentId UNIQUEIDENTIFIER NULL,
|
||||
CONSTRAINT CK_AssetExportRequests_Status CHECK (RequestStatus IN ('pending', 'approved', 'rejected')),
|
||||
CONSTRAINT FK_AssetExportRequests_User FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId),
|
||||
CONSTRAINT FK_AssetExportRequests_Document FOREIGN KEY (ExportDocumentId) REFERENCES dbo.AssetExportDocuments(ExportDocumentId)
|
||||
);
|
||||
CREATE INDEX IX_AssetExportRequests_Creator ON dbo.AssetExportRequests(CreatedBy, CreatedDate DESC);
|
||||
CREATE INDEX IX_AssetExportRequests_Status ON dbo.AssetExportRequests(RequestStatus, CreatedDate DESC);
|
||||
END;
|
||||
COMMIT TRANSACTION;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
|
||||
THROW;
|
||||
END CATCH;
|
||||
53
backend/asset-export-requests.test.js
Normal file
53
backend/asset-export-requests.test.js
Normal file
@@ -0,0 +1,53 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { normalizeExportItems } = require('./asset-export-requests');
|
||||
const { addProjectExports, releaseAllocations } = require('./asset-project-allocations');
|
||||
const { createExportTestApp } = require('./asset-export-test-fixture');
|
||||
|
||||
test('project export proposals require positive integer quantities, project names and unique inventory IDs', () => {
|
||||
for (const value of [[], null, [{ assetId: 0, projectName: 'A', quantity: 1 }],
|
||||
[{ assetId: 1, projectName: '', quantity: 1 }], [{ assetId: 1, projectName: 'A', quantity: 1.5 }],
|
||||
[{ assetId: 1, projectName: 'A', quantity: -1 }],
|
||||
[{ assetId: 1, projectName: 'A', quantity: 1 }, { assetId: 1, projectName: 'B', quantity: 1 }],
|
||||
Array.from({ length: 101 }, (_, i) => ({ assetId: i + 1, projectName: 'A', quantity: 1 }))]) {
|
||||
assert.throws(() => normalizeExportItems(value));
|
||||
}
|
||||
assert.deepEqual(normalizeExportItems([{ assetId: 1, allocations: [
|
||||
{ projectName: 'Dự án A', quantity: 2 }, { projectName: 'Dự án B', quantity: 3 }
|
||||
] }])[0].allocations.map(row => row.quantity), [2, 3]);
|
||||
});
|
||||
|
||||
test('permanent project exports consume the existing stock ledger without adding returnable borrowers', () => {
|
||||
const { prepareAssetExport } = createExportTestApp({});
|
||||
const asset = { AssetId: 1, AssetCode: 'TS-001', Quantity: 12, ImportInPeriod: 3,
|
||||
ExportInPeriod: 4, EndingBalance: 11, NewQuantity: 3, UsedQuantity: 8,
|
||||
Borrower: 'An (2)', ProjectAllocations: JSON.stringify([{ projectName: 'Cũ', borrowerName: '', quantity: 2 }]) };
|
||||
const plan = prepareAssetExport(asset, [{ projectName: 'Dự án A', quantity: 2 }, { projectName: 'Dự án B', quantity: 3 }], 'Dự án mới');
|
||||
assert.equal(plan.exportInPeriod, 9);
|
||||
assert.equal(plan.endingBalance, 6);
|
||||
assert.equal(plan.newQuantity, 0);
|
||||
assert.equal(plan.usedQuantity, 6);
|
||||
assert.equal(plan.borrower, undefined);
|
||||
assert.equal(asset.Borrower, 'An (2)');
|
||||
assert.throws(() => prepareAssetExport(asset, [{ projectName: 'A', quantity: 12 }]), /vượt quá/);
|
||||
assert.throws(() => prepareAssetExport({ ...asset, EndingBalance: 0 }, [{ projectName: 'A', quantity: 1 }]), /hết tồn/);
|
||||
});
|
||||
|
||||
test('returning a loan preserves all quantities permanently issued into projects', () => {
|
||||
const legacyLoan = [{ projectName: 'Mượn cũ', borrowerName: 'An', quantity: 3 }];
|
||||
const allocations = addProjectExports(legacyLoan, [{ projectName: 'Dự án A', quantity: 4 }]);
|
||||
const returned = releaseAllocations(allocations, 'An', 3, 3);
|
||||
assert.deepEqual(returned, [{ projectName: 'Dự án A', borrowerName: '', quantity: 4, allocationType: 'export' }]);
|
||||
});
|
||||
|
||||
test('production session middleware protects proposal creation, listing and decisions', async t => {
|
||||
const { productionApp } = createExportTestApp({});
|
||||
const server = productionApp.listen(0, '127.0.0.1');
|
||||
await new Promise(resolve => server.once('listening', resolve));
|
||||
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
|
||||
for (const [path, method] of [['/api/asset-export-requests', 'GET'], ['/api/asset-export-requests', 'POST'],
|
||||
['/api/asset-export-requests/1/process', 'POST']]) {
|
||||
const response = await fetch(`http://127.0.0.1:${server.address().port}${path}`, { method });
|
||||
assert.equal(response.status, 401);
|
||||
}
|
||||
});
|
||||
78
backend/asset-export-sql-fixture.js
Normal file
78
backend/asset-export-sql-fixture.js
Normal file
@@ -0,0 +1,78 @@
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const sql = require('mssql');
|
||||
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
|
||||
const { ensureAssetExportRequestSchema } = require('./asset-export-requests');
|
||||
const { createExportTestApp } = require('./asset-export-test-fixture');
|
||||
|
||||
async function createExportSqlFixture() {
|
||||
require('dotenv').config();
|
||||
const database = `AccManagerExportTest_${randomUUID().replace(/-/g, '')}`;
|
||||
const config = { server: process.env.DB_SERVER || 'localhost', user: process.env.DB_USER || 'sa', password: process.env.DB_PASSWORD,
|
||||
database: 'master', options: { encrypt: /^(true|1)$/i.test(process.env.DB_ENCRYPT || 'false'),
|
||||
trustServerCertificate: !/^(false|0)$/i.test(process.env.DB_TRUST_CERTIFICATE || 'true'), useUTC: false },
|
||||
pool: { min: 0, max: 8, idleTimeoutMillis: 1000 }, connectionTimeout: 15000, requestTimeout: 20000 };
|
||||
if (process.env.DB_PORT) config.port = Number(process.env.DB_PORT);
|
||||
let admin, pool, server, created = false;
|
||||
const cleanup = async () => {
|
||||
if (server) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
|
||||
if (pool) await pool.close();
|
||||
if (created) {
|
||||
if (!/^AccManagerExportTest_[0-9a-f]{32}$/.test(database)) throw new Error('Unsafe test database name');
|
||||
await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [${database}];`);
|
||||
}
|
||||
if (admin) await admin.close();
|
||||
};
|
||||
try {
|
||||
admin = await new sql.ConnectionPool(config).connect();
|
||||
await admin.request().query(`CREATE DATABASE [${database}]`); created = true;
|
||||
pool = await new sql.ConnectionPool({ ...config, database }).connect();
|
||||
await pool.request().batch(`
|
||||
CREATE TABLE dbo.Users (UserId INT PRIMARY KEY, Username NVARCHAR(100), FullName NVARCHAR(100));
|
||||
INSERT dbo.Users VALUES (1, 'an', N'Nguyễn An'), (2, 'binh', N'Trần Bình'), (3, 'manager', N'Quản lý kho');
|
||||
CREATE TABLE dbo.AssetInventory (
|
||||
AssetId INT PRIMARY KEY, AssetCode NVARCHAR(100), AssetName NVARCHAR(255), Model NVARCHAR(255), SerialNumber NVARCHAR(255),
|
||||
Quantity INT, ImportInPeriod INT, ExportInPeriod INT, EndingBalance INT, NewQuantity INT, UsedQuantity INT,
|
||||
Unit NVARCHAR(50), Department NVARCHAR(100), Project NVARCHAR(150), Location NVARCHAR(150), Custodian NVARCHAR(100),
|
||||
Borrower NVARCHAR(255), ProjectAllocations NVARCHAR(MAX), ExportedBy NVARCHAR(100), Status NVARCHAR(50), Notes NVARCHAR(MAX),
|
||||
PurchaseDate DATE NULL, PurchasePrice DECIMAL(18,2) NULL, CreatedBy INT NULL,
|
||||
IsArchived BIT NOT NULL DEFAULT 0, ArchivedDate DATETIME NULL, CreatedDate DATETIME NOT NULL DEFAULT GETDATE(),
|
||||
UpdatedDate DATETIME NOT NULL DEFAULT GETDATE()
|
||||
);
|
||||
INSERT dbo.AssetInventory (AssetId, AssetCode, AssetName, Model, Quantity, ImportInPeriod, ExportInPeriod, EndingBalance, NewQuantity, UsedQuantity, Unit, Custodian, Borrower, ProjectAllocations, Status)
|
||||
VALUES (1, 'TS-001', N'Máy khoan', 'MK-01', 10, 0, 0, 10, 6, 4, N'cái', N'Quản lý kho', NULL, '[]', 'in_stock'),
|
||||
(2, 'TS-002', N'Đồng hồ', 'DH-01', 5, 0, 0, 5, 5, 0, N'cái', N'Quản lý kho', NULL, '[]', 'in_stock'),
|
||||
(3, 'TS-003', N'Động cơ', 'DC-01', 4, 0, 0, 4, 4, 0, N'cái', N'Quản lý kho', NULL, '[]', 'in_stock');
|
||||
CREATE TABLE dbo.AssetExportHistory (
|
||||
ExportHistoryId INT IDENTITY PRIMARY KEY, AssetId INT, AssetCode NVARCHAR(100), AssetName NVARCHAR(255),
|
||||
ExportQuantity INT, ProjectName NVARCHAR(150), CustodianName NVARCHAR(100), ExportedByName NVARCHAR(100),
|
||||
ExportNote NVARCHAR(1000), CreatedBy INT, ExportedDate DATETIME,
|
||||
CreatedDate DATETIME NOT NULL DEFAULT GETDATE(), UpdatedDate DATETIME NOT NULL DEFAULT GETDATE()
|
||||
);
|
||||
CREATE TABLE dbo.AssetBorrowRequests (
|
||||
BorrowId INT IDENTITY PRIMARY KEY, AssetId INT, RequestType NVARCHAR(20) DEFAULT 'borrow', RequestStatus NVARCHAR(20) DEFAULT 'pending',
|
||||
BorrowerName NVARCHAR(100), BorrowQuantity INT, ReturnedQuantity INT DEFAULT 0, Unit NVARCHAR(50), BorrowDate DATE DEFAULT GETDATE(),
|
||||
RequestNote NVARCHAR(500), RejectReason NVARCHAR(1000), CreatedBy INT, ProcessedBy INT, ProcessedByName NVARCHAR(100),
|
||||
ProcessedDate DATETIME, CreatedDate DATETIME DEFAULT GETDATE(), UpdatedDate DATETIME DEFAULT GETDATE()
|
||||
);
|
||||
CREATE TABLE dbo.AssetBorrowRequestLinks (LinkId INT IDENTITY PRIMARY KEY, BorrowId INT, ReturnId INT, Quantity INT,
|
||||
CreatedDate DATETIME DEFAULT GETDATE());
|
||||
`);
|
||||
await ensureAssetExportDocumentSchema(pool);
|
||||
await ensureAssetExportRequestSchema(pool);
|
||||
await ensureAssetExportRequestSchema(pool);
|
||||
const { app } = createExportTestApp(pool);
|
||||
server = app.listen(0, '127.0.0.1');
|
||||
await new Promise(resolve => server.once('listening', resolve));
|
||||
const origin = `http://127.0.0.1:${server.address().port}`;
|
||||
const request = async (suffix, { user = 1, role = 'user', method = 'GET', body } = {}) => {
|
||||
const response = await fetch(`${origin}/api${suffix}`, { method, headers: {
|
||||
'x-test-user': String(user), 'x-test-role': role, ...(body === undefined ? {} : { 'Content-Type': 'application/json' })
|
||||
}, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
||||
if (response.headers.get('content-type')?.includes('application/json')) return { status: response.status, ...(await response.json()) };
|
||||
return { status: response.status, buffer: Buffer.from(await response.arrayBuffer()) };
|
||||
};
|
||||
return { pool, app, origin, request, cleanup };
|
||||
} catch (err) { await cleanup(); throw err; }
|
||||
}
|
||||
|
||||
module.exports = { createExportSqlFixture };
|
||||
48
backend/asset-export-test-fixture.js
Normal file
48
backend/asset-export-test-fixture.js
Normal file
@@ -0,0 +1,48 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const { createRequire } = require('node:module');
|
||||
const express = require('express');
|
||||
|
||||
// Exercise production handlers against isolated SQL/test pools, without sessions
|
||||
// or notifications touching the application's configured database.
|
||||
function createExportTestApp(pool, { sql, workbookBuilder } = {}) {
|
||||
const filename = path.join(__dirname, 'server.js');
|
||||
const localRequire = createRequire(filename);
|
||||
const sandbox = {
|
||||
require(name) {
|
||||
if (name === 'dotenv') return { config() {} };
|
||||
if (name === 'mssql' && sql) return sql;
|
||||
if (name === './export-request-workbook' && workbookBuilder) return { buildExportRequestWorkbook: workbookBuilder };
|
||||
return localRequire(name);
|
||||
},
|
||||
module: { exports: {} }, __dirname, __filename: filename, Buffer, URL, Date, console, testPool: pool,
|
||||
process: { env: { NODE_ENV: 'test', DATA_ENCRYPTION_SECRET: 'project-export-isolated-test-secret-over-32-characters' }, on() {} }
|
||||
};
|
||||
vm.runInNewContext(`${fs.readFileSync(filename, 'utf8')}
|
||||
pool = testPool;
|
||||
safeCreateSystemNotification = async () => {};
|
||||
module.exports.workflow = assetExportWorkflow;
|
||||
module.exports.prepareAssetExport = prepareAssetExport;
|
||||
`, sandbox, { filename });
|
||||
const production = sandbox.module.exports;
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, res, next) => {
|
||||
const userId = Number(req.headers['x-test-user'] || 1);
|
||||
if (!userId) return res.status(401).json({ success: false });
|
||||
req.user = { UserId: userId, Role: req.headers['x-test-role'] || 'user', FullName: `Người dùng ${userId}` };
|
||||
next();
|
||||
});
|
||||
app.use('/api/asset-export-requests', production.workflow.router);
|
||||
for (const layer of production.app.router.stack) {
|
||||
if (!layer.route || !/^\/api\/(asset-export-(history|documents)|asset-borrows|assets)/.test(layer.route.path)) continue;
|
||||
for (const method of Object.keys(layer.route.methods)) {
|
||||
// The test server provides identity; retain each route's role guards.
|
||||
app[method](layer.route.path, ...layer.route.stack.map(entry => entry.handle));
|
||||
}
|
||||
}
|
||||
return { app, productionApp: production.app, prepareAssetExport: production.prepareAssetExport };
|
||||
}
|
||||
|
||||
module.exports = { createExportTestApp };
|
||||
73
backend/asset-export-ui.test.js
Normal file
73
backend/asset-export-ui.test.js
Normal file
@@ -0,0 +1,73 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
|
||||
function fixture() {
|
||||
const nodes = { borrowAssetIdInput: { value: '1' }, borrowAssetUserInput: { value: 'An' },
|
||||
borrowAssetProjectInput: { value: 'Dự án A' }, borrowQuantityInput: { value: '2' }, borrowAssetNoteInput: { value: '' } };
|
||||
const requests = [], messages = [];
|
||||
const button = { disabled: false };
|
||||
const sandbox = { document: { addEventListener() {}, getElementById: id => nodes[id], querySelector: () => button, querySelectorAll: () => [] },
|
||||
window: {}, location: { hash: '#assets' }, console,
|
||||
fetch: async (url, options) => { requests.push({ url, options }); return { ok: true, json: async () => ({ success: true, data: { RequestStatus: 'pending' } }) }; } };
|
||||
sandbox.window.fetch = sandbox.fetch;
|
||||
vm.runInNewContext(`${fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8')}\napp = Object.create(AccountManager.prototype); globalThis.manager = app;`, sandbox);
|
||||
const manager = sandbox.manager;
|
||||
Object.assign(manager, { currentUser: { UserId: 1, Role: 'user', FullName: 'An' }, apiBase: '/api',
|
||||
selectedAssetIds: new Set([1]), assets: [{ AssetId: 1, AssetCode: 'TS-001', Quantity: 5, ExportInPeriod: 0, EndingBalance: 5 }],
|
||||
notifySuccess: message => messages.push(message), notifyFailure: message => messages.push(message), notifyWarning: message => messages.push(message),
|
||||
closeModals() {} });
|
||||
return { manager, sandbox, requests, messages, nodes, button };
|
||||
}
|
||||
|
||||
test('ordinary users submit existing project allocations as pending proposals without downloading or changing stock', async () => {
|
||||
const f = fixture();
|
||||
await f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
|
||||
assert.equal(f.requests.length, 1); assert.equal(f.requests[0].url, '/api/asset-export-requests');
|
||||
assert.deepEqual(JSON.parse(f.requests[0].options.body).items, [{ assetId: 1, allocations: [{ projectName: 'Dự án A', quantity: 2 }] }]);
|
||||
assert.equal(f.manager.assets[0].EndingBalance, 5); assert.equal(f.manager.lastExportRequestDocument, undefined);
|
||||
assert.equal(f.sandbox.location.hash, '#asset-exports'); assert.match(f.messages[0], /chờ admin\/asset duyệt/);
|
||||
assert.equal(f.manager.selectedAssetIds.size, 0); assert.equal(f.button.disabled, false);
|
||||
});
|
||||
|
||||
test('proposal forms block duplicate submissions and retain selection when the server rejects them', async () => {
|
||||
const f = fixture(); let complete;
|
||||
f.sandbox.fetch = (url, options) => { f.requests.push({ url, options }); return new Promise(resolve => { complete = resolve; }); };
|
||||
const first = f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
|
||||
await f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
|
||||
assert.equal(f.requests.length, 1); assert.equal(f.button.disabled, true);
|
||||
complete({ ok: false, json: async () => ({ success: false, message: 'Không đủ tồn' }) });
|
||||
await first;
|
||||
assert.equal(f.manager.selectedAssetIds.size, 1); assert.equal(f.button.disabled, false); assert.equal(f.messages[0], 'Không đủ tồn');
|
||||
});
|
||||
|
||||
test('proposal forms reject missing projects, fractional quantities and quantities exceeding stock before submission', async () => {
|
||||
for (const [field, value] of [['borrowAssetProjectInput', ''], ['borrowQuantityInput', '1.5'], ['borrowQuantityInput', '6']]) {
|
||||
const f = fixture(); f.nodes[field].value = value;
|
||||
await f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
|
||||
assert.equal(f.requests.length, 0); assert.equal(f.messages.length, 1);
|
||||
}
|
||||
});
|
||||
|
||||
test('export lists filter by creator, status and project, and show processing controls only to managers', () => {
|
||||
const f = fixture();
|
||||
const own = { ExportRequestId: 1, CreatedBy: 1, RequesterName: 'An', RequestStatus: 'pending', Items: [
|
||||
{ assetCode: 'TS-001', assetName: '<Máy khoan>', allocations: [{ projectName: 'Dự án A', quantity: 2 }] }
|
||||
] };
|
||||
f.manager.assetExportRequests = [own, { ...own, ExportRequestId: 2, CreatedBy: 2 }];
|
||||
f.manager.assetExportTab = 'requests';
|
||||
assert.equal(f.manager.getFilteredAssetExportRows().length, 1);
|
||||
f.manager.assetExportSearchTerm = 'dự án a'; assert.equal(f.manager.getFilteredAssetExportRows().length, 1);
|
||||
f.manager.assetExportStatusFilter = 'rejected'; assert.equal(f.manager.getFilteredAssetExportRows().length, 0);
|
||||
const userRows = f.manager.renderAssetExportRequestsRows([own]);
|
||||
assert.doesNotMatch(userRows, /process-asset-export|<Máy khoan>/); assert.match(userRows, /<Máy khoan>/);
|
||||
f.manager.currentUser.Role = 'asset'; assert.match(f.manager.renderAssetExportRequestsRows([own]), /Duyệt xuất/);
|
||||
});
|
||||
|
||||
test('ordinary users cannot invoke the proposal decision UI', async () => {
|
||||
const f = fixture();
|
||||
await f.manager.processAssetExportRequest(1, 'approved', '');
|
||||
assert.equal(f.requests.length, 0);
|
||||
});
|
||||
@@ -6,7 +6,8 @@ function parseAllocations(value) {
|
||||
return rows.map(row => ({
|
||||
projectName: String(row.projectName || '').trim(),
|
||||
borrowerName: String(row.borrowerName || '').trim(),
|
||||
quantity: Number(row.quantity)
|
||||
quantity: Number(row.quantity),
|
||||
...(row.allocationType === 'export' ? { allocationType: 'export' } : {})
|
||||
})).filter(row => row.projectName && Number.isSafeInteger(row.quantity) && row.quantity > 0);
|
||||
}
|
||||
|
||||
@@ -38,9 +39,13 @@ function addAllocations(current, rows, borrowerName) {
|
||||
return [...parseAllocations(current), ...rows.map(row => ({ ...row, borrowerName }))];
|
||||
}
|
||||
|
||||
function addProjectExports(current, rows) {
|
||||
return [...parseAllocations(current), ...rows.map(row => ({ ...row, borrowerName: '', allocationType: 'export' }))];
|
||||
}
|
||||
|
||||
function releaseAllocations(current, borrowerName, returnedQuantity, borrowerOutstanding) {
|
||||
const rows = parseAllocations(current);
|
||||
const matches = row => row.borrowerName.toLowerCase() === borrowerName.toLowerCase();
|
||||
const matches = row => row.allocationType !== 'export' && row.borrowerName.toLowerCase() === borrowerName.toLowerCase();
|
||||
const attributed = rows.filter(matches).reduce((sum, row) => sum + row.quantity, 0);
|
||||
// Older loans without a project (including request-based loans) are consumed first.
|
||||
let remaining = Math.max(returnedQuantity - Math.max(borrowerOutstanding - attributed, 0), 0);
|
||||
@@ -53,4 +58,4 @@ function releaseAllocations(current, borrowerName, returnedQuantity, borrowerOut
|
||||
return rows.filter(row => row.quantity > 0);
|
||||
}
|
||||
|
||||
module.exports = { parseAllocations, normalizeExportAllocations, addAllocations, releaseAllocations };
|
||||
module.exports = { parseAllocations, normalizeExportAllocations, addAllocations, addProjectExports, releaseAllocations };
|
||||
|
||||
@@ -13,9 +13,10 @@ const dotenv = require('dotenv');
|
||||
const helmet = require('helmet');
|
||||
const { rateLimit } = require('express-rate-limit');
|
||||
const { ensureAssetArchiveSchema } = require('./asset-archive-schema');
|
||||
const { parseAllocations, normalizeExportAllocations, addAllocations, releaseAllocations } = require('./asset-project-allocations');
|
||||
const { parseAllocations, addProjectExports, releaseAllocations } = require('./asset-project-allocations');
|
||||
const { buildExportRequestWorkbook } = require('./export-request-workbook');
|
||||
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
|
||||
const { ensureAssetExportRequestSchema, createAssetExportWorkflow } = require('./asset-export-requests');
|
||||
const { ensureRobotSchema, createRobotRouter } = require('./robots');
|
||||
const { ensureRobotBomSchema, createRobotBomRouter } = require('./robot-bom');
|
||||
const { createAnnouncementRouter } = require('./announcements');
|
||||
@@ -3112,6 +3113,7 @@ async function createTables() {
|
||||
// Fail startup if history preservation cannot be installed.
|
||||
await ensureAssetArchiveSchema(pool);
|
||||
await ensureAssetExportDocumentSchema(pool);
|
||||
await ensureAssetExportRequestSchema(pool);
|
||||
await ensureRobotSchema(pool);
|
||||
await ensureRobotBomSchema(pool);
|
||||
await pool.request().query(`
|
||||
@@ -8589,11 +8591,12 @@ app.get('/api/assets/:id', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/asset-export-history', requireAssetOrAdmin, async (req, res) => {
|
||||
app.get('/api/asset-export-history', async (req, res) => {
|
||||
try {
|
||||
const limit = Math.min(parsePositiveInteger(req.query.limit, 300), 2000);
|
||||
const result = await pool.request()
|
||||
.input('limit', sql.Int, limit)
|
||||
.input('requesterId', sql.Int, getUserIdFromRequest(req) || -1)
|
||||
.query(`
|
||||
SELECT TOP (@limit)
|
||||
h.ExportHistoryId, h.AssetId, h.AssetCode, h.AssetName,
|
||||
@@ -8602,6 +8605,7 @@ app.get('/api/asset-export-history', requireAssetOrAdmin, async (req, res) => {
|
||||
h.ExportDocumentId, d.FileName AS DocumentFileName
|
||||
FROM AssetExportHistory h
|
||||
LEFT JOIN AssetExportDocuments d ON d.ExportDocumentId = h.ExportDocumentId
|
||||
${['admin', 'asset'].includes(getRequesterRole(req)) ? '' : 'WHERE h.CreatedBy = @requesterId'}
|
||||
ORDER BY h.ExportedDate DESC, h.ExportHistoryId DESC
|
||||
`);
|
||||
|
||||
@@ -8618,11 +8622,13 @@ function isExportDocumentId(value) {
|
||||
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(String(value || ''));
|
||||
}
|
||||
|
||||
app.get('/api/asset-export-documents/:id', requireAssetOrAdmin, async (req, res) => {
|
||||
app.get('/api/asset-export-documents/:id', async (req, res) => {
|
||||
if (!isExportDocumentId(req.params.id)) return res.status(400).json({ success: false, message: 'Mã phiếu không hợp lệ.' });
|
||||
try {
|
||||
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id).query(`
|
||||
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id)
|
||||
.input('requesterId', sql.Int, getUserIdFromRequest(req) || -1).query(`
|
||||
SELECT ExportDocumentId, FileName, SnapshotJson FROM AssetExportDocuments WHERE ExportDocumentId = @documentId
|
||||
${['admin', 'asset'].includes(getRequesterRole(req)) ? '' : 'AND CreatedBy = @requesterId'}
|
||||
`);
|
||||
const document = result.recordset?.[0];
|
||||
if (!document) return res.status(404).json({ success: false, message: 'Không tìm thấy phiếu xuất đã lưu.' });
|
||||
@@ -8632,11 +8638,13 @@ app.get('/api/asset-export-documents/:id', requireAssetOrAdmin, async (req, res)
|
||||
} catch (err) { sendInternalError(res, err); }
|
||||
});
|
||||
|
||||
app.get('/api/asset-export-documents/:id/download', requireAssetOrAdmin, async (req, res) => {
|
||||
app.get('/api/asset-export-documents/:id/download', async (req, res) => {
|
||||
if (!isExportDocumentId(req.params.id)) return res.status(400).json({ success: false, message: 'Mã phiếu không hợp lệ.' });
|
||||
try {
|
||||
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id).query(`
|
||||
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id)
|
||||
.input('requesterId', sql.Int, getUserIdFromRequest(req) || -1).query(`
|
||||
SELECT FileName, MimeType, FileContent FROM AssetExportDocuments WHERE ExportDocumentId = @documentId
|
||||
${['admin', 'asset'].includes(getRequesterRole(req)) ? '' : 'AND CreatedBy = @requesterId'}
|
||||
`);
|
||||
const document = result.recordset?.[0];
|
||||
if (!document) return res.status(404).json({ success: false, message: 'Không tìm thấy file Excel đã lưu.' });
|
||||
@@ -8931,7 +8939,7 @@ app.post('/api/assets/:id/damage-disposal', requireAssetOrAdmin, async (req, res
|
||||
}
|
||||
});
|
||||
|
||||
function prepareAssetExport(asset, allocations, borrowerName, exportNote) {
|
||||
function prepareAssetExport(asset, allocations, exportNote) {
|
||||
const fail = message => { throw Object.assign(new Error(message), { statusCode: 400 }); };
|
||||
const exportQuantity = allocations.reduce((sum, row) => sum + row.quantity, 0);
|
||||
const quantity = parseNonNegativeInteger(asset.Quantity, 0);
|
||||
@@ -8945,144 +8953,107 @@ function prepareAssetExport(asset, allocations, borrowerName, exportNote) {
|
||||
const label = String(asset.AssetCode || asset.AssetName || asset.AssetId);
|
||||
if (available <= 0) fail(`${label}: Tài sản đã hết tồn cuối kỳ, không thể xuất thêm.`);
|
||||
if (exportQuantity > available) fail(`${label}: Số lượng xuất (${exportQuantity}) vượt quá tồn cuối kỳ (${available}).`);
|
||||
const borrower = mergeBorrowerEntries(asset.Borrower, borrowerName, exportQuantity);
|
||||
if (borrower && borrower.length > 255) fail('Danh sách người mượn quá dài, vui lòng rút gọn tên.');
|
||||
const exportDelta = parseBorrowerEntries(borrower)
|
||||
.reduce((sum, entry) => sum + parseNonNegativeInteger(entry?.quantity, 0), 0) - previousBorrowerExport;
|
||||
// Permanent project exports never enter the returnable borrower ledger.
|
||||
const exportDelta = exportQuantity;
|
||||
const stock = normalizeAssetStockBuckets(available,
|
||||
parseOptionalNonNegativeInteger(asset.NewQuantity) ?? available,
|
||||
parseOptionalNonNegativeInteger(asset.UsedQuantity) ?? 0);
|
||||
const borrowFromNew = Math.min(stock.newQuantity, exportDelta);
|
||||
const exportFromNew = Math.min(stock.newQuantity, exportDelta);
|
||||
const endingBalance = Math.max(available - exportDelta, 0);
|
||||
const exportInPeriod = Math.max(baseExportInPeriod + exportDelta, 0);
|
||||
const oldNotes = String(asset.Notes || '').trim();
|
||||
return { asset, allocations, available, borrower, endingBalance, exportInPeriod,
|
||||
newQuantity: Math.max(stock.newQuantity - borrowFromNew, 0),
|
||||
usedQuantity: Math.max(stock.usedQuantity - Math.max(exportDelta - borrowFromNew, 0), 0),
|
||||
return { asset, allocations, available, endingBalance, exportInPeriod,
|
||||
newQuantity: Math.max(stock.newQuantity - exportFromNew, 0),
|
||||
usedQuantity: Math.max(stock.usedQuantity - Math.max(exportDelta - exportFromNew, 0), 0),
|
||||
status: resolveAssetStatusFromStock(endingBalance, exportInPeriod),
|
||||
notes: exportNote ? (oldNotes ? `${oldNotes}\n${exportNote}` : exportNote) : (oldNotes || null) };
|
||||
}
|
||||
|
||||
async function handleAssetExport(req, res, singleAssetId) {
|
||||
let transaction;
|
||||
try {
|
||||
const rawItems = singleAssetId === undefined ? req.body?.items : [{ ...req.body, assetId: singleAssetId }];
|
||||
let items;
|
||||
try {
|
||||
if (!Array.isArray(rawItems) || !rawItems.length || rawItems.length > 100) throw new Error('Vui lòng chọn từ 1 đến 100 tài sản.');
|
||||
const seen = new Set();
|
||||
items = rawItems.map(row => {
|
||||
const assetId = Number(row?.assetId);
|
||||
if (!Number.isSafeInteger(assetId) || assetId <= 0 || assetId > 2147483647) throw new Error('Mã tài sản không hợp lệ.');
|
||||
if (seen.has(assetId)) throw new Error('Mỗi tài sản chỉ được xuất hiện một lần trong phiếu.');
|
||||
seen.add(assetId);
|
||||
return { assetId, allocations: normalizeExportAllocations(row) };
|
||||
});
|
||||
if (items.reduce((sum, item) => sum + item.allocations.length, 0) > 100) throw new Error('Một phiếu chỉ hỗ trợ tối đa 100 dòng tài sản / dự án.');
|
||||
} catch (err) {
|
||||
return res.status(400).json({ success: false, message: err.message });
|
||||
}
|
||||
const borrowerName = String(req.body?.borrowerName || req.body?.custodianName || '').trim();
|
||||
const exportNote = String(req.body?.note || '').trim() || null;
|
||||
if (!borrowerName || borrowerName.length > 100) return res.status(400).json({ success: false, message: 'Vui lòng chọn người mượn, tối đa 100 ký tự.' });
|
||||
if (exportNote && exportNote.length > 1000) return res.status(400).json({ success: false, message: 'Ghi chú xuất tối đa 1000 ký tự.' });
|
||||
const createdBy = getUserIdFromRequest(req);
|
||||
const exportedByName = await getUserDisplayNameById(createdBy) || req.user?.FullName || req.user?.Username || 'Unknown';
|
||||
const exportedDate = new Date();
|
||||
transaction = new sql.Transaction(pool);
|
||||
await transaction.begin();
|
||||
const lockedAssets = new Map();
|
||||
// Consistent lock order avoids deadlocks between overlapping batches.
|
||||
for (const { assetId } of [...items].sort((a, b) => a.assetId - b.assetId)) {
|
||||
const result = await new sql.Request(transaction).input('assetId', sql.Int, assetId).query(`
|
||||
SELECT TOP 1 AssetId, AssetCode, AssetName, Quantity, ImportInPeriod, ExportInPeriod,
|
||||
EndingBalance, NewQuantity, UsedQuantity, Custodian, Borrower, ProjectAllocations,
|
||||
Model, SerialNumber, Unit, Department, Notes
|
||||
FROM AssetInventory WITH (UPDLOCK, ROWLOCK)
|
||||
WHERE AssetId = @assetId AND IsArchived = 0
|
||||
`);
|
||||
if (!result.recordset?.[0]) throw Object.assign(new Error(`Không tìm thấy tài sản ${assetId} trong danh mục hiện tại.`), { statusCode: 404 });
|
||||
lockedAssets.set(assetId, result.recordset[0]);
|
||||
}
|
||||
// Validate every asset before creating the file or writing any inventory.
|
||||
const plans = items.map(item => prepareAssetExport(lockedAssets.get(item.assetId), item.allocations, borrowerName, exportNote));
|
||||
const workbookItems = plans.map(plan => ({ item: plan.asset, rows: plan.allocations, availableStock: plan.available }));
|
||||
const document = await buildExportRequestWorkbook({
|
||||
...(plans.length === 1 ? workbookItems[0] : { items: workbookItems }),
|
||||
requesterName: borrowerName, recipientName: borrowerName, exportedByName, note: exportNote, exportedDate
|
||||
});
|
||||
const documentId = crypto.randomUUID();
|
||||
const snapshot = { version: 1, exportedDate: exportedDate.toISOString(), borrowerName, exportedByName, note: exportNote,
|
||||
items: plans.map(plan => ({ assetId: plan.asset.AssetId, assetCode: plan.asset.AssetCode,
|
||||
assetName: plan.asset.AssetName, model: plan.asset.Model, serialNumber: plan.asset.SerialNumber,
|
||||
unit: plan.asset.Unit, department: plan.asset.Department, availableStock: plan.available,
|
||||
allocations: plan.allocations })) };
|
||||
async function performAssetExport(transaction, plans, { createdBy, requesterName, exportedByName, exportNote }) {
|
||||
const exportedDate = new Date();
|
||||
const workbookItems = plans.map(plan => ({ item: plan.asset, rows: plan.allocations, availableStock: plan.available }));
|
||||
const document = await buildExportRequestWorkbook({
|
||||
...(plans.length === 1 ? workbookItems[0] : { items: workbookItems }),
|
||||
requesterName, recipientName: requesterName, exportedByName, note: exportNote, exportedDate
|
||||
});
|
||||
const documentId = crypto.randomUUID();
|
||||
const snapshot = { version: 1, exportedDate: exportedDate.toISOString(), borrowerName: requesterName, requesterName, exportedByName, note: exportNote,
|
||||
items: plans.map(plan => ({ assetId: plan.asset.AssetId, assetCode: plan.asset.AssetCode,
|
||||
assetName: plan.asset.AssetName, model: plan.asset.Model, serialNumber: plan.asset.SerialNumber,
|
||||
unit: plan.asset.Unit, department: plan.asset.Department, availableStock: plan.available,
|
||||
allocations: plan.allocations })) };
|
||||
await new sql.Request(transaction)
|
||||
.input('documentId', sql.UniqueIdentifier, documentId)
|
||||
.input('fileName', sql.NVarChar(255), document.fileName)
|
||||
.input('mimeType', sql.NVarChar(150), document.mimeType)
|
||||
.input('fileContent', sql.VarBinary(sql.MAX), Buffer.from(document.contentBase64, 'base64'))
|
||||
.input('snapshotJson', sql.NVarChar(sql.MAX), JSON.stringify(snapshot))
|
||||
.input('createdBy', sql.Int, createdBy)
|
||||
.input('exportedDate', sql.DateTime, exportedDate)
|
||||
.query(`INSERT INTO AssetExportDocuments (ExportDocumentId, FileName, MimeType, FileContent, SnapshotJson, CreatedBy, ExportedDate)
|
||||
VALUES (@documentId, @fileName, @mimeType, @fileContent, @snapshotJson, @createdBy, @exportedDate)`);
|
||||
const histories = [];
|
||||
for (const plan of plans) {
|
||||
const { asset } = plan;
|
||||
await new sql.Request(transaction)
|
||||
.input('documentId', sql.UniqueIdentifier, documentId)
|
||||
.input('fileName', sql.NVarChar(255), document.fileName)
|
||||
.input('mimeType', sql.NVarChar(150), document.mimeType)
|
||||
.input('fileContent', sql.VarBinary(sql.MAX), Buffer.from(document.contentBase64, 'base64'))
|
||||
.input('snapshotJson', sql.NVarChar(sql.MAX), JSON.stringify(snapshot))
|
||||
.input('createdBy', sql.Int, createdBy)
|
||||
.input('exportedDate', sql.DateTime, exportedDate)
|
||||
.query(`INSERT INTO AssetExportDocuments (ExportDocumentId, FileName, MimeType, FileContent, SnapshotJson, CreatedBy, ExportedDate)
|
||||
VALUES (@documentId, @fileName, @mimeType, @fileContent, @snapshotJson, @createdBy, @exportedDate)`);
|
||||
const histories = [];
|
||||
for (const plan of plans) {
|
||||
const { asset } = plan;
|
||||
await new sql.Request(transaction)
|
||||
.input('assetId', sql.Int, asset.AssetId)
|
||||
// No borrower: returns can release loans while keeping these project exports.
|
||||
.input('projectAllocations', sql.NVarChar(sql.MAX), JSON.stringify(addProjectExports(asset.ProjectAllocations, plan.allocations)))
|
||||
.input('exportInPeriod', sql.Int, plan.exportInPeriod)
|
||||
.input('endingBalance', sql.Int, plan.endingBalance)
|
||||
.input('newQuantity', sql.Int, plan.newQuantity)
|
||||
.input('usedQuantity', sql.Int, plan.usedQuantity)
|
||||
.input('status', sql.NVarChar, plan.status)
|
||||
.input('exportedBy', sql.NVarChar, exportedByName)
|
||||
.input('notes', sql.NVarChar, plan.notes)
|
||||
.query(`UPDATE AssetInventory SET ProjectAllocations = @projectAllocations,
|
||||
ExportInPeriod = @exportInPeriod, EndingBalance = @endingBalance, NewQuantity = @newQuantity,
|
||||
UsedQuantity = @usedQuantity, Status = @status, ExportedBy = @exportedBy, Notes = @notes,
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
WHERE AssetId = @assetId AND IsArchived = 0`);
|
||||
for (const allocation of plan.allocations) {
|
||||
const result = await new sql.Request(transaction)
|
||||
.input('assetId', sql.Int, asset.AssetId)
|
||||
.input('projectAllocations', sql.NVarChar(sql.MAX), JSON.stringify(addAllocations(asset.ProjectAllocations, plan.allocations, borrowerName)))
|
||||
.input('borrower', sql.NVarChar, plan.borrower)
|
||||
.input('exportInPeriod', sql.Int, plan.exportInPeriod)
|
||||
.input('endingBalance', sql.Int, plan.endingBalance)
|
||||
.input('newQuantity', sql.Int, plan.newQuantity)
|
||||
.input('usedQuantity', sql.Int, plan.usedQuantity)
|
||||
.input('status', sql.NVarChar, plan.status)
|
||||
.input('exportedBy', sql.NVarChar, exportedByName)
|
||||
.input('notes', sql.NVarChar, plan.notes)
|
||||
.query(`UPDATE AssetInventory SET ProjectAllocations = @projectAllocations, Borrower = @borrower,
|
||||
ExportInPeriod = @exportInPeriod, EndingBalance = @endingBalance, NewQuantity = @newQuantity,
|
||||
UsedQuantity = @usedQuantity, Status = @status, ExportedBy = @exportedBy, Notes = @notes,
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
WHERE AssetId = @assetId AND IsArchived = 0`);
|
||||
for (const allocation of plan.allocations) {
|
||||
const result = await new sql.Request(transaction)
|
||||
.input('assetId', sql.Int, asset.AssetId)
|
||||
.input('assetCode', sql.NVarChar, String(asset.AssetCode || '').trim())
|
||||
.input('assetName', sql.NVarChar, String(asset.AssetName || '').trim())
|
||||
.input('exportQuantity', sql.Int, allocation.quantity)
|
||||
.input('projectName', sql.NVarChar, allocation.projectName)
|
||||
.input('custodianName', sql.NVarChar, String(asset.Custodian || '').trim() || '-')
|
||||
.input('exportedByName', sql.NVarChar, exportedByName)
|
||||
.input('exportNote', sql.NVarChar, exportNote)
|
||||
.input('createdBy', sql.Int, createdBy)
|
||||
.input('exportedDate', sql.DateTime, exportedDate)
|
||||
.input('documentId', sql.UniqueIdentifier, documentId)
|
||||
.query(`INSERT INTO AssetExportHistory (AssetId, AssetCode, AssetName, ExportQuantity, ProjectName,
|
||||
CustodianName, ExportedByName, ExportNote, CreatedBy, ExportedDate, ExportDocumentId)
|
||||
OUTPUT INSERTED.*
|
||||
VALUES (@assetId, @assetCode, @assetName, @exportQuantity, @projectName,
|
||||
@custodianName, @exportedByName, @exportNote, @createdBy, @exportedDate, @documentId)`);
|
||||
histories.push(result.recordset?.[0] || null);
|
||||
}
|
||||
.input('assetCode', sql.NVarChar, String(asset.AssetCode || '').trim())
|
||||
.input('assetName', sql.NVarChar, String(asset.AssetName || '').trim())
|
||||
.input('exportQuantity', sql.Int, allocation.quantity)
|
||||
.input('projectName', sql.NVarChar, allocation.projectName)
|
||||
.input('custodianName', sql.NVarChar, String(asset.Custodian || '').trim() || '-')
|
||||
.input('exportedByName', sql.NVarChar, exportedByName)
|
||||
.input('exportNote', sql.NVarChar, exportNote)
|
||||
.input('createdBy', sql.Int, createdBy)
|
||||
.input('exportedDate', sql.DateTime, exportedDate)
|
||||
.input('documentId', sql.UniqueIdentifier, documentId)
|
||||
.query(`INSERT INTO AssetExportHistory (AssetId, AssetCode, AssetName, ExportQuantity, ProjectName,
|
||||
CustodianName, ExportedByName, ExportNote, CreatedBy, ExportedDate, ExportDocumentId)
|
||||
OUTPUT INSERTED.*
|
||||
VALUES (@assetId, @assetCode, @assetName, @exportQuantity, @projectName,
|
||||
@custodianName, @exportedByName, @exportNote, @createdBy, @exportedDate, @documentId)`);
|
||||
histories.push(result.recordset?.[0] || null);
|
||||
}
|
||||
await transaction.commit();
|
||||
res.json({ success: true, message: 'Xuất tài sản thành công',
|
||||
data: singleAssetId !== undefined && req.body.allocations === undefined ? histories[0] : histories,
|
||||
document: { ...document, documentId } });
|
||||
} catch (err) {
|
||||
if (transaction) {
|
||||
try { await transaction.rollback(); } catch (_rollbackErr) { /* Preserve the original error. */ }
|
||||
}
|
||||
if (err.statusCode) res.status(err.statusCode).json({ success: false, message: err.message });
|
||||
else sendInternalError(res, err);
|
||||
}
|
||||
|
||||
return { document: { ...document, documentId }, histories };
|
||||
}
|
||||
|
||||
app.post('/api/assets/export', requireAssetOrAdmin, (req, res) => handleAssetExport(req, res));
|
||||
app.post('/api/assets/:id/export', requireAssetOrAdmin, (req, res) => handleAssetExport(req, res, req.params.id));
|
||||
|
||||
const assetExportWorkflow = createAssetExportWorkflow({
|
||||
getPool: () => pool, sql, requireManage: requireAssetOrAdmin, getRequesterRole, getUserIdFromRequest,
|
||||
getUserDisplayNameById: id => getUserDisplayNameById(id), prepareAssetExport, performAssetExport, sendInternalError,
|
||||
notifyCreated: target => safeCreateSystemNotification({
|
||||
severity: 'info', title: 'Đơn xuất vào dự án mới',
|
||||
message: `${target.RequesterName} đã gửi đơn xuất #${target.ExportRequestId}, chờ duyệt.`,
|
||||
actionUrl: '#asset-exports', audiences: [{ type: 'role', value: 'admin' }, { type: 'role', value: 'asset' }]
|
||||
}),
|
||||
notifyProcessed: (target, action, rejectReason) => safeCreateSystemNotification({
|
||||
severity: action === 'approved' ? 'success' : 'error',
|
||||
title: action === 'approved' ? 'Đơn xuất dự án được duyệt' : 'Đơn xuất dự án bị từ chối',
|
||||
message: `Đơn xuất #${target.ExportRequestId} đã ${action === 'approved' ? 'được duyệt và trừ kho' : `bị từ chối. Lý do: ${rejectReason}`}.`,
|
||||
actionUrl: '#asset-exports', audiences: [{ type: 'user', value: Number(target.CreatedBy) }]
|
||||
})
|
||||
});
|
||||
app.use('/api/asset-export-requests', assetExportWorkflow.router);
|
||||
app.post('/api/assets/export', requireAssetOrAdmin, (req, res) => assetExportWorkflow.directExport(req, res));
|
||||
app.post('/api/assets/:id/export', requireAssetOrAdmin, (req, res) => assetExportWorkflow.directExport(req, res, req.params.id));
|
||||
|
||||
app.post('/api/assets', requireAssetOrAdmin, async (req, res) => {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user