Add admin actions to the student detail view: cancel, withdraw, edit account
CI / Tests (PHP 8.2) (pull_request) Successful in 43s
CI / No Debug Code (pull_request) Successful in 2s
CI / Tests (PHP 8.3) (pull_request) Successful in 2m37s
CI / Tests (PHP 8.1) (pull_request) Successful in 44s
CI / Coding Standards (pull_request) Successful in 2m43s
CI / PHPStan (pull_request) Successful in 2m50s
CI / Build Plugin Zip (pull_request) Skipped

Adds the #70 follow-up onto the student detail page: studio admins can now
cancel an upcoming lesson (same path as student cancellation — slot freed,
pending payment voided), withdraw an active group-class enrolment (seat
freed, pending payment voided), and edit the student's display name and
email with validation and uniqueness checks.

Action logic lives in the new Auth\StudentActions (unit-tested with mocked
repositories); the controller routes nonce-protected POSTs to it and shows
success/error notices.

Closes #70

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
2026-07-18 18:25:12 -03:00
co-authored by Claude Fable 5
parent c49171695a
commit 5808523140
6 changed files with 393 additions and 15 deletions
+21 -4
View File
@@ -1,9 +1,10 @@
# Feature: Student Administration # Feature: Student Administration
## Overview ## Overview
A read-only studio-admin area to browse students and drill into one student's A studio-admin area to browse students, drill into one student's history and
history and upcoming activity — lessons and group-class enrolments — without upcoming activity — lessons and group-class enrolments — and act on their
digging through individual records. behalf: cancel a lesson, withdraw them from a group class, or fix their account
details.
## Data Model ## Data Model
No new tables. The views are composed from existing data: No new tables. The views are composed from existing data:
@@ -35,7 +36,17 @@ No new tables. The views are composed from existing data:
- **Payment history** (`manage_billing` only) — every payment, newest first: - **Payment history** (`manage_billing` only) — every payment, newest first:
date, context, method, status, subtotal, HST, total, and receipt number. date, context, method, status, subtotal, HST, total, and receipt number.
Read-only in this iteration; cancel/edit actions are a possible follow-up (#70). ### Admin actions (detail view)
All actions are nonce-protected POSTs handled on the detail page:
- **Edit account** — display name and email. The email must be valid and not in
use by another account.
- **Cancel lesson** — on any non-cancelled upcoming lesson. Uses the same path
as student-initiated cancellation: the lesson is marked `cancelled`, the
availability slot is freed for rebooking, and a still-pending payment is
voided. Paid lessons keep their payment — refunds stay a manual decision (#72).
- **Withdraw** — on an active group-class enrolment: marked `cancelled` (freeing
its capacity seat), with the same pending-payment voiding.
## Capabilities ## Capabilities
- `manage_students` — studio admin (administrators inherit it via the - `manage_students` — studio admin (administrators inherit it via the
@@ -53,6 +64,10 @@ Read-only in this iteration; cancel/edit actions are a possible follow-up (#70).
`Registration\AnswerRepository::findByStudent`, and `Registration\AnswerRepository::findByStudent`, and
`Payment\PaymentRepository::findByStudent`, resolving policy/version titles and `Payment\PaymentRepository::findByStudent`, resolving policy/version titles and
question labels (unit-tested with mocked repositories). question labels (unit-tested with mocked repositories).
- Actions: `Auth\StudentActions` — cancel lesson / withdraw enrolment (both
refuse records that don't belong to the student, and reuse
`Payment\PaymentService::voidPending`) and account updates via
`wp_update_user` (unit-tested with mocked repositories).
- Upcoming/past split: `Auth\StudentSchedule::partition()` (pure, unit-tested) - Upcoming/past split: `Auth\StudentSchedule::partition()` (pure, unit-tested)
- The upcoming/past split is extracted into a small pure helper so it is - The upcoming/past split is extracted into a small pure helper so it is
unit-testable (the controller itself follows the repo convention of not being unit-testable (the controller itself follows the repo convention of not being
@@ -61,6 +76,8 @@ Read-only in this iteration; cancel/edit actions are a possible follow-up (#70).
## Tests ## Tests
- `tests/Unit/Auth/StudentScheduleTest.php` (the pure upcoming/past split helper) - `tests/Unit/Auth/StudentScheduleTest.php` (the pure upcoming/past split helper)
- `tests/Unit/Auth/StudentHistoryTest.php` (history display rows + fallbacks) - `tests/Unit/Auth/StudentHistoryTest.php` (history display rows + fallbacks)
- `tests/Unit/Auth/StudentActionsTest.php` (cancel/withdraw guards + side
effects, account validation)
- `findByStudent` coverage in `tests/Unit/Policy/AcceptanceRepositoryTest.php`, - `findByStudent` coverage in `tests/Unit/Policy/AcceptanceRepositoryTest.php`,
`tests/Unit/Registration/AnswerRepositoryTest.php`, and `tests/Unit/Registration/AnswerRepositoryTest.php`, and
`tests/Unit/Payment/PaymentRepositoryTest.php` `tests/Unit/Payment/PaymentRepositoryTest.php`
+2 -1
View File
@@ -12,6 +12,7 @@ use Unsupervised\Schedular\Auth\RegistrationApprovalController;
use Unsupervised\Schedular\Auth\RegistrationController; use Unsupervised\Schedular\Auth\RegistrationController;
use Unsupervised\Schedular\Auth\RegistrationMailer; use Unsupervised\Schedular\Auth\RegistrationMailer;
use Unsupervised\Schedular\Auth\RoleManager; use Unsupervised\Schedular\Auth\RoleManager;
use Unsupervised\Schedular\Auth\StudentActions;
use Unsupervised\Schedular\Auth\StudentController; use Unsupervised\Schedular\Auth\StudentController;
use Unsupervised\Schedular\Auth\StudentHistory; use Unsupervised\Schedular\Auth\StudentHistory;
use Unsupervised\Schedular\Booking\BookingRepository; use Unsupervised\Schedular\Booking\BookingRepository;
@@ -61,7 +62,7 @@ class AdminMenu {
$this->registrationController = new RegistrationController( $invites ); $this->registrationController = new RegistrationController( $invites );
$this->registrationApprovalController = new RegistrationApprovalController( new RegistrationMailer() ); $this->registrationApprovalController = new RegistrationApprovalController( new RegistrationMailer() );
$this->groupClassController = new GroupClassController( $enrollments, $offerings ); $this->groupClassController = new GroupClassController( $enrollments, $offerings );
$this->studentController = new StudentController( $bookings, $availability, $offerings, $enrollments, $resolver, new StudentHistory( $acceptances, $policies, $policyVersions, $answers, $questions, $payments ) ); $this->studentController = new StudentController( $bookings, $availability, $offerings, $enrollments, $resolver, new StudentHistory( $acceptances, $policies, $policyVersions, $answers, $questions, $payments ), new StudentActions( $bookings, $availability, $enrollments, $paymentService ) );
$this->instructorController = new InstructorController(); $this->instructorController = new InstructorController();
$this->settings = $settings; $this->settings = $settings;
$this->accessSettings = new AccessSettings(); $this->accessSettings = new AccessSettings();
+92
View File
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Auth;
use Unsupervised\Schedular\Availability\AvailabilityRepository;
use Unsupervised\Schedular\Booking\BookingRepository;
use Unsupervised\Schedular\Booking\Lesson;
use Unsupervised\Schedular\GroupClass\Enrollment;
use Unsupervised\Schedular\GroupClass\EnrollmentRepository;
use Unsupervised\Schedular\Payment\PaymentService;
/**
* Studio-admin actions on a single student from the student detail view:
* cancelling a lesson, withdrawing a group-class enrolment, and editing basic
* account details. Mutations go through the same paths as the student-facing
* flows so slot release and pending-payment voiding stay consistent.
*/
class StudentActions {
public function __construct(
private BookingRepository $bookings,
private AvailabilityRepository $availability,
private EnrollmentRepository $enrollments,
private PaymentService $payments,
) {}
/**
* Cancel a lesson on the student's behalf: marks it cancelled, frees the
* slot for rebooking, and voids a still-pending payment. Paid lessons keep
* their payment — refunds are a manual, admin-side decision.
*/
public function cancelLesson( int $lessonId, int $studentId ): bool {
$lesson = $this->bookings->findById( $lessonId );
if ( null === $lesson || $lesson->studentId !== $studentId || Lesson::STATUS_CANCELLED === $lesson->status ) {
return false;
}
$this->bookings->updateStatus( $lessonId, Lesson::STATUS_CANCELLED );
$this->availability->release( $lesson->slotId );
$this->payments->voidPending( $lesson->paymentId );
return true;
}
/**
* Withdraw the student from a group class: marks the active enrolment
* cancelled (freeing its capacity seat) and voids a still-pending payment.
*/
public function withdrawEnrollment( int $enrollmentId, int $studentId ): bool {
$enrollment = $this->enrollments->findById( $enrollmentId );
if ( null === $enrollment || $enrollment->studentId !== $studentId || Enrollment::STATUS_ACTIVE !== $enrollment->status ) {
return false;
}
$this->enrollments->updateStatus( $enrollmentId, Enrollment::STATUS_CANCELLED );
$this->payments->voidPending( $enrollment->paymentId );
return true;
}
/**
* Update the student's display name and email. The email must be valid and
* not belong to another user.
*/
public function updateAccount( int $studentId, string $displayName, string $email ): bool|\WP_Error {
if ( '' === $displayName ) {
return new \WP_Error( 'empty_name', __( 'Display name cannot be empty.', 'unsupervised-schedular' ) );
}
if ( ! is_email( $email ) ) {
return new \WP_Error( 'invalid_email', __( 'Please enter a valid email address.', 'unsupervised-schedular' ) );
}
$existing = email_exists( $email );
if ( false !== $existing && (int) $existing !== $studentId ) {
return new \WP_Error( 'email_taken', __( 'Another account already uses this email address.', 'unsupervised-schedular' ) );
}
$result = wp_update_user(
[
'ID' => $studentId,
'display_name' => $displayName,
'user_email' => $email,
]
);
return $result instanceof \WP_Error ? $result : true;
}
}
+46 -1
View File
@@ -22,6 +22,7 @@ class StudentController {
private EnrollmentRepository $enrollments, private EnrollmentRepository $enrollments,
private BillingMethodResolver $resolver, private BillingMethodResolver $resolver,
private StudentHistory $history, private StudentHistory $history,
private StudentActions $actions,
) {} ) {}
public function renderPage(): void { public function renderPage(): void {
@@ -66,7 +67,13 @@ class StudentController {
private function renderDetail( \WP_User $student ): void { private function renderDetail( \WP_User $student ): void {
$canBilling = current_user_can( RoleManager::CAP_MANAGE_BILLING ); $canBilling = current_user_can( RoleManager::CAP_MANAGE_BILLING );
if ( $canBilling && isset( $_POST['usc_action'] ) && check_admin_referer( 'usc_student_billing' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- routing only; each action below verifies its own nonce.
$action = sanitize_key( Val::string( wp_unslash( $_POST['usc_action'] ?? '' ) ) );
$notice = '';
$error = '';
if ( $canBilling && 'set_billing' === $action && check_admin_referer( 'usc_student_billing' ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce checked above. // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce checked above.
$method = sanitize_key( Val::string( wp_unslash( $_POST['payment_method'] ?? '' ) ) ); $method = sanitize_key( Val::string( wp_unslash( $_POST['payment_method'] ?? '' ) ) );
if ( in_array( $method, Payment::VALID_METHODS, true ) ) { if ( in_array( $method, Payment::VALID_METHODS, true ) ) {
@@ -76,6 +83,42 @@ class StudentController {
} }
} }
if ( 'update_account' === $action && check_admin_referer( 'usc_student_actions' ) ) {
// phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce checked above.
$displayName = sanitize_text_field( Val::string( wp_unslash( $_POST['display_name'] ?? '' ) ) );
$email = sanitize_email( Val::string( wp_unslash( $_POST['user_email'] ?? '' ) ) );
// phpcs:enable WordPress.Security.NonceVerification.Missing
$result = $this->actions->updateAccount( (int) $student->ID, $displayName, $email );
if ( $result instanceof \WP_Error ) {
$error = $result->get_error_message();
} else {
$notice = __( 'Account details updated.', 'unsupervised-schedular' );
$fresh = get_userdata( (int) $student->ID );
$student = $fresh instanceof \WP_User ? $fresh : $student;
}
}
if ( 'cancel_lesson' === $action && check_admin_referer( 'usc_student_actions' ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce checked above.
$lessonId = absint( Val::int( $_POST['lesson_id'] ?? 0 ) );
if ( $this->actions->cancelLesson( $lessonId, (int) $student->ID ) ) {
$notice = __( 'Lesson cancelled.', 'unsupervised-schedular' );
} else {
$error = __( 'This lesson could not be cancelled.', 'unsupervised-schedular' );
}
}
if ( 'withdraw_enrollment' === $action && check_admin_referer( 'usc_student_actions' ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce checked above.
$enrollmentId = absint( Val::int( $_POST['enrollment_id'] ?? 0 ) );
if ( $this->actions->withdrawEnrollment( $enrollmentId, (int) $student->ID ) ) {
$notice = __( 'Enrolment withdrawn.', 'unsupervised-schedular' );
} else {
$error = __( 'This enrolment could not be withdrawn.', 'unsupervised-schedular' );
}
}
$billingOverride = Val::string( get_user_meta( (int) $student->ID, BillingMethodResolver::META_METHOD, true ) ); $billingOverride = Val::string( get_user_meta( (int) $student->ID, BillingMethodResolver::META_METHOD, true ) );
$billingDefault = $this->resolver->defaultMethod(); $billingDefault = $this->resolver->defaultMethod();
@@ -94,6 +137,7 @@ class StudentController {
$offering = $this->offerings->findById( $enrollment->offeringId ); $offering = $this->offerings->findById( $enrollment->offeringId );
return [ return [
'id' => (int) $enrollment->id,
'offering' => $offering ? $offering->title : (string) $enrollment->offeringId, 'offering' => $offering ? $offering->title : (string) $enrollment->offeringId,
'status' => $enrollment->status, 'status' => $enrollment->status,
]; ];
@@ -120,6 +164,7 @@ class StudentController {
$instructor = get_userdata( $lesson->instructorId ); $instructor = get_userdata( $lesson->instructorId );
return [ return [
'id' => (int) $lesson->id,
'start_dt' => $slot ? $slot->startDt : '', 'start_dt' => $slot ? $slot->startDt : '',
'end_dt' => $slot ? $slot->endDt : '', 'end_dt' => $slot ? $slot->endDt : '',
'offering' => $offering ? $offering->title : '—', 'offering' => $offering ? $offering->title : '—',
+61 -7
View File
@@ -7,9 +7,9 @@ if (! defined('ABSPATH')) {
/** /**
* @var \WP_User $student * @var \WP_User $student
* @var list<array{start_dt: string, end_dt: string, offering: string, instructor: string, status: string}> $upcoming * @var list<array{id: int, start_dt: string, end_dt: string, offering: string, instructor: string, status: string}> $upcoming
* @var list<array{start_dt: string, end_dt: string, offering: string, instructor: string, status: string}> $past * @var list<array{id: int, start_dt: string, end_dt: string, offering: string, instructor: string, status: string}> $past
* @var list<array{offering: string, status: string}> $enrolments * @var list<array{id: int, offering: string, status: string}> $enrolments
* @var list<array{policy: string, version: string, context: string, accepted_at: string}> $acceptances * @var list<array{policy: string, version: string, context: string, accepted_at: string}> $acceptances
* @var list<array{question: string, answer: string, context: string}> $intake * @var list<array{question: string, answer: string, context: string}> $intake
* @var list<array{created_at: string, context: string, method: string, status: string, amount: float, tax_amount: float, total: float, currency: string, receipt: string}> $payments * @var list<array{created_at: string, context: string, method: string, status: string, amount: float, tax_amount: float, total: float, currency: string, receipt: string}> $payments
@@ -17,9 +17,11 @@ if (! defined('ABSPATH')) {
* @var bool $canBilling * @var bool $canBilling
* @var string $billingOverride * @var string $billingOverride
* @var string $billingDefault * @var string $billingDefault
* @var string $notice
* @var string $error
*/ */
$renderLessons = static function (array $rows): void { $renderLessons = static function (array $rows, bool $withActions = false): void {
if (empty($rows)) { if (empty($rows)) {
echo '<p>' . esc_html__('None.', 'unsupervised-schedular') . '</p>'; echo '<p>' . esc_html__('None.', 'unsupervised-schedular') . '</p>';
return; return;
@@ -32,6 +34,9 @@ $renderLessons = static function (array $rows): void {
<th><?php esc_html_e('Offering', 'unsupervised-schedular'); ?></th> <th><?php esc_html_e('Offering', 'unsupervised-schedular'); ?></th>
<th><?php esc_html_e('Instructor', 'unsupervised-schedular'); ?></th> <th><?php esc_html_e('Instructor', 'unsupervised-schedular'); ?></th>
<th><?php esc_html_e('Status', 'unsupervised-schedular'); ?></th> <th><?php esc_html_e('Status', 'unsupervised-schedular'); ?></th>
<?php if ($withActions) : ?>
<th><?php esc_html_e('Actions', 'unsupervised-schedular'); ?></th>
<?php endif; ?>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -41,6 +46,20 @@ $renderLessons = static function (array $rows): void {
<td><?php echo esc_html($row['offering']); ?></td> <td><?php echo esc_html($row['offering']); ?></td>
<td><?php echo esc_html($row['instructor']); ?></td> <td><?php echo esc_html($row['instructor']); ?></td>
<td><?php echo esc_html($row['status']); ?></td> <td><?php echo esc_html($row['status']); ?></td>
<?php if ($withActions) : ?>
<td>
<?php if ($row['status'] !== 'cancelled') : ?>
<form method="post" style="display:inline">
<?php wp_nonce_field('usc_student_actions'); ?>
<input type="hidden" name="usc_action" value="cancel_lesson">
<input type="hidden" name="lesson_id" value="<?php echo esc_attr((string) $row['id']); ?>">
<button type="submit" class="button-link button-link-delete" onclick="return confirm('<?php echo esc_js(__('Cancel this lesson? The slot is freed and any pending payment is voided.', 'unsupervised-schedular')); ?>');">
<?php esc_html_e('Cancel lesson', 'unsupervised-schedular'); ?>
</button>
</form>
<?php endif; ?>
</td>
<?php endif; ?>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
</tbody> </tbody>
@@ -54,11 +73,33 @@ $renderLessons = static function (array $rows): void {
<a href="<?php echo esc_url($backUrl); ?>" class="page-title-action"><?php esc_html_e('Back to students', 'unsupervised-schedular'); ?></a> <a href="<?php echo esc_url($backUrl); ?>" class="page-title-action"><?php esc_html_e('Back to students', 'unsupervised-schedular'); ?></a>
</h1> </h1>
<?php if ($notice !== '') : ?>
<div class="notice notice-success is-dismissible"><p><?php echo esc_html($notice); ?></p></div>
<?php endif; ?>
<?php if ($error !== '') : ?>
<div class="notice notice-error is-dismissible"><p><?php echo esc_html($error); ?></p></div>
<?php endif; ?>
<h2><?php esc_html_e('Account', 'unsupervised-schedular'); ?></h2> <h2><?php esc_html_e('Account', 'unsupervised-schedular'); ?></h2>
<form method="post">
<?php wp_nonce_field('usc_student_actions'); ?>
<input type="hidden" name="usc_action" value="update_account">
<table class="form-table"> <table class="form-table">
<tr><th><?php esc_html_e('Email', 'unsupervised-schedular'); ?></th><td><?php echo esc_html($student->user_email); ?></td></tr> <tr>
<tr><th><?php esc_html_e('Registered', 'unsupervised-schedular'); ?></th><td><?php echo esc_html($student->user_registered); ?></td></tr> <th><label for="usc-display-name"><?php esc_html_e('Display name', 'unsupervised-schedular'); ?></label></th>
<td><input type="text" id="usc-display-name" name="display_name" class="regular-text" value="<?php echo esc_attr($student->display_name); ?>" required></td>
</tr>
<tr>
<th><label for="usc-user-email"><?php esc_html_e('Email', 'unsupervised-schedular'); ?></label></th>
<td><input type="email" id="usc-user-email" name="user_email" class="regular-text" value="<?php echo esc_attr($student->user_email); ?>" required></td>
</tr>
<tr>
<th><?php esc_html_e('Registered', 'unsupervised-schedular'); ?></th>
<td><?php echo esc_html($student->user_registered); ?></td>
</tr>
</table> </table>
<?php submit_button(esc_html__('Save account details', 'unsupervised-schedular'), 'secondary', 'submit', false); ?>
</form>
<?php if ($canBilling) : ?> <?php if ($canBilling) : ?>
<h2><?php esc_html_e('Billing method', 'unsupervised-schedular'); ?></h2> <h2><?php esc_html_e('Billing method', 'unsupervised-schedular'); ?></h2>
@@ -81,7 +122,7 @@ $renderLessons = static function (array $rows): void {
<?php endif; ?> <?php endif; ?>
<h2><?php esc_html_e('Upcoming lessons', 'unsupervised-schedular'); ?></h2> <h2><?php esc_html_e('Upcoming lessons', 'unsupervised-schedular'); ?></h2>
<?php $renderLessons($upcoming); ?> <?php $renderLessons($upcoming, true); ?>
<h2><?php esc_html_e('Past lessons', 'unsupervised-schedular'); ?></h2> <h2><?php esc_html_e('Past lessons', 'unsupervised-schedular'); ?></h2>
<?php $renderLessons($past); ?> <?php $renderLessons($past); ?>
@@ -95,6 +136,7 @@ $renderLessons = static function (array $rows): void {
<tr> <tr>
<th><?php esc_html_e('Class', 'unsupervised-schedular'); ?></th> <th><?php esc_html_e('Class', 'unsupervised-schedular'); ?></th>
<th><?php esc_html_e('Status', 'unsupervised-schedular'); ?></th> <th><?php esc_html_e('Status', 'unsupervised-schedular'); ?></th>
<th><?php esc_html_e('Actions', 'unsupervised-schedular'); ?></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -102,6 +144,18 @@ $renderLessons = static function (array $rows): void {
<tr> <tr>
<td><?php echo esc_html($enrolment['offering']); ?></td> <td><?php echo esc_html($enrolment['offering']); ?></td>
<td><?php echo esc_html($enrolment['status']); ?></td> <td><?php echo esc_html($enrolment['status']); ?></td>
<td>
<?php if ($enrolment['status'] === 'active') : ?>
<form method="post" style="display:inline">
<?php wp_nonce_field('usc_student_actions'); ?>
<input type="hidden" name="usc_action" value="withdraw_enrollment">
<input type="hidden" name="enrollment_id" value="<?php echo esc_attr((string) $enrolment['id']); ?>">
<button type="submit" class="button-link button-link-delete" onclick="return confirm('<?php echo esc_js(__('Withdraw this student from the class? The seat is freed and any pending payment is voided.', 'unsupervised-schedular')); ?>');">
<?php esc_html_e('Withdraw', 'unsupervised-schedular'); ?>
</button>
</form>
<?php endif; ?>
</td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
</tbody> </tbody>
+169
View File
@@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Tests\Unit\Auth;
use Brain\Monkey\Functions;
use Mockery;
use Unsupervised\Schedular\Auth\StudentActions;
use Unsupervised\Schedular\Availability\AvailabilityRepository;
use Unsupervised\Schedular\Booking\BookingRepository;
use Unsupervised\Schedular\Booking\Lesson;
use Unsupervised\Schedular\GroupClass\Enrollment;
use Unsupervised\Schedular\GroupClass\EnrollmentRepository;
use Unsupervised\Schedular\Payment\PaymentService;
use Unsupervised\Schedular\Tests\Unit\TestCase;
class StudentActionsTest extends TestCase
{
private BookingRepository&Mockery\MockInterface $bookings;
private AvailabilityRepository&Mockery\MockInterface $availability;
private EnrollmentRepository&Mockery\MockInterface $enrollments;
private PaymentService&Mockery\MockInterface $payments;
private StudentActions $actions;
protected function setUp(): void
{
parent::setUp();
$this->bookings = Mockery::mock(BookingRepository::class);
$this->availability = Mockery::mock(AvailabilityRepository::class);
$this->enrollments = Mockery::mock(EnrollmentRepository::class);
$this->payments = Mockery::mock(PaymentService::class);
$this->actions = new StudentActions($this->bookings, $this->availability, $this->enrollments, $this->payments);
}
public function testCancelLessonCancelsFreesSlotAndVoidsPayment(): void
{
$this->bookings->shouldReceive('findById')->with(12)
->andReturn(new Lesson(7, 5, 3, status: Lesson::STATUS_PENDING, paymentId: 40, id: 12));
$this->bookings->shouldReceive('updateStatus')->once()->with(12, Lesson::STATUS_CANCELLED)->andReturn(true);
$this->availability->shouldReceive('release')->once()->with(7)->andReturn(true);
$this->payments->shouldReceive('voidPending')->once()->with(40);
self::assertTrue($this->actions->cancelLesson(12, 5));
}
public function testCancelLessonRefusesAnotherStudentsLesson(): void
{
$this->bookings->shouldReceive('findById')->with(12)
->andReturn(new Lesson(7, 6, 3, status: Lesson::STATUS_PENDING, id: 12));
$this->bookings->shouldNotReceive('updateStatus');
$this->availability->shouldNotReceive('release');
self::assertFalse($this->actions->cancelLesson(12, 5));
}
public function testCancelLessonRefusesAlreadyCancelledLesson(): void
{
$this->bookings->shouldReceive('findById')->with(12)
->andReturn(new Lesson(7, 5, 3, status: Lesson::STATUS_CANCELLED, id: 12));
$this->bookings->shouldNotReceive('updateStatus');
self::assertFalse($this->actions->cancelLesson(12, 5));
}
public function testCancelLessonRefusesMissingLesson(): void
{
$this->bookings->shouldReceive('findById')->with(99)->andReturn(null);
self::assertFalse($this->actions->cancelLesson(99, 5));
}
public function testWithdrawEnrollmentCancelsAndVoidsPayment(): void
{
$this->enrollments->shouldReceive('findById')->with(3)
->andReturn(new Enrollment(1, 5, 3, Enrollment::STATUS_ACTIVE, 41, 3));
$this->enrollments->shouldReceive('updateStatus')->once()->with(3, Enrollment::STATUS_CANCELLED)->andReturn(true);
$this->payments->shouldReceive('voidPending')->once()->with(41);
self::assertTrue($this->actions->withdrawEnrollment(3, 5));
}
public function testWithdrawEnrollmentRefusesInactiveEnrolment(): void
{
$this->enrollments->shouldReceive('findById')->with(3)
->andReturn(new Enrollment(1, 5, 3, Enrollment::STATUS_CANCELLED, null, 3));
$this->enrollments->shouldNotReceive('updateStatus');
self::assertFalse($this->actions->withdrawEnrollment(3, 5));
}
public function testWithdrawEnrollmentRefusesAnotherStudentsEnrolment(): void
{
$this->enrollments->shouldReceive('findById')->with(3)
->andReturn(new Enrollment(1, 6, 3, Enrollment::STATUS_ACTIVE, null, 3));
$this->enrollments->shouldNotReceive('updateStatus');
self::assertFalse($this->actions->withdrawEnrollment(3, 5));
}
public function testUpdateAccountSavesNameAndEmail(): void
{
Functions\when('is_email')->justReturn(true);
Functions\when('email_exists')->justReturn(false);
Functions\expect('wp_update_user')
->once()
->with(['ID' => 5, 'display_name' => 'New Name', 'user_email' => '[email protected]'])
->andReturn(5);
self::assertTrue($this->actions->updateAccount(5, 'New Name', '[email protected]'));
}
public function testUpdateAccountAllowsKeepingOwnEmail(): void
{
Functions\when('is_email')->justReturn(true);
Functions\when('email_exists')->justReturn(5);
Functions\when('wp_update_user')->justReturn(5);
self::assertTrue($this->actions->updateAccount(5, 'Name', '[email protected]'));
}
public function testUpdateAccountRejectsEmptyName(): void
{
$result = $this->actions->updateAccount(5, '', '[email protected]');
self::assertInstanceOf(\WP_Error::class, $result);
self::assertSame('empty_name', $result->get_error_code());
}
public function testUpdateAccountRejectsInvalidEmail(): void
{
Functions\when('is_email')->justReturn(false);
$result = $this->actions->updateAccount(5, 'Name', 'not-an-email');
self::assertInstanceOf(\WP_Error::class, $result);
self::assertSame('invalid_email', $result->get_error_code());
}
public function testUpdateAccountRejectsEmailOwnedByAnotherUser(): void
{
Functions\when('is_email')->justReturn(true);
Functions\when('email_exists')->justReturn(9);
$result = $this->actions->updateAccount(5, 'Name', '[email protected]');
self::assertInstanceOf(\WP_Error::class, $result);
self::assertSame('email_taken', $result->get_error_code());
}
public function testUpdateAccountPassesThroughWpError(): void
{
Functions\when('is_email')->justReturn(true);
Functions\when('email_exists')->justReturn(false);
Functions\when('wp_update_user')->justReturn(new \WP_Error('update_failed', 'nope'));
$result = $this->actions->updateAccount(5, 'Name', '[email protected]');
self::assertInstanceOf(\WP_Error::class, $result);
self::assertSame('update_failed', $result->get_error_code());
}
}