feat(vm): hoàn tiền khi cấp VM lỗi, theo dõi job queue, uuid dịch vụ cho ticket, chuẩn hoá RAM addon
- VmProvisionException/VmProvisionRefund xử lý lỗi cấp phát VM - QueueJobInspector + QueueMonitorController xem chi tiết job - Thêm service uuid cho ticket, thời lượng cho activity_logs - Migration chuẩn hoá RAM addon sang MB, trạng thái deleting cho snapshot Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
7136bec265
commit
62596d9063
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Jobs\LogActivityJob;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
@@ -25,6 +26,8 @@ class ActivityLogger
|
||||
?Model $subject = null,
|
||||
array $oldValues = [],
|
||||
array $newValues = [],
|
||||
?CarbonInterface $startedAt = null,
|
||||
?CarbonInterface $finishedAt = null,
|
||||
): void {
|
||||
try {
|
||||
[$causerType, $causerId, $causerName] = $this->resolveCauser();
|
||||
@@ -42,6 +45,9 @@ class ActivityLogger
|
||||
'new_values' => $newValues ?: null,
|
||||
'ip_address' => request()->getClientIp(),
|
||||
'user_agent' => request()->userAgent(),
|
||||
'started_at' => $startedAt?->format('Y-m-d H:i:s.v'),
|
||||
'finished_at' => $finishedAt?->format('Y-m-d H:i:s.v'),
|
||||
'created_at' => now()->format('Y-m-d H:i:s.v'),
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('[ActivityLogger] Failed to dispatch log job', [
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Services\Api\Order;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Enums\Order\OrderStatus;
|
||||
use App\Enums\Product\ProductTypeEnums;
|
||||
use App\Helpers\OrderHelper;
|
||||
use App\Models\Order;
|
||||
use App\Models\Product;
|
||||
@@ -13,6 +14,7 @@ use App\Repositories\Api\Service\ServiceRepository;
|
||||
use App\Services\InvoicePaymentService;
|
||||
use App\Services\AdminPaymentNotifier;
|
||||
use App\Services\Coupon\CouponService;
|
||||
use App\Services\VirtualMachine\VmIpReservationService;
|
||||
use App\Support\AddonQuantityValidator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
@@ -25,6 +27,7 @@ class OrderService
|
||||
protected InvoicePaymentService $invoicePaymentService,
|
||||
protected AdminPaymentNotifier $adminPaymentNotifier,
|
||||
protected CouponService $couponService,
|
||||
protected VmIpReservationService $vmIpReservation,
|
||||
) {}
|
||||
|
||||
// =========================================================================
|
||||
@@ -46,6 +49,8 @@ class OrderService
|
||||
['product' => $product, 'base_price' => $basePrice, 'addons_meta' => $addonsMeta, 'sub_total' => $subTotal] = $this->quote($data);
|
||||
$couponCode = $data['coupon_code'] ?? null;
|
||||
|
||||
$this->assertInfrastructureAvailable([$product]);
|
||||
|
||||
$expectedTotal = $couponCode
|
||||
? $subTotal - $this->couponService->preview($couponCode, $customer, $product, $data['billing_cycle'], $subTotal)['discount']
|
||||
: $subTotal;
|
||||
@@ -100,6 +105,19 @@ class OrderService
|
||||
});
|
||||
}
|
||||
|
||||
private function assertInfrastructureAvailable(iterable $products): void
|
||||
{
|
||||
$needsVm = collect($products)->contains(fn ($product) => in_array(
|
||||
ProductTypeEnums::tryFrom($product?->category?->type ?? ''),
|
||||
[ProductTypeEnums::VPS, ProductTypeEnums::CLOUD],
|
||||
true
|
||||
));
|
||||
|
||||
if ($needsVm && !$this->vmIpReservation->hasFreeIp()) {
|
||||
throw new \InvalidArgumentException('Hiện tại hạ tầng đang đầy vui lòng liên hệ quản trị viên');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Giá niêm yết (chu kỳ + addon) tính phía server; nguồn duy nhất cho create() và preview mã giảm giá.
|
||||
*
|
||||
@@ -143,6 +161,8 @@ class OrderService
|
||||
throw new \InvalidArgumentException('Đơn hàng đã được thanh toán hoặc đang xử lý.');
|
||||
}
|
||||
|
||||
$this->assertInfrastructureAvailable($order->orderItems->map->product);
|
||||
|
||||
$processedOrder = DB::transaction(function () use ($order, $method) {
|
||||
$customer = $order->customer;
|
||||
|
||||
|
||||
@@ -269,7 +269,7 @@ trait ActivatesPaidInvoices
|
||||
ServiceAddon::create([
|
||||
'service_id' => $service->id,
|
||||
'addon_type' => $type,
|
||||
'addon_value' => (string) $value,
|
||||
'addon_value' => (string) ($type === 'ram' ? (int) $value * 1024 : $value),
|
||||
'price' => 0,
|
||||
]);
|
||||
}
|
||||
@@ -288,7 +288,7 @@ trait ActivatesPaidInvoices
|
||||
ServiceAddon::create([
|
||||
'service_id' => $service->id,
|
||||
'addon_type' => strtolower((string) $addon->code),
|
||||
'addon_value' => (string) ($meta['qty'] ?? 1),
|
||||
'addon_value' => (string) (strtolower((string) $addon->code) === 'ram' ? (int) ($meta['qty'] ?? 1) * 1024 : ($meta['qty'] ?? 1)),
|
||||
'price' => (int) ($meta['price'] ?? $addon->price),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -42,6 +42,8 @@ class CustomerRenewalNotifier
|
||||
'data' => ['service_id' => $service->id, 'invoice_id' => $invoice->id, 'months' => $months],
|
||||
]);
|
||||
|
||||
app(ServiceRenewalNotifier::class)->notifyCustomerRenewal($service, $invoice, $months, $previousExpiresAt);
|
||||
|
||||
$adminEmail = json_decode((string) Setting::where('key', 'setting')->value('value'), true)['admin_email'] ?? null;
|
||||
if (! $adminEmail || ! AutoEmailGate::allows(self::SCENARIO)) {
|
||||
return;
|
||||
|
||||
@@ -34,11 +34,44 @@ class ServiceRenewalNotifier
|
||||
return;
|
||||
}
|
||||
|
||||
$data = $this->payload(
|
||||
$service,
|
||||
$invoice,
|
||||
$months,
|
||||
$previousExpiresAt,
|
||||
$payment === 'balance' ? 'Trừ số dư tài khoản' : 'Đã thu ngoài hệ thống',
|
||||
) + ['admin_name' => $adminName];
|
||||
|
||||
AutoEmailGate::markManual();
|
||||
|
||||
$this->safely(fn () => $this->sendToCustomer($service, $data, $adminId));
|
||||
$this->safely(fn () => $this->sendToAdmin($data));
|
||||
}
|
||||
|
||||
public function notifyCustomerRenewal(
|
||||
Service $service,
|
||||
Invoice $invoice,
|
||||
int $months,
|
||||
?CarbonInterface $previousExpiresAt,
|
||||
): void {
|
||||
if (! AutoEmailGate::allows(self::CUSTOMER_SCENARIO)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$paymentLabel = $invoice->payment_method === 'balance' ? 'Trừ số dư tài khoản' : (string) ($invoice->payment_method ?: 'N/A');
|
||||
$data = $this->payload($service, $invoice, $months, $previousExpiresAt, $paymentLabel);
|
||||
|
||||
$this->safely(fn () => $this->sendToCustomer($service, $data, null));
|
||||
}
|
||||
|
||||
private function payload(Service $service, Invoice $invoice, int $months, ?CarbonInterface $previousExpiresAt, string $paymentLabel): array
|
||||
{
|
||||
$service->loadMissing(['customer', 'product']);
|
||||
$customer = $service->customer;
|
||||
$serverName = (string) $service->server_name;
|
||||
$amount = number_format((float) $invoice->total, 0, ',', '.') . ' VNĐ';
|
||||
|
||||
$data = [
|
||||
return [
|
||||
'client_name' => $customer->fullname ?? '',
|
||||
'customer_name' => $customer->fullname ?? '',
|
||||
'customer_email' => $customer->email ?? '',
|
||||
@@ -48,16 +81,10 @@ class ServiceRenewalNotifier
|
||||
'old_expires_at' => $previousExpiresAt?->format('d/m/Y') ?? 'N/A',
|
||||
'expires_at' => $service->expires_at?->format('d/m/Y') ?? 'N/A',
|
||||
'invoice_number' => $invoice->invoice_number,
|
||||
'amount_formatted' => number_format((float) $invoice->total, 0, ',', '.') . ' VNĐ',
|
||||
'payment_method_label' => $payment === 'balance' ? 'Trừ số dư tài khoản' : 'Đã thu ngoài hệ thống',
|
||||
'admin_name' => $adminName,
|
||||
'price_row' => EmailTemplateShell::row('Số tiền gia hạn', number_format((float) $invoice->total, 0, ',', '.') . ' VNĐ'),
|
||||
'amount_formatted' => $amount,
|
||||
'payment_method_label' => $paymentLabel,
|
||||
'price_row' => EmailTemplateShell::row('Số tiền gia hạn', $amount),
|
||||
];
|
||||
|
||||
AutoEmailGate::markManual();
|
||||
|
||||
$this->safely(fn () => $this->sendToCustomer($service, $data, $adminId));
|
||||
$this->safely(fn () => $this->sendToAdmin($data));
|
||||
}
|
||||
|
||||
private function sendToCustomer(Service $service, array $data, ?int $adminId): void
|
||||
|
||||
@@ -14,8 +14,8 @@ use RuntimeException;
|
||||
*
|
||||
* active vCenter → active Datacenter → active Host → active Datastore + Network
|
||||
*
|
||||
* Product/OS host binding is informational only — it no longer drives VM
|
||||
* creation. Datastore, network, resource pool and folder are exceptions: if
|
||||
* The OS host (and its datacenter) overrides the active host when set, because the
|
||||
* OS template, datastore, network, resource pool and folder belong to that host. Datastore, network, resource pool and folder are exceptions: if
|
||||
* the OS has datastore_id / module_network_id / resource_pool_id / folder_id
|
||||
* set, they override the active chain / global default (an OS can target a
|
||||
* different datastore/IP pool/resource pool/folder than whatever happens to
|
||||
@@ -32,7 +32,7 @@ class VmInfrastructureResolver
|
||||
|
||||
public function resolve(OrderItem $item, $product): VmInfrastructureContext
|
||||
{
|
||||
$os = Os::with(['osGroup', 'network', 'datastore', 'resourcePool', 'folder'])->find($item->os_id);
|
||||
$os = Os::with(['osGroup', 'host.datacenter', 'network', 'datastore', 'resourcePool', 'folder'])->find($item->os_id);
|
||||
|
||||
if (!$os) {
|
||||
throw new RuntimeException(
|
||||
@@ -41,6 +41,8 @@ class VmInfrastructureResolver
|
||||
}
|
||||
|
||||
$chain = $this->activeProvider->resolveChain();
|
||||
$host = $os->host ?? $chain['host'];
|
||||
$datacenter = $os->host?->datacenter ?? $chain['datacenter'];
|
||||
$network = $os->network ?? $chain['network'];
|
||||
$datastore = $os->datastore ?? $chain['datastore'];
|
||||
$folderId = $os->folder?->folder ?? $this->providerSettings->defaultFolder();
|
||||
@@ -50,7 +52,8 @@ class VmInfrastructureResolver
|
||||
'order_item_id' => $item->id,
|
||||
'vcenter_id' => $chain['vcenter']->id,
|
||||
'datacenter_id' => $chain['datacenter']->id,
|
||||
'host_id' => $chain['host']->id,
|
||||
'host_id' => $host->id,
|
||||
'host_from_os' => $os->host !== null,
|
||||
'datastore_id' => $datastore->id,
|
||||
'datastore_from_os' => $os->datastore !== null,
|
||||
'network_id' => $network->id,
|
||||
@@ -66,8 +69,8 @@ class VmInfrastructureResolver
|
||||
|
||||
return new VmInfrastructureContext(
|
||||
os: $os,
|
||||
host: $chain['host'],
|
||||
datacenter: $chain['datacenter'],
|
||||
host: $host,
|
||||
datacenter: $datacenter,
|
||||
vcenter: $chain['vcenter'],
|
||||
template: $os->template_id,
|
||||
isWindows: $isWindows,
|
||||
|
||||
@@ -18,6 +18,11 @@ use Illuminate\Support\Facades\Log;
|
||||
*/
|
||||
class VmIpReservationService
|
||||
{
|
||||
public function hasFreeIp(): bool
|
||||
{
|
||||
return $this->availableIps()->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{reservation:ModuleIpAddress,ip_pool_id:int,gateway:string,cidr:int}|null
|
||||
*/
|
||||
@@ -25,8 +30,7 @@ class VmIpReservationService
|
||||
{
|
||||
return DB::transaction(function () use ($networkId, $hostId, $dns) {
|
||||
// ip_pools.status is the single source of truth for availability.
|
||||
$ipPool = IpPool::where('module_network_id', $networkId)
|
||||
->whereIn('status', ['free', 'reserved'])
|
||||
$ipPool = $this->availableIps()
|
||||
->lockForUpdate()
|
||||
->inRandomOrder()
|
||||
->first();
|
||||
@@ -44,7 +48,6 @@ class VmIpReservationService
|
||||
// module_ip_address mirrors ip_pools — update the existing synced row
|
||||
// (created when the IP was added to ip_pools) instead of inserting a new one.
|
||||
$reservation = ModuleIpAddress::where('ip', $ipPool->ip_address)
|
||||
->where('module_network_id', $networkId)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
@@ -101,6 +104,13 @@ class VmIpReservationService
|
||||
});
|
||||
}
|
||||
|
||||
private function availableIps()
|
||||
{
|
||||
return IpPool::whereIn('status', ['free', 'reserved'])
|
||||
->whereNotNull('gateway')
|
||||
->where('gateway', '!=', '');
|
||||
}
|
||||
|
||||
public function freeIpsInNetwork(int $networkId)
|
||||
{
|
||||
return IpPool::where('module_network_id', $networkId)
|
||||
|
||||
@@ -15,7 +15,7 @@ class VmModuleService
|
||||
* Create ModuleVmware shell. IP and final password are filled in later
|
||||
* by AssignIpToGuestJob → ChangePasswordViaVsphereJob.
|
||||
*/
|
||||
public function create(OrderItem $item, VmInfrastructureContext $infra, string $vmId): ModuleVmware
|
||||
public function create(OrderItem $item, VmInfrastructureContext $infra, string $vmId, array $specs = []): ModuleVmware
|
||||
{
|
||||
$customer = $item->order->customer;
|
||||
$serverName = $item->server_name ?? ('VM-' . $vmId);
|
||||
@@ -43,6 +43,9 @@ class VmModuleService
|
||||
'os_id' => $item->os_id ?? 1,
|
||||
'customer_id' => $customer->id,
|
||||
'status' => 1,
|
||||
'cpu' => $specs['cpu'] ?? null,
|
||||
'ram_mb' => $specs['ram_mb'] ?? null,
|
||||
'disk_gb' => $specs['disk_gb'] ?? null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\VirtualMachine;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Enums\Order\OrderStatus;
|
||||
use App\Models\OrderItem;
|
||||
use App\Services\InvoicePaymentService;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
class VmProvisionRefund
|
||||
{
|
||||
public function __construct(private readonly InvoicePaymentService $payments)
|
||||
{
|
||||
}
|
||||
|
||||
public function refund(OrderItem $item, string $reason): bool
|
||||
{
|
||||
$order = $item->order;
|
||||
$invoice = $order?->invoice;
|
||||
|
||||
if (!$invoice || (int) $invoice->status !== InvoiceStatus::PAID->value || $order->orderItems()->count() !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->payments->refund($invoice, null, null, 'Tự động hoàn tiền do khởi tạo máy ảo thất bại: ' . $reason);
|
||||
|
||||
$order->update(['status' => OrderStatus::CANCELLED->value]);
|
||||
|
||||
return true;
|
||||
} catch (Throwable $e) {
|
||||
Log::error('VmProvisionRefund failed', ['order_item_id' => $item->id, 'error' => $e->getMessage()]);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,18 @@ class VmVcenterErrorTranslator
|
||||
'TIMED_OUT' => 'Yêu cầu khởi tạo máy chủ hết thời gian chờ. Vui lòng thử lại sau.',
|
||||
];
|
||||
|
||||
public function detail(array $result): string
|
||||
{
|
||||
$data = $result['data'] ?? [];
|
||||
$messages = is_array($data) ? collect($data['messages'] ?? [])->pluck('default_message')->filter() : collect();
|
||||
|
||||
if ($messages->isNotEmpty()) {
|
||||
return ($data['error_type'] ?? 'vCenter') . ': ' . $messages->implode(' | ');
|
||||
}
|
||||
|
||||
return is_string($data) ? $data : (string) json_encode($data, JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
|
||||
public function translate(array $result, ?string $serverName = null): string
|
||||
{
|
||||
$data = $result['data'] ?? [];
|
||||
|
||||
Reference in New Issue
Block a user