commit 0fbafc9d18f553b1fc7c31fa8903dc619753f3c3 Author: James Griffin Date: Mon Mar 30 12:44:46 2026 -0300 Initial plugin scaffold: lesson scheduling WordPress plugin - Custom DB tables for availability slots and lesson bookings - Instructor (wp-admin) and student (front-end) roles with custom capabilities - REST API under us-scheduler/v1 for availability CRUD and booking - [us_booking] and [us_student_login] shortcodes for student front end - PHPUnit + Brain\Monkey unit test suite (29 tests) - Gitea Actions CI: lint, PHPStan, tests on PHP 8.1/8.2/8.3, no-debug check - Feature docs under docs/features/ Co-Authored-By: Claude Sonnet 4.6 diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..b5ba3c9 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,102 @@ +name: CI + +on: + push: + branches: + - main + - develop + pull_request: + +jobs: + lint: + name: Coding Standards + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + tools: composer:v2 + + - name: Cache Composer packages + uses: actions/cache@v3 + with: + path: ~/.composer/cache + key: composer-${{ hashFiles('composer.json') }} + + - name: Install dependencies + run: composer install --prefer-dist --no-progress --no-interaction + + - name: Run PHPCS + run: composer cs + + static-analysis: + name: PHPStan + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + tools: composer:v2 + + - name: Cache Composer packages + uses: actions/cache@v3 + with: + path: ~/.composer/cache + key: composer-${{ hashFiles('composer.json') }} + + - name: Install dependencies + run: composer install --prefer-dist --no-progress --no-interaction + + - name: Run PHPStan + run: composer lint + + test: + name: Tests (PHP ${{ matrix.php }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: + - '8.1' + - '8.2' + - '8.3' + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: mbstring, intl + coverage: none + tools: composer:v2 + + - name: Cache Composer packages + uses: actions/cache@v3 + with: + path: ~/.composer/cache + key: ${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} + + - name: Install dependencies + run: composer install --prefer-dist --no-progress --no-interaction + + - name: Run PHPUnit + run: composer test + + no-debug: + name: No Debug Code + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Check for debug statements + run: | + if grep -rn --include="*.php" -E "(var_dump|var_export|print_r|error_log|dd\(|dump\()" src/; then + echo "Debug code found in src/ — please remove before merging." + exit 1 + fi diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c254820 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +vendor/ +composer.lock +coverage/ +.phpunit.result.cache +*.log diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..f2a7488 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,94 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Commands + +```bash +composer install # Install all dependencies + +composer test # Run the full test suite (required after every change) +composer lint # PHPStan static analysis +composer cs # PHPCS coding standards check +composer cs:fix # Auto-fix coding standards + +# Run a single test file +./vendor/bin/phpunit tests/Unit/Data/AvailabilityRepositoryTest.php + +# Run a single test by name +./vendor/bin/phpunit --filter testInsertCallsWpdbInsertAndReturnsId +``` + +**Run `composer test` after every code change before considering a task complete.** + +## Architecture + +### Plugin Bootstrap +`unsupervised-schedular.php` defines constants (`USC_VERSION`, `USC_PLUGIN_DIR`, `USC_PLUGIN_URL`), registers activation/deactivation hooks, then calls `Plugin::boot()` on `plugins_loaded`. No logic lives in the root file. + +### Directory Structure +``` +src/ — All plugin PHP (PSR-4 namespace: Unsupervised\Schedular\) +templates/ — PHP view files included by controllers/shortcodes +assets/ — CSS and JS (vanilla JS, no build step) +tests/Unit/ — PHPUnit unit tests (PSR-4: Unsupervised\Schedular\Tests\) +docs/features/— One markdown file per feature describing data model, API, and test locations +``` + +### Data Storage +Two custom database tables (created via `dbDelta` on activation): +- `{prefix}us_availability` — instructor availability windows +- `{prefix}us_lessons` — booked lessons + +All database access goes through repository classes in `src/Data/`. No direct `$wpdb` calls outside repositories. + +### Key Classes + +| Class | Responsibility | +|---|---| +| `Plugin` | Wires all components together on `plugins_loaded` | +| `Installer` | Creates DB tables and roles on activation | +| `Roles\RoleManager` | Registers `us_instructor` and `us_student` roles with custom caps | +| `Data\AvailabilityRepository` | CRUD for availability slots | +| `Data\BookingRepository` | CRUD for lesson bookings | +| `Model\AvailabilitySlot` | Immutable value object for a slot row | +| `Model\Lesson` | Immutable value object for a lesson row | +| `Admin\AdminMenu` | Registers wp-admin menu pages | +| `Admin\AvailabilityController` | Instructor availability management page | +| `Admin\LessonController` | Admin and instructor lesson list pages | +| `Api\RestRegistrar` | Registers all REST routes under `us-scheduler/v1` | +| `Api\AvailabilityEndpoint` | REST handlers for availability CRUD | +| `Api\BookingEndpoint` | REST handlers for booking and status updates | +| `Frontend\ShortcodeRegistrar` | Registers `[us_booking]` and `[us_student_login]` shortcodes | +| `Frontend\BookingPage` | Renders student booking UI shell (JS takes over) | +| `Frontend\LoginPage` | Renders front-end student login form | + +### REST API Namespace +All endpoints live under `/wp-json/us-scheduler/v1/`. Permissions are enforced via `permission_callback` using capability checks (`manage_availability`, `book_lesson`), never role name checks. + +### Testing Approach +Tests use [Brain\Monkey](https://brain-wp.github.io/BrainMonkey/) to stub WordPress functions without a full WP installation, and Mockery to mock `$wpdb` and other dependencies. + +All test classes extend `tests/Unit/TestCase.php`, which handles `Monkey\setUp()` / `Monkey\tearDown()` and stubs all WP translation/escape functions automatically. + +**Brain\Monkey API notes:** +- `Functions\when('fn')->alias(fn() => ...)` — stub with a closure (NOT `returnUsing()`) +- `Functions\when('fn')->justReturn($val)` — stub returning a fixed value +- `Functions\expect('fn')->once()->with(...)` — assert call count and arguments +- Use `Functions\when()` (not `Functions\expect()`) when you need argument-routing (e.g. `get_role` returning different values per argument) to avoid chaining ambiguity +- Mockery matchers (e.g. `\Mockery::type()`) inside plain PHP arrays do not work with `with()` — use `\Mockery::on(fn($arr) => ...)` or `\Mockery::any()` instead +- When mocking `$wpdb`, set `$mock->prefix = 'wp_'` explicitly — it is a public property, not a method + +### Adding a Feature +1. Write the feature doc in `docs/features/.md` (data model, API, classes, test paths). +2. Implement the classes under `src/`. +3. Add template(s) under `templates/` if needed. +4. Write unit tests under `tests/Unit/` mirroring the `src/` directory structure. +5. Run `composer test` — all tests must pass before the feature is complete. + +### CI +Gitea Actions (`.gitea/workflows/ci.yml`) runs on every push and pull request: +- **lint** — PHPCS WordPress coding standards +- **static-analysis** — PHPStan level 6 +- **test** — PHPUnit on PHP 8.1, 8.2, 8.3 +- **no-debug** — rejects commits with `var_dump`, `error_log`, etc. in `src/` diff --git a/assets/css/frontend.css b/assets/css/frontend.css new file mode 100644 index 0000000..4978dce --- /dev/null +++ b/assets/css/frontend.css @@ -0,0 +1,35 @@ +.us-login-form label { + display: block; + margin-bottom: 4px; + font-weight: 600; +} + +.us-login-form input[type="text"], +.us-login-form input[type="password"] { + width: 100%; + max-width: 340px; + padding: 8px; + border: 1px solid #ccc; + border-radius: 4px; +} + +.us-error { + color: #c00; + border-left: 4px solid #c00; + padding-left: 8px; +} + +#us-booking-app .us-slot { + border: 1px solid #ddd; + border-radius: 4px; + padding: 12px 16px; + margin-bottom: 8px; + display: flex; + justify-content: space-between; + align-items: center; +} + +#us-booking-error { + color: #c00; + margin-top: 8px; +} diff --git a/assets/js/booking.js b/assets/js/booking.js new file mode 100644 index 0000000..892e95a --- /dev/null +++ b/assets/js/booking.js @@ -0,0 +1,76 @@ +/* global usScheduler */ +(function () { + 'use strict'; + + const app = document.getElementById('us-booking-app'); + if (!app) return; + + const slotList = document.getElementById('us-slot-list'); + const confirm = document.getElementById('us-booking-confirmation'); + const errorBox = document.getElementById('us-booking-error'); + const { restUrl, nonce } = usScheduler; + + function apiFetch(path, options = {}) { + return fetch(restUrl + path, { + ...options, + headers: { + 'Content-Type': 'application/json', + 'X-WP-Nonce': nonce, + ...(options.headers || {}), + }, + }).then(async (res) => { + const data = await res.json(); + if (!res.ok) throw new Error(data.message || 'Request failed'); + return data; + }); + } + + function showError(message) { + errorBox.textContent = message; + errorBox.style.display = 'block'; + } + + function renderSlots(slots) { + if (!slots.length) { + slotList.innerHTML = '

No available lesson slots at this time.

'; + return; + } + + slotList.innerHTML = slots.map((slot) => ` +
+ ${escHtml(slot.start_dt)} – ${escHtml(slot.end_dt)} + +
+ `).join(''); + + slotList.querySelectorAll('.us-book-btn').forEach((btn) => { + btn.addEventListener('click', () => bookSlot(Number(btn.dataset.slotId))); + }); + } + + function escHtml(str) { + return String(str) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); + } + + function bookSlot(slotId) { + errorBox.style.display = 'none'; + + apiFetch('bookings', { + method: 'POST', + body: JSON.stringify({ slot_id: slotId }), + }) + .then(() => { + slotList.style.display = 'none'; + confirm.style.display = 'block'; + }) + .catch((err) => showError(err.message)); + } + + apiFetch('availability') + .then(renderSlots) + .catch((err) => showError(err.message)); +}()); diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..b8eedad --- /dev/null +++ b/composer.json @@ -0,0 +1,41 @@ +{ + "name": "unsupervised/schedular", + "description": "WordPress plugin for instructor/student lesson scheduling", + "type": "wordpress-plugin", + "license": "GPL-2.0-or-later", + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.5", + "brain/monkey": "^2.6", + "mockery/mockery": "^1.6", + "phpstan/phpstan": "^1.10", + "szepeviktor/phpstan-wordpress": "^1.3", + "php-stubs/wordpress-stubs": "^6.0", + "squizlabs/php_codesniffer": "^3.7", + "wp-coding-standards/wpcs": "^3.0" + }, + "autoload": { + "psr-4": { + "Unsupervised\\Schedular\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Unsupervised\\Schedular\\Tests\\": "tests/" + } + }, + "scripts": { + "test": "phpunit --configuration phpunit.xml", + "test:coverage": "phpunit --configuration phpunit.xml --coverage-html coverage/", + "lint": "phpstan analyse src/ --level=6 --configuration phpstan.neon", + "cs": "phpcs --standard=WordPress src/", + "cs:fix": "phpcbf --standard=WordPress src/" + }, + "config": { + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + } + } +} diff --git a/docs/features/availability-management.md b/docs/features/availability-management.md new file mode 100644 index 0000000..8d7109b --- /dev/null +++ b/docs/features/availability-management.md @@ -0,0 +1,39 @@ +# Feature: Availability Management + +## Overview +Instructors define date/time windows during which they are available for lessons. Students book from these windows. + +## Data Model — `{prefix}us_availability` + +| Column | Type | Notes | +|----------------|------------------|----------------------------------------------| +| `id` | BIGINT UNSIGNED | Primary key | +| `instructor_id`| BIGINT UNSIGNED | WordPress user ID | +| `start_dt` | DATETIME | Slot start — stored as `Y-m-d H:i:s` | +| `end_dt` | DATETIME | Slot end — stored as `Y-m-d H:i:s` | +| `is_booked` | TINYINT(1) | 0 = available, 1 = booked | +| `created_at` | DATETIME | Insertion time | + +## Admin Interface +Instructors access **My Availability** in wp-admin (`?page=us-availability`). +- Add a slot: provide start and end datetime +- Delete a slot: only allowed if `is_booked = 0` + +## REST API +| Method | Endpoint | Permission | +|----------|-----------------------------------|-------------------------| +| `GET` | `/wp-json/us-scheduler/v1/availability` | `book_lesson` | +| `POST` | `/wp-json/us-scheduler/v1/availability` | `manage_availability` | +| `DELETE` | `/wp-json/us-scheduler/v1/availability/{id}` | `manage_availability` + slot owner | + +`GET` supports query params: `instructor_id`, `from` (datetime), `to` (datetime). + +## Implementation +- Repository: `Unsupervised\Schedular\Data\AvailabilityRepository` +- Model: `Unsupervised\Schedular\Model\AvailabilitySlot` +- Admin controller: `Unsupervised\Schedular\Admin\AvailabilityController` +- REST endpoint: `Unsupervised\Schedular\Api\AvailabilityEndpoint` + +## Tests +- `tests/Unit/Data/AvailabilityRepositoryTest.php` +- `tests/Unit/Model/AvailabilitySlotTest.php` diff --git a/docs/features/lesson-booking.md b/docs/features/lesson-booking.md new file mode 100644 index 0000000..33b4058 --- /dev/null +++ b/docs/features/lesson-booking.md @@ -0,0 +1,52 @@ +# Feature: Lesson Booking + +## Overview +Students browse available slots and submit a booking. Instructors then confirm or cancel from wp-admin or via the REST API. + +## Data Model — `{prefix}us_lessons` + +| Column | Type | Notes | +|----------------|------------------|--------------------------------------------------| +| `id` | BIGINT UNSIGNED | Primary key | +| `slot_id` | BIGINT UNSIGNED | FK → `us_availability.id` | +| `student_id` | BIGINT UNSIGNED | WordPress user ID | +| `instructor_id`| BIGINT UNSIGNED | WordPress user ID (denormalised for fast queries) | +| `status` | VARCHAR(20) | `pending` / `confirmed` / `cancelled` | +| `notes` | TEXT | Optional student notes | +| `created_at` | DATETIME | Insertion time | + +## Booking Flow +1. Student opens the page with `[us_booking]` shortcode. +2. JS fetches `GET /availability` → renders available slots. +3. Student clicks **Book** → `POST /bookings` with `slot_id`. +4. Server creates the lesson row (`status = pending`) and sets `us_availability.is_booked = 1`. +5. Instructor sees the booking under **My Lessons** in wp-admin. +6. Instructor updates status via `PATCH /bookings/{id}/status`. + +## REST API +| Method | Endpoint | Permission | +|-----------|------------------------------------------------|-------------------------------| +| `GET` | `/wp-json/us-scheduler/v1/bookings` | Any logged-in user | +| `POST` | `/wp-json/us-scheduler/v1/bookings` | `book_lesson` | +| `PATCH` | `/wp-json/us-scheduler/v1/bookings/{id}/status`| `manage_availability` or admin | + +`GET /bookings` returns the caller's own lessons (student view) or upcoming lessons for the instructor if the caller has `manage_availability`. + +## Admin Interface +- **Scheduler** (`manage_options` only): all upcoming lessons across all instructors +- **My Lessons** (`view_own_lessons`): upcoming lessons for the logged-in instructor + +## Frontend Shortcodes +- `[us_booking]` — student booking form; requires `book_lesson` capability +- `[us_student_login]` — front-end login form for students + +## Implementation +- Repository: `Unsupervised\Schedular\Data\BookingRepository` +- Model: `Unsupervised\Schedular\Model\Lesson` +- Admin controller: `Unsupervised\Schedular\Admin\LessonController` +- REST endpoint: `Unsupervised\Schedular\Api\BookingEndpoint` +- Frontend: `Unsupervised\Schedular\Frontend\BookingPage`, `LoginPage` + +## Tests +- `tests/Unit/Data/BookingRepositoryTest.php` +- `tests/Unit/Model/LessonTest.php` diff --git a/docs/features/user-roles.md b/docs/features/user-roles.md new file mode 100644 index 0000000..c26d923 --- /dev/null +++ b/docs/features/user-roles.md @@ -0,0 +1,28 @@ +# Feature: User Roles + +## Overview +Two custom WordPress user roles control access to all scheduling features. + +## Roles + +### Instructor (`us_instructor`) +Created on plugin activation. Logs in via standard wp-admin. Can: +- Manage their own availability slots (add/delete) +- View their upcoming confirmed/pending lessons in wp-admin + +**Capabilities:** `read`, `manage_availability`, `view_own_lessons` + +### Student (`us_student`) +Logs in via the front-end `[us_student_login]` shortcode. Can: +- Browse available lesson slots from all instructors +- Book a lesson slot + +**Capabilities:** `read`, `book_lesson`, `view_own_lessons` + +## Implementation +- Class: `Unsupervised\Schedular\Roles\RoleManager` +- Roles are created on `plugins_loaded → init` and on plugin activation via `Installer`. +- Permissions are checked with `current_user_can()` against the capability string, not the role name. + +## Tests +- `tests/Unit/Roles/RoleManagerTest.php` diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..13109ce --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,11 @@ +includes: + - vendor/szepeviktor/phpstan-wordpress/extension.neon + +parameters: + level: 6 + paths: + - src + bootstrapFiles: + - tests/bootstrap.php + ignoreErrors: + - '#Unsafe usage of new static\(\)#' diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..dccdd48 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,22 @@ + + + + + tests/Unit + + + + + + src + + + diff --git a/src/Admin/AdminMenu.php b/src/Admin/AdminMenu.php new file mode 100644 index 0000000..849f8f9 --- /dev/null +++ b/src/Admin/AdminMenu.php @@ -0,0 +1,61 @@ +availabilityController = new AvailabilityController($availability); + $this->lessonController = new LessonController($bookings); + } + + public function register(): void + { + add_action('admin_menu', [$this, 'addPages']); + } + + public function addPages(): void + { + // Admin-only dashboard: all upcoming lessons + add_menu_page( + __('Scheduler', 'unsupervised-schedular'), + __('Scheduler', 'unsupervised-schedular'), + 'manage_options', + 'us-scheduler', + [$this->lessonController, 'renderAdminDashboard'], + 'dashicons-calendar-alt', + 30 + ); + + // Instructor: manage their own availability + add_menu_page( + __('My Availability', 'unsupervised-schedular'), + __('My Availability', 'unsupervised-schedular'), + RoleManager::CAP_MANAGE_AVAILABILITY, + 'us-availability', + [$this->availabilityController, 'renderPage'], + 'dashicons-clock', + 31 + ); + + // Instructor: view their upcoming lessons + add_menu_page( + __('My Lessons', 'unsupervised-schedular'), + __('My Lessons', 'unsupervised-schedular'), + RoleManager::CAP_VIEW_LESSONS, + 'us-my-lessons', + [$this->lessonController, 'renderInstructorLessons'], + 'dashicons-welcome-learn-more', + 32 + ); + } +} diff --git a/src/Admin/AvailabilityController.php b/src/Admin/AvailabilityController.php new file mode 100644 index 0000000..1e3a3a2 --- /dev/null +++ b/src/Admin/AvailabilityController.php @@ -0,0 +1,54 @@ +handleFormAction($instructorId); + } + + $slots = $this->repository->findByInstructor($instructorId); + + include USC_PLUGIN_DIR . 'templates/admin/availability.php'; + } + + private function handleFormAction(int $instructorId): void + { + $action = sanitize_key($_POST['usc_action'] ?? ''); + + if ($action === 'add') { + $startDt = sanitize_text_field($_POST['start_dt'] ?? ''); + $endDt = sanitize_text_field($_POST['end_dt'] ?? ''); + + if ($startDt !== '' && $endDt !== '') { + $this->repository->insert(new AvailabilitySlot($instructorId, $startDt, $endDt)); + } + } + + if ($action === 'delete') { + $slotId = absint($_POST['slot_id'] ?? 0); + if ($slotId > 0) { + $slot = $this->repository->findById($slotId); + if ($slot && $slot->instructorId === $instructorId) { + $this->repository->delete($slotId); + } + } + } + } +} diff --git a/src/Admin/LessonController.php b/src/Admin/LessonController.php new file mode 100644 index 0000000..9a20543 --- /dev/null +++ b/src/Admin/LessonController.php @@ -0,0 +1,34 @@ +repository->findAllUpcoming(); + + include USC_PLUGIN_DIR . 'templates/admin/lessons.php'; + } + + public function renderInstructorLessons(): void + { + if (! current_user_can(RoleManager::CAP_VIEW_LESSONS)) { + wp_die(esc_html__('You do not have permission to view lessons.', 'unsupervised-schedular')); + } + + $lessons = $this->repository->findUpcomingForInstructor(get_current_user_id()); + + include USC_PLUGIN_DIR . 'templates/admin/lessons.php'; + } +} diff --git a/src/Api/AvailabilityEndpoint.php b/src/Api/AvailabilityEndpoint.php new file mode 100644 index 0000000..ef737be --- /dev/null +++ b/src/Api/AvailabilityEndpoint.php @@ -0,0 +1,102 @@ + \WP_REST_Server::READABLE, + 'callback' => [$this, 'index'], + 'permission_callback' => [$this, 'canBook'], + 'args' => [ + 'instructor_id' => ['type' => 'integer', 'default' => 0], + 'from' => ['type' => 'string', 'default' => ''], + 'to' => ['type' => 'string', 'default' => ''], + ], + ], + [ + 'methods' => \WP_REST_Server::CREATABLE, + 'callback' => [$this, 'create'], + 'permission_callback' => [$this, 'canManage'], + 'args' => [ + 'start_dt' => ['type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field'], + 'end_dt' => ['type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field'], + ], + ], + ]); + + register_rest_route($namespace, '/availability/(?P\d+)', [ + [ + 'methods' => \WP_REST_Server::DELETABLE, + 'callback' => [$this, 'delete'], + 'permission_callback' => [$this, 'canManage'], + ], + ]); + } + + public function index(\WP_REST_Request $request): \WP_REST_Response + { + $slots = $this->repository->findAvailable( + (int) $request->get_param('instructor_id'), + (string) $request->get_param('from'), + (string) $request->get_param('to'), + ); + + return new \WP_REST_Response(array_map(fn(AvailabilitySlot $s) => $s->toArray(), $slots), 200); + } + + public function create(\WP_REST_Request $request): \WP_REST_Response + { + $slot = new AvailabilitySlot( + instructorId: get_current_user_id(), + startDt: (string) $request->get_param('start_dt'), + endDt: (string) $request->get_param('end_dt'), + ); + + $id = $this->repository->insert($slot); + + return new \WP_REST_Response(['id' => $id], 201); + } + + public function delete(\WP_REST_Request $request): \WP_REST_Response|\WP_Error + { + $id = absint($request->get_param('id')); + $slot = $this->repository->findById($id); + + if ($slot === null) { + return new \WP_Error('not_found', __('Slot not found.', 'unsupervised-schedular'), ['status' => 404]); + } + + if ($slot->instructorId !== get_current_user_id()) { + return new \WP_Error('forbidden', __('You cannot delete this slot.', 'unsupervised-schedular'), ['status' => 403]); + } + + if ($slot->isBooked) { + return new \WP_Error('slot_booked', __('Cannot delete a booked slot.', 'unsupervised-schedular'), ['status' => 409]); + } + + $this->repository->delete($id); + + return new \WP_REST_Response(null, 204); + } + + public function canBook(): bool + { + return is_user_logged_in() && current_user_can(RoleManager::CAP_BOOK_LESSON); + } + + public function canManage(): bool + { + return is_user_logged_in() && current_user_can(RoleManager::CAP_MANAGE_AVAILABILITY); + } +} diff --git a/src/Api/BookingEndpoint.php b/src/Api/BookingEndpoint.php new file mode 100644 index 0000000..5cd9a04 --- /dev/null +++ b/src/Api/BookingEndpoint.php @@ -0,0 +1,123 @@ + \WP_REST_Server::READABLE, + 'callback' => [$this, 'myLessons'], + 'permission_callback' => [$this, 'isLoggedIn'], + ], + [ + 'methods' => \WP_REST_Server::CREATABLE, + 'callback' => [$this, 'book'], + 'permission_callback' => [$this, 'canBook'], + 'args' => [ + 'slot_id' => ['type' => 'integer', 'required' => true, 'sanitize_callback' => 'absint'], + 'notes' => ['type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_textarea_field'], + ], + ], + ]); + + register_rest_route($namespace, '/bookings/(?P\d+)/status', [ + [ + 'methods' => \WP_REST_Server::EDITABLE, + 'callback' => [$this, 'updateStatus'], + 'permission_callback' => [$this, 'canManage'], + 'args' => [ + 'status' => [ + 'type' => 'string', + 'required' => true, + 'enum' => Lesson::VALID_STATUSES, + ], + ], + ], + ]); + } + + public function myLessons(\WP_REST_Request $request): \WP_REST_Response + { + $userId = get_current_user_id(); + $lessons = current_user_can(RoleManager::CAP_MANAGE_AVAILABILITY) + ? $this->bookings->findUpcomingForInstructor($userId) + : $this->bookings->findByStudent($userId); + + return new \WP_REST_Response(array_map(fn(Lesson $l) => $l->toArray(), $lessons), 200); + } + + public function book(\WP_REST_Request $request): \WP_REST_Response|\WP_Error + { + $slotId = (int) $request->get_param('slot_id'); + $slot = $this->availability->findById($slotId); + + if ($slot === null) { + return new \WP_Error('not_found', __('Slot not found.', 'unsupervised-schedular'), ['status' => 404]); + } + + if ($slot->isBooked) { + return new \WP_Error('slot_taken', __('This slot is already booked.', 'unsupervised-schedular'), ['status' => 409]); + } + + $lesson = new Lesson( + slotId: $slotId, + studentId: get_current_user_id(), + instructorId: $slot->instructorId, + notes: (string) $request->get_param('notes') ?: null, + ); + + $id = $this->bookings->insert($lesson); + $this->availability->markBooked($slotId); + + return new \WP_REST_Response(['id' => $id, 'status' => Lesson::STATUS_PENDING], 201); + } + + public function updateStatus(\WP_REST_Request $request): \WP_REST_Response|\WP_Error + { + $id = absint($request->get_param('id')); + $lesson = $this->bookings->findById($id); + + if ($lesson === null) { + return new \WP_Error('not_found', __('Booking not found.', 'unsupervised-schedular'), ['status' => 404]); + } + + if ($lesson->instructorId !== get_current_user_id() && ! current_user_can('manage_options')) { + return new \WP_Error('forbidden', __('You cannot update this booking.', 'unsupervised-schedular'), ['status' => 403]); + } + + $this->bookings->updateStatus($id, (string) $request->get_param('status')); + + return new \WP_REST_Response(['id' => $id, 'status' => $request->get_param('status')], 200); + } + + public function isLoggedIn(): bool + { + return is_user_logged_in(); + } + + public function canBook(): bool + { + return is_user_logged_in() && current_user_can(RoleManager::CAP_BOOK_LESSON); + } + + public function canManage(): bool + { + return is_user_logged_in() && ( + current_user_can(RoleManager::CAP_MANAGE_AVAILABILITY) || current_user_can('manage_options') + ); + } +} diff --git a/src/Api/RestRegistrar.php b/src/Api/RestRegistrar.php new file mode 100644 index 0000000..ea1d39e --- /dev/null +++ b/src/Api/RestRegistrar.php @@ -0,0 +1,32 @@ +availabilityEndpoint = new AvailabilityEndpoint($availability); + $this->bookingEndpoint = new BookingEndpoint($availability, $bookings); + } + + public function register(): void + { + add_action('rest_api_init', [$this, 'registerRoutes']); + } + + public function registerRoutes(): void + { + $this->availabilityEndpoint->registerRoutes(self::NAMESPACE); + $this->bookingEndpoint->registerRoutes(self::NAMESPACE); + } +} diff --git a/src/Data/AvailabilityRepository.php b/src/Data/AvailabilityRepository.php new file mode 100644 index 0000000..3f45bd2 --- /dev/null +++ b/src/Data/AvailabilityRepository.php @@ -0,0 +1,117 @@ +table = $db->prefix . 'us_availability'; + } + + public function insert(AvailabilitySlot $slot): int + { + $this->db->insert( + $this->table, + [ + 'instructor_id' => $slot->instructorId, + 'start_dt' => $slot->startDt, + 'end_dt' => $slot->endDt, + 'is_booked' => 0, + 'created_at' => current_time('mysql'), + ], + ['%d', '%s', '%s', '%d', '%s'] + ); + + return $this->db->insert_id; + } + + /** + * Find unbooked slots, optionally filtered by instructor and date range. + * + * @return list + */ + public function findAvailable(int $instructorId = 0, string $from = '', string $to = ''): array + { + $where = ['is_booked = 0']; + $params = []; + + if ($instructorId > 0) { + $where[] = 'instructor_id = %d'; + $params[] = $instructorId; + } + + if ($from !== '') { + $where[] = 'start_dt >= %s'; + $params[] = $from; + } + + if ($to !== '') { + $where[] = 'end_dt <= %s'; + $params[] = $to; + } + + $whereClause = implode(' AND ', $where); + $sql = "SELECT * FROM {$this->table} WHERE {$whereClause} ORDER BY start_dt ASC"; + + $rows = $params + ? $this->db->get_results($this->db->prepare($sql, $params)) + : $this->db->get_results($sql); + + return array_map(AvailabilitySlot::fromRow(...), $rows ?? []); + } + + /** + * Find all slots for an instructor (booked and unbooked). + * + * @return list + */ + public function findByInstructor(int $instructorId): array + { + $rows = $this->db->get_results( + $this->db->prepare( + "SELECT * FROM {$this->table} WHERE instructor_id = %d ORDER BY start_dt ASC", + $instructorId + ) + ); + + return array_map(AvailabilitySlot::fromRow(...), $rows ?? []); + } + + public function findById(int $id): ?AvailabilitySlot + { + $row = $this->db->get_row( + $this->db->prepare("SELECT * FROM {$this->table} WHERE id = %d", $id) + ); + + return $row ? AvailabilitySlot::fromRow($row) : null; + } + + public function markBooked(int $id): bool + { + return (bool) $this->db->update( + $this->table, + ['is_booked' => 1], + ['id' => $id], + ['%d'], + ['%d'] + ); + } + + /** + * Delete an unbooked slot. Returns false if the slot is already booked. + */ + public function delete(int $id): bool + { + return (bool) $this->db->delete( + $this->table, + ['id' => $id, 'is_booked' => 0], + ['%d', '%d'] + ); + } +} diff --git a/src/Data/BookingRepository.php b/src/Data/BookingRepository.php new file mode 100644 index 0000000..57b4dda --- /dev/null +++ b/src/Data/BookingRepository.php @@ -0,0 +1,125 @@ +table = $db->prefix . 'us_lessons'; + } + + public function insert(Lesson $lesson): int + { + $this->db->insert( + $this->table, + [ + 'slot_id' => $lesson->slotId, + 'student_id' => $lesson->studentId, + 'instructor_id' => $lesson->instructorId, + 'status' => $lesson->status, + 'notes' => $lesson->notes, + 'created_at' => current_time('mysql'), + ], + ['%d', '%d', '%d', '%s', '%s', '%s'] + ); + + return $this->db->insert_id; + } + + public function findById(int $id): ?Lesson + { + $row = $this->db->get_row( + $this->db->prepare("SELECT * FROM {$this->table} WHERE id = %d", $id) + ); + + return $row ? Lesson::fromRow($row) : null; + } + + /** + * Upcoming lessons for an instructor (status != cancelled, slot in the future). + * + * @return list + */ + public function findUpcomingForInstructor(int $instructorId): array + { + $avTable = str_replace('us_lessons', 'us_availability', $this->table); + + $rows = $this->db->get_results( + $this->db->prepare( + "SELECT l.* FROM {$this->table} l + JOIN {$avTable} a ON a.id = l.slot_id + WHERE l.instructor_id = %d + AND l.status != %s + AND a.start_dt >= %s + ORDER BY a.start_dt ASC", + $instructorId, + Lesson::STATUS_CANCELLED, + current_time('mysql') + ) + ); + + return array_map(Lesson::fromRow(...), $rows ?? []); + } + + /** + * All lessons for a student. + * + * @return list + */ + public function findByStudent(int $studentId): array + { + $rows = $this->db->get_results( + $this->db->prepare( + "SELECT * FROM {$this->table} WHERE student_id = %d ORDER BY created_at DESC", + $studentId + ) + ); + + return array_map(Lesson::fromRow(...), $rows ?? []); + } + + /** + * All upcoming lessons across all instructors (admin view). + * + * @return list + */ + public function findAllUpcoming(): array + { + $avTable = str_replace('us_lessons', 'us_availability', $this->table); + + $rows = $this->db->get_results( + $this->db->prepare( + "SELECT l.* FROM {$this->table} l + JOIN {$avTable} a ON a.id = l.slot_id + WHERE l.status != %s + AND a.start_dt >= %s + ORDER BY a.start_dt ASC", + Lesson::STATUS_CANCELLED, + current_time('mysql') + ) + ); + + return array_map(Lesson::fromRow(...), $rows ?? []); + } + + public function updateStatus(int $id, string $status): bool + { + if (! in_array($status, Lesson::VALID_STATUSES, true)) { + return false; + } + + return (bool) $this->db->update( + $this->table, + ['status' => $status], + ['id' => $id], + ['%s'], + ['%d'] + ); + } +} diff --git a/src/Data/Schema.php b/src/Data/Schema.php new file mode 100644 index 0000000..2536467 --- /dev/null +++ b/src/Data/Schema.php @@ -0,0 +1,43 @@ + + */ + public static function tables(string $prefix, string $charset): array + { + return [ + "CREATE TABLE {$prefix}us_availability ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + instructor_id BIGINT UNSIGNED NOT NULL, + start_dt DATETIME NOT NULL, + end_dt DATETIME NOT NULL, + is_booked TINYINT(1) NOT NULL DEFAULT 0, + created_at DATETIME NOT NULL, + PRIMARY KEY (id), + KEY instructor_id (instructor_id), + KEY start_dt (start_dt) + ) {$charset};", + + "CREATE TABLE {$prefix}us_lessons ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + slot_id BIGINT UNSIGNED NOT NULL, + student_id BIGINT UNSIGNED NOT NULL, + instructor_id BIGINT UNSIGNED NOT NULL, + status VARCHAR(20) NOT NULL DEFAULT 'pending', + notes TEXT, + created_at DATETIME NOT NULL, + PRIMARY KEY (id), + KEY slot_id (slot_id), + KEY student_id (student_id), + KEY instructor_id (instructor_id) + ) {$charset};", + ]; + } +} diff --git a/src/Frontend/BookingPage.php b/src/Frontend/BookingPage.php new file mode 100644 index 0000000..66a6326 --- /dev/null +++ b/src/Frontend/BookingPage.php @@ -0,0 +1,39 @@ +%s %s.

', + esc_html__('Please', 'unsupervised-schedular'), + esc_url(wp_login_url(get_permalink())), + esc_html__('log in to book a lesson', 'unsupervised-schedular') + ); + } + + if (! current_user_can(RoleManager::CAP_BOOK_LESSON)) { + return '

' . esc_html__('This page is for students only.', 'unsupervised-schedular') . '

'; + } + + wp_enqueue_style('us-scheduler'); + wp_enqueue_script('us-scheduler'); + + ob_start(); + include USC_PLUGIN_DIR . 'templates/frontend/booking-page.php'; + return (string) ob_get_clean(); + } +} diff --git a/src/Frontend/LoginPage.php b/src/Frontend/LoginPage.php new file mode 100644 index 0000000..b898686 --- /dev/null +++ b/src/Frontend/LoginPage.php @@ -0,0 +1,44 @@ +%s %s.

', + esc_html__('You are already logged in.', 'unsupervised-schedular'), + $redirect, + esc_html__('View available lessons', 'unsupervised-schedular') + ); + } + + $error = ''; + $redirect = sanitize_url(get_permalink() ?? ''); + + if (isset($_POST['us_login']) && check_admin_referer('us_student_login')) { + $credentials = [ + 'user_login' => sanitize_user($_POST['log'] ?? ''), + 'user_password' => $_POST['pwd'] ?? '', + 'remember' => isset($_POST['rememberme']), + ]; + + $user = wp_signon($credentials, false); + + if (is_wp_error($user)) { + $error = esc_html__('Invalid username or password.', 'unsupervised-schedular'); + } else { + wp_safe_redirect($redirect); + exit; + } + } + + ob_start(); + include USC_PLUGIN_DIR . 'templates/frontend/login-page.php'; + return (string) ob_get_clean(); + } +} diff --git a/src/Frontend/ShortcodeRegistrar.php b/src/Frontend/ShortcodeRegistrar.php new file mode 100644 index 0000000..789f16f --- /dev/null +++ b/src/Frontend/ShortcodeRegistrar.php @@ -0,0 +1,37 @@ +bookingPage = new BookingPage($availability, $bookings); + $this->loginPage = new LoginPage(); + } + + public function register(): void + { + add_shortcode('us_booking', [$this->bookingPage, 'render']); + add_shortcode('us_student_login', [$this->loginPage, 'render']); + add_action('wp_enqueue_scripts', [$this, 'enqueueAssets']); + } + + public function enqueueAssets(): void + { + wp_register_style('us-scheduler', USC_PLUGIN_URL . 'assets/css/frontend.css', [], USC_VERSION); + wp_register_script('us-scheduler', USC_PLUGIN_URL . 'assets/js/booking.js', [], USC_VERSION, true); + + wp_localize_script('us-scheduler', 'usScheduler', [ + 'restUrl' => rest_url('us-scheduler/v1/'), + 'nonce' => wp_create_nonce('wp_rest'), + ]); + } +} diff --git a/src/Installer.php b/src/Installer.php new file mode 100644 index 0000000..b83bc97 --- /dev/null +++ b/src/Installer.php @@ -0,0 +1,30 @@ +createTables(); + (new RoleManager())->createRoles(); + flush_rewrite_rules(); + update_option('us_schedular_version', USC_VERSION); + } + + private function createTables(): void + { + global $wpdb; + $charset = $wpdb->get_charset_collate(); + + require_once ABSPATH . 'wp-admin/includes/upgrade.php'; + + foreach (Schema::tables($wpdb->prefix, $charset) as $sql) { + dbDelta($sql); + } + } +} diff --git a/src/Model/AvailabilitySlot.php b/src/Model/AvailabilitySlot.php new file mode 100644 index 0000000..991eb6f --- /dev/null +++ b/src/Model/AvailabilitySlot.php @@ -0,0 +1,37 @@ +instructor_id, + startDt: $row->start_dt, + endDt: $row->end_dt, + isBooked: (bool) $row->is_booked, + id: (int) $row->id, + ); + } + + public function toArray(): array + { + return [ + 'id' => $this->id, + 'instructor_id' => $this->instructorId, + 'start_dt' => $this->startDt, + 'end_dt' => $this->endDt, + 'is_booked' => $this->isBooked, + ]; + } +} diff --git a/src/Model/Lesson.php b/src/Model/Lesson.php new file mode 100644 index 0000000..e71716a --- /dev/null +++ b/src/Model/Lesson.php @@ -0,0 +1,47 @@ + */ + public const VALID_STATUSES = [self::STATUS_PENDING, self::STATUS_CONFIRMED, self::STATUS_CANCELLED]; + + public function __construct( + public readonly int $slotId, + public readonly int $studentId, + public readonly int $instructorId, + public readonly string $status = self::STATUS_PENDING, + public readonly ?string $notes = null, + public readonly ?int $id = null, + ) {} + + public static function fromRow(object $row): self + { + return new self( + slotId: (int) $row->slot_id, + studentId: (int) $row->student_id, + instructorId: (int) $row->instructor_id, + status: $row->status, + notes: $row->notes, + id: (int) $row->id, + ); + } + + public function toArray(): array + { + return [ + 'id' => $this->id, + 'slot_id' => $this->slotId, + 'student_id' => $this->studentId, + 'instructor_id' => $this->instructorId, + 'status' => $this->status, + 'notes' => $this->notes, + ]; + } +} diff --git a/src/Plugin.php b/src/Plugin.php new file mode 100644 index 0000000..2f429c6 --- /dev/null +++ b/src/Plugin.php @@ -0,0 +1,28 @@ +register(); + (new AdminMenu($availability, $bookings))->register(); + (new RestRegistrar($availability, $bookings))->register(); + (new ShortcodeRegistrar($availability, $bookings))->register(); + } +} diff --git a/src/Roles/RoleManager.php b/src/Roles/RoleManager.php new file mode 100644 index 0000000..0d8710c --- /dev/null +++ b/src/Roles/RoleManager.php @@ -0,0 +1,46 @@ + true, + self::CAP_MANAGE_AVAILABILITY => true, + self::CAP_VIEW_LESSONS => true, + ] + ); + } + + if (get_role(self::STUDENT) === null) { + add_role( + self::STUDENT, + __('Student', 'unsupervised-schedular'), + [ + 'read' => true, + self::CAP_BOOK_LESSON => true, + self::CAP_VIEW_LESSONS => true, + ] + ); + } + } +} diff --git a/templates/admin/availability.php b/templates/admin/availability.php new file mode 100644 index 0000000..9686dc2 --- /dev/null +++ b/templates/admin/availability.php @@ -0,0 +1,67 @@ + $slots */ +?> +
+

+ +

+
+ + + + + + + + + + + +
+ +
+ +

+ + +

+ + + + + + + + + + + + + + + + + + + + +
startDt); ?>endDt); ?>isBooked ? esc_html__('Booked', 'unsupervised-schedular') : esc_html__('Available', 'unsupervised-schedular'); ?> + isBooked) : ?> +
+ + + + +
+ +
+ +
diff --git a/templates/admin/lessons.php b/templates/admin/lessons.php new file mode 100644 index 0000000..6b1ecf6 --- /dev/null +++ b/templates/admin/lessons.php @@ -0,0 +1,43 @@ + $lessons */ +?> +
+

+ + +

+ + + + + + + + + + + + + + studentId); + $instructor = get_userdata($lesson->instructorId); + ?> + + + + + + + + + +
display_name : (string) $lesson->studentId); ?>display_name : (string) $lesson->instructorId); ?>slotId); ?>status); ?>notes ?? ''); ?>
+ +
diff --git a/templates/frontend/booking-page.php b/templates/frontend/booking-page.php new file mode 100644 index 0000000..1b2fc70 --- /dev/null +++ b/templates/frontend/booking-page.php @@ -0,0 +1,16 @@ + +
+
+

+
+ + +
diff --git a/templates/frontend/login-page.php b/templates/frontend/login-page.php new file mode 100644 index 0000000..6ef5f56 --- /dev/null +++ b/templates/frontend/login-page.php @@ -0,0 +1,37 @@ + + diff --git a/tests/Unit/Data/AvailabilityRepositoryTest.php b/tests/Unit/Data/AvailabilityRepositoryTest.php new file mode 100644 index 0000000..8857f3c --- /dev/null +++ b/tests/Unit/Data/AvailabilityRepositoryTest.php @@ -0,0 +1,149 @@ +db = Mockery::mock(\wpdb::class); + $this->db->prefix = 'wp_'; + $this->repo = new AvailabilityRepository($this->db); + } + + public function testInsertCallsWpdbInsertAndReturnsId(): void + { + Functions\expect('current_time')->with('mysql')->andReturn('2026-04-01 12:00:00'); + + $this->db->shouldReceive('insert') + ->once() + ->with( + 'wp_us_availability', + Mockery::on(static function (array $data): bool { + return $data['instructor_id'] === 5 + && $data['start_dt'] === '2026-04-01 09:00:00' + && $data['is_booked'] === 0; + }), + ['%d', '%s', '%s', '%d', '%s'] + ); + + $this->db->insert_id = 42; + + $slot = new AvailabilitySlot(5, '2026-04-01 09:00:00', '2026-04-01 10:00:00'); + $result = $this->repo->insert($slot); + + self::assertSame(42, $result); + } + + public function testFindByIdReturnsNullWhenNotFound(): void + { + $this->db->shouldReceive('prepare') + ->once() + ->andReturn('SELECT * FROM wp_us_availability WHERE id = 99'); + + $this->db->shouldReceive('get_row') + ->once() + ->andReturn(null); + + $result = $this->repo->findById(99); + + self::assertNull($result); + } + + public function testFindByIdReturnsSlotWhenFound(): void + { + $row = (object) [ + 'id' => '10', + 'instructor_id' => '5', + 'start_dt' => '2026-04-01 09:00:00', + 'end_dt' => '2026-04-01 10:00:00', + 'is_booked' => '0', + ]; + + $this->db->shouldReceive('prepare')->andReturn('SELECT ...'); + $this->db->shouldReceive('get_row')->andReturn($row); + + $slot = $this->repo->findById(10); + + self::assertInstanceOf(AvailabilitySlot::class, $slot); + self::assertSame(10, $slot->id); + self::assertSame(5, $slot->instructorId); + } + + public function testMarkBookedUpdatesRecord(): void + { + $this->db->shouldReceive('update') + ->once() + ->with('wp_us_availability', ['is_booked' => 1], ['id' => 7], ['%d'], ['%d']) + ->andReturn(1); + + $result = $this->repo->markBooked(7); + + self::assertTrue($result); + } + + public function testDeleteReturnsFalseWhenRowNotDeleted(): void + { + $this->db->shouldReceive('delete') + ->once() + ->with('wp_us_availability', ['id' => 1, 'is_booked' => 0], ['%d', '%d']) + ->andReturn(0); + + self::assertFalse($this->repo->delete(1)); + } + + public function testFindAvailableWithNoFiltersUsesNoParams(): void + { + $this->db->shouldReceive('get_results') + ->once() + ->with(Mockery::pattern('/WHERE is_booked = 0/')) + ->andReturn([]); + + $result = $this->repo->findAvailable(); + + self::assertSame([], $result); + } + + public function testFindAvailableWithInstructorFilterPreparesQuery(): void + { + $this->db->shouldReceive('prepare') + ->once() + ->with(Mockery::pattern('/instructor_id = %d/'), Mockery::any()) + ->andReturn('SELECT ...'); + + $this->db->shouldReceive('get_results')->andReturn([]); + + $this->repo->findAvailable(instructorId: 3); + } + + public function testFindByInstructorReturnsSlots(): void + { + $row = (object) [ + 'id' => '5', + 'instructor_id' => '3', + 'start_dt' => '2026-04-01 09:00:00', + 'end_dt' => '2026-04-01 10:00:00', + 'is_booked' => '0', + ]; + + $this->db->shouldReceive('prepare')->andReturn('SELECT ...'); + $this->db->shouldReceive('get_results')->andReturn([$row]); + + $slots = $this->repo->findByInstructor(3); + + self::assertCount(1, $slots); + self::assertInstanceOf(AvailabilitySlot::class, $slots[0]); + } +} diff --git a/tests/Unit/Data/BookingRepositoryTest.php b/tests/Unit/Data/BookingRepositoryTest.php new file mode 100644 index 0000000..963ddd2 --- /dev/null +++ b/tests/Unit/Data/BookingRepositoryTest.php @@ -0,0 +1,126 @@ +db = Mockery::mock(\wpdb::class); + $this->db->prefix = 'wp_'; + $this->repo = new BookingRepository($this->db); + } + + public function testInsertCallsWpdbInsertAndReturnsId(): void + { + Functions\expect('current_time')->with('mysql')->andReturn('2026-04-01 12:00:00'); + + $this->db->shouldReceive('insert') + ->once() + ->with( + 'wp_us_lessons', + Mockery::on(static function (array $data): bool { + return $data['slot_id'] === 10 + && $data['student_id'] === 5 + && $data['status'] === Lesson::STATUS_PENDING; + }), + ['%d', '%d', '%d', '%s', '%s', '%s'] + ); + + $this->db->insert_id = 77; + + $lesson = new Lesson(slotId: 10, studentId: 5, instructorId: 3); + $result = $this->repo->insert($lesson); + + self::assertSame(77, $result); + } + + public function testFindByIdReturnsNullWhenNotFound(): void + { + $this->db->shouldReceive('prepare')->andReturn('SELECT ...'); + $this->db->shouldReceive('get_row')->andReturn(null); + + self::assertNull($this->repo->findById(99)); + } + + public function testFindByIdReturnsLesson(): void + { + $row = (object) [ + 'id' => '15', + 'slot_id' => '10', + 'student_id' => '5', + 'instructor_id' => '3', + 'status' => 'pending', + 'notes' => null, + ]; + + $this->db->shouldReceive('prepare')->andReturn('SELECT ...'); + $this->db->shouldReceive('get_row')->andReturn($row); + + $lesson = $this->repo->findById(15); + + self::assertInstanceOf(Lesson::class, $lesson); + self::assertSame(15, $lesson->id); + } + + public function testUpdateStatusReturnsFalseForInvalidStatus(): void + { + $result = $this->repo->updateStatus(1, 'invalid'); + self::assertFalse($result); + } + + public function testUpdateStatusCallsWpdbUpdate(): void + { + $this->db->shouldReceive('update') + ->once() + ->with( + 'wp_us_lessons', + ['status' => Lesson::STATUS_CONFIRMED], + ['id' => 1], + ['%s'], + ['%d'] + ) + ->andReturn(1); + + self::assertTrue($this->repo->updateStatus(1, Lesson::STATUS_CONFIRMED)); + } + + public function testUpdateStatusReturnsFalseWhenDbFails(): void + { + $this->db->shouldReceive('update')->andReturn(0); + + self::assertFalse($this->repo->updateStatus(1, Lesson::STATUS_CONFIRMED)); + } + + public function testFindByStudentReturnsLessons(): void + { + $row = (object) [ + 'id' => '1', + 'slot_id' => '2', + 'student_id' => '5', + 'instructor_id' => '3', + 'status' => 'pending', + 'notes' => null, + ]; + + $this->db->shouldReceive('prepare')->andReturn('SELECT ...'); + $this->db->shouldReceive('get_results')->andReturn([$row]); + + $lessons = $this->repo->findByStudent(5); + + self::assertCount(1, $lessons); + self::assertInstanceOf(Lesson::class, $lessons[0]); + } +} diff --git a/tests/Unit/Model/AvailabilitySlotTest.php b/tests/Unit/Model/AvailabilitySlotTest.php new file mode 100644 index 0000000..441fae9 --- /dev/null +++ b/tests/Unit/Model/AvailabilitySlotTest.php @@ -0,0 +1,68 @@ +instructorId); + self::assertSame('2026-04-01 09:00:00', $slot->startDt); + self::assertSame('2026-04-01 10:00:00', $slot->endDt); + self::assertFalse($slot->isBooked); + self::assertSame(42, $slot->id); + } + + public function testFromRowMapsCorrectly(): void + { + $row = (object) [ + 'id' => '7', + 'instructor_id' => '3', + 'start_dt' => '2026-05-10 14:00:00', + 'end_dt' => '2026-05-10 15:00:00', + 'is_booked' => '1', + ]; + + $slot = AvailabilitySlot::fromRow($row); + + self::assertSame(7, $slot->id); + self::assertSame(3, $slot->instructorId); + self::assertTrue($slot->isBooked); + } + + public function testToArrayContainsExpectedKeys(): void + { + $slot = new AvailabilitySlot(1, '2026-04-01 09:00:00', '2026-04-01 10:00:00', false, 10); + $arr = $slot->toArray(); + + self::assertArrayHasKey('id', $arr); + self::assertArrayHasKey('instructor_id', $arr); + self::assertArrayHasKey('start_dt', $arr); + self::assertArrayHasKey('end_dt', $arr); + self::assertArrayHasKey('is_booked', $arr); + } + + public function testDefaultIsBookedIsFalse(): void + { + $slot = new AvailabilitySlot(1, '2026-04-01 09:00:00', '2026-04-01 10:00:00'); + self::assertFalse($slot->isBooked); + } + + public function testDefaultIdIsNull(): void + { + $slot = new AvailabilitySlot(1, '2026-04-01 09:00:00', '2026-04-01 10:00:00'); + self::assertNull($slot->id); + } +} diff --git a/tests/Unit/Model/LessonTest.php b/tests/Unit/Model/LessonTest.php new file mode 100644 index 0000000..439c9be --- /dev/null +++ b/tests/Unit/Model/LessonTest.php @@ -0,0 +1,68 @@ +status); + self::assertNull($lesson->notes); + self::assertNull($lesson->id); + } + + public function testFromRowMapsCorrectly(): void + { + $row = (object) [ + 'id' => '99', + 'slot_id' => '10', + 'student_id' => '20', + 'instructor_id' => '30', + 'status' => 'confirmed', + 'notes' => 'Bring your guitar.', + ]; + + $lesson = Lesson::fromRow($row); + + self::assertSame(99, $lesson->id); + self::assertSame(10, $lesson->slotId); + self::assertSame(20, $lesson->studentId); + self::assertSame(30, $lesson->instructorId); + self::assertSame('confirmed', $lesson->status); + self::assertSame('Bring your guitar.', $lesson->notes); + } + + public function testToArrayContainsExpectedKeys(): void + { + $lesson = new Lesson(1, 2, 3, Lesson::STATUS_PENDING, 'Note', 5); + $arr = $lesson->toArray(); + + self::assertArrayHasKey('id', $arr); + self::assertArrayHasKey('slot_id', $arr); + self::assertArrayHasKey('student_id', $arr); + self::assertArrayHasKey('instructor_id', $arr); + self::assertArrayHasKey('status', $arr); + self::assertArrayHasKey('notes', $arr); + } +} diff --git a/tests/Unit/Roles/RoleManagerTest.php b/tests/Unit/Roles/RoleManagerTest.php new file mode 100644 index 0000000..0cabd0b --- /dev/null +++ b/tests/Unit/Roles/RoleManagerTest.php @@ -0,0 +1,70 @@ +once() + ->with('init', \Mockery::any()); + + (new RoleManager())->register(); + } + + public function testCreateRolesSkipsExistingRoles(): void + { + Functions\when('get_role')->alias(static fn() => new \stdClass()); + Functions\expect('add_role')->never(); + + (new RoleManager())->createRoles(); + } + + public function testCreateRolesAddsInstructorRoleWithCorrectCaps(): void + { + Functions\when('get_role')->alias(static function (string $role): ?object { + return $role === RoleManager::INSTRUCTOR ? null : new \stdClass(); + }); + + Functions\expect('add_role') + ->once() + ->with( + RoleManager::INSTRUCTOR, + \Mockery::any(), + \Mockery::on(static function (array $caps): bool { + return ($caps['read'] ?? false) === true + && ($caps[RoleManager::CAP_MANAGE_AVAILABILITY] ?? false) === true + && ($caps[RoleManager::CAP_VIEW_LESSONS] ?? false) === true; + }) + ); + + (new RoleManager())->createRoles(); + } + + public function testCreateRolesAddsStudentRoleWithCorrectCaps(): void + { + Functions\when('get_role')->alias(static function (string $role): ?object { + return $role === RoleManager::STUDENT ? null : new \stdClass(); + }); + + Functions\expect('add_role') + ->once() + ->with( + RoleManager::STUDENT, + \Mockery::any(), + \Mockery::on(static function (array $caps): bool { + return ($caps['read'] ?? false) === true + && ($caps[RoleManager::CAP_BOOK_LESSON] ?? false) === true + && ($caps[RoleManager::CAP_VIEW_LESSONS] ?? false) === true; + }) + ); + + (new RoleManager())->createRoles(); + } +} diff --git a/tests/Unit/TestCase.php b/tests/Unit/TestCase.php new file mode 100644 index 0000000..3a75e02 --- /dev/null +++ b/tests/Unit/TestCase.php @@ -0,0 +1,27 @@ +query("DROP TABLE IF EXISTS {$wpdb->prefix}us_lessons"); +$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}us_availability"); + +remove_role('us_instructor'); +remove_role('us_student'); + +delete_option('us_schedular_version'); diff --git a/unsupervised-schedular.php b/unsupervised-schedular.php new file mode 100644 index 0000000..5e57b5e --- /dev/null +++ b/unsupervised-schedular.php @@ -0,0 +1,41 @@ +prefix . 'us_availability'); +define('USC_TABLE_LESSONS', $GLOBALS['wpdb']->prefix . 'us_lessons'); + +require_once USC_PLUGIN_DIR . 'vendor/autoload.php'; + +register_activation_hook(__FILE__, static function (): void { + (new Installer())->run(); +}); + +register_deactivation_hook(__FILE__, static function (): void { + flush_rewrite_rules(); +}); + +add_action('plugins_loaded', static function (): void { + Plugin::boot(); +});