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

68 lines
1.9 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 Exception;
class OrderService
{
public function __construct(
protected OrderRepository $orderRepo,
protected ServiceRepository $productRepo,
protected InvoiceRepository $invoiceRepo
) {}
public function create(array $data, $customer)
{
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([
'customer_id' => $customer->id,
'amount' => $price,
'status' => 'pending'
]);
$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
]);
$invoice = $this->invoiceRepo->createFromOrder($order);
return [
'order' => $order,
'invoice' => $invoice
];
});
}
public function pay($order, string $method)
{
if ($order->status === 'paid') {
throw new Exception('Đơn hàng đã thanh toán');
}
return $this->orderRepo->processPayment($order, $method);
}
}