Files
portal-api/app/Services/InvoicePaymentService.php
T
2026-09-09 16:56:22 +07:00

259 lines
9.9 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
{
public function payWithBalance(Invoice $invoice, Customer $customer, string $method = 'balance'): 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) {
// 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']);
}
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.');
}
if ((int) $customer->total < (int) $invoice->total) {
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)
));
}
$customer->decrement('total', (int) $invoice->total);
$invoice->update([
'status' => InvoiceStatus::PAID->value,
'paid_at' => now(),
'payment_method' => $method,
]);
$this->recordTransaction($invoice, $method, 'Khách hàng thanh toán hóa đơn #' . $invoice->invoice_number);
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Đ.',
$invoice->invoice_number,
number_format((int) $invoice->total),
number_format((int) $customer->fresh()->total)
),
]);
if ((int) $invoice->invoice_type === 2) {
$this->activateRenewal($invoice);
} elseif ($invoice->order) {
$this->activateOrder($invoice);
}
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
});
}
public function markPaidByAdmin(Invoice $invoice, ?int $adminId = null, string $method = 'admin'): Invoice
{
if ((int) $invoice->status === InvoiceStatus::PAID->value) {
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
}
return DB::transaction(function () use ($invoice, $adminId, $method) {
$invoice->update([
'status' => InvoiceStatus::PAID->value,
'paid_at' => now(),
'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);
if ((int) $invoice->invoice_type === 2) {
$this->activateRenewal($invoice);
} elseif ($invoice->order) {
$this->activateOrder($invoice);
}
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
});
}
public function recordTransaction(Invoice $invoice, string $method, string $note, ?int $adminId = null): Transaction
{
return Transaction::firstOrCreate(
[
'customer_id' => $invoice->customer_id,
'trans' => $invoice->invoice_number,
'type' => 'invoice',
],
[
'uuid' => (string) Str::uuid(),
'public_code' => 'INV-PAY-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)),
'amount' => (int) $invoice->total,
'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),
]);
}
}
}