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,74 +8953,31 @@ 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';
|
||||
async function performAssetExport(transaction, plans, { createdBy, requesterName, exportedByName, exportNote }) {
|
||||
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
|
||||
requesterName, recipientName: requesterName, exportedByName, note: exportNote, exportedDate
|
||||
});
|
||||
const documentId = crypto.randomUUID();
|
||||
const snapshot = { version: 1, exportedDate: exportedDate.toISOString(), borrowerName, exportedByName, note: exportNote,
|
||||
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,
|
||||
@@ -9032,8 +8997,8 @@ async function handleAssetExport(req, res, singleAssetId) {
|
||||
const { asset } = plan;
|
||||
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)
|
||||
// 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)
|
||||
@@ -9041,7 +9006,7 @@ async function handleAssetExport(req, res, singleAssetId) {
|
||||
.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,
|
||||
.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())
|
||||
@@ -9067,22 +9032,28 @@ async function handleAssetExport(req, res, singleAssetId) {
|
||||
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 {
|
||||
|
||||
@@ -1404,3 +1404,39 @@ BEGIN CATCH
|
||||
END CATCH;
|
||||
|
||||
GO
|
||||
|
||||
GO
|
||||
-- Project export approval workflow. Preserves legacy exports.
|
||||
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;
|
||||
|
||||
GO
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -153,57 +153,39 @@ textarea {
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
/* Keep saved export files and both actions visible beside wide history rows. */
|
||||
#assetExportHistoryModal .asset-export-history-dialog {
|
||||
width: min(1600px, calc(100vw - 2rem));
|
||||
max-width: none;
|
||||
max-height: calc(100dvh - 2rem);
|
||||
}
|
||||
|
||||
.asset-export-history-scroll {
|
||||
max-height: calc(100dvh - 10rem);
|
||||
overflow: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.asset-export-history-table {
|
||||
min-width: 1280px;
|
||||
table-layout: fixed;
|
||||
/* Keep project export decisions and saved files accessible in wide tables. */
|
||||
.asset-exports-page table {
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
}
|
||||
|
||||
.asset-export-history-table th,
|
||||
.asset-export-history-table td {
|
||||
border-bottom: 1px solid #f1f5f9;
|
||||
.asset-exports-page th,
|
||||
.asset-exports-page td {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.asset-export-history-table thead th {
|
||||
@media (min-width: 901px) {
|
||||
.asset-exports-page thead th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
background: #f8fafc;
|
||||
overflow-wrap: normal;
|
||||
}
|
||||
|
||||
.asset-export-history-table .asset-export-history-document {
|
||||
.asset-exports-page tbody td:last-child {
|
||||
position: sticky;
|
||||
right: 0;
|
||||
z-index: 1;
|
||||
min-width: 190px;
|
||||
background: #fff;
|
||||
border-left: 1px solid #e2e8f0;
|
||||
box-shadow: -6px 0 12px -10px rgb(15 23 42 / 0.3);
|
||||
}
|
||||
|
||||
.asset-export-history-table thead .asset-export-history-document {
|
||||
.asset-exports-page thead th:last-child {
|
||||
right: 0;
|
||||
z-index: 3;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.asset-export-history-table tr:hover .asset-export-history-document {
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.asset-export-history-file-actions {
|
||||
|
||||
374
public/js/app.js
374
public/js/app.js
@@ -152,6 +152,13 @@ class AccountManager {
|
||||
this.assetProjects = [];
|
||||
this.assetProjectSearchTerm = '';
|
||||
this.assetExportHistories = [];
|
||||
this.assetExportRequests = [];
|
||||
this.assetExportTab = 'requests';
|
||||
this.assetExportSearchTerm = '';
|
||||
this.assetExportStatusFilter = '';
|
||||
this.assetExportPage = 1;
|
||||
this.assetExportLoading = false;
|
||||
this.assetExportLoadError = '';
|
||||
this.assetDamageHistories = [];
|
||||
this.consumableExportHistories = [];
|
||||
this.consumableBorrowRequests = [];
|
||||
@@ -387,6 +394,10 @@ class AccountManager {
|
||||
mainContent.innerHTML = this.getAssetBorrowsContent();
|
||||
this.setupAssetBorrowListeners();
|
||||
this.setupAddButtonListeners();
|
||||
} else if (page === 'asset-exports') {
|
||||
mainContent.innerHTML = this.getAssetExportsContent();
|
||||
this.setupAssetExportsListeners();
|
||||
this.refreshAssetExportsPage();
|
||||
} else if (page === 'my-borrowed-assets') {
|
||||
mainContent.innerHTML = this.getMyBorrowedAssetsContent();
|
||||
this.setupMyBorrowedAssetsListeners();
|
||||
@@ -1338,10 +1349,8 @@ class AccountManager {
|
||||
}
|
||||
|
||||
refreshBorrowAssetUserOptions(selectedValue = '') {
|
||||
this.populateUserSelectOptions('borrowAssetUserInput', {
|
||||
selectedValue,
|
||||
emptyLabel: '-- Chọn người mượn --'
|
||||
});
|
||||
const input = document.getElementById('borrowAssetUserInput');
|
||||
if (input) input.value = this.getCurrentUserDisplayName();
|
||||
}
|
||||
|
||||
refreshConsumableExportUserOptions(selectedValue = '') {
|
||||
@@ -2086,23 +2095,178 @@ class AccountManager {
|
||||
}
|
||||
}
|
||||
|
||||
async fetchAssetExportHistories(limit = 300) {
|
||||
try {
|
||||
const safeLimit = Number.isFinite(Number(limit)) ? Math.max(1, Math.min(Number(limit), 2000)) : 300;
|
||||
const res = await fetch(`${this.apiBase}/asset-export-history?limit=${safeLimit}`, {
|
||||
headers: this.getAuthHeaders(false)
|
||||
getAssetExportsContent() {
|
||||
const manager = this.canCurrentUserManageAssets();
|
||||
return `<div class="asset-exports-page flex flex-col p-4 md:p-6 overflow-hidden h-full">
|
||||
<div class="page-header flex items-center justify-between gap-4 mb-5 shrink-0">
|
||||
<div><h1 class="text-2xl font-extrabold text-on-surface tracking-tight">Xuất tài sản vào dự án</h1>
|
||||
<p class="text-sm text-on-surface-variant">${manager ? 'Duyệt đề xuất và theo dõi tài sản đã xuất cho các dự án.' : 'Theo dõi các đơn xuất dự án do bạn đề xuất.'} Tài sản đã xuất không hoàn lại kho.</p></div>
|
||||
<div class="compact-page-actions flex flex-wrap gap-2">
|
||||
<button id="refreshAssetExportsBtn" class="border border-slate-200 rounded-lg px-3 py-2 text-xs font-bold">Làm mới</button>
|
||||
<button id="createAssetExportBtn" class="bg-primary text-on-primary rounded-lg px-4 py-2 text-xs font-bold">Tạo đơn xuất dự án</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2 mb-4 shrink-0" role="tablist" aria-label="Danh sách xuất tài sản">
|
||||
<button id="assetExportRequestsTab" role="tab" aria-controls="assetExportsPanel" aria-selected="${this.assetExportTab === 'requests'}" class="px-4 py-2 rounded-lg text-sm font-bold border border-slate-200">Đơn đề xuất</button>
|
||||
<button id="assetExportHistoryTab" role="tab" aria-controls="assetExportsPanel" aria-selected="${this.assetExportTab === 'history'}" class="px-4 py-2 rounded-lg text-sm font-bold border border-slate-200">Lịch sử đã xuất</button>
|
||||
</div>
|
||||
<div class="page-filters flex flex-wrap items-center gap-3 mb-4 shrink-0">
|
||||
<input id="assetExportSearchInput" aria-label="Tìm đơn xuất" placeholder="Tìm mã đơn, tài sản, dự án, người đề xuất..." class="flex-1 min-w-0 border border-slate-200 rounded-lg px-3 py-2 text-sm" value="${this.escapeHtml(this.assetExportSearchTerm)}">
|
||||
<select id="assetExportStatusFilter" aria-label="Trạng thái đơn xuất" class="border border-slate-200 rounded-lg px-3 py-2 text-sm">
|
||||
<option value="">Tất cả trạng thái</option><option value="pending">Chờ duyệt</option><option value="approved">Đã duyệt / Đã xuất</option><option value="rejected">Đã từ chối</option>
|
||||
</select>
|
||||
</div>
|
||||
<p id="assetExportsFeedback" class="mb-3 text-sm text-slate-600" role="status"></p>
|
||||
<div id="assetExportsPanel" role="tabpanel" aria-labelledby="assetExportRequestsTab" class="flex flex-col min-h-0 bg-white rounded-xl border border-slate-200 overflow-hidden flex-1">
|
||||
<div class="overflow-auto flex-1"><table class="w-full text-left text-sm" style="min-width: 1080px;">
|
||||
<thead id="assetExportsTableHead" class="bg-slate-50 text-xs text-slate-500"></thead>
|
||||
<tbody id="assetExportsTableBody" class="divide-y divide-slate-100"></tbody>
|
||||
</table></div>
|
||||
<div id="assetExportsPager" class="page-pager flex items-center justify-between gap-2 px-4 py-2 border-t border-slate-200 bg-slate-50 text-xs text-slate-600"></div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
getFilteredAssetExportRows() {
|
||||
const history = this.assetExportTab === 'history';
|
||||
const search = String(this.assetExportSearchTerm || '').trim().toLocaleLowerCase('vi');
|
||||
return (history ? this.assetExportHistories : this.assetExportRequests).filter(row => {
|
||||
// The API also enforces ownership, including saved document URLs.
|
||||
if (!this.canCurrentUserManageAssets() && Number(row.CreatedBy) !== Number(this.getUserId())) return false;
|
||||
if (!history && this.assetExportStatusFilter && row.RequestStatus !== this.assetExportStatusFilter) return false;
|
||||
const values = history ? [row.AssetCode, row.AssetName, row.ProjectName, row.ExportedByName, row.ExportNote]
|
||||
: [row.ExportRequestId, row.RequesterName, row.ProcessedByName, row.RequestNote, row.RejectReason,
|
||||
...(row.Items || []).flatMap(item => [item.assetCode, item.assetName, item.model, ...item.allocations.map(allocation => allocation.projectName)])];
|
||||
return !search || values.some(value => String(value || '').toLocaleLowerCase('vi').includes(search));
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
this.assetExportHistories = Array.isArray(data.data) ? data.data : [];
|
||||
} else {
|
||||
console.error('Load asset export history failed:', data.message);
|
||||
}
|
||||
|
||||
renderAssetExportRequestsRows(rows) {
|
||||
const safe = value => this.escapeHtml(String(value || '-'));
|
||||
const manager = this.canCurrentUserManageAssets();
|
||||
return rows.map(row => {
|
||||
const pending = row.RequestStatus === 'pending';
|
||||
const status = { pending: ['Chờ duyệt', 'bg-amber-50 text-amber-700'], approved: ['Đã duyệt / Đã xuất', 'bg-emerald-50 text-emerald-700'], rejected: ['Đã từ chối', 'bg-red-50 text-red-700'] }[row.RequestStatus] || ['Không xác định', 'bg-slate-50'];
|
||||
const items = (row.Items || []).map(item => `<div class="mb-2"><div class="font-semibold">${safe(item.assetCode)} · ${safe(item.assetName)}</div>
|
||||
${item.allocations.map(allocation => `<div class="text-xs text-slate-600 mt-1">${safe(allocation.projectName)}: <strong>${Number(allocation.quantity)}</strong> ${safe(item.unit)}</div>`).join('')}</div>`).join('');
|
||||
return `<tr>
|
||||
<td class="px-4 py-3 whitespace-nowrap font-semibold">#${Number(row.ExportRequestId)}<div class="mt-1 text-xs font-normal text-slate-500">${this.formatDateTime(row.CreatedDate)}</div></td>
|
||||
<td class="px-4 py-3">${safe(row.RequesterName)}</td>
|
||||
<td class="px-4 py-3">${items}</td>
|
||||
<td class="px-4 py-3"><span class="inline-block rounded-lg px-2 py-1 text-xs font-bold ${status[1]}">${status[0]}</span></td>
|
||||
<td class="px-4 py-3 whitespace-pre-line text-slate-600">${safe(row.RequestNote)}${row.RejectReason ? `<div class="mt-2 text-red-700">Lý do từ chối: ${safe(row.RejectReason)}</div>` : ''}</td>
|
||||
<td class="px-4 py-3 text-slate-600">${safe(row.ProcessedByName)}${row.ProcessedDate ? `<div class="mt-1 text-xs">${this.formatDateTime(row.ProcessedDate)}</div>` : ''}</td>
|
||||
<td class="px-4 py-3">${manager && pending ? `<div class="flex gap-2">
|
||||
<button class="process-asset-export rounded-lg bg-primary text-on-primary px-3 py-2 text-xs font-bold" data-request-id="${Number(row.ExportRequestId)}" data-action="approved">Duyệt xuất</button>
|
||||
<button class="process-asset-export rounded-lg border border-red-200 text-red-700 px-3 py-2 text-xs font-bold" data-request-id="${Number(row.ExportRequestId)}" data-action="rejected">Từ chối</button></div>` : ''}
|
||||
${row.ExportDocumentId ? `<div class="flex gap-2 mt-2"><button class="view-asset-export-document rounded-lg border border-slate-200 px-2 py-1 text-xs text-primary" data-document-id="${safe(row.ExportDocumentId)}">Xem phiếu</button><button class="download-asset-export-document rounded-lg border border-slate-200 px-2 py-1 text-xs text-primary" data-document-id="${safe(row.ExportDocumentId)}" data-file-name="${safe(row.DocumentFileName || 'phieu-xuat.xlsx')}">Tải Excel</button></div>` : pending && !manager ? '<span class="text-xs text-slate-500">Chờ admin/asset duyệt</span>' : ''}
|
||||
</td></tr>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
renderAssetExportsTable() {
|
||||
if (this.currentPage !== 'asset-exports') return;
|
||||
const tbody = document.getElementById('assetExportsTableBody');
|
||||
if (!tbody) return;
|
||||
const history = this.assetExportTab === 'history';
|
||||
const columns = history ? ['Ngày xuất', 'Tài sản', 'Số lượng', 'Dự án', 'Người phụ trách', 'Người duyệt xuất', 'Ghi chú', 'Phiếu Excel']
|
||||
: ['Đơn / Ngày tạo', 'Người đề xuất', 'Tài sản / Dự án / Số lượng', 'Trạng thái', 'Ghi chú', 'Người xử lý', 'Thao tác'];
|
||||
document.getElementById('assetExportsTableHead').innerHTML = `<tr>${columns.map(label => `<th class="px-4 py-3 font-bold whitespace-nowrap">${label}</th>`).join('')}</tr>`;
|
||||
const page = this.getPaged(this.getFilteredAssetExportRows(), this.assetExportPage, 10);
|
||||
this.assetExportPage = page.current;
|
||||
tbody.innerHTML = this.assetExportLoading ? `<tr><td colspan="${columns.length}" class="px-4 py-8 text-center text-slate-500">Đang tải đơn xuất...</td></tr>`
|
||||
: !page.total ? `<tr><td colspan="${columns.length}" class="px-4 py-8 text-center text-slate-500">${this.assetExportLoadError ? 'Chưa tải được dữ liệu. Bấm Làm mới để thử lại.' : 'Chưa có đơn xuất phù hợp.'}</td></tr>`
|
||||
: history ? this.buildAssetExportHistoryRowsHtml(page.data) : this.renderAssetExportRequestsRows(page.data);
|
||||
document.getElementById('assetExportsFeedback').textContent = this.assetExportLoadError;
|
||||
document.getElementById('assetExportStatusFilter').hidden = history;
|
||||
document.getElementById('assetExportsPanel').setAttribute('aria-labelledby', history ? 'assetExportHistoryTab' : 'assetExportRequestsTab');
|
||||
for (const [id, selected] of [['assetExportRequestsTab', !history], ['assetExportHistoryTab', history]]) {
|
||||
const button = document.getElementById(id);
|
||||
button.setAttribute('aria-selected', String(selected));
|
||||
button.classList.toggle('bg-primary', selected);
|
||||
button.classList.toggle('text-on-primary', selected);
|
||||
}
|
||||
document.getElementById('assetExportsPager').innerHTML = `<span>Hiển thị ${page.start}-${page.end} / ${page.total}</span><div class="flex items-center gap-2">
|
||||
<button class="asset-export-page-btn border border-slate-200 rounded px-2 py-1" data-page="${page.current - 1}" ${page.current === 1 ? 'disabled' : ''}>Trước</button><span>Trang ${page.current} / ${page.totalPages}</span><button class="asset-export-page-btn border border-slate-200 rounded px-2 py-1" data-page="${page.current + 1}" ${page.current === page.totalPages ? 'disabled' : ''}>Sau</button></div>`;
|
||||
this.enhanceResponsiveTables(document.getElementById('assetExportsPanel'));
|
||||
}
|
||||
|
||||
async refreshAssetExportsPage() {
|
||||
if (this.assetExportLoading) return;
|
||||
this.assetExportLoading = true;
|
||||
this.assetExportLoadError = '';
|
||||
this.renderAssetExportsTable();
|
||||
try {
|
||||
const [requests, history] = await Promise.all([
|
||||
fetch(`${this.apiBase}/asset-export-requests`, { headers: this.getAuthHeaders(false), cache: 'no-store' }),
|
||||
fetch(`${this.apiBase}/asset-export-history?limit=2000`, { headers: this.getAuthHeaders(false), cache: 'no-store' })
|
||||
]);
|
||||
const [requestData, historyData] = await Promise.all([requests.json(), history.json()]);
|
||||
if (!requests.ok || !requestData.success || !history.ok || !historyData.success) throw new Error(requestData.message || historyData.message || 'Không tải được danh sách đơn xuất.');
|
||||
this.assetExportRequests = requestData.data || [];
|
||||
this.assetExportHistories = historyData.data || [];
|
||||
} catch (err) {
|
||||
console.error('Fetch asset export history error:', err);
|
||||
this.assetExportRequests = [];
|
||||
this.assetExportHistories = [];
|
||||
this.assetExportLoadError = err.message || 'Không tải được danh sách đơn xuất.';
|
||||
} finally {
|
||||
this.assetExportLoading = false;
|
||||
this.renderAssetExportsTable();
|
||||
}
|
||||
}
|
||||
|
||||
setupAssetExportsListeners() {
|
||||
document.getElementById('assetExportStatusFilter').value = this.assetExportStatusFilter;
|
||||
document.getElementById('assetExportStatusFilter').onchange = event => { this.assetExportStatusFilter = event.target.value; this.assetExportPage = 1; this.renderAssetExportsTable(); };
|
||||
document.getElementById('assetExportSearchInput').oninput = event => { this.assetExportSearchTerm = event.target.value; this.assetExportPage = 1; this.renderAssetExportsTable(); };
|
||||
document.getElementById('refreshAssetExportsBtn').onclick = () => this.refreshAssetExportsPage();
|
||||
document.getElementById('createAssetExportBtn').onclick = () => { location.hash = '#assets'; this.notifyWarning('Chọn một hoặc nhiều tài sản, sau đó bấm Tạo đơn xuất dự án.'); };
|
||||
for (const [id, tab] of [['assetExportRequestsTab', 'requests'], ['assetExportHistoryTab', 'history']]) {
|
||||
document.getElementById(id).onclick = () => { this.assetExportTab = tab; this.assetExportPage = 1; this.renderAssetExportsTable(); };
|
||||
}
|
||||
document.getElementById('assetExportsPanel').onclick = event => {
|
||||
const button = event.target.closest('button');
|
||||
if (!button) return;
|
||||
if (button.matches('.asset-export-page-btn')) { this.assetExportPage = Number(button.dataset.page); this.renderAssetExportsTable(); }
|
||||
if (button.matches('.view-asset-export-document')) this.openSavedAssetExportPreview(button.dataset.documentId);
|
||||
if (button.matches('.download-asset-export-document')) this.downloadSavedAssetExport(button.dataset.documentId, button.dataset.fileName, button);
|
||||
if (button.matches('.process-asset-export')) this.openAssetExportProcessModal(Number(button.dataset.requestId), button.dataset.action);
|
||||
};
|
||||
this.renderAssetExportsTable();
|
||||
}
|
||||
|
||||
openAssetExportProcessModal(requestId, action) {
|
||||
if (!this.canCurrentUserManageAssets() || this.assetExportProcessing) return;
|
||||
const modal = document.getElementById('assetExportProcessModal');
|
||||
const rejected = action === 'rejected';
|
||||
const reason = document.getElementById('assetExportRejectReason');
|
||||
reason.value = '';
|
||||
reason.required = rejected;
|
||||
document.getElementById('assetExportRejectField').hidden = !rejected;
|
||||
document.getElementById('assetExportProcessTitle').textContent = `${rejected ? 'Từ chối' : 'Duyệt xuất dự án'} — Đơn #${requestId}`;
|
||||
document.getElementById('assetExportProcessMessage').textContent = rejected ? 'Nhập lý do để người đề xuất biết và điều chỉnh.' : 'Khi duyệt, toàn bộ số lượng trong đơn sẽ được xuất vào các dự án đã chọn và trừ tồn kho. Tài sản đã xuất không hoàn lại kho.';
|
||||
document.getElementById('assetExportProcessSubmit').textContent = rejected ? 'Từ chối đơn' : 'Duyệt và xuất vào dự án';
|
||||
document.getElementById('assetExportProcessForm').onsubmit = event => { event.preventDefault(); this.processAssetExportRequest(requestId, action, reason.value.trim()); };
|
||||
modal.classList.add('open');
|
||||
if (rejected) reason.focus();
|
||||
}
|
||||
|
||||
async processAssetExportRequest(requestId, action, rejectReason) {
|
||||
if (!this.canCurrentUserManageAssets() || this.assetExportProcessing) return;
|
||||
const button = document.getElementById('assetExportProcessSubmit');
|
||||
this.assetExportProcessing = true;
|
||||
button.disabled = true;
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/asset-export-requests/${requestId}/process`, { method: 'POST', headers: this.getAuthHeaders(true), body: JSON.stringify({ action, rejectReason }) });
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) { this.notifyFailure(data.message || 'Không xử lý được đơn xuất.'); return; }
|
||||
document.getElementById('assetExportProcessModal').classList.remove('open');
|
||||
this.notifySuccess(data.message);
|
||||
await Promise.all([this.refreshAssetExportsPage(), this.fetchAssets()]);
|
||||
} catch (err) { this.notifyFailure(err.message || 'Không xử lý được đơn xuất.'); }
|
||||
finally { this.assetExportProcessing = false; button.disabled = false; }
|
||||
}
|
||||
|
||||
buildAssetExportHistoryRowsHtml(rows = []) {
|
||||
if (!Array.isArray(rows) || rows.length === 0) {
|
||||
return `
|
||||
@@ -2139,42 +2303,8 @@ class AccountManager {
|
||||
}).join('');
|
||||
}
|
||||
|
||||
renderAssetExportHistoryModal() {
|
||||
const tbody = document.getElementById('assetExportHistoryTableBody');
|
||||
if (!tbody) {
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = this.buildAssetExportHistoryRowsHtml(this.assetExportHistories);
|
||||
tbody.querySelectorAll('.view-asset-export-document').forEach(button => {
|
||||
button.onclick = () => this.openSavedAssetExportPreview(button.dataset.documentId);
|
||||
});
|
||||
tbody.querySelectorAll('.download-asset-export-document').forEach(button => {
|
||||
button.onclick = () => this.downloadSavedAssetExport(button.dataset.documentId, button.dataset.fileName, button);
|
||||
});
|
||||
}
|
||||
|
||||
async openAssetExportHistoryModal() {
|
||||
if (!this.ensureAssetManagePermission('xem lich su xuat tai san')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const modal = document.getElementById('assetExportHistoryModal');
|
||||
const tbody = document.getElementById('assetExportHistoryTableBody');
|
||||
if (!modal || !tbody) {
|
||||
this.notifyFailure('Không tìm thấy biểu mẫu lịch sử xuất tài sản.');
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = `
|
||||
<tr>
|
||||
<td colspan="8" class="px-4 py-8 text-sm text-center text-slate-500">Đang tải lịch sử xuất...</td>
|
||||
</tr>
|
||||
`;
|
||||
modal.classList.add('open');
|
||||
|
||||
await this.fetchAssetExportHistories();
|
||||
this.renderAssetExportHistoryModal();
|
||||
openAssetExportsPage() {
|
||||
location.hash = '#asset-exports';
|
||||
}
|
||||
|
||||
buildSavedAssetExportPreviewHtml(snapshot) {
|
||||
@@ -2198,7 +2328,7 @@ class AccountManager {
|
||||
return `<div class="grid grid-cols-1 md:grid-cols-2 gap-3 rounded-lg bg-slate-50 p-4 text-sm text-slate-700">
|
||||
<p><span class="font-semibold">Ngày xuất:</span> ${this.formatDateTime(snapshot.exportedDate)}</p>
|
||||
<p><span class="font-semibold">Người xuất:</span> ${safe(snapshot.exportedByName)}</p>
|
||||
<p><span class="font-semibold">Người mượn:</span> ${safe(snapshot.borrowerName)}</p>
|
||||
<p><span class="font-semibold">Người đề xuất:</span> ${safe(snapshot.requesterName || snapshot.borrowerName)}</p>
|
||||
<p><span class="font-semibold">Số tài sản:</span> ${(snapshot.items || []).length}</p>
|
||||
<p class="md:col-span-2 whitespace-pre-line"><span class="font-semibold">Ghi chú:</span> ${safe(snapshot.note)}</p>
|
||||
</div>
|
||||
@@ -2211,7 +2341,6 @@ class AccountManager {
|
||||
}
|
||||
|
||||
async openSavedAssetExportPreview(documentId) {
|
||||
if (!this.ensureAssetManagePermission('xem phiếu xuất tài sản')) return;
|
||||
const modal = document.getElementById('assetExportPreviewModal');
|
||||
const content = document.getElementById('assetExportPreviewContent');
|
||||
const downloadButton = document.getElementById('assetExportPreviewDownloadBtn');
|
||||
@@ -2236,7 +2365,6 @@ class AccountManager {
|
||||
}
|
||||
|
||||
async downloadSavedAssetExport(documentId, fileName, button) {
|
||||
if (!this.ensureAssetManagePermission('tải phiếu xuất tài sản')) return;
|
||||
if (button?.disabled) return;
|
||||
if (button) button.disabled = true;
|
||||
try {
|
||||
@@ -7683,7 +7811,7 @@ class AccountManager {
|
||||
<article class="asset-mobile-card rounded-xl border border-slate-200 bg-white p-3 shadow-sm">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="flex min-w-0 items-start gap-2">
|
||||
<input type="checkbox" class="asset-row-checkbox mt-1 w-4 h-4 shrink-0" data-asset-id="${asset?.AssetId}" ${isSelected ? 'checked' : ''} ${canManageAssets ? '' : 'disabled'} aria-label="Chọn tài sản ${safe(asset?.AssetCode)}">
|
||||
<input type="checkbox" class="asset-row-checkbox mt-1 w-4 h-4 shrink-0" data-asset-id="${asset?.AssetId}" ${isSelected ? 'checked' : ''} aria-label="Chọn tài sản ${safe(asset?.AssetCode)}">
|
||||
<div class="min-w-0">
|
||||
<div class="text-[10px] font-bold uppercase tracking-wider text-slate-400">#${rowNumber} · ${safe(asset?.AssetCode)}</div>
|
||||
<h3 class="mt-0.5 text-sm font-extrabold text-slate-800">${safe(asset?.AssetName)}</h3>
|
||||
@@ -7734,12 +7862,12 @@ class AccountManager {
|
||||
const canManageAssets = this.canCurrentUserManageAssets();
|
||||
const filteredAssets = this.getFilteredAssets();
|
||||
const pageInfo = this.getPaged(filteredAssets, this.assetPage, this.assetPageSize);
|
||||
const selectedCount = canManageAssets ? this.selectedAssetIds.size : 0;
|
||||
const selectedCount = this.selectedAssetIds.size;
|
||||
const pageAssetIds = pageInfo.data
|
||||
.map(asset => Number(asset.AssetId))
|
||||
.filter(id => Number.isFinite(id));
|
||||
const selectedOnPageCount = pageAssetIds.filter(id => this.selectedAssetIds.has(id)).length;
|
||||
const allOnPageSelected = canManageAssets && pageAssetIds.length > 0 && selectedOnPageCount === pageAssetIds.length;
|
||||
const allOnPageSelected = pageAssetIds.length > 0 && selectedOnPageCount === pageAssetIds.length;
|
||||
this.assetPage = pageInfo.current;
|
||||
|
||||
return `
|
||||
@@ -7766,7 +7894,7 @@ class AccountManager {
|
||||
<span class="material-symbols-outlined text-base">download</span>
|
||||
Xuất Excel
|
||||
</button>
|
||||
<button id="openAssetExportHistoryBtn" class="border border-amber-300 text-amber-700 px-3 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all active:scale-95 ${canManageAssets ? 'hover:bg-amber-50' : 'opacity-50 cursor-not-allowed'}" ${canManageAssets ? '' : 'disabled'}>
|
||||
<button id="openAssetExportHistoryBtn" class="border border-amber-300 text-amber-700 px-3 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all active:scale-95 hover:bg-amber-50">
|
||||
<span class="material-symbols-outlined text-base">history</span>
|
||||
Lịch sử xuất
|
||||
</button>
|
||||
@@ -7778,9 +7906,9 @@ class AccountManager {
|
||||
<span class="material-symbols-outlined text-base">add_box</span>
|
||||
Thêm tài sản
|
||||
</button>
|
||||
<button id="borrowAssetBtn" class="border border-primary text-primary px-4 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all active:scale-95 ${(canManageAssets && selectedCount > 0) ? 'hover:bg-primary/5' : 'opacity-50 cursor-not-allowed'}" ${(canManageAssets && selectedCount > 0) ? '' : 'disabled'}>
|
||||
<button id="borrowAssetBtn" class="border border-primary text-primary px-4 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all active:scale-95 ${(selectedCount > 0) ? 'hover:bg-primary/5' : 'opacity-50 cursor-not-allowed'}" ${(selectedCount > 0) ? '' : 'disabled'}>
|
||||
<span class="material-symbols-outlined text-base">handshake</span>
|
||||
Xuất tài sản
|
||||
Tạo đơn xuất dự án
|
||||
</button>
|
||||
<button id="damageAssetBtn" class="border border-red-300 text-red-700 px-4 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all active:scale-95 ${(canManageAssets && selectedCount === 1) ? 'hover:bg-red-50' : 'opacity-50 cursor-not-allowed'}" ${(canManageAssets && selectedCount === 1) ? '' : 'disabled'}>
|
||||
<span class="material-symbols-outlined text-base">broken_image</span>
|
||||
@@ -7817,7 +7945,7 @@ class AccountManager {
|
||||
<thead class="sticky top-0 z-50 bg-slate-50 border-b border-slate-200">
|
||||
<tr>
|
||||
<th class="px-4 py-2.5 text-center">
|
||||
<input type="checkbox" id="selectAllAssetsCheckbox" class="w-4 h-4" ${allOnPageSelected ? 'checked' : ''} ${canManageAssets ? '' : 'disabled'} title="Chọn tất cả dòng trong trang hiện tại">
|
||||
<input type="checkbox" id="selectAllAssetsCheckbox" class="w-4 h-4" ${allOnPageSelected ? 'checked' : ''} title="Chọn tất cả dòng trong trang hiện tại">
|
||||
</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">STT</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Mã</th>
|
||||
@@ -7855,7 +7983,7 @@ class AccountManager {
|
||||
return `
|
||||
<tr class="group hover:bg-slate-50/80 transition-colors">
|
||||
<td class="px-4 py-3 text-center">
|
||||
<input type="checkbox" class="asset-row-checkbox w-4 h-4" data-asset-id="${asset.AssetId}" ${isSelected ? 'checked' : ''} ${canManageAssets ? '' : 'disabled'}>
|
||||
<input type="checkbox" class="asset-row-checkbox w-4 h-4" data-asset-id="${asset.AssetId}" ${isSelected ? 'checked' : ''}>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${rowNumber}</td>
|
||||
<td class="px-4 py-3 text-sm font-semibold text-slate-700">${asset.AssetCode || '-'}</td>
|
||||
@@ -7946,7 +8074,7 @@ class AccountManager {
|
||||
return `
|
||||
<tr class="group hover:bg-slate-50/80 transition-colors">
|
||||
<td class="px-4 py-3 text-center">
|
||||
<input type="checkbox" class="asset-row-checkbox w-4 h-4" data-asset-id="${asset.AssetId}" ${isSelected ? 'checked' : ''} ${canManageAssets ? '' : 'disabled'}>
|
||||
<input type="checkbox" class="asset-row-checkbox w-4 h-4" data-asset-id="${asset.AssetId}" ${isSelected ? 'checked' : ''}>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${rowNumber}</td>
|
||||
<td class="px-4 py-3 text-sm font-semibold text-slate-700">${asset.AssetCode || '-'}</td>
|
||||
@@ -8015,22 +8143,6 @@ class AccountManager {
|
||||
}
|
||||
|
||||
setupAssetSelectionListeners() {
|
||||
if (!this.canCurrentUserManageAssets()) {
|
||||
this.selectedAssetIds.clear();
|
||||
document.querySelectorAll('.asset-row-checkbox').forEach(checkbox => {
|
||||
checkbox.checked = false;
|
||||
checkbox.disabled = true;
|
||||
});
|
||||
const selectAllCheckbox = document.getElementById('selectAllAssetsCheckbox');
|
||||
if (selectAllCheckbox) {
|
||||
selectAllCheckbox.checked = false;
|
||||
selectAllCheckbox.indeterminate = false;
|
||||
selectAllCheckbox.disabled = true;
|
||||
}
|
||||
this.updateAssetBulkActionState();
|
||||
return;
|
||||
}
|
||||
|
||||
document.querySelectorAll('.asset-row-checkbox').forEach(checkbox => {
|
||||
checkbox.addEventListener('change', () => {
|
||||
const assetId = Number(checkbox.dataset.assetId);
|
||||
@@ -8099,23 +8211,17 @@ class AccountManager {
|
||||
});
|
||||
const selectedOnPage = Array.from(assetSelectionById.values()).filter(Boolean).length;
|
||||
|
||||
if (!canManageAssets) {
|
||||
this.selectedAssetIds.clear();
|
||||
}
|
||||
rowCheckboxes.forEach(checkbox => {
|
||||
checkbox.disabled = !canManageAssets;
|
||||
});
|
||||
|
||||
const selectAllCheckbox = document.getElementById('selectAllAssetsCheckbox');
|
||||
if (selectAllCheckbox) {
|
||||
const assetCountOnPage = assetSelectionById.size;
|
||||
const hasRows = assetCountOnPage > 0;
|
||||
selectAllCheckbox.checked = canManageAssets && hasRows && selectedOnPage === assetCountOnPage;
|
||||
selectAllCheckbox.indeterminate = canManageAssets && selectedOnPage > 0 && selectedOnPage < assetCountOnPage;
|
||||
selectAllCheckbox.disabled = !canManageAssets;
|
||||
selectAllCheckbox.checked = hasRows && selectedOnPage === assetCountOnPage;
|
||||
selectAllCheckbox.indeterminate = selectedOnPage > 0 && selectedOnPage < assetCountOnPage;
|
||||
selectAllCheckbox.disabled = !hasRows;
|
||||
}
|
||||
|
||||
const selectedCount = canManageAssets ? this.selectedAssetIds.size : 0;
|
||||
const selectedCount = this.selectedAssetIds.size;
|
||||
const selectedCountNode = document.getElementById('selectedAssetCount');
|
||||
if (selectedCountNode) {
|
||||
selectedCountNode.textContent = String(selectedCount);
|
||||
@@ -8131,7 +8237,7 @@ class AccountManager {
|
||||
|
||||
const borrowAssetBtn = document.getElementById('borrowAssetBtn');
|
||||
if (borrowAssetBtn) {
|
||||
const disabled = !canManageAssets || selectedCount === 0;
|
||||
const disabled = selectedCount === 0;
|
||||
borrowAssetBtn.disabled = disabled;
|
||||
borrowAssetBtn.classList.toggle('opacity-50', disabled);
|
||||
borrowAssetBtn.classList.toggle('cursor-not-allowed', disabled);
|
||||
@@ -8251,9 +8357,16 @@ class AccountManager {
|
||||
return (this.archivedAssets || []).map(asset => {
|
||||
const borrowerQuantity = this.parseBorrowerEntries(asset.Borrower)
|
||||
.reduce((sum, entry) => sum + this.parseNonNegativeInteger(entry.quantity, 0), 0);
|
||||
let allocations = asset.ProjectAllocations || [];
|
||||
if (typeof allocations === 'string') {
|
||||
try { allocations = JSON.parse(allocations); } catch { allocations = []; }
|
||||
}
|
||||
const permanentQuantity = (Array.isArray(allocations) ? allocations : [])
|
||||
.filter(row => row.allocationType === 'export')
|
||||
.reduce((sum, row) => sum + this.parseNonNegativeInteger(row.quantity, 0), 0);
|
||||
return {
|
||||
...asset,
|
||||
OutstandingQuantity: Math.max(borrowerQuantity, this.parseNonNegativeInteger(asset.ExportInPeriod, 0))
|
||||
OutstandingQuantity: Math.max(borrowerQuantity, this.parseNonNegativeInteger(asset.ExportInPeriod, 0) - permanentQuantity)
|
||||
};
|
||||
}).filter(asset => !search || [
|
||||
asset.AssetId, asset.AssetCode, asset.AssetName, asset.Model, asset.SerialNumber,
|
||||
@@ -8883,7 +8996,6 @@ class AccountManager {
|
||||
}
|
||||
|
||||
async openBatchAssetExportModal() {
|
||||
if (!this.ensureAssetManagePermission('xuất nhiều tài sản')) return;
|
||||
const assets = this.assets.filter(asset => this.selectedAssetIds.has(Number(asset.AssetId)));
|
||||
if (!assets.length || assets.length > 100) {
|
||||
this.notifyWarning('Vui lòng chọn từ 1 đến 100 tài sản để xuất.');
|
||||
@@ -8894,12 +9006,11 @@ class AccountManager {
|
||||
this.notifyWarning(`${unavailable.AssetCode || unavailable.AssetName}: đã hết tồn, hãy bỏ chọn tài sản này.`);
|
||||
return;
|
||||
}
|
||||
if (!this.users.length) await this.fetchUsers();
|
||||
if (!this.assetProjects.length) await this.fetchAssetProjects();
|
||||
const modal = document.getElementById('batchAssetExportModal');
|
||||
const form = document.getElementById('batchAssetExportForm');
|
||||
if (!modal || !form) { this.notifyFailure('Không tìm thấy biểu mẫu xuất nhiều tài sản.'); return; }
|
||||
this.populateUserSelectOptions('batchAssetExportUserInput', { selectedValue: '', emptyLabel: '-- Chọn người mượn --' });
|
||||
document.getElementById('batchAssetExportUserInput').value = this.getCurrentUserDisplayName();
|
||||
const commonProject = document.getElementById('batchAssetExportCommonProject');
|
||||
commonProject.innerHTML = '<option value="">-- Áp dụng dự án cho tất cả --</option>'
|
||||
+ this.getUniqueAssetProjectNames().map(name => `<option value="${this.escapeHtml(name)}">${this.escapeHtml(name)}</option>`).join('');
|
||||
@@ -8921,11 +9032,11 @@ class AccountManager {
|
||||
|
||||
async handleBatchAssetExportSubmit(event) {
|
||||
event.preventDefault();
|
||||
if (!this.ensureAssetManagePermission('xuất nhiều tài sản') || this.assetExportSubmitting) return;
|
||||
if (this.assetExportSubmitting) return;
|
||||
const items = this.collectBatchAssetExportItems();
|
||||
const borrowerName = String(document.getElementById('batchAssetExportUserInput')?.value || '').trim();
|
||||
const note = String(document.getElementById('batchAssetExportNoteInput')?.value || '').trim();
|
||||
if (!borrowerName) { this.notifyWarning('Vui lòng chọn người mượn.'); return; }
|
||||
if (!borrowerName) { this.notifyWarning('Không xác định được người đề xuất.'); return; }
|
||||
if (!items.length || items.length > 100) { this.notifyWarning('Vui lòng chọn từ 1 đến 100 tài sản.'); return; }
|
||||
for (const item of items) {
|
||||
const asset = this.assets.find(asset => Number(asset.AssetId) === item.assetId);
|
||||
@@ -8940,20 +9051,23 @@ class AccountManager {
|
||||
if (button) button.disabled = true;
|
||||
let exportSucceeded = false;
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/assets/export`, {
|
||||
const response = await fetch(`${this.apiBase}/asset-export-requests`, {
|
||||
method: 'POST', headers: this.getAuthHeaders(true), body: JSON.stringify({ borrowerName, note, items })
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) { this.notifyFailure(data.message || 'Xuất tài sản thất bại.'); return; }
|
||||
exportSucceeded = true;
|
||||
this.selectedAssetIds.clear();
|
||||
this.notifySuccess(`Đã xuất ${items.length} tài sản và lưu phiếu Excel vào lịch sử.`);
|
||||
this.notifySuccess('Đã gửi đơn xuất vào dự án, chờ admin/asset duyệt.');
|
||||
this.closeModals();
|
||||
this.showExportRequestDocument(data.document);
|
||||
await this.refreshAssetsUI();
|
||||
this.assetExportTab = 'requests';
|
||||
this.assetExportPage = 1;
|
||||
this.assetExportSearchTerm = '';
|
||||
this.assetExportStatusFilter = '';
|
||||
location.hash = '#asset-exports';
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
if (exportSucceeded) this.notifyWarning('Đã xuất tài sản thành công. Chưa cập nhật được danh sách; hãy tải lại trang.');
|
||||
if (exportSucceeded) this.notifyWarning('Đã gửi đơn xuất. Hãy mở danh sách đơn xuất để kiểm tra.');
|
||||
else this.notifyFailure('Xuất tài sản thất bại.');
|
||||
} finally {
|
||||
this.assetExportSubmitting = false;
|
||||
@@ -9005,19 +9119,12 @@ class AccountManager {
|
||||
}
|
||||
|
||||
async openBorrowAssetModal() {
|
||||
if (!this.ensureAssetManagePermission('xuat tai san')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.selectedAssetIds.size > 1) return this.openBatchAssetExportModal();
|
||||
const asset = this.getSingleSelectedAssetForBorrowing(true);
|
||||
if (!asset) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.users.length) {
|
||||
await this.fetchUsers();
|
||||
}
|
||||
if (!this.assetProjects.length) {
|
||||
await this.fetchAssetProjects();
|
||||
}
|
||||
@@ -9036,8 +9143,6 @@ class AccountManager {
|
||||
const quantityInput = document.getElementById('borrowQuantityInput');
|
||||
const projectInput = document.getElementById('borrowAssetProjectInput');
|
||||
const noteInput = document.getElementById('borrowAssetNoteInput');
|
||||
const borrowByInput = document.getElementById('borrowByInput');
|
||||
const borrowRoleInput = document.getElementById('borrowRoleInput');
|
||||
const modal = document.getElementById('borrowAssetModal');
|
||||
|
||||
if (!modal || !assetNameInput || !endingInput || !quantityInput || !projectInput || !noteInput) {
|
||||
@@ -9055,7 +9160,7 @@ class AccountManager {
|
||||
quantityInput.min = '1';
|
||||
quantityInput.max = String(available);
|
||||
|
||||
this.refreshBorrowAssetUserOptions('');
|
||||
document.getElementById('borrowAssetUserInput').value = this.getCurrentUserDisplayName();
|
||||
this.refreshBorrowAssetProjectOptions(String(asset?.Project || '').trim());
|
||||
noteInput.value = '';
|
||||
document.getElementById('borrowAdditionalProjects').innerHTML = '';
|
||||
@@ -9065,24 +9170,12 @@ class AccountManager {
|
||||
document.getElementById('borrowAssetForm').oninput = () => this.updateBorrowAllocationSummary();
|
||||
this.updateBorrowAllocationSummary();
|
||||
|
||||
if (borrowByInput) {
|
||||
borrowByInput.value = this.getCurrentUserDisplayName();
|
||||
}
|
||||
|
||||
if (borrowRoleInput) {
|
||||
borrowRoleInput.value = String(this.getCurrentUserRoleRaw() || '').trim() || '-';
|
||||
}
|
||||
|
||||
modal.classList.add('open');
|
||||
}
|
||||
|
||||
async handleBorrowAssetSubmit(e) {
|
||||
e.preventDefault();
|
||||
|
||||
if (!this.ensureAssetManagePermission('xuat tai san')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const assetIdInput = document.getElementById('borrowAssetIdInput');
|
||||
const borrowerInput = document.getElementById('borrowAssetUserInput');
|
||||
const noteInput = document.getElementById('borrowAssetNoteInput');
|
||||
@@ -9101,7 +9194,7 @@ class AccountManager {
|
||||
|
||||
const borrowerName = String(borrowerInput?.value || '').trim();
|
||||
if (!borrowerName) {
|
||||
this.notifyWarning('Vui lòng chọn người mượn.');
|
||||
this.notifyWarning('Không xác định được người đề xuất.');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -9134,14 +9227,11 @@ class AccountManager {
|
||||
if (submitButton) submitButton.disabled = true;
|
||||
let exportSucceeded = false;
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/assets/${selectedAssetId}/export`, {
|
||||
const response = await fetch(`${this.apiBase}/asset-export-requests`, {
|
||||
method: 'POST',
|
||||
headers: this.getAuthHeaders(true),
|
||||
body: JSON.stringify({
|
||||
quantity: borrowQuantity,
|
||||
borrowerName,
|
||||
custodianName: borrowerName,
|
||||
allocations,
|
||||
items: [{ assetId: selectedAssetId, allocations }],
|
||||
note: exportNote
|
||||
})
|
||||
});
|
||||
@@ -9154,18 +9244,17 @@ class AccountManager {
|
||||
|
||||
exportSucceeded = true;
|
||||
this.pendingBorrowAssetId = undefined;
|
||||
this.notifySuccess('Xuất tài sản thành công');
|
||||
this.selectedAssetIds.clear();
|
||||
this.notifySuccess('Đã gửi đơn xuất vào dự án, chờ admin/asset duyệt.');
|
||||
this.closeModals();
|
||||
this.showExportRequestDocument(data.document);
|
||||
await this.refreshAssetsUI();
|
||||
const exportHistoryModal = document.getElementById('assetExportHistoryModal');
|
||||
if (exportHistoryModal?.classList.contains('open')) {
|
||||
await this.fetchAssetExportHistories();
|
||||
this.renderAssetExportHistoryModal();
|
||||
}
|
||||
this.assetExportTab = 'requests';
|
||||
this.assetExportPage = 1;
|
||||
this.assetExportSearchTerm = '';
|
||||
this.assetExportStatusFilter = '';
|
||||
location.hash = '#asset-exports';
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
if (exportSucceeded) this.notifyWarning('Đã xuất tài sản thành công. Chưa cập nhật được danh sách; hãy tải lại trang.');
|
||||
if (exportSucceeded) this.notifyWarning('Đã gửi đơn xuất. Hãy mở danh sách đơn xuất để kiểm tra.');
|
||||
else this.notifyFailure('Xuất tài sản thất bại');
|
||||
} finally {
|
||||
this.assetExportSubmitting = false;
|
||||
@@ -11980,7 +12069,7 @@ class AccountManager {
|
||||
}
|
||||
|
||||
if (openAssetExportHistoryBtn && !openAssetExportHistoryBtn.dataset.boundClick) {
|
||||
openAssetExportHistoryBtn.addEventListener('click', () => this.openAssetExportHistoryModal());
|
||||
openAssetExportHistoryBtn.addEventListener('click', () => this.openAssetExportsPage());
|
||||
openAssetExportHistoryBtn.dataset.boundClick = 'true';
|
||||
}
|
||||
|
||||
@@ -13310,13 +13399,6 @@ function closeAssetDamageModal() {
|
||||
}
|
||||
}
|
||||
|
||||
function closeAssetExportHistoryModal() {
|
||||
const modal = document.getElementById('assetExportHistoryModal');
|
||||
if (modal) {
|
||||
modal.classList.remove('open');
|
||||
}
|
||||
}
|
||||
|
||||
function closeAssetDamageHistoryModal() {
|
||||
const modal = document.getElementById('assetDamageHistoryModal');
|
||||
if (modal) {
|
||||
|
||||
@@ -702,13 +702,14 @@
|
||||
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="borrowAssetModal">
|
||||
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
|
||||
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
|
||||
<h3 class="text-base font-extrabold text-slate-900">Xuất tài sản</h3>
|
||||
<h3 class="text-base font-extrabold text-slate-900">Tạo đơn xuất tài sản vào dự án</h3>
|
||||
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400 transition-colors" data-close-modal="borrowAssetModal">
|
||||
<span class="material-symbols-outlined">close</span>
|
||||
</button>
|
||||
</div>
|
||||
<form id="borrowAssetForm" class="p-6 space-y-4 overflow-y-auto" style="max-height: 80vh;">
|
||||
<input type="hidden" id="borrowAssetIdInput">
|
||||
<p class="text-sm text-slate-600">Xuất vào dự án, không hoàn lại kho. Số lượng chỉ trừ khi admin/asset duyệt đơn.</p>
|
||||
<p id="borrowAssetStockSummary" class="text-sm font-semibold text-slate-700"></p>
|
||||
<div>
|
||||
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Tài sản</label>
|
||||
@@ -720,10 +721,8 @@
|
||||
<input type="number" id="borrowCurrentEndingInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
|
||||
</div>
|
||||
<div>
|
||||
<label for="borrowAssetUserInput" class="text-xs font-bold text-slate-500 block mb-1">Người mượn</label>
|
||||
<select id="borrowAssetUserInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" required>
|
||||
<option value="">-- Chọn người mượn --</option>
|
||||
</select>
|
||||
<label for="borrowAssetUserInput" class="text-xs font-bold text-slate-500 block mb-1">Người đề xuất</label>
|
||||
<input type="text" id="borrowAssetUserInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly required>
|
||||
</div>
|
||||
<div class="md:col-span-2 space-y-3">
|
||||
<div class="flex items-end gap-2">
|
||||
@@ -740,22 +739,14 @@
|
||||
<button type="button" id="addBorrowProjectBtn" class="mt-2 px-3 py-2 text-xs font-bold text-primary border border-slate-200 rounded-lg">+ Thêm dự án</button>
|
||||
<p id="borrowAllocationSummary" class="mt-2 text-sm font-semibold" aria-live="polite"></p>
|
||||
</div>
|
||||
<div>
|
||||
<label for="borrowByInput" class="text-xs font-bold text-slate-500 block mb-1">Người xuất</label>
|
||||
<input type="text" id="borrowByInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
|
||||
</div>
|
||||
<div>
|
||||
<label for="borrowRoleInput" class="text-xs font-bold text-slate-500 block mb-1">Role người thao tác</label>
|
||||
<input type="text" id="borrowRoleInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<label for="borrowAssetNoteInput" class="text-xs font-bold text-slate-500 block mb-1">Ghi chú xuất</label>
|
||||
<textarea id="borrowAssetNoteInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 h-20 resize-none" placeholder="Nhập ghi chú (nếu có)"></textarea>
|
||||
<textarea id="borrowAssetNoteInput" maxlength="1000" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 h-20 resize-none" placeholder="Nhập ghi chú (nếu có)"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-3 pt-2">
|
||||
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg" data-close-modal="borrowAssetModal">Hủy</button>
|
||||
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Xuất và tải Excel</button>
|
||||
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Gửi đơn chờ duyệt</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -765,12 +756,12 @@
|
||||
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="batchAssetExportModal">
|
||||
<div class="modal-content w-full max-w-5xl bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4 flex flex-col" style="max-height: calc(100vh - 2rem);">
|
||||
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
|
||||
<div><h3 class="text-base font-extrabold text-slate-900">Xuất nhiều tài sản</h3><p class="mt-1 text-xs text-slate-500">Chọn số lượng và dự án cho từng tài sản trong một phiếu.</p></div>
|
||||
<div><h3 class="text-base font-extrabold text-slate-900">Tạo đơn xuất nhiều tài sản vào dự án</h3><p class="mt-1 text-xs text-slate-500">Chọn số lượng và dự án cho từng tài sản. Chỉ trừ kho khi được duyệt; tài sản xuất không hoàn lại kho.</p></div>
|
||||
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400" data-close-modal="batchAssetExportModal" aria-label="Đóng"><span class="material-symbols-outlined">close</span></button>
|
||||
</div>
|
||||
<form id="batchAssetExportForm" class="p-6 space-y-4 overflow-y-auto">
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<label class="text-xs font-semibold text-slate-600">Người mượn<select id="batchAssetExportUserInput" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm" required><option value="">-- Chọn người mượn --</option></select></label>
|
||||
<label class="text-xs font-semibold text-slate-600">Người đề xuất<input id="batchAssetExportUserInput" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm bg-slate-50" readonly required></label>
|
||||
<label class="text-xs font-semibold text-slate-600">Dự án chung (tùy chọn)<select id="batchAssetExportCommonProject" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"><option value="">-- Áp dụng dự án cho tất cả --</option></select></label>
|
||||
</div>
|
||||
<p id="batchAssetExportSummary" class="text-sm font-semibold text-slate-700" aria-live="polite"></p>
|
||||
@@ -783,7 +774,7 @@
|
||||
<label class="block text-xs font-semibold text-slate-600">Ghi chú xuất<textarea id="batchAssetExportNoteInput" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm h-20 resize-none" maxlength="1000" placeholder="Nhập ghi chú (nếu có)"></textarea></label>
|
||||
<div class="flex gap-3 pt-2">
|
||||
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg" data-close-modal="batchAssetExportModal">Hủy</button>
|
||||
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Xuất và tải Excel</button>
|
||||
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Gửi đơn chờ duyệt</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -864,48 +855,24 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Asset Export History Modal -->
|
||||
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="assetExportHistoryModal" style="z-index: 125;">
|
||||
<div class="modal-content asset-export-history-dialog bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden flex flex-col">
|
||||
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50 shrink-0">
|
||||
<h3 class="text-base font-extrabold text-slate-900">Lịch sử xuất tài sản</h3>
|
||||
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400 transition-colors" data-close-modal="assetExportHistoryModal">
|
||||
<span class="material-symbols-outlined">close</span>
|
||||
</button>
|
||||
<!-- Approve/reject a project export proposal -->
|
||||
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="assetExportProcessModal">
|
||||
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
|
||||
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
|
||||
<h3 id="assetExportProcessTitle" class="text-base font-extrabold text-slate-900">Duyệt xuất dự án</h3>
|
||||
<button type="button" class="p-1.5 rounded-lg text-slate-500" data-close-modal="assetExportProcessModal" aria-label="Đóng"><span class="material-symbols-outlined">close</span></button>
|
||||
</div>
|
||||
<div class="p-6 pt-4 min-h-0">
|
||||
<div class="asset-export-history-scroll rounded-xl border border-slate-200">
|
||||
<table class="asset-export-history-table w-full text-left">
|
||||
<colgroup>
|
||||
<col style="width: 180px;">
|
||||
<col>
|
||||
<col style="width: 88px;">
|
||||
<col style="width: 144px;">
|
||||
<col style="width: 156px;">
|
||||
<col style="width: 140px;">
|
||||
<col style="width: 168px;">
|
||||
<col style="width: 248px;">
|
||||
</colgroup>
|
||||
<thead class="bg-slate-50 border-b border-slate-200">
|
||||
<tr>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Ngày giờ</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Tài sản</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Số lượng</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Dự án</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Người phụ trách</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Người xuất</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Ghi chú</th>
|
||||
<th class="asset-export-history-document px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500 whitespace-nowrap">Phiếu Excel</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="assetExportHistoryTableBody" class="divide-y divide-slate-100">
|
||||
<tr>
|
||||
<td colspan="8" class="px-4 py-8 text-sm text-center text-slate-500">Chưa có dữ liệu lịch sử xuất.</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<form id="assetExportProcessForm" class="p-6 space-y-4">
|
||||
<p id="assetExportProcessMessage" class="text-sm text-slate-600"></p>
|
||||
<div id="assetExportRejectField" hidden>
|
||||
<label for="assetExportRejectReason" class="block mb-1 text-sm font-bold text-slate-700">Lý do từ chối</label>
|
||||
<textarea id="assetExportRejectReason" maxlength="1000" class="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm h-24"></textarea>
|
||||
</div>
|
||||
<div class="flex gap-3 pt-2">
|
||||
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold border border-slate-200 rounded-lg" data-close-modal="assetExportProcessModal">Hủy</button>
|
||||
<button id="assetExportProcessSubmit" type="submit" class="flex-1 px-4 py-2 bg-primary text-on-primary rounded-lg text-xs font-bold">Duyệt và xuất vào dự án</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -305,6 +305,10 @@
|
||||
<span class="material-symbols-outlined" aria-hidden="true">assignment_returned</span>
|
||||
<span class="sidebar-text">Mượn/Trả tài sản</span>
|
||||
</a></li>
|
||||
<li><a href="#asset-exports" data-nav="asset-exports" class="sidebar-link">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">outbox</span>
|
||||
<span class="sidebar-text">Xuất vào dự án</span>
|
||||
</a></li>
|
||||
<li><a href="#my-borrowed-assets" data-nav="my-borrowed-assets" class="sidebar-link">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">inventory</span>
|
||||
<span class="sidebar-text">Tài sản đang mượn</span>
|
||||
|
||||
Reference in New Issue
Block a user