Files
portal-api/app/Integrations/Whmcs/Writers/CustomerDomainWriter.php

85 lines
3.1 KiB
PHP

<?php
namespace App\Integrations\Whmcs\Writers;
use App\Integrations\Whmcs\DTOs\CustomerDomainData;
use App\Integrations\Whmcs\Support\DnsDomainLinker;
use App\Integrations\Whmcs\Support\SyncReport;
use Illuminate\Support\Facades\DB;
class CustomerDomainWriter
{
public function __construct(private DnsDomainLinker $dnsLinker, private SyncReport $report)
{
}
/**
* Skips domains whose WHMCS client couldn't be resolved to a local customer.
* A domain name that already exists under another legacy id is merged into that row instead of duplicated.
*/
public function write(CustomerDomainData $data): bool
{
if ($data->customerId === null) {
return false;
}
$attributes = [
'name' => $data->name,
'order_id' => $data->orderId,
'first_payment' => $data->firstPayment,
'module_dns_id' => 0,
'next_payment' => $data->nextPayment,
'next_due_date' => $data->nextDueDate,
'next_invoice_date' => $data->nextInvoiceDate,
'customer_id' => $data->customerId,
'domain_type_id' => 0,
'registrar_id' => $data->registrarId,
'note' => $data->note,
'status' => $data->status,
];
$duplicate = DB::table('module_domain')->where('legacy_id', $data->legacyId)->doesntExist()
? DB::table('module_domain')->whereRaw('LOWER(TRIM(name)) = ?', [mb_strtolower(trim($data->name))])->orderBy('id')->first()
: null;
if ($duplicate !== null) {
$this->mergeInto($duplicate, $attributes, $data);
} else {
DB::table('module_domain')->updateOrInsert(['legacy_id' => $data->legacyId], $attributes);
}
$this->dnsLinker->link($data->name, $duplicate->customer_id ?? $data->customerId, $data->registrarId);
return true;
}
private function mergeInto(object $existing, array $incoming, CustomerDomainData $data): void
{
$update = [];
foreach (['order_id', 'registrar_id', 'note', 'first_payment', 'next_payment'] as $column) {
if (in_array($existing->{$column}, [null, '', 0], true) && ! in_array($incoming[$column], [null, '', 0], true)) {
$update[$column] = $incoming[$column];
}
}
if (($incoming['next_due_date'] ?? 0) > ($existing->next_due_date ?? 0)) {
$update += [
'next_due_date' => $incoming['next_due_date'],
'next_invoice_date' => $incoming['next_invoice_date'],
'next_payment' => $incoming['next_payment'],
];
}
if ($update !== []) {
DB::table('module_domain')->where('id', $existing->id)->update($update);
}
$this->report->note(
'domain',
$data->name,
$data->legacyId,
'trung_ten_mien_da_gop',
"Tên miền đã có ở module_domain #{$existing->id}; gộp bản ghi WHMCS #{$data->legacyId}, "
. ($update ? 'cập nhật: ' . implode(', ', array_keys($update)) : 'không có trường nào cần cập nhật') . '.',
);
}
}