Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions Core/Assets/JS/PDFViewer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* This file is part of FacturaScripts
* Copyright (C) 2026 Carlos Garcia Gomez <carlos@facturascripts.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

function fsPdfPreviewModal(labels) {
const existing = document.getElementById('fsPdfPreviewModal');
if (existing) {
return existing;
}

const modalHTML = `
<div class="modal fade" id="fsPdfPreviewModal" tabindex="-1" aria-labelledby="fsPdfPreviewModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="fsPdfPreviewModalLabel">${labels.title}</h5>
<div class="ms-auto me-2">
<button type="button" id="fsPdfPreviewPrintBtn" class="btn btn-secondary me-1">
<i class="fa-solid fa-print fa-fw"></i> ${labels.print}
</button>
<button type="button" id="fsPdfPreviewDownloadBtn" class="btn btn-primary">
<i class="fa-solid fa-download fa-fw"></i> ${labels.download}
</button>
</div>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body p-0">
<iframe id="fsPdfPreviewFrame" style="width: 100%; height: 75vh; border: 0; display: block;"></iframe>
</div>
</div>
</div>
</div>
`;
document.body.insertAdjacentHTML('beforeend', modalHTML);

const modalEl = document.getElementById('fsPdfPreviewModal');
const frame = document.getElementById('fsPdfPreviewFrame');

document.getElementById('fsPdfPreviewPrintBtn').addEventListener('click', function () {
if (frame.contentWindow && typeof frame.contentWindow.fsPrint === 'function') {
frame.contentWindow.fsPrint();
}
});

document.getElementById('fsPdfPreviewDownloadBtn').addEventListener('click', function () {
if (!frame.contentWindow || typeof frame.contentWindow.fsDownloadPdf !== 'function') {
return;
}

const btn = this;
const original = btn.innerHTML;
btn.disabled = true;
btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> ' + labels.generating;
frame.contentWindow.fsDownloadPdf(modalEl.dataset.filename || null).then(function () {
btn.disabled = false;
btn.innerHTML = original;
}).catch(function () {
btn.disabled = false;
btn.innerHTML = original;
});
});

return modalEl;
}

function fsShowPdfPreview(extraData = {}, filename = '', labels = {}) {
labels = Object.assign({
title: 'PDF',
print: 'Print',
download: 'PDF',
generating: '...'
}, labels);

const modalEl = fsPdfPreviewModal(labels);
modalEl.dataset.filename = filename;

animateSpinner('add');
$.ajax({
method: 'POST',
url: window.location.href,
data: Object.assign({action: 'pdf-preview'}, extraData),
dataType: 'html',
success: function (html) {
animateSpinner('remove');
document.getElementById('fsPdfPreviewFrame').srcdoc = html;
bootstrap.Modal.getOrCreateInstance(modalEl).show();
},
error: function () {
animateSpinner('remove', false);
}
});
}
59 changes: 59 additions & 0 deletions Core/Controller/EditEmpresa.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
use FacturaScripts\Core\Lib\ExtendedController\EditController;
use FacturaScripts\Core\Tools;
use FacturaScripts\Core\Where;
use FacturaScripts\Core\Lib\PDF\Dynamic\PDFBuilder;
use FacturaScripts\Core\Lib\PDF\Dynamic\PDFPreviewTrait;
use FacturaScripts\Dinamic\Lib\RegimenIVA;

/**
Expand All @@ -34,6 +36,8 @@
*/
class EditEmpresa extends EditController
{
use PDFPreviewTrait;

public function getModelClassName(): string
{
return 'Empresa';
Expand All @@ -48,6 +52,57 @@ public function getPageData(): array
return $data;
}

protected function buildPdf(): PDFBuilder
{
$empresa = $this->getModel();
$empresa->loadFromCode($this->request->input('code'));
$i18n = Tools::lang();

$doc = PDFBuilder::create()
->setTitle($empresa->nombrecorto ?? $empresa->nombre ?? 'company')
->addDocumentHeader($empresa)
->addTitle($i18n->trans('company') . ': ' . $empresa->nombre)
->addHtml('<hr/>')
->addParallelTable([
$i18n->trans('name') => $empresa->nombre,
$i18n->trans('short-name') => $empresa->nombrecorto,
$i18n->trans('fiscal-id') => $empresa->tipoidfiscal,
$i18n->trans('fiscal-number') => $empresa->cifnif,
$i18n->trans('address') => $empresa->direccion,
$i18n->trans('zip-code') => $empresa->codpostal,
$i18n->trans('city') => $empresa->ciudad,
$i18n->trans('province') => $empresa->provincia,
$i18n->trans('country') => $empresa->codpais,
$i18n->trans('phone') => $empresa->telefono1,
$i18n->trans('phone2') => $empresa->telefono2,
$i18n->trans('fax') => $empresa->fax,
$i18n->trans('email') => $empresa->email,
$i18n->trans('web') => $empresa->web,
$i18n->trans('admin') => $empresa->administrador,
$i18n->trans('start-date') => $empresa->fechaalta,
]);

// las vistas relacionadas, como hace el export original con cada pestaña
foreach (['EditAlmacen', 'ListCuentaBanco', 'ListFormaPago', 'ListEjercicio'] as $viewName) {
$view = $this->views[$viewName] ?? null;
if (null === $view) {
continue;
}

$modelClass = get_class($view->model);
$cursor = $modelClass::all([Where::eq('idempresa', $empresa->idempresa)]);
if (empty($cursor)) {
continue;
}

$doc->addSpacer(3)
->addTitle($view->title, 2)
->addModelTable($cursor, $view->getColumns());
}

return $doc->addPageFooter('1 / 1', $i18n->trans('generated-at', ['%when%' => Tools::dateTime()]));
}

protected function checkViesAction(): bool
{
$model = $this->getModel();
Expand All @@ -66,6 +121,7 @@ protected function checkViesAction(): bool
protected function createViews()
{
parent::createViews();
$this->loadPdfViewerAssets();

$this->createViewWarehouse();
$this->createViewBankAccounts();
Expand Down Expand Up @@ -103,6 +159,9 @@ protected function execPreviousAction($action): bool
case 'check-vies':
return $this->checkViesAction();

case 'pdf-preview':
return $this->pdfPreviewAction();

default:
return parent::execPreviousAction($action);
}
Expand Down
145 changes: 145 additions & 0 deletions Core/Controller/EditFacturaCliente.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@
namespace FacturaScripts\Core\Controller;

use FacturaScripts\Core\Lib\ExtendedController\BaseView;
use FacturaScripts\Core\Lib\PDF\Dynamic\ModelTableHelper;
use FacturaScripts\Core\Lib\PDF\Dynamic\PDFBuilder;
use FacturaScripts\Core\Lib\PDF\Dynamic\PDFPreviewTrait;
use FacturaScripts\Core\Tools;
use FacturaScripts\Core\Where;
use FacturaScripts\Dinamic\Model\Empresa;
use FacturaScripts\Dinamic\Lib\Accounting\InvoiceToAccounting;
use FacturaScripts\Dinamic\Lib\AjaxForms\SalesController;
use FacturaScripts\Dinamic\Lib\Calculator;
Expand All @@ -22,6 +26,8 @@
*/
class EditFacturaCliente extends SalesController
{
use PDFPreviewTrait;

private const VIEW_ACCOUNTS = 'ListAsiento';
private const VIEW_RECEIPTS = 'ListReciboCliente';

Expand All @@ -46,6 +52,7 @@ public function getPageData(): array
protected function createViews(): void
{
parent::createViews();
$this->loadPdfViewerAssets();

$this->createViewsReceipts();
$this->createViewsAccounting();
Expand Down Expand Up @@ -128,6 +135,9 @@ private function createViewsReceipts(string $viewName = self::VIEW_RECEIPTS): vo
protected function execPreviousAction($action)
{
switch ($action) {
case 'pdf-preview':
return $this->pdfPreviewAction();

case 'generate-accounting':
return $this->generateAccountingAction();

Expand All @@ -144,6 +154,141 @@ protected function execPreviousAction($action)
return parent::execPreviousAction($action);
}

protected function buildPdf(): PDFBuilder
{
$invoice = new FacturaCliente();
$invoice->load($this->request->queryOrInput('code'));
$i18n = Tools::lang();

$empresa = new Empresa();
$empresa->load($invoice->idempresa);

// cabecera general + datos del documento, como insertBusinessDocHeader()
$subject = $invoice->getSubject();
$doc = PDFBuilder::create()
->setTitle($invoice->codigo)
->addDocumentHeader($empresa)
->addTitle($i18n->trans('invoice') . ': ' . $invoice->codigo)
->addHtml('<hr/>')
->addParallelTable([
$i18n->trans('customer') => $invoice->nombrecliente,
$i18n->trans('date') => $invoice->fecha,
$i18n->trans('address') => $this->pdfDocAddress($invoice),
$i18n->trans('code') => $invoice->codigo,
$subject->tipoidfiscal ?: $i18n->trans('cifnif') => $invoice->cifnif,
$i18n->trans('number') => $invoice->numero,
$i18n->trans('serie') => $invoice->getSerie()->descripcion,
])
->addSpacer(3);

// líneas del documento, como insertBusinessDocBody()
$titles = [
'referencia' => $i18n->trans('reference') . ' - ' . $i18n->trans('description'),
'cantidad' => $i18n->trans('quantity'),
'pvpunitario' => $i18n->trans('price'),
'dtopor' => $i18n->trans('dto'),
'dtopor2' => $i18n->trans('dto-2'),
'pvptotal' => $i18n->trans('net'),
'iva' => $i18n->trans('tax'),
'recargo' => $i18n->trans('re'),
'irpf' => $i18n->trans('irpf'),
];
$alignments = array_fill_keys(array_keys($titles), 'right');
$alignments['referencia'] = 'left';

$rows = [];
foreach ($invoice->getLines() as $line) {
$rows[] = [
'referencia' => empty($line->referencia) ? $line->descripcion : $line->referencia . ' - ' . $line->descripcion,
'cantidad' => Tools::number($line->cantidad),
'pvpunitario' => Tools::number($line->pvpunitario),
'dtopor' => Tools::number($line->dtopor) . '%',
'dtopor2' => Tools::number($line->dtopor2) . '%',
'pvptotal' => Tools::number($line->pvptotal),
'iva' => Tools::number($line->iva) . '%',
'recargo' => Tools::number($line->recargo) . '%',
'irpf' => Tools::number($line->irpf) . '%',
];
}

$zero = Tools::number(0);
ModelTableHelper::removeEmptyColumns($rows, $titles, $alignments, [$zero, $zero . '%']);
$doc->addTable(array_map('array_values', $rows), array_values($titles), array_values($alignments));

// totales, como insertBusinessDocFooter()
$totalTitles = [
'net' => $i18n->trans('net'),
'taxes' => $i18n->trans('taxes'),
'totalSurcharge' => $i18n->trans('re'),
'totalIrpf' => $i18n->trans('retention'),
'totalSupplied' => $i18n->trans('supplied-amount'),
'total' => $i18n->trans('total'),
];
$totalAlignments = array_fill_keys(array_keys($totalTitles), 'right');
$totalRows = [[
'net' => Tools::number($invoice->neto),
'taxes' => Tools::number($invoice->totaliva),
'totalSurcharge' => Tools::number($invoice->totalrecargo),
'totalIrpf' => Tools::number(0 - $invoice->totalirpf),
'totalSupplied' => Tools::number($invoice->totalsuplidos),
'total' => Tools::number($invoice->total),
]];
ModelTableHelper::removeEmptyColumns($totalRows, $totalTitles, $totalAlignments, [$zero]);
$doc->addSpacer(3)
->addTable(array_map('array_values', $totalRows), array_values($totalTitles), array_values($totalAlignments));

// recibos, como insertInvoiceReceipts()
$receiptRows = [];
foreach ($invoice->getReceipts() as $receipt) {
$receiptRows[] = [
$receipt->numero,
Tools::number($receipt->importe),
Tools::date($receipt->vencimiento),
$i18n->trans($receipt->pagado ? 'paid' : 'unpaid'),
];
}

if (false === empty($receiptRows)) {
$doc->addSpacer(3)
->addTitle($i18n->trans('receipts'), 3)
->addTable($receiptRows, [
$i18n->trans('receipt'),
$i18n->trans('amount'),
$i18n->trans('expiration'),
$i18n->trans('status'),
], ['left', 'right', 'right', 'right']);
}

if (false === empty($invoice->observaciones)) {
$doc->addSpacer(3)
->addTitle($i18n->trans('observations'), 3)
->addText($invoice->observaciones);
}

// aviso de factura no emitida, como el export original
if ($invoice->editable) {
$doc->addWatermarkText($i18n->trans('sketch-invoice-warning'));
}

return $doc->addPageFooter('1 / 1', $i18n->trans('generated-at', ['%when%' => Tools::dateTime()]));
}

private function pdfDocAddress(FacturaCliente $invoice): string
{
$address = $invoice->direccion ?? '';
if (!empty($invoice->codpostal)) {
$address .= empty($address) ? $invoice->codpostal : ', ' . $invoice->codpostal;
}
if (!empty($invoice->ciudad)) {
$address .= empty($address) ? $invoice->ciudad : ', ' . $invoice->ciudad;
}
if (!empty($invoice->provincia)) {
$address .= ' (' . $invoice->provincia . ')';
}

return $address;
}

private function generateAccountingAction(): bool
{
$invoice = new FacturaCliente();
Expand Down
Loading
Loading