update
This commit is contained in:
@@ -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([
|
||||
|
||||
Reference in New Issue
Block a user