Reconcile up-front charges when a class switches to monthly billing
CI / Coding Standards (pull_request) Successful in 25s
CI / No Debug Code (pull_request) Successful in 3s
CI / Tests (PHP 8.1) (pull_request) Successful in 36s
CI / Tests (PHP 8.2) (pull_request) Successful in 39s
CI / Tests (PHP 8.3) (pull_request) Successful in 51s
CI / Tests (PHP 8.5) (pull_request) Successful in 59s
CI / Static Analysis (pull_request) Successful in 1m3s
CI / Build Plugin Zip (pull_request) Skipped

A student who enrols while a group class is pay-now is charged once at
enrolment, and that charge carries no period_key. When the class is
later switched to monthly, the daily scan — which dedups scheduled
charges by period_key — does not see the up-front charge and bills the
enrolment again for the current month, double-charging students who
had already paid. The differing payer between the two rows (student vs
guardian) was a side effect of guardian links created between the two
charge dates, not the cause.

Switching a group class into monthly now adopts each active enrolment's
up-front charge into the current month (stamping period_key and
due_date) so the scan treats that month as billed and charges from the
next month on. Enrolments with no up-front charge, or already billed
for the month, are left alone; weekly and non-group offerings are not
touched. Wired into both offering-update paths (admin form and REST).

Co-authored-by: anthropic/claude-opus-4-8
This commit is contained in:
2026-09-17 15:07:22 -03:00
co-authored by anthropic/claude-opus-4-8
parent e389e40843
commit acda3cda0f
14 changed files with 406 additions and 8 deletions
+3 -2
View File
@@ -25,6 +25,7 @@ use Unsupervised\Schedular\GroupClass\EnrollmentRepository;
use Unsupervised\Schedular\GroupClass\GroupAccessRepository;
use Unsupervised\Schedular\GroupClass\GroupClassController;
use Unsupervised\Schedular\GroupClass\SessionSchedule;
use Unsupervised\Schedular\Offering\BillingModeReconciler;
use Unsupervised\Schedular\Offering\ClassSlotReconciler;
use Unsupervised\Schedular\Offering\OfferingController;
use Unsupervised\Schedular\Offering\OfferingRepository;
@@ -70,7 +71,7 @@ class AdminMenu {
private PaymentController $paymentController;
private PaymentReportController $paymentReportController;
public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings, QuestionRepository $questions, AnswerRepository $answers, PolicyRepository $policies, PolicyVersionRepository $policyVersions, PolicyService $policyService, AcceptanceRepository $acceptances, InviteRepository $invites, EnrollmentRepository $enrollments, GroupAccessRepository $groupAccess, StudioSettings $settings, PaymentRepository $payments, PaymentService $paymentService, BillingMethodResolver $resolver, RegistrationMailer $registrationMailer, CreditRepository $credits, GuardianService $guardians, LessonBooker $booker, RegistrationGate $gate ) {
public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings, QuestionRepository $questions, AnswerRepository $answers, PolicyRepository $policies, PolicyVersionRepository $policyVersions, PolicyService $policyService, AcceptanceRepository $acceptances, InviteRepository $invites, EnrollmentRepository $enrollments, GroupAccessRepository $groupAccess, StudioSettings $settings, PaymentRepository $payments, PaymentService $paymentService, BillingMethodResolver $resolver, RegistrationMailer $registrationMailer, CreditRepository $credits, GuardianService $guardians, LessonBooker $booker, RegistrationGate $gate, BillingModeReconciler $billingModeReconciler ) {
// One audit presenter and one recorder, shared by the lesson and enrolment
// detail views: intake is the same thing whichever registration it hangs off.
$intakeAudit = new IntakeAudit( $answers, $questions, $acceptances, $policies, $policyVersions );
@@ -78,7 +79,7 @@ class AdminMenu {
$this->availabilityController = new AvailabilityController( $availability, $offerings, new WindowValidator( $offerings ) );
$this->lessonController = new LessonController( $bookings, $payments, $availability, $offerings, $intakeAudit, new AdminBooking( $availability, $offerings, $booker ), $intakeRecording );
$this->offeringController = new OfferingController( $offerings, new ClassSlotReconciler( $availability ) );
$this->offeringController = new OfferingController( $offerings, new ClassSlotReconciler( $availability ), $billingModeReconciler );
$this->questionController = new QuestionController( $questions, $offerings );
$this->policyController = new PolicyController( $policies, $policyVersions, $policyService );
$this->registrationController = new RegistrationController( $invites );
+18
View File
@@ -82,6 +82,24 @@ class EnrollmentRepository {
return $count > 0;
}
/**
* Active enrolments in one offering, oldest first.
*
* @return list<Enrollment>
*/
public function findActiveByOffering( int $offeringId ): array {
$rows = $this->db->get_results(
$this->db->prepare(
'SELECT * FROM %i WHERE offering_id = %d AND status = %s ORDER BY id ASC',
$this->table,
$offeringId,
Enrollment::STATUS_ACTIVE
)
);
return array_map( Enrollment::fromRow( ... ), $rows ?? [] );
}
/**
* A student's enrolments, newest first.
*
+85
View File
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Offering;
use Unsupervised\Schedular\GroupClass\EnrollmentRepository;
use Unsupervised\Schedular\Payment\Payment;
use Unsupervised\Schedular\Payment\PaymentRepository;
use Unsupervised\Schedular\Val;
/**
* Keeps existing enrolments from being billed twice when a group class is
* switched from a pay-now billing mode (one-time / full-term) to a scheduled one
* (weekly / monthly).
*
* A student who enrols while a class is pay-now is charged once at enrolment, and
* that charge carries no `period_key`. The daily scan dedups scheduled charges by
* `period_key`, so once the class becomes scheduled the scan does not see the
* up-front charge and bills the enrolment again for the same period. This adopts
* each such up-front charge into the current billing period so the scan treats it
* as already billed; later periods bill normally.
*
* Only the transition *into* scheduled billing is handled — going the other way,
* or editing an already-scheduled class, needs no reconciliation. Weekly is left
* alone: a weekly class is billed per session as sessions come due, so there is
* no single up-front period a prior charge maps onto.
*/
class BillingModeReconciler {
public function __construct(
private EnrollmentRepository $enrollments,
private PaymentRepository $payments,
) {}
/**
* Reconcile an offering edit. Given the offering as it was and as it now is,
* adopt up-front enrolment charges into the current month when the class has
* just become monthly. Returns the number of charges adopted (0 when the edit
* is not a pay-now -> monthly transition, or nothing needed adopting).
*/
public function reconcile( Offering $before, Offering $after ): int {
if ( null === $after->id || Offering::KIND_GROUP_CLASS !== $after->kind ) {
return 0;
}
// Only a fresh switch into monthly scheduling can strand an up-front charge.
$becameMonthly = Offering::BILLING_MONTHLY === $after->billingMode
&& Offering::BILLING_MONTHLY !== $before->billingMode;
if ( ! $becameMonthly ) {
return 0;
}
$period = $this->currentMonth();
$dueDate = $period . '-01';
$adopted = 0;
foreach ( $this->enrollments->findActiveByOffering( $after->id ) as $enrollment ) {
$enrollmentId = (int) $enrollment->id;
// Nothing to adopt unless the enrolment holds an up-front (unscheduled)
// charge, and never when the scan has already billed this month for it —
// adopting then would leave two charges for the month, the opposite of
// the fix.
if ( ! $this->payments->hasUnscheduledCharge( Payment::REG_ENROLLMENT, $enrollmentId )
|| $this->payments->existsForPeriod( Payment::REG_ENROLLMENT, $enrollmentId, $period )
) {
continue;
}
$adopted += $this->payments->claimPeriodForUnscheduled( Payment::REG_ENROLLMENT, $enrollmentId, $period, $dueDate );
}
return $adopted;
}
/**
* The current calendar month as a `Y-m` period key, from WordPress site time
* so it matches how the billing scan derives its periods.
*/
private function currentMonth(): string {
$mysql = Val::string( current_time( 'mysql' ) );
return ( false !== strtotime( $mysql ) ? new \DateTimeImmutable( $mysql ) : new \DateTimeImmutable() )->format( 'Y-m' );
}
}
+6
View File
@@ -12,6 +12,7 @@ class OfferingController {
public function __construct(
private OfferingRepository $repository,
private ClassSlotReconciler $reconciler,
private BillingModeReconciler $billingModeReconciler,
private AccessSettings $access = new AccessSettings(),
) {}
@@ -81,6 +82,11 @@ class OfferingController {
if ( null !== $offering ) {
$this->repository->update( $offeringId, $offering );
// Adopt any up-front enrolment charge into the current period when
// this edit switched the class to monthly, so the daily scan does
// not bill those enrolments a second time for the month.
$this->billingModeReconciler->reconcile( $existing, $offering );
return $this->reconcileNotice( $offering );
}
}
+6
View File
@@ -13,6 +13,7 @@ class OfferingEndpoint {
public function __construct(
private OfferingRepository $repository,
private GroupAccessRepository $access,
private BillingModeReconciler $billingModeReconciler,
) {}
/**
@@ -237,6 +238,11 @@ class OfferingEndpoint {
$this->repository->update( $id, $offering );
// Adopt any up-front enrolment charge into the current period when this edit
// switched the class to monthly, so the daily scan does not bill those
// enrolments a second time for the month.
$this->billingModeReconciler->reconcile( $existing, $offering );
return new \WP_REST_Response( $offering->toArray(), 200 );
}
+55
View File
@@ -272,6 +272,61 @@ class PaymentRepository {
);
}
/**
* Whether a registration has an unscheduled, un-voided charge — one taken at
* registration (`period_key IS NULL`, `status != failed`). The billing-mode
* reconciler uses this to spot an up-front charge that a newly-scheduled
* offering would otherwise cause the scan to bill a second time.
*/
public function hasUnscheduledCharge( string $registrationType, int $registrationId ): bool {
$found = $this->db->get_var(
$this->db->prepare(
'SELECT id FROM %i WHERE registration_type = %s AND registration_id = %d AND period_key IS NULL AND status != %s LIMIT 1',
$this->table,
$registrationType,
$registrationId,
Payment::STATUS_FAILED
)
);
return null !== $found;
}
/**
* Stamp a registration's existing unscheduled charge with a billing period and
* due date so the daily scan treats that period as already billed. Used when
* an offering is switched to scheduled billing: the charge taken at enrolment
* (which carries no `period_key`) would otherwise never match the scan's
* per-period dedup, and the enrolment would be billed a second time for the
* period the up-front charge already covers.
*
* Only ever adopts a charge that is genuinely unscheduled (`period_key IS
* NULL`) and not voided (`status != failed`) — so it cannot overwrite a real
* scheduled charge or revive a cancelled one. The caller guards against a
* period that already has a scheduled charge (see {@see existsForPeriod}).
* Returns the number of rows adopted (0 or 1).
*/
public function claimPeriodForUnscheduled( string $registrationType, int $registrationId, string $periodKey, string $dueDate ): int {
$sql = $this->db->prepare(
'UPDATE %i SET period_key = %s, due_date = %s
WHERE registration_type = %s AND registration_id = %d
AND period_key IS NULL AND status != %s
ORDER BY id ASC LIMIT 1',
$this->table,
$periodKey,
$dueDate,
$registrationType,
$registrationId,
Payment::STATUS_FAILED
);
if ( null === $sql ) {
return 0;
}
return (int) $this->db->query( $sql );
}
/**
* Atomically claim a payment for its one due-payment notice. Stamps
* `notice_sent_at` only if it is still null, and returns whether *this* call
+8 -2
View File
@@ -24,6 +24,7 @@ use Unsupervised\Schedular\Guardian\ChildLoginGate;
use Unsupervised\Schedular\Guardian\FamilyPage;
use Unsupervised\Schedular\Guardian\GuardianRepository;
use Unsupervised\Schedular\Guardian\GuardianService;
use Unsupervised\Schedular\Offering\BillingModeReconciler;
use Unsupervised\Schedular\Offering\OfferingRepository;
use Unsupervised\Schedular\Payment\BillingMethodResolver;
use Unsupervised\Schedular\Payment\CreditRepository;
@@ -129,6 +130,11 @@ class Plugin {
$familyPage = new FamilyPage( $guardians, $questions, $answers );
$accountPage = new AccountPage();
// Adopts an up-front enrolment charge into the current billing period when a
// group class is switched to monthly, so the daily scan does not bill it a
// second time for a month the up-front charge already covers.
$billingModeReconciler = new BillingModeReconciler( $enrollments, $paymentRepo );
( new ScheduledBillingRunner( $paymentService, $bookings, $enrollments, $offerings, new PaymentDueMailer(), $guardians ) )->register();
( new UpdateChecker() )->register();
@@ -138,8 +144,8 @@ class Plugin {
( new StudentAdminGuard() )->register();
( new DeletedUserCleanup( $bookings, $availability, $enrollments, $paymentService, $guardianRepo, $guardians ) )->register();
( new EmailConfirmationHandler( $settings, $registrationMailer ) )->register();
( new AdminMenu( $availability, $bookings, $offerings, $questions, $answers, $policies, $policyVersions, $policyService, $acceptances, $invites, $enrollments, $groupAccess, $settings, $paymentRepo, $paymentService, $resolver, $registrationMailer, $creditRepo, $guardians, $lessonBooker, $registrationGate ) )->register();
( new RestRegistrar( $availability, $bookings, $offerings, $questions, $policies, $policyVersions, $policyService, $registrationGate, $enrollments, $groupAccess, $paymentService, $guardians, $lessonBooker ) )->register();
( new AdminMenu( $availability, $bookings, $offerings, $questions, $answers, $policies, $policyVersions, $policyService, $acceptances, $invites, $enrollments, $groupAccess, $settings, $paymentRepo, $paymentService, $resolver, $registrationMailer, $creditRepo, $guardians, $lessonBooker, $registrationGate, $billingModeReconciler ) )->register();
( new RestRegistrar( $availability, $bookings, $offerings, $questions, $policies, $policyVersions, $policyService, $registrationGate, $enrollments, $groupAccess, $paymentService, $guardians, $lessonBooker, $billingModeReconciler ) )->register();
( new ShortcodeRegistrar( $bookingPage, $loginPage, $registrationPage, $groupClassPage, $familyPage, $accountPage ) )->register();
( new BlockRegistrar( $bookingPage, $loginPage, $registrationPage, $groupClassPage, $familyPage, $accountPage ) )->register();
}
+3 -2
View File
@@ -15,6 +15,7 @@ use Unsupervised\Schedular\GroupClass\GroupAccessRepository;
use Unsupervised\Schedular\GroupClass\EnrollmentRepository;
use Unsupervised\Schedular\GroupClass\SessionSchedule;
use Unsupervised\Schedular\Guardian\GuardianService;
use Unsupervised\Schedular\Offering\BillingModeReconciler;
use Unsupervised\Schedular\Offering\OfferingEndpoint;
use Unsupervised\Schedular\Offering\OfferingRepository;
use Unsupervised\Schedular\Payment\PaymentEndpoint;
@@ -40,10 +41,10 @@ class RestRegistrar {
private EnrollmentEndpoint $enrollmentEndpoint;
private PaymentEndpoint $paymentEndpoint;
public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings, QuestionRepository $questions, PolicyRepository $policies, PolicyVersionRepository $policyVersions, PolicyService $policyService, RegistrationGate $gate, EnrollmentRepository $enrollments, GroupAccessRepository $groupAccess, PaymentService $paymentService, GuardianService $guardians, LessonBooker $booker ) {
public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings, QuestionRepository $questions, PolicyRepository $policies, PolicyVersionRepository $policyVersions, PolicyService $policyService, RegistrationGate $gate, EnrollmentRepository $enrollments, GroupAccessRepository $groupAccess, PaymentService $paymentService, GuardianService $guardians, LessonBooker $booker, BillingModeReconciler $billingModeReconciler ) {
$this->availabilityEndpoint = new AvailabilityEndpoint( $availability, new WindowValidator( $offerings ) );
$this->bookingEndpoint = new BookingEndpoint( $availability, $bookings, $offerings, $gate, $paymentService, $booker, new CancellationPolicy( new StudioSettings() ), $guardians, new SessionSchedule( $enrollments, $offerings ) );
$this->offeringEndpoint = new OfferingEndpoint( $offerings, $groupAccess );
$this->offeringEndpoint = new OfferingEndpoint( $offerings, $groupAccess, $billingModeReconciler );
$this->questionEndpoint = new QuestionEndpoint( $questions, $offerings );
$this->policyEndpoint = new PolicyEndpoint( $policies, $policyVersions, $policyService );
$this->enrollmentEndpoint = new EnrollmentEndpoint( $enrollments, $offerings, $gate, $paymentService, $groupAccess, $guardians );