This commit is contained in:
baodev0
2026-09-23 15:17:18 +07:00
parent cd38c5d6d0
commit 82a71244ca
107 changed files with 3332 additions and 3306 deletions
+67 -17
View File
@@ -4,7 +4,7 @@ namespace App\Services\Api\Client;
use App\Http\Services\Telegram;
use App\Mail\Admin\TrialRegistrationRequest as TrialRegistrationRequestMail;
use App\Mail\Customer\PasswordResetByAdmin;
use App\Mail\Customer\PasswordResetLink;
use App\Mail\Customer\VerifyAccount as VerifyAccountMail;
use App\Mail\Customer\Welcome as WelcomeMail;
use App\Models\Customer;
@@ -12,10 +12,11 @@ use App\Models\RefreshToken;
use App\Models\Setting;
use App\Repositories\Api\Client\ClientRepositoryInterface;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Tymon\JWTAuth\Facades\JWTAuth;
@@ -25,6 +26,8 @@ class ClientAuthService
// Refresh token lifetime in days
const REFRESH_TOKEN_TTL_DAYS = 30;
const VERIFY_MAX_ATTEMPTS = 5;
protected $clientRepository;
public function __construct(ClientRepositoryInterface $clientRepository)
@@ -143,12 +146,28 @@ class ClientAuthService
{
$client = \App\Models\Customer::whereRaw('LOWER(email) = ?', [strtolower(trim($email))])->first();
if (! $client || $client->email_verify_code !== $code) {
// Chống brute-force mã 6 số: sai quá VERIFY_MAX_ATTEMPTS lần thì huỷ mã, buộc gửi lại.
$attemptKey = 'verify-email:' . strtolower(trim($email));
if (! $client || ! $client->email_verify_code || ! hash_equals($client->email_verify_code, $code)) {
if ($client?->email_verify_code && RateLimiter::hit($attemptKey, 600) >= self::VERIFY_MAX_ATTEMPTS) {
RateLimiter::clear($attemptKey);
$client->email_verify_code = null;
$client->email_verify_code_expired_at = null;
$client->save();
throw ValidationException::withMessages([
'code' => ['Nhập sai quá nhiều lần, vui lòng yêu cầu gửi lại mã xác thực.'],
]);
}
throw ValidationException::withMessages([
'code' => ['Mã xác thực không chính xác.'],
]);
}
RateLimiter::clear($attemptKey);
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.'],
@@ -305,10 +324,11 @@ class ClientAuthService
}
/**
* Cấp mật khẩu mới ngẫu nhiên khi khách hàng quên mật khẩu. Không tiết lộ
* email có tồn tại hay không — trả về null nếu không tìm thấy tài khoản.
* Gửi link đặt lại mật khẩu (token một lần, hết hạn theo auth.passwords.users.expire).
* Không đổi mật khẩu ngay — chỉ chủ hộp thư mới đổi được. Trả về null nếu không có
* tài khoản; caller không được tiết lộ kết quả cho client.
*/
public function resetForgottenPassword(string $email): ?Customer
public function sendPasswordResetLink(string $email): ?Customer
{
$customer = Customer::whereRaw('LOWER(email) = ?', [strtolower(trim($email))])->first();
@@ -316,22 +336,49 @@ class ClientAuthService
return null;
}
$newPassword = Str::password(16);
// Broker tự throttle theo email (auth.passwords.users.throttle).
Password::broker('users')->sendResetLink(
['email' => $customer->email],
function (Customer $customer, string $token) {
$url = rtrim(config('app.frontend_url'), '/') . '/dat-lai-mat-khau?' . http_build_query([
'token' => $token,
'email' => $customer->email,
]);
DB::transaction(function () use ($customer, $newPassword) {
$customer->password = Hash::make($newPassword);
$customer->save();
Mail::to($customer->email)->later(now()->addSeconds(5), new PasswordResetByAdmin([
'fullname' => $customer->fullname,
'email' => $customer->email,
'password' => $newPassword,
]));
});
Mail::to($customer->email)->queue(new PasswordResetLink([
'fullname' => $customer->fullname,
'reset_url' => $url,
]));
},
);
return $customer;
}
/**
* Đặt lại mật khẩu bằng token trong email. Thành công thì thu hồi toàn bộ refresh token
* để các phiên cũ (có thể của kẻ gian) phải đăng nhập lại.
*/
public function resetPassword(array $data): ?Customer
{
$resetCustomer = null;
$status = Password::broker('users')->reset($data, function (Customer $customer, string $password) use (&$resetCustomer) {
$customer->password = Hash::make($password);
$customer->save();
RefreshToken::where('customer_id', $customer->id)->delete();
$resetCustomer = $customer;
});
if ($status !== Password::PASSWORD_RESET) {
throw ValidationException::withMessages([
'token' => ['Link đặt lại mật khẩu không hợp lệ hoặc đã hết hạn.'],
]);
}
return $resetCustomer;
}
/**
* Cập nhật thông tin cá nhân. Trả về old/dirty values để caller ghi activity log.
*/
@@ -375,5 +422,8 @@ class ClientAuthService
$client->password = Hash::make($newPassword);
$client->save();
// Access token cũ tự vô hiệu nhờ claim `pv`; thu hồi luôn refresh token để mọi phiên phải đăng nhập lại.
RefreshToken::where('customer_id', $client->id)->delete();
}
}
-110
View File
@@ -5,14 +5,8 @@ namespace App\Services\Api\Order;
use App\Enums\Order\OrderStatus;
use App\Helpers\OrderHelper;
use App\Jobs\Mail\Admin\AdminOrderNotificationJob;
use App\Jobs\VirtualMachine\Create\CreateVirtualMachineJob;
use App\Models\VmProvisionLock;
use App\Models\Addon;
use App\Models\Log as CustomerActivityLog;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Service;
use App\Models\ServiceAddon;
use App\Repositories\Api\Invoice\InvoiceRepository;
use App\Repositories\Api\Order\OrderRepository;
use App\Repositories\Api\Service\ServiceRepository;
@@ -144,110 +138,6 @@ class OrderService
});
}
// =========================================================================
// Private — provisionService
// =========================================================================
private function provisionService(Order $order, OrderItem $item, $customer): void
{
$invoice = $order->invoice;
$months = $item->months ?: OrderHelper::cycleToMonths($item->billing_cycle);
$expiresAt = now()->addMonths($months);
$service = Service::create([
'customer_id' => $customer->id,
'product_id' => $item->product_id,
'type' => $item->product?->product_type,
'order_item_id' => $item->id,
'invoice_id' => $invoice?->id,
'server_name' => $item->server_name,
'status' => 'pending',
'auto_renew' => false,
'started_at' => now(),
'expires_at' => $expiresAt,
]);
$this->attachServiceAddons($service, $item);
// VPS: requires product + os_id → dispatch VM creation job
if ($item->product_id && $item->os_id) {
$this->dispatchVmJob($order, $item, $service, $customer);
} else {
// Hosting / Domain / non-VM services activate immediately
$service->update(['status' => 'active']);
}
}
// -------------------------------------------------------------------------
/**
* Create ServiceAddon rows from:
* 1. Base product specs (cpu, ram, disk, bandwidth)
* 2. Customer's configurable addon selections stored in addons_meta
*/
private function attachServiceAddons(Service $service, OrderItem $item): void
{
// 1. Base product specs
$product = $item->product;
if ($product) {
foreach (['cpu' => $product->cpu, 'ram' => $product->ram, 'disk' => $product->disk, 'bandwidth' => $product->bandwidth] as $type => $value) {
if ($value !== null && $value !== '') {
ServiceAddon::create([
'service_id' => $service->id,
'addon_type' => $type,
'addon_value' => (string) $value,
'price' => 0,
]);
}
}
}
// 2. Customer-selected addons
$addonsMeta = is_array($item->addons_meta)
? $item->addons_meta
: json_decode($item->addons_meta ?? '[]', true);
foreach ((array) $addonsMeta as $meta) {
$addon = Addon::find($meta['addon_id'] ?? null);
if (!$addon) {
continue;
}
ServiceAddon::create([
'service_id' => $service->id,
'addon_type' => strtolower((string) $addon->code),
'addon_value' => (string) ($meta['qty'] ?? 1),
'price' => (int) ($meta['price'] ?? $addon->price),
]);
}
}
// -------------------------------------------------------------------------
private function dispatchVmJob(Order $order, OrderItem $item, Service $service, $customer): void
{
try {
if (VmProvisionLock::isRunning($customer->id)) {
Log::warning('dispatchVmJob: blocked — customer already has a running VM provision', [
'customer_id' => $customer->id,
'order_item_id' => $item->id,
]);
return;
}
dispatch(new CreateVirtualMachineJob($item));
Log::info('dispatchVmJob: CreateVirtualMachineJob dispatched', [
'order_id' => $order->id,
'service_id' => $service->id,
'order_item_id' => $item->id,
]);
} catch (Exception $e) {
Log::error('dispatchVmJob: exception', [
'order_id' => $order->id,
'error' => $e->getMessage(),
]);
}
}
// =========================================================================
// Helpers
@@ -1,160 +0,0 @@
<?php
namespace App\Services;
use App\Models\EmailNotificationTemplate;
use App\Models\Invoice;
use Illuminate\Support\Facades\View;
class EmailNotificationTemplateRenderer
{
private const BANNERS = [
'vm_credentials' => 'https://res.cloudinary.com/izpast9i/image/upload/v1786503590/email_banner_cloud_vps.png',
];
public function render(EmailNotificationTemplate $tpl, Invoice $invoice, string $companyName = ''): string
{
$blocks = collect($tpl->blocks)
->filter(fn($b) => $b['enabled'] ?? false)
->sortBy('order')
->values();
$bodyHtml = '';
foreach ($blocks as $block) {
$bodyHtml .= $this->renderBlock($block, $invoice, $companyName);
}
$title = $tpl->header_title ?? 'Thông báo hóa đơn';
return $this->wrapLayout($title, $bodyHtml, $companyName, self::BANNERS[$tpl->type] ?? null);
}
/**
* Render a vm_credentials template using the emailData array from SendVmCredentialsEmailJob.
* $emailData keys: company_name, client_name, product_name, product_billing, product_price,
* service_host, service_username, service_port, service_password, os_name, service_due_exp
*/
public function renderVmCredentials(EmailNotificationTemplate $tpl, array $emailData, ?Invoice $invoice = null): string
{
$blocks = collect($tpl->blocks)
->filter(fn($b) => $b['enabled'] ?? false)
->sortBy('order')
->values();
$companyName = $emailData['company_name'] ?? '';
$bodyHtml = '';
foreach ($blocks as $block) {
$bodyHtml .= match ($block['type'] ?? '') {
'greeting' => $this->renderView('emails.partials.greeting', ['name' => $emailData['client_name'] ?? 'Quý khách']),
'vm_credentials' => $this->renderView('emails.partials.vm-credentials', ['fields' => $block['config']['fields'] ?? null, 'data' => $emailData]),
'product_info' => $this->renderView('emails.partials.product-info', ['fields' => $block['config']['fields'] ?? null, 'data' => $emailData]),
'invoice_info' => $invoice ? $this->renderView('emails.partials.invoice-info', ['fields' => $block['config']['fields'] ?? null, 'invoice' => $invoice]) : '',
'order_items' => $invoice ? $this->renderOrderItems($invoice) : '',
'attachments' => $invoice ? $this->renderAttachments($invoice) : '',
'custom_text' => $this->renderView('emails.partials.custom-text', ['content' => $block['config']['content'] ?? '']),
'footer' => $this->renderView('emails.partials.signature', ['companyName' => $companyName]),
default => '',
};
}
$title = $tpl->header_title ?? 'Thông tin truy cập VPS';
return $this->wrapLayout($title, $bodyHtml, $companyName, self::BANNERS[$tpl->type] ?? null);
}
public function renderPreview(EmailNotificationTemplate $tpl): string
{
if ($tpl->type === 'vm_credentials') {
return $this->renderVmCredentials($tpl, $this->sampleVmData(), null);
}
$invoice = $this->sampleInvoice();
return $this->render($tpl, $invoice, 'Công ty Demo');
}
// ─── Block renderers ──────────────────────────────────────────────────────
private function renderBlock(array $block, Invoice $invoice, string $companyName): string
{
return match ($block['type'] ?? '') {
'greeting' => $this->renderView('emails.partials.greeting', ['name' => $invoice->customer?->fullname ?? 'Quý khách']),
'invoice_info' => $this->renderView('emails.partials.invoice-info', ['fields' => $block['config']['fields'] ?? null, 'invoice' => $invoice]),
'customer_info' => $this->renderView('emails.partials.customer-info', ['fields' => $block['config']['fields'] ?? null, 'customer' => $invoice->customer]),
'order_items' => $this->renderOrderItems($invoice),
'attachments' => $this->renderAttachments($invoice),
'custom_text' => $this->renderView('emails.partials.custom-text', ['content' => $block['config']['content'] ?? '']),
'footer' => $this->renderView('emails.partials.signature', ['companyName' => $companyName]),
default => '',
};
}
private function renderOrderItems(Invoice $invoice): string
{
$order = $invoice->order;
if (!$order) return '';
$order->loadMissing('orderItems.product');
return $this->renderView('emails.partials.order-items', ['items' => $order->orderItems]);
}
private function renderAttachments(Invoice $invoice): string
{
$invoice->loadMissing('attachments');
return $this->renderView('emails.partials.attachments', ['attachments' => $invoice->attachments]);
}
private function renderView(string $view, array $data): string
{
return View::make($view, $data)->render();
}
// ─── Layout wrapper ───────────────────────────────────────────────────────
private function wrapLayout(string $title, string $body, string $companyName, ?string $bannerUrl = null): string
{
return View::make('emails.layouts.notification', [
'title' => $title,
'body' => $body,
'companyName' => $companyName ?: config('app.name', 'Thế Giới Số'),
'bannerUrl' => $bannerUrl,
])->render();
}
// ─── Sample data for preview ──────────────────────────────────────────────
private function sampleVmData(): array
{
return [
'company_name' => 'Công ty Demo',
'company_logo' => '',
'client_name' => 'Nguyễn Văn A',
'product_name' => 'VPS Starter',
'product_billing' => 'Hàng tháng',
'product_price' => '420.000',
'service_host' => '203.113.x.x',
'service_username' => 'root',
'service_port' => '22',
'service_password' => 'P@ssw0rd!2026',
'os_name' => 'Ubuntu 22.04 LTS',
'service_due_exp' => date('d/m/Y', strtotime('+1 month')),
];
}
private function sampleInvoice(): Invoice
{
$invoice = new Invoice([
'invoice_number' => 'INV-20260521-00001',
'sub_total' => 420000,
'tax' => 0,
'total' => 420000,
'status' => 2,
'payment_method' => 'credit',
]);
$invoice->created_at = now();
$invoice->due_date = now()->addDays(7)->toDateString();
return $invoice;
}
}
+188 -20
View File
@@ -23,7 +23,30 @@ use Illuminate\Support\Str;
class InvoicePaymentService
{
public function payWithBalance(Invoice $invoice, Customer $customer, string $method = 'balance'): Invoice
/** Trạng thái hoá đơn còn có thể thu tiền. Dùng chung cho cả khách trả lẫn admin xác nhận. */
public const PAYABLE_STATUSES = [InvoiceStatus::UNPAID->value, InvoiceStatus::OVERDUE->value];
/**
* Chặn thu tiền trên hoá đơn đã huỷ/đã hoàn — trước đây chỉ payWithBalance() kiểm tra,
* markPaidByAdmin() thì không, nên hoá đơn CANCELLED vẫn bật sang PAID và kích hoạt dịch vụ thật.
*/
public static function assertPayable(Invoice $invoice): void
{
if (! in_array((int) $invoice->status, self::PAYABLE_STATUSES, true)) {
throw new \InvalidArgumentException(sprintf(
'Hóa đơn #%s đang ở trạng thái "%s", không thể ghi nhận thanh toán.',
$invoice->invoice_number,
InvoiceStatus::tryFrom((int) $invoice->status)?->label() ?? 'không xác định',
));
}
}
/**
* @param int|null $amount Số tiền muốn trả lần này. Null = trả hết phần còn thiếu.
* Trả ít hơn thì hoá đơn giữ nguyên UNPAID/OVERDUE, chỉ cộng dồn
* amount_paid — dịch vụ chưa được kích hoạt cho tới khi thu đủ.
*/
public function payWithBalance(Invoice $invoice, Customer $customer, string $method = 'balance', ?int $amount = null): Invoice
{
if ((int) $invoice->customer_id !== (int) $customer->id) {
throw new \InvalidArgumentException('Hóa đơn không thuộc tài khoản này.');
@@ -35,7 +58,7 @@ class InvoicePaymentService
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
}
return DB::transaction(function () use ($invoice, $customer, $method) {
return DB::transaction(function () use ($invoice, $customer, $method, $amount) {
// Lock both rows so two concurrent payment requests for the same invoice/customer
// (double-click, retry) cannot both pass the balance check before either commits.
$invoice = Invoice::where('id', $invoice->id)->lockForUpdate()->firstOrFail();
@@ -45,40 +68,61 @@ class InvoicePaymentService
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
}
if (! in_array((int) $invoice->status, [InvoiceStatus::UNPAID->value, InvoiceStatus::OVERDUE->value], true)) {
throw new \InvalidArgumentException('Hóa đơn không ở trạng thái có thể thanh toán.');
self::assertPayable($invoice);
$outstanding = self::outstanding($invoice);
$payNow = $amount === null ? $outstanding : min($amount, $outstanding);
if ($payNow <= 0) {
throw new \InvalidArgumentException('Số tiền thanh toán phải lớn hơn 0.');
}
if ((int) $customer->total < (int) $invoice->total) {
if ((int) $customer->total < $payNow) {
throw new \InvalidArgumentException(sprintf(
'Số dư không đủ. Hiện có: %s VNĐ, cần: %s VNĐ.',
number_format((int) $customer->total),
number_format((int) $invoice->total)
number_format($payNow)
));
}
$customer->decrement('total', (int) $invoice->total);
$customer->decrement('total', $payNow);
$paidSoFar = (int) $invoice->amount_paid + $payNow;
$settled = $paidSoFar >= (int) $invoice->total;
$invoice->update([
'status' => InvoiceStatus::PAID->value,
'paid_at' => now(),
'amount_paid' => $paidSoFar,
'status' => $settled ? InvoiceStatus::PAID->value : $invoice->status,
'paid_at' => $settled ? now() : null,
'payment_method' => $method,
]);
$this->recordTransaction($invoice, $method, 'Khách hàng thanh toán hóa đơn #' . $invoice->invoice_number);
$this->recordTransaction(
$invoice,
$method,
'Khách hàng thanh toán hóa đơn #' . $invoice->invoice_number
. ($settled ? '' : sprintf(' (một phần: %s/%s VNĐ)', number_format($paidSoFar), number_format((int) $invoice->total))),
amount: $payNow,
sequence: $settled && $payNow === (int) $invoice->total ? null : $paidSoFar,
);
CustomerActivityLog::create([
'agent' => 'api',
'client_ip' => request()?->ip(),
'customer_id' => $customer->id,
'description' => sprintf(
'Thanh toán hóa đơn #%s. Số tiền: %s VNĐ. Số dư còn: %s VNĐ.',
'Thanh toán hóa đơn #%s. Số tiền: %s VNĐ.%s Số dư còn: %s VNĐ.',
$invoice->invoice_number,
number_format((int) $invoice->total),
number_format($payNow),
$settled ? '' : sprintf(' Còn thiếu: %s VNĐ.', number_format(self::outstanding($invoice->fresh()))),
number_format((int) $customer->fresh()->total)
),
]);
if (! $settled) {
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
}
if ((int) $invoice->invoice_type === 2) {
$this->activateRenewal($invoice);
} elseif ($invoice->order) {
@@ -89,20 +133,67 @@ class InvoicePaymentService
});
}
public function markPaidByAdmin(Invoice $invoice, ?int $adminId = null, string $method = 'admin'): Invoice
/** Số tiền còn phải thu của một hoá đơn. */
public static function outstanding(Invoice $invoice): int
{
return max(0, (int) $invoice->total - (int) $invoice->amount_paid);
}
/**
* @param int|null $receivedAmount Số tiền admin xác nhận đã thực nhận. Null = thu đủ hoá đơn.
* Nhập ít hơn thì hoá đơn ghi nhận trả một phần và KHÔNG kích
* hoạt dịch vụ — tránh việc bấm "Đã thanh toán" khi tiền chưa
* về đủ mà sổ vẫn ghi đủ như trước.
*/
public function markPaidByAdmin(
Invoice $invoice,
?int $adminId = null,
string $method = 'admin',
?int $receivedAmount = null,
): Invoice {
if ((int) $invoice->status === InvoiceStatus::PAID->value) {
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
}
return DB::transaction(function () use ($invoice, $adminId, $method) {
return DB::transaction(function () use ($invoice, $adminId, $method, $receivedAmount) {
$invoice = Invoice::where('id', $invoice->id)->lockForUpdate()->firstOrFail();
if ((int) $invoice->status === InvoiceStatus::PAID->value) {
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
}
self::assertPayable($invoice);
$outstanding = self::outstanding($invoice);
$received = $receivedAmount === null ? $outstanding : min(max(0, $receivedAmount), $outstanding);
if ($received <= 0) {
throw new \InvalidArgumentException('Số tiền thực nhận phải lớn hơn 0.');
}
$paidSoFar = (int) $invoice->amount_paid + $received;
$settled = $paidSoFar >= (int) $invoice->total;
$invoice->update([
'status' => InvoiceStatus::PAID->value,
'paid_at' => now(),
'amount_paid' => $paidSoFar,
'status' => $settled ? InvoiceStatus::PAID->value : $invoice->status,
'paid_at' => $settled ? now() : null,
'payment_method' => $invoice->payment_method ?: $method,
]);
$this->recordTransaction($invoice, $method, 'Admin xác nhận thanh toán hóa đơn #' . $invoice->invoice_number, $adminId);
$this->recordTransaction(
$invoice,
$method,
'Admin xác nhận thanh toán hóa đơn #' . $invoice->invoice_number
. ($settled ? '' : sprintf(' (một phần: %s/%s VNĐ)', number_format($paidSoFar), number_format((int) $invoice->total))),
$adminId,
amount: $received,
sequence: $settled && $received === (int) $invoice->total ? null : $paidSoFar,
);
if (! $settled) {
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
}
if ((int) $invoice->invoice_type === 2) {
$this->activateRenewal($invoice);
@@ -114,18 +205,95 @@ class InvoicePaymentService
});
}
public function recordTransaction(Invoice $invoice, string $method, string $note, ?int $adminId = null): Transaction
/**
* Hoàn tiền hoá đơn đã thu: cộng lại số dư, ghi Transaction âm, chuyển hoá đơn sang REFUNDED.
* Trước đây chỉ luồng tên miền có hoàn tiền, VPS/hosting phải làm tay và không để lại dấu vết.
*/
public function refund(Invoice $invoice, ?int $adminId = null, ?int $amount = null, string $reason = ''): Invoice
{
if ((int) $invoice->status !== InvoiceStatus::PAID->value) {
throw new \InvalidArgumentException('Chỉ hoàn tiền được hoá đơn đã thanh toán.');
}
return DB::transaction(function () use ($invoice, $adminId, $amount, $reason) {
$invoice = Invoice::where('id', $invoice->id)->lockForUpdate()->firstOrFail();
if ((int) $invoice->status !== InvoiceStatus::PAID->value) {
throw new \InvalidArgumentException('Chỉ hoàn tiền được hoá đơn đã thanh toán.');
}
$paid = (int) $invoice->amount_paid ?: (int) $invoice->total;
$refundAmount = $amount === null ? $paid : min(max(0, $amount), $paid);
if ($refundAmount <= 0) {
throw new \InvalidArgumentException('Số tiền hoàn phải lớn hơn 0.');
}
$customer = Customer::where('id', $invoice->customer_id)->lockForUpdate()->firstOrFail();
$customer->increment('total', $refundAmount);
$invoice->update([
'status' => InvoiceStatus::REFUNDED->value,
'amount_paid' => max(0, $paid - $refundAmount),
]);
Transaction::create([
'uuid' => (string) Str::uuid(),
'public_code' => 'INV-REF-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)),
'trans' => $invoice->invoice_number . '-REFUND',
'type' => 'refund',
'amount' => -$refundAmount,
'received_amount' => -$refundAmount,
'customer_id' => $customer->id,
'user_id' => $adminId,
'status' => TransactionStatus::COMPLETED->value,
'note' => trim('Hoàn tiền hóa đơn #' . $invoice->invoice_number . ' ' . $reason),
]);
CustomerActivityLog::create([
'agent' => 'admin',
'client_ip' => request()?->ip(),
'customer_id' => $customer->id,
'description' => sprintf(
'Hoàn tiền hóa đơn #%s: %s VNĐ. Số dư mới: %s VNĐ.%s',
$invoice->invoice_number,
number_format($refundAmount),
number_format((int) $customer->fresh()->total),
$reason ? ' Lý do: ' . $reason : '',
),
]);
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
});
}
/**
* @param int|null $amount Số thực thu lần này; null = toàn bộ hoá đơn (hành vi cũ).
* @param int|null $sequence Khoá phụ để mỗi lần trả từng phần là một dòng riêng. Dưới row
* lock, amount_paid sau mỗi lần trả là duy nhất và tăng dần, nên
* vẫn chống được ghi trùng khi job retry.
*/
public function recordTransaction(
Invoice $invoice,
string $method,
string $note,
?int $adminId = null,
?int $amount = null,
?int $sequence = null,
): Transaction {
$amount = $amount ?? (int) $invoice->total;
return Transaction::firstOrCreate(
[
'customer_id' => $invoice->customer_id,
'trans' => $invoice->invoice_number,
'trans' => $invoice->invoice_number . ($sequence === null ? '' : '-P' . $sequence),
'type' => 'invoice',
],
[
'uuid' => (string) Str::uuid(),
'public_code' => 'INV-PAY-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)),
'amount' => (int) $invoice->total,
'amount' => $amount,
'received_amount' => $amount,
'user_id' => $adminId,
'status' => TransactionStatus::COMPLETED->value,
'note' => $note . ' (' . $method . ')',
+119
View File
@@ -0,0 +1,119 @@
<?php
namespace App\Services;
use App\Models\Customer;
use App\Models\Invoice;
use App\Services\Email\EmailTemplateService;
use Carbon\Carbon;
/**
* Nhắc thanh toán hoá đơn. Cột invoices.reminder_step có từ migration đầu tiên nhưng chưa
* từng được đọc/ghi — khách chỉ biết mình nợ khi dịch vụ đã bị tắt. Ở đây reminder_step là
* SỐ MỐC NHẮC ĐÃ GỬI, nên chạy lại command trong ngày không gửi trùng.
*/
class InvoiceReminderService
{
public function __construct(
private readonly EmailTemplateService $templates,
) {}
public const SCENARIO = 'invoice_payment_reminder';
/** Hoá đơn còn phải thu thì mới nhắc. */
public function isRemindable(Invoice $invoice): bool
{
return in_array((int) $invoice->status, InvoicePaymentService::PAYABLE_STATUSES, true);
}
/**
* Số mốc nhắc đã đến hạn tính tới hôm nay, theo config('billing.reminder_offsets')
* (số âm = trước hạn, dương = sau hạn).
*/
public function dueStep(Invoice $invoice, ?Carbon $now = null): int
{
if (! $invoice->due_date) {
return 0;
}
$now = $now ?? now();
$daysFromDue = $invoice->due_date->copy()->startOfDay()->diffInDays($now->copy()->startOfDay(), false);
$offsets = (array) config('billing.reminder_offsets', []);
if ($offsets === []) {
return 0;
}
sort($offsets);
// Quá mốc nhắc cuối cùng (cộng ân hạn) thì chuỗi nhắc đã đóng — không mở lại.
//
// Không có guard này, một lần import dữ liệu cũ (WHMCS) sẽ khiến mọi hoá đơn chưa
// thanh toán từ nhiều năm trước có reminder_step = 0 và due_date quá hạn rất lâu,
// cron 08:00 hôm sau bắn email nhắc nợ cho toàn bộ khách hàng cũ cùng lúc.
if ($daysFromDue > self::reminderCutoff($offsets)) {
return 0;
}
return count(array_filter($offsets, fn ($offset) => $daysFromDue >= $offset));
}
/** Ngày quá hạn tối đa còn nằm trong chuỗi nhắc. */
public static function reminderCutoff(array $offsets): int
{
return (int) max($offsets) + (int) config('billing.reminder_grace_days', 7);
}
/**
* Gửi nhắc nếu có mốc mới chưa gửi. Trả về true khi thực sự gửi.
* $force dùng cho nút "Nhắc thanh toán" thủ công của admin — bỏ qua việc đã gửi mốc đó rồi.
*/
public function remind(Invoice $invoice, bool $force = false, ?Carbon $now = null): bool
{
if (! $this->isRemindable($invoice)) {
return false;
}
$dueStep = $this->dueStep($invoice, $now);
if (! $force && $dueStep <= (int) $invoice->reminder_step) {
return false;
}
$customer = $invoice->customer;
if (! $customer?->email) {
return false;
}
$this->templates->send(self::SCENARIO, $customer->email, $this->vars($invoice, $customer, $now));
$invoice->update(['reminder_step' => max($dueStep, (int) $invoice->reminder_step + ($force ? 1 : 0))]);
return true;
}
private function vars(Invoice $invoice, Customer $customer, ?Carbon $now): array
{
$now = $now ?? now();
$dueDate = $invoice->due_date;
$daysLate = $dueDate ? $dueDate->copy()->startOfDay()->diffInDays($now->copy()->startOfDay(), false) : 0;
$outstanding = max(0, (int) $invoice->total - (int) ($invoice->amount_paid ?? 0));
return [
'client_name' => $customer->fullname ?? '',
'invoice_number' => $invoice->invoice_number,
'total' => number_format((int) $invoice->total, 0, ',', '.'),
'outstanding' => number_format($outstanding, 0, ',', '.'),
'due_date' => $dueDate?->format('d/m/Y') ?? '-',
'status_line' => $daysLate > 0
? 'Hoá đơn đã quá hạn ' . $daysLate . ' ngày.'
: ($daysLate === 0 ? 'Hôm nay là hạn thanh toán của hoá đơn này.' : 'Hoá đơn sẽ đến hạn sau ' . abs($daysLate) . ' ngày.'),
'paid_row' => (int) ($invoice->amount_paid ?? 0) > 0
? '<tr><td style="padding: 7px 11px; border-right: 1px solid #e8e8e8;">Đã thanh toán:</td><td style="padding: 7px 11px;"><strong>'
. number_format((int) $invoice->amount_paid, 0, ',', '.') . ' VNĐ</strong></td></tr>'
: '',
'login_url' => rtrim((string) config('app.frontend_url', ''), '/') . '/dang-nhap',
'support_email' => 'support@tgs.com.vn',
'support_phone' => '(028) 7309. 7379',
];
}
}
-244
View File
@@ -1,244 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\ModuleVmware;
use App\Models\ModuleIpAddress;
use App\Models\OrderItem;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
class VMDataService
{
/**
* Lưu dữ liệu VM và IP address khi tạo VM thành công
*/
public function saveVMData(OrderItem $orderItem, string $vmwareId, array $ipAddresses = []): array
{
// Lấy server_name từ order item
$serverName = $orderItem->server_name;
// Chỉ lưu dữ liệu khi có server_name
if (!$serverName) {
Log::info('ℹ️ Bỏ qua lưu dữ liệu VM vì không có server_name trong order item', [
'order_item_id' => $orderItem->id,
'vmware_id' => $vmwareId
]);
return [
'success' => true,
'message' => 'Bỏ qua lưu dữ liệu VM vì không có server_name trong order item',
'skipped' => true
];
}
try {
DB::beginTransaction();
$product = $orderItem->getProductAttribute();
$customer = $orderItem->order->customer;
$host = $product->host;
if (!$product || !$customer || !$host) {
throw new \Exception('Thiếu thông tin sản phẩm, khách hàng hoặc host');
}
// Tạo mới IP address với server_name
$ipAddress = $this->createIpAddress($orderItem, $host, $ipAddresses, $serverName);
// Tạo mới VM với server_name
$vm = $this->createVM($orderItem, $vmwareId, $ipAddress, $customer, $serverName);
DB::commit();
Log::info('✅ Lưu dữ liệu VM thành công với server_name từ order item', [
'vm_id' => $vm->id,
'vmware_id' => $vm->vmware_id,
'ip_address_id' => $ipAddress->id,
'order_item_id' => $orderItem->id,
'customer_id' => $customer->id,
'server_name' => $serverName
]);
return [
'success' => true,
'vm' => $vm,
'ip_address' => $ipAddress,
'message' => 'Lưu dữ liệu VM thành công với server_name từ order item'
];
} catch (\Exception $e) {
DB::rollBack();
Log::error('❌ Lỗi khi lưu dữ liệu VM', [
'order_item_id' => $orderItem->id,
'vmware_id' => $vmwareId,
'server_name' => $serverName,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return [
'success' => false,
'message' => 'Lỗi khi lưu dữ liệu VM: ' . $e->getMessage()
];
}
}
/**
* Tạo mới IP address với server_name
*/
private function createIpAddress(OrderItem $orderItem, $host, array $ipAddresses, string $serverName): ModuleIpAddress
{
$product = $orderItem->getProductAttribute();
// Lấy IP đầu tiên từ danh sách IP addresses
$primaryIp = null;
if (!empty($ipAddresses)) {
$primaryIp = $ipAddresses[0]['ip'] ?? null;
}
// Nếu không có IP từ vCenter, sử dụng IP từ sản phẩm
if (!$primaryIp && $product->ipAddress) {
$primaryIp = $product->ipAddress->ip;
}
$ipData = [
'vm_name' => $serverName,
'module_host_id' => $host->id,
'module_network_id' => $product->ipAddress?->module_network_id ?? 1, // Default network
'ip' => $primaryIp ?? '0.0.0.0',
'gateway' => $product->ipAddress?->gateway ?? '0.0.0.0', // Default gateway
'netmask' => $product->ipAddress?->netmask ?? '255.255.255.0',
'dns' => $product->ipAddress?->dns ?? '8.8.8.8',
'status' => $primaryIp ? 1 : 0 // 1 = Assigned, 0 = Free
];
$newIp = ModuleIpAddress::create($ipData);
Log::info('✅ Tạo mới IP address với server_name', [
'ip_id' => $newIp->id,
'ip' => $ipData['ip'],
'vm_name' => $ipData['vm_name'],
'server_name' => $serverName
]);
return $newIp;
}
/**
* Tạo mới VM với server_name
*/
private function createVM(OrderItem $orderItem, string $vmwareId, ModuleIpAddress $ipAddress, $customer, string $serverName): ModuleVmware
{
$product = $orderItem->getProductAttribute();
// Xử lý payment fields với type casting
$firstPayment = $orderItem->order->first_payment;
$nextPayment = $orderItem->order->next_payment;
$nextInvoice = $orderItem->order->next_invoice;
$vmData = [
'name' => $serverName,
'module_ip_address_id' => $ipAddress->id,
'port' => 1, // Default port
'order_id' => $orderItem->order->id,
'first_payment' => is_numeric($firstPayment) ? (int) $firstPayment : 0, // Ensure integer
'next_payment' => is_numeric($nextPayment) ? (int) $nextPayment : 0, // Ensure integer
'next_due_date' => $orderItem->order->next_due_date ?? null,
'next_invoice' => is_numeric($nextInvoice) ? (int) $nextInvoice : 0, // Ensure integer
'user' => 'admin', // Default user
'password' => '', // Will be set later
'hostname' => $serverName, // Sử dụng server_name cho hostname
'vmware_id' => $vmwareId,
'os_id' => $orderItem->os_id ?? 0,
'customer_id' => $customer->id,
'status' => 1 // Active
];
$newVM = ModuleVmware::create($vmData);
Log::info('✅ Tạo mới VM với server_name', [
'vm_id' => $newVM->id,
'vmware_id' => $vmwareId,
'name' => $serverName,
'server_name' => $serverName
]);
return $newVM;
}
/**
* Cập nhật trạng thái VM
*/
public function updateVMStatus(string $vmwareId, int $status): bool
{
try {
$vm = ModuleVmware::where('vmware_id', $vmwareId)->first();
if (!$vm) {
Log::warning('⚠️ Không tìm thấy VM để cập nhật trạng thái', [
'vmware_id' => $vmwareId,
'status' => $status
]);
return false;
}
$vm->update(['status' => $status]);
Log::info('🔄 Cập nhật trạng thái VM', [
'vm_id' => $vm->id,
'vmware_id' => $vmwareId,
'old_status' => $vm->getOriginal('status'),
'new_status' => $status
]);
return true;
} catch (\Exception $e) {
Log::error('❌ Lỗi khi cập nhật trạng thái VM', [
'vmware_id' => $vmwareId,
'status' => $status,
'error' => $e->getMessage()
]);
return false;
}
}
/**
* Cập nhật IP address cho VM
*/
public function updateVMIPAddress(string $vmwareId, string $ipAddress): bool
{
try {
$vm = ModuleVmware::where('vmware_id', $vmwareId)->first();
if (!$vm || !$vm->ipAddress) {
Log::warning('⚠️ Không tìm thấy VM hoặc IP address để cập nhật', [
'vmware_id' => $vmwareId,
'ip' => $ipAddress
]);
return false;
}
$vm->ipAddress->update([
'ip' => $ipAddress,
'status' => 1 // Assigned
]);
Log::info('🔄 Cập nhật IP address cho VM', [
'vm_id' => $vm->id,
'vmware_id' => $vmwareId,
'ip' => $ipAddress
]);
return true;
} catch (\Exception $e) {
Log::error('❌ Lỗi khi cập nhật IP address cho VM', [
'vmware_id' => $vmwareId,
'ip' => $ipAddress,
'error' => $e->getMessage()
]);
return false;
}
}
}