This commit is contained in:
baodev0
2026-09-23 15:17:18 +07:00
parent cd38c5d6d0
commit 82a71244ca
107 changed files with 3332 additions and 3306 deletions
@@ -24,6 +24,9 @@ class ResetPasswordTest extends TestCase
{
parent::setUp();
// Email render từ template DB; template password_reset_admin chỉ có trong seeder.
$this->seed(\Database\Seeders\TemplateSeeder::class);
Role::firstOrCreate(['name' => 'Full Administrator', 'guard_name' => 'admin']);
$this->admin = User::factory()->create();
$this->admin->assignRole('Full Administrator');
@@ -59,7 +59,6 @@ class PermissionGatingTest extends TestCase
'banks index' => ['GET', '/api/v1/administrator/banks', 'setting.manager'],
'domain-pricing index' => ['GET', '/api/v1/administrator/domain-pricing', 'setting.manager'],
'email-templates index' => ['GET', '/api/v1/administrator/email-templates', 'email-template.manager'],
'notification-templates' => ['GET', '/api/v1/administrator/notification-templates', 'email-template.manager'],
'tickets index' => ['GET', '/api/v1/administrator/tickets', 'support.view'],
'activity-logs index' => ['GET', '/api/v1/administrator/activity-logs', 'system-log.manager'],
'email-logs index' => ['GET', '/api/v1/administrator/email-logs', 'system-log.manager'],
@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Client;
use App\Mail\Customer\PasswordResetLink;
use App\Models\Customer;
use App\Models\RefreshToken;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class ClientAuthSecurityTest extends TestCase
{
use RefreshDatabase;
private function api(): static
{
return $this->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
}
public function test_access_token_older_than_skew_window_is_rejected(): void
{
$this->withHeaders(['x-access-token' => $this->buildClientAccessToken(time() - 3600)])
->getJson('/v1/banks')
->assertStatus(403);
}
public function test_verify_email_code_is_invalidated_after_too_many_wrong_attempts(): void
{
$customer = Customer::factory()->create([
'status' => 0,
'email_verify_code' => '123456',
'email_verify_code_expired_at' => now()->addMinutes(5),
]);
for ($i = 0; $i < 5; $i++) {
$this->api()->postJson('/v1/client/verify-email', ['email' => $customer->email, 'code' => '000000'])
->assertStatus(422);
}
// Lần sai thứ 5 huỷ mã: mã đúng cũng vô dụng, phải gửi lại.
$this->assertNull($customer->fresh()->email_verify_code);
$this->assertSame(0, (int) $customer->fresh()->status);
// throttle:client-auth khoá theo email: lần thứ 6 trong phút bị chặn, email khác vẫn qua.
$this->api()->postJson('/v1/client/verify-email', ['email' => $customer->email, 'code' => '123456'])
->assertStatus(429);
$this->api()->postJson('/v1/client/verify-email', ['email' => 'other@example.com', 'code' => '123456'])
->assertStatus(422);
}
public function test_forgot_password_sends_link_without_changing_password_and_reset_revokes_sessions(): void
{
Mail::fake();
$customer = Customer::factory()->create(['status' => 1]);
$oldHash = $customer->password;
RefreshToken::create(['customer_id' => $customer->id, 'token' => 'x', 'expires_at' => now()->addDay()]);
$this->api()->postJson('/v1/client/forgot-password', ['email' => strtoupper($customer->email)])->assertOk();
$this->assertSame($oldHash, $customer->fresh()->password);
Mail::assertQueued(PasswordResetLink::class, function (PasswordResetLink $mail) use ($customer) {
// Template seed bằng migration phải render được và chứa link reset, không chứa mật khẩu.
$html = $mail->render();
return $mail->hasTo($customer->email)
&& str_contains($html, '/dat-lai-mat-khau?token=')
&& str_contains($html, '60 phút');
});
$token = Password::broker('users')->createToken($customer);
$this->api()->postJson('/v1/client/reset-password', [
'email' => $customer->email, 'token' => 'wrong', 'password' => 'NewPass123', 'password_confirmation' => 'NewPass123',
])->assertStatus(422);
$this->api()->postJson('/v1/client/reset-password', [
'email' => $customer->email, 'token' => $token, 'password' => 'NewPass123', 'password_confirmation' => 'NewPass123',
])->assertOk();
$this->assertTrue(Hash::check('NewPass123', $customer->fresh()->password));
$this->assertSame(0, RefreshToken::where('customer_id', $customer->id)->count());
}
public function test_cccd_images_are_private_and_served_only_via_signed_url(): void
{
Storage::fake('local');
Storage::disk('local')->put('cccd/front.jpg', 'img');
$customer = Customer::factory()->create([
'status' => 1,
'identity_number' => '079123456789',
'front_identity_number' => 'cccd/front.jpg',
]);
$me = $this->actingAs($customer, 'client')->api()->getJson('/v1/client/me')->assertOk();
$data = $me->json('data.client.customer');
$this->assertSame('********6789', $data['cmnd']);
$this->assertStringStartsWith('/v1/client/cccd/' . $customer->id . '/front?expires=', $data['cmnd_before']);
$this->api()->get('/v1/client/cccd/' . $customer->id . '/front')->assertStatus(403);
$this->api()->get($data['cmnd_before'])->assertOk();
}
public function test_access_token_is_revoked_when_password_changes(): void
{
$customer = Customer::factory()->create(['status' => 1, 'password' => Hash::make('OldPass123')]);
$jwt = \Tymon\JWTAuth\Facades\JWTAuth::fromUser($customer);
$call = fn () => $this->api()->withHeader('Authorization', "Bearer {$jwt}")->getJson('/v1/client/me');
$call()->assertOk();
$this->api()->withHeader('Authorization', "Bearer {$jwt}")->putJson('/v1/client/change-password', [
'current_password' => 'OldPass123', 'password' => 'NewPass123', 'password_confirmation' => 'NewPass123',
])->assertOk();
$this->app['auth']->forgetGuards();
$call()->assertStatus(401);
}
public function test_throttle_uses_client_ip_from_encrypted_payload_not_next_server_ip(): void
{
// Cùng REMOTE_ADDR (Next server) nhưng IP khách khác nhau → không bị đếm chung.
foreach (['203.0.113.1', '203.0.113.2'] as $ip) {
for ($i = 0; $i < 60; $i++) {
$this->withHeaders(['x-access-token' => $this->buildClientAccessToken(null, $ip)])
->getJson('/v1/banks')->assertOk();
}
}
$this->withHeaders(['x-access-token' => $this->buildClientAccessToken(null, '203.0.113.1')])
->getJson('/v1/banks')->assertStatus(429);
}
public function test_legacy_cccd_path_is_not_exposed(): void
{
$customer = Customer::factory()->create(['status' => 1, 'front_identity_number' => '/uploads/2023/11/06/abc.jpg']);
$url = $this->actingAs($customer, 'client')->api()->getJson('/v1/client/me')
->json('data.client.customer.cmnd_before');
$this->assertStringNotContainsString('uploads', $url);
$this->api()->get($url)->assertNotFound();
}
}
@@ -23,7 +23,14 @@ class ClientDomainOrderTest extends TestCase
{
parent::setUp();
$this->customer = Customer::factory()->create(['total' => 1_000_000]);
$this->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
$this->customer = Customer::factory()->create([
'total' => 1_000_000,
// DomainOrderService bắt buộc đã có ảnh CCCD 2 mặt
'front_identity_number' => 'cccd/front.jpg',
'back_identity_number' => 'cccd/back.jpg',
]);
// Minimal domain product — product_type is set automatically from category
// but we force it directly since we have no category seeder in tests
@@ -41,15 +41,6 @@ class RenewServiceTest extends TestCase
}
/** Encrypts the shared secret the same way ClientAccessTokenCheck expects, for test requests. */
private function buildClientAccessToken(): string
{
$key = hex2bin((string) config('services.client_api.key'));
$secret = (string) config('services.client_api.secret');
$iv = random_bytes(16);
$ciphertext = openssl_encrypt($secret, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv . $ciphertext);
}
private function createServiceWithOldPrice(int $oldPrice): Service
{
@@ -13,15 +13,6 @@ class VmOwnershipTest extends TestCase
{
use RefreshDatabase;
private function buildClientAccessToken(): string
{
$key = hex2bin((string) config('services.client_api.key'));
$secret = (string) config('services.client_api.secret');
$iv = random_bytes(16);
$ciphertext = openssl_encrypt($secret, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv . $ciphertext);
}
public function test_customer_cannot_read_power_state_of_another_customers_vm_by_numeric_id(): void
{
@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Console;
use App\Enums\Invoice\InvoiceStatus;
use App\Enums\Order\OrderStatus;
use App\Models\Customer;
use App\Models\Invoice;
use App\Models\Order;
use App\Services\InvoiceReminderService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
class InvoiceReminderTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
// EmailTemplateService::send() đẩy qua SendTemplateEmailJob — fake queue để test
// không phụ thuộc template có trong DB hay không.
Queue::fake();
config(['billing.reminder_offsets' => [-7, -3, 0, 3]]);
}
public function test_no_reminder_is_sent_before_the_first_offset(): void
{
$invoice = $this->makeInvoice(now()->addDays(30));
$this->artisan('invoices:send-reminders')->assertExitCode(0);
$this->assertSame(0, (int) $invoice->fresh()->reminder_step);
}
public function test_reminder_step_advances_once_per_offset_reached(): void
{
// Hạn còn 5 ngày → đã qua mốc -7, chưa tới mốc -3.
$invoice = $this->makeInvoice(now()->addDays(5));
$this->artisan('invoices:send-reminders')->assertExitCode(0);
$this->assertSame(1, (int) $invoice->fresh()->reminder_step);
// Chạy lại trong ngày không được gửi trùng.
$this->artisan('invoices:send-reminders')->assertExitCode(0);
$this->assertSame(1, (int) $invoice->fresh()->reminder_step);
}
public function test_an_overdue_invoice_reaches_the_later_offsets(): void
{
$invoice = $this->makeInvoice(now()->subDays(4), InvoiceStatus::OVERDUE->value);
$this->artisan('invoices:send-reminders')->assertExitCode(0);
// Đã qua cả 4 mốc: -7, -3, 0, +3.
$this->assertSame(4, (int) $invoice->fresh()->reminder_step);
}
public function test_a_paid_invoice_is_never_reminded(): void
{
$invoice = $this->makeInvoice(now()->subDays(10), InvoiceStatus::PAID->value);
$this->artisan('invoices:send-reminders')->assertExitCode(0);
$this->assertSame(0, (int) $invoice->fresh()->reminder_step);
$this->assertFalse(app(InvoiceReminderService::class)->isRemindable($invoice->fresh()));
}
/** Nút nhắc thủ công của kế toán gửi được kể cả khi mốc đó đã gửi rồi. */
public function test_manual_reminder_sends_even_when_the_offset_was_already_used(): void
{
$invoice = $this->makeInvoice(now()->addDays(5));
$reminders = app(InvoiceReminderService::class);
$this->assertTrue($reminders->remind($invoice));
$this->assertFalse($reminders->remind($invoice->fresh()));
$this->assertTrue($reminders->remind($invoice->fresh(), force: true));
}
private function makeInvoice(\Carbon\Carbon $dueDate, int $status = InvoiceStatus::UNPAID->value): Invoice
{
$customer = Customer::factory()->create();
$order = Order::create([
'order_num' => 'ORD-' . uniqid(),
'customer_id' => $customer->id,
'sub_total' => 100_000,
'total' => 100_000,
'status' => OrderStatus::PENDING->value,
]);
return Invoice::create([
'invoice_number' => 'INV-' . uniqid(),
'customer_id' => $customer->id,
'order_id' => $order->id,
'invoice_type' => 1,
'sub_total' => 100_000,
'tax' => 0,
'total' => 100_000,
'status' => $status,
'due_date' => $dueDate->toDateString(),
]);
}
}
@@ -0,0 +1,182 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Console;
use App\Enums\Invoice\InvoiceStatus;
use App\Enums\Order\OrderStatus;
use App\Models\Customer;
use App\Models\Invoice;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\Service;
use App\Repositories\Api\Order\OrderRepository;
use App\Services\InvoiceReminderService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
/**
* Dữ liệu import từ WHMCS mang theo hàng loạt hoá đơn quá hạn nhiều năm, đơn pending cũ và
* dịch vụ đã hết hạn. Các test này chặn những hậu quả dây chuyền ngay sau lần sync đầu tiên.
*/
class PostWhmcsSyncSafetyTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Queue::fake();
config(['billing.reminder_offsets' => [-7, -3, 0, 3, 7]]);
}
/** Hoá đơn quá hạn nhiều năm KHÔNG được mở lại chuỗi nhắc nợ. */
public function test_reminder_chain_does_not_reopen_for_long_overdue_legacy_invoices(): void
{
$invoice = $this->makeInvoice(now()->subYears(2), InvoiceStatus::OVERDUE->value);
$this->artisan('invoices:send-reminders')->assertExitCode(0);
$this->assertSame(0, (int) $invoice->fresh()->reminder_step);
$this->assertSame(0, app(InvoiceReminderService::class)->dueStep($invoice->fresh()));
}
/** Hoá đơn vừa quá hạn trong cửa sổ nhắc thì vẫn phải được nhắc như thường. */
public function test_recently_overdue_invoice_is_still_reminded(): void
{
$invoice = $this->makeInvoice(now()->subDays(3), InvoiceStatus::OVERDUE->value);
$this->artisan('invoices:send-reminders')->assertExitCode(0);
$this->assertGreaterThan(0, (int) $invoice->fresh()->reminder_step);
}
/** Admin vẫn nhắc tay được hoá đơn cũ dù chuỗi tự động đã đóng. */
public function test_manual_reminder_still_works_on_an_old_invoice(): void
{
$invoice = $this->makeInvoice(now()->subYears(2), InvoiceStatus::OVERDUE->value);
$this->assertTrue(
app(InvoiceReminderService::class)->remind($invoice->load('customer'), force: true)
);
}
/** Đơn import từ WHMCS ở trạng thái pending không được khoá khách đặt đơn mới. */
public function test_legacy_pending_order_does_not_block_new_orders(): void
{
$customer = Customer::factory()->create();
Order::create([
'legacy_id' => 90001,
'order_num' => 'WHMCS-' . uniqid(),
'customer_id' => $customer->id,
'sub_total' => 500_000,
'total' => 500_000,
'status' => OrderStatus::PENDING->value,
]);
$this->assertFalse(app(OrderRepository::class)->hasPendingOrder($customer->id));
}
/** Đơn pending tạo trên portal thì vẫn phải chặn như cũ. */
public function test_local_pending_order_still_blocks_new_orders(): void
{
$customer = Customer::factory()->create();
Order::create([
'order_num' => 'ORD-' . uniqid(),
'customer_id' => $customer->id,
'sub_total' => 500_000,
'total' => 500_000,
'status' => OrderStatus::PENDING->value,
]);
$this->assertTrue(app(OrderRepository::class)->hasPendingOrder($customer->id));
}
/**
* Dịch vụ import có invoice_id NULL dù hoá đơn gia hạn của nó đã được đồng bộ —
* không được xuất thêm hoá đơn trùng kỳ.
*/
public function test_expiry_does_not_duplicate_an_invoice_already_synced_on_the_order(): void
{
$customer = Customer::factory()->create();
$product = Product::factory()->create(['product_type' => 'hosting', 'is_active' => true]);
$order = Order::create([
'legacy_id' => 90002,
'order_num' => 'WHMCS-' . uniqid(),
'customer_id' => $customer->id,
'sub_total' => 90_000,
'total' => 90_000,
'status' => OrderStatus::ACTIVE->value,
]);
$orderItem = OrderItem::create([
'order_id' => $order->id,
'product_id' => $product->id,
'billing_cycle' => 'monthly',
'months' => 1,
'quantity' => 1,
'price' => 90_000,
]);
// Hoá đơn gia hạn đã đồng bộ từ WHMCS, còn chưa thanh toán.
Invoice::create([
'legacy_id' => 90003,
'invoice_number' => 'WHMCS-INV-' . uniqid(),
'customer_id' => $customer->id,
'order_id' => $order->id,
'invoice_type' => 2,
'sub_total' => 90_000,
'tax' => 0,
'total' => 90_000,
'status' => InvoiceStatus::UNPAID->value,
'due_date' => now()->addDays(3)->toDateString(),
]);
// Service import: invoice_id để trống đúng như ServiceWriter ghi.
$service = Service::create([
'customer_id' => $customer->id,
'product_id' => $product->id,
'order_item_id' => $orderItem->id,
'status' => 'active',
'server_name' => 'legacy-server',
'expires_at' => now()->addDays(3),
]);
$this->assertNull($service->invoice_id);
$this->artisan('service:expiry')->assertExitCode(0);
// Vẫn đúng 1 hoá đơn — và service đã được trỏ về hoá đơn đang mở.
$this->assertSame(1, Invoice::where('order_id', $order->id)->count());
$this->assertNotNull($service->fresh()->invoice_id);
}
private function makeInvoice(\Carbon\Carbon $dueDate, int $status): Invoice
{
$customer = Customer::factory()->create();
$order = Order::create([
'order_num' => 'ORD-' . uniqid(),
'customer_id' => $customer->id,
'sub_total' => 100_000,
'total' => 100_000,
'status' => OrderStatus::PENDING->value,
]);
return Invoice::create([
'invoice_number' => 'INV-' . uniqid(),
'customer_id' => $customer->id,
'order_id' => $order->id,
'invoice_type' => 1,
'sub_total' => 100_000,
'tax' => 0,
'total' => 100_000,
'status' => $status,
'due_date' => $dueDate->toDateString(),
]);
}
}
@@ -127,4 +127,50 @@ class ServiceExpiryTest extends TestCase
// Vẫn đúng là OVERDUE — service:expiry không được đụng vào status của invoice.
$this->assertSame(InvoiceStatus::OVERDUE->value, (int) $invoice->fresh()->status);
}
/**
* Hoá đơn gia hạn dùng lại order_id gốc. Khi nó quá hạn, cron KHÔNG được kéo đơn đang chạy
* về PENDING — vừa hiển thị sai, vừa làm hasPendingOrder() khoá khách đặt đơn mới.
*/
public function test_overdue_renewal_invoice_does_not_reset_an_active_order(): void
{
$service = $this->createExpiringService(90_000);
$order = $service->orderItem->order;
$this->assertSame(OrderStatus::ACTIVE->value, (int) $order->status);
$this->artisan('service:expiry')->assertExitCode(0);
Invoice::whereKey($service->refresh()->invoice_id)->update(['due_date' => now()->subDay()->toDateString()]);
$this->artisan('invoices:check-overdue')->assertExitCode(0);
$this->assertSame(OrderStatus::ACTIVE->value, (int) $order->fresh()->status);
}
/** Giá gia hạn phải theo bảng giá hiện hành, không đóng băng theo giá lúc mua. */
public function test_renewal_invoice_uses_the_current_price_list(): void
{
$service = $this->createExpiringService(90_000);
$service->orderItem->product->pricings()->create([
'billing_cycle' => 'monthly',
'price' => 120_000,
'is_active' => 1,
]);
$this->artisan('service:expiry')->assertExitCode(0);
$invoice = Invoice::find($service->refresh()->invoice_id);
$this->assertSame(120_000, (int) $invoice->total);
}
/** Không có giá hiện hành (sản phẩm ngừng bán) thì lùi về giá cũ, vẫn xuất được hoá đơn. */
public function test_renewal_falls_back_to_the_original_price_when_no_current_price_exists(): void
{
$service = $this->createExpiringService(90_000);
$this->artisan('service:expiry')->assertExitCode(0);
$invoice = Invoice::find($service->refresh()->invoice_id);
$this->assertSame(90_000, (int) $invoice->total);
}
}
-21
View File
@@ -1,21 +0,0 @@
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function test_the_application_returns_a_successful_response()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
@@ -9,6 +9,7 @@ use App\Http\Controllers\Api\Admin\Transaction\AdminTransactionController;
use App\Models\Customer;
use App\Models\Transaction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;
@@ -33,8 +34,8 @@ class AdminTransactionApproveTest extends TestCase
$controller = app(AdminTransactionController::class);
$first = $controller->approve($transaction->uuid);
$second = $controller->approve($transaction->uuid);
$first = $controller->approve(new Request(), $transaction->uuid);
$second = $controller->approve(new Request(), $transaction->uuid);
$this->assertSame(200, $first->getStatusCode());
// Second call finds the transaction no longer PENDING → treated as not-approvable.
@@ -42,4 +43,61 @@ class AdminTransactionApproveTest extends TestCase
$this->assertSame(100_000, (int) $customer->fresh()->total);
}
/**
* Khách khai 5tr nhưng sao kê chỉ về 4tr: số dư phải cộng theo số THỰC NHẬN, phần chênh
* được ghi lại để kế toán đối chiếu. Trước đây luôn cộng theo số khách khai.
*/
public function test_approving_credits_the_received_amount_not_the_declared_one(): void
{
Mail::fake();
$customer = Customer::factory()->create(['total' => 0, 'credit' => 0, 'total_pending' => 5_000_000]);
$transaction = Transaction::create([
'uuid' => (string) \Illuminate\Support\Str::uuid(),
'public_code' => 'DEP-TEST-0002',
'trans' => 'DEP-TEST-0002',
'amount' => 5_000_000,
'customer_id' => $customer->id,
'type' => 'manual',
'status' => TransactionStatus::PENDING->value,
]);
$request = Request::create('/', 'POST', ['received_amount' => 4_000_000]);
$response = app(AdminTransactionController::class)->approve($request, $transaction->uuid);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame(4_000_000, (int) $customer->fresh()->total);
$this->assertSame(40_000, (int) $customer->fresh()->credit);
$this->assertSame(0, (int) $customer->fresh()->total_pending);
$transaction->refresh();
$this->assertSame(5_000_000, (int) $transaction->amount);
$this->assertSame(4_000_000, (int) $transaction->received_amount);
$this->assertStringContainsString('Lệch ' . number_format(1_000_000), (string) $transaction->note);
}
/** Bỏ trống received_amount = tin số khách khai, giữ nguyên hành vi cũ. */
public function test_approving_without_received_amount_credits_the_declared_amount(): void
{
Mail::fake();
$customer = Customer::factory()->create(['total' => 0, 'credit' => 0, 'total_pending' => 300_000]);
$transaction = Transaction::create([
'uuid' => (string) \Illuminate\Support\Str::uuid(),
'public_code' => 'DEP-TEST-0003',
'trans' => 'DEP-TEST-0003',
'amount' => 300_000,
'customer_id' => $customer->id,
'type' => 'manual',
'status' => TransactionStatus::PENDING->value,
]);
app(AdminTransactionController::class)->approve(new Request(), $transaction->uuid);
$this->assertSame(300_000, (int) $customer->fresh()->total);
$this->assertSame(300_000, (int) $transaction->fresh()->received_amount);
$this->assertStringNotContainsString('Lệch', (string) $transaction->fresh()->note);
}
}
@@ -81,4 +81,109 @@ class InvoicePaymentServiceTest extends TestCase
$this->assertNull($invoice->fresh()->paid_at);
}
}
/** Guard mới: admin không được bật hoá đơn đã huỷ sang đã thanh toán. */
public function test_admin_cannot_mark_a_cancelled_invoice_as_paid(): void
{
$customer = Customer::factory()->create(['total' => 200_000]);
$invoice = $this->makeInvoice($customer, 100_000, InvoiceStatus::CANCELLED->value);
$this->expectException(\InvalidArgumentException::class);
try {
app(InvoicePaymentService::class)->markPaidByAdmin($invoice, null);
} finally {
$this->assertSame(InvoiceStatus::CANCELLED->value, (int) $invoice->fresh()->status);
$this->assertNull($invoice->fresh()->paid_at);
}
}
/** Trả thiếu: cộng dồn amount_paid, hoá đơn vẫn chưa thanh toán, dịch vụ chưa kích hoạt. */
public function test_partial_payment_records_amount_paid_and_keeps_invoice_unpaid(): void
{
$customer = Customer::factory()->create(['total' => 200_000]);
$invoice = $this->makeInvoice($customer, 100_000);
$service = app(InvoicePaymentService::class);
$invoice = $service->payWithBalance($invoice, $customer, 'balance', 40_000);
$this->assertSame(40_000, (int) $invoice->amount_paid);
$this->assertSame(InvoiceStatus::UNPAID->value, (int) $invoice->status);
$this->assertNull($invoice->paid_at);
$this->assertSame(60_000, InvoicePaymentService::outstanding($invoice));
$this->assertSame(160_000, (int) $customer->fresh()->total);
$this->assertSame(OrderStatus::PENDING->value, (int) $invoice->order->fresh()->status);
}
/** Trả nốt phần còn thiếu thì hoá đơn mới chuyển PAID và đơn hàng mới được kích hoạt. */
public function test_paying_the_remainder_settles_the_invoice(): void
{
$customer = Customer::factory()->create(['total' => 200_000]);
$invoice = $this->makeInvoice($customer, 100_000);
$service = app(InvoicePaymentService::class);
$service->payWithBalance($invoice, $customer, 'balance', 40_000);
$invoice = $service->payWithBalance($invoice->fresh(), $customer->fresh(), 'balance');
$this->assertSame(100_000, (int) $invoice->amount_paid);
$this->assertSame(InvoiceStatus::PAID->value, (int) $invoice->status);
$this->assertNotNull($invoice->paid_at);
$this->assertSame(100_000, (int) $customer->fresh()->total);
$this->assertSame(OrderStatus::ACTIVE->value, (int) $invoice->order->fresh()->status);
// Mỗi lần trả là một dòng sổ riêng, không gộp cũng không ghi đè.
$this->assertSame(2, Transaction::where('customer_id', $customer->id)->where('type', 'invoice')->count());
}
/** Trả quá số còn thiếu thì chỉ trừ đúng phần còn thiếu, không thu dư. */
public function test_overpaying_only_charges_the_outstanding_amount(): void
{
$customer = Customer::factory()->create(['total' => 500_000]);
$invoice = $this->makeInvoice($customer, 100_000);
$invoice = app(InvoicePaymentService::class)->payWithBalance($invoice, $customer, 'balance', 300_000);
$this->assertSame(100_000, (int) $invoice->amount_paid);
$this->assertSame(400_000, (int) $customer->fresh()->total);
}
/** Hoàn tiền: cộng lại số dư, ghi Transaction âm, hoá đơn sang REFUNDED. */
public function test_refund_returns_balance_and_records_a_negative_transaction(): void
{
$customer = Customer::factory()->create(['total' => 200_000]);
$invoice = $this->makeInvoice($customer, 100_000);
$service = app(InvoicePaymentService::class);
$invoice = $service->payWithBalance($invoice, $customer, 'balance');
$this->assertSame(100_000, (int) $customer->fresh()->total);
$invoice = $service->refund($invoice, null, null, 'Khách huỷ dịch vụ');
$this->assertSame(InvoiceStatus::REFUNDED->value, (int) $invoice->status);
$this->assertSame(200_000, (int) $customer->fresh()->total);
$this->assertSame(
-100_000,
(int) Transaction::where('customer_id', $customer->id)->where('type', 'refund')->value('amount'),
);
}
private function makeInvoice(Customer $customer, int $total, int $status = InvoiceStatus::UNPAID->value): Invoice
{
$order = Order::create([
'order_num' => 'ORD-' . uniqid(),
'customer_id' => $customer->id,
'sub_total' => $total,
'total' => $total,
'status' => OrderStatus::PENDING->value,
]);
return Invoice::create([
'invoice_number' => 'INV-' . uniqid(),
'customer_id' => $customer->id,
'order_id' => $order->id,
'invoice_type' => 1,
'sub_total' => $total,
'tax' => 0,
'total' => $total,
'status' => $status,
]);
}
}