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:
baodev0
2026-08-26 16:19:38 +07:00
parent 382b7c0ef8
commit c917e3bf5e
47 changed files with 2992 additions and 1759 deletions
@@ -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,
]);
}
}