From 207702c2f1e849c6f6523304edc5f0e2b488f38f Mon Sep 17 00:00:00 2001 From: smarcet Date: Wed, 18 Nov 2026 20:07:35 -0300 Subject: [PATCH 1/5] fix(refunds): give back the tax an order was charged, to the cent An order is charged each tax rounded to cents once, over all its tickets. A refund stored each ticket's tax without rounding and rounded once per refund request, so refunding every ticket of an order asked the payment gateway for a cent or more under the charge, or over it. Each tax refund now follows the order's running total for that tax: the tax on everything the order has refunded so far, rounded the way the charge rounds it, less the tax its other approved refunds already gave back. Tickets without taxes refund as before. --- .../SummitAttendeeTicketRefundRequest.php | 44 +++- .../SummitOrderRefundRoundingTest.php | 201 ++++++++++++++++++ 2 files changed, 242 insertions(+), 3 deletions(-) create mode 100644 tests/Unit/Entities/SummitOrderRefundRoundingTest.php diff --git a/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php b/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php index 5f1ef9574e..1882e2d2aa 100644 --- a/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php +++ b/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php @@ -77,17 +77,55 @@ public function __construct(?Member $requested_by = null) */ protected function calculateTaxesRefundedAmountFrom(float $amount_2_refund):Collection{ $this->refunded_taxes->clear(); - // create a collection of all applied taxes and their refunds components + if ($this->ticket->getAppliedTaxes()->isEmpty()) return $this->refunded_taxes; + // The order is charged each tax rounded to cents once, over all its + // tickets (SummitOrder::getFinalAmount). A refund follows that same + // running total: the tax on everything refunded so far, rounded the + // same way, less the tax already given back. Refunding the whole + // order then gives back the tax that was charged, to the cent. + $so_far = $this->getOrderTaxRefundsSoFar(); foreach ($this->ticket->getAppliedTaxes() as $applied_tax) { + $tax = $applied_tax->getTax(); + list($tax_so_far, $refunded_so_far) = $so_far[$tax->getId()] ?? [0.0, 0.0]; + $tax_so_far += $applied_tax->applyTo($amount_2_refund, false); $tax_refund = new SummitTaxRefund ( $this, - $applied_tax->getTax(), - $applied_tax->applyTo($amount_2_refund, false) + $tax, + max(0.0, $tax->round($tax->round($tax_so_far) - $refunded_so_far)) ); $this->refunded_taxes->add($tax_refund); } return $this->refunded_taxes; } + /** + * What the order's other approved refunds add up to, by tax id: the tax on + * the refunded ticket price before rounding, and the tax given back. + * The tax is worked out again from the refunded ticket price because the + * tax refunds stored before refunds followed the charge are not rounded. + * @return float[][] + */ + private function getOrderTaxRefundsSoFar():array{ + $so_far = []; + foreach ($this->ticket->getOrder()->getTickets() as $ticket) { + foreach ($ticket->getRefundedRequests() as $request) { + // approve() marks this request as approved before its taxes are calculated + if ($request === $this) continue; + if ($request->getStatus() !== ISummitRefundRequestConstants::ApprovedStatus) continue; + foreach ($ticket->getAppliedTaxes() as $applied_tax) { + $tax_id = $applied_tax->getTax()->getId(); + $so_far[$tax_id] ??= [0.0, 0.0]; + $so_far[$tax_id][0] += $applied_tax->applyTo($request->getRefundedAmount(), false); + } + foreach ($request->getRefundedTaxes() as $tax_refund) { + $tax_id = $tax_refund->getTax()->getId(); + $so_far[$tax_id] ??= [0.0, 0.0]; + $so_far[$tax_id][1] += $tax_refund->getRefundedAmount(); + } + } + } + return $so_far; + } + } \ No newline at end of file diff --git a/tests/Unit/Entities/SummitOrderRefundRoundingTest.php b/tests/Unit/Entities/SummitOrderRefundRoundingTest.php new file mode 100644 index 0000000000..4871b03ad9 --- /dev/null +++ b/tests/Unit/Entities/SummitOrderRefundRoundingTest.php @@ -0,0 +1,201 @@ +setValue($entity, self::$next_id++); + return $entity; + } + + /** + * @param float $price ticket price + * @param int $qty tickets on the order + * @param float[] $rates one tax per rate, in percent + */ + private static function buildOrder(float $price, int $qty, array $rates): SummitOrder + { + // a ticket type asks its summit for the default badge type, and a + // ticket takes its summit from the order + $summit = new Summit(); + + $ticket_type = self::withId(new SummitTicketType()); + $ticket_type->setSummit($summit); + $ticket_type->setName('General Admission'); + $ticket_type->setCost($price); + + $taxes = []; + foreach ($rates as $rate) { + $tax = self::withId(new SummitTaxType()); + $tax->setName(sprintf('%s%% tax', $rate)); + $tax->setRate($rate); + $taxes[] = $tax; + } + + $order = self::withId(new SummitOrder()); + $order->setSummit($summit); + for ($i = 0; $i < $qty; $i++) { + $ticket = self::withId(new SummitAttendeeTicket()); + $ticket->setTicketType($ticket_type); + $ticket->applyTaxes($taxes); + $order->addTicket($ticket); + } + return $order; + } + + /** + * Refunds each ticket in the given parts and returns what each refund + * sends to the payment gateway, in cents: StripeApi::refundPayment converts + * SummitRefundRequest::getTotalRefundedAmount the same way. + * + * @param float[] $parts ticket price parts refunded on every ticket, in order + * @return int[] + */ + private static function refundEveryTicket(SummitOrder $order, array $parts): array + { + $sent = []; + foreach ($order->getTickets() as $ticket) { + foreach ($parts as $part) { + $request = $ticket->refund(null, $part, null, null, false); + $sent[] = $request->getTotalRefundedAmountInCents(); + } + } + return $sent; + } + + public static function fullyRefundedOrders(): array + { + return [ + // 1.938 + 0.255 of tax: charged 1.94 + 0.26 + 'one ticket, two taxes' => [10.20, 1, [19.0, 2.5], [10.20], 1240], + // 1.9038 of tax per ticket: charged round(5.7114) = 5.71 + 'three tickets, one tax, tax fractions under half a cent' => [10.02, 3, [19.0], [10.02], 3577], + // 1.9076 of tax per ticket: charged round(5.7228) = 5.72 + 'three tickets, one tax, tax fractions over half a cent' => [10.04, 3, [19.0], [10.04], 3584], + // charged round(3.876) + round(0.51) = 3.88 + 0.51 + 'two tickets, two taxes' => [10.20, 2, [19.0, 2.5], [10.20], 2479], + // the same ticket refunded in three parts + 'one ticket, two taxes, refunded in parts' => [10.20, 1, [19.0, 2.5], [4.0, 4.0, 2.2], 1240], + // whole cents all the way: nothing to round + 'one ticket, one tax, no fractions' => [1.00, 1, [19.0], [1.00], 119], + ]; + } + + #[DataProvider('fullyRefundedOrders')] + public function testFullRefundSendsBackExactlyWhatWasCharged( + float $price, int $qty, array $rates, array $parts, int $charged_cents + ): void + { + $order = self::buildOrder($price, $qty, $rates); + // what StripeApi::generatePayment charges + $this->assertSame($charged_cents, $order->getFinalAmountInCents(), 'charged amount'); + + $sent = self::refundEveryTicket($order, $parts); + + $this->assertSame($charged_cents, array_sum($sent), 'sent to the gateway: ' . implode(' + ', $sent)); + } + + #[DataProvider('fullyRefundedOrders')] + public function testRefundsNeverGoOverTheCharge( + float $price, int $qty, array $rates, array $parts, int $charged_cents + ): void + { + $order = self::buildOrder($price, $qty, $rates); + $running = 0; + foreach ($order->getTickets() as $ticket) { + foreach ($parts as $part) { + $running += $ticket->refund(null, $part, null, null, false)->getTotalRefundedAmountInCents(); + $this->assertLessThanOrEqual($charged_cents, $running); + } + } + } + + #[DataProvider('fullyRefundedOrders')] + public function testRefundedTaxReadsTheSameEitherWayAClientAddsItUp( + float $price, int $qty, array $rates, array $parts, int $charged_cents + ): void + { + $order = self::buildOrder($price, $qty, $rates); + self::refundEveryTicket($order, $parts); + + // the order's own totals, as the API serializes them (json_money) + $from_order_totals = + self::cents(JsonUtils::toJsonMoney($order->getTotalRefundedAmount())) - + self::cents(JsonUtils::toJsonMoney($order->getRefundedAmount())); + + // each tax added up over the refund requests, then rounded to cents + $by_tax = []; + foreach ($order->getTickets() as $ticket) { + foreach ($ticket->getRefundedRequests() as $request) { + foreach ($request->getRefundedTaxes() as $tax_refund) { + $tax_id = $tax_refund->getTax()->getId(); + $by_tax[$tax_id] = ($by_tax[$tax_id] ?? 0.0) + $tax_refund->getRefundedAmount(); + } + } + } + $from_refund_requests = array_sum(array_map( + fn(float $amount) => self::cents(JsonUtils::toJsonMoney($amount)), + $by_tax + )); + + $this->assertSame($from_refund_requests, $from_order_totals); + // and it is the tax the order was charged + $this->assertSame($order->getTaxesAmountInCents(), $from_order_totals); + } + + private static function cents(float $amount): int + { + return intval(round($amount * 100)); + } +} From 1139bfbc28d62f7233f98c5494cb4cd8df9a06e4 Mon Sep 17 00:00:00 2001 From: smarcet Date: Wed, 18 Nov 2026 20:30:05 -0300 Subject: [PATCH 2/5] fix(refunds): approve the refunds of an order one at a time A refund works out its taxes from what the order has refunded so far, so two refunds of the same order approved at the same time both started from the same total and drifted by a cent again. Asking a refund for a whole order queues one ProcessTicketRefundRequest job per ticket, which makes that the usual case. SummitOrderService::refundTicket and ProcessTicketRefundRequest now lock the order before the ticket, the order the other flows of the service already follow. Taking the lock also reads the refund requests of the order's tickets again: a queue worker keeps its entity manager from one job to the next and would otherwise compute from what it loaded before the lock was granted. --- .github/workflows/push.yml | 1 + app/Jobs/ProcessTicketRefundRequest.php | 21 +- .../Repositories/ISummitOrderRepository.php | 9 + .../Summit/DoctrineSummitOrderRepository.php | 27 +++ app/Services/Model/Imp/SummitOrderService.php | 20 +- tests/SummitOrderRefundSerializationTest.php | 200 ++++++++++++++++++ 6 files changed, 269 insertions(+), 9 deletions(-) create mode 100644 tests/SummitOrderRefundSerializationTest.php diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml index c4323141e3..559933ca19 100644 --- a/.github/workflows/push.yml +++ b/.github/workflows/push.yml @@ -83,6 +83,7 @@ jobs: - { name: "SpeakerBulkEmailChunkResume", filter: "tests/SpeakerServiceBulkSendChunkingTest.php tests/SpeakerServiceResumeSendEmailsTest.php tests/ProcessSpeakersEmailRequestJobResumeTest.php tests/ProcessSpeakersEmailRequestJobFailedHookTest.php" } - { name: "AttendeeBulkEmailChunkResume", filter: "tests/AttendeeServiceBulkSendChunkingTest.php tests/AttendeeServiceResumeSendEmailsTest.php tests/ProcessAttendeesEmailRequestJobResumeTest.php tests/ProcessAttendeesEmailRequestJobFailedHookTest.php tests/SummitAttendeeAnnouncementEmailTest.php tests/DoctrineSummitAttendeeRepositoryTest.php tests/SummitExtraQuestionsMemoizationTest.php" } - { name: "SummitJsonGenerator", filter: "tests/SummitJsonGeneratorCommandTest.php" } + - { name: "SummitOrderRefundSerialization", filter: "tests/SummitOrderRefundSerializationTest.php" } - { name: "Repositories", filter: "tests/Repositories/" } - { name: "Services", filter: "tests/Unit/Services/" } - { name: "Integration", filter: "tests/Integration/" } diff --git a/app/Jobs/ProcessTicketRefundRequest.php b/app/Jobs/ProcessTicketRefundRequest.php index f94bd481eb..6b675d75b4 100644 --- a/app/Jobs/ProcessTicketRefundRequest.php +++ b/app/Jobs/ProcessTicketRefundRequest.php @@ -13,6 +13,7 @@ **/ use App\Models\Foundation\Summit\Registration\IBuildDefaultPaymentGatewayProfileStrategy; +use App\Models\Foundation\Summit\Repositories\ISummitOrderRepository; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; @@ -24,6 +25,7 @@ use models\summit\IPaymentConstants; use models\summit\ISummitAttendeeTicketRepository; use models\summit\SummitAttendeeTicket; +use models\summit\SummitOrder; /** * Class ProcessTicketRefundRequest @@ -60,25 +62,38 @@ public function __construct(int $ticket_id, int $requested_n_days_before_summit) * @param IBuildDefaultPaymentGatewayProfileStrategy $default_payment_gateway_strategy * @param ISummitAttendeeTicketRepository $repository * @param ITransactionService $tx_service + * @param ISummitOrderRepository $order_repository * @throws \Exception */ public function handle ( IBuildDefaultPaymentGatewayProfileStrategy $default_payment_gateway_strategy, ISummitAttendeeTicketRepository $repository, - ITransactionService $tx_service + ITransactionService $tx_service, + ISummitOrderRepository $order_repository ) { // todo : move to service layer try { - $tx_service->transaction(function () use ($default_payment_gateway_strategy, $repository) { + $tx_service->transaction(function () use ($default_payment_gateway_strategy, $repository, $order_repository) { Log::debug(sprintf("ProcessTicketRefundRequest::handle processing ticket %s", $this->ticket_id)); + $ticket = $repository->getById($this->ticket_id); + + if (!$ticket instanceof SummitAttendeeTicket) return; + + // A refund works out its taxes from what the order has refunded so + // far, and refunding a whole order queues one of these jobs per + // ticket: lock the order first, then the ticket, so they are + // approved one at a time. + $order = $order_repository->getByIdExclusiveLockRefreshingRefunds($ticket->getOrderId()); + + if (!$order instanceof SummitOrder) return; + $ticket = $repository->getByIdExclusiveLock($this->ticket_id); if (!$ticket instanceof SummitAttendeeTicket || !$ticket->isRefundRequested()) return; - $order = $ticket->getOrder(); $summit = $order->getSummit(); Log::debug(sprintf("ProcessTicketRefundRequest::handle got ticket %s", $ticket->getNumber())); diff --git a/app/Models/Foundation/Summit/Repositories/ISummitOrderRepository.php b/app/Models/Foundation/Summit/Repositories/ISummitOrderRepository.php index 6c220b8382..b4f1c428ee 100644 --- a/app/Models/Foundation/Summit/Repositories/ISummitOrderRepository.php +++ b/app/Models/Foundation/Summit/Repositories/ISummitOrderRepository.php @@ -35,6 +35,15 @@ public function getByHashLockExclusive(string $hash): ?SummitOrder; */ public function getByPaymentGatewayCartIdExclusiveLock(string $payment_gateway_cart_id): ?SummitOrder; + /** + * Locks the order and reads again the refund requests of all its tickets, + * so refunds of the same order are approved one at a time and each one + * sees the refunds approved before it. + * @param int $order_id + * @return SummitOrder|null + */ + public function getByIdExclusiveLockRefreshingRefunds(int $order_id): ?SummitOrder; + /** * @param string $externalId * @return SummitOrder|null diff --git a/app/Repositories/Summit/DoctrineSummitOrderRepository.php b/app/Repositories/Summit/DoctrineSummitOrderRepository.php index 317bbe5cdb..c5ea88ad17 100644 --- a/app/Repositories/Summit/DoctrineSummitOrderRepository.php +++ b/app/Repositories/Summit/DoctrineSummitOrderRepository.php @@ -89,6 +89,33 @@ public function getByPaymentGatewayCartIdExclusiveLock(string $payment_gateway_c ->getOneOrNullResult(); } + /** + * @param int $order_id + * @return SummitOrder|null + */ + public function getByIdExclusiveLockRefreshingRefunds(int $order_id): ?SummitOrder + { + $order = $this->getByIdExclusiveLock($order_id); + if (!$order instanceof SummitOrder) return null; + + // A queue worker keeps its entity manager from one job to the next, so + // it can hold the order's tickets and their refund requests as they + // were before the lock was granted. Read them again, in one query. + $this->getEntityManager() + ->createQueryBuilder() + ->select("t, r, tr") + ->from(SummitAttendeeTicket::class, "t") + ->leftJoin("t.refund_requests", "r") + ->leftJoin("r.refunded_taxes", "tr") + ->where("t.order = :order") + ->setParameter("order", $order) + ->getQuery() + ->setHint(\Doctrine\ORM\Query::HINT_REFRESH, true) + ->getResult(); + + return $order; + } + /** * @param string $email * @return mixed diff --git a/app/Services/Model/Imp/SummitOrderService.php b/app/Services/Model/Imp/SummitOrderService.php index 9f490a9551..a20cc08f7e 100644 --- a/app/Services/Model/Imp/SummitOrderService.php +++ b/app/Services/Model/Imp/SummitOrderService.php @@ -2639,7 +2639,7 @@ public function refundTicket(Summit $summit, Member $currentUser, $ticket_id, fl ) ); - $ticket = $this->ticket_repository->getByIdExclusiveLock(intval($ticket_id)); + $ticket = $this->ticket_repository->getById(intval($ticket_id)); if (!$ticket instanceof SummitAttendeeTicket) $this->ticket_repository->getByNumberExclusiveLock(strval($ticket_id)); @@ -2651,6 +2651,19 @@ public function refundTicket(Summit $summit, Member $currentUser, $ticket_id, fl throw new ValidationException("Can not refund an amount lower than zero."); } + // A refund works out its taxes from what the order has refunded so + // far, so refunds of the same order are approved one at a time: + // lock the order first, then the ticket. + $order = $this->order_repository->getByIdExclusiveLockRefreshingRefunds($ticket->getOrderId()); + + if (!$order instanceof SummitOrder || $order->getSummitId() != $summit->getId()) + throw new EntityNotFoundException('Ticket not found.'); + + $ticket = $this->ticket_repository->getByIdExclusiveLock($ticket->getId()); + + if (!$ticket instanceof SummitAttendeeTicket) + throw new EntityNotFoundException('Ticket not found.'); + if (!$ticket->canRefund($amount_2_refund)) { throw new ValidationException ( @@ -2662,11 +2675,6 @@ public function refundTicket(Summit $summit, Member $currentUser, $ticket_id, fl ); } - $order = $ticket->getOrder(); - - if ($order->getSummitId() != $summit->getId()) - throw new EntityNotFoundException('Ticket not found.'); - $request = $ticket->refund($currentUser, $amount_2_refund, null, $notes); return [$ticket, $order, $request]; diff --git a/tests/SummitOrderRefundSerializationTest.php b/tests/SummitOrderRefundSerializationTest.php new file mode 100644 index 0000000000..c9e457db59 --- /dev/null +++ b/tests/SummitOrderRefundSerializationTest.php @@ -0,0 +1,200 @@ +setOrder($order); + $ticket->setTicketType(self::$default_ticket_type); + $ticket->generateNumber(); + self::$default_ticket_type->sell(1); + $ticket->generateHash(); + $ticket->generateQRCode(); + $ticket->applyTaxes(self::$summit->getTaxTypes()->toArray()); + $order->addTicket($ticket); + $ticket->setPaid(); + } + self::$em->persist(self::$summit); + self::$em->flush(); + + $this->order_id = $order->getId(); + $this->tickets = $order->getTickets()->toArray(); + + // what a long running worker holds: the tickets with their refund requests loaded, none yet + foreach ($this->tickets as $ticket) + $this->assertCount(0, $ticket->getRefundedRequests()->toArray()); + + // refunds queue emails and the payment gateway job + Bus::fake(); + } + + protected function tearDown(): void + { + self::clearSummitTestData(); + parent::tearDown(); + } + + /** + * Another worker approves a refund. It goes through its own entity manager, + * so the one under test knows nothing about it. + */ + private function refundFromAnotherWorker(SummitAttendeeTicket $ticket, float $amount): void + { + $other = new EntityManager(self::$em->getConnection(), self::$em->getConfiguration()); + $other->find(SummitAttendeeTicket::class, $ticket->getId())->refund(null, $amount, null, null, false); + $other->flush(); + + $this->assertCount(0, $ticket->getRefundedRequests(), 'the entity manager under test must not know the refund'); + } + + /** + * @return int[] cents given back by the ticket's approved refunds, by tax name + */ + private function approvedTaxRefundsInCents(SummitAttendeeTicket $ticket): array + { + $cents = []; + foreach ($ticket->getRefundedRequests() as $request) { + if ($request->getStatus() !== ISummitRefundRequestConstants::ApprovedStatus) continue; + foreach ($request->getRefundedTaxes() as $tax_refund) { + $name = $tax_refund->getTax()->getName(); + $cents[$name] = ($cents[$name] ?? 0) + $tax_refund->getRefundedAmountInCents(); + } + } + ksort($cents); + return $cents; + } + + public function testLockingTheOrderReadsAgainTheRefundsOfItsTickets(): void + { + list($first) = $this->tickets; + $this->refundFromAnotherWorker($first, self::Amount); + + App::make(ITransactionService::class)->transaction(function () { + App::make(ISummitOrderRepository::class)->getByIdExclusiveLockRefreshingRefunds($this->order_id); + }); + + $this->assertSame(['TAX 1' => 105, 'TAX 2' => 15], $this->approvedTaxRefundsInCents($first)); + } + + public function testTheOrderStaysLockedUntilTheTransactionEnds(): void + { + $other = DriverManager::getConnection(self::$em->getConnection()->getParams()); + $lock_order = function () use ($other) { + // autocommit: the lock is released as soon as the statement ends + return $other->fetchOne('SELECT ID FROM SummitOrder WHERE ID = ? FOR UPDATE NOWAIT', [$this->order_id]); + }; + + $refused_with = null; + App::make(ITransactionService::class)->transaction(function () use ($lock_order, &$refused_with) { + App::make(ISummitOrderRepository::class)->getByIdExclusiveLockRefreshingRefunds($this->order_id); + try { + $lock_order(); + } catch (DriverException $ex) { + $refused_with = $ex->getCode(); + } + }); + + $this->assertSame(self::LockNotAvailable, $refused_with, 'another connection must not get the order while it is locked'); + $this->assertEquals($this->order_id, $lock_order(), 'the order is free again once the transaction ends'); + $other->close(); + } + + public function testAdminRefundCountsARefundAnotherWorkerCommitted(): void + { + list($first, $second) = $this->tickets; + $this->refundFromAnotherWorker($first, self::Amount); + + $ticket = App::make(ISummitOrderService::class) + ->refundTicket(self::$summit, self::$member, $second->getId(), self::Amount, null); + + $this->assertSame(['TAX 1' => 106, 'TAX 2' => 15], $this->approvedTaxRefundsInCents($ticket)); + } + + public function testRefundPolicyJobCountsARefundAnotherWorkerCommitted(): void + { + list($first, $second) = $this->tickets; + + // a policy that gives back 10.04% of a 100.00 ticket, and the buyer's pending request + $policy = new SummitRefundPolicyType(); + $policy->setName('REFUND POLICY'); + $policy->setUntilXDaysBeforeEventStarts(0); + $policy->setRefundRate(self::Amount); + self::$summit->addRefundPolicy($policy); + $pending = new SummitAttendeeTicketRefundRequest(self::$member); + $pending->setTicket($second); + $second->getRefundedRequests()->add($pending); + self::$em->persist(self::$summit); + self::$em->flush(); + + $this->refundFromAnotherWorker($first, self::Amount); + + App::call([new ProcessTicketRefundRequest($second->getId(), 10), 'handle']); + + $this->assertSame(['TAX 1' => 106, 'TAX 2' => 15], $this->approvedTaxRefundsInCents($second)); + } +} From b5355c2cc64ae417f47280119bdc34280a8bb574 Mon Sep 17 00:00:00 2001 From: smarcet Date: Wed, 18 Nov 2026 22:38:34 -0300 Subject: [PATCH 3/5] fix(refunds): count what earlier refunds sent to the gateway A refund subtracts the tax the order's other refunds already gave back. For refunds approved before refunds followed the charge, that was read from tax refunds stored without rounding, while the gateway had been sent the total of the request rounded once. The next refund could then ask for a cent more than was left on the charge: two 10.12 tickets taxed 19 and 2.5 percent, the first refunded by the old code, sent 1230 + 1231 for a 2460 charge. Each earlier refund now counts for the tax it sent to the gateway, in cents, split among its taxes. --- .../SummitAttendeeTicketRefundRequest.php | 34 ++++++++++-- .../SummitOrderRefundRoundingTest.php | 53 +++++++++++++++++++ 2 files changed, 84 insertions(+), 3 deletions(-) diff --git a/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php b/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php index 1882e2d2aa..a3a68a8c4f 100644 --- a/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php +++ b/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php @@ -118,14 +118,42 @@ private function getOrderTaxRefundsSoFar():array{ $so_far[$tax_id] ??= [0.0, 0.0]; $so_far[$tax_id][0] += $applied_tax->applyTo($request->getRefundedAmount(), false); } - foreach ($request->getRefundedTaxes() as $tax_refund) { - $tax_id = $tax_refund->getTax()->getId(); + foreach (self::getTaxesSentToGatewayInCents($request) as $tax_id => $cents) { $so_far[$tax_id] ??= [0.0, 0.0]; - $so_far[$tax_id][1] += $tax_refund->getRefundedAmount(); + $so_far[$tax_id][1] += $cents / 100; } } } return $so_far; } + /** + * What an approved refund gave back of each tax, by tax id, in cents that + * add up to the tax it sent to the payment gateway. The gateway is sent + * the total of the request rounded once (getTotalRefundedAmountInCents), + * and the tax refunds stored before refunds followed the charge are not + * rounded: rounded one by one they can add up to a cent more or less than + * what was sent. That cent goes to the tax that was furthest from its + * rounded amount. + * @return int[] + */ + private static function getTaxesSentToGatewayInCents(SummitRefundRequest $request):array{ + $cents = []; + $left_over = []; + foreach ($request->getRefundedTaxes() as $tax_refund) { + $tax_id = $tax_refund->getTax()->getId(); + $exact = $tax_refund->getRefundedAmount() * 100; + $cents[$tax_id] = intval(round($exact)); + $left_over[$tax_id] = $exact - $cents[$tax_id]; + } + $diff = $request->getTotalRefundedAmountInCents() - $request->getRefundedAmountInCents() - array_sum($cents); + if ($diff > 0) arsort($left_over); else asort($left_over); + foreach (array_keys($left_over) as $tax_id) { + if ($diff === 0) break; + $cents[$tax_id] += $diff <=> 0; + $diff -= $diff <=> 0; + } + return $cents; + } + } \ No newline at end of file diff --git a/tests/Unit/Entities/SummitOrderRefundRoundingTest.php b/tests/Unit/Entities/SummitOrderRefundRoundingTest.php index 4871b03ad9..4b3f744f8c 100644 --- a/tests/Unit/Entities/SummitOrderRefundRoundingTest.php +++ b/tests/Unit/Entities/SummitOrderRefundRoundingTest.php @@ -18,6 +18,8 @@ use models\summit\Summit; use models\summit\SummitAttendeeTicket; use models\summit\SummitOrder; +use models\summit\SummitRefundRequest; +use models\summit\SummitTaxRefund; use models\summit\SummitTaxType; use models\summit\SummitTicketType; use PHPUnit\Framework\Attributes\DataProvider; @@ -194,6 +196,57 @@ public function testRefundedTaxReadsTheSameEitherWayAClientAddsItUp( $this->assertSame($order->getTaxesAmountInCents(), $from_order_totals); } + public static function ordersPartlyRefundedBeforeThisChange(): array + { + return [ + // 1.9228 + 0.253 of tax per ticket: charged 3.85 + 0.51. The old + // code sent 10.12 + 2.1758 as 12.30, a cent more than its two + // taxes rounded one by one + 'two tickets, two taxes, the old refund a cent over its taxes' => [10.12, 2, [19.0, 2.5], 1, 2460], + // 9.025 of tax per ticket, sent as 9.03 by the old code: charged round(36.10) + 'four tickets, one tax, half a cent of tax per ticket' => [47.50, 4, [19.0], 1, 22610], + // 1.938 + 0.255 of tax per ticket: charged 3.88 + 0.51. The old + // code sent 10.20 + 2.193 as 12.39 + 'two tickets, two taxes, the old refund a cent short' => [10.20, 2, [19.0, 2.5], 1, 2479], + ]; + } + + #[DataProvider('ordersPartlyRefundedBeforeThisChange')] + public function testOrderPartlyRefundedBeforeThisChangeEndsOnTheCharge( + float $price, int $qty, array $rates, int $refunded_before, int $charged_cents + ): void + { + $order = self::buildOrder($price, $qty, $rates); + $this->assertSame($charged_cents, $order->getFinalAmountInCents(), 'charged amount'); + + $sent = []; + foreach ($order->getTickets()->toArray() as $i => $ticket) { + $request = $ticket->refund(null, $price, null, null, false); + if ($i < $refunded_before) self::storeTaxRefundsAsBeforeThisChange($ticket, $request); + $sent[] = $request->getTotalRefundedAmountInCents(); + } + + $this->assertSame($charged_cents, array_sum($sent), 'sent to the gateway: ' . implode(' + ', $sent)); + } + + /** + * Before this change a refund stored each tax on the refunded ticket price + * as it came out, not rounded to cents, and the gateway was sent the total + * of the request rounded once. + */ + private static function storeTaxRefundsAsBeforeThisChange( + SummitAttendeeTicket $ticket, SummitRefundRequest $request + ): void + { + $amount = new \ReflectionProperty(SummitTaxRefund::class, 'refunded_amount'); + foreach ($request->getRefundedTaxes() as $tax_refund) { + foreach ($ticket->getAppliedTaxes() as $applied_tax) { + if ($applied_tax->getTax() === $tax_refund->getTax()) + $amount->setValue($tax_refund, $applied_tax->applyTo($request->getRefundedAmount(), false)); + } + } + } + private static function cents(float $amount): int { return intval(round($amount * 100)); From 3238d691afac33fd55bc82497c21ffcf7fb3eb22 Mon Sep 17 00:00:00 2001 From: smarcet Date: Thu, 19 Nov 2026 00:29:53 -0300 Subject: [PATCH 4/5] fix(refunds): settle earlier refunds against the tax the order owes back Splitting what an earlier refund sent to the gateway among its taxes is not enough when the tickets of an order carry different taxes (a tax can be limited to some ticket types). Two 10.12 tickets, the first with 19 and 2.5 percent taxes and refunded by the old code, the second with the 19 percent tax only, sent 1230 + 1205 for a 2434 charge: the cent the old refund was over landed on a tax the second ticket does not carry. The tax a refund gives back is now also settled for the order as a whole: the tax the order owes back on everything refunded so far, each tax rounded the way the charge rounds it, less the tax the other refunds sent to the gateway. Each tax refund still follows the running total of its tax; what the earlier refunds were off is added to, or taken from, the largest. Orders refunded only by this code get the same tax refunds as before. A refund with no tax refunds on record, approved before the SummitTaxRefund table existed, is left out of the running total. Counting it made the next refund of the order give back the tax on the earlier ticket as well: two 10.00 tickets at 19 percent sent 1380 instead of 1190. --- .../SummitAttendeeTicketRefundRequest.php | 94 +++++++++---------- .../SummitOrderRefundRoundingTest.php | 50 ++++++++-- 2 files changed, 84 insertions(+), 60 deletions(-) diff --git a/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php b/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php index a3a68a8c4f..bbe04dd352 100644 --- a/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php +++ b/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php @@ -83,77 +83,71 @@ protected function calculateTaxesRefundedAmountFrom(float $amount_2_refund):Coll // running total: the tax on everything refunded so far, rounded the // same way, less the tax already given back. Refunding the whole // order then gives back the tax that was charged, to the cent. - $so_far = $this->getOrderTaxRefundsSoFar(); + list($so_far, $sent_so_far) = $this->getOrderTaxRefundsSoFar(); + $cents = []; + foreach ($this->ticket->getAppliedTaxes() as $applied_tax) { + $tax = $applied_tax->getTax(); + $so_far[$tax->getId()] ??= [$tax, 0.0, 0]; + $so_far[$tax->getId()][1] += $applied_tax->applyTo($amount_2_refund, false); + $cents[$tax->getId()] = 0; + } + $owed = 0; + foreach ($so_far as $tax_id => list($tax, $tax_so_far, $refunded_so_far)) { + $tax_owed = self::convertToCents($tax->round($tax_so_far)); + $owed += $tax_owed; + if (isset($cents[$tax_id])) $cents[$tax_id] = max(0, $tax_owed - $refunded_so_far); + } + // A refund approved before refunds followed the charge sent the gateway + // its total rounded once, which can be a cent more or less than its tax + // refunds add up to, also on a tax this ticket does not carry. This + // refund makes up for it, so that the order as a whole gives back the + // tax it was charged. + $off = max(0, $owed - $sent_so_far) - array_sum($cents); + arsort($cents); + foreach ($cents as $tax_id => $tax_cents) { + $cents[$tax_id] = max(0, $tax_cents + $off); + $off -= $cents[$tax_id] - $tax_cents; + } foreach ($this->ticket->getAppliedTaxes() as $applied_tax) { - $tax = $applied_tax->getTax(); - list($tax_so_far, $refunded_so_far) = $so_far[$tax->getId()] ?? [0.0, 0.0]; - $tax_so_far += $applied_tax->applyTo($amount_2_refund, false); - $tax_refund = new SummitTaxRefund - ( - $this, - $tax, - max(0.0, $tax->round($tax->round($tax_so_far) - $refunded_so_far)) - ); - $this->refunded_taxes->add($tax_refund); + $tax = $applied_tax->getTax(); + $this->refunded_taxes->add(new SummitTaxRefund($this, $tax, $cents[$tax->getId()] / 100)); } return $this->refunded_taxes; } /** - * What the order's other approved refunds add up to, by tax id: the tax on - * the refunded ticket price before rounding, and the tax given back. + * What the order's other approved refunds add up to. By tax id: the tax, + * the tax on the refunded ticket price before rounding, and the cents of + * it given back. And the cents of tax they sent to the payment gateway. * The tax is worked out again from the refunded ticket price because the * tax refunds stored before refunds followed the charge are not rounded. - * @return float[][] + * @return array */ private function getOrderTaxRefundsSoFar():array{ $so_far = []; + $sent_so_far = 0; foreach ($this->ticket->getOrder()->getTickets() as $ticket) { foreach ($ticket->getRefundedRequests() as $request) { // approve() marks this request as approved before its taxes are calculated if ($request === $this) continue; if ($request->getStatus() !== ISummitRefundRequestConstants::ApprovedStatus) continue; + // a refund approved before tax refunds were recorded has none: no tax to follow + if ($request->getRefundedTaxes()->isEmpty()) continue; foreach ($ticket->getAppliedTaxes() as $applied_tax) { - $tax_id = $applied_tax->getTax()->getId(); - $so_far[$tax_id] ??= [0.0, 0.0]; - $so_far[$tax_id][0] += $applied_tax->applyTo($request->getRefundedAmount(), false); + $tax = $applied_tax->getTax(); + $so_far[$tax->getId()] ??= [$tax, 0.0, 0]; + $so_far[$tax->getId()][1] += $applied_tax->applyTo($request->getRefundedAmount(), false); } - foreach (self::getTaxesSentToGatewayInCents($request) as $tax_id => $cents) { - $so_far[$tax_id] ??= [0.0, 0.0]; - $so_far[$tax_id][1] += $cents / 100; + foreach ($request->getRefundedTaxes() as $tax_refund) { + $tax = $tax_refund->getTax(); + $so_far[$tax->getId()] ??= [$tax, 0.0, 0]; + $so_far[$tax->getId()][2] += $tax_refund->getRefundedAmountInCents(); } + // the gateway is sent the total of the request rounded once + $sent_so_far += $request->getTotalRefundedAmountInCents() - $request->getRefundedAmountInCents(); } } - return $so_far; - } - - /** - * What an approved refund gave back of each tax, by tax id, in cents that - * add up to the tax it sent to the payment gateway. The gateway is sent - * the total of the request rounded once (getTotalRefundedAmountInCents), - * and the tax refunds stored before refunds followed the charge are not - * rounded: rounded one by one they can add up to a cent more or less than - * what was sent. That cent goes to the tax that was furthest from its - * rounded amount. - * @return int[] - */ - private static function getTaxesSentToGatewayInCents(SummitRefundRequest $request):array{ - $cents = []; - $left_over = []; - foreach ($request->getRefundedTaxes() as $tax_refund) { - $tax_id = $tax_refund->getTax()->getId(); - $exact = $tax_refund->getRefundedAmount() * 100; - $cents[$tax_id] = intval(round($exact)); - $left_over[$tax_id] = $exact - $cents[$tax_id]; - } - $diff = $request->getTotalRefundedAmountInCents() - $request->getRefundedAmountInCents() - array_sum($cents); - if ($diff > 0) arsort($left_over); else asort($left_over); - foreach (array_keys($left_over) as $tax_id) { - if ($diff === 0) break; - $cents[$tax_id] += $diff <=> 0; - $diff -= $diff <=> 0; - } - return $cents; + return [$so_far, $sent_so_far]; } } \ No newline at end of file diff --git a/tests/Unit/Entities/SummitOrderRefundRoundingTest.php b/tests/Unit/Entities/SummitOrderRefundRoundingTest.php index 4b3f744f8c..de629b4073 100644 --- a/tests/Unit/Entities/SummitOrderRefundRoundingTest.php +++ b/tests/Unit/Entities/SummitOrderRefundRoundingTest.php @@ -65,8 +65,11 @@ private static function withId(BaseEntity $entity): BaseEntity * @param float $price ticket price * @param int $qty tickets on the order * @param float[] $rates one tax per rate, in percent + * @param float[][] $rates_of_ticket by ticket position, the rates of the + * taxes a ticket carries when it does not carry all of them: a tax can be + * limited to some ticket types (SummitTaxType::mustApplyTo) */ - private static function buildOrder(float $price, int $qty, array $rates): SummitOrder + private static function buildOrder(float $price, int $qty, array $rates, array $rates_of_ticket = []): SummitOrder { // a ticket type asks its summit for the default badge type, and a // ticket takes its summit from the order @@ -90,7 +93,9 @@ private static function buildOrder(float $price, int $qty, array $rates): Summit for ($i = 0; $i < $qty; $i++) { $ticket = self::withId(new SummitAttendeeTicket()); $ticket->setTicketType($ticket_type); - $ticket->applyTaxes($taxes); + $ticket->applyTaxes(array_filter( + $taxes, fn(SummitTaxType $tax) => in_array($tax->getRate(), $rates_of_ticket[$i] ?? $rates) + )); $order->addTicket($ticket); } return $order; @@ -131,15 +136,18 @@ public static function fullyRefundedOrders(): array 'one ticket, two taxes, refunded in parts' => [10.20, 1, [19.0, 2.5], [4.0, 4.0, 2.2], 1240], // whole cents all the way: nothing to round 'one ticket, one tax, no fractions' => [1.00, 1, [19.0], [1.00], 119], + // 1.938 of the first tax per ticket and 0.255 of the second on the + // first ticket only: charged 3.88 + 0.26 + 'two tickets, the second without the second tax' => [10.20, 2, [19.0, 2.5], [10.20], 2454, [1 => [19.0]]], ]; } #[DataProvider('fullyRefundedOrders')] public function testFullRefundSendsBackExactlyWhatWasCharged( - float $price, int $qty, array $rates, array $parts, int $charged_cents + float $price, int $qty, array $rates, array $parts, int $charged_cents, array $rates_of_ticket = [] ): void { - $order = self::buildOrder($price, $qty, $rates); + $order = self::buildOrder($price, $qty, $rates, $rates_of_ticket); // what StripeApi::generatePayment charges $this->assertSame($charged_cents, $order->getFinalAmountInCents(), 'charged amount'); @@ -150,10 +158,10 @@ public function testFullRefundSendsBackExactlyWhatWasCharged( #[DataProvider('fullyRefundedOrders')] public function testRefundsNeverGoOverTheCharge( - float $price, int $qty, array $rates, array $parts, int $charged_cents + float $price, int $qty, array $rates, array $parts, int $charged_cents, array $rates_of_ticket = [] ): void { - $order = self::buildOrder($price, $qty, $rates); + $order = self::buildOrder($price, $qty, $rates, $rates_of_ticket); $running = 0; foreach ($order->getTickets() as $ticket) { foreach ($parts as $part) { @@ -165,10 +173,10 @@ public function testRefundsNeverGoOverTheCharge( #[DataProvider('fullyRefundedOrders')] public function testRefundedTaxReadsTheSameEitherWayAClientAddsItUp( - float $price, int $qty, array $rates, array $parts, int $charged_cents + float $price, int $qty, array $rates, array $parts, int $charged_cents, array $rates_of_ticket = [] ): void { - $order = self::buildOrder($price, $qty, $rates); + $order = self::buildOrder($price, $qty, $rates, $rates_of_ticket); self::refundEveryTicket($order, $parts); // the order's own totals, as the API serializes them (json_money) @@ -208,15 +216,20 @@ public static function ordersPartlyRefundedBeforeThisChange(): array // 1.938 + 0.255 of tax per ticket: charged 3.88 + 0.51. The old // code sent 10.20 + 2.193 as 12.39 'two tickets, two taxes, the old refund a cent short' => [10.20, 2, [19.0, 2.5], 1, 2479], + // 1.9228 of the first tax per ticket and 0.253 of the second on the + // first ticket only: charged 3.85 + 0.25. The old code sent + // 10.12 + 2.1758 as 12.30, and the ticket left to refund has no + // second tax to take that cent from + 'two tickets, the second without the second tax, the old refund a cent over its taxes' => [10.12, 2, [19.0, 2.5], 1, 2434, [1 => [19.0]]], ]; } #[DataProvider('ordersPartlyRefundedBeforeThisChange')] public function testOrderPartlyRefundedBeforeThisChangeEndsOnTheCharge( - float $price, int $qty, array $rates, int $refunded_before, int $charged_cents + float $price, int $qty, array $rates, int $refunded_before, int $charged_cents, array $rates_of_ticket = [] ): void { - $order = self::buildOrder($price, $qty, $rates); + $order = self::buildOrder($price, $qty, $rates, $rates_of_ticket); $this->assertSame($charged_cents, $order->getFinalAmountInCents(), 'charged amount'); $sent = []; @@ -247,6 +260,23 @@ private static function storeTaxRefundsAsBeforeThisChange( } } + /** + * Tax refunds are on record since the SummitTaxRefund table was added + * (migration Version20240226193210). A refund approved before has none, so + * it is not part of the running total: a later refund on its order gives + * back the tax on its own ticket price and nothing for the earlier one. + */ + public function testRefundWithoutTaxRefundsOnRecordIsLeftOutOfTheRunningTotal(): void + { + $order = self::buildOrder(10.00, 2, [19.0]); + [$first, $second] = $order->getTickets()->toArray(); + $first->refund(null, 10.00, null, null, false)->getRefundedTaxes()->clear(); + + $request = $second->refund(null, 10.00, null, null, false); + + $this->assertSame(1190, $request->getTotalRefundedAmountInCents()); + } + private static function cents(float $amount): int { return intval(round($amount * 100)); From 0cf12e7e0c4d1870253e1415e5ebd87f88c6d857 Mon Sep 17 00:00:00 2001 From: smarcet Date: Thu, 19 Nov 2026 09:53:56 -0300 Subject: [PATCH 5/5] fix(refunds): refund a ticket by its number refundTicket looked the ticket up by number when the lookup by id found nothing, but did not keep the result, so DELETE /api/v1/summits/{id}/tickets/{ticket_id}/refund answered "Ticket not found." for every ticket number. It now keeps the ticket it finds. The lookup by number takes no lock: the order is locked first and the ticket after it, the same as for a lookup by id. The endpoint is now documented as taking the ticket id or number. --- .../OAuth2SummitTicketApiController.php | 2 +- app/Services/Model/Imp/SummitOrderService.php | 3 +- tests/oauth2/OAuth2SummitTicketsApiTest.php | 37 +++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitTicketApiController.php b/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitTicketApiController.php index b77584a415..f0352bd6e1 100644 --- a/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitTicketApiController.php +++ b/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitTicketApiController.php @@ -1084,7 +1084,7 @@ protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity tags: ['Tickets'], parameters: [ new OA\Parameter(name: 'id', in: 'path', required: true, description: 'Summit ID', schema: new OA\Schema(type: 'string')), - new OA\Parameter(name: 'ticket_id', in: 'path', required: true, description: 'Ticket ID', schema: new OA\Schema(type: 'integer')), + new OA\Parameter(name: 'ticket_id', in: 'path', required: true, description: 'Ticket ID or number', schema: new OA\Schema(type: 'string')), ], requestBody: new OA\RequestBody( required: true, diff --git a/app/Services/Model/Imp/SummitOrderService.php b/app/Services/Model/Imp/SummitOrderService.php index a20cc08f7e..3320f1809c 100644 --- a/app/Services/Model/Imp/SummitOrderService.php +++ b/app/Services/Model/Imp/SummitOrderService.php @@ -2641,8 +2641,9 @@ public function refundTicket(Summit $summit, Member $currentUser, $ticket_id, fl $ticket = $this->ticket_repository->getById(intval($ticket_id)); + // by ticket number; not locked here, the order is locked before the ticket if (!$ticket instanceof SummitAttendeeTicket) - $this->ticket_repository->getByNumberExclusiveLock(strval($ticket_id)); + $ticket = $this->ticket_repository->getByNumber(strval($ticket_id)); if (!$ticket instanceof SummitAttendeeTicket) throw new EntityNotFoundException('Ticket not found.'); diff --git a/tests/oauth2/OAuth2SummitTicketsApiTest.php b/tests/oauth2/OAuth2SummitTicketsApiTest.php index 555617c4ad..4d24b2f20e 100644 --- a/tests/oauth2/OAuth2SummitTicketsApiTest.php +++ b/tests/oauth2/OAuth2SummitTicketsApiTest.php @@ -295,6 +295,43 @@ public function testRefundTicketWithNote() $this->assertTrue($refund_requests->total == 1); } + /** + * The endpoint takes the ticket id or the ticket number (TICKET_...). + */ + public function testRefundTicketByNumber() + { + $ticket = self::$summit_orders[0]->getFirstTicket(); + + $params = [ + 'id' => self::$summit->getId(), + 'ticket_id' => $ticket->getNumber(), + 'expand' => 'refund_requests' + ]; + + $headers = [ + "HTTP_Authorization" => " Bearer " . $this->access_token, + "CONTENT_TYPE" => "application/json" + ]; + + $response = $this->action( + "DELETE", + "OAuth2SummitTicketApiController@refundTicket", + $params, + [], + [], + [], + $headers, + json_encode(['amount' => 1.5]) + ); + + $content = $response->getContent(); + $this->assertResponseStatus(201); + $refunded = json_decode($content); + $this->assertSame($ticket->getNumber(), $refunded->number); + $this->assertCount(1, $refunded->refund_requests); + $this->assertEquals(1.5, $refunded->refund_requests[0]->refunded_amount); + } + public function testRejectRefund(){ $ticket = self::$summit_orders[0]->getFirstTicket(); $order = $ticket->getOrder();