Files

80 lines
2.8 KiB
PHP

<?php
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
{
$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();
}
}