From 354437ffd2fcb03bbf5122f970863529e1d7c17a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20S=C3=A1nchez?= Date: Tue, 10 Nov 2026 16:38:08 +0100 Subject: [PATCH 1/2] =?UTF-8?q?A=C3=B1ade=20generador=20de=20documentos=20?= =?UTF-8?q?de=20negocio=20y=20carga=20de=20extensiones?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://facturascripts.com/roadmap/5452 - Se crea la clase BusinessDocumentGenerator para gestionar la herencia de la propiedad excluir347 en documentos generados. - Se añade la carga de la nueva extensión BusinessDocumentGenerator en Init.php. - Se implementan pruebas unitarias en BusinessDocumentGeneratorTest.php para verificar el comportamiento esperado al generar facturas desde pedidos y albaranes. --- Extension/Lib/BusinessDocumentGenerator.php | 58 ++++++ Init.php | 4 + Test/main/BusinessDocumentGeneratorTest.php | 199 ++++++++++++++++++++ 3 files changed, 261 insertions(+) create mode 100644 Extension/Lib/BusinessDocumentGenerator.php create mode 100644 Test/main/BusinessDocumentGeneratorTest.php diff --git a/Extension/Lib/BusinessDocumentGenerator.php b/Extension/Lib/BusinessDocumentGenerator.php new file mode 100644 index 0000000..ae64425 --- /dev/null +++ b/Extension/Lib/BusinessDocumentGenerator.php @@ -0,0 +1,58 @@ + + * + * 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 . + */ + +namespace FacturaScripts\Plugins\Modelo347\Extension\Lib; + +use Closure; + +/** + * Extensión del generador de documentos de negocio. + * - generateBefore: hereda excluir347 de la ficha del cliente o proveedor + * cuando la factura se genera desde un documento que no tiene esa columna + * (pedidos y albaranes), ya que en ese caso no se llama a setSubject(). + * + * @author Esteban Sánchez Martínez + */ +class BusinessDocumentGenerator +{ + /** + * Copia excluir347 del cliente o proveedor al nuevo documento antes de guardarlo. + * + * No hace nada si el nuevo documento no tiene la columna, si el documento + * de origen ya la tiene (su valor ya se ha copiado) o si el valor se ha + * indicado expresamente en las propiedades de la generación. + * + * @return Closure + */ + public function generateBefore(): Closure + { + return function ($prototype, $lines, $quantity, $properties, $newDoc) { + if (false === $newDoc->hasColumn('excluir347') + || $prototype->hasColumn('excluir347') + || array_key_exists('excluir347', $properties)) { + return; + } + + $subject = $newDoc->getSubject(); + if ($subject->exists() && $subject->hasColumn('excluir347')) { + $newDoc->excluir347 = (bool)$subject->excluir347; + } + }; + } +} diff --git a/Init.php b/Init.php index ea747c4..ed1fb2a 100644 --- a/Init.php +++ b/Init.php @@ -33,9 +33,13 @@ */ final class Init extends InitClass { + /** + * Carga las extensiones, mods y workers del plugin. + */ public function init(): void { // extensiones + $this->loadExtension(new Extension\Lib\BusinessDocumentGenerator()); $this->loadExtension(new Extension\Model\Cliente()); $this->loadExtension(new Extension\Model\FacturaCliente()); $this->loadExtension(new Extension\Model\FacturaProveedor()); diff --git a/Test/main/BusinessDocumentGeneratorTest.php b/Test/main/BusinessDocumentGeneratorTest.php new file mode 100644 index 0000000..5ef8d83 --- /dev/null +++ b/Test/main/BusinessDocumentGeneratorTest.php @@ -0,0 +1,199 @@ + + * + * 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 . + */ + +namespace FacturaScripts\Test\Plugins; + +use FacturaScripts\Core\Lib\Calculator; +use FacturaScripts\Core\Model\Base\BusinessDocument; +use FacturaScripts\Dinamic\Lib\BusinessDocumentGenerator; +use FacturaScripts\Dinamic\Model\AlbaranProveedor; +use FacturaScripts\Dinamic\Model\Cliente; +use FacturaScripts\Dinamic\Model\PedidoCliente; +use FacturaScripts\Dinamic\Model\Proveedor; +use FacturaScripts\Test\Traits\DefaultSettingsTrait; +use FacturaScripts\Test\Traits\LogErrorsTrait; +use PHPUnit\Framework\TestCase; +use Throwable; + +/** + * Comprueba que las facturas generadas desde pedidos o albaranes heredan + * excluir347 de la ficha del cliente o proveedor. + * + * @author Esteban Sánchez Martínez + */ +final class BusinessDocumentGeneratorTest extends TestCase +{ + use DefaultSettingsTrait; + use LogErrorsTrait; + + /** @var array Registros creados en cada test, en orden de borrado. */ + private array $created = []; + + public static function setUpBeforeClass(): void + { + self::setDefaultSettings(); + self::installAccountingPlan(); + self::removeTaxRegularization(); + } + + /** + * Factura de cliente generada desde un pedido de un cliente excluido del 347. + */ + public function testInvoiceFromCustomerOrderInheritsExclusion(): void + { + $customer = $this->createCustomer(true); + $order = $this->createDocument(new PedidoCliente(), $customer); + + $invoice = $this->generate($order, 'FacturaCliente'); + $this->assertTrue($invoice->excluir347, 'invoice-must-inherit-excluir347'); + } + + /** + * Factura de cliente generada desde un pedido de un cliente no excluido. + */ + public function testInvoiceFromCustomerOrderNotExcluded(): void + { + $customer = $this->createCustomer(false); + $order = $this->createDocument(new PedidoCliente(), $customer); + + $invoice = $this->generate($order, 'FacturaCliente'); + $this->assertFalse($invoice->excluir347, 'invoice-must-not-be-excluded'); + } + + /** + * El valor indicado expresamente en las propiedades de la generación prevalece sobre la ficha. + */ + public function testExplicitPropertyIsRespected(): void + { + $customer = $this->createCustomer(true); + $order = $this->createDocument(new PedidoCliente(), $customer); + + $invoice = $this->generate($order, 'FacturaCliente', ['excluir347' => false]); + $this->assertFalse($invoice->excluir347, 'explicit-property-must-be-respected'); + } + + /** + * Factura de proveedor generada desde un albarán de un proveedor excluido del 347. + */ + public function testInvoiceFromSupplierDeliveryNoteInheritsExclusion(): void + { + $supplier = $this->createSupplier(true); + $deliveryNote = $this->createDocument(new AlbaranProveedor(), $supplier); + + $invoice = $this->generate($deliveryNote, 'FacturaProveedor'); + $this->assertTrue($invoice->excluir347, 'invoice-must-inherit-excluir347'); + } + + protected function tearDown(): void + { + // borramos en orden inverso de creación; cada borrado aislado para no dejar restos + foreach (array_reverse($this->created) as $item) { + try { + if ($item->exists()) { + $item->delete(); + } + } catch (Throwable $e) { + // ignoramos el error para seguir limpiando el resto + } + } + $this->created = []; + + $this->logErrors(); + } + + /** + * Crea un cliente con el valor de excluir347 indicado. + * + * @param bool $exclude + * + * @return Cliente + */ + private function createCustomer(bool $exclude): Cliente + { + $customer = new Cliente(); + $customer->cifnif = 'B' . mt_rand(1, 999999); + $customer->nombre = 'Test 347 ' . mt_rand(1, 99999); + $customer->excluir347 = $exclude; + $this->assertTrue($customer->save(), 'cant-create-customer'); + $this->created[] = $customer; + $this->created[] = $customer->getDefaultAddress(); + return $customer; + } + + /** + * Crea un proveedor con el valor de excluir347 indicado. + * + * @param bool $exclude + * + * @return Proveedor + */ + private function createSupplier(bool $exclude): Proveedor + { + $supplier = new Proveedor(); + $supplier->cifnif = 'B' . mt_rand(1, 999999); + $supplier->nombre = 'Test 347 ' . mt_rand(1, 99999); + $supplier->excluir347 = $exclude; + $this->assertTrue($supplier->save(), 'cant-create-supplier'); + $this->created[] = $supplier; + $this->created[] = $supplier->getDefaultAddress(); + return $supplier; + } + + /** + * Guarda el documento con una línea para el sujeto indicado. + * + * @param BusinessDocument $doc + * @param Cliente|Proveedor $subject + * + * @return BusinessDocument + */ + private function createDocument(BusinessDocument $doc, $subject): BusinessDocument + { + $this->assertTrue($doc->setSubject($subject), 'cant-set-subject'); + $this->assertTrue($doc->save(), 'cant-create-document'); + $this->created[] = $doc; + + $line = $doc->getNewLine(['descripcion' => 'Test 347', 'cantidad' => 1, 'pvpunitario' => 100]); + $this->assertTrue($line->save(), 'cant-create-line'); + + $lines = $doc->getLines(); + $this->assertTrue(Calculator::calculate($doc, $lines, true), 'cant-calculate-document'); + return $doc; + } + + /** + * Genera el documento de destino y lo devuelve recargado de la base de datos. + * + * @param BusinessDocument $prototype + * @param string $newClass + * @param array $properties + * + * @return BusinessDocument + */ + private function generate(BusinessDocument $prototype, string $newClass, array $properties = []): BusinessDocument + { + $generator = new BusinessDocumentGenerator(); + $this->assertTrue($generator->generate($prototype, $newClass, [], [], $properties), 'cant-generate-' . $newClass); + + $newDoc = $generator->getLastDocs()[0]; + $this->created[] = $newDoc; + $this->assertTrue($newDoc->reload(), 'cant-reload-' . $newClass); + return $newDoc; + } +} From eb2482f838cc1394e3d5ea38940e4ea06933a822 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Fern=C3=A1ndez=20Gim=C3=A9nez?= Date: Mon, 16 Nov 2026 10:46:34 +0100 Subject: [PATCH 2/2] test(347): crear las tablas antes de generar facturas en BusinessDocumentGeneratorTest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Con el core actual, al guardar y borrar facturas (y sus recibos) se abre una transacción, y dentro de ella no se pueden crear tablas. El test fallaba con "cant create table albaranesprov in transaction" en MySQL y con "current transaction is aborted" en PostgreSQL, porque el tearDown() se traga la excepción y deja la transacción abierta para los tests siguientes. Se crean en setUpBeforeClass() las tablas de pedidos, albaranes, facturas, recibos y pagos que usa el test, igual que en FacturasTest. Co-Authored-By: Claude Opus 5.5 --- Test/main/BusinessDocumentGeneratorTest.php | 119 ++++++++++++-------- 1 file changed, 71 insertions(+), 48 deletions(-) diff --git a/Test/main/BusinessDocumentGeneratorTest.php b/Test/main/BusinessDocumentGeneratorTest.php index 5ef8d83..4569220 100644 --- a/Test/main/BusinessDocumentGeneratorTest.php +++ b/Test/main/BusinessDocumentGeneratorTest.php @@ -24,8 +24,14 @@ use FacturaScripts\Dinamic\Lib\BusinessDocumentGenerator; use FacturaScripts\Dinamic\Model\AlbaranProveedor; use FacturaScripts\Dinamic\Model\Cliente; +use FacturaScripts\Dinamic\Model\FacturaCliente; +use FacturaScripts\Dinamic\Model\FacturaProveedor; +use FacturaScripts\Dinamic\Model\PagoCliente; +use FacturaScripts\Dinamic\Model\PagoProveedor; use FacturaScripts\Dinamic\Model\PedidoCliente; use FacturaScripts\Dinamic\Model\Proveedor; +use FacturaScripts\Dinamic\Model\ReciboCliente; +use FacturaScripts\Dinamic\Model\ReciboProveedor; use FacturaScripts\Test\Traits\DefaultSettingsTrait; use FacturaScripts\Test\Traits\LogErrorsTrait; use PHPUnit\Framework\TestCase; @@ -45,11 +51,37 @@ final class BusinessDocumentGeneratorTest extends TestCase /** @var array Registros creados en cada test, en orden de borrado. */ private array $created = []; + /** + * Prepara la configuración y la contabilidad por defecto y crea las tablas que se usan en los tests. + */ public static function setUpBeforeClass(): void { self::setDefaultSettings(); self::installAccountingPlan(); self::removeTaxRegularization(); + + // creamos las tablas antes de guardar o borrar documentos: el core guarda y borra las facturas + // (y sus recibos) dentro de una transacción y no se pueden crear tablas dentro de ella + new PedidoCliente(); + new AlbaranProveedor(); + new FacturaCliente(); + new FacturaProveedor(); + new ReciboCliente(); + new ReciboProveedor(); + new PagoCliente(); + new PagoProveedor(); + } + + /** + * El valor indicado expresamente en las propiedades de la generación prevalece sobre la ficha. + */ + public function testExplicitPropertyIsRespected(): void + { + $customer = $this->createCustomer(true); + $order = $this->createDocument(new PedidoCliente(), $customer); + + $invoice = $this->generate($order, 'FacturaCliente', ['excluir347' => false]); + $this->assertFalse($invoice->excluir347, 'explicit-property-must-be-respected'); } /** @@ -76,18 +108,6 @@ public function testInvoiceFromCustomerOrderNotExcluded(): void $this->assertFalse($invoice->excluir347, 'invoice-must-not-be-excluded'); } - /** - * El valor indicado expresamente en las propiedades de la generación prevalece sobre la ficha. - */ - public function testExplicitPropertyIsRespected(): void - { - $customer = $this->createCustomer(true); - $order = $this->createDocument(new PedidoCliente(), $customer); - - $invoice = $this->generate($order, 'FacturaCliente', ['excluir347' => false]); - $this->assertFalse($invoice->excluir347, 'explicit-property-must-be-respected'); - } - /** * Factura de proveedor generada desde un albarán de un proveedor excluido del 347. */ @@ -100,23 +120,6 @@ public function testInvoiceFromSupplierDeliveryNoteInheritsExclusion(): void $this->assertTrue($invoice->excluir347, 'invoice-must-inherit-excluir347'); } - protected function tearDown(): void - { - // borramos en orden inverso de creación; cada borrado aislado para no dejar restos - foreach (array_reverse($this->created) as $item) { - try { - if ($item->exists()) { - $item->delete(); - } - } catch (Throwable $e) { - // ignoramos el error para seguir limpiando el resto - } - } - $this->created = []; - - $this->logErrors(); - } - /** * Crea un cliente con el valor de excluir347 indicado. * @@ -136,25 +139,6 @@ private function createCustomer(bool $exclude): Cliente return $customer; } - /** - * Crea un proveedor con el valor de excluir347 indicado. - * - * @param bool $exclude - * - * @return Proveedor - */ - private function createSupplier(bool $exclude): Proveedor - { - $supplier = new Proveedor(); - $supplier->cifnif = 'B' . mt_rand(1, 999999); - $supplier->nombre = 'Test 347 ' . mt_rand(1, 99999); - $supplier->excluir347 = $exclude; - $this->assertTrue($supplier->save(), 'cant-create-supplier'); - $this->created[] = $supplier; - $this->created[] = $supplier->getDefaultAddress(); - return $supplier; - } - /** * Guarda el documento con una línea para el sujeto indicado. * @@ -177,6 +161,25 @@ private function createDocument(BusinessDocument $doc, $subject): BusinessDocume return $doc; } + /** + * Crea un proveedor con el valor de excluir347 indicado. + * + * @param bool $exclude + * + * @return Proveedor + */ + private function createSupplier(bool $exclude): Proveedor + { + $supplier = new Proveedor(); + $supplier->cifnif = 'B' . mt_rand(1, 999999); + $supplier->nombre = 'Test 347 ' . mt_rand(1, 99999); + $supplier->excluir347 = $exclude; + $this->assertTrue($supplier->save(), 'cant-create-supplier'); + $this->created[] = $supplier; + $this->created[] = $supplier->getDefaultAddress(); + return $supplier; + } + /** * Genera el documento de destino y lo devuelve recargado de la base de datos. * @@ -196,4 +199,24 @@ private function generate(BusinessDocument $prototype, string $newClass, array $ $this->assertTrue($newDoc->reload(), 'cant-reload-' . $newClass); return $newDoc; } + + /** + * Borra los registros creados en el test y muestra los errores registrados. + */ + protected function tearDown(): void + { + // borramos en orden inverso de creación; cada borrado aislado para no dejar restos + foreach (array_reverse($this->created) as $item) { + try { + if ($item->exists()) { + $item->delete(); + } + } catch (Throwable $e) { + // ignoramos el error para seguir limpiando el resto + } + } + $this->created = []; + + $this->logErrors(); + } }