Files
ManagerAccount/backend/asset-export-requests.js
2026-11-10 11:01:24 +07:00

177 lines
11 KiB
JavaScript

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 };