update rm deadcode
This commit is contained in:
@@ -25,6 +25,7 @@ class ClientAuthService
|
||||
{
|
||||
// Refresh token lifetime in days
|
||||
const REFRESH_TOKEN_TTL_DAYS = 30;
|
||||
const REFRESH_TOKEN_REUSE_GRACE_SECONDS = 30;
|
||||
|
||||
const VERIFY_MAX_ATTEMPTS = 5;
|
||||
|
||||
@@ -280,9 +281,27 @@ class ClientAuthService
|
||||
|
||||
$record = RefreshToken::where('token', $hash)->first();
|
||||
|
||||
if (!$record || $record->isExpired()) {
|
||||
// Xoá token cũ nếu tồn tại nhưng hết hạn
|
||||
$record?->delete();
|
||||
if (!$record) {
|
||||
throw ValidationException::withMessages([
|
||||
'refresh_token' => ['Refresh token không hợp lệ hoặc đã hết hạn.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$isConcurrentRefresh = $record->revoked_at !== null
|
||||
&& $record->revoked_at->gt(now()->subSeconds(self::REFRESH_TOKEN_REUSE_GRACE_SECONDS));
|
||||
|
||||
if ($record->revoked_at !== null && !$isConcurrentRefresh) {
|
||||
// Token đã rotate rồi mà còn bị dùng lại: có thể đã bị đánh cắp,
|
||||
// thu hồi toàn bộ refresh token của khách này để buộc đăng nhập lại.
|
||||
RefreshToken::where('customer_id', $record->customer_id)->delete();
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'refresh_token' => ['Refresh token đã được sử dụng, mọi phiên đã bị thu hồi.'],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($record->isExpired()) {
|
||||
$record->delete();
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'refresh_token' => ['Refresh token không hợp lệ hoặc đã hết hạn.'],
|
||||
@@ -298,8 +317,10 @@ class ClientAuthService
|
||||
]);
|
||||
}
|
||||
|
||||
// Rotation: xoá token cũ
|
||||
$record->delete();
|
||||
// Rotation: đánh dấu đã dùng thay vì xoá, để phát hiện reuse nếu bị dùng lại
|
||||
if (!$isConcurrentRefresh) {
|
||||
RefreshToken::whereKey($record->getKey())->whereNull('revoked_at')->update(['revoked_at' => now()]);
|
||||
}
|
||||
|
||||
// Tạo access token mới
|
||||
$newAccessToken = JWTAuth::fromUser($customer);
|
||||
|
||||
@@ -46,8 +46,7 @@ class DomainOrderService
|
||||
|
||||
$domainName = $this->normalizeDomain($data['domain_name']);
|
||||
$years = max(1, (int) ($data['years'] ?? 1));
|
||||
$pricing = $this->findDomainPricing($domainName);
|
||||
$price = (int) $pricing['firstYear'] * $years;
|
||||
$price = DomainPricing::findByDomain($domainName)->orderPrice($years);
|
||||
$months = $years * 12;
|
||||
|
||||
return DB::transaction(function () use ($customer, $product, $domainName, $price, $months, $years) {
|
||||
@@ -363,17 +362,6 @@ class DomainOrderService
|
||||
// Private helpers
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Find pricing for the given domain using longest-match TLD.
|
||||
* TLDs in settings are stored with a leading dot (e.g. ".com.vn").
|
||||
*
|
||||
* @throws \InvalidArgumentException if no matching TLD found
|
||||
*/
|
||||
private function findDomainPricing(string $domain): array
|
||||
{
|
||||
return DomainPricing::findByDomain($domain)->toDomainArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize: lowercase, trim, strip protocol and path.
|
||||
* "HTTPS://My-Site.COM.VN/path" → "my-site.com.vn"
|
||||
|
||||
@@ -17,6 +17,7 @@ use App\Models\Service;
|
||||
use App\Models\VirtualMachines;
|
||||
use App\Repositories\Api\Order\OrderRepository;
|
||||
use App\Repositories\Api\Service\ServiceRepositoryInterface;
|
||||
use App\Support\RenewalPricing;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -204,6 +205,19 @@ class OrderQueryService
|
||||
return ['ok' => false, 'message' => 'Không thể xác định giá gia hạn dịch vụ.', 'code' => 400];
|
||||
}
|
||||
|
||||
$cycleMonths = OrderHelper::cycleToMonths($orderItem->billing_cycle);
|
||||
$validMonths = RenewalPricing::validMonths($orderItem->billing_cycle);
|
||||
|
||||
if (! in_array($months, $validMonths, true)) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Số tháng gia hạn không hợp lệ với chu kỳ của dịch vụ này. Vui lòng chọn: ' . implode(', ', $validMonths) . ' tháng.',
|
||||
'code' => 422,
|
||||
];
|
||||
}
|
||||
|
||||
$cycles = intdiv($months, $cycleMonths);
|
||||
|
||||
// Gia hạn luôn dùng giá sản phẩm hiện tại trong bảng giá, không dùng giá đã
|
||||
// chốt lúc đặt mua ban đầu — giá cũ chỉ để hiển thị trên đơn hàng/hoá đơn gốc.
|
||||
$currentPrice = $this->productRepo->getPricing((int) $service->product_id, $orderItem->billing_cycle);
|
||||
@@ -211,7 +225,9 @@ class OrderQueryService
|
||||
return ['ok' => false, 'message' => 'Sản phẩm hiện không còn bán, không thể gia hạn.', 'code' => 400];
|
||||
}
|
||||
|
||||
$price = (int) $currentPrice * $months;
|
||||
$renewalPrice = (int) $currentPrice * $cycles;
|
||||
$addonTotal = RenewalPricing::addonTotal($service, $cycles);
|
||||
$price = $renewalPrice + $addonTotal;
|
||||
|
||||
if ($service->invoice_id && Invoice::where('id', $service->invoice_id)
|
||||
->where('invoice_type', 2)
|
||||
@@ -238,7 +254,7 @@ class OrderQueryService
|
||||
$periodStart = $service->expires_at && $service->expires_at->isFuture() ? $service->expires_at->copy() : now();
|
||||
$periodEnd = $periodStart->copy()->addMonths($months);
|
||||
|
||||
$invoice = DB::transaction(function () use ($service, $orderItem, $price, $months, $periodStart, $periodEnd) {
|
||||
$invoice = DB::transaction(function () use ($service, $orderItem, $price, $renewalPrice, $cycles, $months, $periodStart, $periodEnd) {
|
||||
$invoice = Invoice::create([
|
||||
'invoice_number' => OrderHelper::generateOrderNumber('INV'),
|
||||
'customer_id' => $service->customer_id,
|
||||
@@ -261,10 +277,14 @@ class OrderQueryService
|
||||
'description' => 'Gia hạn dịch vụ: ' . ($orderItem->product?->name ?? $service->server_name ?? ''),
|
||||
'months' => $months,
|
||||
'quantity' => 1,
|
||||
'unit_price' => $price,
|
||||
'total_price' => $price,
|
||||
'unit_price' => $renewalPrice,
|
||||
'total_price' => $renewalPrice,
|
||||
]);
|
||||
|
||||
foreach (RenewalPricing::addonInvoiceItems($service, $cycles, $months) as $addonItem) {
|
||||
\App\Models\InvoiceItem::create($addonItem + ['invoice_id' => $invoice->id]);
|
||||
}
|
||||
|
||||
$service->update(['invoice_id' => $invoice->id]);
|
||||
|
||||
return $invoice;
|
||||
|
||||
@@ -5,12 +5,13 @@ namespace App\Services\Api\Order;
|
||||
use App\Enums\Order\OrderStatus;
|
||||
use App\Helpers\OrderHelper;
|
||||
use App\Jobs\Mail\Admin\AdminOrderNotificationJob;
|
||||
use App\Models\Addon;
|
||||
use App\Models\Order;
|
||||
use App\Models\Product;
|
||||
use App\Repositories\Api\Invoice\InvoiceRepository;
|
||||
use App\Repositories\Api\Order\OrderRepository;
|
||||
use App\Repositories\Api\Service\ServiceRepository;
|
||||
use App\Services\InvoicePaymentService;
|
||||
use App\Support\AddonQuantityValidator;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -32,31 +33,31 @@ class OrderService
|
||||
* Validate → calculate price → persist Order + OrderItem + Invoice.
|
||||
*
|
||||
* @return array{order: Order, invoice: \App\Models\Invoice}
|
||||
* @throws Exception
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function create(array $data, $customer): array
|
||||
{
|
||||
if ($this->orderRepo->hasPendingOrder($customer->id)) {
|
||||
throw new Exception('Bạn có đơn hàng chưa thanh toán. Vui lòng thanh toán trước khi tạo đơn mới.');
|
||||
throw new \InvalidArgumentException('Bạn có đơn hàng chưa thanh toán. Vui lòng thanh toán trước khi tạo đơn mới.');
|
||||
}
|
||||
|
||||
$product = $this->productRepo->find($data['product_id']);
|
||||
if (!$product) {
|
||||
throw new Exception('Sản phẩm không tồn tại.');
|
||||
throw new \InvalidArgumentException('Sản phẩm không tồn tại.');
|
||||
}
|
||||
|
||||
$basePrice = $this->productRepo->getPricing($product->id, $data['billing_cycle']);
|
||||
if (is_null($basePrice)) {
|
||||
throw new Exception('Không tìm thấy giá cho chu kỳ thanh toán này.');
|
||||
throw new \InvalidArgumentException('Không tìm thấy giá cho chu kỳ thanh toán này.');
|
||||
}
|
||||
|
||||
// Resolve addons → enriched meta with price & subtotal
|
||||
$addonsMeta = $this->resolveAddons($data['addons'] ?? []);
|
||||
$addonsMeta = $this->resolveAddons($data['addons'] ?? [], $product);
|
||||
$addonsPrice = array_sum(array_column($addonsMeta, 'subtotal'));
|
||||
$total = $basePrice + $addonsPrice;
|
||||
|
||||
if ($customer->total < $total) {
|
||||
throw new Exception(sprintf(
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
'Số dư không đủ. Hiện có: %s VNĐ, cần: %s VNĐ.',
|
||||
number_format($customer->total),
|
||||
number_format($total)
|
||||
@@ -101,19 +102,19 @@ class OrderService
|
||||
/**
|
||||
* Debit customer balance → mark Order+Invoice paid → provision Service records.
|
||||
*
|
||||
* @throws Exception
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function pay(Order $order, string $method): Order
|
||||
{
|
||||
if (in_array($order->status, [OrderStatus::ACTIVE->value, OrderStatus::PROCESSING->value], true)) {
|
||||
throw new Exception('Đơn hàng đã được thanh toán hoặc đang xử lý.');
|
||||
throw new \InvalidArgumentException('Đơn hàng đã được thanh toán hoặc đang xử lý.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($order, $method) {
|
||||
$customer = $order->customer;
|
||||
|
||||
if ($customer->total < $order->total) {
|
||||
throw new Exception(sprintf(
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
'Số dư không đủ. Hiện có: %s VNĐ, cần: %s VNĐ.',
|
||||
number_format($customer->total),
|
||||
number_format($order->total)
|
||||
@@ -126,7 +127,7 @@ class OrderService
|
||||
}
|
||||
|
||||
if (! $order->invoice) {
|
||||
throw new Exception('Không tìm thấy hóa đơn của đơn hàng.');
|
||||
throw new \InvalidArgumentException('Không tìm thấy hóa đơn của đơn hàng.');
|
||||
}
|
||||
|
||||
$this->invoicePaymentService->payWithBalance($order->invoice, $customer, $method);
|
||||
@@ -175,25 +176,13 @@ class OrderService
|
||||
*
|
||||
* Input: [['addon_id' => 1, 'qty' => 2], ...]
|
||||
* Output: [['addon_id' => 1, 'qty' => 2, 'price' => 50000, 'subtotal' => 100000], ...]
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
private function resolveAddons(array $raw): array
|
||||
private function resolveAddons(array $raw, Product $product): array
|
||||
{
|
||||
$resolved = [];
|
||||
foreach ($raw as $entry) {
|
||||
$addon = Addon::find($entry['addon_id'] ?? null);
|
||||
if (!$addon) {
|
||||
continue;
|
||||
}
|
||||
$qty = max(1, (int) ($entry['qty'] ?? 1));
|
||||
$resolved[] = [
|
||||
'addon_id' => $addon->id,
|
||||
'code' => strtolower((string) $addon->code),
|
||||
'name' => $addon->name,
|
||||
'qty' => $qty,
|
||||
'price' => $addon->price,
|
||||
'subtotal' => $addon->price * $qty,
|
||||
];
|
||||
}
|
||||
return $resolved;
|
||||
$activeAddons = $product->addons()->where('status', true)->get()->keyBy('id');
|
||||
|
||||
return AddonQuantityValidator::resolve($raw, $activeAddons);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,7 +76,13 @@ class CustomerServiceProvisioningService
|
||||
{
|
||||
$services = $this->serviceRepository->filter(
|
||||
['customer_uuid' => $uuid],
|
||||
['product', 'orderItem', 'invoice', 'vmware.os.osGroup'],
|
||||
[
|
||||
'product',
|
||||
'orderItem',
|
||||
'invoice',
|
||||
'vmware.os.osGroup',
|
||||
...Service::HOSTING_ACCOUNT_RELATIONS,
|
||||
],
|
||||
);
|
||||
|
||||
ModuleVmware::resolveVirtualMachineIds($services->pluck('vmware'));
|
||||
|
||||
@@ -9,6 +9,8 @@ use App\Helpers\OrderHelper;
|
||||
use App\Jobs\Hosting\ProvisionHostingAccountJob;
|
||||
use App\Jobs\VirtualMachine\Action\VMJobs;
|
||||
use App\Jobs\VirtualMachine\Create\CreateVirtualMachineJob;
|
||||
use App\Jobs\VirtualMachine\Provision\UpdateVmConfigJob;
|
||||
use App\Http\Services\vCenter as ServiceVCenter;
|
||||
use App\Models\Addon;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Invoice;
|
||||
@@ -19,6 +21,7 @@ use App\Models\ServiceAddon;
|
||||
use App\Models\Transaction;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class InvoicePaymentService
|
||||
@@ -125,6 +128,8 @@ class InvoicePaymentService
|
||||
|
||||
if ((int) $invoice->invoice_type === 2) {
|
||||
$this->activateRenewal($invoice);
|
||||
} elseif ((int) $invoice->invoice_type === 3) {
|
||||
$this->activateUpgrade($invoice);
|
||||
} elseif ($invoice->order) {
|
||||
$this->activateOrder($invoice);
|
||||
}
|
||||
@@ -197,6 +202,8 @@ class InvoicePaymentService
|
||||
|
||||
if ((int) $invoice->invoice_type === 2) {
|
||||
$this->activateRenewal($invoice);
|
||||
} elseif ((int) $invoice->invoice_type === 3) {
|
||||
$this->activateUpgrade($invoice);
|
||||
} elseif ($invoice->order) {
|
||||
$this->activateOrder($invoice);
|
||||
}
|
||||
@@ -385,6 +392,107 @@ class InvoicePaymentService
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges the purchased addons into order_items.addons_meta (so RenewalPricing charges
|
||||
* them on the next renewal) and applies the new absolute CPU/RAM/disk totals to the VM.
|
||||
*/
|
||||
private function activateUpgrade(Invoice $invoice): void
|
||||
{
|
||||
$service = Service::query()
|
||||
->with(['orderItem.product', 'vmware'])
|
||||
->find($invoice->service_id);
|
||||
|
||||
$orderItem = $service?->orderItem;
|
||||
if (! $service || ! $orderItem) {
|
||||
return;
|
||||
}
|
||||
|
||||
$upgradeItems = $invoice->invoiceItems()->where('type', 'upgrade')->get();
|
||||
if ($upgradeItems->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$meta = collect(is_array($orderItem->addons_meta) ? $orderItem->addons_meta : []);
|
||||
$purchasedCodes = [];
|
||||
|
||||
foreach ($upgradeItems as $item) {
|
||||
$addon = Addon::find($item->addon_id);
|
||||
if (! $addon) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$code = strtolower((string) $addon->code);
|
||||
$purchasedCodes[] = $code;
|
||||
|
||||
$qty = (int) $item->quantity;
|
||||
$index = $meta->search(fn ($entry) => (int) ($entry['addon_id'] ?? 0) === $addon->id);
|
||||
$currentQty = $index === false ? 0 : (int) ($meta->get($index)['qty'] ?? 0);
|
||||
$newQty = $currentQty + $qty;
|
||||
|
||||
$entry = [
|
||||
'addon_id' => $addon->id,
|
||||
'code' => $code,
|
||||
'name' => $addon->name,
|
||||
'qty' => $newQty,
|
||||
'price' => (float) $addon->price,
|
||||
'subtotal' => $newQty * (float) $addon->price,
|
||||
];
|
||||
|
||||
if ($index === false) {
|
||||
$meta->push($entry);
|
||||
} else {
|
||||
$meta->put($index, $entry);
|
||||
}
|
||||
}
|
||||
|
||||
$orderItem->update(['addons_meta' => $meta->values()->all()]);
|
||||
|
||||
$moduleVmware = $service->vmware;
|
||||
if (! $moduleVmware) {
|
||||
return;
|
||||
}
|
||||
|
||||
$addonQtyByCode = $meta->keyBy(fn ($entry) => $entry['code'] ?? '');
|
||||
$product = $orderItem->product;
|
||||
|
||||
if (array_intersect(['cpu', 'ram'], $purchasedCodes)) {
|
||||
$totalCpu = (int) ($product?->cpu ?? 0) + (int) ($addonQtyByCode->get('cpu')['qty'] ?? 0);
|
||||
$totalRam = (int) ($product?->ram ?? 0) + (int) ($addonQtyByCode->get('ram')['qty'] ?? 0);
|
||||
|
||||
UpdateVmConfigJob::dispatch(
|
||||
$moduleVmware->id,
|
||||
(string) $moduleVmware->vmware_id,
|
||||
'',
|
||||
$totalCpu,
|
||||
$totalRam,
|
||||
)->afterCommit();
|
||||
}
|
||||
|
||||
if (in_array('disk', $purchasedCodes, true)) {
|
||||
$totalDisk = (int) ($product?->disk ?? 0) + (int) ($addonQtyByCode->get('disk')['qty'] ?? 0);
|
||||
$vcenter = $moduleVmware->vCenter ?? $moduleVmware->ipAddress?->host?->datacenter?->vCenter;
|
||||
|
||||
if ($vcenter) {
|
||||
DB::afterCommit(function () use ($vcenter, $moduleVmware, $totalDisk, $invoice) {
|
||||
try {
|
||||
$serviceVCenter = new ServiceVCenter();
|
||||
if (! $serviceVCenter->loginServer($vcenter)) {
|
||||
throw new \RuntimeException('vCenter login failed');
|
||||
}
|
||||
$serviceVCenter->UpgradeDiskVirtualMachine($moduleVmware, $totalDisk);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('activateUpgrade: disk upgrade failed', [
|
||||
'invoice_id' => $invoice->id,
|
||||
'module_vmware_id' => $moduleVmware->id,
|
||||
'total_disk' => $totalDisk,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function attachServiceAddons(Service $service, OrderItem $item): void
|
||||
{
|
||||
if ($service->addons()->exists()) {
|
||||
|
||||
@@ -37,7 +37,7 @@ class InvoiceReminderService
|
||||
}
|
||||
|
||||
$now = $now ?? now();
|
||||
$daysFromDue = $invoice->due_date->copy()->startOfDay()->diffInDays($now->copy()->startOfDay(), false);
|
||||
$daysFromDue = (int) $invoice->due_date->copy()->startOfDay()->diffInDays($now->copy()->startOfDay(), false);
|
||||
|
||||
$offsets = (array) config('billing.reminder_offsets', []);
|
||||
if ($offsets === []) {
|
||||
@@ -95,7 +95,7 @@ class InvoiceReminderService
|
||||
{
|
||||
$now = $now ?? now();
|
||||
$dueDate = $invoice->due_date;
|
||||
$daysLate = $dueDate ? $dueDate->copy()->startOfDay()->diffInDays($now->copy()->startOfDay(), false) : 0;
|
||||
$daysLate = $dueDate ? (int) $dueDate->copy()->startOfDay()->diffInDays($now->copy()->startOfDay(), false) : 0;
|
||||
$outstanding = max(0, (int) $invoice->total - (int) ($invoice->amount_paid ?? 0));
|
||||
|
||||
return [
|
||||
|
||||
@@ -6,7 +6,7 @@ use App\Facades\BaseHelperFacade as BaseHelper;
|
||||
use App\Models\DnsServer;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
|
||||
class PleskService
|
||||
{
|
||||
@@ -17,7 +17,7 @@ class PleskService
|
||||
|
||||
public function client(DnsServer $server, int $timeout = 30): PendingRequest
|
||||
{
|
||||
return Http::withoutVerifying()
|
||||
return TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($server->username, Crypt::decryptString($server->password))
|
||||
->timeout($timeout);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use App\Facades\BaseHelperFacade as BaseHelper;
|
||||
use App\Models\DnsServer;
|
||||
use App\Repositories\DnsManager\Server\DnsServerRepositoryInterface;
|
||||
use App\Services\Plesk\PleskDomainService;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Http\Client\RequestException;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -77,7 +77,7 @@ class ServerService
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($this->server->username, Crypt::decryptString($this->server->password))
|
||||
->timeout(10)
|
||||
->post(
|
||||
@@ -103,7 +103,7 @@ class ServerService
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($this->server->username, Crypt::decryptString($this->server->password))
|
||||
->timeout(15)
|
||||
->get(
|
||||
@@ -127,7 +127,7 @@ class ServerService
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($this->server->username, Crypt::decryptString($this->server->password))
|
||||
->timeout(10)
|
||||
->put(
|
||||
@@ -153,7 +153,7 @@ class ServerService
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($this->server->username, Crypt::decryptString($this->server->password))
|
||||
->timeout(30)
|
||||
->delete(
|
||||
@@ -178,7 +178,7 @@ class ServerService
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($data['username'], $data['password'])
|
||||
->timeout(10)
|
||||
->get(BaseHelper::url($data['ip_address']) . $this->entry_points['server']);
|
||||
|
||||
@@ -8,7 +8,7 @@ use App\DTOs\VirtualMachine\Rebuild\RebuildContext;
|
||||
use App\Http\Services\vCenter as VCenterService;
|
||||
use App\Models\ModuleDatastore;
|
||||
use App\Models\vCenter as VCenterModel;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use RuntimeException;
|
||||
|
||||
@@ -74,7 +74,7 @@ final class VmRebuildCloneService
|
||||
'template' => $ctx->template,
|
||||
]);
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->timeout(self::CLONE_TIMEOUT)
|
||||
->connectTimeout(30)
|
||||
->withHeaders([
|
||||
@@ -121,7 +121,7 @@ final class VmRebuildCloneService
|
||||
throw new RuntimeException("Rebuild powerOn: cannot login to vCenter #{$ctx->vcenterId}");
|
||||
}
|
||||
|
||||
$powerResp = Http::withoutVerifying()
|
||||
$powerResp = TlsHttpClientFactory::vCenter()
|
||||
->timeout(self::POWER_ON_TIMEOUT)
|
||||
->withHeaders(['vmware-api-session-id' => $this->vCenter->token])
|
||||
->post("https://{$this->vCenter->apiUri}/rest/vcenter/vm/{$ctx->newVmId}/power/start");
|
||||
@@ -138,7 +138,7 @@ final class VmRebuildCloneService
|
||||
]);
|
||||
|
||||
for ($i = 1; $i <= self::TOOLS_MAX_ATTEMPTS; $i++) {
|
||||
$info = Http::withoutVerifying()
|
||||
$info = TlsHttpClientFactory::vCenter()
|
||||
->timeout(10)
|
||||
->withHeaders(['vmware-api-session-id' => $this->vCenter->token])
|
||||
->get("https://{$this->vCenter->apiUri}/rest/vcenter/vm/{$ctx->newVmId}/guest/identity")
|
||||
@@ -185,7 +185,7 @@ final class VmRebuildCloneService
|
||||
}
|
||||
|
||||
try {
|
||||
Http::withoutVerifying()
|
||||
TlsHttpClientFactory::vCenter()
|
||||
->timeout(30)
|
||||
->withHeaders(['vmware-api-session-id' => $this->vCenter->token])
|
||||
->post("https://{$this->vCenter->apiUri}/rest/vcenter/vm/{$ctx->oldVmId}/power/stop");
|
||||
|
||||
@@ -74,6 +74,53 @@ class VmIpReservationService
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reserve a specific, still-free IP within a network (customer-picked change-IP flow).
|
||||
*
|
||||
* @return array{ip_pool_id:int, gateway:string}|null
|
||||
*/
|
||||
public function reserveInNetwork(int $networkId, string $ipAddress, int $serviceId): ?array
|
||||
{
|
||||
return DB::transaction(function () use ($networkId, $ipAddress, $serviceId) {
|
||||
$ipPool = IpPool::where('module_network_id', $networkId)
|
||||
->where('ip_address', $ipAddress)
|
||||
->where('status', 'free')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (!$ipPool) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ipPool->update(['status' => 'assigned', 'service_id' => $serviceId]);
|
||||
|
||||
return [
|
||||
'ip_pool_id' => $ipPool->id,
|
||||
'gateway' => (string) ($ipPool->gateway ?? ''),
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
public function freeIpsInNetwork(int $networkId)
|
||||
{
|
||||
return IpPool::where('module_network_id', $networkId)
|
||||
->where('status', 'free')
|
||||
->orderBy('ip_address')
|
||||
->get(['id', 'ip_address', 'gateway']);
|
||||
}
|
||||
|
||||
public function releaseByPoolId(int $ipPoolId): void
|
||||
{
|
||||
try {
|
||||
IpPool::where('id', $ipPoolId)->update(['status' => 'free', 'service_id' => null]);
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('VmIpReservationService: releaseByPoolId failed', [
|
||||
'ip_pool_id' => $ipPoolId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function release(ModuleIpAddress $reservation, ?int $ipPoolId): void
|
||||
{
|
||||
try {
|
||||
|
||||
@@ -5,7 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Services\VirtualMachine;
|
||||
|
||||
use App\Http\Services\vCenter;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
@@ -18,7 +18,7 @@ class VmPowerService
|
||||
return 'Login_Again';
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders(['vmware-api-session-id' => $vCenter->token])
|
||||
->post("https://{$vCenter->apiUri}/rest/vcenter/vm/{$vmId}/power/start");
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace App\Services;
|
||||
use App\Http\Facade\SignRSA;
|
||||
use App\Http\Services\vCenter as VCenterService;
|
||||
use App\Models\ModuleVmware;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
final class VmProvisionService
|
||||
@@ -38,7 +38,7 @@ final class VmProvisionService
|
||||
public function getVmGuestInfo(VCenterService $service, string $vmId): array
|
||||
{
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders(['vmware-api-session-id' => $service->token])
|
||||
->timeout(10)
|
||||
->get("https://{$service->apiUri}/rest/vcenter/vm/{$vmId}/guest/identity");
|
||||
|
||||
@@ -6,6 +6,8 @@ namespace App\Services;
|
||||
|
||||
use App\Http\Facade\SignRSA;
|
||||
use App\Models\InfraManagement;
|
||||
use App\Support\PowerShellEscaper;
|
||||
use App\Support\SshHostKeyVerifier;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use phpseclib3\Net\SSH2;
|
||||
|
||||
@@ -207,6 +209,8 @@ final class VsphereHostSshService
|
||||
|
||||
$client = new SSH2($config['host'], $config['port'], self::CONNECT_TIMEOUT);
|
||||
|
||||
SshHostKeyVerifier::verify($client, $config['host']);
|
||||
|
||||
if (!$client->login($config['username'], $config['password'])) {
|
||||
throw new \RuntimeException(
|
||||
"SSH login failed: {$config['host']}:{$config['port']}"
|
||||
@@ -364,23 +368,14 @@ final class VsphereHostSshService
|
||||
*/
|
||||
private function windowsPowerShellCommand(string $workingDirectory, string $script, array $arguments): string
|
||||
{
|
||||
return sprintf(
|
||||
'powershell -ExecutionPolicy Bypass -NonInteractive -File "%s\\%s" %s',
|
||||
$workingDirectory,
|
||||
$script,
|
||||
implode(' ', array_map(
|
||||
fn (string $argument): string => $this->warg($argument),
|
||||
$arguments,
|
||||
)),
|
||||
);
|
||||
}
|
||||
$scriptPath = $workingDirectory . '\\' . $script;
|
||||
$psScript = '& ' . PowerShellEscaper::singleQuote($scriptPath) . ' ' . implode(' ', array_map(
|
||||
fn (string $argument): string => PowerShellEscaper::singleQuote($argument),
|
||||
$arguments,
|
||||
));
|
||||
|
||||
/**
|
||||
* Windows cmd.exe safe argument: wrap in double quotes, escape inner double quotes.
|
||||
*/
|
||||
private function warg(string $value): string
|
||||
{
|
||||
return '"' . str_replace('"', '\\"', $value) . '"';
|
||||
return 'powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand '
|
||||
. PowerShellEscaper::encodedCommand($psScript);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user