xuất excel

This commit is contained in:
2026-10-14 09:10:37 +07:00
parent dff0d32912
commit 533923076c
19 changed files with 1655 additions and 236 deletions

View File

@@ -37,6 +37,68 @@ 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;
border-collapse: separate;
border-spacing: 0;
}
.asset-export-history-table th,
.asset-export-history-table td {
border-bottom: 1px solid #f1f5f9;
overflow-wrap: anywhere;
}
.asset-export-history-table thead th {
position: sticky;
top: 0;
z-index: 2;
background: #f8fafc;
overflow-wrap: normal;
}
.asset-export-history-table .asset-export-history-document {
position: sticky;
right: 0;
z-index: 1;
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 {
z-index: 3;
background: #f8fafc;
}
.asset-export-history-table tr:hover .asset-export-history-document {
background: #f8fafc;
}
.asset-export-history-file-actions {
flex-wrap: nowrap;
}
.asset-export-history-file-actions > button {
flex: 0 0 auto;
white-space: nowrap;
}
@media (max-width: 900px) {
body.app-shell,
#appMain,

View File

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

View File

@@ -680,6 +680,25 @@
</div>
<!-- Export Asset Modal -->
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="exportRequestDocumentModal">
<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">Phiếu đề nghị xuất Excel</h3>
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400" data-close-modal="exportRequestDocumentModal" aria-label="Đóng">
<span class="material-symbols-outlined">close</span>
</button>
</div>
<div class="p-6 space-y-4">
<p class="text-sm text-slate-700">Đã xuất thành công và tạo phiếu Excel. Nếu file chưa tải xuống, bạn có thể tải lại bên dưới.</p>
<p id="exportRequestDocumentName" class="text-sm font-semibold text-slate-700 break-all"></p>
<p class="text-xs text-slate-500">Phần chữ ký, họ tên và ngày ký để trống để điền sau.</p>
<div class="flex gap-3">
<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="exportRequestDocumentModal">Đóng</button>
<button type="button" id="downloadExportRequestDocumentBtn" class="flex-1 px-4 py-2 bg-primary text-on-primary rounded-lg text-xs font-bold">Tải lại phiếu Excel</button>
</div>
</div>
</div>
</div>
<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">
@@ -736,12 +755,55 @@
</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">Xác nhận xuất</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>
</div>
</form>
</div>
</div>
<!-- Batch Asset Export Modal -->
<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>
<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">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>
<div class="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">Tài sản</th><th class="px-3 py-3">Có thể xuất</th><th class="px-3 py-3">Số lượng</th><th class="px-3 py-3">Dự án</th><th class="px-3 py-3"></th></tr></thead>
<tbody id="batchAssetExportTableBody" class="divide-y divide-slate-100"></tbody>
</table>
</div>
<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>
</div>
</form>
</div>
</div>
<!-- Saved Asset Export Preview -->
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="assetExportPreviewModal" style="z-index: 145;">
<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 class="min-w-0"><h3 class="text-base font-extrabold text-slate-900">Phiếu xuất tài sản</h3><p id="assetExportPreviewFileName" class="mt-1 truncate text-xs text-slate-500"></p></div>
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400" data-close-modal="assetExportPreviewModal" aria-label="Đóng"><span class="material-symbols-outlined">close</span></button>
</div>
<div id="assetExportPreviewContent" class="p-6 overflow-y-auto"></div>
<div class="px-6 py-4 border-t border-slate-100 flex items-center justify-between gap-3">
<p class="text-xs text-slate-500">Nội dung ghi nhận tại thời điểm xuất.</p>
<button type="button" id="assetExportPreviewDownloadBtn" class="shrink-0 px-4 py-2 bg-primary text-on-primary rounded-lg text-xs font-bold">Tải Excel</button>
</div>
</div>
</div>
<!-- Asset Damage/Disposal Modal -->
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="assetDamageModal">
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
@@ -804,17 +866,26 @@
<!-- 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 w-full max-w-6xl 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 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>
</div>
<div class="p-6 pt-4 overflow-auto">
<div class="rounded-xl border border-slate-200 overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-left border-collapse" style="min-width: 1100px;">
<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>
@@ -824,15 +895,15 @@
<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="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>
</tbody>
</table>
</div>
</div>
</div>
</div>

View File

@@ -268,7 +268,7 @@
}
</style>
<link rel="stylesheet" href="../css/responsive.css?v=20260807-1" />
<link rel="stylesheet" href="../css/responsive.css?v=20261013-1" />
</head>
<body class="app-shell bg-background text-on-surface antialiased flex h-screen w-screen">
<!-- SideNavBar -->
@@ -425,6 +425,6 @@
</div>
</main>
<script src="../js/app.js?v=20260915-1"></script>
<script src="../js/app.js?v=20261013-3"></script>
</body>
</html>