Add feature tests for domain order management

- Implement AdminDomainOrderTest to cover admin functionalities for domain orders including listing, confirming registration, KYC updates, activation, rejection, and refunds.
- Implement ClientDomainOrderTest to cover client functionalities for placing domain orders, including validation for balance, duplicate orders, and domain normalization.
- Ensure proper handling of domain pricing and service statuses throughout the tests.
This commit is contained in:
baodev0
2026-07-10 14:16:35 +07:00
parent 61c0e026c8
commit dfb926055d
81 changed files with 35743 additions and 481 deletions
+93 -8
View File
@@ -2,6 +2,7 @@
namespace App\Services\Api\Client;
use App\Mail\Customer\VerifyAccount as VerifyAccountMail;
use App\Mail\Customer\Welcome as WelcomeMail;
use App\Models\RefreshToken;
use App\Repositories\Api\Client\ClientRepositoryInterface;
@@ -39,12 +40,18 @@ class ClientAuthService
if ((int)$client->status !== 1) {
$statusLabel = match ((int)$client->status) {
0 => 'chờ xác thực',
0 => 'PENDING_VERIFY',
2 => 'tạm ngưng hoạt động',
3 => 'bị khoá',
default => 'vô hiệu hoá',
};
if ($statusLabel === 'PENDING_VERIFY') {
throw ValidationException::withMessages([
'email' => ['PENDING_VERIFY'],
]);
}
throw ValidationException::withMessages([
'email' => ["Tài khoản của bạn đã {$statusLabel}, vui lòng liên hệ hotline."],
]);
@@ -60,18 +67,53 @@ class ClientAuthService
}
/**
* Đăng ký khách hàng mới và tạo access + refresh token
* Đăng ký khách hàng mới — status=0 (chờ xác thực OTP), chưa cấp token.
*/
public function registerClient(array $data): array
{
$code = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
$client = $this->clientRepository->create([
'fullname' => $data['fullname'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'fullname' => $data['fullname'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'status' => 0,
'email_verify_code' => $code,
'email_verify_code_expired_at' => now()->addMinutes(5),
]);
$token = JWTAuth::fromUser($client);
$this->sendVerifyEmail($client, $code);
return ['client' => $client];
}
/**
* Xác thực OTP — kích hoạt tài khoản, trả về token.
*/
public function verifyEmail(string $email, string $code): array
{
$client = \App\Models\Customer::whereRaw('LOWER(email) = ?', [strtolower(trim($email))])->first();
if (! $client || $client->email_verify_code !== $code) {
throw ValidationException::withMessages([
'code' => ['Mã xác thực không chính xác.'],
]);
}
if (! $client->email_verify_code_expired_at || now()->gt($client->email_verify_code_expired_at)) {
throw ValidationException::withMessages([
'code' => ['Mã xác thực đã hết hạn, vui lòng yêu cầu gửi lại.'],
]);
}
$client->status = 1;
$client->email_verify_code = null;
$client->email_verify_code_expired_at = null;
$client->email_verified_at = now();
$client->save();
$token = JWTAuth::fromUser($client);
$refreshToken = $this->createRefreshToken($client->id);
$this->sendWelcomeEmail($client);
@@ -84,7 +126,50 @@ class ClientAuthService
}
/**
* Gửi email chào mừng cho khách hàng mới đăng ký.
* Gửi lại OTP xác thực (rate limit bởi caller nếu cần).
*/
public function resendVerifyCode(string $email): void
{
$client = \App\Models\Customer::whereRaw('LOWER(email) = ?', [strtolower(trim($email))])->first();
if (! $client || $client->status !== 0) {
return;
}
// Nếu mã cũ còn hạn thì không gửi lại — phải đợi hết hạn
if ($client->email_verify_code_expired_at && now()->lt($client->email_verify_code_expired_at)) {
throw ValidationException::withMessages([
'email' => ['Mã xác thực vẫn còn hiệu lực, vui lòng kiểm tra email của bạn.'],
]);
}
$code = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
$client->email_verify_code = $code;
$client->email_verify_code_expired_at = now()->addMinutes(5);
$client->save();
$this->sendVerifyEmail($client, $code);
}
protected function sendVerifyEmail($client, string $code): void
{
try {
Mail::to($client->email)->send(new VerifyAccountMail([
'fullname' => $client->fullname,
'email' => $client->email,
'verify_code' => $code,
]));
} catch (\Throwable $e) {
Log::warning('Send verify email failed: ' . $e->getMessage(), [
'customer_id' => $client->id,
'email' => $client->email,
]);
}
}
/**
* Gửi email chào mừng sau khi xác thực tài khoản thành công.
*/
protected function sendWelcomeEmail($client): void
{
@@ -0,0 +1,413 @@
<?php
namespace App\Services\Api\Domain;
use App\Enums\Domain\DomainProvisioningStatus;
use App\Enums\Invoice\InvoiceStatus;
use App\Enums\Order\OrderStatus;
use App\Enums\Product\ProductTypeEnums;
use App\Enums\TransactionStatus;
use App\Helpers\OrderHelper;
use App\Models\Customer;
use App\Models\DnsDomain;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\Log as CustomerActivityLog;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\Service;
use App\Models\Setting;
use App\Models\Transaction;
use App\Repositories\Api\Domain\DomainOrderRepository;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class DomainOrderService
{
public function __construct(
private readonly DomainOrderRepository $repo,
) {}
// =========================================================================
// Client: Place domain order
// =========================================================================
/**
* @return array{order: Order, invoice: Invoice, service: Service}
*/
public function placeOrder(array $data, Customer $customer): array
{
$product = Product::where('uuid', $data['product_uuid'])
->where('product_type', ProductTypeEnums::DOMAIN->value)
->where('is_active', true)
->whereNull('deleted_at')
->firstOrFail();
$domainName = $this->normalizeDomain($data['domain_name']);
$years = max(1, (int) ($data['years'] ?? 1));
$pricing = $this->findDomainPricing($domainName);
$price = (int) $pricing['firstYear'] * $years;
$months = $years * 12;
return DB::transaction(function () use ($customer, $product, $domainName, $price, $months, $years) {
$lockedCustomer = Customer::lockForUpdate()->find($customer->id);
if ((int) $lockedCustomer->total < $price) {
throw new \InvalidArgumentException('Số dư không đủ để đặt mua tên miền. Vui lòng nạp thêm tiền vào tài khoản.');
}
if ($this->repo->hasPendingOrActiveDomainByName($domainName)) {
throw new \InvalidArgumentException('Tên miền đang có đơn xử lý hoặc đã được kích hoạt. Vui lòng chọn tên miền khác.');
}
if (DnsDomain::where('domain_name', $domainName)->exists()) {
throw new \InvalidArgumentException('Tên miền đã được đăng ký trong hệ thống. Vui lòng chọn tên miền khác.');
}
$lockedCustomer->decrement('total', $price);
$order = Order::create([
'order_num' => OrderHelper::generateOrderNumber(),
'customer_id' => $lockedCustomer->id,
'sub_total' => $price,
'discount_amount' => 0,
'total' => $price,
'status' => OrderStatus::PROCESSING->value,
'payment_method' => 'balance',
'client_ip' => request()?->ip(),
'note' => "Đăng ký tên miền: {$domainName} ({$years} năm)",
]);
$orderItem = OrderItem::create([
'order_id' => $order->id,
'product_id' => $product->id,
'domain_name' => $domainName,
'billing_cycle' => 'yearly',
'months' => $months,
'quantity' => 1,
'price' => $price,
'server_name' => $domainName,
]);
$invoice = Invoice::create([
'invoice_number' => OrderHelper::generateOrderNumber('INV'),
'customer_id' => $lockedCustomer->id,
'order_id' => $order->id,
'invoice_type' => 1, // new
'sub_total' => $price,
'discount_amount' => 0,
'tax' => 0,
'total' => $price,
'status' => InvoiceStatus::PAID->value,
'payment_method' => 'balance',
'paid_at' => now(),
'due_date' => now()->toDateString(),
'client_ip' => request()?->ip(),
]);
InvoiceItem::create([
'invoice_id' => $invoice->id,
'product_id' => $product->id,
'type' => 'domain',
'description' => "Đăng ký tên miền {$domainName} ({$years} năm)",
'months' => $months,
'quantity' => 1,
'unit_price' => $price,
'total_price' => $price,
]);
Transaction::create([
'uuid' => (string) Str::uuid(),
'public_code' => 'DOM-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)),
'trans' => $invoice->invoice_number,
'amount' => $price,
'customer_id' => $lockedCustomer->id,
'status' => TransactionStatus::COMPLETED->value,
'type' => 'invoice',
'note' => "Thanh toán đăng ký tên miền {$domainName} ({$years} năm) - {$invoice->invoice_number} (balance)",
]);
CustomerActivityLog::create([
'agent' => 'api',
'client_ip' => request()?->ip(),
'customer_id' => $lockedCustomer->id,
'description' => "Đặt mua tên miền {$domainName} ({$years} năm). Số tiền: " . number_format($price) . " VNĐ. Mã đơn hàng: {$order->order_num}.",
]);
$service = Service::create([
'customer_id' => $lockedCustomer->id,
'product_id' => $product->id,
'order_item_id' => $orderItem->id,
'invoice_id' => $invoice->id,
'server_name' => $domainName,
'status' => DomainProvisioningStatus::PENDING->value,
'auto_renew' => false,
]);
return compact('order', 'invoice', 'service');
});
}
// =========================================================================
// Admin: Confirm registration → create DNS domain entry
// =========================================================================
public function confirmRegistration(Order $order, array $data): Service
{
return DB::transaction(function () use ($order, $data) {
$lockedOrder = Order::lockForUpdate()->find($order->id);
$orderItem = $lockedOrder->orderItems()
->whereHas('product', fn ($q) => $q->where('product_type', ProductTypeEnums::DOMAIN->value))
->with('service')
->firstOrFail();
$service = $orderItem->service;
if (!$service || $service->status !== DomainProvisioningStatus::PENDING->value) {
throw new \InvalidArgumentException('Đơn hàng không ở trạng thái chờ xử lý. Không thể xác nhận đăng ký.');
}
$domainName = strtolower(trim($orderItem->domain_name));
if (DnsDomain::where('domain_name', $domainName)->exists()) {
throw new \InvalidArgumentException("Tên miền {$domainName} đã tồn tại trong DNS Manager.");
}
$dnsDomain = DnsDomain::create([
'domain_name' => $domainName,
'dns_manager_server_id' => $data['dns_manager_server_id'] ?? 0,
'is_created' => 1,
]);
$dnsDomain->customer()->syncWithoutDetaching([$lockedOrder->customer_id]);
$nextStatus = !empty($data['kyc_url'])
? DomainProvisioningStatus::PENDING_KYC->value
: DomainProvisioningStatus::REGISTRAR_CREATED->value;
$serviceUpdate = [
'status' => $nextStatus,
'registrar_reference' => $data['registrar_reference'] ?? null,
'kyc_url' => $data['kyc_url'] ?? null,
];
if (!empty($data['registered_at'])) {
$serviceUpdate['started_at'] = $data['registered_at'];
}
if (!empty($data['expires_at'])) {
$serviceUpdate['expires_at'] = $data['expires_at'];
}
$service->update($serviceUpdate);
return $service->fresh();
});
}
// =========================================================================
// Admin: Update KYC URL
// =========================================================================
public function updateKycUrl(Order $order, string $kycUrl): Service
{
return DB::transaction(function () use ($order, $kycUrl) {
$orderItem = $order->orderItems()
->whereHas('product', fn ($q) => $q->where('product_type', ProductTypeEnums::DOMAIN->value))
->with('service')
->firstOrFail();
$service = $orderItem->service;
if (!$service) {
throw new \InvalidArgumentException('Không tìm thấy dịch vụ cho đơn hàng này.');
}
$allowedStatuses = [
DomainProvisioningStatus::REGISTRAR_CREATED->value,
DomainProvisioningStatus::PENDING_KYC->value,
];
if (!in_array($service->status, $allowedStatuses, true)) {
throw new \InvalidArgumentException('Chỉ có thể cập nhật KYC khi tên miền đã được tạo tại nhà đăng ký hoặc đang chờ KYC.');
}
$service->update([
'kyc_url' => $kycUrl,
'status' => DomainProvisioningStatus::PENDING_KYC->value,
]);
return $service->fresh();
});
}
// =========================================================================
// Admin: Activate domain service
// =========================================================================
public function activate(Order $order): Service
{
return DB::transaction(function () use ($order) {
$orderItem = $order->orderItems()
->whereHas('product', fn ($q) => $q->where('product_type', ProductTypeEnums::DOMAIN->value))
->with('service')
->firstOrFail();
$service = $orderItem->service;
if (!$service) {
throw new \InvalidArgumentException('Không tìm thấy dịch vụ cho đơn hàng này.');
}
$activatableStatuses = [
DomainProvisioningStatus::REGISTRAR_CREATED->value,
DomainProvisioningStatus::PENDING_KYC->value,
];
if (!in_array($service->status, $activatableStatuses, true)) {
throw new \InvalidArgumentException('Chỉ có thể kích hoạt tên miền sau khi đã tạo tại nhà đăng ký (hoặc sau khi KYC).');
}
$service->update([
'status' => DomainProvisioningStatus::ACTIVE->value,
'started_at' => $service->started_at ?? now(),
]);
$order->update(['status' => OrderStatus::ACTIVE->value]);
return $service->fresh();
});
}
// =========================================================================
// Admin: Reject and refund
// =========================================================================
public function rejectAndRefund(Order $order, string $reason): Service
{
return DB::transaction(function () use ($order, $reason) {
$lockedOrder = Order::lockForUpdate()->find($order->id);
$orderItem = $lockedOrder->orderItems()
->whereHas('product', fn ($q) => $q->where('product_type', ProductTypeEnums::DOMAIN->value))
->with('service')
->firstOrFail();
$service = $orderItem->service;
if (!$service || $service->status !== DomainProvisioningStatus::PENDING->value) {
throw new \InvalidArgumentException('Chỉ có thể từ chối đơn hàng đang chờ xử lý.');
}
// Anti-double-refund guard
if ($service->refunded_at !== null) {
throw new \InvalidArgumentException('Đơn hàng này đã được hoàn tiền trước đó.');
}
$invoice = $lockedOrder->invoice;
if (!$invoice || (int) $invoice->status !== InvoiceStatus::PAID->value) {
throw new \InvalidArgumentException('Không tìm thấy hóa đơn đã thanh toán.');
}
$refundAmount = (int) $invoice->total; // snapshot — NOT recalculated
$lockedCustomer = Customer::lockForUpdate()->find($lockedOrder->customer_id);
if (!$lockedCustomer) {
throw new \InvalidArgumentException('Không tìm thấy khách hàng.');
}
$lockedCustomer->increment('total', $refundAmount);
$invoice->update(['status' => InvoiceStatus::REFUNDED->value]);
$lockedOrder->update(['status' => OrderStatus::CANCELLED->value]);
$service->update([
'status' => DomainProvisioningStatus::REFUNDED->value,
'rejection_reason' => $reason,
'refunded_at' => now(),
'cancelled_at' => now(),
]);
Transaction::create([
'uuid' => (string) Str::uuid(),
'public_code' => 'DOM-REF-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)),
'trans' => 'REF-' . $invoice->invoice_number,
'amount' => $refundAmount,
'customer_id' => $lockedCustomer->id,
'status' => TransactionStatus::COMPLETED->value,
'type' => 'refund',
'note' => "Hoàn tiền đăng ký tên miền {$orderItem->domain_name}: {$reason} (balance)",
]);
CustomerActivityLog::create([
'agent' => 'api',
'client_ip' => request()?->ip(),
'customer_id' => $lockedCustomer->id,
'description' => "Hoàn tiền đăng ký tên miền {$orderItem->domain_name}. Số tiền: " . number_format($refundAmount) . " VNĐ. Lý do: {$reason}.",
]);
return $service->fresh();
});
}
// =========================================================================
// Private helpers
// =========================================================================
/**
* Find pricing for the given domain using longest-match TLD.
* TLDs in settings are stored with a leading dot (e.g. ".com.vn").
*
* @throws \InvalidArgumentException if no matching TLD found
*/
private function findDomainPricing(string $domain): array
{
$setting = Setting::where('key', 'domain_pricing')->first();
if (!$setting || empty($setting->value)) {
throw new \InvalidArgumentException('Không tìm thấy cấu hình giá tên miền.');
}
$pricingData = is_string($setting->value)
? json_decode($setting->value, true)
: (array) $setting->value;
$domains = $pricingData['domains'] ?? [];
// Longest-match: sort TLDs by length descending so ".com.vn" beats ".vn"
usort($domains, fn ($a, $b) => strlen($b['tld']) - strlen($a['tld']));
foreach ($domains as $entry) {
$tld = ltrim($entry['tld'], '.');
if (str_ends_with($domain, '.' . $tld)) {
return $entry;
}
}
throw new \InvalidArgumentException("Tên miền không được hỗ trợ. Vui lòng chọn đuôi tên miền có trong danh sách.");
}
/**
* Normalize: lowercase, trim, strip protocol and path.
* "HTTPS://My-Site.COM.VN/path" → "my-site.com.vn"
*/
private function normalizeDomain(string $domain): string
{
$domain = strtolower(trim($domain));
// Strip protocol
$domain = preg_replace('#^https?://#', '', $domain);
// Strip path/query after first slash
$domain = explode('/', $domain)[0];
// Strip www. prefix
$domain = preg_replace('#^www\.#', '', $domain);
return $domain;
}
}
+24 -1
View File
@@ -24,7 +24,7 @@ class InvoicePdfService
'companyAddress' => $settingValue->address ?? '',
'companyPhone' => $settingValue->hotline ?? ($settingValue->tel ?? ''),
'companyEmail' => $settingValue->email ?? '',
'companyLogo' => $settingValue->logo ?? '',
'companyLogo' => $this->resolvePdfImagePath($settingValue->logo ?? ''),
'companyTaxCode' => $settingValue->tax ?? '',
'brandColor' => $settingValue->brand_color ?? '#1a56db',
'cfg' => [
@@ -50,4 +50,27 @@ class InvoicePdfService
{
return 'Hoa-don-' . $invoice->invoice_number . '.pdf';
}
private function resolvePdfImagePath(?string $path): string
{
if (!$path) {
return '';
}
$urlPath = parse_url($path, PHP_URL_PATH) ?: $path;
if (str_starts_with($urlPath, '/storage/')) {
$localPath = storage_path('app/public/' . ltrim(substr($urlPath, strlen('/storage/')), '/'));
return file_exists($localPath) ? $localPath : $path;
}
if (str_starts_with($path, 'storage/')) {
$localPath = storage_path('app/public/' . substr($path, strlen('storage/')));
return file_exists($localPath) ? $localPath : $path;
}
return $path;
}
}
+24 -1
View File
@@ -26,7 +26,7 @@ class WebDesignQuotePdfService
'companyAddress' => $settingValue->address ?? '',
'companyPhone' => $settingValue->hotline ?? ($settingValue->tel ?? ''),
'companyEmail' => $settingValue->email ?? '',
'companyLogo' => $settingValue->logo ?? '',
'companyLogo' => $this->resolvePdfImagePath($settingValue->logo ?? ''),
'companyTaxCode' => $settingValue->tax ?? '',
'brandColor' => $settingValue->brand_color ?? '#1a56db',
];
@@ -40,4 +40,27 @@ class WebDesignQuotePdfService
{
return 'Bao-gia-' . $quote->quote_number . '.pdf';
}
private function resolvePdfImagePath(?string $path): string
{
if (!$path) {
return '';
}
$urlPath = parse_url($path, PHP_URL_PATH) ?: $path;
if (str_starts_with($urlPath, '/storage/')) {
$localPath = storage_path('app/public/' . ltrim(substr($urlPath, strlen('/storage/')), '/'));
return file_exists($localPath) ? $localPath : $path;
}
if (str_starts_with($path, 'storage/')) {
$localPath = storage_path('app/public/' . substr($path, strlen('storage/')));
return file_exists($localPath) ? $localPath : $path;
}
return $path;
}
}