228 lines
8.1 KiB
PHP
228 lines
8.1 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Enums\Invoice\InvoiceStatus;
|
|
use App\Enums\Order\OrderStatus;
|
|
use App\Enums\TransactionStatus;
|
|
use App\Jobs\VirtualMachine\Action\VMJobs;
|
|
use App\Jobs\VirtualMachine\Create\CreateVirtualMachineJob;
|
|
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.');
|
|
}
|
|
|
|
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)
|
|
));
|
|
}
|
|
|
|
return DB::transaction(function () use ($invoice, $customer, $method) {
|
|
$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;
|
|
}
|
|
|
|
if ((int) $order->status !== OrderStatus::ACTIVE->value) {
|
|
$order->update([
|
|
'status' => OrderStatus::ACTIVE->value,
|
|
'payment_method' => $invoice->payment_method,
|
|
]);
|
|
}
|
|
|
|
foreach ($order->orderItems as $item) {
|
|
$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 ? 'pending' : 'active',
|
|
'auto_renew' => false,
|
|
'started_at' => now(),
|
|
'expires_at' => now()->addMonths($item->months ?: $this->cycleToMonths($item->billing_cycle)),
|
|
]
|
|
);
|
|
|
|
$this->attachServiceAddons($service, $item);
|
|
|
|
if ($service->wasRecentlyCreated && $item->product_id && $item->os_id) {
|
|
dispatch(new CreateVirtualMachineJob($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 && (int) $invoice->order->status !== OrderStatus::ACTIVE->value) {
|
|
$invoice->order->update([
|
|
'status' => OrderStatus::ACTIVE->value,
|
|
'payment_method' => $invoice->payment_method,
|
|
]);
|
|
}
|
|
|
|
$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,
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private function cycleToMonths(?string $cycle): int
|
|
{
|
|
return match ($cycle) {
|
|
'monthly' => 1,
|
|
'quarterly' => 3,
|
|
'semi_annually' => 6,
|
|
'annually' => 12,
|
|
'biennially' => 24,
|
|
'triennially' => 36,
|
|
default => 1,
|
|
};
|
|
}
|
|
}
|