Files
portal-api/app/Services/Domain/CustomerDomainServiceSync.php
baodev0andClaude Sonnet 5.5 7136bec265 feat(domain): chỉnh ngày bắt đầu/hết hạn tên miền và điền hạn từ dữ liệu cũ
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>
2026-10-28 17:26:41 +07:00

159 lines
6.0 KiB
PHP

<?php
namespace App\Services\Domain;
use App\Enums\Product\ProductBillingCycle;
use App\Models\DnsDomain;
use App\Models\Service;
use App\Services\Order\ServiceOrderRecorder;
use App\Support\BillingCycleCatalog;
use App\Support\LegacyDomainTerms;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class CustomerDomainServiceSync
{
public const AUTO_CREATED_NOTE = 'Tự động tạo từ phân công DNS domain';
public function __construct(private readonly ServiceOrderRecorder $orderRecorder) {}
public function syncCustomers(DnsDomain $domain, array $customerIds, ?string $previousDomainName = null): void
{
$customerIds = collect($customerIds)->map(fn ($id) => (int) $id)->unique()->values();
$previousCustomerIds = $domain->customer()->pluck('customers.id');
$oldName = $previousDomainName ?? $domain->domain_name;
DB::transaction(function () use ($domain, $customerIds, $previousCustomerIds, $oldName): void {
$domain->customer()->sync($customerIds->all());
foreach ($customerIds as $customerId) {
$service = $this->findService($customerId, $oldName, $domain->domain_name);
if ($service?->trashed()) {
$service->restore();
}
$service ??= new Service([
'customer_id' => $customerId,
'type' => 'domain',
'note' => self::AUTO_CREATED_NOTE,
]);
$service->fill([
'server_name' => $domain->domain_name,
'status' => $this->serviceStatus($domain),
'started_at' => $service->started_at ?? $domain->created_at ?? Carbon::now(),
]);
LegacyDomainTerms::fill($service);
$service->save();
if ($service->status !== 'cancelled') {
$this->orderRecorder->ensureForService($service);
}
}
$removedCustomerIds = $previousCustomerIds->diff($customerIds);
if ($removedCustomerIds->isNotEmpty()) {
Service::query()
->whereIn('customer_id', $removedCustomerIds)
->where('type', 'domain')
->whereIn(DB::raw('LOWER(TRIM(server_name))'), array_unique([
$this->domainKey($oldName),
$this->domainKey($domain->domain_name),
]))
->get()
->each(function (Service $service): void {
$this->orderRecorder->cancelUnpaidInvoice($service);
$service->delete();
});
}
});
}
public function updateCustomerDomain(
DnsDomain $domain,
int $customerId,
?string $expiresAt,
): Service {
$this->syncCustomers($domain, $domain->customer()->pluck('customers.id')->all());
$service = $this->findService($customerId, $domain->domain_name, $domain->domain_name);
abort_if(! $service, 404, 'Không tìm thấy dịch vụ tên miền');
$service->fill([
'status' => $this->serviceStatus($domain),
'started_at' => $domain->created_at,
'expires_at' => $expiresAt
? Carbon::parse($expiresAt)->setTimeFrom($service->expires_at ?? Carbon::today())
: null,
])->save();
return $service;
}
public function applyTerm(DnsDomain $domain, ?string $registeredAt, ?string $expiresAt, ?int $cycleYears): int
{
$services = Service::query()
->where('type', 'domain')
->where('status', '!=', 'cancelled')
->whereIn('customer_id', $domain->customer()->pluck('customers.id'))
->whereRaw('LOWER(TRIM(server_name)) = ?', [$this->domainKey($domain->domain_name)])
->with('orderItem')
->get();
DB::transaction(function () use ($services, $registeredAt, $expiresAt, $cycleYears): void {
foreach ($services as $service) {
$attributes = [
'expires_at' => $expiresAt
? Carbon::parse($expiresAt)->setTimeFrom($service->expires_at ?? Carbon::today())
: null,
];
if ($registeredAt) {
$attributes['started_at'] = Carbon::parse($registeredAt);
}
$service->forceFill($attributes)->save();
if ($cycleYears && $service->orderItem) {
$months = $cycleYears * 12;
$service->orderItem->update([
'months' => $months,
'billing_cycle' => collect(ProductBillingCycle::cases())
->first(fn (ProductBillingCycle $cycle) => $cycle->months() === $months)?->value
?? BillingCycleCatalog::codeFor($months),
]);
}
}
});
return $services->count();
}
private function findService(int $customerId, string $oldName, string $currentName): ?Service
{
return Service::withTrashed()
->where('customer_id', $customerId)
->where('type', 'domain')
->whereIn(DB::raw('LOWER(TRIM(server_name))'), array_unique([
$this->domainKey($oldName),
$this->domainKey($currentName),
]))
->orderBy('id')
->first();
}
private function serviceStatus(DnsDomain $domain): string
{
return match ((int) $domain->is_created) {
DnsDomain::STATUS_CREATED => 'active',
DnsDomain::STATUS_INACTIVE => 'suspended',
DnsDomain::STATUS_CANCELLED => 'cancelled',
default => 'pending',
};
}
private function domainKey(?string $domainName): string
{
return mb_strtolower(trim((string) $domainName));
}
}