Add modular layered architecture with Customers module

Introduce a modular monolith under app/Modules with Domain, Application,
Infrastructure and Presentation layers.

- Shared module: DomainException base, TransactionManager and an
  EventDispatcher that publishes events after commit.
- Customers module: Customer entity, CustomerName and BusinessId
  (Y-tunnus checksum) value objects, RegisterCustomer/UpdateCustomer
  use cases, CustomerQueries read contract, Eloquent repository, and
  Livewire list and form pages with Finnish translations.
- Pest arch tests enforce layer and module dependency rules for every
  module; Larastan (level 6) added as a dev dependency.
- Raise Flux error text contrast to meet WCAG 2.2 AA.
- Document the architecture in docs/architecture.md and CLAUDE.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-22 10:23:33 +02:00
co-authored by Claude Opus 5.5
parent d403a86443
commit a3fb09bbf6
55 changed files with 2270 additions and 3 deletions
+10
View File
@@ -98,6 +98,16 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac
- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications.
- Activate the `deploying-to-cloud` skill whenever deploying to Laravel Cloud, configuring Cloud environments or resources, using the Cloud CLI, or troubleshooting Cloud deployments.
=== tests rules ===
# Test Enforcement
- Add or update tests for behavior and logic changes when a test provides meaningful regression coverage.
- Pure copy, styling, and layout-only changes do not require new or updated tests.
- When test coverage applies, run the affected tests and ensure they pass.
- Test the changed behavior and its important failure modes, but do not add tests beyond them.
- Read the `testing-best-practices` skill before writing tests.
=== laravel/core rules ===
# Do Things the Laravel Way
+26 -2
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), Flux UI 2 free edition, Tailwind 4, Vite 8, Pest. No domain code exists yet; `/` is a temporary Livewire demo page (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`).
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), Flux UI 2 free edition, Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared` and `Customers`); `/` is still a temporary Livewire demo page (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`). There is no login yet, so module pages sit behind `auth` and are reachable only in tests (`actingAs`).
- **The specification is `määrittely.txt`** (Finnish). It defines users/roles, customer jobs (*asiakastyö*) and their fields and enums, time tracking, expenses, Kanban tasks, the service unit → service → work task hierarchy, and billing-material export. It ends with Claude's open questions and a proposed phased plan. Read it before designing any domain feature.
- **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start.
@@ -12,6 +12,19 @@ An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5
- **Access control is central.** Roles: admin (*pääkäyttäjä*), management (*johto*), employee (*työntekijä*), intern (*harjoittelija*), subcontractor (*alihankkija*). Employees and interns see only the jobs assigned to them and never see money amounts. Interns have an end date after which they can't log in, plus a supervisor. Subcontractors see only their assigned jobs.
- **UI targets:** logged-in users only (no public pages besides login). It must work on phones (new-job intake, time entry) and on FullHD desktops.
## Architecture (modular monolith)
Read `docs/architecture.md` (Finnish) before adding or changing domain code. `app/Modules/Customers` is the reference module to copy.
- Each business area is a module `app/Modules/<Module>/` with four layers: `Domain`, `Application`, `Infrastructure`, `Presentation`. Create only the folders and modules a feature needs.
- **Domain** is plain PHP: entities, value objects, enums, exceptions extending `Shared\Domain\Exceptions\DomainException`, and repository interfaces in `Domain/Contracts`. No `Illuminate`, `Livewire`, Eloquent or facades.
- **Application** holds one use case per class (`execute()`), `final readonly` DTOs, and query contracts that return DTOs. It never touches Eloquent, `Illuminate\Database`, facades or HTTP. Wrap writes in `Shared\Application\Contracts\TransactionManager` and publish events through `EventDispatcher` (dispatched after commit).
- **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`.
- **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`<module>::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages.
- Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models.
- `tests/Unit/ArchitectureTest.php` enforces these rules for every module. Domain and Application files declare `strict_types=1`. Test domain rules and use cases in `tests/Unit` without Laravel (fakes in `tests/Fakes`), and repositories and pages in `tests/Feature`.
- When writing PHP through a bash heredoc, `\\` can collapse to `\`, and `"App\Modules\{$x}"` then stops interpolating. Write PHP files with the Write tool.
## Accessibility (WCAG 2.2 AA, EN 301 549)
Accessibility is a contractual acceptance criterion. It covers the whole UI: navigation, forms, tables, reports, notifications, dialogs, login, and every business process. Every new or changed view must meet these rules:
@@ -23,7 +36,7 @@ Accessibility is a contractual acceptance criterion. It covers the whole UI: nav
- 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 `flux:table` with column headers. Icon-only buttons need an accessible name (`aria-label` or Flux `tooltip`). Decorative images get `alt=""`.
- Contrast is at least 4.5:1 for text and 3:1 for UI components and focus indicators, in both light and dark mode.
- Contrast is at least 4.5:1 for text and 3:1 for UI components and focus indicators, in both light and dark mode. Flux's default error text (red-500) fails this, so `resources/css/app.css` overrides `[data-flux-error]`.
- Layouts must reflow at 320 px width and 400 % zoom without horizontal scrolling. Touch targets are at least 24×24 px.
- Every new page gets a browser test in `tests/Browser` that uses `assertNoAccessibilityIssues(level: 2)` in light and dark mode and on desktop and mobile. See `tests/Browser/AccessibilityTest.php`. Automated axe checks catch only part of WCAG: also check new flows manually with the keyboard and a screen reader (NVDA).
@@ -36,6 +49,7 @@ npm run build # build frontend assets
php artisan test --compact # full suite (composer test also clears config first)
php artisan test --compact --filter=testName
vendor/bin/pint --dirty --format agent
composer analyse # Larastan level 6 (Blade SFCs excluded)
```
- Runs under XAMPP: Apache on port 8080 serves the app at `http://localhost:8080/toiminnanohjaus/public` (this is `APP_URL`). The database is XAMPP MariaDB 10.11 `toiminnanohjaus` (root, no password).
@@ -146,6 +160,16 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac
- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications.
- Activate the `deploying-to-cloud` skill whenever deploying to Laravel Cloud, configuring Cloud environments or resources, using the Cloud CLI, or troubleshooting Cloud deployments.
=== tests rules ===
# Test Enforcement
- Add or update tests for behavior and logic changes when a test provides meaningful regression coverage.
- Pure copy, styling, and layout-only changes do not require new or updated tests.
- When test coverage applies, run the affected tests and ensure they pass.
- Test the changed behavior and its important failure modes, but do not add tests beyond them.
- Read the `testing-best-practices` skill before writing tests.
=== laravel/core rules ===
# Do Things the Laravel Way
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\Contracts;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
/**
* Read side of the Customers module. Other modules use this contract to
* look up customers, never the module's Eloquent model.
*/
interface CustomerQueries
{
public function findSummary(int $id): ?CustomerSummary;
/**
* Customers ordered by name, filtered by a name or business ID fragment.
*
* @return LengthAwarePaginator<int, CustomerSummary>
*/
public function paginate(?string $search, int $perPage = 25): LengthAwarePaginator;
/**
* Best name matches for autocomplete.
*
* @return list<CustomerSummary>
*/
public function search(string $term, int $limit = 10): array;
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\DTOs;
use App\Modules\Customers\Domain\Enums\CustomerType;
/**
* Input for registering a customer or changing its details.
*/
final readonly class CustomerDetailsData
{
public function __construct(
public string $name,
public CustomerType $type,
public ?string $businessId = null,
) {}
/**
* @param array{name: string, type: string|CustomerType, business_id?: string|null} $data
*/
public static function fromArray(array $data): self
{
$businessId = isset($data['business_id']) ? trim($data['business_id']) : null;
return new self(
name: $data['name'],
type: $data['type'] instanceof CustomerType ? $data['type'] : CustomerType::from($data['type']),
businessId: $businessId === '' ? null : $businessId,
);
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\DTOs;
use App\Modules\Customers\Domain\Enums\CustomerType;
/**
* Read model of a customer for lists, search and other modules.
*/
final readonly class CustomerSummary
{
public function __construct(
public int $id,
public string $name,
public CustomerType $type,
public ?string $businessId,
) {}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases;
use App\Modules\Customers\Application\DTOs\CustomerDetailsData;
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\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Shared\Application\Contracts\EventDispatcher;
use App\Modules\Shared\Application\Contracts\TransactionManager;
final class RegisterCustomer
{
public function __construct(
private CustomerRepository $customers,
private TransactionManager $transactions,
private EventDispatcher $events,
) {}
/**
* @return int The new customer's id.
*
* @throws BusinessIdAlreadyInUse
*/
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);
return $this->transactions->run(function () use ($customer, $businessId): int {
if ($businessId !== null && $this->customers->isBusinessIdTaken($businessId)) {
throw new BusinessIdAlreadyInUse($businessId);
}
$customerId = (int) $this->customers->save($customer)->id();
$this->events->dispatch(new CustomerRegistered($customerId));
return $customerId;
});
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases;
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\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
final class UpdateCustomer
{
public function __construct(
private CustomerRepository $customers,
private TransactionManager $transactions,
) {}
/**
* @throws CustomerNotFound
* @throws BusinessIdAlreadyInUse
*/
public function execute(int $customerId, CustomerDetailsData $data): void
{
$name = new CustomerName($data->name);
$businessId = $data->businessId === null ? null : new BusinessId($data->businessId);
$this->transactions->run(function () use ($customerId, $name, $data, $businessId): 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);
$this->customers->save($customer);
});
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Contracts;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
interface CustomerRepository
{
public function findById(int $id): ?Customer;
/**
* Inserts a new customer or updates a stored one, and returns the
* stored customer (a new one gets its id here).
*/
public function save(Customer $customer): Customer;
public function isBusinessIdTaken(BusinessId $businessId, ?int $exceptCustomerId = null): bool;
}
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Entities;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\ConsumerCannotHaveBusinessId;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
/**
* A customer of the company: a business or a private consumer.
*
* Only the name is needed at job intake; other details are added later.
*/
final class Customer
{
private function __construct(
private ?int $id,
private CustomerName $name,
private CustomerType $type,
private ?BusinessId $businessId,
) {
self::ensureBusinessIdFitsType($type, $businessId);
}
/**
* 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);
}
/**
* 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 function changeDetails(CustomerName $name, CustomerType $type, ?BusinessId $businessId): void
{
self::ensureBusinessIdFitsType($type, $businessId);
$this->name = $name;
$this->type = $type;
$this->businessId = $businessId;
}
public function id(): ?int
{
return $this->id;
}
public function name(): CustomerName
{
return $this->name;
}
public function type(): CustomerType
{
return $this->type;
}
public function businessId(): ?BusinessId
{
return $this->businessId;
}
private static function ensureBusinessIdFitsType(CustomerType $type, ?BusinessId $businessId): void
{
if ($type === CustomerType::Consumer && $businessId !== null) {
throw new ConsumerCannotHaveBusinessId;
}
}
}
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Enums;
enum CustomerType: string
{
case Company = 'company';
case Consumer = 'consumer';
}
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Events;
final readonly class CustomerRegistered
{
public function __construct(public int $customerId) {}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class BusinessIdAlreadyInUse extends DomainException
{
public function __construct(public readonly BusinessId $businessId)
{
parent::__construct("Business ID {$businessId->value} already belongs to another customer.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ConsumerCannotHaveBusinessId extends DomainException
{
public function __construct()
{
parent::__construct('A consumer customer cannot have a business ID.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class CustomerNotFound extends DomainException
{
public function __construct(public readonly int $customerId)
{
parent::__construct("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 InvalidBusinessId extends DomainException
{
public function __construct()
{
parent::__construct('The business ID is not a valid Finnish business ID.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidCustomerName extends DomainException
{
public function __construct()
{
parent::__construct('The customer name must be 1–255 characters.');
}
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\ValueObjects;
use App\Modules\Customers\Domain\Exceptions\InvalidBusinessId;
/**
* Finnish business ID (Y-tunnus), e.g. 0737546-2.
*
* Seven digits, a hyphen and a check digit. Old six-digit IDs are
* accepted and padded with a leading zero.
*/
final readonly class BusinessId
{
private const array WEIGHTS = [7, 9, 10, 5, 8, 4, 2];
public string $value;
public function __construct(string $value)
{
$value = trim($value);
if (preg_match('/^(\d{6,7})-(\d)$/', $value, $matches) !== 1) {
throw new InvalidBusinessId;
}
$digits = str_pad($matches[1], 7, '0', STR_PAD_LEFT);
if (self::checkDigitFor($digits) !== (int) $matches[2]) {
throw new InvalidBusinessId;
}
$this->value = "{$digits}-{$matches[2]}";
}
public function equals(self $other): bool
{
return $this->value === $other->value;
}
/**
* Returns null when no valid check digit exists (remainder 1).
*/
private static function checkDigitFor(string $digits): ?int
{
$sum = 0;
foreach (str_split($digits) as $index => $digit) {
$sum += (int) $digit * self::WEIGHTS[$index];
}
$remainder = $sum % 11;
return match ($remainder) {
0 => 0,
1 => null,
default => 11 - $remainder,
};
}
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\ValueObjects;
use App\Modules\Customers\Domain\Exceptions\InvalidCustomerName;
final readonly class CustomerName
{
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 InvalidCustomerName;
}
$this->value = $value;
}
public function equals(self $other): bool
{
return $this->value === $other->value;
}
}
@@ -0,0 +1,40 @@
<?php
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\Table;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model of a customer. Used only inside the Customers
* Infrastructure layer; everything else works with the Customer entity
* or the CustomerSummary read model.
*
* @property int $id
* @property string $name
* @property CustomerType $type
* @property string|null $business_id
*/
#[Table('customers')]
#[Fillable(['name', 'type', 'business_id'])]
#[UseFactory(CustomerFactory::class)]
class CustomerModel extends Model
{
/** @use HasFactory<CustomerFactory> */
use HasFactory;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'type' => CustomerType::class,
];
}
}
@@ -0,0 +1,59 @@
<?php
namespace App\Modules\Customers\Infrastructure\Persistence\Repositories;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
class EloquentCustomerQueries implements CustomerQueries
{
public function findSummary(int $id): ?CustomerSummary
{
$model = CustomerModel::query()->find($id);
return $model === null ? null : $this->toSummary($model);
}
public function paginate(?string $search, int $perPage = 25): LengthAwarePaginator
{
return $this->matching($search)
->orderBy('name')
->paginate($perPage)
->through(fn (CustomerModel $model): CustomerSummary => $this->toSummary($model));
}
public function search(string $term, int $limit = 10): array
{
return $this->matching($term)
->orderBy('name')
->limit($limit)
->get()
->map(fn (CustomerModel $model): CustomerSummary => $this->toSummary($model))
->values()
->all();
}
/**
* @return Builder<CustomerModel>
*/
private function matching(?string $search): Builder
{
$search = trim((string) $search);
return CustomerModel::query()->when($search !== '', function (Builder $query) use ($search): void {
$pattern = '%'.addcslashes($search, '%_\\').'%';
$query->where(fn (Builder $query) => $query
->where('name', 'like', $pattern)
->orWhere('business_id', 'like', $pattern));
});
}
private function toSummary(CustomerModel $model): CustomerSummary
{
return new CustomerSummary($model->id, $model->name, $model->type, $model->business_id);
}
}
@@ -0,0 +1,52 @@
<?php
namespace App\Modules\Customers\Infrastructure\Persistence\Repositories;
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\Infrastructure\Persistence\Eloquent\CustomerModel;
class EloquentCustomerRepository implements CustomerRepository
{
public function findById(int $id): ?Customer
{
$model = CustomerModel::query()->find($id);
return $model === null ? null : $this->toEntity($model);
}
public function save(Customer $customer): Customer
{
$model = $customer->id() === null
? new CustomerModel
: CustomerModel::query()->findOrFail($customer->id());
$model->fill([
'name' => $customer->name()->value,
'type' => $customer->type(),
'business_id' => $customer->businessId()?->value,
])->save();
return $this->toEntity($model);
}
public function isBusinessIdTaken(BusinessId $businessId, ?int $exceptCustomerId = null): bool
{
return CustomerModel::query()
->where('business_id', $businessId->value)
->when($exceptCustomerId !== null, fn ($query) => $query->whereKeyNot($exceptCustomerId))
->exists();
}
private function toEntity(CustomerModel $model): Customer
{
return Customer::reconstitute(
$model->id,
new CustomerName($model->name),
$model->type,
$model->business_id === null ? null : new BusinessId($model->business_id),
);
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Modules\Customers\Infrastructure\Providers;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerQueries;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerRepository;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;
/**
* Wires the Customers module into Laravel: contract bindings, routes and
* the `customers::` Livewire namespace.
*/
class CustomersServiceProvider extends ServiceProvider
{
/**
* @var array<class-string, class-string>
*/
public array $bindings = [
CustomerRepository::class => EloquentCustomerRepository::class,
CustomerQueries::class => EloquentCustomerQueries::class,
];
public function boot(): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
Livewire::addNamespace('customers', viewPath: $presentationPath.'/Livewire');
if (! $this->app->routesAreCached()) {
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
}
}
}
@@ -0,0 +1,90 @@
<?php
namespace App\Modules\Customers\Presentation\Livewire\Forms;
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\ConsumerCannotHaveBusinessId;
use App\Modules\Customers\Domain\Exceptions\InvalidBusinessId;
use App\Modules\Customers\Domain\Exceptions\InvalidCustomerName;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Illuminate\Validation\Rule;
use Livewire\Form;
/**
* Customer details form shared by the create and edit pages.
*
* Validates only the shape of the input. Business rules (business ID
* checksum, consumer without business ID, uniqueness) stay in the Domain,
* and their exceptions are shown as field errors by showDomainError().
*/
class CustomerForm extends Form
{
public string $name = '';
public string $type = CustomerType::Company->value;
public string $business_id = '';
public function fillFromSummary(CustomerSummary $customer): void
{
$this->name = $customer->name;
$this->type = $customer->type->value;
$this->business_id = $customer->businessId ?? '';
}
public function toData(): CustomerDetailsData
{
$this->validate();
return CustomerDetailsData::fromArray([
'name' => $this->name,
'type' => $this->type,
'business_id' => $this->type === CustomerType::Consumer->value ? null : $this->business_id,
]);
}
/**
* Shows a broken business rule as an error on the field it concerns.
*/
public function showDomainError(DomainException $exception): void
{
[$field, $key] = match ($exception::class) {
InvalidCustomerName::class => ['name', 'customers.errors.invalid_name'],
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'],
default => throw $exception,
};
$this->addError($field, __($key));
}
/**
* @return array<string, array<int, mixed>>
*/
protected function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'type' => ['required', Rule::enum(CustomerType::class)],
'business_id' => ['nullable', 'string', 'max:20'],
];
}
/**
* @return array<string, string>
*/
protected function messages(): array
{
return [
'name.required' => __('customers.errors.name_required'),
'name.max' => __('customers.errors.invalid_name'),
'type.required' => __('customers.errors.type_required'),
'type.enum' => __('customers.errors.type_required'),
'business_id.max' => __('customers.errors.invalid_business_id'),
];
}
}
@@ -0,0 +1,102 @@
<?php
use App\Modules\Customers\Application\Contracts\CustomerQueries;
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\Presentation\Livewire\Forms\CustomerForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Livewire\Component;
/**
* Create page (no route parameter) and edit page (with {customer}).
*/
new class extends Component
{
public ?int $customerId = null;
public CustomerForm $form;
public function mount(CustomerQueries $customerQueries, ?int $customer = null): void
{
if ($customer === null) {
return;
}
$summary = $customerQueries->findSummary($customer);
abort_if($summary === null, 404);
$this->customerId = $summary->id;
$this->form->fillFromSummary($summary);
}
public function save(RegisterCustomer $registerCustomer, UpdateCustomer $updateCustomer): void
{
$data = $this->form->toData();
try {
if ($this->customerId === null) {
$registerCustomer->execute($data);
session()->flash('status', __('customers.created', ['name' => $data->name]));
} else {
$updateCustomer->execute($this->customerId, $data);
session()->flash('status', __('customers.updated', ['name' => $data->name]));
}
} catch (DomainException $exception) {
$this->form->showDomainError($exception);
return;
}
$this->redirectRoute('customers.index', navigate: true);
}
public function render(): mixed
{
return $this->view()->title(__($this->customerId === null ? 'customers.create_title' : 'customers.edit_title'));
}
};
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<flux:heading size="xl" level="1">
{{ __($customerId === null ? 'customers.create_title' : 'customers.edit_title') }}
</flux:heading>
<form wire:submit="save" class="space-y-6" novalidate>
<flux:input
wire:model="form.name"
:label="__('customers.fields.name')"
autocomplete="organization"
required
/>
<flux:radio.group wire:model.live="form.type" :label="__('customers.fields.type')">
@foreach (CustomerType::cases() as $customerType)
<flux:radio
wire:key="type-{{ $customerType->value }}"
:value="$customerType->value"
:label="__('customers.types.'.$customerType->value)"
/>
@endforeach
</flux:radio.group>
@if ($form->type === CustomerType::Company->value)
<flux:input
wire:model="form.business_id"
:label="__('customers.fields.business_id')"
:description="__('customers.fields.business_id_description')"
inputmode="numeric"
autocomplete="off"
/>
@endif
<div class="flex flex-wrap gap-3">
<flux:button type="submit" variant="primary">{{ __('customers.save') }}</flux:button>
<flux:button :href="route('customers.index')" wire:navigate variant="ghost">
{{ __('customers.cancel') }}
</flux:button>
</div>
</form>
</div>
@@ -0,0 +1,98 @@
<?php
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;
new class extends Component
{
use WithPagination;
#[Url(as: 'q', except: '')]
public string $search = '';
protected CustomerQueries $customerQueries;
public function boot(CustomerQueries $customerQueries): void
{
$this->customerQueries = $customerQueries;
}
public function updatedSearch(): void
{
$this->resetPage();
}
/**
* @return LengthAwarePaginator<int, CustomerSummary>
*/
#[Computed]
public function customers(): LengthAwarePaginator
{
return $this->customerQueries->paginate($this->search);
}
public function render(): mixed
{
return $this->view()->title(__('customers.title'));
}
};
?>
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="flex flex-wrap items-center justify-between gap-4">
<flux:heading size="xl" level="1">{{ __('customers.title') }}</flux:heading>
<flux:button :href="route('customers.create')" wire:navigate variant="primary" icon="plus">
{{ __('customers.new') }}
</flux:button>
</div>
@if (session('status'))
<flux:callout variant="success" icon="check-circle" role="status" :heading="session('status')" />
@endif
<flux:input
wire:model.live.debounce.300ms="search"
type="search"
icon="magnifying-glass"
:label="__('customers.search')"
:description="__('customers.search_description')"
/>
<flux:text role="status" aria-live="polite" aria-atomic="true">
{{ trans_choice('customers.result_count', $this->customers->total(), ['count' => $this->customers->total()]) }}
</flux:text>
@if ($this->customers->isEmpty())
<flux:text>{{ __('customers.empty') }}</flux:text>
@else
<flux:table :paginate="$this->customers">
<flux:table.columns>
<flux:table.column>{{ __('customers.fields.name') }}</flux:table.column>
<flux:table.column>{{ __('customers.fields.type') }}</flux:table.column>
<flux:table.column>{{ __('customers.fields.business_id') }}</flux:table.column>
<flux:table.column><span class="sr-only">{{ __('customers.edit') }}</span></flux:table.column>
</flux:table.columns>
<flux:table.rows>
@foreach ($this->customers as $customer)
<flux:table.row wire:key="customer-{{ $customer->id }}">
<flux:table.cell variant="strong">{{ $customer->name }}</flux:table.cell>
<flux:table.cell>{{ __('customers.types.'.$customer->type->value) }}</flux:table.cell>
<flux:table.cell>{{ $customer->businessId ?? '–' }}</flux:table.cell>
<flux:table.cell align="end">
<flux:link :href="route('customers.edit', $customer->id)" wire:navigate>
{{ __('customers.edit') }}<span class="sr-only">: {{ $customer->name }}</span>
</flux:link>
</flux:table.cell>
</flux:table.row>
@endforeach
</flux:table.rows>
</flux:table>
@endif
</div>
@@ -0,0 +1,12 @@
<?php
use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'auth'])
->prefix('customers')
->name('customers.')
->group(function () {
Route::livewire('/', 'customers::index')->name('index');
Route::livewire('/create', 'customers::form')->name('create');
Route::livewire('/{customer}/edit', 'customers::form')->whereNumber('customer')->name('edit');
});
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Application\Contracts;
/**
* Publishes domain events to other modules.
*
* Inside a transaction, the events are published only after it commits,
* so listeners never see data that is rolled back.
*/
interface EventDispatcher
{
public function dispatch(object ...$events): void;
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Application\Contracts;
/**
* Wraps a use case in one database transaction without tying the
* Application layer to Laravel's database layer.
*/
interface TransactionManager
{
/**
* Run the work in a transaction and return its result. Rolls back and
* rethrows when the work throws.
*
* @template TResult
*
* @param callable(): TResult $work
* @return TResult
*/
public function run(callable $work): mixed;
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Domain\Exceptions;
use DomainException as PhpDomainException;
/**
* Base class for broken business rules.
*
* Domain exceptions carry no HTTP status: the Presentation layer decides
* how each one is shown to the user.
*/
abstract class DomainException extends PhpDomainException {}
@@ -0,0 +1,25 @@
<?php
namespace App\Modules\Shared\Infrastructure\Events;
use App\Modules\Shared\Application\Contracts\EventDispatcher;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\Connection;
class LaravelEventDispatcher implements EventDispatcher
{
public function __construct(
private Dispatcher $events,
private Connection $connection,
) {}
/**
* Runs immediately when no transaction is open, otherwise after commit.
*/
public function dispatch(object ...$events): void
{
foreach ($events as $event) {
$this->connection->afterCommit(fn () => $this->events->dispatch($event));
}
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Modules\Shared\Infrastructure\Persistence;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use Illuminate\Database\ConnectionInterface;
class LaravelTransactionManager implements TransactionManager
{
public function __construct(private ConnectionInterface $connection) {}
public function run(callable $work): mixed
{
return $this->connection->transaction(fn () => $work());
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Modules\Shared\Infrastructure\Providers;
use App\Modules\Shared\Application\Contracts\EventDispatcher;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Infrastructure\Events\LaravelEventDispatcher;
use App\Modules\Shared\Infrastructure\Persistence\LaravelTransactionManager;
use Illuminate\Support\ServiceProvider;
class SharedServiceProvider extends ServiceProvider
{
/**
* @var array<class-string, class-string>
*/
public array $bindings = [
TransactionManager::class => LaravelTransactionManager::class,
EventDispatcher::class => LaravelEventDispatcher::class,
];
}
+4
View File
@@ -1,7 +1,11 @@
<?php
use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider;
use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider;
use App\Providers\AppServiceProvider;
return [
AppServiceProvider::class,
SharedServiceProvider::class,
CustomersServiceProvider::class,
];
+4
View File
@@ -17,6 +17,7 @@
},
"require-dev": {
"fakerphp/faker": "^1.23",
"larastan/larastan": "^3.15",
"laravel/boost": "^2.2",
"laravel/pail": "^1.2.5",
"laravel/pao": "^1.0.6",
@@ -74,6 +75,9 @@
],
"pre-package-uninstall": [
"Illuminate\\Foundation\\ComposerScripts::prePackageUninstall"
],
"analyse": [
"phpstan analyse --memory-limit=1G"
]
},
"extra": {
Generated
+198 -1
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "be7132e2dcff604e148e37dff05089f5",
"content-hash": "52ac0c6347bdd6158266297dfbf8842c",
"packages": [
{
"name": "brick/math",
@@ -8120,6 +8120,48 @@
"time": "2026-03-17T11:56:53+00:00",
"published-time": "2026-06-16T10:52:40+00:00"
},
{
"name": "iamcal/sql-parser",
"version": "v0.7",
"source": {
"type": "git",
"url": "https://github.com/iamcal/SQLParser.git",
"reference": "610392f38de49a44dab08dc1659960a29874c4b8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/iamcal/SQLParser/zipball/610392f38de49a44dab08dc1659960a29874c4b8",
"reference": "610392f38de49a44dab08dc1659960a29874c4b8",
"shasum": ""
},
"require-dev": {
"php-coveralls/php-coveralls": "^1.0",
"phpunit/phpunit": "^5|^6|^7|^8|^9"
},
"type": "library",
"autoload": {
"psr-4": {
"iamcal\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Cal Henderson",
"email": "[email protected]"
}
],
"description": "MySQL schema parser",
"support": {
"issues": "https://github.com/iamcal/SQLParser/issues",
"source": "https://github.com/iamcal/SQLParser/tree/v0.7"
},
"time": "2026-01-28T22:20:33+00:00",
"published-time": "2026-01-28T22:23:28+00:00"
},
{
"name": "jean85/pretty-package-versions",
"version": "2.1.1",
@@ -8240,6 +8282,96 @@
"time": "2023-02-03T21:26:53+00:00",
"published-time": "2023-02-03T21:33:41+00:00"
},
{
"name": "larastan/larastan",
"version": "v3.15.0",
"source": {
"type": "git",
"url": "https://github.com/larastan/larastan.git",
"reference": "ffb29680700b7e56000183ddacd68fab991f690b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/larastan/larastan/zipball/ffb29680700b7e56000183ddacd68fab991f690b",
"reference": "ffb29680700b7e56000183ddacd68fab991f690b",
"shasum": ""
},
"require": {
"iamcal/sql-parser": "^0.7.0",
"illuminate/console": "^11.44.2 || ^12.4.1 || ^13",
"illuminate/container": "^11.44.2 || ^12.4.1 || ^13",
"illuminate/contracts": "^11.44.2 || ^12.4.1 || ^13",
"illuminate/database": "^11.44.2 || ^12.4.1 || ^13",
"illuminate/http": "^11.44.2 || ^12.4.1 || ^13",
"illuminate/pipeline": "^11.44.2 || ^12.4.1 || ^13",
"illuminate/support": "^11.44.2 || ^12.4.1 || ^13",
"php": "^8.2",
"phpstan/phpstan": "^2.3.5"
},
"require-dev": {
"doctrine/coding-standard": "^14",
"laravel/framework": "^11.44.2 || ^12.7.2 || ^13",
"mockery/mockery": "^1.6.12",
"nikic/php-parser": "^5.6",
"orchestra/canvas": "^v9.2.2 || ^10.0.1 || ^11",
"orchestra/testbench-core": "^9.12.0 || ^10.1 || ^11",
"phpstan/phpstan-deprecation-rules": "^2.0.1",
"phpunit/phpunit": "^10.5.35 || ^11.5.15 || ^12.5.8 || ^13.3.0"
},
"suggest": {
"orchestra/testbench": "Using Larastan for analysing a package needs Testbench",
"phpmyadmin/sql-parser": "Install to enable Larastan's optional phpMyAdmin-based SQL parser automatically"
},
"type": "phpstan-extension",
"extra": {
"phpstan": {
"includes": [
"extension.neon"
]
},
"branch-alias": {
"dev-master": "3.0-dev"
}
},
"autoload": {
"psr-4": {
"Larastan\\Larastan\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Can Vural",
"email": "[email protected]"
}
],
"description": "Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel",
"keywords": [
"PHPStan",
"code analyse",
"code analysis",
"larastan",
"laravel",
"package",
"php",
"static analysis"
],
"support": {
"issues": "https://github.com/larastan/larastan/issues",
"source": "https://github.com/larastan/larastan/tree/v3.15.0"
},
"funding": [
{
"url": "https://github.com/canvural",
"type": "github"
}
],
"time": "2026-11-11T15:06:29+00:00",
"published-time": "2026-11-11T15:14:16+00:00"
},
{
"name": "laravel/agent-detector",
"version": "v2.0.5",
@@ -9999,6 +10131,71 @@
"time": "2026-10-30T19:36:28+00:00",
"published-time": "2026-10-30T19:37:11+00:00"
},
{
"name": "phpstan/phpstan",
"version": "2.3.7",
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/90c91c2498849ab8cc4e873864bbf1cb2bf6ea12",
"reference": "90c91c2498849ab8cc4e873864bbf1cb2bf6ea12",
"shasum": ""
},
"require": {
"php": "^7.4|^8.0"
},
"conflict": {
"phpstan/phpstan-shim": "*"
},
"bin": [
"phpstan",
"phpstan.phar"
],
"type": "library",
"autoload": {
"files": [
"bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Ondřej Mirtes"
},
{
"name": "Markus Staab"
},
{
"name": "Vincent Langlet"
}
],
"description": "PHPStan - PHP Static Analysis Tool",
"keywords": [
"dev",
"static analysis"
],
"support": {
"docs": "https://phpstan.org/user-guide/getting-started",
"forum": "https://github.com/phpstan/phpstan/discussions",
"issues": "https://github.com/phpstan/phpstan/issues",
"security": "https://github.com/phpstan/phpstan/security/policy",
"source": "https://github.com/phpstan/phpstan-src"
},
"funding": [
{
"url": "https://github.com/ondrejmirtes",
"type": "github"
},
{
"url": "https://github.com/phpstan",
"type": "github"
}
],
"time": "2026-11-19T10:31:11+00:00",
"published-time": "2026-11-19T10:31:27+00:00"
},
{
"name": "phpunit/php-code-coverage",
"version": "14.5.2",
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace Database\Factories;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<CustomerModel>
*/
class CustomerFactory extends Factory
{
protected $model = CustomerModel::class;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->unique()->company(),
'type' => CustomerType::Company,
'business_id' => null,
];
}
public function company(?string $businessId = null): static
{
return $this->state(fn (): array => [
'type' => CustomerType::Company,
'business_id' => $businessId,
]);
}
public function consumer(): static
{
return $this->state(fn (): array => [
'name' => fake()->unique()->name(),
'type' => CustomerType::Consumer,
'business_id' => null,
]);
}
}
@@ -0,0 +1,30 @@
<?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('customers', function (Blueprint $table) {
$table->id();
$table->string('name')->index();
$table->string('type', 20);
$table->string('business_id', 9)->nullable()->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('customers');
}
};
+208
View File
@@ -0,0 +1,208 @@
# Arkkitehtuuri
Toiminnanohjausjärjestelmä on **modulaarinen monoliitti**: yksi Laravel-sovellus, jossa liiketoiminta-alueet ovat omia moduulejaan ja jokainen moduuli on jaettu neljään kerrokseen. Tavoite on ylläpidettävä, testattava ja pitkäikäinen sovellus. Arkkitehtuuri palvelee liiketoimintaa, ei päinvastoin: abstraktio lisätään vasta, kun siitä on todellista hyötyä.
Esimerkkinä koko dokumentissa on `Customers`-moduuli (`app/Modules/Customers`), joka on ensimmäinen kokonaan toteutettu moduuli.
## 1. Periaatteet
- **Separation of Concerns ja Single Responsibility:** yksi luokka, yksi vastuu. Use Case tekee yhden sovelluksen toiminnon.
- **Dependency Inversion:** sisemmät kerrokset määrittelevät rajapinnat, ulommat toteuttavat ne. Toteutukset kytketään Service Providerissa.
- **Low coupling, high cohesion:** moduuli on sisäisesti yhtenäinen ja keskustelee muiden kanssa vain julkisten rajapintojen ja tapahtumien kautta.
- **DDD harkiten:** entiteetit, value objectit ja domain-poikkeukset ovat käytössä, koska ne tekevät liiketoimintasäännöistä testattavia. Aggregaattijuuria, domain-palveluita yms. ei luoda ennen kuin tarve on todellinen.
- **Laravelin omat ominaisuudet ensin:** Service Container, Service Providerit, Eloquent, Events, Queues, Livewire Forms. Niiden päälle ei rakenneta omia vastaavia.
## 2. Kansiorakenne
```
app/
├── Models/User.php # Laravelin auth-käyttäjä (siirtyy moduuliin käyttäjä- ja roolityön yhteydessä)
├── Providers/AppServiceProvider.php
└── Modules/
├── Shared/ # vain aidosti yhteiset, vakaat käsitteet
│ ├── Domain/Exceptions/DomainException.php
│ ├── Application/Contracts/{TransactionManager, EventDispatcher}.php
│ └── Infrastructure/
│ ├── Persistence/LaravelTransactionManager.php
│ ├── Events/LaravelEventDispatcher.php
│ └── Providers/SharedServiceProvider.php
└── Customers/
├── Domain/
│ ├── Entities/Customer.php
│ ├── ValueObjects/{CustomerName, BusinessId}.php
│ ├── Enums/CustomerType.php
│ ├── Exceptions/…
│ ├── Events/CustomerRegistered.php
│ └── Contracts/CustomerRepository.php
├── Application/
│ ├── UseCases/{RegisterCustomer, UpdateCustomer}.php
│ ├── DTOs/{CustomerDetailsData, CustomerSummary}.php
│ └── Contracts/CustomerQueries.php
├── Infrastructure/
│ ├── Persistence/Eloquent/CustomerModel.php
│ ├── Persistence/Repositories/{EloquentCustomerRepository, EloquentCustomerQueries}.php
│ └── Providers/CustomersServiceProvider.php
└── Presentation/
├── Livewire/⚡index.blade.php, ⚡form.blade.php
├── Livewire/Forms/CustomerForm.php
└── Routes/web.php
```
Laravelin normaalit hakemistot pysyvät käytössä: migraatiot `database/migrations`, factoryt `database/factories`, käännökset `lang/fi/<moduuli>.php`, testit `tests/`.
Hakemistoja luodaan vain tarpeeseen. Tyhjiä `Integrations/`- tai `Events/`-kansioita ei tehdä varmuuden vuoksi.
Composerin `App\` → `app/` PSR-4 -määritys kattaa moduulit, joten uusi moduuli ei vaadi muutoksia `composer.json`iin.
## 3. Kerrosten vastuut
### Domain
Liiketoimintasäännöt ja invarianssit puhtaana PHP:nä.
- **Entiteetti** (`Customer`) on tavallinen PHP-olio, ei Eloquent-malli. Se suojaa omat sääntönsä: esimerkiksi kuluttaja-asiakkaalla ei voi olla Y-tunnusta (`ConsumerCannotHaveBusinessId`). Uusi entiteetti luodaan nimetyllä konstruktorilla (`Customer::register()`), tallennettu rakennetaan uudelleen `reconstitute()`-metodilla (vain repositoryjen käyttöön).
- **Value object** (`CustomerName`, `BusinessId`) on muuttumaton (`final readonly`) ja validoi itsensä konstruktorissa. Virheellistä arvoa ei voi olla olemassa.
- **Enumit** ovat merkkijonopohjaisia (`CustomerType::Company = 'company'`). Näyttönimet ovat käännöstiedostoissa, eivät enumissa.
- **Poikkeukset** perivät `Shared\Domain\Exceptions\DomainException`in. Niissä ei ole HTTP-statuskoodeja.
- **Contracts** määrittelevät, mitä domain tarvitsee ulkopuolelta (esim. `CustomerRepository`).
Domain **ei saa** käyttää mitään `Illuminate`- tai `Livewire`-luokkaa, Facadeja, Eloquentia, tietokantaa tai Service Containeria.
### Application
Käyttötapaukset ja niiden koordinointi.
- **Use Case** = yksi toiminto, yksi luokka, yksi julkinen metodi `execute()`. Riippuvuudet konstruktorissa. Esimerkki `RegisterCustomer`: rakentaa value objectit (virheellinen syöte kaatuu ennen transaktiota), avaa transaktion, tarkistaa Y-tunnuksen yksilöllisyyden repositoryn kautta, tallentaa ja julkaisee `CustomerRegistered`-tapahtuman.
- **DTO:t** siirtävät dataa kerrosten välillä (ks. luku 8).
- **Contracts** ovat moduulin julkinen rajapinta muille moduuleille ja Presentationille (esim. `CustomerQueries`).
Application **ei saa** käyttää Eloquentia, `Illuminate\Database`a, Facadeja, `Illuminate\Http`iä, Livewireä eikä Infrastructure- tai Presentation-luokkia.
Sallittu poikkeus: lukumallit saavat palauttaa `Illuminate\Contracts\Pagination\LengthAwarePaginator`-rajapinnan, jotta Livewire-sivutus toimii ilman omaa sivutusabstraktiota. Se on pelkkä rajapinta, ei tietokantariippuvuus.
### Infrastructure
Tekniset toteutukset.
- **Eloquent-mallit** (`CustomerModel`) ovat vain tämän kerroksen sisäisiä. Malli on nimetty `…Model`, jotta sitä ei sekoiteta entiteettiin.
- **Repositoryt** (`EloquentCustomerRepository`) toteuttavat Domainin rajapinnat ja mappaavat mallin ja entiteetin välillä.
- **Lukumallit** (`EloquentCustomerQueries`) toteuttavat Applicationin kyselyrajapinnat ja palauttavat DTO:ita.
- **Service Provider** (`CustomersServiceProvider`) kytkee rajapinnat toteutuksiin (`$bindings`), lataa moduulin reitit ja rekisteröi Livewire-nimiavaruuden (`customers::`).
- Myöhemmin: ulkoiset API:t (laskutusohjelma), tiedostot, sähköposti.
### Presentation
Käyttöliittymä. Tässä projektissa se on **Livewire 4 single-file -komponentteja ja Flux UI:ta**, ei controllereita.
- Sivut ovat `Presentation/Livewire/⚡<nimi>.blade.php` ja niihin viitataan `customers::index`-muodossa.
- **Livewire Form -objekti** (`CustomerForm`) vastaa Form Requestia: se validoi syötteen *muodon* (pakollisuus, pituus, enum) ja rakentaa DTO:n. Liiketoimintasääntöjä (Y-tunnuksen tarkiste, yksilöllisyys) se ei toista, vaan ne tulevat Domainista.
- Komponentti kutsuu Use Casea (metodi-injektiolla) tai kyselyrajapintaa, ei koskaan Eloquentia.
- Domain-poikkeukset muunnetaan kenttävirheiksi (`CustomerForm::showDomainError()`), tuntemattomat heitetään eteenpäin Laravelin virheenkäsittelyyn.
- Reitit ovat `Presentation/Routes/web.php`:ssä `auth`-middlewaren takana.
- Kaikki tekstit `lang/fi/<moduuli>.php`:ssä. Saavutettavuussäännöt ovat `CLAUDE.md`:ssä.
- Controllerit ja API Resourcet lisätään `Presentation/Http/`-kansioon vasta, kun tarvitaan HTTP-rajapinta (esim. laskutusohjelman API).
## 4. Riippuvuussäännöt
| Kerros | Saa käyttää | Ei saa käyttää |
|---|---|---|
| Presentation | Application, Domain | toisten moduulien Infrastructure/Presentation |
| Application | Domain, Shared Application Contracts | Infrastructure, Presentation, Eloquent, DB, Facades, HTTP |
| Domain | vain oma Domain ja Shared Domain | Application, Infrastructure, Presentation, kaikki `Illuminate`/`Livewire` |
| Infrastructure | Domain, Application, Laravel | Presentation |
Moduuli ei koskaan käytä toisen moduulin Infrastructure- tai Presentation-kerrosta.
Säännöt valvotaan automaattisesti:
- **`tests/Unit/ArchitectureTest.php`** (Pest arch) käy läpi jokaisen `app/Modules`-hakemiston ja tarkistaa yllä olevat säännöt, `declare(strict_types=1)`:n Domainissa ja Applicationissa sekä DTO:iden readonly-luonteen. Uusi moduuli tulee mukaan ilman muutoksia.
- **Larastan** (`composer analyse`, taso 6). Livewire single-file -komponentit (`*.blade.php`) on rajattu pois, koska niissä on PHP:tä ja Bladea samassa tiedostossa.
## 5. Moduulien välinen kommunikaatio
1. **Application Contracts**, kun tieto tarvitaan heti. Esimerkiksi tuleva `CustomerJobs`-moduuli hakee asiakkaan autocompleteen `CustomerQueries::search()`-metodilla ja saa `CustomerSummary`-DTO:ita. Se ei koskaan käytä `CustomerModel`ia eikä liitä Eloquent-relaatiota toisen moduulin malliin. Tietokantatasolla vierasavain (`customer_id`) on sallittu.
2. **Tapahtumat**, kun halutaan reagoida. `RegisterCustomer` julkaisee `CustomerRegistered`-tapahtuman `EventDispatcher`-rajapinnan kautta. Toinen moduuli rekisteröi oman listenerinsa omassa Service Providerissaan (`Event::listen(CustomerRegistered::class, …)`). Julkaisija ei tiedä kuuntelijoista mitään.
3. **Jonot** pitkiin tai taustalla ajettaviin tehtäviin (laskuaineiston muodostus, laskutusohjelman API). Listener toteuttaa `ShouldQueue`-rajapinnan, tai Infrastructure lähettää Laravel-jobin.
Kiertäviä riippuvuuksia (A käyttää B:n rajapintaa ja B A:n) vältetään: toinen suunta hoidetaan tapahtumilla.
**Shared**-moduuliin laitetaan vain aidosti yhteisiä, vakaita käsitteitä (transaktiot, tapahtumien julkaisu, domain-poikkeuksen perusluokka). Liiketoimintakäsite ei kuulu sinne vain siksi, että kaksi moduulia käyttää sitä.
## 6. Repository-käytännöt
- Rajapinta `Domain/Contracts`, toteutus `Infrastructure/Persistence/Repositories`, Eloquent-malli `Infrastructure/Persistence/Eloquent`.
- Repository käsittelee **entiteettejä** ja tarjoaa vain ne metodit, joita use caset tarvitsevat (`findById`, `save`, `isBusinessIdTaken`). Ei geneeristä `BaseRepository`a eikä `all()`/`where()`-läpivientejä.
- `save()` hoitaa sekä lisäyksen että päivityksen ja palauttaa tallennetun entiteetin (uusi saa tässä id:n).
- **Lukupuoli on erillään:** listat, haut ja raportit tehdään Application-kerroksen kyselyrajapinnalla (`CustomerQueries`), joka palauttaa DTO:ita suoraan kyselystä. Entiteettejä ei rakenneta pelkkää näyttämistä varten.
- Repository luodaan vain, kun moduulilla on kirjoittavia use caseja ja sääntöjä. Pelkälle hakutaulukolle (esim. asetukset) riittää kyselyrajapinta.
## 7. Transaktiot ja tapahtumat
- Transaktion raja on **use case**: `TransactionManager::run(fn () => …)`. Toteutus käyttää `DB::transaction`ia.
- Syöte validoidaan (value objectit rakennetaan) ennen transaktiota.
- `EventDispatcher` julkaisee tapahtumat `afterCommit`-mekanismilla: avoimen transaktion aikana julkaistu tapahtuma lähtee vasta commitin jälkeen, ja rollbackissa se hylätään. Ilman transaktiota se lähtee heti.
- Ulkoisia API-kutsuja ei tehdä transaktion sisällä. Ne tehdään jonossa tapahtuman perusteella.
## 8. DTO-käytännöt
- `final readonly class`, vain tarvittavat kentät, nimetty tarkoituksen mukaan.
- Syöte-DTO (`CustomerDetailsData`) voi tarjota `fromArray()`-metodin. Se normalisoi lomakedatan (tyhjä Y-tunnus → `null`), mutta ei validoi liiketoimintasääntöjä.
- Luku-DTO (`CustomerSummary`) on se, mitä muut moduulit ja käyttöliittymä näkevät asiakkaasta.
- Laravelin `Request`ia tai Livewire-komponenttia ei koskaan välitetä use caselle.
- Saman syötteen käyttötapaukset saavat jakaa DTO:n (`RegisterCustomer` ja `UpdateCustomer` käyttävät molemmat `CustomerDetailsData`a). Erillinen DTO tehdään, kun syötteet eroavat.
## 9. Virheiden käsittely
| Tyyppi | Missä syntyy | Miten käsitellään |
|---|---|---|
| Validointivirhe | Livewire Form (`validate()`) | Livewire näyttää kenttävirheen |
| Domain-poikkeus | Domain / Use Case | Presentation muuntaa kenttävirheeksi tai ilmoitukseksi käännösavaimella |
| Ei löydy | Kyselyrajapinta palauttaa `null` | Presentation: `abort(404)` |
| Valtuutus | Policy / Gate (tulee roolityön myötä) | 403 |
| Infrastruktuurivirhe | Tietokanta, API | Laravelin virheenkäsittelijä ja loki |
Try/catch-lohkoja ei laiteta joka metodiin. Virhe käsitellään siellä, missä tiedetään, mitä sille tehdään.
## 10. Testausstrategia
| Taso | Sijainti | Mitä | Laravel/tietokanta |
|---|---|---|---|
| Arkkitehtuuri | `tests/Unit/ArchitectureTest.php` | riippuvuussäännöt | ei |
| Domain | `tests/Unit/Modules/<Moduuli>/Domain` | entiteetit, value objectit, invarianssit | ei |
| Application | `tests/Unit/Modules/<Moduuli>/Application` | use caset fakeilla (`tests/Fakes/InMemoryCustomerRepository`, `FakeTransactionManager`, `FakeEventDispatcher`) | ei |
| Feature | `tests/Feature/Modules/<Moduuli>` | repositoryt oikeaa kantaa vasten, Livewire-sivut, transaktiot ja tapahtumat | kyllä, `RefreshDatabase` |
| Selain | `tests/Browser` | saavutettavuus (axe, vaalea/tumma, desktop/mobiili), näppäimistökäyttö | kyllä |
Jokaiselle merkittävälle liiketoimintasäännölle on testi. Unit-testit eivät käynnistä Laravelia, joten ne ovat nopeita.
```powershell
php artisan test --compact tests/Unit
php artisan test --compact tests/Feature
npm run build; php artisan test --compact tests/Browser
composer analyse
vendor/bin/pint --dirty --format agent
```
## 11. Uuden moduulin lisääminen
Esimerkki: vaiheen 1 `CustomerJobs` (asiakastyöt).
1. **Domain:** `app/Modules/CustomerJobs/Domain/` – entiteetti `CustomerJob`, enumit (`JobStatus`, `Priority`, `DurationType`, `PaymentBasis`), value objectit, poikkeukset ja `CustomerJobRepository`-rajapinta. Kirjoita säännöille unit-testit ensin. Kaikkiin tiedostoihin `declare(strict_types=1);`.
2. **Application:** use caset (`CreateCustomerJob`, `ChangeJobStatus` …), DTO:t, kyselyrajapinta `CustomerJobQueries`. Testaa fakeilla (`tests/Fakes`).
3. **Infrastructure:**
- `php artisan make:migration create_customer_jobs_table`
- `CustomerJobModel` + factory `database/factories/CustomerJobFactory.php` (`#[UseFactory]`)
- repository- ja kyselytoteutukset
- `CustomerJobsServiceProvider`: `$bindings`, `loadRoutesFrom`, `Livewire::addNamespace('customer-jobs', viewPath: …)`
- rekisteröi provider `bootstrap/providers.php`:hen
4. **Presentation:** Livewire-sivut, Form-objekti, reitit, `lang/fi/customer-jobs.php`. Asiakas valitaan `CustomerQueries::search()`-rajapinnalla, ei `CustomerModel`illa.
5. **Testit:** Feature-testit sivuille ja repositorylle sekä selaintesti `tests/Browser`iin.
6. **Tarkistus:** `php artisan test --compact`, `composer analyse`, Pint. Arkkitehtuuritesti ottaa uuden moduulin mukaan automaattisesti.
## 12. Poikkeamat alkuperäisestä teknisestä määrittelystä
| Määrittely | Toteutus | Syy |
|---|---|---|
| Laravel 12 | Laravel 13 | Projektiin asennettu versio. Periaatteet ovat samat. |
| Controllerit, Form Requestit, API Resourcet | Livewire SFC + Livewire Form | Projektin käyttöliittymä on Livewire 4 + Flux. Controllerit tulevat API:n myötä. |
| Esimerkkimoduulit Customers, Orders, Products, Invoicing | Shared + Customers | Moduuleja ei luoda varmuuden vuoksi. Tämän yrityksen moduulit ovat `määrittely.txt`:n mukaan Customers, CustomerJobs, TimeTracking, Expenses, ServiceCatalog, Tasks ja Billing, ja ne tehdään omissa vaiheissaan. |
| Moduulikohtaiset migraatiot | `database/migrations` | Laravelin normaalit hakemistot säilytetään. |
| Application ei riipu Laravelista | Sallittu: `Illuminate\Contracts\Pagination` | Sivutus ilman omaa abstraktiota (ks. luku 3). |
| Entiteetti kerää tapahtumansa | Use case julkaisee tapahtuman tallennuksen jälkeen | Uusi entiteetti saa id:n vasta tallennuksessa, ja tapahtuma tarvitsee id:n. Tämä on yksinkertaisempaa kuin tapahtumien keruumekanismi. |
| `App\Models\User` | Ennallaan | Siirretään omaan moduuliin käyttäjä-, rooli- ja kirjautumistyön yhteydessä. |
+40
View File
@@ -0,0 +1,40 @@
<?php
return [
'title' => 'Asiakkaat',
'create_title' => 'Uusi asiakas',
'edit_title' => 'Muokkaa asiakasta',
'new' => 'Uusi asiakas',
'edit' => 'Muokkaa',
'save' => 'Tallenna',
'cancel' => 'Peruuta',
'search' => 'Hae asiakasta',
'search_description' => 'Hae nimellä tai Y-tunnuksella.',
'empty' => 'Asiakkaita ei löytynyt.',
'result_count' => '{0} Ei asiakkaita|{1} :count asiakas|[2,*] :count asiakasta',
'created' => 'Asiakas :name lisätty.',
'updated' => 'Asiakkaan :name tiedot tallennettu.',
'fields' => [
'name' => 'Nimi',
'type' => 'Asiakastyyppi',
'business_id' => 'Y-tunnus',
'business_id_description' => 'Muodossa 1234567-8. Ei pakollinen.',
],
'types' => [
'company' => 'Yritys',
'consumer' => 'Kuluttaja',
],
'errors' => [
'name_required' => 'Anna asiakkaan nimi.',
'invalid_name' => 'Nimen pituus voi olla enintään 255 merkkiä.',
'type_required' => 'Valitse asiakastyyppi.',
'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.',
],
];
+10
View File
@@ -0,0 +1,10 @@
includes:
- vendor/larastan/larastan/extension.neon
parameters:
level: 6
paths:
- app
excludePaths:
# Livewire single-file components mix PHP and Blade, so PHPStan cannot analyse them.
- app/**/*.blade.php
+13
View File
@@ -3,6 +3,7 @@
@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php';
@source '../../storage/framework/views/*.php';
@source '../../app/Modules/**/*.blade.php';
@custom-variant dark (&:where(.dark, .dark *));
@@ -10,3 +11,15 @@
--font-sans: Inter, ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
}
/*
* Flux error messages use red-500, which is only 3.8:1 on white.
* WCAG 2.2 AA needs 4.5:1 for text, so use darker red in light mode.
*/
[data-flux-error] {
color: var(--color-red-700);
}
.dark [data-flux-error] {
color: var(--color-red-400);
}
@@ -0,0 +1,55 @@
<?php
use App\Models\User;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->actingAs(User::factory()->create());
});
it('has no accessibility issues on the customer pages', function (string $routeName, string $device, string $colorScheme) {
$customer = CustomerModel::factory()->company('0737546-2')->create(['name' => 'Mainos Oy']);
$page = visit($routeName === 'customers.edit' ? route($routeName, $customer->id) : route($routeName));
$page = $device === 'mobile' ? $page->on()->mobile() : $page->on()->desktop();
$page = $colorScheme === 'dark' ? $page->inDarkMode() : $page->inLightMode();
$page->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with([
'list' => 'customers.index',
'create' => 'customers.create',
'edit' => 'customers.edit',
])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('shows form errors without accessibility issues', function (string $colorScheme) {
$page = visit(route('customers.create'));
$page = $colorScheme === 'dark' ? $page->inDarkMode() : $page->inLightMode();
$page->fill('[wire\\:model="form.name"]', 'Mainos Oy')
->fill('[wire\\:model="form.business_id"]', '0737546-3')
->press('Tallenna')
->assertSee('Y-tunnus ei ole kelvollinen.')
->assertNoAccessibilityIssues(level: 2);
})->with(['light', 'dark']);
it('creates a customer with the keyboard alone', function () {
visit(route('customers.create'))
->keys('html > body', 'Tab')
->assertScript('document.activeElement.textContent.trim()', 'Siirry pääsisältöön')
->keys('a[href="#main-content"]', 'Tab')
->assertScript('document.activeElement.getAttribute("wire:model")', 'form.name')
->type('[wire\\:model="form.name"]', 'Mainos Oy')
->keys('[wire\\:model="form.name"]', 'Enter')
->assertPathIs('/customers')
->assertSee('Asiakas Mainos Oy lisätty.');
});
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Tests\Fakes;
use App\Modules\Shared\Application\Contracts\EventDispatcher;
class FakeEventDispatcher implements EventDispatcher
{
/**
* @var list<object>
*/
public array $dispatched = [];
public function dispatch(object ...$events): void
{
array_push($this->dispatched, ...$events);
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace Tests\Fakes;
use App\Modules\Shared\Application\Contracts\TransactionManager;
class FakeTransactionManager implements TransactionManager
{
public int $transactionCount = 0;
public function run(callable $work): mixed
{
$this->transactionCount++;
return $work();
}
}
@@ -0,0 +1,43 @@
<?php
namespace Tests\Fakes;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
class InMemoryCustomerRepository implements CustomerRepository
{
/**
* @var array<int, Customer>
*/
public array $customers = [];
private int $nextId = 1;
public function findById(int $id): ?Customer
{
return isset($this->customers[$id]) ? clone $this->customers[$id] : null;
}
public function save(Customer $customer): Customer
{
$id = $customer->id() ?? $this->nextId++;
$stored = Customer::reconstitute($id, $customer->name(), $customer->type(), $customer->businessId());
$this->customers[$id] = $stored;
return clone $stored;
}
public function isBusinessIdTaken(BusinessId $businessId, ?int $exceptCustomerId = null): bool
{
foreach ($this->customers as $id => $customer) {
if ($id !== $exceptCustomerId && $customer->businessId()?->equals($businessId)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,103 @@
<?php
use App\Models\User;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->actingAs(User::factory()->create());
});
it('lists customers and filters them by search', function () {
CustomerModel::factory()->create(['name' => 'Alfa Media Oy']);
CustomerModel::factory()->create(['name' => 'Kahvila Kulma']);
$this->get(route('customers.index'))
->assertOk()
->assertSee('Alfa Media Oy')
->assertSee('Kahvila Kulma');
Livewire::test('customers::index')
->set('search', 'media')
->assertSee('Alfa Media Oy')
->assertDontSee('Kahvila Kulma')
->assertSee('1 asiakas');
});
it('registers a company customer', function () {
$this->get(route('customers.create'))->assertOk()->assertSee('Uusi asiakas');
Livewire::test('customers::form')
->set('form.name', ' Mainos Oy ')
->set('form.business_id', '0737546-2')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('customers.index'));
$customer = CustomerModel::query()->sole();
expect($customer->name)->toBe('Mainos Oy')
->and($customer->type)->toBe(CustomerType::Company)
->and($customer->business_id)->toBe('0737546-2');
});
it('ignores a business id typed before switching to consumer', function () {
Livewire::test('customers::form')
->set('form.name', 'Maija Meikäläinen')
->set('form.business_id', '0737546-2')
->set('form.type', CustomerType::Consumer->value)
->call('save')
->assertHasNoErrors();
expect(CustomerModel::query()->sole()->business_id)->toBeNull();
});
it('shows validation and business rule errors on the fields', function (array $input, string $field, string $message) {
CustomerModel::factory()->company('1572860-0')->create();
Livewire::test('customers::form')
->set($input)
->call('save')
->assertHasErrors([$field])
->assertSee($message);
expect(CustomerModel::query()->count())->toBe(1);
})->with([
'missing name' => [['form.name' => ''], 'form.name', 'Anna asiakkaan nimi.'],
'bad check digit' => [['form.name' => 'Mainos Oy', 'form.business_id' => '0737546-3'], 'form.business_id', 'Y-tunnus ei ole kelvollinen.'],
'business id in use' => [['form.name' => 'Mainos Oy', 'form.business_id' => '1572860-0'], 'form.business_id', 'Tällä Y-tunnuksella on jo asiakas.'],
]);
it('edits a customer', function () {
$customer = CustomerModel::factory()->company('0737546-2')->create(['name' => 'Mainos Oy']);
$this->get(route('customers.edit', $customer->id))
->assertOk()
->assertSee('Muokkaa asiakasta')
->assertSee('0737546-2');
Livewire::test('customers::form', ['customer' => $customer->id])
->assertSet('form.name', 'Mainos Oy')
->set('form.name', 'Mainos Oyj')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('customers.index'));
expect($customer->fresh()->name)->toBe('Mainos Oyj');
});
it('keeps the customer its own business id when editing', function () {
$customer = CustomerModel::factory()->company('0737546-2')->create();
Livewire::test('customers::form', ['customer' => $customer->id])
->call('save')
->assertHasNoErrors();
});
it('returns 404 for an unknown customer', function () {
$this->get(route('customers.edit', 999))->assertNotFound();
});
@@ -0,0 +1,57 @@
<?php
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('stores a new customer and reads it back as an entity', function () {
$repository = app(CustomerRepository::class);
$saved = $repository->save(Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company, new BusinessId('0737546-2')));
$found = $repository->findById((int) $saved->id());
expect($saved->id())->toBeInt()
->and($found?->name()->value)->toBe('Mainos Oy')
->and($found?->type())->toBe(CustomerType::Company)
->and($found?->businessId()?->value)->toBe('0737546-2');
});
it('updates a stored customer', function () {
$repository = app(CustomerRepository::class);
$customer = $repository->save(Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company));
$customer->changeDetails(new CustomerName('Maija Meikäläinen'), CustomerType::Consumer, null);
$repository->save($customer);
expect(CustomerModel::query()->count())->toBe(1)
->and(CustomerModel::query()->sole()->type)->toBe(CustomerType::Consumer);
});
it('tells whether another customer has the business id', function () {
$repository = app(CustomerRepository::class);
$customer = CustomerModel::factory()->company('0737546-2')->create();
expect($repository->isBusinessIdTaken(new BusinessId('0737546-2')))->toBeTrue()
->and($repository->isBusinessIdTaken(new BusinessId('0737546-2'), $customer->id))->toBeFalse()
->and($repository->isBusinessIdTaken(new BusinessId('1572860-0')))->toBeFalse();
});
it('returns summaries filtered by name or business id, ordered by name', function () {
CustomerModel::factory()->create(['name' => 'Bravo Media Oy']);
CustomerModel::factory()->company('0737546-2')->create(['name' => 'Alfa Media Oy']);
CustomerModel::factory()->create(['name' => 'Kahvila Kulma']);
$queries = app(CustomerQueries::class);
expect(array_map(fn ($summary) => $summary->name, $queries->search('media')))->toBe(['Alfa Media Oy', 'Bravo Media Oy'])
->and($queries->paginate('0737546')->total())->toBe(1)
->and($queries->paginate(null)->total())->toBe(3)
->and($queries->search('100%'))->toBe([]);
});
@@ -0,0 +1,55 @@
<?php
use App\Modules\Customers\Application\DTOs\CustomerDetailsData;
use App\Modules\Customers\Application\UseCases\RegisterCustomer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Events\CustomerRegistered;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Shared\Application\Contracts\EventDispatcher;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
uses(RefreshDatabase::class);
it('rolls back everything when the work fails', function () {
expect(fn () => app(TransactionManager::class)->run(function (): void {
CustomerModel::factory()->create();
throw new RuntimeException('fail');
}))->toThrow(RuntimeException::class);
expect(CustomerModel::query()->count())->toBe(0);
});
it('publishes events only after the transaction commits', function () {
Event::fake([CustomerRegistered::class]);
app(TransactionManager::class)->run(function (): void {
app(EventDispatcher::class)->dispatch(new CustomerRegistered(1));
Event::assertNotDispatched(CustomerRegistered::class);
});
Event::assertDispatched(CustomerRegistered::class);
});
it('drops events of a rolled back transaction', function () {
Event::fake([CustomerRegistered::class]);
rescue(fn () => app(TransactionManager::class)->run(function (): void {
app(EventDispatcher::class)->dispatch(new CustomerRegistered(1));
throw new RuntimeException('fail');
}), report: false);
Event::assertNotDispatched(CustomerRegistered::class);
});
it('announces a registered customer to listeners', function () {
Event::fake([CustomerRegistered::class]);
$customerId = app(RegisterCustomer::class)->execute(new CustomerDetailsData('Mainos Oy', CustomerType::Company));
Event::assertDispatched(CustomerRegistered::class, fn (CustomerRegistered $event) => $event->customerId === $customerId);
});
+70
View File
@@ -0,0 +1,70 @@
<?php
/*
|--------------------------------------------------------------------------
| Architecture rules
|--------------------------------------------------------------------------
|
| Enforces the layer and module dependency rules in docs/architecture.md.
| Every directory under app/Modules is picked up automatically.
|
*/
$modules = array_map('basename', glob(dirname(__DIR__, 2).'/app/Modules/*', GLOB_ONLYDIR) ?: []);
it('finds the modules to check', function () use ($modules) {
expect($modules)->toContain('Shared', 'Customers');
});
foreach ($modules as $module) {
$root = 'App\\Modules\\'.$module;
arch("{$module}: domain does not depend on Laravel or outer layers")
->expect($root.'\\Domain')
->not->toUse([
'Illuminate',
'Livewire',
'App\\Models',
$root.'\\Application',
$root.'\\Infrastructure',
$root.'\\Presentation',
]);
arch("{$module}: application does not use the database, facades, HTTP or outer layers")
->expect($root.'\\Application')
->not->toUse([
'Illuminate\\Database',
'Illuminate\\Support\\Facades',
'Illuminate\\Http',
'Livewire',
'App\\Models',
$root.'\\Infrastructure',
$root.'\\Presentation',
]);
arch("{$module}: infrastructure does not depend on presentation")
->expect($root.'\\Infrastructure')
->not->toUse($root.'\\Presentation');
$otherModules = array_values(array_diff($modules, [$module]));
if ($otherModules !== []) {
arch("{$module}: does not use the infrastructure or presentation of other modules")
->expect($root)
->not->toUse(array_merge(...array_map(
fn (string $other): array => [
'App\\Modules\\'.$other.'\\Infrastructure',
'App\\Modules\\'.$other.'\\Presentation',
],
$otherModules,
)));
}
arch("{$module}: domain and application use strict types")
->expect([$root.'\\Domain', $root.'\\Application'])
->toUseStrictTypes();
arch("{$module}: DTOs are readonly")
->expect($root.'\\Application\\DTOs')
->toBeReadonly();
}
@@ -0,0 +1,11 @@
<?php
use App\Modules\Customers\Application\DTOs\CustomerDetailsData;
use App\Modules\Customers\Domain\Enums\CustomerType;
it('builds from form input and treats a blank business id as none', function () {
$data = CustomerDetailsData::fromArray(['name' => 'Mainos Oy', 'type' => 'company', 'business_id' => ' ']);
expect($data->type)->toBe(CustomerType::Company)
->and($data->businessId)->toBeNull();
});
@@ -0,0 +1,47 @@
<?php
use App\Modules\Customers\Application\DTOs\CustomerDetailsData;
use App\Modules\Customers\Application\UseCases\RegisterCustomer;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Events\CustomerRegistered;
use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse;
use App\Modules\Customers\Domain\Exceptions\InvalidBusinessId;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use Tests\Fakes\FakeEventDispatcher;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryCustomerRepository;
beforeEach(function () {
$this->customers = new InMemoryCustomerRepository;
$this->transactions = new FakeTransactionManager;
$this->events = new FakeEventDispatcher;
$this->registerCustomer = new RegisterCustomer($this->customers, $this->transactions, $this->events);
});
it('stores the customer in a transaction and announces it', function () {
$customerId = $this->registerCustomer->execute(new CustomerDetailsData('Mainos Oy', CustomerType::Company, '0737546-2'));
$stored = $this->customers->findById($customerId);
expect($stored?->name()->value)->toBe('Mainos Oy')
->and($stored?->businessId()?->value)->toBe('0737546-2')
->and($this->transactions->transactionCount)->toBe(1)
->and($this->events->dispatched)->toEqual([new CustomerRegistered($customerId)]);
});
it('rejects a business id that another customer has', function () {
$this->customers->save(Customer::register(new CustomerName('Vanha Oy'), CustomerType::Company, new BusinessId('0737546-2')));
expect(fn () => $this->registerCustomer->execute(new CustomerDetailsData('Uusi Oy', CustomerType::Company, '737546-2')))
->toThrow(BusinessIdAlreadyInUse::class)
->and($this->customers->customers)->toHaveCount(1)
->and($this->events->dispatched)->toBeEmpty();
});
it('validates input before opening a transaction', function () {
expect(fn () => $this->registerCustomer->execute(new CustomerDetailsData('Mainos Oy', CustomerType::Company, '0737546-3')))
->toThrow(InvalidBusinessId::class)
->and($this->transactions->transactionCount)->toBe(0);
});
@@ -0,0 +1,47 @@
<?php
use App\Modules\Customers\Application\DTOs\CustomerDetailsData;
use App\Modules\Customers\Application\UseCases\UpdateCustomer;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryCustomerRepository;
beforeEach(function () {
$this->customers = new InMemoryCustomerRepository;
$this->updateCustomer = new UpdateCustomer($this->customers, new FakeTransactionManager);
$this->customerId = $this->customers->save(
Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company, new BusinessId('0737546-2')),
)->id();
});
it('changes the details of a stored customer', function () {
$this->updateCustomer->execute($this->customerId, new CustomerDetailsData('Mainos Oyj', CustomerType::Company, '0737546-2'));
expect($this->customers->findById($this->customerId)?->name()->value)->toBe('Mainos Oyj');
});
it('turns a company into a consumer when the business id is removed', function () {
$this->updateCustomer->execute($this->customerId, new CustomerDetailsData('Maija Meikäläinen', CustomerType::Consumer));
$customer = $this->customers->findById($this->customerId);
expect($customer?->type())->toBe(CustomerType::Consumer)
->and($customer?->businessId())->toBeNull();
});
it('rejects a business id that belongs to another customer', function () {
$this->customers->save(Customer::register(new CustomerName('Toinen Oy'), CustomerType::Company, new BusinessId('1572860-0')));
expect(fn () => $this->updateCustomer->execute($this->customerId, new CustomerDetailsData('Mainos Oy', CustomerType::Company, '1572860-0')))
->toThrow(BusinessIdAlreadyInUse::class)
->and($this->customers->findById($this->customerId)?->businessId()?->value)->toBe('0737546-2');
});
it('fails for an unknown customer', function () {
$this->updateCustomer->execute(999, new CustomerDetailsData('Mainos Oy', CustomerType::Company));
})->throws(CustomerNotFound::class);
@@ -0,0 +1,29 @@
<?php
use App\Modules\Customers\Domain\Exceptions\InvalidBusinessId;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
it('accepts a business id with a correct check digit', function (string $input, string $expected) {
expect((new BusinessId($input))->value)->toBe($expected);
})->with([
'check digit from remainder' => ['0737546-2', '0737546-2'],
'remainder 0 gives check digit 0' => ['1572860-0', '1572860-0'],
'surrounding whitespace' => [' 0737546-2 ', '0737546-2'],
'old six-digit form is padded' => ['737546-2', '0737546-2'],
]);
it('rejects an invalid business id', function (string $input) {
new BusinessId($input);
})->throws(InvalidBusinessId::class)->with([
'wrong check digit' => ['0737546-3'],
'remainder 1 has no valid check digit' => ['0000006-5'],
'missing hyphen' => ['07375462'],
'letters' => ['07375a6-2'],
'too many digits' => ['10737546-2'],
'empty' => [''],
]);
it('compares by value', function () {
expect((new BusinessId('737546-2'))->equals(new BusinessId('0737546-2')))->toBeTrue()
->and((new BusinessId('0737546-2'))->equals(new BusinessId('1572860-0')))->toBeFalse();
});
@@ -0,0 +1,20 @@
<?php
use App\Modules\Customers\Domain\Exceptions\InvalidCustomerName;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
it('trims and collapses whitespace', function () {
expect((new CustomerName(" Mainos Oy \n"))->value)->toBe('Mainos Oy');
});
it('accepts a name of maximum length', function () {
expect(mb_strlen((new CustomerName(str_repeat('ä', 255)))->value))->toBe(255);
});
it('rejects an empty or too long name', function (string $name) {
new CustomerName($name);
})->throws(InvalidCustomerName::class)->with([
'empty' => [''],
'only whitespace' => [' '],
'too long' => [str_repeat('a', 256)],
]);
@@ -0,0 +1,44 @@
<?php
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\ConsumerCannotHaveBusinessId;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
it('registers a company with a business id and no id yet', function () {
$customer = Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company, new BusinessId('0737546-2'));
expect($customer->id())->toBeNull()
->and($customer->name()->value)->toBe('Mainos Oy')
->and($customer->businessId()?->value)->toBe('0737546-2');
});
it('registers a consumer without a business id', function () {
$customer = Customer::register(new CustomerName('Maija Meikäläinen'), CustomerType::Consumer);
expect($customer->type())->toBe(CustomerType::Consumer)
->and($customer->businessId())->toBeNull();
});
it('does not let a consumer have a business id', function () {
Customer::register(new CustomerName('Maija Meikäläinen'), CustomerType::Consumer, new BusinessId('0737546-2'));
})->throws(ConsumerCannotHaveBusinessId::class);
it('does not let a company with a business id become a consumer without removing it', function () {
$customer = Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company, new BusinessId('0737546-2'));
expect(fn () => $customer->changeDetails($customer->name(), CustomerType::Consumer, $customer->businessId()))
->toThrow(ConsumerCannotHaveBusinessId::class)
->and($customer->type())->toBe(CustomerType::Company);
});
it('changes details', function () {
$customer = Customer::reconstitute(7, new CustomerName('Mainos Oy'), CustomerType::Company, null);
$customer->changeDetails(new CustomerName('Mainos Oyj'), CustomerType::Company, new BusinessId('1572860-0'));
expect($customer->id())->toBe(7)
->and($customer->name()->value)->toBe('Mainos Oyj')
->and($customer->businessId()?->value)->toBe('1572860-0');
});