Add weekly and monthly scheduled billing for offerings
CI / Tests (PHP 8.2) (pull_request) Successful in 39s
CI / Tests (PHP 8.1) (pull_request) Successful in 1m12s
CI / No Debug Code (pull_request) Successful in 3s
CI / PHPStan (pull_request) Successful in 2m52s
CI / Coding Standards (pull_request) Successful in 2m54s
CI / Tests (PHP 8.3) (pull_request) Successful in 2m39s
CI / Build Plugin Zip (pull_request) Skipped
CI / Tests (PHP 8.2) (pull_request) Successful in 39s
CI / Tests (PHP 8.1) (pull_request) Successful in 1m12s
CI / No Debug Code (pull_request) Successful in 3s
CI / PHPStan (pull_request) Successful in 2m52s
CI / Coding Standards (pull_request) Successful in 2m54s
CI / Tests (PHP 8.3) (pull_request) Successful in 2m39s
CI / Build Plugin Zip (pull_request) Skipped
Offerings can now bill weekly (a pending payment 24h before each lesson) or monthly (one payment on the 1st for that month's lessons), alongside one-time and full-term. Applies to both private lessons and group classes. - Offering: new `weekly`/`monthly` billing modes + `isScheduledBilling()` - Booking/enrolment defer payment for scheduled modes; a single lesson booked after its due date has passed (e.g. an add-on in an already-billed month) is charged at booking instead - ScheduledBillingRunner: daily WP-Cron scan generates due payments across four cases (private/group × weekly/monthly), deduped via lesson.payment_id and payments.period_key - PaymentDueMailer: one consolidated itemised email per student per scan - Notice batch: payments emailed together share a reference; the admin Payments queue groups them with a lump-sum total for e-transfer reconciliation - Cancellation never voids a scheduled payment (Payment::isScheduled()) - Schema: us_payments gains due_date, period_key, notice_batch; USC_VERSION 1.2.0 composer test, composer lint, composer cs all pass. Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
@@ -383,6 +383,80 @@ class BookingEndpointTest extends TestCase
|
||||
self::assertSame(Lesson::STATUS_PENDING, $result->get_data()['status']);
|
||||
}
|
||||
|
||||
public function testScheduledBillingDefersPaymentAndConfirmsLesson(): void
|
||||
{
|
||||
// Weekly/monthly offerings are billed later by the daily scan, not at
|
||||
// booking: no payment is created now, and the reserved lesson is confirmed.
|
||||
$this->availability->shouldReceive('findById')->with(10)->andReturn($this->slot(10, 3, null));
|
||||
$this->offerings->shouldReceive('findById')->with(8)->andReturn(
|
||||
new Offering(instructorId: 3, kind: Offering::KIND_PRIVATE_LESSON, title: 'Lesson', price: 50.0, billingMode: Offering::BILLING_WEEKLY, id: 8)
|
||||
);
|
||||
$this->gate->shouldReceive('validate')->andReturn(null);
|
||||
$this->availability->shouldReceive('claim')->with(10)->once()->andReturn(true);
|
||||
$this->bookings->shouldReceive('insert')->once()->andReturn(77);
|
||||
$this->gate->shouldReceive('record')->once();
|
||||
$this->payments->shouldNotReceive('createForRegistration');
|
||||
$this->bookings->shouldReceive('updateStatus')->with(77, Lesson::STATUS_CONFIRMED)->once()->andReturn(true);
|
||||
|
||||
$request = new \WP_REST_Request(['slot_id' => 10, 'offering_id' => 8]);
|
||||
$result = $this->endpoint->book($request);
|
||||
|
||||
self::assertInstanceOf(\WP_REST_Response::class, $result);
|
||||
self::assertSame(Lesson::STATUS_CONFIRMED, $result->get_data()['status']);
|
||||
self::assertNull($result->get_data()['payment']);
|
||||
}
|
||||
|
||||
public function testMonthlyLessonInAlreadyBilledMonthChargesAtBooking(): void
|
||||
{
|
||||
// "now" is 2026-06-01; a monthly lesson booked into June (its billing 1st
|
||||
// already reached) is an add-on and must be charged at booking, not deferred.
|
||||
$this->availability->shouldReceive('findById')->with(10)->andReturn(
|
||||
new AvailabilitySlot(instructorId: 3, startDt: '2026-06-20 10:00:00', endDt: '2026-06-20 11:00:00', offeringId: null, id: 10)
|
||||
);
|
||||
$this->offerings->shouldReceive('findById')->with(8)->andReturn(
|
||||
new Offering(instructorId: 3, kind: Offering::KIND_PRIVATE_LESSON, title: 'Lesson', price: 45.0, billingMode: Offering::BILLING_MONTHLY, id: 8)
|
||||
);
|
||||
$this->gate->shouldReceive('validate')->andReturn(null);
|
||||
$this->availability->shouldReceive('claim')->with(10)->once()->andReturn(true);
|
||||
$this->bookings->shouldReceive('insert')->once()->andReturn(77);
|
||||
$this->gate->shouldReceive('record')->once();
|
||||
|
||||
// Charged now, for a single lesson's fee, as a normal (non-scheduled) payment.
|
||||
$this->payments->shouldReceive('createForRegistration')
|
||||
->once()
|
||||
->with(Payment::REG_LESSON, 77, 5, 3, 45.0, 'CAD', null)
|
||||
->andReturn(new Payment(5, 3, Payment::REG_LESSON, 77, 45.0, 'CAD', Payment::METHOD_ETRANSFER, Payment::STATUS_PENDING, id: 12));
|
||||
$this->bookings->shouldNotReceive('updateStatus');
|
||||
|
||||
$result = $this->endpoint->book(new \WP_REST_Request(['slot_id' => 10, 'offering_id' => 8]));
|
||||
|
||||
self::assertInstanceOf(\WP_REST_Response::class, $result);
|
||||
self::assertSame(Lesson::STATUS_PENDING, $result->get_data()['status']);
|
||||
self::assertNotNull($result->get_data()['payment']);
|
||||
}
|
||||
|
||||
public function testMonthlyLessonBeforeBillingDateDefersPayment(): void
|
||||
{
|
||||
// "now" is 2026-06-01; a monthly lesson for July is booked before July's 1st,
|
||||
// so it defers to the daily scan (no payment now, lesson confirmed).
|
||||
$this->availability->shouldReceive('findById')->with(10)->andReturn($this->slot(10, 3, null));
|
||||
$this->offerings->shouldReceive('findById')->with(8)->andReturn(
|
||||
new Offering(instructorId: 3, kind: Offering::KIND_PRIVATE_LESSON, title: 'Lesson', price: 45.0, billingMode: Offering::BILLING_MONTHLY, id: 8)
|
||||
);
|
||||
$this->gate->shouldReceive('validate')->andReturn(null);
|
||||
$this->availability->shouldReceive('claim')->with(10)->once()->andReturn(true);
|
||||
$this->bookings->shouldReceive('insert')->once()->andReturn(77);
|
||||
$this->gate->shouldReceive('record')->once();
|
||||
$this->payments->shouldNotReceive('createForRegistration');
|
||||
$this->bookings->shouldReceive('updateStatus')->with(77, Lesson::STATUS_CONFIRMED)->once()->andReturn(true);
|
||||
|
||||
$result = $this->endpoint->book(new \WP_REST_Request(['slot_id' => 10, 'offering_id' => 8]));
|
||||
|
||||
self::assertInstanceOf(\WP_REST_Response::class, $result);
|
||||
self::assertSame(Lesson::STATUS_CONFIRMED, $result->get_data()['status']);
|
||||
self::assertNull($result->get_data()['payment']);
|
||||
}
|
||||
|
||||
public function testCancelByOwnerCancelsReleasesSlotAndVoidsPayment(): void
|
||||
{
|
||||
$lesson = new Lesson(slotId: 10, studentId: 5, instructorId: 3, status: Lesson::STATUS_PENDING, paymentId: 12, id: 77);
|
||||
|
||||
@@ -184,6 +184,41 @@ class BookingRepositoryTest extends TestCase
|
||||
self::assertSame(15, $lessons[0]->id);
|
||||
}
|
||||
|
||||
public function testFindUnbilledScheduledLessonsJoinsOfferingAndFiltersUnbilled(): void
|
||||
{
|
||||
$this->db->shouldReceive('prepare')
|
||||
->once()
|
||||
->with(
|
||||
Mockery::pattern('/l.status != %s.*l.payment_id IS NULL.*o.billing_mode IN \( %s, %s \)/s'),
|
||||
'wp_us_lessons',
|
||||
'wp_us_availability',
|
||||
'wp_us_offerings',
|
||||
Lesson::STATUS_CANCELLED,
|
||||
'weekly',
|
||||
'monthly'
|
||||
)
|
||||
->andReturn('SELECT ...');
|
||||
|
||||
$row = (object) [
|
||||
'id' => '15',
|
||||
'student_id' => '5',
|
||||
'instructor_id' => '3',
|
||||
'offering_id' => '9',
|
||||
'start_dt' => '2026-07-15 18:00:00',
|
||||
'billing_mode' => 'weekly',
|
||||
'title' => 'Piano',
|
||||
'price' => '35.00',
|
||||
'currency' => 'CAD',
|
||||
'etransfer_email' => null,
|
||||
];
|
||||
$this->db->shouldReceive('get_results')->andReturn([$row]);
|
||||
|
||||
$rows = $this->repo->findUnbilledScheduledLessons();
|
||||
|
||||
self::assertCount(1, $rows);
|
||||
self::assertSame('15', $rows[0]->id);
|
||||
}
|
||||
|
||||
public function testCountUpcomingForStudent(): void
|
||||
{
|
||||
Functions\when('current_time')->justReturn('2026-06-08 12:00:00');
|
||||
|
||||
@@ -109,6 +109,22 @@ class EnrollmentEndpointTest extends TestCase
|
||||
);
|
||||
}
|
||||
|
||||
public function testScheduledBillingEnrollmentDefersPayment(): void
|
||||
{
|
||||
// A monthly group class is billed later by the daily scan, so enrolment
|
||||
// succeeds with no payment created now.
|
||||
$offering = new Offering(instructorId: 3, kind: Offering::KIND_GROUP_CLASS, title: 'Choir', price: 120.0, billingMode: Offering::BILLING_MONTHLY, id: 8);
|
||||
$this->offerings->shouldReceive('findById')->with(8)->andReturn($offering);
|
||||
$this->expectSuccessfulEnrollment();
|
||||
$this->payments->shouldNotReceive('createForRegistration');
|
||||
|
||||
$result = $this->endpoint->enroll(new \WP_REST_Request(['offering_id' => 8]));
|
||||
|
||||
self::assertInstanceOf(\WP_REST_Response::class, $result);
|
||||
self::assertSame(201, $result->get_status());
|
||||
self::assertNull($result->get_data()['payment']);
|
||||
}
|
||||
|
||||
public function testRejectsEnrollmentAfterExplicitDeadline(): void
|
||||
{
|
||||
// current_time is stubbed to 2026-07-24, past the 2026-07-10 deadline.
|
||||
|
||||
@@ -108,6 +108,44 @@ class EnrollmentRepositoryTest extends TestCase
|
||||
self::assertInstanceOf(Enrollment::class, $all[0]);
|
||||
}
|
||||
|
||||
public function testFindActiveByBillingModesJoinsOfferingAndFiltersModes(): void
|
||||
{
|
||||
$this->db->shouldReceive('prepare')
|
||||
->once()
|
||||
->with(
|
||||
Mockery::pattern('/e.status = %s.*o.billing_mode IN \( %s, %s \)/s'),
|
||||
'wp_us_group_enrollments',
|
||||
'wp_us_offerings',
|
||||
Enrollment::STATUS_ACTIVE,
|
||||
'weekly',
|
||||
'monthly'
|
||||
)
|
||||
->andReturn('SELECT ...');
|
||||
|
||||
$this->db->shouldReceive('get_results')->andReturn([
|
||||
(object) [
|
||||
'id' => '12',
|
||||
'offering_id' => '7',
|
||||
'student_id' => '5',
|
||||
'instructor_id' => '3',
|
||||
'status' => Enrollment::STATUS_ACTIVE,
|
||||
'payment_id' => null,
|
||||
],
|
||||
]);
|
||||
|
||||
$found = $this->repo->findActiveByBillingModes(['weekly', 'monthly']);
|
||||
|
||||
self::assertCount(1, $found);
|
||||
self::assertInstanceOf(Enrollment::class, $found[0]);
|
||||
}
|
||||
|
||||
public function testFindActiveByBillingModesReturnsEmptyForNoModes(): void
|
||||
{
|
||||
$this->db->shouldNotReceive('prepare');
|
||||
|
||||
self::assertSame([], $this->repo->findActiveByBillingModes([]));
|
||||
}
|
||||
|
||||
public function testUpdateStatusRejectsInvalid(): void
|
||||
{
|
||||
self::assertFalse($this->repo->updateStatus(1, 'bogus'));
|
||||
|
||||
@@ -276,6 +276,16 @@ class OfferingTest extends TestCase
|
||||
self::assertContains(Offering::KIND_GROUP_CLASS, Offering::VALID_KINDS);
|
||||
self::assertContains(Offering::BILLING_ONE_TIME, Offering::VALID_BILLING_MODES);
|
||||
self::assertContains(Offering::BILLING_FULL_TERM, Offering::VALID_BILLING_MODES);
|
||||
self::assertContains(Offering::BILLING_WEEKLY, Offering::VALID_BILLING_MODES);
|
||||
self::assertContains(Offering::BILLING_MONTHLY, Offering::VALID_BILLING_MODES);
|
||||
}
|
||||
|
||||
public function testIsScheduledBillingOnlyForWeeklyAndMonthly(): void
|
||||
{
|
||||
self::assertFalse((new Offering(1, Offering::KIND_PRIVATE_LESSON, 'A', billingMode: Offering::BILLING_ONE_TIME))->isScheduledBilling());
|
||||
self::assertFalse((new Offering(1, Offering::KIND_PRIVATE_LESSON, 'A', billingMode: Offering::BILLING_FULL_TERM))->isScheduledBilling());
|
||||
self::assertTrue((new Offering(1, Offering::KIND_PRIVATE_LESSON, 'A', billingMode: Offering::BILLING_WEEKLY))->isScheduledBilling());
|
||||
self::assertTrue((new Offering(1, Offering::KIND_GROUP_CLASS, 'A', billingMode: Offering::BILLING_MONTHLY))->isScheduledBilling());
|
||||
}
|
||||
|
||||
public function testEffectiveEnrollmentDeadlineDefaultsToTermStart(): void
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Tests\Unit\Payment;
|
||||
|
||||
use Brain\Monkey\Functions;
|
||||
use Mockery;
|
||||
use Unsupervised\Schedular\Payment\PaymentDueMailer;
|
||||
use Unsupervised\Schedular\Tests\Unit\TestCase;
|
||||
|
||||
class PaymentDueMailerTest extends TestCase
|
||||
{
|
||||
private function student(string $email): \WP_User
|
||||
{
|
||||
$student = Mockery::mock(\WP_User::class);
|
||||
$student->user_email = $email;
|
||||
|
||||
return $student;
|
||||
}
|
||||
|
||||
public function testReturnsFalseWithoutRecipient(): void
|
||||
{
|
||||
$items = [[ 'label' => 'x', 'amount' => 10.0, 'currency' => 'CAD', 'due_date' => '2026-07-14', 'etransfer_email' => null ]];
|
||||
|
||||
self::assertFalse((new PaymentDueMailer())->send($this->student(''), $items));
|
||||
}
|
||||
|
||||
public function testReturnsFalseWithNoItems(): void
|
||||
{
|
||||
self::assertFalse((new PaymentDueMailer())->send($this->student('[email protected]'), []));
|
||||
}
|
||||
|
||||
public function testConsolidatesItemsWithGrandTotal(): void
|
||||
{
|
||||
Functions\expect('wp_mail')
|
||||
->once()
|
||||
->with(
|
||||
'[email protected]',
|
||||
Mockery::type('string'),
|
||||
Mockery::on(static function (string $body): bool {
|
||||
return str_contains($body, 'Piano')
|
||||
&& str_contains($body, 'Jul 15, 2026')
|
||||
&& str_contains($body, 'Guitar')
|
||||
&& str_contains($body, 'Jul 22, 2026')
|
||||
&& str_contains($body, '35.00')
|
||||
&& str_contains($body, '40.00')
|
||||
// 35 + 40 grand total
|
||||
&& str_contains($body, '75.00');
|
||||
})
|
||||
)
|
||||
->andReturn(true);
|
||||
|
||||
$items = [
|
||||
[ 'label' => 'Piano', 'amount' => 35.0, 'currency' => 'CAD', 'due_date' => '2026-07-15', 'etransfer_email' => null ],
|
||||
[ 'label' => 'Guitar', 'amount' => 40.0, 'currency' => 'CAD', 'due_date' => '2026-07-22', 'etransfer_email' => null ],
|
||||
];
|
||||
|
||||
self::assertTrue((new PaymentDueMailer())->send($this->student('[email protected]'), $items));
|
||||
}
|
||||
|
||||
public function testIncludesReferenceWhenProvided(): void
|
||||
{
|
||||
Functions\expect('wp_mail')
|
||||
->once()
|
||||
->with(
|
||||
'[email protected]',
|
||||
Mockery::type('string'),
|
||||
Mockery::on(static fn (string $body): bool => str_contains($body, 'REF12345'))
|
||||
)
|
||||
->andReturn(true);
|
||||
|
||||
$items = [[ 'label' => 'Piano', 'amount' => 35.0, 'currency' => 'CAD', 'due_date' => '2026-07-15', 'etransfer_email' => null ]];
|
||||
|
||||
self::assertTrue((new PaymentDueMailer())->send($this->student('[email protected]'), $items, 'REF12345'));
|
||||
}
|
||||
|
||||
public function testIncludesEtransferDestination(): void
|
||||
{
|
||||
Functions\expect('wp_mail')
|
||||
->once()
|
||||
->with(
|
||||
'[email protected]',
|
||||
Mockery::type('string'),
|
||||
Mockery::on(static fn (string $body): bool => str_contains($body, '[email protected]'))
|
||||
)
|
||||
->andReturn(true);
|
||||
|
||||
$items = [[ 'label' => 'Piano', 'amount' => 35.0, 'currency' => 'CAD', 'due_date' => '2026-07-15', 'etransfer_email' => '[email protected]' ]];
|
||||
|
||||
self::assertTrue((new PaymentDueMailer())->send($this->student('[email protected]'), $items));
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,68 @@ class PaymentRepositoryTest extends TestCase
|
||||
self::assertSame(50, $this->repo->insert(new Payment(5, 3, Payment::REG_LESSON, 12, 35.00)));
|
||||
}
|
||||
|
||||
public function testInsertPersistsScheduledDueDateAndPeriodKey(): void
|
||||
{
|
||||
Functions\expect('current_time')->with('mysql')->andReturn('2026-06-08 12:00:00');
|
||||
|
||||
$this->db->shouldReceive('insert')
|
||||
->once()
|
||||
->with(
|
||||
'wp_us_payments',
|
||||
Mockery::on(static function (array $d): bool {
|
||||
return $d['due_date'] === '2026-07-14'
|
||||
&& $d['period_key'] === '2026-07-15';
|
||||
}),
|
||||
Mockery::type('array')
|
||||
);
|
||||
$this->db->insert_id = 51;
|
||||
|
||||
self::assertSame(
|
||||
51,
|
||||
$this->repo->insert(new Payment(5, 3, Payment::REG_LESSON, 12, 35.00, dueDate: '2026-07-14', periodKey: '2026-07-15'))
|
||||
);
|
||||
}
|
||||
|
||||
public function testExistsForPeriodReturnsTrueWhenRowFound(): void
|
||||
{
|
||||
$this->db->shouldReceive('prepare')
|
||||
->once()
|
||||
->with(Mockery::pattern('/registration_type = %s AND registration_id = %d AND period_key = %s/'), 'wp_us_payments', Payment::REG_ENROLLMENT, 7, '2026-07')
|
||||
->andReturn('SELECT ...');
|
||||
|
||||
$this->db->shouldReceive('get_var')->once()->with('SELECT ...')->andReturn('91');
|
||||
|
||||
self::assertTrue($this->repo->existsForPeriod(Payment::REG_ENROLLMENT, 7, '2026-07'));
|
||||
}
|
||||
|
||||
public function testExistsForPeriodReturnsFalseWhenAbsent(): void
|
||||
{
|
||||
$this->db->shouldReceive('prepare')->once()->andReturn('SELECT ...');
|
||||
$this->db->shouldReceive('get_var')->once()->andReturn(null);
|
||||
|
||||
self::assertFalse($this->repo->existsForPeriod(Payment::REG_ENROLLMENT, 7, '2026-08'));
|
||||
}
|
||||
|
||||
public function testAssignNoticeBatchUpdatesRows(): void
|
||||
{
|
||||
$this->db->shouldReceive('prepare')
|
||||
->once()
|
||||
->with(Mockery::pattern('/SET notice_batch = %s WHERE id IN \( %d, %d \)/'), 'wp_us_payments', 'REF12345', 5, 6)
|
||||
->andReturn('UPDATE ...');
|
||||
|
||||
$this->db->shouldReceive('query')->once()->with('UPDATE ...')->andReturn(2);
|
||||
|
||||
$this->repo->assignNoticeBatch([5, 6], 'REF12345');
|
||||
}
|
||||
|
||||
public function testAssignNoticeBatchNoopForEmptyIds(): void
|
||||
{
|
||||
$this->db->shouldNotReceive('prepare');
|
||||
$this->db->shouldNotReceive('query');
|
||||
|
||||
$this->repo->assignNoticeBatch([], 'REF12345');
|
||||
}
|
||||
|
||||
public function testMarkPaidUpdatesStatusAndReceipt(): void
|
||||
{
|
||||
Functions\expect('current_time')->with('mysql')->andReturn('2026-06-08 12:00:00');
|
||||
|
||||
@@ -76,6 +76,17 @@ class PaymentServiceTest extends TestCase
|
||||
$this->service->voidPending(50);
|
||||
}
|
||||
|
||||
public function testVoidPendingLeavesScheduledPaymentAlone(): void
|
||||
{
|
||||
// A scheduled (weekly/monthly) payment can cover several lessons and may be
|
||||
// collected: cancelling one lesson must never void it or trigger a rebill.
|
||||
$scheduled = new Payment(5, 3, Payment::REG_LESSON, 12, 35.00, 'CAD', Payment::METHOD_ETRANSFER, Payment::STATUS_PENDING, dueDate: '2026-07-14', id: 60);
|
||||
$this->payments->shouldReceive('findById')->with(60)->andReturn($scheduled);
|
||||
$this->payments->shouldNotReceive('updateStatus');
|
||||
|
||||
$this->service->voidPending(60);
|
||||
}
|
||||
|
||||
public function testVoidPendingLeavesPaidPaymentAlone(): void
|
||||
{
|
||||
// Refunds are manual: cancelling a paid lesson must not touch the ledger.
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
<?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\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 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();
|
||||
|
||||
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->runner = new ScheduledBillingRunner(
|
||||
$this->payments,
|
||||
$this->bookings,
|
||||
$this->enrollments,
|
||||
$this->offerings,
|
||||
$this->mailer
|
||||
);
|
||||
}
|
||||
|
||||
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, 'CAD', Payment::METHOD_ETRANSFER, 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')
|
||||
->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')
|
||||
->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')
|
||||
->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')
|
||||
->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')
|
||||
->andReturn($this->pending(701, '2026-07-13'));
|
||||
|
||||
$this->runner->run();
|
||||
}
|
||||
|
||||
public function testGroupMonthlyBillsMonthTotal(): 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: 4 sessions x 20, due on the 1st.
|
||||
$this->payments->shouldReceive('createForRegistration')
|
||||
->once()
|
||||
->with(Payment::REG_ENROLLMENT, 44, 5, 3, 80.0, 'CAD', null, '2026-07-01', '2026-07')
|
||||
->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, 'CAD', Payment::METHOD_COMP, 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'));
|
||||
|
||||
$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,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user