Merge pull request 'Add Policies domain (drafting, versioning, tracked acceptance)' (#15) from feature/policies into main
CI / Coding Standards (push) Successful in 58s
CI / PHPStan (push) Successful in 1m7s
CI / Tests (PHP 8.2) (push) Successful in 58s
CI / Tests (PHP 8.1) (push) Successful in 52s
CI / Tests (PHP 8.3) (push) Successful in 46s
CI / No Debug Code (push) Successful in 2s
CI / Build Plugin Zip (push) Successful in 40s
CI / Coding Standards (push) Successful in 58s
CI / PHPStan (push) Successful in 1m7s
CI / Tests (PHP 8.2) (push) Successful in 58s
CI / Tests (PHP 8.1) (push) Successful in 52s
CI / Tests (PHP 8.3) (push) Successful in 46s
CI / No Debug Code (push) Successful in 2s
CI / Build Plugin Zip (push) Successful in 40s
Reviewed-on: #15
This commit was merged in pull request #15.
This commit is contained in:
+1
-1
@@ -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"
|
||||
|
||||
@@ -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`
|
||||
|
||||
+18
-1
@@ -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' ),
|
||||
|
||||
+12
-6
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 ?? [] );
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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 ] );
|
||||
}
|
||||
}
|
||||
@@ -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' ] );
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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};",
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Unsupervised\Schedular\Policy\PolicyVersion;
|
||||
|
||||
if (! defined('ABSPATH')) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* @var list<\Unsupervised\Schedular\Policy\Policy> $policyList
|
||||
* @var \Unsupervised\Schedular\Policy\Policy|null $selectedPolicy
|
||||
* @var list<\Unsupervised\Schedular\Policy\PolicyVersion>|null $policyVersions
|
||||
*/
|
||||
?>
|
||||
<div class="wrap">
|
||||
<h1><?php esc_html_e('Policies', 'unsupervised-schedular'); ?></h1>
|
||||
|
||||
<h2><?php esc_html_e('Add Policy', 'unsupervised-schedular'); ?></h2>
|
||||
<form method="post">
|
||||
<?php wp_nonce_field('usc_policy_action'); ?>
|
||||
<input type="hidden" name="usc_action" value="create_policy">
|
||||
<table class="form-table">
|
||||
<tr>
|
||||
<th><label for="title"><?php esc_html_e('Title', 'unsupervised-schedular'); ?></label></th>
|
||||
<td><input type="text" name="title" id="title" class="regular-text" required></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><label for="slug"><?php esc_html_e('Slug', 'unsupervised-schedular'); ?></label></th>
|
||||
<td>
|
||||
<input type="text" name="slug" id="slug" class="regular-text" placeholder="<?php esc_attr_e('e.g. cancellation (defaults from title)', 'unsupervised-schedular'); ?>">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<?php submit_button(esc_html__('Add Policy', 'unsupervised-schedular')); ?>
|
||||
</form>
|
||||
|
||||
<hr>
|
||||
|
||||
<form method="get">
|
||||
<input type="hidden" name="page" value="us-policies">
|
||||
<label for="policy_id"><?php esc_html_e('Policy', 'unsupervised-schedular'); ?></label>
|
||||
<select name="policy_id" id="policy_id" onchange="this.form.submit()">
|
||||
<option value="0"><?php esc_html_e('— Select a policy —', 'unsupervised-schedular'); ?></option>
|
||||
<?php foreach ($policyList as $policy) : ?>
|
||||
<option value="<?php echo esc_attr((string) $policy->id); ?>" <?php selected($selectedPolicy && $selectedPolicy->id === $policy->id); ?>>
|
||||
<?php echo esc_html($policy->title); ?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</form>
|
||||
|
||||
<?php if (null !== $selectedPolicy) : ?>
|
||||
<h2><?php echo esc_html(sprintf(/* translators: %s: policy title */ __('Versions of "%s"', 'unsupervised-schedular'), $selectedPolicy->title)); ?></h2>
|
||||
|
||||
<h3><?php esc_html_e('Add Draft Version', 'unsupervised-schedular'); ?></h3>
|
||||
<form method="post">
|
||||
<?php wp_nonce_field('usc_policy_action'); ?>
|
||||
<input type="hidden" name="usc_action" value="add_version">
|
||||
<input type="hidden" name="policy_id" value="<?php echo esc_attr((string) $selectedPolicy->id); ?>">
|
||||
<textarea name="body" rows="8" class="large-text" placeholder="<?php esc_attr_e('Policy text (HTML allowed)', 'unsupervised-schedular'); ?>"></textarea>
|
||||
<?php submit_button(esc_html__('Add Draft', 'unsupervised-schedular')); ?>
|
||||
</form>
|
||||
|
||||
<h3><?php esc_html_e('Versions', 'unsupervised-schedular'); ?></h3>
|
||||
<?php if (empty($policyVersions)) : ?>
|
||||
<p><?php esc_html_e('No versions yet. Add a draft above.', 'unsupervised-schedular'); ?></p>
|
||||
<?php else : ?>
|
||||
<table class="wp-list-table widefat fixed striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><?php esc_html_e('Version', 'unsupervised-schedular'); ?></th>
|
||||
<th><?php esc_html_e('Status', 'unsupervised-schedular'); ?></th>
|
||||
<th><?php esc_html_e('Published', 'unsupervised-schedular'); ?></th>
|
||||
<th><?php esc_html_e('Actions', 'unsupervised-schedular'); ?></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($policyVersions as $version) : ?>
|
||||
<tr>
|
||||
<td>
|
||||
<?php echo esc_html((string) $version->versionNumber); ?>
|
||||
<?php if ($selectedPolicy->currentVersionId === $version->id) : ?>
|
||||
<span class="dashicons dashicons-yes" title="<?php esc_attr_e('Current', 'unsupervised-schedular'); ?>"></span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td><?php echo esc_html($version->status); ?></td>
|
||||
<td><?php echo $version->publishedAt ? esc_html($version->publishedAt) : '—'; ?></td>
|
||||
<td>
|
||||
<?php if (PolicyVersion::STATUS_PUBLISHED !== $version->status) : ?>
|
||||
<form method="post" style="display:inline;">
|
||||
<?php wp_nonce_field('usc_policy_action'); ?>
|
||||
<input type="hidden" name="usc_action" value="publish_version">
|
||||
<input type="hidden" name="policy_id" value="<?php echo esc_attr((string) $selectedPolicy->id); ?>">
|
||||
<input type="hidden" name="version_id" value="<?php echo esc_attr((string) $version->id); ?>">
|
||||
<button type="submit" class="button button-small button-primary">
|
||||
<?php esc_html_e('Publish', 'unsupervised-schedular'); ?>
|
||||
</button>
|
||||
</form>
|
||||
<?php else : ?>
|
||||
<em><?php esc_html_e('Current', 'unsupervised-schedular'); ?></em>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Tests\Unit\Policy;
|
||||
|
||||
use Brain\Monkey\Functions;
|
||||
use Mockery;
|
||||
use Unsupervised\Schedular\Policy\AcceptanceRepository;
|
||||
use Unsupervised\Schedular\Policy\PolicyAcceptance;
|
||||
use Unsupervised\Schedular\Tests\Unit\TestCase;
|
||||
|
||||
class AcceptanceRepositoryTest extends TestCase
|
||||
{
|
||||
private \wpdb $db;
|
||||
private AcceptanceRepository $repo;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->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]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Tests\Unit\Policy;
|
||||
|
||||
use Brain\Monkey\Functions;
|
||||
use Mockery;
|
||||
use Unsupervised\Schedular\Policy\Policy;
|
||||
use Unsupervised\Schedular\Policy\PolicyRepository;
|
||||
use Unsupervised\Schedular\Tests\Unit\TestCase;
|
||||
|
||||
class PolicyRepositoryTest extends TestCase
|
||||
{
|
||||
private \wpdb $db;
|
||||
private PolicyRepository $repo;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Tests\Unit\Policy;
|
||||
|
||||
use Brain\Monkey\Functions;
|
||||
use Mockery;
|
||||
use Unsupervised\Schedular\Policy\Policy;
|
||||
use Unsupervised\Schedular\Policy\PolicyRepository;
|
||||
use Unsupervised\Schedular\Policy\PolicyService;
|
||||
use Unsupervised\Schedular\Policy\PolicyVersion;
|
||||
use Unsupervised\Schedular\Policy\PolicyVersionRepository;
|
||||
use Unsupervised\Schedular\Tests\Unit\TestCase;
|
||||
|
||||
class PolicyServiceTest extends TestCase
|
||||
{
|
||||
private PolicyRepository $policies;
|
||||
private PolicyVersionRepository $versions;
|
||||
private PolicyService $service;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->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, '<p>draft</p>'));
|
||||
}
|
||||
|
||||
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, '<p>x</p>', 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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Tests\Unit\Policy;
|
||||
|
||||
use Unsupervised\Schedular\Policy\Policy;
|
||||
use Unsupervised\Schedular\Policy\PolicyAcceptance;
|
||||
use Unsupervised\Schedular\Policy\PolicyVersion;
|
||||
use Unsupervised\Schedular\Tests\Unit\TestCase;
|
||||
|
||||
class PolicyValueObjectsTest extends TestCase
|
||||
{
|
||||
public function testPolicyFromRowAndToArray(): void
|
||||
{
|
||||
$policy = Policy::fromRow((object) [
|
||||
'id' => '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' => '<p>Policy</p>',
|
||||
'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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Tests\Unit\Policy;
|
||||
|
||||
use Brain\Monkey\Functions;
|
||||
use Mockery;
|
||||
use Unsupervised\Schedular\Policy\PolicyVersion;
|
||||
use Unsupervised\Schedular\Policy\PolicyVersionRepository;
|
||||
use Unsupervised\Schedular\Tests\Unit\TestCase;
|
||||
|
||||
class PolicyVersionRepositoryTest extends TestCase
|
||||
{
|
||||
private \wpdb $db;
|
||||
private PolicyVersionRepository $repo;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->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, '<p>x</p>')));
|
||||
}
|
||||
|
||||
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' => '<p>new</p>'], ['id' => 9], ['%s'], ['%d'])
|
||||
->andReturn(1);
|
||||
|
||||
self::assertTrue($this->repo->updateBody(9, '<p>new</p>'));
|
||||
}
|
||||
|
||||
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]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user