Files
jongryangje/app/Views/bag/order_phone.php
taekyoungc acce968f9c feat: 전화접수 관리·주문 개선 + 매뉴얼 화면 바로가기
- 전화접수 관리: 배달일 기준 조회, 컬럼 보강(구분/포장 O·X/결제/수령/입금/총금액/취소),
  헤더 정렬, 배달일 수정 저장, 포장 명세·포장량 수정, 입금자 영수증 출력
- 전화 주문 접수: 행추가 → 일괄표(카테고리 그룹·포장 헤더)
- 매뉴얼 소제목에 '화면 열기' 바로가기(실제 GET 라우트만 연결)
- shop_order_item.soi_packed_qty 컬럼 추가(SQL)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 14:31:21 +09:00

427 lines
20 KiB
PHP

<section class="border-b border-gray-300 p-2 shrink-0 bg-control-panel">
<span class="text-sm font-bold text-gray-700">전화 주문 접수</span>
</section>
<div class="border border-gray-300 rounded-lg p-4 mt-2 bg-white">
<?php /* success·error 플래시는 레이아웃(embed/portal)에서 한 번만 표시 — 중복 방지. (검증 errors 목록만 여기서 표시) */ ?>
<?php $flashErrors = session()->getFlashdata('errors'); ?>
<?php if (is_array($flashErrors) && $flashErrors !== []): ?>
<div class="mb-3 border border-red-300 bg-red-50 text-red-700 px-3 py-2 rounded-sm text-sm">
<ul class="list-disc list-inside">
<?php foreach ($flashErrors as $err): ?>
<li><?= esc((string) $err) ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form action="<?= base_url('bag/shop-order/store') ?>" method="POST" class="space-y-4" id="phone-order-form">
<?= csrf_field() ?>
<input type="hidden" name="return_to" value="bag/order/phone"/>
<div class="grid grid-cols-1 xl:grid-cols-3 gap-4">
<div class="xl:col-span-2 space-y-3">
<div class="flex flex-wrap items-center gap-2">
<label class="block text-sm font-bold text-gray-700 w-28">판매소 검색</label>
<div class="relative flex-1 min-w-[20rem]">
<input id="shop-search" class="border border-gray-300 rounded px-3 py-1.5 text-sm w-[34rem] max-w-full" type="text" autocomplete="off" placeholder="코드/사업자번호/대표자명/상호/전화/주소 중 하나 입력"/>
<div id="shop-search-suggest" class="hidden absolute left-0 top-full mt-1 w-[48rem] max-w-[90vw] max-h-72 overflow-auto border border-gray-300 rounded-lg bg-white shadow-lg z-30"></div>
</div>
</div>
<div class="flex flex-wrap items-center gap-2">
<label class="block text-sm font-bold text-gray-700 w-28">판매소 선택 <span class="text-red-500">*</span></label>
<select id="shop-select" class="border border-gray-300 rounded px-3 py-1.5 text-sm w-[34rem] max-w-full" name="so_ds_idx" required>
<option value="">선택</option>
<?php foreach ($shops as $shop): ?>
<option
value="<?= esc($shop->ds_idx) ?>"
data-shop-no="<?= esc((string) ($shop->ds_shop_no ?? '')) ?>"
data-biz-no="<?= esc((string) ($shop->ds_biz_no ?? '')) ?>"
data-name="<?= esc((string) ($shop->ds_name ?? '')) ?>"
data-rep-name="<?= esc((string) ($shop->ds_rep_name ?? '')) ?>"
data-tel="<?= esc((string) ($shop->ds_tel ?? '')) ?>"
data-rep-phone="<?= esc((string) ($shop->ds_rep_phone ?? '')) ?>"
data-address="<?= esc(trim((string) ($shop->ds_addr ?? '') . ' ' . (string) ($shop->ds_addr_detail ?? ''))) ?>"
data-va-bank="<?= esc((string) ($shop->ds_va_bank ?? '')) ?>"
data-va-account="<?= esc((string) ($shop->ds_va_account ?? '')) ?>"
>
<?= esc(($shop->ds_shop_no ? '[' . $shop->ds_shop_no . '] ' : '') . $shop->ds_name) ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="border border-gray-300 rounded-lg p-2 bg-gray-50">
<div class="text-sm font-bold text-gray-700 mb-2">접수 정보</div>
<table class="w-full text-sm">
<tr><th class="text-left w-28 py-1">접수번호</th><td class="py-1 text-gray-800 font-semibold"><?= esc((string) ($receiptNo ?? 1)) ?></td></tr>
<tr><th class="text-left py-1">접수일</th><td class="py-1 text-gray-700"><?= esc(date('Y-m-d')) ?></td></tr>
<tr><th class="text-left py-1">배달일</th><td class="py-1 text-gray-700"><?= esc(date('Y-m-d', strtotime('+1 day'))) ?> (자동)</td></tr>
<tr><th class="text-left py-1">담당자</th><td class="py-1 text-gray-700"><?= esc((string) (session()->get('mb_name') ?? '담당자')) ?></td></tr>
</table>
</div>
</div>
<div class="grid grid-cols-1 xl:grid-cols-2 gap-4">
<div class="border border-gray-300 rounded-lg p-2 bg-gray-50">
<div class="text-sm font-bold text-gray-700 mb-2">지정판매소 정보</div>
<table class="w-full text-sm">
<tr><th class="text-left w-28 py-1">코드</th><td id="shop-info-code" class="py-1 text-gray-700">-</td></tr>
<tr><th class="text-left py-1">사업자번호</th><td id="shop-info-biz" class="py-1 text-gray-700">-</td></tr>
<tr><th class="text-left py-1">대표자명</th><td id="shop-info-rep" class="py-1 text-gray-700">-</td></tr>
<tr><th class="text-left py-1">상호명</th><td id="shop-info-name" class="py-1 text-gray-700">-</td></tr>
<tr><th class="text-left py-1">전화번호</th><td id="shop-info-tel" class="py-1 text-gray-700">-</td></tr>
<tr><th class="text-left py-1">주소</th><td id="shop-info-addr" class="py-1 text-gray-700">-</td></tr>
</table>
</div>
<div class="border border-gray-300 rounded-lg p-2 bg-gray-50">
<div class="text-sm font-bold text-gray-700 mb-2">결제/가상계좌</div>
<div class="flex flex-wrap items-center gap-2 mb-2">
<label class="block text-sm font-bold text-gray-700 w-24">결제구분 <span class="text-red-500">*</span></label>
<select id="payment-type" class="border border-gray-300 rounded px-3 py-1.5 text-sm w-40" name="so_payment_type" required>
<option value="">선택</option>
<option value="이체">이체</option>
<option value="가상계좌" selected>가상계좌</option>
</select>
<span id="payment-guide" class="text-xs text-gray-500"></span>
</div>
<div class="text-sm">
<span class="font-semibold text-gray-700">가상계좌:</span>
<span id="shop-info-va" class="text-gray-700">-</span>
</div>
</div>
</div>
<input type="hidden" name="so_delivery_date" value="<?= esc(date('Y-m-d', strtotime('+1 day'))) ?>"/>
<?php
// 일괄표: 봉투코드를 카테고리(일반용·재사용·음식물 스티커·대형폐기물 스티커)로 묶어
// 봉투류는 리터 오름차순, 폐기물 스티커는 금액 오름차순으로 정렬한다.
$catOf = static function (string $name): ?array {
if (mb_strpos($name, '일반용') === 0) { return [1, '일반용', 'liter']; }
if (mb_strpos($name, '재사용') === 0) { return [2, '재사용', 'liter']; }
if (mb_strpos($name, '음식물 스티커') === 0) { return [3, '음식물 스티커', 'liter']; }
if (mb_strpos($name, '폐기물 스티커') === 0) { return [4, '대형폐기물 스티커', 'amount']; }
return null;
};
$orderGroups = [];
foreach (($bagCodes ?? []) as $cd) {
$name = (string) ($cd->cd_name ?? '');
$cat = $catOf($name);
if ($cat === null) { continue; }
$code = (string) $cd->cd_code;
$price = $priceMap[$code] ?? null;
$unit = $unitMap[$code] ?? null;
if ($cat[2] === 'amount') {
preg_match('/([\d,]+)\s*원/u', $name, $m);
$sortVal = (int) str_replace(',', '', $m[1] ?? '0');
} else {
preg_match('/(\d+)\s*[lL]/u', $name, $m);
$sortVal = (int) ($m[1] ?? 0);
}
$orderGroups[$cat[0]]['label'] = $cat[1];
$orderGroups[$cat[0]]['rows'][] = [
'code' => $code,
'name' => $name,
'price' => (int) ($price->bp_consumer ?? 0),
'box' => (int) ($unit->pu_total_per_box ?? 0),
'pack' => (int) ($unit->pu_pack_per_sheet ?? 0),
'sort' => $sortVal,
];
}
ksort($orderGroups);
foreach ($orderGroups as &$g) {
usort($g['rows'], static fn ($a, $b) => $a['sort'] <=> $b['sort']);
}
unset($g);
?>
<div class="mt-4">
<label class="block text-sm font-bold text-gray-700 mb-2">전화 주문접수표 (일괄)</label>
<style>
/* 그룹 헤더(rowspan/colspan) 경계선이 단가까지 이어지는 현상 방지 — 헤더 맨 아래 한 줄만 */
table.phone-batch-table { border-collapse: separate; border-spacing: 0; }
table.phone-batch-table thead th { border-bottom: 0; }
table.phone-batch-table thead tr:last-child th { border-bottom: 1px solid #e5e7eb; } /* 수량/금액 등 하위 헤더 */
table.phone-batch-table thead tr:first-child th[rowspan] { border-bottom: 1px solid #e5e7eb; } /* 구분·봉투종류·단가 */
table.phone-batch-table tbody td { border-bottom: 1px solid #f1f3f5; }
</style>
<div class="border border-gray-300 rounded-lg p-4 overflow-auto">
<table class="w-full data-table text-sm phone-batch-table">
<thead>
<tr>
<th class="text-center" rowspan="2">구분</th>
<th rowspan="2">봉투종류</th>
<th class="text-center" colspan="2">Pack</th>
<th class="text-center" colspan="2">Box</th>
<th class="text-right" rowspan="2">단가</th>
<th class="text-center" colspan="2">주문내용</th>
<th class="text-center" colspan="3">포장</th>
</tr>
<tr>
<th class="text-right">수량</th>
<th class="text-right">금액</th>
<th class="text-right">수량</th>
<th class="text-right">금액</th>
<th class="text-right">판매수량</th>
<th class="text-right">금액</th>
<th class="text-center">B</th>
<th class="text-center">P</th>
<th class="text-center">E</th>
</tr>
</thead>
<tbody id="order-rows">
<?php if (empty($orderGroups)): ?>
<tr><td colspan="12" class="text-center text-gray-400 py-6">등록된 봉투 품목이 없습니다.</td></tr>
<?php else: ?>
<?php foreach ($orderGroups as $g): ?>
<?php $rc = count($g['rows']); $firstRow = true; ?>
<?php foreach ($g['rows'] as $r): ?>
<?php $boxPrice = $r['box'] * $r['price']; $packPrice = $r['pack'] * $r['price']; ?>
<tr class="order-row" data-unit-price="<?= esc((string) $r['price'], 'attr') ?>" data-box-sheets="<?= esc((string) $r['box'], 'attr') ?>" data-pack-sheets="<?= esc((string) $r['pack'], 'attr') ?>">
<?php if ($firstRow): ?>
<td class="text-center align-top font-semibold text-gray-700" rowspan="<?= (int) $rc ?>"><?= esc($g['label']) ?></td>
<?php endif; ?>
<td class="text-left pl-2"><?= esc($r['name']) ?><input type="hidden" name="item_bag_code[]" value="<?= esc($r['code'], 'attr') ?>"/></td>
<td class="text-right px-2"><?= number_format($r['pack']) ?></td>
<td class="text-right px-2"><?= number_format($packPrice) ?></td>
<td class="text-right px-2"><?= number_format($r['box']) ?></td>
<td class="text-right px-2"><?= number_format($boxPrice) ?></td>
<td class="text-right px-2"><?= number_format($r['price']) ?></td>
<td><input class="border border-gray-300 rounded px-2 py-1 text-sm w-full text-right item-qty-input" name="item_qty[]" type="number" min="0" value="0"/></td>
<td class="text-right px-2 item-amount-cell">0</td>
<td class="text-center item-box-cell">0</td>
<td class="text-center item-pack-cell">0</td>
<td class="text-center item-sheet-cell">0</td>
</tr>
<?php $firstRow = false; ?>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
<tfoot>
<tr class="font-semibold bg-gray-50">
<td colspan="7" class="text-right px-2 py-1">합계</td>
<td class="text-right px-2 py-1" id="sum-qty">0</td>
<td class="text-right px-2 py-1" id="sum-amount">0</td>
<td class="text-center px-2 py-1" id="sum-box">0</td>
<td class="text-center px-2 py-1" id="sum-pack">0</td>
<td class="text-center px-2 py-1" id="sum-sheet">0</td>
</tr>
</tfoot>
</table>
</div>
</div>
<div class="flex gap-2 pt-2">
<button type="submit" class="bg-btn-search text-white px-6 py-1.5 rounded-sm text-sm shadow hover:opacity-90 transition">저장</button>
<a href="<?= base_url('bag/sales') ?>" class="bg-gray-200 text-gray-700 px-6 py-1.5 rounded-sm text-sm hover:bg-gray-300 transition">취소</a>
</div>
</form>
</div>
<script>
(() => {
const shopSearch = document.getElementById('shop-search');
const shopSelect = document.getElementById('shop-select');
const shopSuggest = document.getElementById('shop-search-suggest');
const paymentType = document.getElementById('payment-type');
const paymentGuide = document.getElementById('payment-guide');
const orderRows = document.getElementById('order-rows');
const form = document.getElementById('phone-order-form');
const nf = (n) => new Intl.NumberFormat('ko-KR').format(n || 0);
function updateShopInfo() {
const opt = shopSelect.options[shopSelect.selectedIndex];
const bank = opt?.dataset?.vaBank || '';
const account = opt?.dataset?.vaAccount || '';
const va = bank || account ? [bank, account].filter(Boolean).join(' ') : '-';
document.getElementById('shop-info-code').textContent = opt?.dataset?.shopNo || '-';
document.getElementById('shop-info-biz').textContent = opt?.dataset?.bizNo || '-';
document.getElementById('shop-info-rep').textContent = opt?.dataset?.repName || '-';
document.getElementById('shop-info-name').textContent = opt?.dataset?.name || '-';
document.getElementById('shop-info-tel').textContent = opt?.dataset?.tel || opt?.dataset?.repPhone || '-';
document.getElementById('shop-info-addr').textContent = opt?.dataset?.address || '-';
document.getElementById('shop-info-va').textContent = va;
paymentGuide.textContent = paymentType.value === '가상계좌' ? ('안내 계좌: ' + va) : '';
}
function shopMergedText(opt) {
return [
opt.dataset.shopNo || '',
opt.dataset.bizNo || '',
opt.dataset.repName || '',
opt.dataset.name || '',
opt.dataset.tel || '',
opt.dataset.address || '',
].filter(Boolean).join(' ');
}
function matchShopByKeyword(keyword) {
const q = (keyword || '').trim().toLowerCase();
if (!q) return;
for (let i = 0; i < shopSelect.options.length; i++) {
const opt = shopSelect.options[i];
if (!opt.value) continue;
const merged = (shopMergedText(opt) + ' ' + (opt.text || '')).toLowerCase();
if (merged.includes(q)) {
shopSelect.selectedIndex = i;
updateShopInfo();
return;
}
}
}
function hideSuggest() {
if (!shopSuggest) return;
shopSuggest.classList.add('hidden');
shopSuggest.innerHTML = '';
}
function renderSuggest(query) {
if (!shopSuggest || !shopSelect) return;
const q = (query || '').trim().toLowerCase();
const matched = [];
for (let i = 0; i < shopSelect.options.length; i++) {
const opt = shopSelect.options[i];
if (!opt.value) continue;
const merged = shopMergedText(opt);
if (!q || merged.toLowerCase().includes(q)) {
matched.push({ index: i, label: merged });
}
if (matched.length >= 50) break;
}
if (matched.length === 0) {
hideSuggest();
return;
}
shopSuggest.innerHTML = matched.map((m) => `
<button type="button" class="shop-suggest-item w-full text-left px-2 py-1.5 hover:bg-blue-50 text-xs border-b border-gray-100 whitespace-normal break-all" data-index="${m.index}">${m.label}</button>
`).join('');
shopSuggest.classList.remove('hidden');
}
function calcRow(row) {
const qtyInput = row.querySelector('.item-qty-input');
const qty = parseInt(qtyInput.value || '0', 10) || 0;
const unitPrice = parseInt(row.dataset.unitPrice || '0', 10) || 0;
const boxSheets = parseInt(row.dataset.boxSheets || '0', 10) || 0;
const packSheets = parseInt(row.dataset.packSheets || '0', 10) || 0;
let box = 0;
let pack = 0;
let sheet = qty;
if (boxSheets > 0) {
box = Math.floor(qty / boxSheets);
const remain = qty % boxSheets;
if (packSheets > 0) {
pack = Math.floor(remain / packSheets);
sheet = remain % packSheets;
} else {
sheet = remain;
}
} else if (packSheets > 0) {
pack = Math.floor(qty / packSheets);
sheet = qty % packSheets;
}
const amount = unitPrice * qty;
row.querySelector('.item-amount-cell').textContent = nf(amount);
row.querySelector('.item-box-cell').textContent = box ? nf(box) : '';
row.querySelector('.item-pack-cell').textContent = pack ? nf(pack) : '';
row.querySelector('.item-sheet-cell').textContent = sheet ? nf(sheet) : '';
return { qty, amount, box, pack, sheet };
}
function recalcAllRows() {
let sumQty = 0, sumAmount = 0, sumBox = 0, sumPack = 0, sumSheet = 0;
document.querySelectorAll('.order-row').forEach((row) => {
const r = calcRow(row);
sumQty += r.qty;
sumAmount += r.amount;
sumBox += r.box;
sumPack += r.pack;
sumSheet += r.sheet;
});
document.getElementById('sum-qty').textContent = nf(sumQty);
document.getElementById('sum-amount').textContent = nf(sumAmount);
document.getElementById('sum-box').textContent = nf(sumBox);
document.getElementById('sum-pack').textContent = nf(sumPack);
document.getElementById('sum-sheet').textContent = nf(sumSheet);
}
function clearSearchInputOnly() {
if (shopSearch) shopSearch.value = '';
}
// 판매소 검색 input을 다시 누르면(또는 포커스를 다시 받으면) 검색 input 텍스트만 비운다.
// 기존에 선택된 판매소 정보(셀렉트, 지정판매소 정보, 가상계좌 등)는 그대로 유지한다.
shopSearch?.addEventListener('focus', () => {
if (shopSelect && shopSelect.value) clearSearchInputOnly();
renderSuggest('');
});
shopSearch?.addEventListener('mousedown', () => {
if (shopSelect && shopSelect.value) clearSearchInputOnly();
});
shopSearch?.addEventListener('click', () => renderSuggest(shopSearch.value || ''));
shopSearch?.addEventListener('input', (e) => renderSuggest(e.target.value || ''));
shopSuggest?.addEventListener('mousedown', (e) => {
const btn = e.target.closest('.shop-suggest-item');
if (!btn) return;
e.preventDefault();
const idx = Number(btn.dataset.index || -1);
if (!Number.isInteger(idx) || idx < 0 || idx >= shopSelect.options.length) return;
shopSelect.selectedIndex = idx;
const opt = shopSelect.options[idx];
shopSearch.value = shopMergedText(opt);
updateShopInfo();
hideSuggest();
});
document.addEventListener('click', (e) => {
if (!shopSuggest || !shopSearch) return;
if (e.target === shopSearch || shopSuggest.contains(e.target)) return;
hideSuggest();
});
shopSearch?.addEventListener('change', (e) => matchShopByKeyword(e.target.value));
shopSearch?.addEventListener('blur', () => {
// 자동완성 클릭이 우선되도록 약간 지연.
setTimeout(() => {
matchShopByKeyword(shopSearch.value || '');
}, 150);
});
shopSelect?.addEventListener('change', updateShopInfo);
paymentType?.addEventListener('change', updateShopInfo);
orderRows?.addEventListener('input', function (e) {
if (e.target.closest('.item-qty-input')) {
recalcAllRows();
}
});
form?.addEventListener('submit', function (e) {
let hasItem = false;
document.querySelectorAll('.order-row').forEach((row) => {
const qty = parseInt(row.querySelector('.item-qty-input').value || '0', 10) || 0;
if (qty > 0) hasItem = true;
});
if (!hasItem) {
e.preventDefault();
alert('주문 수량을 1개 이상 입력해 주세요.');
}
});
updateShopInfo();
recalcAllRows();
})();
</script>
<?= view('bag/_dev_all_sales_panel') ?>