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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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/" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
21 changes: 18 additions & 3 deletions app/Jobs/ProcessTicketRefundRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -24,6 +25,7 @@
use models\summit\IPaymentConstants;
use models\summit\ISummitAttendeeTicketRepository;
use models\summit\SummitAttendeeTicket;
use models\summit\SummitOrder;

/**
* Class ProcessTicketRefundRequest
Expand Down Expand Up @@ -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()));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
return [$so_far, $sent_so_far];
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions app/Repositories/Summit/DoctrineSummitOrderRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment on lines +106 to +111

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, this is a real gap.

getOrderTaxRefundsSoFar() builds the running total from $this->ticket->getOrder()->getTickets(). The refresh query is rooted at SummitAttendeeTicket, so HINT_REFRESH only refreshes each ticket and the collections fetch-joined from it (refund_requests, refunded_taxes). It does not touch the order's tickets collection once it is initialized. A ticket added after that gets hydrated with its order set, but it never shows up in $order->tickets.

How it happens:

  1. A queue worker processes a ProcessTicketRefundRequest for order O. Iterating getTickets() initializes O->tickets in that worker's entity manager, and nothing clears it between jobs.
  2. An admin adds a taxed ticket to O through POST .../orders/{order_id}/tickets (addTickets) and refunds it through refundTicket. That refund is correct because the HTTP request uses a fresh entity manager.
  3. The same worker processes another refund of O. The new ticket's approved refund is missing from the running total, so the tax drifts by a cent again.

The order lock doesn't prevent this. It serializes the transactions but does not refresh the collection the worker already holds.

Rooting the query at the order and fetch-joining its tickets fixes it (select o, t, r, tr from SummitOrder o left join o.tickets t left join t.refund_requests r left join r.refunded_taxes tr where o.id = :id, with HINT_REFRESH). I would keep the lock in the separate getByIdExclusiveLock query, so FOR UPDATE does not spread to the joined rows. A regression test can follow the second-entity-manager pattern already in SummitOrderRefundSerializationTest: initialize O->tickets, add and refund a taxed ticket from the other entity manager, then refund another ticket and check that the new refund is counted.

->getQuery()
->setHint(\Doctrine\ORM\Query::HINT_REFRESH, true)
->getResult();

return $order;
}

/**
* @param string $email
* @return mixed
Expand Down
23 changes: 16 additions & 7 deletions app/Services/Model/Imp/SummitOrderService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.');
Expand All @@ -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
(
Expand All @@ -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];
Expand Down
Loading
Loading