Stop the availability form failing in silence
CI / Tests (PHP 8.1) (pull_request) Successful in 56s
CI / Tests (PHP 8.2) (pull_request) Successful in 46s
CI / No Debug Code (pull_request) Successful in 2s
CI / Coding Standards (pull_request) Successful in 3m3s
CI / PHPStan (pull_request) Successful in 2m51s
CI / Tests (PHP 8.3) (pull_request) Successful in 2m50s
CI / Build Plugin Zip (pull_request) Skipped

Adding availability for 5:30-6:00 PM with the lesson length left on its
60-minute default saved nothing and said nothing. A window is stored as
consecutive lesson-length slots, so one that fits no lesson splits into
none: splitByDuration() returned [], createFromWindow() inserted
nothing, and addSlot() discarded the result and re-rendered the page
unchanged.

The REST endpoint already rejected that window with a 400. The admin
form checked the same rules separately, and its copy was both laxer and
mute — an unreadable date, an end before the start, and a two-day window
were bare `return`s, and it never checked offering ownership at all, so
a crafted POST could tie a slot to another instructor's offering and
inherit their price and payment routing.

Both callers now go through WindowValidator, which returns the window or
a WP_Error explaining the refusal. The endpoint returns that error as
is; the page renders its message as a notice. handleFormAction returns
a [notice, error] pair so deletes report themselves too, and a
successful add says how many slots it created.

Two failures could also go unnoticed underneath: wpdb::insert's result
was ignored, and insert_id still holds the previous statement's id after
a failed write, so a failure looked like a success — and could become
the recurrence group of a weekly series, orphaning every later
occurrence. weeks was unbounded server-side despite the form's max=52.

availability-admin.js narrows the lesson-length choices to those that
fit the window and blocks submission when none do, which is what makes
the original mistake hard to repeat. It is a convenience: the server
validates regardless.

Closes #130
This commit is contained in:
2026-07-28 23:19:49 -03:00
parent d9dd576630
commit 171b655bb8
15 changed files with 878 additions and 88 deletions
+29 -2
View File
@@ -5,6 +5,7 @@ namespace Unsupervised\Schedular;
use Unsupervised\Schedular\Availability\AvailabilityController;
use Unsupervised\Schedular\Availability\AvailabilityRepository;
use Unsupervised\Schedular\Availability\WindowValidator;
use Unsupervised\Schedular\Auth\AccessSettings;
use Unsupervised\Schedular\Auth\InstructorController;
use Unsupervised\Schedular\Auth\InviteRepository;
@@ -42,6 +43,12 @@ use Unsupervised\Schedular\Registration\QuestionRepository;
class AdminMenu {
/**
* Hook suffix of the availability screen, captured when the page is added so
* its script loads on that screen only.
*/
private string $availabilityHook = '';
private AvailabilityController $availabilityController;
private LessonController $lessonController;
private OfferingController $offeringController;
@@ -58,7 +65,7 @@ class AdminMenu {
private PaymentReportController $paymentReportController;
public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings, QuestionRepository $questions, AnswerRepository $answers, PolicyRepository $policies, PolicyVersionRepository $policyVersions, PolicyService $policyService, AcceptanceRepository $acceptances, InviteRepository $invites, EnrollmentRepository $enrollments, GroupAccessRepository $groupAccess, StudioSettings $settings, PaymentRepository $payments, PaymentService $paymentService, BillingMethodResolver $resolver, RegistrationMailer $registrationMailer, CreditRepository $credits ) {
$this->availabilityController = new AvailabilityController( $availability, $offerings );
$this->availabilityController = new AvailabilityController( $availability, $offerings, new WindowValidator( $offerings ) );
$this->lessonController = new LessonController( $bookings, $payments, $availability, $offerings, new LessonDetail( $answers, $questions, $acceptances, $policies, $policyVersions ) );
$this->offeringController = new OfferingController( $offerings, new ClassSlotReconciler( $availability ) );
$this->questionController = new QuestionController( $questions, $offerings );
@@ -76,9 +83,29 @@ class AdminMenu {
public function register(): void {
add_action( 'admin_menu', [ $this, 'addPages' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'enqueueAssets' ] );
add_action( 'admin_post_' . PaymentReportController::EXPORT_ACTION, [ $this->paymentReportController, 'export' ] );
}
/**
* Load a screen's script on that screen only.
*
* @param string $hookSuffix Screen the enqueue is running for.
*/
public function enqueueAssets( string $hookSuffix ): void {
if ( '' === $this->availabilityHook || $hookSuffix !== $this->availabilityHook ) {
return;
}
wp_enqueue_script(
'us-scheduler-availability-admin',
USC_PLUGIN_URL . 'assets/js/availability-admin.js',
[],
USC_VERSION,
true
);
}
public function addPages(): void {
$this->addStudioSeparators();
@@ -94,7 +121,7 @@ class AdminMenu {
);
// Instructor: manage their own availability.
add_menu_page(
$this->availabilityHook = (string) add_menu_page(
__( 'My Availability', 'unsupervised-schedular' ),
__( 'My Availability', 'unsupervised-schedular' ),
RoleManager::CAP_MANAGE_AVAILABILITY,
+107 -32
View File
@@ -13,6 +13,7 @@ class AvailabilityController {
public function __construct(
private AvailabilityRepository $repository,
private OfferingRepository $offerings,
private WindowValidator $validator,
) {}
public function renderPage(): void {
@@ -21,9 +22,11 @@ class AvailabilityController {
}
$instructorId = get_current_user_id();
$notice = '';
$error = '';
if ( isset( $_POST['usc_action'] ) && check_admin_referer( 'usc_availability_action' ) ) {
$this->handleFormAction( $instructorId );
[ $notice, $error ] = $this->handleFormAction( $instructorId );
}
$slots = $this->repository->findByInstructor( $instructorId );
@@ -44,72 +47,144 @@ class AvailabilityController {
include USC_PLUGIN_DIR . 'templates/admin/availability.php';
}
private function handleFormAction( int $instructorId ): void {
/**
* Run the submitted action and report what happened. Every branch returns a
* message: a form that silently reloads leaves the instructor unable to tell
* "saved 41 slots" from "saved nothing".
*
* @return array{string, string} Success notice and error message; each is
* empty when it does not apply.
*/
private function handleFormAction( int $instructorId ): array {
// Nonce is verified by the caller (renderPage) before this method runs.
// phpcs:disable WordPress.Security.NonceVerification.Missing
$action = sanitize_key( Val::string( wp_unslash( $_POST['usc_action'] ?? '' ) ) );
if ( 'add' === $action ) {
$this->addSlot( $instructorId );
return $this->addSlot( $instructorId );
}
if ( 'delete' === $action ) {
$this->deleteOwnSlot( absint( Val::int( $_POST['slot_id'] ?? 0 ) ), $instructorId );
return $this->deleteOwnSlot( absint( Val::int( $_POST['slot_id'] ?? 0 ) ), $instructorId )
? [ __( 'Availability slot deleted.', 'unsupervised-schedular' ), '' ]
: [ '', __( 'That slot could not be deleted. It may already be booked, or belong to someone else.', 'unsupervised-schedular' ) ];
}
if ( 'bulk_delete' === $action ) {
// The array itself carries no data; each element is coerced and
// absint-sanitized individually below.
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput
$rawIds = $_POST['slot_ids'] ?? [];
$rawIds = $_POST['slot_ids'] ?? [];
$deleted = 0;
$failed = 0;
foreach ( is_array( $rawIds ) ? $rawIds : [] as $rawId ) {
$this->deleteOwnSlot( absint( Val::int( $rawId ) ), $instructorId );
if ( $this->deleteOwnSlot( absint( Val::int( $rawId ) ), $instructorId ) ) {
++$deleted;
continue;
}
++$failed;
}
return $this->bulkDeleteResult( $deleted, $failed );
}
// phpcs:enable WordPress.Security.NonceVerification.Missing
return [ '', '' ];
}
/**
* Wording for a bulk delete, which can partly succeed.
*
* @return array{string, string}
*/
private function bulkDeleteResult( int $deleted, int $failed ): array {
$notice = $deleted > 0
? sprintf(
/* translators: %d: number of availability slots deleted. */
_n( '%d slot deleted.', '%d slots deleted.', $deleted, 'unsupervised-schedular' ),
$deleted
)
: '';
$error = $failed > 0
? sprintf(
/* translators: %d: number of slots that could not be deleted. */
_n(
'%d slot could not be deleted — it may already be booked.',
'%d slots could not be deleted — they may already be booked.',
$failed,
'unsupervised-schedular'
),
$failed
)
: '';
if ( 0 === $deleted && 0 === $failed ) {
$error = __( 'No slots were selected.', 'unsupervised-schedular' );
}
return [ $notice, $error ];
}
/**
* Delete a slot only when it exists and belongs to the given instructor.
* The repository additionally refuses to delete booked slots.
* The repository additionally refuses to delete booked slots. Returns whether
* the row actually went away.
*/
private function deleteOwnSlot( int $slotId, int $instructorId ): void {
private function deleteOwnSlot( int $slotId, int $instructorId ): bool {
if ( $slotId <= 0 ) {
return;
return false;
}
$slot = $this->repository->findById( $slotId );
if ( $slot && $slot->instructorId === $instructorId ) {
$this->repository->delete( $slotId );
if ( null === $slot || $slot->instructorId !== $instructorId ) {
return false;
}
return $this->repository->delete( $slotId );
}
private function addSlot( int $instructorId ): void {
/**
* Validate and persist a submitted window.
*
* @return array{string, string}
*/
private function addSlot( int $instructorId ): array {
// phpcs:disable WordPress.Security.NonceVerification.Missing
$startDt = AvailabilitySlot::normalizeDateTime( sanitize_text_field( Val::string( wp_unslash( $_POST['start_dt'] ?? '' ) ) ) );
$endDt = AvailabilitySlot::normalizeDateTime( sanitize_text_field( Val::string( wp_unslash( $_POST['end_dt'] ?? '' ) ) ) );
// A window must start and end on the same day (weekly repeat covers longer
// ranges) and fit at least one lesson; it is stored as lesson-length slots.
if ( null === $startDt || null === $endDt || $endDt <= $startDt || substr( $startDt, 0, 10 ) !== substr( $endDt, 0, 10 ) ) {
return;
}
$offeringId = absint( Val::int( $_POST['offering_id'] ?? 0 ) );
$duration = absint( Val::int( $_POST['duration_minutes'] ?? 0 ) );
$window = new AvailabilitySlot(
instructorId: $instructorId,
startDt: $startDt,
endDt: $endDt,
durationMinutes: $duration > 0 ? $duration : 60,
offeringId: $offeringId > 0 ? $offeringId : null,
$window = $this->validator->validate(
$instructorId,
sanitize_text_field( Val::string( wp_unslash( $_POST['start_dt'] ?? '' ) ) ),
sanitize_text_field( Val::string( wp_unslash( $_POST['end_dt'] ?? '' ) ) ),
absint( Val::int( $_POST['duration_minutes'] ?? 0 ) ),
absint( Val::int( $_POST['offering_id'] ?? 0 ) ),
);
if ( $window instanceof \WP_Error ) {
return [ '', $window->get_error_message() ];
}
$recurrence = sanitize_key( Val::string( wp_unslash( $_POST['recurrence'] ?? 'single' ) ) );
$weeks = absint( Val::int( $_POST['weeks'] ?? 1 ) );
$this->repository->createFromWindow( $window, 'weekly' === $recurrence, $weeks );
// phpcs:enable WordPress.Security.NonceVerification.Missing
$ids = $this->repository->createFromWindow( $window, 'weekly' === $recurrence, $weeks );
// The window was valid, so it split into at least one slot — an empty
// result means every insert failed.
if ( [] === $ids ) {
return [ '', __( 'The availability could not be saved. Please try again.', 'unsupervised-schedular' ) ];
}
return [
sprintf(
/* translators: %d: number of bookable slots created. */
_n( 'Added %d bookable slot.', 'Added %d bookable slots.', count( $ids ), 'unsupervised-schedular' ),
count( $ids )
),
'',
];
}
}
+17 -34
View File
@@ -4,14 +4,13 @@ declare(strict_types=1);
namespace Unsupervised\Schedular\Availability;
use Unsupervised\Schedular\Auth\RoleManager;
use Unsupervised\Schedular\Offering\OfferingRepository;
use Unsupervised\Schedular\Val;
class AvailabilityEndpoint {
public function __construct(
private AvailabilityRepository $repository,
private OfferingRepository $offerings,
private WindowValidator $validator,
) {}
/**
@@ -113,40 +112,18 @@ class AvailabilityEndpoint {
}
public function create( \WP_REST_Request $request ): \WP_REST_Response|\WP_Error {
$instructorId = get_current_user_id();
$offeringId = absint( Val::int( $request->get_param( 'offering_id' ) ) );
$duration = absint( Val::int( $request->get_param( 'duration_minutes' ) ) );
// A slot may only be tied to an offering the instructor owns, so it can
// never inherit another instructor's price or payment routing at booking.
if ( $offeringId > 0 ) {
$offering = $this->offerings->findById( $offeringId );
if ( null === $offering || $offering->instructorId !== $instructorId ) {
return new \WP_Error( 'invalid_offering', __( 'That offering is not available.', 'unsupervised-schedular' ), [ 'status' => 400 ] );
}
}
$startDt = AvailabilitySlot::normalizeDateTime( Val::string( $request->get_param( 'start_dt' ) ) );
$endDt = AvailabilitySlot::normalizeDateTime( Val::string( $request->get_param( 'end_dt' ) ) );
if ( null === $startDt || null === $endDt || $endDt <= $startDt ) {
return new \WP_Error( 'invalid_datetime', __( 'Provide a valid start and end, with the end after the start.', 'unsupervised-schedular' ), [ 'status' => 400 ] );
}
if ( substr( $startDt, 0, 10 ) !== substr( $endDt, 0, 10 ) ) {
return new \WP_Error( 'invalid_window', __( 'Availability must start and end on the same day. Use the weekly repeat to cover multiple weeks.', 'unsupervised-schedular' ), [ 'status' => 400 ] );
}
$window = new AvailabilitySlot(
instructorId: $instructorId,
startDt: $startDt,
endDt: $endDt,
durationMinutes: $duration > 0 ? $duration : 60,
offeringId: $offeringId > 0 ? $offeringId : null,
// Validation lives in WindowValidator so this endpoint and the admin form
// enforce exactly the same rules.
$window = $this->validator->validate(
get_current_user_id(),
Val::string( $request->get_param( 'start_dt' ) ),
Val::string( $request->get_param( 'end_dt' ) ),
absint( Val::int( $request->get_param( 'duration_minutes' ) ) ),
absint( Val::int( $request->get_param( 'offering_id' ) ) ),
);
if ( [] === $window->splitByDuration() ) {
return new \WP_Error( 'invalid_window', __( 'The availability window is shorter than the lesson length.', 'unsupervised-schedular' ), [ 'status' => 400 ] );
if ( $window instanceof \WP_Error ) {
return $window;
}
$ids = $this->repository->createFromWindow(
@@ -155,6 +132,12 @@ class AvailabilityEndpoint {
absint( Val::int( $request->get_param( 'weeks' ) ) )
);
// A valid window splits into at least one slot, so nothing written means
// every insert failed.
if ( [] === $ids ) {
return new \WP_Error( 'not_saved', __( 'The availability could not be saved.', 'unsupervised-schedular' ), [ 'status' => 500 ] );
}
return new \WP_REST_Response( [ 'ids' => $ids ], 201 );
}
+31 -6
View File
@@ -11,8 +11,14 @@ class AvailabilityRepository {
$this->table = $db->prefix . 'us_availability';
}
/**
* Insert one slot row. Returns its id, or 0 when the write failed —
* `insert_id` still holds the *previous* statement's id after a failed
* insert, so returning it unconditionally made a failed write look like a
* successful one.
*/
public function insert( AvailabilitySlot $slot ): int {
$this->db->insert(
$written = $this->db->insert(
$this->table,
[
'instructor_id' => $slot->instructorId,
@@ -27,7 +33,7 @@ class AvailabilityRepository {
[ '%d', '%d', '%s', '%s', '%d', '%d', '%d', '%s' ]
);
return $this->db->insert_id;
return false === $written ? 0 : $this->db->insert_id;
}
/**
@@ -42,9 +48,17 @@ class AvailabilityRepository {
$ids = [];
foreach ( $window->splitByDuration() as $slot ) {
$ids = $weekly
? array_merge( $ids, $this->createWeeklySeries( $slot, $weeks ) )
: [ ...$ids, $this->insert( $slot ) ];
if ( $weekly ) {
$ids = array_merge( $ids, $this->createWeeklySeries( $slot, $weeks ) );
continue;
}
$id = $this->insert( $slot );
// A failed insert returns 0; it must not reach the caller as an id.
if ( $id > 0 ) {
$ids[] = $id;
}
}
return $ids;
@@ -55,10 +69,14 @@ class AvailabilityRepository {
* separate row one week apart, all sharing a `recurrence_group` (the id of the
* first row).
*
* The count is clamped to `AvailabilitySlot::MAX_WEEKLY_OCCURRENCES`. The
* form's `max` attribute says the same, but only this is binding — a
* hand-crafted POST used to be able to ask for an unbounded number of rows.
*
* @return list<int> Inserted slot IDs.
*/
public function createWeeklySeries( AvailabilitySlot $first, int $occurrences ): array {
$occurrences = max( 1, $occurrences );
$occurrences = max( 1, min( AvailabilitySlot::MAX_WEEKLY_OCCURRENCES, $occurrences ) );
$start = new \DateTimeImmutable( $first->startDt );
$end = new \DateTimeImmutable( $first->endDt );
@@ -79,6 +97,13 @@ class AvailabilityRepository {
)
);
// A failed insert returns 0. Skipping it keeps a bogus id out of the
// returned list and, more importantly, stops 0 becoming the series'
// recurrence group — which would orphan every later occurrence.
if ( $id <= 0 ) {
continue;
}
if ( 0 === $groupId ) {
$groupId = $id;
$this->setRecurrenceGroup( $id, $groupId );
+17
View File
@@ -7,6 +7,23 @@ use Unsupervised\Schedular\Val;
class AvailabilitySlot {
/** Lesson length used when none was submitted. */
public const DEFAULT_DURATION_MINUTES = 60;
/**
* Lesson lengths a window can be split into, offered by the availability
* form. The form hides the ones a given window is too short for.
*
* @var list<int>
*/
public const DURATION_CHOICES = [ 30, 60 ];
/**
* Ceiling on a weekly series, matching the form's `max`. Enforced in the
* repository too, so a hand-crafted POST cannot ask for ten thousand rows.
*/
public const MAX_WEEKLY_OCCURRENCES = 52;
public function __construct(
public readonly int $instructorId,
public readonly string $startDt,
+105
View File
@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Availability;
use Unsupervised\Schedular\Offering\OfferingRepository;
/**
* Validates a submitted availability window.
*
* The admin form and the REST endpoint both accept the same window, and used to
* check it independently — the endpoint returning a specific 400 for each
* failure while the form simply returned, saving nothing and saying nothing. A
* 30-minute window submitted with the default 60-minute lesson length was the
* visible symptom: no rows, no error, no clue. Both callers now come through
* here, so neither can drift from the other again.
*
* Every rejection is a `WP_Error` carrying a message written for the person who
* submitted the form: the endpoint returns it as-is (the `status` data makes it
* a 400), and the admin screen shows `get_error_message()` in a notice.
*/
class WindowValidator {
public function __construct( private OfferingRepository $offerings ) {}
/**
* Check a submitted window and return it ready to persist.
*
* @param int $instructorId Instructor the window belongs to.
* @param string $rawStart Submitted start, in any form {@see AvailabilitySlot::normalizeDateTime()} accepts.
* @param string $rawEnd Submitted end, likewise.
* @param int $durationMinutes Lesson length the window is split into; 0 falls back to the 60-minute default.
* @param int $offeringId Offering the slots are tied to, or 0 for any private lesson.
*
* @return AvailabilitySlot|\WP_Error The window, or why it was rejected.
*/
public function validate( int $instructorId, string $rawStart, string $rawEnd, int $durationMinutes, int $offeringId ): AvailabilitySlot|\WP_Error {
$startDt = AvailabilitySlot::normalizeDateTime( $rawStart );
$endDt = AvailabilitySlot::normalizeDateTime( $rawEnd );
if ( null === $startDt || null === $endDt ) {
return new \WP_Error(
'invalid_datetime',
__( 'Enter a valid start and end date and time.', 'unsupervised-schedular' ),
[ 'status' => 400 ]
);
}
if ( $endDt <= $startDt ) {
return new \WP_Error(
'invalid_datetime',
__( 'The end time must be after the start time.', 'unsupervised-schedular' ),
[ 'status' => 400 ]
);
}
if ( substr( $startDt, 0, 10 ) !== substr( $endDt, 0, 10 ) ) {
return new \WP_Error(
'invalid_window',
__( 'Availability must start and end on the same day. Use the weekly repeat to cover multiple weeks.', 'unsupervised-schedular' ),
[ 'status' => 400 ]
);
}
// A slot may only be tied to an offering the instructor owns, so it can
// never inherit another instructor's price or payment routing at booking.
if ( $offeringId > 0 ) {
$offering = $this->offerings->findById( $offeringId );
if ( null === $offering || $offering->instructorId !== $instructorId ) {
return new \WP_Error(
'invalid_offering',
__( 'That offering is not available.', 'unsupervised-schedular' ),
[ 'status' => 400 ]
);
}
}
$duration = $durationMinutes > 0 ? $durationMinutes : AvailabilitySlot::DEFAULT_DURATION_MINUTES;
$window = new AvailabilitySlot(
instructorId: $instructorId,
startDt: $startDt,
endDt: $endDt,
durationMinutes: $duration,
offeringId: $offeringId > 0 ? $offeringId : null,
);
// The window is stored as lesson-length slots, so one that cannot fit a
// single lesson would persist nothing at all.
if ( [] === $window->splitByDuration() ) {
return new \WP_Error(
'invalid_window',
sprintf(
/* translators: %d: the selected lesson length, in minutes. */
__( 'This window is shorter than the %d-minute lesson length, so it holds no bookable slots. Choose a shorter lesson length or a longer window.', 'unsupervised-schedular' ),
$duration
),
[ 'status' => 400 ]
);
}
return $window;
}
}
+2 -1
View File
@@ -5,6 +5,7 @@ namespace Unsupervised\Schedular;
use Unsupervised\Schedular\Availability\AvailabilityEndpoint;
use Unsupervised\Schedular\Availability\AvailabilityRepository;
use Unsupervised\Schedular\Availability\WindowValidator;
use Unsupervised\Schedular\Booking\BookingEndpoint;
use Unsupervised\Schedular\Booking\BookingRepository;
use Unsupervised\Schedular\Booking\CancellationPolicy;
@@ -37,7 +38,7 @@ class RestRegistrar {
private PaymentEndpoint $paymentEndpoint;
public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings, QuestionRepository $questions, PolicyRepository $policies, PolicyVersionRepository $policyVersions, PolicyService $policyService, RegistrationGate $gate, EnrollmentRepository $enrollments, GroupAccessRepository $groupAccess, PaymentService $paymentService ) {
$this->availabilityEndpoint = new AvailabilityEndpoint( $availability, $offerings );
$this->availabilityEndpoint = new AvailabilityEndpoint( $availability, new WindowValidator( $offerings ) );
$this->bookingEndpoint = new BookingEndpoint( $availability, $bookings, $offerings, $gate, $paymentService, new CancellationPolicy( new StudioSettings() ) );
$this->offeringEndpoint = new OfferingEndpoint( $offerings, $groupAccess );
$this->questionEndpoint = new QuestionEndpoint( $questions, $offerings );