This commit is contained in:
baodev0
2026-07-01 10:51:05 +07:00
parent 914e96138a
commit 3bb59feba3
43 changed files with 1680 additions and 28 deletions
@@ -26,6 +26,9 @@ use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use App\Enums\Invoice\InvoiceStatus;
use App\Enums\Order\OrderStatus;
use App\Helpers\OrderHelper;
class CustomerController extends Controller
{
@@ -292,6 +295,70 @@ class CustomerController extends Controller
}
}
/**
* Tạo mã impersonate một lần (one-time code) để admin đăng nhập hộ khách hàng
* vào giao diện portal-client. Trả về `code` (hiệu lực 120s) — portal-client
* sẽ đổi code lấy token qua endpoint public `v1/client/impersonate/exchange`.
*/
public function loginAs(Request $request, string $uuid): JsonResponse
{
$customer = $this->customerRepository->findBy('uuid', $uuid);
if (!$customer) {
return response()->json([
'error' => true,
'message' => "Can't find customer by UUID #" . $uuid,
], 404);
}
if ((int) $customer->status !== 1) {
return response()->json([
'error' => true,
'message' => 'Khách hàng không hoạt động, không thể đăng nhập hộ.',
], 422);
}
try {
$token = \Tymon\JWTAuth\Facades\JWTAuth::fromUser($customer);
$refreshToken = app(\App\Services\Api\Client\ClientAuthService::class)
->createRefreshToken($customer->id);
$clientResource = (new \App\Http\Resources\Api\Client\ClientResource(
$customer->loadCount(['vps', 'hosting', 'domain'])
))->resolve($request);
$code = Str::random(48);
\Illuminate\Support\Facades\Cache::put("impersonate:{$code}", [
'token' => $token,
'refresh_token' => $refreshToken,
'client' => $clientResource,
], 120);
$admin = Auth::guard('admin')->user();
Log::create([
'agent' => 'admin',
'client_ip' => $request->ip(),
'description' => sprintf(
'%s đăng nhập hộ khách hàng %s',
$admin->username ?? $admin->email ?? 'Admin',
$customer->email,
),
'customer_id' => $customer->id,
]);
return response()->json([
'error' => false,
'data' => ['code' => $code],
]);
} catch (\Throwable $e) {
return response()->json([
'error' => true,
'message' => $e->getMessage(),
], 500);
}
}
public function resetPassword(Request $request, string $uuid): JsonResponse
{
$customer = $this->customerRepository->findBy('uuid', $uuid);
@@ -709,6 +776,85 @@ class CustomerController extends Controller
]);
}
/**
* Xoá nhiều dịch vụ của khách hàng. Chỉ xoá bản ghi trong bảng `services`,
* không xoá VM (module_vmware / virtual_machines) liên kết.
*/
public function bulkDeleteServices(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([
'ids' => 'required|array|min:1',
'ids.*' => 'integer',
]);
$deleted = \App\Models\Service::where('customer_id', $customer->id)
->whereIn('id', $data['ids'])
->delete();
return response()->json([
'error' => false,
'message' => 'Đã xoá ' . $deleted . ' dịch vụ',
'data' => ['deleted' => $deleted],
]);
}
/**
* Cập nhật thông tin dịch vụ của khách hàng (server_name/hostname, status, ngày,...).
* Đồng bộ hostname sang module_vmware nếu service đã gắn VM.
*/
public function updateService(string $uuid, int $serviceId, Request $request): JsonResponse
{
$customer = $this->customerRepository->findBy('uuid', $uuid);
if (!$customer) {
return response()->json(['error' => true, 'message' => "Can't find customer"], 404);
}
$service = \App\Models\Service::where('customer_id', $customer->id)
->where('id', $serviceId)
->first();
if (!$service) {
return response()->json(['error' => true, 'message' => 'Không tìm thấy dịch vụ'], 404);
}
$data = $request->validate([
'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',
]);
try {
DB::beginTransaction();
$service->fill($data);
$service->save();
// Đồng bộ hostname sang module_vmware nếu có gán VM
if ($service->vm_id && array_key_exists('server_name', $data)) {
\App\Models\ModuleVmware::where('id', $service->vm_id)
->update(['hostname' => $data['server_name']]);
}
DB::commit();
return response()->json([
'error' => false,
'message' => 'Cập nhật dịch vụ thành công',
'data' => $service->load(['product', 'orderItem', 'invoice']),
]);
} catch (\Throwable $e) {
DB::rollBack();
return response()->json(['error' => true, 'message' => $e->getMessage()], 500);
}
}
/**
* Create a service for a customer. For VPS products, accepts a
* `virtual_machine_id` from the vCenter inventory and auto-creates the
@@ -730,9 +876,14 @@ class CustomerController extends Controller
'started_at' => 'nullable|date',
'expires_at' => 'nullable|date',
'note' => 'nullable|string',
// New: billing & payment
'billing_cycle' => 'nullable|in:monthly,quarterly,semi_annually,annually,biennially,triennially',
'payment_method' => 'required|in:transfer,balance',
'proof_images' => 'nullable|array',
'proof_images.*' => 'file|image|max:5120',
]);
$product = \App\Models\Product::find($data['product_id']);
$product = \App\Models\Product::with('pricings')->find($data['product_id']);
if ($product->product_type === 'vps' && empty($data['virtual_machine_id'])) {
return response()->json([
'error' => true,
@@ -740,35 +891,164 @@ class CustomerController extends Controller
], 422);
}
$billingCycle = $data['billing_cycle'] ?? 'monthly';
$months = $this->cycleToMonths($billingCycle);
$pricing = $product->pricings
->where('billing_cycle', $billingCycle)
->first();
$basePrice = (int) ($pricing->price ?? 0);
$paymentMethod = $data['payment_method'];
// Đối với balance: kiểm tra số dư trước khi vào transaction
if ($paymentMethod === 'balance' && (int) $customer->total < $basePrice) {
return response()->json([
'error' => true,
'message' => sprintf(
'Số dư khách không đủ. Hiện có: %s VNĐ, cần: %s VNĐ.',
number_format((int) $customer->total),
number_format($basePrice)
),
], 422);
}
// Upload proof images (chuyển khoản)
$proofPaths = [];
if ($paymentMethod === 'transfer' && $request->hasFile('proof_images')) {
foreach ($request->file('proof_images') as $file) {
$proofPaths[] = $file->store('payment-proofs', 'public');
}
}
try {
DB::beginTransaction();
// 1) ModuleVmware: snapshot từ virtual_machines
$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,
]);
$vm = \App\Models\VirtualMachines::with('datacenter')
->find($data['virtual_machine_id']);
$vcenterId = $vm->datacenter->vcenter_id ?? null;
$moduleVm = \App\Models\ModuleVmware::updateOrCreate(
['virtual_machine_id' => $vm->id],
[
'customer_id' => $customer->id,
'name' => $vm->name,
'vmware_id' => $vm->vm_id,
'vcenter_id' => $vcenterId,
'hostname' => $data['server_name'] ?? $vm->name,
'cpu' => $vm->cpu,
'ram_mb' => $vm->ram_mb,
'disk_gb' => $vm->disk_gb ?? null,
'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,
// 2) Order + OrderItem (mô phỏng flow customer đặt hàng)
$order = Order::create([
'order_num' => OrderHelper::generateOrderNumber(),
'customer_id' => $customer->id,
'sub_total' => $basePrice,
'discount_amount' => 0,
'total' => $basePrice,
'status' => OrderStatus::ACTIVE->value,
'payment_method' => $paymentMethod,
'client_ip' => $request->ip(),
]);
$orderItem = \App\Models\OrderItem::create([
'order_id' => $order->id,
'product_id' => $product->id,
'billing_cycle' => $billingCycle,
'months' => $months,
'server_name' => $data['server_name'] ?? null,
'quantity' => 1,
'price' => $basePrice,
]);
// 3) Invoice — đánh dấu PAID luôn vì admin đứng ra tạo & xác nhận thanh toán
$invoice = Invoice::create([
'invoice_number' => OrderHelper::generateOrderNumber('INV'),
'customer_id' => $customer->id,
'order_id' => $order->id,
'invoice_type' => 1,
'sub_total' => $basePrice,
'discount_amount' => 0,
'tax' => 0,
'total' => $basePrice,
'status' => InvoiceStatus::PAID->value,
'payment_method' => $paymentMethod,
'paid_at' => now(),
'due_date' => now()->addMonths($months)->toDateString(),
]);
\App\Models\InvoiceItem::create([
'invoice_id' => $invoice->id,
'product_id' => $product->id,
'type' => 'service',
'description' => $product->name ?? 'Dịch vụ',
'months' => $months,
'quantity' => 1,
'unit_price' => $basePrice,
'total_price' => $basePrice,
]);
// 4) Payment processing
if ($paymentMethod === 'balance') {
$customer->total = (int) $customer->total - $basePrice;
$customer->save();
}
Transaction::create([
'uuid' => (string) Str::uuid(),
'customer_id' => $customer->id,
'user_id' => Auth::id(),
'trans' => $order->order_num,
'amount' => $basePrice,
'type' => $paymentMethod === 'transfer' ? 'transfer' : 'balance',
'status' => 1, // paid
'note' => $paymentMethod === 'transfer'
? 'Admin tạo dịch vụ - thanh toán chuyển khoản'
: 'Admin tạo dịch vụ - trừ số dư khách hàng',
'proof_image' => !empty($proofPaths) ? json_encode($proofPaths) : null,
]);
// 5) Service — updateOrCreate để tránh trùng khi cùng VM được gán lại
$startedAt = $data['started_at'] ?? now();
$expiresAt = $data['expires_at']
?? \Carbon\Carbon::parse($startedAt)->addMonths($months);
$serviceLookup = $vmId
? ['customer_id' => $customer->id, 'vm_id' => $vmId]
: [
'customer_id' => $customer->id,
'product_id' => $product->id,
'vm_id' => null,
'server_name' => $data['server_name'] ?? null,
];
$service = \App\Models\Service::updateOrCreate(
$serviceLookup,
[
'customer_id' => $customer->id,
'product_id' => $product->id,
'vm_id' => $vmId,
'order_item_id' => $orderItem->id,
'invoice_id' => $invoice->id,
'server_name' => $data['server_name'] ?? null,
'status' => $data['status'] ?? 'active',
'auto_renew' => (bool) ($data['auto_renew'] ?? false),
'started_at' => $startedAt,
'expires_at' => $expiresAt,
'note' => $data['note'] ?? null,
]
);
DB::commit();
return response()->json([
'error' => false,
@@ -843,4 +1123,17 @@ class CustomerController extends Controller
'data' => $orders
]);
}
private function cycleToMonths(?string $cycle): int
{
return match ($cycle) {
'monthly' => 1,
'quarterly' => 3,
'semi_annually' => 6,
'annually' => 12,
'biennially' => 24,
'triennially' => 36,
default => 1,
};
}
}
@@ -309,6 +309,37 @@ class ClientController extends Controller
}
}
/**
* Đổi mã impersonate (do admin cấp) lấy access token + refresh token.
* Endpoint public — code chỉ dùng được 1 lần và hết hạn sau 120s.
*/
public function impersonateExchange(Request $request)
{
$request->validate([
'code' => ['required', 'string', 'max:128'],
]);
$code = (string) $request->input('code');
$payload = \Illuminate\Support\Facades\Cache::pull("impersonate:{$code}");
if (!$payload) {
return response()->json([
'error' => true,
'message' => 'Mã đăng nhập không hợp lệ hoặc đã hết hạn.',
], 401);
}
return response()->json([
'error' => false,
'data' => [
'token' => $payload['token'],
'refresh_token' => $payload['refresh_token'],
'client' => $payload['client'],
'expires_in' => config('jwt.ttl', 60) * 60,
],
]);
}
public function forgotPassword(Request $request)
{
$request->validate([
@@ -17,7 +17,7 @@ class VpsServiceResource extends JsonResource
$orderItem = $this->orderItem;
$invoice = $this->invoice;
$order = $orderItem?->order ?? $invoice?->order;
$product = $orderItem?->product;
$product = $orderItem?->product ?? $this->product;
return [
'id' => $this->id,
@@ -46,6 +46,8 @@ class SyncVirtualMachine implements ShouldQueue
$vCenterCount = 0;
$vmTotalCount = 0;
$totalDeletedCount = 0;
foreach ($data as $item) {
Log::info("Processing vCenter: {$item->host}");
$this->vCenter->apiUri = $item->host;
@@ -65,24 +67,27 @@ class SyncVirtualMachine implements ShouldQueue
continue;
}
$syncedVmIds = [];
$fetchFailed = false;
$datacenters = ModuleDatacenter::where('vcenter_id', $item->id)->get();
if ($datacenters->count() > 0) {
foreach ($datacenters as $dc) {
// Get all hosts for this datacenter
$hosts = ModuleHost::where('module_datacenter_id', $dc->id)->get();
if ($hosts->count() > 0) {
foreach ($hosts as $host) {
Log::info("Fetching VMs for host: {$host->host_id} in datacenter: {$dc->name}");
$vms = $this->vCenter->getAllVirtualMachine($dc->datacenter_id, $host->host_id);
$vmCount = $this->processVMs($vms, $item, $dc->id, $host->id);
$vmCount = $this->processVMs($vms, $item, $dc->id, $host->id, $syncedVmIds, $fetchFailed);
$vmTotalCount += $vmCount;
}
} else {
// Fallback: Sync VMs by datacenter only
Log::info("No hosts found for datacenter {$dc->name}, fetching VMs by datacenter only");
$vms = $this->vCenter->getAllVirtualMachine($dc->datacenter_id);
$vmCount = $this->processVMs($vms, $item, $dc->id, null);
$vmCount = $this->processVMs($vms, $item, $dc->id, null, $syncedVmIds, $fetchFailed);
$vmTotalCount += $vmCount;
}
}
@@ -90,10 +95,20 @@ class SyncVirtualMachine implements ShouldQueue
// Fallback: Sync all VMs without datacenter context
Log::info("No datacenters found, fetching all VMs for {$item->host}");
$vms = $this->vCenter->getAllVirtualMachine();
$vmCount = $this->processVMs($vms, $item, null, null);
$vmCount = $this->processVMs($vms, $item, null, null, $syncedVmIds, $fetchFailed);
$vmTotalCount += $vmCount;
}
// Cleanup stale VMs in DB that no longer exist on vCenter.
// Only run when all fetches succeeded to avoid wiping data on transient failures.
if (!$fetchFailed) {
$datacenterIds = $datacenters->pluck('id')->all();
$deletedCount = $this->cleanupStaleVMs($datacenterIds, $syncedVmIds, $item);
$totalDeletedCount += $deletedCount;
} else {
Log::warning("Skip cleanup for vCenter {$item->host} because some VM fetches failed.");
}
$vCenterCount++; // Increment vCenter synced count
}
@@ -102,6 +117,7 @@ class SyncVirtualMachine implements ShouldQueue
'message' => 'Sync VMs completed successfully',
'synced_vcenter_count' => $vCenterCount,
'synced_vm_count' => $vmTotalCount,
'deleted_vm_count' => $totalDeletedCount,
]);
} catch (Throwable $e) {
@@ -117,7 +133,7 @@ class SyncVirtualMachine implements ShouldQueue
}
}
private function processVMs($vms, $vCenterItem, $datacenterId, $hostId)
private function processVMs($vms, $vCenterItem, $datacenterId, $hostId, array &$syncedVmIds, bool &$fetchFailed)
{
// If token expired, retry login (handled inside loop in previous logic, but simpler here if we just handle the array check)
if ($vms === 'Login_Again') {
@@ -139,6 +155,7 @@ class SyncVirtualMachine implements ShouldQueue
if (!is_array($vms)) {
Log::warning("Failed to fetch VMs or empty response. Response: " . json_encode($vms));
$fetchFailed = true;
return 0;
}
@@ -161,8 +178,48 @@ class SyncVirtualMachine implements ShouldQueue
$vmObj->last_synced_at = now();
$vmObj->save();
$syncedVmIds[] = $vmData['vm'];
$count++;
}
return $count;
}
/**
* Delete VMs in DB that belong to the given vCenter but no longer exist on vCenter.
*/
private function cleanupStaleVMs(array $datacenterIds, array $syncedVmIds, $vCenterItem): int
{
$syncedVmIds = array_values(array_unique($syncedVmIds));
if (!empty($datacenterIds)) {
$query = VirtualMachines::whereIn('datacenter_id', $datacenterIds);
} else {
// No datacenter context: fallback - chỉ xoá khi đã sync được ít nhất 1 VM
// để tránh xoá nhầm khi vCenter rỗng do lỗi.
if (empty($syncedVmIds)) {
Log::warning("Skip cleanup for {$vCenterItem->host}: no datacenters and no synced VMs.");
return 0;
}
$query = VirtualMachines::query();
}
if (!empty($syncedVmIds)) {
$query->whereNotIn('vm_id', $syncedVmIds);
}
$staleVms = $query->get(['id', 'vm_id', 'name']);
if ($staleVms->isEmpty()) {
return 0;
}
foreach ($staleVms as $stale) {
Log::info("Deleting stale VM removed from vCenter {$vCenterItem->host}: {$stale->name} ({$stale->vm_id})");
}
$deleted = VirtualMachines::whereIn('id', $staleVms->pluck('id')->all())->delete();
Log::info("Cleanup vCenter {$vCenterItem->host}: deleted {$deleted} stale VM(s).");
return (int) $deleted;
}
}
+3
View File
@@ -34,6 +34,9 @@ class ModuleVmware extends Model
'dns',
'plain_password',
'virtual_machine_id',
'cpu',
'ram_mb',
'disk_gb',
];
// NOTE: password must NOT use 'hashed' cast — it is a VM guest credential
@@ -19,6 +19,7 @@ class ServiceClientRepository extends BaseApiRepository implements ServiceClient
{
$query = $this->model
->with([
'product',
'invoice.order',
'orderItem' => fn($q) => $q->with(['product', 'os.osGroup', 'order']),
])
@@ -27,7 +28,7 @@ class ServiceClientRepository extends BaseApiRepository implements ServiceClient
->orderBy('started_at', 'desc');
if ($productType) {
$query->whereHas('orderItem.product', function ($builder) use ($productType) {
$query->whereHas('product', function ($builder) use ($productType) {
$builder->where('product_type', $productType);
});
}