feat: khởi tạo/huỷ domain Plesk qua job, gửi mail hoá đơn qua queue, đính kèm triển khai

- ProvisionDnsDomainJob/SuspendDnsDomainJob: tạo domain admin lên Plesk, huỷ = suspend (is_created=3)
- Khách xem zone DNS được gán ở /dich-vu/domain, quản lý bản ghi A/AAAA/CNAME/TXT/MX/SRV
- send-mail hoá đơn đẩy SendInvoiceMailJob, preview + sửa nội dung, ghi mail.order_id
- invoice_attachments.type (payment_proof/deployment)
- CacheService xoá theo SCAN pattern, Redis không persistent mặc định
- Backfill transactions.public_code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
baodev0
2026-10-11 09:56:18 +07:00
co-authored by Claude Opus 5.5
parent 30898ea46f
commit 94614d9cb3
55 changed files with 1190 additions and 236 deletions
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Admin\Customer;
use App\Models\Customer;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class ManualTransactionTest extends TestCase
{
use RefreshDatabase;
public function test_admin_records_and_deletes_a_manual_transaction_without_touching_balance(): void
{
Role::firstOrCreate(['name' => 'Full Administrator', 'guard_name' => 'admin']);
$admin = User::factory()->create();
$admin->assignRole('Full Administrator');
$customer = Customer::factory()->create(['total' => 500000]);
$url = "/api/v1/administrator/customers/{$customer->uuid}/transactions";
$created = $this->actingAs($admin, 'admin')
->postJson($url, ['trans' => 'CK VCB 123', 'amount' => 800000, 'note' => 'Thu tiền mặt'])
->assertCreated()
->json('data');
$this->assertMatchesRegularExpression('/^ADM-\d{8}-[A-Z0-9]{6}$/', $created['public_code']);
$this->assertSame('neutral', $created['direction']);
$this->assertSame(500000, (int) $customer->fresh()->total);
$this->actingAs($admin, 'admin')->getJson($url)->assertJsonCount(1, 'data');
$this->actingAs($admin, 'admin')->deleteJson("{$url}/{$created['id']}")->assertOk();
$this->assertSoftDeleted('transactions', ['id' => $created['id']]);
}
public function test_transaction_created_without_code_gets_one(): void
{
$customer = Customer::factory()->create();
$transaction = Transaction::create(['amount' => 1, 'customer_id' => $customer->id, 'type' => 'transfer', 'status' => 1]);
$this->assertMatchesRegularExpression('/^TXN-\d{8}-[A-Z0-9]{6}$/', $transaction->public_code);
}
public function test_cannot_delete_another_customers_transaction(): void
{
Role::firstOrCreate(['name' => 'Full Administrator', 'guard_name' => 'admin']);
$admin = User::factory()->create();
$admin->assignRole('Full Administrator');
$owner = Customer::factory()->create();
$other = Customer::factory()->create();
$transaction = Transaction::create(['amount' => 1, 'customer_id' => $owner->id, 'type' => 'transfer', 'status' => 1]);
$this->actingAs($admin, 'admin')
->deleteJson("/api/v1/administrator/customers/{$other->uuid}/transactions/{$transaction->id}")
->assertNotFound();
$this->assertNotSoftDeleted('transactions', ['id' => $transaction->id]);
}
}
@@ -0,0 +1,167 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Admin\DnsManager;
use App\Jobs\DnsManager\ProvisionDnsDomainJob;
use App\Jobs\DnsManager\SuspendDnsDomainJob;
use App\Models\DnsDomain;
use App\Models\User;
use App\Services\Plesk\PleskDomainService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Queue;
use Mockery;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class ProvisionDnsDomainTest extends TestCase
{
use RefreshDatabase;
private int $serverId;
protected function setUp(): void
{
parent::setUp();
$this->serverId = DB::table('dns_manager_servers')->insertGetId(['ip_address' => '10.0.0.1', 'password' => 'x']);
}
private function domain(): DnsDomain
{
return DnsDomain::create(['domain_name' => 'example.vn', 'dns_manager_server_id' => $this->serverId, 'is_created' => 0]);
}
private function admin(): User
{
Role::firstOrCreate(['name' => 'Full Administrator', 'guard_name' => 'admin']);
$admin = User::factory()->create();
$admin->assignRole('Full Administrator');
return $admin;
}
public function test_destroy_cancels_domain_and_queues_plesk_suspend(): void
{
Queue::fake();
$domain = $this->domain();
$domain->update(['plesk_id' => 55, 'is_created' => DnsDomain::STATUS_CREATED]);
$customerId = \App\Models\Customer::factory()->create()->id;
$domain->customer()->attach($customerId);
$this->actingAs($this->admin(), 'admin')
->deleteJson("/api/v1/administrator/domains/{$domain->id}")
->assertOk();
$this->assertDatabaseHas('dns_manager_domain', ['id' => $domain->id, 'is_created' => DnsDomain::STATUS_CANCELLED]);
$this->assertDatabaseHas('dns_domain_user', ['domain_id' => $domain->id, 'user_id' => $customerId]);
Queue::assertPushed(SuspendDnsDomainJob::class, fn ($job) => $job->domainId === $domain->id);
}
public function test_destroy_without_plesk_domain_only_cancels(): void
{
Queue::fake();
$domain = $this->domain();
$this->actingAs($this->admin(), 'admin')
->deleteJson("/api/v1/administrator/domains/{$domain->id}")
->assertOk();
$this->assertDatabaseHas('dns_manager_domain', ['id' => $domain->id, 'is_created' => DnsDomain::STATUS_CANCELLED]);
Queue::assertNotPushed(SuspendDnsDomainJob::class);
}
public function test_suspend_job_calls_plesk_for_cancelled_domain(): void
{
$domain = $this->domain();
$domain->update(['is_created' => DnsDomain::STATUS_CANCELLED]);
$plesk = Mockery::mock(PleskDomainService::class);
$plesk->shouldReceive('suspend')->once()->with(Mockery::any(), 'example.vn')->andReturn(true);
(new SuspendDnsDomainJob($domain->id))->handle($plesk);
}
public function test_suspend_job_skips_domain_reactivated_before_it_ran(): void
{
$domain = $this->domain();
$plesk = Mockery::mock(PleskDomainService::class);
$plesk->shouldNotReceive('suspend');
(new SuspendDnsDomainJob($domain->id))->handle($plesk);
$this->addToAssertionCount(1);
}
public function test_store_queues_provisioning_on_selected_server(): void
{
Queue::fake();
$id = $this->actingAs($this->admin(), 'admin')
->postJson('/api/v1/administrator/domains', ['domain_name' => 'example.vn', 'dns_manager_server_id' => $this->serverId])
->assertCreated()
->assertJsonPath('data.provisioning_queued', true)
->json('data.id');
Queue::assertPushed(ProvisionDnsDomainJob::class, fn ($job) => $job->domainId === $id);
}
public function test_job_creates_domain_on_plesk_when_missing(): void
{
$domain = $this->domain();
$plesk = Mockery::mock(PleskDomainService::class);
$plesk->shouldReceive('getDomainInfo')->once()->andReturn(false);
$plesk->shouldReceive('createDomain')->once()->with(Mockery::any(), ['domain_name' => 'example.vn'])->andReturn(['id' => 55, 'guid' => 'g']);
(new ProvisionDnsDomainJob($domain->id))->handle($plesk);
$this->assertDatabaseHas('dns_manager_domain', ['id' => $domain->id, 'plesk_id' => 55, 'is_created' => 1]);
}
public function test_job_links_existing_plesk_domain_without_creating(): void
{
$domain = $this->domain();
$plesk = Mockery::mock(PleskDomainService::class);
$plesk->shouldReceive('getDomainInfo')->once()->andReturn(['id' => 77, 'name' => 'example.vn']);
$plesk->shouldNotReceive('createDomain');
(new ProvisionDnsDomainJob($domain->id))->handle($plesk);
$this->assertDatabaseHas('dns_manager_domain', ['id' => $domain->id, 'plesk_id' => 77, 'is_created' => 1]);
}
public function test_job_fails_and_keeps_domain_uncreated_when_plesk_rejects(): void
{
$domain = $this->domain();
$plesk = Mockery::mock(PleskDomainService::class);
$plesk->shouldReceive('getDomainInfo')->andReturn(false);
$plesk->shouldReceive('createDomain')->andReturn(false);
$plesk->shouldReceive('getLastError')->andReturn('boom');
$this->expectExceptionMessage('boom');
try {
(new ProvisionDnsDomainJob($domain->id))->handle($plesk);
} finally {
$this->assertDatabaseHas('dns_manager_domain', ['id' => $domain->id, 'plesk_id' => null, 'is_created' => 0]);
}
}
public function test_provision_endpoint_requeues_only_uncreated_active_domains(): void
{
Queue::fake();
$admin = $this->admin();
$domain = $this->domain();
$url = "/api/v1/administrator/domains/{$domain->id}/provision";
$this->actingAs($admin, 'admin')->postJson($url)->assertOk();
Queue::assertPushed(ProvisionDnsDomainJob::class, 1);
$domain->update(['plesk_id' => 9]);
$this->actingAs($admin, 'admin')->postJson($url)->assertStatus(422);
$domain->update(['plesk_id' => null, 'is_created' => DnsDomain::STATUS_CANCELLED]);
$this->actingAs($admin, 'admin')->postJson($url)->assertStatus(422);
Queue::assertPushed(ProvisionDnsDomainJob::class, 1);
}
}
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Admin\Invoice;
use App\Enums\Invoice\InvoiceStatus;
use App\Enums\Order\OrderStatus;
use App\Jobs\Mail\SendInvoiceMailJob;
use App\Mail\InvoiceNotificationMail;
use App\Models\Customer;
use App\Models\Invoice;
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 Spatie\Permission\Models\Role;
use Tests\TestCase;
class InvoiceSendMailTest extends TestCase
{
use RefreshDatabase;
private User $admin;
private Invoice $invoice;
protected function setUp(): void
{
parent::setUp();
Role::firstOrCreate(['name' => 'Full Administrator', 'guard_name' => 'admin']);
$this->admin = User::factory()->create();
$this->admin->assignRole('Full Administrator');
$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,
]);
$this->invoice = 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' => InvoiceStatus::UNPAID->value,
'due_date' => now()->addDays(5)->toDateString(),
]);
}
private function sendMail(bool $mailEnabled)
{
Queue::fake();
Setting::updateOrCreate(['key' => 'email_settings'], ['value' => json_encode(['mail_enabled' => $mailEnabled])]);
return $this->actingAs($this->admin, 'admin')
->postJson("/api/v1/administrator/invoices/{$this->invoice->id}/send-mail", ['type' => 'invoice', 'message' => 'Hi']);
}
public function test_send_mail_is_queued(): void
{
$this->sendMail(true)->assertOk();
Queue::assertPushed(SendInvoiceMailJob::class, fn ($job) => $job->invoiceId === $this->invoice->id
&& $job->sentBy === $this->admin->id
&& $job->html === null);
}
public function test_send_mail_is_rejected_when_mail_is_disabled(): void
{
$this->sendMail(false)->assertStatus(422);
Queue::assertNothingPushed();
}
public function test_job_sends_invoice_mail_and_logs_it(): void
{
$this->seed(\Database\Seeders\TemplateSeeder::class);
Mail::fake();
dispatch_sync(new SendInvoiceMailJob($this->invoice->id, 'invoice', 'Hi', null, null, $this->admin->id));
Mail::assertSent(InvoiceNotificationMail::class);
$this->assertDatabaseHas('mail', ['order_id' => $this->invoice->order_id, 'sent_by' => $this->admin->id]);
}
}
@@ -0,0 +1,133 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Client;
use App\Models\Customer;
use App\Models\DnsDomain;
use App\Models\DnsManagerNS;
use App\Models\Service;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
class DomainRecordPermissionTest extends TestCase
{
use RefreshDatabase;
private Customer $customer;
private DnsDomain $domain;
protected function setUp(): void
{
parent::setUp();
$this->customer = Customer::factory()->create();
$serverId = DB::table('dns_manager_servers')->insertGetId(['ip_address' => '10.0.0.1', 'password' => 'x']);
$this->domain = DnsDomain::create(['domain_name' => 'example.vn', 'dns_manager_server_id' => $serverId, 'is_created' => 1]);
$this->domain->customer()->attach($this->customer->id);
}
private function client()
{
return $this->actingAs($this->customer, 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
}
private function record(string $type): DnsManagerNS
{
return DnsManagerNS::create([
'dns_manager_domain_id' => $this->domain->id,
'type' => $type,
'type_valid' => $type,
'name' => 'example.vn',
'value' => 'ns1.example.net.',
'ttl' => 3600,
]);
}
public function test_customer_cannot_create_ns_record(): void
{
$this->client()
->postJson("/v1/client/client-service/domains/{$this->domain->id}/records", [
'type' => 'NS', 'name' => 'example.vn', 'value' => 'ns1.other.net.',
])
->assertStatus(422);
}
public function test_customer_cannot_update_or_delete_ns_record(): void
{
$ns = $this->record('NS');
$url = "/v1/client/client-service/domains/{$this->domain->id}/records/{$ns->id}";
$this->client()->putJson($url, ['type' => 'A', 'name' => 'www', 'value' => '1.2.3.4'])->assertStatus(403);
$this->client()->deleteJson($url)->assertStatus(403);
$this->assertDatabaseHas('dns_manager_ns', ['id' => $ns->id, 'type' => 'NS']);
}
public function test_domain_detail_exposes_only_record_fields(): void
{
$this->domain->update(['plesk_id' => 214]);
$this->record('A')->update(['plesk_id' => 3260]);
$data = $this->client()
->getJson("/v1/client/client-service/domains/{$this->domain->id}")
->assertOk()
->assertJsonPath('data.domain_name', 'example.vn')
->json('data');
$this->assertSame(['domain_name', 'records'], array_keys($data));
$this->assertSame(
['id', 'name', 'type', 'priority', 'weight', 'port', 'service_name', 'protocol', 'value', 'ttl'],
array_keys($data['records']['items'][0]),
);
}
public function test_domain_list_merges_domain_services_and_assigned_dns_zones(): void
{
$service = Service::create(['customer_id' => $this->customer->id, 'type' => 'domain', 'server_name' => 'Example.vn', 'status' => 'active']);
Service::create(['customer_id' => $this->customer->id, 'type' => 'domain', 'server_name' => 'other.vn', 'status' => 'active']);
$zone = DnsDomain::create(['domain_name' => 'zone-only.vn', 'dns_manager_server_id' => $this->domain->dns_manager_server_id, 'is_created' => 1]);
$zone->customer()->attach($this->customer->id);
$items = collect($this->client()->getJson('/v1/client/client-service/domain')->assertOk()->json('data.items'))
->keyBy('domain_name');
$this->assertCount(3, $items);
$this->assertSame($service->uuid, $items['Example.vn']['service_uuid']);
$this->assertSame($this->domain->id, $items['Example.vn']['dns_domain_id']);
$this->assertNull($items['other.vn']['dns_domain_id']);
$this->assertNull($items['zone-only.vn']['service_uuid']);
$this->assertSame($zone->id, $items['zone-only.vn']['dns_domain_id']);
}
public function test_cancelled_zone_is_listed_as_cancelled_without_dns_access(): void
{
$this->domain->update(['is_created' => DnsDomain::STATUS_CANCELLED]);
$this->client()->getJson('/v1/client/client-service/domain')
->assertOk()
->assertJsonCount(1, 'data.items')
->assertJsonPath('data.items.0.cancelled', true)
->assertJsonPath('data.items.0.dns_domain_id', null);
$this->client()->getJson("/v1/client/client-service/domains/{$this->domain->id}/records")->assertNotFound();
}
public function test_domain_service_detail_exposes_dns_zone_and_cancelled_state(): void
{
$service = Service::create(['customer_id' => $this->customer->id, 'type' => 'domain', 'server_name' => 'example.vn', 'status' => 'active']);
$url = "/v1/client/client-service/{$service->uuid}";
$this->client()->getJson($url)->assertOk()
->assertJsonPath('data.dns_domain_id', $this->domain->id)
->assertJsonPath('data.dns_cancelled', false);
$this->domain->update(['is_created' => DnsDomain::STATUS_CANCELLED]);
$this->client()->getJson($url)->assertOk()
->assertJsonPath('data.dns_domain_id', null)
->assertJsonPath('data.dns_cancelled', true);
}
}
+19
View File
@@ -2,12 +2,15 @@
namespace Tests\Feature;
use App\Jobs\Mail\SendTemplateEmailJob;
use App\Mail\ExpiryService;
use App\Mail\GenericTemplateMail;
use App\Models\Setting;
use App\Services\Email\EmailTemplateService;
use App\Support\AutoEmailGate;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
class MailEnabledToggleTest extends TestCase
@@ -72,4 +75,20 @@ class MailEnabledToggleTest extends TestCase
{
$this->assertSame('service_expiry', (new ExpiryService(0, []))->buildViewData()[AutoEmailGate::SCENARIO_DATA_KEY]);
}
public function test_template_service_does_not_queue_when_mail_disabled_or_scenario_off(): void
{
Queue::fake();
$service = app(EmailTemplateService::class);
$this->setMailEnabled(false);
$service->send('order_created', 'user@example.com');
$this->disableAuto(['order_created']);
$service->send('order_created', 'user@example.com');
Queue::assertNothingPushed();
$service->send('domain_order_approved', 'user@example.com');
Queue::assertPushed(SendTemplateEmailJob::class, 1);
}
}