Files
jongryangje/app/Controllers/Admin/BagOrder.php
javamon1174 1e8bf1eeeb P2-15~18, P5-04~11, CT-05~06 웹 미구현 기능 전체 구현
P2-15: 지정판매소 다조건 조회 (이름/구군/상태 필터)
P2-17: 지정판매소 지도 표시 (Kakao Maps)
P2-18: 지정판매소 현황 (연도별 신규/취소 통계)
P5-04: 년 판매 현황 (월별 피벗 테이블)
P5-05: 지정판매소별 판매현황 (판매소별 수량/금액)
P5-06: 홈택스 세금계산서 엑셀 내보내기
P5-08: 반품/파기 현황 (기간별 조회)
P5-10: LOT 수불 조회 (LOT 번호 검색)
P5-11: 기타 입출고 (등록 + 재고 연동)
CT-05: CRUD 로깅 (activity_log 테이블 + audit_helper)
CT-06: 대시보드 실 데이터 (발주/판매/재고/불출 통계)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 16:50:28 +09:00

279 lines
12 KiB
PHP

<?php
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use App\Models\BagOrderModel;
use App\Models\BagOrderItemModel;
use App\Models\BagPriceModel;
use App\Models\PackagingUnitModel;
use App\Models\CompanyModel;
use App\Models\SalesAgencyModel;
use App\Models\CodeKindModel;
use App\Models\CodeDetailModel;
use Ramsey\Uuid\Uuid;
class BagOrder extends BaseController
{
private BagOrderModel $orderModel;
private BagOrderItemModel $itemModel;
public function __construct()
{
$this->orderModel = model(BagOrderModel::class);
$this->itemModel = model(BagOrderItemModel::class);
}
public function index()
{
helper('admin');
$lgIdx = admin_effective_lg_idx();
if (!$lgIdx) {
return redirect()->to(site_url('admin'))->with('error', '지자체를 선택해 주세요.');
}
$builder = $this->orderModel->where('bo_lg_idx', $lgIdx);
// 기간 필터
$startDate = $this->request->getGet('start_date');
$endDate = $this->request->getGet('end_date');
$status = $this->request->getGet('status');
if ($startDate) $builder->where('bo_order_date >=', $startDate);
if ($endDate) $builder->where('bo_order_date <=', $endDate);
if ($status) $builder->where('bo_status', $status);
$list = $builder->orderBy('bo_order_date', 'DESC')->orderBy('bo_idx', 'DESC')->paginate(20);
$pager = $this->orderModel->pager;
// 발주별 품목 합계
$itemSummary = [];
foreach ($list as $order) {
$items = $this->itemModel->where('boi_bo_idx', $order->bo_idx)->findAll();
$totalQty = 0; $totalAmt = 0;
foreach ($items as $it) { $totalQty += (int) $it->boi_qty_sheet; $totalAmt += (float) $it->boi_amount; }
$itemSummary[$order->bo_idx] = ['qty' => $totalQty, 'amount' => $totalAmt, 'count' => count($items)];
}
// 제작업체/대행소 이름 매핑
$companyMap = []; $agencyMap = [];
foreach (model(CompanyModel::class)->where('cp_lg_idx', $lgIdx)->findAll() as $c) $companyMap[$c->cp_idx] = $c->cp_name;
foreach (model(SalesAgencyModel::class)->where('sa_lg_idx', $lgIdx)->findAll() as $a) $agencyMap[$a->sa_idx] = $a->sa_name;
return view('admin/layout', [
'title' => '발주 현황',
'content' => view('admin/bag_order/index', compact('list', 'itemSummary', 'companyMap', 'agencyMap', 'startDate', 'endDate', 'status', 'pager')),
]);
}
public function export()
{
helper(['admin', 'export']);
$lgIdx = admin_effective_lg_idx();
if (!$lgIdx) {
return redirect()->to(site_url('admin/bag-orders'))->with('error', '지자체를 선택해 주세요.');
}
$builder = $this->orderModel->where('bo_lg_idx', $lgIdx);
$startDate = $this->request->getGet('start_date');
$endDate = $this->request->getGet('end_date');
$status = $this->request->getGet('status');
if ($startDate) $builder->where('bo_order_date >=', $startDate);
if ($endDate) $builder->where('bo_order_date <=', $endDate);
if ($status) $builder->where('bo_status', $status);
$list = $builder->orderBy('bo_order_date', 'DESC')->orderBy('bo_idx', 'DESC')->findAll();
$rows = [];
$statusMap = ['normal' => '정상', 'cancelled' => '취소', 'deleted' => '삭제'];
foreach ($list as $row) {
$items = $this->itemModel->where('boi_bo_idx', $row->bo_idx)->findAll();
$totalQty = 0;
$totalAmt = 0;
foreach ($items as $it) {
$totalQty += (int) $it->boi_qty_sheet;
$totalAmt += (float) $it->boi_amount;
}
$rows[] = [
$row->bo_idx,
$row->bo_lot_no,
$row->bo_order_date,
count($items),
$totalQty,
$totalAmt,
$statusMap[$row->bo_status] ?? $row->bo_status,
];
}
export_csv(
'발주현황_' . date('Ymd') . '.csv',
['번호', 'LOT번호', '발주일', '품목수', '총수량', '총금액', '상태'],
$rows
);
}
public function create()
{
helper('admin');
$lgIdx = admin_effective_lg_idx();
if (!$lgIdx) return redirect()->to(site_url('admin/bag-orders'))->with('error', '지자체를 선택해 주세요.');
// 봉투 종류 + 단가 + 포장단위
$kind = model(CodeKindModel::class)->where('ck_code', 'O')->first();
$bagCodes = $kind ? model(CodeDetailModel::class)->getByKind((int) $kind->ck_idx, true) : [];
$prices = model(BagPriceModel::class)->where('bp_lg_idx', $lgIdx)->where('bp_state', 1)->findAll();
$units = model(PackagingUnitModel::class)->where('pu_lg_idx', $lgIdx)->where('pu_state', 1)->findAll();
$companies = model(CompanyModel::class)->where('cp_lg_idx', $lgIdx)->where('cp_type', '제작업체')->where('cp_state', 1)->findAll();
$agencies = model(SalesAgencyModel::class)->where('sa_lg_idx', $lgIdx)->where('sa_state', 1)->findAll();
return view('admin/layout', [
'title' => '발주 등록',
'content' => view('admin/bag_order/create', compact('bagCodes', 'prices', 'units', 'companies', 'agencies')),
]);
}
public function store()
{
helper('admin');
$lgIdx = admin_effective_lg_idx();
$rules = [
'bo_order_date' => 'required|valid_date[Y-m-d]',
'bo_company_idx' => 'permit_empty|is_natural_no_zero',
'bo_agency_idx' => 'permit_empty|is_natural_no_zero',
];
if (! $this->validate($rules)) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
$db = \Config\Database::connect();
$db->transStart();
// UUID 생성
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
// LOT 번호 생성
$lotNo = 'LOT-' . date('Ymd') . '-' . strtoupper(substr(md5($uuid), 0, 6));
$orderData = [
'bo_uuid' => $uuid,
'bo_version' => 1,
'bo_lg_idx' => $lgIdx,
'bo_gugun_code' => $this->request->getPost('bo_gugun_code') ?? '',
'bo_dong_code' => $this->request->getPost('bo_dong_code') ?? '',
'bo_company_idx' => $this->request->getPost('bo_company_idx') ?: null,
'bo_agency_idx' => $this->request->getPost('bo_agency_idx') ?: null,
'bo_fee_rate' => (float) ($this->request->getPost('bo_fee_rate') ?: 0),
'bo_order_date' => $this->request->getPost('bo_order_date'),
'bo_lot_no' => $lotNo,
'bo_status' => 'normal',
'bo_orderer_idx' => session()->get('mb_idx'),
'bo_regdate' => date('Y-m-d H:i:s'),
];
// SHA-256 해시
$orderData['bo_hash'] = hash('sha256', json_encode($orderData));
$this->orderModel->insert($orderData);
$boIdx = (int) $this->orderModel->getInsertID();
// CT-05: 감사 로그
helper('audit');
audit_log('create', 'bag_order', $boIdx, null, array_merge($orderData, ['bo_idx' => $boIdx]));
// 품목 저장
$bagCodes = $this->request->getPost('item_bag_code') ?? [];
$qtyBoxes = $this->request->getPost('item_qty_box') ?? [];
foreach ($bagCodes as $i => $code) {
if (empty($code) || empty($qtyBoxes[$i])) continue;
$qtyBox = (int) $qtyBoxes[$i];
// 포장단위에서 낱장 환산
$unit = model(PackagingUnitModel::class)->where('pu_lg_idx', $lgIdx)->where('pu_bag_code', $code)->where('pu_state', 1)->first();
$totalPerBox = $unit ? (int) $unit->pu_total_per_box : 1;
$qtySheet = $qtyBox * $totalPerBox;
// 단가
$price = model(BagPriceModel::class)->where('bp_lg_idx', $lgIdx)->where('bp_bag_code', $code)->where('bp_state', 1)->first();
$unitPrice = $price ? (float) $price->bp_order_price : 0;
// 봉투명
$kindO = model(CodeKindModel::class)->where('ck_code', 'O')->first();
$detail = $kindO ? model(CodeDetailModel::class)->where('cd_ck_idx', $kindO->ck_idx)->where('cd_code', $code)->first() : null;
$this->itemModel->insert([
'boi_bo_idx' => $boIdx,
'boi_bag_code' => $code,
'boi_bag_name' => $detail ? $detail->cd_name : '',
'boi_unit_price' => $unitPrice,
'boi_qty_box' => $qtyBox,
'boi_qty_sheet' => $qtySheet,
'boi_amount' => $unitPrice * $qtySheet,
]);
}
$db->transComplete();
return redirect()->to(site_url('admin/bag-orders'))->with('success', '발주가 등록되었습니다. LOT: ' . $lotNo);
}
public function detail(int $id)
{
helper('admin');
$order = $this->orderModel->find($id);
if (!$order || (int) $order->bo_lg_idx !== admin_effective_lg_idx()) {
return redirect()->to(site_url('admin/bag-orders'))->with('error', '발주를 찾을 수 없습니다.');
}
$items = $this->itemModel->where('boi_bo_idx', $id)->findAll();
$companyName = '';
if ($order->bo_company_idx) {
$c = model(CompanyModel::class)->find($order->bo_company_idx);
$companyName = $c ? $c->cp_name : '';
}
$agencyName = '';
if ($order->bo_agency_idx) {
$a = model(SalesAgencyModel::class)->find($order->bo_agency_idx);
$agencyName = $a ? $a->sa_name : '';
}
return view('admin/layout', [
'title' => '발주 상세 — ' . $order->bo_lot_no,
'content' => view('admin/bag_order/detail', compact('order', 'items', 'companyName', 'agencyName')),
]);
}
public function cancel(int $id)
{
helper('admin');
$order = $this->orderModel->find($id);
if (!$order || (int) $order->bo_lg_idx !== admin_effective_lg_idx()) {
return redirect()->to(site_url('admin/bag-orders'))->with('error', '발주를 찾을 수 없습니다.');
}
$before = (array) $order;
$this->orderModel->update($id, ['bo_status' => 'cancelled', 'bo_moddate' => date('Y-m-d H:i:s')]);
helper('audit');
audit_log('update', 'bag_order', $id, $before, ['bo_status' => 'cancelled']);
return redirect()->to(site_url('admin/bag-orders'))->with('success', '발주가 취소되었습니다.');
}
public function delete(int $id)
{
helper('admin');
$order = $this->orderModel->find($id);
if (!$order || (int) $order->bo_lg_idx !== admin_effective_lg_idx()) {
return redirect()->to(site_url('admin/bag-orders'))->with('error', '발주를 찾을 수 없습니다.');
}
$before = (array) $order;
$this->orderModel->update($id, ['bo_status' => 'deleted', 'bo_moddate' => date('Y-m-d H:i:s')]);
helper('audit');
audit_log('delete', 'bag_order', $id, $before, ['bo_status' => 'deleted']);
return redirect()->to(site_url('admin/bag-orders'))->with('success', '발주가 삭제 처리되었습니다.');
}
}