53 lines
1.6 KiB
PHP
53 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Http\Option;
|
|
use App\Models\Invoice;
|
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
|
|
|
class EController extends Controller
|
|
{
|
|
/**
|
|
* Return an invoice as download for the specified resource.
|
|
*/
|
|
public function downloadInvoice(int $id): StreamedResponse
|
|
{
|
|
$invoice = Invoice::find($id);
|
|
$taxes = self::buildTaxes($invoice->items);
|
|
|
|
return response()->streamDownload(function () use ($invoice, $taxes) {
|
|
echo view('xml.invoice', ['invoice' => $invoice, 'options' => Option::optionsAsObject(), 'taxes' => $taxes]);
|
|
}, 'test.xml', ['Content-Type' => 'application/xml']);
|
|
|
|
}
|
|
|
|
/**
|
|
* Return a rendered xml invoice as string to build an email attachment from it for the specified resource.
|
|
*/
|
|
public function attachInvoice(int $id): string
|
|
{
|
|
$invoice = Invoice::find($id);
|
|
$taxes = self::buildTaxes($invoice->items);
|
|
|
|
return view('xml.invoice', ['invoice' => $invoice, 'options' => Option::optionsAsObject(), 'taxes' => $taxes])->render();
|
|
}
|
|
|
|
/**
|
|
* Build taxes for the given invoice items grouped by tax.
|
|
*/
|
|
private static function buildTaxes($items): array
|
|
{
|
|
$taxes = [];
|
|
foreach ($items as $item) {
|
|
if (!isset($taxes[$item->tax])) {
|
|
$taxes[$item->tax] = ['tax' => 0, 'taxable' => 0];
|
|
}
|
|
$taxes[$item->tax]['tax'] += round($item->price * $item->amount * $item->tax / 100, 2, PHP_ROUND_HALF_UP);
|
|
$taxes[$item->tax]['taxable'] += $item->price * $item->amount;
|
|
}
|
|
|
|
return $taxes;
|
|
}
|
|
}
|