repo->paginateAttemptsWithOrder($sessionMemNo, $filters, 5); return [ 'pageTitle' => '구매내역', 'pageDesc' => '구매내역을 확인하고 상세에서 핀 확인/취소를 진행할 수 있습니다.', 'mypageActive' => 'usage', 'filters' => $filters, 'rows' => $rows, ]; } /** * 상세 */ public function buildDetailPageData(int $attemptId, int $sessionMemNo): array { // 기존 detail 빌더 재사용 (호환/안정) $data = $this->buildPageData($attemptId, $sessionMemNo); if (($data['mode'] ?? '') !== 'detail') abort(404); $order = (array)($data['order'] ?? []); $orderId = (int)($order['id'] ?? 0); $pins = $this->repo->getPinsForOrder($orderId); $cancelLogs = $this->repo->getCancelLogsForAttempt($attemptId, 20); $retData = $order['ret_data'] ?? null; $retArr = is_array($retData) ? $retData : []; $pinsOpened = !empty($retArr['pin_opened_at']); // 결제완료 조건 $attempt = (array)($data['attempt'] ?? []); $isPaid = (($order['stat_pay'] ?? '') === 'p') || (($attempt['status'] ?? '') === 'paid'); // cancel_status 기반 버튼 제어 $aCancel = (string)($attempt['cancel_status'] ?? 'none'); $canCancel = $isPaid && !$pinsOpened && in_array($aCancel, ['none','failed'], true); $data['pins'] = $pins; $data['pinsOpened'] = $pinsOpened; $data['canCancel'] = $canCancel; $data['cancelLogs'] = $cancelLogs; return $data; } /** * 핀 오픈(확인): ret_data에 pin_opened_at 기록 */ public function openPins(int $attemptId, int $sessionMemNo): array { $row = $this->repo->findAttemptWithOrder($attemptId); if (!$row) return ['ok'=>false, 'message'=>'결제내역을 찾을 수 없습니다.']; $attemptMem = (int)($row->attempt_mem_no ?? 0); $orderMem = (int)($row->order_mem_no ?? 0); if ($attemptMem !== $sessionMemNo || ($orderMem > 0 && $orderMem !== $sessionMemNo)) { return ['ok'=>false, 'message'=>'권한이 없습니다.']; } $attemptStatus = (string)($row->attempt_status ?? ''); $orderStatPay = (string)($row->order_stat_pay ?? ''); if (!(($orderStatPay === 'p') || ($attemptStatus === 'paid'))) { return ['ok'=>false, 'message'=>'결제완료 상태에서만 핀 확인이 가능합니다.']; } $oid = (string)($row->order_oid ?? ''); if ($oid === '') return ['ok'=>false, 'message'=>'주문정보가 올바르지 않습니다.']; $order = $this->orders->findByOidForUpdate($oid); if (!$order) return ['ok'=>false, 'message'=>'주문을 찾을 수 없습니다.']; $ret = (array)($order->ret_data ?? []); if (!empty($ret['pin_opened_at'])) { return ['ok'=>true]; } $ret['pin_opened_at'] = now()->toDateTimeString(); $order->ret_data = $ret; $order->save(); return ['ok'=>true]; } /** * 결제완료 후 취소(핀 오픈 전만) */ public function cancelPaidAttempt(int $attemptId, int $sessionMemNo, string $reason): array { $data = $this->buildDetailPageData($attemptId, $sessionMemNo); $pinsOpened = (bool)($data['pinsOpened'] ?? false); return $this->cancelSvc->cancelByAttempt( $attemptId, ['type' => 'user', 'mem_no' => $sessionMemNo, 'id' => $sessionMemNo], $reason, $pinsOpened ); } /** * 기존 상세 빌더(첨부 파일 그대로 유지) */ public function buildPageData(?int $attemptId, int $sessionMemNo): array { if (!$attemptId || $attemptId <= 0) { return [ 'mode' => 'empty', 'mypageActive' => 'usage', ]; } $row = $this->repo->findAttemptWithOrder($attemptId); if (!$row) abort(404); $attemptMem = (int)($row->attempt_mem_no ?? 0); $orderMem = (int)($row->order_mem_no ?? 0); if ($attemptMem !== $sessionMemNo || ($orderMem > 0 && $orderMem !== $sessionMemNo)) { abort(404); } $orderId = (int)($row->order_id ?? 0); if ($orderId <= 0) abort(404); $items = $this->repo->getOrderItems($orderId); // ✅ 핀 발행 선택(핀확인방법): 상품 설정(gc_products.pin_check_methods) 기반 // - 주문에 여러 상품이 섞였을 수 있으므로 "공통으로 가능한 방식"(교집합)만 허용 $orderProductId = (int)($row->order_product_id ?? 0); $issue = $this->resolveIssueOptions($orderProductId, $items); $requiredQty = 0; foreach ($items as $it) $requiredQty += (int)($it->qty ?? 0); $assignedPinsCount = $this->repo->countAssignedPins($orderId); $pinsSummary = $this->repo->getAssignedPinsStatusSummary($orderId); $attemptStatus = (string)($row->attempt_status ?? ''); $orderStatPay = (string)($row->order_stat_pay ?? ''); $stepKey = $this->resolveStepKey($attemptStatus, $orderStatPay, $requiredQty, $assignedPinsCount); return [ 'mode' => 'detail', 'pageTitle' => '구매내역', 'pageDesc' => '결제 상태 및 핀 확인/발급/매입 진행을 확인합니다.', 'mypageActive' => 'usage', 'attempt' => $this->attemptViewModel($row), 'order' => $this->orderViewModel($row), 'items' => $this->itemsViewModel($items), 'productname' => $row->order_product_name, // 핀 발행 선택 UI 제어용 'issueMethods' => $issue['methods'], 'issueMissing' => $issue['missing'], 'requiredQty' => $requiredQty, 'assignedPinsCount' => $assignedPinsCount, 'pinsSummary' => $pinsSummary, 'stepKey' => $stepKey, 'steps' => $this->steps(), 'vactInfo' => $this->extractVactInfo($row), ]; } private function resolveStepKey(string $attemptStatus, string $orderStatPay, int $requiredQty, int $assignedPinsCount): string { if (in_array($orderStatPay, ['c','f'], true) || in_array($attemptStatus, ['cancelled','failed'], true)) return 'failed'; if ($orderStatPay === 'w' || $attemptStatus === 'issued') return 'deposit_wait'; if ($orderStatPay === 'p' || $attemptStatus === 'paid') { if ($requiredQty > 0 && $assignedPinsCount >= $requiredQty) return 'pin_done'; return 'pin_check'; } if (in_array($attemptStatus, ['ready','redirected','auth_ok'], true) || $orderStatPay === 'ready') return 'pay_processing'; return 'pay_processing'; } private function steps(): array { return [ ['key' => 'deposit_wait', 'label' => '입금대기'], ['key' => 'pin_check', 'label' => '결제완료'], ['key' => 'pin_verify', 'label' => '핀발급 확인'], ['key' => 'pin_done', 'label' => '핀발급완료'], ['key' => 'buyback', 'label' => '매입진행'], ['key' => 'settlement', 'label' => '정산완료'], ]; } private function attemptViewModel(object $row): array { return [ 'id' => (int)$row->attempt_id, 'provider' => (string)$row->attempt_provider, 'oid' => (string)$row->attempt_oid, 'pay_method' => (string)$row->attempt_pay_method, 'status' => (string)$row->attempt_status, 'pg_tid' => (string)($row->attempt_pg_tid ?? ''), 'return_code' => (string)($row->attempt_return_code ?? ''), 'return_msg' => (string)($row->attempt_return_msg ?? ''), // 추가: cancel 상태 요약 'cancel_status' => (string)($row->attempt_cancel_status ?? 'none'), 'cancel_last_code' => (string)($row->attempt_cancel_last_code ?? ''), 'cancel_last_msg' => (string)($row->attempt_cancel_last_msg ?? ''), 'cancel_requested_at' => (string)($row->attempt_cancel_requested_at ?? ''), 'cancel_done_at' => (string)($row->attempt_cancel_done_at ?? ''), 'payloads' => [ 'request' => $this->jsonDecodeOrRaw($row->attempt_request_payload ?? null), 'response' => $this->jsonDecodeOrRaw($row->attempt_response_payload ?? null), 'return' => $this->jsonDecodeOrRaw($row->attempt_return_payload ?? null), 'noti' => $this->jsonDecodeOrRaw($row->attempt_noti_payload ?? null), ], 'created_at' => (string)($row->attempt_created_at ?? ''), ]; } private function orderViewModel(object $row): array { return [ 'id' => (int)$row->order_id, 'oid' => (string)$row->order_oid, 'mem_no' => (int)$row->order_mem_no, 'stat_pay' => (string)$row->order_stat_pay, 'provider' => (string)($row->order_provider ?? ''), 'pay_method' => (string)($row->order_pay_method ?? ''), 'pg_tid' => (string)($row->order_pg_tid ?? ''), 'ret_code' => (string)($row->order_ret_code ?? ''), 'ret_msg' => (string)($row->order_ret_msg ?? ''), 'products_name' => (string)($row->products_name ?? ''), 'cancel_status' => (string)($row->order_cancel_status ?? 'none'), 'cancel_last_code' => (string)($row->order_cancel_last_code ?? ''), 'cancel_last_msg' => (string)($row->order_cancel_last_msg ?? ''), 'cancel_reason' => (string)($row->order_cancel_reason ?? ''), 'cancel_requested_at' => (string)($row->order_cancel_requested_at ?? ''), 'cancel_done_at' => (string)($row->order_cancel_done_at ?? ''), 'amounts' => [ 'subtotal' => (int)($row->order_subtotal_amount ?? 0), 'fee' => (int)($row->order_fee_amount ?? 0), 'pg_fee' => (int)($row->order_pg_fee_amount ?? 0), 'pay_money' => (int)($row->order_pay_money ?? 0), ], 'pay_data' => $this->jsonDecodeOrRaw($row->order_pay_data ?? null), 'ret_data' => $this->jsonDecodeOrRaw($row->order_ret_data ?? null), 'created_at' => (string)($row->order_created_at ?? ''), ]; } private function itemsViewModel($items): array { $out = []; foreach ($items as $it) { $out[] = [ 'name' => (string)($it->item_name ?? ''), 'code' => (string)($it->item_code ?? ''), 'qty' => (int)($it->qty ?? 0), 'unit' => (int)($it->unit_pay_price ?? 0), 'total'=> (int)($it->line_total ?? 0), 'meta' => $this->jsonDecodeOrRaw($it->meta ?? null), ]; } return $out; } /** * 주문 아이템에서 상품ID 후보를 추출하고, 상품 설정(pin_check_methods)에 따라 * 사용자 페이지의 "핀 발행 선택" 옵션을 계산한다. * * - 여러 상품이 한 주문에 섞일 수 있으므로 교집합만 허용 * - 설정이 비어있거나 조회 실패 시: 기존 UI 깨짐 방지를 위해 3개 모두 허용 */ private function resolveIssueOptions(int $orderProductId, $items): array { $all = ['PIN_INSTANT', 'SMS', 'BUYBACK']; // ✅ 주문이 단일 상품 구조면 order.product_id를 우선 사용 $productIds = []; if ($orderProductId > 0) { $productIds = [$orderProductId]; } else { // (구조가 바뀌거나 다상품 주문일 수 있는 경우) 아이템에서 추출 $productIds = $this->extractProductIdsFromOrderItems($items); } $opts = $this->repo->getProductsIssueOptions($productIds); if (empty($opts)) { // 조회 실패/미설정 시 UI 깨짐 방지: 3개 모두 허용 return ['methods' => $all, 'missing' => [], 'product_ids' => $productIds]; } $intersection = null; foreach ($opts as $pid => $opt) { $m = $this->normalizeIssueMethods($opt); $intersection = ($intersection === null) ? $m : array_values(array_intersect($intersection, $m)); } if (empty($intersection)) $intersection = ['PIN_INSTANT']; // 표시 순서 고정 $ordered = array_values(array_filter($all, fn($k) => in_array($k, $intersection, true))); $missing = array_values(array_diff($all, $ordered)); return ['methods' => $ordered, 'missing' => $missing, 'product_ids' => array_map('intval', array_keys($opts))]; } /** * 상품 1개의 옵션을 "표시용 methods"로 정규화 * * - pin_check_methods가 명시적으로 설정된 경우: 그 값을 그대로 신뢰 (BUYBACK 포함/제외도 여기서 결정) * - pin_check_methods가 아직 비어있는(레거시) 경우: 기본은 PIN_INSTANT+SMS, BUYBACK은 is_buyback_allowed로만 노출 */ private function normalizeIssueMethods(array $opt): array { $explicit = !empty($opt['has_pin_check_methods']); $m = $opt['pin_check_methods'] ?? []; if (!is_array($m)) $m = []; $m = array_values(array_unique(array_filter(array_map('strval', $m)))); if ($explicit) { // 명시 설정인데 비어있으면 안전하게 즉시확인만 if (empty($m)) return ['PIN_INSTANT']; return $m; } // 레거시: 기본 2개 + 매입은 기존 플래그로만 $out = ['PIN_INSTANT', 'SMS']; if (!empty($opt['is_buyback_allowed'])) $out[] = 'BUYBACK'; return $out; } private function extractProductIdsFromOrderItems($items): array { $ids = []; foreach ($items as $it) { $pid = null; // 1) 컬럼이 존재하는 경우 (gc_pin_order_items.product_id 등) if (is_object($it) && property_exists($it, 'product_id') && is_numeric($it->product_id)) { $pid = (int)$it->product_id; } // 2) meta(JSON) 안에 들어있는 경우 if (!$pid) { $meta = $this->jsonDecodeOrArray($it->meta ?? null); foreach (['product_id', 'gc_product_id', 'productId', 'pid', 'product'] as $k) { if (isset($meta[$k]) && is_numeric($meta[$k])) { $pid = (int)$meta[$k]; break; } } } if ($pid && $pid > 0) $ids[] = $pid; } $ids = array_values(array_unique(array_filter($ids, fn($n) => $n > 0))); return $ids; } private function extractVactInfo(object $row): array { $candidates = [ $this->jsonDecodeOrArray($row->order_pay_data ?? null), $this->jsonDecodeOrArray($row->order_ret_data ?? null), $this->jsonDecodeOrArray($row->attempt_return_payload ?? null), $this->jsonDecodeOrArray($row->attempt_noti_payload ?? null), ]; $pick = function(array $a, array $keys) { foreach ($keys as $k) { if (array_key_exists($k, $a) && $a[$k] !== '' && $a[$k] !== null) return $a[$k]; } return null; }; $info = ['bank'=>null,'account'=>null,'holder'=>null,'amount'=>null,'expire_at'=>null]; foreach ($candidates as $a) { if (!$a) continue; $info['bank'] ??= $pick($a, ['bank', 'vbank', 'Vbank', 'BankName']); $info['account'] ??= $pick($a, ['account', 'vaccount', 'Vaccount', 'AccountNo']); $info['holder'] ??= $pick($a, ['holder', 'depositor', 'Depositor', 'AccountHolder']); $info['amount'] ??= $pick($a, ['amount', 'Amt', 'pay_money', 'PayMoney']); $info['expire_at'] ??= $pick($a, ['expire_at', 'Vdate', 'vdate', 'ExpireDate']); } $hasAny = false; foreach ($info as $v) { if ($v !== null) { $hasAny = true; break; } } return $hasAny ? $info : []; } private function jsonDecodeOrArray($v): array { if ($v === null) return []; if (is_array($v)) return $v; $s = trim((string)$v); if ($s === '') return []; $decoded = json_decode($s, true); return is_array($decoded) ? $decoded : []; } private function jsonDecodeOrRaw($v) { if ($v === null) return null; if (is_array($v)) return $v; $s = trim((string)$v); if ($s === '') return null; $decoded = json_decode($s, true); if (json_last_error() === JSON_ERROR_NONE) return $decoded; return $s; } }