Files
Gnuboard7/plugins/_bundled/sirsoft-message_bizppurio/tests/Unit/Services/AlimtalkChannelDriverTest.php
T
chym1217 11f1d79540 feat(message_bizppurio): 코어 알림 발송 이력 화면에 문자·알림톡 결과 주입
발송 결과(성공/실패·사유·잔액부족·SMS 대체발송)를 코어 "알림 발송 이력" 화면의 각 행에
표시한다. 코어 앱·코어 테이블 무수정 — 연결 표식은 bizppurio_dispatches.notification_log_id
에만 두고, 발송 사이클의 코어 after_log_sent/after_log_failed 훅으로 그 로그 id 를 연결한다.

- 결과 조회는 파라미터 없는 GET /dispatch-results/recent 로 최근 결과 맵을 받아 row.id 매칭
 (목록 로드 순서에 무관 — 빈 배열 전송·타이밍으로 결과가 비던 문제 해소).
- 코어 이력 datagrid 에 결과 컬럼을 layout_extensions 로 주입하고, 행 토글에도 상세 결과를
 얹는다. 메일·사이트내알림 탭에선 컬럼(헤더 포함)을 숨긴다. 다크모드 배지 색 보강.
- 브라우저 검수용 데모 시더(4상태·엣지 케이스 21건) + 전 계층 테스트(백엔드·Vitest 렌더)
 + 시나리오 매니페스트 + API 레퍼런스 동반.
2026-07-28 12:36:26 +09:00

309 lines
12 KiB
PHP

<?php
namespace Plugins\Sirsoft\MessageBizppurio\Tests\Unit\Services;
use App\Models\NotificationTemplate;
use App\Models\User;
use App\Notifications\GenericNotification;
use App\Notifications\GuestNotifiable;
use App\Services\NotificationTemplateService;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Bus;
use Mockery;
use Plugins\Sirsoft\MessageBizppurio\Jobs\SendMessageJob;
use Plugins\Sirsoft\MessageBizppurio\Models\BizppurioDispatch;
use Plugins\Sirsoft\MessageBizppurio\Models\BizppurioNotificationBinding;
use Plugins\Sirsoft\MessageBizppurio\Repositories\BizppurioDispatchRepository;
use Plugins\Sirsoft\MessageBizppurio\Repositories\Contracts\BizppurioNotificationBindingRepositoryInterface;
use Plugins\Sirsoft\MessageBizppurio\Services\AlimtalkChannelDriver;
use Plugins\Sirsoft\MessageBizppurio\Services\DispatchLinkContext;
use Plugins\Sirsoft\MessageBizppurio\Services\MessagePayloadBuilder;
use Plugins\Sirsoft\MessageBizppurio\Tests\PluginTestCase;
/**
* AlimtalkChannelDriver — binding 게이트·변수치환({x}→#{x})·대체발송·Job 위임 검증.
*
* 알림톡은 SMS 와 달리 "관리자가 연결한 승인 템플릿(binding)"이 있을 때만 발송된다.
* 발송 Job dispatch 는 Bus::fake 로 관찰한다(실제 발송은 SendMessageJobTest 가 커버).
*/
class AlimtalkChannelDriverTest extends PluginTestCase
{
/**
* 렌더 결과를 반환하는 NotificationTemplate mock 을 만듭니다.
*
* @param array<string, string> $rendered replaceVariables 반환값
*/
private function fakeTemplate(array $rendered = ['subject' => '', 'body' => '{name} 님 주문이 완료되었습니다.']): NotificationTemplate
{
$template = Mockery::mock(NotificationTemplate::class)->makePartial();
$template->is_active = true;
$template->shouldReceive('replaceVariables')->andReturn($rendered);
return $template;
}
/**
* findActive 반환값을 지정한 binding 리포지토리 mock 을 만듭니다.
*
* @param BizppurioNotificationBinding|null $binding findActive 반환값
*/
private function fakeBindings(?BizppurioNotificationBinding $binding): BizppurioNotificationBindingRepositoryInterface
{
$repo = Mockery::mock(BizppurioNotificationBindingRepositoryInterface::class);
$repo->shouldReceive('findActive')
->with(Mockery::any(), 'alimtalk')
->andReturn($binding);
return $repo;
}
/**
* 연결(binding) 모델을 만듭니다.
*/
private function binding(bool $fallback = false): BizppurioNotificationBinding
{
$binding = new BizppurioNotificationBinding;
$binding->notification_type = 'order_confirmed';
$binding->channel = 'alimtalk';
$binding->template_code = 'TW_1234';
$binding->template_name = '주문완료';
$binding->fallback_sms_enabled = $fallback;
$binding->is_active = true;
return $binding;
}
/**
* 템플릿·binding·빌더를 조합한 driver 를 만듭니다.
*/
private function makeDriver(
?NotificationTemplate $template,
?BizppurioNotificationBinding $binding,
?MessagePayloadBuilder $builder = null,
): AlimtalkChannelDriver {
$templateService = Mockery::mock(NotificationTemplateService::class);
$templateService->shouldReceive('resolve')
->with(Mockery::any(), 'alimtalk')
->andReturn($template);
return new AlimtalkChannelDriver(
$templateService,
$this->fakeBindings($binding),
$builder ?? $this->spyBuilder(),
new BizppurioDispatchRepository,
new DispatchLinkContext,
);
}
/**
* buildAlimtalk 호출 인자를 기록하는 payload 빌더 스파이를 만듭니다.
*/
private function spyBuilder(): MessagePayloadBuilder
{
return new class extends MessagePayloadBuilder
{
/** @var array<int, array<string, mixed>> */
public array $calls = [];
public function __construct() {}
public function buildAlimtalk(
string $to,
string $templateCode,
string $message,
string $refkey,
array $extra = [],
): array {
$this->calls[] = [
'to' => $to,
'templateCode' => $templateCode,
'message' => $message,
'refkey' => $refkey,
];
return ['type' => 'at', 'to' => $to, 'refkey' => $refkey, 'templatecode' => $templateCode];
}
};
}
private function notification(array $data = ['name' => '김철수']): GenericNotification
{
return new GenericNotification('order_confirmed', 'sirsoft-ecommerce', $data, 'module', 'sirsoft-ecommerce');
}
public function test_연결된_템플릿이_없으면_발송하지_않는다(): void
{
Bus::fake();
$member = User::factory()->create(['mobile' => '010-1234-5678']);
// binding = null → 미연결 → skip
$this->makeDriver($this->fakeTemplate(), null)->send($member, $this->notification());
Bus::assertNotDispatched(SendMessageJob::class);
$this->assertDatabaseCount('bizppurio_dispatches', 0);
}
public function test_alimtalk_템플릿이_없으면_발송하지_않는다(): void
{
Bus::fake();
$member = User::factory()->create(['mobile' => '010-1234-5678']);
// binding 은 있으나 코어 alimtalk 본문 템플릿이 없음 → skip
$this->makeDriver(null, $this->binding())->send($member, $this->notification());
Bus::assertNotDispatched(SendMessageJob::class);
}
public function test_회원은_mobile로_연결된_템플릿코드로_발송한다(): void
{
Bus::fake();
$member = User::factory()->create(['mobile' => '010-1234-5678']);
$builder = $this->spyBuilder();
$this->makeDriver($this->fakeTemplate(), $this->binding(), $builder)
->send($member, $this->notification());
Bus::assertDispatched(SendMessageJob::class);
$this->assertCount(1, $builder->calls);
$this->assertSame('01012345678', $builder->calls[0]['to']);
$this->assertSame('TW_1234', $builder->calls[0]['templateCode'], '연결된 카카오 템플릿 코드로 발송해야 한다.');
}
public function test_비회원은_data의_전화번호로_발송한다(): void
{
Bus::fake();
$guest = new GuestNotifiable('guest@example.com', '홍길동', 'ko');
$data = ['name' => '홍길동', AlimtalkChannelDriver::RECIPIENT_PHONE_KEY => '010-9999-0000'];
$builder = $this->spyBuilder();
$this->makeDriver($this->fakeTemplate(), $this->binding(), $builder)
->send($guest, $this->notification($data));
Bus::assertDispatched(SendMessageJob::class);
$this->assertSame('01099990000', $builder->calls[0]['to']);
}
public function test_본문_변수를_알림톡_형식으로_변환한다(): void
{
Bus::fake();
$member = User::factory()->create(['mobile' => '01011112222']);
$builder = $this->spyBuilder();
$this->makeDriver(
$this->fakeTemplate(['subject' => '', 'body' => '{name} 님 {order_number} 주문 완료']),
$this->binding(),
$builder,
)->send($member, $this->notification());
$this->assertSame(
'#{name} 님 #{order_number} 주문 완료',
$builder->calls[0]['message'],
'코어 {var} 형식을 알림톡 #{var} 형식으로 치환해야 한다.',
);
}
public function test_이미_알림톡_형식인_변수는_중복_변환하지_않는다(): void
{
Bus::fake();
$member = User::factory()->create(['mobile' => '01011112222']);
$builder = $this->spyBuilder();
$this->makeDriver(
$this->fakeTemplate(['subject' => '', 'body' => '#{name} 님 {order_number}']),
$this->binding(),
$builder,
)->send($member, $this->notification());
$this->assertSame(
'#{name} 님 #{order_number}',
$builder->calls[0]['message'],
'이미 #{var} 인 변수는 ##{var} 로 이중 변환되면 안 된다.',
);
}
public function test_대체발송_o_n이면_payload에_sms_resend가_병합된다(): void
{
Bus::fake();
$member = User::factory()->create(['mobile' => '01011112222']);
// 실제 payload 병합을 관찰하려면 실 빌더가 필요하므로, buildAlimtalk 만 최소 stub 하고
// withSmsFallback 결과를 dispatch 된 Job payload 로 검증한다.
$builder = new class extends MessagePayloadBuilder
{
public function __construct() {}
public function buildAlimtalk(string $to, string $templateCode, string $message, string $refkey, array $extra = []): array
{
return ['type' => 'at', 'to' => $to, 'refkey' => $refkey, 'content' => ['at' => ['message' => $message]]];
}
};
// replaceVariables 는 치환 완료본을 반환하므로 mock body 도 치환 완료 텍스트로 준다.
// 드라이버는 이 body 를 알림톡 본문(#{var} 변환)과 대체 SMS 본문(원문 그대로) 두 곳에 쓴다.
$this->makeDriver(
$this->fakeTemplate(['subject' => '', 'body' => '김철수 님 주문 완료']),
$this->binding(fallback: true),
$builder,
)->send($member, $this->notification());
Bus::assertDispatched(SendMessageJob::class, function (SendMessageJob $job) {
$this->assertSame(['first' => 'sms'], $job->payload['resend'] ?? null, '대체발송 ON 은 resend:{first:sms} 를 넣어야 한다.');
$this->assertArrayHasKey('recontent', $job->payload);
$this->assertSame('김철수 님 주문 완료', $job->payload['recontent']['sms']['message'] ?? null, '대체 SMS 본문은 치환 완료된 코어 본문(#{var} 미변환)이어야 한다.');
return true;
});
}
public function test_대체발송_of_f이면_resend가_없다(): void
{
Bus::fake();
$member = User::factory()->create(['mobile' => '01011112222']);
$this->makeDriver($this->fakeTemplate(), $this->binding(fallback: false))
->send($member, $this->notification());
Bus::assertDispatched(SendMessageJob::class, function (SendMessageJob $job) {
$this->assertArrayNotHasKey('resend', $job->payload);
return true;
});
}
public function test_회원_발송_시_pending_이력을_alimtalk_채널로_생성한다(): void
{
Bus::fake();
$member = User::factory()->create(['mobile' => '010-1234-5678', 'name' => '김철수']);
$this->makeDriver($this->fakeTemplate(), $this->binding())->send($member, $this->notification());
$this->assertDatabaseCount('bizppurio_dispatches', 1);
$dispatch = BizppurioDispatch::first();
$this->assertSame('pending', $dispatch->status->value);
$this->assertSame('alimtalk', $dispatch->channel->value);
$this->assertSame($member->id, $dispatch->to_user_id);
$this->assertSame('order_confirmed', $dispatch->notification_type);
}
public function test_전화번호가_없으면_발송하지_않는다(): void
{
Bus::fake();
$guest = new GuestNotifiable('guest@example.com', '홍길동', 'ko');
$this->makeDriver($this->fakeTemplate(), $this->binding())
->send($guest, $this->notification(['name' => '홍길동']));
Bus::assertNotDispatched(SendMessageJob::class);
}
public function test_generic_notification이_아니면_무시한다(): void
{
Bus::fake();
$member = User::factory()->create(['mobile' => '01011112222']);
$this->makeDriver($this->fakeTemplate(), $this->binding())->send($member, new Notification);
Bus::assertNotDispatched(SendMessageJob::class);
}
}