From 5ce42f000390b19c6ee86730b089c8fe25d29c47 Mon Sep 17 00:00:00 2001 From: James Griffin Date: Mon, 24 Aug 2026 18:42:59 -0300 Subject: [PATCH] Let the studio register the students who cannot register themselves MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Book a lesson for a student panel built its picker from the us_student role but vetted the submission with the book_lesson capability. ChildLoginGate and RegistrationLoginGate withhold that capability from accounts that keep the role, so the panel offered every guardian-managed child and every unapproved signup and then refused them — with a message claiming no student had been chosen, and a form cleared of all five fields. Withholding book_lesson stops those accounts registering in their own name. It was never meant to stop the studio acting for them, which is what the panel is for, and for a child is the only route to a lesson besides their guardian. Guard the student role instead, via a new RoleManager::isStudent() shared with every picker and guard on the staff side so the two cannot drift apart again. Group enrolment gets the same predicate: addDirect() and grantAccess() vetted their posted ids not at all, and would enrol an instructor, an administrator, or an account deleted since the page was drawn — raising a real payment against them for a priced class. Keep a refused booking's fields as submitted, reading the form through one LessonController::submittedBooking() so what gets booked and what is shown again cannot disagree about a field name. A booking that succeeds still leaves an empty form, so the next one does not inherit it. Closes #185 Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01XunBYk2sFEc1oL14sUiuBU --- CHANGELOG.md | 5 ++ docs/features/group-classes.md | 11 +++ docs/features/lesson-booking.md | 17 +++- src/Auth/RoleManager.php | 21 +++++ src/Booking/AdminBooking.php | 17 +++- src/Booking/LessonController.php | 59 +++++++++++--- src/GroupClass/GroupClassController.php | 12 ++- templates/admin/lessons.php | 13 ++-- tests/Unit/Auth/RoleManagerTest.php | 44 +++++++++++ tests/Unit/Booking/AdminBookingTest.php | 78 +++++++++++++++++-- tests/Unit/Booking/LessonControllerTest.php | 58 ++++++++++++++ .../GroupClass/GroupClassControllerTest.php | 67 +++++++++++++++- 12 files changed, 371 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57220c9..10384ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,11 @@ each change under the current top section as you work. ## [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] ### Added diff --git a/docs/features/group-classes.md b/docs/features/group-classes.md index 575a8c8..0c6a673 100644 --- a/docs/features/group-classes.md +++ b/docs/features/group-classes.md @@ -192,6 +192,17 @@ controls beneath it: 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. +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 account to the grant (`GroupAccessRepository::linkStudentByEmail`), so the invite-only class becomes enrollable for them — they choose whether to enrol. diff --git a/docs/features/lesson-booking.md b/docs/features/lesson-booking.md index d7eaa21..28cc232 100644 --- a/docs/features/lesson-booking.md +++ b/docs/features/lesson-booking.md @@ -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 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 -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), 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.** 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 raised at the lesson type's price, per-occurrence for a weekly reservation, 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 one-off slot, the form refuses (`not_weekly`) rather than quietly booking a diff --git a/src/Auth/RoleManager.php b/src/Auth/RoleManager.php index 9e647e5..84259c0 100644 --- a/src/Auth/RoleManager.php +++ b/src/Auth/RoleManager.php @@ -60,6 +60,27 @@ class RoleManager { 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 register(): void { diff --git a/src/Booking/AdminBooking.php b/src/Booking/AdminBooking.php index fea70e2..f21f39b 100644 --- a/src/Booking/AdminBooking.php +++ b/src/Booking/AdminBooking.php @@ -19,7 +19,7 @@ use Unsupervised\Schedular\Val; * flow. * * 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: * * 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. * 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. + * 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 { @@ -54,7 +58,10 @@ class AdminBooking { * @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 { - 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' ) ); } @@ -250,8 +257,10 @@ class AdminBooking { } /** - * Everyone who can be booked for, by name — students and the children a - * guardian books for alike, since both hold `book_lesson`. + * Everyone who can be booked for, by name — every holder of the student role, + * 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 */ diff --git a/src/Booking/LessonController.php b/src/Booking/LessonController.php index 2cf40f9..4f56771 100644 --- a/src/Booking/LessonController.php +++ b/src/Booking/LessonController.php @@ -177,7 +177,7 @@ class LessonController { * * @param list> $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 { // View-state query params only (which view, which week) — nothing is // mutated from them, so no nonce applies. @@ -193,6 +193,11 @@ class LessonController { $baseUrl = admin_url( 'admin.php?page=' . $pageSlug ); $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'; } @@ -229,23 +234,59 @@ class LessonController { * @return array{string, string} */ private function bookForStudent( int $onlyInstructorId ): array { - // phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce checked by the caller. + $submitted = $this->submittedBooking(); + $result = $this->adminBooking->book( - absint( Val::int( $_POST['student_id'] ?? 0 ) ), - absint( Val::int( $_POST['slot_id'] ?? 0 ) ), - absint( Val::int( $_POST['offering_id'] ?? 0 ) ), - isset( $_POST['recurrence_weekly'] ) ? Lesson::RECURRENCE_WEEKLY : Lesson::RECURRENCE_SINGLE, - isset( $_POST['no_charge'] ), - sanitize_text_field( Val::string( wp_unslash( $_POST['notes'] ?? '' ) ) ), + $submitted['student_id'], + $submitted['slot_id'], + $submitted['offering_id'], + $submitted['weekly'] ? Lesson::RECURRENCE_WEEKLY : Lesson::RECURRENCE_SINGLE, + $submitted['no_charge'], + $submitted['notes'], $onlyInstructorId ); - // phpcs:enable WordPress.Security.NonceVerification.Missing return $result instanceof \WP_Error ? [ '', $result->get_error_message() ] : [ $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 * to the current instructor. diff --git a/src/GroupClass/GroupClassController.php b/src/GroupClass/GroupClassController.php index f69ed1f..783c40d 100644 --- a/src/GroupClass/GroupClassController.php +++ b/src/GroupClass/GroupClassController.php @@ -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 */ @@ -650,7 +658,7 @@ class GroupClassController { $raw = (array) ( $_POST['student_ids'] ?? [] ); $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( ... ) ) ); } /** diff --git a/templates/admin/lessons.php b/templates/admin/lessons.php index 3dad459..a01e20b 100644 --- a/templates/admin/lessons.php +++ b/templates/admin/lessons.php @@ -16,6 +16,7 @@ if (! defined('ABSPATH')) { * @var string $notice * @var string $error * @var array{students: list, offerings: list, slots: list} $bookForm + * @var array{student_id: int, slot_id: int, offering_id: int, weekly: bool, no_charge: bool, notes: string} $bookValues */ ?>
@@ -54,7 +55,7 @@ if (! defined('ABSPATH')) { @@ -65,7 +66,7 @@ if (! defined('ABSPATH')) { @@ -76,7 +77,7 @@ if (! defined('ABSPATH')) {

@@ -86,12 +87,12 @@ if (! defined('ABSPATH')) {

@@ -99,7 +100,7 @@ if (! defined('ABSPATH')) { - +

diff --git a/tests/Unit/Auth/RoleManagerTest.php b/tests/Unit/Auth/RoleManagerTest.php index 7bba0e2..2b0ba7a 100644 --- a/tests/Unit/Auth/RoleManagerTest.php +++ b/tests/Unit/Auth/RoleManagerTest.php @@ -155,4 +155,48 @@ class RoleManagerTest extends TestCase (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 $roles */ + private function userWithRoles(array $roles): \WP_User + { + $user = \Mockery::mock(\WP_User::class); + $user->ID = 5; + $user->roles = $roles; + + return $user; + } } diff --git a/tests/Unit/Booking/AdminBookingTest.php b/tests/Unit/Booking/AdminBookingTest.php index a20be7a..0a4a201 100644 --- a/tests/Unit/Booking/AdminBookingTest.php +++ b/tests/Unit/Booking/AdminBookingTest.php @@ -5,6 +5,7 @@ namespace Unsupervised\Schedular\Tests\Unit\Booking; use Brain\Monkey\Functions; use Mockery; +use Unsupervised\Schedular\Auth\RoleManager; use Unsupervised\Schedular\Availability\AvailabilityRepository; use Unsupervised\Schedular\Availability\AvailabilitySlot; use Unsupervised\Schedular\Booking\AdminBooking; @@ -36,10 +37,10 @@ class AdminBookingTest extends TestCase Functions\when('mysql2date')->alias( 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([]); - // 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. Functions\when('get_current_user_id')->justReturn(3); @@ -175,9 +176,9 @@ class AdminBookingTest extends TestCase 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(); $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()); } + 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 { $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 $roles */ + private function user(int $id, string $name, array $roles = [RoleManager::STUDENT]): \WP_User { $user = Mockery::mock(\WP_User::class); $user->ID = $id; + $user->roles = $roles; $user->first_name = ''; $user->last_name = ''; $user->nickname = $name; diff --git a/tests/Unit/Booking/LessonControllerTest.php b/tests/Unit/Booking/LessonControllerTest.php index caea00c..04041ee 100644 --- a/tests/Unit/Booking/LessonControllerTest.php +++ b/tests/Unit/Booking/LessonControllerTest.php @@ -316,6 +316,54 @@ class LessonControllerTest extends TestCase 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 { $this->postBooking(); @@ -390,6 +438,16 @@ class LessonControllerTest extends TestCase 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 { $_GET['lesson_id'] = '1'; diff --git a/tests/Unit/GroupClass/GroupClassControllerTest.php b/tests/Unit/GroupClass/GroupClassControllerTest.php index ec34a57..fb8874f 100644 --- a/tests/Unit/GroupClass/GroupClassControllerTest.php +++ b/tests/Unit/GroupClass/GroupClassControllerTest.php @@ -7,6 +7,7 @@ use Brain\Monkey\Functions; use Mockery; use Unsupervised\Schedular\Auth\InviteRepository; use Unsupervised\Schedular\Auth\RegistrationMailer; +use Unsupervised\Schedular\Auth\RoleManager; use Unsupervised\Schedular\GroupClass\Enrollment; use Unsupervised\Schedular\GroupClass\EnrollmentRepository; use Unsupervised\Schedular\GroupClass\GroupAccessRepository; @@ -87,7 +88,8 @@ class GroupClassControllerTest extends TestCase { [$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->last_name = $last; $user->nickname = $full; @@ -406,6 +408,8 @@ class GroupClassControllerTest extends TestCase Functions\when('wp_unslash')->returnArg(); Functions\when('sanitize_email')->returnArg(); 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. $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([]); } + /** + * 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 { $_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('insert')->once()->andReturn(1); - $user = Mockery::mock(\WP_User::class); + $user = Mockery::mock(\WP_User::class); + $user->roles = [RoleManager::STUDENT]; $user->user_email = 'ada@b.test'; Functions\when('get_userdata')->justReturn($user); $this->mailer->shouldReceive('sendClassAccessGranted')->once()->with($user, 'Private Choir')->andReturn(true); -- 2.54.0