feat(billing): renewals, coupons, VAT numbering, billing cycles and invoice payment tracking
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
ea9a53f742
commit
25f23d541e
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Api\Admin\Billing;
|
||||
|
||||
use App\Models\Customer;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\InvoiceItem;
|
||||
use App\Models\Order;
|
||||
use App\Models\OrderItem;
|
||||
use App\Models\Product;
|
||||
use App\Models\User;
|
||||
use App\Support\Billing\BillingDuplicateDetector as Detector;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Spatie\Permission\Models\Role;
|
||||
use Tests\TestCase;
|
||||
|
||||
class BillingDuplicateDetectorTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
Detector::flush();
|
||||
}
|
||||
|
||||
private function order(Customer $customer, Product $product, string $name, int $total = 100_000, string $at = 'now', int $status = 0, string $domain = ''): Order
|
||||
{
|
||||
$order = Order::create([
|
||||
'order_num' => 'ORD-' . uniqid(), 'customer_id' => $customer->id, 'sub_total' => $total, 'total' => $total,
|
||||
'status' => $status, 'created_at' => $at, 'updated_at' => $at,
|
||||
]);
|
||||
OrderItem::create([
|
||||
'order_id' => $order->id, 'product_id' => $product->id, 'billing_cycle' => 'monthly', 'months' => 1,
|
||||
'quantity' => 1, 'price' => $total, 'server_name' => $name, 'domain_name' => $domain ?: null,
|
||||
]);
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
private function invoice(Customer $customer, ?Order $order, int $type, int $total, string $at = 'now', ?string $period = null, string $item = 'VPS'): Invoice
|
||||
{
|
||||
$invoice = Invoice::create([
|
||||
'invoice_number' => 'INV-' . uniqid(), 'customer_id' => $customer->id, 'order_id' => $order?->id, 'invoice_type' => $type,
|
||||
'sub_total' => $total, 'tax' => 0, 'total' => $total, 'status' => 1, 'billing_period_start' => $period,
|
||||
'created_at' => $at, 'updated_at' => $at,
|
||||
]);
|
||||
InvoiceItem::create(['invoice_id' => $invoice->id, 'type' => 'service', 'description' => $item, 'months' => 1, 'quantity' => 1, 'unit_price' => $total, 'total_price' => $total]);
|
||||
|
||||
return $invoice;
|
||||
}
|
||||
|
||||
public function test_same_customer_product_and_service_name_is_flagged_even_days_apart(): void
|
||||
{
|
||||
$customer = Customer::factory()->create();
|
||||
$product = Product::factory()->create();
|
||||
$a = $this->order($customer, $product, 'Web-01', at: '2026-10-01 10:00:00');
|
||||
$b = $this->order($customer, $product, ' web-01 ', at: '2026-10-09 10:00:00');
|
||||
$other = $this->order($customer, $product, 'web-02');
|
||||
|
||||
$found = Detector::orders();
|
||||
|
||||
$this->assertSame(Detector::REASON_SAME_SERVICE, $found[$a->id]['reason']);
|
||||
$this->assertSame([$a->order_num], $found[$b->id]['with']);
|
||||
$this->assertArrayNotHasKey($other->id, $found);
|
||||
}
|
||||
|
||||
public function test_rapid_resubmit_needs_same_items_and_window(): void
|
||||
{
|
||||
$customer = Customer::factory()->create();
|
||||
$product = Product::factory()->create();
|
||||
$a = $this->order($customer, $product, '', at: '2026-10-01 10:00:00');
|
||||
$b = $this->order($customer, $product, '', at: '2026-10-01 11:00:00');
|
||||
$late = $this->order($customer, $product, '', at: '2026-10-05 11:00:00');
|
||||
$differentTotal = $this->order($customer, $product, '', total: 200_000, at: '2026-10-01 10:30:00');
|
||||
|
||||
$found = Detector::orders();
|
||||
|
||||
$this->assertSame(Detector::REASON_RESUBMIT, $found[$a->id]['reason']);
|
||||
$this->assertSame([$a->order_num], $found[$b->id]['with']);
|
||||
$this->assertArrayNotHasKey($late->id, $found);
|
||||
$this->assertArrayNotHasKey($differentTotal->id, $found);
|
||||
}
|
||||
|
||||
public function test_domain_ordered_by_two_customers_is_flagged_but_cancelled_orders_are_ignored(): void
|
||||
{
|
||||
$product = Product::factory()->create(['product_type' => 'domain']);
|
||||
$first = $this->order(Customer::factory()->create(), $product, 'shop.vn', domain: 'Shop.vn');
|
||||
$second = $this->order(Customer::factory()->create(), $product, 'shop.vn', domain: 'shop.vn');
|
||||
$cancelled = $this->order(Customer::factory()->create(), $product, 'shop.vn', status: 2, domain: 'shop.vn');
|
||||
|
||||
$found = Detector::orders();
|
||||
|
||||
$this->assertSame(Detector::REASON_DOMAIN_TAKEN, $found[$first->id]['reason']);
|
||||
$this->assertSame(Detector::REASON_DOMAIN_TAKEN, $found[$second->id]['reason']);
|
||||
$this->assertArrayNotHasKey($cancelled->id, $found);
|
||||
}
|
||||
|
||||
public function test_invoices_same_order_and_type_are_flagged_but_renewal_periods_and_upgrades_are_not(): void
|
||||
{
|
||||
$customer = Customer::factory()->create();
|
||||
$order = $this->order($customer, Product::factory()->create(), 'vm-1');
|
||||
$a = $this->invoice($customer, $order, 1, 100_000);
|
||||
$b = $this->invoice($customer, $order, 1, 150_000);
|
||||
$renewal = $this->invoice($customer, $order, 2, 100_000, period: '2026-11-01');
|
||||
$next = $this->invoice($customer, $order, 2, 100_000, period: '2026-12-01');
|
||||
$upgradeA = $this->invoice($customer, $order, 3, 50_000, at: '2026-10-01 10:00:00', item: 'Addon RAM');
|
||||
$upgradeB = $this->invoice($customer, $order, 3, 70_000, at: '2026-10-01 10:30:00', item: 'Addon CPU');
|
||||
|
||||
$found = Detector::invoices();
|
||||
|
||||
$this->assertSame(Detector::REASON_SAME_PERIOD, $found[$a->id]['reason']);
|
||||
$this->assertSame([$a->invoice_number], $found[$b->id]['with']);
|
||||
$this->assertArrayNotHasKey($renewal->id, $found);
|
||||
$this->assertArrayNotHasKey($next->id, $found);
|
||||
$this->assertArrayNotHasKey($upgradeA->id, $found);
|
||||
$this->assertArrayNotHasKey($upgradeB->id, $found);
|
||||
}
|
||||
|
||||
public function test_invoice_rapid_resubmit_requires_identical_items(): void
|
||||
{
|
||||
$customer = Customer::factory()->create();
|
||||
$a = $this->invoice($customer, null, 1, 100_000, at: '2026-10-01 10:00:00');
|
||||
$b = $this->invoice($customer, null, 1, 100_000, at: '2026-10-01 10:05:00');
|
||||
$diff = $this->invoice($customer, null, 1, 100_000, at: '2026-10-01 10:06:00', item: 'Khác');
|
||||
|
||||
$found = Detector::invoices();
|
||||
|
||||
$this->assertSame(Detector::REASON_RESUBMIT, $found[$a->id]['reason']);
|
||||
$this->assertSame([$a->invoice_number], $found[$b->id]['with']);
|
||||
$this->assertArrayNotHasKey($diff->id, $found);
|
||||
}
|
||||
|
||||
public function test_list_endpoints_expose_flag_and_filter(): void
|
||||
{
|
||||
Role::firstOrCreate(['name' => 'Full Administrator', 'guard_name' => 'admin']);
|
||||
$admin = tap(User::factory()->create())->assignRole('Full Administrator');
|
||||
$customer = Customer::factory()->create();
|
||||
$product = Product::factory()->create();
|
||||
$a = $this->order($customer, $product, 'dup-1');
|
||||
$b = $this->order($customer, $product, 'dup-1');
|
||||
$solo = $this->order($customer, $product, 'solo');
|
||||
$inv = $this->invoice($customer, $a, 1, 100_000);
|
||||
$this->invoice($customer, $a, 1, 100_000);
|
||||
|
||||
$orders = $this->actingAs($admin, 'admin')->getJson('/api/v1/administrator/orders?duplicates=1')->assertOk();
|
||||
$this->assertEqualsCanonicalizing([$a->id, $b->id], collect($orders->json('data.items'))->pluck('id')->all());
|
||||
$this->assertSame(Detector::REASON_RESUBMIT, $orders->json('data.items.0.duplicate.reason'));
|
||||
|
||||
$all = $this->actingAs($admin, 'admin')->getJson('/api/v1/administrator/orders')->assertOk();
|
||||
$this->assertCount(3, $all->json('data.items'));
|
||||
$this->assertNull(collect($all->json('data.items'))->firstWhere('id', $solo->id)['duplicate']);
|
||||
|
||||
$invoices = $this->actingAs($admin, 'admin')->getJson('/api/v1/administrator/invoices?duplicates=1')->assertOk();
|
||||
$this->assertCount(2, $invoices->json('data.items'));
|
||||
$this->assertSame(Detector::REASON_SAME_PERIOD, collect($invoices->json('data.items'))->firstWhere('id', $inv->id)['duplicate']['reason']);
|
||||
}
|
||||
|
||||
public function test_order_date_defaults_to_today_when_not_given(): void
|
||||
{
|
||||
$order = Order::create(['order_num' => 'ORD-DATE', 'customer_id' => Customer::factory()->create()->id, 'sub_total' => 1, 'total' => 1, 'status' => 0]);
|
||||
|
||||
$this->assertSame(now()->toDateString(), $order->fresh()->date->toDateString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Models\Coupon;
|
||||
use App\Models\CouponRedemption;
|
||||
use App\Models\Customer;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Spatie\Permission\Models\Permission;
|
||||
use Spatie\Permission\Models\Role;
|
||||
use Tests\TestCase;
|
||||
|
||||
class CouponAdminTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function admin(array $permissions): User
|
||||
{
|
||||
$role = Role::create(['name' => 'role-' . uniqid(), 'guard_name' => 'admin']);
|
||||
foreach ($permissions as $name) {
|
||||
$role->givePermissionTo(Permission::firstOrCreate(['name' => $name, 'guard_name' => 'admin']));
|
||||
}
|
||||
$admin = User::factory()->create();
|
||||
$admin->assignRole($role);
|
||||
|
||||
return $admin;
|
||||
}
|
||||
|
||||
private function payload(array $overrides = []): array
|
||||
{
|
||||
return array_merge([
|
||||
'code' => 'welcome10',
|
||||
'type' => 'percent',
|
||||
'value' => 10,
|
||||
'applies_to' => 'new',
|
||||
'product_types' => ['vps'],
|
||||
], $overrides);
|
||||
}
|
||||
|
||||
public function test_crud_and_code_is_normalized(): void
|
||||
{
|
||||
$admin = $this->admin(['product-service.view', 'product-service.create', 'product-service.edit', 'product-service.destroy']);
|
||||
|
||||
$id = $this->actingAs($admin, 'admin')
|
||||
->postJson('/api/v1/administrator/coupons', $this->payload())
|
||||
->assertCreated()
|
||||
->assertJsonPath('data.code', 'WELCOME10')
|
||||
->json('data.id');
|
||||
|
||||
$this->putJson("/api/v1/administrator/coupons/{$id}", $this->payload(['value' => 15]))
|
||||
->assertOk()->assertJsonPath('data.value', 15);
|
||||
|
||||
$this->getJson('/api/v1/administrator/coupons')->assertOk()->assertJsonPath('data.0.used_count', 0);
|
||||
|
||||
$this->deleteJson("/api/v1/administrator/coupons/{$id}")->assertOk();
|
||||
}
|
||||
|
||||
public function test_validation_rejects_duplicate_code_and_percent_over_99(): void
|
||||
{
|
||||
$admin = $this->admin(['product-service.create']);
|
||||
Coupon::create(['code' => 'DUP', 'type' => 'fixed', 'value' => 1000, 'applies_to' => 'new']);
|
||||
|
||||
$this->actingAs($admin, 'admin')
|
||||
->postJson('/api/v1/administrator/coupons', $this->payload(['code' => 'dup']))
|
||||
->assertStatus(422)->assertJsonValidationErrors('code');
|
||||
$this->postJson('/api/v1/administrator/coupons', $this->payload(['value' => 100]))
|
||||
->assertStatus(422)->assertJsonValidationErrors('value');
|
||||
}
|
||||
|
||||
public function test_used_coupon_cannot_be_deleted(): void
|
||||
{
|
||||
$admin = $this->admin(['product-service.destroy']);
|
||||
$coupon = Coupon::create(['code' => 'USED', 'type' => 'fixed', 'value' => 1000, 'applies_to' => 'new']);
|
||||
CouponRedemption::create([
|
||||
'coupon_id' => $coupon->id,
|
||||
'customer_id' => Customer::factory()->create()->id,
|
||||
'amount' => 1000,
|
||||
]);
|
||||
|
||||
$this->actingAs($admin, 'admin')
|
||||
->deleteJson("/api/v1/administrator/coupons/{$coupon->id}")
|
||||
->assertStatus(422);
|
||||
$this->assertNotNull(Coupon::find($coupon->id));
|
||||
}
|
||||
|
||||
public function test_requires_permission(): void
|
||||
{
|
||||
Permission::firstOrCreate(['name' => 'product-service.view', 'guard_name' => 'admin']);
|
||||
|
||||
$this->actingAs($this->admin([]), 'admin')
|
||||
->getJson('/api/v1/administrator/coupons')
|
||||
->assertForbidden();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Api\Admin\Customer;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Mail\ServiceRenewedMail;
|
||||
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\Models\Setting;
|
||||
use App\Models\User;
|
||||
use Database\Seeders\TemplateSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Spatie\Permission\Models\Permission;
|
||||
use Spatie\Permission\Models\Role;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AdminRenewServiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function admin(): User
|
||||
{
|
||||
$role = Role::create(['name' => 'role-' . uniqid(), 'guard_name' => 'admin']);
|
||||
$role->givePermissionTo(Permission::firstOrCreate(['name' => 'customer.edit', 'guard_name' => 'admin']));
|
||||
$admin = User::factory()->create();
|
||||
$admin->assignRole($role);
|
||||
|
||||
return $admin;
|
||||
}
|
||||
|
||||
private function service(int $balance): Service
|
||||
{
|
||||
$customer = Customer::factory()->create(['total' => $balance]);
|
||||
$product = Product::factory()->create(['product_type' => 'hosting', 'is_active' => true]);
|
||||
$order = Order::create([
|
||||
'order_num' => 'ORD-' . uniqid(),
|
||||
'customer_id' => $customer->id,
|
||||
'sub_total' => 90_000,
|
||||
'total' => 90_000,
|
||||
'status' => OrderStatus::ACTIVE->value,
|
||||
]);
|
||||
$item = OrderItem::create([
|
||||
'order_id' => $order->id,
|
||||
'product_id' => $product->id,
|
||||
'billing_cycle' => 'monthly',
|
||||
'months' => 1,
|
||||
'quantity' => 1,
|
||||
'price' => 90_000,
|
||||
]);
|
||||
|
||||
$product->pricings()->create(['billing_cycle' => 'monthly', 'price' => 90_000, 'is_active' => 1]);
|
||||
|
||||
return Service::create([
|
||||
'customer_id' => $customer->id,
|
||||
'product_id' => $product->id,
|
||||
'order_item_id' => $item->id,
|
||||
'status' => 'suspended',
|
||||
'server_name' => 'test-server',
|
||||
'expires_at' => now()->subDay(),
|
||||
]);
|
||||
}
|
||||
|
||||
private function renew(Service $service, array $payload)
|
||||
{
|
||||
return $this->actingAs($this->admin(), 'admin')
|
||||
->postJson("/api/v1/administrator/customers/{$service->customer->uuid}/services/{$service->id}/renew", $payload);
|
||||
}
|
||||
|
||||
public function test_manual_payment_renews_without_touching_balance(): void
|
||||
{
|
||||
$service = $this->service(0);
|
||||
|
||||
$this->renew($service, ['months' => 1, 'payment' => 'manual', 'note' => 'CK VCB'])->assertOk();
|
||||
|
||||
$service->refresh();
|
||||
$this->assertSame('active', $service->status);
|
||||
$this->assertTrue($service->expires_at->isFuture());
|
||||
$this->assertSame(InvoiceStatus::PAID->value, Invoice::find($service->invoice_id)->status);
|
||||
$this->assertSame(0, (int) $service->customer->fresh()->total);
|
||||
}
|
||||
|
||||
public function test_renewal_is_logged_with_actor_and_payment_method_and_listed(): void
|
||||
{
|
||||
$service = $this->service(0);
|
||||
$admin = $this->admin();
|
||||
$admin->givePermissionTo(\Spatie\Permission\Models\Permission::firstOrCreate(['name' => 'customer.view', 'guard_name' => 'admin']));
|
||||
$base = "/api/v1/administrator/customers/{$service->customer->uuid}/services/{$service->id}";
|
||||
|
||||
$this->actingAs($admin, 'admin')->postJson("{$base}/renew", ['months' => 1, 'payment' => 'manual'])->assertOk();
|
||||
|
||||
$this->actingAs($admin, 'admin')->getJson("{$base}/renewals")
|
||||
->assertOk()
|
||||
->assertJsonCount(1, 'data')
|
||||
->assertJsonPath('data.0.causer_type', 'admin')
|
||||
->assertJsonPath('data.0.new_values.payment_method', 'admin')
|
||||
->assertJsonPath('data.0.new_values.months', 1);
|
||||
}
|
||||
|
||||
public function test_balance_payment_deducts_customer_balance(): void
|
||||
{
|
||||
$service = $this->service(200_000);
|
||||
|
||||
$this->renew($service, ['months' => 1, 'payment' => 'balance'])->assertOk();
|
||||
|
||||
$this->assertSame(110_000, (int) $service->customer->fresh()->total);
|
||||
$this->assertSame('active', $service->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_balance_payment_with_insufficient_funds_leaves_invoice_unpaid(): void
|
||||
{
|
||||
$service = $this->service(1_000);
|
||||
|
||||
$this->renew($service, ['months' => 1, 'payment' => 'balance'])->assertStatus(422);
|
||||
|
||||
$this->assertSame(InvoiceStatus::UNPAID->value, Invoice::find($service->fresh()->invoice_id)->status);
|
||||
}
|
||||
|
||||
public function test_rejects_months_outside_the_billing_cycle(): void
|
||||
{
|
||||
$service = $this->service(200_000);
|
||||
|
||||
$this->renew($service, ['months' => 25, 'payment' => 'manual'])->assertStatus(422);
|
||||
}
|
||||
|
||||
public function test_renewal_queues_email_to_customer_and_admin(): void
|
||||
{
|
||||
Mail::fake();
|
||||
(new TemplateSeeder())->run();
|
||||
Setting::create(['key' => 'setting', 'value' => json_encode(['admin_email' => 'ops@example.com'])]);
|
||||
$service = $this->service(0);
|
||||
|
||||
$this->renew($service, ['months' => 1, 'payment' => 'manual'])->assertOk();
|
||||
|
||||
Mail::assertQueued(ServiceRenewedMail::class, fn ($mail) => $mail->hasTo($service->customer->email));
|
||||
Mail::assertQueued(ServiceRenewedMail::class, fn ($mail) => $mail->hasTo('ops@example.com'));
|
||||
}
|
||||
|
||||
public function test_rejects_period_already_renewed_before(): void
|
||||
{
|
||||
$service = $this->service(0);
|
||||
$this->renew($service, ['months' => 1, 'payment' => 'manual'])->assertOk();
|
||||
|
||||
$service->refresh()->update(['expires_at' => now()->addDays(5)]);
|
||||
|
||||
$this->renew($service, ['months' => 1, 'payment' => 'manual'])
|
||||
->assertStatus(422)
|
||||
->assertJsonPath('error', true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Models\Setting;
|
||||
use App\Models\User;
|
||||
use App\Support\EmailHealth;
|
||||
use Database\Seeders\TemplateSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Spatie\Permission\Models\Role;
|
||||
use Tests\TestCase;
|
||||
|
||||
class EmailHealthTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_health_flags_disabled_lifecycle_scenarios_and_clears_when_enabled(): void
|
||||
{
|
||||
$this->seed(TemplateSeeder::class);
|
||||
Role::firstOrCreate(['name' => 'Full Administrator', 'guard_name' => 'admin']);
|
||||
$admin = User::factory()->create();
|
||||
$admin->assignRole('Full Administrator');
|
||||
|
||||
Setting::updateOrCreate(['key' => 'email_settings'], ['value' => json_encode(['auto_disabled' => ['service_expiry', 'auto_renew_failed']])]);
|
||||
|
||||
$rows = collect($this->actingAs($admin, 'admin')->getJson('/api/v1/administrator/email-templates/health')
|
||||
->assertOk()
|
||||
->json('data.scenarios'))->keyBy('key');
|
||||
|
||||
$this->assertFalse($rows['service_expiry']['auto_enabled']);
|
||||
$this->assertFalse($rows['service_expiry']['ready']);
|
||||
$this->assertTrue($rows['invoice_notification']['has_template']);
|
||||
$this->assertSame(EmailHealth::LIFECYCLE_SCENARIOS, $rows->keys()->all());
|
||||
|
||||
Setting::updateOrCreate(['key' => 'email_settings'], ['value' => json_encode(['auto_disabled' => []])]);
|
||||
|
||||
$rows = collect(EmailHealth::report()['scenarios'])->keyBy('key');
|
||||
$this->assertTrue($rows['service_expiry']['ready']);
|
||||
}
|
||||
}
|
||||
@@ -10,12 +10,14 @@ use App\Jobs\Mail\SendInvoiceMailJob;
|
||||
use App\Mail\InvoiceNotificationMail;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\InvoiceAttachment;
|
||||
use App\Models\Order;
|
||||
use App\Models\Setting;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Spatie\Permission\Models\Role;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -90,4 +92,79 @@ class InvoiceSendMailTest extends TestCase
|
||||
Mail::assertSent(InvoiceNotificationMail::class);
|
||||
$this->assertDatabaseHas('mail', ['order_id' => $this->invoice->order_id, 'sent_by' => $this->admin->id]);
|
||||
}
|
||||
|
||||
private function contract(Invoice $invoice, string $type = InvoiceAttachment::TYPE_CONTRACT): InvoiceAttachment
|
||||
{
|
||||
Storage::fake('public');
|
||||
Storage::disk('public')->put('invoice-attachments/c.pdf', '%PDF-contract');
|
||||
|
||||
return InvoiceAttachment::create([
|
||||
'invoice_id' => $invoice->id, 'type' => $type, 'filename' => 'Hop-dong.pdf', 'path' => 'invoice-attachments/c.pdf',
|
||||
'disk' => 'public', 'mime_type' => 'application/pdf', 'size' => 13, 'uploaded_by' => 'admin',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_admin_can_open_invoice_pdf_and_vat_variant_needs_a_vat_number(): void
|
||||
{
|
||||
$this->actingAs($this->admin, 'admin')->get("/api/v1/administrator/invoices/{$this->invoice->id}/pdf")
|
||||
->assertOk()->assertHeader('content-type', 'application/pdf');
|
||||
|
||||
$this->actingAs($this->admin, 'admin')->getJson("/api/v1/administrator/invoices/{$this->invoice->id}/pdf?variant=vat")
|
||||
->assertStatus(422);
|
||||
|
||||
$this->invoice->update(['vat_serial' => '1C26TCP', 'vat_number' => '00000007', 'vat_issued_at' => now()->toDateString()]);
|
||||
$this->actingAs($this->admin, 'admin')->get("/api/v1/administrator/invoices/{$this->invoice->id}/pdf?variant=vat")
|
||||
->assertOk()->assertHeader('content-disposition', 'inline; filename="Hoa-don-VAT-1C26TCP-00000007.pdf"');
|
||||
}
|
||||
|
||||
public function test_preview_lists_vat_file_and_contracts_only(): void
|
||||
{
|
||||
$contract = $this->contract($this->invoice);
|
||||
$this->contract($this->invoice, InvoiceAttachment::TYPE_DEPLOYMENT);
|
||||
$this->seed(\Database\Seeders\TemplateSeeder::class);
|
||||
|
||||
$this->actingAs($this->admin, 'admin')
|
||||
->postJson("/api/v1/administrator/invoices/{$this->invoice->id}/send-mail/preview", ['type' => 'invoice'])
|
||||
->assertOk()
|
||||
->assertJsonPath('data.vat_attachment_filename', null)
|
||||
->assertJsonCount(1, 'data.contracts')
|
||||
->assertJsonPath('data.contracts.0.id', $contract->id);
|
||||
}
|
||||
|
||||
public function test_send_rejects_vat_attachment_without_vat_number_and_ignores_foreign_contracts(): void
|
||||
{
|
||||
Queue::fake();
|
||||
$this->actingAs($this->admin, 'admin')
|
||||
->postJson("/api/v1/administrator/invoices/{$this->invoice->id}/send-mail", ['attach_vat' => true])
|
||||
->assertStatus(422);
|
||||
|
||||
$other = Invoice::create([
|
||||
'invoice_number' => 'INV-OTHER', 'customer_id' => $this->invoice->customer_id, 'invoice_type' => 1,
|
||||
'sub_total' => 1, 'tax' => 0, 'total' => 1, 'status' => InvoiceStatus::UNPAID->value,
|
||||
]);
|
||||
$foreign = $this->contract($other);
|
||||
$mine = $this->contract($this->invoice);
|
||||
|
||||
$this->actingAs($this->admin, 'admin')
|
||||
->postJson("/api/v1/administrator/invoices/{$this->invoice->id}/send-mail", ['contract_ids' => [$foreign->id, $mine->id]])
|
||||
->assertOk();
|
||||
|
||||
Queue::assertPushed(SendInvoiceMailJob::class, fn ($job) => $job->contractIds === [$mine->id]);
|
||||
}
|
||||
|
||||
public function test_job_attaches_vat_pdf_and_contract_files(): void
|
||||
{
|
||||
$this->seed(\Database\Seeders\TemplateSeeder::class);
|
||||
$this->invoice->update(['vat_serial' => 'AB', 'vat_number' => '0001', 'vat_issued_at' => now()->toDateString()]);
|
||||
$contract = $this->contract($this->invoice);
|
||||
Mail::fake();
|
||||
|
||||
dispatch_sync(new SendInvoiceMailJob($this->invoice->id, 'invoice', 'Hi', null, null, $this->admin->id, true, [$contract->id]));
|
||||
|
||||
Mail::assertSent(InvoiceNotificationMail::class, function (InvoiceNotificationMail $mail) {
|
||||
$names = collect($mail->rawAttachments)->pluck('name')->merge(collect($mail->diskAttachments)->pluck('name'));
|
||||
|
||||
return $names->contains('Hoa-don-VAT-AB-0001.pdf') && $names->contains('Hop-dong.pdf');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Spatie\Permission\Models\Permission;
|
||||
use Spatie\Permission\Models\Role;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvoiceVatTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function admin(array $permissions): User
|
||||
{
|
||||
$role = Role::create(['name' => 'role-' . uniqid(), 'guard_name' => 'admin']);
|
||||
foreach (['invoice.view', 'invoice.edit', 'customer.view', 'customer.edit'] as $name) {
|
||||
Permission::firstOrCreate(['name' => $name, 'guard_name' => 'admin']);
|
||||
}
|
||||
$role->givePermissionTo($permissions);
|
||||
|
||||
return tap(User::factory()->create())->assignRole($role);
|
||||
}
|
||||
|
||||
private function invoice(string $number, Customer $customer): Invoice
|
||||
{
|
||||
return Invoice::create([
|
||||
'invoice_number' => $number, 'customer_id' => $customer->id, 'invoice_type' => 1,
|
||||
'sub_total' => 1000, 'tax' => 0, 'total' => 1000, 'status' => InvoiceStatus::PAID->value,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_recording_vat_freezes_buyer_and_rejects_duplicate_number(): void
|
||||
{
|
||||
$customer = Customer::factory()->create(['tax_code' => '0312345678', 'invoice_company' => 'ABC']);
|
||||
$first = $this->invoice('INV-V1', $customer);
|
||||
$second = $this->invoice('INV-V2', $customer);
|
||||
$payload = ['vat_serial' => '1C26TCP', 'vat_number' => '15', 'vat_issued_at' => '2026-10-19'];
|
||||
$admin = $this->admin(['invoice.view', 'invoice.edit']);
|
||||
|
||||
$this->actingAs($admin, 'admin')->putJson("/api/v1/administrator/invoices/{$first->id}/vat", $payload)
|
||||
->assertOk()->assertJsonPath('data.buyer_locked', true);
|
||||
$customer->update(['tax_code' => '0999999999']);
|
||||
$this->actingAs($admin, 'admin')->getJson("/api/v1/administrator/invoices/{$first->id}/vat")
|
||||
->assertJsonPath('data.buyer.tax_code', '0312345678');
|
||||
|
||||
$this->actingAs($admin, 'admin')->putJson("/api/v1/administrator/invoices/{$second->id}/vat", $payload)
|
||||
->assertStatus(422)->assertJsonValidationErrors('vat_number');
|
||||
}
|
||||
|
||||
public function test_vat_endpoints_require_permissions(): void
|
||||
{
|
||||
$customer = Customer::factory()->create();
|
||||
$invoice = $this->invoice('INV-V3', $customer);
|
||||
$viewer = $this->admin(['invoice.view']);
|
||||
|
||||
$this->actingAs($viewer, 'admin')->putJson("/api/v1/administrator/invoices/{$invoice->id}/vat", [])->assertForbidden();
|
||||
$this->actingAs($viewer, 'admin')->putJson("/api/v1/administrator/customers/{$customer->uuid}/billing-profile", [])->assertForbidden();
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ class RenewalReminderTest extends TestCase
|
||||
private const BASE = '/api/v1/administrator/services/renewal-reminders';
|
||||
|
||||
private User $admin;
|
||||
private Customer $customer;
|
||||
private Service $soon;
|
||||
private Service $later;
|
||||
|
||||
@@ -34,10 +35,10 @@ class RenewalReminderTest extends TestCase
|
||||
$this->admin = User::factory()->create();
|
||||
$this->admin->assignRole('Full Administrator');
|
||||
|
||||
$customer = Customer::factory()->create();
|
||||
$this->soon = Service::create(['customer_id' => $customer->id, 'status' => 'active', 'expires_at' => now()->addDays(5)]);
|
||||
$this->later = Service::create(['customer_id' => $customer->id, 'status' => 'active', 'expires_at' => now()->addDays(40)]);
|
||||
Service::create(['customer_id' => $customer->id, 'status' => 'suspended', 'expires_at' => now()->addDays(3)]);
|
||||
$this->customer = Customer::factory()->create();
|
||||
$this->soon = Service::create(['customer_id' => $this->customer->id, 'status' => 'active', 'expires_at' => now()->addDays(5)]);
|
||||
$this->later = Service::create(['customer_id' => $this->customer->id, 'status' => 'active', 'expires_at' => now()->addDays(40)]);
|
||||
Service::create(['customer_id' => $this->customer->id, 'status' => 'suspended', 'expires_at' => now()->addDays(3)]);
|
||||
}
|
||||
|
||||
public function test_lists_active_services_expiring_within_days(): void
|
||||
@@ -75,4 +76,21 @@ class RenewalReminderTest extends TestCase
|
||||
|
||||
Mail::assertNothingQueued();
|
||||
}
|
||||
|
||||
public function test_customer_service_reminder_queues_mail_and_records_log(): void
|
||||
{
|
||||
Mail::fake();
|
||||
|
||||
$this->actingAs($this->admin, 'admin')
|
||||
->postJson("/api/v1/administrator/customers/{$this->customer->uuid}/services/{$this->soon->id}/notify-renew")
|
||||
->assertOk()
|
||||
->assertJsonPath('error', false);
|
||||
|
||||
Mail::assertQueued(ServiceRenewalReminderMail::class, 1);
|
||||
$this->assertDatabaseHas('mail', [
|
||||
'customer_id' => $this->customer->id,
|
||||
'sent_by' => $this->admin->id,
|
||||
'to' => $this->customer->email,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Mail\InvoiceNotificationMail;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\InvoiceItem;
|
||||
use App\Models\Product;
|
||||
use App\Models\Setting;
|
||||
use App\Models\User;
|
||||
use App\Support\VatCalculator;
|
||||
use App\Support\VatNumbering;
|
||||
use App\Support\VatSettings;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Spatie\Permission\Models\Permission;
|
||||
use Spatie\Permission\Models\Role;
|
||||
use Tests\TestCase;
|
||||
|
||||
class VatAutomationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
VatSettings::forget();
|
||||
}
|
||||
|
||||
private function rates(array $rates): void
|
||||
{
|
||||
Setting::updateOrCreate(['key' => 'vat_settings'], ['value' => json_encode(
|
||||
collect($rates)->map(fn ($rate, $type) => ['type' => $type, 'type_label' => $type, 'vat_rate' => $rate])->values()
|
||||
)]);
|
||||
VatSettings::forget();
|
||||
}
|
||||
|
||||
private function invoice(array $lines, int $discount = 0, int $status = InvoiceStatus::UNPAID->value): Invoice
|
||||
{
|
||||
$customer = Customer::factory()->create();
|
||||
$gross = array_sum(array_column($lines, 1));
|
||||
$invoice = Invoice::create([
|
||||
'invoice_number' => 'INV-' . uniqid(), 'customer_id' => $customer->id, 'invoice_type' => 1,
|
||||
'sub_total' => $gross, 'discount_amount' => $discount, 'tax' => 0, 'total' => $gross - $discount, 'status' => $status,
|
||||
]);
|
||||
foreach ($lines as [$type, $amount]) {
|
||||
InvoiceItem::create([
|
||||
'invoice_id' => $invoice->id, 'product_id' => Product::factory()->create(['product_type' => $type])->id,
|
||||
'type' => 'service', 'description' => $type, 'months' => 1, 'quantity' => 1,
|
||||
'unit_price' => $amount, 'total_price' => $amount,
|
||||
]);
|
||||
}
|
||||
|
||||
return $invoice;
|
||||
}
|
||||
|
||||
private function admin(): User
|
||||
{
|
||||
$role = Role::create(['name' => 'role-' . uniqid(), 'guard_name' => 'admin']);
|
||||
foreach (['invoice.view', 'invoice.edit', 'setting.manager'] as $name) {
|
||||
Permission::firstOrCreate(['name' => $name, 'guard_name' => 'admin']);
|
||||
$role->givePermissionTo($name);
|
||||
}
|
||||
|
||||
return tap(User::factory()->create())->assignRole($role);
|
||||
}
|
||||
|
||||
public function test_tax_is_extracted_from_inclusive_price_per_service_type(): void
|
||||
{
|
||||
$this->rates(['vps' => 10, 'domain' => 0]);
|
||||
$invoice = $this->invoice([['vps', 110_000], ['domain', 500_000]]);
|
||||
|
||||
VatCalculator::refresh($invoice);
|
||||
|
||||
$this->assertSame(10_000, (int) $invoice->fresh()->tax);
|
||||
$this->assertSame(610_000, (int) $invoice->fresh()->total);
|
||||
}
|
||||
|
||||
public function test_discount_reduces_taxable_amount_proportionally(): void
|
||||
{
|
||||
$this->rates(['vps' => 10]);
|
||||
$invoice = $this->invoice([['vps', 220_000]], discount: 110_000);
|
||||
|
||||
VatCalculator::refresh($invoice);
|
||||
|
||||
$this->assertSame(10_000, (int) $invoice->fresh()->tax);
|
||||
}
|
||||
|
||||
public function test_no_configured_rate_keeps_tax_zero(): void
|
||||
{
|
||||
$invoice = $this->invoice([['vps', 110_000]]);
|
||||
|
||||
VatCalculator::refresh($invoice);
|
||||
|
||||
$this->assertSame(0, (int) $invoice->fresh()->tax);
|
||||
}
|
||||
|
||||
public function test_issued_invoice_tax_is_frozen(): void
|
||||
{
|
||||
$this->rates(['vps' => 10]);
|
||||
$invoice = $this->invoice([['vps', 110_000]]);
|
||||
VatNumbering::issue($invoice);
|
||||
$this->rates(['vps' => 8]);
|
||||
|
||||
VatCalculator::refresh($invoice->fresh());
|
||||
|
||||
$this->assertSame(10_000, (int) $invoice->fresh()->tax);
|
||||
}
|
||||
|
||||
public function test_issue_assigns_sequential_numbers_and_skips_manual_collisions(): void
|
||||
{
|
||||
VatSettings::saveNumbering(['serial' => '1C26TCP', 'next_number' => 5, 'padding' => 4, 'auto_issue' => false]);
|
||||
$first = $this->invoice([['vps', 100_000]]);
|
||||
$second = $this->invoice([['vps', 100_000]]);
|
||||
$manual = $this->invoice([['vps', 100_000]]);
|
||||
$manual->update(['vat_serial' => '1C26TCP', 'vat_number' => '0006']);
|
||||
|
||||
$a = VatNumbering::issue($first);
|
||||
$b = VatNumbering::issue($second);
|
||||
|
||||
$this->assertSame('0005', $a->vat_number);
|
||||
$this->assertSame('0007', $b->vat_number);
|
||||
$this->assertSame(8, VatSettings::numbering()['next_number']);
|
||||
$this->assertSame($a->vat_number, VatNumbering::issue($a)->vat_number);
|
||||
$this->assertNotNull($a->buyer_snapshot);
|
||||
}
|
||||
|
||||
public function test_auto_issue_runs_only_when_enabled_and_invoice_becomes_paid(): void
|
||||
{
|
||||
VatSettings::saveNumbering(['serial' => 'AB', 'next_number' => 1, 'padding' => 3, 'auto_issue' => true]);
|
||||
$invoice = $this->invoice([['vps', 100_000]]);
|
||||
$this->assertNull($invoice->fresh()->vat_number);
|
||||
|
||||
$invoice->update(['status' => InvoiceStatus::PAID->value]);
|
||||
|
||||
$this->assertSame('001', $invoice->fresh()->vat_number);
|
||||
|
||||
VatSettings::saveNumbering(['serial' => 'AB', 'next_number' => 2, 'padding' => 3, 'auto_issue' => false]);
|
||||
$other = $this->invoice([['vps', 100_000]]);
|
||||
$other->update(['status' => InvoiceStatus::PAID->value]);
|
||||
$this->assertNull($other->fresh()->vat_number);
|
||||
}
|
||||
|
||||
public function test_admin_can_issue_and_configure_numbering(): void
|
||||
{
|
||||
$admin = $this->admin();
|
||||
$invoice = $this->invoice([['vps', 100_000]]);
|
||||
|
||||
$this->actingAs($admin, 'admin')->putJson('/api/v1/administrator/vat-numbering', [
|
||||
'serial' => '1c26tcp', 'next_number' => 10, 'padding' => 6, 'auto_issue' => false,
|
||||
])->assertOk()->assertJsonPath('data.serial', '1C26TCP');
|
||||
|
||||
$this->actingAs($admin, 'admin')->postJson("/api/v1/administrator/invoices/{$invoice->id}/vat/issue")
|
||||
->assertOk()->assertJsonPath('data.vat_number', '000010')->assertJsonPath('data.vat_serial', '1C26TCP');
|
||||
|
||||
$this->actingAs($admin, 'admin')->postJson("/api/v1/administrator/invoices/{$invoice->id}/vat/issue")
|
||||
->assertStatus(422);
|
||||
|
||||
$this->actingAs($admin, 'admin')->putJson('/api/v1/administrator/vat-numbering', [
|
||||
'serial' => '1C26TCP', 'next_number' => 10, 'padding' => 6, 'auto_issue' => false,
|
||||
])->assertStatus(422);
|
||||
}
|
||||
|
||||
public function test_invoice_notification_email_carries_lookup_code(): void
|
||||
{
|
||||
$this->seed(\Database\Seeders\TemplateSeeder::class);
|
||||
$invoice = $this->invoice([['vps', 100_000]]);
|
||||
|
||||
$html = InvoiceNotificationMail::forInvoice($invoice->load('customer'))->render();
|
||||
|
||||
$this->assertStringContainsString($invoice->lookup_code, $html);
|
||||
$this->assertStringContainsString('/tra-cuu-hoa-don', $html);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Api\Client;
|
||||
|
||||
use App\Models\Customer;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class BillingProfileTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function as(Customer $customer)
|
||||
{
|
||||
return $this->actingAs($customer, 'client')->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
|
||||
}
|
||||
|
||||
public function test_customer_saves_and_reads_own_billing_profile(): void
|
||||
{
|
||||
$customer = Customer::factory()->create(['status' => 1]);
|
||||
|
||||
$this->as($customer)->putJson('/v1/client/billing-profile', [
|
||||
'invoice_company' => 'Cong ty ABC',
|
||||
'tax_code' => '0312345678-001',
|
||||
'invoice_address' => '99 Nguyen Hue',
|
||||
'invoice_email' => 'ketoan@abc.vn',
|
||||
])->assertOk();
|
||||
|
||||
$this->as($customer)->getJson('/v1/client/billing-profile')
|
||||
->assertOk()
|
||||
->assertJsonPath('data.tax_code', '0312345678-001');
|
||||
}
|
||||
|
||||
public function test_invalid_tax_code_and_missing_company_are_rejected(): void
|
||||
{
|
||||
$customer = Customer::factory()->create(['status' => 1]);
|
||||
|
||||
$this->as($customer)->putJson('/v1/client/billing-profile', ['invoice_company' => 'X', 'tax_code' => '123'])
|
||||
->assertStatus(422)->assertJsonValidationErrors('tax_code');
|
||||
$this->as($customer)->putJson('/v1/client/billing-profile', ['tax_code' => '0312345678'])
|
||||
->assertStatus(422)->assertJsonValidationErrors('invoice_company');
|
||||
}
|
||||
|
||||
public function test_empty_payload_clears_profile(): void
|
||||
{
|
||||
$customer = Customer::factory()->create(['status' => 1, 'tax_code' => '0312345678', 'invoice_company' => 'ABC']);
|
||||
|
||||
$this->as($customer)->putJson('/v1/client/billing-profile', [])->assertOk();
|
||||
|
||||
$this->assertNull($customer->fresh()->tax_code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Api\Client;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\InvoiceItem;
|
||||
use App\Support\InvoiceBuyer;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvoiceLookupTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Invoice $invoice;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$customer = Customer::factory()->create([
|
||||
'fullname' => 'Nguyen Van A',
|
||||
'address' => '1 Le Loi',
|
||||
'invoice_company' => 'Cong ty ABC',
|
||||
'tax_code' => '0312345678',
|
||||
'invoice_address' => '99 Nguyen Hue',
|
||||
]);
|
||||
|
||||
$this->invoice = Invoice::create([
|
||||
'invoice_number' => 'INV-LOOKUP-1',
|
||||
'customer_id' => $customer->id,
|
||||
'invoice_type' => 1,
|
||||
'sub_total' => 100_000,
|
||||
'tax' => 10_000,
|
||||
'total' => 110_000,
|
||||
'status' => InvoiceStatus::PAID->value,
|
||||
]);
|
||||
InvoiceItem::create([
|
||||
'invoice_id' => $this->invoice->id,
|
||||
'type' => 'service',
|
||||
'description' => 'VPS 1 thang',
|
||||
'months' => 1,
|
||||
'quantity' => 1,
|
||||
'unit_price' => 100_000,
|
||||
'total_price' => 100_000,
|
||||
]);
|
||||
}
|
||||
|
||||
private function lookup(string $uri, array $body)
|
||||
{
|
||||
return $this->withHeaders(['x-access-token' => $this->buildClientAccessToken()])->postJson($uri, $body);
|
||||
}
|
||||
|
||||
public function test_lookup_code_is_generated_on_create(): void
|
||||
{
|
||||
$this->assertMatchesRegularExpression('/^[A-Z0-9]{10}$/', $this->invoice->lookup_code);
|
||||
}
|
||||
|
||||
public function test_correct_code_returns_limited_payload(): void
|
||||
{
|
||||
$response = $this->lookup('/v1/invoice-lookup', [
|
||||
'invoice_number' => 'INV-LOOKUP-1',
|
||||
'lookup_code' => strtolower($this->invoice->lookup_code),
|
||||
])->assertOk();
|
||||
|
||||
$response->assertJsonPath('data.total', 110_000)
|
||||
->assertJsonPath('data.buyer.tax_code', '0312345678')
|
||||
->assertJsonPath('data.buyer.company', 'Cong ty ABC');
|
||||
|
||||
$body = json_encode($response->json());
|
||||
$this->assertStringNotContainsString('Nguyen Van A', $body);
|
||||
$this->assertStringNotContainsString('99 Nguyen Hue', $body);
|
||||
$this->assertStringNotContainsString($this->invoice->lookup_code, $body);
|
||||
}
|
||||
|
||||
public function test_wrong_code_or_unknown_number_is_404(): void
|
||||
{
|
||||
$this->lookup('/v1/invoice-lookup', ['invoice_number' => 'INV-LOOKUP-1', 'lookup_code' => 'WRONGCODE1'])->assertNotFound();
|
||||
$this->lookup('/v1/invoice-lookup', ['invoice_number' => 'INV-NOPE', 'lookup_code' => $this->invoice->lookup_code])->assertNotFound();
|
||||
$this->lookup('/v1/invoice-lookup/pdf', ['invoice_number' => 'INV-LOOKUP-1', 'lookup_code' => 'WRONGCODE1'])->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_cancelled_invoice_is_not_found(): void
|
||||
{
|
||||
$this->invoice->update(['status' => InvoiceStatus::CANCELLED->value]);
|
||||
|
||||
$this->lookup('/v1/invoice-lookup', [
|
||||
'invoice_number' => 'INV-LOOKUP-1',
|
||||
'lookup_code' => $this->invoice->lookup_code,
|
||||
])->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_pdf_is_returned_for_correct_code(): void
|
||||
{
|
||||
$response = $this->lookup('/v1/invoice-lookup/pdf', [
|
||||
'invoice_number' => 'INV-LOOKUP-1',
|
||||
'lookup_code' => $this->invoice->lookup_code,
|
||||
])->assertOk();
|
||||
|
||||
$this->assertSame('application/pdf', $response->headers->get('Content-Type'));
|
||||
$this->assertStringStartsWith('%PDF', $response->getContent());
|
||||
}
|
||||
|
||||
public function test_requires_client_access_token(): void
|
||||
{
|
||||
$this->postJson('/v1/invoice-lookup', ['invoice_number' => 'INV-LOOKUP-1', 'lookup_code' => $this->invoice->lookup_code])
|
||||
->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_throttles_repeated_guesses_for_one_invoice(): void
|
||||
{
|
||||
for ($i = 0; $i < 10; $i++) {
|
||||
$this->lookup('/v1/invoice-lookup', ['invoice_number' => 'INV-LOOKUP-1', 'lookup_code' => 'GUESS' . $i])->assertNotFound();
|
||||
}
|
||||
|
||||
$this->lookup('/v1/invoice-lookup', ['invoice_number' => 'INV-LOOKUP-1', 'lookup_code' => $this->invoice->lookup_code])
|
||||
->assertStatus(429);
|
||||
}
|
||||
|
||||
public function test_buyer_snapshot_freezes_buyer_after_vat_is_recorded(): void
|
||||
{
|
||||
$this->invoice->update(['buyer_snapshot' => InvoiceBuyer::fromCustomer($this->invoice->customer)]);
|
||||
$this->invoice->customer->update(['tax_code' => '0999999999']);
|
||||
|
||||
$this->assertSame('0312345678', InvoiceBuyer::forInvoice($this->invoice->fresh())['tax_code']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Api\Client;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\Order;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class OrderInvoicesTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Customer $customer;
|
||||
private Order $order;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->customer = Customer::factory()->create(['status' => 1]);
|
||||
$this->order = Order::create(['order_num' => 'ORD-TEST', 'customer_id' => $this->customer->id, 'total' => 100_000, 'status' => 1]);
|
||||
|
||||
foreach ([['INV-FIRST', 1, InvoiceStatus::PAID], ['INV-RENEW', 2, InvoiceStatus::UNPAID]] as [$number, $type, $status]) {
|
||||
Invoice::create([
|
||||
'invoice_number' => $number, 'customer_id' => $this->customer->id, 'order_id' => $this->order->id,
|
||||
'invoice_type' => $type, 'sub_total' => 100_000, 'tax' => 0, 'total' => 100_000, 'status' => $status->value,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function as(): static
|
||||
{
|
||||
return $this->actingAs($this->customer, 'client')->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
|
||||
}
|
||||
|
||||
public function test_order_detail_lists_every_invoice_with_payable_flag_and_pay_url(): void
|
||||
{
|
||||
$response = $this->as()->getJson('/v1/client/orders/num/ORD-TEST')->assertOk();
|
||||
|
||||
$response->assertJsonCount(2, 'data.invoices')
|
||||
->assertJsonPath('data.invoices.0.invoice_number', 'INV-RENEW')
|
||||
->assertJsonPath('data.invoices.0.payable', true)
|
||||
->assertJsonPath('data.invoices.0.type_text', 'Gia hạn')
|
||||
->assertJsonPath('data.invoices.0.payment_url', '/hoa-don/ORD-TEST?invoice=INV-RENEW')
|
||||
->assertJsonPath('data.invoices.1.payable', false)
|
||||
->assertJsonPath('data.invoices.1.payment_url', '/hoa-don/ORD-TEST');
|
||||
}
|
||||
|
||||
public function test_invoice_page_can_target_a_renewal_invoice_of_the_order(): void
|
||||
{
|
||||
$this->as()->getJson('/v1/client/invoices/order/ORD-TEST')
|
||||
->assertOk()
|
||||
->assertJsonPath('data.invoice_number', 'INV-FIRST')
|
||||
->assertJsonPath('data.order.order_num', 'ORD-TEST')
|
||||
->assertJsonPath('data.order.status', 1)
|
||||
->assertJsonPath('data.order.status_text', 'Đã kích hoạt')
|
||||
->assertJsonPath('data.order.total', 100_000);
|
||||
|
||||
$this->as()->getJson('/v1/client/invoices/order/ORD-TEST?invoice=INV-RENEW')
|
||||
->assertOk()->assertJsonPath('data.invoice_number', 'INV-RENEW');
|
||||
|
||||
$this->as()->getJson('/v1/client/invoices/order/ORD-TEST?invoice=INV-OTHER')->assertNotFound();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Api\Service;
|
||||
|
||||
use App\Enums\Order\OrderStatus;
|
||||
use App\Models\Coupon;
|
||||
use App\Models\CouponRedemption;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Order;
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductPricings;
|
||||
use App\Services\Api\Order\OrderService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Bus;
|
||||
use Illuminate\Testing\TestResponse;
|
||||
use Tests\TestCase;
|
||||
|
||||
class CouponOrderTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Customer $customer;
|
||||
private Product $product;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->customer = Customer::factory()->create(['total' => 10_000_000]);
|
||||
$this->product = Product::factory()->create(['product_type' => 'vps', 'is_active' => true]);
|
||||
|
||||
ProductPricings::create([
|
||||
'product_id' => $this->product->id,
|
||||
'billing_cycle' => 'monthly',
|
||||
'price' => 100_000,
|
||||
'is_active' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
private function coupon(array $overrides = []): Coupon
|
||||
{
|
||||
return Coupon::create(array_merge([
|
||||
'code' => 'SALE10',
|
||||
'type' => Coupon::TYPE_PERCENT,
|
||||
'value' => 10,
|
||||
'applies_to' => Coupon::APPLIES_NEW,
|
||||
'is_active' => true,
|
||||
], $overrides));
|
||||
}
|
||||
|
||||
private function as(Customer $customer): static
|
||||
{
|
||||
return $this->actingAs($customer, 'client')
|
||||
->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
|
||||
}
|
||||
|
||||
private function order(string $code, array $extra = [], ?Customer $customer = null): TestResponse
|
||||
{
|
||||
return $this->as($customer ?? $this->customer)->postJson('/v1/orders', array_merge([
|
||||
'product_id' => $this->product->uuid,
|
||||
'billing_cycle' => 'monthly',
|
||||
'coupon_code' => $code,
|
||||
], $extra));
|
||||
}
|
||||
|
||||
public function test_preview_returns_discount_capped_by_max_discount(): void
|
||||
{
|
||||
$this->coupon(['value' => 50, 'max_discount' => 20_000]);
|
||||
|
||||
$this->as($this->customer)->postJson('/v1/orders/coupon-preview', [
|
||||
'product_id' => $this->product->uuid,
|
||||
'billing_cycle' => 'monthly',
|
||||
'coupon_code' => ' sale10 ',
|
||||
])->assertOk()
|
||||
->assertJsonPath('data.discount', 20_000)
|
||||
->assertJsonPath('data.total', 80_000);
|
||||
}
|
||||
|
||||
public function test_order_stores_discount_on_order_invoice_and_charges_discounted_total(): void
|
||||
{
|
||||
Bus::fake();
|
||||
$this->coupon();
|
||||
|
||||
$response = $this->order('SALE10', ['discount_amount' => 99_999, 'total' => 1, 'price' => 1])
|
||||
->assertCreated();
|
||||
|
||||
$order = Order::where('order_num', $response->json('data.order.order_num'))->firstOrFail();
|
||||
$this->assertSame(100_000, (int) $order->sub_total);
|
||||
$this->assertSame(10_000, (int) $order->discount_amount);
|
||||
$this->assertSame(90_000, (int) $order->total);
|
||||
$this->assertSame('SALE10', $order->coupon_code);
|
||||
$this->assertSame(10_000, (int) $order->invoice->discount_amount);
|
||||
$this->assertSame(90_000, (int) $order->invoice->total);
|
||||
$this->assertSame(100_000, (int) $order->invoice->sub_total);
|
||||
$this->assertSame('SALE10', $order->invoice->coupon_code);
|
||||
$this->assertSame(1, CouponRedemption::where('order_id', $order->id)->whereNull('released_at')->count());
|
||||
|
||||
app(OrderService::class)->pay($order->fresh(['invoice', 'customer']), 'balance');
|
||||
$this->assertSame(10_000_000 - 90_000, $this->customer->fresh()->total);
|
||||
}
|
||||
|
||||
public function test_client_cannot_override_price_without_coupon(): void
|
||||
{
|
||||
Bus::fake();
|
||||
|
||||
$response = $this->order('', ['coupon_code' => null, 'discount_amount' => 50_000, 'total' => 1])->assertCreated();
|
||||
|
||||
$order = Order::where('order_num', $response->json('data.order.order_num'))->firstOrFail();
|
||||
$this->assertSame(0, (int) $order->discount_amount);
|
||||
$this->assertSame(100_000, (int) $order->total);
|
||||
}
|
||||
|
||||
public function test_expired_and_not_started_and_inactive_codes_are_rejected(): void
|
||||
{
|
||||
$this->coupon(['code' => 'OLD', 'ends_at' => now()->subDay()]);
|
||||
$this->coupon(['code' => 'SOON', 'starts_at' => now()->addDay()]);
|
||||
$this->coupon(['code' => 'OFF', 'is_active' => false]);
|
||||
|
||||
foreach (['OLD', 'SOON', 'OFF', 'MISSING'] as $code) {
|
||||
$this->order($code)->assertStatus(422);
|
||||
}
|
||||
$this->assertSame(0, Order::count());
|
||||
}
|
||||
|
||||
public function test_scope_and_minimum_order_are_enforced(): void
|
||||
{
|
||||
$this->coupon(['code' => 'HOST', 'product_types' => ['hosting']]);
|
||||
$this->coupon(['code' => 'CYCLE', 'billing_cycles' => ['annually']]);
|
||||
$this->coupon(['code' => 'BIG', 'min_order' => 500_000]);
|
||||
$this->coupon(['code' => 'RENEW', 'applies_to' => Coupon::APPLIES_RENEWAL]);
|
||||
$this->coupon(['code' => 'OTHERPROD', 'product_ids' => [$this->product->id + 999]]);
|
||||
|
||||
foreach (['HOST', 'CYCLE', 'BIG', 'RENEW', 'OTHERPROD'] as $code) {
|
||||
$this->order($code)->assertStatus(422);
|
||||
}
|
||||
$this->assertSame(0, Order::count());
|
||||
}
|
||||
|
||||
public function test_usage_limit_is_enforced_across_customers(): void
|
||||
{
|
||||
Bus::fake();
|
||||
$this->coupon(['usage_limit' => 1]);
|
||||
$other = Customer::factory()->create(['total' => 10_000_000]);
|
||||
|
||||
$this->order('SALE10')->assertCreated();
|
||||
$this->order('SALE10', [], $other)->assertStatus(422)
|
||||
->assertJsonPath('message', 'Mã giảm giá đã hết lượt sử dụng.');
|
||||
}
|
||||
|
||||
public function test_per_customer_limit_is_enforced(): void
|
||||
{
|
||||
Bus::fake();
|
||||
$this->coupon(['per_customer_limit' => 1]);
|
||||
|
||||
$first = $this->order('SALE10')->assertCreated();
|
||||
Order::where('order_num', $first->json('data.order.order_num'))->update(['status' => OrderStatus::ACTIVE->value]);
|
||||
|
||||
$this->order('SALE10')->assertStatus(422)
|
||||
->assertJsonPath('message', 'Bạn đã dùng hết số lần cho phép của mã giảm giá này.');
|
||||
}
|
||||
|
||||
public function test_cancelling_order_releases_redemption_and_restoring_reclaims_it(): void
|
||||
{
|
||||
Bus::fake();
|
||||
$this->coupon(['usage_limit' => 1]);
|
||||
|
||||
$response = $this->order('SALE10')->assertCreated();
|
||||
$order = Order::where('order_num', $response->json('data.order.order_num'))->firstOrFail();
|
||||
|
||||
$order->update(['status' => OrderStatus::CANCELLED->value]);
|
||||
$this->assertNotNull(CouponRedemption::where('order_id', $order->id)->value('released_at'));
|
||||
|
||||
$order->update(['status' => OrderStatus::PENDING->value]);
|
||||
$this->assertNull(CouponRedemption::where('order_id', $order->id)->value('released_at'));
|
||||
}
|
||||
|
||||
public function test_discount_never_drops_total_below_minimum_payable(): void
|
||||
{
|
||||
Bus::fake();
|
||||
$this->coupon(['code' => 'FREE', 'type' => Coupon::TYPE_FIXED, 'value' => 5_000_000]);
|
||||
|
||||
$this->order('FREE')->assertCreated();
|
||||
|
||||
$this->assertSame(1_000, (int) Order::first()->invoice->total);
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ class RenewServiceTest extends TestCase
|
||||
$this->customer = Customer::factory()->create(['total' => 100_000]);
|
||||
$product = Product::factory()->create(['product_type' => 'hosting', 'is_active' => true]);
|
||||
ProductPricings::create(['product_id' => $product->id, 'billing_cycle' => 'monthly', 'price' => 15_000, 'is_active' => true]);
|
||||
ProductPricings::create(['product_id' => $product->id, 'billing_cycle' => 'quarterly', 'price' => 40_000, 'is_active' => true]);
|
||||
|
||||
$this->order = Order::create([
|
||||
'order_num' => 'ORD-RENEW-TEST',
|
||||
@@ -75,11 +76,11 @@ class RenewServiceTest extends TestCase
|
||||
$invoice = Invoice::where('invoice_type', 2)->sole();
|
||||
$this->assertSame($this->order->id, (int) $invoice->order_id);
|
||||
$this->assertSame(InvoiceStatus::PAID->value, (int) $invoice->status);
|
||||
$this->assertSame(45_000, (int) $invoice->total);
|
||||
$this->assertSame(55_000, (int) $this->customer->fresh()->total);
|
||||
$this->assertSame(40_000, (int) $invoice->total);
|
||||
$this->assertSame(60_000, (int) $this->customer->fresh()->total);
|
||||
$this->assertSame(1, Order::count());
|
||||
$this->assertTrue($this->service->fresh()->expires_at->isSameDay($expiresAt->addMonths(3)));
|
||||
$this->assertDatabaseHas('transactions', ['customer_id' => $this->customer->id, 'amount' => 45_000]);
|
||||
$this->assertDatabaseHas('transactions', ['customer_id' => $this->customer->id, 'amount' => 40_000]);
|
||||
}
|
||||
|
||||
public function test_insufficient_balance_keeps_unpaid_invoice_and_does_not_extend(): void
|
||||
@@ -93,12 +94,18 @@ class RenewServiceTest extends TestCase
|
||||
$this->assertTrue($this->service->fresh()->expires_at->equalTo($expiresAt));
|
||||
|
||||
$this->customer->update(['total' => 100_000]);
|
||||
$this->renew(2)->assertOk();
|
||||
$this->renew(3)->assertOk();
|
||||
|
||||
$invoice = Invoice::where('invoice_type', 2)->sole();
|
||||
$this->assertSame(InvoiceStatus::PAID->value, (int) $invoice->status);
|
||||
$this->assertSame(30_000, (int) $invoice->total);
|
||||
$this->assertSame(40_000, (int) $invoice->total);
|
||||
$this->assertSame(1, $invoice->invoiceItems()->count());
|
||||
$this->assertSame(70_000, (int) $this->customer->fresh()->total);
|
||||
$this->assertSame(60_000, (int) $this->customer->fresh()->total);
|
||||
}
|
||||
|
||||
public function test_months_without_a_priced_cycle_are_rejected(): void
|
||||
{
|
||||
$this->renew(2)->assertStatus(422);
|
||||
$this->assertSame(0, Invoice::where('invoice_type', 2)->count());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,4 +173,86 @@ class ServiceExpiryTest extends TestCase
|
||||
$invoice = Invoice::find($service->refresh()->invoice_id);
|
||||
$this->assertSame(90_000, (int) $invoice->total);
|
||||
}
|
||||
|
||||
public function test_auto_renew_service_is_paid_from_balance_and_extended(): void
|
||||
{
|
||||
$service = $this->createExpiringService(90_000);
|
||||
$service->update(['auto_renew' => true]);
|
||||
$service->customer->update(['total' => 200_000]);
|
||||
$oldExpiry = $service->expires_at->copy();
|
||||
|
||||
$this->artisan('service:expiry')->assertExitCode(0);
|
||||
|
||||
$service->refresh();
|
||||
$this->assertSame(InvoiceStatus::PAID->value, Invoice::find($service->invoice_id)->status);
|
||||
$this->assertTrue($service->expires_at->greaterThan($oldExpiry));
|
||||
$this->assertSame(110_000, (int) $service->customer->fresh()->total);
|
||||
|
||||
$log = \App\Models\ActivityLog::where('subject_id', $service->id)->where('event', 'renewed')->first();
|
||||
$this->assertSame('system', $log->causer_type);
|
||||
$this->assertSame('balance', $log->new_values['payment_method']);
|
||||
}
|
||||
|
||||
public function test_auto_renew_with_insufficient_balance_keeps_invoice_unpaid_and_retries_after_topup(): void
|
||||
{
|
||||
$service = $this->createExpiringService(90_000);
|
||||
$service->update(['auto_renew' => true]);
|
||||
$service->customer->update(['total' => 10_000]);
|
||||
|
||||
$this->artisan('service:expiry')->assertExitCode(0);
|
||||
$this->assertSame(InvoiceStatus::UNPAID->value, Invoice::find($service->refresh()->invoice_id)->status);
|
||||
$this->assertSame(10_000, (int) $service->customer->fresh()->total);
|
||||
|
||||
$service->customer->update(['total' => 100_000]);
|
||||
$this->artisan('service:expiry')->assertExitCode(0);
|
||||
$this->assertSame(InvoiceStatus::PAID->value, Invoice::find($service->invoice_id)->status);
|
||||
}
|
||||
|
||||
public function test_service_without_auto_renew_is_not_charged(): void
|
||||
{
|
||||
$service = $this->createExpiringService(90_000);
|
||||
$service->customer->update(['total' => 200_000]);
|
||||
|
||||
$this->artisan('service:expiry')->assertExitCode(0);
|
||||
|
||||
$this->assertSame(InvoiceStatus::UNPAID->value, Invoice::find($service->refresh()->invoice_id)->status);
|
||||
$this->assertSame(200_000, (int) $service->customer->fresh()->total);
|
||||
}
|
||||
|
||||
public function test_renewal_invoice_creates_customer_notification_and_queues_email(): void
|
||||
{
|
||||
\Illuminate\Support\Facades\Queue::fake();
|
||||
\Illuminate\Support\Facades\DB::table('setting')->updateOrInsert(['key' => 'email_settings'], ['value' => json_encode(['auto_disabled' => []])]);
|
||||
$service = $this->createExpiringService(90_000);
|
||||
|
||||
$this->artisan('service:expiry')->assertExitCode(0);
|
||||
|
||||
$invoice = Invoice::find($service->refresh()->invoice_id);
|
||||
$notification = \App\Models\Notification::where('recipient_type', 'client')
|
||||
->where('recipient_id', $service->customer_id)->first();
|
||||
$this->assertNotNull($notification);
|
||||
$this->assertSame('renewal_invoice', $notification->type);
|
||||
$this->assertStringContainsString($invoice->invoice_number, $notification->body);
|
||||
$this->assertStringContainsString('?invoice=' . $invoice->invoice_number, $notification->link);
|
||||
|
||||
\Illuminate\Support\Facades\Queue::assertPushed(
|
||||
\App\Jobs\Mail\SendInvoiceMailJob::class,
|
||||
fn ($job) => $job->invoiceId === $invoice->id && $job->type === 'renewal',
|
||||
);
|
||||
|
||||
$this->artisan('service:expiry')->assertExitCode(0);
|
||||
$this->assertSame(1, \App\Models\Notification::where('recipient_id', $service->customer_id)->count());
|
||||
}
|
||||
|
||||
public function test_email_is_skipped_when_invoice_notification_is_auto_disabled(): void
|
||||
{
|
||||
\Illuminate\Support\Facades\Queue::fake();
|
||||
\Illuminate\Support\Facades\DB::table('setting')->updateOrInsert(['key' => 'email_settings'], ['value' => json_encode(['auto_disabled' => ['invoice_notification']])]);
|
||||
$service = $this->createExpiringService(90_000);
|
||||
|
||||
$this->artisan('service:expiry')->assertExitCode(0);
|
||||
|
||||
$this->assertSame(1, \App\Models\Notification::where('recipient_id', $service->customer_id)->count());
|
||||
\Illuminate\Support\Facades\Queue::assertNotPushed(\App\Jobs\Mail\SendInvoiceMailJob::class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Console;
|
||||
|
||||
use App\Mail\AutoRenewFailedMail;
|
||||
use App\Models\Customer;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Models\Notification;
|
||||
use App\Models\Order;
|
||||
use App\Models\OrderItem;
|
||||
use App\Models\Product;
|
||||
use App\Models\Service;
|
||||
use App\Models\Setting;
|
||||
use Database\Seeders\TemplateSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ServiceExpiryUnificationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function service(array $attributes = [], int $balance = 0): Service
|
||||
{
|
||||
$customer = Customer::factory()->create(['total' => $balance]);
|
||||
$product = Product::factory()->create(['product_type' => 'hosting', 'is_active' => true]);
|
||||
$order = Order::create([
|
||||
'order_num' => 'ORD-' . uniqid(),
|
||||
'customer_id' => $customer->id,
|
||||
'sub_total' => 90_000,
|
||||
'total' => 90_000,
|
||||
'status' => 1,
|
||||
]);
|
||||
$item = OrderItem::create([
|
||||
'order_id' => $order->id,
|
||||
'product_id' => $product->id,
|
||||
'billing_cycle' => 'monthly',
|
||||
'months' => 1,
|
||||
'quantity' => 1,
|
||||
'price' => 90_000,
|
||||
]);
|
||||
|
||||
return Service::create($attributes + [
|
||||
'customer_id' => $customer->id,
|
||||
'product_id' => $product->id,
|
||||
'order_item_id' => $item->id,
|
||||
'status' => 'active',
|
||||
'server_name' => 'srv',
|
||||
'expires_at' => now()->addDays(3),
|
||||
]);
|
||||
}
|
||||
|
||||
private function vmFor(Service $service, ?int $dueDate): ModuleVmware
|
||||
{
|
||||
$vm = ModuleVmware::create([
|
||||
'name' => 'vm-' . uniqid(),
|
||||
'customer_id' => $service->customer_id,
|
||||
'next_due_date' => $dueDate,
|
||||
]);
|
||||
$service->update(['vm_id' => $vm->id]);
|
||||
|
||||
return $vm;
|
||||
}
|
||||
|
||||
public function test_changing_service_expiry_moves_vmware_due_date(): void
|
||||
{
|
||||
$service = $this->service();
|
||||
$vm = $this->vmFor($service, 1);
|
||||
|
||||
$newExpiry = now()->addMonths(2)->startOfSecond();
|
||||
$service->update(['expires_at' => $newExpiry]);
|
||||
|
||||
$this->assertSame($newExpiry->timestamp, (int) $vm->fresh()->next_due_date);
|
||||
}
|
||||
|
||||
public function test_reconcile_is_idempotent_and_dry_run_writes_nothing(): void
|
||||
{
|
||||
$service = $this->service();
|
||||
$vm = $this->vmFor($service, null);
|
||||
ModuleVmware::whereKey($vm->id)->update(['next_due_date' => 1]);
|
||||
|
||||
$this->artisan('service:reconcile-expiry', ['--dry-run' => true])->assertExitCode(0);
|
||||
$this->assertSame(1, (int) $vm->fresh()->next_due_date);
|
||||
|
||||
$this->artisan('service:reconcile-expiry')->assertExitCode(0);
|
||||
$this->assertSame($service->fresh()->expires_at->timestamp, (int) $vm->fresh()->next_due_date);
|
||||
|
||||
$before = $vm->fresh()->updated_at;
|
||||
$this->artisan('service:reconcile-expiry')->expectsOutputToContain('lệch module_vmware: 0')->assertExitCode(0);
|
||||
$this->assertEquals($before, $vm->fresh()->updated_at);
|
||||
}
|
||||
|
||||
public function test_reconcile_backfills_service_expiry_from_legacy_vm(): void
|
||||
{
|
||||
$service = $this->service(['expires_at' => null]);
|
||||
$due = now()->addDays(20)->startOfSecond();
|
||||
$this->vmFor($service, $due->timestamp);
|
||||
|
||||
$this->artisan('service:reconcile-expiry')->assertExitCode(0);
|
||||
|
||||
$this->assertSame($due->timestamp, $service->fresh()->expires_at->timestamp);
|
||||
}
|
||||
|
||||
public function test_auto_renew_without_balance_notifies_once_per_day(): void
|
||||
{
|
||||
Mail::fake();
|
||||
$this->seed(TemplateSeeder::class);
|
||||
$service = $this->service(['auto_renew' => true], balance: 1_000);
|
||||
|
||||
$this->artisan('service:expiry')->assertExitCode(0);
|
||||
$this->artisan('service:expiry')->assertExitCode(0);
|
||||
|
||||
Mail::assertQueued(AutoRenewFailedMail::class, 1);
|
||||
$this->assertSame(1, Notification::where('type', 'auto_renew_failed')->where('recipient_id', $service->customer_id)->count());
|
||||
$this->assertNotNull($service->fresh()->invoice_id);
|
||||
$this->assertSame(1_000, (int) $service->customer->fresh()->total);
|
||||
}
|
||||
|
||||
public function test_auto_renew_failure_mail_respects_auto_email_gate(): void
|
||||
{
|
||||
Mail::fake();
|
||||
$this->seed(TemplateSeeder::class);
|
||||
Setting::updateOrCreate(['key' => 'email_settings'], ['value' => json_encode(['auto_disabled' => ['auto_renew_failed']])]);
|
||||
$service = $this->service(['auto_renew' => true], balance: 0);
|
||||
|
||||
$this->artisan('service:expiry')->assertExitCode(0);
|
||||
|
||||
Mail::assertNotQueued(AutoRenewFailedMail::class);
|
||||
$this->assertSame(1, Notification::where('type', 'auto_renew_failed')->where('recipient_id', $service->customer_id)->count());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Helpers\OrderHelper;
|
||||
use App\Support\BillingCycleCatalog;
|
||||
use App\Support\ProductBillingCycles;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class CustomBillingCycleTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_custom_cycle_is_resolved_end_to_end(): void
|
||||
{
|
||||
$this->assertSame([], BillingCycleCatalog::customMonths());
|
||||
|
||||
BillingCycleCatalog::saveCustomMonths([60, 12, 60, 0, 9999]);
|
||||
|
||||
$this->assertSame([60], BillingCycleCatalog::customMonths());
|
||||
$this->assertContains('months_60', BillingCycleCatalog::codes());
|
||||
$this->assertSame(60, OrderHelper::cycleToMonths('months_60'));
|
||||
$this->assertSame('5 năm', BillingCycleCatalog::labelForCode('months_60'));
|
||||
$this->assertContains('months_60', ProductBillingCycles::forType('vps'));
|
||||
$this->assertSame(['annually'], ProductBillingCycles::forType('domain'));
|
||||
}
|
||||
|
||||
public function test_unknown_code_is_rejected(): void
|
||||
{
|
||||
$this->expectException(\InvalidArgumentException::class);
|
||||
OrderHelper::cycleToMonths('months_x');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Mail;
|
||||
|
||||
use App\Jobs\Mail\Customer\HostingAccountCreatedJob;
|
||||
use App\Mail\Customer\HostingAccountCreated;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Invoice;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Tests\TestCase;
|
||||
|
||||
class HostingAccountCreatedInvoiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function payload(array $extra = []): array
|
||||
{
|
||||
return $extra + ['customer_email' => 'khach@example.test', 'customer_name' => 'Khach', 'domain_name' => 'baodev111.net'];
|
||||
}
|
||||
|
||||
public function test_hosting_ready_email_attaches_the_order_invoice(): void
|
||||
{
|
||||
Mail::fake();
|
||||
$invoice = Invoice::create([
|
||||
'invoice_number' => 'INV-HOST-1', 'customer_id' => Customer::factory()->create()->id,
|
||||
'invoice_type' => 1, 'sub_total' => 100_000, 'tax' => 0, 'total' => 100_000, 'status' => 2,
|
||||
]);
|
||||
|
||||
(new HostingAccountCreatedJob($this->payload(['invoice_id' => $invoice->id])))->handle();
|
||||
|
||||
Mail::assertSent(HostingAccountCreated::class, fn (HostingAccountCreated $mail) => $mail->invoicePdfFileName === 'Hoa-don-INV-HOST-1.pdf'
|
||||
&& str_starts_with((string) $mail->invoicePdf, '%PDF')
|
||||
&& count($mail->attachments()) === 1);
|
||||
}
|
||||
|
||||
public function test_email_still_sent_without_invoice(): void
|
||||
{
|
||||
Mail::fake();
|
||||
|
||||
(new HostingAccountCreatedJob($this->payload()))->handle();
|
||||
|
||||
Mail::assertSent(HostingAccountCreated::class, fn (HostingAccountCreated $mail) => $mail->attachments() === []);
|
||||
}
|
||||
|
||||
public function test_domain_order_received_email_attaches_the_invoice(): void
|
||||
{
|
||||
$invoice = Invoice::create([
|
||||
'invoice_number' => 'INV-DOM-1', 'customer_id' => Customer::factory()->create()->id,
|
||||
'invoice_type' => 1, 'sub_total' => 100_000, 'tax' => 0, 'total' => 100_000, 'status' => 2,
|
||||
]);
|
||||
|
||||
$attachments = (new \App\Mail\Customer\DomainOrderReceivedNotification(['invoice_id' => $invoice->id]))->attachments();
|
||||
|
||||
$this->assertCount(1, $attachments);
|
||||
$this->assertCount(0, (new \App\Mail\Customer\DomainOrderReceivedNotification([]))->attachments());
|
||||
}
|
||||
|
||||
public function test_subject_uses_company_server_and_customer_name_with_fallbacks(): void
|
||||
{
|
||||
$this->seed(\Database\Seeders\TemplateSeeder::class);
|
||||
$subject = fn (array $data) => (new HostingAccountCreated($data + ['server_name' => 'HOST-01']))->envelope()->subject;
|
||||
|
||||
$this->assertSame('V/v: '.\App\Support\MailGlobals::values()['company_name'].' gửi thông tin truy cập - HOST-01 - Nguyen Van A', $subject(['customer_name' => 'Nguyen Van A']));
|
||||
$this->assertStringEndsWith(' - Cong ty ABC', $subject(['customer_name' => ' ', 'customer_company' => 'Cong ty ABC']));
|
||||
$this->assertStringEndsWith(' - Công ty', $subject([]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Support\ProductBillingCycles;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ProductBillingCyclesTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_defaults_and_saved_cycles(): void
|
||||
{
|
||||
$this->assertSame(['annually'], ProductBillingCycles::forType('domain'));
|
||||
$this->assertContains('monthly', ProductBillingCycles::forType('vps'));
|
||||
|
||||
ProductBillingCycles::save(['hosting' => ['monthly', 'annually'], 'domain' => ['annually', 'biennially']]);
|
||||
|
||||
$this->assertSame(['monthly', 'annually'], ProductBillingCycles::forType('hosting'));
|
||||
$this->assertTrue(ProductBillingCycles::allows('domain', 'biennially'));
|
||||
$this->assertFalse(ProductBillingCycles::allows('hosting', 'quarterly'));
|
||||
$this->assertTrue(ProductBillingCycles::allows('hosting', 'onetime'));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user