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,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