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() $paginator = Mail::query()
->with(['sender', 'template:id,name']) ->with(['sender', 'template:id,name'])
->where('customer_id', $customer->id) ->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 ->when($search !== '', fn ($q) => $q->where(fn ($q) => $q
->where('subject', 'like', "%{$search}%") ->where('subject', 'like', "%{$search}%")
->orWhere('to', '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]); 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 public function getOrders(string $uuid): JsonResponse
{ {
return response()->json(['error' => false, 'data' => $this->billingService->getOrders($uuid)]); return response()->json(['error' => false, 'data' => $this->billingService->getOrders($uuid)]);
@@ -66,6 +87,7 @@ trait ManagesCustomerBilling
'sub_total' => 'nullable|integer|min:0', 'sub_total' => 'nullable|integer|min:0',
'discount_amount' => 'nullable|integer|min:0', 'discount_amount' => 'nullable|integer|min:0',
'total' => 'nullable|integer|min:0', 'total' => 'nullable|integer|min:0',
'note' => 'nullable|string|max:5000',
]); ]);
$order = $this->billingService->updateOrder($uuid, $orderId, $data); $order = $this->billingService->updateOrder($uuid, $orderId, $data);
@@ -3,6 +3,9 @@
namespace App\Http\Controllers\Api\Admin\DnsManager; namespace App\Http\Controllers\Api\Admin\DnsManager;
use App\Http\Controllers\Controller; 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\Jobs\DnsManager\SyncDnsFromPlesk;
use App\Repositories\DnsManager\Domain\DnsDomainRepositoryInterface; use App\Repositories\DnsManager\Domain\DnsDomainRepositoryInterface;
use App\Repositories\DnsManager\Record\DnsRecordRepositoryInterface; 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', 'dns_manager_server_id' => 'required|integer|exists:dns_manager_servers,id',
'customer_ids' => 'nullable|array', 'customer_ids' => 'nullable|array',
'customer_ids.*' => 'integer|exists:customers,id', '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', 'registrar_id' => 'nullable|integer|exists:registrars,id',
]); ]);
@@ -116,9 +119,14 @@ class DomainController extends Controller
DB::commit(); DB::commit();
$queued = $this->queueProvisioning($domain->fresh());
return response()->json([ return response()->json([
'error' => false, 'error' => false,
'data' => ['id' => $domain->id, 'domain_name' => $domain->domain_name], '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); ], 201);
} catch (\Exception $e) { } catch (\Exception $e) {
DB::rollBack(); DB::rollBack();
@@ -139,7 +147,7 @@ class DomainController extends Controller
'dns_manager_server_id' => 'nullable|integer|exists:dns_manager_servers,id', 'dns_manager_server_id' => 'nullable|integer|exists:dns_manager_servers,id',
'customer_ids' => 'nullable|array', 'customer_ids' => 'nullable|array',
'customer_ids.*' => 'integer|exists:customers,id', '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', 'registrar_id' => 'nullable|integer|exists:registrars,id',
]); ]);
@@ -159,6 +167,8 @@ class DomainController extends Controller
DB::commit(); DB::commit();
$this->queueProvisioning($domain->fresh());
return $this->show($id); return $this->show($id);
} catch (\Exception $e) { } catch (\Exception $e) {
DB::rollBack(); 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 public function destroy(int $id): JsonResponse
{ {
$domain = $this->domainRepository->find($id); $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); return response()->json(['error' => true, 'message' => "Không tìm thấy domain #$id"], 404);
} }
DB::beginTransaction(); if ((int) $domain->is_created === DnsDomain::STATUS_CANCELLED) {
try { return response()->json(['error' => false, 'message' => "Domain {$domain->domain_name} đã được huỷ trước đó."]);
$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);
} }
$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 ───────────────────────────────────────────────────────── // ─── DNS Records ─────────────────────────────────────────────────────────
// ─── Helpers ───────────────────────────────────────────────────────────── // ─── 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 private function formatDomain($domain): array
{ {
return [ return [
@@ -206,6 +256,7 @@ class DomainController extends Controller
'email' => $c->email, 'email' => $c->email,
])->values()->toArray(), ])->values()->toArray(),
'is_created' => $domain->is_created, 'is_created' => $domain->is_created,
'plesk_id' => $domain->plesk_id,
'registrar_id' => $domain->registrar_id, 'registrar_id' => $domain->registrar_id,
'registrar' => $domain->registrar ? [ 'registrar' => $domain->registrar ? [
'id' => $domain->registrar->id, 'id' => $domain->registrar->id,
@@ -2,6 +2,7 @@
namespace App\Http\Controllers\Api\Admin\Invoice\Concerns; namespace App\Http\Controllers\Api\Admin\Invoice\Concerns;
use App\Models\InvoiceAttachment;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -30,7 +31,8 @@ trait HandlesInvoiceAttachments
} }
$request->validate([ $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'); $file = $request->file('file');
@@ -39,6 +41,7 @@ trait HandlesInvoiceAttachments
$attachment = $this->attachmentRepository->create([ $attachment = $this->attachmentRepository->create([
'invoice_id' => $id, 'invoice_id' => $id,
'type' => $request->input('type', InvoiceAttachment::TYPE_PAYMENT_PROOF),
'filename' => $file->getClientOriginalName(), 'filename' => $file->getClientOriginalName(),
'path' => $path, 'path' => $path,
'disk' => 'public', 'disk' => 'public',
@@ -2,15 +2,15 @@
namespace App\Http\Controllers\Api\Admin\Invoice\Concerns; namespace App\Http\Controllers\Api\Admin\Invoice\Concerns;
use App\Jobs\Mail\SendInvoiceMailJob;
use App\Mail\InvoiceNotificationMail; use App\Mail\InvoiceNotificationMail;
use App\Models\Customer; use App\Models\Invoice;
use App\Services\InvoiceReminderService; use App\Services\InvoiceReminderService;
use App\Support\AutoEmailGate; use App\Support\AutoEmailGate;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Queue;
use Throwable;
trait SendsInvoiceNotifications trait SendsInvoiceNotifications
{ {
@@ -29,6 +29,10 @@ trait SendsInvoiceNotifications
], 404); ], 404);
} }
if ($disabled = $this->mailDisabledResponse()) {
return $disabled;
}
if (!$reminders->isRemindable($invoice)) { if (!$reminders->isRemindable($invoice)) {
return response()->json([ return response()->json([
'error' => true, '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 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([ $request->validate([
'message' => 'nullable|string|max:1000', 'message' => 'nullable|string|max:1000',
'type' => 'nullable|string|in:invoice,renewal', '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); $invoice = $this->invoiceRepository->find($id);
@@ -65,57 +127,10 @@ trait SendsInvoiceNotifications
} }
$invoice->load('customer'); $invoice->load('customer');
$customer = $invoice->customer; if (!$invoice->customer?->email) {
if (!$customer || !$customer->email) {
return response()->json(['error' => true, 'message' => 'Customer email not found'], 422); return response()->json(['error' => true, 'message' => 'Customer email not found'], 422);
} }
$attachments = $this->attachmentRepository->getByInvoice($id); return $invoice;
$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}",
]);
} }
} }
@@ -206,6 +206,7 @@ class ExportController extends Controller
'status' => match ((int) $model->is_created) { 'status' => match ((int) $model->is_created) {
1 => 'Đã khởi tạo', 1 => 'Đã khởi tạo',
2 => 'Không hoạt động', 2 => 'Không hoạt động',
3 => 'Đã huỷ',
default => 'Chưa khởi tạo', default => 'Chưa khởi tạo',
}, },
'created_at' => optional($model->created_at)->format('Y-m-d H:i'), 'created_at' => optional($model->created_at)->format('Y-m-d H:i'),
@@ -3,7 +3,6 @@
namespace App\Http\Controllers\Api\Client\Service; namespace App\Http\Controllers\Api\Client\Service;
use App\Http\Controllers\Controller; 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\DomainDetailResource;
use App\Http\Resources\Api\Service\DomainNSResource; use App\Http\Resources\Api\Service\DomainNSResource;
use App\Models\DnsDomain; use App\Models\DnsDomain;
@@ -13,35 +12,17 @@ use App\Services\ServerService;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
class DomainController extends Controller class DomainController extends Controller
{ {
public const CLIENT_EDITABLE_TYPES = ['A', 'AAAA', 'CNAME', 'TXT', 'MX', 'SRV'];
public function __construct( public function __construct(
protected ActivityLogger $activityLogger, protected ActivityLogger $activityLogger,
protected ServerService $serverService, 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 public function show(Request $request, int $domainId): JsonResponse
{ {
$domain = $this->resolveCustomerDomain($request, $domainId); $domain = $this->resolveCustomerDomain($request, $domainId);
@@ -52,8 +33,6 @@ class DomainController extends Controller
$perPage = min((int) $request->get('per_page', 15), 100); $perPage = min((int) $request->get('per_page', 15), 100);
$domain->load('server')->loadCount('record');
$records = DnsManagerNS::query() $records = DnsManagerNS::query()
->where('dns_manager_domain_id', $domain->id) ->where('dns_manager_domain_id', $domain->id)
->orderBy('type') ->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); 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); $payload = $this->validateDomainRecordPayload($request);
if (! empty($record->plesk_id)) { 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); 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)) { if (! empty($record->plesk_id)) {
$this->serverService->findServerByID($domain->dns_manager_server_id); $this->serverService->findServerByID($domain->dns_manager_server_id);
$serverPayload = $this->serverService->deleteRecord((int) $record->plesk_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 private function resolveCustomerDomain(Request $request, int $domainId): ?DnsDomain
{ {
$customer = $request->user(); $customer = $request->user();
return DnsDomain::query() return DnsDomain::query()
->notCancelled()
->with('server') ->with('server')
->where('id', $domainId) ->where('id', $domainId)
->whereHas('customer', fn ($query) => $query->where('customers.id', $customer->id)) ->whereHas('customer', fn ($query) => $query->where('customers.id', $customer->id))
@@ -272,7 +268,7 @@ class DomainController extends Controller
private function validateDomainRecordPayload(Request $request): array private function validateDomainRecordPayload(Request $request): array
{ {
return $request->validate([ 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'], 'name' => ['required', 'string', 'max:255'],
'value' => ['required', 'string'], 'value' => ['required', 'string'],
'ttl' => ['nullable', 'integer', 'min:60', 'max:86400'], '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\Service\Order\InvoiceSummaryResource;
use App\Http\Resources\Api\Client\Service\ServiceClientDetailResource; use App\Http\Resources\Api\Client\Service\ServiceClientDetailResource;
use App\Http\Services\vCenter; use App\Http\Services\vCenter;
use App\Models\DnsDomain;
use App\Models\Order; use App\Models\Order;
use App\Models\Service; use App\Models\Service;
use App\Repositories\Api\ServiceClient\ServiceClientRepository; use App\Repositories\Api\ServiceClient\ServiceClientRepository;
@@ -67,6 +68,56 @@ class ServiceController extends Controller
->response(); ->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 public function overview(Request $request, OrderQueryService $orderQueryService): JsonResponse
{ {
$customerId = (int) $request->user()->id; $customerId = (int) $request->user()->id;
@@ -215,7 +215,7 @@ class OrderControllerRefactor extends Controller
return response()->json([ return response()->json([
'success' => true, 'success' => true,
'data' => new InvoiceDetailResource($invoice), '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(); $uuid = Str::uuid()->toString();
$publicCode = 'MAN-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)); $publicCode = Transaction::newPublicCode('MAN');
DB::beginTransaction(); DB::beginTransaction();
try { try {
@@ -70,6 +70,7 @@ class OrderResource extends JsonResource
'attachments' => $invoice->relationLoaded('attachments') 'attachments' => $invoice->relationLoaded('attachments')
? $invoice->attachments->map(fn($attachment) => [ ? $invoice->attachments->map(fn($attachment) => [
'id' => $attachment->id, 'id' => $attachment->id,
'type' => $attachment->type,
'filename' => $attachment->filename, 'filename' => $attachment->filename,
'url' => $attachment->url, 'url' => $attachment->url,
'mime_type' => $attachment->mime_type, 'mime_type' => $attachment->mime_type,
@@ -2,6 +2,7 @@
namespace App\Http\Resources\Api\Client\Service; namespace App\Http\Resources\Api\Client\Service;
use App\Models\DnsDomain;
use App\Models\ModuleHostingPleskClient; use App\Models\ModuleHostingPleskClient;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -27,6 +28,18 @@ class ServiceClientDetailResource extends JsonResource
]; ];
} }
private function resolveDnsZone(): ?DnsDomain
{
if ($this->type !== 'domain' || !$this->server_name) {
return null;
}
return DnsDomain::query()
->whereRaw('LOWER(domain_name) = ?', [mb_strtolower(trim($this->server_name))])
->whereHas('customer', fn ($query) => $query->where('customers.id', $this->customer_id))
->first(['id', 'is_created']);
}
/** /**
* Transform the resource into an array. * Transform the resource into an array.
* *
@@ -72,6 +85,8 @@ class ServiceClientDetailResource extends JsonResource
$product = $orderItem?->product; $product = $orderItem?->product;
$hosting = $this->resource->hostingAccount; $hosting = $this->resource->hostingAccount;
$pleskCredentials = $hosting ? $this->resolvePleskCredentials($hosting) : null; $pleskCredentials = $hosting ? $this->resolvePleskCredentials($hosting) : null;
$dnsZone = $this->resolveDnsZone();
$dnsCancelled = $dnsZone !== null && (int) $dnsZone->is_created === DnsDomain::STATUS_CANCELLED;
return [ return [
'id' => $this->id, 'id' => $this->id,
@@ -115,6 +130,8 @@ class ServiceClientDetailResource extends JsonResource
'password' => $pleskCredentials['password'] ?? null, 'password' => $pleskCredentials['password'] ?? null,
'status' => $hosting->status, 'status' => $hosting->status,
] : null, ] : null,
'dns_domain_id' => $dnsZone && !$dnsCancelled ? $dnsZone->id : null,
'dns_cancelled' => $dnsCancelled,
]; ];
} }
} }
@@ -1,34 +0,0 @@
<?php
namespace App\Http\Resources\Api\Service;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
class DomainCollection extends ResourceCollection
{
public $collects = DomainResource::class;
/**
* Transform the resource collection into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
$data = [
'items' => $this->collection,
];
if (method_exists($this->resource, 'total')) {
$data['pagination'] = [
'total' => $this->resource->total(),
'per_page' => $this->resource->perPage(),
'current_page' => $this->resource->currentPage(),
'last_page' => $this->resource->lastPage(),
];
}
return $data;
}
}
@@ -20,8 +20,7 @@ class DomainDetailResource extends JsonResource
public function toArray(Request $request): array public function toArray(Request $request): array
{ {
return [ return [
'domain' => new DomainResource($this->resource), 'domain_name' => $this->domain_name,
'ns_count' => (int) ($this->record_count ?? 0),
'records' => $this->records ? new DomainNSCollection($this->records) : [ 'records' => $this->records ? new DomainNSCollection($this->records) : [
'items' => [], 'items' => [],
'pagination' => [ 'pagination' => [
@@ -16,10 +16,8 @@ class DomainNSResource extends JsonResource
{ {
return [ return [
'id' => $this->id, 'id' => $this->id,
'dns_manager_domain_id' => $this->dns_manager_domain_id,
'name' => $this->name, 'name' => $this->name,
'type' => $this->type, 'type' => $this->type,
'type_valid' => $this->type_valid,
'priority' => $this->priority, 'priority' => $this->priority,
'weight' => $this->weight, 'weight' => $this->weight,
'port' => $this->port, 'port' => $this->port,
@@ -27,9 +25,6 @@ class DomainNSResource extends JsonResource
'protocol' => $this->protocol, 'protocol' => $this->protocol,
'value' => $this->value, 'value' => $this->value,
'ttl' => isset($this->ttl) ? (int) $this->ttl : null, 'ttl' => isset($this->ttl) ? (int) $this->ttl : null,
'plesk_id' => $this->plesk_id,
'created_at' => optional($this->created_at)->toISOString(),
'updated_at' => optional($this->updated_at)->toISOString(),
]; ];
} }
} }
@@ -1,30 +0,0 @@
<?php
namespace App\Http\Resources\Api\Service;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class DomainResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'domain_name' => $this->domain_name,
'dns_manager_server_id' => $this->dns_manager_server_id,
'server_name' => $this->server?->name,
'server_ip' => $this->server?->ip_address,
'is_created' => isset($this->is_created) ? (int) $this->is_created : null,
'plesk_id' => $this->plesk_id,
'record_count' => $this->whenCounted('record'),
'created_at' => optional($this->created_at)->toISOString(),
'updated_at' => optional($this->updated_at)->toISOString(),
];
}
}
@@ -3,6 +3,7 @@
namespace App\Http\Resources\Api\Service\Order; namespace App\Http\Resources\Api\Service\Order;
use App\Enums\Invoice\InvoiceStatus; use App\Enums\Invoice\InvoiceStatus;
use App\Models\InvoiceAttachment;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -46,7 +47,10 @@ class InvoiceDetailResource extends JsonResource
'months' => $item->months, 'months' => $item->months,
'os_id' => $item->os_id, 'os_id' => $item->os_id,
])->values()->all()), ])->values()->all()),
'attachments' => $this->whenLoaded('attachments', fn () => $this->attachments->map(fn ($a) => [ 'attachments' => $this->whenLoaded('attachments', fn () => $this->attachments
->where('type', '!=', InvoiceAttachment::TYPE_DEPLOYMENT)
->values()
->map(fn ($a) => [
'filename' => $a->filename, 'filename' => $a->filename,
'url' => $a->url, 'url' => $a->url,
'mime_type' => $a->mime_type, 'mime_type' => $a->mime_type,
@@ -0,0 +1,57 @@
<?php
namespace App\Jobs\DnsManager;
use App\Models\DnsDomain;
use App\Models\DnsServer;
use App\Services\Plesk\PleskDomainService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use RuntimeException;
class ProvisionDnsDomainJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $backoff = 60;
public function __construct(public readonly int $domainId) {}
public function handle(PleskDomainService $plesk): void
{
$domain = DnsDomain::find($this->domainId);
if (!$domain || $domain->plesk_id) {
return;
}
$server = DnsServer::find($domain->dns_manager_server_id);
if (!$server) {
throw new RuntimeException("Không tìm thấy DNS server #{$domain->dns_manager_server_id} cho domain {$domain->domain_name}");
}
$pleskDomain = $plesk->getDomainInfo($server, $domain->domain_name)
?: $plesk->createDomain($server, ['domain_name' => $domain->domain_name]);
if (empty($pleskDomain['id'])) {
throw new RuntimeException("Không tạo được domain {$domain->domain_name} trên Plesk: " . ($plesk->getLastError() ?? 'không rõ lỗi'));
}
$domain->forceFill(['plesk_id' => $pleskDomain['id'], 'is_created' => 1])->save();
Log::info('DNS domain provisioned on Plesk', [
'domain' => $domain->domain_name,
'server_id' => $server->id,
'plesk_id' => $pleskDomain['id'],
]);
}
public function failed(\Throwable $e): void
{
Log::error('ProvisionDnsDomainJob failed', ['domain_id' => $this->domainId, 'error' => $e->getMessage()]);
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Jobs\DnsManager;
use App\Models\DnsDomain;
use App\Models\DnsServer;
use App\Services\Plesk\PleskDomainService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use RuntimeException;
class SuspendDnsDomainJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $backoff = 60;
public function __construct(public readonly int $domainId) {}
public function handle(PleskDomainService $plesk): void
{
$domain = DnsDomain::find($this->domainId);
if (!$domain || (int) $domain->is_created !== DnsDomain::STATUS_CANCELLED) {
return;
}
$server = DnsServer::find($domain->dns_manager_server_id);
if (!$server) {
throw new RuntimeException("Không tìm thấy DNS server #{$domain->dns_manager_server_id} cho domain {$domain->domain_name}");
}
if (!$plesk->suspend($server, $domain->domain_name)) {
throw new RuntimeException("Không suspend được domain {$domain->domain_name} trên Plesk: " . ($plesk->getLastError() ?: 'không rõ lỗi'));
}
Log::info('DNS domain suspended on Plesk', ['domain' => $domain->domain_name, 'server_id' => $server->id]);
}
public function failed(\Throwable $e): void
{
Log::error('SuspendDnsDomainJob failed', ['domain_id' => $this->domainId, 'error' => $e->getMessage()]);
}
}
+1
View File
@@ -25,6 +25,7 @@ class SyncDnsFromPlesk implements ShouldQueue
ServerService $serverService, ServerService $serverService,
): void { ): void {
$domains = $domainRepository->model $domains = $domainRepository->model
->notCancelled()
->whereNotNull('dns_manager_server_id') ->whereNotNull('dns_manager_server_id')
->get(); ->get();
+96
View File
@@ -0,0 +1,96 @@
<?php
namespace App\Jobs\Mail;
use App\Mail\GenericTemplateMail;
use App\Mail\InvoiceNotificationMail;
use App\Models\Invoice;
use App\Models\Mail as MailLog;
use App\Services\Email\EmailTemplateService;
use App\Services\InvoicePdfService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
class SendInvoiceMailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 1;
public function __construct(
public readonly int $invoiceId,
public readonly string $type,
public readonly ?string $message,
public readonly ?string $subject,
public readonly ?string $html,
public readonly ?int $sentBy,
) {}
public function handle(InvoicePdfService $pdfService, EmailTemplateService $templates): void
{
$invoice = Invoice::with('customer')->find($this->invoiceId);
if (!$invoice?->customer?->email) {
return;
}
$mail = null;
try {
$pdf = $pdfService->generate($invoice);
$pdfFileName = $pdfService->generateFileName($invoice);
$mail = $this->html !== null
? $this->editedMail($templates, $pdf, $pdfFileName)
: InvoiceNotificationMail::forInvoice($invoice, $this->type, $this->message, $pdf, $pdfFileName);
$sent = Mail::to($invoice->customer->email)->send($mail);
$this->log($templates, $invoice, $mail, $sent === null ? 'failed' : 'sent');
} catch (Throwable $e) {
Log::error('SendInvoiceMailJob failed', [
'invoice_id' => $invoice->id,
'customer_email' => $invoice->customer->email,
'type' => $this->type,
'error' => $e->getMessage(),
]);
if ($mail) {
$this->log($templates, $invoice, $mail, 'failed');
}
throw $e;
}
}
private function editedMail(EmailTemplateService $templates, string $pdf, string $pdfFileName): GenericTemplateMail
{
return (new GenericTemplateMail(
$this->subject,
$this->html,
$templates->loadTemplate(InvoiceNotificationMail::SCENARIO)->mailConfig(),
InvoiceNotificationMail::SCENARIO,
))->attachData($pdf, $pdfFileName, ['mime' => 'application/pdf']);
}
private function log(EmailTemplateService $templates, Invoice $invoice, Mailable $mail, string $status): void
{
$envelope = $mail->envelope();
$addresses = fn (array $list) => implode(', ', array_map(fn ($a) => is_string($a) ? $a : $a->address, $list));
MailLog::create([
'template_id' => $templates->loadTemplate(InvoiceNotificationMail::SCENARIO)->id,
'subject' => $envelope->subject,
'from_address' => $envelope->from?->address ?? config('mail.from.address'),
'to' => $invoice->customer->email,
'cc' => $addresses($envelope->cc),
'bcc' => $addresses($envelope->bcc),
'customer_id' => $invoice->customer_id,
'order_id' => $invoice->order_id,
'sent_by' => $this->sentBy,
'message' => $mail->render(),
'status' => $status,
]);
}
}
+28 -22
View File
@@ -5,9 +5,9 @@ namespace App\Mail;
use App\Enums\Invoice\InvoiceStatus; use App\Enums\Invoice\InvoiceStatus;
use App\Models\Invoice; use App\Models\Invoice;
use App\Services\InvoicePaymentService; use App\Services\InvoicePaymentService;
use App\Support\MailGlobals;
use App\Support\EmailTemplateShell; use App\Support\EmailTemplateShell;
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Mail\Mailables\Attachment; use Illuminate\Mail\Mailables\Attachment;
/** /**
@@ -19,9 +19,10 @@ use Illuminate\Mail\Mailables\Attachment;
*/ */
class InvoiceNotificationMail extends TemplateMailable class InvoiceNotificationMail extends TemplateMailable
{ {
public const SCENARIO = 'invoice_notification';
public function __construct( public function __construct(
public readonly Invoice $invoice, public readonly Invoice $invoice,
public readonly Collection $invoiceAttachments,
public readonly string $customerName, public readonly string $customerName,
public readonly string $message, public readonly string $message,
public readonly string $companyName, public readonly string $companyName,
@@ -31,6 +32,29 @@ class InvoiceNotificationMail extends TemplateMailable
public readonly ?string $paymentUrl = null, public readonly ?string $paymentUrl = null,
) {} ) {}
public static function forInvoice(
Invoice $invoice,
string $type = 'invoice',
?string $message = null,
?string $invoicePdf = null,
?string $invoicePdfFileName = null,
): self {
$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.";
return new self(
$invoice,
$invoice->customer->fullname,
$message,
setting('general.company_name') ?: config('app.name'),
$type,
$invoicePdf,
$invoicePdfFileName,
MailGlobals::frontendUrl() . $invoice->clientPath(),
);
}
public function attachments(): array public function attachments(): array
{ {
if ($this->invoicePdf !== null && $this->invoicePdfFileName !== null) { if ($this->invoicePdf !== null && $this->invoicePdfFileName !== null) {
@@ -45,7 +69,7 @@ class InvoiceNotificationMail extends TemplateMailable
protected function scenario(): string protected function scenario(): string
{ {
return 'invoice_notification'; return self::SCENARIO;
} }
protected function variables(): array protected function variables(): array
@@ -67,7 +91,7 @@ class InvoiceNotificationMail extends TemplateMailable
? 'File PDF hóa đơn gia hạn đã được đính kèm trong email này. Vui lòng hoàn tất thanh toán trước hạn để dịch vụ không bị gián đoạn.' ? 'File PDF hóa đơn gia hạn đã được đính kèm trong email này. Vui lòng hoàn tất thanh toán trước hạn để dịch vụ không bị gián đoạn.'
: 'File PDF hóa đơn đã được đính kèm trong email này để Quý khách tiện lưu trữ và đối chiếu.', : 'File PDF hóa đơn đã được đính kèm trong email này để Quý khách tiện lưu trữ và đối chiếu.',
'pay_button' => $this->payButton(), 'pay_button' => $this->payButton(),
'attachments_block' => $this->attachmentsBlock(), 'attachments_block' => '',
'note_block' => $this->noteBlock(), 'note_block' => $this->noteBlock(),
]; ];
} }
@@ -132,24 +156,6 @@ class InvoiceNotificationMail extends TemplateMailable
. '<p style="margin: 0 0 18px 0; word-break: break-all; font-size: 13px; color: #6b7280;">Hoặc sao chép liên kết thanh toán: <a href="' . $url . '" style="color: #f16723;">' . $url . '</a></p>'; . '<p style="margin: 0 0 18px 0; word-break: break-all; font-size: 13px; color: #6b7280;">Hoặc sao chép liên kết thanh toán: <a href="' . $url . '" style="color: #f16723;">' . $url . '</a></p>';
} }
private function attachmentsBlock(): string
{
if ($this->invoiceAttachments->isEmpty()) {
return '';
}
$items = $this->invoiceAttachments
->map(fn($file) => '<li style="margin-bottom: 6px;"><a href="'
. htmlspecialchars((string) $file->url, ENT_QUOTES, 'UTF-8')
. '" target="_blank" rel="noopener" style="color: #f16723; text-decoration: none;">'
. htmlspecialchars((string) $file->filename, ENT_QUOTES, 'UTF-8')
. '</a></li>')
->implode('');
return '<div style="margin: 20px 0;"><p style="margin: 0 0 8px 0; font-size: 14px; font-weight: 600; color: #374151;">File đính kèm</p>'
. '<ul style="padding-left: 18px; margin: 0; font-size: 14px;">' . $items . '</ul></div>';
}
private function noteBlock(): string private function noteBlock(): string
{ {
if (empty($this->invoice->note)) { if (empty($this->invoice->note)) {
+10
View File
@@ -10,6 +10,11 @@ class DnsDomain extends Model
{ {
use HasFactory, LogsActivity; use HasFactory, LogsActivity;
public const STATUS_PENDING = 0;
public const STATUS_CREATED = 1;
public const STATUS_INACTIVE = 2;
public const STATUS_CANCELLED = 3;
protected $table = 'dns_manager_domain'; protected $table = 'dns_manager_domain';
protected $fillable = [ protected $fillable = [
@@ -20,6 +25,11 @@ class DnsDomain extends Model
'registrar_id', 'registrar_id',
]; ];
public function scopeNotCancelled($query)
{
return $query->where('is_created', '!=', self::STATUS_CANCELLED);
}
public function customer() public function customer()
{ {
return $this->belongsToMany(Customer::class, 'dns_domain_user', 'domain_id', 'user_id')->withTimestamps(); return $this->belongsToMany(Customer::class, 'dns_domain_user', 'domain_id', 'user_id')->withTimestamps();
+5
View File
@@ -36,6 +36,11 @@ class Invoice extends Model
} }
/** The order that originated this invoice. */ /** The order that originated this invoice. */
public function clientPath(): string
{
return '/hoa-don/' . ($this->order?->order_num ?? $this->invoice_number);
}
public function order() public function order()
{ {
return $this->belongsTo(Order::class, 'order_id'); return $this->belongsTo(Order::class, 'order_id');
+3
View File
@@ -7,6 +7,9 @@ use Illuminate\Support\Facades\Storage;
class InvoiceAttachment extends Model class InvoiceAttachment extends Model
{ {
public const TYPE_PAYMENT_PROOF = 'payment_proof';
public const TYPE_DEPLOYMENT = 'deployment';
protected $table = 'invoice_attachments'; protected $table = 'invoice_attachments';
protected $guarded = []; protected $guarded = [];
+1
View File
@@ -20,6 +20,7 @@ class Mail extends Model
'cc', 'cc',
'bcc', 'bcc',
'customer_id', 'customer_id',
'order_id',
'sent_by', 'sent_by',
'message', 'message',
'status' 'status'
+22 -1
View File
@@ -2,11 +2,14 @@
namespace App\Models; namespace App\Models;
use App\Services\Cache\CacheServiceInterface;
use App\Traits\LogsActivity; use App\Traits\LogsActivity;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use App\Traits\HasUuid; use App\Traits\HasUuid;
class Transaction extends Model class Transaction extends Model
@@ -30,6 +33,24 @@ class Transaction extends Model
protected $appends = ['direction', 'proof_image_urls']; protected $appends = ['direction', 'proof_image_urls'];
protected static function booted(): void
{
static::creating(function (Transaction $transaction) {
$transaction->public_code ??= self::newPublicCode('TXN');
});
$flushListCache = fn () => DB::afterCommit(
fn () => app(CacheServiceInterface::class)->clearByModule('transaction')
);
static::saved($flushListCache);
static::deleted($flushListCache);
}
public static function newPublicCode(string $prefix): string
{
return $prefix . '-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6));
}
public function customer() public function customer()
{ {
return $this->belongsTo(Customer::class, 'customer_id'); return $this->belongsTo(Customer::class, 'customer_id');
@@ -53,7 +74,7 @@ class Transaction extends Model
'admin_add_total', 'admin_add_credit', 'manual', 'refund' => 'credit', 'admin_add_total', 'admin_add_credit', 'manual', 'refund' => 'credit',
'admin_deduct_credit' => 'debit', 'admin_deduct_credit' => 'debit',
'balance' => 'debit', 'balance' => 'debit',
'transfer' => 'neutral', 'transfer', 'admin_record' => 'neutral',
'invoice' => str_starts_with((string) $this->note, 'Admin xác nhận') 'invoice' => str_starts_with((string) $this->note, 'Admin xác nhận')
? 'neutral' ? 'neutral'
: 'debit', : 'debit',
@@ -122,7 +122,7 @@ class DomainOrderService
Transaction::create([ Transaction::create([
'uuid' => (string) Str::uuid(), 'uuid' => (string) Str::uuid(),
'public_code' => 'DOM-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)), 'public_code' => Transaction::newPublicCode('DOM'),
'trans' => $invoice->invoice_number, 'trans' => $invoice->invoice_number,
'amount' => $price, 'amount' => $price,
'customer_id' => $lockedCustomer->id, 'customer_id' => $lockedCustomer->id,
@@ -341,7 +341,7 @@ class DomainOrderService
Transaction::create([ Transaction::create([
'uuid' => (string) Str::uuid(), 'uuid' => (string) Str::uuid(),
'public_code' => 'DOM-REF-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)), 'public_code' => Transaction::newPublicCode('DOM-REF'),
'trans' => 'REF-' . $invoice->invoice_number, 'trans' => 'REF-' . $invoice->invoice_number,
'amount' => $refundAmount, 'amount' => $refundAmount,
'customer_id' => $lockedCustomer->id, 'customer_id' => $lockedCustomer->id,
+2 -2
View File
@@ -223,7 +223,7 @@ class OrderQueryService
'invoice_number' => $invoice?->invoice_number, 'invoice_number' => $invoice?->invoice_number,
'total' => (float) ($invoice?->total ?? 0), 'total' => (float) ($invoice?->total ?? 0),
'status' => $invoice?->status, 'status' => $invoice?->status,
'payment_url' => url('/client/invoices/' . $invoice?->invoice_number . '/payment'), 'payment_url' => $invoice?->clientPath(),
], ],
]; ];
} }
@@ -278,7 +278,7 @@ class OrderQueryService
'invoice_number' => $invoice->invoice_number, 'invoice_number' => $invoice->invoice_number,
'total' => (float) $invoice->total, 'total' => (float) $invoice->total,
'status' => $invoice->status, 'status' => $invoice->status,
'payment_url' => url('/client/invoices/' . $invoice->invoice_number . '/payment'), 'payment_url' => $invoice->clientPath(),
], ],
]; ];
} }
+12 -24
View File
@@ -3,10 +3,11 @@
namespace App\Services\Cache; namespace App\Services\Cache;
use Closure; use Closure;
use Illuminate\Cache\RedisStore;
use Illuminate\Contracts\Cache\Repository as CacheRepository; use Illuminate\Contracts\Cache\Repository as CacheRepository;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis; use Illuminate\Support\Str;
use stdClass; use stdClass;
class CacheService implements CacheServiceInterface class CacheService implements CacheServiceInterface
@@ -66,11 +67,6 @@ class CacheService implements CacheServiceInterface
public function clearByModule(string $module): void public function clearByModule(string $module): void
{ {
if ($this->supportsTagging()) {
Cache::tags([$module])->flush();
return;
}
$this->scanAndDelete($module); $this->scanAndDelete($module);
} }
@@ -87,32 +83,24 @@ class CacheService implements CacheServiceInterface
return Cache::store(); return Cache::store();
} }
/**
* Delete all keys for a module using SCAN (safe for production).
*
* KEYS is O(N) and blocks Redis; SCAN iterates in batches without blocking.
* The pattern matches: {cache_prefix}:{module}:*
*/
private function scanAndDelete(string $module): void private function scanAndDelete(string $module): void
{ {
$redis = Redis::connection('cache'); $store = Cache::store()->getStore();
$prefix = config('cache.prefix'); if (! $store instanceof RedisStore) {
$pattern = "{$prefix}:{$module}:*"; return;
}
$redis = $store->connection();
$connectionPrefix = (string) config('database.redis.options.prefix');
$pattern = $connectionPrefix . $store->getPrefix() . $module . ':*';
$cursor = '0'; $cursor = '0';
do { do {
$result = $redis->scan($cursor, 'MATCH', $pattern, 'COUNT', 100); [$cursor, $keys] = $redis->scan($cursor, ['match' => $pattern, 'count' => 500]) ?: ['0', []];
if ($result === false) {
break;
}
[$cursor, $keys] = $result;
foreach ((array) $keys as $key) { foreach ((array) $keys as $key) {
$redis->del($key); $redis->del(Str::after($key, $connectionPrefix));
} }
} while ((string) $cursor !== '0'); } while ((string) $cursor !== '0');
} }
@@ -4,6 +4,7 @@ namespace App\Services\Customer;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\Order; use App\Models\Order;
use App\Enums\TransactionStatus;
use App\Models\Transaction; use App\Models\Transaction;
use App\Repositories\Customer\CustomerRepositoryInterface; use App\Repositories\Customer\CustomerRepositoryInterface;
use App\Repositories\Invoice\InvoiceRepositoryInterface; use App\Repositories\Invoice\InvoiceRepositoryInterface;
@@ -11,6 +12,7 @@ use App\Repositories\Order\OrderRepositoryInterface;
use App\Repositories\Transaction\TransactionRepositoryInterface; use App\Repositories\Transaction\TransactionRepositoryInterface;
use App\Services\Customer\Concerns\ResolvesCustomer; use App\Services\Customer\Concerns\ResolvesCustomer;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Str;
class CustomerBillingService class CustomerBillingService
{ {
@@ -91,6 +93,36 @@ class CustomerBillingService
return $transaction->refresh()->load('user'); return $transaction->refresh()->load('user');
} }
public function createTransaction(string $uuid, array $data, ?int $adminId): Transaction
{
$customer = $this->resolveCustomer($uuid);
$transaction = $this->transactionRepository->create([
'uuid' => (string) Str::uuid(),
'public_code' => Transaction::newPublicCode('ADM'),
'trans' => $data['trans'] ?? null,
'amount' => $data['amount'],
'received_amount' => $data['amount'],
'customer_id' => $customer->id,
'user_id' => $adminId,
'status' => $data['status'] ?? TransactionStatus::COMPLETED->value,
'type' => 'admin_record',
'note' => $data['note'] ?? null,
]);
return $transaction->load('user');
}
public function deleteTransaction(string $uuid, int $transactionId): void
{
$customer = $this->resolveCustomer($uuid);
$exists = Transaction::where('customer_id', $customer->id)->where('id', $transactionId)->exists();
abort_if(!$exists, 404, 'Không tìm thấy giao dịch');
$this->transactionRepository->delete($transactionId);
}
public function getOrders(string $uuid): Collection public function getOrders(string $uuid): Collection
{ {
$customer = $this->resolveCustomer($uuid); $customer = $this->resolveCustomer($uuid);
@@ -294,6 +294,7 @@ class CustomerServiceProvisioningService
Transaction::create([ Transaction::create([
'uuid' => (string) Str::uuid(), 'uuid' => (string) Str::uuid(),
'public_code' => Transaction::newPublicCode('SVC'),
'customer_id' => $customer->id, 'customer_id' => $customer->id,
'user_id' => Auth::id(), 'user_id' => Auth::id(),
'trans' => $order->order_num, 'trans' => $order->order_num,
@@ -83,6 +83,7 @@ class CustomerWalletService
{ {
return Transaction::create([ return Transaction::create([
'uuid' => (string) Str::uuid(), 'uuid' => (string) Str::uuid(),
'public_code' => Transaction::newPublicCode('ADM'),
'trans' => 'ADMIN' . now()->format('YmdHis'), 'trans' => 'ADMIN' . now()->format('YmdHis'),
'amount' => $amount, 'amount' => $amount,
'customer_id' => $customer->id, 'customer_id' => $customer->id,
@@ -4,6 +4,7 @@ namespace App\Services\Email;
use App\Jobs\Mail\SendTemplateEmailJob; use App\Jobs\Mail\SendTemplateEmailJob;
use App\Models\Template; use App\Models\Template;
use App\Support\AutoEmailGate;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
/** /**
@@ -21,6 +22,10 @@ class EmailTemplateService
*/ */
public function send(string $scenario, string|array $to, array $data = []): void public function send(string $scenario, string|array $to, array $data = []): void
{ {
if (!AutoEmailGate::allows($scenario)) {
return;
}
SendTemplateEmailJob::dispatch($scenario, is_array($to) ? $to : [$to], $data); SendTemplateEmailJob::dispatch($scenario, is_array($to) ? $to : [$to], $data);
} }
+2 -2
View File
@@ -243,7 +243,7 @@ class InvoicePaymentService
Transaction::create([ Transaction::create([
'uuid' => (string) Str::uuid(), 'uuid' => (string) Str::uuid(),
'public_code' => 'INV-REF-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)), 'public_code' => Transaction::newPublicCode('INV-REF'),
'trans' => $invoice->invoice_number . '-REFUND', 'trans' => $invoice->invoice_number . '-REFUND',
'type' => 'refund', 'type' => 'refund',
'amount' => -$refundAmount, 'amount' => -$refundAmount,
@@ -295,7 +295,7 @@ class InvoicePaymentService
], ],
[ [
'uuid' => (string) Str::uuid(), 'uuid' => (string) Str::uuid(),
'public_code' => 'INV-PAY-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)), 'public_code' => Transaction::newPublicCode('INV-PAY'),
'amount' => $amount, 'amount' => $amount,
'received_amount' => $amount, 'received_amount' => $amount,
'user_id' => $adminId, 'user_id' => $adminId,
+4 -1
View File
@@ -24,6 +24,7 @@ use App\Repositories\InvoiceItem\InvoiceItemRepositoryInterface;
use App\Repositories\Module\Hosting\HostingRepositoryInterface as ModuleHostingRepositoryInterface; use App\Repositories\Module\Hosting\HostingRepositoryInterface as ModuleHostingRepositoryInterface;
use App\Repositories\Module\HostingServer\HostingServerRepositoryInterface; use App\Repositories\Module\HostingServer\HostingServerRepositoryInterface;
use App\Repositories\Order\OrderRepositoryInterface; use App\Repositories\Order\OrderRepositoryInterface;
use App\Support\AutoEmailGate;
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@@ -246,7 +247,7 @@ class OrderService
], ],
[ [
'uuid' => (string) Str::uuid(), 'uuid' => (string) Str::uuid(),
'public_code' => 'INV-PAY-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)), 'public_code' => Transaction::newPublicCode('INV-PAY'),
'amount' => $orderTotal, 'amount' => $orderTotal,
'user_id' => Auth::guard('admin')->id(), 'user_id' => Auth::guard('admin')->id(),
'status' => TransactionStatus::COMPLETED->value, 'status' => TransactionStatus::COMPLETED->value,
@@ -258,6 +259,7 @@ class OrderService
return $order; return $order;
}); });
if (AutoEmailGate::allows('order_created')) {
OrderCreatedJob::dispatch([ OrderCreatedJob::dispatch([
'customer_email' => $customer->email, 'customer_email' => $customer->email,
'client_name' => $customer->fullname, 'client_name' => $customer->fullname,
@@ -267,6 +269,7 @@ class OrderService
'company_name' => setting('general.company_name') ?: config('app.name'), 'company_name' => setting('general.company_name') ?: config('app.name'),
'company_logo' => setting('general.company_logo') ?: '', 'company_logo' => setting('general.company_logo') ?: '',
]); ]);
}
return $order; return $order;
} }
+23
View File
@@ -3,6 +3,7 @@
namespace App\Services\Plesk; namespace App\Services\Plesk;
use App\Models\DnsServer; use App\Models\DnsServer;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException; use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str; use Illuminate\Support\Str;
@@ -83,6 +84,28 @@ class PleskDomainService
return false; return false;
} }
public function suspend(DnsServer $server, string $domain): bool
{
$this->lastError = null;
try {
$response = $this->plesk->client($server, 30)
->post($this->plesk->url($server, 'cli', '/subscription/call'), ['params' => ['--webspace-off', $domain]]);
} catch (ConnectionException $e) {
$this->lastError = $e->getMessage();
return false;
}
if ($response->successful() && (int) $response->json('code', 1) === 0) {
return true;
}
$this->lastError = trim((string) ($response->json('stderr') ?: $response->json('message') ?: $response->body()));
return false;
}
public function getDomainInfo(DnsServer $server, string $domain = ''): array|false public function getDomainInfo(DnsServer $server, string $domain = ''): array|false
{ {
if (empty($domain)) { if (empty($domain)) {
+5
View File
@@ -25,6 +25,11 @@ final class AutoEmailGate
return in_array($scenario, self::disabledScenarios(), true); return in_array($scenario, self::disabledScenarios(), true);
} }
public static function allows(?string $scenario): bool
{
return self::mailEnabled() && !self::blocks($scenario);
}
public static function mailEnabled(): bool public static function mailEnabled(): bool
{ {
return (bool) (self::emailSettings()['mail_enabled'] ?? true); return (bool) (self::emailSettings()['mail_enabled'] ?? true);
+1 -1
View File
@@ -57,7 +57,7 @@ return [
'url' => env('APP_URL', 'http://localhost'), 'url' => env('APP_URL', 'http://localhost'),
'frontend_url' => 'https://portal.tgs.com.vn', 'frontend_url' => env('FRONTEND_URL', 'https://portal.tgs.com.vn'),
'api_agency_url' => env('API_AGENCY_URL'), 'api_agency_url' => env('API_AGENCY_URL'),
+2 -2
View File
@@ -177,7 +177,7 @@ return [
'password' => env('REDIS_PASSWORD'), 'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'), 'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'), 'database' => env('REDIS_DB', '0'),
'persistent' => true, 'persistent' => env('REDIS_PERSISTENT', false),
'persistent_id' => 'default', 'persistent_id' => 'default',
'read_write_timeout' => 0, 'read_write_timeout' => 0,
], ],
@@ -188,7 +188,7 @@ return [
'password' => env('REDIS_PASSWORD'), 'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'), 'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'), 'database' => env('REDIS_CACHE_DB', '1'),
'persistent' => true, 'persistent' => env('REDIS_PERSISTENT', false),
'persistent_id' => 'cache', 'persistent_id' => 'cache',
'read_write_timeout' => 0, 'read_write_timeout' => 0,
], ],
@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
return new class extends Migration
{
public function up(): void
{
DB::table('transactions')
->whereNull('public_code')
->orderBy('id')
->select(['id', 'type', 'created_at'])
->chunkById(500, function ($transactions) {
foreach ($transactions as $transaction) {
$prefix = $transaction->type === 'transfer' || $transaction->type === 'balance' ? 'SVC' : 'TXN';
$date = $transaction->created_at ? date('Ymd', strtotime($transaction->created_at)) : now()->format('Ymd');
DB::table('transactions')
->where('id', $transaction->id)
->update(['public_code' => $prefix . '-' . $date . '-' . strtoupper(Str::random(6))]);
}
});
}
public function down(): void
{
}
};
@@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('invoice_attachments', function (Blueprint $table) {
$table->string('type', 30)->default('payment_proof')->after('invoice_id')->index();
});
}
public function down(): void
{
Schema::table('invoice_attachments', function (Blueprint $table) {
$table->dropColumn('type');
});
}
};
@@ -0,0 +1,23 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('mail', function (Blueprint $table) {
$table->unsignedBigInteger('order_id')->nullable()->index()->after('customer_id');
});
}
public function down(): void
{
Schema::table('mail', function (Blueprint $table) {
$table->dropIndex(['order_id']);
$table->dropColumn('order_id');
});
}
};
+1
View File
@@ -44,6 +44,7 @@ Route::prefix('invoices')
); );
// Send mail notification // Send mail notification
Route::post('{id}/send-mail', 'sendMail')->middleware('perm:invoice.edit'); Route::post('{id}/send-mail', 'sendMail')->middleware('perm:invoice.edit');
Route::post('{id}/send-mail/preview', 'previewMail')->middleware('perm:invoice.edit');
}); });
// Reports / Data exports // Reports / Data exports
+4
View File
@@ -54,6 +54,10 @@ Route::prefix('customers')
Route::put('{uuid}/transactions/{transactionId}', 'updateTransaction')->middleware( Route::put('{uuid}/transactions/{transactionId}', 'updateTransaction')->middleware(
'perm:customer.edit', 'perm:customer.edit',
); );
Route::post('{uuid}/transactions', 'createTransaction')->middleware('perm:customer.edit');
Route::delete('{uuid}/transactions/{transactionId}', 'deleteTransaction')->middleware(
'perm:customer.edit',
);
Route::get('{uuid}/domains', 'getDomains')->middleware('perm:customer.view'); Route::get('{uuid}/domains', 'getDomains')->middleware('perm:customer.view');
Route::get('{uuid}/dns-domains', 'getDnsDomains')->middleware('perm:customer.view'); Route::get('{uuid}/dns-domains', 'getDnsDomains')->middleware('perm:customer.view');
Route::get('{uuid}/dns-domains/{domainId}/records', 'getDnsDomainRecords')->middleware( Route::get('{uuid}/dns-domains/{domainId}/records', 'getDnsDomainRecords')->middleware(
+1
View File
@@ -18,6 +18,7 @@ Route::prefix('domains')
Route::post('sync-dns', 'syncDns')->middleware('perm:domain.manager'); Route::post('sync-dns', 'syncDns')->middleware('perm:domain.manager');
Route::get('{id}', 'show')->middleware('perm:domain.manager'); Route::get('{id}', 'show')->middleware('perm:domain.manager');
Route::put('{id}', 'update')->middleware('perm:domain.manager'); Route::put('{id}', 'update')->middleware('perm:domain.manager');
Route::post('{id}/provision', 'provision')->middleware('perm:domain.manager');
Route::delete('{id}', 'destroy')->middleware('perm:domain.manager'); Route::delete('{id}', 'destroy')->middleware('perm:domain.manager');
// DNS Records // DNS Records
Route::get('{id}/dns', 'dnsIndex')->middleware('perm:domain.manager'); Route::get('{id}/dns', 'dnsIndex')->middleware('perm:domain.manager');
+1 -1
View File
@@ -88,7 +88,6 @@ Route::prefix('v1')
->controller(ClientDomainController::class) ->controller(ClientDomainController::class)
->as('client-service.domains.') ->as('client-service.domains.')
->group(function () { ->group(function () {
Route::get('/', 'index')->name('list');
Route::get('{domainId}', 'show')->name('detail'); Route::get('{domainId}', 'show')->name('detail');
Route::get('{domainId}/records', 'show')->name('records'); Route::get('{domainId}/records', 'show')->name('records');
Route::post('{domainId}/records', 'storeRecord')->name('records.store'); Route::post('{domainId}/records', 'storeRecord')->name('records.store');
@@ -108,6 +107,7 @@ Route::prefix('v1')
Route::get('vps', 'indexVps')->name('vps.list'); Route::get('vps', 'indexVps')->name('vps.list');
Route::get('hosting', 'indexHosting')->name('hosting.list'); Route::get('hosting', 'indexHosting')->name('hosting.list');
Route::get('web-design', 'indexWebDesign')->name('web-design.list'); Route::get('web-design', 'indexWebDesign')->name('web-design.list');
Route::get('domain', 'indexDomain')->name('domain.list');
Route::get('{uuid}', 'getDetail')->name('detail'); Route::get('{uuid}', 'getDetail')->name('detail');
Route::get('{uuid}/console-ticket', 'getConsoleTicket')->name('console-ticket'); Route::get('{uuid}/console-ticket', 'getConsoleTicket')->name('console-ticket');
Route::get('{uuid}/available-os', 'getAvailableOs')->name('available-os'); Route::get('{uuid}/available-os', 'getAvailableOs')->name('available-os');
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

@@ -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; namespace Tests\Feature;
use App\Jobs\Mail\SendTemplateEmailJob;
use App\Mail\ExpiryService; use App\Mail\ExpiryService;
use App\Mail\GenericTemplateMail; use App\Mail\GenericTemplateMail;
use App\Models\Setting; use App\Models\Setting;
use App\Services\Email\EmailTemplateService;
use App\Support\AutoEmailGate; use App\Support\AutoEmailGate;
use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase; use Tests\TestCase;
class MailEnabledToggleTest extends 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]); $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);
}
} }