무통장입금 주문의 현금영수증 발급을 관리자·회원·비회원 세 경로에서 제공하고,
입금이 확인되면 자동 발급하며, 부분환불로 금액이 바뀌면 전액취소 후 재발급한다.
발급 프로바이더에 종속되지 않도록 발급/취소는 필터 훅으로 위임한다.
자동발급 리스너는 결제완료 전이(after_payment_complete)와 입금만 기록
(after_deposit_recorded) 두 경로를 모두 구독한다 — 후자가 없으면 관리자가
"입금만 기록"했을 때 자동발급이 통째로 누락된다.
금액 동기화(syncFromOrder)는 트랜잭션이 닫힌 뒤에 부른다. 재발급 실패 이력은
국세청 신고 누락을 막는 원장이라 롤백에 휩쓸리면 안 되고, 프로바이더 왕복 2회
동안 DB 잠금을 붙들 수 없기 때문이다. 환불은 이미 확정됐으므로 어떤 실패도
호출부로 전파하지 않고 FAILED 이력 + 로그로 남겨 관리자 수동 복구에 맡긴다.
식별번호는 재발급용으로만 암호화 보관하고 구매확정 시점에 폐기한다.
그 시점을 잡기 위해 order.after_purchase_confirmed 훅을 신설했다.
함께 고친 사전 결함:
- 취소 시 total_cash_equivalent_amount 가 재계산되지 않아 syncFromOrder 가
"금액 변동 없음"으로 판정, 부분환불 후 재발급이 아예 동작하지 않았다.
산정 규칙을 PaymentMethodEnum::resolveCashEquivalentAmount 로 SSoT 화해
주문 생성 시점과 취소 재계산 시점이 같은 규칙을 쓰게 했다.
- 현금영수증 발급이 payment.receipt_url 을 덮어써 카드 매출전표 URL 이
유실됐다. 한 컬럼이 두 의미를 갖던 문제로, 현금영수증 URL 은 이력 테이블이
보관하도록 분리했다.
- OrderService::confirmOption 이 confirmed_at 을 무조건 now 로 덮어썼다
(v0.16.1 부터 존재). 재확정 시 최초 확정 시점이 소실되고 구매확정 훅이
중복 발화한다. OrderOptionService 와 대칭으로 멱등 가드를 넣었다.
- 코어 api:docgen 이 사람이 작성한 API 문서를 재생성 때마다 지웠다.
@generated 블록 안의 표 셀·응답 본문이 대상이었고, extractGeneratedBlock
이 앞의 `## ` 헤딩까지 거슬러 올라가 여러 엔드포인트를 한 덩어리로 반환하던
문제도 함께 고쳤다. 실측 산출 응답 예시에 @probed 출처 마커를 붙여, 마커가
없는 본문은 사람 작성분으로 보고 보존한다 — 실측 1회의 표본은 사람이 코드에서
읽어낸 사실보다 좁으므로 실측은 기본값이지 덮어쓰기 권한이 아니다.
ParameterDescriber 가 {order} 같은 path 파라미터를 "정렬 방향 asc/desc" 로
설명하던 오염도 정정했다.
231 lines
9.2 KiB
PHP
231 lines
9.2 KiB
PHP
<?php
|
|
|
|
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Resources;
|
|
|
|
use App\Extension\HookManager;
|
|
use Illuminate\Http\Request;
|
|
use Modules\Sirsoft\Ecommerce\Enums\CashReceiptIdentifierType;
|
|
use Modules\Sirsoft\Ecommerce\Enums\CashReceiptIssueStatus;
|
|
use Modules\Sirsoft\Ecommerce\Enums\CashReceiptType;
|
|
use Modules\Sirsoft\Ecommerce\Enums\PaymentMethodEnum;
|
|
use Modules\Sirsoft\Ecommerce\Enums\PaymentStatusEnum;
|
|
use Modules\Sirsoft\Ecommerce\Http\Resources\OrderPaymentResource;
|
|
use Modules\Sirsoft\Ecommerce\Http\Resources\OrderResource;
|
|
use Modules\Sirsoft\Ecommerce\Models\Order;
|
|
use Modules\Sirsoft\Ecommerce\Models\OrderPayment;
|
|
use Modules\Sirsoft\Ecommerce\Services\CashReceiptService;
|
|
use Modules\Sirsoft\Ecommerce\Services\EcommerceSettingsService;
|
|
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
|
use PHPUnit\Framework\Attributes\Test;
|
|
|
|
/**
|
|
* 현금영수증 리소스 노출 테스트 (A-5)
|
|
*
|
|
* OrderResource 는 활성 영수증 1건(cash_receipt)과 전체 이력(cash_receipts)을 노출한다.
|
|
* 전체 이력은 관리자 화면의 "취소 성공 + 재발급 실패" 경고 배지 판정 근거다.
|
|
* 어느 쪽도 식별번호 원본이나 프로바이더 원응답을 노출하지 않는다.
|
|
*/
|
|
class CashReceiptResourceTest extends ModuleTestCase
|
|
{
|
|
private const PROVIDER = 'tosspayments';
|
|
|
|
private const IDENTIFIER = '01012345678';
|
|
|
|
private bool $issueShouldFail = false;
|
|
|
|
private int $receiptSequence = 0;
|
|
|
|
protected function setUp(): void
|
|
{
|
|
parent::setUp();
|
|
|
|
$this->issueShouldFail = false;
|
|
$this->receiptSequence = 0;
|
|
|
|
app(EcommerceSettingsService::class)->setSetting('order_settings.cash_receipt_provider', self::PROVIDER);
|
|
}
|
|
|
|
private function registerProvider(): void
|
|
{
|
|
HookManager::addFilter(
|
|
'sirsoft-ecommerce.cash_receipt.issue',
|
|
function (array $result, Order $order, string $provider, array $payload) {
|
|
if ($provider !== self::PROVIDER) {
|
|
return $result;
|
|
}
|
|
|
|
if ($this->issueShouldFail) {
|
|
return [
|
|
'success' => false,
|
|
'error_code' => 'PROVIDER_ERROR',
|
|
'error_message' => '발급 실패',
|
|
'receipt_key' => null,
|
|
'receipt_url' => null,
|
|
'issue_number' => null,
|
|
'raw_response' => null,
|
|
];
|
|
}
|
|
|
|
$key = 'receipt-'.(++$this->receiptSequence);
|
|
|
|
return [
|
|
'success' => true,
|
|
'error_code' => null,
|
|
'error_message' => null,
|
|
'receipt_key' => $key,
|
|
'receipt_url' => "https://example.test/receipt/{$key}",
|
|
'issue_number' => '12345678',
|
|
// 원응답에 민감 정보가 섞여 와도 리소스는 노출하지 않아야 한다.
|
|
'raw_response' => ['customerIdentityNumber' => self::IDENTIFIER],
|
|
];
|
|
},
|
|
);
|
|
}
|
|
|
|
private function makeOrder(): Order
|
|
{
|
|
$order = Order::factory()->create([
|
|
'total_amount' => 11000,
|
|
'total_cash_equivalent_amount' => 11000,
|
|
'total_tax_amount' => 11000,
|
|
'total_tax_free_amount' => 0,
|
|
]);
|
|
|
|
OrderPayment::factory()->forOrder($order)->create([
|
|
'payment_method' => PaymentMethodEnum::DBANK,
|
|
'payment_status' => PaymentStatusEnum::PAID,
|
|
'receipt_url' => 'https://pg.example.test/slip/1',
|
|
]);
|
|
|
|
return $order->fresh();
|
|
}
|
|
|
|
/**
|
|
* 관계를 로드한 뒤 OrderResource 의 현금영수증 관련 필드만 직렬화합니다.
|
|
*
|
|
* 주문 리소스 전체를 json_encode 하면 미로드 관계(shippingAddress 등)의 리소스가
|
|
* null 을 만나 터진다 — 본 테스트의 관심사가 아니므로 해당 필드만 뽑아 직렬화한다.
|
|
*
|
|
* @return array{payment: array, cash_receipt: array|null, cash_receipts: array}
|
|
*/
|
|
private function resourceArray(Order $order): array
|
|
{
|
|
$order = $order->fresh();
|
|
$order->load(['payment', 'cashReceipts']);
|
|
|
|
$request = Request::create('/');
|
|
$array = (new OrderResource($order))->toArray($request);
|
|
|
|
return [
|
|
'payment' => json_decode(json_encode($array['payment']), true),
|
|
'cash_receipt' => json_decode(json_encode($array['cash_receipt']), true),
|
|
'cash_receipts' => json_decode(json_encode($array['cash_receipts']), true),
|
|
];
|
|
}
|
|
|
|
#[Test]
|
|
public function 현금영수증_발급이_결제영수증_주소를_덮어쓰지_않는다(): void
|
|
{
|
|
// payment.receipt_url = PG 매출전표, cash_receipts.receipt_url = 현금영수증.
|
|
// 한 컬럼이 두 의미를 갖지 않도록 서로 침범하지 않아야 한다.
|
|
$this->registerProvider();
|
|
$order = $this->makeOrder();
|
|
app(CashReceiptService::class)->issue(
|
|
$order, CashReceiptType::INCOME, self::IDENTIFIER, CashReceiptIdentifierType::PHONE,
|
|
);
|
|
|
|
$payment = $order->fresh()->payment;
|
|
$array = json_decode(json_encode(
|
|
(new OrderPaymentResource($payment))->toArray(Request::create('/'))
|
|
), true);
|
|
|
|
$this->assertSame('https://pg.example.test/slip/1', $array['receipt_url'], 'PG 매출전표가 보존되어야 한다');
|
|
$this->assertSame('https://pg.example.test/slip/1', $array['pg_receipt_url']);
|
|
$this->assertTrue($array['is_cash_receipt_issued']);
|
|
$this->assertSame('*******5678', $array['cash_receipt_identifier']);
|
|
$this->assertNotNull($array['cash_receipt_issued_at']);
|
|
|
|
// 평문·암호문은 어디에도 없어야 한다
|
|
$this->assertStringNotContainsString(self::IDENTIFIER, json_encode($array));
|
|
$this->assertArrayNotHasKey('cash_receipt_identifier_encrypted', $array);
|
|
}
|
|
|
|
#[Test]
|
|
public function 주문_리소스가_결제영수증과_현금영수증을_따로_노출한다(): void
|
|
{
|
|
$this->registerProvider();
|
|
$order = $this->makeOrder();
|
|
app(CashReceiptService::class)->issue(
|
|
$order, CashReceiptType::INCOME, self::IDENTIFIER, CashReceiptIdentifierType::PHONE,
|
|
);
|
|
|
|
$array = $this->resourceArray($order);
|
|
|
|
// 두 영수증이 각각 다른 경로로 조회된다 (복합결제 도입 시 두 버튼을 동시 노출 가능)
|
|
$this->assertSame('https://pg.example.test/slip/1', $array['payment']['pg_receipt_url']);
|
|
|
|
$this->assertNotNull($array['cash_receipt']);
|
|
$this->assertSame('https://example.test/receipt/receipt-1', $array['cash_receipt']['receipt_url']);
|
|
$this->assertSame('*******5678', $array['cash_receipt']['identifier_masked']);
|
|
$this->assertSame(CashReceiptType::INCOME->value, $array['cash_receipt']['receipt_type']);
|
|
}
|
|
|
|
#[Test]
|
|
public function 발급_이력이_없으면_활성_영수증은_null_이다(): void
|
|
{
|
|
$order = $this->makeOrder();
|
|
|
|
$array = $this->resourceArray($order);
|
|
|
|
$this->assertNull($array['cash_receipt']);
|
|
$this->assertCount(0, $array['cash_receipts']);
|
|
}
|
|
|
|
#[Test]
|
|
public function 재발급_실패_상태는_활성없음_과_실패이력으로_드러난다(): void
|
|
{
|
|
// 관리자 화면의 "경고 배지 + 수동 재발급" 판정 근거.
|
|
$this->registerProvider();
|
|
$order = $this->makeOrder();
|
|
$service = app(CashReceiptService::class);
|
|
$service->issue($order, CashReceiptType::INCOME, self::IDENTIFIER, CashReceiptIdentifierType::PHONE);
|
|
|
|
HookManager::addFilter(
|
|
'sirsoft-ecommerce.cash_receipt.cancel',
|
|
fn (array $result, Order $order, string $provider, string $receiptKey) => [
|
|
'success' => true, 'error_code' => null, 'error_message' => null,
|
|
'receipt_key' => $receiptKey, 'raw_response' => null,
|
|
],
|
|
);
|
|
|
|
$this->issueShouldFail = true;
|
|
$order->fresh()->update(['total_cash_equivalent_amount' => 5500, 'total_tax_amount' => 5500]);
|
|
$service->syncFromOrder($order->fresh(), '부분환불');
|
|
|
|
$array = $this->resourceArray($order);
|
|
|
|
$this->assertNull($array['cash_receipt'], '활성 영수증이 없어야 한다');
|
|
|
|
// 최신순: 실패한 발급 → 취소 → 최초 발급
|
|
$ledger = $array['cash_receipts'];
|
|
$this->assertCount(3, $ledger);
|
|
$this->assertSame(CashReceiptIssueStatus::FAILED->value, $ledger[0]['issue_status']);
|
|
$this->assertSame('PROVIDER_ERROR', $ledger[0]['error_code']);
|
|
}
|
|
|
|
#[Test]
|
|
public function 리소스는_프로바이더_원응답을_노출하지_않는다(): void
|
|
{
|
|
$this->registerProvider();
|
|
$order = $this->makeOrder();
|
|
app(CashReceiptService::class)->issue(
|
|
$order, CashReceiptType::INCOME, self::IDENTIFIER, CashReceiptIdentifierType::PHONE,
|
|
);
|
|
|
|
$array = $this->resourceArray($order);
|
|
|
|
$this->assertArrayNotHasKey('raw_response', $array['cash_receipt']);
|
|
$this->assertStringNotContainsString(self::IDENTIFIER, json_encode($array['cash_receipt']));
|
|
}
|
|
}
|