feat(service): custom product, lịch sử giám sát VM và mã hoá response theo phiên
- Dịch vụ custom: bảng custom_products + services.custom_product_id; createService nhận
custom{} thay product_id, giá = đơn giá tháng x số tháng chu kỳ (1/3/6/12/24/36),
gia hạn tính theo cùng đơn giá, ServiceClientDetailResource trả custom_product và specs.
- Giám sát VM: GET v1/system/vm-metrics/history gom lịch sử về tối đa 240 điểm;
lỗi lấy dung lượng đĩa không còn làm hỏng cả thẻ metrics.
- SealResponse: AES-256-GCM theo khoá phiên do proxy Next cấp qua header x-seal-key
(HMAC của session id). Client opt-in bằng x-seal; chi tiết dịch vụ, mật khẩu VM và
console ticket luôn được mã hoá. Body gửi lên dạng {enc} được giải mã trước validate;
khoá lệch trả 428 để client lấy khoá mới. Đây là che mắt DevTools, không phải bảo mật
chống chính chủ tài khoản.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
8108e8fe53
commit
6315a392c0
@@ -217,7 +217,7 @@ class OrderQueryService
|
||||
private function issueRenewal(int $serviceId, Customer $customer, int $months): array
|
||||
{
|
||||
$service = Service::query()
|
||||
->with(['orderItem.product'])
|
||||
->with(['orderItem.product', 'customProduct'])
|
||||
->where('id', $serviceId)
|
||||
->where('customer_id', $customer->id)
|
||||
->whereNotIn('status', ['terminated', 'cancelled'])
|
||||
@@ -232,7 +232,7 @@ class OrderQueryService
|
||||
return ['ok' => false, 'message' => 'Không thể xác định giá gia hạn dịch vụ.', 'code' => 400];
|
||||
}
|
||||
|
||||
$product = $service->product ?? $orderItem->product;
|
||||
$product = $service->customProduct ?? $service->product ?? $orderItem->product;
|
||||
$option = RenewalPricing::option($product, $months);
|
||||
|
||||
if ($option === null) {
|
||||
@@ -336,7 +336,7 @@ class OrderQueryService
|
||||
'invoice_id' => $invoice->id,
|
||||
'product_id' => $service->product_id ?: $orderItem->product_id,
|
||||
'type' => 'renewal',
|
||||
'description' => 'Gia hạn dịch vụ: ' . ($orderItem->product?->name ?? $service->server_name ?? ''),
|
||||
'description' => 'Gia hạn dịch vụ: ' . ($service->customProduct?->name ?? $orderItem->product?->name ?? $service->server_name ?? ''),
|
||||
'months' => $months,
|
||||
'quantity' => 1,
|
||||
'unit_price' => $renewalPrice,
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Services\Customer;
|
||||
|
||||
use App\Helpers\OrderHelper;
|
||||
use App\Models\Customer;
|
||||
use App\Models\CustomProduct;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Models\Order;
|
||||
use App\Models\Product;
|
||||
@@ -88,9 +89,13 @@ class CustomerServiceProvisioningService
|
||||
return DB::transaction(function () use ($customer, $service, $data) {
|
||||
$vmFields = ['virtual_machine_id', 'os_id', 'vm_cpu', 'vm_ram_mb', 'vm_disk_gb', 'vm_ip', 'vm_dns', 'vm_user', 'vm_password', 'vm_port'];
|
||||
|
||||
$service->fill(collect($data)->except(['price', 'billing_cycle', ...$vmFields])->all());
|
||||
$service->fill(collect($data)->except(['price', 'billing_cycle', 'product_id', ...$vmFields])->all());
|
||||
$service->save();
|
||||
|
||||
if (!empty($data['product_id']) && (int) $data['product_id'] !== $service->product_id) {
|
||||
$this->replaceProduct($service, Product::findOrFail($data['product_id']));
|
||||
}
|
||||
|
||||
if (!empty($data['virtual_machine_id'])) {
|
||||
$this->assignVirtualMachine($service, $customer, (int) $data['virtual_machine_id']);
|
||||
}
|
||||
@@ -142,6 +147,12 @@ class CustomerServiceProvisioningService
|
||||
});
|
||||
}
|
||||
|
||||
private function replaceProduct(Service $service, Product $product): void
|
||||
{
|
||||
$service->update(['product_id' => $product->id, 'custom_product_id' => null, 'type' => $product->product_type]);
|
||||
$service->orderItem?->update(['product_id' => $product->id]);
|
||||
}
|
||||
|
||||
private function assignVirtualMachine(Service $service, Customer $customer, int $virtualMachineId): void
|
||||
{
|
||||
$vm = VirtualMachines::with('datacenter')->findOrFail($virtualMachineId);
|
||||
@@ -194,9 +205,10 @@ class CustomerServiceProvisioningService
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$product = Product::find($data['product_id']);
|
||||
$custom = $data['custom'] ?? null;
|
||||
$product = $custom ? null : Product::find($data['product_id']);
|
||||
abort_if(
|
||||
$product->product_type === 'vps' && empty($data['virtual_machine_id']),
|
||||
$product?->product_type === 'vps' && empty($data['virtual_machine_id']),
|
||||
422,
|
||||
'VPS service requires a virtual_machine_id',
|
||||
);
|
||||
@@ -204,9 +216,13 @@ class CustomerServiceProvisioningService
|
||||
$billingCycle = $data['billing_cycle'] ?? 'monthly';
|
||||
$months = OrderHelper::cycleToMonths($billingCycle);
|
||||
|
||||
$listPrice = $this->orderRecorder->listPrice($product, $billingCycle, $data['server_name'] ?? null);
|
||||
abort_if($custom && !in_array($months, CustomProduct::CYCLE_MONTHS, true), 422, 'Chu kỳ không hợp lệ cho sản phẩm custom.');
|
||||
|
||||
$listPrice = $custom
|
||||
? (int) round((float) $custom['unit_price']) * $months
|
||||
: $this->orderRecorder->listPrice($product, $billingCycle, $data['server_name'] ?? null);
|
||||
abort_if(
|
||||
!isset($data['price']) && $listPrice === null && $product->product_type === 'domain',
|
||||
!isset($data['price']) && $listPrice === null && $product?->product_type === 'domain',
|
||||
422,
|
||||
'Tên miền không có giá trong bảng giá tên miền, vui lòng nhập giá.',
|
||||
);
|
||||
@@ -236,7 +252,9 @@ class CustomerServiceProvisioningService
|
||||
),
|
||||
);
|
||||
|
||||
return DB::transaction(function () use ($customer, $product, $data, $billingCycle, $months, $basePrice, $paidAmount, $paymentStatus, $paymentMethod, $clientIp) {
|
||||
return DB::transaction(function () use ($customer, $product, $custom, $data, $billingCycle, $months, $basePrice, $paidAmount, $paymentStatus, $paymentMethod, $clientIp) {
|
||||
$customProduct = $custom ? CustomProduct::create($custom) : null;
|
||||
|
||||
['order' => $order, 'orderItem' => $orderItem, 'invoice' => $invoice] = $this->orderRecorder->create(
|
||||
$customer->id,
|
||||
$product,
|
||||
@@ -247,6 +265,7 @@ class CustomerServiceProvisioningService
|
||||
paymentMethod: $paymentMethod,
|
||||
clientIp: $clientIp,
|
||||
amountPaid: $paidAmount,
|
||||
label: $customProduct?->name,
|
||||
);
|
||||
|
||||
// Ngày bắt đầu/hết hạn dùng chung cho cả module_vmware (next_due_date/next_invoice) và services.
|
||||
@@ -289,7 +308,8 @@ class CustomerServiceProvisioningService
|
||||
? ['customer_id' => $customer->id, 'vm_id' => $vmId]
|
||||
: [
|
||||
'customer_id' => $customer->id,
|
||||
'product_id' => $product->id,
|
||||
'product_id' => $product?->id,
|
||||
'custom_product_id' => $customProduct?->id,
|
||||
'vm_id' => null,
|
||||
'server_name' => $data['server_name'] ?? null,
|
||||
];
|
||||
@@ -298,7 +318,9 @@ class CustomerServiceProvisioningService
|
||||
|
||||
$service = Service::updateOrCreate($serviceLookup, [
|
||||
'customer_id' => $customer->id,
|
||||
'product_id' => $product->id,
|
||||
'product_id' => $product?->id,
|
||||
'custom_product_id' => $customProduct?->id,
|
||||
'type' => $customProduct?->category,
|
||||
'vm_id' => $vmId,
|
||||
'order_item_id' => $orderItem->id,
|
||||
'invoice_id' => $invoice->id,
|
||||
@@ -317,7 +339,7 @@ class CustomerServiceProvisioningService
|
||||
ModuleVmware::where('id', $vmId)->update(['service_id' => $service->id]);
|
||||
}
|
||||
|
||||
return $service->load(['product', 'vmware.os.osGroup']);
|
||||
return $service->load(['product', 'customProduct', 'vmware.os.osGroup']);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ class ServiceOrderRecorder
|
||||
?string $paymentMethod = null,
|
||||
?string $clientIp = null,
|
||||
int $amountPaid = 0,
|
||||
?string $label = null,
|
||||
): array {
|
||||
$months = OrderHelper::cycleToMonths($billingCycle);
|
||||
$isDomain = $product?->product_type === 'domain';
|
||||
@@ -80,7 +81,7 @@ class ServiceOrderRecorder
|
||||
'invoice_id' => $invoice->id,
|
||||
'product_id' => $product?->id,
|
||||
'type' => 'service',
|
||||
'description' => $this->describe($product, $serverName),
|
||||
'description' => $this->describe($product, $serverName, $label),
|
||||
'months' => $months,
|
||||
'quantity' => 1,
|
||||
'unit_price' => $price,
|
||||
@@ -184,9 +185,9 @@ class ServiceOrderRecorder
|
||||
: null;
|
||||
}
|
||||
|
||||
private function describe(?Product $product, ?string $serverName): string
|
||||
private function describe(?Product $product, ?string $serverName, ?string $label = null): string
|
||||
{
|
||||
$name = $product->name ?? 'Dịch vụ';
|
||||
$name = $label ?? $product->name ?? 'Dịch vụ';
|
||||
|
||||
return $serverName ? "{$name} - {$serverName}" : $name;
|
||||
}
|
||||
|
||||
@@ -18,7 +18,16 @@ class PortalMonitorClient
|
||||
return $this->get($vmwareId, 'storage', 'VM storage is unavailable');
|
||||
}
|
||||
|
||||
private function get(string $vmwareId, string $resource, string $notFoundMessage): array
|
||||
public function vmHistory(string $vmwareId, \DateTimeInterface $from, \DateTimeInterface $to): array
|
||||
{
|
||||
return $this->get($vmwareId, 'history', 'VM metrics are unavailable', [
|
||||
'from' => $from->format(DATE_RFC3339),
|
||||
'to' => $to->format(DATE_RFC3339),
|
||||
'limit' => 10000,
|
||||
]);
|
||||
}
|
||||
|
||||
private function get(string $vmwareId, string $resource, string $notFoundMessage, array $query = []): array
|
||||
{
|
||||
$url = rtrim((string) config('portal-monitor.url'), '/');
|
||||
$apiKey = (string) config('portal-monitor.api_key');
|
||||
@@ -31,7 +40,7 @@ class PortalMonitorClient
|
||||
$response = Http::acceptJson()
|
||||
->withHeaders(['X-API-Key' => $apiKey])
|
||||
->timeout((int) config('portal-monitor.timeout', 5))
|
||||
->get($url . '/api/v1/vsphere/vms/' . rawurlencode($vmwareId) . '/' . $resource);
|
||||
->get($url . '/api/v1/vsphere/vms/' . rawurlencode($vmwareId) . '/' . $resource, $query);
|
||||
} catch (ConnectionException) {
|
||||
throw new RuntimeException('Portal Monitor is unavailable');
|
||||
}
|
||||
|
||||
@@ -11,7 +11,11 @@ class VmMetricsService
|
||||
public function get(string $vmwareId, ?int $memoryTotalMb = null, ?int $cpuCores = null): array
|
||||
{
|
||||
$stats = $this->portalMonitor->vmMetrics($vmwareId);
|
||||
$storage = $this->portalMonitor->vmStorage($vmwareId);
|
||||
try {
|
||||
$storage = $this->portalMonitor->vmStorage($vmwareId);
|
||||
} catch (\RuntimeException) {
|
||||
$storage = [];
|
||||
}
|
||||
$provisionedDiskBytes = collect($storage['disks'] ?? [])->sum(
|
||||
fn ($disk) => is_array($disk) ? (int) ($disk['capacity_bytes'] ?? 0) : 0
|
||||
);
|
||||
@@ -38,4 +42,36 @@ class VmMetricsService
|
||||
'stale' => (bool) ($stats['stale'] ?? false),
|
||||
];
|
||||
}
|
||||
|
||||
private const HISTORY_FIELDS = [
|
||||
'cpu' => 'cpu_usage_percent',
|
||||
'mem' => 'guest_memory_usage_percent',
|
||||
'disk_read_bps' => 'disk_read_bps',
|
||||
'disk_write_bps' => 'disk_write_bps',
|
||||
'net_rx_bps' => 'network_rx_bps',
|
||||
'net_tx_bps' => 'network_tx_bps',
|
||||
];
|
||||
|
||||
public function history(string $vmwareId, \DateTimeInterface $from, \DateTimeInterface $to, int $maxPoints = 240): array
|
||||
{
|
||||
$rows = $this->portalMonitor->vmHistory($vmwareId, $from, $to);
|
||||
$span = max(1, $to->getTimestamp() - $from->getTimestamp());
|
||||
$bucket = max(1, (int) ceil($span / $maxPoints));
|
||||
|
||||
return collect($rows)
|
||||
->filter(fn ($row) => is_array($row) && isset($row['timestamp']))
|
||||
->groupBy(fn ($row) => intdiv(strtotime($row['timestamp']), $bucket))
|
||||
->map(function ($group, $key) use ($bucket) {
|
||||
$point = ['t' => gmdate('c', $key * $bucket + intdiv($bucket, 2))];
|
||||
foreach (self::HISTORY_FIELDS as $name => $source) {
|
||||
$values = $group->pluck($source)->filter(fn ($v) => $v !== null);
|
||||
$point[$name] = $values->isEmpty() ? null : round($values->avg(), 2);
|
||||
}
|
||||
|
||||
return $point;
|
||||
})
|
||||
->sortKeys()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user