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
+4 -1
View File
@@ -38,12 +38,15 @@ Accessibility is a contractual acceptance criterion. It covers the whole UI: nav
- `<x-theme-switch>`: unnamed `role="switch"`. Use `resources/views/partials/theme-toggle.blade.php`, which drives `tallstackui_darkTheme({ default: 'system' })` on `<html>` (localStorage `dark-theme`; an inline script in the layout applies it before paint).
- `<tallstackui:script />`: root-relative asset URLs that 404 in a subfolder (local XAMPP). The layout includes `resources/views/partials/tallstackui-script.blade.php` instead.
- `<x-select.native>`: the label is not tied to the control, so also pass `:aria-label` with the same text.
- `<x-modal>`: `aria-labelledby` points at an id its title lacks, the close button has no name, and focus neither moves in nor returns. Use `<x-confirm-dialog>` (`resources/views/components/confirm-dialog.blade.php`, native `<dialog>` + `showModal()`), opened from Livewire with `$this->js("document.getElementById('<id>').showModal()")`; see `customers::show`.
- Solid `color="red"` buttons: white on red-500 is 3.5:1, so the solid red is red-700 in the published `NormalButtonColors`.
- `<x-input>` without `wire:model` (e.g. a read-only value): pass an explicit `id`, or the label is not tied to it. `<x-clipboard>` has an unlabelled input and a button whose name changes; build copy fields from `<x-input readonly>` + `<x-button>` + a `role="status"` message instead (see `users::form`).
- Contrast: the primary palette is one step darker (`resources/css/app.css`); error text, label error and asterisk, and input/select error colours are changed by soft customization in `App\Providers\AppServiceProvider`; light alert and link text colours are in published colour classes `app/View/Components/TallStackUi/Colors/`. `flat` and `outline` buttons have no dark-mode text colour: use `subtle color="black"` for neutral buttons.
- Finnish strings for TallStackUI's own components are in `lang/vendor/ts-ui/fi/messages.php`.
- **Personal identity codes** (*henkilötunnus*, consumer customers) are sensitive personal data: stored encrypted (`encrypted` cast, `$hidden`) with an HMAC blind index for duplicates, never in `CustomerSummary`, search, logs, exception messages or Livewire public properties, and shown in full only behind `customers.view-personal-identity-code` (admin, management) via `CustomerQueries::personalIdentityCodeOf()`; everyone else sees `masked()`.
- Never convey meaning by colour alone. Statuses, priorities (e.g. *kiire* = red), errors and warnings always also have visible text or an icon with text.
- Announce dynamic changes: put status text in `role="status"` / `aria-live="polite"` (errors: `role="alert"`), or a TallStackUI toast (`<x-toast />` must then be added to the layout). Keep button names stable instead of putting changing state in them.
- Make everything work with the keyboard alone, with a visible focus indicator and no focus traps. Use `<x-modal>` for dialogs and check that focus moves in and returns.
- Make everything work with the keyboard alone, with a visible focus indicator and no focus traps. Use `<x-confirm-dialog>` for dialogs (not `<x-modal>`, see above) and check that focus moves in and returns.
- The layout (`resources/views/layouts/app.blade.php`) provides a skip link and a `<main id="main-content">` landmark. Keep them, and add `<nav aria-label="…">` for navigation.
- One `h1` per page, logical heading order, and a descriptive page `#[Title]` on every page component.
- Data tables use `<x-table>` with `headers` (custom cells with `@interact('column_<index>', $row)`). Icon-only buttons need an `aria-label` (a `tooltip` alone is not a name). Decorative images get `alt=""`.
@@ -4,6 +4,8 @@ declare(strict_types=1);
namespace App\Modules\Customers\Application\Contracts;
use App\Modules\Customers\Application\DTOs\BillingUnitSummary;
use App\Modules\Customers\Application\DTOs\ContactSummary;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
@@ -15,6 +17,12 @@ interface CustomerQueries
{
public function findSummary(int $id): ?CustomerSummary;
/**
* The full personal identity code. Sensitive: call only after checking
* the customers.view-personal-identity-code ability, and never log it.
*/
public function personalIdentityCodeOf(int $customerId): ?string;
/**
* Customers ordered by name, filtered by a name or business ID fragment.
*
@@ -28,4 +36,28 @@ interface CustomerQueries
* @return list<CustomerSummary>
*/
public function search(string $term, int $limit = 10): array;
/**
* The customer's contacts ordered by name.
*
* @return list<ContactSummary>
*/
public function contactsOf(int $customerId): array;
/**
* Null when the contact does not exist or belongs to another customer.
*/
public function findContact(int $customerId, int $contactId): ?ContactSummary;
/**
* The customer's billing units ordered by name.
*
* @return list<BillingUnitSummary>
*/
public function billingUnitsOf(int $customerId): array;
/**
* Null when the billing unit does not exist or belongs to another customer.
*/
public function findBillingUnit(int $customerId, int $billingUnitId): ?BillingUnitSummary;
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\DTOs;
/**
* Input for adding a billing unit or changing its details.
*/
final readonly class BillingUnitData
{
public function __construct(
public string $name,
public ?string $billingAddress = null,
public ?string $eInvoiceAddress = null,
public ?string $eInvoiceOperator = null,
public ?string $reference = null,
) {}
/**
* @param array{name: string, billing_address?: string|null, e_invoice_address?: string|null, e_invoice_operator?: string|null, reference?: string|null} $data
*/
public static function fromArray(array $data): self
{
$eInvoiceAddress = trim($data['e_invoice_address'] ?? '');
return new self(
name: $data['name'],
billingAddress: $data['billing_address'] ?? null,
eInvoiceAddress: $eInvoiceAddress === '' ? null : $eInvoiceAddress,
eInvoiceOperator: $data['e_invoice_operator'] ?? null,
reference: $data['reference'] ?? null,
);
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\DTOs;
/**
* Read model of a customer's billing unit.
*/
final readonly class BillingUnitSummary
{
public function __construct(
public int $id,
public int $customerId,
public string $name,
public ?string $billingAddress,
public ?string $eInvoiceAddress,
public ?string $eInvoiceOperator,
public ?string $reference,
) {}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\DTOs;
/**
* Input for adding a contact or changing its details.
*/
final readonly class ContactData
{
public function __construct(
public string $name,
public ?string $title = null,
public ?string $phone = null,
public ?string $email = null,
public ?string $note = null,
) {}
/**
* @param array{name: string, title?: string|null, phone?: string|null, email?: string|null, note?: string|null} $data
*/
public static function fromArray(array $data): self
{
$email = trim($data['email'] ?? '');
return new self(
name: $data['name'],
title: $data['title'] ?? null,
phone: $data['phone'] ?? null,
email: $email === '' ? null : $email,
note: $data['note'] ?? null,
);
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\DTOs;
/**
* Read model of a customer's contact person.
*/
final readonly class ContactSummary
{
public function __construct(
public int $id,
public int $customerId,
public string $name,
public ?string $title,
public ?string $phone,
public ?string $email,
public ?string $note,
) {}
}
@@ -8,6 +8,9 @@ use App\Modules\Customers\Domain\Enums\CustomerType;
/**
* Input for registering a customer or changing its details.
*
* The personal identity code is never shown back in a form, so null means
* "keep the stored code"; removing it is asked for explicitly.
*/
final readonly class CustomerDetailsData
{
@@ -15,19 +18,24 @@ final readonly class CustomerDetailsData
public string $name,
public CustomerType $type,
public ?string $businessId = null,
public ?string $personalIdentityCode = null,
public bool $removePersonalIdentityCode = false,
) {}
/**
* @param array{name: string, type: string|CustomerType, business_id?: string|null} $data
* @param array{name: string, type: string|CustomerType, business_id?: string|null, personal_identity_code?: string|null, remove_personal_identity_code?: bool} $data
*/
public static function fromArray(array $data): self
{
$businessId = isset($data['business_id']) ? trim($data['business_id']) : null;
$personalIdentityCode = isset($data['personal_identity_code']) ? trim($data['personal_identity_code']) : null;
return new self(
name: $data['name'],
type: $data['type'] instanceof CustomerType ? $data['type'] : CustomerType::from($data['type']),
businessId: $businessId === '' ? null : $businessId,
personalIdentityCode: $personalIdentityCode === '' ? null : $personalIdentityCode,
removePersonalIdentityCode: $data['remove_personal_identity_code'] ?? false,
);
}
}
@@ -8,6 +8,10 @@ use App\Modules\Customers\Domain\Enums\CustomerType;
/**
* Read model of a customer for lists, search and other modules.
*
* Never carries the full personal identity code, only whether there is
* one and its masked form. The full code comes from
* CustomerQueries::personalIdentityCodeOf() after a permission check.
*/
final readonly class CustomerSummary
{
@@ -16,5 +20,11 @@ final readonly class CustomerSummary
public string $name,
public CustomerType $type,
public ?string $businessId,
public ?string $personalIdentityCodeMasked = null,
) {}
public function hasPersonalIdentityCode(): bool
{
return $this->personalIdentityCodeMasked !== null;
}
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases;
use App\Modules\Customers\Application\DTOs\BillingUnitData;
use App\Modules\Customers\Domain\Contracts\BillingUnitRepository;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Entities\BillingUnit;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\Exceptions\EInvoiceOperatorRequired;
use App\Modules\Customers\Domain\ValueObjects\BillingUnitName;
use App\Modules\Customers\Domain\ValueObjects\EInvoiceAddress;
use App\Modules\Shared\Application\Contracts\TransactionManager;
final class AddBillingUnit
{
public function __construct(
private CustomerRepository $customers,
private BillingUnitRepository $billingUnits,
private TransactionManager $transactions,
) {}
/**
* @return int The new billing unit's id.
*
* @throws CustomerNotFound
* @throws EInvoiceOperatorRequired
*/
public function execute(int $customerId, BillingUnitData $data): int
{
$billingUnit = BillingUnit::create(
$customerId,
new BillingUnitName($data->name),
$data->billingAddress,
$data->eInvoiceAddress === null ? null : new EInvoiceAddress($data->eInvoiceAddress),
$data->eInvoiceOperator,
$data->reference,
);
return $this->transactions->run(function () use ($customerId, $billingUnit): int {
if ($this->customers->findById($customerId) === null) {
throw new CustomerNotFound($customerId);
}
return (int) $this->billingUnits->save($billingUnit)->id();
});
}
}
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases;
use App\Modules\Customers\Application\DTOs\ContactData;
use App\Modules\Customers\Domain\Contracts\CustomerContactRepository;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Entities\CustomerContact;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\ValueObjects\ContactName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
final class AddContact
{
public function __construct(
private CustomerRepository $customers,
private CustomerContactRepository $contacts,
private TransactionManager $transactions,
) {}
/**
* @return int The new contact's id.
*
* @throws CustomerNotFound
*/
public function execute(int $customerId, ContactData $data): int
{
$contact = CustomerContact::create(
$customerId,
new ContactName($data->name),
$data->title,
$data->phone,
$data->email === null ? null : new EmailAddress($data->email),
$data->note,
);
return $this->transactions->run(function () use ($customerId, $contact): int {
if ($this->customers->findById($customerId) === null) {
throw new CustomerNotFound($customerId);
}
return (int) $this->contacts->save($contact)->id();
});
}
}
@@ -9,8 +9,10 @@ use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Events\CustomerRegistered;
use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse;
use App\Modules\Customers\Domain\Exceptions\PersonalIdentityCodeAlreadyInUse;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
use App\Modules\Shared\Application\Contracts\EventDispatcher;
use App\Modules\Shared\Application\Contracts\TransactionManager;
@@ -26,17 +28,23 @@ final class RegisterCustomer
* @return int The new customer's id.
*
* @throws BusinessIdAlreadyInUse
* @throws PersonalIdentityCodeAlreadyInUse
*/
public function execute(CustomerDetailsData $data): int
{
$businessId = $data->businessId === null ? null : new BusinessId($data->businessId);
$customer = Customer::register(new CustomerName($data->name), $data->type, $businessId);
$personalIdentityCode = $data->personalIdentityCode === null ? null : new PersonalIdentityCode($data->personalIdentityCode);
$customer = Customer::register(new CustomerName($data->name), $data->type, $businessId, $personalIdentityCode);
return $this->transactions->run(function () use ($customer, $businessId): int {
return $this->transactions->run(function () use ($customer, $businessId, $personalIdentityCode): int {
if ($businessId !== null && $this->customers->isBusinessIdTaken($businessId)) {
throw new BusinessIdAlreadyInUse($businessId);
}
if ($personalIdentityCode !== null && $this->customers->isPersonalIdentityCodeTaken($personalIdentityCode)) {
throw new PersonalIdentityCodeAlreadyInUse;
}
$customerId = (int) $this->customers->save($customer)->id();
$this->events->dispatch(new CustomerRegistered($customerId));
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases;
use App\Modules\Customers\Domain\Contracts\BillingUnitRepository;
use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Deletes a billing unit. Nothing refers to billing units yet; once customer
* jobs and invoices do, a billing unit in use cannot be removed.
*/
final class RemoveBillingUnit
{
public function __construct(
private BillingUnitRepository $billingUnits,
private TransactionManager $transactions,
) {}
/**
* @throws BillingUnitNotFound
*/
public function execute(int $customerId, int $billingUnitId): void
{
$this->transactions->run(function () use ($customerId, $billingUnitId): void {
$billingUnit = $this->billingUnits->findForCustomer($customerId, $billingUnitId)
?? throw new BillingUnitNotFound($customerId, $billingUnitId);
$this->billingUnits->delete($billingUnit);
});
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases;
use App\Modules\Customers\Domain\Contracts\CustomerContactRepository;
use App\Modules\Customers\Domain\Exceptions\ContactNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Deletes a contact. Nothing refers to contacts yet; once customer jobs do,
* a contact in use cannot be removed.
*/
final class RemoveContact
{
public function __construct(
private CustomerContactRepository $contacts,
private TransactionManager $transactions,
) {}
/**
* @throws ContactNotFound
*/
public function execute(int $customerId, int $contactId): void
{
$this->transactions->run(function () use ($customerId, $contactId): void {
$contact = $this->contacts->findForCustomer($customerId, $contactId)
?? throw new ContactNotFound($customerId, $contactId);
$this->contacts->delete($contact);
});
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases;
use App\Modules\Customers\Application\DTOs\BillingUnitData;
use App\Modules\Customers\Domain\Contracts\BillingUnitRepository;
use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound;
use App\Modules\Customers\Domain\Exceptions\EInvoiceOperatorRequired;
use App\Modules\Customers\Domain\ValueObjects\BillingUnitName;
use App\Modules\Customers\Domain\ValueObjects\EInvoiceAddress;
use App\Modules\Shared\Application\Contracts\TransactionManager;
final class UpdateBillingUnit
{
public function __construct(
private BillingUnitRepository $billingUnits,
private TransactionManager $transactions,
) {}
/**
* @throws BillingUnitNotFound
* @throws EInvoiceOperatorRequired
*/
public function execute(int $customerId, int $billingUnitId, BillingUnitData $data): void
{
$name = new BillingUnitName($data->name);
$eInvoiceAddress = $data->eInvoiceAddress === null ? null : new EInvoiceAddress($data->eInvoiceAddress);
$this->transactions->run(function () use ($customerId, $billingUnitId, $name, $eInvoiceAddress, $data): void {
$billingUnit = $this->billingUnits->findForCustomer($customerId, $billingUnitId)
?? throw new BillingUnitNotFound($customerId, $billingUnitId);
$billingUnit->changeDetails($name, $data->billingAddress, $eInvoiceAddress, $data->eInvoiceOperator, $data->reference);
$this->billingUnits->save($billingUnit);
});
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases;
use App\Modules\Customers\Application\DTOs\ContactData;
use App\Modules\Customers\Domain\Contracts\CustomerContactRepository;
use App\Modules\Customers\Domain\Exceptions\ContactNotFound;
use App\Modules\Customers\Domain\ValueObjects\ContactName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
final class UpdateContact
{
public function __construct(
private CustomerContactRepository $contacts,
private TransactionManager $transactions,
) {}
/**
* @throws ContactNotFound
*/
public function execute(int $customerId, int $contactId, ContactData $data): void
{
$name = new ContactName($data->name);
$email = $data->email === null ? null : new EmailAddress($data->email);
$this->transactions->run(function () use ($customerId, $contactId, $name, $email, $data): void {
$contact = $this->contacts->findForCustomer($customerId, $contactId)
?? throw new ContactNotFound($customerId, $contactId);
$contact->changeDetails($name, $data->title, $data->phone, $email, $data->note);
$this->contacts->save($contact);
});
}
}
@@ -8,10 +8,16 @@ use App\Modules\Customers\Application\DTOs\CustomerDetailsData;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\Exceptions\PersonalIdentityCodeAlreadyInUse;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Changes a customer's details. Who may remove a personal identity code is
* decided by the caller (only users who may see the code).
*/
final class UpdateCustomer
{
public function __construct(
@@ -22,20 +28,30 @@ final class UpdateCustomer
/**
* @throws CustomerNotFound
* @throws BusinessIdAlreadyInUse
* @throws PersonalIdentityCodeAlreadyInUse
*/
public function execute(int $customerId, CustomerDetailsData $data): void
{
$name = new CustomerName($data->name);
$businessId = $data->businessId === null ? null : new BusinessId($data->businessId);
$personalIdentityCode = $data->personalIdentityCode === null ? null : new PersonalIdentityCode($data->personalIdentityCode);
$this->transactions->run(function () use ($customerId, $name, $data, $businessId): void {
$this->transactions->run(function () use ($customerId, $name, $data, $businessId, $personalIdentityCode): void {
$customer = $this->customers->findById($customerId) ?? throw new CustomerNotFound($customerId);
if ($businessId !== null && $this->customers->isBusinessIdTaken($businessId, $customerId)) {
throw new BusinessIdAlreadyInUse($businessId);
}
$customer->changeDetails($name, $data->type, $businessId);
if ($personalIdentityCode !== null && $this->customers->isPersonalIdentityCodeTaken($personalIdentityCode, $customerId)) {
throw new PersonalIdentityCodeAlreadyInUse;
}
if ($data->removePersonalIdentityCode && $personalIdentityCode === null) {
$customer->removePersonalIdentityCode();
}
$customer->changeDetails($name, $data->type, $businessId, $personalIdentityCode);
$this->customers->save($customer);
});
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Contracts;
use App\Modules\Customers\Domain\Entities\BillingUnit;
interface BillingUnitRepository
{
/**
* Null when the billing unit does not exist or belongs to another customer.
*/
public function findForCustomer(int $customerId, int $billingUnitId): ?BillingUnit;
/**
* Inserts a new billing unit or updates a stored one, and returns the
* stored billing unit (a new one gets its id here).
*/
public function save(BillingUnit $billingUnit): BillingUnit;
public function delete(BillingUnit $billingUnit): void;
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Contracts;
use App\Modules\Customers\Domain\Entities\CustomerContact;
interface CustomerContactRepository
{
/**
* Null when the contact does not exist or belongs to another customer.
*/
public function findForCustomer(int $customerId, int $contactId): ?CustomerContact;
/**
* Inserts a new contact or updates a stored one, and returns the stored
* contact (a new one gets its id here).
*/
public function save(CustomerContact $contact): CustomerContact;
public function delete(CustomerContact $contact): void;
}
@@ -6,6 +6,7 @@ namespace App\Modules\Customers\Domain\Contracts;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
interface CustomerRepository
{
@@ -18,4 +19,6 @@ interface CustomerRepository
public function save(Customer $customer): Customer;
public function isBusinessIdTaken(BusinessId $businessId, ?int $exceptCustomerId = null): bool;
public function isPersonalIdentityCodeTaken(PersonalIdentityCode $code, ?int $exceptCustomerId = null): bool;
}
@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Entities;
use App\Modules\Customers\Domain\Exceptions\EInvoiceOperatorRequired;
use App\Modules\Customers\Domain\ValueObjects\BillingUnitName;
use App\Modules\Customers\Domain\ValueObjects\EInvoiceAddress;
/**
* A billing unit (laskutusyksikkö) of a customer. Each billing unit gets
* its own invoices, and a customer job picks one.
*/
final class BillingUnit
{
private function __construct(
private ?int $id,
private int $customerId,
private BillingUnitName $name,
private ?string $billingAddress,
private ?EInvoiceAddress $eInvoiceAddress,
private ?string $eInvoiceOperator,
private ?string $reference,
) {
self::ensureOperatorForEInvoice($eInvoiceAddress, $eInvoiceOperator);
}
/**
* A new billing unit that is not stored yet, so it has no id.
*
* @throws EInvoiceOperatorRequired
*/
public static function create(
int $customerId,
BillingUnitName $name,
?string $billingAddress = null,
?EInvoiceAddress $eInvoiceAddress = null,
?string $eInvoiceOperator = null,
?string $reference = null,
): self {
return new self(
null,
$customerId,
$name,
OptionalText::from($billingAddress),
$eInvoiceAddress,
self::normaliseOperator($eInvoiceOperator),
OptionalText::from($reference),
);
}
/**
* Rebuilds a stored billing unit. Used only by repositories.
*/
public static function reconstitute(
int $id,
int $customerId,
BillingUnitName $name,
?string $billingAddress,
?EInvoiceAddress $eInvoiceAddress,
?string $eInvoiceOperator,
?string $reference,
): self {
return new self($id, $customerId, $name, $billingAddress, $eInvoiceAddress, $eInvoiceOperator, $reference);
}
/**
* @throws EInvoiceOperatorRequired
*/
public function changeDetails(
BillingUnitName $name,
?string $billingAddress,
?EInvoiceAddress $eInvoiceAddress,
?string $eInvoiceOperator,
?string $reference,
): void {
$eInvoiceOperator = self::normaliseOperator($eInvoiceOperator);
self::ensureOperatorForEInvoice($eInvoiceAddress, $eInvoiceOperator);
$this->name = $name;
$this->billingAddress = OptionalText::from($billingAddress);
$this->eInvoiceAddress = $eInvoiceAddress;
$this->eInvoiceOperator = $eInvoiceOperator;
$this->reference = OptionalText::from($reference);
}
public function id(): ?int
{
return $this->id;
}
public function customerId(): int
{
return $this->customerId;
}
public function name(): BillingUnitName
{
return $this->name;
}
public function billingAddress(): ?string
{
return $this->billingAddress;
}
public function eInvoiceAddress(): ?EInvoiceAddress
{
return $this->eInvoiceAddress;
}
public function eInvoiceOperator(): ?string
{
return $this->eInvoiceOperator;
}
public function reference(): ?string
{
return $this->reference;
}
/**
* Operator codes such as 003721291126 or NDEAFIHH: no spaces, upper case.
*/
private static function normaliseOperator(?string $operator): ?string
{
$operator = OptionalText::from($operator);
return $operator === null ? null : strtoupper(preg_replace('/\s+/', '', $operator) ?? $operator);
}
private static function ensureOperatorForEInvoice(?EInvoiceAddress $address, ?string $operator): void
{
if ($address !== null && $operator === null) {
throw new EInvoiceOperatorRequired;
}
}
}
@@ -5,14 +5,17 @@ declare(strict_types=1);
namespace App\Modules\Customers\Domain\Entities;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\CompanyCannotHavePersonalIdentityCode;
use App\Modules\Customers\Domain\Exceptions\ConsumerCannotHaveBusinessId;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
/**
* A customer of the company: a business or a private consumer.
*
* Only the name is needed at job intake; other details are added later.
* A consumer who is invoiced needs a personal identity code.
*/
final class Customer
{
@@ -21,33 +24,61 @@ final class Customer
private CustomerName $name,
private CustomerType $type,
private ?BusinessId $businessId,
private ?PersonalIdentityCode $personalIdentityCode,
) {
self::ensureBusinessIdFitsType($type, $businessId);
self::ensureIdentifiersFitType($type, $businessId, $personalIdentityCode);
}
/**
* A new customer that is not stored yet, so it has no id.
*/
public static function register(CustomerName $name, CustomerType $type, ?BusinessId $businessId = null): self
{
return new self(null, $name, $type, $businessId);
public static function register(
CustomerName $name,
CustomerType $type,
?BusinessId $businessId = null,
?PersonalIdentityCode $personalIdentityCode = null,
): self {
return new self(null, $name, $type, $businessId, $personalIdentityCode);
}
/**
* Rebuilds a stored customer. Used only by repositories.
*/
public static function reconstitute(int $id, CustomerName $name, CustomerType $type, ?BusinessId $businessId): self
{
return new self($id, $name, $type, $businessId);
public static function reconstitute(
int $id,
CustomerName $name,
CustomerType $type,
?BusinessId $businessId,
?PersonalIdentityCode $personalIdentityCode = null,
): self {
return new self($id, $name, $type, $businessId, $personalIdentityCode);
}
public function changeDetails(CustomerName $name, CustomerType $type, ?BusinessId $businessId): void
{
self::ensureBusinessIdFitsType($type, $businessId);
/**
* Changes the details. A null personal identity code keeps the stored
* one, except that a company never keeps one.
*/
public function changeDetails(
CustomerName $name,
CustomerType $type,
?BusinessId $businessId,
?PersonalIdentityCode $personalIdentityCode = null,
): void {
if ($personalIdentityCode === null && $type === CustomerType::Consumer) {
$personalIdentityCode = $this->personalIdentityCode;
}
self::ensureIdentifiersFitType($type, $businessId, $personalIdentityCode);
$this->name = $name;
$this->type = $type;
$this->businessId = $businessId;
$this->personalIdentityCode = $personalIdentityCode;
}
public function removePersonalIdentityCode(): void
{
$this->personalIdentityCode = null;
}
public function id(): ?int
@@ -70,10 +101,22 @@ final class Customer
return $this->businessId;
}
private static function ensureBusinessIdFitsType(CustomerType $type, ?BusinessId $businessId): void
public function personalIdentityCode(): ?PersonalIdentityCode
{
return $this->personalIdentityCode;
}
private static function ensureIdentifiersFitType(
CustomerType $type,
?BusinessId $businessId,
?PersonalIdentityCode $personalIdentityCode,
): void {
if ($type === CustomerType::Consumer && $businessId !== null) {
throw new ConsumerCannotHaveBusinessId;
}
if ($type === CustomerType::Company && $personalIdentityCode !== null) {
throw new CompanyCannotHavePersonalIdentityCode;
}
}
}
@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Entities;
use App\Modules\Customers\Domain\ValueObjects\ContactName;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
/**
* A contact person of a customer. A customer job later picks one of the
* customer's contacts as its customer contact.
*/
final class CustomerContact
{
private function __construct(
private ?int $id,
private int $customerId,
private ContactName $name,
private ?string $title,
private ?string $phone,
private ?EmailAddress $email,
private ?string $note,
) {}
/**
* A new contact that is not stored yet, so it has no id.
*/
public static function create(
int $customerId,
ContactName $name,
?string $title = null,
?string $phone = null,
?EmailAddress $email = null,
?string $note = null,
): self {
return new self(null, $customerId, $name, OptionalText::from($title), OptionalText::from($phone), $email, OptionalText::from($note));
}
/**
* Rebuilds a stored contact. Used only by repositories.
*/
public static function reconstitute(
int $id,
int $customerId,
ContactName $name,
?string $title,
?string $phone,
?EmailAddress $email,
?string $note,
): self {
return new self($id, $customerId, $name, $title, $phone, $email, $note);
}
public function changeDetails(ContactName $name, ?string $title, ?string $phone, ?EmailAddress $email, ?string $note): void
{
$this->name = $name;
$this->title = OptionalText::from($title);
$this->phone = OptionalText::from($phone);
$this->email = $email;
$this->note = OptionalText::from($note);
}
public function id(): ?int
{
return $this->id;
}
public function customerId(): int
{
return $this->customerId;
}
public function name(): ContactName
{
return $this->name;
}
public function title(): ?string
{
return $this->title;
}
public function phone(): ?string
{
return $this->phone;
}
public function email(): ?EmailAddress
{
return $this->email;
}
public function note(): ?string
{
return $this->note;
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Entities;
/**
* Normalises optional free-text fields: trimmed, and empty means none.
*
* @internal
*/
final class OptionalText
{
public static function from(?string $value): ?string
{
$value = $value === null ? '' : trim($value);
return $value === '' ? null : $value;
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* The row does not exist or belongs to another customer.
*/
final class BillingUnitNotFound extends DomainException
{
public function __construct(public readonly int $customerId, public readonly int $id)
{
parent::__construct("Billing unit {$id} of customer {$customerId} was not found.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class CompanyCannotHavePersonalIdentityCode extends DomainException
{
public function __construct()
{
parent::__construct('A company customer cannot have a personal identity code.');
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* The row does not exist or belongs to another customer.
*/
final class ContactNotFound extends DomainException
{
public function __construct(public readonly int $customerId, public readonly int $id)
{
parent::__construct("Contact {$id} of customer {$customerId} was not found.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class EInvoiceOperatorRequired extends DomainException
{
public function __construct()
{
parent::__construct('An e-invoice address needs an e-invoice operator.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidBillingUnitName extends DomainException
{
public function __construct()
{
parent::__construct('The billing unit name must be 1–255 characters.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidContactName extends DomainException
{
public function __construct()
{
parent::__construct('The contact name must be 1–255 characters.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidEInvoiceAddress extends DomainException
{
public function __construct()
{
parent::__construct('The e-invoice address must be 12–35 letters or digits.');
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* The message never contains the code: it is sensitive personal data.
*/
final class InvalidPersonalIdentityCode extends DomainException
{
public function __construct()
{
parent::__construct('The personal identity code is not a valid Finnish personal identity code.');
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* The message never contains the code: it is sensitive personal data.
*/
final class PersonalIdentityCodeAlreadyInUse extends DomainException
{
public function __construct()
{
parent::__construct('The personal identity code already belongs to another customer.');
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\ValueObjects;
use App\Modules\Customers\Domain\Exceptions\InvalidBillingUnitName;
/**
* Name of a billing unit, e.g. "Mainos Oy, markkinointi".
*/
final readonly class BillingUnitName
{
public const int MAX_LENGTH = 255;
public string $value;
public function __construct(string $value)
{
$value = trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
throw new InvalidBillingUnitName;
}
$this->value = $value;
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\ValueObjects;
use App\Modules\Customers\Domain\Exceptions\InvalidContactName;
/**
* Name of a customer's contact person.
*/
final readonly class ContactName
{
public const int MAX_LENGTH = 255;
public string $value;
public function __construct(string $value)
{
$value = trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
throw new InvalidContactName;
}
$this->value = $value;
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\ValueObjects;
use App\Modules\Customers\Domain\Exceptions\InvalidEInvoiceAddress;
/**
* E-invoice address (verkkolaskuosoite), e.g. an OVT code 003712345678 or
* an IBAN. Spaces are removed and letters upper-cased.
*/
final readonly class EInvoiceAddress
{
public string $value;
public function __construct(string $value)
{
$value = strtoupper(preg_replace('/\s+/', '', $value) ?? $value);
if (preg_match('/^[A-Z0-9]{12,35}$/', $value) !== 1) {
throw new InvalidEInvoiceAddress;
}
$this->value = $value;
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\ValueObjects;
use App\Modules\Customers\Domain\Exceptions\InvalidPersonalIdentityCode;
/**
* Finnish personal identity code (henkilötunnus), e.g. 131052-308T.
*
* Sensitive personal data: never put the value in exception messages or
* logs, and show it only to users allowed to see it (masked() otherwise).
*/
final readonly class PersonalIdentityCode
{
private const string CHECK_CHARACTERS = '0123456789ABCDEFHJKLMNPRSTUVWXY';
/**
* Century sign => the century the two-digit year belongs to.
*/
private const array CENTURIES = [
'+' => 1800,
'-' => 1900, 'Y' => 1900, 'X' => 1900, 'W' => 1900, 'V' => 1900, 'U' => 1900,
'A' => 2000, 'B' => 2000, 'C' => 2000, 'D' => 2000, 'E' => 2000, 'F' => 2000,
];
public string $value;
public function __construct(string $value)
{
$value = strtoupper(preg_replace('/\s+/', '', $value) ?? $value);
if (preg_match('/^(\d{2})(\d{2})(\d{2})([-+A-FU-Y])(\d{3})([0-9A-Y])$/', $value, $parts) !== 1) {
throw new InvalidPersonalIdentityCode;
}
[, $day, $month, $year, $centurySign, $individualNumber, $checkCharacter] = $parts;
if (! checkdate((int) $month, (int) $day, self::CENTURIES[$centurySign] + (int) $year)) {
throw new InvalidPersonalIdentityCode;
}
$expected = self::CHECK_CHARACTERS[(int) ($day.$month.$year.$individualNumber) % 31];
if ($checkCharacter !== $expected) {
throw new InvalidPersonalIdentityCode;
}
$this->value = $value;
}
/**
* The code with the date of birth hidden, e.g. ••••••-308T.
*/
public function masked(): string
{
return '••••••'.substr($this->value, 6);
}
public function equals(self $other): bool
{
return $this->value === $other->value;
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Modules\Customers\Infrastructure\Persistence\Eloquent;
use Database\Factories\BillingUnitFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model of a customer's billing unit. Used only inside the
* Customers Infrastructure layer.
*
* @property int $id
* @property int $customer_id
* @property string $name
* @property string|null $billing_address
* @property string|null $e_invoice_address
* @property string|null $e_invoice_operator
* @property string|null $reference
*/
#[Table('billing_units')]
#[Fillable(['customer_id', 'name', 'billing_address', 'e_invoice_address', 'e_invoice_operator', 'reference'])]
#[UseFactory(BillingUnitFactory::class)]
class BillingUnitModel extends Model
{
/** @use HasFactory<BillingUnitFactory> */
use HasFactory;
}
@@ -0,0 +1,31 @@
<?php
namespace App\Modules\Customers\Infrastructure\Persistence\Eloquent;
use Database\Factories\CustomerContactFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model of a customer's contact person. Used only inside the
* Customers Infrastructure layer.
*
* @property int $id
* @property int $customer_id
* @property string $name
* @property string|null $title
* @property string|null $phone
* @property string|null $email
* @property string|null $note
*/
#[Table('customer_contacts')]
#[Fillable(['customer_id', 'name', 'title', 'phone', 'email', 'note'])]
#[UseFactory(CustomerContactFactory::class)]
class CustomerContactModel extends Model
{
/** @use HasFactory<CustomerContactFactory> */
use HasFactory;
}
@@ -5,6 +5,7 @@ namespace App\Modules\Customers\Infrastructure\Persistence\Eloquent;
use App\Modules\Customers\Domain\Enums\CustomerType;
use Database\Factories\CustomerFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -19,9 +20,12 @@ use Illuminate\Database\Eloquent\Model;
* @property string $name
* @property CustomerType $type
* @property string|null $business_id
* @property string|null $personal_identity_code Decrypted by the cast; sensitive.
* @property string|null $personal_identity_code_hash
*/
#[Table('customers')]
#[Fillable(['name', 'type', 'business_id'])]
#[Fillable(['name', 'type', 'business_id', 'personal_identity_code', 'personal_identity_code_hash'])]
#[Hidden(['personal_identity_code', 'personal_identity_code_hash'])]
#[UseFactory(CustomerFactory::class)]
class CustomerModel extends Model
{
@@ -35,6 +39,7 @@ class CustomerModel extends Model
{
return [
'type' => CustomerType::class,
'personal_identity_code' => 'encrypted',
];
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Modules\Customers\Infrastructure\Persistence;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
use RuntimeException;
/**
* Keyed hash (blind index) of a personal identity code. The code itself is
* stored encrypted, which cannot be compared in SQL; this hash can, so
* duplicates are found without decrypting rows. Keyed with the app key, so
* the hash cannot be reversed by hashing every possible code.
*
* Rotating APP_KEY needs re-encrypting the codes and rebuilding these hashes.
*/
class PersonalIdentityCodeHasher
{
public function hash(PersonalIdentityCode $code): string
{
$key = (string) config('app.key');
if ($key === '') {
throw new RuntimeException('APP_KEY is not set.');
}
return hash_hmac('sha256', 'personal_identity_code|'.$code->value, $key);
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Modules\Customers\Infrastructure\Persistence\Repositories;
use App\Modules\Customers\Domain\Contracts\BillingUnitRepository;
use App\Modules\Customers\Domain\Entities\BillingUnit;
use App\Modules\Customers\Domain\ValueObjects\BillingUnitName;
use App\Modules\Customers\Domain\ValueObjects\EInvoiceAddress;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\BillingUnitModel;
class EloquentBillingUnitRepository implements BillingUnitRepository
{
public function findForCustomer(int $customerId, int $billingUnitId): ?BillingUnit
{
$model = BillingUnitModel::query()->where('customer_id', $customerId)->find($billingUnitId);
return $model === null ? null : $this->toEntity($model);
}
public function save(BillingUnit $billingUnit): BillingUnit
{
$model = $billingUnit->id() === null
? new BillingUnitModel
: BillingUnitModel::query()->findOrFail($billingUnit->id());
$model->fill([
'customer_id' => $billingUnit->customerId(),
'name' => $billingUnit->name()->value,
'billing_address' => $billingUnit->billingAddress(),
'e_invoice_address' => $billingUnit->eInvoiceAddress()?->value,
'e_invoice_operator' => $billingUnit->eInvoiceOperator(),
'reference' => $billingUnit->reference(),
])->save();
return $this->toEntity($model);
}
public function delete(BillingUnit $billingUnit): void
{
BillingUnitModel::query()->whereKey($billingUnit->id())->delete();
}
private function toEntity(BillingUnitModel $model): BillingUnit
{
return BillingUnit::reconstitute(
$model->id,
$model->customer_id,
new BillingUnitName($model->name),
$model->billing_address,
$model->e_invoice_address === null ? null : new EInvoiceAddress($model->e_invoice_address),
$model->e_invoice_operator,
$model->reference,
);
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Modules\Customers\Infrastructure\Persistence\Repositories;
use App\Modules\Customers\Domain\Contracts\CustomerContactRepository;
use App\Modules\Customers\Domain\Entities\CustomerContact;
use App\Modules\Customers\Domain\ValueObjects\ContactName;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerContactModel;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
class EloquentCustomerContactRepository implements CustomerContactRepository
{
public function findForCustomer(int $customerId, int $contactId): ?CustomerContact
{
$model = CustomerContactModel::query()->where('customer_id', $customerId)->find($contactId);
return $model === null ? null : $this->toEntity($model);
}
public function save(CustomerContact $contact): CustomerContact
{
$model = $contact->id() === null
? new CustomerContactModel
: CustomerContactModel::query()->findOrFail($contact->id());
$model->fill([
'customer_id' => $contact->customerId(),
'name' => $contact->name()->value,
'title' => $contact->title(),
'phone' => $contact->phone(),
'email' => $contact->email()?->value,
'note' => $contact->note(),
])->save();
return $this->toEntity($model);
}
public function delete(CustomerContact $contact): void
{
CustomerContactModel::query()->whereKey($contact->id())->delete();
}
private function toEntity(CustomerContactModel $model): CustomerContact
{
return CustomerContact::reconstitute(
$model->id,
$model->customer_id,
new ContactName($model->name),
$model->title,
$model->phone,
$model->email === null ? null : new EmailAddress($model->email),
$model->note,
);
}
}
@@ -3,7 +3,12 @@
namespace App\Modules\Customers\Infrastructure\Persistence\Repositories;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\DTOs\BillingUnitSummary;
use App\Modules\Customers\Application\DTOs\ContactSummary;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
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\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
@@ -17,6 +22,11 @@ class EloquentCustomerQueries implements CustomerQueries
return $model === null ? null : $this->toSummary($model);
}
public function personalIdentityCodeOf(int $customerId): ?string
{
return CustomerModel::query()->find($customerId)?->personal_identity_code;
}
public function paginate(?string $search, int $perPage = 25): LengthAwarePaginator
{
return $this->matching($search)
@@ -36,6 +46,44 @@ class EloquentCustomerQueries implements CustomerQueries
->all();
}
public function contactsOf(int $customerId): array
{
return CustomerContactModel::query()
->where('customer_id', $customerId)
->orderBy('name')
->orderBy('id')
->get()
->map(fn (CustomerContactModel $model): ContactSummary => $this->toContactSummary($model))
->values()
->all();
}
public function findContact(int $customerId, int $contactId): ?ContactSummary
{
$model = CustomerContactModel::query()->where('customer_id', $customerId)->find($contactId);
return $model === null ? null : $this->toContactSummary($model);
}
public function billingUnitsOf(int $customerId): array
{
return BillingUnitModel::query()
->where('customer_id', $customerId)
->orderBy('name')
->orderBy('id')
->get()
->map(fn (BillingUnitModel $model): BillingUnitSummary => $this->toBillingUnitSummary($model))
->values()
->all();
}
public function findBillingUnit(int $customerId, int $billingUnitId): ?BillingUnitSummary
{
$model = BillingUnitModel::query()->where('customer_id', $customerId)->find($billingUnitId);
return $model === null ? null : $this->toBillingUnitSummary($model);
}
/**
* @return Builder<CustomerModel>
*/
@@ -54,6 +102,28 @@ class EloquentCustomerQueries implements CustomerQueries
private function toSummary(CustomerModel $model): CustomerSummary
{
return new CustomerSummary($model->id, $model->name, $model->type, $model->business_id);
$masked = $model->personal_identity_code === null
? null
: (new PersonalIdentityCode($model->personal_identity_code))->masked();
return new CustomerSummary($model->id, $model->name, $model->type, $model->business_id, $masked);
}
private function toContactSummary(CustomerContactModel $model): ContactSummary
{
return new ContactSummary($model->id, $model->customer_id, $model->name, $model->title, $model->phone, $model->email, $model->note);
}
private function toBillingUnitSummary(BillingUnitModel $model): BillingUnitSummary
{
return new BillingUnitSummary(
$model->id,
$model->customer_id,
$model->name,
$model->billing_address,
$model->e_invoice_address,
$model->e_invoice_operator,
$model->reference,
);
}
}
@@ -6,10 +6,14 @@ 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\CustomerName;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Customers\Infrastructure\Persistence\PersonalIdentityCodeHasher;
class EloquentCustomerRepository implements CustomerRepository
{
public function __construct(private PersonalIdentityCodeHasher $hasher) {}
public function findById(int $id): ?Customer
{
$model = CustomerModel::query()->find($id);
@@ -27,6 +31,8 @@ class EloquentCustomerRepository implements CustomerRepository
'name' => $customer->name()->value,
'type' => $customer->type(),
'business_id' => $customer->businessId()?->value,
'personal_identity_code' => $customer->personalIdentityCode()?->value,
'personal_identity_code_hash' => $customer->personalIdentityCode() === null ? null : $this->hasher->hash($customer->personalIdentityCode()),
])->save();
return $this->toEntity($model);
@@ -40,6 +46,14 @@ class EloquentCustomerRepository implements CustomerRepository
->exists();
}
public function isPersonalIdentityCodeTaken(PersonalIdentityCode $code, ?int $exceptCustomerId = null): bool
{
return CustomerModel::query()
->where('personal_identity_code_hash', $this->hasher->hash($code))
->when($exceptCustomerId !== null, fn ($query) => $query->whereKeyNot($exceptCustomerId))
->exists();
}
private function toEntity(CustomerModel $model): Customer
{
return Customer::reconstitute(
@@ -47,6 +61,7 @@ class EloquentCustomerRepository implements CustomerRepository
new CustomerName($model->name),
$model->type,
$model->business_id === null ? null : new BusinessId($model->business_id),
$model->personal_identity_code === null ? null : new PersonalIdentityCode($model->personal_identity_code),
);
}
}
@@ -4,7 +4,11 @@ namespace App\Modules\Customers\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Domain\Contracts\BillingUnitRepository;
use App\Modules\Customers\Domain\Contracts\CustomerContactRepository;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentBillingUnitRepository;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerContactRepository;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerQueries;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerRepository;
use App\Modules\Users\Domain\Enums\Role;
@@ -24,6 +28,8 @@ class CustomersServiceProvider extends ServiceProvider
public array $bindings = [
CustomerRepository::class => EloquentCustomerRepository::class,
CustomerQueries::class => EloquentCustomerQueries::class,
CustomerContactRepository::class => EloquentCustomerContactRepository::class,
BillingUnitRepository::class => EloquentBillingUnitRepository::class,
];
public function boot(): void
@@ -38,5 +44,12 @@ class CustomersServiceProvider extends ServiceProvider
// Subcontractors see only the customer jobs assigned to them, not the customer register.
Gate::define('customers.use', fn (User $user): bool => $user->role !== Role::Subcontractor);
// A consumer's personal identity code is sensitive personal data: only
// admins and management (who make the invoices) see it in full or remove it.
Gate::define(
'customers.view-personal-identity-code',
fn (User $user): bool => in_array($user->role, [Role::Admin, Role::Management], true),
);
}
}
@@ -0,0 +1,93 @@
<?php
namespace App\Modules\Customers\Presentation\Livewire\Forms;
use App\Modules\Customers\Application\DTOs\BillingUnitData;
use App\Modules\Customers\Application\DTOs\BillingUnitSummary;
use App\Modules\Customers\Domain\Exceptions\EInvoiceOperatorRequired;
use App\Modules\Customers\Domain\Exceptions\InvalidBillingUnitName;
use App\Modules\Customers\Domain\Exceptions\InvalidEInvoiceAddress;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Livewire\Form;
/**
* Billing unit form shared by the add and edit pages.
*/
class BillingUnitForm extends Form
{
public string $name = '';
public string $billing_address = '';
public string $e_invoice_address = '';
public string $e_invoice_operator = '';
public string $reference = '';
public function fillFromSummary(BillingUnitSummary $billingUnit): void
{
$this->name = $billingUnit->name;
$this->billing_address = $billingUnit->billingAddress ?? '';
$this->e_invoice_address = $billingUnit->eInvoiceAddress ?? '';
$this->e_invoice_operator = $billingUnit->eInvoiceOperator ?? '';
$this->reference = $billingUnit->reference ?? '';
}
public function toData(): BillingUnitData
{
$this->validate();
return BillingUnitData::fromArray([
'name' => $this->name,
'billing_address' => $this->billing_address,
'e_invoice_address' => $this->e_invoice_address,
'e_invoice_operator' => $this->e_invoice_operator,
'reference' => $this->reference,
]);
}
/**
* Shows a broken business rule as an error on the field it concerns.
*/
public function showDomainError(DomainException $exception): void
{
[$field, $key] = match ($exception::class) {
InvalidBillingUnitName::class => ['name', 'customers.errors.invalid_billing_unit_name'],
InvalidEInvoiceAddress::class => ['e_invoice_address', 'customers.errors.invalid_e_invoice_address'],
EInvoiceOperatorRequired::class => ['e_invoice_operator', 'customers.errors.e_invoice_operator_required'],
default => throw $exception,
};
$this->addError($field, __($key));
}
/**
* @return array<string, array<int, mixed>>
*/
protected function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'billing_address' => ['nullable', 'string', 'max:1000'],
'e_invoice_address' => ['nullable', 'string', 'max:50'],
'e_invoice_operator' => ['nullable', 'string', 'max:35'],
'reference' => ['nullable', 'string', 'max:255'],
];
}
/**
* @return array<string, string>
*/
protected function messages(): array
{
return [
'name.required' => __('customers.errors.billing_unit_name_required'),
'name.max' => __('customers.errors.invalid_billing_unit_name'),
'billing_address.max' => __('customers.errors.too_long', ['max' => 1000]),
'e_invoice_address.max' => __('customers.errors.invalid_e_invoice_address'),
'e_invoice_operator.max' => __('customers.errors.too_long', ['max' => 35]),
'reference.max' => __('customers.errors.too_long', ['max' => 255]),
];
}
}
@@ -0,0 +1,92 @@
<?php
namespace App\Modules\Customers\Presentation\Livewire\Forms;
use App\Modules\Customers\Application\DTOs\ContactData;
use App\Modules\Customers\Application\DTOs\ContactSummary;
use App\Modules\Customers\Domain\Exceptions\InvalidContactName;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use Livewire\Form;
/**
* Contact person form shared by the add and edit pages.
*/
class ContactForm extends Form
{
public string $name = '';
public string $title = '';
public string $phone = '';
public string $email = '';
public string $note = '';
public function fillFromSummary(ContactSummary $contact): void
{
$this->name = $contact->name;
$this->title = $contact->title ?? '';
$this->phone = $contact->phone ?? '';
$this->email = $contact->email ?? '';
$this->note = $contact->note ?? '';
}
public function toData(): ContactData
{
$this->validate();
return ContactData::fromArray([
'name' => $this->name,
'title' => $this->title,
'phone' => $this->phone,
'email' => $this->email,
'note' => $this->note,
]);
}
/**
* Shows a broken business rule as an error on the field it concerns.
*/
public function showDomainError(DomainException $exception): void
{
[$field, $key] = match ($exception::class) {
InvalidContactName::class => ['name', 'customers.errors.invalid_contact_name'],
InvalidEmailAddress::class => ['email', 'customers.errors.invalid_email'],
default => throw $exception,
};
$this->addError($field, __($key));
}
/**
* @return array<string, array<int, mixed>>
*/
protected function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'title' => ['nullable', 'string', 'max:255'],
'phone' => ['nullable', 'string', 'max:50'],
'email' => ['nullable', 'string', 'email', 'max:255'],
'note' => ['nullable', 'string', 'max:2000'],
];
}
/**
* @return array<string, string>
*/
protected function messages(): array
{
return [
'name.required' => __('customers.errors.contact_name_required'),
'name.max' => __('customers.errors.invalid_contact_name'),
'title.max' => __('customers.errors.too_long', ['max' => 255]),
'phone.max' => __('customers.errors.too_long', ['max' => 50]),
'email.email' => __('customers.errors.invalid_email'),
'email.max' => __('customers.errors.invalid_email'),
'note.max' => __('customers.errors.too_long', ['max' => 2000]),
];
}
}
@@ -6,9 +6,12 @@ use App\Modules\Customers\Application\DTOs\CustomerDetailsData;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse;
use App\Modules\Customers\Domain\Exceptions\CompanyCannotHavePersonalIdentityCode;
use App\Modules\Customers\Domain\Exceptions\ConsumerCannotHaveBusinessId;
use App\Modules\Customers\Domain\Exceptions\InvalidBusinessId;
use App\Modules\Customers\Domain\Exceptions\InvalidCustomerName;
use App\Modules\Customers\Domain\Exceptions\InvalidPersonalIdentityCode;
use App\Modules\Customers\Domain\Exceptions\PersonalIdentityCodeAlreadyInUse;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Illuminate\Validation\Rule;
use Livewire\Form;
@@ -28,6 +31,14 @@ class CustomerForm extends Form
public string $business_id = '';
/**
* A new personal identity code. Never filled from the stored code: empty
* keeps the stored one.
*/
public string $personal_identity_code = '';
public bool $remove_personal_identity_code = false;
public function fillFromSummary(CustomerSummary $customer): void
{
$this->name = $customer->name;
@@ -43,6 +54,8 @@ class CustomerForm extends Form
'name' => $this->name,
'type' => $this->type,
'business_id' => $this->type === CustomerType::Consumer->value ? null : $this->business_id,
'personal_identity_code' => $this->type === CustomerType::Consumer->value ? $this->personal_identity_code : null,
'remove_personal_identity_code' => $this->remove_personal_identity_code,
]);
}
@@ -56,6 +69,9 @@ class CustomerForm extends Form
InvalidBusinessId::class => ['business_id', 'customers.errors.invalid_business_id'],
ConsumerCannotHaveBusinessId::class => ['business_id', 'customers.errors.consumer_business_id'],
BusinessIdAlreadyInUse::class => ['business_id', 'customers.errors.business_id_taken'],
InvalidPersonalIdentityCode::class => ['personal_identity_code', 'customers.errors.invalid_personal_identity_code'],
CompanyCannotHavePersonalIdentityCode::class => ['personal_identity_code', 'customers.errors.company_personal_identity_code'],
PersonalIdentityCodeAlreadyInUse::class => ['personal_identity_code', 'customers.errors.personal_identity_code_taken'],
default => throw $exception,
};
@@ -71,6 +87,8 @@ class CustomerForm extends Form
'name' => ['required', 'string', 'max:255'],
'type' => ['required', Rule::enum(CustomerType::class)],
'business_id' => ['nullable', 'string', 'max:20'],
'personal_identity_code' => ['nullable', 'string', 'max:20'],
'remove_personal_identity_code' => ['boolean'],
];
}
@@ -85,6 +103,7 @@ class CustomerForm extends Form
'type.required' => __('customers.errors.type_required'),
'type.enum' => __('customers.errors.type_required'),
'business_id.max' => __('customers.errors.invalid_business_id'),
'personal_identity_code.max' => __('customers.errors.invalid_personal_identity_code'),
];
}
}
@@ -0,0 +1,117 @@
<?php
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\UseCases\AddBillingUnit;
use App\Modules\Customers\Application\UseCases\UpdateBillingUnit;
use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Presentation\Livewire\Forms\BillingUnitForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Add page (no {billingUnit}) and edit page (with {billingUnit}) of a customer's billing unit.
*/
new class extends Component
{
#[Locked]
public int $customerId;
#[Locked]
public ?int $billingUnitId = null;
#[Locked]
public string $customerName = '';
public BillingUnitForm $form;
public function mount(CustomerQueries $customerQueries, int $customer, ?int $billingUnit = null): void
{
$this->authorize('customers.use');
$summary = $customerQueries->findSummary($customer);
abort_if($summary === null, 404);
$this->customerId = $summary->id;
$this->customerName = $summary->name;
if ($billingUnit === null) {
// A new billing unit is usually named after the customer.
$this->form->name = $summary->name;
return;
}
$billingUnitSummary = $customerQueries->findBillingUnit($customer, $billingUnit);
abort_if($billingUnitSummary === null, 404);
$this->billingUnitId = $billingUnitSummary->id;
$this->form->fillFromSummary($billingUnitSummary);
}
public function save(AddBillingUnit $addBillingUnit, UpdateBillingUnit $updateBillingUnit): void
{
$this->authorize('customers.use');
$data = $this->form->toData();
try {
if ($this->billingUnitId === null) {
$addBillingUnit->execute($this->customerId, $data);
session()->flash('status', __('customers.billing_units.created', ['name' => $data->name]));
} else {
$updateBillingUnit->execute($this->customerId, $this->billingUnitId, $data);
session()->flash('status', __('customers.billing_units.updated', ['name' => $data->name]));
}
} catch (CustomerNotFound|BillingUnitNotFound) {
abort(404);
} catch (DomainException $exception) {
$this->form->showDomainError($exception);
return;
}
$this->redirectRoute('customers.show', $this->customerId, navigate: true);
}
public function render(): mixed
{
return $this->view()->title($this->heading().' – '.$this->customerName);
}
public function heading(): string
{
return __($this->billingUnitId === null ? 'customers.billing_units.create_title' : 'customers.billing_units.edit_title');
}
};
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
{{ __('customers.customer_label') }}:
<x-link :href="route('customers.show', $customerId)" navigate>{{ $customerName }}</x-link>
</p>
</div>
<form wire:submit="save" class="space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('customers.billing_units.fields.name')" :hint="__('customers.billing_units.fields.name_description')" autocomplete="off" required />
<x-textarea wire:model="form.billing_address" :label="__('customers.billing_units.fields.billing_address')" :hint="__('customers.billing_units.fields.billing_address_description')" resize-auto />
<x-input wire:model="form.e_invoice_address" :label="__('customers.billing_units.fields.e_invoice_address')" :hint="__('customers.billing_units.fields.e_invoice_address_description')" autocomplete="off" />
<x-input wire:model="form.e_invoice_operator" :label="__('customers.billing_units.fields.e_invoice_operator')" :hint="__('customers.billing_units.fields.e_invoice_operator_description')" autocomplete="off" />
<x-input wire:model="form.reference" :label="__('customers.billing_units.fields.reference')" :hint="__('customers.billing_units.fields.reference_description')" autocomplete="off" />
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('customers.save')" />
<x-button :href="route('customers.show', $customerId)" wire:navigate subtle color="black" :text="__('customers.cancel')" />
</div>
</form>
</div>
@@ -0,0 +1,114 @@
<?php
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\UseCases\AddContact;
use App\Modules\Customers\Application\UseCases\UpdateContact;
use App\Modules\Customers\Domain\Exceptions\ContactNotFound;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Presentation\Livewire\Forms\ContactForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Add page (no {contact}) and edit page (with {contact}) of a customer's contact.
*/
new class extends Component
{
#[Locked]
public int $customerId;
#[Locked]
public ?int $contactId = null;
#[Locked]
public string $customerName = '';
public ContactForm $form;
public function mount(CustomerQueries $customerQueries, int $customer, ?int $contact = null): void
{
$this->authorize('customers.use');
$summary = $customerQueries->findSummary($customer);
abort_if($summary === null, 404);
$this->customerId = $summary->id;
$this->customerName = $summary->name;
if ($contact === null) {
return;
}
$contactSummary = $customerQueries->findContact($customer, $contact);
abort_if($contactSummary === null, 404);
$this->contactId = $contactSummary->id;
$this->form->fillFromSummary($contactSummary);
}
public function save(AddContact $addContact, UpdateContact $updateContact): void
{
$this->authorize('customers.use');
$data = $this->form->toData();
try {
if ($this->contactId === null) {
$addContact->execute($this->customerId, $data);
session()->flash('status', __('customers.contacts.created', ['name' => $data->name]));
} else {
$updateContact->execute($this->customerId, $this->contactId, $data);
session()->flash('status', __('customers.contacts.updated', ['name' => $data->name]));
}
} catch (CustomerNotFound|ContactNotFound) {
abort(404);
} catch (DomainException $exception) {
$this->form->showDomainError($exception);
return;
}
$this->redirectRoute('customers.show', $this->customerId, navigate: true);
}
public function render(): mixed
{
return $this->view()->title($this->heading().' – '.$this->customerName);
}
public function heading(): string
{
return __($this->contactId === null ? 'customers.contacts.create_title' : 'customers.contacts.edit_title');
}
};
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
{{ __('customers.customer_label') }}:
<x-link :href="route('customers.show', $customerId)" navigate>{{ $customerName }}</x-link>
</p>
</div>
<form wire:submit="save" class="space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('customers.contacts.fields.name')" autocomplete="off" required />
<x-input wire:model="form.title" :label="__('customers.contacts.fields.title')" :hint="__('customers.contacts.fields.title_description')" autocomplete="off" />
<x-input wire:model="form.phone" type="tel" :label="__('customers.contacts.fields.phone')" autocomplete="off" />
<x-input wire:model="form.email" type="email" :label="__('customers.contacts.fields.email')" autocomplete="off" />
<x-textarea wire:model="form.note" :label="__('customers.contacts.fields.note')" resize-auto />
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('customers.save')" />
<x-button :href="route('customers.show', $customerId)" wire:navigate subtle color="black" :text="__('customers.cancel')" />
</div>
</form>
</div>
@@ -20,6 +20,13 @@ new class extends Component
public CustomerForm $form;
/**
* The stored personal identity code, masked (e.g. ••••••-308T). The
* full code never reaches the form.
*/
#[Locked]
public ?string $storedPersonalIdentityCode = null;
public function mount(CustomerQueries $customerQueries, ?int $customer = null): void
{
$this->authorize('customers.use');
@@ -33,6 +40,7 @@ new class extends Component
abort_if($summary === null, 404);
$this->customerId = $summary->id;
$this->storedPersonalIdentityCode = $summary->personalIdentityCodeMasked;
$this->form->fillFromSummary($summary);
}
@@ -40,14 +48,19 @@ new class extends Component
{
$this->authorize('customers.use');
if ($this->form->remove_personal_identity_code) {
$this->authorize('customers.view-personal-identity-code');
}
$data = $this->form->toData();
try {
if ($this->customerId === null) {
$registerCustomer->execute($data);
$customerId = $registerCustomer->execute($data);
session()->flash('status', __('customers.created', ['name' => $data->name]));
} else {
$updateCustomer->execute($this->customerId, $data);
$customerId = $this->customerId;
session()->flash('status', __('customers.updated', ['name' => $data->name]));
}
} catch (CustomerNotFound) {
@@ -58,7 +71,8 @@ new class extends Component
return;
}
$this->redirectRoute('customers.index', navigate: true);
// The customer's page, where contacts and billing units are added.
$this->redirectRoute('customers.show', $customerId, navigate: true);
}
public function render(): mixed
@@ -95,11 +109,37 @@ new class extends Component
:hint="__('customers.fields.business_id_description')"
autocomplete="off"
/>
@else
{{-- Never filled from the stored code; type="text" because the code has letters. --}}
<x-input
wire:model="form.personal_identity_code"
:label="__('customers.fields.personal_identity_code')"
:hint="$storedPersonalIdentityCode === null
? __('customers.fields.personal_identity_code_description')
: __('customers.fields.personal_identity_code_stored', ['code' => $storedPersonalIdentityCode])"
autocomplete="off"
spellcheck="false"
/>
@if ($storedPersonalIdentityCode !== null)
@can('customers.view-personal-identity-code')
<x-checkbox
wire:model="form.remove_personal_identity_code"
:label="__('customers.fields.remove_personal_identity_code')"
/>
@endcan
@endif
@endif
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('customers.save')" />
<x-button :href="route('customers.index')" wire:navigate subtle color="black" :text="__('customers.cancel')" />
<x-button
:href="$customerId === null ? route('customers.index') : route('customers.show', $customerId)"
wire:navigate
subtle
color="black"
:text="__('customers.cancel')"
/>
</div>
</form>
</div>
@@ -89,7 +89,7 @@ new class extends Component
@else
<x-table :headers="$this->headers()" :rows="$this->customers" paginate>
@interact('column_name', $customer)
<span class="font-medium">{{ $customer->name }}</span>
<x-link :href="route('customers.show', $customer->id)" navigate class="font-medium">{{ $customer->name }}</x-link>
@endinteract
@interact('column_type', $customer)
@@ -0,0 +1,357 @@
<?php
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\DTOs\BillingUnitSummary;
use App\Modules\Customers\Application\DTOs\ContactSummary;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use App\Modules\Customers\Application\UseCases\RemoveBillingUnit;
use App\Modules\Customers\Application\UseCases\RemoveContact;
use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound;
use App\Modules\Customers\Domain\Exceptions\ContactNotFound;
use App\Modules\Customers\Domain\Enums\CustomerType;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* A customer's page: details, contacts and billing units.
*/
new class extends Component
{
public const string REMOVE_DIALOG = 'remove-dialog';
#[Locked]
public int $customerId;
/**
* The row the remove dialog asks about: 'contact' or 'billing_unit'.
*/
#[Locked]
public ?string $removalType = null;
#[Locked]
public ?int $removalId = null;
#[Locked]
public string $removalName = '';
public string $statusMessage = '';
protected CustomerQueries $customerQueries;
public function boot(CustomerQueries $customerQueries): void
{
$this->customerQueries = $customerQueries;
}
public function mount(int $customer): void
{
$this->authorize('customers.use');
abort_if($this->customerQueries->findSummary($customer) === null, 404);
$this->customerId = $customer;
}
#[Computed]
public function customer(): CustomerSummary
{
return $this->customerQueries->findSummary($this->customerId) ?? abort(404);
}
/**
* The personal identity code as this user may see it: in full for admins
* and management, masked for others. Computed, so the full code is never
* kept in the component state sent to the browser.
*/
#[Computed]
public function personalIdentityCode(): ?string
{
if (Gate::allows('customers.view-personal-identity-code')) {
return $this->customerQueries->personalIdentityCodeOf($this->customerId);
}
return $this->customer->personalIdentityCodeMasked;
}
/**
* @return list<ContactSummary>
*/
#[Computed]
public function contacts(): array
{
return $this->customerQueries->contactsOf($this->customerId);
}
/**
* @return list<BillingUnitSummary>
*/
#[Computed]
public function billingUnits(): array
{
return $this->customerQueries->billingUnitsOf($this->customerId);
}
/**
* Opens the remove dialog for a contact or a billing unit of this customer.
*/
public function confirmRemoval(string $type, int $id): void
{
$this->authorize('customers.use');
$name = match ($type) {
'contact' => $this->customerQueries->findContact($this->customerId, $id)?->name,
'billing_unit' => $this->customerQueries->findBillingUnit($this->customerId, $id)?->name,
default => null,
};
if ($name === null) {
$this->statusMessage = __('customers.removal.already_removed');
return;
}
$this->removalType = $type;
$this->removalId = $id;
$this->removalName = $name;
$this->statusMessage = '';
$this->js("document.getElementById('".self::REMOVE_DIALOG."').showModal()");
}
public function remove(RemoveContact $removeContact, RemoveBillingUnit $removeBillingUnit): void
{
$this->authorize('customers.use');
if ($this->removalType === null || $this->removalId === null) {
return;
}
try {
match ($this->removalType) {
'contact' => $removeContact->execute($this->customerId, $this->removalId),
'billing_unit' => $removeBillingUnit->execute($this->customerId, $this->removalId),
};
$this->statusMessage = __('customers.removal.removed_'.$this->removalType, ['name' => $this->removalName]);
} catch (ContactNotFound|BillingUnitNotFound) {
$this->statusMessage = __('customers.removal.already_removed');
}
// The removed row's button is gone, so focus moves to its section heading.
$heading = $this->removalType === 'contact' ? 'contacts-heading' : 'billing-units-heading';
$this->js("document.getElementById('".self::REMOVE_DIALOG."').close(); document.getElementById('{$heading}').focus()");
$this->reset('removalType', 'removalId', 'removalName');
}
public function render(): mixed
{
return $this->view()->title($this->customer->name);
}
};
?>
<div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6">
<div class="space-y-4">
<div class="flex flex-wrap items-center justify-between gap-4">
<h1 class="text-2xl font-semibold break-words">{{ $this->customer->name }}</h1>
<x-button
:href="route('customers.edit', $customerId)"
wire:navigate
subtle
color="black"
icon="pencil"
:text="__('customers.edit_details')"
/>
</div>
@if (session('status'))
<x-alert role="status" color="green" light icon="check-circle" :text="session('status')" />
@endif
<dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-[max-content_1fr]">
<dt class="font-medium">{{ __('customers.fields.type') }}</dt>
<dd>{{ __('customers.types.'.$this->customer->type->value) }}</dd>
@if ($this->customer->businessId !== null)
<dt class="font-medium">{{ __('customers.fields.business_id') }}</dt>
<dd>{{ $this->customer->businessId }}</dd>
@endif
@if ($this->customer->type === CustomerType::Consumer)
<dt class="font-medium">{{ __('customers.fields.personal_identity_code') }}</dt>
<dd>
@if ($this->personalIdentityCode !== null)
{{ $this->personalIdentityCode }}
@else
<span class="inline-flex items-center gap-1">
<x-icon name="exclamation-triangle" class="size-4 shrink-0" aria-hidden="true" />
{{ __('customers.fields.personal_identity_code_missing') }}
</span>
@endif
</dd>
@endif
</dl>
<p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p>
</div>
<section aria-labelledby="contacts-heading" class="space-y-4">
<div class="flex flex-wrap items-center justify-between gap-4">
<h2 id="contacts-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">
{{ __('customers.contacts.title') }}
</h2>
<x-button
:href="route('customers.contacts.create', $customerId)"
wire:navigate
icon="plus"
:text="__('customers.contacts.new')"
/>
</div>
@if ($this->contacts === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('customers.contacts.empty') }}</p>
@else
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-200 dark:divide-zinc-700 dark:border-zinc-700">
@foreach ($this->contacts as $contact)
<li wire:key="contact-{{ $contact->id }}" class="flex flex-wrap items-start justify-between gap-4 p-4">
<div class="min-w-0 space-y-1 text-sm">
<h3 class="text-base font-medium break-words">{{ $contact->name }}</h3>
@if ($contact->title !== null)
<p>{{ $contact->title }}</p>
@endif
@if ($contact->phone !== null)
<p>
<span class="sr-only">{{ __('customers.contacts.fields.phone') }}:</span>
<x-link :href="'tel:'.preg_replace('/[^\d+]/', '', $contact->phone)">{{ $contact->phone }}</x-link>
</p>
@endif
@if ($contact->email !== null)
<p class="break-all">
<span class="sr-only">{{ __('customers.contacts.fields.email') }}:</span>
<x-link :href="'mailto:'.$contact->email">{{ $contact->email }}</x-link>
</p>
@endif
@if ($contact->note !== null)
<p class="whitespace-pre-line text-zinc-600 dark:text-zinc-300">{{ $contact->note }}</p>
@endif
</div>
<div class="flex flex-wrap gap-2">
<x-button
:href="route('customers.contacts.edit', [$customerId, $contact->id])"
wire:navigate
subtle
color="black"
sm
icon="pencil"
:text="__('customers.edit')"
:aria-label="__('customers.contacts.edit_named', ['name' => $contact->name])"
/>
<x-button
wire:click="confirmRemoval('contact', {{ $contact->id }})"
subtle
color="black"
sm
icon="trash"
:text="__('customers.remove')"
:aria-label="__('customers.contacts.remove_named', ['name' => $contact->name])"
/>
</div>
</li>
@endforeach
</ul>
@endif
</section>
<section aria-labelledby="billing-units-heading" class="space-y-4">
<div class="flex flex-wrap items-center justify-between gap-4">
<h2 id="billing-units-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">
{{ __('customers.billing_units.title') }}
</h2>
<x-button
:href="route('customers.billing-units.create', $customerId)"
wire:navigate
icon="plus"
:text="__('customers.billing_units.new')"
/>
</div>
@if ($this->billingUnits === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('customers.billing_units.empty') }}</p>
@else
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-200 dark:divide-zinc-700 dark:border-zinc-700">
@foreach ($this->billingUnits as $billingUnit)
<li wire:key="billing-unit-{{ $billingUnit->id }}" class="flex flex-wrap items-start justify-between gap-4 p-4">
<div class="min-w-0 space-y-1 text-sm">
<h3 class="text-base font-medium break-words">{{ $billingUnit->name }}</h3>
<dl class="grid gap-x-4 gap-y-1 sm:grid-cols-[max-content_1fr]">
@if ($billingUnit->billingAddress !== null)
<dt class="font-medium">{{ __('customers.billing_units.fields.billing_address') }}</dt>
<dd class="whitespace-pre-line">{{ $billingUnit->billingAddress }}</dd>
@endif
@if ($billingUnit->eInvoiceAddress !== null)
<dt class="font-medium">{{ __('customers.billing_units.fields.e_invoice_address') }}</dt>
<dd class="break-all">{{ $billingUnit->eInvoiceAddress }}</dd>
<dt class="font-medium">{{ __('customers.billing_units.fields.e_invoice_operator') }}</dt>
<dd class="break-all">{{ $billingUnit->eInvoiceOperator }}</dd>
@endif
@if ($billingUnit->reference !== null)
<dt class="font-medium">{{ __('customers.billing_units.fields.reference') }}</dt>
<dd class="break-words">{{ $billingUnit->reference }}</dd>
@endif
</dl>
</div>
<div class="flex flex-wrap gap-2">
<x-button
:href="route('customers.billing-units.edit', [$customerId, $billingUnit->id])"
wire:navigate
subtle
color="black"
sm
icon="pencil"
:text="__('customers.edit')"
:aria-label="__('customers.billing_units.edit_named', ['name' => $billingUnit->name])"
/>
<x-button
wire:click="confirmRemoval('billing_unit', {{ $billingUnit->id }})"
subtle
color="black"
sm
icon="trash"
:text="__('customers.remove')"
:aria-label="__('customers.billing_units.remove_named', ['name' => $billingUnit->name])"
/>
</div>
</li>
@endforeach
</ul>
@endif
</section>
<x-confirm-dialog id="remove-dialog" :title="__('customers.removal.title')">
<p>
@if ($removalType !== null)
{{ __('customers.removal.question_'.$removalType, ['name' => $removalName]) }}
@endif
</p>
<x-slot:actions>
<x-button wire:click="remove" color="red" icon="trash" :text="__('customers.remove')" />
</x-slot:actions>
</x-confirm-dialog>
</div>
@@ -8,5 +8,20 @@ Route::middleware(['web', 'auth', 'can:customers.use'])
->group(function () {
Route::livewire('/', 'customers::index')->name('index');
Route::livewire('/create', 'customers::form')->name('create');
Route::livewire('/{customer}', 'customers::show')->whereNumber('customer')->name('show');
Route::livewire('/{customer}/edit', 'customers::form')->whereNumber('customer')->name('edit');
Route::livewire('/{customer}/contacts/create', 'customers::contact-form')
->whereNumber('customer')
->name('contacts.create');
Route::livewire('/{customer}/contacts/{contact}/edit', 'customers::contact-form')
->whereNumber(['customer', 'contact'])
->name('contacts.edit');
Route::livewire('/{customer}/billing-units/create', 'customers::billing-unit-form')
->whereNumber('customer')
->name('billing-units.create');
Route::livewire('/{customer}/billing-units/{billingUnit}/edit', 'customers::billing-unit-form')
->whereNumber(['customer', 'billingUnit'])
->name('billing-units.edit');
});
@@ -2,9 +2,7 @@
declare(strict_types=1);
namespace App\Modules\Users\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
namespace App\Modules\Shared\Domain\Exceptions;
final class InvalidEmailAddress extends DomainException
{
@@ -2,13 +2,13 @@
declare(strict_types=1);
namespace App\Modules\Users\Domain\ValueObjects;
namespace App\Modules\Shared\Domain\ValueObjects;
use App\Modules\Users\Domain\Exceptions\InvalidEmailAddress;
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
/**
* Login email address, stored in lower case so it is unique regardless
* of how it was typed.
* An email address, stored in lower case so it compares equal regardless
* of how it was typed (login addresses, customer contacts).
*/
final readonly class EmailAddress
{
@@ -4,8 +4,8 @@ declare(strict_types=1);
namespace App\Modules\Users\Application\Contracts;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Application\DTOs\IssuedSetupLink;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
/**
* Makes and emails links for setting a new password. New users get the same
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Modules\Users\Application\UseCases;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
use App\Modules\Users\Application\DTOs\CreatedUserAccount;
use App\Modules\Users\Application\DTOs\UserAccountData;
@@ -13,7 +14,6 @@ use App\Modules\Users\Domain\Entities\UserAccount;
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
use App\Modules\Users\Domain\Services\SupervisorRule;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\ValueObjects\PersonName;
/**
@@ -4,10 +4,10 @@ declare(strict_types=1);
namespace App\Modules\Users\Application\UseCases;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Application\Contracts\Clock;
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
/**
* A user asks for a set-password link on the login page. Only users who
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Modules\Users\Application\UseCases;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Application\DTOs\UserAccountData;
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
@@ -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;
final class UpdateUserAccount
@@ -4,8 +4,8 @@ declare(strict_types=1);
namespace App\Modules\Users\Domain\Contracts;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\Entities\UserAccount;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
interface UserAccountRepository
{
@@ -4,10 +4,10 @@ declare(strict_types=1);
namespace App\Modules\Users\Domain\Entities;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
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;
use DateTimeImmutable;
@@ -3,9 +3,9 @@
namespace App\Modules\Users\Infrastructure\Auth;
use App\Models\User;
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;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Support\Facades\Password;
use LogicException;
@@ -3,10 +3,10 @@
namespace App\Modules\Users\Infrastructure\Persistence\Repositories;
use App\Models\User;
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\Enums\Role;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\ValueObjects\PersonName;
use DateTimeImmutable;
use Illuminate\Support\Str;
@@ -3,12 +3,12 @@
namespace App\Modules\Users\Presentation\Livewire\Forms;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use App\Modules\Users\Application\DTOs\UserAccountData;
use App\Modules\Users\Application\DTOs\UserSummary;
use App\Modules\Users\Domain\Enums\Role;
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
use App\Modules\Users\Domain\Exceptions\InternRequiresEndDateAndSupervisor;
use App\Modules\Users\Domain\Exceptions\InvalidEmailAddress;
use App\Modules\Users\Domain\Exceptions\InvalidPersonName;
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
use App\Modules\Users\Domain\Exceptions\LastAdminCannotBeRemoved;
@@ -1,7 +1,7 @@
<?php
use App\Modules\Users\Application\UseCases\RequestPasswordReset;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use Livewire\Component;
new class extends Component
@@ -0,0 +1,377 @@
<?php
namespace App\View\Components\TallStackUi\Colors;
use Illuminate\View\Component;
/**
* TallStackUI button colours, published from the package stub. The solid
* red button (destructive actions) has white text on red-500 in light mode,
* only 3.5:1; red-700 meets 4.5:1 in both themes. Null keeps the package
* default.
*/
class NormalButtonColors
{
/**
* Background colors, by button style and colour.
*
* @return array<string, array<string, string|null>>
*/
public function backgroundColors(Component $component): array
{
return [
'solid' => [
'black' => null,
'primary' => null,
'secondary' => null,
'slate' => null,
'gray' => null,
'zinc' => null,
'neutral' => null,
'stone' => null,
'red' => 'text-white ring-red-700 bg-red-700 focus:bg-red-800 hover:bg-red-800 border-transparent focus:ring-offset-2 dark:focus:ring-offset-dark-900 dark:focus:ring-red-500 dark:bg-red-700 dark:hover:bg-red-800',
'orange' => null,
'amber' => null,
'yellow' => null,
'lime' => null,
'green' => null,
'emerald' => null,
'teal' => null,
'cyan' => null,
'sky' => null,
'blue' => null,
'indigo' => null,
'violet' => null,
'purple' => null,
'fuchsia' => null,
'pink' => null,
'rose' => null,
'mauve' => null,
'olive' => null,
'mist' => null,
'taupe' => null,
],
'outline' => [
'black' => null,
'primary' => null,
'secondary' => null,
'slate' => null,
'gray' => null,
'zinc' => null,
'neutral' => null,
'stone' => null,
'red' => null,
'orange' => null,
'amber' => null,
'yellow' => null,
'lime' => null,
'green' => null,
'emerald' => null,
'teal' => null,
'cyan' => null,
'sky' => null,
'blue' => null,
'indigo' => null,
'violet' => null,
'purple' => null,
'fuchsia' => null,
'pink' => null,
'rose' => null,
'mauve' => null,
'olive' => null,
'mist' => null,
'taupe' => null,
],
'light' => [
'black' => null,
'primary' => null,
'secondary' => null,
'slate' => null,
'gray' => null,
'zinc' => null,
'neutral' => null,
'stone' => null,
'red' => null,
'orange' => null,
'amber' => null,
'yellow' => null,
'lime' => null,
'green' => null,
'emerald' => null,
'teal' => null,
'cyan' => null,
'sky' => null,
'blue' => null,
'indigo' => null,
'violet' => null,
'purple' => null,
'fuchsia' => null,
'pink' => null,
'rose' => null,
'mauve' => null,
'olive' => null,
'mist' => null,
'taupe' => null,
],
'flat' => [
'black' => null,
'primary' => null,
'secondary' => null,
'slate' => null,
'gray' => null,
'zinc' => null,
'neutral' => null,
'stone' => null,
'red' => null,
'orange' => null,
'amber' => null,
'yellow' => null,
'lime' => null,
'green' => null,
'emerald' => null,
'teal' => null,
'cyan' => null,
'sky' => null,
'blue' => null,
'indigo' => null,
'violet' => null,
'purple' => null,
'fuchsia' => null,
'pink' => null,
'rose' => null,
'mauve' => null,
'olive' => null,
'mist' => null,
'taupe' => null,
],
'subtle' => [
'black' => null,
'primary' => null,
'secondary' => null,
'slate' => null,
'gray' => null,
'zinc' => null,
'neutral' => null,
'stone' => null,
'red' => null,
'orange' => null,
'amber' => null,
'yellow' => null,
'lime' => null,
'green' => null,
'emerald' => null,
'teal' => null,
'cyan' => null,
'sky' => null,
'blue' => null,
'indigo' => null,
'violet' => null,
'purple' => null,
'fuchsia' => null,
'pink' => null,
'rose' => null,
'mauve' => null,
'olive' => null,
'mist' => null,
'taupe' => null,
],
'tinted' => [
'black' => null,
'primary' => null,
'secondary' => null,
'slate' => null,
'gray' => null,
'zinc' => null,
'neutral' => null,
'stone' => null,
'red' => null,
'orange' => null,
'amber' => null,
'yellow' => null,
'lime' => null,
'green' => null,
'emerald' => null,
'teal' => null,
'cyan' => null,
'sky' => null,
'blue' => null,
'indigo' => null,
'violet' => null,
'purple' => null,
'fuchsia' => null,
'pink' => null,
'rose' => null,
'mauve' => null,
'olive' => null,
'mist' => null,
'taupe' => null,
],
];
}
/**
* Icon colors, by button style and colour.
*
* @return array<string, array<string, string|null>>
*/
public function iconColors(Component $component): array
{
return [
'solid' => [
'black' => null,
'primary' => null,
'secondary' => null,
'slate' => null,
'gray' => null,
'zinc' => null,
'neutral' => null,
'stone' => null,
'red' => null,
'orange' => null,
'amber' => null,
'yellow' => null,
'lime' => null,
'green' => null,
'emerald' => null,
'teal' => null,
'cyan' => null,
'sky' => null,
'blue' => null,
'indigo' => null,
'violet' => null,
'purple' => null,
'fuchsia' => null,
'pink' => null,
'rose' => null,
'mauve' => null,
'olive' => null,
'mist' => null,
'taupe' => null,
],
'outline' => [
'black' => null,
'primary' => null,
'secondary' => null,
'slate' => null,
'gray' => null,
'zinc' => null,
'neutral' => null,
'stone' => null,
'red' => null,
'orange' => null,
'amber' => null,
'yellow' => null,
'lime' => null,
'green' => null,
'emerald' => null,
'teal' => null,
'cyan' => null,
'sky' => null,
'blue' => null,
'indigo' => null,
'violet' => null,
'purple' => null,
'fuchsia' => null,
'pink' => null,
'rose' => null,
'mauve' => null,
'olive' => null,
'mist' => null,
'taupe' => null,
],
'light' => [
'black' => null,
'primary' => null,
'secondary' => null,
'slate' => null,
'gray' => null,
'zinc' => null,
'neutral' => null,
'stone' => null,
'red' => null,
'orange' => null,
'amber' => null,
'yellow' => null,
'lime' => null,
'green' => null,
'emerald' => null,
'teal' => null,
'cyan' => null,
'sky' => null,
'blue' => null,
'indigo' => null,
'violet' => null,
'purple' => null,
'fuchsia' => null,
'pink' => null,
'rose' => null,
'mauve' => null,
'olive' => null,
'mist' => null,
'taupe' => null,
],
'flat' => [
'black' => null,
'primary' => null,
'secondary' => null,
'slate' => null,
'gray' => null,
'zinc' => null,
'neutral' => null,
'stone' => null,
'red' => null,
'orange' => null,
'amber' => null,
'yellow' => null,
'lime' => null,
'green' => null,
'emerald' => null,
'teal' => null,
'cyan' => null,
'sky' => null,
'blue' => null,
'indigo' => null,
'violet' => null,
'purple' => null,
'fuchsia' => null,
'pink' => null,
'rose' => null,
'mauve' => null,
'olive' => null,
'mist' => null,
'taupe' => null,
],
'subtle' => [
'black' => null,
'primary' => null,
'secondary' => null,
'slate' => null,
'gray' => null,
'zinc' => null,
'neutral' => null,
'stone' => null,
'red' => null,
'orange' => null,
'amber' => null,
'yellow' => null,
'lime' => null,
'green' => null,
'emerald' => null,
'teal' => null,
'cyan' => null,
'sky' => null,
'blue' => null,
'indigo' => null,
'violet' => null,
'purple' => null,
'fuchsia' => null,
'pink' => null,
'rose' => null,
'mauve' => null,
'olive' => null,
'mist' => null,
'taupe' => null,
],
];
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace Database\Factories;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\BillingUnitModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<BillingUnitModel>
*/
class BillingUnitFactory extends Factory
{
protected $model = BillingUnitModel::class;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'customer_id' => CustomerModel::factory(),
'name' => fake()->company(),
'billing_address' => fake()->streetAddress()."\n".fake()->postcode().' '.fake()->city(),
'e_invoice_address' => null,
'e_invoice_operator' => null,
'reference' => null,
];
}
public function eInvoice(string $address = '003712345678', string $operator = '003721291126'): static
{
return $this->state(fn (): array => [
'e_invoice_address' => $address,
'e_invoice_operator' => $operator,
]);
}
}
@@ -0,0 +1,30 @@
<?php
namespace Database\Factories;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerContactModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<CustomerContactModel>
*/
class CustomerContactFactory extends Factory
{
protected $model = CustomerContactModel::class;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'customer_id' => CustomerModel::factory(),
'name' => fake()->name(),
'title' => fake()->optional()->jobTitle(),
'phone' => fake()->optional()->phoneNumber(),
'email' => fake()->optional()->safeEmail(),
'note' => null,
];
}
}
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('customer_contacts', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_id')->constrained()->cascadeOnDelete();
$table->string('name');
$table->string('title')->nullable();
$table->string('phone', 50)->nullable();
$table->string('email')->nullable();
$table->text('note')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('customer_contacts');
}
};
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('billing_units', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_id')->constrained()->cascadeOnDelete();
$table->string('name');
$table->text('billing_address')->nullable();
$table->string('e_invoice_address', 35)->nullable();
$table->string('e_invoice_operator', 35)->nullable();
$table->string('reference')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('billing_units');
}
};
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* A consumer's personal identity code, encrypted with the app key, and a
* keyed hash of it (blind index) so duplicates can be found without
* decrypting every row.
*/
public function up(): void
{
Schema::table('customers', function (Blueprint $table) {
$table->text('personal_identity_code')->nullable()->after('business_id');
$table->char('personal_identity_code_hash', 64)->nullable()->unique()->after('personal_identity_code');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('customers', function (Blueprint $table) {
$table->dropUnique(['personal_identity_code_hash']);
$table->dropColumn(['personal_identity_code', 'personal_identity_code_hash']);
});
}
};
+2 -1
View File
@@ -20,7 +20,8 @@ app/
├── Providers/AppServiceProvider.php
└── Modules/
├── Shared/ # vain aidosti yhteiset, vakaat käsitteet
│ ├── Domain/Exceptions/DomainException.php
│ ├── Domain/Exceptions/{DomainException, InvalidEmailAddress}.php
│ ├── Domain/ValueObjects/EmailAddress.php # käyttäjät ja asiakkaiden yhteyshenkilöt
│ ├── Application/Contracts/{TransactionManager, EventDispatcher}.php
│ └── Infrastructure/
│ ├── Persistence/LaravelTransactionManager.php
+14 -6
View File
@@ -71,6 +71,7 @@ Nimi, sähköposti, rooli (yksi per käyttäjä, *K13*), aktiivinen, harjoitteli
| Laskuaineiston muodostus | ✔ | ✔ | – | – | – |
| Raportit | ✔ | ✔ | – | – | – |
| Rahamäärät | ✔ | ✔ | ◐ 2.3 | ◐ 2.3 | – |
| Kuluttajan henkilötunnus | ✔ näkee ja poistaa | ✔ näkee ja poistaa | ◐ syöttää, näkee peitettynä | ◐ syöttää, näkee peitettynä | – |
## 3. Kirjautuminen ja salasanat *(K4, K15)*
@@ -87,8 +88,13 @@ Nimi, sähköposti, rooli (yksi per käyttäjä, *K13*), aktiivinen, harjoitteli
## 4. Asiakas *(K16, K17)*
- Nimi, tyyppi (yritys / kuluttaja), Y-tunnus (vain yritykselle).
- **Yhteyshenkilöt**: useita; nimi, puhelin, sähköposti, rooli/huomio.
- **Laskutusyksiköt**: useita; nimi, laskutusosoite tai verkkolaskuosoite, viite. Saman asiakkaan eri laskutusyksiköt laskutetaan omilla laskuillaan.
- **Henkilötunnus** (vain kuluttajalle): tarvitaan, kun kuluttajalle lähetetään lasku. Ei pakollinen asiakasta luotaessa eikä pikavastaanotossa; käteis- ja korttimyynti ei tarvitse sitä. Henkilötunnus on erityisen suojattava tieto (tietosuojalaki 29 §), ja sitä käytetään vain asiakkaan yksilöintiin laskutuksessa ja perinnässä:
- Tallennetaan salattuna. Päällekkäisyys tarkistetaan avaimellisella tiivisteellä, joten tunnusta ei voi hakea eikä se näy listoissa.
- Pääkäyttäjä ja johto näkevät koko tunnuksen ja voivat poistaa sen. Työntekijä ja harjoittelija voivat syöttää tai vaihtaa tunnuksen, mutta näkevät vain peitetyn muodon (`••••••-308T`).
- Lomake ei koskaan näytä tallennettua tunnusta; tyhjä kenttä säilyttää sen. Kun kuluttaja muutetaan yritykseksi, tunnus poistetaan.
- **Yhteyshenkilöt**: useita; nimi (pakollinen), titteli tai rooli, puhelin, sähköposti ja lisätieto.
- **Laskutusyksiköt**: useita; nimi (pakollinen, oletuksena asiakkaan nimi), laskutusosoite (vapaa teksti: postiosoite tai laskutussähköposti), verkkolaskuosoite (12–35 kirjainta tai numeroa), välittäjätunnus (pakollinen, jos verkkolaskuosoite on annettu) ja viite. Saman asiakkaan eri laskutusyksiköt laskutetaan omilla laskuillaan.
- Asiakkaalla on oma sivu, jolla näkyvät perustiedot, yhteyshenkilöt ja laskutusyksiköt. Uuden asiakkaan tallennus vie asiakkaan sivulle.
- Asiakastyön vastaanotossa riittää asiakkaan nimi (ja tyyppi); muut tiedot täydennetään myöhemmin.
- Yrityksen oma sisäinen asiakas, jonka asiakastöihin kirjataan sisäinen työ (hallinto, myynti, koulutus) *(K39)*.
@@ -286,6 +292,7 @@ Hierarkiaa muokataan pohjatietojen hallinnasta.
- Aineistoon tulevat valmiit, hyväksytyt ja laskuttamattomat tunnit ja kulut sekä kuukausilaskutusrivit.
- Tuntityö: aineistoa muodostaessaan johto näkee jokaiselle työlle hyväksytyt tunnit työtehtävittäin ja kirjaa niiden perusteella laskutettavan kokonaistuntimäärän (oletuksena hyväksyttyjen tuntien summa). Laskutettava määrä voi poiketa kirjatuista tunneista, ja molemmat tallennetaan, jotta ero näkyy raporteissa.
- Laskulle tulee työtehtävittäin rivi: laskutettavat tunnit × tuntihinta. Kulut eriteltyinä.
- **Kuluttajan laskutus** vaatii henkilötunnuksen: laskuaineistoa ei muodosteta kuluttajalle, jolta tunnus puuttuu, vaan puute näytetään johdolle.
- **Laskun peruste**: lasku tehdään joko yhdestä asiakastyöstä tai yhdistämällä useampi saman asiakkaan ja saman laskutusyksikön asiakastyö yhdelle laskulle. Johto valitsee aineistoa muodostaessaan, mitkä työt yhdistetään. Eri laskutusyksiköiden töitä ei yhdistetä samalle laskulle. Töitä, joilla on eri asiakkaan viite (PO-numero), ei myöskään yhdistetä: niistä tehdään omat laskunsa. Töitä, joilla ei ole viitettä, voi yhdistää keskenään tai saman viitteen töihin.
- Yhdistetyllä laskulla rivit ryhmitellään asiakastöittäin (työn numero ja nimi otsikkona), jotta asiakas näkee, mistä työstä kukin rivi tulee.
- Aineiston muodostus asettaa töille tilan "Lasku luotu" ja merkitsee rivit laskutetuiksi, jotta niitä ei laskuteta kahdesti.
@@ -304,9 +311,9 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up
- `user_money_permissions` *(V2)*: `user_id`, `can_see_prices`, `can_see_expenses`, `can_see_quotes`, `can_see_billing`
**Customers**
- `customers`: `name`, `type` (`company`/`consumer`), `business_id`, `is_internal` *(olemassa, `is_internal` lisätään)*
- `customer_contacts`: `customer_id`, `name`, `phone`, `email`, `note`
- `billing_units`: `customer_id`, `name`, `billing_address`, `e_invoice_address`, `e_invoice_operator`, `reference`
- `customers`: `name`, `type` (`company`/`consumer`), `business_id`, `personal_identity_code` (salattu), `personal_identity_code_hash` (HMAC, uniikki), `is_internal` *(olemassa, `is_internal` lisätään)*
- `customer_contacts`: `customer_id`, `name`, `title`, `phone`, `email`, `note` *(olemassa)*
- `billing_units`: `customer_id`, `name`, `billing_address`, `e_invoice_address`, `e_invoice_operator`, `reference` *(olemassa)*
**Catalog** (palveluyksiköt ja hinnasto)
- `service_units`: `name`, `sort_order`, `is_shared` (kaikille yhteiset)
@@ -381,7 +388,8 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t
- Kun pääkäyttäjä luo käyttäjän tai pyytää uutta salasanalinkkiä, linkki lähetetään sähköpostiin ja näytetään pääkäyttäjälle kopioitavana. Kopiointi ilmoitetaan ruudunlukijalle.
### 16.2 Asiakkaat
- Asiakkaalle voi lisätä, muokata ja poistaa yhteyshenkilöitä ja laskutusyksiköitä asiakkaan sivulla.
- Asiakkaalle voi lisätä, muokata ja poistaa yhteyshenkilöitä ja laskutusyksiköitä asiakkaan sivulla *(valmis)*. Poisto vahvistetaan dialogissa.
- Kun asiakastyöt viittaavat yhteyshenkilöön tai laskutusyksikköön, käytössä olevan rivin poisto estetään.
- Sisäinen asiakas on merkitty, eikä sitä voi poistaa.
### 16.3 Pohjatiedot
+73 -1
View File
@@ -15,14 +15,75 @@ return [
'empty' => 'Asiakkaita ei löytynyt.',
'result_count' => '{0} Ei asiakkaita|{1} :count asiakas|[2,*] :count asiakasta',
'created' => 'Asiakas :name lisätty.',
'created' => 'Asiakas :name lisätty. Voit nyt lisätä yhteyshenkilöt ja laskutusyksiköt.',
'updated' => 'Asiakkaan :name tiedot tallennettu.',
'edit_details' => 'Muokkaa tietoja',
'remove' => 'Poista',
'customer_label' => 'Asiakas',
'contacts' => [
'title' => 'Yhteyshenkilöt',
'new' => 'Lisää yhteyshenkilö',
'empty' => 'Asiakkaalle ei ole vielä lisätty yhteyshenkilöitä.',
'create_title' => 'Uusi yhteyshenkilö',
'edit_title' => 'Muokkaa yhteyshenkilöä',
'edit_named' => 'Muokkaa yhteyshenkilöä :name',
'remove_named' => 'Poista yhteyshenkilö :name',
'created' => 'Yhteyshenkilö :name lisätty.',
'updated' => 'Yhteyshenkilön :name tiedot tallennettu.',
'fields' => [
'name' => 'Nimi',
'title' => 'Titteli tai rooli',
'title_description' => 'Esimerkiksi markkinointipäällikkö tai laskujen hyväksyjä.',
'phone' => 'Puhelin',
'email' => 'Sähköposti',
'note' => 'Lisätieto',
],
],
'billing_units' => [
'title' => 'Laskutusyksiköt',
'new' => 'Lisää laskutusyksikkö',
'empty' => 'Asiakkaalle ei ole vielä lisätty laskutusyksiköitä.',
'create_title' => 'Uusi laskutusyksikkö',
'edit_title' => 'Muokkaa laskutusyksikköä',
'edit_named' => 'Muokkaa laskutusyksikköä :name',
'remove_named' => 'Poista laskutusyksikkö :name',
'created' => 'Laskutusyksikkö :name lisätty.',
'updated' => 'Laskutusyksikön :name tiedot tallennettu.',
'fields' => [
'name' => 'Nimi',
'name_description' => 'Jokainen laskutusyksikkö saa omat laskunsa.',
'billing_address' => 'Laskutusosoite',
'billing_address_description' => 'Postiosoite paperilaskulle tai laskutussähköposti.',
'e_invoice_address' => 'Verkkolaskuosoite',
'e_invoice_address_description' => 'Esimerkiksi OVT-tunnus 003712345678. Ei pakollinen.',
'e_invoice_operator' => 'Välittäjätunnus',
'e_invoice_operator_description' => 'Verkkolaskuoperaattorin tunnus, esimerkiksi 003721291126. Pakollinen, jos verkkolaskuosoite on annettu.',
'reference' => 'Viite',
'reference_description' => 'Asiakkaan pyytämä viite, joka tulostuu laskulle.',
],
],
'removal' => [
'title' => 'Vahvista poisto',
'question_contact' => 'Poistetaanko yhteyshenkilö :name? Poistoa ei voi perua.',
'question_billing_unit' => 'Poistetaanko laskutusyksikkö :name? Poistoa ei voi perua.',
'removed_contact' => 'Yhteyshenkilö :name poistettu.',
'removed_billing_unit' => 'Laskutusyksikkö :name poistettu.',
'already_removed' => 'Riviä ei löytynyt. Se on ehkä jo poistettu.',
],
'fields' => [
'name' => 'Nimi',
'type' => 'Asiakastyyppi',
'business_id' => 'Y-tunnus',
'business_id_description' => 'Muodossa 1234567-8. Ei pakollinen.',
'personal_identity_code' => 'Henkilötunnus',
'personal_identity_code_description' => 'Tarvitaan, kun kuluttajalle lähetetään lasku. Muodossa 131052-308T. Ei pakollinen.',
'personal_identity_code_stored' => 'Tallennettu: :code. Jätä tyhjäksi, jos et muuta sitä.',
'personal_identity_code_missing' => 'Ei annettu – tarvitaan laskutukseen',
'remove_personal_identity_code' => 'Poista tallennettu henkilötunnus',
],
'types' => [
@@ -37,5 +98,16 @@ return [
'invalid_business_id' => 'Y-tunnus ei ole kelvollinen. Tarkista numerot ja muoto 1234567-8.',
'consumer_business_id' => 'Kuluttaja-asiakkaalla ei voi olla Y-tunnusta.',
'business_id_taken' => 'Tällä Y-tunnuksella on jo asiakas.',
'invalid_personal_identity_code' => 'Henkilötunnus ei ole kelvollinen. Tarkista päivämäärä, välimerkki ja tarkistusmerkki, esimerkiksi 131052-308T.',
'company_personal_identity_code' => 'Yritysasiakkaalla ei voi olla henkilötunnusta.',
'personal_identity_code_taken' => 'Tällä henkilötunnuksella on jo asiakas. Hae asiakas listasta nimellä.',
'contact_name_required' => 'Anna yhteyshenkilön nimi.',
'invalid_contact_name' => 'Nimen pituus voi olla enintään 255 merkkiä.',
'invalid_email' => 'Sähköpostiosoite ei ole kelvollinen.',
'billing_unit_name_required' => 'Anna laskutusyksikön nimi.',
'invalid_billing_unit_name' => 'Nimen pituus voi olla enintään 255 merkkiä.',
'invalid_e_invoice_address' => 'Verkkolaskuosoitteessa on oltava 12–35 kirjainta tai numeroa, esimerkiksi 003712345678.',
'e_invoice_operator_required' => 'Anna välittäjätunnus, koska verkkolaskuosoite on annettu.',
'too_long' => 'Teksti voi olla enintään :max merkkiä.',
],
];
+1
View File
@@ -9,4 +9,5 @@ return [
'signed_in_as' => 'Kirjautuneena: :name',
'logout' => 'Kirjaudu ulos',
'theme_toggle' => 'Tumma teema',
'cancel' => 'Peruuta',
];
@@ -0,0 +1,41 @@
{{--
Modal confirmation dialog built on the native <dialog> element.
Not <x-modal />: TallStackUI's modal points aria-labelledby at an id its
title does not have, its close button has no name, and it neither moves
focus into the dialog nor returns it (WCAG 2.4.3, 4.1.2). showModal()
gives a real modal: focus moves in and is kept there, Escape closes it,
and closing returns focus to the button that opened it.
Open it from Livewire with $this->js("document.getElementById('<id>').showModal()").
wire:ignore.self keeps the browser-set open attribute when Livewire
re-renders the page; the content inside still updates.
--}}
@props([
'id',
'title',
])
<dialog
id="{{ $id }}"
aria-labelledby="{{ $id }}-title"
wire:ignore.self
{{ $attributes->class('m-auto w-[calc(100%-2rem)] max-w-md rounded-xl bg-white p-6 text-zinc-900 shadow-xl backdrop:bg-black/50 dark:bg-zinc-800 dark:text-zinc-100') }}
>
<h2 id="{{ $id }}-title" class="text-lg font-semibold">{{ $title }}</h2>
<div class="mt-3 text-sm">
{{ $slot }}
</div>
<div class="mt-6 flex flex-wrap justify-end gap-3">
<x-button
subtle
color="black"
:text="__('layout.cancel')"
x-on:click="document.getElementById('{{ $id }}').close()"
/>
{{ $actions }}
</div>
</dialog>
+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 () {