feat: Reimplement order and invoice management with new service and repository layers, introduce compression middleware, and update database schema.
This commit is contained in:
@@ -2,92 +2,113 @@
|
||||
|
||||
namespace App\Services\Api\Order;
|
||||
|
||||
use App\Repositories\Api\Service\ServiceRepository;
|
||||
use App\Repositories\Api\Invoice\InvoiceRepository;
|
||||
use App\Repositories\Api\Order\OrderRepository;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Enums\Order\OrderStatus;
|
||||
use Exception;
|
||||
use App\Helpers\OrderHelper;
|
||||
use App\Jobs\VirtualMachine\Create\CreateVMJobs;
|
||||
use App\Models\Log as CustomerLog;
|
||||
use App\Models\Addon;
|
||||
use App\Models\Log as CustomerActivityLog;
|
||||
use App\Models\ModuleIpAddress;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Models\Order;
|
||||
use App\Models\OrderItem;
|
||||
use App\Models\Os;
|
||||
use App\Models\Service;
|
||||
use App\Models\ServiceAddon;
|
||||
use App\Repositories\Api\Invoice\InvoiceRepository;
|
||||
use App\Repositories\Api\Order\OrderRepository;
|
||||
use App\Repositories\Api\Service\ServiceRepository;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class OrderService
|
||||
{
|
||||
public function __construct(
|
||||
protected OrderRepository $orderRepo,
|
||||
protected OrderRepository $orderRepo,
|
||||
protected ServiceRepository $productRepo,
|
||||
protected InvoiceRepository $invoiceRepo
|
||||
protected InvoiceRepository $invoiceRepo,
|
||||
) {}
|
||||
|
||||
public function create(array $data, $customer)
|
||||
// =========================================================================
|
||||
// create — Step 1: Customer places an order
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Validate → calculate price → persist Order + OrderItem + Invoice.
|
||||
*
|
||||
* @return array{order: Order, invoice: \App\Models\Invoice}
|
||||
* @throws Exception
|
||||
*/
|
||||
public function create(array $data, $customer): array
|
||||
{
|
||||
// Check for existing pending orders
|
||||
if ($this->orderRepo->hasPendingOrder($customer->id)) {
|
||||
throw new Exception('Bạn có đơn hàng chưa thanh toán. Vui lòng thanh toán trước khi tạo đơn mới.');
|
||||
}
|
||||
|
||||
$product = $this->productRepo->find($data['product_id']);
|
||||
|
||||
if (!$product) {
|
||||
throw new Exception('Sản phẩm không tồn tại');
|
||||
throw new Exception('Sản phẩm không tồn tại.');
|
||||
}
|
||||
|
||||
$price = $this->productRepo->getPricing($product->id, $data['billing_cycle']);
|
||||
|
||||
if (is_null($price)) {
|
||||
throw new Exception('Không tìm thấy giá cho sản phẩm này');
|
||||
$basePrice = $this->productRepo->getPricing($product->id, $data['billing_cycle']);
|
||||
if (is_null($basePrice)) {
|
||||
throw new Exception('Không tìm thấy giá cho chu kỳ thanh toán này.');
|
||||
}
|
||||
|
||||
// Tính tổng tiền bao gồm addons
|
||||
$addonsPrice = 0;
|
||||
if (!empty($data['addons'])) {
|
||||
foreach ($data['addons'] as $addonData) {
|
||||
$addon = \App\Models\Addon::find($addonData['addon_id']);
|
||||
if ($addon) {
|
||||
$addonsPrice += $addon->price * ($addonData['qty'] ?? 1);
|
||||
}
|
||||
}
|
||||
// Resolve addons → enriched meta with price & subtotal
|
||||
$addonsMeta = $this->resolveAddons($data['addons'] ?? []);
|
||||
$addonsPrice = array_sum(array_column($addonsMeta, 'subtotal'));
|
||||
$total = $basePrice + $addonsPrice;
|
||||
|
||||
if ($customer->total < $total) {
|
||||
throw new Exception(sprintf(
|
||||
'Số dư không đủ. Hiện có: %s VNĐ, cần: %s VNĐ.',
|
||||
number_format($customer->total),
|
||||
number_format($total)
|
||||
));
|
||||
}
|
||||
|
||||
$totalPrice = $price + $addonsPrice;
|
||||
|
||||
// Kiểm tra số dư tài khoản (cột total) trước khi tạo đơn
|
||||
if ($customer->total < $totalPrice) {
|
||||
throw new Exception('Số dư không đủ để đặt hàng. Vui lòng nạp thêm tiền. Số dư hiện tại: ' . number_format($customer->total) . ' VNĐ, cần: ' . number_format($totalPrice) . ' VNĐ');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($data, $customer, $product, $price, $totalPrice) {
|
||||
|
||||
return DB::transaction(function () use ($data, $customer, $product, $basePrice, $total, $addonsMeta) {
|
||||
$order = $this->orderRepo->create([
|
||||
'order_num' => \App\Helpers\OrderHelper::generateOrderNumber(),
|
||||
'customer_id' => $customer->id,
|
||||
'amount' => $price,
|
||||
'status' => OrderStatus::PENDING->value
|
||||
'order_num' => OrderHelper::generateOrderNumber(),
|
||||
'customer_id' => $customer->id,
|
||||
'sub_total' => $basePrice,
|
||||
'discount_amount' => 0,
|
||||
'total' => $total,
|
||||
'status' => OrderStatus::PENDING->value,
|
||||
'client_ip' => request()?->ip(),
|
||||
]);
|
||||
|
||||
$this->orderRepo->createItem($order->id, [
|
||||
'product_id' => $product->id,
|
||||
'product_id' => $product->id,
|
||||
'billing_cycle' => $data['billing_cycle'],
|
||||
'server_name' => $data['server_name'] ?? null,
|
||||
'os_id' => $data['os_id'] ?? null,
|
||||
'price' => $price,
|
||||
'addons' => $data['addons'] ?? []
|
||||
'months' => $this->cycleToMonths($data['billing_cycle']),
|
||||
'server_name' => $data['server_name'] ?? null,
|
||||
'os_id' => $data['os_id'] ?? null,
|
||||
'quantity' => 1,
|
||||
'price' => $basePrice,
|
||||
'addons' => $addonsMeta, // serialised to addons_meta JSON
|
||||
]);
|
||||
|
||||
// Reload items so invoice repo can iterate them
|
||||
$order->load('orderItems.product');
|
||||
|
||||
$invoice = $this->invoiceRepo->createFromOrder($order);
|
||||
|
||||
return [
|
||||
'order' => $order,
|
||||
'invoice' => $invoice
|
||||
];
|
||||
return ['order' => $order, 'invoice' => $invoice];
|
||||
});
|
||||
}
|
||||
|
||||
public function pay($order, string $method)
|
||||
// =========================================================================
|
||||
// pay — Step 2: Customer pays the pending order
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Debit customer balance → mark Order+Invoice paid → provision Service records.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function pay(Order $order, string $method): Order
|
||||
{
|
||||
if (in_array($order->status, [OrderStatus::ACTIVE->value, OrderStatus::PROCESSING->value], true)) {
|
||||
throw new Exception('Đơn hàng đã được thanh toán hoặc đang xử lý.');
|
||||
@@ -96,105 +117,229 @@ class OrderService
|
||||
return DB::transaction(function () use ($order, $method) {
|
||||
$customer = $order->customer;
|
||||
|
||||
// Kiểm tra số dư và trừ tiền
|
||||
if ($customer->total < $order->amount) {
|
||||
throw new Exception('Số dư không đủ để thanh toán. Vui lòng nạp thêm tiền. Số dư hiện tại: ' . number_format($customer->total) . ' VNĐ, cần: ' . number_format($order->amount) . ' VNĐ');
|
||||
if ($customer->total < $order->total) {
|
||||
throw new Exception(sprintf(
|
||||
'Số dư không đủ. Hiện có: %s VNĐ, cần: %s VNĐ.',
|
||||
number_format($customer->total),
|
||||
number_format($order->total)
|
||||
));
|
||||
}
|
||||
|
||||
$customer->total -= $order->amount;
|
||||
// Debit balance
|
||||
$customer->total -= $order->total;
|
||||
$customer->save();
|
||||
|
||||
CustomerLog::create([
|
||||
'agent' => 'api',
|
||||
'client_ip' => request()?->ip(),
|
||||
CustomerActivityLog::create([
|
||||
'agent' => 'api',
|
||||
'client_ip' => request()?->ip(),
|
||||
'customer_id' => $customer->id,
|
||||
'description' => 'Thanh toán đơn hàng #' . $order->order_num
|
||||
. ' thành công. Số tiền: ' . number_format((int) $order->amount) . ' VNĐ'
|
||||
. '. Số dư sau thanh toán: ' . number_format((int) $customer->total) . ' VNĐ',
|
||||
'description' => sprintf(
|
||||
'Thanh toán đơn hàng #%s. Số tiền: %s VNĐ. Số dư còn: %s VNĐ.',
|
||||
$order->order_num,
|
||||
number_format($order->total),
|
||||
number_format($customer->total)
|
||||
),
|
||||
]);
|
||||
|
||||
// Cho phép thanh toán lại đơn đã hủy bằng cách đưa về pending trước khi process.
|
||||
// Allow re-paying a cancelled order
|
||||
if ($order->status === OrderStatus::CANCELLED->value) {
|
||||
$order->status = OrderStatus::PENDING->value;
|
||||
$order->save();
|
||||
$order->update(['status' => OrderStatus::PENDING->value]);
|
||||
}
|
||||
|
||||
// Mark order → ACTIVE, invoice → PAID
|
||||
$processedOrder = $this->orderRepo->processPayment($order, $method);
|
||||
|
||||
// Sau khi thanh toán, tạo module_vmware rồi dispatch CreateVMJobs.
|
||||
foreach ($order->orderItems as $item) {
|
||||
if (empty($item->product_id) || empty($item->os_id)) {
|
||||
Log::warning('Skip VM job: product_id/os_id is missing', [
|
||||
'order_id' => $order->id,
|
||||
'order_item_id' => $item->id,
|
||||
'product_id' => $item->product_id,
|
||||
'os_id' => $item->os_id,
|
||||
]);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$os = Os::with('osGroup.host')->find($item->os_id);
|
||||
|
||||
if (!$os || !$os->osGroup || !$os->osGroup->module_host_id) {
|
||||
Log::warning('Skip VM job: không tìm thấy OS/OsGroup/Host', [
|
||||
'order_id' => $order->id,
|
||||
'order_item_id' => $item->id,
|
||||
'os_id' => $item->os_id,
|
||||
]);
|
||||
continue;
|
||||
}
|
||||
|
||||
$ip = ModuleIpAddress::where('module_host_id', $os->osGroup->module_host_id)
|
||||
->where('status', 0)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (!$ip) {
|
||||
Log::warning('Skip VM job: không còn IP khả dụng', [
|
||||
'order_id' => $order->id,
|
||||
'module_host_id' => $os->osGroup->module_host_id,
|
||||
]);
|
||||
continue;
|
||||
}
|
||||
|
||||
$ip->update(['status' => 1, 'vm_name' => $item->server_name ?? 'VM-' . $order->id]);
|
||||
|
||||
$moduleVmware = ModuleVmware::create([
|
||||
'name' => $item->server_name ?? 'VM-' . $order->id,
|
||||
'module_ip_address_id' => $ip->id,
|
||||
'port' => 22,
|
||||
'order_id' => $order->id,
|
||||
'first_payment' => $order->amount,
|
||||
'next_payment' => $order->amount,
|
||||
'next_due_date' => null,
|
||||
'next_invoice' => 0,
|
||||
'user' => 'Administrator',
|
||||
'password' => '',
|
||||
'hostname' => $item->server_name ?? 'vm-' . $order->id,
|
||||
'vmware_id' => null,
|
||||
'os_id' => $item->os_id,
|
||||
'customer_id' => $order->customer_id,
|
||||
'status' => 0,
|
||||
]);
|
||||
|
||||
dispatch(new CreateVMJobs($moduleVmware->id))->delay(now()->addSeconds(10));
|
||||
|
||||
Log::info('Dispatched CreateVMJobs', [
|
||||
'order_id' => $order->id,
|
||||
'module_vmware_id' => $moduleVmware->id,
|
||||
'ip' => $ip->ip,
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Lỗi khi tạo module_vmware hoặc dispatch job', [
|
||||
'order_id' => $order->id,
|
||||
'order_item_id' => $item->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
// Provision a Service for each order item
|
||||
foreach ($processedOrder->orderItems as $item) {
|
||||
$this->provisionService($processedOrder, $item, $customer);
|
||||
}
|
||||
|
||||
return $processedOrder;
|
||||
});
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Private — provisionService
|
||||
// =========================================================================
|
||||
|
||||
private function provisionService(Order $order, OrderItem $item, $customer): void
|
||||
{
|
||||
$invoice = $order->invoice;
|
||||
$months = $item->months ?: $this->cycleToMonths($item->billing_cycle);
|
||||
$expiresAt = now()->addMonths($months);
|
||||
|
||||
$service = Service::create([
|
||||
'customer_id' => $customer->id,
|
||||
'product_id' => $item->product_id,
|
||||
'order_item_id' => $item->id,
|
||||
'invoice_id' => $invoice?->id,
|
||||
'server_name' => $item->server_name,
|
||||
'status' => 'pending',
|
||||
'auto_renew' => false,
|
||||
'started_at' => now(),
|
||||
'expires_at' => $expiresAt,
|
||||
]);
|
||||
|
||||
$this->attachServiceAddons($service, $item);
|
||||
|
||||
// VPS: requires product + os_id → dispatch VM creation job
|
||||
if ($item->product_id && $item->os_id) {
|
||||
$this->dispatchVmJob($order, $item, $service, $customer);
|
||||
} else {
|
||||
// Hosting / Domain / non-VM services activate immediately
|
||||
$service->update(['status' => 'active']);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create ServiceAddon rows from:
|
||||
* 1. Base product specs (cpu, ram, disk, bandwidth)
|
||||
* 2. Customer's configurable addon selections stored in addons_meta
|
||||
*/
|
||||
private function attachServiceAddons(Service $service, OrderItem $item): void
|
||||
{
|
||||
// 1. Base product specs
|
||||
$product = $item->product;
|
||||
if ($product) {
|
||||
foreach (['cpu' => $product->cpu, 'ram' => $product->ram, 'disk' => $product->disk, 'bandwidth' => $product->bandwidth] as $type => $value) {
|
||||
if ($value !== null && $value !== '') {
|
||||
ServiceAddon::create([
|
||||
'service_id' => $service->id,
|
||||
'addon_type' => $type,
|
||||
'addon_value' => (string) $value,
|
||||
'price' => 0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Customer-selected addons
|
||||
$addonsMeta = is_array($item->addons_meta)
|
||||
? $item->addons_meta
|
||||
: json_decode($item->addons_meta ?? '[]', true);
|
||||
|
||||
foreach ((array) $addonsMeta as $meta) {
|
||||
$addon = Addon::find($meta['addon_id'] ?? null);
|
||||
if (!$addon) {
|
||||
continue;
|
||||
}
|
||||
ServiceAddon::create([
|
||||
'service_id' => $service->id,
|
||||
'addon_type' => strtolower((string) $addon->code),
|
||||
'addon_value' => (string) ($meta['qty'] ?? 1),
|
||||
'price' => (int) ($meta['price'] ?? $addon->price),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private function dispatchVmJob(Order $order, OrderItem $item, Service $service, $customer): void
|
||||
{
|
||||
try {
|
||||
$os = Os::with('osGroup.host')->find($item->os_id);
|
||||
|
||||
if (!$os?->osGroup?->module_host_id) {
|
||||
Log::warning('dispatchVmJob: OS/OsGroup/Host not found', [
|
||||
'order_id' => $order->id,
|
||||
'os_id' => $item->os_id,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$ip = ModuleIpAddress::where('module_host_id', $os->osGroup->module_host_id)
|
||||
->where('status', 0)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (!$ip) {
|
||||
Log::warning('dispatchVmJob: no available IP', [
|
||||
'order_id' => $order->id,
|
||||
'module_host_id' => $os->osGroup->module_host_id,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$vmName = $item->server_name ?? ('VM-' . $order->id);
|
||||
$ip->update(['status' => 1, 'vm_name' => $vmName]);
|
||||
|
||||
$moduleVmware = ModuleVmware::create([
|
||||
'name' => $vmName,
|
||||
'module_ip_address_id' => $ip->id,
|
||||
'port' => 22,
|
||||
'order_id' => $order->id,
|
||||
'first_payment' => $order->total,
|
||||
'next_payment' => $order->total,
|
||||
'next_due_date' => $service->expires_at,
|
||||
'next_invoice' => 0,
|
||||
'user' => 'Administrator',
|
||||
'password' => '',
|
||||
'hostname' => strtolower($vmName),
|
||||
'vmware_id' => null,
|
||||
'os_id' => $item->os_id,
|
||||
'customer_id' => $customer->id,
|
||||
'status' => 0,
|
||||
]);
|
||||
|
||||
// Store module_vmware.id as vm_id on Service for quick lookup
|
||||
$service->update(['vm_id' => (string) $moduleVmware->id]);
|
||||
|
||||
dispatch(new CreateVMJobs($moduleVmware->id))->delay(now()->addSeconds(10));
|
||||
|
||||
Log::info('dispatchVmJob: CreateVMJobs dispatched', [
|
||||
'order_id' => $order->id,
|
||||
'service_id' => $service->id,
|
||||
'module_vmware_id' => $moduleVmware->id,
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
Log::error('dispatchVmJob: exception', [
|
||||
'order_id' => $order->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Helpers
|
||||
// =========================================================================
|
||||
|
||||
private function cycleToMonths(?string $cycle): int
|
||||
{
|
||||
return match ($cycle) {
|
||||
'monthly' => 1,
|
||||
'quarterly' => 3,
|
||||
'semi_annually' => 6,
|
||||
'annually' => 12,
|
||||
'biennially' => 24,
|
||||
'triennially' => 36,
|
||||
default => 1,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Enrich raw addon entries with resolved price & subtotal.
|
||||
*
|
||||
* Input: [['addon_id' => 1, 'qty' => 2], ...]
|
||||
* Output: [['addon_id' => 1, 'qty' => 2, 'price' => 50000, 'subtotal' => 100000], ...]
|
||||
*/
|
||||
private function resolveAddons(array $raw): array
|
||||
{
|
||||
$resolved = [];
|
||||
foreach ($raw as $entry) {
|
||||
$addon = Addon::find($entry['addon_id'] ?? null);
|
||||
if (!$addon) {
|
||||
continue;
|
||||
}
|
||||
$qty = max(1, (int) ($entry['qty'] ?? 1));
|
||||
$resolved[] = [
|
||||
'addon_id' => $addon->id,
|
||||
'qty' => $qty,
|
||||
'price' => $addon->price,
|
||||
'subtotal' => $addon->price * $qty,
|
||||
];
|
||||
}
|
||||
return $resolved;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class CompressionService
|
||||
{
|
||||
/**
|
||||
* Check compression capabilities of the client
|
||||
*/
|
||||
public static function getClientCapabilities(Request $request): array
|
||||
{
|
||||
$acceptEncoding = $request->header('Accept-Encoding', '');
|
||||
|
||||
return [
|
||||
'supports_gzip' => str_contains($acceptEncoding, 'gzip'),
|
||||
'supports_deflate' => str_contains($acceptEncoding, 'deflate'),
|
||||
'supports_brotli' => str_contains($acceptEncoding, 'br'),
|
||||
'raw_header' => $acceptEncoding,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get compression info for debugging
|
||||
*/
|
||||
public static function getCompressionInfo(string $content): array
|
||||
{
|
||||
$originalSize = strlen($content);
|
||||
$info = ['original_size' => $originalSize];
|
||||
|
||||
if (function_exists('gzencode')) {
|
||||
$gzipped = gzencode($content, 6);
|
||||
if ($gzipped !== false) {
|
||||
$gzippedSize = strlen($gzipped);
|
||||
$info['gzip'] = [
|
||||
'compressed_size' => $gzippedSize,
|
||||
'ratio' => round(($gzippedSize / $originalSize) * 100, 2) . '%',
|
||||
'savings' => round((1 - $gzippedSize / $originalSize) * 100, 2) . '%'
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if (function_exists('gzdeflate')) {
|
||||
$deflated = gzdeflate($content, 6);
|
||||
if ($deflated !== false) {
|
||||
$deflatedSize = strlen($deflated);
|
||||
$info['deflate'] = [
|
||||
'compressed_size' => $deflatedSize,
|
||||
'ratio' => round(($deflatedSize / $originalSize) * 100, 2) . '%',
|
||||
'savings' => round((1 - $deflatedSize / $originalSize) * 100, 2) . '%'
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if (function_exists('brotli_compress')) {
|
||||
$brotlied = brotli_compress($content, 6);
|
||||
if ($brotlied !== false) {
|
||||
$brotliedSize = strlen($brotlied);
|
||||
$info['brotli'] = [
|
||||
'compressed_size' => $brotliedSize,
|
||||
'ratio' => round(($brotliedSize / $originalSize) * 100, 2) . '%',
|
||||
'savings' => round((1 - $brotliedSize / $originalSize) * 100, 2) . '%'
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format bytes to human readable format
|
||||
*/
|
||||
public static function formatBytes(int $bytes, int $precision = 2): string
|
||||
{
|
||||
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
|
||||
for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
|
||||
$bytes /= 1024;
|
||||
}
|
||||
|
||||
return round($bytes, $precision) . ' ' . $units[$i];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\Product\ProductBillingCycle;
|
||||
use App\Http\Helpers\Helper;
|
||||
use App\Jobs\Hosting\CreateHostingJobs;
|
||||
use App\Jobs\VirtualMachine\Create\CreateVirtualMachineJob;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Order;
|
||||
use App\Models\OrderItem;
|
||||
use App\Models\Payment;
|
||||
use App\Repositories\Invoice\InvoiceRepositoryInterface;
|
||||
use App\Repositories\InvoiceItem\InvoiceItemRepositoryInterface;
|
||||
use App\Repositories\Module\Hosting\HostingRepositoryInterface as ModuleHostingRepositoryInterface;
|
||||
use App\Repositories\Module\Vmware\VmwareRepositoryInterface;
|
||||
use App\Repositories\Order\OrderRepositoryInterface;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class OrderService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly OrderRepositoryInterface $orderRepository,
|
||||
private readonly InvoiceRepositoryInterface $invoiceRepository,
|
||||
private readonly InvoiceItemRepositoryInterface $invoiceItemRepository,
|
||||
private readonly ModuleHostingRepositoryInterface $moduleHostingRepository,
|
||||
private readonly VmwareRepositoryInterface $moduleVmwareRepository,
|
||||
) {}
|
||||
|
||||
public function createOrder(array $data): Order
|
||||
{
|
||||
$customer = Customer::find($data['customer_id']);
|
||||
if (!$customer || (int) $customer->status !== 1) {
|
||||
throw new \InvalidArgumentException('Tài khoản khách hàng không hoạt động. Không thể tạo đơn hàng.');
|
||||
}
|
||||
|
||||
$paymentRecord = Payment::find((int) $data['payment_method']);
|
||||
$isBankTransfer = $paymentRecord && (int) $paymentRecord->type === 1;
|
||||
|
||||
[$productItems, $relIdData, $total] = $this->buildProductItems($data);
|
||||
|
||||
$invoiceData = [
|
||||
'date' => Carbon::today()->toDateString(),
|
||||
'due_date' => Carbon::today()->toDateString(),
|
||||
'date_paid' => (int) $data['status'] === 1 ? Carbon::today()->toDateString() : null,
|
||||
'sub_total' => $total,
|
||||
'tax' => $total * (10 / 100),
|
||||
'total' => $total + ($total * (10 / 100)),
|
||||
'payment_method' => $paymentRecord?->id,
|
||||
'customer_id' => ($data['create_invoice'] ?? false) ? $data['customer_id'] : 0,
|
||||
'status' => $data['status'],
|
||||
];
|
||||
|
||||
$orderData = [
|
||||
'order_num' => Helper::generateUniqueCode(),
|
||||
'customer_id' => $data['customer_id'],
|
||||
'discount_id' => $data['discount_id'] ?? null,
|
||||
'sub_total' => $total,
|
||||
'total' => $total + ($total * (10 / 100)),
|
||||
'payment_method' => $paymentRecord?->code ?? null,
|
||||
'payment_proof' => $data['payment_proof'] ?? null,
|
||||
'user_id' => Auth::guard('admin')->id(),
|
||||
'status' => $data['status'],
|
||||
'client_ip' => request()->getClientIp(),
|
||||
];
|
||||
|
||||
return DB::transaction(function () use ($invoiceData, $orderData, $productItems, $relIdData, $data, $total, $isBankTransfer) {
|
||||
$invoice = $this->invoiceRepository->create($invoiceData);
|
||||
|
||||
$productItems = array_map(fn ($item) => array_merge($item, ['invoice_id' => $invoice->id]), $productItems);
|
||||
|
||||
if ($data['create_invoice'] ?? false) {
|
||||
$orderData['invoice_id'] = $invoice->id;
|
||||
}
|
||||
|
||||
$order = $this->orderRepository->create($orderData);
|
||||
|
||||
$relIdData = array_map(function ($item) use ($order) {
|
||||
$item['data']['order_id'] = $order->id;
|
||||
return $item;
|
||||
}, $relIdData);
|
||||
|
||||
$this->createModules($relIdData);
|
||||
|
||||
$invoiceItemData = array_map(
|
||||
fn ($item) => \Illuminate\Support\Arr::except($item, ['billing_cycle', 'code']),
|
||||
$productItems
|
||||
);
|
||||
$this->invoiceItemRepository->insert($invoiceItemData);
|
||||
|
||||
$now = now();
|
||||
OrderItem::insert(array_map(fn ($item) => [
|
||||
'order_id' => $order->id,
|
||||
'product_id' => $item['product_id'],
|
||||
'billing_cycle' => $item['billing_cycle'],
|
||||
'months' => $item['months'],
|
||||
'os_id' => $item['os_id'],
|
||||
'quantity' => $item['quantity'],
|
||||
'server_name' => $item['server_name'],
|
||||
'price' => $item['price'],
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
], $productItems));
|
||||
|
||||
$vpsTypes = ['vps', 'cloud'];
|
||||
foreach (OrderItem::where('order_id', $order->id)->get() as $orderItem) {
|
||||
if (in_array($orderItem->product?->product_type, $vpsTypes)) {
|
||||
CreateVirtualMachineJob::dispatch($orderItem)->delay(now()->addSeconds(10));
|
||||
}
|
||||
}
|
||||
|
||||
if (!$isBankTransfer) {
|
||||
$orderTotal = (int) ($total + ($total * (10 / 100)));
|
||||
$customer = Customer::lockForUpdate()->find($data['customer_id']);
|
||||
|
||||
if ($customer->total < $orderTotal) {
|
||||
throw new \Exception('Số dư tài khoản không đủ để thanh toán đơn hàng.');
|
||||
}
|
||||
|
||||
$customer->decrement('total', $orderTotal);
|
||||
}
|
||||
|
||||
return $order;
|
||||
});
|
||||
}
|
||||
|
||||
private function buildProductItems(array $data): array
|
||||
{
|
||||
$total = 0;
|
||||
$productItems = [];
|
||||
$relIdData = [];
|
||||
|
||||
foreach ($data['product'] as $key => $item) {
|
||||
$product = \App\Models\Product::with('category')->find($item['product_id']);
|
||||
|
||||
if (!$product) {
|
||||
throw new \InvalidArgumentException("Sản phẩm không tồn tại (ID: {$item['product_id']}).");
|
||||
}
|
||||
|
||||
$moduleType = match ($product->product_type) {
|
||||
'hosting' => 3,
|
||||
'vps' => 4,
|
||||
default => 0,
|
||||
};
|
||||
|
||||
$billingDetails = $this->calculateBillingDetails($item['billing']);
|
||||
$priceSelect = $item['price_custom'] ?? $product->price_sale ?? $product->price;
|
||||
|
||||
$billingCycle = ProductBillingCycle::fromLegacyCode((int) $item['billing']);
|
||||
$generalCode = Helper::generateUniqueCode();
|
||||
|
||||
$productItems[$key] = [
|
||||
'product_id' => $product->id,
|
||||
'product_type' => $product->product_type,
|
||||
'months' => $billingCycle->months(),
|
||||
'billing_cycle' => $billingCycle->value,
|
||||
'os_id' => $item['os_id'] ?? null,
|
||||
'quantity' => (int) ($item['quantity'] ?? 1),
|
||||
'server_name' => $item['domain'] ?? null,
|
||||
'price' => (int) $priceSelect,
|
||||
'invoice_type' => 1,
|
||||
'code' => $generalCode,
|
||||
];
|
||||
|
||||
$relIdData[$key] = [
|
||||
'type' => $moduleType,
|
||||
'code' => $generalCode,
|
||||
'data' => [
|
||||
'customer_id' => $data['customer_id'],
|
||||
'status' => 0,
|
||||
'name' => $item['domain'] ?? $product->name,
|
||||
'first_payment' => $priceSelect * $billingDetails['billing'],
|
||||
'next_payment' => ($item['price_custom'] ?? $product->price) * $billingDetails['billing'],
|
||||
...$billingDetails,
|
||||
],
|
||||
];
|
||||
|
||||
if ($item['quantity'] > 1) {
|
||||
for ($i = 1; $i < $item['quantity']; $i++) {
|
||||
$newCode = Helper::generateUniqueCode();
|
||||
$productItems[] = array_merge($productItems[$key], ['code' => $newCode]);
|
||||
$relIdData[] = array_merge($relIdData[$key], ['code' => $newCode]);
|
||||
}
|
||||
}
|
||||
|
||||
$total += $item['quantity'] * ($item['price_custom'] ?? ($product->price_sale ?? $product->price)) * $billingDetails['billing'];
|
||||
}
|
||||
|
||||
return [$productItems, $relIdData, $total];
|
||||
}
|
||||
|
||||
private function createModules(array $relIdData): void
|
||||
{
|
||||
foreach ($relIdData as $item) {
|
||||
match ($item['type']) {
|
||||
3 => $this->moduleHostingRepository->create($item['data']),
|
||||
4 => $this->moduleVmwareRepository->create(array_merge($item['data'], ['status' => 2])),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private function calculateBillingDetails(int|string $billing): array
|
||||
{
|
||||
$months = match ((int) $billing) {
|
||||
2 => 1,
|
||||
3 => 3,
|
||||
4 => 6,
|
||||
5 => 12,
|
||||
default => 0,
|
||||
};
|
||||
|
||||
return [
|
||||
'next_due_date' => $months ? Carbon::today()->addMonths($months)->timestamp : null,
|
||||
'next_invoice' => $months ? Carbon::today()->addMonths($months)->timestamp : null,
|
||||
'billing' => $months ?: 1,
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user