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,
]);
}
}
+12
View File
@@ -7,4 +7,16 @@ use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
/**
* Header `x-access-token` như portal-client gửi (xem ClientAccessTokenCheck).
*/
protected function buildClientAccessToken(?int $timestamp = null, ?string $ip = null): string
{
$key = hex2bin((string) config('services.client_api.key'));
$payload = ['s' => (string) config('services.client_api.secret'), 't' => $timestamp ?? time()] + ($ip ? ['ip' => $ip] : []);
$iv = random_bytes(16);
return base64_encode($iv . openssl_encrypt(json_encode($payload), 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv));
}
}
-320
View File
@@ -1,320 +0,0 @@
<?php
declare(strict_types=1);
namespace Tests\Unit;
use App\Models\Customer;
use App\Models\ModuleHost;
use App\Models\ModuleIpAddress;
use App\Models\ModuleVmware;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Services\VMDataService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use Mockery;
class VMDataServiceTest extends TestCase
{
use RefreshDatabase;
private VMDataService $vmDataService;
protected function setUp(): void
{
parent::setUp();
$this->vmDataService = new VMDataService();
}
/** @test */
public function it_can_save_vm_data_successfully()
{
// Arrange
$customer = Customer::factory()->create();
$order = Order::factory()->create(['customer_id' => $customer->id]);
$host = ModuleHost::factory()->create();
$product = Product::factory()->create(['module_host_id' => $host->id]);
$orderItem = OrderItem::factory()->create([
'order_id' => $order->id,
'product_id' => $product->id
]);
$vmwareId = 'vm-12345';
$ipAddresses = [
['ip' => '192.168.1.100', 'type' => 'IPV4', 'state' => 'PREFERRED']
];
// Act
$result = $this->vmDataService->saveVMData($orderItem, $vmwareId, $ipAddresses);
// Assert
$this->assertTrue($result['success']);
$this->assertInstanceOf(ModuleVmware::class, $result['vm']);
$this->assertInstanceOf(ModuleIpAddress::class, $result['ip_address']);
$this->assertEquals($vmwareId, $result['vm']->vmware_id);
$this->assertEquals('192.168.1.100', $result['ip_address']->ip);
$this->assertEquals($customer->id, $result['vm']->customer_id);
$this->assertEquals($order->id, $result['vm']->order_id);
}
/** @test */
public function it_can_update_existing_vm_data()
{
// Arrange
$customer = Customer::factory()->create();
$order = Order::factory()->create(['customer_id' => $customer->id]);
$host = ModuleHost::factory()->create();
$product = Product::factory()->create(['module_host_id' => $host->id]);
$orderItem = OrderItem::factory()->create([
'order_id' => $order->id,
'product_id' => $product->id
]);
$vmwareId = 'vm-12345';
$ipAddresses = [
['ip' => '192.168.1.100', 'type' => 'IPV4', 'state' => 'PREFERRED']
];
// Create existing VM
$existingVM = ModuleVmware::factory()->create([
'vmware_id' => $vmwareId,
'name' => $product->name
]);
// Act
$result = $this->vmDataService->saveVMData($orderItem, $vmwareId, $ipAddresses);
// Assert
$this->assertTrue($result['success']);
$this->assertEquals($existingVM->id, $result['vm']->id);
$this->assertEquals($order->id, $result['vm']->order_id);
}
/** @test */
public function it_can_update_vm_status()
{
// Arrange
$vm = ModuleVmware::factory()->create(['vmware_id' => 'vm-12345']);
// Act
$result = $this->vmDataService->updateVMStatus('vm-12345', 2);
// Assert
$this->assertTrue($result);
$this->assertEquals(2, $vm->fresh()->status);
}
/** @test */
public function it_can_update_vm_ip_address()
{
// Arrange
$ipAddress = ModuleIpAddress::factory()->create(['ip' => '192.168.1.100']);
$vm = ModuleVmware::factory()->create([
'vmware_id' => 'vm-12345',
'module_ip_address_id' => $ipAddress->id
]);
// Act
$result = $this->vmDataService->updateVMIPAddress('vm-12345', '192.168.1.200');
// Assert
$this->assertTrue($result);
$this->assertEquals('192.168.1.200', $ipAddress->fresh()->ip);
$this->assertEquals(1, $ipAddress->fresh()->status);
}
/** @test */
public function it_returns_false_when_vm_not_found_for_status_update()
{
// Act
$result = $this->vmDataService->updateVMStatus('non-existent-vm', 1);
// Assert
$this->assertFalse($result);
}
/** @test */
public function it_returns_false_when_vm_not_found_for_ip_update()
{
// Act
$result = $this->vmDataService->updateVMIPAddress('non-existent-vm', '192.168.1.100');
// Assert
$this->assertFalse($result);
}
/** @test */
public function it_handles_payment_fields_with_default_values()
{
// Arrange
$customer = Customer::factory()->create();
$order = Order::factory()->create([
'customer_id' => $customer->id,
'first_payment' => null, // Test null value
'next_payment' => '', // Test empty string
'next_invoice' => 'invalid', // Test invalid value
]);
$host = ModuleHost::factory()->create();
$product = Product::factory()->create(['module_host_id' => $host->id]);
$orderItem = OrderItem::factory()->create([
'order_id' => $order->id,
'product_id' => $product->id
]);
$vmwareId = 'vm-12345';
$ipAddresses = [
['ip' => '192.168.1.100', 'type' => 'IPV4', 'state' => 'PREFERRED']
];
// Act
$result = $this->vmDataService->saveVMData($orderItem, $vmwareId, $ipAddresses);
// Assert
$this->assertTrue($result['success']);
$this->assertEquals(0, $result['vm']->first_payment); // Should default to 0
$this->assertEquals(0, $result['vm']->next_payment); // Should default to 0
$this->assertEquals(0, $result['vm']->next_invoice); // Should default to 0
$this->assertEquals('0.0.0.0', $result['ip_address']->gateway); // Should default to 0.0.0.0
}
/** @test */
public function it_handles_valid_payment_fields()
{
// Arrange
$customer = Customer::factory()->create();
$order = Order::factory()->create([
'customer_id' => $customer->id,
'first_payment' => 100000,
'next_payment' => 200000,
'next_invoice' => 300000,
]);
$host = ModuleHost::factory()->create();
$product = Product::factory()->create(['module_host_id' => $host->id]);
$orderItem = OrderItem::factory()->create([
'order_id' => $order->id,
'product_id' => $product->id
]);
$vmwareId = 'vm-12345';
$ipAddresses = [
['ip' => '192.168.1.100', 'type' => 'IPV4', 'state' => 'PREFERRED']
];
// Act
$result = $this->vmDataService->saveVMData($orderItem, $vmwareId, $ipAddresses);
// Assert
$this->assertTrue($result['success']);
$this->assertEquals(100000, $result['vm']->first_payment);
$this->assertEquals(200000, $result['vm']->next_payment);
$this->assertEquals(300000, $result['vm']->next_invoice);
}
/**
* Test saving VM data with server_name in order item (should create new records)
*/
public function test_save_vm_data_with_server_name(): void
{
// Arrange
$orderItem = OrderItem::factory()->create([
'server_name' => 'linuxtestpb.com'
]);
$vmwareId = 'vm-12345';
$ipAddresses = [
['ip' => '192.168.1.100', 'type' => 'ipv4']
];
// Mock the product and related models
$product = Mockery::mock();
$product->shouldReceive('getAttribute')->andReturnSelf();
$product->name = 'Test Product';
$product->host = Mockery::mock(['id' => 1]);
$product->ipAddress = null;
$orderItem->shouldReceive('getProductAttribute')->andReturn($product);
$orderItem->order = Mockery::mock([
'id' => 1,
'customer' => Mockery::mock(['id' => 1]),
'first_payment' => 100,
'next_payment' => 200,
'next_invoice' => 300,
'next_due_date' => now()->addMonth()
]);
// Mock ModuleIpAddress - should only create
$ipAddress = Mockery::mock(ModuleIpAddress::class);
$ipAddress->id = 1;
ModuleIpAddress::shouldReceive('create')
->andReturn($ipAddress);
// Mock ModuleVmware - should only create
$vm = Mockery::mock(ModuleVmware::class);
$vm->id = 1;
$vm->vmware_id = $vmwareId;
ModuleVmware::shouldReceive('create')
->andReturn($vm);
// Act
$result = $this->vmDataService->saveVMData($orderItem, $vmwareId, $ipAddresses);
// Assert
$this->assertTrue($result['success']);
$this->assertEquals($vm, $result['vm']);
$this->assertEquals($ipAddress, $result['ip_address']);
$this->assertArrayNotHasKey('skipped', $result);
}
/**
* Test saving VM data without server_name in order item (should skip saving)
*/
public function test_save_vm_data_without_server_name(): void
{
// Arrange
$orderItem = OrderItem::factory()->create([
'server_name' => null
]);
$vmwareId = 'vm-12345';
$ipAddresses = [
['ip' => '192.168.1.100', 'type' => 'ipv4']
];
// Act
$result = $this->vmDataService->saveVMData($orderItem, $vmwareId, $ipAddresses);
// Assert
$this->assertTrue($result['success']);
$this->assertTrue($result['skipped']);
$this->assertEquals('Bỏ qua lưu dữ liệu VM vì không có server_name trong order item', $result['message']);
$this->assertArrayNotHasKey('vm', $result);
$this->assertArrayNotHasKey('ip_address', $result);
}
/**
* Test saving VM data with empty server_name in order item (should skip saving)
*/
public function test_save_vm_data_with_empty_server_name(): void
{
// Arrange
$orderItem = OrderItem::factory()->create([
'server_name' => ''
]);
$vmwareId = 'vm-12345';
$ipAddresses = [
['ip' => '192.168.1.100', 'type' => 'ipv4']
];
// Act
$result = $this->vmDataService->saveVMData($orderItem, $vmwareId, $ipAddresses);
// Assert
$this->assertTrue($result['success']);
$this->assertTrue($result['skipped']);
$this->assertEquals('Bỏ qua lưu dữ liệu VM vì không có server_name trong order item', $result['message']);
$this->assertArrayNotHasKey('vm', $result);
$this->assertArrayNotHasKey('ip_address', $result);
}
}
+111
View File
@@ -0,0 +1,111 @@
<?php
/**
* Soát toàn bộ template email đang bật trong tbl.template:
* 1. Mọi {{placeholder}} trong subject/message phải được khai báo ở metadata.variables,
* nếu không EmailTemplateRenderer sẽ ném InvalidTemplateVariableException lúc gửi.
* 2. Không còn placeholder kiểu blade {{ $var }} — renderer không hiểu, sẽ in ra nguyên văn.
* 3. Mọi scenario mà Mailable đang trỏ tới đều phải có row tương ứng.
*
* Chạy: php -d zend.assertions=1 tests/check-email-template-placeholders.php
*/
require __DIR__ . '/../vendor/autoload.php';
$app = require __DIR__ . '/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$failures = 0;
// ── 1 + 2. Từng template phải render được ────────────────────────────────────
$templates = App\Models\Template::where('status', 1)->get();
echo "Soát {$templates->count()} template đang bật.\n\n";
foreach ($templates as $template) {
$name = $template->scenario ?: ($template->key ?: "#{$template->id}");
$content = (string) $template->subject . ' ' . (string) $template->message;
preg_match_all('/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/', $content, $matches);
$used = array_unique($matches[1]);
$declared = array_keys($template->variables());
$undeclared = array_values(array_diff($used, $declared));
// Layout dùng {{$content}} làm chỗ cắm nội dung — đó là quy ước riêng, không phải biến.
$bladeish = $template->scenario === 'layout'
? []
: array_values(array_filter(
preg_match_all('/\{\{\s*\$[a-zA-Z_]+\s*\}\}/', $content, $m2) ? $m2[0] : []
));
if ($undeclared !== []) {
echo " ✘ {$name}: biến chưa khai báo → " . implode(', ', $undeclared) . "\n";
$failures++;
continue;
}
if ($bladeish !== []) {
echo " ✘ {$name}: còn placeholder blade → " . implode(', ', array_unique($bladeish)) . "\n";
$failures++;
continue;
}
echo " ✔ {$name}\n";
}
// ── 3. Mailable nào trỏ tới scenario chưa có row ─────────────────────────────
echo "\nSoát scenario mà Mailable đang dùng.\n\n";
$mailFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__ . '/../app/Mail'));
$referenced = [];
foreach ($mailFiles as $file) {
if ($file->isDir() || $file->getExtension() !== 'php') {
continue;
}
if (preg_match_all("/renderFromTemplate\(\s*'([a-z0-9_]+)'/", file_get_contents($file->getPathname()), $m)) {
foreach ($m[1] as $scenario) {
$referenced[$scenario] = basename($file->getPathname());
}
}
}
$existing = App\Models\Template::where('status', 1)
->get(['scenario', 'key'])
->flatMap(fn ($t) => array_filter([$t->scenario, $t->key]))
->unique()
->all();
foreach ($referenced as $scenario => $mailable) {
if (in_array($scenario, $existing, true)) {
echo " ✔ {$scenario} ({$mailable})\n";
} else {
echo " ✘ {$scenario} ({$mailable}): KHÔNG có template — gửi sẽ ném ModelNotFoundException\n";
$failures++;
}
}
// ── 4. Không còn Mailable nào render qua Blade ───────────────────────────────
echo "\nSoát Blade trong app/Mail.\n\n";
$bladeMailables = [];
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__ . '/../app/Mail')) as $file) {
if ($file->isDir() || $file->getExtension() !== 'php') {
continue;
}
if (preg_match('/\bview:\s*\'|\bmarkdown:\s*\'|->view\(|->markdown\(/', file_get_contents($file->getPathname()))) {
$bladeMailables[] = basename($file->getPathname());
}
}
if ($bladeMailables === []) {
echo " ✔ Không Mailable nào dùng Blade.\n";
} else {
echo " ✘ Còn dùng Blade: " . implode(', ', $bladeMailables) . "\n";
$failures += count($bladeMailables);
}
echo "\n" . ($failures === 0 ? "TẤT CẢ ĐẠT.\n" : "CÓ {$failures} LỖI.\n");
assert($failures === 0, "Có {$failures} template/mailable không đạt");
exit($failures === 0 ? 0 : 1);