update logic
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\Imports\LegacyPortalImporter;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class SyncLegacyPortal extends Command
|
||||
{
|
||||
protected $signature = 'legacy:sync-portal
|
||||
{--preview : Count and validate only, no writes}
|
||||
{--default-product=1 : Fallback portal.products.id used when legacy product is not mapped}
|
||||
{--map=* : Explicit legacy→new product map, format "legacyId:newId" (repeatable)}';
|
||||
|
||||
protected $description = 'Sync customers + services from legacy `portal` DB (connection: legacy) into current schema';
|
||||
|
||||
public function handle(LegacyPortalImporter $importer): int
|
||||
{
|
||||
$preview = (bool) $this->option('preview');
|
||||
$importer->setDefaultVpsProductId((int) $this->option('default-product'));
|
||||
|
||||
$map = [];
|
||||
foreach ((array) $this->option('map') as $pair) {
|
||||
if (! str_contains($pair, ':')) continue;
|
||||
[$legacy, $new] = explode(':', $pair, 2);
|
||||
$map[(int) $legacy] = (int) $new;
|
||||
}
|
||||
if ($map) {
|
||||
$importer->setProductMap($map);
|
||||
$this->info('Product map: ' . json_encode($map));
|
||||
}
|
||||
|
||||
if (! $preview && ! $this->confirm('This will write to the current DB. Continue?', true)) {
|
||||
$this->warn('Aborted.');
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
try {
|
||||
$summary = $importer->import(
|
||||
preview: $preview,
|
||||
log: fn ($msg) => $this->line($msg),
|
||||
);
|
||||
} catch (\Throwable $e) {
|
||||
$this->error($e->getMessage());
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->info('=== Summary ===');
|
||||
foreach ($summary as $section => $stats) {
|
||||
$this->line(str_pad(ucfirst($section), 12) . ': ' . json_encode($stats));
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DTOs\Order;
|
||||
|
||||
class ClientOrderFilters
|
||||
{
|
||||
public function __construct(
|
||||
public readonly ?string $totalPrice = null,
|
||||
public readonly bool $pending = false,
|
||||
) {
|
||||
}
|
||||
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
return new self(
|
||||
totalPrice: $data['total_price'] ?? null,
|
||||
pending: filter_var($data['pending'] ?? false, FILTER_VALIDATE_BOOLEAN),
|
||||
);
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'total_price' => $this->totalPrice,
|
||||
'pending' => $this->pending,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -575,6 +575,119 @@ class CustomerController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a service for a customer. For VPS products, accepts a
|
||||
* `virtual_machine_id` from the vCenter inventory and auto-creates the
|
||||
* matching module_vmware row so `services.vm_id` can be linked.
|
||||
*/
|
||||
public function createService(string $uuid, Request $request): JsonResponse
|
||||
{
|
||||
$customer = $this->customerRepository->findBy('uuid', $uuid);
|
||||
if (!$customer) {
|
||||
return response()->json(['error' => true, 'message' => "Can't find customer"], 404);
|
||||
}
|
||||
|
||||
$data = $request->validate([
|
||||
'product_id' => 'required|integer|exists:products,id',
|
||||
'virtual_machine_id' => 'nullable|integer|exists:virtual_machines,id',
|
||||
'server_name' => 'nullable|string|max:255',
|
||||
'status' => 'nullable|in:pending,active,suspended,expired,cancelled,terminated',
|
||||
'auto_renew' => 'nullable|boolean',
|
||||
'started_at' => 'nullable|date',
|
||||
'expires_at' => 'nullable|date',
|
||||
'note' => 'nullable|string',
|
||||
]);
|
||||
|
||||
$product = \App\Models\Product::find($data['product_id']);
|
||||
if ($product->product_type === 'vps' && empty($data['virtual_machine_id'])) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'VPS service requires a virtual_machine_id',
|
||||
], 422);
|
||||
}
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
$vmId = null;
|
||||
if (!empty($data['virtual_machine_id'])) {
|
||||
$vm = \App\Models\VirtualMachines::find($data['virtual_machine_id']);
|
||||
$moduleVm = \App\Models\ModuleVmware::create([
|
||||
'customer_id' => $customer->id,
|
||||
'name' => $vm->name,
|
||||
'vmware_id' => $vm->vm_id,
|
||||
'virtual_machine_id' => $vm->id,
|
||||
'hostname' => $data['server_name'] ?? $vm->name,
|
||||
'status' => 1,
|
||||
]);
|
||||
$vmId = $moduleVm->id;
|
||||
}
|
||||
|
||||
$service = \App\Models\Service::create([
|
||||
'customer_id' => $customer->id,
|
||||
'product_id' => $data['product_id'],
|
||||
'vm_id' => $vmId,
|
||||
'server_name' => $data['server_name'] ?? null,
|
||||
'status' => $data['status'] ?? 'active',
|
||||
'auto_renew' => (bool) ($data['auto_renew'] ?? false),
|
||||
'started_at' => $data['started_at'] ?? now(),
|
||||
'expires_at' => $data['expires_at'] ?? null,
|
||||
'note' => $data['note'] ?? null,
|
||||
]);
|
||||
|
||||
DB::commit();
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'message' => 'Service created',
|
||||
'data' => $service->load(['product']),
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
DB::rollBack();
|
||||
return response()->json(['error' => true, 'message' => $e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List virtual machines from vCenter inventory for the VPS picker.
|
||||
* Annotates each VM with `assigned_service_id` if already linked to a service.
|
||||
*/
|
||||
public function listAvailableVms(Request $request): JsonResponse
|
||||
{
|
||||
$search = trim((string) $request->get('q', ''));
|
||||
|
||||
$assignments = DB::table('module_vmware as mv')
|
||||
->join('services as s', 's.vm_id', '=', 'mv.id')
|
||||
->whereNotNull('mv.virtual_machine_id')
|
||||
->select(
|
||||
'mv.virtual_machine_id',
|
||||
's.id as service_id',
|
||||
's.customer_id as service_customer_id',
|
||||
)
|
||||
->get()
|
||||
->keyBy('virtual_machine_id');
|
||||
|
||||
$vms = DB::table('virtual_machines')
|
||||
->select('id', 'vm_id', 'name', 'power_state', 'cpu', 'ram_mb', 'ip')
|
||||
->where('is_template', 0)
|
||||
->where('is_system', 0)
|
||||
->when($search, fn ($q) => $q->where(function ($w) use ($search) {
|
||||
$w->where('name', 'like', "%{$search}%")
|
||||
->orWhere('vm_id', 'like', "%{$search}%")
|
||||
->orWhere('ip', 'like', "%{$search}%");
|
||||
}))
|
||||
->orderBy('name')
|
||||
->limit(200)
|
||||
->get()
|
||||
->map(function ($vm) use ($assignments) {
|
||||
$a = $assignments->get($vm->id);
|
||||
$vm->assigned_service_id = $a->service_id ?? null;
|
||||
$vm->assigned_customer_id = $a->service_customer_id ?? null;
|
||||
return $vm;
|
||||
});
|
||||
|
||||
return response()->json(['error' => false, 'data' => $vms]);
|
||||
}
|
||||
|
||||
public function getOrders(string $uuid, Request $request): JsonResponse
|
||||
{
|
||||
$customer = $this->customerRepository->findBy('uuid', $uuid);
|
||||
|
||||
@@ -189,6 +189,7 @@ class VCenterController extends Controller
|
||||
'db_id' => $vm->id,
|
||||
'uuid' => $vm->uuid,
|
||||
'vm_id' => $vm->vm_id,
|
||||
'ip' => $vm->ip,
|
||||
'power_state' => $vm->power_state,
|
||||
'folder' => $vm->folder,
|
||||
'cpu' => $vm->cpu,
|
||||
@@ -263,6 +264,7 @@ class VCenterController extends Controller
|
||||
'db_id' => $vm->id,
|
||||
'uuid' => $vm->uuid,
|
||||
'vm_id' => $vm->vm_id,
|
||||
'ip' => $vm->ip,
|
||||
'power_state' => $vm->power_state,
|
||||
'folder' => $vm->folder,
|
||||
'cpu' => $vm->cpu,
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Service;
|
||||
|
||||
use App\DTOs\Order\ClientOrderFilters;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Api\Order\CheckServerNameRequest;
|
||||
use App\Http\Requests\Api\Order\PayOrderRequest;
|
||||
use App\Http\Requests\Api\Order\RenewServiceRequest;
|
||||
use App\Http\Requests\Api\Order\StoreOrderRequest;
|
||||
use App\Http\Resources\Api\Service\Order\InvoiceDetailResource;
|
||||
use App\Http\Resources\Api\Service\Order\InvoiceSummaryResource;
|
||||
use App\Http\Resources\Api\Service\Order\OrderDetailResource;
|
||||
use App\Http\Resources\Api\Service\Order\OrderItemResource;
|
||||
use App\Http\Resources\Api\Service\Order\OrderSummaryResource;
|
||||
use App\Http\Resources\Api\Service\Order\ServiceDetailResource;
|
||||
use App\Http\Resources\Api\Service\Order\ServiceSummaryResource;
|
||||
use App\Repositories\Api\Order\OrderRepository;
|
||||
use App\Services\ActivityLogger;
|
||||
use App\Services\Api\Order\OrderQueryService;
|
||||
use App\Services\Api\Order\OrderService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class OrderControllerRefactor extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly OrderService $orderService,
|
||||
private readonly OrderRepository $orderRepository,
|
||||
private readonly OrderQueryService $orderQueryService,
|
||||
private readonly ActivityLogger $activityLogger,
|
||||
) {
|
||||
}
|
||||
|
||||
public function getList(Request $request): JsonResponse
|
||||
{
|
||||
$orders = $this->orderQueryService->getOrdersForCustomer(
|
||||
(int) $request->user()->id,
|
||||
ClientOrderFilters::fromArray($request->only(['total_price', 'pending']))
|
||||
);
|
||||
|
||||
return response()->json(['success' => true, 'data' => $orders]);
|
||||
}
|
||||
|
||||
public function checkServerName(CheckServerNameRequest $request): JsonResponse
|
||||
{
|
||||
$result = $this->orderQueryService->checkServerName($request->string('name')->toString());
|
||||
|
||||
return response()->json($result['available'] ? ['available' => true] : $result);
|
||||
}
|
||||
|
||||
public function getClientOrders(Request $request): JsonResponse
|
||||
{
|
||||
$orders = $this->orderRepository->getOrders((int) $request->user()->id, []);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => OrderSummaryResource::collection($orders->getCollection()->load('invoice')),
|
||||
]);
|
||||
}
|
||||
|
||||
public function getClientOrderDetail(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$order = $this->orderQueryService->findCustomerOrder((int) $request->user()->id, $id);
|
||||
|
||||
if (! $order) {
|
||||
return response()->json(['success' => false, 'message' => 'Đơn hàng không tồn tại.'], 404);
|
||||
}
|
||||
|
||||
return response()->json(['success' => true, 'data' => new OrderDetailResource($order)]);
|
||||
}
|
||||
|
||||
public function storeOrder(StoreOrderRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$customer = $request->user();
|
||||
$data = $request->validated();
|
||||
|
||||
$product = \App\Models\Product::where('uuid', $data['product_id'])->first();
|
||||
if (! $product) {
|
||||
return response()->json(['success' => false, 'message' => 'Sản phẩm không tìm thấy hoặc đã bị xóa.'], 404);
|
||||
}
|
||||
|
||||
$data['product_id'] = $product->id;
|
||||
$result = $this->orderService->create($data, $customer);
|
||||
|
||||
$order = $result['order']->load(['orderItems.product', 'invoice', 'customer']);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Tạo đơn hàng thành công.',
|
||||
'notice' => 'Dịch vụ VPS sẽ được khởi tạo trong 5-10 phút sau khi thanh toán.',
|
||||
'data' => [
|
||||
'order' => new OrderDetailResource($order),
|
||||
'invoice' => new InvoiceDetailResource($result['invoice']->load(['customer', 'order'])),
|
||||
'items' => OrderItemResource::collection($order->orderItems),
|
||||
],
|
||||
], 201);
|
||||
} catch (\Throwable $e) {
|
||||
return response()->json(['success' => false, 'message' => $e->getMessage()], 400);
|
||||
}
|
||||
}
|
||||
|
||||
public function payOrder(int $id, PayOrderRequest $request): JsonResponse
|
||||
{
|
||||
$order = $this->orderRepository->find($id);
|
||||
|
||||
if (! $order) {
|
||||
return response()->json(['success' => false, 'message' => 'Đơn hàng không tồn tại.'], 404);
|
||||
}
|
||||
|
||||
if ($order->customer_id !== $request->user()->id) {
|
||||
return response()->json(['success' => false, 'message' => 'Không có quyền truy cập.'], 403);
|
||||
}
|
||||
|
||||
$this->orderService->pay($order, $request->payment_method);
|
||||
|
||||
$this->activityLogger->log(
|
||||
event: 'payment',
|
||||
logName: 'Order',
|
||||
description: "Customer {$request->user()->email} thanh toán đơn hàng #{$order->order_num} qua {$request->payment_method}",
|
||||
subject: $order,
|
||||
newValues: ['payment_method' => $request->payment_method, 'total' => $order->total],
|
||||
);
|
||||
|
||||
return response()->json(['success' => true, 'message' => 'Thanh toán thành công.']);
|
||||
}
|
||||
|
||||
public function retryOrderProvisioning(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$order = $this->orderRepository->find($id);
|
||||
|
||||
if (! $order) {
|
||||
return response()->json(['success' => false, 'message' => 'Đơn hàng không tồn tại.'], 404);
|
||||
}
|
||||
|
||||
$result = $this->orderQueryService->retryProvisioning($order, (int) $request->user()->id);
|
||||
|
||||
if (! $result['ok']) {
|
||||
return response()->json(['success' => false, 'message' => $result['message']], $result['code']);
|
||||
}
|
||||
|
||||
$this->activityLogger->log(
|
||||
event: 'retry_provisioning',
|
||||
logName: 'Order',
|
||||
description: "Customer {$request->user()->email} yêu cầu khởi tạo lại dịch vụ cho đơn hàng #{$order->order_num}",
|
||||
subject: $order,
|
||||
);
|
||||
|
||||
return response()->json(['success' => true, 'message' => $result['message']]);
|
||||
}
|
||||
|
||||
public function getClientInvoices(Request $request): JsonResponse
|
||||
{
|
||||
$invoices = $this->orderQueryService->getCustomerInvoices((int) $request->user()->id);
|
||||
|
||||
return response()->json(['success' => true, 'data' => InvoiceSummaryResource::collection($invoices)]);
|
||||
}
|
||||
|
||||
public function getClientInvoiceDetail(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$invoice = $this->orderQueryService->findCustomerInvoice((int) $request->user()->id, $id);
|
||||
|
||||
if (! $invoice) {
|
||||
return response()->json(['success' => false, 'message' => 'Hóa đơn không tồn tại.'], 404);
|
||||
}
|
||||
|
||||
return response()->json(['success' => true, 'data' => new InvoiceDetailResource($invoice)]);
|
||||
}
|
||||
|
||||
public function getClientInvoiceDetailByOrderNum(Request $request, string $orderNumber): JsonResponse
|
||||
{
|
||||
$order = $this->orderQueryService->findCustomerInvoiceByOrderNum((int) $request->user()->id, $orderNumber);
|
||||
|
||||
if (! $order?->invoice) {
|
||||
return response()->json(['success' => false, 'message' => 'Hóa đơn không tồn tại.'], 404);
|
||||
}
|
||||
|
||||
return response()->json(['success' => true, 'data' => new InvoiceDetailResource($order->invoice->setRelation('order', $order))]);
|
||||
}
|
||||
|
||||
public function getClientServices(Request $request): JsonResponse
|
||||
{
|
||||
$services = $this->orderQueryService->getCustomerServices((int) $request->user()->id);
|
||||
|
||||
return response()->json(['success' => true, 'data' => ServiceSummaryResource::collection($services)]);
|
||||
}
|
||||
|
||||
public function getClientServiceDetail(Request $request, string $uuid): JsonResponse
|
||||
{
|
||||
$service = $this->orderQueryService->findCustomerService((int) $request->user()->id, $uuid);
|
||||
|
||||
if (! $service) {
|
||||
return response()->json(['success' => false, 'message' => 'Không tìm thấy dịch vụ.'], 404);
|
||||
}
|
||||
|
||||
return response()->json(['success' => true, 'data' => new ServiceDetailResource($service)]);
|
||||
}
|
||||
|
||||
public function updateClientServiceAutoRenew(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$validated = $request->validate(['auto_renew' => ['required', 'boolean']]);
|
||||
|
||||
$service = \App\Models\Service::query()
|
||||
->where('id', $id)
|
||||
->where('customer_id', $request->user()->id)
|
||||
->first();
|
||||
|
||||
if (! $service) {
|
||||
return response()->json(['success' => false, 'message' => 'Không tìm thấy dịch vụ.'], 404);
|
||||
}
|
||||
|
||||
$service->update(['auto_renew' => (bool) $validated['auto_renew']]);
|
||||
|
||||
$this->activityLogger->log(
|
||||
event: 'updated',
|
||||
logName: 'Service',
|
||||
description: "Customer {$request->user()->email} " . ($validated['auto_renew'] ? 'bật' : 'tắt') . " tự động gia hạn dịch vụ #{$service->id}",
|
||||
subject: $service,
|
||||
newValues: ['auto_renew' => (bool) $validated['auto_renew']],
|
||||
);
|
||||
|
||||
return response()->json(['success' => true, 'message' => 'Cập nhật tự động gia hạn thành công.', 'data' => ['id' => $service->id, 'auto_renew' => (bool) $service->auto_renew]]);
|
||||
}
|
||||
|
||||
public function renewService(RenewServiceRequest $request, int $id): JsonResponse
|
||||
{
|
||||
$result = $this->orderQueryService->renewService($id, (int) $request->user()->id, (int) $request->validated()['months']);
|
||||
|
||||
if (! $result['ok']) {
|
||||
return response()->json(['success' => false, 'message' => $result['message']], $result['code']);
|
||||
}
|
||||
|
||||
return response()->json(['success' => true, 'message' => $result['message'], 'data' => $result['data']]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\Api\Order;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class CheckServerNameRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'name.required' => 'Tên server không được để trống.',
|
||||
'name.string' => 'Tên server không hợp lệ.',
|
||||
'name.max' => 'Tên server tối đa 255 ký tự.',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\Api\Order;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class RenewServiceRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'months' => ['required', 'integer', 'min:1', 'max:24'],
|
||||
];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'months.required' => 'Vui lòng chọn số tháng gia hạn.',
|
||||
'months.integer' => 'Số tháng gia hạn không hợp lệ.',
|
||||
'months.min' => 'Số tháng gia hạn tối thiểu là 1.',
|
||||
'months.max' => 'Số tháng gia hạn tối đa là 24.',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources\Api\Service\Order;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class InvoiceDetailResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'invoice_number' => $this->invoice_number,
|
||||
'invoice_type' => $this->invoice_type,
|
||||
'status' => $this->status,
|
||||
'status_text' => InvoiceStatus::tryFrom((int) $this->status)?->label() ?? '-',
|
||||
'sub_total' => (float) $this->sub_total,
|
||||
'discount_amount' => (float) ($this->discount_amount ?? 0),
|
||||
'tax' => (float) $this->tax,
|
||||
'total' => (float) $this->total,
|
||||
'payment_method' => $this->payment_method,
|
||||
'auto_renew' => (bool) $this->auto_renew,
|
||||
'created_at' => $this->created_at?->toISOString(),
|
||||
'due_date' => $this->due_date?->toISOString(),
|
||||
'paid_at' => $this->paid_at?->toISOString(),
|
||||
'customer' => $this->whenLoaded('customer', fn () => [
|
||||
'id' => $this->customer->id,
|
||||
'name' => $this->customer->fullname,
|
||||
'email' => $this->customer->email,
|
||||
'address' => $this->customer->address,
|
||||
]),
|
||||
'order' => $this->whenLoaded('order', fn () => [
|
||||
'id' => $this->order->id,
|
||||
'order_num' => $this->order->order_num,
|
||||
'total' => (float) $this->order->total,
|
||||
]),
|
||||
'items' => $this->whenLoaded('order', fn () => $this->order->orderItems->map(fn ($item) => [
|
||||
'id' => $item->id,
|
||||
'product_name' => $item->product?->name,
|
||||
'server_name' => $item->server_name,
|
||||
'billing_cycle' => $item->billing_cycle,
|
||||
'price' => (float) $item->price,
|
||||
'months' => $item->months,
|
||||
'os_id' => $item->os_id,
|
||||
])->values()->all()),
|
||||
'attachments' => $this->whenLoaded('attachments', fn () => $this->attachments->map(fn ($a) => [
|
||||
'id' => $a->id,
|
||||
'filename' => $a->filename,
|
||||
'url' => $a->url,
|
||||
'mime_type' => $a->mime_type,
|
||||
])->all()),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources\Api\Service\Order;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class InvoiceSummaryResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'invoice_number' => $this->invoice_number,
|
||||
'service_name' => $this->order?->orderItems->first()?->product?->name ?? ('Đơn hàng ' . $this->order?->order_num),
|
||||
'total' => (float) $this->total,
|
||||
'status' => $this->status,
|
||||
'status_text' => InvoiceStatus::tryFrom((int) $this->status)?->label() ?? '-',
|
||||
'created_at' => $this->created_at?->toISOString(),
|
||||
'order_id' => $this->order?->id,
|
||||
'order_num' => $this->order?->order_num,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources\Api\Service\Order;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Enums\Order\OrderStatus;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class OrderDetailResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'order_num' => $this->order_num,
|
||||
'status' => $this->status,
|
||||
'status_text' => OrderStatus::from((int) $this->status)->label(),
|
||||
'total' => (float) $this->total,
|
||||
'created_at' => $this->created_at?->toISOString(),
|
||||
'customer' => $this->whenLoaded('customer', fn () => [
|
||||
'id' => $this->customer->id,
|
||||
'name' => $this->customer->fullname,
|
||||
'email' => $this->customer->email,
|
||||
]),
|
||||
'invoice' => $this->whenLoaded('invoice', fn () => [
|
||||
'id' => $this->invoice->id,
|
||||
'invoice_number' => $this->invoice->invoice_number,
|
||||
'status' => $this->invoice->status,
|
||||
'status_text' => InvoiceStatus::tryFrom((int) $this->invoice->status)?->label() ?? '-',
|
||||
'sub_total' => (float) $this->invoice->sub_total,
|
||||
'tax' => (float) $this->invoice->tax,
|
||||
'total' => (float) $this->invoice->total,
|
||||
'due_date' => $this->invoice->due_date?->toISOString(),
|
||||
'paid_at' => $this->invoice->paid_at?->toISOString(),
|
||||
]),
|
||||
'items' => $this->whenLoaded('orderItems') ? OrderItemResource::collection($this->orderItems) : [],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources\Api\Service\Order;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class OrderItemResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'billing_cycle' => $this->billing_cycle,
|
||||
'months' => $this->months,
|
||||
'server_name' => $this->server_name,
|
||||
'os_id' => $this->os_id,
|
||||
'price' => (float) $this->price,
|
||||
'service' => $this->whenLoaded('service', fn () => [
|
||||
'id' => $this->service->id,
|
||||
'status' => $this->service->status,
|
||||
'status_text' => $this->service->status_label,
|
||||
'retry_requested_at' => $this->service->retry_requested_at?->toISOString(),
|
||||
'can_retry_provisioning' => $this->service->status === 'pending' && ! $this->service->retry_requested_at,
|
||||
]),
|
||||
'product' => $this->whenLoaded('product', fn () => [
|
||||
'id' => $this->product->id,
|
||||
'uuid' => $this->product->uuid,
|
||||
'name' => $this->product->name,
|
||||
'product_type' => $this->product->product_type,
|
||||
'specs' => [
|
||||
'cpu' => $this->product->cpu,
|
||||
'ram' => $this->product->ram,
|
||||
'disk' => $this->product->disk,
|
||||
'bandwidth' => $this->product->bandwidth,
|
||||
],
|
||||
]),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources\Api\Service\Order;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Enums\Order\OrderStatus;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class OrderSummaryResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'order_num' => $this->order_num,
|
||||
'status' => $this->status,
|
||||
'status_text' => OrderStatus::from((int) $this->status)->label(),
|
||||
'total' => (float) $this->total,
|
||||
'created_at' => $this->created_at?->toISOString(),
|
||||
'invoice' => $this->whenLoaded('invoice', fn () => [
|
||||
'id' => $this->invoice->id,
|
||||
'invoice_number' => $this->invoice->invoice_number,
|
||||
'status' => $this->invoice->status,
|
||||
'status_text' => InvoiceStatus::tryFrom((int) $this->invoice->status)?->label() ?? '-',
|
||||
'total' => (float) $this->invoice->total,
|
||||
]),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources\Api\Service\Order;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class ServiceDetailResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'uuid' => $this->uuid,
|
||||
'service_name' => $this->product?->name ?? $this->server_name,
|
||||
'server_name' => $this->server_name,
|
||||
'product_type' => $this->product?->product_type,
|
||||
'billing_cycle' => $this->orderItem?->billing_cycle,
|
||||
'status' => $this->status,
|
||||
'status_text' => $this->status_label,
|
||||
'auto_renew' => (bool) $this->auto_renew,
|
||||
'started_at' => $this->started_at?->toISOString(),
|
||||
'expires_at' => $this->expires_at?->toISOString(),
|
||||
'note' => $this->note,
|
||||
'invoice_id' => $this->invoice_id,
|
||||
'invoice_number' => $this->invoice?->invoice_number,
|
||||
'product' => $this->whenLoaded('product', fn () => [
|
||||
'id' => $this->product->id,
|
||||
'uuid' => $this->product->uuid,
|
||||
'name' => $this->product->name,
|
||||
'product_type' => $this->product->product_type,
|
||||
'specs' => [
|
||||
'cpu' => $this->product->cpu,
|
||||
'ram' => $this->product->ram,
|
||||
'disk' => $this->product->disk,
|
||||
'bandwidth' => $this->product->bandwidth,
|
||||
],
|
||||
]),
|
||||
'addons' => $this->whenLoaded('addons', fn () => $this->addons->map(fn ($a) => [
|
||||
'type' => $a->addon_type,
|
||||
'value' => $a->addon_value,
|
||||
'price' => $a->price,
|
||||
])->all()),
|
||||
'vmware' => $this->whenLoaded('vmware', fn () => $this->vmware ? [
|
||||
'id' => $this->vmware->id,
|
||||
'name' => $this->vmware->name,
|
||||
'hostname' => $this->vmware->hostname,
|
||||
'ip_address' => $this->vmware->ipAddress?->ip,
|
||||
'os_name' => $this->vmware->os?->name,
|
||||
'status' => $this->vmware->status,
|
||||
'next_due_date' => $this->vmware->next_due_date?->toISOString(),
|
||||
] : null),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources\Api\Service\Order;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class ServiceSummaryResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'uuid' => $this->uuid,
|
||||
'service_name' => $this->product?->name ?? $this->server_name,
|
||||
'server_name' => $this->server_name,
|
||||
'product_type' => $this->product?->product_type,
|
||||
'billing_cycle' => $this->orderItem?->billing_cycle,
|
||||
'status' => $this->status,
|
||||
'status_text' => $this->status_label,
|
||||
'auto_renew' => (bool) $this->auto_renew,
|
||||
'started_at' => $this->started_at?->toISOString(),
|
||||
'expires_at' => $this->expires_at?->toISOString(),
|
||||
'invoice_id' => $this->invoice_id,
|
||||
'invoice_number' => $this->invoice?->invoice_number,
|
||||
'addons' => $this->whenLoaded('addons', fn () => $this->addons->map(fn ($a) => [
|
||||
'type' => $a->addon_type,
|
||||
'value' => $a->addon_value,
|
||||
'price' => $a->price,
|
||||
])->all()),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -40,21 +40,20 @@ class SyncNetwork implements ShouldQueue
|
||||
{
|
||||
|
||||
foreach ($this->data as $item) {
|
||||
$this->vCenter->apiUri = $item->host;
|
||||
|
||||
if (!$item->token) {
|
||||
$token = $this->vCenter->loginServer($item);
|
||||
if ($token) {
|
||||
vCenter::where('id', $item->id)->update(['token' => $token]);
|
||||
$this->vCenter->token = $token;
|
||||
$item->token = $token;
|
||||
}
|
||||
}
|
||||
$this->vCenter->token = $item->token;
|
||||
|
||||
if (! $this->vCenter->token) {
|
||||
if (! $item->token) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->vCenter->setConnection($item->host, $item->token);
|
||||
|
||||
$dataCenter = ModuleDatacenter::where('vcenter_id', $item->id)->select('id', 'datacenter_id')->get();
|
||||
foreach ($dataCenter as $_item) {
|
||||
$allHost = ModuleHost::where('module_datacenter_id', $_item->id)
|
||||
|
||||
@@ -33,6 +33,7 @@ class ModuleVmware extends Model
|
||||
'ip',
|
||||
'dns',
|
||||
'plain_password',
|
||||
'virtual_machine_id',
|
||||
];
|
||||
|
||||
// NOTE: password must NOT use 'hashed' cast — it is a VM guest credential
|
||||
|
||||
@@ -25,13 +25,9 @@ class OrderRepository extends BaseApiRepository implements OrderRepositoryInterf
|
||||
$addons = $data['addons'] ?? [];
|
||||
unset($data['addons']);
|
||||
|
||||
return OrderItem::create(array_merge(
|
||||
['order_id' => $orderId],
|
||||
$data,
|
||||
// Preserve addon selections as JSON; read again at provisioning time
|
||||
// to build service_addons records.
|
||||
['addons_meta' => !empty($addons) ? $addons : null],
|
||||
));
|
||||
return OrderItem::create(
|
||||
array_merge(['order_id' => $orderId], $data, ['addons_meta' => !empty($addons) ? $addons : null]),
|
||||
);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -41,15 +37,15 @@ class OrderRepository extends BaseApiRepository implements OrderRepositoryInterf
|
||||
public function processPayment(Order $order, string $method): Order
|
||||
{
|
||||
$order->update([
|
||||
'status' => OrderStatus::ACTIVE->value,
|
||||
'status' => OrderStatus::ACTIVE->value,
|
||||
'payment_method' => $method,
|
||||
]);
|
||||
|
||||
if ($order->invoice) {
|
||||
$order->invoice->update([
|
||||
'status' => InvoiceStatus::PAID->value,
|
||||
'status' => InvoiceStatus::PAID->value,
|
||||
'payment_method' => $method,
|
||||
'paid_at' => now(),
|
||||
'paid_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -62,10 +58,7 @@ class OrderRepository extends BaseApiRepository implements OrderRepositoryInterf
|
||||
|
||||
public function hasPendingOrder(int $customerId): bool
|
||||
{
|
||||
return $this->model
|
||||
->where('customer_id', $customerId)
|
||||
->where('status', OrderStatus::PENDING->value)
|
||||
->exists();
|
||||
return $this->model->where('customer_id', $customerId)->where('status', OrderStatus::PENDING->value)->exists();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Api\Order;
|
||||
|
||||
use App\DTOs\Order\ClientOrderFilters;
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Enums\Order\OrderStatus;
|
||||
use App\Helpers\OrderHelper;
|
||||
use App\Jobs\VirtualMachine\Action\VMJobs;
|
||||
use App\Jobs\VirtualMachine\Provision\RetryProvisioningOrchestrator;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Models\Order;
|
||||
use App\Models\OrderItem;
|
||||
use App\Models\Service;
|
||||
use App\Models\VirtualMachines;
|
||||
use App\Repositories\Api\Order\OrderRepository;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class OrderQueryService
|
||||
{
|
||||
public function __construct(private readonly OrderRepository $orderRepository)
|
||||
{
|
||||
}
|
||||
|
||||
public function getOrdersForCustomer(int $customerId, ClientOrderFilters $filters): LengthAwarePaginator
|
||||
{
|
||||
return $this->orderRepository->getOrders($customerId, $filters->toArray());
|
||||
}
|
||||
|
||||
public function checkServerName(string $name): array
|
||||
{
|
||||
$exists = OrderItem::where('server_name', $name)->exists()
|
||||
|| Service::where('server_name', $name)->exists()
|
||||
|| ModuleVmware::where('name', $name)->exists()
|
||||
|| ModuleVmware::where('hostname', $name)->exists()
|
||||
|| VirtualMachines::where('name', $name)->exists();
|
||||
|
||||
return [
|
||||
'available' => ! $exists,
|
||||
'message' => $exists
|
||||
? 'Tên server này đã được sử dụng, vui lòng chọn tên khác.'
|
||||
: null,
|
||||
];
|
||||
}
|
||||
|
||||
public function findCustomerOrder(int $customerId, int $id): ?Order
|
||||
{
|
||||
return Order::query()
|
||||
->with(['invoice', 'orderItems.product', 'orderItems.service', 'customer'])
|
||||
->where('customer_id', $customerId)
|
||||
->where('id', $id)
|
||||
->first();
|
||||
}
|
||||
|
||||
public function getCustomerInvoices(int $customerId)
|
||||
{
|
||||
return Invoice::query()
|
||||
->with(['order.orderItems.product'])
|
||||
->where('customer_id', $customerId)
|
||||
->orderByDesc('created_at')
|
||||
->get();
|
||||
}
|
||||
|
||||
public function findCustomerInvoice(int $customerId, int $id): ?Invoice
|
||||
{
|
||||
return Invoice::query()
|
||||
->with([
|
||||
'order.orderItems.product',
|
||||
'order.vmWare.ipAddress',
|
||||
'order.vmWare.os',
|
||||
'customer',
|
||||
'attachments',
|
||||
])
|
||||
->where('customer_id', $customerId)
|
||||
->where('id', $id)
|
||||
->first();
|
||||
}
|
||||
|
||||
public function findCustomerInvoiceByOrderNum(int $customerId, string $orderNumber): ?Order
|
||||
{
|
||||
return Order::query()
|
||||
->with([
|
||||
'invoice.invoiceItems',
|
||||
'invoice.attachments',
|
||||
'invoice.customer',
|
||||
'orderItems.product',
|
||||
'customer',
|
||||
'vmWare.ipAddress',
|
||||
'vmWare.os',
|
||||
])
|
||||
->where('customer_id', $customerId)
|
||||
->where('order_num', $orderNumber)
|
||||
->first();
|
||||
}
|
||||
|
||||
public function getCustomerServices(int $customerId)
|
||||
{
|
||||
return Service::query()
|
||||
->with(['product', 'addons', 'invoice', 'orderItem', 'vmware.ipAddress', 'vmware.os'])
|
||||
->where('customer_id', $customerId)
|
||||
->orderByDesc('created_at')
|
||||
->get();
|
||||
}
|
||||
|
||||
public function findCustomerService(int $customerId, string $uuid): ?Service
|
||||
{
|
||||
return Service::query()
|
||||
->with(['product', 'addons', 'invoice', 'orderItem', 'vmware.ipAddress', 'vmware.os', 'vmware.vCenter'])
|
||||
->where('uuid', $uuid)
|
||||
->where('customer_id', $customerId)
|
||||
->first();
|
||||
}
|
||||
|
||||
public function canRetryProvisioning(Service $service): bool
|
||||
{
|
||||
if ($service->status !== 'pending' || $service->retry_requested_at) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$paidAt = $service->invoice?->paid_at;
|
||||
|
||||
return $paidAt ? Carbon::parse($paidAt)->diffInMinutes(now()) >= 180 : false;
|
||||
}
|
||||
|
||||
public function retryProvisioning(Order $order, int $customerId): array
|
||||
{
|
||||
$order = Order::where('id', $order->id)
|
||||
->with(['invoice', 'orderItems.service'])
|
||||
->where('customer_id', $customerId)
|
||||
->first();
|
||||
|
||||
if (! $order) {
|
||||
return ['ok' => false, 'message' => 'Đơn hàng không tồn tại.', 'code' => 404];
|
||||
}
|
||||
|
||||
if (! $order->invoice || (int) $order->invoice->status !== InvoiceStatus::PAID->value) {
|
||||
return ['ok' => false, 'message' => 'Đơn hàng chưa được thanh toán.', 'code' => 400];
|
||||
}
|
||||
|
||||
$paidAt = $order->invoice->paid_at ? Carbon::parse($order->invoice->paid_at) : null;
|
||||
if (! $paidAt || $paidAt->diffInMinutes(now()) < 180) {
|
||||
return ['ok' => false, 'message' => 'Vui lòng chờ khoảng 3 tiếng sau khi thanh toán mới có thể khởi tạo lại dịch vụ.', 'code' => 400];
|
||||
}
|
||||
|
||||
$service = $order->orderItems->first()?->service;
|
||||
if (! $service || (int) $service->customer_id !== $customerId) {
|
||||
return ['ok' => false, 'message' => 'Không tìm thấy dịch vụ hợp lệ để khởi tạo lại.', 'code' => 400];
|
||||
}
|
||||
|
||||
if ($service->status !== 'pending') {
|
||||
return ['ok' => false, 'message' => 'Dịch vụ đã được khởi tạo hoặc không ở trạng thái chờ.', 'code' => 400];
|
||||
}
|
||||
|
||||
if ($service->retry_requested_at) {
|
||||
return ['ok' => false, 'message' => 'Dịch vụ đã được yêu cầu khởi tạo lại một lần. Vui lòng liên hệ kỹ thuật qua mailto:kythuat@tgs.com.vn', 'code' => 400];
|
||||
}
|
||||
|
||||
$service->update(['retry_requested_at' => now()]);
|
||||
RetryProvisioningOrchestrator::dispatch($order->id, $customerId);
|
||||
|
||||
return ['ok' => true, 'message' => 'Đã yêu cầu khởi tạo lại dịch vụ. Hệ thống sẽ kiểm tra và xử lý trong vài phút.'];
|
||||
}
|
||||
|
||||
public function renewService(int $serviceId, int $customerId, int $months): array
|
||||
{
|
||||
$customer = \App\Models\Customer::find($customerId);
|
||||
|
||||
$service = Service::query()
|
||||
->with(['orderItem.product'])
|
||||
->where('id', $serviceId)
|
||||
->where('customer_id', $customerId)
|
||||
->whereNotIn('status', ['terminated', 'cancelled'])
|
||||
->first();
|
||||
|
||||
if (! $service) {
|
||||
return ['ok' => false, 'message' => 'Không tìm thấy dịch vụ hoặc dịch vụ đã bị hủy.', 'code' => 404];
|
||||
}
|
||||
|
||||
$orderItem = $service->orderItem;
|
||||
if (! $orderItem || (int) $orderItem->price <= 0) {
|
||||
return ['ok' => false, 'message' => 'Không thể xác định giá gia hạn dịch vụ.', 'code' => 400];
|
||||
}
|
||||
|
||||
$price = (int) $orderItem->price * $months;
|
||||
|
||||
if ($customer->total < $price) {
|
||||
return ['ok' => false, 'message' => sprintf('Số dư không đủ. Hiện có: %s VNĐ, cần: %s VNĐ.', number_format($customer->total), number_format($price)), 'code' => 400];
|
||||
}
|
||||
|
||||
$needsVmStart = $service->vm_id !== null;
|
||||
|
||||
$invoice = DB::transaction(function () use ($customer, $service, $orderItem, $price, $months) {
|
||||
$customer->total -= $price;
|
||||
$customer->save();
|
||||
|
||||
\App\Models\Log::create([
|
||||
'agent' => 'api',
|
||||
'client_ip' => request()?->ip(),
|
||||
'customer_id' => $customer->id,
|
||||
'description' => sprintf('Gia hạn dịch vụ #%s. Số tiền: %s VNĐ. Số dư còn: %s VNĐ.', $service->server_name ?? $service->id, number_format($price), number_format($customer->total)),
|
||||
]);
|
||||
|
||||
$invoice = Invoice::create([
|
||||
'invoice_number' => OrderHelper::generateOrderNumber('INV'),
|
||||
'customer_id' => $customer->id,
|
||||
'order_id' => null,
|
||||
'invoice_type' => 2,
|
||||
'sub_total' => $price,
|
||||
'discount_amount' => 0,
|
||||
'tax' => 0,
|
||||
'total' => $price,
|
||||
'status' => InvoiceStatus::PAID->value,
|
||||
'paid_at' => now(),
|
||||
'payment_method' => 'credit',
|
||||
]);
|
||||
|
||||
\App\Models\InvoiceItem::create([
|
||||
'invoice_id' => $invoice->id,
|
||||
'product_id' => $service->product_id,
|
||||
'type' => 'renewal',
|
||||
'description' => 'Gia hạn dịch vụ: ' . ($orderItem->product?->name ?? $service->server_name ?? ''),
|
||||
'months' => $months,
|
||||
'quantity' => 1,
|
||||
'unit_price' => $price,
|
||||
'total_price' => $price,
|
||||
]);
|
||||
|
||||
$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,
|
||||
'invoice_id' => $invoice->id,
|
||||
]);
|
||||
|
||||
return $invoice;
|
||||
});
|
||||
|
||||
if ($needsVmStart) {
|
||||
dispatch(new VMJobs((int) $service->vm_id, 'Start', false))->delay(now()->addSeconds(5));
|
||||
}
|
||||
|
||||
return [
|
||||
'ok' => true,
|
||||
'message' => 'Gia hạn thành công. Dịch vụ đã được kích hoạt lại.',
|
||||
'data' => [
|
||||
'invoice_number' => $invoice->invoice_number,
|
||||
'total' => (float) $invoice->total,
|
||||
'expires_at' => $service->fresh()?->expires_at?->toISOString(),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Imports;
|
||||
|
||||
use App\Models\Customer;
|
||||
use App\Models\Service;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Sync customers + services + product mapping from legacy `portal` DB
|
||||
* (connection: `legacy`) into the current portal schema.
|
||||
*
|
||||
* Idempotent via `legacy_id` columns. Conflicting customers (existing email
|
||||
* or phone) are skipped — never overwritten.
|
||||
*/
|
||||
class LegacyPortalImporter
|
||||
{
|
||||
/** Default new-system product id used when no explicit mapping is given. */
|
||||
protected int $defaultVpsProductId = 1;
|
||||
|
||||
/** Map legacy product_id => new product_id. Built from CLI option / config. */
|
||||
protected array $productMap = [];
|
||||
|
||||
public function setProductMap(array $map): self
|
||||
{
|
||||
$this->productMap = $map;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setDefaultVpsProductId(int $id): self
|
||||
{
|
||||
$this->defaultVpsProductId = $id;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{customers: array, services: array, products: array}
|
||||
*/
|
||||
public function import(bool $preview = false, ?callable $log = null): array
|
||||
{
|
||||
$log ??= fn ($_msg) => null;
|
||||
|
||||
$summary = [
|
||||
'customers' => ['created' => 0, 'skipped_conflict' => 0, 'already_synced' => 0, 'errors' => 0],
|
||||
'vmware' => ['created' => 0, 'updated' => 0, 'vcenter_matched' => 0, 'vcenter_missing' => 0, 'errors' => 0],
|
||||
'services' => ['created' => 0, 'updated' => 0, 'skipped_no_customer' => 0, 'vm_linked' => 0, 'vm_unlinked' => 0, 'errors' => 0],
|
||||
'products' => ['mapped' => 0, 'fallback_default' => 0],
|
||||
];
|
||||
|
||||
$log("→ Connecting to legacy DB and counting rows...");
|
||||
$legacyUsers = DB::connection('legacy')->table('users')->count();
|
||||
$legacyServices = DB::connection('legacy')->table('services')->count();
|
||||
$legacyVmware = DB::connection('legacy')->table('vmware')->count();
|
||||
$log(" legacy.users = {$legacyUsers}, legacy.services = {$legacyServices}, legacy.vmware = {$legacyVmware}");
|
||||
|
||||
if ($preview) {
|
||||
$log("PREVIEW MODE — no writes will be performed.");
|
||||
}
|
||||
|
||||
// ----- Customers -----
|
||||
$log("→ Syncing customers...");
|
||||
$customerIdMap = []; // legacy user_id => new customer_id
|
||||
|
||||
DB::connection('legacy')->table('users')->orderBy('id')->chunk(200, function ($rows) use (&$summary, &$customerIdMap, $preview, $log) {
|
||||
foreach ($rows as $row) {
|
||||
try {
|
||||
$existingByLegacy = Customer::where('legacy_id', $row->id)->first();
|
||||
if ($existingByLegacy) {
|
||||
$customerIdMap[$row->id] = $existingByLegacy->id;
|
||||
$summary['customers']['already_synced']++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$email = trim((string) $row->email) ?: null;
|
||||
$phone = trim((string) ($row->sdt ?? '')) ?: null;
|
||||
|
||||
$conflict = Customer::query()
|
||||
->when($email, fn ($q) => $q->where('email', $email))
|
||||
->when($phone, fn ($q, $p) => $q->orWhere('phone', $p))
|
||||
->first();
|
||||
|
||||
if ($conflict) {
|
||||
$customerIdMap[$row->id] = $conflict->id;
|
||||
$summary['customers']['skipped_conflict']++;
|
||||
$log(" · skip user#{$row->id} ({$email}) — conflict with customer#{$conflict->id}");
|
||||
if (! $preview) {
|
||||
// Backfill legacy_id on existing record so future runs are idempotent.
|
||||
$conflict->forceFill(['legacy_id' => $row->id])->saveQuietly();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'legacy_id' => $row->id,
|
||||
'fullname' => $row->fullname,
|
||||
'avatar' => $row->thumb ?: null,
|
||||
'gender' => (int) ($row->gender ?? 0),
|
||||
'address' => $row->address,
|
||||
'company' => $row->company,
|
||||
'phone' => $phone,
|
||||
'email' => $email,
|
||||
'email_verify' => $row->email_verification,
|
||||
'password' => $row->password,
|
||||
'credit' => (int) ($row->price ?? 0),
|
||||
'total' => (int) ($row->total ?? 0),
|
||||
'identity_number' => $row->cccd,
|
||||
'front_identity_number' => $row->cccd_mattruoc,
|
||||
'back_identity_number' => $row->cccd_matsau,
|
||||
'status' => (int) ($row->is_active ?? 1),
|
||||
'created_at' => $row->create_at,
|
||||
'updated_at' => $row->update_at,
|
||||
];
|
||||
|
||||
if ($preview) {
|
||||
// sentinel so services chunk can resolve in dry-run
|
||||
$customerIdMap[$row->id] = -1;
|
||||
$summary['customers']['created']++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$customer = new Customer();
|
||||
$customer->uuid = (string) Str::uuid();
|
||||
$customer->forceFill($payload)->saveQuietly();
|
||||
|
||||
$customerIdMap[$row->id] = $customer->id;
|
||||
$summary['customers']['created']++;
|
||||
} catch (\Throwable $e) {
|
||||
$summary['customers']['errors']++;
|
||||
Log::warning("LegacyPortalImporter customer#{$row->id} failed", ['error' => $e->getMessage()]);
|
||||
$log(" ! user#{$row->id} ERROR: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (! $preview) {
|
||||
Customer::whereNotNull('legacy_id')->pluck('id', 'legacy_id')
|
||||
->each(fn ($newId, $legacyId) => $customerIdMap[$legacyId] = $newId);
|
||||
}
|
||||
|
||||
// ----- VMware (module_vmware) -----
|
||||
$log("→ Syncing vmware → module_vmware...");
|
||||
$vmwareIdMap = []; // legacy_vmware.id => new module_vmware.id
|
||||
|
||||
// Build vCenter inventory lookup: vmware_id string => virtual_machines.id
|
||||
$vcenterLookup = DB::table('virtual_machines')->pluck('id', 'vm_id');
|
||||
|
||||
DB::connection('legacy')->table('vmware')->orderBy('id')->chunk(200, function ($rows) use (&$summary, &$vmwareIdMap, $customerIdMap, $vcenterLookup, $preview, $log) {
|
||||
foreach ($rows as $row) {
|
||||
try {
|
||||
$newCustomerId = $customerIdMap[$row->user_id] ?? null;
|
||||
$vcVmId = $row->vmware_id; // e.g. "vm-4327"
|
||||
$vmInventoryId = $vcVmId ? ($vcenterLookup[$vcVmId] ?? null) : null;
|
||||
|
||||
if ($vmInventoryId) $summary['vmware']['vcenter_matched']++;
|
||||
else $summary['vmware']['vcenter_missing']++;
|
||||
|
||||
$payload = [
|
||||
'legacy_id' => $row->id,
|
||||
'customer_id' => $newCustomerId,
|
||||
'name' => $row->vmware_name,
|
||||
'ip' => $row->vmware_ip,
|
||||
'port' => is_numeric($row->vmware_port) ? (int) $row->vmware_port : null,
|
||||
'user' => $row->vmware_user,
|
||||
'password' => $row->vmware_password,
|
||||
'hostname' => $row->vmware_hostname,
|
||||
'vmware_id' => $vcVmId,
|
||||
'virtual_machine_id' => $vmInventoryId,
|
||||
'status' => (int) ($row->vmware_status ?? 1),
|
||||
'created_at' => $row->create_at,
|
||||
'updated_at' => $row->update_at,
|
||||
];
|
||||
|
||||
if ($preview) {
|
||||
$vmwareIdMap[$row->id] = -1;
|
||||
$summary['vmware']['created']++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$existing = DB::table('module_vmware')->where('legacy_id', $row->id)->first();
|
||||
if ($existing) {
|
||||
DB::table('module_vmware')->where('id', $existing->id)->update($payload);
|
||||
$vmwareIdMap[$row->id] = $existing->id;
|
||||
$summary['vmware']['updated']++;
|
||||
} else {
|
||||
$newId = DB::table('module_vmware')->insertGetId($payload);
|
||||
$vmwareIdMap[$row->id] = $newId;
|
||||
$summary['vmware']['created']++;
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$summary['vmware']['errors']++;
|
||||
Log::warning("LegacyPortalImporter vmware#{$row->id} failed", ['error' => $e->getMessage()]);
|
||||
$log(" ! vmware#{$row->id} ERROR: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (! $preview) {
|
||||
DB::table('module_vmware')->whereNotNull('legacy_id')->select('id', 'legacy_id')->get()
|
||||
->each(fn ($r) => $vmwareIdMap[$r->legacy_id] = $r->id);
|
||||
}
|
||||
|
||||
// ----- Services -----
|
||||
$log("→ Syncing services...");
|
||||
|
||||
DB::connection('legacy')->table('services')->orderBy('id')->chunk(200, function ($rows) use (&$summary, $customerIdMap, $vmwareIdMap, $preview, $log) {
|
||||
foreach ($rows as $row) {
|
||||
try {
|
||||
$newCustomerId = $customerIdMap[$row->user_id] ?? null;
|
||||
if (! $newCustomerId) {
|
||||
$summary['services']['skipped_no_customer']++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$productId = $this->resolveProductId((int) $row->product_id, $summary);
|
||||
$newVmId = $row->vmware_id !== null ? ($vmwareIdMap[$row->vmware_id] ?? null) : null;
|
||||
if ($newVmId) $summary['services']['vm_linked']++;
|
||||
else $summary['services']['vm_unlinked']++;
|
||||
|
||||
$payload = [
|
||||
'legacy_id' => $row->id,
|
||||
'customer_id' => $newCustomerId === -1 ? null : $newCustomerId,
|
||||
'product_id' => $productId,
|
||||
'legacy_product_id' => (int) $row->product_id,
|
||||
'vm_id' => $newVmId === -1 ? null : $newVmId,
|
||||
'status' => $this->mapStatus((int) $row->is_active),
|
||||
'auto_renew' => (bool) $row->auto_pay,
|
||||
'started_at' => $row->create_at,
|
||||
'expires_at' => $row->date_exp,
|
||||
'note' => 'product_info(legacy): ' . $row->product_info,
|
||||
'created_at' => $row->create_at,
|
||||
'updated_at' => $row->create_at,
|
||||
];
|
||||
|
||||
if ($preview) {
|
||||
$summary['services']['created']++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$service = Service::where('legacy_id', $row->id)->first();
|
||||
|
||||
if ($service) {
|
||||
$service->forceFill($payload)->saveQuietly();
|
||||
$summary['services']['updated']++;
|
||||
} else {
|
||||
$service = new Service();
|
||||
$service->uuid = (string) Str::uuid();
|
||||
$service->forceFill($payload)->saveQuietly();
|
||||
$summary['services']['created']++;
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$summary['services']['errors']++;
|
||||
Log::warning("LegacyPortalImporter service#{$row->id} failed", ['error' => $e->getMessage()]);
|
||||
$log(" ! service#{$row->id} ERROR: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
protected function resolveProductId(int $legacyProductId, array &$summary): int
|
||||
{
|
||||
if (isset($this->productMap[$legacyProductId])) {
|
||||
$summary['products']['mapped']++;
|
||||
return $this->productMap[$legacyProductId];
|
||||
}
|
||||
|
||||
$summary['products']['fallback_default']++;
|
||||
return $this->defaultVpsProductId;
|
||||
}
|
||||
|
||||
/** Convert legacy `is_active` int → new lifecycle string. */
|
||||
protected function mapStatus(int $legacy): string
|
||||
{
|
||||
return match ($legacy) {
|
||||
0 => 'expired',
|
||||
1 => 'active',
|
||||
2 => 'pending',
|
||||
3 => 'suspended',
|
||||
default => 'pending',
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user