Add invite-only group classes
CI / Tests (PHP 8.2) (pull_request) Successful in 44s
CI / Tests (PHP 8.1) (pull_request) Successful in 49s
CI / No Debug Code (pull_request) Successful in 2s
CI / PHPStan (pull_request) Successful in 2m49s
CI / Coding Standards (pull_request) Successful in 2m55s
CI / Tests (PHP 8.3) (pull_request) Successful in 2m40s
CI / Build Plugin Zip (pull_request) Skipped

Group classes can now be marked invite-only (us_offerings.access_mode).
Invite-only classes are hidden from the public catalog and reachable only
when the instructor lets someone in via one of three paths, managed from
My Lessons -> My Group Classes:

- Add students directly: enrols them now with a pending payment.
- Make available: grants registered students access to self-enrol through
  the normal paid flow (multi-select, emailed a notice).
- Invite by email: tokenised registration invite tied to the class for a
  non-account address; after they register the class becomes enrollable.
  Reuses an existing pending invite instead of sending a second link.

New us_group_access table records grants; GET /offerings merges granted
invite-only classes for the caller; enrolment requires a grant
(403 invite_required) and flips it to enrolled on success.

composer test (487), composer lint, composer cs all pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
2026-07-23 13:51:02 -03:00
co-authored by Claude Opus 4.8
parent 25aeba9dc1
commit a281935811
33 changed files with 1598 additions and 38 deletions
@@ -7,6 +7,7 @@ use Brain\Monkey\Functions;
use Mockery;
use Unsupervised\Schedular\GroupClass\EnrollmentEndpoint;
use Unsupervised\Schedular\GroupClass\EnrollmentRepository;
use Unsupervised\Schedular\GroupClass\GroupAccessRepository;
use Unsupervised\Schedular\Offering\Offering;
use Unsupervised\Schedular\Offering\OfferingRepository;
use Unsupervised\Schedular\Payment\Payment;
@@ -20,6 +21,7 @@ class EnrollmentEndpointTest extends TestCase
private OfferingRepository $offerings;
private RegistrationGate $gate;
private PaymentService $payments;
private GroupAccessRepository $access;
private EnrollmentEndpoint $endpoint;
protected function setUp(): void
@@ -35,12 +37,14 @@ class EnrollmentEndpointTest extends TestCase
$this->offerings = Mockery::mock(OfferingRepository::class);
$this->gate = Mockery::mock(RegistrationGate::class);
$this->payments = Mockery::mock(PaymentService::class);
$this->access = Mockery::mock(GroupAccessRepository::class);
$this->endpoint = new EnrollmentEndpoint(
$this->enrollments,
$this->offerings,
$this->gate,
$this->payments,
$this->access,
);
}
@@ -49,6 +53,11 @@ class EnrollmentEndpointTest extends TestCase
return new Offering(instructorId: 3, kind: Offering::KIND_GROUP_CLASS, title: 'Choir', price: $price, id: 8);
}
private function inviteOnlyOffering(): Offering
{
return new Offering(instructorId: 3, kind: Offering::KIND_GROUP_CLASS, title: 'Private Choir', accessMode: Offering::ACCESS_INVITE_ONLY, id: 8);
}
private function expectSuccessfulEnrollment(): void
{
$this->enrollments->shouldReceive('hasActiveEnrollment')->with(8, 5)->andReturn(false);
@@ -98,4 +107,31 @@ class EnrollmentEndpointTest extends TestCase
$result->get_data()['payment']
);
}
public function testInviteOnlyClassRejectsStudentWithoutGrant(): void
{
$this->offerings->shouldReceive('findById')->with(8)->andReturn($this->inviteOnlyOffering());
$this->enrollments->shouldReceive('hasActiveEnrollment')->with(8, 5)->andReturn(false);
$this->access->shouldReceive('hasGrant')->with(8, 5)->andReturn(false);
$this->enrollments->shouldReceive('insert')->never();
$result = $this->endpoint->enroll(new \WP_REST_Request(['offering_id' => 8]));
self::assertInstanceOf(\WP_Error::class, $result);
self::assertSame('invite_required', $result->get_error_code());
self::assertSame(403, $result->error_data['invite_required']['status']);
}
public function testInviteOnlyClassAllowsGrantedStudentAndMarksEnrolled(): void
{
$this->offerings->shouldReceive('findById')->with(8)->andReturn($this->inviteOnlyOffering());
$this->access->shouldReceive('hasGrant')->with(8, 5)->andReturn(true);
$this->expectSuccessfulEnrollment();
$this->access->shouldReceive('markEnrolled')->once()->with(8, 5);
$result = $this->endpoint->enroll(new \WP_REST_Request(['offering_id' => 8]));
self::assertInstanceOf(\WP_REST_Response::class, $result);
self::assertSame(201, $result->get_status());
}
}
@@ -0,0 +1,158 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Tests\Unit\GroupClass;
use Brain\Monkey\Functions;
use Mockery;
use Unsupervised\Schedular\GroupClass\GroupAccess;
use Unsupervised\Schedular\GroupClass\GroupAccessRepository;
use Unsupervised\Schedular\Tests\Unit\TestCase;
class GroupAccessRepositoryTest extends TestCase
{
private \wpdb $db;
private GroupAccessRepository $repo;
protected function setUp(): void
{
parent::setUp();
$this->db = Mockery::mock(\wpdb::class);
$this->db->prefix = 'wp_';
$this->repo = new GroupAccessRepository($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_group_access',
Mockery::on(static function (array $d): bool {
return $d['offering_id'] === 8
&& $d['student_id'] === 5
&& $d['status'] === GroupAccess::STATUS_INVITED;
}),
['%d', '%d', '%s', '%d', '%s', '%d', '%s']
);
$this->db->insert_id = 3;
self::assertSame(3, $this->repo->insert(new GroupAccess(offeringId: 8, studentId: 5, invitedBy: 2)));
}
public function testHasGrantTrueWhenCountPositive(): void
{
$this->db->shouldReceive('prepare')
->once()
->with(
Mockery::pattern('/offering_id = %d AND student_id = %d AND status IN/'),
'wp_us_group_access',
8,
5,
GroupAccess::STATUS_INVITED,
GroupAccess::STATUS_ENROLLED
)
->andReturn('SELECT ...');
$this->db->shouldReceive('get_var')->andReturn('1');
self::assertTrue($this->repo->hasGrant(8, 5));
}
public function testHasGrantFalseWhenZero(): void
{
$this->db->shouldReceive('prepare')->andReturn('SELECT ...');
$this->db->shouldReceive('get_var')->andReturn('0');
self::assertFalse($this->repo->hasGrant(8, 5));
}
public function testFindGrantedOfferingIdsReturnsInts(): void
{
$this->db->shouldReceive('prepare')
->once()
->with(
Mockery::pattern('/DISTINCT offering_id.*student_id = %d/s'),
'wp_us_group_access',
5,
GroupAccess::STATUS_INVITED,
GroupAccess::STATUS_ENROLLED
)
->andReturn('SELECT ...');
$this->db->shouldReceive('get_col')->andReturn(['8', '9']);
self::assertSame([8, 9], $this->repo->findGrantedOfferingIds(5));
}
public function testFindByOfferingMapsRows(): void
{
$this->db->shouldReceive('prepare')->andReturn('SELECT ...');
$this->db->shouldReceive('get_results')->andReturn([
(object) [
'id' => '1',
'offering_id' => '8',
'student_id' => '5',
'email' => '',
'invite_id' => null,
'status' => GroupAccess::STATUS_INVITED,
'invited_by' => '2',
],
]);
$grants = $this->repo->findByOffering(8);
self::assertCount(1, $grants);
self::assertSame(5, $grants[0]->studentId);
}
public function testLinkStudentByEmailUpdatesNullStudentRows(): void
{
$this->db->shouldReceive('prepare')
->once()
->with(
Mockery::pattern('/UPDATE %i SET student_id = %d WHERE email = %s AND student_id IS NULL/'),
'wp_us_group_access',
5,
'[email protected]'
)
->andReturn('UPDATE ...');
$this->db->shouldReceive('query')->once()->with('UPDATE ...')->andReturn(1);
self::assertTrue($this->repo->linkStudentByEmail('[email protected]', 5));
}
public function testLinkStudentByEmailIgnoresEmptyEmail(): void
{
$this->db->shouldReceive('prepare')->never();
self::assertFalse($this->repo->linkStudentByEmail('', 5));
}
public function testMarkEnrolledUpdatesStatus(): void
{
$this->db->shouldReceive('update')
->once()
->with(
'wp_us_group_access',
['status' => GroupAccess::STATUS_ENROLLED],
['offering_id' => 8, 'student_id' => 5],
['%s'],
['%d', '%d']
)
->andReturn(1);
self::assertTrue($this->repo->markEnrolled(8, 5));
}
public function testRevokeUpdatesStatus(): void
{
$this->db->shouldReceive('update')
->once()
->with('wp_us_group_access', ['status' => GroupAccess::STATUS_REVOKED], ['id' => 3], ['%s'], ['%d'])
->andReturn(1);
self::assertTrue($this->repo->revoke(3));
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Tests\Unit\GroupClass;
use Unsupervised\Schedular\GroupClass\GroupAccess;
use Unsupervised\Schedular\Tests\Unit\TestCase;
class GroupAccessTest extends TestCase
{
public function testDefaultsToInvitedStatusAndNullStudent(): void
{
$access = new GroupAccess(offeringId: 8);
self::assertSame(GroupAccess::STATUS_INVITED, $access->status);
self::assertNull($access->studentId);
self::assertSame('', $access->email);
}
public function testFromRowMapsColumns(): void
{
$row = (object) [
'id' => '3',
'offering_id' => '8',
'student_id' => '5',
'email' => '[email protected]',
'invite_id' => '9',
'status' => GroupAccess::STATUS_ENROLLED,
'invited_by' => '2',
];
$access = GroupAccess::fromRow($row);
self::assertSame(3, $access->id);
self::assertSame(8, $access->offeringId);
self::assertSame(5, $access->studentId);
self::assertSame('[email protected]', $access->email);
self::assertSame(9, $access->inviteId);
self::assertSame(GroupAccess::STATUS_ENROLLED, $access->status);
self::assertSame(2, $access->invitedBy);
}
public function testFromRowCastsNullStudentAndInvite(): void
{
$row = (object) [
'id' => '3',
'offering_id' => '8',
'student_id' => null,
'email' => '[email protected]',
'invite_id' => null,
'status' => GroupAccess::STATUS_INVITED,
'invited_by' => null,
];
$access = GroupAccess::fromRow($row);
self::assertNull($access->studentId);
self::assertNull($access->inviteId);
self::assertNull($access->invitedBy);
}
public function testToArrayContainsExpectedKeys(): void
{
$arr = (new GroupAccess(offeringId: 8, studentId: 5, id: 3))->toArray();
foreach (['id', 'offering_id', 'student_id', 'email', 'invite_id', 'status', 'invited_by'] as $key) {
self::assertArrayHasKey($key, $arr);
}
}
}
@@ -5,13 +5,17 @@ namespace Unsupervised\Schedular\Tests\Unit\GroupClass;
use Brain\Monkey\Functions;
use Mockery;
use Unsupervised\Schedular\Auth\InviteRepository;
use Unsupervised\Schedular\Auth\RegistrationMailer;
use Unsupervised\Schedular\GroupClass\Enrollment;
use Unsupervised\Schedular\GroupClass\EnrollmentRepository;
use Unsupervised\Schedular\GroupClass\GroupAccessRepository;
use Unsupervised\Schedular\GroupClass\GroupClassController;
use Unsupervised\Schedular\Offering\Offering;
use Unsupervised\Schedular\Offering\OfferingRepository;
use Unsupervised\Schedular\Payment\Payment;
use Unsupervised\Schedular\Payment\PaymentRepository;
use Unsupervised\Schedular\Payment\PaymentService;
use Unsupervised\Schedular\Tests\Unit\TestCase;
class GroupClassControllerTest extends TestCase
@@ -19,19 +23,38 @@ class GroupClassControllerTest extends TestCase
private EnrollmentRepository&Mockery\MockInterface $enrollments;
private OfferingRepository&Mockery\MockInterface $offerings;
private PaymentRepository&Mockery\MockInterface $payments;
private GroupAccessRepository&Mockery\MockInterface $access;
private PaymentService&Mockery\MockInterface $paymentService;
private InviteRepository&Mockery\MockInterface $invites;
private RegistrationMailer&Mockery\MockInterface $mailer;
private GroupClassController $controller;
protected function setUp(): void
{
parent::setUp();
$this->enrollments = Mockery::mock(EnrollmentRepository::class);
$this->offerings = Mockery::mock(OfferingRepository::class);
$this->payments = Mockery::mock(PaymentRepository::class);
$this->controller = new GroupClassController($this->enrollments, $this->offerings, $this->payments);
$this->enrollments = Mockery::mock(EnrollmentRepository::class);
$this->offerings = Mockery::mock(OfferingRepository::class);
$this->payments = Mockery::mock(PaymentRepository::class);
$this->access = Mockery::mock(GroupAccessRepository::class);
$this->paymentService = Mockery::mock(PaymentService::class);
$this->invites = Mockery::mock(InviteRepository::class);
$this->mailer = Mockery::mock(RegistrationMailer::class);
$this->controller = new GroupClassController(
$this->enrollments,
$this->offerings,
$this->payments,
$this->access,
$this->paymentService,
$this->invites,
$this->mailer,
);
Functions\when('current_user_can')->justReturn(true);
Functions\when('get_current_user_id')->justReturn(3);
Functions\when('get_users')->justReturn([]);
Functions\when('esc_attr')->returnArg();
Functions\when('esc_attr_e')->returnArg();
}
private function offering(int $id, string $title, ?int $capacity): Offering
@@ -157,4 +180,170 @@ class GroupClassControllerTest extends TestCase
$this->controller->renderInstructorPage();
}
protected function tearDown(): void
{
$_POST = [];
parent::tearDown();
}
private function inviteOnlyOffering(float $price = 0.0): Offering
{
return new Offering(
instructorId: 3,
kind: Offering::KIND_GROUP_CLASS,
title: 'Private Choir',
price: $price,
accessMode: Offering::ACCESS_INVITE_ONLY,
id: 8,
);
}
/** Stub the form-processing helpers and the render tail shared by all action tests. */
private function stubActionContext(): void
{
Functions\when('check_admin_referer')->justReturn(true);
Functions\when('sanitize_key')->alias(static fn ($v) => strtolower((string) $v));
Functions\when('wp_unslash')->returnArg();
Functions\when('sanitize_email')->returnArg();
Functions\when('absint')->alias(static fn ($v) => abs((int) $v));
// Render tail: no classes/enrolments to draw so the assertion targets the notice.
$this->offerings->shouldReceive('findAll')->with(3, Offering::KIND_GROUP_CLASS)->andReturn([]);
$this->enrollments->shouldReceive('findByInstructor')->with(3)->andReturn([]);
}
public function testAddDirectEnrolsStudentWithPendingPayment(): void
{
$_POST = ['usc_action' => 'add_direct', 'offering_id' => 8, 'student_ids' => [5]];
$this->stubActionContext();
$this->offerings->shouldReceive('findById')->with(8)->andReturn($this->inviteOnlyOffering(100.0));
$this->enrollments->shouldReceive('hasActiveEnrollment')->with(8, 5)->andReturn(false);
$this->enrollments->shouldReceive('insert')->once()->andReturn(44);
$payment = new Payment(
studentId: 5,
instructorId: 3,
registrationType: Payment::REG_ENROLLMENT,
registrationId: 44,
amount: 100.0,
method: Payment::METHOD_ETRANSFER,
status: Payment::STATUS_PENDING,
id: 12,
);
$this->paymentService->shouldReceive('createForRegistration')
->once()
->with(Payment::REG_ENROLLMENT, 44, 5, 3, 100.0, 'CAD', null)
->andReturn($payment);
$this->enrollments->shouldReceive('setPaymentId')->once()->with(44, 12)->andReturn(true);
$this->access->shouldReceive('markEnrolled')->once()->with(8, 5);
$html = $this->renderInstructor();
self::assertStringContainsString('1 student(s) added to the class.', $html);
}
public function testGrantAccessCreatesGrantAndEmailsStudent(): void
{
$_POST = ['usc_action' => 'grant_access', 'offering_id' => 8, 'student_ids' => [5]];
$this->stubActionContext();
$this->offerings->shouldReceive('findById')->with(8)->andReturn($this->inviteOnlyOffering());
$this->enrollments->shouldReceive('hasActiveEnrollment')->with(8, 5)->andReturn(false);
$this->access->shouldReceive('hasGrant')->with(8, 5)->andReturn(false);
$this->access->shouldReceive('insert')->once()->andReturn(1);
$user = Mockery::mock(\WP_User::class);
$user->user_email = '[email protected]';
Functions\when('get_userdata')->justReturn($user);
$this->mailer->shouldReceive('sendClassAccessGranted')->once()->with($user, 'Private Choir')->andReturn(true);
$html = $this->renderInstructor();
self::assertStringContainsString('1 student(s) granted access.', $html);
}
public function testInviteEmailForNewAddressCreatesInviteAndSendsLink(): void
{
$_POST = ['usc_action' => 'invite_email', 'offering_id' => 8, 'email' => '[email protected]'];
$this->stubActionContext();
$this->offerings->shouldReceive('findById')->with(8)->andReturn($this->inviteOnlyOffering());
Functions\when('is_email')->justReturn(true);
Functions\when('email_exists')->justReturn(false);
$this->invites->shouldReceive('findPendingByEmail')->with('[email protected]')->andReturn(null);
Functions\when('wp_generate_password')->justReturn('rawtoken');
Functions\when('get_option')->justReturn(0);
Functions\when('home_url')->justReturn('http://home.test/');
Functions\when('add_query_arg')->justReturn('http://home.test/?us_invite=rawtoken');
$this->invites->shouldReceive('insert')->once()->andReturn(7);
$this->access->shouldReceive('insert')->once()->andReturn(2);
$this->mailer->shouldReceive('sendClassInvite')->once()->with('[email protected]', 'http://home.test/?us_invite=rawtoken', 'Private Choir')->andReturn(true);
$html = $this->renderInstructor();
self::assertStringContainsString('Invitation sent.', $html);
}
public function testInviteEmailReusesPendingInviteWithoutSendingLink(): void
{
$_POST = ['usc_action' => 'invite_email', 'offering_id' => 8, 'email' => '[email protected]'];
$this->stubActionContext();
$this->offerings->shouldReceive('findById')->with(8)->andReturn($this->inviteOnlyOffering());
Functions\when('is_email')->justReturn(true);
Functions\when('email_exists')->justReturn(false);
$this->invites->shouldReceive('findPendingByEmail')->with('[email protected]')->andReturn(
new \Unsupervised\Schedular\Auth\Invite(email: '[email protected]', token: 'hash', id: 9)
);
// No new invite row and no email — just a grant attached to the existing invite.
$this->invites->shouldReceive('insert')->never();
$this->mailer->shouldReceive('sendClassInvite')->never();
$this->access->shouldReceive('insert')->once()->andReturn(2);
$html = $this->renderInstructor();
self::assertStringContainsString('No new link was sent.', $html);
}
public function testInviteEmailForExistingAccountGrantsAccess(): void
{
$_POST = ['usc_action' => 'invite_email', 'offering_id' => 8, 'email' => '[email protected]'];
$this->stubActionContext();
$this->offerings->shouldReceive('findById')->with(8)->andReturn($this->inviteOnlyOffering());
Functions\when('is_email')->justReturn(true);
Functions\when('email_exists')->justReturn(55);
$this->enrollments->shouldReceive('hasActiveEnrollment')->with(8, 55)->andReturn(false);
$this->access->shouldReceive('hasGrant')->with(8, 55)->andReturn(false);
$this->access->shouldReceive('insert')->once()->andReturn(3);
$user = Mockery::mock(\WP_User::class);
$user->user_email = '[email protected]';
Functions\when('get_userdata')->justReturn($user);
$this->mailer->shouldReceive('sendClassAccessGranted')->once()->andReturn(true);
$html = $this->renderInstructor();
self::assertStringContainsString('1 student(s) granted access.', $html);
}
public function testActionRejectedForClassNotOwnedByInstructor(): void
{
$_POST = ['usc_action' => 'add_direct', 'offering_id' => 8, 'student_ids' => [5]];
$this->stubActionContext();
// Offering owned by a different instructor (7, not the current user 3).
$foreign = new Offering(instructorId: 7, kind: Offering::KIND_GROUP_CLASS, title: 'Other', accessMode: Offering::ACCESS_INVITE_ONLY, id: 8);
$this->offerings->shouldReceive('findById')->with(8)->andReturn($foreign);
$this->enrollments->shouldReceive('insert')->never();
$html = $this->renderInstructor();
self::assertStringContainsString('That group class was not found.', $html);
}
}