diff --git a/composer.json b/composer.json index 9ab98c2..6611d02 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ "scripts": { "test": "phpunit --configuration phpunit.xml", "test:coverage": "phpunit --configuration phpunit.xml --coverage-html coverage/", - "lint": "phpstan analyse src/ --level=6 --configuration phpstan.neon", + "lint": "phpstan analyse src/ --level=6 --configuration phpstan.neon --memory-limit=1G", "cs": "phpcs --standard=phpcs.xml.dist", "cs:fix": "phpcbf --standard=phpcs.xml.dist", "build": "bash bin/build-zip.sh" diff --git a/docs/features/policies.md b/docs/features/policies.md index a75d084..8602e1d 100644 --- a/docs/features/policies.md +++ b/docs/features/policies.md @@ -63,10 +63,13 @@ cover every policy's current version or the registration is rejected. ## Implementation - Repositories: `Unsupervised\Schedular\Policy\PolicyRepository`, `Unsupervised\Schedular\Policy\PolicyVersionRepository`, `Unsupervised\Schedular\Policy\AcceptanceRepository` - Models: `Unsupervised\Schedular\Policy\Policy`, `Unsupervised\Schedular\Policy\PolicyVersion`, `Unsupervised\Schedular\Policy\PolicyAcceptance` +- Service: `Unsupervised\Schedular\Policy\PolicyService` — orchestrates create / add-draft / publish across the policies and versions tables (archive prior current version, stamp `published_at`, repoint `current_version_id`) - Admin controller: `Unsupervised\Schedular\Policy\PolicyController` - REST endpoint: `Unsupervised\Schedular\Policy\PolicyEndpoint` ## Tests +- `tests/Unit/Policy/PolicyValueObjectsTest.php` - `tests/Unit/Policy/PolicyRepositoryTest.php` - `tests/Unit/Policy/PolicyVersionRepositoryTest.php` - `tests/Unit/Policy/AcceptanceRepositoryTest.php` +- `tests/Unit/Policy/PolicyServiceTest.php` diff --git a/src/AdminMenu.php b/src/AdminMenu.php index 61bccf0..d7ea139 100644 --- a/src/AdminMenu.php +++ b/src/AdminMenu.php @@ -10,6 +10,10 @@ use Unsupervised\Schedular\Booking\BookingRepository; use Unsupervised\Schedular\Booking\LessonController; use Unsupervised\Schedular\Offering\OfferingController; use Unsupervised\Schedular\Offering\OfferingRepository; +use Unsupervised\Schedular\Policy\PolicyController; +use Unsupervised\Schedular\Policy\PolicyRepository; +use Unsupervised\Schedular\Policy\PolicyService; +use Unsupervised\Schedular\Policy\PolicyVersionRepository; use Unsupervised\Schedular\Registration\QuestionController; use Unsupervised\Schedular\Registration\QuestionRepository; @@ -19,12 +23,14 @@ class AdminMenu { private LessonController $lessonController; private OfferingController $offeringController; private QuestionController $questionController; + private PolicyController $policyController; - public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings, QuestionRepository $questions ) { + public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings, QuestionRepository $questions, PolicyRepository $policies, PolicyVersionRepository $policyVersions, PolicyService $policyService ) { $this->availabilityController = new AvailabilityController( $availability ); $this->lessonController = new LessonController( $bookings ); $this->offeringController = new OfferingController( $offerings ); $this->questionController = new QuestionController( $questions, $offerings ); + $this->policyController = new PolicyController( $policies, $policyVersions, $policyService ); } public function register(): void { @@ -75,6 +81,17 @@ class AdminMenu { [ $this->questionController, 'renderPage' ] ); + // Studio admin: draft, version, and publish policies. + add_menu_page( + __( 'Policies', 'unsupervised-schedular' ), + __( 'Policies', 'unsupervised-schedular' ), + RoleManager::CAP_MANAGE_POLICIES, + 'us-policies', + [ $this->policyController, 'renderPage' ], + 'dashicons-text-page', + 34 + ); + // Instructor: view their upcoming lessons. add_menu_page( __( 'My Lessons', 'unsupervised-schedular' ), diff --git a/src/Plugin.php b/src/Plugin.php index 0339d39..7737506 100644 --- a/src/Plugin.php +++ b/src/Plugin.php @@ -7,6 +7,9 @@ use Unsupervised\Schedular\Auth\RoleManager; use Unsupervised\Schedular\Availability\AvailabilityRepository; use Unsupervised\Schedular\Booking\BookingRepository; use Unsupervised\Schedular\Offering\OfferingRepository; +use Unsupervised\Schedular\Policy\PolicyRepository; +use Unsupervised\Schedular\Policy\PolicyService; +use Unsupervised\Schedular\Policy\PolicyVersionRepository; use Unsupervised\Schedular\Registration\QuestionRepository; class Plugin { @@ -15,14 +18,17 @@ class Plugin { load_plugin_textdomain( 'unsupervised-schedular', false, dirname( plugin_basename( USC_PLUGIN_FILE ) ) . '/languages' ); global $wpdb; - $availability = new AvailabilityRepository( $wpdb ); - $bookings = new BookingRepository( $wpdb ); - $offerings = new OfferingRepository( $wpdb ); - $questions = new QuestionRepository( $wpdb ); + $availability = new AvailabilityRepository( $wpdb ); + $bookings = new BookingRepository( $wpdb ); + $offerings = new OfferingRepository( $wpdb ); + $questions = new QuestionRepository( $wpdb ); + $policies = new PolicyRepository( $wpdb ); + $policyVersions = new PolicyVersionRepository( $wpdb ); + $policyService = new PolicyService( $policies, $policyVersions ); ( new RoleManager() )->register(); - ( new AdminMenu( $availability, $bookings, $offerings, $questions ) )->register(); - ( new RestRegistrar( $availability, $bookings, $offerings, $questions ) )->register(); + ( new AdminMenu( $availability, $bookings, $offerings, $questions, $policies, $policyVersions, $policyService ) )->register(); + ( new RestRegistrar( $availability, $bookings, $offerings, $questions, $policies, $policyVersions, $policyService ) )->register(); ( new ShortcodeRegistrar() )->register(); } } diff --git a/src/Policy/AcceptanceRepository.php b/src/Policy/AcceptanceRepository.php new file mode 100644 index 0000000..a1f51e4 --- /dev/null +++ b/src/Policy/AcceptanceRepository.php @@ -0,0 +1,57 @@ +table = $db->prefix . 'us_policy_acceptances'; + } + + public function insert( PolicyAcceptance $acceptance ): int { + $this->db->insert( + $this->table, + [ + 'policy_version_id' => $acceptance->policyVersionId, + 'student_id' => $acceptance->studentId, + 'registration_type' => $acceptance->registrationType, + 'registration_id' => $acceptance->registrationId, + 'ip_address' => $acceptance->ipAddress, + 'accepted_at' => current_time( 'mysql' ), + ], + [ '%d', '%d', '%s', '%d', '%s', '%s' ] + ); + + return $this->db->insert_id; + } + + /** + * Persist a batch of acceptances for a single registration. + * + * @param list $acceptances + * @return list Inserted acceptance IDs. + */ + public function insertMany( array $acceptances ): array { + return array_map( fn( PolicyAcceptance $a ): int => $this->insert( $a ), $acceptances ); + } + + /** + * Find all acceptances attached to a registration (lesson or enrolment). + * + * @return list + */ + public function findByRegistration( string $registrationType, int $registrationId ): array { + $rows = $this->db->get_results( + $this->db->prepare( + "SELECT * FROM {$this->table} WHERE registration_type = %s AND registration_id = %d ORDER BY id ASC", + $registrationType, + $registrationId + ) + ); + + return array_map( PolicyAcceptance::fromRow( ... ), $rows ?? [] ); + } +} diff --git a/src/Policy/Policy.php b/src/Policy/Policy.php new file mode 100644 index 0000000..fbb2344 --- /dev/null +++ b/src/Policy/Policy.php @@ -0,0 +1,37 @@ +title, + slug: $row->slug, + currentVersionId: null !== $row->current_version_id ? (int) $row->current_version_id : null, + id: (int) $row->id, + ); + } + + /** + * Returns a plain array representation of the policy. + * + * @return array + */ + public function toArray(): array { + return [ + 'id' => $this->id, + 'title' => $this->title, + 'slug' => $this->slug, + 'current_version_id' => $this->currentVersionId, + ]; + } +} diff --git a/src/Policy/PolicyAcceptance.php b/src/Policy/PolicyAcceptance.php new file mode 100644 index 0000000..ea534cf --- /dev/null +++ b/src/Policy/PolicyAcceptance.php @@ -0,0 +1,56 @@ + + */ + public const VALID_REGISTRATION_TYPES = [ self::REG_LESSON, self::REG_ENROLLMENT ]; + + public function __construct( + public readonly int $policyVersionId, + public readonly int $studentId, + public readonly string $registrationType, + public readonly int $registrationId, + public readonly ?string $ipAddress = null, + public readonly ?string $acceptedAt = null, + public readonly ?int $id = null, + ) {} + + public static function fromRow( object $row ): self { + return new self( + policyVersionId: (int) $row->policy_version_id, + studentId: (int) $row->student_id, + registrationType: $row->registration_type, + registrationId: (int) $row->registration_id, + ipAddress: $row->ip_address, + acceptedAt: $row->accepted_at, + id: (int) $row->id, + ); + } + + /** + * Returns a plain array representation of the acceptance. + * + * @return array + */ + public function toArray(): array { + return [ + 'id' => $this->id, + 'policy_version_id' => $this->policyVersionId, + 'student_id' => $this->studentId, + 'registration_type' => $this->registrationType, + 'registration_id' => $this->registrationId, + 'ip_address' => $this->ipAddress, + 'accepted_at' => $this->acceptedAt, + ]; + } +} diff --git a/src/Policy/PolicyController.php b/src/Policy/PolicyController.php new file mode 100644 index 0000000..7403ff5 --- /dev/null +++ b/src/Policy/PolicyController.php @@ -0,0 +1,69 @@ +handleFormAction(); + } + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only policy selector. + $policyId = absint( $_GET['policy_id'] ?? 0 ); + $policyList = $this->policies->findAll(); + $selectedPolicy = $policyId > 0 ? $this->policies->findById( $policyId ) : null; + $policyVersions = null !== $selectedPolicy ? $this->versions->findByPolicy( (int) $selectedPolicy->id ) : null; + + include USC_PLUGIN_DIR . 'templates/admin/policies.php'; + } + + private function handleFormAction(): void { + // Nonce is verified by the caller (renderPage) before this method runs. + // phpcs:disable WordPress.Security.NonceVerification.Missing + $action = sanitize_key( wp_unslash( $_POST['usc_action'] ?? '' ) ); + + if ( 'create_policy' === $action ) { + $title = sanitize_text_field( wp_unslash( $_POST['title'] ?? '' ) ); + $slugRaw = sanitize_text_field( wp_unslash( $_POST['slug'] ?? '' ) ); + $slug = sanitize_title( '' !== $slugRaw ? $slugRaw : $title ); + + if ( '' !== $title && '' !== $slug && null === $this->policies->findBySlug( $slug ) ) { + $this->service->createPolicy( $title, $slug ); + } + + return; + } + + $policyId = absint( $_POST['policy_id'] ?? 0 ); + if ( $policyId <= 0 || null === $this->policies->findById( $policyId ) ) { + return; + } + + if ( 'add_version' === $action ) { + $body = wp_kses_post( wp_unslash( $_POST['body'] ?? '' ) ); + $this->service->addDraftVersion( $policyId, $body ); + } + + if ( 'publish_version' === $action ) { + $versionId = absint( $_POST['version_id'] ?? 0 ); + if ( $versionId > 0 ) { + $this->service->publishVersion( $policyId, $versionId ); + } + } + // phpcs:enable WordPress.Security.NonceVerification.Missing + } +} diff --git a/src/Policy/PolicyEndpoint.php b/src/Policy/PolicyEndpoint.php new file mode 100644 index 0000000..7d6ebe8 --- /dev/null +++ b/src/Policy/PolicyEndpoint.php @@ -0,0 +1,197 @@ + \WP_REST_Server::READABLE, + 'callback' => [ $this, 'index' ], + 'permission_callback' => '__return_true', + ], + [ + 'methods' => \WP_REST_Server::CREATABLE, + 'callback' => [ $this, 'create' ], + 'permission_callback' => [ $this, 'canManage' ], + ], + ] + ); + + register_rest_route( + $route_namespace, + '/policies/(?P\d+)/versions', + [ + [ + 'methods' => \WP_REST_Server::CREATABLE, + 'callback' => [ $this, 'addVersion' ], + 'permission_callback' => [ $this, 'canManage' ], + ], + ] + ); + + register_rest_route( + $route_namespace, + '/policies/(?P\d+)/versions/(?P\d+)', + [ + [ + 'methods' => \WP_REST_Server::EDITABLE, + 'callback' => [ $this, 'updateVersion' ], + 'permission_callback' => [ $this, 'canManage' ], + ], + ] + ); + + register_rest_route( + $route_namespace, + '/policies/(?P\d+)/versions/(?P\d+)/publish', + [ + [ + 'methods' => \WP_REST_Server::CREATABLE, + 'callback' => [ $this, 'publish' ], + 'permission_callback' => [ $this, 'canManage' ], + ], + ] + ); + } + + /** + * Public: the current published version of every policy (the registration gate). + */ + public function index(): \WP_REST_Response { + $out = []; + + foreach ( $this->policies->findAll() as $policy ) { + if ( null === $policy->currentVersionId ) { + continue; + } + + $version = $this->versions->findById( $policy->currentVersionId ); + if ( null === $version || ! $version->isPublished() ) { + continue; + } + + $out[] = [ + 'id' => $policy->id, + 'title' => $policy->title, + 'slug' => $policy->slug, + 'policy_version_id' => $version->id, + 'version_number' => $version->versionNumber, + 'body' => $version->body, + ]; + } + + return new \WP_REST_Response( $out, 200 ); + } + + public function create( \WP_REST_Request $request ): \WP_REST_Response|\WP_Error { + $title = sanitize_text_field( (string) $request->get_param( 'title' ) ); + if ( '' === $title ) { + return $this->invalid( __( 'A policy title is required.', 'unsupervised-schedular' ) ); + } + + $slugParam = sanitize_text_field( (string) $request->get_param( 'slug' ) ); + $slug = sanitize_title( '' !== $slugParam ? $slugParam : $title ); + if ( '' === $slug ) { + return $this->invalid( __( 'A valid policy slug is required.', 'unsupervised-schedular' ) ); + } + + if ( null !== $this->policies->findBySlug( $slug ) ) { + return new \WP_Error( 'duplicate_slug', __( 'A policy with that slug already exists.', 'unsupervised-schedular' ), [ 'status' => 409 ] ); + } + + $id = $this->service->createPolicy( $title, $slug ); + + return new \WP_REST_Response( [ 'id' => $id ], 201 ); + } + + public function addVersion( \WP_REST_Request $request ): \WP_REST_Response|\WP_Error { + $policy = $this->policies->findById( absint( $request->get_param( 'id' ) ) ); + if ( null === $policy ) { + return $this->notFound(); + } + + $body = wp_kses_post( (string) $request->get_param( 'body' ) ); + $id = $this->service->addDraftVersion( (int) $policy->id, $body ); + + return new \WP_REST_Response( [ 'id' => $id ], 201 ); + } + + public function updateVersion( \WP_REST_Request $request ): \WP_REST_Response|\WP_Error { + $version = $this->loadVersionForPolicy( $request ); + if ( $version instanceof \WP_Error ) { + return $version; + } + + if ( PolicyVersion::STATUS_DRAFT !== $version->status ) { + return $this->invalid( __( 'Only draft versions can be edited.', 'unsupervised-schedular' ) ); + } + + $body = wp_kses_post( (string) $request->get_param( 'body' ) ); + $this->versions->updateBody( (int) $version->id, $body ); + + return new \WP_REST_Response( + [ + 'id' => $version->id, + 'body' => $body, + ], + 200 + ); + } + + public function publish( \WP_REST_Request $request ): \WP_REST_Response|\WP_Error { + $version = $this->loadVersionForPolicy( $request ); + if ( $version instanceof \WP_Error ) { + return $version; + } + + $this->service->publishVersion( (int) $request->get_param( 'id' ), (int) $version->id ); + + return new \WP_REST_Response( + [ + 'id' => $version->id, + 'status' => PolicyVersion::STATUS_PUBLISHED, + ], + 200 + ); + } + + public function canManage(): bool { + return is_user_logged_in() && current_user_can( RoleManager::CAP_MANAGE_POLICIES ); + } + + /** + * Load the version named in the route and confirm it belongs to the policy. + */ + private function loadVersionForPolicy( \WP_REST_Request $request ): PolicyVersion|\WP_Error { + $policyId = absint( $request->get_param( 'id' ) ); + $version = $this->versions->findById( absint( $request->get_param( 'vid' ) ) ); + + if ( null === $version || $version->policyId !== $policyId ) { + return $this->notFound(); + } + + return $version; + } + + private function notFound(): \WP_Error { + return new \WP_Error( 'not_found', __( 'Policy or version not found.', 'unsupervised-schedular' ), [ 'status' => 404 ] ); + } + + private function invalid( string $message ): \WP_Error { + return new \WP_Error( 'invalid_policy', $message, [ 'status' => 400 ] ); + } +} diff --git a/src/Policy/PolicyRepository.php b/src/Policy/PolicyRepository.php new file mode 100644 index 0000000..7dec220 --- /dev/null +++ b/src/Policy/PolicyRepository.php @@ -0,0 +1,69 @@ +table = $db->prefix . 'us_policies'; + } + + public function insert( Policy $policy ): int { + $this->db->insert( + $this->table, + [ + 'title' => $policy->title, + 'slug' => $policy->slug, + 'current_version_id' => $policy->currentVersionId, + 'created_at' => current_time( 'mysql' ), + ], + [ '%s', '%s', '%d', '%s' ] + ); + + return $this->db->insert_id; + } + + public function updateCurrentVersion( int $policyId, int $versionId ): bool { + return false !== $this->db->update( + $this->table, + [ 'current_version_id' => $versionId ], + [ 'id' => $policyId ], + [ '%d' ], + [ '%d' ] + ); + } + + /** + * All policies, ordered by title. + * + * @return list + */ + public function findAll(): array { + $rows = $this->db->get_results( "SELECT * FROM {$this->table} ORDER BY title ASC" ); + + return array_map( Policy::fromRow( ... ), $rows ?? [] ); + } + + public function findById( int $id ): ?Policy { + $row = $this->db->get_row( + $this->db->prepare( "SELECT * FROM {$this->table} WHERE id = %d", $id ) + ); + + return $row ? Policy::fromRow( $row ) : null; + } + + public function findBySlug( string $slug ): ?Policy { + $row = $this->db->get_row( + $this->db->prepare( "SELECT * FROM {$this->table} WHERE slug = %s", $slug ) + ); + + return $row ? Policy::fromRow( $row ) : null; + } + + public function delete( int $id ): bool { + return (bool) $this->db->delete( $this->table, [ 'id' => $id ], [ '%d' ] ); + } +} diff --git a/src/Policy/PolicyService.php b/src/Policy/PolicyService.php new file mode 100644 index 0000000..23a1aa1 --- /dev/null +++ b/src/Policy/PolicyService.php @@ -0,0 +1,58 @@ +policies->insert( new Policy( $title, $slug ) ); + } + + /** + * Add a new draft version to a policy, numbered after the latest existing one. + */ + public function addDraftVersion( int $policyId, ?string $body ): int { + $next = $this->versions->maxVersionNumber( $policyId ) + 1; + + return $this->versions->insert( + new PolicyVersion( + policyId: $policyId, + versionNumber: $next, + body: $body, + status: PolicyVersion::STATUS_DRAFT, + ) + ); + } + + /** + * Publish a version: archive the policy's previously current version, mark + * the new one published, and point the policy at it. Returns false if the + * version does not belong to the policy. + */ + public function publishVersion( int $policyId, int $versionId ): bool { + $policy = $this->policies->findById( $policyId ); + $version = $this->versions->findById( $versionId ); + + if ( null === $policy || null === $version || $version->policyId !== $policyId ) { + return false; + } + + if ( null !== $policy->currentVersionId && $policy->currentVersionId !== $versionId ) { + $this->versions->updateStatus( $policy->currentVersionId, PolicyVersion::STATUS_ARCHIVED ); + } + + $this->versions->updateStatus( $versionId, PolicyVersion::STATUS_PUBLISHED, current_time( 'mysql' ) ); + $this->policies->updateCurrentVersion( $policyId, $versionId ); + + return true; + } +} diff --git a/src/Policy/PolicyVersion.php b/src/Policy/PolicyVersion.php new file mode 100644 index 0000000..f455bdf --- /dev/null +++ b/src/Policy/PolicyVersion.php @@ -0,0 +1,58 @@ + + */ + public const VALID_STATUSES = [ self::STATUS_DRAFT, self::STATUS_PUBLISHED, self::STATUS_ARCHIVED ]; + + public function __construct( + public readonly int $policyId, + public readonly int $versionNumber, + public readonly ?string $body = null, + public readonly string $status = self::STATUS_DRAFT, + public readonly ?string $publishedAt = null, + public readonly ?int $id = null, + ) {} + + public static function fromRow( object $row ): self { + return new self( + policyId: (int) $row->policy_id, + versionNumber: (int) $row->version_number, + body: $row->body, + status: $row->status, + publishedAt: $row->published_at, + id: (int) $row->id, + ); + } + + public function isPublished(): bool { + return self::STATUS_PUBLISHED === $this->status; + } + + /** + * Returns a plain array representation of the version. + * + * @return array + */ + public function toArray(): array { + return [ + 'id' => $this->id, + 'policy_id' => $this->policyId, + 'version_number' => $this->versionNumber, + 'body' => $this->body, + 'status' => $this->status, + 'published_at' => $this->publishedAt, + ]; + } +} diff --git a/src/Policy/PolicyVersionRepository.php b/src/Policy/PolicyVersionRepository.php new file mode 100644 index 0000000..ce46cab --- /dev/null +++ b/src/Policy/PolicyVersionRepository.php @@ -0,0 +1,88 @@ +table = $db->prefix . 'us_policy_versions'; + } + + public function insert( PolicyVersion $version ): int { + $this->db->insert( + $this->table, + [ + 'policy_id' => $version->policyId, + 'version_number' => $version->versionNumber, + 'body' => $version->body, + 'status' => $version->status, + 'published_at' => $version->publishedAt, + 'created_at' => current_time( 'mysql' ), + ], + [ '%d', '%d', '%s', '%s', '%s', '%s' ] + ); + + return $this->db->insert_id; + } + + public function updateBody( int $id, ?string $body ): bool { + return false !== $this->db->update( + $this->table, + [ 'body' => $body ], + [ 'id' => $id ], + [ '%s' ], + [ '%d' ] + ); + } + + public function updateStatus( int $id, string $status, ?string $publishedAt = null ): bool { + return false !== $this->db->update( + $this->table, + [ + 'status' => $status, + 'published_at' => $publishedAt, + ], + [ 'id' => $id ], + [ '%s', '%s' ], + [ '%d' ] + ); + } + + /** + * All versions of a policy, newest version number first. + * + * @return list + */ + public function findByPolicy( int $policyId ): array { + $rows = $this->db->get_results( + $this->db->prepare( + "SELECT * FROM {$this->table} WHERE policy_id = %d ORDER BY version_number DESC", + $policyId + ) + ); + + return array_map( PolicyVersion::fromRow( ... ), $rows ?? [] ); + } + + public function findById( int $id ): ?PolicyVersion { + $row = $this->db->get_row( + $this->db->prepare( "SELECT * FROM {$this->table} WHERE id = %d", $id ) + ); + + return $row ? PolicyVersion::fromRow( $row ) : null; + } + + /** + * Highest version_number assigned for a policy (0 when none exist yet). + */ + public function maxVersionNumber( int $policyId ): int { + $max = $this->db->get_var( + $this->db->prepare( "SELECT MAX(version_number) FROM {$this->table} WHERE policy_id = %d", $policyId ) + ); + + return null === $max ? 0 : (int) $max; + } +} diff --git a/src/RestRegistrar.php b/src/RestRegistrar.php index 0e9fd4d..bc3ac49 100644 --- a/src/RestRegistrar.php +++ b/src/RestRegistrar.php @@ -9,6 +9,10 @@ use Unsupervised\Schedular\Booking\BookingEndpoint; use Unsupervised\Schedular\Booking\BookingRepository; use Unsupervised\Schedular\Offering\OfferingEndpoint; use Unsupervised\Schedular\Offering\OfferingRepository; +use Unsupervised\Schedular\Policy\PolicyEndpoint; +use Unsupervised\Schedular\Policy\PolicyRepository; +use Unsupervised\Schedular\Policy\PolicyService; +use Unsupervised\Schedular\Policy\PolicyVersionRepository; use Unsupervised\Schedular\Registration\QuestionEndpoint; use Unsupervised\Schedular\Registration\QuestionRepository; @@ -20,12 +24,14 @@ class RestRegistrar { private BookingEndpoint $bookingEndpoint; private OfferingEndpoint $offeringEndpoint; private QuestionEndpoint $questionEndpoint; + private PolicyEndpoint $policyEndpoint; - public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings, QuestionRepository $questions ) { + public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings, QuestionRepository $questions, PolicyRepository $policies, PolicyVersionRepository $policyVersions, PolicyService $policyService ) { $this->availabilityEndpoint = new AvailabilityEndpoint( $availability ); $this->bookingEndpoint = new BookingEndpoint( $availability, $bookings ); $this->offeringEndpoint = new OfferingEndpoint( $offerings ); $this->questionEndpoint = new QuestionEndpoint( $questions, $offerings ); + $this->policyEndpoint = new PolicyEndpoint( $policies, $policyVersions, $policyService ); } public function register(): void { @@ -37,5 +43,6 @@ class RestRegistrar { $this->bookingEndpoint->registerRoutes( self::NAMESPACE ); $this->offeringEndpoint->registerRoutes( self::NAMESPACE ); $this->questionEndpoint->registerRoutes( self::NAMESPACE ); + $this->policyEndpoint->registerRoutes( self::NAMESPACE ); } } diff --git a/src/Schema.php b/src/Schema.php index 3675b90..4a41888 100644 --- a/src/Schema.php +++ b/src/Schema.php @@ -89,6 +89,43 @@ class Schema { KEY registration (registration_type, registration_id), KEY student_id (student_id) ) {$charset};", + + "CREATE TABLE {$prefix}us_policies ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + title VARCHAR(191) NOT NULL, + slug VARCHAR(191) NOT NULL, + current_version_id BIGINT UNSIGNED DEFAULT NULL, + created_at DATETIME NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY slug (slug) + ) {$charset};", + + "CREATE TABLE {$prefix}us_policy_versions ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + policy_id BIGINT UNSIGNED NOT NULL, + version_number INT NOT NULL DEFAULT 1, + body LONGTEXT, + status VARCHAR(20) NOT NULL DEFAULT 'draft', + published_at DATETIME DEFAULT NULL, + created_at DATETIME NOT NULL, + PRIMARY KEY (id), + KEY policy_id (policy_id), + KEY status (status) + ) {$charset};", + + "CREATE TABLE {$prefix}us_policy_acceptances ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + policy_version_id BIGINT UNSIGNED NOT NULL, + student_id BIGINT UNSIGNED NOT NULL, + registration_type VARCHAR(20) NOT NULL, + registration_id BIGINT UNSIGNED NOT NULL, + accepted_at DATETIME NOT NULL, + ip_address VARCHAR(45) DEFAULT NULL, + PRIMARY KEY (id), + KEY policy_version_id (policy_version_id), + KEY student_id (student_id), + KEY registration (registration_type, registration_id) + ) {$charset};", ]; } } diff --git a/templates/admin/policies.php b/templates/admin/policies.php new file mode 100644 index 0000000..3497059 --- /dev/null +++ b/templates/admin/policies.php @@ -0,0 +1,110 @@ + $policyList + * @var \Unsupervised\Schedular\Policy\Policy|null $selectedPolicy + * @var list<\Unsupervised\Schedular\Policy\PolicyVersion>|null $policyVersions + */ +?> +
+

+ +

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

title)); ?>

+ +

+
+ + + + + +
+ +

+ +

+ + + + + + + + + + + + + + + + + + + + +
+ versionNumber); ?> + currentVersionId === $version->id) : ?> + + + status); ?>publishedAt ? esc_html($version->publishedAt) : '—'; ?> + status) : ?> +
+ + + + + +
+ + + +
+ + +
diff --git a/tests/Unit/Policy/AcceptanceRepositoryTest.php b/tests/Unit/Policy/AcceptanceRepositoryTest.php new file mode 100644 index 0000000..08dc1c0 --- /dev/null +++ b/tests/Unit/Policy/AcceptanceRepositoryTest.php @@ -0,0 +1,93 @@ +db = Mockery::mock(\wpdb::class); + $this->db->prefix = 'wp_'; + $this->repo = new AcceptanceRepository($this->db); + } + + public function testInsertReturnsId(): void + { + Functions\expect('current_time')->with('mysql')->andReturn('2026-06-02 09:00:00'); + + $this->db->shouldReceive('insert') + ->once() + ->with( + 'wp_us_policy_acceptances', + Mockery::on(static function (array $d): bool { + return $d['policy_version_id'] === 9 + && $d['student_id'] === 5 + && $d['registration_type'] === PolicyAcceptance::REG_LESSON + && $d['registration_id'] === 12 + && $d['ip_address'] === '203.0.113.7'; + }), + ['%d', '%d', '%s', '%d', '%s', '%s'] + ); + $this->db->insert_id = 1; + + $acceptance = new PolicyAcceptance(9, 5, PolicyAcceptance::REG_LESSON, 12, '203.0.113.7'); + + self::assertSame(1, $this->repo->insert($acceptance)); + } + + public function testInsertManyReturnsAllIds(): void + { + Functions\when('current_time')->justReturn('2026-06-02 09:00:00'); + + $ids = [11, 12]; + $this->db->shouldReceive('insert') + ->twice() + ->andReturnUsing(function () use (&$ids): void { + $this->db->insert_id = array_shift($ids); + }); + + $result = $this->repo->insertMany([ + new PolicyAcceptance(9, 5, PolicyAcceptance::REG_LESSON, 12), + new PolicyAcceptance(10, 5, PolicyAcceptance::REG_LESSON, 12), + ]); + + self::assertSame([11, 12], $result); + } + + public function testFindByRegistrationMapsRows(): void + { + $this->db->shouldReceive('prepare') + ->once() + ->with(Mockery::pattern('/registration_type = %s AND registration_id = %d/'), PolicyAcceptance::REG_LESSON, 12) + ->andReturn('SELECT ...'); + + $this->db->shouldReceive('get_results')->andReturn([ + (object) [ + 'id' => '1', + 'policy_version_id' => '9', + 'student_id' => '5', + 'registration_type' => PolicyAcceptance::REG_LESSON, + 'registration_id' => '12', + 'accepted_at' => '2026-06-02 09:00:00', + 'ip_address' => null, + ], + ]); + + $rows = $this->repo->findByRegistration(PolicyAcceptance::REG_LESSON, 12); + + self::assertCount(1, $rows); + self::assertInstanceOf(PolicyAcceptance::class, $rows[0]); + } +} diff --git a/tests/Unit/Policy/PolicyRepositoryTest.php b/tests/Unit/Policy/PolicyRepositoryTest.php new file mode 100644 index 0000000..868e374 --- /dev/null +++ b/tests/Unit/Policy/PolicyRepositoryTest.php @@ -0,0 +1,94 @@ +db = Mockery::mock(\wpdb::class); + $this->db->prefix = 'wp_'; + $this->repo = new PolicyRepository($this->db); + } + + public function testInsertReturnsId(): void + { + Functions\expect('current_time')->with('mysql')->andReturn('2026-06-01 12:00:00'); + + $this->db->shouldReceive('insert') + ->once() + ->with( + 'wp_us_policies', + Mockery::on(static fn (array $d): bool => $d['title'] === 'Cancellation' && $d['slug'] === 'cancellation' && $d['current_version_id'] === null), + ['%s', '%s', '%d', '%s'] + ); + $this->db->insert_id = 7; + + self::assertSame(7, $this->repo->insert(new Policy('Cancellation', 'cancellation'))); + } + + public function testUpdateCurrentVersion(): void + { + $this->db->shouldReceive('update') + ->once() + ->with('wp_us_policies', ['current_version_id' => 9], ['id' => 7], ['%d'], ['%d']) + ->andReturn(1); + + self::assertTrue($this->repo->updateCurrentVersion(7, 9)); + } + + public function testFindBySlugReturnsPolicy(): void + { + $this->db->shouldReceive('prepare')->andReturn('SELECT ...'); + $this->db->shouldReceive('get_row')->andReturn((object) [ + 'id' => '7', + 'title' => 'Cancellation', + 'slug' => 'cancellation', + 'current_version_id' => null, + ]); + + $policy = $this->repo->findBySlug('cancellation'); + + self::assertInstanceOf(Policy::class, $policy); + self::assertSame('cancellation', $policy->slug); + } + + public function testFindBySlugReturnsNullWhenMissing(): void + { + $this->db->shouldReceive('prepare')->andReturn('SELECT ...'); + $this->db->shouldReceive('get_row')->andReturn(null); + + self::assertNull($this->repo->findBySlug('nope')); + } + + public function testFindAllMapsRows(): void + { + $this->db->shouldReceive('get_results')->andReturn([ + (object) ['id' => '1', 'title' => 'A', 'slug' => 'a', 'current_version_id' => null], + ]); + + $all = $this->repo->findAll(); + + self::assertCount(1, $all); + self::assertInstanceOf(Policy::class, $all[0]); + } + + public function testDeleteCallsWpdb(): void + { + $this->db->shouldReceive('delete')->once()->with('wp_us_policies', ['id' => 3], ['%d'])->andReturn(1); + + self::assertTrue($this->repo->delete(3)); + } +} diff --git a/tests/Unit/Policy/PolicyServiceTest.php b/tests/Unit/Policy/PolicyServiceTest.php new file mode 100644 index 0000000..9784c96 --- /dev/null +++ b/tests/Unit/Policy/PolicyServiceTest.php @@ -0,0 +1,91 @@ +policies = Mockery::mock(PolicyRepository::class); + $this->versions = Mockery::mock(PolicyVersionRepository::class); + $this->service = new PolicyService($this->policies, $this->versions); + } + + public function testCreatePolicyInsertsPolicy(): void + { + $this->policies->shouldReceive('insert') + ->once() + ->with(Mockery::on(static fn (Policy $p): bool => $p->title === 'Cancellation' && $p->slug === 'cancellation')) + ->andReturn(7); + + self::assertSame(7, $this->service->createPolicy('Cancellation', 'cancellation')); + } + + public function testAddDraftVersionNumbersAfterLatest(): void + { + $this->versions->shouldReceive('maxVersionNumber')->once()->with(4)->andReturn(2); + $this->versions->shouldReceive('insert') + ->once() + ->with(Mockery::on(static function (PolicyVersion $v): bool { + return $v->policyId === 4 + && $v->versionNumber === 3 + && $v->status === PolicyVersion::STATUS_DRAFT; + })) + ->andReturn(15); + + self::assertSame(15, $this->service->addDraftVersion(4, '

draft

')); + } + + public function testPublishArchivesPriorCurrentAndPointsPolicyAtNewVersion(): void + { + Functions\expect('current_time')->with('mysql')->andReturn('2026-06-01 12:00:00'); + + $this->policies->shouldReceive('findById')->once()->with(4)->andReturn(new Policy('T', 't', 8, 4)); + $this->versions->shouldReceive('findById')->once()->with(9)->andReturn(new PolicyVersion(4, 2, '

x

', PolicyVersion::STATUS_DRAFT, null, 9)); + + $this->versions->shouldReceive('updateStatus')->once()->with(8, PolicyVersion::STATUS_ARCHIVED); + $this->versions->shouldReceive('updateStatus')->once()->with(9, PolicyVersion::STATUS_PUBLISHED, '2026-06-01 12:00:00'); + $this->policies->shouldReceive('updateCurrentVersion')->once()->with(4, 9)->andReturn(true); + + self::assertTrue($this->service->publishVersion(4, 9)); + } + + public function testPublishFirstVersionDoesNotArchive(): void + { + Functions\expect('current_time')->andReturn('2026-06-01 12:00:00'); + + $this->policies->shouldReceive('findById')->once()->with(4)->andReturn(new Policy('T', 't', null, 4)); + $this->versions->shouldReceive('findById')->once()->with(9)->andReturn(new PolicyVersion(4, 1, null, PolicyVersion::STATUS_DRAFT, null, 9)); + + // No archive call expected (no prior current version). + $this->versions->shouldReceive('updateStatus')->once()->with(9, PolicyVersion::STATUS_PUBLISHED, '2026-06-01 12:00:00'); + $this->policies->shouldReceive('updateCurrentVersion')->once()->with(4, 9)->andReturn(true); + + self::assertTrue($this->service->publishVersion(4, 9)); + } + + public function testPublishRejectsVersionFromAnotherPolicy(): void + { + $this->policies->shouldReceive('findById')->once()->with(4)->andReturn(new Policy('T', 't', null, 4)); + $this->versions->shouldReceive('findById')->once()->with(9)->andReturn(new PolicyVersion(99, 1, null, PolicyVersion::STATUS_DRAFT, null, 9)); + + // No status/current-version writes when the version belongs elsewhere. + self::assertFalse($this->service->publishVersion(4, 9)); + } +} diff --git a/tests/Unit/Policy/PolicyValueObjectsTest.php b/tests/Unit/Policy/PolicyValueObjectsTest.php new file mode 100644 index 0000000..51b8c76 --- /dev/null +++ b/tests/Unit/Policy/PolicyValueObjectsTest.php @@ -0,0 +1,85 @@ + '4', + 'title' => 'Cancellation', + 'slug' => 'cancellation', + 'current_version_id' => '9', + ]); + + self::assertSame(4, $policy->id); + self::assertSame('cancellation', $policy->slug); + self::assertSame(9, $policy->currentVersionId); + self::assertArrayHasKey('current_version_id', $policy->toArray()); + } + + public function testPolicyHandlesNullCurrentVersion(): void + { + $policy = Policy::fromRow((object) [ + 'id' => '4', + 'title' => 'Cancellation', + 'slug' => 'cancellation', + 'current_version_id' => null, + ]); + + self::assertNull($policy->currentVersionId); + } + + public function testPolicyVersionFromRowAndStatusHelper(): void + { + $version = PolicyVersion::fromRow((object) [ + 'id' => '9', + 'policy_id' => '4', + 'version_number' => '2', + 'body' => '

Policy

', + 'status' => PolicyVersion::STATUS_PUBLISHED, + 'published_at' => '2026-06-01 10:00:00', + ]); + + self::assertSame(9, $version->id); + self::assertSame(2, $version->versionNumber); + self::assertTrue($version->isPublished()); + self::assertSame('2026-06-01 10:00:00', $version->publishedAt); + } + + public function testPolicyVersionDefaultsToDraft(): void + { + $version = new PolicyVersion(4, 1); + + self::assertSame(PolicyVersion::STATUS_DRAFT, $version->status); + self::assertFalse($version->isPublished()); + self::assertNull($version->publishedAt); + self::assertContains(PolicyVersion::STATUS_ARCHIVED, PolicyVersion::VALID_STATUSES); + } + + public function testPolicyAcceptanceFromRowAndToArray(): void + { + $acceptance = PolicyAcceptance::fromRow((object) [ + 'id' => '1', + 'policy_version_id' => '9', + 'student_id' => '5', + 'registration_type' => PolicyAcceptance::REG_LESSON, + 'registration_id' => '12', + 'accepted_at' => '2026-06-02 09:00:00', + 'ip_address' => '203.0.113.7', + ]); + + self::assertSame(9, $acceptance->policyVersionId); + self::assertSame(PolicyAcceptance::REG_LESSON, $acceptance->registrationType); + self::assertSame('203.0.113.7', $acceptance->ipAddress); + self::assertArrayHasKey('policy_version_id', $acceptance->toArray()); + self::assertContains(PolicyAcceptance::REG_ENROLLMENT, PolicyAcceptance::VALID_REGISTRATION_TYPES); + } +} diff --git a/tests/Unit/Policy/PolicyVersionRepositoryTest.php b/tests/Unit/Policy/PolicyVersionRepositoryTest.php new file mode 100644 index 0000000..dcb60f3 --- /dev/null +++ b/tests/Unit/Policy/PolicyVersionRepositoryTest.php @@ -0,0 +1,103 @@ +db = Mockery::mock(\wpdb::class); + $this->db->prefix = 'wp_'; + $this->repo = new PolicyVersionRepository($this->db); + } + + public function testInsertReturnsId(): void + { + Functions\expect('current_time')->with('mysql')->andReturn('2026-06-01 12:00:00'); + + $this->db->shouldReceive('insert') + ->once() + ->with( + 'wp_us_policy_versions', + Mockery::on(static fn (array $d): bool => $d['policy_id'] === 4 && $d['version_number'] === 1 && $d['status'] === PolicyVersion::STATUS_DRAFT), + ['%d', '%d', '%s', '%s', '%s', '%s'] + ); + $this->db->insert_id = 9; + + self::assertSame(9, $this->repo->insert(new PolicyVersion(4, 1, '

x

'))); + } + + public function testUpdateStatusWithPublishedAt(): void + { + $this->db->shouldReceive('update') + ->once() + ->with( + 'wp_us_policy_versions', + ['status' => PolicyVersion::STATUS_PUBLISHED, 'published_at' => '2026-06-01 12:00:00'], + ['id' => 9], + ['%s', '%s'], + ['%d'] + ) + ->andReturn(1); + + self::assertTrue($this->repo->updateStatus(9, PolicyVersion::STATUS_PUBLISHED, '2026-06-01 12:00:00')); + } + + public function testUpdateBody(): void + { + $this->db->shouldReceive('update') + ->once() + ->with('wp_us_policy_versions', ['body' => '

new

'], ['id' => 9], ['%s'], ['%d']) + ->andReturn(1); + + self::assertTrue($this->repo->updateBody(9, '

new

')); + } + + public function testMaxVersionNumberReturnsZeroWhenNone(): void + { + $this->db->shouldReceive('prepare')->andReturn('SELECT ...'); + $this->db->shouldReceive('get_var')->andReturn(null); + + self::assertSame(0, $this->repo->maxVersionNumber(4)); + } + + public function testMaxVersionNumberCastsResult(): void + { + $this->db->shouldReceive('prepare')->andReturn('SELECT ...'); + $this->db->shouldReceive('get_var')->andReturn('3'); + + self::assertSame(3, $this->repo->maxVersionNumber(4)); + } + + public function testFindByPolicyMapsRows(): void + { + $this->db->shouldReceive('prepare')->andReturn('SELECT ...'); + $this->db->shouldReceive('get_results')->andReturn([ + (object) [ + 'id' => '9', + 'policy_id' => '4', + 'version_number' => '1', + 'body' => null, + 'status' => PolicyVersion::STATUS_DRAFT, + 'published_at' => null, + ], + ]); + + $versions = $this->repo->findByPolicy(4); + + self::assertCount(1, $versions); + self::assertInstanceOf(PolicyVersion::class, $versions[0]); + } +}