From 0f5df0e72301fb646d4300732eec4868e9755908 Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Tue, 24 Nov 2026 10:17:34 +0100 Subject: [PATCH 1/2] [FEATURE] Store the taxes per tax class of order discounts A percentage coupon reduces the taxes of every tax class of the cart, but the discount of the order stored only the tax of the coupon in its own tax class, which is 0.0 for percentage coupons. The tax class of the discount was not stored at all, Order\Discount::$taxClass was not mapped. The totals of the order were correct. The discount of an order now stores the taxes per tax class of the order as JSON (`taxes`), the tax class of the order (`tax_class`) and the class of the cart coupon (`coupon_type`). The taxes are calculated like Cart::getCouponTaxes(), for fixed and percentage coupons. The order views in the backend and in the frontend show the taxes of a discount in the columns of their tax classes. The frontend view shows the discounts of the order, too. Passing the tax class of the cart to the constructor of Order\Discount is deprecated, it expects the tax class of the order. Resolves: #896 Co-Authored-By: Claude Opus 5.5 --- Build/phpstan-baseline.neon | 42 ---- Classes/Domain/Model/Order/Discount.php | 98 ++++++++- .../Order/Create/PersistOrder/Coupons.php | 47 +++- .../tx_cart_domain_model_order_discount.php | 32 ++- ...recation-896-OrderDiscountCartTaxClass.rst | 66 ++++++ Documentation/Changelog/12.8/Index.rst | 24 ++ Documentation/Changelog/Index.rst | 1 + Resources/Private/Language/locallang_db.xlf | 9 + .../Show/CartTable/DiscountTaxColumns.html | 18 ++ .../Backend/Order/Show/CartTable/Footer.html | 8 +- .../Order/Show/DiscountTaxColumns.html | 23 ++ .../Private/Partials/Order/Show/Summary.html | 17 ++ .../Order/Create/PersistOrder/CouponsTest.php | 207 ++++++++++++++++++ .../Templates/Fixtures/OrderWithTaxes.php | 18 ++ .../Templates/OrderTaxColumnsTest.php | 8 +- .../Unit/Domain/Model/Order/DiscountTest.php | 80 ++++++- ext_tables.sql | 3 + 17 files changed, 641 insertions(+), 60 deletions(-) create mode 100644 Documentation/Changelog/12.8/Deprecation-896-OrderDiscountCartTaxClass.rst create mode 100644 Documentation/Changelog/12.8/Index.rst create mode 100644 Resources/Private/Partials/Backend/Order/Show/CartTable/DiscountTaxColumns.html create mode 100644 Resources/Private/Partials/Order/Show/DiscountTaxColumns.html create mode 100644 Tests/Functional/EventListener/Order/Create/PersistOrder/CouponsTest.php diff --git a/Build/phpstan-baseline.neon b/Build/phpstan-baseline.neon index 83576bb2..6ac6face 100644 --- a/Build/phpstan-baseline.neon +++ b/Build/phpstan-baseline.neon @@ -2874,48 +2874,6 @@ parameters: count: 1 path: ../Classes/EventListener/Order/Create/OrderNumber.php - - - message: '#^Cannot call method getCode\(\) on mixed\.$#' - identifier: method.nonObject - count: 2 - path: ../Classes/EventListener/Order/Create/PersistOrder/Coupons.php - - - - message: '#^Cannot call method getGross\(\) on mixed\.$#' - identifier: method.nonObject - count: 1 - path: ../Classes/EventListener/Order/Create/PersistOrder/Coupons.php - - - - message: '#^Cannot call method getNet\(\) on mixed\.$#' - identifier: method.nonObject - count: 1 - path: ../Classes/EventListener/Order/Create/PersistOrder/Coupons.php - - - - message: '#^Cannot call method getTax\(\) on mixed\.$#' - identifier: method.nonObject - count: 1 - path: ../Classes/EventListener/Order/Create/PersistOrder/Coupons.php - - - - message: '#^Cannot call method getTaxClass\(\) on mixed\.$#' - identifier: method.nonObject - count: 1 - path: ../Classes/EventListener/Order/Create/PersistOrder/Coupons.php - - - - message: '#^Cannot call method getTitle\(\) on mixed\.$#' - identifier: method.nonObject - count: 1 - path: ../Classes/EventListener/Order/Create/PersistOrder/Coupons.php - - - - message: '#^Cannot call method isUseable\(\) on mixed\.$#' - identifier: method.nonObject - count: 1 - path: ../Classes/EventListener/Order/Create/PersistOrder/Coupons.php - - message: '#^Cannot access offset ''currency'' on mixed\.$#' identifier: offsetAccess.nonOffsetAccessible diff --git a/Classes/Domain/Model/Order/Discount.php b/Classes/Domain/Model/Order/Discount.php index 91783270..321e8ce5 100644 --- a/Classes/Domain/Model/Order/Discount.php +++ b/Classes/Domain/Model/Order/Discount.php @@ -11,7 +11,7 @@ * LICENSE file that was distributed with this source code. */ -use Extcode\Cart\Domain\Model\Cart\TaxClass; +use Extcode\Cart\Domain\Model\Cart\TaxClass as CartTaxClass; use TYPO3\CMS\Extbase\Attribute\ORM\Lazy; use TYPO3\CMS\Extbase\Attribute\Validate; use TYPO3\CMS\Extbase\DomainObject\AbstractEntity; @@ -22,6 +22,30 @@ class Discount extends AbstractEntity #[Lazy] protected Item|LazyLoadingProxy $item; + protected ?TaxClass $taxClass = null; + + /** + * Class of the cart coupon, e.g. \Extcode\Cart\Domain\Model\Cart\CartCouponPercentage. + */ + protected string $couponType = ''; + + /** + * JSON encoded taxes of the discount per tax class of the order (uid => tax). + * An empty string means that the taxes per tax class are unknown (orders + * which were not migrated by the upgrade wizard). + * + * @var string JSON, the tag keeps Extbase from taking the array type of getTaxes() for the property + */ + protected string $taxes = ''; + + /** + * The discount is not changed after the order was persisted, so there are + * no setters. + * + * @param null|CartTaxClass|TaxClass $taxClass the tax class of the order; passing the tax class of the cart is deprecated + * @param string $couponType class of the cart coupon + * @param null|array $taxes uid of the tax class of the order => tax, null if unknown + */ public function __construct( #[Validate(validator: 'NotEmpty')] protected string $title, @@ -31,11 +55,28 @@ public function __construct( protected float $gross, #[Validate(validator: 'NotEmpty')] protected float $net, + null|CartTaxClass|TaxClass $taxClass, #[Validate(validator: 'NotEmpty')] - protected TaxClass $taxClass, - #[Validate(validator: 'NotEmpty')] - protected float $tax + protected float $tax, + string $couponType = '', + ?array $taxes = null ) { + // TODO: 13.0.0 Accept only the tax class of the order, see Deprecation #896. + if ($taxClass instanceof CartTaxClass) { + trigger_error( + 'Passing a tax class of the cart (' . CartTaxClass::class . ') to ' . self::class . ' is deprecated' + . ' since cart 12.8 and will stop working in cart 13.0. Pass the tax class of the order (' + . TaxClass::class . ') instead.', + E_USER_DEPRECATED + ); + $taxClass = null; + } + + $this->taxClass = $taxClass; + $this->couponType = $couponType; + if ($taxes !== null) { + $this->taxes = json_encode((object) $taxes, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION); + } } public function getItem(): ?Item @@ -67,13 +108,62 @@ public function getNet(): float return $this->net; } + /** + * Returns the tax class of the order the coupon was configured with. The + * tax class is not stored for orders created before cart 12.8. + */ public function getTaxClass(): ?TaxClass { return $this->taxClass; } + /** + * Returns the tax of the coupon in its own tax class. It is 0.0 for + * percentage coupons, their tax is split over the tax classes of the + * products, see getTaxes(). + */ public function getTax(): float { return $this->tax; } + + public function getCouponType(): string + { + return $this->couponType; + } + + /** + * Returns the taxes of the discount per tax class of the order. + * + * @return array uid of the tax class of the order => tax + */ + public function getTaxes(): array + { + if ($this->taxes === '') { + return []; + } + + $taxes = json_decode($this->taxes, true); + if (!is_array($taxes)) { + return []; + } + + $result = []; + foreach ($taxes as $taxClassUid => $tax) { + if (is_numeric($taxClassUid) && is_numeric($tax)) { + $result[(int) $taxClassUid] = (float) $tax; + } + } + + return $result; + } + + /** + * Returns false for discounts of orders created before cart 12.8 which + * were not migrated by the upgrade wizard "extcodeCartOrderDiscountTaxes". + */ + public function hasTaxes(): bool + { + return $this->taxes !== ''; + } } diff --git a/Classes/EventListener/Order/Create/PersistOrder/Coupons.php b/Classes/EventListener/Order/Create/PersistOrder/Coupons.php index 7940acc8..7b920dee 100644 --- a/Classes/EventListener/Order/Create/PersistOrder/Coupons.php +++ b/Classes/EventListener/Order/Create/PersistOrder/Coupons.php @@ -11,8 +11,10 @@ * LICENSE file that was distributed with this source code. */ +use Extcode\Cart\Domain\Model\Cart\CartCouponInterface; use Extcode\Cart\Domain\Model\Coupon; use Extcode\Cart\Domain\Model\Order\Discount; +use Extcode\Cart\Domain\Model\Order\TaxClass; use Extcode\Cart\Domain\Repository\CouponRepository; use Extcode\Cart\Domain\Repository\Order\DiscountRepository; use Extcode\Cart\Domain\Repository\Order\ItemRepository; @@ -35,21 +37,27 @@ public function __invoke(PersistOrderEvent $event): void $cart = $event->getCart(); $orderItem = $event->getOrderItem(); $storagePid = $event->getStoragePid(); + $taxClasses = array_filter( + $event->getTaxClasses(), + static fn (mixed $taxClass): bool => $taxClass instanceof TaxClass + ); if (!$cart->getCoupons()) { return; } foreach ($cart->getCoupons() as $cartCoupon) { - if ($cartCoupon->isUseable()) { + if ($cartCoupon instanceof CartCouponInterface && $cartCoupon->isUseable()) { $orderDiscount = GeneralUtility::makeInstance( Discount::class, $cartCoupon->getTitle(), $cartCoupon->getCode(), $cartCoupon->getGross(), $cartCoupon->getNet(), - $cartCoupon->getTaxClass(), - $cartCoupon->getTax() + $taxClasses[$cartCoupon->getTaxClass()->getId()] ?? null, + $cartCoupon->getTax(), + $cartCoupon::class, + self::getTaxesPerOrderTaxClass($cartCoupon, $taxClasses) ); $orderDiscount->setPid($storagePid); @@ -69,4 +77,37 @@ public function __invoke(PersistOrderEvent $event): void $this->persistenceManager->persistAll(); } + + /** + * Returns the taxes of the coupon per tax class of the order. They are + * calculated like in Cart::getCouponTaxes(), so the taxes of all discounts + * of an order add up to the coupon taxes of the cart. + * + * @param array $taxClasses id of the tax class of the cart => tax class of the order + * + * @return array uid of the tax class of the order => tax + */ + private static function getTaxesPerOrderTaxClass(CartCouponInterface $cartCoupon, array $taxClasses): array + { + $cartTaxes = [ + $cartCoupon->getTaxClass()->getId() => $cartCoupon->getTax(), + ]; + $couponTaxes = method_exists($cartCoupon, 'getTaxes') ? $cartCoupon->getTaxes() : []; + foreach (is_array($couponTaxes) ? $couponTaxes : [] as $taxClassId => $tax) { + if (is_int($taxClassId) && is_numeric($tax)) { + $cartTaxes[$taxClassId] = ($cartTaxes[$taxClassId] ?? 0.0) + (float) $tax; + } + } + + $taxes = []; + foreach ($cartTaxes as $taxClassId => $tax) { + $taxClassUid = ($taxClasses[$taxClassId] ?? null)?->getUid(); + if ($taxClassUid !== null) { + // rounded like the amounts in the decimal(17,5) columns + $taxes[$taxClassUid] = round($tax, 5); + } + } + + return $taxes; + } } diff --git a/Configuration/TCA/tx_cart_domain_model_order_discount.php b/Configuration/TCA/tx_cart_domain_model_order_discount.php index cc238adc..89d68ad2 100644 --- a/Configuration/TCA/tx_cart_domain_model_order_discount.php +++ b/Configuration/TCA/tx_cart_domain_model_order_discount.php @@ -25,7 +25,7 @@ 'hideTable' => 1, 'types' => [ '1' => [ - 'showitem' => 'title, code, gross, net, tax_class_id, tax', + 'showitem' => 'title, code, coupon_type, gross, net, tax_class, tax, taxes', ], ], 'palettes' => [ @@ -72,6 +72,7 @@ 'format' => 'decimal', ], ], + // TODO: 13.0.0 Remove the column tax_class_id, it is replaced by tax_class, see Deprecation #896. 'tax_class_id' => [ 'exclude' => 1, 'label' => $_LLL . ':tx_cart_domain_model_order_discount.tax_class_id', @@ -96,6 +97,35 @@ ], ], + 'tax_class' => [ + 'exclude' => 0, + 'label' => $_LLL . ':tx_cart_domain_model_order_discount.tax_class', + 'config' => [ + 'type' => 'inline', + 'readOnly' => 1, + 'foreign_table' => 'tx_cart_domain_model_order_taxclass', + 'minitems' => 0, + 'maxitems' => 1, + ], + ], + 'coupon_type' => [ + 'exclude' => 0, + 'label' => $_LLL . ':tx_cart_domain_model_order_discount.coupon_type', + 'config' => [ + 'type' => 'input', + 'readOnly' => 1, + 'size' => 30, + ], + ], + 'taxes' => [ + 'exclude' => 0, + 'label' => $_LLL . ':tx_cart_domain_model_order_discount.taxes', + 'config' => [ + 'type' => 'text', + 'readOnly' => 1, + ], + ], + 'item' => [ 'config' => [ 'type' => 'passthrough', diff --git a/Documentation/Changelog/12.8/Deprecation-896-OrderDiscountCartTaxClass.rst b/Documentation/Changelog/12.8/Deprecation-896-OrderDiscountCartTaxClass.rst new file mode 100644 index 00000000..cbe2deea --- /dev/null +++ b/Documentation/Changelog/12.8/Deprecation-896-OrderDiscountCartTaxClass.rst @@ -0,0 +1,66 @@ +.. include:: ../../Includes.rst.txt + +===================================================================== +Deprecation: #896 - Tax class of the cart in the discount of an order +===================================================================== + +See `Issue 896 `__ + +Description +=========== + +The constructor of ``\Extcode\Cart\Domain\Model\Order\Discount`` expected the +tax class of the cart (``\Extcode\Cart\Domain\Model\Cart\TaxClass``), which +was never stored. It now expects the tax class of the order +(``\Extcode\Cart\Domain\Model\Order\TaxClass``) or ``null``, and +``getTaxClass()`` returns the tax class of the order. + +The column ``tax_class_id`` of ``tx_cart_domain_model_order_discount`` is +deprecated. It always contained ``1`` and is replaced by ``tax_class``, which +references the tax class of the order. + +Impact +====== + +Passing the tax class of the cart logs a deprecation, the discount gets no tax +class. It will stop working in cart 13.0. + +The column ``tax_class_id`` will be removed in cart 13.0. + +Affected Installations +====================== + +Installations with extensions which create discounts of an order themselves, +e.g. with an own event listener of the ``PersistOrderEvent`` instead of +``\Extcode\Cart\EventListener\Order\Create\PersistOrder\Coupons``. + +Installations which read the column ``tax_class_id`` of the discounts of an +order, e.g. in exports or reports. + +Migration +========= + +Read the tax class with ``getTaxClass()`` or from the column ``tax_class`` +instead of ``tax_class_id``. + +Pass the tax class of the order. The listeners of the ``PersistOrderEvent`` +get them from ``$event->getTaxClasses()`` with the id of the tax class of the +cart as key: + +.. code-block:: php + + $orderDiscount = new Discount( + $cartCoupon->getTitle(), + $cartCoupon->getCode(), + $cartCoupon->getGross(), + $cartCoupon->getNet(), + $event->getTaxClasses()[$cartCoupon->getTaxClass()->getId()] ?? null, + $cartCoupon->getTax(), + $cartCoupon::class, + $taxesPerTaxClassOfTheOrder + ); + +The parameters ``$couponType`` and ``$taxes`` are optional, see +:doc:`Feature-OrderDiscountTaxesPerTaxClass`. + +.. index:: PHP-API diff --git a/Documentation/Changelog/12.8/Index.rst b/Documentation/Changelog/12.8/Index.rst new file mode 100644 index 00000000..b44b7e74 --- /dev/null +++ b/Documentation/Changelog/12.8/Index.rst @@ -0,0 +1,24 @@ +.. include:: ../../Includes.rst.txt + +12.8 Changes +============ + +**Table of contents** + +.. contents:: + :local: + :depth: 1 + +12.8.0 +------ + +Deprecations +~~~~~~~~~~~~ + +* :doc:`#896 - Tax class of the cart in the discount of an order ` + +.. toctree:: + :hidden: + :glob: + + *-* diff --git a/Documentation/Changelog/Index.rst b/Documentation/Changelog/Index.rst index ce019c25..32898e25 100644 --- a/Documentation/Changelog/Index.rst +++ b/Documentation/Changelog/Index.rst @@ -10,6 +10,7 @@ ChangeLog :maxdepth: 5 :titlesonly: + 12.8/Index 12.7/Index 12.6/Index 12.5/Index diff --git a/Resources/Private/Language/locallang_db.xlf b/Resources/Private/Language/locallang_db.xlf index de01c5b0..2e1e6ce2 100644 --- a/Resources/Private/Language/locallang_db.xlf +++ b/Resources/Private/Language/locallang_db.xlf @@ -343,6 +343,15 @@ Tax + + Tax Class + + + Coupon Type + + + Taxes per Tax Class + Order Product Additional diff --git a/Resources/Private/Partials/Backend/Order/Show/CartTable/DiscountTaxColumns.html b/Resources/Private/Partials/Backend/Order/Show/CartTable/DiscountTaxColumns.html new file mode 100644 index 00000000..d54fd62a --- /dev/null +++ b/Resources/Private/Partials/Backend/Order/Show/CartTable/DiscountTaxColumns.html @@ -0,0 +1,18 @@ + + + + One column per tax class of the order (totalTaxes), the taxes of a discount (tax class uid => tax) are shown in the + columns of their tax classes. The columns stay empty if the discount has no tax in the tax class or if the taxes + of the discount are unknown (orders which were not migrated by the upgrade wizard). + + + + + + {discountTax} + + + + diff --git a/Resources/Private/Partials/Backend/Order/Show/CartTable/Footer.html b/Resources/Private/Partials/Backend/Order/Show/CartTable/Footer.html index 14a9417f..bef29d1c 100644 --- a/Resources/Private/Partials/Backend/Order/Show/CartTable/Footer.html +++ b/Resources/Private/Partials/Backend/Order/Show/CartTable/Footer.html @@ -67,12 +67,8 @@ {orderDiscount.gross} - - The tax class of a discount is not stored in the order, so its tax can not be assigned to a column. - - - - + diff --git a/Resources/Private/Partials/Order/Show/DiscountTaxColumns.html b/Resources/Private/Partials/Order/Show/DiscountTaxColumns.html new file mode 100644 index 00000000..0e44b49b --- /dev/null +++ b/Resources/Private/Partials/Order/Show/DiscountTaxColumns.html @@ -0,0 +1,23 @@ + + + + One column per tax class of the order (totalTaxes), the taxes of a discount (tax class uid => tax) are shown in the + columns of their tax classes. The columns stay empty if the discount has no tax in the tax class or if the taxes + of the discount are unknown (orders which were not migrated by the upgrade wizard). + + + + + + + {discountTax} + + +   + + + + + diff --git a/Resources/Private/Partials/Order/Show/Summary.html b/Resources/Private/Partials/Order/Show/Summary.html index c2ef7905..9ae35d34 100644 --- a/Resources/Private/Partials/Order/Show/Summary.html +++ b/Resources/Private/Partials/Order/Show/Summary.html @@ -23,6 +23,23 @@ + + + + + {orderDiscount.title} + + + {orderDiscount.net} + + + {orderDiscount.gross} + + + + + diff --git a/Tests/Functional/EventListener/Order/Create/PersistOrder/CouponsTest.php b/Tests/Functional/EventListener/Order/Create/PersistOrder/CouponsTest.php new file mode 100644 index 00000000..277ac5b7 --- /dev/null +++ b/Tests/Functional/EventListener/Order/Create/PersistOrder/CouponsTest.php @@ -0,0 +1,207 @@ +persistOrder( + new CartCouponPercentage('10 %', 'percentage', CartCouponPercentage::class, 10.0, self::normal(), 0.0) + ); + + $row = self::getDiscountRow(); + self::assertSame(CartCouponPercentage::class, $row['coupon_type']); + self::assertSame($orderTaxClassUids['normal'], $row['tax_class']); + self::assertEqualsWithDelta(3.45, $row['gross'], 0.00001); + self::assertEqualsWithDelta(3.00, $row['net'], 0.00001); + self::assertEqualsWithDelta(0.0, $row['tax'], 0.00001); + self::assertTaxes( + [ + $orderTaxClassUids['normal'] => 0.38, + $orderTaxClassUids['reduced'] => 0.07, + ], + json_decode($row['taxes'], true) + ); + } + + #[Test] + public function storesTheTaxOfAFixedCouponInItsTaxClass(): void + { + $orderTaxClassUids = $this->persistOrder( + new CartCouponFix('11.90', 'fix', 'cartdiscount', 11.90, self::normal(), 0.0) + ); + + $row = self::getDiscountRow(); + self::assertSame(CartCouponFix::class, $row['coupon_type']); + self::assertSame($orderTaxClassUids['normal'], $row['tax_class']); + self::assertEqualsWithDelta(1.90, $row['tax'], 0.00001); + self::assertTaxes( + [ + $orderTaxClassUids['normal'] => 1.90, + ], + json_decode($row['taxes'], true) + ); + } + + #[Test] + public function mapsTheTaxClassAndTheTaxesInTheModel(): void + { + $orderTaxClassUids = $this->persistOrder( + new CartCouponPercentage('10 %', 'percentage', CartCouponPercentage::class, 10.0, self::normal(), 0.0) + ); + $this->getService(PersistenceManager::class)->clearState(); + + $discount = $this->getService(PersistenceManager::class)->getObjectByIdentifier( + self::getDiscountRow()['uid'], + Discount::class + ); + + self::assertInstanceOf(Discount::class, $discount); + self::assertSame($orderTaxClassUids['normal'], $discount->getTaxClass()?->getUid()); + self::assertSame('19', $discount->getTaxClass()->getValue()); + self::assertSame(CartCouponPercentage::class, $discount->getCouponType()); + self::assertTrue($discount->hasTaxes()); + self::assertTaxes( + [ + $orderTaxClassUids['normal'] => 0.38, + $orderTaxClassUids['reduced'] => 0.07, + ], + $discount->getTaxes() + ); + } + + /** + * Runs the listeners of the PersistOrderEvent which persist the tax + * classes and the coupons. + * + * @return array name of the tax class => uid of the tax class of the order + */ + private function persistOrder(CartCouponInterface $coupon): array + { + $taxClasses = [ + 1 => self::normal(), + 2 => new TaxClass(2, '7', 0.07, 'reduced'), + ]; + $cart = new Cart($taxClasses); + $cart->addProduct(new Product('simple', 1, 'shirt', 'Shirt', 23.80, $taxClasses[1], 1)); + $cart->addProduct(new Product('simple', 2, 'book', 'Book', 10.70, $taxClasses[2], 1)); + $cart->addCoupon($coupon); + + $orderItem = new Item(); + $orderItem->setPid(1); + $this->getService(ItemRepository::class)->add($orderItem); + $this->getService(PersistenceManager::class)->persistAll(); + + $event = new PersistOrderEvent($cart, $orderItem, ['settings' => ['order' => ['pid' => 1]]]); + $this->getService(TaxClasses::class)($event); + $this->getService(Coupons::class)($event); + + $orderTaxClassUids = []; + foreach ($event->getTaxClasses() as $orderTaxClass) { + self::assertInstanceOf(OrderTaxClass::class, $orderTaxClass); + $orderTaxClassUids[$orderTaxClass->getTitle()] = (int) $orderTaxClass->getUid(); + } + + return $orderTaxClassUids; + } + + private static function normal(): TaxClass + { + return new TaxClass(1, '19', 0.19, 'normal'); + } + + /** + * @return array{uid: int, gross: float, net: float, tax: float, tax_class: int, coupon_type: string, taxes: string} + */ + private static function getDiscountRow(): array + { + $rows = (new ConnectionPool()) + ->getConnectionForTable('tx_cart_domain_model_order_discount') + ->select(['*'], 'tx_cart_domain_model_order_discount') + ->fetchAllAssociative() + ; + self::assertCount(1, $rows); + $row = $rows[0]; + foreach (['uid', 'gross', 'net', 'tax', 'tax_class'] as $field) { + self::assertIsNumeric($row[$field]); + } + self::assertIsString($row['coupon_type']); + self::assertIsString($row['taxes']); + + return [ + 'uid' => (int) $row['uid'], + 'gross' => (float) $row['gross'], + 'net' => (float) $row['net'], + 'tax' => (float) $row['tax'], + 'tax_class' => (int) $row['tax_class'], + 'coupon_type' => $row['coupon_type'], + 'taxes' => $row['taxes'], + ]; + } + + /** + * @template T of object + * + * @param class-string $className + * + * @return T + */ + private function getService(string $className): object + { + $service = $this->get($className); + self::assertInstanceOf($className, $service); + + return $service; + } + + /** + * @param array $expected + */ + private static function assertTaxes(array $expected, mixed $actual): void + { + self::assertIsArray($actual); + self::assertSame(array_keys($expected), array_map(intval(...), array_keys($actual))); + foreach ($expected as $taxClassUid => $tax) { + self::assertEqualsWithDelta($tax, $actual[$taxClassUid], 0.00001); + } + } +} diff --git a/Tests/Functional/Templates/Fixtures/OrderWithTaxes.php b/Tests/Functional/Templates/Fixtures/OrderWithTaxes.php index 93420884..46fa4ba3 100644 --- a/Tests/Functional/Templates/Fixtures/OrderWithTaxes.php +++ b/Tests/Functional/Templates/Fixtures/OrderWithTaxes.php @@ -1,6 +1,10 @@ [ [ @@ -80,6 +84,20 @@ 'net' => -10.00, 'tax_class_id' => 1, 'tax' => -1.90, + 'tax_class' => 1, + 'coupon_type' => CartCouponFix::class, + 'taxes' => '{"1":-1.9}', + ], + [ + 'uid' => 2, + 'pid' => 1, + 'item' => 1, + 'title' => 'Old coupon', + 'code' => 'old-coupon', + 'gross' => 0.0, + 'net' => 0.0, + 'tax_class_id' => 1, + 'tax' => 0.0, ], ], 'tx_cart_domain_model_order_tax' => [ diff --git a/Tests/Functional/Templates/OrderTaxColumnsTest.php b/Tests/Functional/Templates/OrderTaxColumnsTest.php index 8cefe6b1..a4d5d2e4 100644 --- a/Tests/Functional/Templates/OrderTaxColumnsTest.php +++ b/Tests/Functional/Templates/OrderTaxColumnsTest.php @@ -33,8 +33,9 @@ * The cart table of the order in the backend (partial Backend/Order/Show/Cart) * and in the frontend (partial Order/Show/Cart) renders one column per tax * class of the order with the taxes of the products and the services in the - * column of their tax class. The tax class of a discount is not stored, its - * row has empty tax columns. + * column of their tax class. The taxes of a discount are shown in the columns + * of their tax classes; a discount without taxes per tax class (orders created + * before cart 12.8) has empty tax columns. */ final class OrderTaxColumnsTest extends FunctionalTestCase { @@ -55,6 +56,7 @@ public function backendRendersTheTaxesInTheColumnOfTheirTaxClass(): void ['3,80€', '0,70€'], ['0,95€', ''], ['0,19€', ''], + ['-1,90€', ''], ['', ''], ['3,04€', '0,70€'], ], @@ -71,6 +73,8 @@ public function frontendRendersTheTaxesInTheColumnOfTheirTaxClass(): void ['', '0,70€'], ['3,80€', ''], ['3,80€', '0,70€'], + ['-1,90€', ''], + ['', ''], ['0,95€', ''], ['0,19€', ''], ['3,04€', '0,70€'], diff --git a/Tests/Unit/Domain/Model/Order/DiscountTest.php b/Tests/Unit/Domain/Model/Order/DiscountTest.php index de5f2436..96c846a5 100644 --- a/Tests/Unit/Domain/Model/Order/DiscountTest.php +++ b/Tests/Unit/Domain/Model/Order/DiscountTest.php @@ -11,9 +11,12 @@ * LICENSE file that was distributed with this source code. */ -use Extcode\Cart\Domain\Model\Cart\TaxClass; +use Extcode\Cart\Domain\Model\Cart\CartCouponPercentage; +use Extcode\Cart\Domain\Model\Cart\TaxClass as CartTaxClass; use Extcode\Cart\Domain\Model\Order\Discount; +use Extcode\Cart\Domain\Model\Order\TaxClass; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\IgnoreDeprecations; use PHPUnit\Framework\Attributes\Test; use TYPO3\TestingFramework\Core\Unit\UnitTestCase; @@ -36,7 +39,10 @@ class DiscountTest extends UnitTestCase protected function setUp(): void { - $this->taxClass = new TaxClass(1, '19 %', 0.19, 'normal'); + $this->taxClass = new TaxClass(); + $this->taxClass->setTitle('normal'); + $this->taxClass->setValue('19'); + $this->taxClass->setCalc(0.19); $this->title = 'Discount'; $this->code = 'discount'; @@ -101,6 +107,29 @@ public function getTaxClassInitiallyReturnsTaxClassSetDirectlyByConstructor(): v ); } + #[Test] + public function constructorAcceptsNoTaxClass(): void + { + $discount = new Discount('Discount', 'discount', 10.0, 10.0, null, 0.0); + + self::assertNull($discount->getTaxClass()); + } + + #[IgnoreDeprecations] + #[Test] + public function constructorIgnoresTheDeprecatedTaxClassOfTheCart(): void + { + $this->expectUserDeprecationMessage( + 'Passing a tax class of the cart (' . CartTaxClass::class . ') to ' . Discount::class . ' is deprecated' + . ' since cart 12.8 and will stop working in cart 13.0. Pass the tax class of the order (' + . TaxClass::class . ') instead.' + ); + + $discount = new Discount('Discount', 'discount', 10.0, 8.40, new CartTaxClass(1, '19 %', 0.19, 'normal'), 1.60); + + self::assertNull($discount->getTaxClass()); + } + #[Test] public function getTaxInitiallyReturnsTaxSetDirectlyByConstructor(): void { @@ -109,4 +138,51 @@ public function getTaxInitiallyReturnsTaxSetDirectlyByConstructor(): void $this->discount->getTax() ); } + + #[Test] + public function getCouponTypeInitiallyReturnsEmptyString(): void + { + self::assertSame('', $this->discount->getCouponType()); + } + + #[Test] + public function getCouponTypeReturnsCouponTypeSetByConstructor(): void + { + $discount = new Discount('Discount', 'discount', 10.0, 8.40, null, 0.0, CartCouponPercentage::class); + + self::assertSame(CartCouponPercentage::class, $discount->getCouponType()); + } + + #[Test] + public function getTaxesInitiallyReturnsEmptyArrayAndHasTaxesReturnsFalse(): void + { + self::assertSame([], $this->discount->getTaxes()); + self::assertFalse($this->discount->hasTaxes()); + } + + #[Test] + public function getTaxesReturnsTaxesPerTaxClassSetByConstructor(): void + { + $discount = new Discount('Discount', 'discount', 10.0, 7.40, null, 0.0, CartCouponPercentage::class, [1 => 1.9, 2 => 0.7]); + + self::assertSame([1 => 1.9, 2 => 0.7], $discount->getTaxes()); + self::assertTrue($discount->hasTaxes()); + } + + #[Test] + public function emptyTaxesMarkTheTaxesAsKnown(): void + { + $discount = new Discount('Discount', 'discount', 10.0, 10.0, null, 0.0, CartCouponPercentage::class, []); + + self::assertSame([], $discount->getTaxes()); + self::assertTrue($discount->hasTaxes()); + } + + #[Test] + public function getTaxesReturnsFloatsForStoredIntegers(): void + { + $this->discount->_setProperty('taxes', '{"3":2,"4":"0.5"}'); + + self::assertSame([3 => 2.0, 4 => 0.5], $this->discount->getTaxes()); + } } diff --git a/ext_tables.sql b/ext_tables.sql index 3313b071..badc22a9 100644 --- a/ext_tables.sql +++ b/ext_tables.sql @@ -138,6 +138,9 @@ CREATE TABLE tx_cart_domain_model_order_discount ( net decimal(17,5) DEFAULT '0.00' NOT NULL, tax_class_id int(11) unsigned DEFAULT '1' NOT NULL, tax decimal(17,5) DEFAULT '0.00' NOT NULL, + tax_class int(11) unsigned DEFAULT '0' NOT NULL, + coupon_type varchar(255) DEFAULT '' NOT NULL, + taxes text, INDEX `parent` (pid), INDEX `t3ver_oid` (t3ver_oid,t3ver_wsid), ); From 99b543f033c1d4321c50135fc79bef887940f76a Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Tue, 24 Nov 2026 10:17:34 +0100 Subject: [PATCH 2/2] [TASK] Add an upgrade wizard for the taxes of order discounts The upgrade wizard calculates the taxes per tax class of the discounts of existing orders from the stored taxes of the order: tax of the products plus tax of shipping and payment minus total tax. The taxes of several discounts are split by their gross. It stores the tax class of fixed coupons and the coupon type, if a coupon with the code exists. Orders whose numbers do not add up are skipped and listed, e.g. orders with special services or with fixed coupons of different tax classes. The taxes of their discounts stay unknown. Resolves: #896 Co-Authored-By: Claude Opus 5.5 --- Classes/Updates/OrderDiscountTaxesUpdate.php | 360 ++++++++++++++++++ ...recation-896-OrderDiscountCartTaxClass.rst | 2 +- ...ture-896-OrderDiscountTaxesPerTaxClass.rst | 61 +++ Documentation/Changelog/12.8/Index.rst | 5 + .../Updates/Fixtures/OrderDiscountTaxes.php | 95 +++++ .../Updates/OrderDiscountTaxesUpdateTest.php | 167 ++++++++ 6 files changed, 689 insertions(+), 1 deletion(-) create mode 100644 Classes/Updates/OrderDiscountTaxesUpdate.php create mode 100644 Documentation/Changelog/12.8/Feature-896-OrderDiscountTaxesPerTaxClass.rst create mode 100644 Tests/Functional/Updates/Fixtures/OrderDiscountTaxes.php create mode 100644 Tests/Functional/Updates/OrderDiscountTaxesUpdateTest.php diff --git a/Classes/Updates/OrderDiscountTaxesUpdate.php b/Classes/Updates/OrderDiscountTaxesUpdate.php new file mode 100644 index 00000000..26760e99 --- /dev/null +++ b/Classes/Updates/OrderDiscountTaxesUpdate.php @@ -0,0 +1,360 @@ +output = new NullOutput(); + } + + public function setOutput(OutputInterface $output): void + { + $this->output = $output; + } + + public function getTitle(): string + { + return 'Cart: Store the taxes per tax class of the discounts of orders'; + } + + public function getDescription(): string + { + return 'Calculates the taxes per tax class, the tax class and the coupon type of the discounts of existing' + . ' orders from the stored taxes of the order. Orders whose numbers do not add up are skipped and listed.'; + } + + public function getPrerequisites(): array + { + return [ + DatabaseUpdatedPrerequisite::class, + ]; + } + + public function updateNecessary(): bool + { + return $this->findOrderItemsWithUnknownDiscountTaxes() !== []; + } + + public function executeUpdate(): bool + { + $skipped = []; + foreach ($this->findOrderItemsWithUnknownDiscountTaxes() as $orderItemUid) { + $reason = $this->migrateOrderItem($orderItemUid); + if ($reason !== null) { + $skipped[] = $orderItemUid; + $this->output->writeln( + sprintf('Skipped order item %d: %s', $orderItemUid, $reason) + ); + } + } + + if ($skipped !== []) { + $this->output->writeln( + sprintf( + 'The taxes per tax class of the discounts of %d order(s) are unknown: %s', + count($skipped), + implode(', ', $skipped) + ) + ); + } + + return true; + } + + /** + * @return list + */ + private function findOrderItemsWithUnknownDiscountTaxes(): array + { + $queryBuilder = $this->connectionPool->getQueryBuilderForTable(self::TABLE_DISCOUNT); + $rows = $queryBuilder + ->select('item') + ->distinct() + ->from(self::TABLE_DISCOUNT) + ->where( + $queryBuilder->expr()->or( + $queryBuilder->expr()->isNull('taxes'), + $queryBuilder->expr()->eq('taxes', $queryBuilder->createNamedParameter('')) + ) + ) + ->orderBy('item') + ->executeQuery() + ->fetchFirstColumn() + ; + + return array_map(self::toInt(...), $rows); + } + + /** + * @return null|string the reason why the order item was skipped, null if it was migrated + */ + private function migrateOrderItem(int $orderItemUid): ?string + { + $orderItem = $this->fetchRows('tx_cart_domain_model_order_item', 'uid', $orderItemUid)[0] ?? null; + if ($orderItem === null) { + return 'the order item does not exist or is deleted'; + } + + $discounts = $this->fetchRows(self::TABLE_DISCOUNT, 'item', $orderItemUid); + foreach ($discounts as $discount) { + if (self::toString($discount['taxes']) !== '') { + return 'some discounts already have taxes per tax class'; + } + } + + $services = array_merge( + $this->fetchRows('tx_cart_domain_model_order_shipping', 'item', $orderItemUid), + $this->fetchRows('tx_cart_domain_model_order_payment', 'item', $orderItemUid) + ); + + $couponGross = self::sum($discounts, 'gross'); + $couponNet = self::sum($discounts, 'net'); + $expectedTotalGross = self::toFloat($orderItem['gross']) - $couponGross + self::sum($services, 'gross'); + $expectedTotalNet = self::toFloat($orderItem['net']) - $couponNet + self::sum($services, 'net'); + if ( + !self::equals($expectedTotalGross, self::toFloat($orderItem['total_gross'])) + || !self::equals($expectedTotalNet, self::toFloat($orderItem['total_net'])) + ) { + return 'the total price does not match the prices of the cart, the discounts and the services'; + } + + $couponTaxes = $this->calculateCouponTaxes($orderItemUid, $services); + $taxClassUids = array_map( + static fn (array $row): int => self::toInt($row['uid']), + $this->fetchRows('tx_cart_domain_model_order_taxclass', 'item', $orderItemUid) + ); + foreach ($couponTaxes as $taxClassUid => $tax) { + if (!in_array($taxClassUid, $taxClassUids, true)) { + return sprintf('tax class %d does not belong to the order', $taxClassUid); + } + if ($tax < 0) { + return sprintf('the coupon tax of tax class %d is negative', $taxClassUid); + } + } + if (!self::equals(array_sum($couponTaxes), $couponGross - $couponNet)) { + return 'the taxes do not match gross minus net of the discounts'; + } + + $updates = []; + foreach ($discounts as $discount) { + $gross = self::toFloat($discount['gross']); + $tax = $gross - self::toFloat($discount['net']); + + $taxes = []; + foreach ($couponTaxes as $taxClassUid => $couponTax) { + $share = count($discounts) === 1 ? $couponTax : $couponTax * $gross / $couponGross; + $taxes[$taxClassUid] = round($share, 5); + } + if (!self::equals(array_sum($taxes), $tax)) { + return 'the split of the taxes by gross does not match gross minus net of each discount'; + } + + $updates[self::toInt($discount['uid'])] = [ + 'taxes' => json_encode((object) $taxes, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION), + 'tax_class' => self::determineTaxClass($discount, $taxes), + 'coupon_type' => $this->determineCouponType($discount), + ]; + } + + $connection = $this->connectionPool->getConnectionForTable(self::TABLE_DISCOUNT); + foreach ($updates as $uid => $values) { + $connection->update( + self::TABLE_DISCOUNT, + $values, + ['uid' => $uid], + [ + 'taxes' => Connection::PARAM_STR, + 'tax_class' => Connection::PARAM_INT, + 'coupon_type' => Connection::PARAM_STR, + ] + ); + } + + return null; + } + + /** + * Coupon tax per tax class = tax of the products + tax of the services - total tax. + * + * @param list> $services + * + * @return array uid of the tax class of the order => tax, without zero values + */ + private function calculateCouponTaxes(int $orderItemUid, array $services): array + { + $couponTaxes = []; + foreach ($this->fetchRows('tx_cart_domain_model_order_tax', 'item', $orderItemUid) as $row) { + $taxClassUid = self::toInt($row['tax_class']); + $couponTaxes[$taxClassUid] ??= 0.0; + if ($row['record_type'] === 'tax') { + $couponTaxes[$taxClassUid] += self::toFloat($row['tax']); + } elseif ($row['record_type'] === 'total_tax') { + $couponTaxes[$taxClassUid] -= self::toFloat($row['tax']); + } + } + foreach ($services as $service) { + $taxClassUid = self::toInt($service['tax_class']); + $couponTaxes[$taxClassUid] ??= 0.0; + $couponTaxes[$taxClassUid] += self::toFloat($service['tax']); + } + + $couponTaxes = array_map(static fn (float $tax): float => round($tax, 5), $couponTaxes); + + return array_filter($couponTaxes, static fn (float $tax): bool => abs($tax) > self::TOLERANCE); + } + + /** + * The tax class of a fixed coupon is the only tax class with a tax. The tax + * class of a percentage coupon is not used for the calculation and stays + * unknown. + * + * @param array $discount + * @param array $taxes + */ + private static function determineTaxClass(array $discount, array $taxes): int + { + $tax = self::toFloat($discount['tax']); + if (count($taxes) !== 1 || abs($tax) <= self::TOLERANCE) { + return 0; + } + + $taxClassUid = (int) array_key_first($taxes); + + return self::equals($taxes[$taxClassUid], $tax) ? $taxClassUid : 0; + } + + /** + * Takes the type of the coupon record with the same code, if there is + * exactly one type and it matches the stored tax: a fixed coupon stores its + * tax, a percentage coupon stores 0.0. + * + * @param array $discount + */ + private function determineCouponType(array $discount): string + { + $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tx_cart_domain_model_coupon'); + $queryBuilder->getRestrictions()->removeAll(); + $couponTypes = $queryBuilder + ->select('coupon_type') + ->distinct() + ->from('tx_cart_domain_model_coupon') + ->where( + $queryBuilder->expr()->eq('code', $queryBuilder->createNamedParameter(self::toString($discount['code']))) + ) + ->executeQuery() + ->fetchFirstColumn() + ; + if (count($couponTypes) !== 1) { + return ''; + } + + $couponType = self::toString($couponTypes[0]); + if ($couponType === 'cartdiscount') { + $couponType = CartCouponFix::class; + } + + $tax = self::toFloat($discount['tax']); + $grossMinusNet = self::toFloat($discount['gross']) - self::toFloat($discount['net']); + + return match (true) { + $couponType === CartCouponFix::class && self::equals($tax, $grossMinusNet) => $couponType, + $couponType === CartCouponPercentage::class && self::equals($tax, 0.0) => $couponType, + default => '', + }; + } + + /** + * @return list> + */ + private function fetchRows(string $table, string $field, int $value): array + { + $queryBuilder = $this->connectionPool->getQueryBuilderForTable($table); + + return $queryBuilder + ->select('*') + ->from($table) + ->where( + $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($value, Connection::PARAM_INT)) + ) + ->orderBy('uid') + ->executeQuery() + ->fetchAllAssociative() + ; + } + + /** + * @param list> $rows + */ + private static function sum(array $rows, string $field): float + { + return array_sum(array_map(static fn (array $row): float => self::toFloat($row[$field]), $rows)); + } + + private static function equals(float $a, float $b): bool + { + return abs($a - $b) <= self::TOLERANCE; + } + + private static function toFloat(mixed $value): float + { + return is_numeric($value) ? (float) $value : 0.0; + } + + private static function toInt(mixed $value): int + { + return is_numeric($value) ? (int) $value : 0; + } + + private static function toString(mixed $value): string + { + return is_scalar($value) ? (string) $value : ''; + } +} diff --git a/Documentation/Changelog/12.8/Deprecation-896-OrderDiscountCartTaxClass.rst b/Documentation/Changelog/12.8/Deprecation-896-OrderDiscountCartTaxClass.rst index cbe2deea..576cd3ca 100644 --- a/Documentation/Changelog/12.8/Deprecation-896-OrderDiscountCartTaxClass.rst +++ b/Documentation/Changelog/12.8/Deprecation-896-OrderDiscountCartTaxClass.rst @@ -61,6 +61,6 @@ cart as key: ); The parameters ``$couponType`` and ``$taxes`` are optional, see -:doc:`Feature-OrderDiscountTaxesPerTaxClass`. +:doc:`Feature-896-OrderDiscountTaxesPerTaxClass`. .. index:: PHP-API diff --git a/Documentation/Changelog/12.8/Feature-896-OrderDiscountTaxesPerTaxClass.rst b/Documentation/Changelog/12.8/Feature-896-OrderDiscountTaxesPerTaxClass.rst new file mode 100644 index 00000000..c7492ae7 --- /dev/null +++ b/Documentation/Changelog/12.8/Feature-896-OrderDiscountTaxesPerTaxClass.rst @@ -0,0 +1,61 @@ +.. include:: ../../Includes.rst.txt + +================================================================ +Feature: #896 - Taxes per tax class of the discounts of an order +================================================================ + +See `Issue 896 `__ + +Description +=========== + +A percentage coupon reduces the taxes of all tax classes of the cart, but the +discount of the order (``tx_cart_domain_model_order_discount``) stored only +the tax of the coupon in its own tax class, which is ``0.0`` for percentage +coupons. The tax class of the discount was not stored at all. The totals of +the order were correct. + +The discount of an order now stores: + +``taxes`` + The taxes of the discount per tax class of the order as JSON, the uid of + the tax class of the order (``tx_cart_domain_model_order_taxclass``) is the + key, e.g. ``{"1":0.38,"2":0.07}``. + +``tax_class`` + The tax class of the order the coupon is configured with. + +``coupon_type`` + The class of the coupon in the cart, e.g. + ``Extcode\Cart\Domain\Model\Cart\CartCouponPercentage``. + +The model ``\Extcode\Cart\Domain\Model\Order\Discount`` provides them with +``getTaxes()``, ``getTaxClass()`` and ``getCouponType()``. ``hasTaxes()`` +returns ``false`` if the taxes per tax class are unknown. The constructor got +the optional parameters ``$couponType`` and ``$taxes``; the discount has no +setters, it is not changed after the order was persisted. + +The order views in the backend and in the frontend show the taxes of a +discount in the columns of their tax classes. The frontend view shows the +discounts of the order, too. + +Impact +====== + +Run the database analyzer to add the columns and the upgrade wizard +"Cart: Store the taxes per tax class of the discounts of orders" +(``extcodeCartOrderDiscountTaxes``) for existing orders. + +The upgrade wizard calculates the taxes of the discounts per tax class from +the stored taxes of the order: tax of the products plus tax of shipping and +payment minus total tax. If an order has several discounts, the taxes are +split by their gross. It also stores the tax class of fixed coupons and the +coupon type, if a coupon with the same code still exists. + +The upgrade wizard skips and lists orders whose numbers do not add up, e.g. +orders with special services, whose prices are not stored in the order, or +orders with fixed coupons of different tax classes. The taxes per tax class +of their discounts stay unknown and the tax columns of the discounts stay +empty. + +.. index:: Database, Frontend, Backend diff --git a/Documentation/Changelog/12.8/Index.rst b/Documentation/Changelog/12.8/Index.rst index b44b7e74..9f31b09e 100644 --- a/Documentation/Changelog/12.8/Index.rst +++ b/Documentation/Changelog/12.8/Index.rst @@ -12,6 +12,11 @@ 12.8.0 ------ +Features +~~~~~~~~ + +* :doc:`#896 - Taxes per tax class of the discounts of an order ` + Deprecations ~~~~~~~~~~~~ diff --git a/Tests/Functional/Updates/Fixtures/OrderDiscountTaxes.php b/Tests/Functional/Updates/Fixtures/OrderDiscountTaxes.php new file mode 100644 index 00000000..c2f579f3 --- /dev/null +++ b/Tests/Functional/Updates/Fixtures/OrderDiscountTaxes.php @@ -0,0 +1,95 @@ + [ + ['uid' => 1, 'pid' => 1, 'title' => '10 %', 'code' => 'percentage', 'coupon_type' => CartCouponPercentage::class, 'discount' => 10.0], + ['uid' => 2, 'pid' => 1, 'title' => '11.90', 'code' => 'fix', 'coupon_type' => 'cartdiscount', 'discount' => 11.90, 'deleted' => 1], + ], + 'tx_cart_domain_model_order_item' => [ + ['uid' => 1, 'pid' => 1, 'gross' => 34.50, 'net' => 30.00, 'total_gross' => 38.19, 'total_net' => 33.00], + ['uid' => 2, 'pid' => 1, 'gross' => 34.50, 'net' => 30.00, 'total_gross' => 22.60, 'total_net' => 20.00], + ['uid' => 3, 'pid' => 1, 'gross' => 34.50, 'net' => 30.00, 'total_gross' => 16.65, 'total_net' => 15.00], + ['uid' => 4, 'pid' => 1, 'gross' => 34.50, 'net' => 30.00, 'total_gross' => 11.90, 'total_net' => 10.00], + ['uid' => 5, 'pid' => 1, 'gross' => 34.50, 'net' => 30.00, 'total_gross' => 25.00, 'total_net' => 22.00], + ['uid' => 6, 'pid' => 1, 'gross' => 34.50, 'net' => 30.00, 'total_gross' => 22.60, 'total_net' => 20.00], + ], + 'tx_cart_domain_model_order_taxclass' => [ + ['uid' => 1, 'pid' => 1, 'item' => 1, 'title' => 'normal', 'value' => '19', 'calc' => 0.19], + ['uid' => 2, 'pid' => 1, 'item' => 1, 'title' => 'reduced', 'value' => '7', 'calc' => 0.07], + ['uid' => 3, 'pid' => 1, 'item' => 2, 'title' => 'normal', 'value' => '19', 'calc' => 0.19], + ['uid' => 4, 'pid' => 1, 'item' => 2, 'title' => 'reduced', 'value' => '7', 'calc' => 0.07], + ['uid' => 5, 'pid' => 1, 'item' => 3, 'title' => 'normal', 'value' => '19', 'calc' => 0.19], + ['uid' => 6, 'pid' => 1, 'item' => 3, 'title' => 'reduced', 'value' => '7', 'calc' => 0.07], + ['uid' => 7, 'pid' => 1, 'item' => 4, 'title' => 'normal', 'value' => '19', 'calc' => 0.19], + ['uid' => 8, 'pid' => 1, 'item' => 4, 'title' => 'reduced', 'value' => '7', 'calc' => 0.07], + ['uid' => 9, 'pid' => 1, 'item' => 5, 'title' => 'normal', 'value' => '19', 'calc' => 0.19], + ['uid' => 10, 'pid' => 1, 'item' => 5, 'title' => 'reduced', 'value' => '7', 'calc' => 0.07], + ['uid' => 11, 'pid' => 1, 'item' => 6, 'title' => 'normal', 'value' => '19', 'calc' => 0.19], + ['uid' => 12, 'pid' => 1, 'item' => 6, 'title' => 'reduced', 'value' => '7', 'calc' => 0.07], + ], + 'tx_cart_domain_model_order_shipping' => [ + ['uid' => 1, 'pid' => 1, 'item' => 1, 'name' => 'Standard', 'gross' => 5.95, 'net' => 5.00, 'tax' => 0.95, 'tax_class' => 1], + ], + 'tx_cart_domain_model_order_payment' => [ + ['uid' => 1, 'pid' => 1, 'item' => 1, 'name' => 'Invoice', 'gross' => 1.19, 'net' => 1.00, 'tax' => 0.19, 'tax_class' => 1], + ], + 'tx_cart_domain_model_order_discount' => [ + ['uid' => 1, 'pid' => 1, 'item' => 1, 'title' => '10 %', 'code' => 'percentage', 'gross' => 3.45, 'net' => 3.00, 'tax' => 0.0], + ['uid' => 2, 'pid' => 1, 'item' => 2, 'title' => '11.90', 'code' => 'fix', 'gross' => 11.90, 'net' => 10.00, 'tax' => 1.90], + ['uid' => 3, 'pid' => 1, 'item' => 3, 'title' => '5.95', 'code' => 'first', 'gross' => 5.95, 'net' => 5.00, 'tax' => 0.95], + ['uid' => 4, 'pid' => 1, 'item' => 3, 'title' => '11.90', 'code' => 'second', 'gross' => 11.90, 'net' => 10.00, 'tax' => 1.90], + ['uid' => 5, 'pid' => 1, 'item' => 4, 'title' => '11.90', 'code' => 'normal', 'gross' => 11.90, 'net' => 10.00, 'tax' => 1.90], + ['uid' => 6, 'pid' => 1, 'item' => 4, 'title' => '10.70', 'code' => 'reduced', 'gross' => 10.70, 'net' => 10.00, 'tax' => 0.70], + ['uid' => 7, 'pid' => 1, 'item' => 5, 'title' => '11.90', 'code' => 'fix', 'gross' => 11.90, 'net' => 10.00, 'tax' => 1.90], + ['uid' => 8, 'pid' => 1, 'item' => 6, 'title' => '11.90', 'code' => 'fix', 'gross' => 11.90, 'net' => 10.00, 'tax' => 1.90, 'tax_class' => 11, 'taxes' => '{"11":1.9}'], + ], + 'tx_cart_domain_model_order_tax' => [ + ['uid' => 1, 'pid' => 1, 'item' => 1, 'record_type' => 'tax', 'tax' => 3.80, 'tax_class' => 1], + ['uid' => 2, 'pid' => 1, 'item' => 1, 'record_type' => 'tax', 'tax' => 0.70, 'tax_class' => 2], + ['uid' => 3, 'pid' => 1, 'item' => 1, 'record_type' => 'total_tax', 'tax' => 4.56, 'tax_class' => 1], + ['uid' => 4, 'pid' => 1, 'item' => 1, 'record_type' => 'total_tax', 'tax' => 0.63, 'tax_class' => 2], + + ['uid' => 5, 'pid' => 1, 'item' => 2, 'record_type' => 'tax', 'tax' => 3.80, 'tax_class' => 3], + ['uid' => 6, 'pid' => 1, 'item' => 2, 'record_type' => 'tax', 'tax' => 0.70, 'tax_class' => 4], + ['uid' => 7, 'pid' => 1, 'item' => 2, 'record_type' => 'total_tax', 'tax' => 1.90, 'tax_class' => 3], + ['uid' => 8, 'pid' => 1, 'item' => 2, 'record_type' => 'total_tax', 'tax' => 0.70, 'tax_class' => 4], + + ['uid' => 9, 'pid' => 1, 'item' => 3, 'record_type' => 'tax', 'tax' => 3.80, 'tax_class' => 5], + ['uid' => 10, 'pid' => 1, 'item' => 3, 'record_type' => 'tax', 'tax' => 0.70, 'tax_class' => 6], + ['uid' => 11, 'pid' => 1, 'item' => 3, 'record_type' => 'total_tax', 'tax' => 0.95, 'tax_class' => 5], + ['uid' => 12, 'pid' => 1, 'item' => 3, 'record_type' => 'total_tax', 'tax' => 0.70, 'tax_class' => 6], + + ['uid' => 13, 'pid' => 1, 'item' => 4, 'record_type' => 'tax', 'tax' => 3.80, 'tax_class' => 7], + ['uid' => 14, 'pid' => 1, 'item' => 4, 'record_type' => 'tax', 'tax' => 0.70, 'tax_class' => 8], + ['uid' => 15, 'pid' => 1, 'item' => 4, 'record_type' => 'total_tax', 'tax' => 1.90, 'tax_class' => 7], + ['uid' => 16, 'pid' => 1, 'item' => 4, 'record_type' => 'total_tax', 'tax' => 0.00, 'tax_class' => 8], + + ['uid' => 17, 'pid' => 1, 'item' => 5, 'record_type' => 'tax', 'tax' => 3.80, 'tax_class' => 9], + ['uid' => 18, 'pid' => 1, 'item' => 5, 'record_type' => 'tax', 'tax' => 0.70, 'tax_class' => 10], + ['uid' => 19, 'pid' => 1, 'item' => 5, 'record_type' => 'total_tax', 'tax' => 1.90, 'tax_class' => 9], + ['uid' => 20, 'pid' => 1, 'item' => 5, 'record_type' => 'total_tax', 'tax' => 0.70, 'tax_class' => 10], + + ['uid' => 21, 'pid' => 1, 'item' => 6, 'record_type' => 'tax', 'tax' => 3.80, 'tax_class' => 11], + ['uid' => 22, 'pid' => 1, 'item' => 6, 'record_type' => 'tax', 'tax' => 0.70, 'tax_class' => 12], + ['uid' => 23, 'pid' => 1, 'item' => 6, 'record_type' => 'total_tax', 'tax' => 1.90, 'tax_class' => 11], + ['uid' => 24, 'pid' => 1, 'item' => 6, 'record_type' => 'total_tax', 'tax' => 0.70, 'tax_class' => 12], + ], +]; diff --git a/Tests/Functional/Updates/OrderDiscountTaxesUpdateTest.php b/Tests/Functional/Updates/OrderDiscountTaxesUpdateTest.php new file mode 100644 index 00000000..28df9096 --- /dev/null +++ b/Tests/Functional/Updates/OrderDiscountTaxesUpdateTest.php @@ -0,0 +1,167 @@ +importPHPDataSet(__DIR__ . '/Fixtures/OrderDiscountTaxes.php'); + + $registry = $this->get(UpgradeWizardRegistry::class); + self::assertInstanceOf(UpgradeWizardRegistry::class, $registry); + $subject = $registry->getUpgradeWizard('extcodeCartOrderDiscountTaxes'); + self::assertInstanceOf(OrderDiscountTaxesUpdate::class, $subject); + $this->subject = $subject; + $this->output = new BufferedOutput(); + $this->subject->setOutput($this->output); + } + + #[Test] + public function updateIsNecessaryForDiscountsWithoutTaxesPerTaxClass(): void + { + self::assertTrue($this->subject->updateNecessary()); + } + + #[Test] + public function updateIsNotNecessaryIfAllDiscountsHaveTaxesPerTaxClass(): void + { + GeneralUtility::makeInstance(ConnectionPool::class) + ->getConnectionForTable('tx_cart_domain_model_order_discount') + ->executeStatement('UPDATE tx_cart_domain_model_order_discount SET taxes = \'{}\' ') + ; + + self::assertFalse($this->subject->updateNecessary()); + } + + #[Test] + public function storesTheTaxesPerTaxClassOfAPercentageCoupon(): void + { + self::assertTrue($this->subject->executeUpdate()); + + self::assertSame( + ['taxes' => '{"1":0.38,"2":0.07}', 'tax_class' => 0, 'coupon_type' => CartCouponPercentage::class], + self::getDiscount(1) + ); + } + + #[Test] + public function storesTheTaxAndTheTaxClassOfAFixedCoupon(): void + { + self::assertTrue($this->subject->executeUpdate()); + + self::assertSame( + ['taxes' => '{"3":1.9}', 'tax_class' => 3, 'coupon_type' => CartCouponFix::class], + self::getDiscount(2) + ); + } + + #[Test] + public function splitsTheTaxesOfSeveralCouponsByGross(): void + { + self::assertTrue($this->subject->executeUpdate()); + + self::assertSame( + ['taxes' => '{"5":0.95}', 'tax_class' => 5, 'coupon_type' => ''], + self::getDiscount(3) + ); + self::assertSame( + ['taxes' => '{"5":1.9}', 'tax_class' => 5, 'coupon_type' => ''], + self::getDiscount(4) + ); + } + + #[Test] + public function skipsOrdersWhoseNumbersDoNotAddUp(): void + { + self::assertTrue($this->subject->executeUpdate()); + + foreach ([5, 6, 7] as $discountUid) { + self::assertSame( + ['taxes' => '', 'tax_class' => 0, 'coupon_type' => ''], + self::getDiscount($discountUid) + ); + } + + $output = $this->output->fetch(); + self::assertStringContainsString( + 'Skipped order item 4: the split of the taxes by gross does not match gross minus net of each discount', + $output + ); + self::assertStringContainsString( + 'Skipped order item 5: the total price does not match the prices of the cart, the discounts and the services', + $output + ); + self::assertStringContainsString( + 'The taxes per tax class of the discounts of 2 order(s) are unknown: 4, 5', + $output + ); + } + + #[Test] + public function keepsDiscountsWhichAlreadyHaveTaxesPerTaxClass(): void + { + self::assertTrue($this->subject->executeUpdate()); + + self::assertSame( + ['taxes' => '{"11":1.9}', 'tax_class' => 11, 'coupon_type' => ''], + self::getDiscount(8) + ); + } + + /** + * @return array{taxes: string, tax_class: int, coupon_type: string} + */ + private static function getDiscount(int $uid): array + { + $row = GeneralUtility::makeInstance(ConnectionPool::class) + ->getConnectionForTable('tx_cart_domain_model_order_discount') + ->select(['taxes', 'tax_class', 'coupon_type'], 'tx_cart_domain_model_order_discount', ['uid' => $uid]) + ->fetchAssociative() + ; + self::assertIsArray($row); + self::assertTrue($row['taxes'] === null || is_string($row['taxes'])); + self::assertIsNumeric($row['tax_class']); + self::assertIsString($row['coupon_type']); + + return [ + 'taxes' => $row['taxes'] ?? '', + 'tax_class' => (int) $row['tax_class'], + 'coupon_type' => $row['coupon_type'], + ]; + } +}