Files
unsupervised-scheduler/tests/Unit/Payment/ScheduledBillingRunnerTest.php
T
thatguygriffandClaude Opus 5 4a41ba96fb
CI / Tests (PHP 8.2) (pull_request) Successful in 42s
CI / Tests (PHP 8.3) (pull_request) Successful in 2m45s
CI / Build Plugin Zip (pull_request) Skipped
CI / Tests (PHP 8.1) (pull_request) Failing after 52s
CI / No Debug Code (pull_request) Successful in 2s
CI / PHPStan (pull_request) Successful in 2m52s
CI / Coding Standards (pull_request) Successful in 2m57s
Let parents register once and book for their children
A parent registers once and manages lessons for one or more children, who
need no login of their own. A child is a real wp_users row with the student
role but no usable login — so student_id keeps meaning "a WordPress user"
on every table, and booking, credits, policies and enrolments work unchanged.
A us_guardians link table maps guardian to child.

The signup form gains a parent/guardian tick that reveals a block per child,
with the account-signup questions asked per child rather than per guardian
— they describe the student, not the account holder. Signup policies are
recorded once per child with the guardian as the acceptor, which is the
record that actually means something. A family that half-creates is rolled
back entirely rather than leaving a guardian who cannot re-register.

The booking and enrolment forms gain a "Who is this for?" picker listing
children first, so the default selection is never the parent — booking for
the wrong child is correctable, quietly billing a parent for their kid's
lesson is not. POST /bookings and POST /enrollments take an optional
student_id honoured only for that child's guardian; anything else is a 403.
That check is the authorisation boundary of the feature.

Payments and credits gain a payer: the charge names the child it was for and
the guardian who owes it, so per-child reporting is unchanged while notices,
receipts and the payment step reach the parent. Credit is held by the payer,
so one child's cancellation can settle a sibling's charge, and the daily
billing scan sends a guardian one notice covering every child.

Closes #132

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-07-29 16:00:34 -03:00

432 lines
19 KiB
PHP

<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Tests\Unit\Payment;
use Brain\Monkey\Functions;
use Mockery;
use Unsupervised\Schedular\Booking\BookingRepository;
use Unsupervised\Schedular\GroupClass\Enrollment;
use Unsupervised\Schedular\GroupClass\EnrollmentRepository;
use Unsupervised\Schedular\Guardian\GuardianService;
use Unsupervised\Schedular\Offering\Offering;
use Unsupervised\Schedular\Offering\OfferingRepository;
use Unsupervised\Schedular\Payment\Payment;
use Unsupervised\Schedular\Payment\PaymentDueMailer;
use Unsupervised\Schedular\Payment\PaymentService;
use Unsupervised\Schedular\Payment\ScheduledBillingRunner;
use Unsupervised\Schedular\Tests\Unit\TestCase;
class ScheduledBillingRunnerTest extends TestCase
{
private GuardianService&Mockery\MockInterface $guardians;
private PaymentService $payments;
private BookingRepository $bookings;
private EnrollmentRepository $enrollments;
private OfferingRepository $offerings;
private PaymentDueMailer $mailer;
private ScheduledBillingRunner $runner;
protected function setUp(): void
{
parent::setUp();
$this->payments = Mockery::mock(PaymentService::class);
$this->bookings = Mockery::mock(BookingRepository::class);
$this->enrollments = Mockery::mock(EnrollmentRepository::class);
$this->offerings = Mockery::mock(OfferingRepository::class);
$this->mailer = Mockery::mock(PaymentDueMailer::class);
// Defaults: nothing to bill unless a test says otherwise.
$this->bookings->shouldReceive('findUnbilledScheduledLessons')->andReturn([])->byDefault();
$this->enrollments->shouldReceive('findActiveByBillingModes')->andReturn([])->byDefault();
$this->mailer->shouldReceive('send')->andReturn(true)->byDefault();
$this->payments->shouldReceive('assignNoticeBatch')->byDefault();
// No account credit unless a test says otherwise.
$this->payments->shouldReceive('applyCredits')->andReturn([])->byDefault();
Functions\when('wp_generate_uuid4')->justReturn('abcdef12-3456-7890-abcd-ef1234567890');
$student = Mockery::mock(\WP_User::class);
$student->user_email = '[email protected]';
Functions\when('get_userdata')->justReturn($student);
$this->guardians = Mockery::mock(GuardianService::class);
$this->guardians->shouldReceive('payerFor')->andReturnUsing(static fn (int $id): int => $id)->byDefault();
$this->guardians->shouldReceive('studentName')->andReturn('Ada')->byDefault();
$this->runner = new ScheduledBillingRunner(
$this->payments,
$this->bookings,
$this->enrollments,
$this->offerings,
$this->mailer,
$this->guardians
);
}
private function now(string $mysql): void
{
Functions\when('current_time')->justReturn($mysql);
}
private function pending(int $id, string $due): Payment
{
return new Payment(5, 3, Payment::REG_LESSON, 12, 35.00, currency: 'CAD', method: Payment::METHOD_ETRANSFER, status: Payment::STATUS_PENDING, dueDate: $due, id: $id);
}
private function lessonRow(int $id, string $mode, string $start, float $price, int $offeringId = 9): object
{
return (object) [
'id' => (string) $id,
'student_id' => '5',
'instructor_id' => '3',
'offering_id' => (string) $offeringId,
'start_dt' => $start,
'billing_mode' => $mode,
'title' => 'Piano',
'price' => (string) $price,
'currency' => 'CAD',
'etransfer_email' => '[email protected]',
];
}
public function testPrivateWeeklyBillsLessonWithin24h(): void
{
$this->now('2026-07-15 09:00:00');
$this->bookings->shouldReceive('findUnbilledScheduledLessons')
->andReturn([ $this->lessonRow(101, Offering::BILLING_WEEKLY, '2026-07-15 18:00:00', 35.0) ]);
$this->payments->shouldReceive('createForRegistration')
->once()
->with(Payment::REG_LESSON, 101, 5, 3, 35.0, 'CAD', '[email protected]', '2026-07-14', '2026-07-15', 5)
->andReturn($this->pending(500, '2026-07-14'));
$this->mailer->shouldReceive('send')->once();
$this->runner->run();
}
public function testPrivateWeeklySkipsLessonBeyond24h(): void
{
$this->now('2026-07-15 09:00:00');
$this->bookings->shouldReceive('findUnbilledScheduledLessons')
->andReturn([ $this->lessonRow(101, Offering::BILLING_WEEKLY, '2026-07-18 18:00:00', 35.0) ]);
$this->payments->shouldNotReceive('createForRegistration');
$this->mailer->shouldNotReceive('send');
$this->runner->run();
}
public function testPrivateMonthlyGroupsLessonsIntoOnePayment(): void
{
$this->now('2026-07-15 09:00:00');
$this->bookings->shouldReceive('findUnbilledScheduledLessons')->andReturn([
$this->lessonRow(201, Offering::BILLING_MONTHLY, '2026-07-07 18:00:00', 30.0),
$this->lessonRow(202, Offering::BILLING_MONTHLY, '2026-07-14 18:00:00', 30.0),
$this->lessonRow(203, Offering::BILLING_MONTHLY, '2026-07-21 18:00:00', 30.0),
]);
// One payment for the month: 3 x 30, due on the 1st, linked to the earliest.
$this->payments->shouldReceive('createForRegistration')
->once()
->with(Payment::REG_LESSON, 201, 5, 3, 90.0, 'CAD', '[email protected]', '2026-07-01', '2026-07', 5)
->andReturn($this->pending(600, '2026-07-01'));
// The other two lessons are pointed at the same payment so they are not re-billed.
$this->bookings->shouldReceive('setPaymentId')->once()->with(202, 600);
$this->bookings->shouldReceive('setPaymentId')->once()->with(203, 600);
$this->runner->run();
}
public function testPrivateMonthlySkipsFutureMonth(): void
{
$this->now('2026-07-15 09:00:00');
$this->bookings->shouldReceive('findUnbilledScheduledLessons')
->andReturn([ $this->lessonRow(301, Offering::BILLING_MONTHLY, '2026-08-04 18:00:00', 30.0) ]);
$this->payments->shouldNotReceive('createForRegistration');
$this->runner->run();
}
public function testGroupWeeklyBillsDueSessionsOnly(): void
{
$this->now('2026-07-15 09:00:00');
$enrollment = new Enrollment(offeringId: 9, studentId: 5, instructorId: 3, id: 44);
$this->enrollments->shouldReceive('findActiveByBillingModes')->andReturn([ $enrollment ]);
$this->offerings->shouldReceive('findById')->with(9)->andReturn($this->groupOffering(Offering::BILLING_WEEKLY, '2026-07-07', '2026-07-21'));
// Sessions Jul 7 (due Jul 6) and Jul 14 (due Jul 13) are due by Jul 15; Jul 21 is not.
$this->payments->shouldReceive('scheduledPaymentExists')->with(Payment::REG_ENROLLMENT, 44, '2026-07-07')->andReturn(false);
$this->payments->shouldReceive('scheduledPaymentExists')->with(Payment::REG_ENROLLMENT, 44, '2026-07-14')->andReturn(false);
$this->payments->shouldReceive('createForRegistration')
->once()
->with(Payment::REG_ENROLLMENT, 44, 5, 3, 20.0, 'CAD', null, '2026-07-06', '2026-07-07', 5)
->andReturn($this->pending(700, '2026-07-06'));
$this->payments->shouldReceive('createForRegistration')
->once()
->with(Payment::REG_ENROLLMENT, 44, 5, 3, 20.0, 'CAD', null, '2026-07-13', '2026-07-14', 5)
->andReturn($this->pending(701, '2026-07-13'));
$this->runner->run();
}
public function testGroupWeeklyDedupSkipsExistingPeriod(): void
{
$this->now('2026-07-15 09:00:00');
$enrollment = new Enrollment(offeringId: 9, studentId: 5, instructorId: 3, id: 44);
$this->enrollments->shouldReceive('findActiveByBillingModes')->andReturn([ $enrollment ]);
$this->offerings->shouldReceive('findById')->with(9)->andReturn($this->groupOffering(Offering::BILLING_WEEKLY, '2026-07-07', '2026-07-21'));
// First session already billed; only the second generates a payment.
$this->payments->shouldReceive('scheduledPaymentExists')->with(Payment::REG_ENROLLMENT, 44, '2026-07-07')->andReturn(true);
$this->payments->shouldReceive('scheduledPaymentExists')->with(Payment::REG_ENROLLMENT, 44, '2026-07-14')->andReturn(false);
$this->payments->shouldReceive('createForRegistration')
->once()
->with(Payment::REG_ENROLLMENT, 44, 5, 3, 20.0, 'CAD', null, '2026-07-13', '2026-07-14', 5)
->andReturn($this->pending(701, '2026-07-13'));
$this->runner->run();
}
/**
* A monthly group class is priced per month, not per session: the same fee
* is charged whether the class meets four times in the month or once. This
* is what the class card quotes and what the student agrees to pay.
*/
public function testGroupMonthlyBillsTheMonthlyFeeOnceHoweverManySessions(): void
{
$this->now('2026-07-15 09:00:00');
$enrollment = new Enrollment(offeringId: 9, studentId: 5, instructorId: 3, id: 44);
$this->enrollments->shouldReceive('findActiveByBillingModes')->andReturn([ $enrollment ]);
// 4 Tuesday sessions in July.
$this->offerings->shouldReceive('findById')->with(9)->andReturn($this->groupOffering(Offering::BILLING_MONTHLY, '2026-07-07', '2026-07-28'));
$this->payments->shouldReceive('scheduledPaymentExists')->with(Payment::REG_ENROLLMENT, 44, '2026-07')->andReturn(false);
// One payment of the monthly fee — not 4 x 20 — due on the 1st.
$this->payments->shouldReceive('createForRegistration')
->once()
->with(Payment::REG_ENROLLMENT, 44, 5, 3, 20.0, 'CAD', null, '2026-07-01', '2026-07', 5)
->andReturn($this->pending(800, '2026-07-01'));
$this->runner->run();
}
/**
* The per-month fee does not shrink for a short month either — a month with
* a single session is billed the same as a month with four.
*/
public function testGroupMonthlyBillsTheSameFeeForAMonthWithOneSession(): void
{
$this->now('2026-07-15 09:00:00');
$enrollment = new Enrollment(offeringId: 9, studentId: 5, instructorId: 3, id: 44);
$this->enrollments->shouldReceive('findActiveByBillingModes')->andReturn([ $enrollment ]);
// A single July session.
$this->offerings->shouldReceive('findById')->with(9)->andReturn($this->groupOffering(Offering::BILLING_MONTHLY, '2026-07-07', '2026-07-07'));
$this->payments->shouldReceive('scheduledPaymentExists')->with(Payment::REG_ENROLLMENT, 44, '2026-07')->andReturn(false);
$this->payments->shouldReceive('createForRegistration')
->once()
->with(Payment::REG_ENROLLMENT, 44, 5, 3, 20.0, 'CAD', null, '2026-07-01', '2026-07', 5)
->andReturn($this->pending(800, '2026-07-01'));
$this->runner->run();
}
public function testCompPaymentIsNotBucketed(): void
{
$this->now('2026-07-15 09:00:00');
$this->bookings->shouldReceive('findUnbilledScheduledLessons')
->andReturn([ $this->lessonRow(101, Offering::BILLING_WEEKLY, '2026-07-15 18:00:00', 35.0) ]);
// A comp student's payment comes back paid — no due notice should be sent.
$comp = new Payment(5, 3, Payment::REG_LESSON, 12, 35.00, currency: 'CAD', method: Payment::METHOD_COMP, status: Payment::STATUS_PAID, dueDate: '2026-07-14', id: 900);
$this->payments->shouldReceive('createForRegistration')->once()->andReturn($comp);
$this->mailer->shouldNotReceive('send');
$this->runner->run();
}
public function testConsolidatesAllItemsIntoOneEmailPerStudent(): void
{
$this->now('2026-07-15 09:00:00');
$this->bookings->shouldReceive('findUnbilledScheduledLessons')
->andReturn([ $this->lessonRow(101, Offering::BILLING_WEEKLY, '2026-07-15 18:00:00', 35.0) ]);
$enrollment = new Enrollment(offeringId: 9, studentId: 5, instructorId: 3, id: 44);
$this->enrollments->shouldReceive('findActiveByBillingModes')->andReturn([ $enrollment ]);
$this->offerings->shouldReceive('findById')->with(9)->andReturn($this->groupOffering(Offering::BILLING_WEEKLY, '2026-07-14', '2026-07-14'));
$this->payments->shouldReceive('scheduledPaymentExists')->andReturn(false);
$this->payments->shouldReceive('createForRegistration')->andReturn($this->pending(500, '2026-07-14'), $this->pending(501, '2026-07-13'));
// Same student billed twice in one run -> exactly one email with both items,
// and both payments tagged with one shared notice-batch reference.
$this->payments->shouldReceive('assignNoticeBatch')
->once()
->with(Mockery::on(static fn (array $ids): bool => count($ids) === 2), Mockery::type('string'));
$this->mailer->shouldReceive('send')
->once()
->with(Mockery::type(\WP_User::class), Mockery::on(static fn (array $items): bool => count($items) === 2), Mockery::type('string'), 0.0);
$this->runner->run();
}
public function testAppliesAccountCreditToTheRun(): void
{
$this->now('2026-07-15 09:00:00');
$this->bookings->shouldReceive('findUnbilledScheduledLessons')
->andReturn([ $this->lessonRow(101, Offering::BILLING_WEEKLY, '2026-07-15 18:00:00', 35.0) ]);
$payment = $this->pending(500, '2026-07-14');
$this->payments->shouldReceive('createForRegistration')->once()->andReturn($payment);
// Student holds $20 credit, applied to the one $35 charge — still $15 owing,
// so the payment stays in the notice batch and the notice quotes the credit.
$this->payments->shouldReceive('applyCredits')
->once()
->with(5, Mockery::on(static fn (array $p): bool => count($p) === 1))
->andReturn([500 => 20.0]);
$this->payments->shouldReceive('assignNoticeBatch')
->once()
->with([500], Mockery::type('string'));
$this->mailer->shouldReceive('send')
->once()
->with(Mockery::type(\WP_User::class), Mockery::type('array'), Mockery::type('string'), 20.0);
$this->runner->run();
}
public function testCreditFullyCoveringAChargeLeavesItOutOfTheBatch(): void
{
$this->now('2026-07-15 09:00:00');
$this->bookings->shouldReceive('findUnbilledScheduledLessons')
->andReturn([ $this->lessonRow(101, Offering::BILLING_WEEKLY, '2026-07-15 18:00:00', 35.0) ]);
$payment = $this->pending(500, '2026-07-14');
$this->payments->shouldReceive('createForRegistration')->once()->andReturn($payment);
// Credit covers the whole $35 charge: nothing owing, so no reconciliation
// batch and no reference on the (zero-balance) notice.
$this->payments->shouldReceive('applyCredits')->once()->andReturn([500 => 35.0]);
$this->payments->shouldReceive('assignNoticeBatch')->once()->with([], '');
$this->mailer->shouldReceive('send')
->once()
->with(Mockery::type(\WP_User::class), Mockery::type('array'), '', 35.0);
$this->runner->run();
}
private function groupOffering(string $mode, string $termStart, string $termEnd): Offering
{
return new Offering(
instructorId: 3,
kind: Offering::KIND_GROUP_CLASS,
title: 'Ensemble',
price: 20.0,
currency: 'CAD',
billingMode: $mode,
durationMinutes: 60,
termStart: $termStart,
termEnd: $termEnd,
classTime: '16:00:00',
id: 9,
);
}
/**
* Two children billed on the same day belong to one payer, so the guardian
* gets a single notice covering both — not one email per child — and each
* line names whose lesson it is.
*/
public function testAGuardiansChildrenShareOneNoticeWithNamedLines(): void
{
$this->now('2026-07-15 09:00:00');
$adas = $this->lessonRow(101, Offering::BILLING_WEEKLY, '2026-07-15 18:00:00', 35.0);
$alans = $this->lessonRow(102, Offering::BILLING_WEEKLY, '2026-07-15 19:00:00', 35.0);
$adas->student_id = '42';
$alans->student_id = '43';
$this->bookings->shouldReceive('findUnbilledScheduledLessons')->andReturn([$adas, $alans]);
$this->guardians->shouldReceive('payerFor')->with(42)->andReturn(5);
$this->guardians->shouldReceive('payerFor')->with(43)->andReturn(5);
$this->guardians->shouldReceive('studentName')->with(42)->andReturn('Ada');
$this->guardians->shouldReceive('studentName')->with(43)->andReturn('Alan');
$this->payments->shouldReceive('createForRegistration')
->andReturn($this->pending(500, '2026-07-14'), $this->pending(501, '2026-07-14'));
// One send, two lines, each prefixed with the child it is for.
$this->mailer->shouldReceive('send')
->once()
->with(
Mockery::type(\WP_User::class),
Mockery::on(static function (array $items): bool {
return count($items) === 2
&& str_starts_with((string) $items[0]['label'], 'Ada: ')
&& str_starts_with((string) $items[1]['label'], 'Alan: ');
}),
Mockery::type('string'),
0.0
);
$this->runner->run();
}
/**
* A student who pays for themselves gets the plain label — prefixing every
* line with their own name would be noise.
*/
public function testAStudentPayingForThemselvesGetsAnUnprefixedLabel(): void
{
$this->now('2026-07-15 09:00:00');
$this->bookings->shouldReceive('findUnbilledScheduledLessons')
->andReturn([$this->lessonRow(101, Offering::BILLING_WEEKLY, '2026-07-15 18:00:00', 35.0)]);
$this->payments->shouldReceive('createForRegistration')->andReturn($this->pending(500, '2026-07-14'));
$this->mailer->shouldReceive('send')
->once()
->with(
Mockery::type(\WP_User::class),
Mockery::on(static fn (array $items): bool => str_starts_with((string) $items[0]['label'], 'Piano — ')),
Mockery::type('string'),
0.0
);
$this->runner->run();
}
/**
* The family balance is drawn against the payer, so a credit one child
* earned can settle a sibling's charge.
*/
public function testCreditsAreAppliedAgainstThePayerNotEachStudent(): void
{
$this->now('2026-07-15 09:00:00');
$adas = $this->lessonRow(101, Offering::BILLING_WEEKLY, '2026-07-15 18:00:00', 35.0);
$adas->student_id = '42';
$this->bookings->shouldReceive('findUnbilledScheduledLessons')->andReturn([$adas]);
$this->guardians->shouldReceive('payerFor')->with(42)->andReturn(5);
$this->guardians->shouldReceive('studentName')->with(42)->andReturn('Ada');
$this->payments->shouldReceive('createForRegistration')->andReturn($this->pending(500, '2026-07-14'));
$this->payments->shouldReceive('applyCredits')->once()->with(5, Mockery::type('array'))->andReturn([]);
$this->mailer->shouldReceive('send')->once();
$this->runner->run();
}
}