Merge pull request 'Let the studio register the students who cannot register themselves' (#186) from fix/185-book-for-child-and-vet-group-enrolment into main
CI / Coding Standards & Static Analysis (push) Successful in 13m23s
CI / Tests (PHP 8.1) (push) Successful in 55s
CI / Tests (PHP 8.2) (push) Successful in 1m7s
CI / Tests (PHP 8.3) (push) Successful in 6m59s
CI / Tests (PHP 8.5) (push) Successful in 12m55s
CI / No Debug Code (push) Successful in 3s
CI / Build Plugin Zip (push) Successful in 5m53s
Release / Build and Publish Release (push) Successful in 8m5s
Release / Open next-version bump PR (push) Successful in 5s

Reviewed-on: #186
This commit was merged in pull request #186.
This commit is contained in:
2026-08-24 22:03:11 +00:00
12 changed files with 371 additions and 31 deletions
+5
View File
@@ -13,6 +13,11 @@ each change under the current top section as you work.
## [1.5.4] ## [1.5.4]
### Fixed
- **Adding students to a group class now checks that each one is actually a student.** **Add students directly** and **Make available** acted on whatever ids the form posted without confirming they named students at all, so a stale page — or a tampered submission — could put an instructor, an administrator, or an account that had since been deleted onto a class roster, raising a real payment against them. Both controls now skip anything that is not a student, and the "%d student(s) added" count tells you how many actually went through. Children and students awaiting approval are unaffected: they are students, and adding them is what these controls are for.
- **A refused booking no longer empties the Book a lesson for a student form.** Whatever the reason it came back — the time taken while you were typing, a weekly reservation asked for on a time that does not repeat — the panel reopens with the student, time, lesson type, both ticks and your note exactly as you left them, so a correction is one field, not five. A booking that goes through still leaves an empty form behind for the next one.
- **Booking a lesson for a child, or for a student you have not approved yet, no longer fails with "Choose a student to book for."** The **Book a lesson for a student** panel offered every student it could see, but then refused a good half of them: a parent's child and a self-signup still awaiting approval both appeared in the list, and both were rejected on submit — with an error that read as though no student had been chosen, and which cleared the form. Neither of those accounts is allowed to book *in their own name* (a child's is never signed in to at all, and an unapproved signup waits for you), and the panel was mistakenly applying that same restriction to the studio booking on their behalf, which is precisely the case it was built for. Anyone the panel offers can now be booked for.
## [1.5.3] ## [1.5.3]
### Added ### Added
+11
View File
@@ -192,6 +192,17 @@ controls beneath it:
a **pending** invite, the grant is attached to that invite and **no second link is a **pending** invite, the grant is attached to that invite and **no second link is
sent**. An address that already has an account is treated as **Make available** instead. sent**. An address that already has an account is treated as **Make available** instead.
Both student-picking controls vet every posted id with `Auth\RoleManager::isStudent()`
before acting on it — the same predicate the picker is built from, and the same one
`Booking\AdminBooking` guards a staff booking with. A posted id naming an instructor,
an administrator, or an account deleted since the page was drawn is skipped rather
than enrolled, so nothing can put a non-student on a roster or raise a payment
against one. Being a student is a matter of the **role**, not the `book_lesson`
capability, so a guardian's child and a signup still awaiting approval are both
fully enrollable — neither may enrol *themselves*, which is exactly what the studio
adding them is for. The reported count is what was actually added, so a skipped id
shows up as a smaller number.
When an email-invited person completes registration, `RegistrationPage` links their new When an email-invited person completes registration, `RegistrationPage` links their new
account to the grant (`GroupAccessRepository::linkStudentByEmail`), so the invite-only account to the grant (`GroupAccessRepository::linkStudentByEmail`), so the invite-only
class becomes enrollable for them — they choose whether to enrol. class becomes enrollable for them — they choose whether to enrol.
+15 -2
View File
@@ -96,11 +96,13 @@ lesson. The times offered are the open slots of the next eight weeks — every
instructor's on the studio **Scheduler**, only the instructor's own on **My instructor's on the studio **Scheduler**, only the instructor's own on **My
Lessons**, which `AdminBooking::book()` re-checks rather than trusting the Lessons**, which `AdminBooking::book()` re-checks rather than trusting the
posted slot id. The result is reported as a notice above the panel saying what posted slot id. The result is reported as a notice above the panel saying what
was booked and what it left owing; a refusal reopens the panel with the reason. was booked and what it left owing; a refusal reopens the panel with the reason
and every field as it was submitted, so only the mistake needs correcting. A
booking that succeeds clears the form, so the next one does not inherit it.
It is the same booking a student makes — `LessonBooker` claims the slot(s), It is the same booking a student makes — `LessonBooker` claims the slot(s),
writes the lesson row(s), and raises the payment exactly as `POST /bookings` writes the lesson row(s), and raises the payment exactly as `POST /bookings`
does — and differs in three deliberate ways: does — and differs in four deliberate ways:
1. **No intake answers or policy acceptances are recorded at booking time.** 1. **No intake answers or policy acceptances are recorded at booking time.**
Those are the student's to give; staff ticking the boxes for them would be an Those are the student's to give; staff ticking the boxes for them would be an
@@ -113,6 +115,17 @@ does — and differs in three deliberate ways:
whole series) is `confirmed` at once. Without the tick a pending payment is whole series) is `confirmed` at once. Without the tick a pending payment is
raised at the lesson type's price, per-occurrence for a weekly reservation, raised at the lesson type's price, per-occurrence for a weekly reservation,
and the lesson confirms when it settles like any other. and the lesson confirms when it settles like any other.
4. **It can book for a student who cannot book at all.** The guard is
`Auth\RoleManager::isStudent()` — the student *role*, not the `book_lesson`
capability — so it covers a guardian's child and a self-signup still awaiting
approval alike, and is shared with the group-class **Add students directly**
and **Make available** controls so the two paths cannot drift. Both hold the role;
both have `book_lesson` withheld (`Guardian\ChildLoginGate`,
`Auth\RegistrationLoginGate`) so that neither can book in their own name.
That restriction is on them, not on the studio acting for them — and for a
child, whose account is never signed in to, it is the only route to a lesson
besides their guardian's. The picker and the guard therefore accept exactly
the same set, so nothing offered in the panel can be refused as ineligible.
A weekly reservation needs a time that actually repeats: asked for one on a A weekly reservation needs a time that actually repeats: asked for one on a
one-off slot, the form refuses (`not_weekly`) rather than quietly booking a one-off slot, the form refuses (`not_weekly`) rather than quietly booking a
+21
View File
@@ -60,6 +60,27 @@ class RoleManager {
self::CAP_EXPORT_PAYMENTS, self::CAP_EXPORT_PAYMENTS,
]; ];
/**
* Whether a user account is a student the studio may act for.
*
* Deliberately the role and not the `book_lesson` capability: that capability
* is withheld from a guardian's child ({@see \Unsupervised\Schedular\Guardian\ChildLoginGate})
* and from a self-signup still awaiting approval
* ({@see \Unsupervised\Schedular\Auth\RegistrationLoginGate}), so that neither
* can book or enrol *in their own name*. Staff booking or enrolling on their
* behalf is the case those restrictions exist to leave open — and for a child,
* whose account is never signed in to, it is the only route there is.
*
* Use this for every "may the studio register this person?" check, so the
* pickers staff choose from and the guards that vet their choice cannot drift
* into offering someone who is then refused.
*/
public static function isStudent( int $userId ): bool {
$user = $userId > 0 ? get_userdata( $userId ) : false;
return $user instanceof \WP_User && in_array( self::STUDENT, (array) $user->roles, true );
}
public function __construct( private AccessSettings $access = new AccessSettings() ) {} public function __construct( private AccessSettings $access = new AccessSettings() ) {}
public function register(): void { public function register(): void {
+13 -4
View File
@@ -19,7 +19,7 @@ use Unsupervised\Schedular\Val;
* flow. * flow.
* *
* It reuses `LessonBooker` — the same offering rules, the same atomic slot claim, * It reuses `LessonBooker` — the same offering rules, the same atomic slot claim,
* the same billing — and differs from a student's own booking in exactly three * the same billing — and differs from a student's own booking in exactly four
* ways, each deliberate: * ways, each deliberate:
* *
* 1. **No intake questions or policy acceptances are recorded.** They are the * 1. **No intake questions or policy acceptances are recorded.** They are the
@@ -30,6 +30,10 @@ use Unsupervised\Schedular\Val;
* slot of the instructor's, including one only reachable past a deadline. * slot of the instructor's, including one only reachable past a deadline.
* 3. **It can be booked at no charge**, for a make-up or goodwill lesson, which * 3. **It can be booked at no charge**, for a make-up or goodwill lesson, which
* skips the payment entirely and confirms the lesson at once. * skips the payment entirely and confirms the lesson at once.
* 4. **It can book for a student who cannot book at all** — a guardian's child,
* or someone still awaiting approval. Both hold the student role but have
* `book_lesson` withheld so that neither can book in their own name; that is
* a limit on them, never on the studio acting for them.
*/ */
class AdminBooking { class AdminBooking {
@@ -54,7 +58,10 @@ class AdminBooking {
* @return string|\WP_Error Success notice, or why nothing was booked. * @return string|\WP_Error Success notice, or why nothing was booked.
*/ */
public function book( int $studentId, int $slotId, int $offeringId, string $recurrence, bool $noCharge, string $notes, int $onlyInstructorId = 0 ): string|\WP_Error { public function book( int $studentId, int $slotId, int $offeringId, string $recurrence, bool $noCharge, string $notes, int $onlyInstructorId = 0 ): string|\WP_Error {
if ( $studentId <= 0 || ! user_can( $studentId, RoleManager::CAP_BOOK_LESSON ) ) { // The student role, not the `book_lesson` capability — see
// {@see RoleManager::isStudent()} for why a child and an unapproved signup
// must both be bookable for.
if ( ! RoleManager::isStudent( $studentId ) ) {
return new \WP_Error( 'invalid_student', __( 'Choose a student to book for.', 'unsupervised-schedular' ) ); return new \WP_Error( 'invalid_student', __( 'Choose a student to book for.', 'unsupervised-schedular' ) );
} }
@@ -250,8 +257,10 @@ class AdminBooking {
} }
/** /**
* Everyone who can be booked for, by name — students and the children a * Everyone who can be booked for, by name — every holder of the student role,
* guardian books for alike, since both hold `book_lesson`. * which is exactly the set {@see book()} accepts. That deliberately includes
* the children a guardian books for and students still awaiting approval:
* neither may book in their own name, both may be booked for.
* *
* @return list<array{id: int, name: string}> * @return list<array{id: int, name: string}>
*/ */
+50 -9
View File
@@ -177,7 +177,7 @@ class LessonController {
* *
* @param list<array<string, mixed>> $rows * @param list<array<string, mixed>> $rows
*/ */
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter -- $notice and $error are read by the included template. // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter -- $notice is read by the included template.
private function renderLessonsPage( array $rows, string $pageSlug, int $onlyInstructorId, string $notice, string $error ): void { private function renderLessonsPage( array $rows, string $pageSlug, int $onlyInstructorId, string $notice, string $error ): void {
// View-state query params only (which view, which week) — nothing is // View-state query params only (which view, which week) — nothing is
// mutated from them, so no nonce applies. // mutated from them, so no nonce applies.
@@ -193,6 +193,11 @@ class LessonController {
$baseUrl = admin_url( 'admin.php?page=' . $pageSlug ); $baseUrl = admin_url( 'admin.php?page=' . $pageSlug );
$bookForm = $this->adminBooking->formData( $onlyInstructorId ); $bookForm = $this->adminBooking->formData( $onlyInstructorId );
// A refused booking is shown again as it was typed — losing five fields to a
// single mistake is what made the panel infuriating to correct. A successful
// one starts empty, so the next booking does not inherit the last one's.
$bookValues = '' !== $error ? $this->submittedBooking() : $this->emptyBooking();
include USC_PLUGIN_DIR . 'templates/admin/lessons.php'; include USC_PLUGIN_DIR . 'templates/admin/lessons.php';
} }
@@ -229,23 +234,59 @@ class LessonController {
* @return array{string, string} * @return array{string, string}
*/ */
private function bookForStudent( int $onlyInstructorId ): array { private function bookForStudent( int $onlyInstructorId ): array {
// phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce checked by the caller. $submitted = $this->submittedBooking();
$result = $this->adminBooking->book( $result = $this->adminBooking->book(
absint( Val::int( $_POST['student_id'] ?? 0 ) ), $submitted['student_id'],
absint( Val::int( $_POST['slot_id'] ?? 0 ) ), $submitted['slot_id'],
absint( Val::int( $_POST['offering_id'] ?? 0 ) ), $submitted['offering_id'],
isset( $_POST['recurrence_weekly'] ) ? Lesson::RECURRENCE_WEEKLY : Lesson::RECURRENCE_SINGLE, $submitted['weekly'] ? Lesson::RECURRENCE_WEEKLY : Lesson::RECURRENCE_SINGLE,
isset( $_POST['no_charge'] ), $submitted['no_charge'],
sanitize_text_field( Val::string( wp_unslash( $_POST['notes'] ?? '' ) ) ), $submitted['notes'],
$onlyInstructorId $onlyInstructorId
); );
// phpcs:enable WordPress.Security.NonceVerification.Missing
return $result instanceof \WP_Error return $result instanceof \WP_Error
? [ '', $result->get_error_message() ] ? [ '', $result->get_error_message() ]
: [ $result, '' ]; : [ $result, '' ];
} }
/**
* The book-for-a-student form exactly as submitted. Read in one place so what
* gets booked and what the form shows again after a refusal cannot drift apart
* on a field name.
*
* @return array{student_id: int, slot_id: int, offering_id: int, weekly: bool, no_charge: bool, notes: string}
*/
private function submittedBooking(): array {
// phpcs:disable WordPress.Security.NonceVerification.Missing -- read only after handleFormAction() has verified the nonce: to book, or to re-render (escaped) a form it refused.
return [
'student_id' => absint( Val::int( $_POST['student_id'] ?? 0 ) ),
'slot_id' => absint( Val::int( $_POST['slot_id'] ?? 0 ) ),
'offering_id' => absint( Val::int( $_POST['offering_id'] ?? 0 ) ),
'weekly' => isset( $_POST['recurrence_weekly'] ),
'no_charge' => isset( $_POST['no_charge'] ),
'notes' => sanitize_text_field( Val::string( wp_unslash( $_POST['notes'] ?? '' ) ) ),
];
// phpcs:enable WordPress.Security.NonceVerification.Missing
}
/**
* An untouched book-for-a-student form.
*
* @return array{student_id: int, slot_id: int, offering_id: int, weekly: bool, no_charge: bool, notes: string}
*/
private function emptyBooking(): array {
return [
'student_id' => 0,
'slot_id' => 0,
'offering_id' => 0,
'weekly' => false,
'no_charge' => false,
'notes' => '',
];
}
/** /**
* Apply a per-lesson payment override. When $onlyOwn, the payment must belong * Apply a per-lesson payment override. When $onlyOwn, the payment must belong
* to the current instructor. * to the current instructor.
+10 -2
View File
@@ -640,7 +640,15 @@ class GroupClassController {
} }
/** /**
* The de-duplicated positive student ids posted from a multi-select. * The de-duplicated student ids posted from a multi-select, keeping only ids
* that are actually students.
*
* The select is built from {@see studentOptions()}, but nothing stops a posted
* id naming an instructor, an administrator, or an account deleted since the
* page was drawn and enrolling one would write a roster row, and bill it,
* against someone who is not in the class. Vetting here covers both actions at
* once, and against the same {@see RoleManager::isStudent()} the picker uses,
* so a child or an unapproved signup is still perfectly enrollable.
* *
* @return list<int> * @return list<int>
*/ */
@@ -650,7 +658,7 @@ class GroupClassController {
$raw = (array) ( $_POST['student_ids'] ?? [] ); $raw = (array) ( $_POST['student_ids'] ?? [] );
$ids = array_filter( array_map( static fn( mixed $v ): int => absint( Val::int( $v ) ), $raw ) ); $ids = array_filter( array_map( static fn( mixed $v ): int => absint( Val::int( $v ) ), $raw ) );
return array_values( array_unique( $ids ) ); return array_values( array_filter( array_unique( $ids ), RoleManager::isStudent( ... ) ) );
} }
/** /**
+7 -6
View File
@@ -16,6 +16,7 @@ if (! defined('ABSPATH')) {
* @var string $notice * @var string $notice
* @var string $error * @var string $error
* @var array{students: list<array{id: int, name: string}>, offerings: list<array{id: int, label: string}>, slots: list<array{id: int, label: string, weekly: bool}>} $bookForm * @var array{students: list<array{id: int, name: string}>, offerings: list<array{id: int, label: string}>, slots: list<array{id: int, label: string, weekly: bool}>} $bookForm
* @var array{student_id: int, slot_id: int, offering_id: int, weekly: bool, no_charge: bool, notes: string} $bookValues
*/ */
?> ?>
<div class="wrap"> <div class="wrap">
@@ -54,7 +55,7 @@ if (! defined('ABSPATH')) {
<select name="student_id" id="usc-book-student" required> <select name="student_id" id="usc-book-student" required>
<option value=""><?php esc_html_e('Choose a student', 'unsupervised-schedular'); ?></option> <option value=""><?php esc_html_e('Choose a student', 'unsupervised-schedular'); ?></option>
<?php foreach ($bookForm['students'] as $student) : ?> <?php foreach ($bookForm['students'] as $student) : ?>
<option value="<?php echo esc_attr((string) $student['id']); ?>"><?php echo esc_html($student['name']); ?></option> <option value="<?php echo esc_attr((string) $student['id']); ?>" <?php selected($bookValues['student_id'], $student['id']); ?>><?php echo esc_html($student['name']); ?></option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
</td> </td>
@@ -65,7 +66,7 @@ if (! defined('ABSPATH')) {
<select name="slot_id" id="usc-book-slot" required style="max-width:100%;"> <select name="slot_id" id="usc-book-slot" required style="max-width:100%;">
<option value=""><?php esc_html_e('Choose an open time', 'unsupervised-schedular'); ?></option> <option value=""><?php esc_html_e('Choose an open time', 'unsupervised-schedular'); ?></option>
<?php foreach ($bookForm['slots'] as $slot) : ?> <?php foreach ($bookForm['slots'] as $slot) : ?>
<option value="<?php echo esc_attr((string) $slot['id']); ?>"><?php echo esc_html($slot['label']); ?></option> <option value="<?php echo esc_attr((string) $slot['id']); ?>" <?php selected($bookValues['slot_id'], $slot['id']); ?>><?php echo esc_html($slot['label']); ?></option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
</td> </td>
@@ -76,7 +77,7 @@ if (! defined('ABSPATH')) {
<select name="offering_id" id="usc-book-offering" style="max-width:100%;"> <select name="offering_id" id="usc-book-offering" style="max-width:100%;">
<option value="0"><?php esc_html_e('Use the time\'s own lesson type', 'unsupervised-schedular'); ?></option> <option value="0"><?php esc_html_e('Use the time\'s own lesson type', 'unsupervised-schedular'); ?></option>
<?php foreach ($bookForm['offerings'] as $offering) : ?> <?php foreach ($bookForm['offerings'] as $offering) : ?>
<option value="<?php echo esc_attr((string) $offering['id']); ?>"><?php echo esc_html($offering['label']); ?></option> <option value="<?php echo esc_attr((string) $offering['id']); ?>" <?php selected($bookValues['offering_id'], $offering['id']); ?>><?php echo esc_html($offering['label']); ?></option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
<p class="description"><?php esc_html_e('A time already tied to a lesson type is booked as that type; a general time needs one chosen here.', 'unsupervised-schedular'); ?></p> <p class="description"><?php esc_html_e('A time already tied to a lesson type is booked as that type; a general time needs one chosen here.', 'unsupervised-schedular'); ?></p>
@@ -86,12 +87,12 @@ if (! defined('ABSPATH')) {
<th scope="row"><?php esc_html_e('Options', 'unsupervised-schedular'); ?></th> <th scope="row"><?php esc_html_e('Options', 'unsupervised-schedular'); ?></th>
<td> <td>
<label> <label>
<input type="checkbox" name="recurrence_weekly" value="1"> <input type="checkbox" name="recurrence_weekly" value="1" <?php checked($bookValues['weekly']); ?>>
<?php esc_html_e('Reserve this time weekly for the rest of the term', 'unsupervised-schedular'); ?> <?php esc_html_e('Reserve this time weekly for the rest of the term', 'unsupervised-schedular'); ?>
</label> </label>
<p class="description"><?php esc_html_e('Only for a time that repeats weekly. Billed upfront as one payment.', 'unsupervised-schedular'); ?></p> <p class="description"><?php esc_html_e('Only for a time that repeats weekly. Billed upfront as one payment.', 'unsupervised-schedular'); ?></p>
<label> <label>
<input type="checkbox" name="no_charge" value="1"> <input type="checkbox" name="no_charge" value="1" <?php checked($bookValues['no_charge']); ?>>
<?php esc_html_e('No charge — book it free and confirm it now', 'unsupervised-schedular'); ?> <?php esc_html_e('No charge — book it free and confirm it now', 'unsupervised-schedular'); ?>
</label> </label>
<p class="description"><?php esc_html_e('For a make-up or goodwill lesson. Otherwise a pending payment is raised at the lesson type\'s price.', 'unsupervised-schedular'); ?></p> <p class="description"><?php esc_html_e('For a make-up or goodwill lesson. Otherwise a pending payment is raised at the lesson type\'s price.', 'unsupervised-schedular'); ?></p>
@@ -99,7 +100,7 @@ if (! defined('ABSPATH')) {
</tr> </tr>
<tr> <tr>
<th scope="row"><label for="usc-book-notes"><?php esc_html_e('Notes', 'unsupervised-schedular'); ?></label></th> <th scope="row"><label for="usc-book-notes"><?php esc_html_e('Notes', 'unsupervised-schedular'); ?></label></th>
<td><input type="text" name="notes" id="usc-book-notes" class="regular-text" maxlength="500"></td> <td><input type="text" name="notes" id="usc-book-notes" class="regular-text" maxlength="500" value="<?php echo esc_attr($bookValues['notes']); ?>"></td>
</tr> </tr>
</table> </table>
<p> <p>
+44
View File
@@ -155,4 +155,48 @@ class RoleManagerTest extends TestCase
(new RoleManager())->createRoles(); (new RoleManager())->createRoles();
} }
/**
* The predicate every staff-side "register this person" path shares. It is
* deliberately the role and not `book_lesson`, so the two accounts that have
* that capability withheld a guardian's child and an unapproved signup are
* still people the studio can act for.
*/
public function testIsStudentAcceptsAnyHolderOfTheStudentRole(): void
{
Functions\when('get_userdata')->justReturn($this->userWithRoles([RoleManager::STUDENT]));
self::assertTrue(RoleManager::isStudent(5));
}
public function testIsStudentRejectsSomeoneWhoIsNotAStudent(): void
{
Functions\when('get_userdata')->justReturn($this->userWithRoles([RoleManager::INSTRUCTOR]));
self::assertFalse(RoleManager::isStudent(5));
}
public function testIsStudentRejectsAnAccountThatNoLongerExists(): void
{
Functions\when('get_userdata')->justReturn(false);
self::assertFalse(RoleManager::isStudent(5));
}
public function testIsStudentRejectsNoOneChosenWithoutLookingAnyoneUp(): void
{
Functions\expect('get_userdata')->never();
self::assertFalse(RoleManager::isStudent(0));
}
/** @param list<string> $roles */
private function userWithRoles(array $roles): \WP_User
{
$user = \Mockery::mock(\WP_User::class);
$user->ID = 5;
$user->roles = $roles;
return $user;
}
} }
+72 -6
View File
@@ -5,6 +5,7 @@ namespace Unsupervised\Schedular\Tests\Unit\Booking;
use Brain\Monkey\Functions; use Brain\Monkey\Functions;
use Mockery; use Mockery;
use Unsupervised\Schedular\Auth\RoleManager;
use Unsupervised\Schedular\Availability\AvailabilityRepository; use Unsupervised\Schedular\Availability\AvailabilityRepository;
use Unsupervised\Schedular\Availability\AvailabilitySlot; use Unsupervised\Schedular\Availability\AvailabilitySlot;
use Unsupervised\Schedular\Booking\AdminBooking; use Unsupervised\Schedular\Booking\AdminBooking;
@@ -36,10 +37,10 @@ class AdminBookingTest extends TestCase
Functions\when('mysql2date')->alias( Functions\when('mysql2date')->alias(
static fn (string $format, string $date): string => date($format, (int) strtotime($date)) static fn (string $format, string $date): string => date($format, (int) strtotime($date))
); );
Functions\when('get_userdata')->justReturn(false); // The picker offers holders of the student role, and that is what the guard
// accepts; it is exercised on its own below.
Functions\when('get_userdata')->alias(fn (int $id): \WP_User => $this->user($id, 'Jane Doe'));
Functions\when('get_users')->justReturn([]); Functions\when('get_users')->justReturn([]);
// Everyone offered in the picker can book; the guard is exercised on its own.
Functions\when('user_can')->justReturn(true);
// The staff member doing the booking; stamped on the lesson as booked_by. // The staff member doing the booking; stamped on the lesson as booked_by.
Functions\when('get_current_user_id')->justReturn(3); Functions\when('get_current_user_id')->justReturn(3);
@@ -175,9 +176,9 @@ class AdminBookingTest extends TestCase
self::assertSame('slot_taken', $result->get_error_code()); self::assertSame('slot_taken', $result->get_error_code());
} }
public function testSomeoneWhoCannotBookLessonsIsRefused(): void public function testSomeoneWhoIsNotAStudentIsRefused(): void
{ {
Functions\when('user_can')->justReturn(false); Functions\when('get_userdata')->alias(fn (int $id): \WP_User => $this->user($id, 'Jane Doe', [RoleManager::INSTRUCTOR]));
$this->availability->shouldReceive('findById')->never(); $this->availability->shouldReceive('findById')->never();
$result = $this->admin->book(42, 7, 3, Lesson::RECURRENCE_SINGLE, false, ''); $result = $this->admin->book(42, 7, 3, Lesson::RECURRENCE_SINGLE, false, '');
@@ -186,6 +187,69 @@ class AdminBookingTest extends TestCase
self::assertSame('invalid_student', $result->get_error_code()); self::assertSame('invalid_student', $result->get_error_code());
} }
public function testAnAccountThatNoLongerExistsIsRefused(): void
{
Functions\when('get_userdata')->justReturn(false);
$this->availability->shouldReceive('findById')->never();
$result = $this->admin->book(42, 7, 3, Lesson::RECURRENCE_SINGLE, false, '');
self::assertInstanceOf(\WP_Error::class, $result);
self::assertSame('invalid_student', $result->get_error_code());
}
public function testNoStudentChosenIsRefusedWithoutLookingAnyoneUp(): void
{
Functions\expect('get_userdata')->never();
$this->availability->shouldReceive('findById')->never();
$result = $this->admin->book(0, 7, 3, Lesson::RECURRENCE_SINGLE, false, '');
self::assertInstanceOf(\WP_Error::class, $result);
self::assertSame('invalid_student', $result->get_error_code());
}
/**
* A child holds the student role but never `book_lesson` withheld so the
* account cannot book in its own name. The studio booking for them is the only
* route a child has to a lesson, so it must not be blocked by that.
*/
public function testBooksForAGuardiansChildWhoCannotBookThemselves(): void
{
Functions\when('user_can')->justReturn(false);
$this->availability->shouldReceive('findById')->with(7)->andReturn($this->slot());
$this->offerings->shouldReceive('findById')->with(3)->andReturn($this->offering());
$this->availability->shouldReceive('claim')->once()->with(7)->andReturn(true);
$this->bookings->shouldReceive('insert')->once()->andReturn(100);
$this->payments->shouldReceive('createForRegistration')->once()->andReturn($this->pendingPayment());
$notice = $this->admin->book(42, 7, 3, Lesson::RECURRENCE_SINGLE, false, '');
self::assertIsString($notice);
self::assertStringContainsString('30 min piano', $notice);
}
/**
* Same for a self-signup the studio has not approved yet: the front desk can
* still get them onto the calendar while the paperwork catches up.
*/
public function testBooksForAStudentStillAwaitingApproval(): void
{
Functions\when('user_can')->justReturn(false);
$this->availability->shouldReceive('findById')->with(7)->andReturn($this->slot());
$this->offerings->shouldReceive('findById')->with(3)->andReturn($this->offering());
$this->availability->shouldReceive('claim')->once()->with(7)->andReturn(true);
$this->bookings->shouldReceive('insert')->once()->with(Mockery::on(
static fn (Lesson $l): bool => 42 === $l->studentId
))->andReturn(100);
$this->payments->shouldReceive('createForRegistration')->once()->andReturn($this->pendingPayment());
$notice = $this->admin->book(42, 7, 3, Lesson::RECURRENCE_SINGLE, false, '');
self::assertIsString($notice);
self::assertStringContainsString('pending payment', $notice);
}
public function testATiedTimeCannotBeBookedAsADifferentLessonType(): void public function testATiedTimeCannotBeBookedAsADifferentLessonType(): void
{ {
$this->availability->shouldReceive('findById')->with(7)->andReturn($this->slot(offeringId: 3)); $this->availability->shouldReceive('findById')->with(7)->andReturn($this->slot(offeringId: 3));
@@ -299,10 +363,12 @@ class AdminBookingTest extends TestCase
); );
} }
private function user(int $id, string $name): \WP_User /** @param list<string> $roles */
private function user(int $id, string $name, array $roles = [RoleManager::STUDENT]): \WP_User
{ {
$user = Mockery::mock(\WP_User::class); $user = Mockery::mock(\WP_User::class);
$user->ID = $id; $user->ID = $id;
$user->roles = $roles;
$user->first_name = ''; $user->first_name = '';
$user->last_name = ''; $user->last_name = '';
$user->nickname = $name; $user->nickname = $name;
@@ -316,6 +316,54 @@ class LessonControllerTest extends TestCase
self::assertStringContainsString('name="usc_action" value="book_for_student"', $html); self::assertStringContainsString('name="usc_action" value="book_for_student"', $html);
} }
/**
* A refusal used to clear all five fields, so one mistake meant retyping the
* whole form and the panel is only ever reopened *because* something was
* refused.
*/
public function testARefusedBookingComesBackWithEveryFieldStillFilledIn(): void
{
$this->postBooking();
$this->offerPanel();
$this->adminBooking->shouldReceive('book')->once()->andReturn(
new \WP_Error('slot_taken', 'That time has already been booked.')
);
$this->bookings->shouldReceive('findAllUpcoming')->once()->andReturn([]);
$html = $this->render();
self::assertStringContainsString('That time has already been booked.', $html);
// Attribute spacing in the template is not what is under test here.
$tags = (string) preg_replace('/\s+/', ' ', $html);
// The panel is reopened, showing the student, time and lesson type as posted.
self::assertStringContainsString(' open>', $html);
self::assertStringContainsString('value="42" selected=\'selected\'', $tags);
self::assertStringContainsString('value="7" selected=\'selected\'', $tags);
self::assertStringContainsString('value="3" selected=\'selected\'', $tags);
// Both ticks and the note survive too.
self::assertSame(2, substr_count($html, "checked='checked'"));
self::assertStringContainsString('value="Make-up lesson"', $html);
}
public function testASuccessfulBookingLeavesAnEmptyFormForTheNextOne(): void
{
$this->postBooking();
$this->offerPanel();
$this->adminBooking->shouldReceive('book')->once()->andReturn('Booked.');
$this->bookings->shouldReceive('findAllUpcoming')->once()->andReturn([]);
$html = $this->render();
self::assertStringContainsString('Booked.', $html);
// Nothing carried over, or the next booking silently inherits this one's.
self::assertStringNotContainsString("selected='selected'", $html);
self::assertStringNotContainsString("checked='checked'", $html);
self::assertStringContainsString('value=""', $html);
}
public function testTheStudioSchedulerBooksAgainstAnyInstructorsTime(): void public function testTheStudioSchedulerBooksAgainstAnyInstructorsTime(): void
{ {
$this->postBooking(); $this->postBooking();
@@ -390,6 +438,16 @@ class LessonControllerTest extends TestCase
Functions\when('absint')->alias(static fn ($v): int => abs((int) $v)); Functions\when('absint')->alias(static fn ($v): int => abs((int) $v));
} }
/** The panel with one of each choice, so a re-selected value has somewhere to land. */
private function offerPanel(): void
{
$this->adminBooking->shouldReceive('formData')->once()->andReturn([
'students' => [['id' => 42, 'name' => 'Ada Lovelace']],
'offerings' => [['id' => 3, 'label' => '30 min piano (30 min)']],
'slots' => [['id' => 7, 'label' => 'Wed Jul 1, 2026 10:00 AM (30 min)', 'weekly' => false]],
]);
}
public function testAStaffBookedLessonOffersTheRecordIntakeForm(): void public function testAStaffBookedLessonOffersTheRecordIntakeForm(): void
{ {
$_GET['lesson_id'] = '1'; $_GET['lesson_id'] = '1';
@@ -7,6 +7,7 @@ use Brain\Monkey\Functions;
use Mockery; use Mockery;
use Unsupervised\Schedular\Auth\InviteRepository; use Unsupervised\Schedular\Auth\InviteRepository;
use Unsupervised\Schedular\Auth\RegistrationMailer; use Unsupervised\Schedular\Auth\RegistrationMailer;
use Unsupervised\Schedular\Auth\RoleManager;
use Unsupervised\Schedular\GroupClass\Enrollment; use Unsupervised\Schedular\GroupClass\Enrollment;
use Unsupervised\Schedular\GroupClass\EnrollmentRepository; use Unsupervised\Schedular\GroupClass\EnrollmentRepository;
use Unsupervised\Schedular\GroupClass\GroupAccessRepository; use Unsupervised\Schedular\GroupClass\GroupAccessRepository;
@@ -87,7 +88,8 @@ class GroupClassControllerTest extends TestCase
{ {
[$first, $last] = array_pad(explode(' ', $full, 2), 2, ''); [$first, $last] = array_pad(explode(' ', $full, 2), 2, '');
$user = Mockery::mock(\WP_User::class); $user = Mockery::mock(\WP_User::class);
$user->roles = [RoleManager::STUDENT];
$user->first_name = $first; $user->first_name = $first;
$user->last_name = $last; $user->last_name = $last;
$user->nickname = $full; $user->nickname = $full;
@@ -406,6 +408,8 @@ class GroupClassControllerTest extends TestCase
Functions\when('wp_unslash')->returnArg(); Functions\when('wp_unslash')->returnArg();
Functions\when('sanitize_email')->returnArg(); Functions\when('sanitize_email')->returnArg();
Functions\when('absint')->alias(static fn ($v) => abs((int) $v)); Functions\when('absint')->alias(static fn ($v) => abs((int) $v));
// Every posted id is vetted as a student before it is enrolled or granted.
Functions\when('get_userdata')->justReturn($this->userNamed('Ada Lovelace'));
// Render tail: no classes/enrolments to draw so the assertion targets the notice. // Render tail: no classes/enrolments to draw so the assertion targets the notice.
$this->offerings->shouldReceive('findAll')->with(3, Offering::KIND_GROUP_CLASS)->andReturn([]); $this->offerings->shouldReceive('findAll')->with(3, Offering::KIND_GROUP_CLASS)->andReturn([]);
@@ -544,6 +548,64 @@ class GroupClassControllerTest extends TestCase
$this->audit->shouldReceive('acceptances')->with($enrollment)->andReturn([]); $this->audit->shouldReceive('acceptances')->with($enrollment)->andReturn([]);
} }
/**
* The multi-select is built from the studio's students, but a posted id is just
* a number: it could name an instructor, an administrator, or an account
* deleted since the page was drawn. Enrolling one would put a non-student on
* the roster and raise a payment against them.
*/
public function testAddDirectIgnoresAnIdThatIsNotAStudent(): void
{
$_POST = ['usc_action' => 'add_direct', 'offering_id' => 8, 'student_ids' => [5]];
$this->stubActionContext();
$instructor = Mockery::mock(\WP_User::class);
$instructor->roles = [RoleManager::INSTRUCTOR];
Functions\when('get_userdata')->justReturn($instructor);
$this->offerings->shouldReceive('findById')->with(8)->andReturn($this->inviteOnlyOffering(100.0));
$this->enrollments->shouldReceive('insert')->never();
$this->paymentService->shouldReceive('createForRegistration')->never();
$this->access->shouldReceive('markEnrolled')->never();
$html = $this->renderInstructor();
self::assertStringContainsString('0 student(s) added to the class.', $html);
}
public function testAddDirectIgnoresAnAccountThatNoLongerExists(): void
{
$_POST = ['usc_action' => 'add_direct', 'offering_id' => 8, 'student_ids' => [5]];
$this->stubActionContext();
Functions\when('get_userdata')->justReturn(false);
$this->offerings->shouldReceive('findById')->with(8)->andReturn($this->inviteOnlyOffering(100.0));
$this->enrollments->shouldReceive('insert')->never();
$this->paymentService->shouldReceive('createForRegistration')->never();
$html = $this->renderInstructor();
self::assertStringContainsString('0 student(s) added to the class.', $html);
}
public function testGrantAccessIgnoresAnIdThatIsNotAStudent(): void
{
$_POST = ['usc_action' => 'grant_access', 'offering_id' => 8, 'student_ids' => [5]];
$this->stubActionContext();
$instructor = Mockery::mock(\WP_User::class);
$instructor->roles = [RoleManager::INSTRUCTOR];
Functions\when('get_userdata')->justReturn($instructor);
$this->offerings->shouldReceive('findById')->with(8)->andReturn($this->inviteOnlyOffering());
$this->access->shouldReceive('insert')->never();
$this->mailer->shouldReceive('sendClassAccessGranted')->never();
$html = $this->renderInstructor();
self::assertStringContainsString('0 student(s) granted access.', $html);
}
public function testGrantAccessCreatesGrantAndEmailsStudent(): void public function testGrantAccessCreatesGrantAndEmailsStudent(): void
{ {
$_POST = ['usc_action' => 'grant_access', 'offering_id' => 8, 'student_ids' => [5]]; $_POST = ['usc_action' => 'grant_access', 'offering_id' => 8, 'student_ids' => [5]];
@@ -554,7 +616,8 @@ class GroupClassControllerTest extends TestCase
$this->access->shouldReceive('hasGrant')->with(8, 5)->andReturn(false); $this->access->shouldReceive('hasGrant')->with(8, 5)->andReturn(false);
$this->access->shouldReceive('insert')->once()->andReturn(1); $this->access->shouldReceive('insert')->once()->andReturn(1);
$user = Mockery::mock(\WP_User::class); $user = Mockery::mock(\WP_User::class);
$user->roles = [RoleManager::STUDENT];
$user->user_email = '[email protected]'; $user->user_email = '[email protected]';
Functions\when('get_userdata')->justReturn($user); Functions\when('get_userdata')->justReturn($user);
$this->mailer->shouldReceive('sendClassAccessGranted')->once()->with($user, 'Private Choir')->andReturn(true); $this->mailer->shouldReceive('sendClassAccessGranted')->once()->with($user, 'Private Choir')->andReturn(true);