feat: 발주입고(스캐너)·일괄입고 좌우 워크스페이스 재설계 + 실시간 스캔 입고

- 발주입고/일괄입고를 공용 워크스페이스로 통합: 좌측 발주현황(탭: 제작업체·발주기간 /
  인수자·인계자, 정렬) · 우측 선택발주 상세 + 스캔/수량 입고 · 하단 입고 세부내역(박스코드)
- 실시간 스캔 입고 엔드포인트 receivingScanBox 추가(스캔 1회=1박스, 수량 직접입력 병행)
- buildReceivingCandidateRows에 카테고리(봉투/음식물·폐기물)·발주기간·대행소 필터 추가
- 일괄입고를 '일괄입고(음식물,폐기물)'로 개편, 음식물·폐기물만 표시(메뉴명 변경 SQL 포함)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
taekyoungc
2026-07-09 16:20:14 +09:00
parent 7e958a7ac9
commit 62f7bda290
4 changed files with 592 additions and 227 deletions

View File

@@ -1,148 +1,360 @@
<?php
$mode = (string) ($mode ?? 'scanner');
$isBatch = (bool) ($isBatch ?? false);
$tab = (string) ($tab ?? 'company');
$companies = is_array($companies ?? null) ? $companies : [];
$agencies = is_array($agencies ?? null) ? $agencies : [];
$rows = is_array($rows ?? null) ? $rows : [];
$monthOptions = is_array($monthOptions ?? null) ? $monthOptions : [];
$receiverOptions = is_array($receiverOptions ?? null) ? $receiverOptions : [];
$senders = is_array($senders ?? null) ? $senders : [];
$companyIdx = (int) ($companyIdx ?? 0);
$agencyIdx = (int) ($agencyIdx ?? 0);
$baseUrl = $isBatch ? base_url('bag/receiving/batch') : base_url('bag/receiving/scanner');
$otherUrl = $isBatch ? base_url('bag/receiving/scanner') : base_url('bag/receiving/batch');
$otherLabel = $isBatch ? '발주 입고(스캐너)' : '일괄입고(음식물,폐기물)';
$tabUrl = static function (string $t) use ($baseUrl): string {
return $baseUrl . '?' . http_build_query(['tab' => $t]);
};
?>
<section class="border-b border-gray-300 p-2 shrink-0 bg-control-panel flex flex-wrap items-center justify-between gap-2">
<span class="text-sm font-bold text-gray-700">발주 입고(스캐너 대체 수동입력)</span>
<span class="text-sm font-bold text-gray-700"><?= esc((string) ($workspaceTitle ?? '발주 입고')) ?></span>
<div class="flex items-center gap-2">
<a href="<?= base_url('bag/receiving/batch') ?>" class="border border-gray-300 text-gray-700 px-3 py-1 rounded-sm text-sm hover:bg-gray-50">일괄 입고</a>
<a href="<?= esc($otherUrl) ?>" class="border border-gray-300 text-gray-700 px-3 py-1 rounded-sm text-sm hover:bg-gray-50"><?= esc($otherLabel) ?></a>
<a href="<?= base_url('bag/receiving/status') ?>" class="border border-gray-300 text-gray-700 px-3 py-1 rounded-sm text-sm hover:bg-gray-50">입고 현황</a>
</div>
</section>
<?php /* 플래시 메시지는 레이아웃(embed/portal)에서 한 번만 표시 — 중복 출력 방지 */ ?>
<div class="grid grid-cols-1 xl:grid-cols-12 gap-3 mt-2">
<!-- 좌: 발주 현황 -->
<section class="xl:col-span-7 border border-gray-300 rounded-lg bg-white overflow-hidden flex flex-col">
<div class="px-3 py-2 border-b border-gray-200 bg-gray-50 text-sm font-semibold text-gray-700">발주 현황</div>
<section class="p-2 bg-white border border-gray-300 rounded-lg mt-2">
<form method="get" action="<?= base_url('bag/receiving/scanner') ?>" class="flex flex-wrap items-end gap-2">
<div class="flex flex-col min-w-[14rem] max-w-[22rem]">
<label class="text-xs text-gray-500 mb-1">제작업체</label>
<select name="company_idx" class="border border-gray-300 rounded px-2 py-1.5 text-sm bg-white">
<option value="0">제작업체 선택</option>
<?php foreach (($companies ?? []) as $company): ?>
<option value="<?= (int) ($company->cp_idx ?? 0) ?>" <?= (int) ($companyIdx ?? 0) === (int) ($company->cp_idx ?? 0) ? 'selected' : '' ?>>
<?= esc((string) ($company->cp_name ?? '')) ?>
</option>
<?php endforeach; ?>
</select>
<!-- 조회 기준 탭 -->
<div class="flex border-b border-gray-200 text-sm">
<a href="<?= esc($tabUrl('company')) ?>" class="px-4 py-2 border-b-2 <?= $tab === 'company' ? 'border-blue-600 text-blue-700 font-semibold' : 'border-transparent text-gray-500 hover:text-gray-700' ?>">제작업체 · 발주기간</a>
<a href="<?= esc($tabUrl('agency')) ?>" class="px-4 py-2 border-b-2 <?= $tab === 'agency' ? 'border-blue-600 text-blue-700 font-semibold' : 'border-transparent text-gray-500 hover:text-gray-700' ?>">인수자 · 인계자</a>
</div>
<button type="submit" class="bg-btn-search text-white px-4 py-1.5 rounded-sm text-sm shrink-0">조회</button>
</form>
<?php if ((int) ($companyIdx ?? 0) <= 0): ?>
<p class="text-xs text-gray-600 mt-2">제작업체를 선택하면 해당 업체 발주 중 미입고 내역을 조회합니다.</p>
<?php elseif (empty($rows ?? [])): ?>
<p class="text-xs text-amber-700 mt-2">미입고 잔량이 있는 발주가 없습니다. 발주 등록 후 다시 확인해 주세요.</p>
<?php endif; ?>
</section>
<form action="<?= base_url('bag/receiving/scanner/store') ?>" method="post" class="mt-2 space-y-2">
<?= csrf_field() ?>
<input type="hidden" name="company_idx" value="<?= (int) ($companyIdx ?? 0) ?>" />
<section class="p-2 bg-white border border-gray-300 rounded-lg">
<div class="grid grid-cols-1 xl:grid-cols-12 gap-2 items-end">
<div class="xl:col-span-3 flex items-center gap-2">
<label class="text-sm text-gray-600 shrink-0 w-28">인수자 (대행소)</label>
<select name="br_receiver_ref" class="border border-gray-300 rounded px-2 py-1 text-sm w-full" required>
<?php foreach (($receiverOptions ?? []) as $opt): ?>
<option value="<?= esc((string) ($opt['ref'] ?? '')) ?>" <?= (string) ($receiverRef ?? '') === (string) ($opt['ref'] ?? '') ? 'selected' : '' ?>>
<?= esc((string) ($opt['label'] ?? '')) ?>
</option>
<!-- 조회 필터 -->
<form method="get" action="<?= esc($baseUrl) ?>" class="p-2 flex flex-wrap items-end gap-2 border-b border-gray-100 text-sm">
<input type="hidden" name="tab" value="<?= esc($tab) ?>"/>
<?php if ($tab === 'company'): ?>
<div class="flex flex-col">
<label class="text-xs text-gray-500 mb-0.5">제작업체</label>
<select name="company_idx" class="border border-gray-300 rounded px-2 py-1 text-sm min-w-[10rem]">
<option value="0">전체</option>
<?php foreach ($companies as $c): ?>
<option value="<?= (int) ($c->cp_idx ?? 0) ?>" <?= $companyIdx === (int) ($c->cp_idx ?? 0) ? 'selected' : '' ?>><?= esc((string) ($c->cp_name ?? '')) ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="xl:col-span-3 flex items-center gap-2">
<label class="text-sm text-gray-600 shrink-0 w-28">인계자 (제작업체)</label>
<select name="br_sender_idx" class="border border-gray-300 rounded px-2 py-1 text-sm w-full">
<?php foreach (($senders ?? []) as $sender): ?>
<option value="<?= (int) ($sender->mg_idx ?? 0) ?>" <?= (int) ($senderIdx ?? 0) === (int) ($sender->mg_idx ?? 0) ? 'selected' : '' ?>>
<?= esc((string) ($sender->mg_name ?? '')) ?>
</option>
<div class="flex flex-col">
<label class="text-xs text-gray-500 mb-0.5">발주기간(시작월)</label>
<select name="start_month" class="border border-gray-300 rounded px-2 py-1 text-sm min-w-[8rem]">
<option value="">전체</option>
<?php foreach ($monthOptions as $opt): ?>
<option value="<?= esc((string) $opt['value']) ?>" <?= (string) ($startMonth ?? '') === (string) $opt['value'] ? 'selected' : '' ?>><?= esc((string) $opt['label']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="xl:col-span-2 flex items-center gap-2">
<label class="text-sm text-gray-600 w-16">입고일</label>
<input type="date" name="br_receive_date" value="<?= esc((string) old('br_receive_date', date('Y-m-d'))) ?>" class="border border-gray-300 rounded px-2 py-1 text-sm w-full" required />
<div class="flex flex-col">
<label class="text-xs text-gray-500 mb-0.5">종료월</label>
<select name="end_month" class="border border-gray-300 rounded px-2 py-1 text-sm min-w-[8rem]">
<option value="">전체</option>
<?php foreach ($monthOptions as $opt): ?>
<option value="<?= esc((string) $opt['value']) ?>" <?= (string) ($endMonth ?? '') === (string) $opt['value'] ? 'selected' : '' ?>><?= esc((string) $opt['label']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="xl:col-span-2">
<button type="submit" class="w-full border border-blue-600 text-blue-700 px-2 py-1 rounded-sm text-sm hover:bg-blue-50">입고 처리</button>
<?php else: ?>
<div class="flex flex-col">
<label class="text-xs text-gray-500 mb-0.5">인수자(대행소)</label>
<select name="agency_idx" class="border border-gray-300 rounded px-2 py-1 text-sm min-w-[10rem]">
<option value="0">전체</option>
<?php foreach ($agencies as $a): ?>
<option value="<?= (int) ($a->sa_idx ?? 0) ?>" <?= $agencyIdx === (int) ($a->sa_idx ?? 0) ? 'selected' : '' ?>><?= esc((string) ($a->sa_name ?? '')) ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="xl:col-span-2 text-xs text-gray-500">상단에서 제작업체를 조회한 뒤, 아래에서 입고량(매)을 입력해 저장합니다.</div>
<div class="flex flex-col">
<label class="text-xs text-gray-500 mb-0.5">인계자(제작업체)</label>
<select name="company_idx" class="border border-gray-300 rounded px-2 py-1 text-sm min-w-[10rem]">
<option value="0">전체</option>
<?php foreach ($companies as $c): ?>
<option value="<?= (int) ($c->cp_idx ?? 0) ?>" <?= $companyIdx === (int) ($c->cp_idx ?? 0) ? 'selected' : '' ?>><?= esc((string) ($c->cp_name ?? '')) ?></option>
<?php endforeach; ?>
</select>
</div>
<?php endif; ?>
<button type="submit" class="bg-btn-search text-white px-4 py-1 rounded-sm text-sm">조회</button>
</form>
<div class="overflow-auto max-h-[60vh]">
<table class="w-full data-table text-sm" id="order-status-table">
<thead>
<tr>
<th class="text-center sort-th cursor-pointer select-none" data-sort="order_date" data-type="str" style="background:#fff;box-shadow:inset 0 -1px 0 #e5e7eb;">발주일자<span class="sort-ind"></span></th>
<th class="text-left sort-th cursor-pointer select-none" data-sort="bag_name" data-type="str" style="background:#fff;box-shadow:inset 0 -1px 0 #e5e7eb;">봉투종류<span class="sort-ind"></span></th>
<th class="text-right sort-th cursor-pointer select-none" data-sort="order_qty" data-type="num" style="background:#fff;box-shadow:inset 0 -1px 0 #e5e7eb;">발주량<span class="sort-ind"></span></th>
<th class="text-right sort-th cursor-pointer select-none" data-sort="pending" data-type="num" style="background:#fff;box-shadow:inset 0 -1px 0 #e5e7eb;">미입고량<span class="sort-ind"></span></th>
<th class="text-right sort-th cursor-pointer select-none" data-sort="received" data-type="num" style="background:#fff;box-shadow:inset 0 -1px 0 #e5e7eb;">입고량<span class="sort-ind"></span></th>
<th class="text-left" style="background:#fff;box-shadow:inset 0 -1px 0 #e5e7eb;">제작업체</th>
<th class="text-center" style="background:#fff;box-shadow:inset 0 -1px 0 #e5e7eb;">LOT</th>
</tr>
</thead>
<tbody id="order-status-body">
<?php foreach ($rows as $row): $k = (string) ($row['row_key'] ?? ''); ?>
<tr class="os-row cursor-pointer hover:bg-blue-50"
data-row-key="<?= esc($k, 'attr') ?>"
data-bag-name="<?= esc((string) ($row['bag_name'] ?? ''), 'attr') ?>"
data-company="<?= esc((string) ($row['company_name'] ?? ''), 'attr') ?>"
data-lot="<?= esc((string) ($row['lot_no'] ?? ''), 'attr') ?>"
data-order-qty="<?= (int) ($row['order_qty_sheet'] ?? 0) ?>"
data-pending="<?= (int) ($row['pending_qty_sheet'] ?? 0) ?>"
data-received="<?= (int) ($row['received_qty_sheet'] ?? 0) ?>"
data-total-per-box="<?= (int) ($row['total_per_box'] ?? 1) ?>">
<td class="text-center"><?= esc((string) ($row['order_date'] ?? '')) ?></td>
<td class="text-left pl-2"><?= esc((string) ($row['bag_name'] ?? '')) ?></td>
<td class="text-right pr-2"><?= number_format((int) ($row['order_qty_sheet'] ?? 0)) ?></td>
<td class="text-right pr-2 cell-pending"><?= number_format((int) ($row['pending_qty_sheet'] ?? 0)) ?></td>
<td class="text-right pr-2 cell-received"><?= number_format((int) ($row['received_qty_sheet'] ?? 0)) ?></td>
<td class="text-left pl-2"><?= esc((string) ($row['company_name'] ?? '')) ?></td>
<td class="text-center font-mono"><?= esc((string) ($row['lot_no'] ?? '')) ?></td>
</tr>
<?php endforeach; ?>
<?php if (empty($rows)): ?>
<tr><td colspan="7" class="text-center text-gray-400 py-6">조회 조건에 맞는 미입고 발주가 없습니다.</td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
</section>
<div class="border border-gray-300 rounded-lg p-4 overflow-auto bg-white">
<table class="w-full data-table text-sm">
<thead>
<tr>
<th class="text-center">발주일자</th>
<th>봉투종류</th>
<th class="text-right">발주량(매)</th>
<th class="text-right">미입고량(매)</th>
<th class="text-right">입고량(매)</th>
<th>제작업체</th>
<th class="text-center">LOT NO</th>
<th class="text-center">발주NO</th>
</tr>
</thead>
<tbody>
<?php foreach (($rows ?? []) as $row): ?>
<?php $k = (string) ($row['row_key'] ?? ''); ?>
<tr data-row-key="<?= esc($k) ?>" data-lot-no="<?= esc((string) ($row['lot_no'] ?? '')) ?>" data-bag-code="<?= esc((string) ($row['bag_code'] ?? '')) ?>" data-total-per-box="<?= (int) ($row['total_per_box'] ?? 1) ?>" data-pack-per-sheet="<?= (int) ($row['pack_per_sheet'] ?? 1) ?>" data-pending-original="<?= (int) ($row['pending_qty_sheet'] ?? 0) ?>">
<td class="text-center"><?= esc((string) ($row['order_date'] ?? '')) ?></td>
<td class="text-left pl-2"><?= esc((string) ($row['bag_name'] ?? '')) ?></td>
<td class="text-right"><?= number_format((int) ($row['order_qty_sheet'] ?? 0)) ?></td>
<td class="text-right pending-cell"><?= number_format((int) ($row['pending_qty_sheet'] ?? 0)) ?></td>
<td class="text-right">
<input type="number" min="0" max="<?= (int) ($row['pending_qty_sheet'] ?? 0) ?>" name="receive_qty_sheet[<?= esc($k) ?>]" value="<?= esc((string) old('receive_qty_sheet.' . $k, '0')) ?>" class="w-24 border border-gray-300 rounded px-1 py-0.5 text-sm text-right receive-input" />
</td>
<td class="text-left pl-2"><?= esc((string) ($row['company_name'] ?? '')) ?></td>
<td class="text-center font-mono"><?= esc((string) ($row['lot_no'] ?? '')) ?></td>
<td class="text-center"><?= esc((string) ($row['order_no'] ?? '')) ?></td>
</tr>
<?php endforeach; ?>
<?php if (empty($rows ?? [])): ?>
<tr><td colspan="8" class="text-center text-gray-400 py-4"><?php
if ((int) ($companyIdx ?? 0) <= 0) {
echo '제작업체를 선택하고 조회해 주세요.';
} else {
echo '해당 제작업체의 미입고 발주 내역이 없습니다.';
}
?></td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
<!-- 우: 선택 발주 상세 + 스캔/수량 입고 + 입고 세부내역 -->
<section class="xl:col-span-5 flex flex-col gap-3">
<div class="border border-gray-300 rounded-lg bg-white overflow-hidden">
<div class="px-3 py-2 border-b border-gray-200 bg-gray-50 text-sm font-semibold text-gray-700">선택 발주 · 입고 처리</div>
<div class="p-3 space-y-3 text-sm">
<div id="recv-empty" class="text-gray-400 py-6 text-center">좌측 발주 현황에서 발주를 선택하세요.</div>
<div id="recv-detail" class="hidden space-y-3">
<dl class="grid grid-cols-[5rem_1fr] gap-y-1 text-[13px] border border-gray-200 rounded p-2 bg-gray-50">
<dt class="font-semibold text-gray-600">봉투종류</dt><dd id="sel-bag"></dd>
<dt class="font-semibold text-gray-600">제작업체</dt><dd id="sel-company"></dd>
<dt class="font-semibold text-gray-600">발주량</dt><dd><span id="sel-orderqty">0</span> 매</dd>
<dt class="font-semibold text-gray-600">입고량</dt><dd><span id="sel-received" class="font-bold text-blue-700">0</span> 매</dd>
<dt class="font-semibold text-gray-600">미입고량</dt><dd><span id="sel-pending" class="font-bold text-red-600">0</span> 매</dd>
</dl>
<div class="flex items-center gap-2">
<a href="<?= base_url('bag/purchase-inbound') ?>" class="bg-gray-200 text-gray-700 px-6 py-1.5 rounded-sm text-sm">취소</a>
</div>
</form>
<div class="grid grid-cols-2 gap-2">
<label class="flex flex-col text-xs text-gray-500">인수자(대행소)
<select id="br_receiver_ref" class="mt-0.5 border border-gray-300 rounded px-2 py-1 text-sm">
<?php foreach ($receiverOptions as $opt): ?>
<option value="<?= esc((string) ($opt['ref'] ?? ''), 'attr') ?>" <?= (string) ($receiverRef ?? '') === (string) ($opt['ref'] ?? '') ? 'selected' : '' ?>><?= esc((string) ($opt['label'] ?? '')) ?></option>
<?php endforeach; ?>
</select>
</label>
<label class="flex flex-col text-xs text-gray-500">인계자(제작업체)
<select id="br_sender_idx" class="mt-0.5 border border-gray-300 rounded px-2 py-1 text-sm">
<?php foreach ($senders as $s): ?>
<option value="<?= (int) ($s->mg_idx ?? 0) ?>" <?= (int) ($senderIdx ?? 0) === (int) ($s->mg_idx ?? 0) ? 'selected' : '' ?>><?= esc((string) ($s->mg_name ?? '')) ?></option>
<?php endforeach; ?>
</select>
</label>
</div>
<label class="flex flex-col text-xs text-gray-500">입고일
<input type="date" id="br_receive_date" value="<?= esc(date('Y-m-d'), 'attr') ?>" class="mt-0.5 border border-gray-300 rounded px-2 py-1 text-sm w-40"/>
</label>
<div class="border border-emerald-300 rounded-lg p-2 bg-emerald-50/40">
<label class="block text-xs font-semibold text-emerald-800 mb-1"><i class="fa-solid fa-barcode mr-1"></i>박스 바코드 스캔 (스캔 1회 = 1박스 입고)</label>
<input type="text" id="scan-input" autocomplete="off" placeholder="박스 바코드를 스캔 후 Enter" class="border border-gray-300 rounded px-2 py-1 text-sm w-full" disabled/>
<div class="flex items-center gap-2 mt-2">
<span class="text-xs text-gray-500 shrink-0">또는 수량 직접입력(매)</span>
<input type="number" id="qty-input" min="1" placeholder="매수" class="border border-gray-300 rounded px-2 py-1 text-sm w-28 text-right" disabled/>
<button type="button" id="btn-receive" class="border border-blue-600 text-blue-700 px-3 py-1 rounded-sm text-sm hover:bg-blue-50 disabled:opacity-50" disabled>입고 처리</button>
</div>
<p id="scan-msg" class="text-xs text-gray-500 mt-1"></p>
</div>
</div>
</div>
</div>
<div class="border border-gray-300 rounded-lg bg-white overflow-hidden">
<div class="px-3 py-2 border-b border-gray-200 bg-gray-50 text-sm font-semibold text-gray-700 flex items-center justify-between">
<span>입고 세부내역 (박스코드)</span>
<span class="text-gray-500 text-xs">박스 <span id="detail-count" class="font-bold text-blue-700">0</span></span>
</div>
<div class="overflow-auto max-h-[36vh]">
<table class="w-full data-table text-sm">
<thead>
<tr>
<th class="w-10 text-center" style="background:#fff;box-shadow:inset 0 -1px 0 #e5e7eb;">No</th>
<th class="text-left" style="background:#fff;box-shadow:inset 0 -1px 0 #e5e7eb;">봉투종류</th>
<th class="text-left" style="background:#fff;box-shadow:inset 0 -1px 0 #e5e7eb;">박스코드</th>
<th class="w-16 text-right" style="background:#fff;box-shadow:inset 0 -1px 0 #e5e7eb;">수량</th>
</tr>
</thead>
<tbody id="detail-body">
<tr><td colspan="4" class="text-center text-gray-400 py-6">스캔/입고 시 박스코드가 추가됩니다.</td></tr>
</tbody>
</table>
</div>
</div>
</section>
</div>
<script>
(() => {
const parseIntSafe = (v) => {
const n = Number(String(v ?? '').replace(/,/g, ''));
return Number.isFinite(n) ? Math.max(0, Math.floor(n)) : 0;
};
const mode = <?= json_encode($mode) ?>;
const scanApi = new URL('<?= base_url('bag/receiving/scan-box') ?>', window.location.href).pathname;
const csrfName = '<?= csrf_token() ?>';
let csrfHash = '<?= csrf_hash() ?>';
const nf = (n) => new Intl.NumberFormat('ko-KR').format(Number(n) || 0);
const esc = (s) => String(s == null ? '' : s).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
const refreshPending = (row) => {
const pendingCell = row.querySelector('.pending-cell');
const input = row.querySelector('.receive-input');
if (!pendingCell || !input) return;
const original = parseIntSafe(row.getAttribute('data-pending-original'));
const current = parseIntSafe(input.value);
const remain = Math.max(0, original - current);
pendingCell.textContent = Number(remain || 0).toLocaleString('ko-KR');
};
const tbody = document.getElementById('order-status-body');
const detailBody = document.getElementById('detail-body');
const detailCountEl = document.getElementById('detail-count');
const scanInput = document.getElementById('scan-input');
const qtyInput = document.getElementById('qty-input');
const btnReceive = document.getElementById('btn-receive');
const scanMsg = document.getElementById('scan-msg');
let selectedRow = null;
let detailNo = 0;
document.querySelectorAll('.receive-input').forEach((input) => {
input.addEventListener('input', (e) => {
const row = e.target.closest('tr');
if (!row) return;
const original = parseIntSafe(row.getAttribute('data-pending-original'));
const current = Math.min(parseIntSafe(input.value), original);
input.value = String(current);
refreshPending(row);
// ── 정렬 ──
let sortKey = '', sortDir = 'asc';
const numOf = (tr, key) => {
const map = { order_qty: 'data-order-qty', pending: 'data-pending', received: 'data-received' };
if (map[key]) return Number(tr.getAttribute(map[key]) || 0);
return 0;
};
const strOf = (tr, key) => {
if (key === 'order_date') return tr.children[0].textContent.trim();
if (key === 'bag_name') return tr.getAttribute('data-bag-name') || '';
return '';
};
document.querySelectorAll('#order-status-table .sort-th').forEach((th) => {
th.addEventListener('click', () => {
const key = th.dataset.sort, type = th.dataset.type;
if (sortKey === key) { sortDir = sortDir === 'asc' ? 'desc' : 'asc'; } else { sortKey = key; sortDir = 'asc'; }
const rows = Array.prototype.slice.call(tbody.querySelectorAll('tr.os-row'));
rows.sort((a, b) => {
let va, vb;
if (type === 'num') { va = numOf(a, key); vb = numOf(b, key); return sortDir === 'asc' ? va - vb : vb - va; }
va = strOf(a, key); vb = strOf(b, key);
return sortDir === 'asc' ? va.localeCompare(vb, 'ko') : vb.localeCompare(va, 'ko');
});
rows.forEach((r) => tbody.appendChild(r));
document.querySelectorAll('#order-status-table .sort-ind').forEach((s) => { s.textContent = ''; });
const ind = th.querySelector('.sort-ind');
if (ind) ind.textContent = sortDir === 'asc' ? ' ▲' : ' ▼';
});
const row = input.closest('tr');
if (row) refreshPending(row);
});
// ── 행 선택 ──
function selectRow(tr) {
if (selectedRow) selectedRow.classList.remove('bg-blue-100');
selectedRow = tr;
tr.classList.add('bg-blue-100');
document.getElementById('recv-empty').classList.add('hidden');
document.getElementById('recv-detail').classList.remove('hidden');
document.getElementById('sel-bag').textContent = tr.getAttribute('data-bag-name') || '';
document.getElementById('sel-company').textContent = tr.getAttribute('data-company') || '-';
document.getElementById('sel-orderqty').textContent = nf(tr.getAttribute('data-order-qty'));
document.getElementById('sel-received').textContent = nf(tr.getAttribute('data-received'));
document.getElementById('sel-pending').textContent = nf(tr.getAttribute('data-pending'));
const pending = Number(tr.getAttribute('data-pending') || 0);
const enabled = pending > 0;
scanInput.disabled = !enabled;
qtyInput.disabled = !enabled;
btnReceive.disabled = !enabled;
scanMsg.textContent = enabled ? '' : '이미 전량 입고된 발주입니다.';
scanMsg.className = 'text-xs mt-1 ' + (enabled ? 'text-gray-500' : 'text-amber-700');
if (enabled) scanInput.focus();
}
tbody.addEventListener('click', (e) => {
const tr = e.target.closest('tr.os-row');
if (tr) selectRow(tr);
});
// ── 입고 처리(스캔/수량) AJAX ──
async function doReceive(barcode, qtySheet) {
if (!selectedRow) return;
const body = new URLSearchParams();
body.set(csrfName, csrfHash);
body.set('mode', mode);
body.set('row_key', selectedRow.getAttribute('data-row-key'));
body.set('br_receiver_ref', document.getElementById('br_receiver_ref').value || '');
body.set('br_sender_idx', document.getElementById('br_sender_idx').value || '0');
body.set('br_receive_date', document.getElementById('br_receive_date').value || '');
body.set('barcode', barcode || '');
body.set('qty_sheet', String(qtySheet || 0));
let data;
try {
const res = await fetch(scanApi, {
method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
body: body.toString(),
});
data = await res.json();
} catch (err) {
scanMsg.textContent = '통신 오류가 발생했습니다.'; scanMsg.className = 'text-xs mt-1 text-red-600';
return;
}
if (data && data.csrf) csrfHash = data.csrf;
if (!data || !data.ok) {
scanMsg.textContent = (data && data.message) || '입고 처리 실패';
scanMsg.className = 'text-xs mt-1 text-red-600 font-semibold';
return;
}
// 선택 행 · 상세 수치 갱신
selectedRow.setAttribute('data-received', String(data.received_qty_sheet));
selectedRow.setAttribute('data-pending', String(data.pending_qty_sheet));
selectedRow.querySelector('.cell-received').textContent = nf(data.received_qty_sheet);
selectedRow.querySelector('.cell-pending').textContent = nf(data.pending_qty_sheet);
document.getElementById('sel-received').textContent = nf(data.received_qty_sheet);
document.getElementById('sel-pending').textContent = nf(data.pending_qty_sheet);
// 입고 세부내역에 박스코드 추가(최신이 위로)
(data.boxes || []).forEach((b) => {
detailNo++;
if (detailNo === 1) detailBody.innerHTML = '';
const tr = document.createElement('tr');
tr.innerHTML = '<td class="text-center">' + detailNo + '</td>'
+ '<td class="text-left pl-2">' + esc(data.bag_name) + '</td>'
+ '<td class="text-left pl-2 font-mono text-gray-600">' + esc(b.box_code) + '</td>'
+ '<td class="text-right pr-2">' + nf(b.sheet) + '</td>';
detailBody.insertBefore(tr, detailBody.firstChild);
});
detailCountEl.textContent = nf(detailNo);
scanMsg.textContent = '입고: ' + data.bag_name + ' / ' + nf(data.qty_sheet) + '매' + (data.qty_box ? ' (' + data.qty_box + '박스)' : '') + ' · 잔량 ' + nf(data.pending_qty_sheet);
scanMsg.className = 'text-xs mt-1 text-emerald-700';
// 전량 입고되면 입력 잠금
if (Number(data.pending_qty_sheet) <= 0) {
scanInput.disabled = true; qtyInput.disabled = true; btnReceive.disabled = true;
}
}
scanInput.addEventListener('keydown', (e) => {
if (e.key !== 'Enter') return;
e.preventDefault();
const code = (scanInput.value || '').trim();
if (!code) return;
doReceive(code, 0);
scanInput.value = '';
scanInput.focus();
});
btnReceive.addEventListener('click', () => {
const q = Math.floor(Number(qtyInput.value || 0));
if (!(q > 0)) { scanMsg.textContent = '입고 수량(매)을 입력하세요.'; scanMsg.className = 'text-xs mt-1 text-amber-700'; return; }
doReceive('', q);
qtyInput.value = '';
});
})();
</script>