Eliminate popup when downloading xml invoices.

This commit is contained in:
2025-02-03 12:44:59 +01:00
parent 588b56d71e
commit 33c0a421c9
5 changed files with 32 additions and 6 deletions

View File

@@ -0,0 +1,53 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
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) * (100 - $item->discount) / 100, 2, PHP_ROUND_HALF_UP);
$taxes[$item->tax]['taxable'] += $item->price * $item->amount * (100 - $item->discount) / 100;
}
return $taxes;
}
}