feat: Add IT Support catalog and related migrations, seeders, and email templates
- Created migration to add 'group_label' to 'product_type_fields' table. - Implemented ItSupportCatalogSeeder to populate IT Support features and tiers. - Added ProductCategorySeeder for initial product categories. - Developed ProductMockupSeeder for mockup products in various categories. - Introduced ProductTypeFieldSeeder to define fields for different product types. - Created email templates for VPS service information and service renewal reminders.
This commit is contained in:
@@ -12,6 +12,9 @@ enum ProductTypeEnums: string
|
||||
case DOMAIN = 'domain';
|
||||
case WEB_DESIGN = 'web design';
|
||||
case ADDON = 'addon';
|
||||
case HARDWARE = 'hardware';
|
||||
case IT_SUPPORT = 'it_support';
|
||||
case SERVER_RENTAL = 'server_rental';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
@@ -24,6 +27,9 @@ enum ProductTypeEnums: string
|
||||
self::DOMAIN => 'Domain',
|
||||
self::WEB_DESIGN => 'Web Design',
|
||||
self::ADDON => 'Addon',
|
||||
self::HARDWARE => 'Hardware',
|
||||
self::IT_SUPPORT => 'IT Support',
|
||||
self::SERVER_RENTAL => 'Thuê máy chủ',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -38,6 +44,9 @@ enum ProductTypeEnums: string
|
||||
self::DOMAIN => 'purple',
|
||||
self::WEB_DESIGN => 'pink',
|
||||
self::ADDON => 'orange',
|
||||
self::HARDWARE => 'volcano',
|
||||
self::IT_SUPPORT => 'geekblue',
|
||||
self::SERVER_RENTAL => 'magenta',
|
||||
};
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,37 +6,17 @@ use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\OrderRequest;
|
||||
use App\Http\Requests\UpdateOrderRequest;
|
||||
use App\Http\Resources\Api\Admin\OrderResource;
|
||||
use App\Jobs\Hosting\CreateHostingJobs;
|
||||
use App\Jobs\VirtualMachine\Create\CreateVMJobs;
|
||||
use App\Jobs\VirtualMachine\Upgrade\UpgradeVirtualMachine;
|
||||
use App\Models\Order;
|
||||
use App\Repositories\Addon\AddonRepositoryInterface;
|
||||
use App\Repositories\Invoice\InvoiceRepositoryInterface;
|
||||
use App\Repositories\InvoiceItem\InvoiceItemRepositoryInterface;
|
||||
use App\Repositories\Module\Hosting\HostingRepositoryInterface as ModuleHostingRepositoryInterface;
|
||||
use App\Repositories\Module\HostingServer\HostingServerRepositoryInterface;
|
||||
use App\Repositories\Module\IpAddress\IpAddressRepositoryInterface;
|
||||
use App\Repositories\Module\Vmware\VmwareRepositoryInterface;
|
||||
use App\Repositories\Order\OrderRepositoryInterface;
|
||||
use App\Repositories\Os\OsRepositoryInterface;
|
||||
use App\Services\OrderService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class OrderController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly OrderRepositoryInterface $orderRepository,
|
||||
private readonly InvoiceRepositoryInterface $invoiceRepository,
|
||||
private readonly InvoiceItemRepositoryInterface $invoiceItemRepository,
|
||||
private readonly ModuleHostingRepositoryInterface $moduleHostingRepository,
|
||||
private readonly VmwareRepositoryInterface $moduleVmwareRepository,
|
||||
private readonly HostingServerRepositoryInterface $moduleHostingServerRepository,
|
||||
private readonly OsRepositoryInterface $osRepository,
|
||||
private readonly IpAddressRepositoryInterface $ipAddressRepository,
|
||||
private readonly AddonRepositoryInterface $addonRepository,
|
||||
private readonly OrderService $orderService,
|
||||
) {}
|
||||
|
||||
@@ -83,12 +63,7 @@ class OrderController extends Controller
|
||||
{
|
||||
$order = $this->orderRepository->findByOrderNum($order_num);
|
||||
|
||||
if (!$order) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => "Can't find order by ID #" . $order_num,
|
||||
], 404);
|
||||
}
|
||||
abort_if(!$order, 404, "Can't find order by ID #{$order_num}");
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
@@ -100,173 +75,48 @@ class OrderController extends Controller
|
||||
{
|
||||
$order = $this->orderRepository->findWithRelationships($id, ['invoice', 'orderItem']);
|
||||
|
||||
if (!$order) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => "Can't find order by ID #" . $id,
|
||||
], 404);
|
||||
}
|
||||
abort_if(!$order, 404, "Can't find order by ID #{$id}");
|
||||
|
||||
$status = match ($request->action) {
|
||||
"accept" => 1,
|
||||
"cancel" => 2,
|
||||
default => 0
|
||||
match ($request->action) {
|
||||
'accept' => $this->orderService->confirmOrder($order, (bool) $request->module),
|
||||
'cancel' => $this->orderService->setStatus($order, 2),
|
||||
default => $this->orderService->setStatus($order, 0),
|
||||
};
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
$this->orderRepository->update($id, ['status' => $status]);
|
||||
|
||||
if ($status === 1 && $request->module == 1) {
|
||||
$jobs = [];
|
||||
$addon = [];
|
||||
$product = 0;
|
||||
|
||||
foreach ($order->orderItem as $key => $item) {
|
||||
switch ((int) $item->type_id) {
|
||||
case 1:
|
||||
$itemData = $this->addonRepository->find($item->relid);
|
||||
if ($itemData) {
|
||||
$price = match ((int) $item->billing) {
|
||||
2 => $item->amount / 1,
|
||||
3 => $item->amount / 3,
|
||||
4 => $item->amount / 6,
|
||||
5 => $item->amount / 12,
|
||||
default => 0
|
||||
};
|
||||
$addon[strtolower($itemData->name)] = (int) $price / $itemData->price;
|
||||
$product = $item->parent_id;
|
||||
}
|
||||
break;
|
||||
case 3:
|
||||
$hostingServer = $this->moduleHostingServerRepository->get_active();
|
||||
if ($hostingServer) {
|
||||
$this->moduleHostingRepository->update($item->relid, ['module_server_id' => $hostingServer->first()->id]);
|
||||
$jobs[] = new CreateHostingJobs($item->relid);
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
$product = $this->moduleVmwareRepository->find($item->relid);
|
||||
|
||||
if ($product && $product->os_id) {
|
||||
$os = $this->osRepository->findWithRelationships($product->os_id, ['osGroup']);
|
||||
if (!$os || !$os->osGroup->isNotEmpty()) break;
|
||||
|
||||
$ip_address = $this->ipAddressRepository->filter([
|
||||
'module_host_id' => $os->osGroup->module_host_id,
|
||||
'status' => 0,
|
||||
]);
|
||||
|
||||
if (count($ip_address) > 0) {
|
||||
$this->moduleVmwareRepository->update($item->relid, [
|
||||
'module_ipaddress_id' => $ip_address->first()->id,
|
||||
]);
|
||||
$this->ipAddressRepository->update($ip_address->first()->id, ['status' => 1]);
|
||||
$jobs[] = new CreateVMJobs($product->id);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (count($order->orderItem) === count($addon)) {
|
||||
dispatch(new UpgradeVirtualMachine($product, $addon, $order->id))->delay(now()->addSeconds(10));
|
||||
}
|
||||
|
||||
foreach ($jobs as $item) {
|
||||
dispatch($item)->delay(now()->addSeconds(10));
|
||||
}
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'Order updated successfully']);
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
return response()->json(['error' => true, 'message' => $e->getMessage()], 500);
|
||||
}
|
||||
return response()->json(['error' => false, 'message' => 'Order updated successfully']);
|
||||
}
|
||||
|
||||
public function destroy(int $id): JsonResponse
|
||||
{
|
||||
$order = Order::with('Invoice', 'Invoice.InvoiceItem')->find($id);
|
||||
$order = Order::with('invoice', 'invoice.invoiceItem')->find($id);
|
||||
|
||||
if (!$order) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => "Can't find order by ID #" . $id,
|
||||
], 404);
|
||||
}
|
||||
abort_if(!$order, 404, "Can't find order by ID #{$id}");
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
$this->orderService->deleteOrder($order);
|
||||
|
||||
if ($order->Invoice) {
|
||||
$order->Invoice->delete();
|
||||
|
||||
if ($order->Invoice->InvoiceItem->count()) {
|
||||
foreach ($order->Invoice->InvoiceItem->all() as $item) {
|
||||
$item->delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$order->delete();
|
||||
|
||||
DB::commit();
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'Order deleted successfully']);
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
return response()->json(['error' => true, 'message' => $e->getMessage()], 500);
|
||||
}
|
||||
return response()->json(['error' => false, 'message' => 'Order deleted successfully']);
|
||||
}
|
||||
|
||||
public function accept(int $id): JsonResponse
|
||||
{
|
||||
$order = $this->orderRepository->findWithRelationships($id, ['invoice', 'orderItem']);
|
||||
$order = $this->orderRepository->find($id);
|
||||
|
||||
if (!$order) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => "Can't find order by ID #" . $id,
|
||||
], 404);
|
||||
}
|
||||
abort_if(!$order, 404, "Can't find order by ID #{$id}");
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
$this->orderRepository->update($id, ['status' => 1]);
|
||||
DB::commit();
|
||||
$this->orderService->setStatus($order, 1);
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'Order accepted successfully']);
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
return response()->json(['error' => true, 'message' => $e->getMessage()], 500);
|
||||
}
|
||||
return response()->json(['error' => false, 'message' => 'Order accepted successfully']);
|
||||
}
|
||||
|
||||
public function cancel(int $id): JsonResponse
|
||||
{
|
||||
$order = $this->orderRepository->find($id);
|
||||
|
||||
if (!$order) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => "Can't find order by ID #" . $id,
|
||||
], 404);
|
||||
}
|
||||
abort_if(!$order, 404, "Can't find order by ID #{$id}");
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
$this->orderRepository->update($id, ['status' => 2]);
|
||||
DB::commit();
|
||||
$this->orderService->setStatus($order, 2);
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'Order cancelled successfully']);
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
return response()->json(['error' => true, 'message' => $e->getMessage()], 500);
|
||||
}
|
||||
return response()->json(['error' => false, 'message' => 'Order cancelled successfully']);
|
||||
}
|
||||
|
||||
public function uploadProof(Request $request): JsonResponse
|
||||
|
||||
@@ -72,6 +72,7 @@ class ProductController extends Controller
|
||||
'ram' => 'nullable|numeric|min:0',
|
||||
'disk' => 'nullable|numeric|min:0',
|
||||
'bandwidth' => 'nullable|numeric|min:0',
|
||||
'domain_count' => 'nullable|integer|min:0',
|
||||
'billing_type' => 'nullable|string|in:recurring,onetime',
|
||||
'currency' => 'nullable|string|max:10',
|
||||
'price_monthly' => 'nullable|numeric|min:0',
|
||||
@@ -81,6 +82,7 @@ class ProductController extends Controller
|
||||
'price_biennially' => 'nullable|numeric|min:0',
|
||||
'price_triennially' => 'nullable|numeric|min:0',
|
||||
'price_onetime' => 'nullable|numeric|min:0',
|
||||
'features' => 'nullable|array',
|
||||
]);
|
||||
|
||||
$productType = $validated['product_type'] ?? null;
|
||||
@@ -103,6 +105,8 @@ class ProductController extends Controller
|
||||
'ram' => $validated['ram'] ?? null,
|
||||
'disk' => $validated['disk'] ?? null,
|
||||
'bandwidth' => $validated['bandwidth'] ?? null,
|
||||
'domain_count' => $validated['domain_count'] ?? null,
|
||||
'features' => $validated['features'] ?? null,
|
||||
]);
|
||||
|
||||
$this->savePricings($product, $validated);
|
||||
@@ -135,6 +139,7 @@ class ProductController extends Controller
|
||||
'ram' => 'nullable|numeric|min:0',
|
||||
'disk' => 'nullable|numeric|min:0',
|
||||
'bandwidth' => 'nullable|numeric|min:0',
|
||||
'domain_count' => 'nullable|integer|min:0',
|
||||
'os_ids' => 'nullable|array',
|
||||
'os_ids.*' => 'integer|exists:os,id',
|
||||
'module_host_id' => 'nullable|integer|exists:module_host,id',
|
||||
@@ -148,6 +153,7 @@ class ProductController extends Controller
|
||||
'price_biennially' => 'nullable|numeric|min:0',
|
||||
'price_triennially' => 'nullable|numeric|min:0',
|
||||
'price_onetime' => 'nullable|numeric|min:0',
|
||||
'features' => 'nullable|array',
|
||||
]);
|
||||
|
||||
if (isset($validated['name']) && $validated['name'] !== $product->name) {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin\Product;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\ProductTypeField\ProductTypeFieldRequest;
|
||||
use App\Http\Resources\Api\Admin\ProductTypeFieldResource;
|
||||
use App\Models\ProductTypeField;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ProductTypeFieldController extends Controller
|
||||
{
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$items = ProductTypeField::query()
|
||||
->when($request->get('product_type'), fn ($q, $type) => $q->where('product_type', $type))
|
||||
->orderBy('sort_order')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => ProductTypeFieldResource::collection($items),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(ProductTypeFieldRequest $request): JsonResponse
|
||||
{
|
||||
$field = ProductTypeField::create($request->validated());
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'message' => 'Tạo field thành công.',
|
||||
'data' => new ProductTypeFieldResource($field),
|
||||
], 201);
|
||||
}
|
||||
|
||||
public function update(ProductTypeFieldRequest $request, int $id): JsonResponse
|
||||
{
|
||||
$field = ProductTypeField::find($id);
|
||||
|
||||
if (!$field) {
|
||||
return response()->json(['error' => true, 'message' => 'Không tìm thấy field.'], 404);
|
||||
}
|
||||
|
||||
$field->update($request->validated());
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'message' => 'Cập nhật field thành công.',
|
||||
'data' => new ProductTypeFieldResource($field),
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy(int $id): JsonResponse
|
||||
{
|
||||
$field = ProductTypeField::find($id);
|
||||
|
||||
if (!$field) {
|
||||
return response()->json(['error' => true, 'message' => 'Không tìm thấy field.'], 404);
|
||||
}
|
||||
|
||||
$field->delete();
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'message' => 'Xoá field thành công.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace App\Http\Controllers\Api\Admin\Service;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Jobs\VirtualMachine\Provision\ResendVmCredentialsEmailJob;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Models\Service;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -34,9 +36,11 @@ class ServiceController extends Controller
|
||||
|
||||
public function show(int $id): JsonResponse
|
||||
{
|
||||
$service = Service::with(['customer', 'product', 'orderItem', 'invoice', 'vmware', 'addons'])
|
||||
$service = Service::with(['customer', 'product', 'orderItem', 'invoice', 'vmware.os.osGroup', 'addons'])
|
||||
->findOrFail($id);
|
||||
|
||||
ModuleVmware::resolveVirtualMachineIds([$service->vmware]);
|
||||
|
||||
return response()->json(['error' => false, 'data' => $service]);
|
||||
}
|
||||
|
||||
@@ -47,4 +51,15 @@ class ServiceController extends Controller
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'Đã gỡ khách hàng khỏi dịch vụ.']);
|
||||
}
|
||||
|
||||
public function resendCredentials(int $id): JsonResponse
|
||||
{
|
||||
$service = Service::findOrFail($id);
|
||||
|
||||
abort_if(!$service->vm_id, 422, 'Dịch vụ chưa gắn VM.');
|
||||
|
||||
ResendVmCredentialsEmailJob::dispatch($service->vm_id);
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'Đã xếp hàng gửi lại thông tin VPS cho khách hàng.']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,10 +12,7 @@ use App\Http\Resources\Api\Client\ClientResource;
|
||||
use App\Services\ActivityLogger;
|
||||
use App\Services\Api\Client\ClientAuthService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Tymon\JWTAuth\Facades\JWTAuth;
|
||||
use Tymon\JWTAuth\Exceptions\JWTException;
|
||||
|
||||
/**
|
||||
* @OA\Tag(
|
||||
@@ -390,80 +387,37 @@ class ClientController extends Controller
|
||||
'email' => ['required', 'email', 'max:255'],
|
||||
]);
|
||||
|
||||
$email = strtolower(trim((string) $request->input('email')));
|
||||
|
||||
$customer = \App\Models\Customer::whereRaw('LOWER(email) = ?', [$email])->first();
|
||||
|
||||
if (! $customer) {
|
||||
// Do not disclose whether the email exists.
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'message' => 'Nếu email tồn tại, mật khẩu mới đã được gửi đến hộp thư của bạn.',
|
||||
]);
|
||||
}
|
||||
|
||||
$alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*';
|
||||
$newPassword = '';
|
||||
$max = strlen($alphabet) - 1;
|
||||
for ($i = 0; $i < 16; $i++) {
|
||||
$newPassword .= $alphabet[random_int(0, $max)];
|
||||
}
|
||||
|
||||
try {
|
||||
\Illuminate\Support\Facades\DB::beginTransaction();
|
||||
|
||||
$customer->password = Hash::make($newPassword);
|
||||
$customer->save();
|
||||
|
||||
\Illuminate\Support\Facades\Mail::to($customer->email)->later(
|
||||
now()->addSeconds(5),
|
||||
new \App\Mail\Customer\PasswordResetByAdmin([
|
||||
'fullname' => $customer->fullname,
|
||||
'email' => $customer->email,
|
||||
'password' => $newPassword,
|
||||
])
|
||||
);
|
||||
$customer = $this->authService->resetForgottenPassword($request->input('email'));
|
||||
|
||||
if ($customer) {
|
||||
$this->activityLogger->log(
|
||||
event: 'password_forgot',
|
||||
logName: 'Customer',
|
||||
description: "Customer {$customer->email} yêu cầu cấp lại mật khẩu",
|
||||
subject: $customer,
|
||||
);
|
||||
|
||||
\Illuminate\Support\Facades\DB::commit();
|
||||
} catch (\Throwable) {
|
||||
\Illuminate\Support\Facades\DB::rollBack();
|
||||
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'Không thể gửi email, vui lòng thử lại sau.',
|
||||
], 500);
|
||||
}
|
||||
|
||||
// Do not disclose whether the email exists.
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'message' => 'Mật khẩu mới đã được gửi đến email của bạn.',
|
||||
'message' => 'Nếu email tồn tại, mật khẩu mới đã được gửi đến hộp thư của bạn.',
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(ClientUpdateRequest $request)
|
||||
{
|
||||
$user = auth('client')->user();
|
||||
$result = $this->authService->updateProfile(auth('client')->user(), $request->validated());
|
||||
$user = $result['client'];
|
||||
|
||||
$oldValues = array_intersect_key($user->toArray(), $request->validated());
|
||||
$user->fill($request->validated());
|
||||
$dirty = $user->getDirty();
|
||||
$user->save();
|
||||
|
||||
if (!empty($dirty)) {
|
||||
if (!empty($result['dirty'])) {
|
||||
$this->activityLogger->log(
|
||||
event: 'profile_update',
|
||||
logName: 'Customer',
|
||||
description: "Customer {$user->email} cập nhật thông tin cá nhân: " . implode(', ', array_keys($dirty)),
|
||||
description: "Customer {$user->email} cập nhật thông tin cá nhân: " . implode(', ', array_keys($result['dirty'])),
|
||||
subject: $user,
|
||||
oldValues: array_intersect_key($oldValues, $dirty),
|
||||
newValues: array_diff_key($dirty, array_flip(['password', 'remember_token'])),
|
||||
oldValues: $result['old'],
|
||||
newValues: array_diff_key($result['dirty'], array_flip(['password', 'remember_token'])),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -478,29 +432,25 @@ class ClientController extends Controller
|
||||
|
||||
public function updateCccd(ClientUpdateCccdRequest $request)
|
||||
{
|
||||
$user = auth('client')->user();
|
||||
$frontUrl = Storage::disk('public')->url($request->file('cmnd_before')->store('cccd', 'public'));
|
||||
$backUrl = Storage::disk('public')->url($request->file('cmnd_after')->store('cccd', 'public'));
|
||||
|
||||
$oldValues = array_intersect_key($user->toArray(), $request->validated());
|
||||
|
||||
$user->identity_number = $request->validated('cmnd');
|
||||
$user->front_identity_number = Storage::disk('public')->url(
|
||||
$request->file('cmnd_before')->store('cccd', 'public')
|
||||
);
|
||||
$user->back_identity_number = Storage::disk('public')->url(
|
||||
$request->file('cmnd_after')->store('cccd', 'public')
|
||||
$result = $this->authService->updateCccd(
|
||||
auth('client')->user(),
|
||||
$request->validated('cmnd'),
|
||||
$frontUrl,
|
||||
$backUrl,
|
||||
);
|
||||
$user = $result['client'];
|
||||
|
||||
$dirty = $user->getDirty();
|
||||
$user->save();
|
||||
|
||||
if (!empty($dirty)) {
|
||||
if (!empty($result['dirty'])) {
|
||||
$this->activityLogger->log(
|
||||
event: 'cccd_update',
|
||||
logName: 'Customer',
|
||||
description: "Customer {$user->email} cập nhật chứng minh thư",
|
||||
subject: $user,
|
||||
oldValues: array_intersect_key($oldValues, $dirty),
|
||||
newValues: $dirty,
|
||||
oldValues: $result['old'],
|
||||
newValues: $result['dirty'],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -517,16 +467,19 @@ class ClientController extends Controller
|
||||
{
|
||||
$user = auth('client')->user();
|
||||
|
||||
if (!Hash::check($request->input('current_password'), $user->password)) {
|
||||
try {
|
||||
$this->authService->changePassword(
|
||||
$user,
|
||||
$request->input('current_password'),
|
||||
$request->input('password'),
|
||||
);
|
||||
} catch (\Illuminate\Validation\ValidationException $e) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'Mật khẩu hiện tại không chính xác',
|
||||
'message' => collect($e->errors())->flatten()->first(),
|
||||
], 422);
|
||||
}
|
||||
|
||||
$user->password = bcrypt($request->input('password'));
|
||||
$user->save();
|
||||
|
||||
$this->activityLogger->log(
|
||||
event: 'password_change',
|
||||
logName: 'Customer',
|
||||
|
||||
@@ -7,6 +7,7 @@ use Illuminate\Http\JsonResponse;
|
||||
use Laravel\Horizon\Contracts\JobRepository;
|
||||
use Laravel\Horizon\Contracts\MetricsRepository;
|
||||
use Laravel\Horizon\Contracts\WorkloadRepository;
|
||||
use Laravel\Horizon\Jobs\RetryFailedJob;
|
||||
|
||||
class QueueMonitorController extends Controller
|
||||
{
|
||||
@@ -70,6 +71,19 @@ class QueueMonitorController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/queue/jobs/failed/{id}/retry
|
||||
* Re-queue a failed job by its Horizon job ID.
|
||||
*/
|
||||
public function retry(string $id): JsonResponse
|
||||
{
|
||||
abort_if(!$this->jobs->findFailed($id), 404, "Can't find failed job #{$id}");
|
||||
|
||||
dispatch(new RetryFailedJob($id));
|
||||
|
||||
return response()->json(['success' => true, 'message' => 'Job đã được đưa lại vào hàng đợi']);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/queue/jobs/metrics
|
||||
* Queue throughput, runtime, and per-queue/per-job breakdown.
|
||||
|
||||
@@ -442,6 +442,19 @@ class VCenterManagerController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
public function powerState(Request $request)
|
||||
{
|
||||
$vmId = (int) $request->input('vm_id');
|
||||
|
||||
$vm = VirtualMachines::find($vmId);
|
||||
|
||||
if (!$vm) {
|
||||
return response()->json(['error' => true, 'message' => 'VM not found'], 404);
|
||||
}
|
||||
|
||||
return response()->json(['error' => false, 'data' => ['power_state' => $vm->power_state]]);
|
||||
}
|
||||
|
||||
public function powerOn(Request $request)
|
||||
{
|
||||
$vmId = (int) $request->input('vm_id');
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\ProductTypeField;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class ProductTypeFieldRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
$sometimes = $this->isMethod('put') || $this->isMethod('patch') ? 'sometimes|' : '';
|
||||
|
||||
return [
|
||||
'product_type' => $sometimes . 'required|string|max:50',
|
||||
'group_label' => 'nullable|string|max:255',
|
||||
'key' => $sometimes . 'required|string|max:255',
|
||||
'label' => $sometimes . 'required|string|max:255',
|
||||
'field_type' => $sometimes . 'required|string|in:text,number,textarea,repeater',
|
||||
'sort_order' => 'nullable|integer',
|
||||
'is_required' => 'boolean',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,8 @@ class ProductResource extends JsonResource
|
||||
'ram' => $this->ram,
|
||||
'disk' => $this->disk,
|
||||
'bandwidth' => $this->bandwidth,
|
||||
'domain_count' => $this->domain_count,
|
||||
'features' => $this->features,
|
||||
'setup_fee' => $this->setup_fee,
|
||||
'min_price' => $minPrice,
|
||||
'billing_type' => $this->whenLoaded('pricings', function () {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources\Api\Admin;
|
||||
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class ProductTypeFieldResource extends JsonResource
|
||||
{
|
||||
public function toArray($request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'product_type' => $this->product_type,
|
||||
'group_label' => $this->group_label,
|
||||
'key' => $this->key,
|
||||
'label' => $this->label,
|
||||
'field_type' => $this->field_type,
|
||||
'sort_order' => $this->sort_order,
|
||||
'is_required' => $this->is_required,
|
||||
'created_at' => $this->created_at,
|
||||
'updated_at' => $this->updated_at,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,8 @@
|
||||
namespace App\Jobs\Mail;
|
||||
|
||||
use App\Http\Services\Telegram;
|
||||
use App\Mail\CreateVirtualMachine;
|
||||
use App\Mail\VmCredentialsMail;
|
||||
use App\Models\EmailNotificationTemplate;
|
||||
use App\Mail\VmInfoMail;
|
||||
use App\Models\Invoice;
|
||||
use App\Services\EmailNotificationTemplateRenderer;
|
||||
use App\Services\InvoicePdfService;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Bus\Queueable;
|
||||
@@ -59,17 +56,7 @@ class SendInformationVirtualMachine implements ShouldQueue
|
||||
}
|
||||
}
|
||||
|
||||
// Try block-based DB template first
|
||||
$dbTemplate = EmailNotificationTemplate::where('type', 'vm_credentials')
|
||||
->where('is_active', true)
|
||||
->first();
|
||||
|
||||
if ($dbTemplate) {
|
||||
$email = new VmCredentialsMail($dbTemplate, $this->data, $invoice, $invoicePdf, $invoicePdfFileName);
|
||||
} else {
|
||||
// Fallback: legacy Template model (ID=2)
|
||||
$email = new CreateVirtualMachine(2, $this->data, $invoicePdf, $invoicePdfFileName);
|
||||
}
|
||||
$email = new VmInfoMail($this->data, $invoicePdf, $invoicePdfFileName);
|
||||
|
||||
Mail::to($this->customer->email)->send($email);
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Jobs\VirtualMachine\Provision;
|
||||
|
||||
use App\Http\Services\Telegram;
|
||||
use App\Jobs\Mail\SendInformationVirtualMachine;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Services\VirtualMachine\VmCredentialsEmailDataBuilder;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Admin-triggered resend of the VPS credentials email — same email as
|
||||
* SendVmCredentialsEmailJob, but without re-running service/VM activation
|
||||
* or the admin "new order" notification.
|
||||
*/
|
||||
class ResendVmCredentialsEmailJob implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
public int $tries = 3;
|
||||
public int $timeout = 60;
|
||||
|
||||
public function __construct(
|
||||
public readonly int $moduleVmwareId,
|
||||
) {}
|
||||
|
||||
public function handle(Telegram $telegram): void
|
||||
{
|
||||
$vm = ModuleVmware::with([
|
||||
'customer',
|
||||
'os.osGroup',
|
||||
'order.orderItems.service',
|
||||
])->find($this->moduleVmwareId);
|
||||
|
||||
if (!$vm) {
|
||||
$msg = "ResendVmCredentialsEmailJob: ModuleVmware #{$this->moduleVmwareId} not found";
|
||||
Log::error($msg);
|
||||
$telegram->SendErrorMessage($msg);
|
||||
return;
|
||||
}
|
||||
|
||||
$customer = $vm->customer;
|
||||
|
||||
if (!$customer?->email) {
|
||||
$msg = "ResendVmCredentialsEmailJob: customer or email missing for ModuleVmware #{$this->moduleVmwareId}";
|
||||
Log::error($msg, ['module_vmware_id' => $this->moduleVmwareId]);
|
||||
$telegram->SendErrorMessage($msg);
|
||||
return;
|
||||
}
|
||||
|
||||
$orderItem = $vm->order?->orderItems?->first();
|
||||
$emailData = app(VmCredentialsEmailDataBuilder::class)->build($vm, $orderItem);
|
||||
|
||||
$invoice = Invoice::where('order_id', $vm->order_id)->first();
|
||||
|
||||
SendInformationVirtualMachine::dispatch($emailData, $customer, $invoice?->id);
|
||||
|
||||
Log::info('ResendVmCredentialsEmailJob: email dispatched', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'customer_email' => $customer->email,
|
||||
]);
|
||||
}
|
||||
|
||||
public function failed(\Throwable $e): void
|
||||
{
|
||||
Log::error('ResendVmCredentialsEmailJob: failed', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use App\Jobs\Mail\SendInformationVirtualMachine;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Models\Service;
|
||||
use App\Models\Setting;
|
||||
use App\Services\VirtualMachine\VmCredentialsEmailDataBuilder;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
@@ -72,30 +72,8 @@ class SendVmCredentialsEmailJob implements ShouldQueue
|
||||
|
||||
// ── [3] Build email payload ───────────────────────────────────────────
|
||||
|
||||
$setting = Setting::where('key', 'setting')->first();
|
||||
$settingValue = $setting ? json_decode((string) $setting->value) : null;
|
||||
|
||||
$months = (int) ($orderItem?->months ?? 0);
|
||||
$osGroupName = $vm->os?->osGroup?->name ?? '';
|
||||
$isWindows = str_contains(strtolower($osGroupName), 'windows');
|
||||
$osUsername = $isWindows ? 'Administrator' : 'root';
|
||||
|
||||
$emailData = $this->safeUtf8([
|
||||
'company_name' => $settingValue->company ?? 'Thế Giới Số',
|
||||
'company_logo' => $settingValue->logo ?? '',
|
||||
'client_name' => $customer->fullname ?? '',
|
||||
'product_name' => $orderItem?->getProductAttribute()?->name ?? 'Cloud VPS',
|
||||
'product_billing' => $this->billingLabel($months),
|
||||
'product_price' => $orderItem ? number_format((float) $orderItem->price, 0, ',', '.') : 'N/A',
|
||||
'service_host' => $vm->ip ?? 'N/A',
|
||||
'service_username' => $osUsername,
|
||||
'service_port' => (string) ($vm->port ?? '22'),
|
||||
'service_password' => $vm->plain_password ?? '(xem tai khoan quan ly)',
|
||||
'os_name' => $vm->os ? ($osGroupName . ' ' . $vm->os->version) : 'Unknown OS',
|
||||
'service_due_exp' => $vm->next_due_date
|
||||
? date('d/m/Y', (int) $vm->next_due_date)
|
||||
: 'N/A',
|
||||
]);
|
||||
$months = (int) ($orderItem?->months ?? 0);
|
||||
$emailData = app(VmCredentialsEmailDataBuilder::class)->build($vm, $orderItem);
|
||||
|
||||
// PDF is generated inside the mail job — never pass binary blobs through queue payload
|
||||
$invoice = Invoice::where('order_id', $vm->order_id)->first();
|
||||
@@ -123,7 +101,7 @@ class SendVmCredentialsEmailJob implements ShouldQueue
|
||||
'total' => $orderItem?->price ?? 0,
|
||||
'created_at' => $order?->created_at?->format('d/m/Y H:i:s') ?? now()->format('d/m/Y H:i:s'),
|
||||
'ip' => $vm->ip ?? '',
|
||||
'username' => $osUsername,
|
||||
'username' => $emailData['service_username'],
|
||||
'password' => $vm->plain_password ?? '',
|
||||
]);
|
||||
|
||||
@@ -204,26 +182,4 @@ class SendVmCredentialsEmailJob implements ShouldQueue
|
||||
default => ($months ?? 0) . ' Thang',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize tất cả string trong array thành UTF-8 hợp lệ.
|
||||
* Loại bỏ ký tự binary/invalid trước khi đẩy vào queue (tránh JSON encode lỗi).
|
||||
*/
|
||||
private function safeUtf8(array $data): array
|
||||
{
|
||||
return array_map(function ($value) {
|
||||
if (!is_string($value)) return $value;
|
||||
|
||||
// Nếu đã là UTF-8 hợp lệ → giữ nguyên
|
||||
if (mb_check_encoding($value, 'UTF-8')) return $value;
|
||||
|
||||
// Thử convert từ encoding khác sang UTF-8
|
||||
$converted = mb_convert_encoding($value, 'UTF-8', mb_detect_encoding($value, ['UTF-8', 'ISO-8859-1', 'Windows-1252'], true) ?: 'ISO-8859-1');
|
||||
|
||||
// Nếu vẫn invalid → strip ký tự lỗi
|
||||
return mb_check_encoding($converted, 'UTF-8')
|
||||
? $converted
|
||||
: preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]|[^\x09\x0A\x0D\x20-\x{10FFFF}]/u', '', $value);
|
||||
}, $data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\Customer;
|
||||
use App\Models\Service;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
class ServiceRenewalReminderMail extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(
|
||||
public readonly Customer $customer,
|
||||
public readonly Service $service,
|
||||
) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
$name = $this->service->server_name ?? $this->service->product?->name ?? 'dịch vụ';
|
||||
|
||||
return new Envelope(subject: "Nhắc gia hạn dịch vụ {$name}");
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
view: 'emails.customer.service-renewal-reminder',
|
||||
with: [
|
||||
'clientName' => $this->customer->fullname ?? '',
|
||||
'productName' => $this->service->product?->name ?? 'Dịch vụ',
|
||||
'serverName' => $this->service->server_name ?? '',
|
||||
'expiresAt' => $this->service->expires_at
|
||||
? \Carbon\Carbon::parse($this->service->expires_at)->format('d/m/Y')
|
||||
: 'N/A',
|
||||
'price' => $this->service->orderItem?->price
|
||||
? number_format((float) $this->service->orderItem->price, 0, ',', '.')
|
||||
: null,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Attachment;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Gửi thông tin VPS bằng template tĩnh send-info-vps.blade.php
|
||||
* (không phụ thuộc EmailNotificationTemplate/Template trong DB).
|
||||
*
|
||||
* KHÔNG implement ShouldQueue — mailable này được gọi từ bên trong
|
||||
* SendInformationVirtualMachine (đã là queued job). Gửi đồng bộ để
|
||||
* tránh Laravel cố JSON-encode $invoicePdf (binary PDF).
|
||||
*/
|
||||
class VmInfoMail extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(
|
||||
public readonly array $data,
|
||||
public readonly ?string $invoicePdf = null,
|
||||
public readonly ?string $invoicePdfFileName = null,
|
||||
) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
$osName = $this->data['os_name'] ?? '';
|
||||
|
||||
return new Envelope(
|
||||
subject: "VPS của bạn đã sẵn sàng" . ($osName ? " — {$osName}" : ''),
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
view: 'emails.customer.send-info-vps',
|
||||
with: [
|
||||
'companyName' => $this->data['company_name'] ?? '',
|
||||
'companyLogo' => $this->data['company_logo'] ?? '',
|
||||
'clientName' => $this->data['client_name'] ?? '',
|
||||
'productName' => $this->data['product_name'] ?? '',
|
||||
'productBilling' => $this->data['product_billing'] ?? '',
|
||||
'productPrice' => $this->data['product_price'] ?? '',
|
||||
'serviceHost' => $this->data['service_host'] ?? '',
|
||||
'serviceUsername' => $this->data['service_username'] ?? '',
|
||||
'servicePort' => $this->data['service_port'] ?? '',
|
||||
'servicePassword' => $this->data['service_password'] ?? '',
|
||||
'osName' => $this->data['os_name'] ?? '',
|
||||
'serviceDueExp' => $this->data['service_due_exp'] ?? '',
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
public function attachments(): array
|
||||
{
|
||||
if ($this->invoicePdf !== null && $this->invoicePdfFileName !== null) {
|
||||
return [
|
||||
Attachment::fromData(fn () => $this->invoicePdf, $this->invoicePdfFileName)
|
||||
->withMime('application/pdf'),
|
||||
];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -94,4 +94,40 @@ class ModuleVmware extends Model
|
||||
default => '<span class="badge bg-danger">Pending</span>',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* `virtual_machine_id`/`cpu`/`ram_mb` are only written when a service is
|
||||
* created directly against a known vCenter inventory row (admin "create
|
||||
* service" flow) or after a manual config change (UpdateVmConfigJob) —
|
||||
* the normal auto-provisioning pipeline never sets them, since the VM
|
||||
* isn't synced into `virtual_machines` yet at creation time. Backfill
|
||||
* them here from the live `vmware_id` ↔ `virtual_machines.vm_id` match
|
||||
* so API responses always expose the real link/spec (needed by the
|
||||
* admin UI to show CPU/RAM and enable power on/off/restart/console).
|
||||
*
|
||||
* `disk_gb` has no source anywhere in the app (vCenter sync doesn't
|
||||
* track disk size) — it stays null until captured some other way.
|
||||
*/
|
||||
public static function resolveVirtualMachineIds(iterable $vmwares): void
|
||||
{
|
||||
$candidates = collect($vmwares)->filter(fn ($vm) => $vm && $vm->vmware_id
|
||||
&& (!$vm->virtual_machine_id || !$vm->cpu || !$vm->ram_mb));
|
||||
if ($candidates->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$inventory = \App\Models\VirtualMachines::whereIn('vm_id', $candidates->pluck('vmware_id')->unique())
|
||||
->get(['id', 'vm_id', 'cpu', 'ram_mb'])
|
||||
->keyBy('vm_id');
|
||||
|
||||
foreach ($candidates as $vm) {
|
||||
$match = $inventory->get($vm->vmware_id);
|
||||
if (!$match) {
|
||||
continue;
|
||||
}
|
||||
$vm->virtual_machine_id ??= $match->id;
|
||||
$vm->cpu ??= $match->cpu;
|
||||
$vm->ram_mb ??= $match->ram_mb;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ class Product extends Model
|
||||
'gpu',
|
||||
'disk',
|
||||
'bandwidth',
|
||||
'domain_count',
|
||||
'stock',
|
||||
'is_unlimited',
|
||||
'is_active',
|
||||
@@ -39,6 +40,7 @@ class Product extends Model
|
||||
'module_host_id',
|
||||
'module_datastore_id',
|
||||
'published_at',
|
||||
'features',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
@@ -47,6 +49,7 @@ class Product extends Model
|
||||
'published_at' => 'date',
|
||||
'gallery' => 'array',
|
||||
'product_type' => 'string',
|
||||
'features' => 'array',
|
||||
];
|
||||
|
||||
protected static function boot()
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ProductTypeField extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'product_type',
|
||||
'group_label',
|
||||
'key',
|
||||
'label',
|
||||
'field_type',
|
||||
'sort_order',
|
||||
'is_required',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_required' => 'boolean',
|
||||
'sort_order' => 'integer',
|
||||
];
|
||||
}
|
||||
@@ -4,12 +4,16 @@ namespace App\Services\Api\Client;
|
||||
|
||||
use App\Http\Services\Telegram;
|
||||
use App\Mail\Admin\TrialRegistrationRequest as TrialRegistrationRequestMail;
|
||||
use App\Mail\Customer\PasswordResetByAdmin;
|
||||
use App\Mail\Customer\VerifyAccount as VerifyAccountMail;
|
||||
use App\Mail\Customer\Welcome as WelcomeMail;
|
||||
use App\Models\Customer;
|
||||
use App\Models\RefreshToken;
|
||||
use App\Models\Setting;
|
||||
use App\Repositories\Api\Client\ClientRepositoryInterface;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -299,4 +303,77 @@ class ClientAuthService
|
||||
$hash = hash('sha256', $rawToken);
|
||||
RefreshToken::where('token', $hash)->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cấp mật khẩu mới ngẫu nhiên khi khách hàng quên mật khẩu. Không tiết lộ
|
||||
* email có tồn tại hay không — trả về null nếu không tìm thấy tài khoản.
|
||||
*/
|
||||
public function resetForgottenPassword(string $email): ?Customer
|
||||
{
|
||||
$customer = Customer::whereRaw('LOWER(email) = ?', [strtolower(trim($email))])->first();
|
||||
|
||||
if (!$customer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$newPassword = Str::password(16);
|
||||
|
||||
DB::transaction(function () use ($customer, $newPassword) {
|
||||
$customer->password = Hash::make($newPassword);
|
||||
$customer->save();
|
||||
|
||||
Mail::to($customer->email)->later(now()->addSeconds(5), new PasswordResetByAdmin([
|
||||
'fullname' => $customer->fullname,
|
||||
'email' => $customer->email,
|
||||
'password' => $newPassword,
|
||||
]));
|
||||
});
|
||||
|
||||
return $customer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cập nhật thông tin cá nhân. Trả về old/dirty values để caller ghi activity log.
|
||||
*/
|
||||
public function updateProfile(Customer $client, array $data): array
|
||||
{
|
||||
$oldValues = array_intersect_key($client->toArray(), $data);
|
||||
$client->fill($data);
|
||||
$dirty = $client->getDirty();
|
||||
$client->save();
|
||||
|
||||
return ['client' => $client, 'old' => array_intersect_key($oldValues, $dirty), 'dirty' => $dirty];
|
||||
}
|
||||
|
||||
/**
|
||||
* Cập nhật CMT/CCCD (số + 2 ảnh đã được lưu sẵn trên storage bởi caller).
|
||||
*/
|
||||
public function updateCccd(Customer $client, string $number, string $frontUrl, string $backUrl): array
|
||||
{
|
||||
$oldValues = $client->only(['identity_number', 'front_identity_number', 'back_identity_number']);
|
||||
|
||||
$client->identity_number = $number;
|
||||
$client->front_identity_number = $frontUrl;
|
||||
$client->back_identity_number = $backUrl;
|
||||
|
||||
$dirty = $client->getDirty();
|
||||
$client->save();
|
||||
|
||||
return ['client' => $client, 'old' => array_intersect_key($oldValues, $dirty), 'dirty' => $dirty];
|
||||
}
|
||||
|
||||
/**
|
||||
* Đổi mật khẩu. Ném ValidationException nếu mật khẩu hiện tại không đúng.
|
||||
*/
|
||||
public function changePassword(Customer $client, string $currentPassword, string $newPassword): void
|
||||
{
|
||||
if (!Hash::check($currentPassword, $client->password)) {
|
||||
throw ValidationException::withMessages([
|
||||
'current_password' => ['Mật khẩu hiện tại không chính xác'],
|
||||
]);
|
||||
}
|
||||
|
||||
$client->password = Hash::make($newPassword);
|
||||
$client->save();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Customer\Concerns;
|
||||
|
||||
use App\Models\Customer;
|
||||
use App\Repositories\Customer\CustomerRepositoryInterface;
|
||||
|
||||
/**
|
||||
* @property-read CustomerRepositoryInterface $customerRepository
|
||||
*/
|
||||
trait ResolvesCustomer
|
||||
{
|
||||
protected function resolveCustomer(string $uuid): Customer
|
||||
{
|
||||
$customer = $this->customerRepository->findBy('uuid', $uuid);
|
||||
|
||||
abort_if(!$customer, 404, "Can't find customer by UUID #{$uuid}");
|
||||
|
||||
return $customer;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Customer;
|
||||
|
||||
use App\Models\Customer;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\Order;
|
||||
use App\Models\Transaction;
|
||||
use App\Repositories\Customer\CustomerRepositoryInterface;
|
||||
use App\Services\Customer\Concerns\ResolvesCustomer;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
||||
class CustomerAccountService
|
||||
{
|
||||
use ResolvesCustomer;
|
||||
|
||||
public function __construct(
|
||||
private readonly CustomerRepositoryInterface $customerRepository,
|
||||
) {}
|
||||
|
||||
public function create(array $data): Customer
|
||||
{
|
||||
if ($this->customerRepository->findBy('email', $data['email'] ?? null)) {
|
||||
abort(422, 'Email already exists on the system!');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($data) {
|
||||
$note = $data['note'] ?? null;
|
||||
unset($data['note']);
|
||||
|
||||
$data['password'] = Hash::make($data['password']);
|
||||
$data['email_marketing'] = ($data['email_marketing'] ?? null) === 'on' ? 1 : 0;
|
||||
|
||||
$customer = $this->customerRepository->create($data);
|
||||
|
||||
if ($note !== null) {
|
||||
$customer->update(['note' => $note]);
|
||||
}
|
||||
|
||||
return $customer->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function update(string $uuid, array $data): Customer
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
return DB::transaction(function () use ($customer, $data) {
|
||||
$note = $data['note'] ?? null;
|
||||
unset($data['note'], $data['password']);
|
||||
|
||||
if (!empty($data['password_raw'])) {
|
||||
$data['password'] = Hash::make($data['password_raw']);
|
||||
unset($data['password_raw']);
|
||||
}
|
||||
|
||||
$this->customerRepository->update($customer->id, $data);
|
||||
|
||||
if ($note !== null) {
|
||||
$customer->update(['note' => $note]);
|
||||
}
|
||||
|
||||
return $customer->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function destroy(string $uuid): void
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
DB::transaction(function () use ($customer) {
|
||||
$this->deleteRelatedRecords($customer->id);
|
||||
$customer->delete();
|
||||
});
|
||||
}
|
||||
|
||||
public function restore(string $uuid): void
|
||||
{
|
||||
$customer = $this->customerRepository->findBy('uuid', $uuid)
|
||||
?? $this->customerRepository->onlyTrashed()->where('uuid', $uuid)->first();
|
||||
|
||||
abort_if(!$customer, 404, "Can't find customer by UUID #{$uuid}");
|
||||
|
||||
DB::transaction(function () use ($customer) {
|
||||
$customer->restore();
|
||||
$this->restoreRelatedRecords($customer->id);
|
||||
});
|
||||
}
|
||||
|
||||
public function forceDelete(string $uuid): void
|
||||
{
|
||||
$customer = $this->customerRepository->onlyTrashed()->where('uuid', $uuid)->first();
|
||||
|
||||
abort_if(!$customer, 404, "Can't find customer by UUID #{$uuid}");
|
||||
|
||||
DB::transaction(function () use ($customer) {
|
||||
$this->forceDeleteRelatedRecords($customer->id);
|
||||
$customer->forceDelete();
|
||||
});
|
||||
}
|
||||
|
||||
public function updateStatus(string $uuid, int $status): void
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
$customer->update(['status' => $status]);
|
||||
}
|
||||
|
||||
public function bulkDelete(array $uuids): int
|
||||
{
|
||||
$customers = Customer::whereIn('uuid', $uuids)->get();
|
||||
|
||||
DB::transaction(function () use ($customers) {
|
||||
foreach ($customers as $customer) {
|
||||
$this->deleteRelatedRecords($customer->id);
|
||||
$customer->delete();
|
||||
}
|
||||
});
|
||||
|
||||
return $customers->count();
|
||||
}
|
||||
|
||||
public function bulkRestore(array $uuids): int
|
||||
{
|
||||
$customers = Customer::onlyTrashed()->whereIn('uuid', $uuids)->get();
|
||||
|
||||
DB::transaction(function () use ($customers) {
|
||||
foreach ($customers as $customer) {
|
||||
$customer->restore();
|
||||
$this->restoreRelatedRecords($customer->id);
|
||||
}
|
||||
});
|
||||
|
||||
return $customers->count();
|
||||
}
|
||||
|
||||
public function bulkForceDelete(array $uuids): int
|
||||
{
|
||||
$customers = Customer::onlyTrashed()->whereIn('uuid', $uuids)->get();
|
||||
|
||||
DB::transaction(function () use ($customers) {
|
||||
foreach ($customers as $customer) {
|
||||
$this->forceDeleteRelatedRecords($customer->id);
|
||||
$customer->forceDelete();
|
||||
}
|
||||
});
|
||||
|
||||
return $customers->count();
|
||||
}
|
||||
|
||||
public function bulkStatus(array $uuids, int $status): int
|
||||
{
|
||||
return Customer::whereIn('uuid', $uuids)->update(['status' => $status]);
|
||||
}
|
||||
|
||||
private function deleteRelatedRecords(int $customerId): void
|
||||
{
|
||||
Invoice::where('customer_id', $customerId)->delete();
|
||||
Order::where('customer_id', $customerId)->delete();
|
||||
Transaction::where('customer_id', $customerId)->delete();
|
||||
}
|
||||
|
||||
private function restoreRelatedRecords(int $customerId): void
|
||||
{
|
||||
Invoice::withTrashed()->where('customer_id', $customerId)->restore();
|
||||
Order::withTrashed()->where('customer_id', $customerId)->restore();
|
||||
Transaction::withTrashed()->where('customer_id', $customerId)->restore();
|
||||
}
|
||||
|
||||
private function forceDeleteRelatedRecords(int $customerId): void
|
||||
{
|
||||
Invoice::withTrashed()->where('customer_id', $customerId)->forceDelete();
|
||||
Order::withTrashed()->where('customer_id', $customerId)->forceDelete();
|
||||
Transaction::withTrashed()->where('customer_id', $customerId)->forceDelete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Customer;
|
||||
|
||||
use App\Models\Invoice;
|
||||
use App\Models\Order;
|
||||
use App\Models\Transaction;
|
||||
use App\Repositories\Customer\CustomerRepositoryInterface;
|
||||
use App\Repositories\Invoice\InvoiceRepositoryInterface;
|
||||
use App\Repositories\Order\OrderRepositoryInterface;
|
||||
use App\Repositories\Transaction\TransactionRepositoryInterface;
|
||||
use App\Services\Customer\Concerns\ResolvesCustomer;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class CustomerBillingService
|
||||
{
|
||||
use ResolvesCustomer;
|
||||
|
||||
public function __construct(
|
||||
private readonly CustomerRepositoryInterface $customerRepository,
|
||||
private readonly InvoiceRepositoryInterface $invoiceRepository,
|
||||
private readonly TransactionRepositoryInterface $transactionRepository,
|
||||
private readonly OrderRepositoryInterface $orderRepository,
|
||||
) {}
|
||||
|
||||
public function getInvoices(string $uuid): Collection
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$invoices = $this->invoiceRepository->filter(['customer_id' => $customer->id], ['payment']);
|
||||
// Frontend đọc ngày thanh toán qua `date_paid` — alias từ cột paid_at.
|
||||
$invoices->each(fn($invoice) => $invoice->date_paid = $invoice->paid_at);
|
||||
|
||||
return $invoices;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sửa hóa đơn của khách hàng, kể cả số tiền (sub_total/tax/total). Không
|
||||
* tự đồng bộ lại invoice_items hay customer.total.
|
||||
*/
|
||||
public function updateInvoice(string $uuid, int $invoiceId, array $data): Invoice
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$invoice = Invoice::where('customer_id', $customer->id)->where('id', $invoiceId)->first();
|
||||
abort_if(!$invoice, 404, 'Không tìm thấy hóa đơn');
|
||||
|
||||
// `date_paid` là tên field phía frontend — cột thật trong DB là paid_at.
|
||||
if (array_key_exists('date_paid', $data)) {
|
||||
$data['paid_at'] = $data['date_paid'];
|
||||
unset($data['date_paid']);
|
||||
}
|
||||
|
||||
// Đi qua repository (không gọi $invoice->update() trực tiếp) để cache
|
||||
// của invoiceRepository->filter() (dùng ở getInvoices) được xoá theo,
|
||||
// nếu không danh sách hóa đơn sẽ hiển thị dữ liệu cũ cho tới khi cache hết hạn.
|
||||
$this->invoiceRepository->update($invoiceId, $data);
|
||||
|
||||
$invoice = $invoice->refresh();
|
||||
$invoice->date_paid = $invoice->paid_at;
|
||||
|
||||
return $invoice->load('payment');
|
||||
}
|
||||
|
||||
public function getTransactions(string $uuid): Collection
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
return $this->transactionRepository->filter(['customer_id' => $customer->id], ['user']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sửa thông tin giao dịch, kể cả amount (để sửa số tiền nhập/hiển thị sai).
|
||||
* Không tự động cộng/trừ lại customer.total khi sửa amount — chiều +/- của
|
||||
* amount phụ thuộc vào type (balance trừ tiền, transfer/admin_add_total
|
||||
* cộng tiền,...) và không có field nào lưu lại chiều đó, nên tự suy luận
|
||||
* dễ làm sai số dư hơn là sửa đúng. Nếu cần đồng bộ lại số dư, dùng
|
||||
* "Cộng tiền" ở tab Tổng quan sau khi sửa xong.
|
||||
*/
|
||||
public function updateTransaction(string $uuid, int $transactionId, array $data): Transaction
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$transaction = Transaction::where('customer_id', $customer->id)->where('id', $transactionId)->first();
|
||||
abort_if(!$transaction, 404, 'Không tìm thấy giao dịch');
|
||||
|
||||
// Đi qua repository để cache của transactionRepository->filter()
|
||||
// (dùng ở getTransactions) được xoá theo — xem ghi chú ở updateInvoice.
|
||||
$this->transactionRepository->update($transactionId, $data);
|
||||
|
||||
return $transaction->refresh()->load('user');
|
||||
}
|
||||
|
||||
public function getOrders(string $uuid): Collection
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
return $this->orderRepository->filter(['client' => $customer->id], ['customer', 'payment', 'invoice']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sửa đơn hàng của khách hàng, kể cả số tiền (sub_total/discount_amount/
|
||||
* total). Không tự đồng bộ lại invoice/invoice_item hay customer.total —
|
||||
* nếu số tiền hóa đơn liên kết cũng cần sửa, sửa riêng ở updateInvoice.
|
||||
*/
|
||||
public function updateOrder(string $uuid, int $orderId, array $data): Order
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$order = Order::where('customer_id', $customer->id)->where('id', $orderId)->first();
|
||||
abort_if(!$order, 404, 'Không tìm thấy đơn hàng');
|
||||
|
||||
// Đi qua repository để cache của orderRepository->filter()
|
||||
// (dùng ở getOrders) được xoá theo — xem ghi chú ở updateInvoice.
|
||||
$this->orderRepository->update($orderId, $data);
|
||||
|
||||
return $order->refresh()->load(['payment', 'invoice']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Customer;
|
||||
|
||||
use App\Http\Resources\Api\Client\ClientResource;
|
||||
use App\Models\Log;
|
||||
use App\Models\User;
|
||||
use App\Repositories\Customer\CustomerRepositoryInterface;
|
||||
use App\Services\Api\Client\ClientAuthService;
|
||||
use App\Services\Customer\Concerns\ResolvesCustomer;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Str;
|
||||
use Tymon\JWTAuth\Facades\JWTAuth;
|
||||
|
||||
class CustomerImpersonationService
|
||||
{
|
||||
use ResolvesCustomer;
|
||||
|
||||
private const TTL_SECONDS = 120;
|
||||
|
||||
public function __construct(
|
||||
private readonly CustomerRepositoryInterface $customerRepository,
|
||||
private readonly ClientAuthService $clientAuthService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Tạo mã impersonate một lần (hiệu lực 120s) để admin đăng nhập hộ khách hàng.
|
||||
* portal-client đổi code lấy token qua endpoint public `v1/client/impersonate/exchange`.
|
||||
*/
|
||||
public function createLoginCode(string $uuid, User $admin, Request $request): string
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
abort_if((int) $customer->status !== 1, 422, 'Khách hàng không hoạt động, không thể đăng nhập hộ.');
|
||||
|
||||
$token = JWTAuth::fromUser($customer);
|
||||
$refreshToken = $this->clientAuthService->createRefreshToken($customer->id);
|
||||
$clientResource = (new ClientResource($customer->loadCount(['vps', 'hosting', 'domain'])))->resolve($request);
|
||||
|
||||
$code = Str::random(48);
|
||||
Cache::put("impersonate:{$code}", [
|
||||
'token' => $token,
|
||||
'refresh_token' => $refreshToken,
|
||||
'client' => $clientResource,
|
||||
], self::TTL_SECONDS);
|
||||
|
||||
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 $code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Customer;
|
||||
|
||||
use App\Mail\Customer\ManualCustomerEmail;
|
||||
use App\Mail\Customer\PasswordResetByAdmin;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Log;
|
||||
use App\Models\Mail as MailLog;
|
||||
use App\Models\Template;
|
||||
use App\Models\User;
|
||||
use App\Repositories\Customer\CustomerRepositoryInterface;
|
||||
use App\Services\Customer\Concerns\ResolvesCustomer;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
class CustomerMailService
|
||||
{
|
||||
use ResolvesCustomer;
|
||||
|
||||
public function __construct(
|
||||
private readonly CustomerRepositoryInterface $customerRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Reset về mật khẩu ngẫu nhiên và gửi mail cho khách hàng.
|
||||
*/
|
||||
public function resetPassword(string $uuid): void
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$this->setPasswordAndNotify($customer, str()->random(10));
|
||||
}
|
||||
|
||||
/**
|
||||
* Đặt mật khẩu do admin nhập và gửi mail cho khách hàng, có ghi log.
|
||||
*/
|
||||
public function sendPasswordEmail(string $uuid, string $password, string $clientIp): void
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$this->setPasswordAndNotify($customer, $password);
|
||||
|
||||
Log::create([
|
||||
'agent' => 'admin',
|
||||
'client_ip' => $clientIp,
|
||||
'description' => sprintf('Admin gửi lại mật khẩu mới cho customer %s', $customer->email),
|
||||
'customer_id' => $customer->id,
|
||||
]);
|
||||
}
|
||||
|
||||
private function setPasswordAndNotify(Customer $customer, string $password): void
|
||||
{
|
||||
DB::transaction(function () use ($customer, $password) {
|
||||
$this->customerRepository->update($customer->id, ['password' => Hash::make($password)]);
|
||||
|
||||
$mail = new PasswordResetByAdmin([
|
||||
'fullname' => $customer->fullname,
|
||||
'email' => $customer->email,
|
||||
'password' => $password,
|
||||
]);
|
||||
|
||||
Mail::to($customer->email)->send($mail);
|
||||
|
||||
MailLog::create([
|
||||
'subject' => $mail->envelope()->subject,
|
||||
'to' => $customer->email,
|
||||
'customer_id' => $customer->id,
|
||||
'message' => $mail->render(),
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gửi email tự do (hoặc theo template) cho khách hàng, có ghi log.
|
||||
*/
|
||||
public function sendCustomEmail(string $uuid, array $data, User $admin, string $clientIp): void
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$template = null;
|
||||
$subject = trim((string) ($data['subject'] ?? ''));
|
||||
$message = trim((string) ($data['message'] ?? ''));
|
||||
|
||||
if (!empty($data['template_id'])) {
|
||||
$template = Template::query()->whereKey($data['template_id'])->where('status', 1)->first();
|
||||
abort_if(!$template, 422, 'Template không tồn tại hoặc đang bị tắt.');
|
||||
|
||||
$subject = trim((string) $template->subject);
|
||||
$message = trim((string) $template->message);
|
||||
}
|
||||
|
||||
abort_if($subject === '' || $message === '', 422, 'Subject và content không được để trống.');
|
||||
|
||||
$to = $this->parseEmailRecipients($data['to'] ?? null) ?: [$customer->email];
|
||||
$cc = $this->parseEmailRecipients($data['cc'] ?? null);
|
||||
$bcc = $this->parseEmailRecipients($data['bcc'] ?? null);
|
||||
|
||||
abort_if($to === [], 422, 'Không có địa chỉ email nhận hợp lệ.');
|
||||
|
||||
$mailer = Mail::to($to);
|
||||
if ($cc !== []) {
|
||||
$mailer->cc($cc);
|
||||
}
|
||||
if ($bcc !== []) {
|
||||
$mailer->bcc($bcc);
|
||||
}
|
||||
$mailer->send(new ManualCustomerEmail($subject, $message));
|
||||
|
||||
MailLog::create([
|
||||
'template_id' => $template->id ?? 0,
|
||||
'subject' => $subject,
|
||||
'to' => implode(', ', $to),
|
||||
'cc' => implode(', ', $cc),
|
||||
'customer_id' => $customer->id,
|
||||
'message' => $message,
|
||||
]);
|
||||
|
||||
Log::create([
|
||||
'agent' => 'admin',
|
||||
'client_ip' => $clientIp,
|
||||
'description' => sprintf(
|
||||
'%s gửi email cho customer %s%s',
|
||||
$admin->username ?? $admin->email ?? 'Admin',
|
||||
$customer->email,
|
||||
$template ? sprintf(' bằng template #%s', $template->id) : '',
|
||||
),
|
||||
'customer_id' => $customer->id,
|
||||
]);
|
||||
}
|
||||
|
||||
private function parseEmailRecipients(?string $value): array
|
||||
{
|
||||
if (!$value) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return collect(preg_split('/[,;]+/', $value) ?: [])
|
||||
->map(fn($email) => trim((string) $email))
|
||||
->filter(fn($email) => $email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL))
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Customer;
|
||||
|
||||
use App\Models\Note;
|
||||
use App\Repositories\Customer\CustomerRepositoryInterface;
|
||||
use App\Services\Customer\Concerns\ResolvesCustomer;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class CustomerNoteService
|
||||
{
|
||||
use ResolvesCustomer;
|
||||
|
||||
public function __construct(
|
||||
private readonly CustomerRepositoryInterface $customerRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Ghi chú của khách hàng (không gắn với dịch vụ cụ thể).
|
||||
*/
|
||||
public function getCustomerNotes(string $uuid): Collection
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
return Note::with('user:id,username')
|
||||
->where('customer_id', $customer->id)
|
||||
->whereNull('service_id')
|
||||
->latest()
|
||||
->get();
|
||||
}
|
||||
|
||||
public function storeCustomerNote(string $uuid, string $note, int $userId): Note
|
||||
{
|
||||
return $this->storeNote($uuid, ['note' => $note], $userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ghi chú gắn với 1 dịch vụ cụ thể của khách hàng.
|
||||
*/
|
||||
public function getServiceNotes(string $uuid, int $serviceId): Collection
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
return Note::with('user:id,username')
|
||||
->where('customer_id', $customer->id)
|
||||
->where('service_id', $serviceId)
|
||||
->latest()
|
||||
->get();
|
||||
}
|
||||
|
||||
public function storeServiceNote(string $uuid, int $serviceId, string $note, int $userId): Note
|
||||
{
|
||||
return $this->storeNote($uuid, ['note' => $note, 'service_id' => $serviceId], $userId);
|
||||
}
|
||||
|
||||
public function destroyNote(string $uuid, int $noteId): void
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$deleted = Note::where('id', $noteId)->where('customer_id', $customer->id)->delete();
|
||||
abort_if(!$deleted, 404, 'Không tìm thấy ghi chú');
|
||||
}
|
||||
|
||||
private function storeNote(string $uuid, array $attributes, int $userId): Note
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$note = Note::create([
|
||||
...$attributes,
|
||||
'customer_id' => $customer->id,
|
||||
'user_id' => $userId,
|
||||
]);
|
||||
|
||||
return $note->load('user:id,username');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Customer;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Enums\Order\OrderStatus;
|
||||
use App\Helpers\OrderHelper;
|
||||
use App\Mail\ServiceRenewalReminderMail;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\InvoiceItem;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Models\Order;
|
||||
use App\Models\OrderItem;
|
||||
use App\Models\Product;
|
||||
use App\Models\Service;
|
||||
use App\Models\Transaction;
|
||||
use App\Models\VirtualMachines;
|
||||
use App\Repositories\Customer\CustomerRepositoryInterface;
|
||||
use App\Repositories\Module\Hosting\HostingRepositoryInterface as ModuleHostingRepositoryInterface;
|
||||
use App\Repositories\Module\Vmware\VmwareRepositoryInterface;
|
||||
use App\Repositories\Service\ServiceRepositoryInterface;
|
||||
use App\Services\Customer\Concerns\ResolvesCustomer;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class CustomerServiceProvisioningService
|
||||
{
|
||||
use ResolvesCustomer;
|
||||
|
||||
public function __construct(
|
||||
private readonly CustomerRepositoryInterface $customerRepository,
|
||||
private readonly ModuleHostingRepositoryInterface $moduleHostingRepository,
|
||||
private readonly VmwareRepositoryInterface $vmwareRepository,
|
||||
private readonly ServiceRepositoryInterface $serviceRepository,
|
||||
) {}
|
||||
|
||||
public function getProducts(string $uuid): Collection
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$hostingServices = $this->moduleHostingRepository->filter(['customer_id' => $customer->id], ['server']);
|
||||
$vpsServices = $this->vmwareRepository->filter(
|
||||
['customer_id' => $customer->id],
|
||||
['ipaddress.host.datacenter.vCenter', 'os.osGroup'],
|
||||
);
|
||||
|
||||
$allService = collect();
|
||||
|
||||
foreach ($hostingServices as $hosting) {
|
||||
$allService->push([
|
||||
'product_id' => $hosting->id,
|
||||
'product_type' => 3,
|
||||
'name' => $hosting->name,
|
||||
'description' => $hosting->name . ' (Hosting)',
|
||||
]);
|
||||
}
|
||||
|
||||
foreach ($vpsServices as $vps) {
|
||||
$allService->push([
|
||||
'product_id' => $vps->id,
|
||||
'product_type' => 4,
|
||||
'name' => $vps->name,
|
||||
'description' => $vps->name . ' (VPS)',
|
||||
]);
|
||||
}
|
||||
|
||||
return $allService->values();
|
||||
}
|
||||
|
||||
public function getServices(string $uuid): Collection
|
||||
{
|
||||
$services = $this->serviceRepository->filter(
|
||||
['customer_uuid' => $uuid],
|
||||
['product', 'orderItem', 'invoice', 'vmware.os.osGroup'],
|
||||
);
|
||||
|
||||
ModuleVmware::resolveVirtualMachineIds($services->pluck('vmware'));
|
||||
|
||||
return $services;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, array $ids): int
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
return Service::where('customer_id', $customer->id)->whereIn('id', $ids)->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, array $data): Service
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$service = Service::where('customer_id', $customer->id)->where('id', $serviceId)->first();
|
||||
abort_if(!$service, 404, 'Không tìm thấy dịch vụ');
|
||||
|
||||
return DB::transaction(function () use ($service, $data) {
|
||||
$vmFields = ['os_id', 'vm_cpu', 'vm_ram_mb', 'vm_disk_gb', 'vm_ip', 'vm_dns', 'vm_user', 'vm_password', 'vm_port'];
|
||||
|
||||
$service->fill(collect($data)->except(['price', ...$vmFields])->all());
|
||||
$service->save();
|
||||
|
||||
if (array_key_exists('price', $data) && $data['price'] !== null && $service->orderItem) {
|
||||
$service->orderItem->update(['price' => $data['price']]);
|
||||
}
|
||||
|
||||
// Đồng bộ sang module_vmware nếu có gán VM
|
||||
if ($service->vm_id) {
|
||||
$vmData = array_filter([
|
||||
'hostname' => $data['server_name'] ?? null,
|
||||
'os_id' => $data['os_id'] ?? null,
|
||||
'cpu' => $data['vm_cpu'] ?? null,
|
||||
'ram_mb' => $data['vm_ram_mb'] ?? null,
|
||||
'disk_gb' => $data['vm_disk_gb'] ?? null,
|
||||
'ip' => $data['vm_ip'] ?? null,
|
||||
'dns' => $data['vm_dns'] ?? null,
|
||||
'user' => $data['vm_user'] ?? null,
|
||||
'password' => $data['vm_password'] ?? null,
|
||||
'plain_password' => $data['vm_password'] ?? null,
|
||||
'port' => $data['vm_port'] ?? null,
|
||||
], fn($v) => $v !== null);
|
||||
|
||||
if ($vmData) {
|
||||
ModuleVmware::findOrFail($service->vm_id)->update($vmData);
|
||||
}
|
||||
}
|
||||
|
||||
$service->load(['product', 'orderItem', 'invoice', 'vmware.os.osGroup']);
|
||||
ModuleVmware::resolveVirtualMachineIds([$service->vmware]);
|
||||
|
||||
return $service;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gửi email nhắc gia hạn dịch vụ cho khách hàng.
|
||||
*/
|
||||
public function notifyRenewal(string $uuid, int $serviceId): void
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$service = Service::where('customer_id', $customer->id)->where('id', $serviceId)
|
||||
->with(['product', 'orderItem'])
|
||||
->first();
|
||||
abort_if(!$service, 404, 'Không tìm thấy dịch vụ');
|
||||
abort_if(!$customer->email, 422, 'Khách hàng chưa có email');
|
||||
|
||||
Mail::to($customer->email)->send(new ServiceRenewalReminderMail($customer, $service));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, array $data, string $clientIp): Service
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
$product = Product::with('pricings')->find($data['product_id']);
|
||||
abort_if(
|
||||
$product->product_type === 'vps' && empty($data['virtual_machine_id']),
|
||||
422,
|
||||
'VPS service requires a virtual_machine_id',
|
||||
);
|
||||
|
||||
$billingCycle = $data['billing_cycle'] ?? 'monthly';
|
||||
$months = $this->cycleToMonths($billingCycle);
|
||||
|
||||
$pricing = $product->pricings->where('billing_cycle', $billingCycle)->first();
|
||||
// Số tiền đã thanh toán: admin nhập tay để khớp với thực tế (có thể lệch giá niêm yết do khuyến mãi/thoả thuận)
|
||||
$basePrice = isset($data['amount_paid']) ? (int) $data['amount_paid'] : (int) ($pricing->price ?? 0);
|
||||
|
||||
$paymentMethod = $data['payment_method'];
|
||||
|
||||
// Đối với balance: kiểm tra số dư trước khi vào transaction
|
||||
abort_if(
|
||||
$paymentMethod === 'balance' && (int) $customer->total < $basePrice,
|
||||
422,
|
||||
sprintf(
|
||||
'Số dư khách không đủ. Hiện có: %s VNĐ, cần: %s VNĐ.',
|
||||
number_format((int) $customer->total),
|
||||
number_format($basePrice),
|
||||
),
|
||||
);
|
||||
|
||||
return DB::transaction(function () use ($customer, $product, $data, $billingCycle, $months, $basePrice, $paymentMethod, $clientIp) {
|
||||
// 1) Order + OrderItem (mô phỏng flow customer đặt hàng)
|
||||
$order = Order::create([
|
||||
'order_num' => OrderHelper::generateOrderNumber(),
|
||||
'customer_id' => $customer->id,
|
||||
'date' => now()->toDateString(),
|
||||
'sub_total' => $basePrice,
|
||||
'discount_amount' => 0,
|
||||
'total' => $basePrice,
|
||||
'status' => OrderStatus::ACTIVE->value,
|
||||
'payment_method' => $paymentMethod,
|
||||
'client_ip' => $clientIp,
|
||||
]);
|
||||
|
||||
$orderItem = 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,
|
||||
]);
|
||||
|
||||
// Ngày bắt đầu/hết hạn dùng chung cho cả module_vmware (next_due_date/next_invoice) và services.
|
||||
$startedAt = $data['started_at'] ?? now();
|
||||
$expiresAt = $data['expires_at'] ?? Carbon::parse($startedAt)->addMonths($months);
|
||||
|
||||
// 2) ModuleVmware: snapshot từ virtual_machines. `order_id` phải trỏ về
|
||||
// order vừa tạo — client console-ticket/rebuild resolve VM qua
|
||||
// service->orderItem->order->vmWare, không qua services.vm_id.
|
||||
$vmId = $this->createModuleVmwareIfNeeded($data, $customer, $order, $basePrice, $expiresAt);
|
||||
|
||||
// 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,
|
||||
'date' => now()->toDateString(),
|
||||
'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(),
|
||||
]);
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
$proofPaths = $data['_proof_paths'] ?? [];
|
||||
|
||||
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
|
||||
$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 = 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,
|
||||
]);
|
||||
|
||||
// module_vmware.service_id chỉ biết được sau khi Service đã tồn tại.
|
||||
if ($vmId) {
|
||||
ModuleVmware::where('id', $vmId)->update(['service_id' => $service->id]);
|
||||
}
|
||||
|
||||
return $service->load(['product', 'vmware.os.osGroup']);
|
||||
});
|
||||
}
|
||||
|
||||
private function createModuleVmwareIfNeeded(array $data, Customer $customer, Order $order, int $basePrice, string|Carbon $expiresAt): ?int
|
||||
{
|
||||
if (empty($data['virtual_machine_id'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$vm = VirtualMachines::with('datacenter')->find($data['virtual_machine_id']);
|
||||
$vcenterId = $vm->datacenter->vcenter_id ?? null;
|
||||
|
||||
$moduleVm = ModuleVmware::updateOrCreate(
|
||||
['virtual_machine_id' => $vm->id],
|
||||
[
|
||||
'customer_id' => $customer->id,
|
||||
'order_id' => $order->id,
|
||||
'name' => $vm->name,
|
||||
'vmware_id' => $vm->vm_id,
|
||||
'vcenter_id' => $vcenterId,
|
||||
'hostname' => $data['server_name'] ?? $vm->name,
|
||||
'cpu' => $data['vm_cpu'] ?? $vm->cpu,
|
||||
'ram_mb' => $data['vm_ram_mb'] ?? $vm->ram_mb,
|
||||
'disk_gb' => $data['vm_disk_gb'] ?? null,
|
||||
'os_id' => $data['os_id'] ?? null,
|
||||
'ip' => $data['vm_ip'] ?? $vm->ip,
|
||||
'dns' => $data['vm_dns'] ?? null,
|
||||
'user' => $data['vm_user'] ?? null,
|
||||
'password' => $data['vm_password'] ?? null,
|
||||
'plain_password' => $data['vm_password'] ?? null,
|
||||
'port' => $data['vm_port'] ?? null,
|
||||
'status' => 1,
|
||||
'first_payment' => $basePrice,
|
||||
'next_payment' => $basePrice,
|
||||
'next_due_date' => Carbon::parse($expiresAt)->timestamp,
|
||||
'next_invoice' => Carbon::parse($expiresAt)->timestamp,
|
||||
],
|
||||
);
|
||||
|
||||
return $moduleVm->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(string $search): Collection
|
||||
{
|
||||
$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');
|
||||
|
||||
return DB::table('virtual_machines as vm')
|
||||
->leftJoin('module_datacenter as dc', 'dc.id', '=', 'vm.datacenter_id')
|
||||
->leftJoin('module_host as h', 'h.id', '=', 'vm.host_id')
|
||||
->leftJoin('module_vcenter as vc', 'vc.id', '=', 'dc.vcenter_id')
|
||||
->select(
|
||||
'vm.id', 'vm.vm_id', 'vm.name', 'vm.power_state', 'vm.cpu', 'vm.ram_mb', 'vm.ip',
|
||||
'vc.host as vcenter_name',
|
||||
'dc.name as datacenter_name',
|
||||
'h.name as host_name',
|
||||
)
|
||||
->where('vm.is_template', 0)
|
||||
->where('vm.is_system', 0)
|
||||
->when($search, fn($q) => $q->where(function ($w) use ($search) {
|
||||
$w->where('vm.name', 'like', "%{$search}%")
|
||||
->orWhere('vm.vm_id', 'like', "%{$search}%")
|
||||
->orWhere('vm.ip', 'like', "%{$search}%");
|
||||
}))
|
||||
->orderBy('vm.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;
|
||||
});
|
||||
}
|
||||
|
||||
private function cycleToMonths(?string $cycle): int
|
||||
{
|
||||
return match ($cycle) {
|
||||
'monthly' => 1,
|
||||
'quarterly' => 3,
|
||||
'semi_annually' => 6,
|
||||
'annually' => 12,
|
||||
'biennially' => 24,
|
||||
'triennially' => 36,
|
||||
default => 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Customer;
|
||||
|
||||
use App\Enums\TransactionStatus;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Log;
|
||||
use App\Models\Transaction;
|
||||
use App\Models\User;
|
||||
use App\Repositories\Customer\CustomerRepositoryInterface;
|
||||
use App\Services\Customer\Concerns\ResolvesCustomer;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class CustomerWalletService
|
||||
{
|
||||
use ResolvesCustomer;
|
||||
|
||||
public function __construct(
|
||||
private readonly CustomerRepositoryInterface $customerRepository,
|
||||
) {}
|
||||
|
||||
public function adjustCredit(string $uuid, User $admin, int $amount, bool $isAdd): Customer
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
return DB::transaction(function () use ($customer, $admin, $amount, $isAdd) {
|
||||
$this->customerRepository->update($customer->id, [
|
||||
'credit' => (int) $customer->credit + ($isAdd ? $amount : -$amount),
|
||||
'total' => (int) $customer->total + ($isAdd ? $amount : -$amount),
|
||||
]);
|
||||
|
||||
$this->recordTransaction(
|
||||
$customer,
|
||||
$admin,
|
||||
$amount,
|
||||
$isAdd ? 'admin_add_credit' : 'admin_deduct_credit',
|
||||
sprintf(
|
||||
'%s %s tiền trực tiếp cho khách hàng: %s VNĐ',
|
||||
$admin->username ?? $admin->email ?? 'Admin',
|
||||
$isAdd ? 'cộng' : 'trừ',
|
||||
number_format($amount),
|
||||
),
|
||||
);
|
||||
|
||||
return $customer->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function addTotal(string $uuid, User $admin, int $amount, string $note, string $clientIp): Transaction
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
return DB::transaction(function () use ($customer, $admin, $amount, $note, $clientIp) {
|
||||
$transaction = $this->recordTransaction(
|
||||
$customer,
|
||||
$admin,
|
||||
$amount,
|
||||
'admin_add_total',
|
||||
$note,
|
||||
);
|
||||
|
||||
$customer->update(['total' => (int) $customer->total + $amount]);
|
||||
|
||||
Log::create([
|
||||
'agent' => 'admin',
|
||||
'client_ip' => $clientIp,
|
||||
'description' => sprintf(
|
||||
'%s cộng tiền trực tiếp cho customer %s: %s VNĐ - %s',
|
||||
$admin->username ?? $admin->email,
|
||||
$customer->email,
|
||||
number_format($amount),
|
||||
$note,
|
||||
),
|
||||
'customer_id' => $customer->id,
|
||||
]);
|
||||
|
||||
return $transaction;
|
||||
});
|
||||
}
|
||||
|
||||
private function recordTransaction(Customer $customer, User $admin, int $amount, string $type, string $note): Transaction
|
||||
{
|
||||
return Transaction::create([
|
||||
'uuid' => (string) Str::uuid(),
|
||||
'trans' => 'ADMIN' . now()->format('YmdHis'),
|
||||
'amount' => $amount,
|
||||
'customer_id' => $customer->id,
|
||||
'user_id' => $admin->id,
|
||||
'status' => TransactionStatus::COMPLETED->value,
|
||||
'type' => $type,
|
||||
'note' => $note,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -11,14 +11,17 @@ use App\Http\Helpers\Helper;
|
||||
use App\Jobs\Hosting\CreateHostingJobs;
|
||||
use App\Jobs\Mail\Customer\OrderCreatedJob;
|
||||
use App\Jobs\VirtualMachine\Create\CreateVirtualMachineJob;
|
||||
use App\Jobs\VirtualMachine\Upgrade\UpgradeVirtualMachine;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Order;
|
||||
use App\Models\OrderItem;
|
||||
use App\Models\Payment;
|
||||
use App\Models\Transaction;
|
||||
use App\Repositories\Addon\AddonRepositoryInterface;
|
||||
use App\Repositories\Invoice\InvoiceRepositoryInterface;
|
||||
use App\Repositories\InvoiceItem\InvoiceItemRepositoryInterface;
|
||||
use App\Repositories\Module\Hosting\HostingRepositoryInterface as ModuleHostingRepositoryInterface;
|
||||
use App\Repositories\Module\HostingServer\HostingServerRepositoryInterface;
|
||||
use App\Repositories\Module\Vmware\VmwareRepositoryInterface;
|
||||
use App\Repositories\Order\OrderRepositoryInterface;
|
||||
use Carbon\Carbon;
|
||||
@@ -34,8 +37,88 @@ class OrderService
|
||||
private readonly InvoiceItemRepositoryInterface $invoiceItemRepository,
|
||||
private readonly ModuleHostingRepositoryInterface $moduleHostingRepository,
|
||||
private readonly VmwareRepositoryInterface $moduleVmwareRepository,
|
||||
private readonly HostingServerRepositoryInterface $moduleHostingServerRepository,
|
||||
private readonly AddonRepositoryInterface $addonRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Xác nhận đơn hàng (status=1). Nếu $provisionModules, chạy thêm logic
|
||||
* cấp phát hosting/VM/addon dựa trên các order item (module=1 từ FE).
|
||||
*/
|
||||
public function confirmOrder(Order $order, bool $provisionModules): void
|
||||
{
|
||||
DB::transaction(function () use ($order, $provisionModules) {
|
||||
$this->orderRepository->update($order->id, ['status' => 1]);
|
||||
|
||||
if ($provisionModules) {
|
||||
$this->provisionOrderItems($order);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function setStatus(Order $order, int $status): void
|
||||
{
|
||||
$this->orderRepository->update($order->id, ['status' => $status]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Xoá đơn hàng cùng hóa đơn và các dòng hóa đơn liên quan.
|
||||
*/
|
||||
public function deleteOrder(Order $order): void
|
||||
{
|
||||
DB::transaction(function () use ($order) {
|
||||
if ($order->invoice) {
|
||||
$order->invoice->invoiceItem()->delete();
|
||||
$order->invoice->delete();
|
||||
}
|
||||
|
||||
$order->delete();
|
||||
});
|
||||
}
|
||||
|
||||
private function provisionOrderItems(Order $order): void
|
||||
{
|
||||
$jobs = [];
|
||||
$addon = [];
|
||||
$product = 0;
|
||||
|
||||
foreach ($order->orderItem as $item) {
|
||||
switch ((int) $item->type_id) {
|
||||
case 1:
|
||||
$itemData = $this->addonRepository->find($item->relid);
|
||||
if ($itemData) {
|
||||
$price = match ((int) $item->billing) {
|
||||
2 => $item->amount / 1,
|
||||
3 => $item->amount / 3,
|
||||
4 => $item->amount / 6,
|
||||
5 => $item->amount / 12,
|
||||
default => 0
|
||||
};
|
||||
$addon[strtolower($itemData->name)] = (int) $price / $itemData->price;
|
||||
$product = $item->parent_id;
|
||||
}
|
||||
break;
|
||||
case 3:
|
||||
$hostingServer = $this->moduleHostingServerRepository->get_active();
|
||||
if ($hostingServer) {
|
||||
$this->moduleHostingRepository->update($item->relid, ['module_server_id' => $hostingServer->first()->id]);
|
||||
$jobs[] = new CreateHostingJobs($item->relid);
|
||||
}
|
||||
break;
|
||||
// case 4 (VPS/Cloud): xử lý bởi CreateVirtualMachineJob, đã dispatch
|
||||
// ngay lúc tạo đơn trong createOrder() — không provision lại ở đây.
|
||||
}
|
||||
}
|
||||
|
||||
if (count($order->orderItem) === count($addon)) {
|
||||
dispatch(new UpgradeVirtualMachine($product, $addon, $order->id))->delay(now()->addSeconds(10));
|
||||
}
|
||||
|
||||
foreach ($jobs as $item) {
|
||||
dispatch($item)->delay(now()->addSeconds(10));
|
||||
}
|
||||
}
|
||||
|
||||
public function createOrder(array $data): Order
|
||||
{
|
||||
$customer = Customer::find($data['customer_id']);
|
||||
|
||||
@@ -82,7 +82,7 @@ final class VmRebuildPasswordService
|
||||
|
||||
$encrypted = SignRSA::EncryptFunc($newPassword);
|
||||
|
||||
ModuleVmware::where('id', $ctx->moduleVmwareId)->update([
|
||||
ModuleVmware::findOrFail($ctx->moduleVmwareId)->update([
|
||||
'password' => $encrypted,
|
||||
'plain_password' => $newPassword,
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\VirtualMachine;
|
||||
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Models\OrderItem;
|
||||
use App\Models\Setting;
|
||||
|
||||
/**
|
||||
* Builds the email payload for VPS credential emails — shared by the
|
||||
* initial provisioning send (SendVmCredentialsEmailJob) and the admin
|
||||
* "resend" action (ResendVmCredentialsEmailJob).
|
||||
*/
|
||||
class VmCredentialsEmailDataBuilder
|
||||
{
|
||||
public function build(ModuleVmware $vm, ?OrderItem $orderItem): array
|
||||
{
|
||||
$setting = Setting::where('key', 'setting')->first();
|
||||
$settingValue = $setting ? json_decode((string) $setting->value) : null;
|
||||
|
||||
$months = (int) ($orderItem?->months ?? 0);
|
||||
$osGroupName = $vm->os?->osGroup?->name ?? '';
|
||||
$isWindows = str_contains(strtolower($osGroupName), 'windows');
|
||||
$osUsername = $isWindows ? 'Administrator' : 'root';
|
||||
|
||||
return $this->safeUtf8([
|
||||
'company_name' => $settingValue->company ?? 'Thế Giới Số',
|
||||
'company_logo' => $settingValue->logo ?? '',
|
||||
'client_name' => $vm->customer->fullname ?? '',
|
||||
'product_name' => $orderItem?->getProductAttribute()?->name ?? 'Cloud VPS',
|
||||
'product_billing' => $this->billingLabel($months),
|
||||
'product_price' => $orderItem ? number_format((float) $orderItem->price, 0, ',', '.') : 'N/A',
|
||||
'service_host' => $vm->ip ?? 'N/A',
|
||||
'service_username' => $osUsername,
|
||||
'service_port' => (string) ($vm->port ?? '22'),
|
||||
'service_password' => $vm->plain_password ?? '(xem tai khoan quan ly)',
|
||||
'os_name' => $vm->os ? ($osGroupName . ' ' . $vm->os->version) : 'Unknown OS',
|
||||
'service_due_exp' => $vm->next_due_date
|
||||
? date('d/m/Y', (int) $vm->next_due_date)
|
||||
: 'N/A',
|
||||
]);
|
||||
}
|
||||
|
||||
private function billingLabel(?int $months): string
|
||||
{
|
||||
return match ($months) {
|
||||
1 => 'Hang thang',
|
||||
3 => '3 Thang',
|
||||
6 => '6 Thang',
|
||||
12 => 'Hang nam',
|
||||
24 => '2 Nam',
|
||||
default => ($months ?? 0) . ' Thang',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize tất cả string trong array thành UTF-8 hợp lệ.
|
||||
* Loại bỏ ký tự binary/invalid trước khi đẩy vào queue (tránh JSON encode lỗi).
|
||||
*/
|
||||
private function safeUtf8(array $data): array
|
||||
{
|
||||
return array_map(function ($value) {
|
||||
if (!is_string($value)) return $value;
|
||||
|
||||
if (mb_check_encoding($value, 'UTF-8')) return $value;
|
||||
|
||||
$converted = mb_convert_encoding($value, 'UTF-8', mb_detect_encoding($value, ['UTF-8', 'ISO-8859-1', 'Windows-1252'], true) ?: 'ISO-8859-1');
|
||||
|
||||
return mb_check_encoding($converted, 'UTF-8')
|
||||
? $converted
|
||||
: preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]|[^\x09\x0A\x0D\x20-\x{10FFFF}]/u', '', $value);
|
||||
}, $data);
|
||||
}
|
||||
}
|
||||
@@ -115,7 +115,7 @@ final class VmProvisionService
|
||||
*/
|
||||
public function updatePassword(int $moduleVmwareId, string $plainPassword): void
|
||||
{
|
||||
ModuleVmware::where('id', $moduleVmwareId)->update([
|
||||
ModuleVmware::findOrFail($moduleVmwareId)->update([
|
||||
'password' => $this->encryptPassword($plainPassword),
|
||||
'plain_password' => $plainPassword,
|
||||
]);
|
||||
@@ -130,7 +130,7 @@ final class VmProvisionService
|
||||
*/
|
||||
public function savePassword(int $moduleVmwareId, string $ip, string $plainPassword): void
|
||||
{
|
||||
ModuleVmware::where('id', $moduleVmwareId)->update([
|
||||
ModuleVmware::findOrFail($moduleVmwareId)->update([
|
||||
'ip' => $ip,
|
||||
'password' => $this->encryptPassword($plainPassword),
|
||||
'plain_password' => $plainPassword,
|
||||
|
||||
Reference in New Issue
Block a user