feat: 실사 재고 바코드 리스트 레이지 로딩 — 스크롤 시 추가 로딩

- 상위 2,000건 상한 제거 → 초기 200건 렌더 후 스크롤 시 청크(200건) 추가 로딩
- 서버: ajax=1&offset&limit 로 청크 JSON 반환, 합계는 SQL 집계(전체 행 미적재)
- 클라: IntersectionObserver 자동 로딩 + '더 보기' 폴백 버튼
- 인쇄 시 전체 먼저 로드 후 출력(부분 인쇄 방지)
- fetch는 현재 origin 기준 상대경로로 호출(baseURL/포트 불일치에도 동작)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
taekyoungc
2026-07-15 16:29:50 +09:00
parent a3f3e9cd64
commit c5df784f91
2 changed files with 259 additions and 86 deletions

View File

@@ -1,24 +1,29 @@
<?php
/**
* 실사 재고 바코드 리스트 — 현재 창고에 있어야 하는 봉투 번호(바코드) 목록.
* 초기 1페이지만 렌더하고, 스크롤 시 AJAX 로 다음 청크를 이어 붙인다(레이지 로딩).
* @var string $bagCode
* @var string $keyword
* @var list<array<string,mixed>> $itemOptions
* @var list<array<string,mixed>> $rows
* @var list<array<string,mixed>> $rows 초기 청크
* @var int $totalBoxes
* @var int $totalPacks
* @var int $totalSheets
* @var int $pageSize
* @var int $loadedCount
*/
$bagCode = (string) ($bagCode ?? '');
$keyword = (string) ($keyword ?? '');
$itemOptions = is_array($itemOptions ?? null) ? $itemOptions : [];
$rows = is_array($rows ?? null) ? $rows : [];
$totalBoxes = (int) ($totalBoxes ?? 0);
$totalPacks = (int) ($totalPacks ?? 0);
$totalSheets = (int) ($totalSheets ?? 0);
$displayTruncated = (bool) ($displayTruncated ?? false);
$displayLimit = (int) ($displayLimit ?? 2000);
$exportQs = http_build_query(['bag_code' => $bagCode, 'keyword' => $keyword, 'export' => 1]);
$totalBoxes = (int) ($totalBoxes ?? 0);
$totalPacks = (int) ($totalPacks ?? 0);
$totalSheets = (int) ($totalSheets ?? 0);
$pageSize = (int) ($pageSize ?? 200);
$loadedCount = (int) ($loadedCount ?? count($rows));
$baseUrl = site_url('bag/inventory/stock-barcode-list');
$exportQs = http_build_query(['bag_code' => $bagCode, 'keyword' => $keyword, 'export' => 1]);
$hasMore = $loadedCount < $totalPacks;
?>
<div class="space-y-2">
<section class="border border-gray-300 rounded-lg bg-white p-3 no-print">
@@ -28,12 +33,12 @@ $exportQs = http_build_query(['bag_code' => $bagCode, 'keyword' => $keyw
<p class="text-xs text-gray-500 mt-0.5">현재 창고에 남아있어야 하는(재고 상태) 봉투 번호를 뽑아 실사 시 실물과 대조하세요.</p>
</div>
<div class="flex items-center gap-2 shrink-0">
<button type="button" onclick="window.print()" class="border border-gray-300 text-gray-600 px-3 py-1.5 rounded-sm text-sm hover:bg-gray-50 transition">인쇄</button>
<a href="<?= esc(site_url('bag/inventory/stock-barcode-list') . '?' . $exportQs) ?>" class="border border-green-500 text-green-700 px-3 py-1.5 rounded-sm text-sm hover:bg-green-50 transition">엑셀저장</a>
<button type="button" id="sbl-print" class="border border-gray-300 text-gray-600 px-3 py-1.5 rounded-sm text-sm hover:bg-gray-50 transition">인쇄</button>
<a href="<?= esc($baseUrl . '?' . $exportQs) ?>" class="border border-green-500 text-green-700 px-3 py-1.5 rounded-sm text-sm hover:bg-green-50 transition">엑셀저장</a>
</div>
</div>
<form method="get" action="<?= esc(site_url('bag/inventory/stock-barcode-list')) ?>" class="flex flex-wrap items-end gap-2 text-sm">
<form method="get" action="<?= esc($baseUrl) ?>" class="flex flex-wrap items-end gap-2 text-sm">
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">품목</label>
<select name="bag_code" class="border border-gray-300 rounded px-2 py-1 w-56">
@@ -51,9 +56,9 @@ $exportQs = http_build_query(['bag_code' => $bagCode, 'keyword' => $keyw
<label class="block text-xs font-bold text-gray-600 mb-1">번호 검색</label>
<input type="text" name="keyword" value="<?= esc($keyword, 'attr') ?>" placeholder="박스/팩/시트번호/LOT" class="border border-gray-300 rounded px-2 py-1 w-56"/>
</div>
<button type="submit" class="bg-navy-700 text-white px-4 py-1.5 rounded-sm text-sm hover:opacity-90 transition" style="background:#1f2b4d;">조회</button>
<button type="submit" class="text-white px-4 py-1.5 rounded-sm text-sm hover:opacity-90 transition" style="background:#1f2b4d;">조회</button>
<?php if ($bagCode !== '' || $keyword !== ''): ?>
<a href="<?= esc(site_url('bag/inventory/stock-barcode-list')) ?>" class="text-gray-500 hover:underline text-sm pb-1">초기화</a>
<a href="<?= esc($baseUrl) ?>" class="text-gray-500 hover:underline text-sm pb-1">초기화</a>
<?php endif; ?>
</form>
</section>
@@ -64,17 +69,19 @@ $exportQs = http_build_query(['bag_code' => $bagCode, 'keyword' => $keyw
<span class="text-gray-600">박스 <b class="text-gray-900"><?= number_format($totalBoxes) ?></b></span>
<span class="text-gray-600">팩 <b class="text-gray-900"><?= number_format($totalPacks) ?></b></span>
<span class="text-gray-600">총 매수 <b class="text-gray-900"><?= number_format($totalSheets) ?></b></span>
<span class="text-gray-400 text-xs ml-auto no-print"><?= esc(date('Y-m-d H:i')) ?> 기준</span>
<span class="text-gray-400 text-xs ml-auto no-print"><?= esc(date('Y-m-d H:i')) ?> 기준 · 표시 <b id="sbl-shown"><?= number_format($loadedCount) ?></b>/<?= number_format($totalPacks) ?></span>
</div>
<?php if ($displayTruncated): ?>
<div class="mb-2 text-xs text-amber-700 bg-amber-50 border border-amber-200 rounded px-2 py-1 no-print">
전체 <?= number_format($totalPacks) ?>건 중 화면에는 상위 <?= number_format($displayLimit) ?>건만 표시됩니다. 전체는 <b>엑셀저장</b>으로 받거나 <b>품목</b>을 선택해 좁혀 보세요.
</div>
<?php endif; ?>
<div class="overflow-x-auto">
<table class="w-full text-sm border-collapse">
<table class="w-full text-sm border-collapse"
id="sbl-table"
data-endpoint="<?= esc($baseUrl, 'attr') ?>"
data-bag-code="<?= esc($bagCode, 'attr') ?>"
data-keyword="<?= esc($keyword, 'attr') ?>"
data-offset="<?= (int) $loadedCount ?>"
data-page-size="<?= (int) $pageSize ?>"
data-total="<?= (int) $totalPacks ?>"
data-has-more="<?= $hasMore ? '1' : '0' ?>">
<thead>
<tr class="bg-gray-100 text-gray-700">
<th class="border border-gray-300 px-2 py-1 text-center w-12">No</th>
@@ -87,9 +94,9 @@ $exportQs = http_build_query(['bag_code' => $bagCode, 'keyword' => $keyw
<th class="border border-gray-300 px-2 py-1 text-right w-20">매수</th>
</tr>
</thead>
<tbody>
<tbody id="sbl-tbody">
<?php if ($rows === []): ?>
<tr><td colspan="8" class="border border-gray-300 px-2 py-6 text-center text-gray-400">재고로 남아있는 바코드가 없습니다.</td></tr>
<tr id="sbl-empty"><td colspan="8" class="border border-gray-300 px-2 py-6 text-center text-gray-400">재고로 남아있는 바코드가 없습니다.</td></tr>
<?php else: ?>
<?php foreach ($rows as $i => $r): ?>
<tr class="hover:bg-blue-50/40">
@@ -117,6 +124,12 @@ $exportQs = http_build_query(['bag_code' => $bagCode, 'keyword' => $keyw
<?php endif; ?>
</table>
</div>
<!-- 레이지 로딩 감시 지점 + 수동 더보기 폴백 -->
<div id="sbl-sentinel" class="no-print py-3 text-center text-sm text-gray-400" <?= $hasMore ? '' : 'style="display:none;"' ?>>
<span id="sbl-loading" style="display:none;">불러오는 중…</span>
<button type="button" id="sbl-more" class="border border-gray-300 text-gray-600 px-4 py-1.5 rounded-sm hover:bg-gray-50 transition">더 보기</button>
</div>
</section>
</div>
@@ -127,3 +140,132 @@ $exportQs = http_build_query(['bag_code' => $bagCode, 'keyword' => $keyw
table { font-size: 11px; }
}
</style>
<script>
(function () {
var table = document.getElementById('sbl-table');
if (!table) return;
var tbody = document.getElementById('sbl-tbody');
var sentinel = document.getElementById('sbl-sentinel');
var loading = document.getElementById('sbl-loading');
var moreBtn = document.getElementById('sbl-more');
var shownEl = document.getElementById('sbl-shown');
var printBtn = document.getElementById('sbl-print');
// baseURL(예: 로컬 :8080)과 실제 접속 origin(:8045 등)이 달라도 항상 현재 origin 기준으로 호출
var endpoint = table.getAttribute('data-endpoint');
try { endpoint = location.origin + new URL(endpoint, location.href).pathname; }
catch (e) { endpoint = location.pathname; }
var bagCode = table.getAttribute('data-bag-code') || '';
var keyword = table.getAttribute('data-keyword') || '';
var pageSize = parseInt(table.getAttribute('data-page-size'), 10) || 200;
var offset = parseInt(table.getAttribute('data-offset'), 10) || 0;
var total = parseInt(table.getAttribute('data-total'), 10) || 0;
var hasMore = table.getAttribute('data-has-more') === '1';
var busy = false;
function esc(s) {
return String(s == null ? '' : s)
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function fmt(n) { return (n || 0).toLocaleString(); }
function rowHtml(r, no) {
return '<tr class="hover:bg-blue-50/40">'
+ '<td class="border border-gray-300 px-2 py-1 text-center text-gray-500">' + no + '</td>'
+ '<td class="border border-gray-300 px-2 py-1">' + esc(r.name) + '</td>'
+ '<td class="border border-gray-300 px-2 py-1">' + esc(r.lot) + '</td>'
+ '<td class="border border-gray-300 px-2 py-1 font-mono text-xs">' + esc(r.box) + '</td>'
+ '<td class="border border-gray-300 px-2 py-1 font-mono text-xs">' + esc(r.pack) + '</td>'
+ '<td class="border border-gray-300 px-2 py-1 font-mono text-xs">' + esc(r.start) + '</td>'
+ '<td class="border border-gray-300 px-2 py-1 font-mono text-xs">' + esc(r.end) + '</td>'
+ '<td class="border border-gray-300 px-2 py-1 text-right">' + fmt(r.qty) + '</td>'
+ '</tr>';
}
function buildUrl(off, lim) {
var p = new URLSearchParams();
p.set('ajax', '1');
p.set('offset', off);
p.set('limit', lim);
if (bagCode) p.set('bag_code', bagCode);
if (keyword) p.set('keyword', keyword);
return endpoint + '?' + p.toString();
}
function appendRows(rows) {
if (!rows || !rows.length) return;
var html = '';
for (var i = 0; i < rows.length; i++) {
html += rowHtml(rows[i], offset + i + 1);
}
tbody.insertAdjacentHTML('beforeend', html);
offset += rows.length;
if (shownEl) shownEl.textContent = fmt(offset);
}
// 다음 청크 한 번 로드
function loadMore() {
if (busy || !hasMore) return Promise.resolve();
busy = true;
if (loading) loading.style.display = 'inline';
if (moreBtn) moreBtn.style.display = 'none';
return fetch(buildUrl(offset, pageSize), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
.then(function (res) { return res.json(); })
.then(function (data) {
appendRows(data.rows);
hasMore = !!data.hasMore;
if (!hasMore && sentinel) sentinel.style.display = 'none';
})
.catch(function () { /* 네트워크 오류 시 더보기 버튼 유지 */ })
.finally(function () {
busy = false;
if (loading) loading.style.display = 'none';
if (hasMore && moreBtn) moreBtn.style.display = '';
});
}
// 남은 전체를 한 번에 로드(인쇄용)
function loadAll() {
if (!hasMore) return Promise.resolve();
busy = true;
if (loading) loading.style.display = 'inline';
if (moreBtn) moreBtn.style.display = 'none';
return fetch(buildUrl(offset, 5000), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
.then(function (res) { return res.json(); })
.then(function (data) {
appendRows(data.rows);
hasMore = !!data.hasMore;
busy = false;
if (hasMore) return loadAll();
if (sentinel) sentinel.style.display = 'none';
if (loading) loading.style.display = 'none';
});
}
// 스크롤 자동 로딩(IntersectionObserver) — 미지원/iframe 대비 더보기 버튼 폴백 병행
if (hasMore && 'IntersectionObserver' in window) {
var io = new IntersectionObserver(function (entries) {
if (entries[0] && entries[0].isIntersecting) loadMore();
}, { rootMargin: '300px' });
io.observe(sentinel);
}
if (moreBtn) moreBtn.addEventListener('click', loadMore);
// 인쇄 — 전체를 먼저 불러온 뒤 출력(부분만 인쇄되는 것 방지)
if (printBtn) {
printBtn.addEventListener('click', function () {
if (!hasMore) { window.print(); return; }
printBtn.disabled = true;
var orig = printBtn.textContent;
printBtn.textContent = '전체 불러오는 중…';
loadAll().then(function () {
printBtn.disabled = false;
printBtn.textContent = orig;
window.print();
});
});
}
})();
</script>