// Current allocations are separate from the immutable export history and the // legacy Project metadata. Never guess a project for old, unattributed loans. function parseAllocations(value) { const rows = typeof value === 'string' ? JSON.parse(value || '[]') : (value || []); if (!Array.isArray(rows)) throw new Error('Invalid asset project allocations'); return rows.map(row => ({ projectName: String(row.projectName || '').trim(), borrowerName: String(row.borrowerName || '').trim(), quantity: Number(row.quantity) })).filter(row => row.projectName && Number.isSafeInteger(row.quantity) && row.quantity > 0); } function normalizeExportAllocations(body = {}) { const rows = body.allocations === undefined ? [{ projectName: body.projectName, quantity: body.quantity }] : body.allocations; if (!Array.isArray(rows) || !rows.length || rows.length > 100) { throw new Error('Vui lòng chọn từ 1 đến 100 dòng dự án.'); } const result = []; for (const row of rows) { const projectName = String(row?.projectName || '').trim(); const quantity = Number(row?.quantity); if (!projectName || projectName.length > 150) throw new Error('Tên dự án là bắt buộc, tối đa 150 ký tự.'); if (!['number', 'string'].includes(typeof row?.quantity) || !Number.isSafeInteger(quantity) || quantity <= 0 || quantity > 2147483647) { throw new Error('Số lượng xuất cho mỗi dự án phải là số nguyên dương.'); } const existing = result.find(item => item.projectName.toLowerCase() === projectName.toLowerCase()); if (existing) existing.quantity += quantity; else result.push({ projectName, quantity }); } if (result.reduce((sum, row) => sum + row.quantity, 0) > 2147483647) throw new Error('Tổng số lượng xuất quá lớn.'); return result; } function addAllocations(current, rows, borrowerName) { // Keep export order so unlinked returns can consume the oldest export first. return [...parseAllocations(current), ...rows.map(row => ({ ...row, borrowerName }))]; } function releaseAllocations(current, borrowerName, returnedQuantity, borrowerOutstanding) { const rows = parseAllocations(current); const matches = row => 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); for (const row of rows) { if (!matches(row)) continue; const taken = Math.min(row.quantity, remaining); row.quantity -= taken; remaining -= taken; } return rows.filter(row => row.quantity > 0); } module.exports = { parseAllocations, normalizeExportAllocations, addAllocations, releaseAllocations };