giftcon_dev/app/Services/Mypage/UsageService.php
2026-02-24 13:07:23 +09:00

237 lines
8.7 KiB
PHP

<?php
namespace App\Services\Mypage;
use App\Repositories\Mypage\UsageRepository;
final class UsageService
{
public function __construct(
private readonly UsageRepository $repo,
) {}
public function buildPageData(?int $attemptId, int $sessionMemNo): array
{
// attempt_id 없으면 "구매내역(리스트) 준비중" 모드로 렌더
if (!$attemptId || $attemptId <= 0) {
return [
'mode' => 'empty',
'pageTitle' => '구매내역',
'pageDesc' => '결제 완료 후 핀 확인/발급/매입을 진행할 수 있습니다.',
'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);
$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),
'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 ?? ''),
'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 ?? ''),
'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;
}
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']);
}
// 다 null이면 빈 배열로 처리
$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;
// JSON이 아니라면 원문 그대로(운영 디버그용)
return $s;
}
}