Add customer contacts, billing units and consumer personal identity codes

Customer page and contacts/billing units (phase 1, item 2):
- New customer page (customers.show) with details, contacts and billing
  units; add and edit on their own pages, delete after confirmation.
  Creating or editing a customer now leads to this page.
- Contacts: name, title, phone, email, note. Billing units: name,
  billing address, e-invoice address (12-35 letters/digits), operator
  (required with an e-invoice address) and reference.
- Use cases check that the row belongs to the customer, so ids in the
  URL can't reach another customer's rows.
- EmailAddress moves from Users to Shared so both modules can use it.
- <x-confirm-dialog> (native <dialog>) replaces <x-modal>, whose title,
  close button and focus handling are not accessible; solid red buttons
  use red-700 via published NormalButtonColors for 4.5:1 contrast.

Personal identity code (henkilötunnus) for consumers who are invoiced:
- Validated (date, century sign, check character), stored encrypted
  with an HMAC blind index for duplicate checks; never in
  CustomerSummary, search, logs or Livewire state.
- Admins and management see it in full and may remove it; others enter
  it and see only the masked form. The form never shows the stored code.

Spec, architecture doc and CLAUDE.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-23 18:11:06 +02:00
co-authored by Claude Opus 5.5
parent 8dfc02c4e5
commit e0b8f4970f
93 changed files with 3777 additions and 58 deletions
+122 -1
View File
@@ -1,6 +1,8 @@
<?php
use App\Models\User;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\BillingUnitModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerContactModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -51,6 +53,125 @@ it('creates a customer with the keyboard alone', function () {
->assertScript('document.activeElement.getAttribute("wire:model")', 'form.name')
->type('[wire\\:model="form.name"]', 'Mainos Oy')
->keys('[wire\\:model="form.name"]', 'Enter')
->assertPathIs('/customers')
->assertPathBeginsWith('/customers/')
->assertSee('Asiakas Mainos Oy lisätty.');
});
it('has no accessibility issues on the customer page and the contact and billing unit forms', function (string $page, string $device, string $colorScheme) {
$customer = CustomerModel::factory()->company('0737546-2')->create(['name' => 'Mainos Oy']);
$contact = CustomerContactModel::factory()->create([
'customer_id' => $customer->id,
'name' => 'Maija Meikäläinen',
'title' => 'Markkinointipäällikkö',
'phone' => '040 123 4567',
'email' => '[email protected]',
'note' => 'Soita aamupäivisin.',
]);
$billingUnit = BillingUnitModel::factory()->eInvoice()->create(['customer_id' => $customer->id, 'name' => 'Mainos Oy, markkinointi', 'reference' => 'PO-42']);
$url = match ($page) {
'customer page' => route('customers.show', $customer->id),
'new contact' => route('customers.contacts.create', $customer->id),
'edit contact' => route('customers.contacts.edit', [$customer->id, $contact->id]),
'new billing unit' => route('customers.billing-units.create', $customer->id),
'edit billing unit' => route('customers.billing-units.edit', [$customer->id, $billingUnit->id]),
};
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with([
'customer page',
'new contact',
'edit contact',
'new billing unit',
'edit billing unit',
])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('shows billing unit errors without accessibility issues', function (string $colorScheme) {
$customer = CustomerModel::factory()->create(['name' => 'Mainos Oy']);
$page = visit(route('customers.billing-units.create', $customer->id));
$page = $colorScheme === 'dark' ? $page->inDarkMode() : $page->inLightMode();
$page->fill('[wire\:model="form.e_invoice_address"]', '003712345678')
->press('Tallenna')
->assertSee('Anna välittäjätunnus, koska verkkolaskuosoite on annettu.')
->assertNoAccessibilityIssues(level: 2);
})->with(['light', 'dark']);
it('removes a contact with the keyboard, in a dialog that keeps and returns focus', function (string $colorScheme) {
$customer = CustomerModel::factory()->create(['name' => 'Mainos Oy']);
CustomerContactModel::factory()->create(['customer_id' => $customer->id, 'name' => 'Maija']);
CustomerContactModel::factory()->create(['customer_id' => $customer->id, 'name' => 'Pekka']);
$page = visit(route('customers.show', $customer->id));
$page = $colorScheme === 'dark' ? $page->inDarkMode() : $page->inLightMode();
$removeMaija = '[aria-label="Poista yhteyshenkilö Maija"]';
// Cancel: the dialog opens with focus inside it, and Escape returns focus to the button.
$page->keys($removeMaija, 'Enter')
->assertSee('Poistetaanko yhteyshenkilö Maija?')
->assertScript('document.getElementById("remove-dialog").open', true)
->assertScript('document.getElementById("remove-dialog").contains(document.activeElement)', true)
->assertNoAccessibilityIssues(level: 2)
->keys('#remove-dialog', 'Escape')
->assertScript('document.getElementById("remove-dialog").open', false)
->assertScript('document.activeElement.getAttribute("aria-label")', 'Poista yhteyshenkilö Maija');
// Confirm: the row goes away and focus moves to the section heading.
$page->keys($removeMaija, 'Enter')
->click('#remove-dialog button.bg-red-600, #remove-dialog [wire\:click="remove"]')
->assertSee('Yhteyshenkilö Maija poistettu.')
->assertDontSee('Poista yhteyshenkilö Maija')
->assertScript('document.activeElement.id', 'contacts-heading')
->assertSee('Pekka');
})->with(['light', 'dark']);
it('has no accessibility issues with a consumer\'s personal identity code', function (string $page, string $device, string $colorScheme) {
$this->actingAs(User::factory()->management()->create());
$consumer = CustomerModel::factory()->consumer()->create([
'name' => 'Maija Meikäläinen',
'personal_identity_code' => '131052-308T',
'personal_identity_code_hash' => str_repeat('a', 64),
]);
$url = match ($page) {
'customer page' => route('customers.show', $consumer->id),
'edit form' => route('customers.edit', $consumer->id),
};
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertSee($page === 'customer page' ? '131052-308T' : 'Poista tallennettu henkilötunnus')
->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['customer page', 'edit form'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('shows an invalid personal identity code error without accessibility issues', function (string $colorScheme) {
$page = visit(route('customers.create'));
$page = $colorScheme === 'dark' ? $page->inDarkMode() : $page->inLightMode();
$page->fill('[wire\:model="form.name"]', 'Maija Meikäläinen')
->click('Kuluttaja')
->fill('[wire\:model="form.personal_identity_code"]', '131052-308U')
->press('Tallenna')
->assertSee('Henkilötunnus ei ole kelvollinen.')
->assertNoAccessibilityIssues(level: 2);
})->with(['light', 'dark']);
+1 -1
View File
@@ -2,9 +2,9 @@
namespace Tests\Fakes;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
use App\Modules\Users\Application\DTOs\IssuedSetupLink;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
class FakePasswordLinkSender implements PasswordLinkSender
{
@@ -0,0 +1,46 @@
<?php
namespace Tests\Fakes;
use App\Modules\Customers\Domain\Contracts\BillingUnitRepository;
use App\Modules\Customers\Domain\Entities\BillingUnit;
class InMemoryBillingUnitRepository implements BillingUnitRepository
{
/**
* @var array<int, BillingUnit>
*/
public array $billingUnits = [];
private int $nextId = 1;
public function findForCustomer(int $customerId, int $billingUnitId): ?BillingUnit
{
$billingUnit = $this->billingUnits[$billingUnitId] ?? null;
return $billingUnit !== null && $billingUnit->customerId() === $customerId ? clone $billingUnit : null;
}
public function save(BillingUnit $billingUnit): BillingUnit
{
$id = $billingUnit->id() ?? $this->nextId++;
$stored = BillingUnit::reconstitute(
$id,
$billingUnit->customerId(),
$billingUnit->name(),
$billingUnit->billingAddress(),
$billingUnit->eInvoiceAddress(),
$billingUnit->eInvoiceOperator(),
$billingUnit->reference(),
);
$this->billingUnits[$id] = $stored;
return clone $stored;
}
public function delete(BillingUnit $billingUnit): void
{
unset($this->billingUnits[$billingUnit->id()]);
}
}
@@ -0,0 +1,46 @@
<?php
namespace Tests\Fakes;
use App\Modules\Customers\Domain\Contracts\CustomerContactRepository;
use App\Modules\Customers\Domain\Entities\CustomerContact;
class InMemoryCustomerContactRepository implements CustomerContactRepository
{
/**
* @var array<int, CustomerContact>
*/
public array $contacts = [];
private int $nextId = 1;
public function findForCustomer(int $customerId, int $contactId): ?CustomerContact
{
$contact = $this->contacts[$contactId] ?? null;
return $contact !== null && $contact->customerId() === $customerId ? clone $contact : null;
}
public function save(CustomerContact $contact): CustomerContact
{
$id = $contact->id() ?? $this->nextId++;
$stored = CustomerContact::reconstitute(
$id,
$contact->customerId(),
$contact->name(),
$contact->title(),
$contact->phone(),
$contact->email(),
$contact->note(),
);
$this->contacts[$id] = $stored;
return clone $stored;
}
public function delete(CustomerContact $contact): void
{
unset($this->contacts[$contact->id()]);
}
}
+13 -1
View File
@@ -5,6 +5,7 @@ namespace Tests\Fakes;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
class InMemoryCustomerRepository implements CustomerRepository
{
@@ -23,13 +24,24 @@ class InMemoryCustomerRepository implements CustomerRepository
public function save(Customer $customer): Customer
{
$id = $customer->id() ?? $this->nextId++;
$stored = Customer::reconstitute($id, $customer->name(), $customer->type(), $customer->businessId());
$stored = Customer::reconstitute($id, $customer->name(), $customer->type(), $customer->businessId(), $customer->personalIdentityCode());
$this->customers[$id] = $stored;
return clone $stored;
}
public function isPersonalIdentityCodeTaken(PersonalIdentityCode $code, ?int $exceptCustomerId = null): bool
{
foreach ($this->customers as $id => $customer) {
if ($id !== $exceptCustomerId && $customer->personalIdentityCode()?->equals($code)) {
return true;
}
}
return false;
}
public function isBusinessIdTaken(BusinessId $businessId, ?int $exceptCustomerId = null): bool
{
foreach ($this->customers as $id => $customer) {
@@ -2,9 +2,9 @@
namespace Tests\Fakes;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
use App\Modules\Users\Domain\Entities\UserAccount;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
class InMemoryUserAccountRepository implements UserAccountRepository
{
@@ -0,0 +1,186 @@
<?php
use App\Models\User;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\BillingUnitModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerContactModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->actingAs(User::factory()->create());
$this->customer = CustomerModel::factory()->company('0737546-2')->create(['name' => 'Mainos Oy']);
});
it('shows the customer with its contacts and billing units', function () {
CustomerContactModel::factory()->create([
'customer_id' => $this->customer->id,
'name' => 'Maija Meikäläinen',
'phone' => '040 123 4567',
'email' => '[email protected]',
]);
BillingUnitModel::factory()->eInvoice()->create(['customer_id' => $this->customer->id, 'name' => 'Mainos Oy, markkinointi']);
CustomerContactModel::factory()->create(['name' => 'Toisen asiakkaan kontakti']);
$this->get(route('customers.show', $this->customer->id))
->assertOk()
->assertSee('Mainos Oy')
->assertSee('0737546-2')
->assertSee('Maija Meikäläinen')
->assertSee('tel:0401234567', false)
->assertSee('Mainos Oy, markkinointi')
->assertSee('003712345678')
->assertDontSee('Toisen asiakkaan kontakti');
});
it('says when a customer has no contacts or billing units yet', function () {
$this->get(route('customers.show', $this->customer->id))
->assertOk()
->assertSee('Asiakkaalle ei ole vielä lisätty yhteyshenkilöitä.')
->assertSee('Asiakkaalle ei ole vielä lisätty laskutusyksiköitä.');
});
it('adds and edits a contact', function () {
$this->get(route('customers.contacts.create', $this->customer->id))->assertOk()->assertSee('Uusi yhteyshenkilö');
Livewire::test('customers::contact-form', ['customer' => $this->customer->id])
->set('form.name', 'Maija Meikäläinen')
->set('form.title', 'Markkinointipäällikkö')
->set('form.email', '[email protected]')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('customers.show', $this->customer->id));
$contact = CustomerContactModel::query()->sole();
expect($contact->customer_id)->toBe($this->customer->id)
->and($contact->email)->toBe('[email protected]')
->and($contact->phone)->toBeNull();
Livewire::test('customers::contact-form', ['customer' => $this->customer->id, 'contact' => $contact->id])
->assertSet('form.name', 'Maija Meikäläinen')
->set('form.phone', '040 123 4567')
->call('save')
->assertHasNoErrors();
expect($contact->fresh()->phone)->toBe('040 123 4567');
});
it('shows contact form errors in Finnish', function () {
Livewire::test('customers::contact-form', ['customer' => $this->customer->id])
->set('form.email', 'maija@')
->call('save')
->assertHasErrors(['form.name', 'form.email'])
->assertSee('Anna yhteyshenkilön nimi.')
->assertSee('Sähköpostiosoite ei ole kelvollinen.');
});
it('adds and edits a billing unit, named after the customer by default', function () {
Livewire::test('customers::billing-unit-form', ['customer' => $this->customer->id])
->assertSet('form.name', 'Mainos Oy')
->set('form.e_invoice_address', '0037 1234 5678')
->set('form.e_invoice_operator', '003721291126')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('customers.show', $this->customer->id));
$billingUnit = BillingUnitModel::query()->sole();
expect($billingUnit->e_invoice_address)->toBe('003712345678');
Livewire::test('customers::billing-unit-form', ['customer' => $this->customer->id, 'billingUnit' => $billingUnit->id])
->set('form.reference', 'PO-42')
->call('save')
->assertHasNoErrors();
expect($billingUnit->fresh()->reference)->toBe('PO-42');
});
it('asks for an operator when an e-invoice address is given', function () {
Livewire::test('customers::billing-unit-form', ['customer' => $this->customer->id])
->set('form.e_invoice_address', '003712345678')
->call('save')
->assertHasErrors(['form.e_invoice_operator'])
->assertSee('Anna välittäjätunnus, koska verkkolaskuosoite on annettu.');
expect(BillingUnitModel::query()->count())->toBe(0);
});
it('removes a contact and a billing unit after confirmation', function () {
$contact = CustomerContactModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Maija']);
$billingUnit = BillingUnitModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Mainos Oy']);
Livewire::test('customers::show', ['customer' => $this->customer->id])
->call('confirmRemoval', 'contact', $contact->id)
->assertSee('Poistetaanko yhteyshenkilö Maija?')
->call('remove')
->assertSee('Yhteyshenkilö Maija poistettu.')
->call('confirmRemoval', 'billing_unit', $billingUnit->id)
->call('remove')
->assertSee('Laskutusyksikkö Mainos Oy poistettu.');
expect(CustomerContactModel::query()->exists())->toBeFalse()
->and(BillingUnitModel::query()->exists())->toBeFalse();
});
it('does not remove a row of another customer', function () {
$otherContact = CustomerContactModel::factory()->create();
Livewire::test('customers::show', ['customer' => $this->customer->id])
->call('confirmRemoval', 'contact', $otherContact->id)
->assertSet('removalId', null)
->call('remove');
expect($otherContact->fresh())->not->toBeNull();
});
it('does not let the row to remove be changed in the browser', function () {
Livewire::test('customers::show', ['customer' => $this->customer->id])
->set('removalId', 1);
})->throws(CannotUpdateLockedPropertyException::class);
it('returns 404 for an unknown customer or a row of another customer', function (string $route) {
$otherContact = CustomerContactModel::factory()->create();
$otherBillingUnit = BillingUnitModel::factory()->create();
$url = match ($route) {
'unknown customer' => route('customers.show', 999),
'contact of another customer' => route('customers.contacts.edit', [$this->customer->id, $otherContact->id]),
'billing unit of another customer' => route('customers.billing-units.edit', [$this->customer->id, $otherBillingUnit->id]),
};
$this->get($url)->assertNotFound();
})->with(['unknown customer', 'contact of another customer', 'billing unit of another customer']);
it('keeps subcontractors out of the customer pages', function () {
$this->actingAs(User::factory()->subcontractor()->create());
$this->get(route('customers.show', $this->customer->id))->assertForbidden();
$this->get(route('customers.contacts.create', $this->customer->id))->assertForbidden();
$this->get(route('customers.billing-units.create', $this->customer->id))->assertForbidden();
});
it('lists contacts and billing units for other modules, ordered by name', function () {
CustomerContactModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Pekka']);
CustomerContactModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Anna']);
BillingUnitModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'B-yksikkö']);
BillingUnitModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'A-yksikkö']);
CustomerContactModel::factory()->create(['name' => 'Toinen']);
$queries = app(CustomerQueries::class);
expect(array_map(fn ($contact) => $contact->name, $queries->contactsOf($this->customer->id)))->toBe(['Anna', 'Pekka'])
->and(array_map(fn ($unit) => $unit->name, $queries->billingUnitsOf($this->customer->id)))->toBe(['A-yksikkö', 'B-yksikkö']);
});
it('deletes the contacts and billing units of a deleted customer', function () {
CustomerContactModel::factory()->create(['customer_id' => $this->customer->id]);
BillingUnitModel::factory()->create(['customer_id' => $this->customer->id]);
$this->customer->delete();
expect(CustomerContactModel::query()->count())->toBe(0)
->and(BillingUnitModel::query()->count())->toBe(0);
});
@@ -36,7 +36,7 @@ it('registers a company customer', function () {
->set('form.business_id', '0737546-2')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('customers.index'));
->assertRedirect(route('customers.show', CustomerModel::query()->sole()->id));
$customer = CustomerModel::query()->sole();
@@ -85,7 +85,7 @@ it('edits a customer', function () {
->set('form.name', 'Mainos Oyj')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('customers.index'));
->assertRedirect(route('customers.show', $customer->id));
expect($customer->fresh()->name)->toBe('Mainos Oyj');
});
@@ -0,0 +1,146 @@
<?php
use App\Models\User;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Livewire\Livewire;
uses(RefreshDatabase::class);
/**
* Registers a consumer with a personal identity code through the form.
*/
function registerConsumerWithCode(string $code = '131052-308T'): CustomerModel
{
Livewire::test('customers::form')
->set('form.name', 'Maija Meikäläinen')
->set('form.type', CustomerType::Consumer->value)
->set('form.personal_identity_code', $code)
->call('save')
->assertHasNoErrors();
return CustomerModel::query()->latest('id')->firstOrFail();
}
it('stores the code encrypted, with a hash that is not the code', function () {
$this->actingAs(User::factory()->create());
$customer = registerConsumerWithCode();
$row = DB::table('customers')->where('id', $customer->id)->first();
expect($row->personal_identity_code)->not->toContain('131052')
->and($row->personal_identity_code_hash)->toHaveLength(64)
->and($row->personal_identity_code_hash)->not->toContain('131052')
->and($customer->personal_identity_code)->toBe('131052-308T')
->and($customer->toArray())->not->toHaveKey('personal_identity_code');
});
it('never puts the full code in the summary other modules get', function () {
$this->actingAs(User::factory()->create());
$customer = registerConsumerWithCode();
$summary = app(CustomerQueries::class)->findSummary($customer->id);
expect($summary?->personalIdentityCodeMasked)->toBe('••••••-308T')
->and($summary?->hasPersonalIdentityCode())->toBeTrue()
->and(serialize($summary))->not->toContain('131052');
});
it('shows the full code only to admins and management', function (string $role, bool $full) {
$this->actingAs(User::factory()->create());
$customer = registerConsumerWithCode();
$response = $this->actingAs(User::factory()->{$role}()->create())->get(route('customers.show', $customer->id))->assertOk();
if ($full) {
$response->assertSee('131052-308T');
} else {
$response->assertSee('••••••-308T')->assertDontSee('131052');
}
})->with([
'admin' => ['admin', true],
'management' => ['management', true],
'employee' => ['employee', false],
'intern' => ['intern', false],
]);
it('tells when a consumer has no code yet', function () {
$this->actingAs(User::factory()->create());
$customer = CustomerModel::factory()->consumer()->create();
$this->get(route('customers.show', $customer->id))->assertSee('Ei annettu – tarvitaan laskutukseen');
});
it('never fills the form with the code, and keeps it when the field is left empty', function () {
$this->actingAs(User::factory()->create());
$customer = registerConsumerWithCode();
$this->get(route('customers.edit', $customer->id))
->assertSee('Tallennettu: ••••••-308T.')
->assertDontSee('131052');
Livewire::test('customers::form', ['customer' => $customer->id])
->assertSet('form.personal_identity_code', '')
->set('form.name', 'Maija M.')
->call('save')
->assertHasNoErrors();
expect($customer->fresh()->personal_identity_code)->toBe('131052-308T');
});
it('lets management remove the code, but not an employee', function () {
$this->actingAs(User::factory()->create());
$customer = registerConsumerWithCode();
Livewire::test('customers::form', ['customer' => $customer->id])
->assertDontSee('Poista tallennettu henkilötunnus')
->set('form.remove_personal_identity_code', true)
->call('save')
->assertForbidden();
expect($customer->fresh()->personal_identity_code)->toBe('131052-308T');
Livewire::actingAs(User::factory()->management()->create())
->test('customers::form', ['customer' => $customer->id])
->assertSee('Poista tallennettu henkilötunnus')
->set('form.remove_personal_identity_code', true)
->call('save')
->assertHasNoErrors();
expect($customer->fresh()->personal_identity_code)->toBeNull()
->and($customer->fresh()->personal_identity_code_hash)->toBeNull();
});
it('shows code errors in Finnish without repeating the code', function (string $code, string $message) {
$this->actingAs(User::factory()->create());
if ($message === 'Tällä henkilötunnuksella on jo asiakas.') {
registerConsumerWithCode();
}
Livewire::test('customers::form')
->set('form.name', 'Pekka')
->set('form.type', CustomerType::Consumer->value)
->set('form.personal_identity_code', $code)
->call('save')
->assertHasErrors(['form.personal_identity_code'])
->assertSee($message);
})->with([
'invalid' => ['131052-308U', 'Henkilötunnus ei ole kelvollinen.'],
'taken' => ['131052-308t', 'Tällä henkilötunnuksella on jo asiakas.'],
]);
it('drops the code when a consumer becomes a company', function () {
$this->actingAs(User::factory()->create());
$customer = registerConsumerWithCode();
Livewire::test('customers::form', ['customer' => $customer->id])
->set('form.type', CustomerType::Company->value)
->call('save')
->assertHasNoErrors();
expect($customer->fresh()->personal_identity_code)->toBeNull();
});
@@ -0,0 +1,104 @@
<?php
use App\Modules\Customers\Application\DTOs\BillingUnitData;
use App\Modules\Customers\Application\DTOs\ContactData;
use App\Modules\Customers\Application\UseCases\AddBillingUnit;
use App\Modules\Customers\Application\UseCases\AddContact;
use App\Modules\Customers\Application\UseCases\RemoveBillingUnit;
use App\Modules\Customers\Application\UseCases\RemoveContact;
use App\Modules\Customers\Application\UseCases\UpdateBillingUnit;
use App\Modules\Customers\Application\UseCases\UpdateContact;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound;
use App\Modules\Customers\Domain\Exceptions\ContactNotFound;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\Exceptions\EInvoiceOperatorRequired;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryBillingUnitRepository;
use Tests\Fakes\InMemoryCustomerContactRepository;
use Tests\Fakes\InMemoryCustomerRepository;
beforeEach(function () {
$this->customers = new InMemoryCustomerRepository;
$this->contacts = new InMemoryCustomerContactRepository;
$this->billingUnits = new InMemoryBillingUnitRepository;
$transactions = new FakeTransactionManager;
$this->addContact = new AddContact($this->customers, $this->contacts, $transactions);
$this->updateContact = new UpdateContact($this->contacts, $transactions);
$this->removeContact = new RemoveContact($this->contacts, $transactions);
$this->addBillingUnit = new AddBillingUnit($this->customers, $this->billingUnits, $transactions);
$this->updateBillingUnit = new UpdateBillingUnit($this->billingUnits, $transactions);
$this->removeBillingUnit = new RemoveBillingUnit($this->billingUnits, $transactions);
$this->customerId = $this->customers->save(Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company))->id();
$this->otherCustomerId = $this->customers->save(Customer::register(new CustomerName('Toinen Oy'), CustomerType::Company))->id();
});
it('adds, changes and removes a contact', function () {
$contactId = $this->addContact->execute($this->customerId, new ContactData('Maija', 'Markkinointi', '040 123 4567', '[email protected]'));
expect($this->contacts->findForCustomer($this->customerId, $contactId)?->email()?->value)->toBe('[email protected]');
$this->updateContact->execute($this->customerId, $contactId, new ContactData('Maija Meikäläinen'));
$contact = $this->contacts->findForCustomer($this->customerId, $contactId);
expect($contact?->name()->value)->toBe('Maija Meikäläinen')
->and($contact?->email())->toBeNull();
$this->removeContact->execute($this->customerId, $contactId);
expect($this->contacts->contacts)->toBeEmpty();
});
it('rejects an invalid contact email', function () {
$this->addContact->execute($this->customerId, new ContactData('Maija', email: 'maija@'));
})->throws(InvalidEmailAddress::class);
it('adds a contact or a billing unit only to a stored customer', function (string $useCase, object $data) {
$this->{$useCase}->execute(999, $data);
})->throws(CustomerNotFound::class)->with([
'contact' => ['addContact', new ContactData('Maija')],
'billing unit' => ['addBillingUnit', new BillingUnitData('Mainos Oy')],
]);
it('does not touch a contact of another customer', function (string $action) {
$contactId = $this->addContact->execute($this->otherCustomerId, new ContactData('Toisen kontakti'));
match ($action) {
'update' => $this->updateContact->execute($this->customerId, $contactId, new ContactData('Muutettu')),
'remove' => $this->removeContact->execute($this->customerId, $contactId),
};
})->throws(ContactNotFound::class)->with(['update', 'remove']);
it('adds, changes and removes a billing unit', function () {
$billingUnitId = $this->addBillingUnit->execute($this->customerId, new BillingUnitData('Mainos Oy', "Katu 1\n00100 Helsinki"));
$this->updateBillingUnit->execute($this->customerId, $billingUnitId, new BillingUnitData('Mainos Oy, markkinointi', null, '0037 1234 5678', '003721291126', 'PO-42'));
$billingUnit = $this->billingUnits->findForCustomer($this->customerId, $billingUnitId);
expect($billingUnit?->name()->value)->toBe('Mainos Oy, markkinointi')
->and($billingUnit?->billingAddress())->toBeNull()
->and($billingUnit?->eInvoiceAddress()?->value)->toBe('003712345678')
->and($billingUnit?->reference())->toBe('PO-42');
$this->removeBillingUnit->execute($this->customerId, $billingUnitId);
expect($this->billingUnits->billingUnits)->toBeEmpty();
});
it('rejects an e-invoice address without an operator', function () {
$this->addBillingUnit->execute($this->customerId, new BillingUnitData('Mainos Oy', eInvoiceAddress: '003712345678'));
})->throws(EInvoiceOperatorRequired::class);
it('does not touch a billing unit of another customer', function (string $action) {
$billingUnitId = $this->addBillingUnit->execute($this->otherCustomerId, new BillingUnitData('Toinen Oy'));
match ($action) {
'update' => $this->updateBillingUnit->execute($this->customerId, $billingUnitId, new BillingUnitData('Muutettu')),
'remove' => $this->removeBillingUnit->execute($this->customerId, $billingUnitId),
};
})->throws(BillingUnitNotFound::class)->with(['update', 'remove']);
@@ -0,0 +1,50 @@
<?php
use App\Modules\Customers\Application\DTOs\CustomerDetailsData;
use App\Modules\Customers\Application\UseCases\RegisterCustomer;
use App\Modules\Customers\Application\UseCases\UpdateCustomer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\PersonalIdentityCodeAlreadyInUse;
use Tests\Fakes\FakeEventDispatcher;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryCustomerRepository;
beforeEach(function () {
$this->customers = new InMemoryCustomerRepository;
$transactions = new FakeTransactionManager;
$this->registerCustomer = new RegisterCustomer($this->customers, $transactions, new FakeEventDispatcher);
$this->updateCustomer = new UpdateCustomer($this->customers, $transactions);
$this->customerId = $this->registerCustomer->execute(
new CustomerDetailsData('Maija Meikäläinen', CustomerType::Consumer, personalIdentityCode: '131052-308t'),
);
});
it('stores the normalised code of a consumer', function () {
expect($this->customers->findById($this->customerId)?->personalIdentityCode()?->value)->toBe('131052-308T');
});
it('rejects a code that belongs to another customer', function (string $useCase) {
match ($useCase) {
'register' => $this->registerCustomer->execute(new CustomerDetailsData('Toinen', CustomerType::Consumer, personalIdentityCode: '131052-308T')),
'update' => $this->updateCustomer->execute(
$this->registerCustomer->execute(new CustomerDetailsData('Toinen', CustomerType::Consumer)),
new CustomerDetailsData('Toinen', CustomerType::Consumer, personalIdentityCode: '131052-308T'),
),
};
})->throws(PersonalIdentityCodeAlreadyInUse::class)->with(['register', 'update']);
it('keeps the stored code when the form leaves it empty, and lets the customer keep its own code', function () {
$this->updateCustomer->execute($this->customerId, new CustomerDetailsData('Maija M.', CustomerType::Consumer));
$this->updateCustomer->execute($this->customerId, new CustomerDetailsData('Maija M.', CustomerType::Consumer, personalIdentityCode: '131052-308T'));
expect($this->customers->findById($this->customerId)?->personalIdentityCode()?->value)->toBe('131052-308T');
});
it('removes the code when asked, unless a new code is given', function () {
$this->updateCustomer->execute($this->customerId, new CustomerDetailsData('Maija', CustomerType::Consumer, personalIdentityCode: '010594Y9032', removePersonalIdentityCode: true));
expect($this->customers->findById($this->customerId)?->personalIdentityCode()?->value)->toBe('010594Y9032');
$this->updateCustomer->execute($this->customerId, new CustomerDetailsData('Maija', CustomerType::Consumer, removePersonalIdentityCode: true));
expect($this->customers->findById($this->customerId)?->personalIdentityCode())->toBeNull();
});
@@ -0,0 +1,58 @@
<?php
use App\Modules\Customers\Domain\Entities\BillingUnit;
use App\Modules\Customers\Domain\Entities\CustomerContact;
use App\Modules\Customers\Domain\Exceptions\EInvoiceOperatorRequired;
use App\Modules\Customers\Domain\Exceptions\InvalidBillingUnitName;
use App\Modules\Customers\Domain\Exceptions\InvalidContactName;
use App\Modules\Customers\Domain\Exceptions\InvalidEInvoiceAddress;
use App\Modules\Customers\Domain\ValueObjects\BillingUnitName;
use App\Modules\Customers\Domain\ValueObjects\ContactName;
use App\Modules\Customers\Domain\ValueObjects\EInvoiceAddress;
it('normalises an e-invoice address', function (string $input, string $expected) {
expect((new EInvoiceAddress($input))->value)->toBe($expected);
})->with([
'OVT with spaces' => ['0037 1234 5678', '003712345678'],
'IBAN in lower case' => ['fi49 5000 9420 0287 30', 'FI4950009420028730'],
]);
it('rejects an e-invoice address that is too short or has other characters', function (string $input) {
new EInvoiceAddress($input);
})->throws(InvalidEInvoiceAddress::class)->with(['00371234', '0037-1234-5678', '', str_repeat('1', 36)]);
it('rejects an empty or too long contact or billing unit name', function (string $class, string $exception, string $name) {
expect(fn () => new $class($name))->toThrow($exception);
})->with([
'contact, empty' => [ContactName::class, InvalidContactName::class, ' '],
'contact, too long' => [ContactName::class, InvalidContactName::class, str_repeat('a', 256)],
'billing unit, empty' => [BillingUnitName::class, InvalidBillingUnitName::class, ''],
'billing unit, too long' => [BillingUnitName::class, InvalidBillingUnitName::class, str_repeat('a', 256)],
]);
it('stores empty optional contact fields as none', function () {
$contact = CustomerContact::create(1, new ContactName('Maija Meikäläinen'), ' ', '', null, " Soita aamulla \n");
expect($contact->title())->toBeNull()
->and($contact->phone())->toBeNull()
->and($contact->note())->toBe('Soita aamulla');
});
it('requires an operator for an e-invoice address', function () {
BillingUnit::create(1, new BillingUnitName('Mainos Oy'), null, new EInvoiceAddress('003712345678'), ' ');
})->throws(EInvoiceOperatorRequired::class);
it('requires an operator when an e-invoice address is added later', function () {
$billingUnit = BillingUnit::create(1, new BillingUnitName('Mainos Oy'), "Katu 1\n00100 Helsinki");
expect(fn () => $billingUnit->changeDetails(new BillingUnitName('Mainos Oy'), null, new EInvoiceAddress('003712345678'), null, null))
->toThrow(EInvoiceOperatorRequired::class)
->and($billingUnit->eInvoiceAddress())->toBeNull()
->and($billingUnit->billingAddress())->toBe("Katu 1\n00100 Helsinki");
});
it('normalises the operator code', function () {
$billingUnit = BillingUnit::create(1, new BillingUnitName('Mainos Oy'), null, new EInvoiceAddress('003712345678'), ' ndea fihh ');
expect($billingUnit->eInvoiceOperator())->toBe('NDEAFIHH');
});
@@ -0,0 +1,59 @@
<?php
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\CompanyCannotHavePersonalIdentityCode;
use App\Modules\Customers\Domain\Exceptions\InvalidPersonalIdentityCode;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
it('accepts valid personal identity codes of every century', function (string $code) {
expect((new PersonalIdentityCode($code))->value)->toBe($code);
})->with([
'1900s, hyphen' => '131052-308T',
'1900s, new sign Y' => '010594Y9032',
'1800s' => '010185+123B',
'2000s, leap day' => '290200A4561',
'2000s, new sign E' => '020502E902X',
]);
it('normalises spaces and lower case', function () {
expect((new PersonalIdentityCode(' 020502e902x '))->value)->toBe('020502E902X');
});
it('rejects a wrong check character, an impossible date or a wrong format', function (string $code) {
new PersonalIdentityCode($code);
})->throws(InvalidPersonalIdentityCode::class)->with([
'wrong check character' => '131052-308U',
'no such day (29.2.2001)' => '290201A4569',
'no such day (31.4.1952)' => '310452-308K',
'unknown century sign' => '131052G308T',
'too short' => '131052-30T',
'empty' => '',
]);
it('keeps the code out of the exception message', function () {
try {
new PersonalIdentityCode('131052-308U');
} catch (InvalidPersonalIdentityCode $exception) {
expect($exception->getMessage())->not->toContain('131052');
}
});
it('masks the date of birth', function () {
expect((new PersonalIdentityCode('131052-308T'))->masked())->toBe('••••••-308T');
});
it('gives a personal identity code only to a consumer', function () {
Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company, null, new PersonalIdentityCode('131052-308T'));
})->throws(CompanyCannotHavePersonalIdentityCode::class);
it('keeps the stored code when no new one is given, and drops it when the customer becomes a company', function () {
$customer = Customer::register(new CustomerName('Maija'), CustomerType::Consumer, null, new PersonalIdentityCode('131052-308T'));
$customer->changeDetails(new CustomerName('Maija Meikäläinen'), CustomerType::Consumer, null);
expect($customer->personalIdentityCode()?->value)->toBe('131052-308T');
$customer->changeDetails(new CustomerName('Maijan Kuvaamo Oy'), CustomerType::Company, null);
expect($customer->personalIdentityCode())->toBeNull();
});
@@ -1,5 +1,6 @@
<?php
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Application\DTOs\UserAccountData;
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
use App\Modules\Users\Application\UseCases\CreateUserAccount;
@@ -13,7 +14,6 @@ use App\Modules\Users\Domain\Exceptions\LastAdminCannotBeRemoved;
use App\Modules\Users\Domain\Exceptions\SupervisorHasInterns;
use App\Modules\Users\Domain\Exceptions\UserAccountNotFound;
use App\Modules\Users\Domain\Services\SupervisorRule;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\ValueObjects\PersonName;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakePasswordLinkSender;
@@ -1,10 +1,10 @@
<?php
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\Entities\UserAccount;
use App\Modules\Users\Domain\Enums\Role;
use App\Modules\Users\Domain\Exceptions\InternRequiresEndDateAndSupervisor;
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\ValueObjects\PersonName;
function makeIntern(?string $endsOn = '2027-05-31', ?int $supervisorId = 1): UserAccount
@@ -1,9 +1,9 @@
<?php
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\Enums\Role;
use App\Modules\Users\Domain\Exceptions\InvalidEmailAddress;
use App\Modules\Users\Domain\Exceptions\InvalidPersonName;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\ValueObjects\PersonName;
it('normalises an email address to lower case', function () {