Let parents register once and book for their children

A parent registers once and manages lessons for one or more children, who
need no login of their own. A child is a real wp_users row with the student
role but no usable login — so student_id keeps meaning "a WordPress user"
on every table, and booking, credits, policies and enrolments work unchanged.
A us_guardians link table maps guardian to child.

The signup form gains a parent/guardian tick that reveals a block per child,
with the account-signup questions asked per child rather than per guardian
— they describe the student, not the account holder. Signup policies are
recorded once per child with the guardian as the acceptor, which is the
record that actually means something. A family that half-creates is rolled
back entirely rather than leaving a guardian who cannot re-register.

The booking and enrolment forms gain a "Who is this for?" picker listing
children first, so the default selection is never the parent — booking for
the wrong child is correctable, quietly billing a parent for their kid's
lesson is not. POST /bookings and POST /enrollments take an optional
student_id honoured only for that child's guardian; anything else is a 403.
That check is the authorisation boundary of the feature.

Payments and credits gain a payer: the charge names the child it was for and
the guardian who owes it, so per-child reporting is unchanged while notices,
receipts and the payment step reach the parent. Credit is held by the payer,
so one child's cancellation can settle a sibling's charge, and the daily
billing scan sends a guardian one notice covering every child.

Closes #132

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
2026-07-29 16:07:52 -03:00
co-authored by Claude Opus 5
parent c25260a367
commit b772e1811e
71 changed files with 4192 additions and 191 deletions
+122
View File
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Tests\Unit\Guardian;
use Brain\Monkey\Filters;
use Brain\Monkey\Functions;
use Mockery;
use Unsupervised\Schedular\Auth\RoleManager;
use Unsupervised\Schedular\Guardian\ChildLoginGate;
use Unsupervised\Schedular\Guardian\GuardianService;
use Unsupervised\Schedular\Tests\Unit\TestCase;
class ChildLoginGateTest extends TestCase
{
private ChildLoginGate $gate;
protected function setUp(): void
{
parent::setUp();
$this->gate = new ChildLoginGate();
}
/**
* @param array<int, string> $children User IDs flagged as child accounts.
*/
private function stubChildren(array $children): void
{
Functions\when('get_user_meta')->alias(
static fn (int $userId, string $key, bool $single = false): string => in_array($userId, $children, true) ? '1' : ''
);
}
private function user(int $id): \WP_User
{
$user = Mockery::mock(\WP_User::class);
$user->ID = $id;
return $user;
}
public function testRegisterHooksBothFilters(): void
{
$this->gate->register();
self::assertNotFalse(Filters\has('wp_authenticate_user', [$this->gate, 'blockChildLogin']));
self::assertNotFalse(Filters\has('user_has_cap', [$this->gate, 'withholdBooking']));
}
public function testChildAccountCannotAuthenticate(): void
{
$this->stubChildren([42]);
$result = $this->gate->blockChildLogin($this->user(42));
self::assertInstanceOf(\WP_Error::class, $result);
self::assertSame('us_child_account', $result->get_error_code());
}
public function testOrdinaryStudentPassesThrough(): void
{
$this->stubChildren([42]);
$user = $this->user(9);
self::assertSame($user, $this->gate->blockChildLogin($user));
}
public function testAnEarlierAuthenticationErrorIsPassedThroughUntouched(): void
{
$this->stubChildren([42]);
$error = new \WP_Error('bad_password', 'Nope.');
self::assertSame($error, $this->gate->blockChildLogin($error));
}
public function testBookingCapabilityIsWithheldFromAChild(): void
{
$this->stubChildren([42]);
$caps = $this->gate->withholdBooking(
['read' => true, RoleManager::CAP_BOOK_LESSON => true],
[],
[],
$this->user(42)
);
self::assertArrayNotHasKey(RoleManager::CAP_BOOK_LESSON, $caps);
self::assertTrue($caps['read']);
}
public function testBookingCapabilityIsLeftAloneForAnOrdinaryStudent(): void
{
$this->stubChildren([42]);
$caps = $this->gate->withholdBooking(
[RoleManager::CAP_BOOK_LESSON => true],
[],
[],
$this->user(9)
);
self::assertTrue($caps[RoleManager::CAP_BOOK_LESSON]);
}
public function testNonUserSubjectIsIgnored(): void
{
$caps = [RoleManager::CAP_BOOK_LESSON => true];
self::assertSame($caps, $this->gate->withholdBooking($caps, [], [], null));
}
public function testGuardianServiceIsTheSingleSourceOfTheChildFlag(): void
{
$this->stubChildren([42]);
self::assertTrue(GuardianService::isChild(42));
self::assertFalse(GuardianService::isChild(9));
}
}
+276
View File
@@ -0,0 +1,276 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Tests\Unit\Guardian;
use Brain\Monkey\Functions;
use Mockery;
use Unsupervised\Schedular\Guardian\FamilyPage;
use Unsupervised\Schedular\Guardian\GuardianService;
use Unsupervised\Schedular\Registration\Answer;
use Unsupervised\Schedular\Registration\AnswerRepository;
use Unsupervised\Schedular\Registration\Question;
use Unsupervised\Schedular\Registration\QuestionRepository;
use Unsupervised\Schedular\Tests\Unit\TestCase;
class FamilyPageTest extends TestCase
{
private GuardianService&Mockery\MockInterface $guardians;
private QuestionRepository&Mockery\MockInterface $questions;
private AnswerRepository&Mockery\MockInterface $answers;
private FamilyPage $page;
protected function setUp(): void
{
parent::setUp();
$this->guardians = Mockery::mock(GuardianService::class);
$this->questions = Mockery::mock(QuestionRepository::class);
$this->answers = Mockery::mock(AnswerRepository::class);
$this->page = new FamilyPage($this->guardians, $this->questions, $this->answers);
$_POST = [];
$_GET = [];
Functions\when('is_user_logged_in')->justReturn(true);
Functions\when('get_current_user_id')->justReturn(5);
Functions\when('wp_enqueue_style')->justReturn(null);
Functions\when('wp_nonce_field')->justReturn('');
Functions\when('get_permalink')->justReturn('https://studio.test/family/');
Functions\when('absint')->alias(static fn ($value) => abs((int) $value));
Functions\when('sanitize_key')->alias(static fn (string $v): string => strtolower(preg_replace('/[^a-z0-9_\-]/i', '', $v) ?? ''));
Functions\when('sanitize_text_field')->alias(static fn (string $v): string => trim($v));
Functions\when('sanitize_textarea_field')->alias(static fn (string $v): string => trim($v));
Functions\when('wp_unslash')->alias(static fn ($v) => $v);
Functions\when('check_admin_referer')->justReturn(true);
Functions\when('add_query_arg')->alias(
static fn (string $key, $value, string $url): string => $url . '?' . $key . '=' . $value
);
}
protected function tearDown(): void
{
$_POST = [];
$_GET = [];
parent::tearDown();
}
/**
* A FamilyPage whose redirect is captured instead of exiting the process.
*
* @param-out string $captured
*/
private function capturingPage(?string &$captured): FamilyPage
{
$page = Mockery::mock(FamilyPage::class, [$this->guardians, $this->questions, $this->answers])
->makePartial()
->shouldAllowMockingProtectedMethods();
$page->shouldReceive('redirect')->andReturnUsing(static function (string $url) use (&$captured): void {
$captured = $url;
});
return $page;
}
private function question(int $id, bool $required): Question
{
return new Question(offeringId: null, label: 'Instrument', isRequired: $required, scope: Question::SCOPE_ACCOUNT, id: $id);
}
public function testLoggedOutVisitorIsOfferedALoginLink(): void
{
Functions\when('is_user_logged_in')->justReturn(false);
Functions\when('wp_login_url')->justReturn('https://studio.test/wp-login.php');
$html = $this->page->render([]);
self::assertStringContainsString('log in to manage your family', $html);
}
public function testRenderListsTheGuardiansChildren(): void
{
$this->guardians->shouldReceive('children')->once()->with(5)->andReturn([
['id' => 42, 'name' => 'Ada', 'date_of_birth' => '2015-04-02', 'relationship' => 'Parent'],
]);
$this->questions->shouldReceive('findByScope')->andReturn([]);
$html = $this->page->render([]);
self::assertStringContainsString('Ada', $html);
self::assertStringContainsString('2015-04-02', $html);
self::assertStringContainsString('Add a child', $html);
}
public function testAddCreatesTheChildRecordsItsAnswersAndRedirects(): void
{
$_POST = [
'us_family_action' => 'add',
'child_name' => 'Ada',
'child_dob' => '2015-04-02',
'child_relationship' => 'Parent',
'us_answers' => [7 => 'Piano'],
];
$this->questions->shouldReceive('findByScope')->once()->andReturn([$this->question(7, true)]);
$this->guardians->shouldReceive('createChild')->once()->with(5, 'Ada', '2015-04-02', 'Parent')->andReturn(42);
$this->answers->shouldReceive('insert')
->once()
->with(Mockery::on(static fn (Answer $a): bool =>
$a->questionId === 7
&& $a->studentId === 42
&& $a->registrationId === 42
&& $a->registrationType === Answer::REG_ACCOUNT
&& $a->answerValue === 'Piano'));
$captured = null;
$this->capturingPage($captured)->maybeHandleSubmit();
self::assertSame('https://studio.test/family/?us_family=added', $captured);
}
/**
* Validating before creating is what stops a missing answer from leaving a
* half-added child behind.
*/
public function testAddRefusesAMissingRequiredAnswerBeforeCreatingTheChild(): void
{
$_POST = [
'us_family_action' => 'add',
'child_name' => 'Ada',
'us_answers' => [7 => ' '],
];
$this->questions->shouldReceive('findByScope')->once()->andReturn([$this->question(7, true)]);
$this->guardians->shouldNotReceive('createChild');
$this->answers->shouldNotReceive('insert');
$captured = null;
$page = $this->capturingPage($captured);
$page->shouldNotReceive('redirect');
$page->maybeHandleSubmit();
self::assertNull($captured);
}
public function testAddSurfacesAServiceErrorInsteadOfRedirecting(): void
{
$_POST = ['us_family_action' => 'add', 'child_name' => ''];
$this->questions->shouldReceive('findByScope')->once()->andReturn([]);
$this->guardians->shouldReceive('createChild')->once()->andReturn(new \WP_Error('missing_name', 'Please give each child a name.'));
$this->answers->shouldNotReceive('insert');
$captured = null;
$page = $this->capturingPage($captured);
$page->shouldNotReceive('redirect');
$page->maybeHandleSubmit();
self::assertNull($captured);
}
public function testEditDelegatesToTheServiceAndRedirects(): void
{
$_POST = [
'us_family_action' => 'edit',
'child_id' => '42',
'child_name' => 'Ada L',
'child_dob' => '2015-04-02',
];
$this->guardians->shouldReceive('updateChild')->once()->with(5, 42, 'Ada L', '2015-04-02')->andReturn(true);
$captured = null;
$this->capturingPage($captured)->maybeHandleSubmit();
self::assertSame('https://studio.test/family/?us_family=updated', $captured);
}
public function testRemoveDelegatesToTheServiceAndRedirects(): void
{
$_POST = ['us_family_action' => 'remove', 'child_id' => '42'];
$this->guardians->shouldReceive('removeChild')->once()->with(5, 42)->andReturn(true);
$captured = null;
$this->capturingPage($captured)->maybeHandleSubmit();
self::assertSame('https://studio.test/family/?us_family=removed', $captured);
}
public function testRemoveRefusalIsShownRatherThanRedirected(): void
{
$_POST = ['us_family_action' => 'remove', 'child_id' => '42'];
$this->guardians->shouldReceive('removeChild')->once()->andReturn(
new \WP_Error('has_history', 'This child has lessons or enrolments on record.')
);
$captured = null;
$page = $this->capturingPage($captured);
$page->shouldNotReceive('redirect');
$page->maybeHandleSubmit();
self::assertNull($captured);
}
public function testAnUnrecognisedActionDoesNothing(): void
{
$_POST = ['us_family_action' => 'destroy'];
$this->guardians->shouldNotReceive('createChild');
$this->guardians->shouldNotReceive('removeChild');
$captured = null;
$page = $this->capturingPage($captured);
$page->shouldNotReceive('redirect');
$page->maybeHandleSubmit();
self::assertNull($captured);
}
public function testNoActionIsANoOp(): void
{
$this->guardians->shouldNotReceive('createChild');
$captured = null;
$page = $this->capturingPage($captured);
$page->shouldNotReceive('redirect');
$page->maybeHandleSubmit();
self::assertNull($captured);
}
public function testLoggedOutSubmissionIsIgnored(): void
{
Functions\when('is_user_logged_in')->justReturn(false);
$_POST = ['us_family_action' => 'remove', 'child_id' => '42'];
$this->guardians->shouldNotReceive('removeChild');
$captured = null;
$page = $this->capturingPage($captured);
$page->shouldNotReceive('redirect');
$page->maybeHandleSubmit();
self::assertNull($captured);
}
public function testCompletedActionRendersItsConfirmation(): void
{
$_GET = ['us_family' => 'added'];
$this->guardians->shouldReceive('children')->andReturn([]);
$this->questions->shouldReceive('findByScope')->andReturn([]);
self::assertStringContainsString('Child added.', $this->page->render([]));
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Tests\Unit\Guardian;
use Unsupervised\Schedular\Guardian\GuardianLink;
use Unsupervised\Schedular\Tests\Unit\TestCase;
class GuardianLinkTest extends TestCase
{
public function testFromRowCoercesWpdbStrings(): void
{
$link = GuardianLink::fromRow((object) [
'id' => '7',
'guardian_id' => '5',
'student_id' => '42',
'relationship' => 'Parent',
'created_at' => '2026-07-29 09:00:00',
]);
self::assertSame(7, $link->id);
self::assertSame(5, $link->guardianId);
self::assertSame(42, $link->studentId);
self::assertSame('Parent', $link->relationship);
self::assertSame('2026-07-29 09:00:00', $link->createdAt);
}
public function testRelationshipDefaultsToEmptyWhenTheColumnIsNull(): void
{
$link = GuardianLink::fromRow((object) [
'id' => '7',
'guardian_id' => '5',
'student_id' => '42',
'relationship' => null,
'created_at' => null,
]);
self::assertSame('', $link->relationship);
self::assertNull($link->createdAt);
}
public function testToArrayExposesEveryColumn(): void
{
$link = new GuardianLink(guardianId: 5, studentId: 42, relationship: 'Parent', createdAt: '2026-07-29 09:00:00', id: 7);
self::assertSame(
[
'id' => 7,
'guardian_id' => 5,
'student_id' => 42,
'relationship' => 'Parent',
'created_at' => '2026-07-29 09:00:00',
],
$link->toArray()
);
}
}
@@ -0,0 +1,126 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Tests\Unit\Guardian;
use Brain\Monkey\Functions;
use Mockery;
use Unsupervised\Schedular\Guardian\GuardianLink;
use Unsupervised\Schedular\Guardian\GuardianRepository;
use Unsupervised\Schedular\Tests\Unit\TestCase;
class GuardianRepositoryTest extends TestCase
{
private \wpdb $db;
private GuardianRepository $repo;
protected function setUp(): void
{
parent::setUp();
$this->db = Mockery::mock(\wpdb::class);
$this->db->prefix = 'wp_';
$this->repo = new GuardianRepository($this->db);
$this->db->shouldReceive('prepare')->andReturnUsing(
static fn (string $sql, ...$args): string => $sql . '|' . implode(',', $args)
)->byDefault();
}
public function testInsertStoresTheLinkAndReturnsId(): void
{
Functions\expect('current_time')->with('mysql')->andReturn('2026-07-29 09:00:00');
$this->db->shouldReceive('get_row')->once()->andReturn(null);
$this->db->shouldReceive('insert')
->once()
->with(
'wp_us_guardians',
[
'guardian_id' => 5,
'student_id' => 42,
'relationship' => 'Parent',
'created_at' => '2026-07-29 09:00:00',
],
['%d', '%d', '%s', '%s']
);
$this->db->insert_id = 7;
self::assertSame(7, $this->repo->insert(new GuardianLink(5, 42, 'Parent')));
}
/**
* v1 is one guardian per child. The check lives in the repository so every
* caller — signup, the family screen, admin — gets it without repeating it.
*/
public function testInsertRefusesAChildThatAlreadyHasAGuardian(): void
{
$this->db->shouldReceive('get_row')->once()->andReturn((object) [
'id' => 1,
'guardian_id' => 9,
'student_id' => 42,
'relationship' => '',
'created_at' => '2026-07-01 09:00:00',
]);
$this->db->shouldNotReceive('insert');
self::assertSame(0, $this->repo->insert(new GuardianLink(5, 42)));
}
public function testFindByStudentReturnsNullWhenTheyBookForThemselves(): void
{
$this->db->shouldReceive('get_row')->once()->andReturn(null);
self::assertNull($this->repo->findByStudent(42));
}
public function testFindByGuardianMapsEveryRow(): void
{
$this->db->shouldReceive('get_results')->once()->andReturn([
(object) ['id' => 1, 'guardian_id' => 5, 'student_id' => 42, 'relationship' => '', 'created_at' => '2026-07-01 09:00:00'],
(object) ['id' => 2, 'guardian_id' => 5, 'student_id' => 43, 'relationship' => '', 'created_at' => '2026-07-02 09:00:00'],
]);
$links = $this->repo->findByGuardian(5);
self::assertCount(2, $links);
self::assertSame([42, 43], array_map(static fn (GuardianLink $l): int => $l->studentId, $links));
}
public function testFindByGuardianReturnsAnEmptyListWhenTheQueryReturnsNull(): void
{
$this->db->shouldReceive('get_results')->once()->andReturn(null);
self::assertSame([], $this->repo->findByGuardian(5));
}
public function testIsGuardianOfIsTrueOnlyForALinkedPair(): void
{
$this->db->shouldReceive('get_var')->once()->andReturn('1');
self::assertTrue($this->repo->isGuardianOf(5, 42));
$this->db->shouldReceive('get_var')->once()->andReturn(null);
self::assertFalse($this->repo->isGuardianOf(5, 99));
}
public function testDeleteReportsWhetherARowWasRemoved(): void
{
$this->db->shouldReceive('delete')
->once()
->with('wp_us_guardians', ['guardian_id' => 5, 'student_id' => 42], ['%d', '%d'])
->andReturn(1);
self::assertTrue($this->repo->delete(5, 42));
$this->db->shouldReceive('delete')->once()->andReturn(0);
self::assertFalse($this->repo->delete(5, 99));
}
public function testCountChildrenReturnsAnInt(): void
{
$this->db->shouldReceive('get_var')->once()->andReturn('2');
self::assertSame(2, $this->repo->countChildren(5));
}
}
+296
View File
@@ -0,0 +1,296 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Tests\Unit\Guardian;
use Brain\Monkey\Functions;
use Mockery;
use Unsupervised\Schedular\Booking\BookingRepository;
use Unsupervised\Schedular\GroupClass\EnrollmentRepository;
use Unsupervised\Schedular\Guardian\GuardianLink;
use Unsupervised\Schedular\Guardian\GuardianRepository;
use Unsupervised\Schedular\Guardian\GuardianService;
use Unsupervised\Schedular\Tests\Unit\TestCase;
class GuardianServiceTest extends TestCase
{
private GuardianRepository&Mockery\MockInterface $guardians;
private BookingRepository&Mockery\MockInterface $bookings;
private EnrollmentRepository&Mockery\MockInterface $enrollments;
private GuardianService $service;
/** @var array<int, array<string, string>> */
private array $meta = [];
protected function setUp(): void
{
parent::setUp();
$this->guardians = Mockery::mock(GuardianRepository::class);
$this->bookings = Mockery::mock(BookingRepository::class);
$this->enrollments = Mockery::mock(EnrollmentRepository::class);
$this->service = new GuardianService($this->guardians, $this->bookings, $this->enrollments);
$meta = &$this->meta;
Functions\when('update_user_meta')->alias(
static function (int $userId, string $key, $value) use (&$meta): bool {
$meta[$userId][$key] = (string) $value;
return true;
}
);
// A regular closure, not an arrow fn: arrow functions capture by value,
// so the stub would read a snapshot of the meta taken at setUp.
Functions\when('get_user_meta')->alias(
static function (int $userId, string $key, bool $single = false) use (&$meta): string {
return $meta[$userId][$key] ?? '';
}
);
Functions\when('delete_user_meta')->alias(
static function (int $userId, string $key) use (&$meta): bool {
unset($meta[$userId][$key]);
return true;
}
);
Functions\when('wp_generate_password')->justReturn('abc123def456');
Functions\when('email_exists')->justReturn(false);
Functions\when('is_wp_error')->alias(static fn ($thing): bool => $thing instanceof \WP_Error);
}
private function user(int $id, string $first = '', string $last = '', string $nickname = '', string $email = ''): \WP_User
{
$user = Mockery::mock(\WP_User::class);
$user->ID = $id;
$user->first_name = $first;
$user->last_name = $last;
$user->nickname = $nickname;
$user->user_email = $email;
return $user;
}
public function testCreateChildInsertsALoginLessUserAndLinksIt(): void
{
$captured = [];
Functions\when('wp_insert_user')->alias(
static function (array $args) use (&$captured): int {
$captured = $args;
return 42;
}
);
$this->guardians->shouldReceive('insert')
->once()
->with(Mockery::on(static fn (GuardianLink $l): bool => $l->guardianId === 5 && $l->studentId === 42 && $l->relationship === 'Parent'))
->andReturn(7);
$result = $this->service->createChild(5, ' Ada ', '2015-04-02', 'Parent');
self::assertSame(42, $result);
self::assertSame('Ada', $captured['display_name']);
// The address is on the reserved .invalid TLD, so it can never receive mail.
self::assertStringEndsWith('@child.invalid', $captured['user_email']);
self::assertSame('1', $this->meta[42][GuardianService::META_CHILD]);
self::assertSame('2015-04-02', $this->meta[42][GuardianService::META_DOB]);
}
public function testCreateChildRejectsABlankName(): void
{
Functions\expect('wp_insert_user')->never();
$result = $this->service->createChild(5, ' ');
self::assertInstanceOf(\WP_Error::class, $result);
}
/**
* A child whose link could not be written would be an unreachable orphan
* account, so the user is removed again rather than left behind.
*/
public function testCreateChildDeletesTheUserWhenTheLinkFails(): void
{
Functions\when('wp_insert_user')->justReturn(42);
$this->guardians->shouldReceive('insert')->once()->andReturn(0);
Functions\expect('wp_delete_user')->once()->with(42);
self::assertInstanceOf(\WP_Error::class, $this->service->createChild(5, 'Ada'));
}
public function testCreateChildClearsAnUnparseableDateOfBirth(): void
{
Functions\when('wp_insert_user')->justReturn(42);
$this->guardians->shouldReceive('insert')->once()->andReturn(7);
$this->service->createChild(5, 'Ada', 'not-a-date');
self::assertArrayNotHasKey(GuardianService::META_DOB, $this->meta[42] ?? []);
}
public function testCanActForSelfAndOwnChildOnly(): void
{
$this->guardians->shouldReceive('isGuardianOf')->with(5, 42)->andReturn(true);
$this->guardians->shouldReceive('isGuardianOf')->with(5, 99)->andReturn(false);
self::assertTrue($this->service->canActFor(5, 5));
self::assertTrue($this->service->canActFor(5, 42));
self::assertFalse($this->service->canActFor(5, 99));
}
public function testCanActForRejectsNonPositiveIds(): void
{
self::assertFalse($this->service->canActFor(0, 42));
self::assertFalse($this->service->canActFor(5, 0));
}
public function testPayerForResolvesTheGuardianAndFallsBackToTheStudent(): void
{
$this->guardians->shouldReceive('findByStudent')->with(42)->andReturn(new GuardianLink(5, 42));
$this->guardians->shouldReceive('findByStudent')->with(9)->andReturn(null);
self::assertSame(5, $this->service->payerFor(42));
self::assertSame(9, $this->service->payerFor(9));
}
public function testHouseholdIdsCoverTheUserAndEveryChild(): void
{
$this->guardians->shouldReceive('findByGuardian')->with(5)->andReturn([
new GuardianLink(5, 42),
new GuardianLink(5, 43),
]);
self::assertSame([5, 42, 43], $this->service->householdIds(5));
}
/**
* The order is the feature: a guardian's default selection must be a child,
* never themselves, so a lesson meant for a kid is not booked in the
* parent's name by simply not touching the picker.
*/
public function testBookableStudentsListsChildrenBeforeTheAccountHolder(): void
{
$this->guardians->shouldReceive('findByGuardian')->with(5)->andReturn([
new GuardianLink(5, 42),
new GuardianLink(5, 43),
]);
Functions\when('get_userdata')->alias(fn (int $id): \WP_User => match ($id) {
5 => $this->user(5, 'Grace', 'Hopper'),
42 => $this->user(42, 'Ada', 'Lovelace'),
default => $this->user(43, 'Alan', 'Turing'),
});
$students = $this->service->bookableStudents(5);
self::assertSame(['Ada Lovelace', 'Alan Turing', 'Grace Hopper'], array_column($students, 'name'));
self::assertSame([42, 43, 5], array_column($students, 'id'));
self::assertSame([false, false, true], array_column($students, 'is_self'));
}
public function testBookableStudentsIsJustTheUserWithoutChildren(): void
{
$this->guardians->shouldReceive('findByGuardian')->with(9)->andReturn([]);
Functions\when('get_userdata')->justReturn($this->user(9, 'Ada', 'Lovelace'));
$students = $this->service->bookableStudents(9);
self::assertCount(1, $students);
self::assertTrue($students[0]['is_self']);
}
public function testContactForPrefersTheGuardian(): void
{
$this->guardians->shouldReceive('findByStudent')->with(42)->andReturn(new GuardianLink(5, 42));
Functions\when('get_userdata')->justReturn($this->user(5, 'Grace', 'Hopper', email: '[email protected]'));
self::assertSame(
['id' => 5, 'name' => 'Grace Hopper', 'email' => '[email protected]'],
$this->service->contactFor(42)
);
}
public function testContactForFallsBackToTheStudentThemselves(): void
{
$this->guardians->shouldReceive('findByStudent')->with(9)->andReturn(null);
Functions\when('get_userdata')->justReturn($this->user(9, 'Ada', 'Lovelace', email: '[email protected]'));
self::assertSame(
['id' => 9, 'name' => 'Ada Lovelace', 'email' => '[email protected]'],
$this->service->contactFor(9)
);
}
public function testUpdateChildRefusesAStudentTheCallerDoesNotGuard(): void
{
$this->guardians->shouldReceive('isGuardianOf')->with(5, 99)->andReturn(false);
Functions\expect('wp_update_user')->never();
self::assertInstanceOf(\WP_Error::class, $this->service->updateChild(5, 99, 'Mallory'));
}
public function testUpdateChildRenamesAndStoresTheDateOfBirth(): void
{
$this->guardians->shouldReceive('isGuardianOf')->with(5, 42)->andReturn(true);
Functions\expect('wp_update_user')
->once()
->with(['ID' => 42, 'display_name' => 'Ada L', 'nickname' => 'Ada L'])
->andReturn(42);
self::assertTrue($this->service->updateChild(5, 42, 'Ada L', '2015-04-02'));
self::assertSame('2015-04-02', $this->meta[42][GuardianService::META_DOB]);
}
public function testRemoveChildUnlinksAndDeletesAChildWithNoHistory(): void
{
$this->guardians->shouldReceive('isGuardianOf')->with(5, 42)->andReturn(true);
$this->bookings->shouldReceive('findByStudent')->with(42)->andReturn([]);
$this->enrollments->shouldReceive('findByStudent')->with(42)->andReturn([]);
$this->guardians->shouldReceive('delete')->once()->with(5, 42)->andReturn(true);
Functions\expect('wp_delete_user')->once()->with(42);
self::assertTrue($this->service->removeChild(5, 42));
}
/**
* A child's id is referenced by lessons, payments and credits, so deleting
* one with history would orphan all of it.
*/
public function testRemoveChildRefusesOnceTheyHaveLessons(): void
{
$this->guardians->shouldReceive('isGuardianOf')->with(5, 42)->andReturn(true);
$this->bookings->shouldReceive('findByStudent')->with(42)->andReturn([Mockery::mock(\stdClass::class)]);
$this->guardians->shouldNotReceive('delete');
$result = $this->service->removeChild(5, 42);
self::assertInstanceOf(\WP_Error::class, $result);
self::assertSame('has_history', $result->get_error_code());
}
public function testRemoveChildRefusesOnceTheyHaveEnrolments(): void
{
$this->guardians->shouldReceive('isGuardianOf')->with(5, 42)->andReturn(true);
$this->bookings->shouldReceive('findByStudent')->with(42)->andReturn([]);
$this->enrollments->shouldReceive('findByStudent')->with(42)->andReturn([Mockery::mock(\stdClass::class)]);
$this->guardians->shouldNotReceive('delete');
self::assertInstanceOf(\WP_Error::class, $this->service->removeChild(5, 42));
}
public function testRemoveChildRefusesAStudentTheCallerDoesNotGuard(): void
{
$this->guardians->shouldReceive('isGuardianOf')->with(5, 99)->andReturn(false);
$this->guardians->shouldNotReceive('delete');
self::assertInstanceOf(\WP_Error::class, $this->service->removeChild(5, 99));
}
public function testIsChildReadsTheMetaFlag(): void
{
$this->meta[42][GuardianService::META_CHILD] = '1';
self::assertTrue(GuardianService::isChild(42));
self::assertFalse(GuardianService::isChild(9));
}
}