Add Policies domain (drafting, versioning, tracked acceptance)
CI / Coding Standards (pull_request) Successful in 1m0s
CI / PHPStan (pull_request) Successful in 1m4s
CI / Tests (PHP 8.1) (pull_request) Successful in 59s
CI / Tests (PHP 8.2) (pull_request) Successful in 56s
CI / Tests (PHP 8.3) (pull_request) Successful in 57s
CI / No Debug Code (pull_request) Successful in 3s
CI / Build Plugin Zip (pull_request) Has been skipped

Implements #6: studio admins draft, version, and publish policies; the
public registration gate reads the current published version of each, and
acceptance is recorded against the exact version so a new version must be
re-accepted at the next booking.

- src/Policy/: Policy, PolicyVersion, PolicyAcceptance value objects;
  PolicyRepository, PolicyVersionRepository, AcceptanceRepository;
  PolicyService (orchestrates create/add-draft/publish across the policies
  and versions tables); PolicyEndpoint (REST); PolicyController +
  templates/admin/policies.php (Policies admin menu, manage_policies)
- us_policies, us_policy_versions, us_policy_acceptances tables in Schema
- REST: public GET /policies (current published versions); manage_policies
  for create, add version, edit draft, and publish
- Wiring in Plugin, RestRegistrar, AdminMenu

AcceptanceRepository is built now and consumed by the booking/enrolment
gate in #3/#4.

Also bump PHPStan to --memory-limit=1G in the composer lint script; the
default 128M now crashes the analysis as the codebase has grown.

Tests: tests/Unit/Policy/ (value objects, repositories, service).
composer test (90 total), cs, and PHPStan level 6 all pass.

Refs #6

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-05 15:00:54 -03:00
parent 74fb27ea05
commit 6225e772f8
21 changed files with 1344 additions and 9 deletions
+57
View File
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Policy;
class AcceptanceRepository {
private string $table;
public function __construct( private \wpdb $db ) {
$this->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<PolicyAcceptance> $acceptances
* @return list<int> 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<PolicyAcceptance>
*/
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 ?? [] );
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Policy;
class Policy {
public function __construct(
public readonly string $title,
public readonly string $slug,
public readonly ?int $currentVersionId = null,
public readonly ?int $id = null,
) {}
public static function fromRow( object $row ): self {
return new self(
title: $row->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<string, mixed>
*/
public function toArray(): array {
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'current_version_id' => $this->currentVersionId,
];
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Policy;
class PolicyAcceptance {
public const REG_LESSON = 'lesson';
public const REG_ENROLLMENT = 'enrollment';
/**
* Polymorphic registration targets an acceptance can attach to.
*
* @var list<string>
*/
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<string, mixed>
*/
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,
];
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Policy;
use Unsupervised\Schedular\Auth\RoleManager;
class PolicyController {
public function __construct(
private PolicyRepository $policies,
private PolicyVersionRepository $versions,
private PolicyService $service,
) {}
public function renderPage(): void {
if ( ! current_user_can( RoleManager::CAP_MANAGE_POLICIES ) ) {
wp_die( esc_html__( 'You do not have permission to manage policies.', 'unsupervised-schedular' ) );
}
if ( isset( $_POST['usc_action'] ) && check_admin_referer( 'usc_policy_action' ) ) {
$this->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
}
}
+197
View File
@@ -0,0 +1,197 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Policy;
use Unsupervised\Schedular\Auth\RoleManager;
class PolicyEndpoint {
public function __construct(
private PolicyRepository $policies,
private PolicyVersionRepository $versions,
private PolicyService $service,
) {}
public function registerRoutes( string $route_namespace ): void {
register_rest_route(
$route_namespace,
'/policies',
[
[
'methods' => \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<id>\d+)/versions',
[
[
'methods' => \WP_REST_Server::CREATABLE,
'callback' => [ $this, 'addVersion' ],
'permission_callback' => [ $this, 'canManage' ],
],
]
);
register_rest_route(
$route_namespace,
'/policies/(?P<id>\d+)/versions/(?P<vid>\d+)',
[
[
'methods' => \WP_REST_Server::EDITABLE,
'callback' => [ $this, 'updateVersion' ],
'permission_callback' => [ $this, 'canManage' ],
],
]
);
register_rest_route(
$route_namespace,
'/policies/(?P<id>\d+)/versions/(?P<vid>\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 ] );
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Policy;
class PolicyRepository {
private string $table;
public function __construct( private \wpdb $db ) {
$this->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<Policy>
*/
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' ] );
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Policy;
/**
* Orchestrates policy operations that span the policies and versions tables.
*/
class PolicyService {
public function __construct(
private PolicyRepository $policies,
private PolicyVersionRepository $versions,
) {}
public function createPolicy( string $title, string $slug ): int {
return $this->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;
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Policy;
class PolicyVersion {
public const STATUS_DRAFT = 'draft';
public const STATUS_PUBLISHED = 'published';
public const STATUS_ARCHIVED = 'archived';
/**
* All valid version statuses.
*
* @var list<string>
*/
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<string, mixed>
*/
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,
];
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Policy;
class PolicyVersionRepository {
private string $table;
public function __construct( private \wpdb $db ) {
$this->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<PolicyVersion>
*/
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;
}
}