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:
@@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
+59
@@ -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);
|
||||
}
|
||||
}
|
||||
+52
@@ -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,
|
||||
];
|
||||
}
|
||||
Reference in New Issue
Block a user