PUT administrator/domains/{id}/term, LegacyDomainTerms và migration backfill hạn cho dịch vụ domain chưa có expires_at.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
480 lines
19 KiB
PHP
480 lines
19 KiB
PHP
<?php
|
|
|
|
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;
|
|
use App\Services\ServerService;
|
|
use App\Support\DomainServiceSummary;
|
|
use App\Services\Domain\CustomerDomainServiceSync;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class DomainController extends Controller
|
|
{
|
|
private const RECORD_RULES = [
|
|
'type' => 'required|string|in:A,AAAA,CNAME,TXT,MX,NS,SRV',
|
|
'name' => 'required|string|max:255',
|
|
'value' => 'required|string',
|
|
'ttl' => 'nullable|integer|min:60',
|
|
'priority' => 'nullable|integer|min:0',
|
|
'weight' => 'nullable|integer|min:0',
|
|
'port' => 'nullable|integer|min:0',
|
|
'service_name' => 'nullable|string|max:255',
|
|
'protocol' => 'nullable|string|max:50',
|
|
];
|
|
|
|
public function __construct(
|
|
private readonly DnsDomainRepositoryInterface $domainRepository,
|
|
private readonly DnsRecordRepositoryInterface $recordRepository,
|
|
private readonly ServerService $serverService,
|
|
private readonly CustomerDomainServiceSync $customerDomainServiceSync,
|
|
) {}
|
|
|
|
// ─── Domains ─────────────────────────────────────────────────────────────
|
|
|
|
public function index(Request $request): JsonResponse
|
|
{
|
|
$perPage = min((int) $request->get('per_page', 15), 500);
|
|
$filter = $request->get('filter');
|
|
$status = $request->get('status');
|
|
$customerName = trim((string) $request->get('customer_name', ''));
|
|
|
|
$query = $this->domainRepository->model
|
|
->with(['server', 'customer', 'registrar'])
|
|
->newQuery();
|
|
|
|
if ($filter) {
|
|
$query->where('domain_name', 'like', "%{$filter}%");
|
|
}
|
|
|
|
if ($status !== null && $status !== '') {
|
|
$query->where('is_created', (int) $status);
|
|
}
|
|
|
|
if ($customerName !== '') {
|
|
$query->whereHas('customer', function ($q) use ($customerName) {
|
|
$q->where('fullname', 'like', "%{$customerName}%");
|
|
});
|
|
}
|
|
|
|
$paginator = $query->orderByDesc('id')->paginate($perPage);
|
|
|
|
$summaries = DomainServiceSummary::forDomains($paginator->getCollection());
|
|
$items = $paginator->getCollection()->map(fn($domain) => $this->formatDomain($domain) + [
|
|
'service' => $summaries[DomainServiceSummary::key($domain->domain_name)] ?? null,
|
|
]);
|
|
|
|
return response()->json([
|
|
'error' => false,
|
|
'data' => [
|
|
'items' => $items,
|
|
'total' => $paginator->total(),
|
|
'per_page' => $paginator->perPage(),
|
|
'current_page' => $paginator->currentPage(),
|
|
'last_page' => $paginator->lastPage(),
|
|
],
|
|
]);
|
|
}
|
|
|
|
public function show(int $id): JsonResponse
|
|
{
|
|
$domain = $this->domainRepository->model
|
|
->with(['server', 'customer', 'registrar'])
|
|
->find($id);
|
|
|
|
if (!$domain) {
|
|
return response()->json(['error' => true, 'message' => "Không tìm thấy domain #$id"], 404);
|
|
}
|
|
|
|
$summary = DomainServiceSummary::forDomains(collect([$domain]));
|
|
|
|
return response()->json([
|
|
'error' => false,
|
|
'data' => $this->formatDomain($domain) + [
|
|
'service' => $summary[DomainServiceSummary::key($domain->domain_name)] ?? null,
|
|
],
|
|
]);
|
|
}
|
|
|
|
public function store(Request $request): JsonResponse
|
|
{
|
|
$request->validate([
|
|
'domain_name' => 'required|string|max:255',
|
|
'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,3',
|
|
'registrar_id' => 'nullable|integer|exists:registrars,id',
|
|
]);
|
|
|
|
DB::beginTransaction();
|
|
try {
|
|
$domain = $this->domainRepository->create([
|
|
'domain_name' => $request->domain_name,
|
|
'dns_manager_server_id' => $request->dns_manager_server_id,
|
|
'is_created' => $request->is_created ?? 0,
|
|
'registrar_id' => $request->registrar_id,
|
|
]);
|
|
|
|
if (!empty($request->customer_ids)) {
|
|
$this->customerDomainServiceSync->syncCustomers($domain, $request->customer_ids);
|
|
}
|
|
|
|
DB::commit();
|
|
|
|
$queued = $this->queueProvisioning($domain->fresh());
|
|
|
|
return response()->json([
|
|
'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();
|
|
return response()->json(['error' => true, 'message' => $e->getMessage()], 500);
|
|
}
|
|
}
|
|
|
|
public function update(int $id, Request $request): JsonResponse
|
|
{
|
|
$domain = $this->domainRepository->find($id);
|
|
|
|
if (!$domain) {
|
|
return response()->json(['error' => true, 'message' => "Không tìm thấy domain #$id"], 404);
|
|
}
|
|
|
|
$request->validate([
|
|
'domain_name' => 'sometimes|required|string|max:255',
|
|
'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,3',
|
|
'registrar_id' => 'nullable|integer|exists:registrars,id',
|
|
]);
|
|
|
|
DB::beginTransaction();
|
|
try {
|
|
$previousDomainName = $domain->domain_name;
|
|
$this->domainRepository->update($id, $request->only([
|
|
'domain_name',
|
|
'dns_manager_server_id',
|
|
'is_created',
|
|
'registrar_id',
|
|
]));
|
|
|
|
// Sync customers (empty array = detach all)
|
|
$freshDomain = $domain->fresh();
|
|
if ($request->has('customer_ids')) {
|
|
$this->customerDomainServiceSync->syncCustomers(
|
|
$freshDomain,
|
|
$request->customer_ids ?? [],
|
|
$previousDomainName,
|
|
);
|
|
} elseif ($previousDomainName !== $freshDomain->domain_name) {
|
|
$this->customerDomainServiceSync->syncCustomers(
|
|
$freshDomain,
|
|
$freshDomain->customer()->pluck('customers.id')->all(),
|
|
$previousDomainName,
|
|
);
|
|
}
|
|
|
|
DB::commit();
|
|
|
|
$this->queueProvisioning($domain->fresh());
|
|
|
|
return $this->show($id);
|
|
} catch (\Exception $e) {
|
|
DB::rollBack();
|
|
return response()->json(['error' => true, 'message' => $e->getMessage()], 500);
|
|
}
|
|
}
|
|
|
|
public function updateTerm(int $id, Request $request): JsonResponse
|
|
{
|
|
$domain = $this->domainRepository->find($id);
|
|
|
|
if (!$domain) {
|
|
return response()->json(['error' => true, 'message' => "Không tìm thấy domain #$id"], 404);
|
|
}
|
|
|
|
$data = $request->validate([
|
|
'registered_at' => 'nullable|date',
|
|
'expires_at' => 'nullable|date|after_or_equal:registered_at',
|
|
'cycle_years' => 'nullable|integer|min:1|max:10',
|
|
]);
|
|
|
|
$updated = $this->customerDomainServiceSync->applyTerm(
|
|
$domain,
|
|
$data['registered_at'] ?? null,
|
|
$data['expires_at'] ?? null,
|
|
$data['cycle_years'] ?? null,
|
|
);
|
|
|
|
if ($updated === 0) {
|
|
return response()->json([
|
|
'error' => true,
|
|
'message' => 'Tên miền chưa gắn khách hàng nên chưa có dịch vụ để lưu ngày đăng ký/hết hạn.',
|
|
], 422);
|
|
}
|
|
|
|
return $this->show($id);
|
|
}
|
|
|
|
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);
|
|
|
|
if (!$domain) {
|
|
return response()->json(['error' => true, 'message' => "Không tìm thấy domain #$id"], 404);
|
|
}
|
|
|
|
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 [
|
|
'id' => $domain->id,
|
|
'domain_name' => $domain->domain_name,
|
|
'dns_manager_server_id' => $domain->dns_manager_server_id,
|
|
'server_name' => $domain->server?->name,
|
|
'customer_ids' => $domain->customer->pluck('id')->toArray(),
|
|
'customers' => $domain->customer->map(fn($c) => [
|
|
'id' => $c->id,
|
|
'name' => $c->fullname,
|
|
'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,
|
|
'name' => $domain->registrar->name,
|
|
'short_name' => $domain->registrar->short_name,
|
|
] : null,
|
|
'created_at' => $domain->created_at,
|
|
'updated_at' => $domain->updated_at,
|
|
];
|
|
}
|
|
|
|
// ─── Sync from Plesk ─────────────────────────────────────────────────────
|
|
|
|
public function syncDns(Request $request): JsonResponse
|
|
{
|
|
$validated = $request->validate([
|
|
'dns_manager_server_id' => ['nullable', 'integer', 'exists:dns_manager_servers,id'],
|
|
]);
|
|
|
|
dispatch(new SyncDnsFromPlesk($validated['dns_manager_server_id'] ?? null));
|
|
|
|
return response()->json([
|
|
'error' => false,
|
|
'message' => 'Đã đưa lệnh đồng bộ DNS vào hàng đợi, quá trình sẽ chạy nền.',
|
|
]);
|
|
}
|
|
|
|
// ─── DNS Records ─────────────────────────────────────────────────────────
|
|
|
|
public function dnsIndex(int $domainId): JsonResponse
|
|
{
|
|
$domain = $this->domainRepository->find($domainId);
|
|
|
|
if (!$domain) {
|
|
return response()->json(['error' => true, 'message' => "Không tìm thấy domain #$domainId"], 404);
|
|
}
|
|
|
|
$records = $this->recordRepository->model
|
|
->where('dns_manager_domain_id', $domainId)
|
|
->orderBy('type')
|
|
->get();
|
|
|
|
return response()->json(['error' => false, 'data' => $records]);
|
|
}
|
|
|
|
public function dnsStore(int $domainId, Request $request): JsonResponse
|
|
{
|
|
$domain = $this->domainRepository->find($domainId);
|
|
|
|
if (!$domain) {
|
|
return response()->json(['error' => true, 'message' => "Không tìm thấy domain #$domainId"], 404);
|
|
}
|
|
|
|
$validated = $request->validate(self::RECORD_RULES);
|
|
|
|
if (!$this->serverService->addServerById($domain->dns_manager_server_id)) {
|
|
return response()->json(['error' => true, 'message' => 'Không tìm thấy server DNS'], 404);
|
|
}
|
|
|
|
$result = $this->serverService
|
|
->handlePayload(['domain' => $domain->domain_name, ...$validated])
|
|
->addRecord();
|
|
|
|
if ($result['error']) {
|
|
return response()->json(['error' => true, 'message' => $result['message'] ?? 'Tạo bản ghi DNS trên Plesk thất bại'], 422);
|
|
}
|
|
|
|
$record = $this->recordRepository->create([
|
|
'dns_manager_domain_id' => $domainId,
|
|
'type' => $validated['type'],
|
|
'type_valid' => $validated['type'],
|
|
'name' => $validated['name'],
|
|
'value' => $validated['value'],
|
|
'ttl' => $validated['ttl'] ?? 300,
|
|
'priority' => $validated['priority'] ?? null,
|
|
'weight' => $validated['weight'] ?? null,
|
|
'port' => $validated['port'] ?? null,
|
|
'service_name' => $validated['service_name'] ?? null,
|
|
'protocol' => $validated['protocol'] ?? null,
|
|
'plesk_id' => $result['data']['id'] ?? null,
|
|
]);
|
|
|
|
return response()->json(['error' => false, 'data' => $record], 201);
|
|
}
|
|
|
|
public function dnsUpdate(int $domainId, int $recordId, Request $request): JsonResponse
|
|
{
|
|
$domain = $this->domainRepository->find($domainId);
|
|
|
|
if (!$domain) {
|
|
return response()->json(['error' => true, 'message' => "Không tìm thấy domain #$domainId"], 404);
|
|
}
|
|
|
|
$record = $this->recordRepository->model
|
|
->where('dns_manager_domain_id', $domainId)
|
|
->find($recordId);
|
|
|
|
if (!$record) {
|
|
return response()->json(['error' => true, 'message' => "Không tìm thấy bản ghi DNS #$recordId"], 404);
|
|
}
|
|
|
|
$validated = $request->validate(self::RECORD_RULES);
|
|
|
|
// ponytail: records created before Plesk sync was wired up have no plesk_id, update locally only
|
|
if ($record->plesk_id) {
|
|
if (!$this->serverService->addServerById($domain->dns_manager_server_id)) {
|
|
return response()->json(['error' => true, 'message' => 'Không tìm thấy server DNS'], 404);
|
|
}
|
|
|
|
$result = $this->serverService
|
|
->handlePayload(['domain' => $domain->domain_name, ...$validated])
|
|
->updateRecord($record->plesk_id);
|
|
|
|
if ($result['error']) {
|
|
return response()->json(['error' => true, 'message' => $result['message'] ?? 'Cập nhật bản ghi DNS trên Plesk thất bại'], 422);
|
|
}
|
|
}
|
|
|
|
$this->recordRepository->update($recordId, [
|
|
'type' => $validated['type'],
|
|
'type_valid' => $validated['type'],
|
|
'name' => $validated['name'],
|
|
'value' => $validated['value'],
|
|
'ttl' => $validated['ttl'] ?? 300,
|
|
'priority' => $validated['priority'] ?? null,
|
|
'weight' => $validated['weight'] ?? null,
|
|
'port' => $validated['port'] ?? null,
|
|
'service_name' => $validated['service_name'] ?? null,
|
|
'protocol' => $validated['protocol'] ?? null,
|
|
]);
|
|
|
|
return response()->json(['error' => false, 'data' => $this->recordRepository->find($recordId)]);
|
|
}
|
|
|
|
public function dnsDestroy(int $domainId, int $recordId): JsonResponse
|
|
{
|
|
$domain = $this->domainRepository->find($domainId);
|
|
|
|
if (!$domain) {
|
|
return response()->json(['error' => true, 'message' => "Không tìm thấy domain #$domainId"], 404);
|
|
}
|
|
|
|
$record = $this->recordRepository->model
|
|
->where('dns_manager_domain_id', $domainId)
|
|
->find($recordId);
|
|
|
|
if (!$record) {
|
|
return response()->json(['error' => true, 'message' => "Không tìm thấy bản ghi DNS #$recordId"], 404);
|
|
}
|
|
|
|
if ($record->plesk_id) {
|
|
if (!$this->serverService->addServerById($domain->dns_manager_server_id)) {
|
|
return response()->json(['error' => true, 'message' => 'Không tìm thấy server DNS'], 404);
|
|
}
|
|
|
|
$result = $this->serverService->deleteRecord($record->plesk_id);
|
|
|
|
if ($result['error']) {
|
|
return response()->json(['error' => true, 'message' => $result['message'] ?? 'Xoá bản ghi DNS trên Plesk thất bại'], 422);
|
|
}
|
|
}
|
|
|
|
$this->recordRepository->delete($recordId);
|
|
|
|
return response()->json(['error' => false, 'message' => 'Đã xoá bản ghi DNS']);
|
|
}
|
|
}
|