feat(portal): lead module, WHMCS sync report/contacts/mapping, service lifecycle email templates

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
baodev0
2026-10-21 16:55:19 +07:00
co-authored by Claude Sonnet 5.5
parent 3c7710f1de
commit a443ec3bf6
66 changed files with 2032 additions and 124 deletions
+62 -20
View File
@@ -3,35 +3,77 @@
namespace App\Integrations\Whmcs\Writers;
use App\Integrations\Whmcs\DTOs\ClientData;
use App\Integrations\Whmcs\Support\CustomerIdResolver;
use App\Integrations\Whmcs\Support\SyncReport;
use Illuminate\Support\Facades\DB;
class ClientWriter
{
private const FILL_BLANK_COLUMNS = ['fullname', 'company', 'address', 'state', 'city', 'saler', 'country', 'phone', 'note'];
public function __construct(private SyncReport $report)
{
}
/**
* Upsert into `customers` keyed by `uuid` (WHMCS already assigns a uuid per client).
* A customer that already exists on the portal under another uuid is matched by email and only
* has its blank fields filled — uuid, password, credit and status stay as the portal has them.
*/
public function write(ClientData $data): void
{
DB::table('customers')->updateOrInsert(
['uuid' => $data->uuid],
[
'fullname' => $data->fullname,
'company' => $data->company,
'address' => $data->address,
'state' => $data->state,
'city' => $data->city,
'saler' => $data->saler,
'country' => $data->country,
'phone' => $data->phone,
'email' => $data->email,
'password' => $data->password,
'note' => $data->note,
'credit' => $data->credit,
'status' => $data->status,
'email_marketing' => $data->emailMarketing,
'created_at' => $data->createdAt,
'updated_at' => $data->updatedAt,
]
$attributes = [
'fullname' => $data->fullname,
'company' => $data->company,
'address' => $data->address,
'state' => $data->state,
'city' => $data->city,
'saler' => $data->saler,
'country' => $data->country,
'phone' => $data->phone,
'email' => $data->email,
'password' => $data->password,
'note' => $data->note,
'credit' => $data->credit,
'status' => $data->status,
'email_marketing' => $data->emailMarketing,
'created_at' => $data->createdAt,
'updated_at' => $data->updatedAt,
];
if (DB::table('customers')->where('uuid', $data->uuid)->exists()) {
DB::table('customers')->where('uuid', $data->uuid)->update($attributes);
return;
}
$existing = $data->email ? DB::table('customers')->whereRaw('LOWER(email) = ?', [strtolower($data->email)])->first() : null;
if ($existing === null) {
DB::table('customers')->insert(['uuid' => $data->uuid, ...$attributes]);
return;
}
$filled = [];
foreach (self::FILL_BLANK_COLUMNS as $column) {
if (($existing->{$column} === null || $existing->{$column} === '') && $attributes[$column] !== null) {
$filled[$column] = $attributes[$column];
}
}
if ($filled !== []) {
DB::table('customers')->where('id', $existing->id)->update($filled);
}
$this->report->note(
'client',
(string) $data->email,
$data->uuid,
'lech_uuid_khop_theo_email',
"Khách portal #{$existing->id} có uuid khác WHMCS ({$data->uuid}), đã khớp theo email."
. ($filled ? ' Đã bổ sung: ' . implode(', ', array_keys($filled)) . '.' : ' Không có trường nào cần bổ sung.'),
);
CustomerIdResolver::flush();
}
}
@@ -4,16 +4,18 @@ 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)
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
{
@@ -21,26 +23,62 @@ class CustomerDomainWriter
return false;
}
DB::table('module_domain')->updateOrInsert(
['legacy_id' => $data->legacyId],
[
'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,
]
);
$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,
];
$this->dnsLinker->link($data->name, $data->customerId, $data->registrarId);
$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') . '.',
);
}
}
@@ -0,0 +1,87 @@
<?php
namespace App\Integrations\Whmcs\Writers;
use App\Integrations\Whmcs\Support\SyncReport;
use App\Support\PhoneNumber;
use Modules\Lead\App\Models\Lead;
class LeadWriter
{
private const FLAGS = [
'receives_invoice_emails' => 'invoiceemails',
'receives_domain_emails' => 'domainemails',
'receives_support_emails' => 'supportemails',
'receives_product_emails' => 'productemails',
'receives_general_emails' => 'generalemails',
];
public function __construct(private SyncReport $report)
{
}
public function write(object $row, ?int $customerId): void
{
$email = strtolower(trim((string) $row->email));
if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->report->note('contact', $email, $row->id, 'email_khong_hop_le', 'Email liên hệ không hợp lệ, bỏ qua.');
return;
}
if (preg_match('/\.kgm$/i', $email)) {
$this->report->note('contact', $email, $row->id, 'email_nghi_sai', 'Email có đuôi .kgm, giữ nguyên như WHMCS.');
}
$attributes = $this->attributes($row, $customerId);
$lead = Lead::query()->where('email', $email)->first();
if ($lead === null) {
Lead::create([...$attributes, 'email' => $email, 'legacy_id' => $row->id, 'source' => 'whmcs_contact', 'status' => 'new']);
return;
}
$this->merge($lead, $attributes, $row);
}
private function attributes(object $row, ?int $customerId): array
{
$fullname = trim("{$row->firstname} {$row->lastname}") ?: ($row->companyname ?: null);
$address = implode(', ', array_filter([$row->address1, $row->address2, $row->city, $row->state, $row->country]));
$flags = array_map(fn (string $column) => (bool) $row->{$column}, self::FLAGS);
return [
'customer_id' => $customerId,
'whmcs_client_id' => $row->userid,
'fullname' => $fullname,
'company' => $row->companyname ?: null,
'phone' => PhoneNumber::normalize($row->phonenumber),
'address' => $address ?: null,
'note' => $customerId === null ? "Liên hệ của khách WHMCS #{$row->userid} (khách đã bị xoá)." : null,
...$flags,
];
}
private function merge(Lead $lead, array $incoming, object $row): void
{
$update = [];
foreach (['customer_id', 'whmcs_client_id', 'fullname', 'company', 'phone', 'address', 'note'] as $column) {
if (blank($lead->{$column}) && filled($incoming[$column])) {
$update[$column] = $incoming[$column];
}
}
foreach (array_keys(self::FLAGS) as $flag) {
if (! $lead->{$flag} && $incoming[$flag]) {
$update[$flag] = true;
}
}
if ($lead->legacy_id === null && ! Lead::where('legacy_id', $row->id)->exists()) {
$update['legacy_id'] = $row->id;
}
if ($update !== []) {
$lead->update($update);
}
$this->report->note('contact', $lead->email, $row->id, 'email_trung_da_gop', "Email đã có ở khách tiềm năng {$lead->uuid}; gộp liên hệ WHMCS #{$row->id}" . ($update ? ', bổ sung: ' . implode(', ', array_keys($update)) : '') . '.');
}
}