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
@@ -16,6 +16,7 @@ trait ListsCustomerEmails
$paginator = Mail::query()
->with(['sender', 'template:id,name'])
->where('customer_id', $customer->id)
->when($request->filled('order_id'), fn ($q) => $q->where('order_id', (int) $request->get('order_id')))
->when($search !== '', fn ($q) => $q->where(fn ($q) => $q
->where('subject', 'like', "%{$search}%")
->orWhere('to', 'like', "%{$search}%")))
@@ -51,6 +51,27 @@ trait ManagesCustomerBilling
return response()->json(['error' => false, 'message' => 'Đã cập nhật giao dịch', 'data' => $transaction]);
}
public function createTransaction(string $uuid, Request $request): JsonResponse
{
$data = $request->validate([
'trans' => 'nullable|string|max:255',
'note' => 'nullable|string',
'amount' => 'required|integer|min:0',
'status' => 'nullable|integer|in:0,1,2',
]);
$transaction = $this->billingService->createTransaction($uuid, $data, $request->user()?->id);
return response()->json(['error' => false, 'message' => 'Đã thêm giao dịch', 'data' => $transaction], 201);
}
public function deleteTransaction(string $uuid, int $transactionId): JsonResponse
{
$this->billingService->deleteTransaction($uuid, $transactionId);
return response()->json(['error' => false, 'message' => 'Đã xoá giao dịch']);
}
public function getOrders(string $uuid): JsonResponse
{
return response()->json(['error' => false, 'data' => $this->billingService->getOrders($uuid)]);
@@ -66,6 +87,7 @@ trait ManagesCustomerBilling
'sub_total' => 'nullable|integer|min:0',
'discount_amount' => 'nullable|integer|min:0',
'total' => 'nullable|integer|min:0',
'note' => 'nullable|string|max:5000',
]);
$order = $this->billingService->updateOrder($uuid, $orderId, $data);
@@ -3,6 +3,9 @@
namespace App\Http\Controllers\Api\Admin\DnsManager;
use App\Http\Controllers\Controller;
use App\Jobs\DnsManager\ProvisionDnsDomainJob;
use App\Jobs\DnsManager\SuspendDnsDomainJob;
use App\Models\DnsDomain;
use App\Jobs\DnsManager\SyncDnsFromPlesk;
use App\Repositories\DnsManager\Domain\DnsDomainRepositoryInterface;
use App\Repositories\DnsManager\Record\DnsRecordRepositoryInterface;
@@ -97,7 +100,7 @@ class DomainController extends Controller
'dns_manager_server_id' => 'required|integer|exists:dns_manager_servers,id',
'customer_ids' => 'nullable|array',
'customer_ids.*' => 'integer|exists:customers,id',
'is_created' => 'nullable|integer|in:0,1,2',
'is_created' => 'nullable|integer|in:0,1,2,3',
'registrar_id' => 'nullable|integer|exists:registrars,id',
]);
@@ -116,9 +119,14 @@ class DomainController extends Controller
DB::commit();
$queued = $this->queueProvisioning($domain->fresh());
return response()->json([
'error' => false,
'data' => ['id' => $domain->id, 'domain_name' => $domain->domain_name],
'error' => false,
'message' => $queued
? "Đã lưu domain {$domain->domain_name}, đang khởi tạo trên server (queue)."
: "Đã lưu domain {$domain->domain_name}.",
'data' => ['id' => $domain->id, 'domain_name' => $domain->domain_name, 'provisioning_queued' => $queued],
], 201);
} catch (\Exception $e) {
DB::rollBack();
@@ -139,7 +147,7 @@ class DomainController extends Controller
'dns_manager_server_id' => 'nullable|integer|exists:dns_manager_servers,id',
'customer_ids' => 'nullable|array',
'customer_ids.*' => 'integer|exists:customers,id',
'is_created' => 'nullable|integer|in:0,1,2',
'is_created' => 'nullable|integer|in:0,1,2,3',
'registrar_id' => 'nullable|integer|exists:registrars,id',
]);
@@ -159,6 +167,8 @@ class DomainController extends Controller
DB::commit();
$this->queueProvisioning($domain->fresh());
return $this->show($id);
} catch (\Exception $e) {
DB::rollBack();
@@ -166,6 +176,30 @@ class DomainController extends Controller
}
}
public function provision(int $id): JsonResponse
{
$domain = $this->domainRepository->find($id);
if (!$domain) {
return response()->json(['error' => true, 'message' => "Không tìm thấy domain #$id"], 404);
}
if ($domain->plesk_id) {
return response()->json(['error' => true, 'message' => "Domain {$domain->domain_name} đã được khởi tạo trên Plesk."], 422);
}
if ((int) $domain->is_created === DnsDomain::STATUS_CANCELLED) {
return response()->json(['error' => true, 'message' => "Domain {$domain->domain_name} đã huỷ, không thể khởi tạo."], 422);
}
ProvisionDnsDomainJob::dispatch($domain->id);
return response()->json([
'error' => false,
'message' => "Đã đưa {$domain->domain_name} vào queue khởi tạo trên Plesk.",
]);
}
public function destroy(int $id): JsonResponse
{
$domain = $this->domainRepository->find($id);
@@ -174,24 +208,40 @@ class DomainController extends Controller
return response()->json(['error' => true, 'message' => "Không tìm thấy domain #$id"], 404);
}
DB::beginTransaction();
try {
$domain->customer()->detach();
$domain->record()->delete();
$this->domainRepository->delete($id);
DB::commit();
return response()->json(['error' => false, 'message' => 'Đã xoá domain thành công']);
} catch (\Exception $e) {
DB::rollBack();
return response()->json(['error' => true, 'message' => $e->getMessage()], 500);
if ((int) $domain->is_created === DnsDomain::STATUS_CANCELLED) {
return response()->json(['error' => false, 'message' => "Domain {$domain->domain_name} đã được huỷ trước đó."]);
}
$onPlesk = (bool) $domain->plesk_id;
$domain->update(['is_created' => DnsDomain::STATUS_CANCELLED]);
if ($onPlesk) {
SuspendDnsDomainJob::dispatch($domain->id);
}
return response()->json([
'error' => false,
'message' => $onPlesk
? "Đã huỷ domain {$domain->domain_name}, đang suspend trên server (queue)."
: "Đã huỷ domain {$domain->domain_name}.",
]);
}
// ─── DNS Records ─────────────────────────────────────────────────────────
// ─── Helpers ─────────────────────────────────────────────────────────────
private function queueProvisioning($domain): bool
{
if ($domain->plesk_id || in_array((int) $domain->is_created, [DnsDomain::STATUS_INACTIVE, DnsDomain::STATUS_CANCELLED], true)) {
return false;
}
ProvisionDnsDomainJob::dispatch($domain->id);
return true;
}
private function formatDomain($domain): array
{
return [
@@ -206,6 +256,7 @@ class DomainController extends Controller
'email' => $c->email,
])->values()->toArray(),
'is_created' => $domain->is_created,
'plesk_id' => $domain->plesk_id,
'registrar_id' => $domain->registrar_id,
'registrar' => $domain->registrar ? [
'id' => $domain->registrar->id,
@@ -2,6 +2,7 @@
namespace App\Http\Controllers\Api\Admin\Invoice\Concerns;
use App\Models\InvoiceAttachment;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@@ -30,7 +31,8 @@ trait HandlesInvoiceAttachments
}
$request->validate([
'file' => 'required|file|mimes:jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx|max:10240',
'file' => 'required|file|mimes:jpg,jpeg,png,gif,webp,pdf,doc,docx,xls,xlsx|max:51200',
'type' => 'nullable|in:' . InvoiceAttachment::TYPE_PAYMENT_PROOF . ',' . InvoiceAttachment::TYPE_DEPLOYMENT,
]);
$file = $request->file('file');
@@ -39,6 +41,7 @@ trait HandlesInvoiceAttachments
$attachment = $this->attachmentRepository->create([
'invoice_id' => $id,
'type' => $request->input('type', InvoiceAttachment::TYPE_PAYMENT_PROOF),
'filename' => $file->getClientOriginalName(),
'path' => $path,
'disk' => 'public',
@@ -2,15 +2,15 @@
namespace App\Http\Controllers\Api\Admin\Invoice\Concerns;
use App\Jobs\Mail\SendInvoiceMailJob;
use App\Mail\InvoiceNotificationMail;
use App\Models\Customer;
use App\Models\Invoice;
use App\Services\InvoiceReminderService;
use App\Support\AutoEmailGate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Queue;
trait SendsInvoiceNotifications
{
@@ -29,6 +29,10 @@ trait SendsInvoiceNotifications
], 404);
}
if ($disabled = $this->mailDisabledResponse()) {
return $disabled;
}
if (!$reminders->isRemindable($invoice)) {
return response()->json([
'error' => true,
@@ -52,11 +56,69 @@ trait SendsInvoiceNotifications
]);
}
public function previewMail(Request $request, int $id): JsonResponse
{
$invoice = $this->invoiceForMail($request, $id);
if ($invoice instanceof JsonResponse) {
return $invoice;
}
$mail = InvoiceNotificationMail::forInvoice($invoice, $request->input('type') ?: 'invoice', $request->input('message'));
return response()->json([
'error' => false,
'data' => [
'to' => $invoice->customer->email,
'subject' => $mail->envelope()->subject,
'html' => $mail->render(),
'attachment_filename' => $this->invoicePdfService->generateFileName($invoice),
],
]);
}
public function sendMail(Request $request, int $id): JsonResponse
{
if ($disabled = $this->mailDisabledResponse()) {
return $disabled;
}
$invoice = $this->invoiceForMail($request, $id);
if ($invoice instanceof JsonResponse) {
return $invoice;
}
AutoEmailGate::markManual();
$jobId = Queue::push(new SendInvoiceMailJob(
$invoice->id,
$request->input('type') ?: 'invoice',
$request->input('message'),
$request->input('subject'),
$request->filled('html') ? $request->input('html') : null,
Auth::guard('admin')->id(),
));
return response()->json([
'error' => false,
'message' => "Đã đưa email vào hàng đợi gửi tới {$invoice->customer->email}",
'data' => ['job_id' => $jobId],
]);
}
private function mailDisabledResponse(): ?JsonResponse
{
return AutoEmailGate::mailEnabled() ? null : response()->json([
'error' => true,
'message' => 'Chức năng gửi email đang tắt. Bật lại tại Cài đặt → Thông báo.',
], 422);
}
private function invoiceForMail(Request $request, int $id): Invoice|JsonResponse
{
$request->validate([
'message' => 'nullable|string|max:1000',
'type' => 'nullable|string|in:invoice,renewal',
'subject' => 'nullable|required_with:html|string|max:255',
'html' => 'nullable|required_with:subject|string|max:500000',
]);
$invoice = $this->invoiceRepository->find($id);
@@ -65,57 +127,10 @@ trait SendsInvoiceNotifications
}
$invoice->load('customer');
$customer = $invoice->customer;
if (!$customer || !$customer->email) {
if (!$invoice->customer?->email) {
return response()->json(['error' => true, 'message' => 'Customer email not found'], 422);
}
$attachments = $this->attachmentRepository->getByInvoice($id);
$companyName = setting('general.company_name') ?: config('app.name');
$type = $request->get('type', 'invoice');
$message = $request->get(
'message',
$type === 'renewal'
? "Dịch vụ của quý khách sắp đến hạn gia hạn. Vui lòng kiểm tra hóa đơn #{$invoice->order_num} được đính kèm và hoàn tất thanh toán để dịch vụ không bị gián đoạn."
: "Vui lòng xem thông tin hóa đơn #{$invoice->order_num} của bạn."
);
$paymentUrl = url('/client/invoices/' . $invoice->invoice_number . '/payment');
try {
AutoEmailGate::markManual();
$invoicePdf = $this->invoicePdfService->generate($invoice);
$invoicePdfFileName = $this->invoicePdfService->generateFileName($invoice);
Mail::to($customer->email)->send(
new InvoiceNotificationMail(
$invoice,
$attachments,
$customer->fullname,
$message,
$companyName,
$type,
$invoicePdf,
$invoicePdfFileName,
$paymentUrl
)
);
} catch (Throwable $e) {
Log::error('InvoiceController@sendMail failed', [
'invoice_id' => $id,
'invoice_number' => $invoice->invoice_number ?? null,
'customer_email' => $customer->email,
'type' => $type,
'error' => $e->getMessage(),
]);
return response()->json([
'error' => true,
'message' => 'Không thể gửi email: ' . $e->getMessage(),
], 500);
}
return response()->json([
'error' => false,
'message' => "Email đã được gửi tới {$customer->email}",
]);
return $invoice;
}
}
@@ -206,6 +206,7 @@ class ExportController extends Controller
'status' => match ((int) $model->is_created) {
1 => 'Đã khởi tạo',
2 => 'Không hoạt động',
3 => 'Đã huỷ',
default => 'Chưa khởi tạo',
},
'created_at' => optional($model->created_at)->format('Y-m-d H:i'),
@@ -3,7 +3,6 @@
namespace App\Http\Controllers\Api\Client\Service;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\Service\DomainCollection;
use App\Http\Resources\Api\Service\DomainDetailResource;
use App\Http\Resources\Api\Service\DomainNSResource;
use App\Models\DnsDomain;
@@ -13,35 +12,17 @@ use App\Services\ServerService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
class DomainController extends Controller
{
public const CLIENT_EDITABLE_TYPES = ['A', 'AAAA', 'CNAME', 'TXT', 'MX', 'SRV'];
public function __construct(
protected ActivityLogger $activityLogger,
protected ServerService $serverService,
) {}
public function index(Request $request): JsonResponse
{
$customer = $request->user();
$perPage = min((int) $request->get('per_page', 15), 100);
$domains = DnsDomain::query()
->with('server')
->withCount('record')
->whereHas('customer', fn ($query) => $query->where('customers.id', $customer->id))
->orderByDesc('id')
->paginate($perPage);
return (new DomainCollection($domains))
->additional([
'error' => false,
'message' => 'Lấy dữ liệu thành công',
'page_type' => 'service_domain',
])
->response();
}
public function show(Request $request, int $domainId): JsonResponse
{
$domain = $this->resolveCustomerDomain($request, $domainId);
@@ -52,8 +33,6 @@ class DomainController extends Controller
$perPage = min((int) $request->get('per_page', 15), 100);
$domain->load('server')->loadCount('record');
$records = DnsManagerNS::query()
->where('dns_manager_domain_id', $domain->id)
->orderBy('type')
@@ -155,6 +134,10 @@ class DomainController extends Controller
return response()->json(['error' => true, 'message' => 'Không tìm thấy bản ghi DNS'], 404);
}
if ($locked = $this->lockedRecordResponse($record)) {
return $locked;
}
$payload = $this->validateDomainRecordPayload($request);
if (! empty($record->plesk_id)) {
@@ -223,6 +206,10 @@ class DomainController extends Controller
return response()->json(['error' => true, 'message' => 'Không tìm thấy bản ghi DNS'], 404);
}
if ($locked = $this->lockedRecordResponse($record)) {
return $locked;
}
if (! empty($record->plesk_id)) {
$this->serverService->findServerByID($domain->dns_manager_server_id);
$serverPayload = $this->serverService->deleteRecord((int) $record->plesk_id);
@@ -258,11 +245,20 @@ class DomainController extends Controller
]);
}
private function lockedRecordResponse(DnsManagerNS $record): ?JsonResponse
{
return in_array(strtoupper((string) $record->type), self::CLIENT_EDITABLE_TYPES, true) ? null : response()->json([
'error' => true,
'message' => "Bản ghi {$record->type} không thể tự thay đổi. Vui lòng liên hệ bộ phận kỹ thuật.",
], 403);
}
private function resolveCustomerDomain(Request $request, int $domainId): ?DnsDomain
{
$customer = $request->user();
return DnsDomain::query()
->notCancelled()
->with('server')
->where('id', $domainId)
->whereHas('customer', fn ($query) => $query->where('customers.id', $customer->id))
@@ -272,7 +268,7 @@ class DomainController extends Controller
private function validateDomainRecordPayload(Request $request): array
{
return $request->validate([
'type' => ['required', 'string', 'in:A,AAAA,CNAME,TXT,MX,NS,SRV'],
'type' => ['required', 'string', Rule::in(self::CLIENT_EDITABLE_TYPES)],
'name' => ['required', 'string', 'max:255'],
'value' => ['required', 'string'],
'ttl' => ['nullable', 'integer', 'min:60', 'max:86400'],
@@ -7,6 +7,7 @@ use App\Http\Resources\Api\Service\VpsServiceCollection;
use App\Http\Resources\Api\Service\Order\InvoiceSummaryResource;
use App\Http\Resources\Api\Client\Service\ServiceClientDetailResource;
use App\Http\Services\vCenter;
use App\Models\DnsDomain;
use App\Models\Order;
use App\Models\Service;
use App\Repositories\Api\ServiceClient\ServiceClientRepository;
@@ -67,6 +68,56 @@ class ServiceController extends Controller
->response();
}
public function indexDomain(Request $request): JsonResponse
{
$customerId = $request->user()->id;
$zones = DnsDomain::query()
->whereHas('customer', fn ($query) => $query->where('customers.id', $customerId))
->get(['id', 'domain_name', 'is_created'])
->keyBy(fn (DnsDomain $zone) => mb_strtolower(trim($zone->domain_name)));
$zoneFields = fn (?DnsDomain $zone) => [
'dns_domain_id' => $zone && !$this->isCancelledZone($zone) ? $zone->id : null,
'cancelled' => $zone !== null && $this->isCancelledZone($zone),
];
$items = Service::query()
->where('customer_id', $customerId)
->where('type', 'domain')
->orderByDesc('id')
->get(['uuid', 'server_name', 'status', 'started_at', 'expires_at'])
->map(fn (Service $service) => [
'domain_name' => $service->server_name,
'service_uuid' => $service->uuid,
'status' => $service->status,
'started_at' => $service->started_at?->toISOString(),
'expires_at' => $service->expires_at?->toISOString(),
...$zoneFields($zones->pull(mb_strtolower(trim((string) $service->server_name)))),
])
->concat($zones->values()->map(fn (DnsDomain $zone) => [
'domain_name' => $zone->domain_name,
'service_uuid' => null,
'status' => null,
'started_at' => null,
'expires_at' => null,
...$zoneFields($zone),
]))
->values();
return response()->json([
'error' => false,
'message' => 'Lấy dữ liệu thành công',
'page_type' => 'service_domain',
'data' => ['items' => $items],
]);
}
private function isCancelledZone(DnsDomain $zone): bool
{
return (int) $zone->is_created === DnsDomain::STATUS_CANCELLED;
}
public function overview(Request $request, OrderQueryService $orderQueryService): JsonResponse
{
$customerId = (int) $request->user()->id;
@@ -215,7 +215,7 @@ class OrderControllerRefactor extends Controller
return response()->json([
'success' => true,
'data' => new InvoiceDetailResource($invoice),
'payment_url' => url('/client/invoices/' . $invoice->invoice_number . '/payment'),
'payment_url' => $invoice->clientPath(),
]);
}
@@ -94,7 +94,7 @@ class ManualDepositController extends Controller
}
$uuid = Str::uuid()->toString();
$publicCode = 'MAN-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6));
$publicCode = Transaction::newPublicCode('MAN');
DB::beginTransaction();
try {