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/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/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/Registration/Refunds/SummitAttendeeTicketRefundRequest.php b/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php index 5f1ef9574e..bbe04dd352 100644 --- a/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php +++ b/app/Models/Foundation/Summit/Registration/Refunds/SummitAttendeeTicketRefundRequest.php @@ -77,17 +77,77 @@ 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. + list($so_far, $sent_so_far) = $this->getOrderTaxRefundsSoFar(); + $cents = []; foreach ($this->ticket->getAppliedTaxes() as $applied_tax) { - $tax_refund = new SummitTaxRefund - ( - $this, - $applied_tax->getTax(), - $applied_tax->applyTo($amount_2_refund, false) - ); - $this->refunded_taxes->add($tax_refund); + $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(); + $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, + * 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 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 = $applied_tax->getTax(); + $so_far[$tax->getId()] ??= [$tax, 0.0, 0]; + $so_far[$tax->getId()][1] += $applied_tax->applyTo($request->getRefundedAmount(), false); + } + 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, $sent_so_far]; + } + } \ No newline at end of file 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..3320f1809c 100644 --- a/app/Services/Model/Imp/SummitOrderService.php +++ b/app/Services/Model/Imp/SummitOrderService.php @@ -2639,10 +2639,11 @@ 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)); + // 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.'); @@ -2651,6 +2652,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 +2676,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)); + } +} diff --git a/tests/Unit/Entities/SummitOrderRefundRoundingTest.php b/tests/Unit/Entities/SummitOrderRefundRoundingTest.php new file mode 100644 index 0000000000..de629b4073 --- /dev/null +++ b/tests/Unit/Entities/SummitOrderRefundRoundingTest.php @@ -0,0 +1,284 @@ +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 + * @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, 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 + $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(array_filter( + $taxes, fn(SummitTaxType $tax) => in_array($tax->getRate(), $rates_of_ticket[$i] ?? $rates) + )); + $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], + // 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, array $rates_of_ticket = [] + ): void + { + $order = self::buildOrder($price, $qty, $rates, $rates_of_ticket); + // 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, array $rates_of_ticket = [] + ): void + { + $order = self::buildOrder($price, $qty, $rates, $rates_of_ticket); + $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, array $rates_of_ticket = [] + ): void + { + $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) + $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); + } + + 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], + // 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, array $rates_of_ticket = [] + ): void + { + $order = self::buildOrder($price, $qty, $rates, $rates_of_ticket); + $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)); + } + } + } + + /** + * 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)); + } +} 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();