Files
portal-api/app/Services/InvoicePaymentService.php
T
2026-09-23 15:17:18 +07:00

427 lines
18 KiB
PHP

<?php
namespace App\Services;
use App\Enums\Invoice\InvoiceStatus;
use App\Enums\Order\OrderStatus;
use App\Enums\TransactionStatus;
use App\Helpers\OrderHelper;
use App\Jobs\Hosting\ProvisionHostingAccountJob;
use App\Jobs\VirtualMachine\Action\VMJobs;
use App\Jobs\VirtualMachine\Create\CreateVirtualMachineJob;
use App\Models\Addon;
use App\Models\Customer;
use App\Models\Invoice;
use App\Models\Log as CustomerActivityLog;
use App\Models\OrderItem;
use App\Models\Service;
use App\Models\ServiceAddon;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class InvoicePaymentService
{
/** 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.');
}
// Balance/status are re-checked below under row locks — this is just a fast
// fail-fast path so we don't open a transaction for an already-paid invoice.
if ((int) $invoice->status === InvoiceStatus::PAID->value) {
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
}
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();
$customer = Customer::where('id', $customer->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);
$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 < $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($payNow)
));
}
$customer->decrement('total', $payNow);
$paidSoFar = (int) $invoice->amount_paid + $payNow;
$settled = $paidSoFar >= (int) $invoice->total;
$invoice->update([
'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
. ($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 Số dư còn: %s VNĐ.',
$invoice->invoice_number,
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) {
$this->activateOrder($invoice);
}
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
});
}
/** 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, $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([
'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
. ($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);
} elseif ($invoice->order) {
$this->activateOrder($invoice);
}
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
});
}
/**
* 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 . ($sequence === null ? '' : '-P' . $sequence),
'type' => 'invoice',
],
[
'uuid' => (string) Str::uuid(),
'public_code' => 'INV-PAY-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)),
'amount' => $amount,
'received_amount' => $amount,
'user_id' => $adminId,
'status' => TransactionStatus::COMPLETED->value,
'note' => $note . ' (' . $method . ')',
]
);
}
private function activateOrder(Invoice $invoice): void
{
$order = $invoice->order?->loadMissing(['orderItems.product', 'customer', 'invoice']);
if (! $order) {
return;
}
// payment_method/paid_at always mirror the invoice that was just paid, even if the
// order's status doesn't change (e.g. it's already ACTIVE from an earlier payment).
$order->update([
'status' => OrderStatus::ACTIVE->value,
'payment_method' => $invoice->payment_method,
'paid_at' => $invoice->paid_at,
]);
foreach ($order->orderItems as $item) {
$isHostingProvision = ! $item->os_id
&& $item->server_name
&& $item->product?->product_type === 'hosting';
$service = Service::firstOrCreate(
['order_item_id' => $item->id],
[
'customer_id' => $order->customer_id,
'product_id' => $item->product_id,
'invoice_id' => $invoice->id,
'server_name' => $item->server_name,
'status' => ($item->os_id || $isHostingProvision) ? 'pending' : 'active',
'auto_renew' => false,
'started_at' => now(),
'expires_at' => now()->addMonths($item->months ?: OrderHelper::cycleToMonths($item->billing_cycle)),
]
);
$this->attachServiceAddons($service, $item);
if ($service->wasRecentlyCreated && $item->product_id) {
if ($item->os_id) {
dispatch(new CreateVirtualMachineJob($item));
} elseif ($isHostingProvision) {
dispatch(new ProvisionHostingAccountJob($item));
}
}
}
}
private function activateRenewal(Invoice $invoice): void
{
$service = Service::query()
->with(['orderItem.product'])
->where('invoice_id', $invoice->id)
->first();
if (! $service) {
return;
}
if ($invoice->order) {
// Same rule as activateOrder(): payment_method/paid_at always mirror the invoice
// that was just paid, regardless of whether the order's status actually changes.
$invoice->order->update([
'status' => OrderStatus::ACTIVE->value,
'payment_method' => $invoice->payment_method,
'paid_at' => $invoice->paid_at,
]);
}
$months = (int) ($invoice->invoiceItems()->where('type', 'renewal')->value('months') ?: $service->orderItem?->months ?: 1);
$baseDate = $service->expires_at && $service->expires_at->isFuture()
? $service->expires_at
: now();
$expiresAt = Carbon::parse($baseDate)->addMonths($months);
$service->update([
'status' => 'active',
'expires_at' => $expiresAt,
'suspended_at' => null,
]);
if ($service->vm_id) {
dispatch(new VMJobs((int) $service->vm_id, 'Start', false))->delay(now()->addSeconds(5));
}
}
private function attachServiceAddons(Service $service, OrderItem $item): void
{
if ($service->addons()->exists()) {
return;
}
$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,
]);
}
}
}
$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),
]);
}
}
}