Files
portal-api/app/Repositories/Api/Invoice/InvoiceRepository.php
T

80 lines
2.8 KiB
PHP

<?php
namespace App\Repositories\Api\Invoice;
use App\Models\Invoice;
use App\Repositories\Api\BaseApiRepository;
class InvoiceRepository extends BaseApiRepository implements InvoiceRepositoryInterface
{
public function getModel()
{
return Invoice::class;
}
/**
* Lấy danh sách sản phẩm đang hoạt động
*/
public function getInvoice(int $limit = 10, $customer = null)
{
return $this->model->where('customer_id', $customer)->paginate($limit);
}
public function createFromOrder($order)
{
$invoice = $this->model->create([
'customer_id' => $order->customer_id,
'order_id' => $order->id,
'order_num' => \App\Helpers\OrderHelper::generateOrderNumber('INV'),
'date' => now(),
'due_date' => now()->addDays(3),
'total' => $order->amount,
'sub_total' => $order->amount,
'tax' => 0,
'status' => 1, // Unpaid
]);
$order->update(['invoice_id' => $invoice->id]);
$orderItems = $order->orderItems;
if ($orderItems->isEmpty()) {
$orderItems = $order->orderItems()->get();
}
foreach ($orderItems as $item) {
$invoiceItem = \App\Models\InvoiceItem::create([
'invoice_id' => $invoice->id,
// 'customer_id' removed as not in migration
'product_id' => $item->product_id,
// 'description' removed as not in migration
'price' => $item->price ?? $order->amount,
// 'type_id' removed, use 'product_type'
'product_type' => $item->product->product_type instanceof \App\Enums\Product\ProductTypeEnums
? $item->product->product_type->value
: (\App\Enums\Product\ProductTypeEnums::tryFrom($item->product->product_type)?->value ?? 1),
// 'billing' removed, map to 'months' if possible? default 0 in migration
'months' => match ($item->billing_cycle) {
'quarterly' => 3,
'semi_annually' => 6,
'annually' => 12,
default => 1,
},
'server_name' => $item->server_name,
'os_id' => $item->os_id,
]);
// Copy addons from OrderItem to InvoiceItem
foreach ($item->addons as $addon) {
\App\Models\InvoiceAddons::create([
'invoice_item_id' => $invoiceItem->id,
'addon_id' => $addon->addon_id,
'qty' => $addon->qty,
'price' => $addon->price // Unit price preserved from order
]);
}
}
return $invoice;
}
}