Files
portal-api/app/Services/Api/Order/OrderService.php
T

76 lines
2.4 KiB
PHP

<?php
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;
class OrderService
{
public function __construct(
protected OrderRepository $orderRepo,
protected ServiceRepository $productRepo,
protected InvoiceRepository $invoiceRepo
) {}
public function create(array $data, $customer)
{
// 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.');
}
return DB::transaction(function () use ($data, $customer) {
$product = $this->productRepo->find($data['product_id']);
if (!$product) {
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');
}
$order = $this->orderRepo->create([
'order_num' => \App\Helpers\OrderHelper::generateOrderNumber(),
'customer_id' => $customer->id,
'amount' => $price,
'status' => OrderStatus::PENDING->value
]);
$this->orderRepo->createItem($order->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'] ?? []
]);
$invoice = $this->invoiceRepo->createFromOrder($order);
return [
'order' => $order,
'invoice' => $invoice
];
});
}
public function pay($order, string $method)
{
if ($order->status !== OrderStatus::PENDING->value) {
throw new Exception('Đơn hàng đã được xử lý hoặc hủy bỏ.');
}
return $this->orderRepo->processPayment($order, $method);
}
}