Files
portal-api/app/Integrations/Whmcs/Transformers/ClientTransformer.php
T
2026-09-09 16:56:22 +07:00

77 lines
2.6 KiB
PHP

<?php
namespace App\Integrations\Whmcs\Transformers;
use App\Integrations\Whmcs\DTOs\ClientData;
use Illuminate\Support\Facades\DB;
class ClientTransformer
{
/** @var array<string, int>|null fullname => user id, cached for the process lifetime */
private static ?array $salerIdsByName = null;
/**
* Map a raw `tblclients` row (array or stdClass) to a ClientData DTO.
*/
public function transform(array|object $row): ClientData
{
$row = (array) $row;
$fullname = trim(($row['firstname'] ?? '') . ' ' . ($row['lastname'] ?? ''));
if ($fullname === '') {
$fullname = $row['companyname'] ?: null;
}
return new ClientData(
uuid: $row['uuid'],
fullname: $fullname,
company: $row['companyname'] ?: null,
address: trim(($row['address1'] ?? '') . ', ' . ($row['address2'] ?? ''), ', ') ?: null,
state: $row['state'] ?: null,
city: $row['city'] ?: null,
// ponytail: WHMCS repurposes the `postcode` column to store the salesperson's fullname
saler: $this->resolveSalerId($row['postcode'] ?? null),
country: $row['country'] ?: null,
phone: $this->formatPhone($row['phonenumber'] ?? null),
email: $row['email'] ? strtolower($row['email']) : null,
// ponytail: WHMCS hashes are not Laravel bcrypt, copied as-is; customer must reset password to log into portal
password: $row['password'] ?: null,
note: $row['notes'] ?: null,
credit: (int) round((float) $row['credit']),
status: $row['status'] === 'Active' ? 1 : 0,
emailMarketing: ((int) ($row['emailoptout'] ?? 0)) === 1 ? 0 : 1,
createdAt: $row['created_at'] ?: $row['datecreated'] ?: null,
updatedAt: $row['updated_at'] ?: $row['datecreated'] ?: null,
);
}
private function resolveSalerId(?string $fullname): ?int
{
if (! $fullname) {
return null;
}
self::$salerIdsByName ??= DB::table('user')->pluck('id', 'fullname')->all();
return self::$salerIdsByName[$fullname] ?? null;
}
/**
* "+84.93 613 68 14" -> "0936136814"; other country codes keep their digits as-is (e.g. "+62..." -> "62...").
*/
private function formatPhone(?string $raw): ?string
{
if (! $raw) {
return null;
}
$digits = preg_replace('/\D+/', '', $raw);
if (str_starts_with($digits, '84')) {
$digits = '0' . substr($digits, 2);
}
return $digits ?: null;
}
}