340 lines
13 KiB
PHP
340 lines
13 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Mypage;
|
|
|
|
use App\Repositories\Mypage\UsageRepository;
|
|
use App\Repositories\Payments\GcPinOrderRepository;
|
|
use App\Services\Payments\PaymentCancelService;
|
|
|
|
final class UsageService
|
|
{
|
|
public function __construct(
|
|
private readonly UsageRepository $repo,
|
|
private readonly GcPinOrderRepository $orders,
|
|
private readonly PaymentCancelService $cancelSvc,
|
|
) {}
|
|
|
|
/**
|
|
* 리스트(검색/페이징)
|
|
*/
|
|
public function buildListPageData(int $sessionMemNo, array $filters): array
|
|
{
|
|
$rows = $this->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);
|
|
|
|
$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,
|
|
|
|
'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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|