59 lines
1.4 KiB
PHP
59 lines
1.4 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Invoice;
|
|
use App\Models\InvoiceItem;
|
|
use Barryvdh\DomPDF\Facade\Pdf;
|
|
use Illuminate\Http\Response;
|
|
|
|
final class InvoiceService
|
|
{
|
|
public function create(array $data, array $items): Invoice
|
|
{
|
|
$invoice = Invoice::create([
|
|
...$data,
|
|
'invoice_number' => Invoice::generateNumber(),
|
|
'subtotal' => 0,
|
|
'tax_amount' => 0,
|
|
'total' => 0,
|
|
]);
|
|
|
|
foreach ($items as $item) {
|
|
$item['total'] = $item['quantity'] * $item['unit_price'];
|
|
$invoice->items()->create($item);
|
|
}
|
|
|
|
$invoice->recalculate();
|
|
|
|
return $invoice;
|
|
}
|
|
|
|
public function update(Invoice $invoice, array $data, array $items): Invoice
|
|
{
|
|
$invoice->update($data);
|
|
$invoice->items()->delete();
|
|
|
|
foreach ($items as $item) {
|
|
$item['total'] = $item['quantity'] * $item['unit_price'];
|
|
$invoice->items()->create($item);
|
|
}
|
|
|
|
$invoice->recalculate();
|
|
|
|
return $invoice->fresh();
|
|
}
|
|
|
|
public function generatePdf(Invoice $invoice): Response
|
|
{
|
|
$invoice->load('client', 'items');
|
|
|
|
$pdf = Pdf::loadView('invoices.pdf', compact('invoice'));
|
|
$pdf->setPaper('A4', 'portrait');
|
|
|
|
return $pdf->download("invoice-{$invoice->invoice_number}.pdf");
|
|
}
|
|
}
|