xuất excel
This commit is contained in:
284
public/js/app.js
284
public/js/app.js
@@ -1650,7 +1650,7 @@ class AccountManager {
|
||||
noteLabel.textContent = isProject ? 'Ghi chú xuất' : 'Ghi chú mượn';
|
||||
}
|
||||
if (submitBtn) {
|
||||
submitBtn.textContent = isProject ? 'Xác nhận xuất dự án' : 'Xác nhận mượn';
|
||||
submitBtn.textContent = isProject ? 'Xuất và tải Excel' : 'Mượn và tải Excel';
|
||||
}
|
||||
if (isProject) {
|
||||
projectInput.required = true;
|
||||
@@ -1826,7 +1826,7 @@ class AccountManager {
|
||||
if (!Array.isArray(rows) || rows.length === 0) {
|
||||
return `
|
||||
<tr>
|
||||
<td colspan="7" class="px-4 py-8 text-sm text-center text-slate-500">Chưa có dữ liệu lịch sử xuất.</td>
|
||||
<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>
|
||||
`;
|
||||
}
|
||||
@@ -1844,6 +1844,15 @@ class AccountManager {
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${this.escapeHtml(item?.CustodianName || '-')}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${this.escapeHtml(item?.ExportedByName || '-')}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600 whitespace-pre-line">${this.escapeHtml(item?.ExportNote || '-')}</td>
|
||||
<td class="asset-export-history-document px-4 py-3 text-xs text-slate-600">
|
||||
${item?.ExportDocumentId ? `
|
||||
<div class="truncate font-semibold" style="max-width: 220px;" title="${this.escapeHtml(item.DocumentFileName || '')}">${this.escapeHtml(item.DocumentFileName || 'Phiếu xuất Excel')}</div>
|
||||
<div class="asset-export-history-file-actions mt-2 flex gap-2 whitespace-nowrap">
|
||||
<button type="button" class="view-asset-export-document rounded-md border border-slate-200 px-2 py-1 font-semibold text-primary" data-document-id="${this.escapeHtml(item.ExportDocumentId)}">Xem phiếu</button>
|
||||
<button type="button" class="download-asset-export-document rounded-md border border-slate-200 px-2 py-1 font-semibold text-primary" data-document-id="${this.escapeHtml(item.ExportDocumentId)}" data-file-name="${this.escapeHtml(item.DocumentFileName || 'phieu-xuat.xlsx')}">Tải Excel</button>
|
||||
</div>
|
||||
` : '<span class="text-slate-400">Chưa lưu file</span>'}
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
@@ -1856,6 +1865,12 @@ class AccountManager {
|
||||
}
|
||||
|
||||
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() {
|
||||
@@ -1872,7 +1887,7 @@ class AccountManager {
|
||||
|
||||
tbody.innerHTML = `
|
||||
<tr>
|
||||
<td colspan="7" class="px-4 py-8 text-sm text-center text-slate-500">Đang tải lịch sử xuất...</td>
|
||||
<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');
|
||||
@@ -1881,6 +1896,80 @@ class AccountManager {
|
||||
this.renderAssetExportHistoryModal();
|
||||
}
|
||||
|
||||
buildSavedAssetExportPreviewHtml(snapshot) {
|
||||
const safe = value => this.escapeHtml(String(value ?? '').trim() || '-');
|
||||
let index = 0;
|
||||
const rows = (snapshot.items || []).flatMap(item => {
|
||||
let remaining = Number(item.availableStock) || 0;
|
||||
return (item.allocations || []).map(allocation => {
|
||||
const stockBefore = remaining;
|
||||
remaining -= Number(allocation.quantity) || 0;
|
||||
return `<tr>
|
||||
<td class="px-3 py-3 text-slate-500">${++index}</td>
|
||||
<td class="px-3 py-3"><div class="font-semibold text-slate-800">${safe(item.assetName)}</div><div class="mt-1 text-xs text-slate-500">${safe(item.assetCode)}</div></td>
|
||||
<td class="px-3 py-3 text-slate-600">${safe(item.model)}<div class="mt-1 text-xs text-slate-500">Serial: ${safe(item.serialNumber)}</div></td>
|
||||
<td class="px-3 py-3 font-semibold whitespace-nowrap">${Number(allocation.quantity) || 0} ${safe(item.unit)}</td>
|
||||
<td class="px-3 py-3 text-slate-600">${stockBefore}</td>
|
||||
<td class="px-3 py-3 text-slate-600">${safe(allocation.projectName)}</td>
|
||||
</tr>`;
|
||||
});
|
||||
}).join('');
|
||||
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">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>
|
||||
<div class="mt-4 overflow-x-auto rounded-lg border border-slate-200">
|
||||
<table class="w-full text-left text-sm" style="min-width: 760px;">
|
||||
<thead class="bg-slate-50 text-xs text-slate-500"><tr><th class="px-3 py-3">STT</th><th class="px-3 py-3">Tài sản</th><th class="px-3 py-3">Model / Serial</th><th class="px-3 py-3">Số lượng</th><th class="px-3 py-3">Tồn trước xuất</th><th class="px-3 py-3">Dự án</th></tr></thead>
|
||||
<tbody class="divide-y divide-slate-100">${rows}</tbody>
|
||||
</table>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
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');
|
||||
if (!modal || !content || !downloadButton) return;
|
||||
this.assetExportPreviewRequest = documentId;
|
||||
document.getElementById('assetExportPreviewFileName').textContent = '';
|
||||
content.textContent = 'Đang tải phiếu xuất...';
|
||||
downloadButton.disabled = true;
|
||||
modal.classList.add('open');
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/asset-export-documents/${encodeURIComponent(documentId)}`, { headers: this.getAuthHeaders(false) });
|
||||
const data = await response.json();
|
||||
if (this.assetExportPreviewRequest !== documentId) return;
|
||||
if (!response.ok || !data.success) throw new Error(data.message || 'Không tải được phiếu xuất.');
|
||||
document.getElementById('assetExportPreviewFileName').textContent = data.data.fileName;
|
||||
content.innerHTML = this.buildSavedAssetExportPreviewHtml(data.data.snapshot);
|
||||
downloadButton.disabled = false;
|
||||
downloadButton.onclick = () => this.downloadSavedAssetExport(documentId, data.data.fileName, downloadButton);
|
||||
} catch (err) {
|
||||
if (this.assetExportPreviewRequest === documentId) content.textContent = err.message || 'Không tải được phiếu xuất.';
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
const response = await fetch(`${this.apiBase}/asset-export-documents/${encodeURIComponent(documentId)}/download`, { headers: this.getAuthHeaders(false) });
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.message || 'Không tải được file Excel.');
|
||||
}
|
||||
this.downloadBlobFile(await response.blob(), fileName);
|
||||
} catch (err) {
|
||||
this.notifyFailure(err.message || 'Không tải được file Excel, vui lòng thử lại.');
|
||||
} finally { if (button) button.disabled = false; }
|
||||
}
|
||||
|
||||
async fetchConsumableExportHistories(limit = 300) {
|
||||
try {
|
||||
const safeLimit = Number.isFinite(Number(limit)) ? Math.max(1, Math.min(Number(limit), 2000)) : 300;
|
||||
@@ -6672,6 +6761,15 @@ class AccountManager {
|
||||
return Math.min(metrics.endingBalance, Math.max(metrics.quantity + metrics.importInPeriod - Math.max(metrics.exportInPeriod, metrics.borrowerExportInPeriod, allocated), 0));
|
||||
}
|
||||
|
||||
formatAssetLocationHtml(location, constrainToContainer = false) {
|
||||
const value = String(location ?? '').trim();
|
||||
if (!value) return '-';
|
||||
|
||||
const safeValue = this.escapeHtml(value);
|
||||
const maxWidth = constrainToContainer ? 'min(100%, 160px)' : '160px';
|
||||
return `<span class="inline-block truncate rounded-md bg-slate-100 px-2 py-1 text-xs font-semibold text-slate-700" style="max-width: ${maxWidth}; vertical-align: middle;" title="${safeValue}">${safeValue}</span>`;
|
||||
}
|
||||
|
||||
getAssetMobileCardHtml(asset, rowNumber, canManageAssets) {
|
||||
const statusMeta = this.getAssetStatusMeta(asset?.Status);
|
||||
const assetId = Number(asset?.AssetId);
|
||||
@@ -6703,7 +6801,7 @@ class AccountManager {
|
||||
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Đang mượn</span><span class="font-bold text-slate-800">${borrowedQuantity}${unit ? ` ${safe(unit)}` : ''}</span></div>
|
||||
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Phòng ban</span><span class="text-slate-700">${safe(asset?.Department)}</span></div>
|
||||
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Dự án</span><div class="text-slate-700">${this.formatAssetProjectsHtml(asset)}</div></div>
|
||||
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Vị trí</span><span class="text-slate-700">${safe(asset?.Location)}</span></div>
|
||||
<div class="min-w-0"><span class="block text-[10px] font-bold uppercase text-slate-400">Vị trí</span><div class="mt-1">${this.formatAssetLocationHtml(asset?.Location, true)}</div></div>
|
||||
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Phụ trách</span><span class="text-slate-700">${safe(asset?.Custodian)}</span></div>
|
||||
</div>
|
||||
|
||||
@@ -6781,7 +6879,7 @@ 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 === 1) ? 'hover:bg-primary/5' : 'opacity-50 cursor-not-allowed'}" ${(canManageAssets && selectedCount === 1) ? '' : '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 ${(canManageAssets && selectedCount > 0) ? 'hover:bg-primary/5' : 'opacity-50 cursor-not-allowed'}" ${(canManageAssets && selectedCount > 0) ? '' : 'disabled'}>
|
||||
<span class="material-symbols-outlined text-base">handshake</span>
|
||||
Xuất tài sản
|
||||
</button>
|
||||
@@ -6840,7 +6938,7 @@ class AccountManager {
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">SL hàng mới</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">SL đã qua sử dụng</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">SL đang mượn</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Vị trí</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500" style="width: 144px; min-width: 144px; white-space: nowrap;">Vị trí</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Ngày mua</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500" style="width: 240px; min-width: 240px;">Người mượn</th>
|
||||
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Ghi chú</th>
|
||||
@@ -6880,7 +6978,7 @@ class AccountManager {
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${asset.NewQuantity ?? 0}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${asset.UsedQuantity ?? 0}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${asset.ExportInPeriod ?? 0}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${asset.Location || '-'}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600 whitespace-nowrap" style="width: 144px; min-width: 144px;">${this.formatAssetLocationHtml(asset.Location)}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600 whitespace-nowrap">${this.formatDateOnly(asset.PurchaseDate)}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600 whitespace-normal" style="width: 240px; min-width: 240px;">${this.formatBorrowerTableHtml(asset.Borrower)}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600 max-w-xs truncate" title="${asset.Notes || ''}">${asset.Notes || '-'}</td>
|
||||
@@ -6971,7 +7069,7 @@ class AccountManager {
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${asset.NewQuantity ?? 0}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${asset.UsedQuantity ?? 0}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${asset.ExportInPeriod ?? 0}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600">${asset.Location || '-'}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600 whitespace-nowrap" style="width: 144px; min-width: 144px;">${this.formatAssetLocationHtml(asset.Location)}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600 whitespace-nowrap">${this.formatDateOnly(asset.PurchaseDate)}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600 whitespace-normal" style="width: 240px; min-width: 240px;">${this.formatBorrowerTableHtml(asset.Borrower)}</td>
|
||||
<td class="px-4 py-3 text-sm text-slate-600 max-w-xs truncate" title="${asset.Notes || ''}">${asset.Notes || '-'}</td>
|
||||
@@ -7134,7 +7232,7 @@ class AccountManager {
|
||||
|
||||
const borrowAssetBtn = document.getElementById('borrowAssetBtn');
|
||||
if (borrowAssetBtn) {
|
||||
const disabled = !canManageAssets || selectedCount !== 1;
|
||||
const disabled = !canManageAssets || selectedCount === 0;
|
||||
borrowAssetBtn.disabled = disabled;
|
||||
borrowAssetBtn.classList.toggle('opacity-50', disabled);
|
||||
borrowAssetBtn.classList.toggle('cursor-not-allowed', disabled);
|
||||
@@ -7853,6 +7951,117 @@ class AccountManager {
|
||||
}
|
||||
}
|
||||
|
||||
buildBatchAssetExportRowsHtml(assets) {
|
||||
const projectNames = this.getUniqueAssetProjectNames();
|
||||
return assets.map(asset => {
|
||||
const available = this.getAssetAvailableForExport(asset);
|
||||
const names = [...new Set([...projectNames, String(asset.Project || '').trim()].filter(Boolean))];
|
||||
return `<tr class="batch-asset-export-row" data-asset-id="${Number(asset.AssetId)}">
|
||||
<td class="px-3 py-3"><div class="font-semibold text-slate-800">${this.escapeHtml(asset.AssetName || '-')}</div><div class="mt-1 text-xs text-slate-500">${this.escapeHtml(asset.AssetCode || '-')} · ${this.escapeHtml(asset.Model || '-')}</div></td>
|
||||
<td class="px-3 py-3 text-slate-600 whitespace-nowrap">${available} ${this.escapeHtml(asset.Unit || '')}</td>
|
||||
<td class="px-3 py-3"><input type="number" class="batch-export-quantity w-full rounded-lg border border-slate-200 px-3 py-2 text-sm" min="1" max="${available}" step="1" value="1" required aria-label="Số lượng xuất ${this.escapeHtml(asset.AssetCode || '')}" style="min-width: 80px;"></td>
|
||||
<td class="px-3 py-3"><select class="batch-export-project w-full rounded-lg border border-slate-200 px-3 py-2 text-sm" required aria-label="Dự án của ${this.escapeHtml(asset.AssetCode || '')}" style="min-width: 180px;">
|
||||
<option value="">-- Chọn dự án --</option>
|
||||
${names.map(name => `<option value="${this.escapeHtml(name)}" ${name === asset.Project ? 'selected' : ''}>${this.escapeHtml(name)}</option>`).join('')}
|
||||
</select></td>
|
||||
<td class="px-3 py-3"><button type="button" class="remove-batch-export-asset px-2 py-1 text-xs font-semibold text-red-600" aria-label="Bỏ tài sản ${this.escapeHtml(asset.AssetCode || '')}">Bỏ</button></td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
collectBatchAssetExportItems() {
|
||||
return [...document.querySelectorAll('#batchAssetExportTableBody .batch-asset-export-row')].map(row => ({
|
||||
assetId: Number(row.dataset.assetId),
|
||||
allocations: [{ projectName: String(row.querySelector('.batch-export-project').value || '').trim(),
|
||||
quantity: Number(row.querySelector('.batch-export-quantity').value) }]
|
||||
}));
|
||||
}
|
||||
|
||||
updateBatchAssetExportSummary() {
|
||||
const items = this.collectBatchAssetExportItems();
|
||||
const summary = document.getElementById('batchAssetExportSummary');
|
||||
if (summary) summary.textContent = `${items.length} tài sản đã chọn · 1 phiếu Excel chung`;
|
||||
}
|
||||
|
||||
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.');
|
||||
return;
|
||||
}
|
||||
const unavailable = assets.find(asset => this.getAssetAvailableForExport(asset) <= 0);
|
||||
if (unavailable) {
|
||||
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 --' });
|
||||
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('');
|
||||
commonProject.onchange = () => {
|
||||
if (!commonProject.value) return;
|
||||
form.querySelectorAll('.batch-export-project').forEach(select => { select.value = commonProject.value; });
|
||||
};
|
||||
document.getElementById('batchAssetExportNoteInput').value = '';
|
||||
document.getElementById('batchAssetExportTableBody').innerHTML = this.buildBatchAssetExportRowsHtml(assets);
|
||||
form.onsubmit = event => this.handleBatchAssetExportSubmit(event);
|
||||
form.oninput = () => this.updateBatchAssetExportSummary();
|
||||
form.onclick = event => {
|
||||
const remove = event.target.closest('.remove-batch-export-asset');
|
||||
if (remove) { remove.closest('tr').remove(); this.updateBatchAssetExportSummary(); }
|
||||
};
|
||||
this.updateBatchAssetExportSummary();
|
||||
modal.classList.add('open');
|
||||
}
|
||||
|
||||
async handleBatchAssetExportSubmit(event) {
|
||||
event.preventDefault();
|
||||
if (!this.ensureAssetManagePermission('xuất nhiều tài sản') || 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 (!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);
|
||||
const row = item.allocations[0];
|
||||
if (!asset || !row.projectName) { this.notifyWarning('Vui lòng chọn dự án cho tất cả tài sản.'); return; }
|
||||
if (!Number.isSafeInteger(row.quantity) || row.quantity <= 0) { this.notifyWarning('Số lượng xuất phải là số nguyên dương.'); return; }
|
||||
const available = this.getAssetAvailableForExport(asset);
|
||||
if (row.quantity > available) { this.notifyWarning(`${asset.AssetCode || asset.AssetName}: Số lượng xuất vượt quá tồn cuối kỳ (${available}).`); return; }
|
||||
}
|
||||
const button = document.querySelector('#batchAssetExportForm button[type="submit"]');
|
||||
this.assetExportSubmitting = true;
|
||||
if (button) button.disabled = true;
|
||||
let exportSucceeded = false;
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/assets/export`, {
|
||||
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.closeModals();
|
||||
this.showExportRequestDocument(data.document);
|
||||
await this.refreshAssetsUI();
|
||||
} 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.');
|
||||
else this.notifyFailure('Xuất tài sản thất bại.');
|
||||
} finally {
|
||||
this.assetExportSubmitting = false;
|
||||
if (button) button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
collectBorrowProjectAllocations() {
|
||||
const rows = [{
|
||||
projectName: String(document.getElementById('borrowAssetProjectInput')?.value || '').trim(),
|
||||
@@ -7901,6 +8110,7 @@ class AccountManager {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.selectedAssetIds.size > 1) return this.openBatchAssetExportModal();
|
||||
const asset = this.getSingleSelectedAssetForBorrowing(true);
|
||||
if (!asset) {
|
||||
return;
|
||||
@@ -8023,6 +8233,7 @@ class AccountManager {
|
||||
this.assetExportSubmitting = true;
|
||||
const submitButton = document.querySelector('#borrowAssetForm button[type="submit"]');
|
||||
if (submitButton) submitButton.disabled = true;
|
||||
let exportSucceeded = false;
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/assets/${selectedAssetId}/export`, {
|
||||
method: 'POST',
|
||||
@@ -8042,9 +8253,11 @@ class AccountManager {
|
||||
return;
|
||||
}
|
||||
|
||||
exportSucceeded = true;
|
||||
this.pendingBorrowAssetId = undefined;
|
||||
this.notifySuccess('Xuất tài sản thành công');
|
||||
this.closeModals();
|
||||
this.showExportRequestDocument(data.document);
|
||||
await this.refreshAssetsUI();
|
||||
const exportHistoryModal = document.getElementById('assetExportHistoryModal');
|
||||
if (exportHistoryModal?.classList.contains('open')) {
|
||||
@@ -8053,13 +8266,51 @@ class AccountManager {
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
this.notifyFailure('Xuất tài sản thất bại');
|
||||
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.');
|
||||
else this.notifyFailure('Xuất tài sản thất bại');
|
||||
} finally {
|
||||
this.assetExportSubmitting = false;
|
||||
if (submitButton) submitButton.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
showExportRequestDocument(file) {
|
||||
if (!file?.contentBase64) return;
|
||||
this.lastExportRequestDocument = file;
|
||||
const modal = document.getElementById('exportRequestDocumentModal');
|
||||
const name = document.getElementById('exportRequestDocumentName');
|
||||
const button = document.getElementById('downloadExportRequestDocumentBtn');
|
||||
if (name) name.textContent = file.fileName;
|
||||
if (button) button.onclick = () => this.downloadExportRequestDocument();
|
||||
modal?.classList.add('open');
|
||||
this.downloadExportRequestDocument();
|
||||
}
|
||||
|
||||
downloadExportRequestDocument() {
|
||||
const file = this.lastExportRequestDocument;
|
||||
if (!file?.contentBase64) return;
|
||||
try {
|
||||
const bytes = Uint8Array.from(atob(file.contentBase64), character => character.charCodeAt(0));
|
||||
this.downloadBlobFile(new Blob([bytes], { type: file.mimeType }), file.fileName);
|
||||
} catch (err) {
|
||||
console.error('Download export request failed:', err);
|
||||
// The export has already committed. Do not report it as failed or
|
||||
// invite a second inventory transaction just to retry downloading.
|
||||
this.notifyWarning('Đã xuất thành công. Chưa tải được Excel; hãy bấm Tải lại phiếu Excel.');
|
||||
}
|
||||
}
|
||||
|
||||
downloadBlobFile(blob, fileName) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = fileName;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 30000);
|
||||
}
|
||||
|
||||
async handleAssetSubmit(e) {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -9027,6 +9278,11 @@ class AccountManager {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.consumableExportSubmitting) return;
|
||||
this.consumableExportSubmitting = true;
|
||||
const submitButton = document.querySelector('#consumableExportForm button[type="submit"]');
|
||||
if (submitButton) submitButton.disabled = true;
|
||||
let exportSucceeded = false;
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/consumables/${selectedConsumableId}/export`, {
|
||||
method: 'POST',
|
||||
@@ -9047,11 +9303,13 @@ class AccountManager {
|
||||
return;
|
||||
}
|
||||
|
||||
exportSucceeded = true;
|
||||
this.pendingConsumableExportId = undefined;
|
||||
this.notifySuccess(targetType === 'project'
|
||||
? 'Xuất vật tư cho dự án thành công'
|
||||
: 'Ghi nhận mượn vật tư thành công');
|
||||
this.closeModals();
|
||||
this.showExportRequestDocument(data.document);
|
||||
await this.refreshConsumablesUI();
|
||||
|
||||
const exportHistoryModal = document.getElementById('consumableExportHistoryModal');
|
||||
@@ -9061,7 +9319,11 @@ class AccountManager {
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
this.notifyFailure('Xuất vật tư tiêu hao thất bại');
|
||||
if (exportSucceeded) this.notifyWarning('Đã xuất vật tư thành công. Chưa cập nhật được danh sách; hãy tải lại trang.');
|
||||
else this.notifyFailure('Xuất vật tư tiêu hao thất bại');
|
||||
} finally {
|
||||
this.consumableExportSubmitting = false;
|
||||
if (submitButton) submitButton.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user