diff --git a/.agents/skills/clean-architecture-development/SKILL.md b/.agents/skills/clean-architecture-development/SKILL.md new file mode 100644 index 0000000..21035ba --- /dev/null +++ b/.agents/skills/clean-architecture-development/SKILL.md @@ -0,0 +1,189 @@ +--- +name: clean-architecture-development +description: Build features in a Laravel app that uses plin-code/laravel-clean-architecture, generating domains, actions, services and infrastructure classes with the clean-arch commands and keeping the layer rules green. +--- + +# Clean Architecture development + +## When to use this skill + +Use it when the application has `app/Domain`, `app/Application` and +`app/Infrastructure` (or the paths configured in +`config/clean-architecture.php`), and you are adding a feature, a model, a use +case, a controller, a mailable or a notification, or you are fixing a +`phparkitect check` failure. + +## Before you generate anything + +Read `config/clean-architecture.php` first. `directories` and +`default_namespace` decide where files land and which namespaces they declare, +`generation.model_directory` decides whether the model sits in `Models` or +directly in the domain folder, `generation.job_prefix` (`Process` by default) +prefixes generated jobs and `generation.web_controller_path` +(`Http/Controllers/Web` by default) decides where `make-controller --web` +writes, while API controllers always go to `Http/Controllers/Api`. Never +hardcode `App\Domain`: derive it from the config. + +On a fresh Laravel app, run `php artisan clean-arch:install --user-in-domain` +to move the User model into the Domain layer before generating anything else. + +On an app that already has code in app/Http, app/Actions, app/Concerns or the +other Laravel folders, such as a starter kit app, run +`php artisan clean-arch:install --migrate-app`, then `composer dump-autoload`. +It moves those folders into the layers, rewrites the namespaces in PHP and the +Wayfinder imports in resources/js, and lists what it left outside the layers: +app/Providers on purpose, app/Models when it holds more than User, and folders +discovered by convention such as app/Policies or app/Livewire. It refuses to +change anything when a destination exists, unless `--force` is passed. +Regenerate the Wayfinder actions afterwards with `php artisan wayfinder:generate`, +passing the options the Vite plugin uses. + +## Adding a feature + +1. Generate the domain once per aggregate: + + php artisan clean-arch:make-domain Article + + It writes the model, the domain events, the CRUD actions, the requests, the + resource, the API controller, the migration, a factory and a feature test. Add + `--no-base` to skip the base classes when the project does not use them. + After that it asks whether to also generate an observer, a listener, a job, + a mail, a notification and an export, and `--no-interaction` declines them + all. Add the `Route::apiResource()` line it prints to routes/api.php: + the generated test calls the routes under `/api`. + +2. Add the use cases that are not CRUD as actions, one class one job: + + php artisan clean-arch:make-action PublishArticle Article + +3. Put side effects in the infrastructure layer: + + php artisan clean-arch:make-mail Article + php artisan clean-arch:make-notification Article + php artisan clean-arch:make-observer Article Article + +4. Wire the observer in a service provider, not in the domain model. + +These generators assume a CRUD on a domain model. `make-domain` writes the +whole set with fixed columns, `make-mail`, `make-notification`, `make-job`, +`make-listener`, `make-export` and `make-controller` take the name of a domain +and import its model, and `make-action` writes a body that creates the model. +When the class is not that (a mail named after an event, a controller that +renders one page, a domain that needs only its model, migration and factory), +do not generate and then delete or rewrite: create the class straight in its +layer with `php artisan make:class`, such as +`php artisan make:class Infrastructure/Mail/RegistrationConfirmedMail`, and +the migration and factory with Laravel's own generators. `make-action` is +still worth running for the file, the namespace and the base class: replace +its body. + +The single file commands (`make-action`, `make-service`, `make-controller`, +`make-observer`, `make-listener`, `make-job`, `make-mail`, `make-notification`, +`make-export`, `make-arch-rules`) refuse to overwrite an existing file and exit +1. `install`, `make-domain` and `generate-package` skip the files that already +exist, write the rest and exit 0. Pass `--force` when overwriting is what you +want. + +## Where each class belongs + +- Eloquent models, enums and domain events: `App\Domain`. +- Actions, services, jobs and listeners, which orchestrate use cases: + `App\Application`. +- Controllers, console commands, requests, resources, mail, notifications, + observers and exports: `App\Infrastructure`. A console command is an input + adapter like a controller, the business logic goes in an action. Laravel + only discovers commands in app/Console/Commands, so register the + infrastructure ones in bootstrap/app.php with `->withCommands([...])`. + +Four kinds of class have no `clean-arch` generator. Create them straight in +their layer, never in a Laravel default folder to move them afterwards: + +- Readonly DTOs: the `DTOs` folder of the application layer, for example + `php artisan make:class Application/DTOs/RegistrationData`. +- Policies of a domain model: a `Policies` folder next to the model, for + example `php artisan make:class Domain/Articles/Policies/ArticlePolicy`. + Laravel's policy discovery walks up from the model namespace and finds it + there, with or without the `Models` subfolder, so nothing has to be + registered. `make:policy` writes to app/Policies, outside the layers. A + policy only imports domain classes. +- Domain exceptions: an `Exceptions` folder next to the model, for example + `App\Domain\Articles\Exceptions\ArticleAlreadyPublishedException`, created + with `php artisan make:class Domain/Articles/Exceptions/ArticleAlreadyPublishedException`. + Make it extend PHP's `DomainException`, so the domain imports nothing from + the other layers, throw it from the action, and map it to an HTTP response + in the infrastructure layer, for example in `->withExceptions()` of + bootstrap/app.php. Never throw the exceptions `install` writes to + `App\Infrastructure\Exceptions` from an action or a model: importing them + breaks the layer rules. +- Filament panels: a panel is an input adapter like a controller, so its + resources, pages and widgets go in a `Filament` folder of the infrastructure + layer. Point `discoverResources()`, `discoverPages()` and + `discoverWidgets()` of the panel provider at that folder and namespace + before generating anything: `make:filament-resource` then writes there by + itself. Its resource namespace option is ignored for a namespace the + panel does not discover, and the command falls back to app/Filament, + overwriting what is there. The panel provider stays in app/Providers. + +An action never receives the HTTP request: the controller passes +`$request->validated()`, an array, and models already resolved. A readonly DTO +is fine when several callers must normalise the same input. + +Generated actions do not open a transaction. When an invariant only holds if +several writes, or a read and a write, happen atomically, the action opens it +itself, with `lockForUpdate()` when it reads before writing. Callers may still +wrap it in a larger transaction. Mail, events and jobs go in +`DB::afterCommit()`, so nothing leaves the system before the data is committed. + +The domain must not import the application layer nor the infrastructure layer. +The application layer must not import the infrastructure layer. + +When an action needs an outer service, or the domain needs something it does +not own such as a feature flag, add an interface in the layer that needs it, +implement it one layer out and bind the two in a service provider. Do not widen +`validation.application_infrastructure_allowed` to skip the interface. + +## Keeping the rules green + + php artisan clean-arch:make-arch-rules --force + vendor/bin/phparkitect check + +`check` exits 1 on violations. Two ways out, in order of preference: + +1. Move the class to the layer it belongs to, or put an interface in the + application layer and the implementation in the infrastructure layer. +2. Only when the project has decided that actions send mail or notifications + straight from the infrastructure layer, list the namespace in + `validation.application_infrastructure_allowed` (values are relative to the + infrastructure layer, for example `['Mail', 'Notifications']`), then + regenerate the rules with `--force`. Everything else in the infrastructure + layer stays reported. This is a choice of the project, written in its + config: when the list is empty, do not add to it to make a violation go + away, use the interface of point 1. For a mail that is an interface in the + application layer, such as `RegistrationNotifier`, with the class that + sends the mail in the infrastructure layer. + +Do not turn a rule off in `validation.rules` to silence a single violation: that +hides every other violation of the same rule. + +When `no_classes_outside_layers` is on, a class left in app/Http, app/Models, +app/Actions or any other folder outside the layers fails the check. Move it +into the layer it belongs to and update its namespace and every reference. +Only a folder that the framework or a package discovers by convention, such as +Providers or Policies, goes in `validation.outside_layers_allowed`, relative to +the root namespace. + +## Adopting the rules on an existing codebase + + vendor/bin/phparkitect generate-baseline + vendor/bin/phparkitect check + +The baseline records today's violations and `check` then fails only on new ones. + +## Installing this skill with Boost + +Boost asks whether to add a newly installed package only when `boost:update` +runs in an interactive terminal. Run without interaction, or from a Composer +script such as `post-update-cmd`, it skips the question and leaves the package +out. Add `plin-code/laravel-clean-architecture` to the packages list of +boost.json, then run `php artisan boost:update` again: Boost installs the +guideline and this skill, and records the skill name in boost.json itself. diff --git a/.claude/skills/clean-architecture-development/SKILL.md b/.claude/skills/clean-architecture-development/SKILL.md new file mode 100644 index 0000000..21035ba --- /dev/null +++ b/.claude/skills/clean-architecture-development/SKILL.md @@ -0,0 +1,189 @@ +--- +name: clean-architecture-development +description: Build features in a Laravel app that uses plin-code/laravel-clean-architecture, generating domains, actions, services and infrastructure classes with the clean-arch commands and keeping the layer rules green. +--- + +# Clean Architecture development + +## When to use this skill + +Use it when the application has `app/Domain`, `app/Application` and +`app/Infrastructure` (or the paths configured in +`config/clean-architecture.php`), and you are adding a feature, a model, a use +case, a controller, a mailable or a notification, or you are fixing a +`phparkitect check` failure. + +## Before you generate anything + +Read `config/clean-architecture.php` first. `directories` and +`default_namespace` decide where files land and which namespaces they declare, +`generation.model_directory` decides whether the model sits in `Models` or +directly in the domain folder, `generation.job_prefix` (`Process` by default) +prefixes generated jobs and `generation.web_controller_path` +(`Http/Controllers/Web` by default) decides where `make-controller --web` +writes, while API controllers always go to `Http/Controllers/Api`. Never +hardcode `App\Domain`: derive it from the config. + +On a fresh Laravel app, run `php artisan clean-arch:install --user-in-domain` +to move the User model into the Domain layer before generating anything else. + +On an app that already has code in app/Http, app/Actions, app/Concerns or the +other Laravel folders, such as a starter kit app, run +`php artisan clean-arch:install --migrate-app`, then `composer dump-autoload`. +It moves those folders into the layers, rewrites the namespaces in PHP and the +Wayfinder imports in resources/js, and lists what it left outside the layers: +app/Providers on purpose, app/Models when it holds more than User, and folders +discovered by convention such as app/Policies or app/Livewire. It refuses to +change anything when a destination exists, unless `--force` is passed. +Regenerate the Wayfinder actions afterwards with `php artisan wayfinder:generate`, +passing the options the Vite plugin uses. + +## Adding a feature + +1. Generate the domain once per aggregate: + + php artisan clean-arch:make-domain Article + + It writes the model, the domain events, the CRUD actions, the requests, the + resource, the API controller, the migration, a factory and a feature test. Add + `--no-base` to skip the base classes when the project does not use them. + After that it asks whether to also generate an observer, a listener, a job, + a mail, a notification and an export, and `--no-interaction` declines them + all. Add the `Route::apiResource()` line it prints to routes/api.php: + the generated test calls the routes under `/api`. + +2. Add the use cases that are not CRUD as actions, one class one job: + + php artisan clean-arch:make-action PublishArticle Article + +3. Put side effects in the infrastructure layer: + + php artisan clean-arch:make-mail Article + php artisan clean-arch:make-notification Article + php artisan clean-arch:make-observer Article Article + +4. Wire the observer in a service provider, not in the domain model. + +These generators assume a CRUD on a domain model. `make-domain` writes the +whole set with fixed columns, `make-mail`, `make-notification`, `make-job`, +`make-listener`, `make-export` and `make-controller` take the name of a domain +and import its model, and `make-action` writes a body that creates the model. +When the class is not that (a mail named after an event, a controller that +renders one page, a domain that needs only its model, migration and factory), +do not generate and then delete or rewrite: create the class straight in its +layer with `php artisan make:class`, such as +`php artisan make:class Infrastructure/Mail/RegistrationConfirmedMail`, and +the migration and factory with Laravel's own generators. `make-action` is +still worth running for the file, the namespace and the base class: replace +its body. + +The single file commands (`make-action`, `make-service`, `make-controller`, +`make-observer`, `make-listener`, `make-job`, `make-mail`, `make-notification`, +`make-export`, `make-arch-rules`) refuse to overwrite an existing file and exit +1. `install`, `make-domain` and `generate-package` skip the files that already +exist, write the rest and exit 0. Pass `--force` when overwriting is what you +want. + +## Where each class belongs + +- Eloquent models, enums and domain events: `App\Domain`. +- Actions, services, jobs and listeners, which orchestrate use cases: + `App\Application`. +- Controllers, console commands, requests, resources, mail, notifications, + observers and exports: `App\Infrastructure`. A console command is an input + adapter like a controller, the business logic goes in an action. Laravel + only discovers commands in app/Console/Commands, so register the + infrastructure ones in bootstrap/app.php with `->withCommands([...])`. + +Four kinds of class have no `clean-arch` generator. Create them straight in +their layer, never in a Laravel default folder to move them afterwards: + +- Readonly DTOs: the `DTOs` folder of the application layer, for example + `php artisan make:class Application/DTOs/RegistrationData`. +- Policies of a domain model: a `Policies` folder next to the model, for + example `php artisan make:class Domain/Articles/Policies/ArticlePolicy`. + Laravel's policy discovery walks up from the model namespace and finds it + there, with or without the `Models` subfolder, so nothing has to be + registered. `make:policy` writes to app/Policies, outside the layers. A + policy only imports domain classes. +- Domain exceptions: an `Exceptions` folder next to the model, for example + `App\Domain\Articles\Exceptions\ArticleAlreadyPublishedException`, created + with `php artisan make:class Domain/Articles/Exceptions/ArticleAlreadyPublishedException`. + Make it extend PHP's `DomainException`, so the domain imports nothing from + the other layers, throw it from the action, and map it to an HTTP response + in the infrastructure layer, for example in `->withExceptions()` of + bootstrap/app.php. Never throw the exceptions `install` writes to + `App\Infrastructure\Exceptions` from an action or a model: importing them + breaks the layer rules. +- Filament panels: a panel is an input adapter like a controller, so its + resources, pages and widgets go in a `Filament` folder of the infrastructure + layer. Point `discoverResources()`, `discoverPages()` and + `discoverWidgets()` of the panel provider at that folder and namespace + before generating anything: `make:filament-resource` then writes there by + itself. Its resource namespace option is ignored for a namespace the + panel does not discover, and the command falls back to app/Filament, + overwriting what is there. The panel provider stays in app/Providers. + +An action never receives the HTTP request: the controller passes +`$request->validated()`, an array, and models already resolved. A readonly DTO +is fine when several callers must normalise the same input. + +Generated actions do not open a transaction. When an invariant only holds if +several writes, or a read and a write, happen atomically, the action opens it +itself, with `lockForUpdate()` when it reads before writing. Callers may still +wrap it in a larger transaction. Mail, events and jobs go in +`DB::afterCommit()`, so nothing leaves the system before the data is committed. + +The domain must not import the application layer nor the infrastructure layer. +The application layer must not import the infrastructure layer. + +When an action needs an outer service, or the domain needs something it does +not own such as a feature flag, add an interface in the layer that needs it, +implement it one layer out and bind the two in a service provider. Do not widen +`validation.application_infrastructure_allowed` to skip the interface. + +## Keeping the rules green + + php artisan clean-arch:make-arch-rules --force + vendor/bin/phparkitect check + +`check` exits 1 on violations. Two ways out, in order of preference: + +1. Move the class to the layer it belongs to, or put an interface in the + application layer and the implementation in the infrastructure layer. +2. Only when the project has decided that actions send mail or notifications + straight from the infrastructure layer, list the namespace in + `validation.application_infrastructure_allowed` (values are relative to the + infrastructure layer, for example `['Mail', 'Notifications']`), then + regenerate the rules with `--force`. Everything else in the infrastructure + layer stays reported. This is a choice of the project, written in its + config: when the list is empty, do not add to it to make a violation go + away, use the interface of point 1. For a mail that is an interface in the + application layer, such as `RegistrationNotifier`, with the class that + sends the mail in the infrastructure layer. + +Do not turn a rule off in `validation.rules` to silence a single violation: that +hides every other violation of the same rule. + +When `no_classes_outside_layers` is on, a class left in app/Http, app/Models, +app/Actions or any other folder outside the layers fails the check. Move it +into the layer it belongs to and update its namespace and every reference. +Only a folder that the framework or a package discovers by convention, such as +Providers or Policies, goes in `validation.outside_layers_allowed`, relative to +the root namespace. + +## Adopting the rules on an existing codebase + + vendor/bin/phparkitect generate-baseline + vendor/bin/phparkitect check + +The baseline records today's violations and `check` then fails only on new ones. + +## Installing this skill with Boost + +Boost asks whether to add a newly installed package only when `boost:update` +runs in an interactive terminal. Run without interaction, or from a Composer +script such as `post-update-cmd`, it skips the question and leaves the package +out. Add `plin-code/laravel-clean-architecture` to the packages list of +boost.json, then run `php artisan boost:update` again: Boost installs the +guideline and this skill, and records the skill name in boost.json itself. diff --git a/.cursor/skills/clean-architecture-development/SKILL.md b/.cursor/skills/clean-architecture-development/SKILL.md new file mode 100644 index 0000000..21035ba --- /dev/null +++ b/.cursor/skills/clean-architecture-development/SKILL.md @@ -0,0 +1,189 @@ +--- +name: clean-architecture-development +description: Build features in a Laravel app that uses plin-code/laravel-clean-architecture, generating domains, actions, services and infrastructure classes with the clean-arch commands and keeping the layer rules green. +--- + +# Clean Architecture development + +## When to use this skill + +Use it when the application has `app/Domain`, `app/Application` and +`app/Infrastructure` (or the paths configured in +`config/clean-architecture.php`), and you are adding a feature, a model, a use +case, a controller, a mailable or a notification, or you are fixing a +`phparkitect check` failure. + +## Before you generate anything + +Read `config/clean-architecture.php` first. `directories` and +`default_namespace` decide where files land and which namespaces they declare, +`generation.model_directory` decides whether the model sits in `Models` or +directly in the domain folder, `generation.job_prefix` (`Process` by default) +prefixes generated jobs and `generation.web_controller_path` +(`Http/Controllers/Web` by default) decides where `make-controller --web` +writes, while API controllers always go to `Http/Controllers/Api`. Never +hardcode `App\Domain`: derive it from the config. + +On a fresh Laravel app, run `php artisan clean-arch:install --user-in-domain` +to move the User model into the Domain layer before generating anything else. + +On an app that already has code in app/Http, app/Actions, app/Concerns or the +other Laravel folders, such as a starter kit app, run +`php artisan clean-arch:install --migrate-app`, then `composer dump-autoload`. +It moves those folders into the layers, rewrites the namespaces in PHP and the +Wayfinder imports in resources/js, and lists what it left outside the layers: +app/Providers on purpose, app/Models when it holds more than User, and folders +discovered by convention such as app/Policies or app/Livewire. It refuses to +change anything when a destination exists, unless `--force` is passed. +Regenerate the Wayfinder actions afterwards with `php artisan wayfinder:generate`, +passing the options the Vite plugin uses. + +## Adding a feature + +1. Generate the domain once per aggregate: + + php artisan clean-arch:make-domain Article + + It writes the model, the domain events, the CRUD actions, the requests, the + resource, the API controller, the migration, a factory and a feature test. Add + `--no-base` to skip the base classes when the project does not use them. + After that it asks whether to also generate an observer, a listener, a job, + a mail, a notification and an export, and `--no-interaction` declines them + all. Add the `Route::apiResource()` line it prints to routes/api.php: + the generated test calls the routes under `/api`. + +2. Add the use cases that are not CRUD as actions, one class one job: + + php artisan clean-arch:make-action PublishArticle Article + +3. Put side effects in the infrastructure layer: + + php artisan clean-arch:make-mail Article + php artisan clean-arch:make-notification Article + php artisan clean-arch:make-observer Article Article + +4. Wire the observer in a service provider, not in the domain model. + +These generators assume a CRUD on a domain model. `make-domain` writes the +whole set with fixed columns, `make-mail`, `make-notification`, `make-job`, +`make-listener`, `make-export` and `make-controller` take the name of a domain +and import its model, and `make-action` writes a body that creates the model. +When the class is not that (a mail named after an event, a controller that +renders one page, a domain that needs only its model, migration and factory), +do not generate and then delete or rewrite: create the class straight in its +layer with `php artisan make:class`, such as +`php artisan make:class Infrastructure/Mail/RegistrationConfirmedMail`, and +the migration and factory with Laravel's own generators. `make-action` is +still worth running for the file, the namespace and the base class: replace +its body. + +The single file commands (`make-action`, `make-service`, `make-controller`, +`make-observer`, `make-listener`, `make-job`, `make-mail`, `make-notification`, +`make-export`, `make-arch-rules`) refuse to overwrite an existing file and exit +1. `install`, `make-domain` and `generate-package` skip the files that already +exist, write the rest and exit 0. Pass `--force` when overwriting is what you +want. + +## Where each class belongs + +- Eloquent models, enums and domain events: `App\Domain`. +- Actions, services, jobs and listeners, which orchestrate use cases: + `App\Application`. +- Controllers, console commands, requests, resources, mail, notifications, + observers and exports: `App\Infrastructure`. A console command is an input + adapter like a controller, the business logic goes in an action. Laravel + only discovers commands in app/Console/Commands, so register the + infrastructure ones in bootstrap/app.php with `->withCommands([...])`. + +Four kinds of class have no `clean-arch` generator. Create them straight in +their layer, never in a Laravel default folder to move them afterwards: + +- Readonly DTOs: the `DTOs` folder of the application layer, for example + `php artisan make:class Application/DTOs/RegistrationData`. +- Policies of a domain model: a `Policies` folder next to the model, for + example `php artisan make:class Domain/Articles/Policies/ArticlePolicy`. + Laravel's policy discovery walks up from the model namespace and finds it + there, with or without the `Models` subfolder, so nothing has to be + registered. `make:policy` writes to app/Policies, outside the layers. A + policy only imports domain classes. +- Domain exceptions: an `Exceptions` folder next to the model, for example + `App\Domain\Articles\Exceptions\ArticleAlreadyPublishedException`, created + with `php artisan make:class Domain/Articles/Exceptions/ArticleAlreadyPublishedException`. + Make it extend PHP's `DomainException`, so the domain imports nothing from + the other layers, throw it from the action, and map it to an HTTP response + in the infrastructure layer, for example in `->withExceptions()` of + bootstrap/app.php. Never throw the exceptions `install` writes to + `App\Infrastructure\Exceptions` from an action or a model: importing them + breaks the layer rules. +- Filament panels: a panel is an input adapter like a controller, so its + resources, pages and widgets go in a `Filament` folder of the infrastructure + layer. Point `discoverResources()`, `discoverPages()` and + `discoverWidgets()` of the panel provider at that folder and namespace + before generating anything: `make:filament-resource` then writes there by + itself. Its resource namespace option is ignored for a namespace the + panel does not discover, and the command falls back to app/Filament, + overwriting what is there. The panel provider stays in app/Providers. + +An action never receives the HTTP request: the controller passes +`$request->validated()`, an array, and models already resolved. A readonly DTO +is fine when several callers must normalise the same input. + +Generated actions do not open a transaction. When an invariant only holds if +several writes, or a read and a write, happen atomically, the action opens it +itself, with `lockForUpdate()` when it reads before writing. Callers may still +wrap it in a larger transaction. Mail, events and jobs go in +`DB::afterCommit()`, so nothing leaves the system before the data is committed. + +The domain must not import the application layer nor the infrastructure layer. +The application layer must not import the infrastructure layer. + +When an action needs an outer service, or the domain needs something it does +not own such as a feature flag, add an interface in the layer that needs it, +implement it one layer out and bind the two in a service provider. Do not widen +`validation.application_infrastructure_allowed` to skip the interface. + +## Keeping the rules green + + php artisan clean-arch:make-arch-rules --force + vendor/bin/phparkitect check + +`check` exits 1 on violations. Two ways out, in order of preference: + +1. Move the class to the layer it belongs to, or put an interface in the + application layer and the implementation in the infrastructure layer. +2. Only when the project has decided that actions send mail or notifications + straight from the infrastructure layer, list the namespace in + `validation.application_infrastructure_allowed` (values are relative to the + infrastructure layer, for example `['Mail', 'Notifications']`), then + regenerate the rules with `--force`. Everything else in the infrastructure + layer stays reported. This is a choice of the project, written in its + config: when the list is empty, do not add to it to make a violation go + away, use the interface of point 1. For a mail that is an interface in the + application layer, such as `RegistrationNotifier`, with the class that + sends the mail in the infrastructure layer. + +Do not turn a rule off in `validation.rules` to silence a single violation: that +hides every other violation of the same rule. + +When `no_classes_outside_layers` is on, a class left in app/Http, app/Models, +app/Actions or any other folder outside the layers fails the check. Move it +into the layer it belongs to and update its namespace and every reference. +Only a folder that the framework or a package discovers by convention, such as +Providers or Policies, goes in `validation.outside_layers_allowed`, relative to +the root namespace. + +## Adopting the rules on an existing codebase + + vendor/bin/phparkitect generate-baseline + vendor/bin/phparkitect check + +The baseline records today's violations and `check` then fails only on new ones. + +## Installing this skill with Boost + +Boost asks whether to add a newly installed package only when `boost:update` +runs in an interactive terminal. Run without interaction, or from a Composer +script such as `post-update-cmd`, it skips the question and leaves the package +out. Add `plin-code/laravel-clean-architecture` to the packages list of +boost.json, then run `php artisan boost:update` again: Boost installs the +guideline and this skill, and records the skill name in boost.json itself. diff --git a/.env.example b/.env.example index 9c368b6..c5d8edb 100644 --- a/.env.example +++ b/.env.example @@ -47,7 +47,7 @@ REDIS_HOST=redis REDIS_PASSWORD=null REDIS_PORT=6379 -MAIL_MAILER=smtp +MAIL_MAILER=log MAIL_SCHEME=null MAIL_HOST=mailpit MAIL_PORT=1025 diff --git a/.grok/skills/clean-architecture-development/SKILL.md b/.grok/skills/clean-architecture-development/SKILL.md new file mode 100644 index 0000000..21035ba --- /dev/null +++ b/.grok/skills/clean-architecture-development/SKILL.md @@ -0,0 +1,189 @@ +--- +name: clean-architecture-development +description: Build features in a Laravel app that uses plin-code/laravel-clean-architecture, generating domains, actions, services and infrastructure classes with the clean-arch commands and keeping the layer rules green. +--- + +# Clean Architecture development + +## When to use this skill + +Use it when the application has `app/Domain`, `app/Application` and +`app/Infrastructure` (or the paths configured in +`config/clean-architecture.php`), and you are adding a feature, a model, a use +case, a controller, a mailable or a notification, or you are fixing a +`phparkitect check` failure. + +## Before you generate anything + +Read `config/clean-architecture.php` first. `directories` and +`default_namespace` decide where files land and which namespaces they declare, +`generation.model_directory` decides whether the model sits in `Models` or +directly in the domain folder, `generation.job_prefix` (`Process` by default) +prefixes generated jobs and `generation.web_controller_path` +(`Http/Controllers/Web` by default) decides where `make-controller --web` +writes, while API controllers always go to `Http/Controllers/Api`. Never +hardcode `App\Domain`: derive it from the config. + +On a fresh Laravel app, run `php artisan clean-arch:install --user-in-domain` +to move the User model into the Domain layer before generating anything else. + +On an app that already has code in app/Http, app/Actions, app/Concerns or the +other Laravel folders, such as a starter kit app, run +`php artisan clean-arch:install --migrate-app`, then `composer dump-autoload`. +It moves those folders into the layers, rewrites the namespaces in PHP and the +Wayfinder imports in resources/js, and lists what it left outside the layers: +app/Providers on purpose, app/Models when it holds more than User, and folders +discovered by convention such as app/Policies or app/Livewire. It refuses to +change anything when a destination exists, unless `--force` is passed. +Regenerate the Wayfinder actions afterwards with `php artisan wayfinder:generate`, +passing the options the Vite plugin uses. + +## Adding a feature + +1. Generate the domain once per aggregate: + + php artisan clean-arch:make-domain Article + + It writes the model, the domain events, the CRUD actions, the requests, the + resource, the API controller, the migration, a factory and a feature test. Add + `--no-base` to skip the base classes when the project does not use them. + After that it asks whether to also generate an observer, a listener, a job, + a mail, a notification and an export, and `--no-interaction` declines them + all. Add the `Route::apiResource()` line it prints to routes/api.php: + the generated test calls the routes under `/api`. + +2. Add the use cases that are not CRUD as actions, one class one job: + + php artisan clean-arch:make-action PublishArticle Article + +3. Put side effects in the infrastructure layer: + + php artisan clean-arch:make-mail Article + php artisan clean-arch:make-notification Article + php artisan clean-arch:make-observer Article Article + +4. Wire the observer in a service provider, not in the domain model. + +These generators assume a CRUD on a domain model. `make-domain` writes the +whole set with fixed columns, `make-mail`, `make-notification`, `make-job`, +`make-listener`, `make-export` and `make-controller` take the name of a domain +and import its model, and `make-action` writes a body that creates the model. +When the class is not that (a mail named after an event, a controller that +renders one page, a domain that needs only its model, migration and factory), +do not generate and then delete or rewrite: create the class straight in its +layer with `php artisan make:class`, such as +`php artisan make:class Infrastructure/Mail/RegistrationConfirmedMail`, and +the migration and factory with Laravel's own generators. `make-action` is +still worth running for the file, the namespace and the base class: replace +its body. + +The single file commands (`make-action`, `make-service`, `make-controller`, +`make-observer`, `make-listener`, `make-job`, `make-mail`, `make-notification`, +`make-export`, `make-arch-rules`) refuse to overwrite an existing file and exit +1. `install`, `make-domain` and `generate-package` skip the files that already +exist, write the rest and exit 0. Pass `--force` when overwriting is what you +want. + +## Where each class belongs + +- Eloquent models, enums and domain events: `App\Domain`. +- Actions, services, jobs and listeners, which orchestrate use cases: + `App\Application`. +- Controllers, console commands, requests, resources, mail, notifications, + observers and exports: `App\Infrastructure`. A console command is an input + adapter like a controller, the business logic goes in an action. Laravel + only discovers commands in app/Console/Commands, so register the + infrastructure ones in bootstrap/app.php with `->withCommands([...])`. + +Four kinds of class have no `clean-arch` generator. Create them straight in +their layer, never in a Laravel default folder to move them afterwards: + +- Readonly DTOs: the `DTOs` folder of the application layer, for example + `php artisan make:class Application/DTOs/RegistrationData`. +- Policies of a domain model: a `Policies` folder next to the model, for + example `php artisan make:class Domain/Articles/Policies/ArticlePolicy`. + Laravel's policy discovery walks up from the model namespace and finds it + there, with or without the `Models` subfolder, so nothing has to be + registered. `make:policy` writes to app/Policies, outside the layers. A + policy only imports domain classes. +- Domain exceptions: an `Exceptions` folder next to the model, for example + `App\Domain\Articles\Exceptions\ArticleAlreadyPublishedException`, created + with `php artisan make:class Domain/Articles/Exceptions/ArticleAlreadyPublishedException`. + Make it extend PHP's `DomainException`, so the domain imports nothing from + the other layers, throw it from the action, and map it to an HTTP response + in the infrastructure layer, for example in `->withExceptions()` of + bootstrap/app.php. Never throw the exceptions `install` writes to + `App\Infrastructure\Exceptions` from an action or a model: importing them + breaks the layer rules. +- Filament panels: a panel is an input adapter like a controller, so its + resources, pages and widgets go in a `Filament` folder of the infrastructure + layer. Point `discoverResources()`, `discoverPages()` and + `discoverWidgets()` of the panel provider at that folder and namespace + before generating anything: `make:filament-resource` then writes there by + itself. Its resource namespace option is ignored for a namespace the + panel does not discover, and the command falls back to app/Filament, + overwriting what is there. The panel provider stays in app/Providers. + +An action never receives the HTTP request: the controller passes +`$request->validated()`, an array, and models already resolved. A readonly DTO +is fine when several callers must normalise the same input. + +Generated actions do not open a transaction. When an invariant only holds if +several writes, or a read and a write, happen atomically, the action opens it +itself, with `lockForUpdate()` when it reads before writing. Callers may still +wrap it in a larger transaction. Mail, events and jobs go in +`DB::afterCommit()`, so nothing leaves the system before the data is committed. + +The domain must not import the application layer nor the infrastructure layer. +The application layer must not import the infrastructure layer. + +When an action needs an outer service, or the domain needs something it does +not own such as a feature flag, add an interface in the layer that needs it, +implement it one layer out and bind the two in a service provider. Do not widen +`validation.application_infrastructure_allowed` to skip the interface. + +## Keeping the rules green + + php artisan clean-arch:make-arch-rules --force + vendor/bin/phparkitect check + +`check` exits 1 on violations. Two ways out, in order of preference: + +1. Move the class to the layer it belongs to, or put an interface in the + application layer and the implementation in the infrastructure layer. +2. Only when the project has decided that actions send mail or notifications + straight from the infrastructure layer, list the namespace in + `validation.application_infrastructure_allowed` (values are relative to the + infrastructure layer, for example `['Mail', 'Notifications']`), then + regenerate the rules with `--force`. Everything else in the infrastructure + layer stays reported. This is a choice of the project, written in its + config: when the list is empty, do not add to it to make a violation go + away, use the interface of point 1. For a mail that is an interface in the + application layer, such as `RegistrationNotifier`, with the class that + sends the mail in the infrastructure layer. + +Do not turn a rule off in `validation.rules` to silence a single violation: that +hides every other violation of the same rule. + +When `no_classes_outside_layers` is on, a class left in app/Http, app/Models, +app/Actions or any other folder outside the layers fails the check. Move it +into the layer it belongs to and update its namespace and every reference. +Only a folder that the framework or a package discovers by convention, such as +Providers or Policies, goes in `validation.outside_layers_allowed`, relative to +the root namespace. + +## Adopting the rules on an existing codebase + + vendor/bin/phparkitect generate-baseline + vendor/bin/phparkitect check + +The baseline records today's violations and `check` then fails only on new ones. + +## Installing this skill with Boost + +Boost asks whether to add a newly installed package only when `boost:update` +runs in an interactive terminal. Run without interaction, or from a Composer +script such as `post-update-cmd`, it skips the question and leaves the package +out. Add `plin-code/laravel-clean-architecture` to the packages list of +boost.json, then run `php artisan boost:update` again: Boost installs the +guideline and this skill, and records the skill name in boost.json itself. diff --git a/.pi/skills/clean-architecture-development/SKILL.md b/.pi/skills/clean-architecture-development/SKILL.md new file mode 100644 index 0000000..21035ba --- /dev/null +++ b/.pi/skills/clean-architecture-development/SKILL.md @@ -0,0 +1,189 @@ +--- +name: clean-architecture-development +description: Build features in a Laravel app that uses plin-code/laravel-clean-architecture, generating domains, actions, services and infrastructure classes with the clean-arch commands and keeping the layer rules green. +--- + +# Clean Architecture development + +## When to use this skill + +Use it when the application has `app/Domain`, `app/Application` and +`app/Infrastructure` (or the paths configured in +`config/clean-architecture.php`), and you are adding a feature, a model, a use +case, a controller, a mailable or a notification, or you are fixing a +`phparkitect check` failure. + +## Before you generate anything + +Read `config/clean-architecture.php` first. `directories` and +`default_namespace` decide where files land and which namespaces they declare, +`generation.model_directory` decides whether the model sits in `Models` or +directly in the domain folder, `generation.job_prefix` (`Process` by default) +prefixes generated jobs and `generation.web_controller_path` +(`Http/Controllers/Web` by default) decides where `make-controller --web` +writes, while API controllers always go to `Http/Controllers/Api`. Never +hardcode `App\Domain`: derive it from the config. + +On a fresh Laravel app, run `php artisan clean-arch:install --user-in-domain` +to move the User model into the Domain layer before generating anything else. + +On an app that already has code in app/Http, app/Actions, app/Concerns or the +other Laravel folders, such as a starter kit app, run +`php artisan clean-arch:install --migrate-app`, then `composer dump-autoload`. +It moves those folders into the layers, rewrites the namespaces in PHP and the +Wayfinder imports in resources/js, and lists what it left outside the layers: +app/Providers on purpose, app/Models when it holds more than User, and folders +discovered by convention such as app/Policies or app/Livewire. It refuses to +change anything when a destination exists, unless `--force` is passed. +Regenerate the Wayfinder actions afterwards with `php artisan wayfinder:generate`, +passing the options the Vite plugin uses. + +## Adding a feature + +1. Generate the domain once per aggregate: + + php artisan clean-arch:make-domain Article + + It writes the model, the domain events, the CRUD actions, the requests, the + resource, the API controller, the migration, a factory and a feature test. Add + `--no-base` to skip the base classes when the project does not use them. + After that it asks whether to also generate an observer, a listener, a job, + a mail, a notification and an export, and `--no-interaction` declines them + all. Add the `Route::apiResource()` line it prints to routes/api.php: + the generated test calls the routes under `/api`. + +2. Add the use cases that are not CRUD as actions, one class one job: + + php artisan clean-arch:make-action PublishArticle Article + +3. Put side effects in the infrastructure layer: + + php artisan clean-arch:make-mail Article + php artisan clean-arch:make-notification Article + php artisan clean-arch:make-observer Article Article + +4. Wire the observer in a service provider, not in the domain model. + +These generators assume a CRUD on a domain model. `make-domain` writes the +whole set with fixed columns, `make-mail`, `make-notification`, `make-job`, +`make-listener`, `make-export` and `make-controller` take the name of a domain +and import its model, and `make-action` writes a body that creates the model. +When the class is not that (a mail named after an event, a controller that +renders one page, a domain that needs only its model, migration and factory), +do not generate and then delete or rewrite: create the class straight in its +layer with `php artisan make:class`, such as +`php artisan make:class Infrastructure/Mail/RegistrationConfirmedMail`, and +the migration and factory with Laravel's own generators. `make-action` is +still worth running for the file, the namespace and the base class: replace +its body. + +The single file commands (`make-action`, `make-service`, `make-controller`, +`make-observer`, `make-listener`, `make-job`, `make-mail`, `make-notification`, +`make-export`, `make-arch-rules`) refuse to overwrite an existing file and exit +1. `install`, `make-domain` and `generate-package` skip the files that already +exist, write the rest and exit 0. Pass `--force` when overwriting is what you +want. + +## Where each class belongs + +- Eloquent models, enums and domain events: `App\Domain`. +- Actions, services, jobs and listeners, which orchestrate use cases: + `App\Application`. +- Controllers, console commands, requests, resources, mail, notifications, + observers and exports: `App\Infrastructure`. A console command is an input + adapter like a controller, the business logic goes in an action. Laravel + only discovers commands in app/Console/Commands, so register the + infrastructure ones in bootstrap/app.php with `->withCommands([...])`. + +Four kinds of class have no `clean-arch` generator. Create them straight in +their layer, never in a Laravel default folder to move them afterwards: + +- Readonly DTOs: the `DTOs` folder of the application layer, for example + `php artisan make:class Application/DTOs/RegistrationData`. +- Policies of a domain model: a `Policies` folder next to the model, for + example `php artisan make:class Domain/Articles/Policies/ArticlePolicy`. + Laravel's policy discovery walks up from the model namespace and finds it + there, with or without the `Models` subfolder, so nothing has to be + registered. `make:policy` writes to app/Policies, outside the layers. A + policy only imports domain classes. +- Domain exceptions: an `Exceptions` folder next to the model, for example + `App\Domain\Articles\Exceptions\ArticleAlreadyPublishedException`, created + with `php artisan make:class Domain/Articles/Exceptions/ArticleAlreadyPublishedException`. + Make it extend PHP's `DomainException`, so the domain imports nothing from + the other layers, throw it from the action, and map it to an HTTP response + in the infrastructure layer, for example in `->withExceptions()` of + bootstrap/app.php. Never throw the exceptions `install` writes to + `App\Infrastructure\Exceptions` from an action or a model: importing them + breaks the layer rules. +- Filament panels: a panel is an input adapter like a controller, so its + resources, pages and widgets go in a `Filament` folder of the infrastructure + layer. Point `discoverResources()`, `discoverPages()` and + `discoverWidgets()` of the panel provider at that folder and namespace + before generating anything: `make:filament-resource` then writes there by + itself. Its resource namespace option is ignored for a namespace the + panel does not discover, and the command falls back to app/Filament, + overwriting what is there. The panel provider stays in app/Providers. + +An action never receives the HTTP request: the controller passes +`$request->validated()`, an array, and models already resolved. A readonly DTO +is fine when several callers must normalise the same input. + +Generated actions do not open a transaction. When an invariant only holds if +several writes, or a read and a write, happen atomically, the action opens it +itself, with `lockForUpdate()` when it reads before writing. Callers may still +wrap it in a larger transaction. Mail, events and jobs go in +`DB::afterCommit()`, so nothing leaves the system before the data is committed. + +The domain must not import the application layer nor the infrastructure layer. +The application layer must not import the infrastructure layer. + +When an action needs an outer service, or the domain needs something it does +not own such as a feature flag, add an interface in the layer that needs it, +implement it one layer out and bind the two in a service provider. Do not widen +`validation.application_infrastructure_allowed` to skip the interface. + +## Keeping the rules green + + php artisan clean-arch:make-arch-rules --force + vendor/bin/phparkitect check + +`check` exits 1 on violations. Two ways out, in order of preference: + +1. Move the class to the layer it belongs to, or put an interface in the + application layer and the implementation in the infrastructure layer. +2. Only when the project has decided that actions send mail or notifications + straight from the infrastructure layer, list the namespace in + `validation.application_infrastructure_allowed` (values are relative to the + infrastructure layer, for example `['Mail', 'Notifications']`), then + regenerate the rules with `--force`. Everything else in the infrastructure + layer stays reported. This is a choice of the project, written in its + config: when the list is empty, do not add to it to make a violation go + away, use the interface of point 1. For a mail that is an interface in the + application layer, such as `RegistrationNotifier`, with the class that + sends the mail in the infrastructure layer. + +Do not turn a rule off in `validation.rules` to silence a single violation: that +hides every other violation of the same rule. + +When `no_classes_outside_layers` is on, a class left in app/Http, app/Models, +app/Actions or any other folder outside the layers fails the check. Move it +into the layer it belongs to and update its namespace and every reference. +Only a folder that the framework or a package discovers by convention, such as +Providers or Policies, goes in `validation.outside_layers_allowed`, relative to +the root namespace. + +## Adopting the rules on an existing codebase + + vendor/bin/phparkitect generate-baseline + vendor/bin/phparkitect check + +The baseline records today's violations and `check` then fails only on new ones. + +## Installing this skill with Boost + +Boost asks whether to add a newly installed package only when `boost:update` +runs in an interactive terminal. Run without interaction, or from a Composer +script such as `post-update-cmd`, it skips the question and leaves the package +out. Add `plin-code/laravel-clean-architecture` to the packages list of +boost.json, then run `php artisan boost:update` again: Boost installs the +guideline and this skill, and records the skill name in boost.json itself. diff --git a/AGENTS.md b/AGENTS.md index ed61c2a..d97ca34 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -205,6 +205,126 @@ Use Wayfinder to generate TypeScript functions for Laravel routes. Import from ` - IMPORTANT: Activate `inertia-react-development` when working with Inertia React client-side patterns. +=== plin-code/laravel-clean-architecture/core rules === + +## Laravel Clean Architecture + +This package generates and enforces a three layer structure: `App\Domain`, +`App\Application`, `App\Infrastructure`. Generate code with its commands instead +of writing the folders by hand, so namespaces, base classes and file names stay +consistent with the configured paths. + +### Layers and dependency direction + +- `App\Domain`: Eloquent models, enums, domain events, must not depend on + `App\Application` or `App\Infrastructure`. +- `App\Application`: actions, services, jobs and listeners, the use cases, + must not depend on `App\Infrastructure`, unless the namespace is listed in + `validation.application_infrastructure_allowed`. +- `App\Infrastructure`: controllers, console commands, requests, resources, + mail, notifications, observers, exports. Depends on the layers above, never + the other way round. +- Observers belong to `App\Infrastructure`, not to the domain. Queued jobs + orchestrate use cases and belong to `App\Application`. Console commands are + input adapters like controllers: they belong to `App\Infrastructure` and + call an action, which holds the business logic. Laravel only discovers + commands in app/Console/Commands, so register the infrastructure ones in + bootstrap/app.php with `->withCommands([...])`. +- DTOs, policies and Filament panels have no generator: the skill says + where each one goes. +- An action never receives the HTTP request. The controller passes + `$request->validated()`, an array, and models already resolved. A readonly + DTO is fine when several callers must normalise the same input. +- Generated actions do not open a transaction. When an invariant only holds if + several writes, or a read and a write, happen atomically, the action opens it + itself, with `lockForUpdate()` when it reads before writing. Mail, events and + jobs go in `DB::afterCommit()`. +- To cross a layer, the inner layer declares an interface and the outer layer + implements it, bound in a service provider: a port in `App\Application` with + its adapter in `App\Infrastructure`, or a contract in `App\Domain` + implemented in `App\Application`. A class with one implementation, used only + inside its own layer, needs no contract. + +### Generating code + + +php artisan clean-arch:install +php artisan clean-arch:make-domain Article +php artisan clean-arch:make-action PublishArticle Article +php artisan clean-arch:make-service Article +php artisan clean-arch:make-controller Article +php artisan clean-arch:make-mail Article +php artisan clean-arch:make-notification Article +php artisan clean-arch:make-observer Article Article +php artisan clean-arch:make-job Article +php artisan clean-arch:make-listener Article +php artisan clean-arch:make-export Article + + +`clean-arch:make-domain` writes the model, the events, the actions, the +requests, the resource, the controller, the migration, the factory and the test +in one go. +Pass `--no-base` to skip the base classes. After that it asks, one confirm at a +time, whether to also generate an observer, a listener, a job, a mail, a +notification and an export, and `--no-interaction` declines all six. It does +not write routes: it prints the `Route::apiResource()` line to add to +routes/api.php, which the generated test calls under `/api`. + +Single file commands (make-action, make-service, make-controller, +make-observer, make-listener, make-job, make-mail, make-notification, +make-export, make-arch-rules) refuse to overwrite an existing file and exit 1. +`clean-arch:install`, `clean-arch:make-domain` and `clean-arch:generate-package` +skip existing files instead, write the rest, and exit 0. Either way, pass +`--force` to overwrite. + +`clean-arch:install --migrate-app` moves app/Http, app/Actions, app/Concerns +and the other Laravel folders into the layers and rewrites the references. +`--user-in-domain` moves `User` alone into `App\Domain`. + +### Checking the architecture + +The package does not analyse code itself, it writes a phparkitect +configuration that the application runs. + + +composer require --dev phparkitect/phparkitect +php artisan clean-arch:make-arch-rules +vendor/bin/phparkitect check + + +Regenerate `phparkitect.php` with `clean-arch:make-arch-rules --force` after +changing any key under `validation` in the config, otherwise the file keeps the +old rules. + +### Configuration that changes where code is written + +Read `config/clean-architecture.php` before assuming paths or namespaces: + +- `directories.domain`, `directories.application`, `directories.infrastructure`: + where each layer lives. The namespaces are derived from these paths. +- `default_namespace`: the root namespace, `App` by default. +- `generation.model_directory`: the subfolder of the domain model, `Models` by + default. An empty value puts the model directly in the domain folder. +- `generation.job_prefix`: the prefix of generated jobs, `Process` by default. +- `generation.web_controller_path`: where `make-controller --web` writes, + `Http/Controllers/Web` by default. API controllers always go to + `Http/Controllers/Api`. +- `validation.rules`: the seven rules written into `phparkitect.php`, each can + be turned off by name. `no_commands_in_infrastructure` and + `no_classes_outside_layers` are off by default. The latter reports every class + of the root namespace (app/ with the defaults) outside the three layers. +- `validation.outside_layers_allowed`: namespaces, relative to the root + namespace, that may stay outside the layers. `['Providers']` by default. +- `validation.application_infrastructure_allowed`: infrastructure namespaces the + application layer may import, relative to the infrastructure layer. Empty by + default. + + +'validation' => [ + 'application_infrastructure_allowed' => ['Mail', 'Notifications'], +], + + === plin-code/laravel-custom-fields/core rules === ## Laravel Custom Fields diff --git a/CLEAN_ARCHITECTURE.md b/CLEAN_ARCHITECTURE.md new file mode 100644 index 0000000..773e3a4 --- /dev/null +++ b/CLEAN_ARCHITECTURE.md @@ -0,0 +1,96 @@ +# Clean Architecture - Documentation + +This documentation describes the Clean Architecture structure implemented in the project. + +## Folder structure + +``` +app/ +├── Application/ +│ ├── Actions/ # Application use cases +│ ├── Services/ # Application services +│ ├── Jobs/ # Asynchronous jobs +│ └── Listeners/ # Event listeners +├── Domain/ # Business logic +│ └── Shared/ # Shared classes between domains +└── Infrastructure/ # Implementation details + ├── Http/ + │ ├── Controllers/ + │ │ ├── Api/ # API controllers + │ │ └── Web/ # Web controllers (generation.web_controller_path) + │ ├── Middleware/ # HTTP middleware + │ ├── Requests/ # Form requests + │ └── Resources/ # API resources + ├── Mail/ # Mail classes + ├── Notifications/ # Notifications + ├── Observers/ # Model observers + ├── Exports/ # Excel and CSV exports + ├── Validation/ # Custom validation rules + ├── Console/Commands/ # Console commands (input adapters) + └── Exceptions/ # Custom exceptions +``` + +## Principles + +### 1. Domain Layer + +- Contains business logic +- Does not depend on the Application or Infrastructure layers +- Depends on Eloquent: models generated here extend `App\Domain\Shared\BaseModel`, which extends `Illuminate\Database\Eloquent\Model` +- Includes models, enums, domain events + +### 2. Application Layer + +- Use case orchestration +- Depends only on Domain Layer +- Includes actions and application services + +### 3. Infrastructure Layer + +- Implementation of technical details +- Depends on Application and Domain Layers +- Includes controllers, repositories, external services + +## Available commands + +- `php artisan clean-arch:make-domain {name}` - Create a new domain +- `php artisan clean-arch:make-action {name} {domain}` - Create a new action +- `php artisan clean-arch:make-service {name}` - Create a new service +- `php artisan clean-arch:make-controller {name}` - Create a new controller +- `php artisan clean-arch:make-observer {name} {domain}` - Create a new observer +- `php artisan clean-arch:make-listener {name}` - Create a new listener +- `php artisan clean-arch:make-job {name}` - Create a new job +- `php artisan clean-arch:make-mail {name}` - Create a new mail +- `php artisan clean-arch:make-notification {name}` - Create a new notification +- `php artisan clean-arch:make-export {name}` - Create a new export +- `php artisan clean-arch:make-arch-rules` writes `phparkitect.php`, then `vendor/bin/phparkitect check` validates the architecture + +## Best Practices + +1. **Separation of Concerns**: Each class has a single responsibility +2. **Dependency Inversion**: Depend on abstractions, not concrete implementations +3. **Domain Events**: Use events to communicate between domains +4. **Validation**: Always validate input data +5. **Testing**: Write tests for every layer + +## Examples + +### Creating a new domain + +```bash +php artisan clean-arch:make-domain Product +``` + +### Using an action + +```php +class ProductsController extends Controller +{ + public function store(CreateProductRequest $request): ProductResource + { + $product = $this->createProductAction->execute($request->validated()); + + return new ProductResource($product); + } +} +``` diff --git a/README.md b/README.md new file mode 100644 index 0000000..7ef0d20 --- /dev/null +++ b/README.md @@ -0,0 +1,106 @@ +# Running Club + +Applicazione di esempio per gestire le iscrizioni alle gare di un running club. Laravel 13 con React e Inertia per le pagine pubbliche, Filament per il pannello di amministrazione, Sanctum per l'API di check-in. Il codice segue una struttura a tre layer (`app/Domain`, `app/Application`, `app/Infrastructure`) verificata con phparkitect. + +Il percorso file per file di ogni flusso e le decisioni prese sono in [docs/flow.md](docs/flow.md). + +## Requisiti + +- Docker con Docker Compose (il progetto gira dentro Laravel Sail) +- PHP 8.4 o superiore e Composer sull'host, solo per la prima `composer install` +- Node 24 (dentro il container di Sail) + +## Installazione + +```bash +composer install +cp .env.example .env +vendor/bin/sail up -d +vendor/bin/sail artisan key:generate +vendor/bin/sail npm install +vendor/bin/sail npm run build +``` + +Tutti i comandi PHP, Composer e Node girano dentro Sail. Solo `git` gira sull'host. + +## Seed + +```bash +vendor/bin/sail artisan migrate:fresh --seed +``` + +Il seed crea l'utente admin, le preferenze dei runner (custom fields), i dieci contest di `database/data/contests.csv` e cinque runner già iscritti a un contest. + +## Import dei contest + +```bash +vendor/bin/sail artisan contests:import +vendor/bin/sail artisan contests:import percorso/del/file.csv +``` + +Senza argomento il comando legge `database/data/contests.csv`. La prima riga deve essere l'intestazione `name,date,available_places,registrations_open`. L'import si può ripetere: un contest è identificato da nome e data, quindi una seconda esecuzione aggiorna le righe invece di duplicarle. Una riga non valida annulla tutto l'import. + +## Credenziali admin + +| Email | Password | +| ------------------- | ---------- | +| `admin@example.com` | `password` | + +## URL + +| Pagina | URL | +| ---------------------------------- | ----------------------------------------- | +| Home pubblica con i contest futuri | http://localhost/ | +| Form di iscrizione | http://localhost/contests/{id}/iscrizione | +| Pannello Filament | http://localhost/admin | + +La mail di conferma dell'iscrizione è in coda e il mailer è `log`. Per vederla in `storage/logs/laravel.log` serve un worker: + +```bash +vendor/bin/sail artisan queue:work +``` + +In alternativa `vendor/bin/sail composer run dev` avvia insieme server, coda e Vite. + +## API check-in + +L'endpoint richiede un token Sanctum di un utente admin. Per crearne uno: + +```bash +vendor/bin/sail artisan tinker --execute 'echo App\Domain\Users\Models\User::firstWhere("email", "admin@example.com")->createToken("check-in")->plainTextToken;' +``` + +Poi, con l'id del contest e l'id del runner: + +```bash +curl -X POST http://localhost/api/contests/1/runners/1/check-in \ + -H "Accept: application/json" \ + -H "Authorization: Bearer IL_TUO_TOKEN" +``` + +| Risposta | Significato | +| -------- | ----------------------------------- | +| 200 | check-in registrato | +| 401 | token assente o non valido | +| 403 | l'utente non è admin | +| 404 | il runner non è iscritto al contest | +| 409 | il check-in è già stato fatto | + +## Test e controlli + +```bash +vendor/bin/sail artisan test --compact +vendor/bin/sail bin pint +vendor/bin/sail bin phpstan analyse +vendor/bin/sail npm run types:check +vendor/bin/sail npm run check +``` + +## Regole di architettura (phparkitect) + +```bash +vendor/bin/sail artisan clean-arch:make-arch-rules --force +vendor/bin/sail bin phparkitect check +``` + +Il primo comando rigenera `phparkitect.php` da `config/clean-architecture.php`, il secondo fallisce se una classe viola le regole dei layer o vive fuori da essi. diff --git a/app/Application/Actions/BaseAction.php b/app/Application/Actions/BaseAction.php new file mode 100644 index 0000000..9f6760b --- /dev/null +++ b/app/Application/Actions/BaseAction.php @@ -0,0 +1,36 @@ + $context + */ + protected function log(string $message, array $context = []): void + { + Log::info($message, array_merge([ + 'action' => static::class, + ], $context)); + } + + /** + * Log error during action execution. + * + * @param array $context + */ + protected function logError(string $message, Throwable $exception, array $context = []): void + { + Log::error($message, array_merge([ + 'action' => static::class, + 'exception' => $exception->getMessage(), + 'file' => $exception->getFile(), + 'line' => $exception->getLine(), + ], $context)); + } +} diff --git a/app/Application/Actions/Contests/CheckInRunnerAction.php b/app/Application/Actions/Contests/CheckInRunnerAction.php new file mode 100644 index 0000000..84f5c9a --- /dev/null +++ b/app/Application/Actions/Contests/CheckInRunnerAction.php @@ -0,0 +1,46 @@ +startOfSecond(); + + $updated = $contest->runners() + ->wherePivotNull('checked_in_at') + ->updateExistingPivot($runner->id, ['checked_in_at' => $checkedInAt], touch: false); + + if ($updated === 1) { + $this->log('Runner checked in', [ + 'contest_id' => $contest->id, + 'runner_id' => $runner->id, + ]); + + return $checkedInAt; + } + + if ($contest->runners()->whereKey($runner->id)->exists()) { + throw new RunnerAlreadyCheckedInException; + } + + throw new RunnerNotRegisteredException; + } +} diff --git a/app/Application/Actions/Contests/ImportContestsFromCsvAction.php b/app/Application/Actions/Contests/ImportContestsFromCsvAction.php new file mode 100644 index 0000000..85028c9 --- /dev/null +++ b/app/Application/Actions/Contests/ImportContestsFromCsvAction.php @@ -0,0 +1,124 @@ + */ + private const array COLUMNS = ['name', 'date', 'available_places', 'registrations_open']; + + /** + * Import the contests of a CSV file and return how many rows were read. + * + * The import can be repeated: a contest is identified by name and date, so a second + * run updates the rows instead of duplicating them. One invalid row rolls everything back. + * + * @throws InvalidContestsCsvException + */ + public function execute(string $path): int + { + $rows = $this->read($path); + + DB::transaction(function () use ($rows): void { + foreach ($rows as $row) { + Contest::query()->updateOrCreate( + ['name' => $row['name'], 'date' => $row['date']], + [ + 'available_places' => $row['available_places'], + 'registrations_open' => $row['registrations_open'], + ], + ); + } + }); + + $this->log('Contests imported from CSV', ['path' => $path, 'rows' => count($rows)]); + + return count($rows); + } + + /** + * @return list + */ + private function read(string $path): array + { + $handle = is_file($path) && is_readable($path) ? fopen($path, 'r') : false; + + if ($handle === false) { + throw InvalidContestsCsvException::unreadable($path); + } + + try { + $header = fgetcsv($handle, escape: ''); + + if (! is_array($header) || $this->normalizeHeader($header) !== self::COLUMNS) { + throw InvalidContestsCsvException::missingHeader(self::COLUMNS); + } + + $rows = []; + $line = 1; + + while (($values = fgetcsv($handle, escape: '')) !== false) { + $line++; + + if ($values === [null]) { + continue; + } + + $rows[] = $this->parseRow($values, $line); + } + + return $rows; + } finally { + fclose($handle); + } + } + + /** + * @param array $header + * @return list + */ + private function normalizeHeader(array $header): array + { + return array_map( + fn (?string $column): string => strtolower(trim((string) $column, " \t\n\r\0\x0B\u{FEFF}")), + array_values($header), + ); + } + + /** + * @param array $values + * @return array{name: string, date: string, available_places: int, registrations_open: bool} + */ + private function parseRow(array $values, int $line): array + { + if (count($values) !== count(self::COLUMNS)) { + throw InvalidContestsCsvException::invalidRow($line, 'expected '.count(self::COLUMNS).' columns.'); + } + + $row = array_combine(self::COLUMNS, array_map(fn (?string $value): string => trim((string) $value), $values)); + + $validator = Validator::make($row, [ + 'name' => ['required', 'string', 'max:255'], + 'date' => ['required', 'date_format:Y-m-d'], + 'available_places' => ['required', 'integer', 'min:0'], + 'registrations_open' => ['required', 'in:0,1,true,false'], + ]); + + if ($validator->fails()) { + throw InvalidContestsCsvException::invalidRow($line, $validator->errors()->first()); + } + + return [ + 'name' => $row['name'], + 'date' => $row['date'], + 'available_places' => (int) $row['available_places'], + 'registrations_open' => filter_var($row['registrations_open'], FILTER_VALIDATE_BOOLEAN), + ]; + } +} diff --git a/app/Application/Actions/Contests/ListUpcomingContestsAction.php b/app/Application/Actions/Contests/ListUpcomingContestsAction.php new file mode 100644 index 0000000..b5d8f27 --- /dev/null +++ b/app/Application/Actions/Contests/ListUpcomingContestsAction.php @@ -0,0 +1,26 @@ + + */ + public function execute(): Collection + { + return Contest::query() + ->upcoming(CarbonImmutable::today()) + ->withCount('runners') + ->orderBy('date') + ->orderBy('name') + ->get(); + } +} diff --git a/app/Application/Actions/Contests/RegisterToContestAction.php b/app/Application/Actions/Contests/RegisterToContestAction.php new file mode 100644 index 0000000..3a0e9e1 --- /dev/null +++ b/app/Application/Actions/Contests/RegisterToContestAction.php @@ -0,0 +1,88 @@ +lockForUpdate()->findOrFail($contest->id); + + if ($contest->hasBeenHeld(CarbonImmutable::today())) { + throw new RegistrationRejectedException(RegistrationRejection::ContestAlreadyHeld); + } + + if (! $contest->registrations_open) { + throw new RegistrationRejectedException(RegistrationRejection::RegistrationsClosed); + } + + if ($contest->placesLeft($contest->runners()->count()) === 0) { + throw new RegistrationRejectedException(RegistrationRejection::NoPlacesLeft); + } + + $user = User::query()->where('email', $data->email)->first(); + $runner = $user === null + ? null + : Runner::withTrashed()->where('user_id', $user->id)->first(); + + if ($runner?->trashed()) { + throw new RegistrationRejectedException(RegistrationRejection::RunnerDeleted); + } + + if (! $contest->admitsRunnerBornOn($runner->birth_date ?? $data->birthDate)) { + throw new RegistrationRejectedException(RegistrationRejection::Underage); + } + + if ($runner !== null && $contest->runners()->whereKey($runner->id)->exists()) { + throw new RegistrationRejectedException(RegistrationRejection::AlreadyRegistered); + } + + $user ??= User::query()->create([ + 'name' => $data->fullName(), + 'email' => $data->email, + 'password' => Str::password(32), + ]); + + $runner ??= Runner::query()->create([ + 'user_id' => $user->id, + 'first_name' => $data->firstName, + 'last_name' => $data->lastName, + 'birth_date' => $data->birthDate, + ]); + + $contest->runners()->attach($runner->id, ['registered_at' => CarbonImmutable::now()]); + + $this->log('Runner registered to contest', [ + 'contest_id' => $contest->id, + 'runner_id' => $runner->id, + ]); + + DB::afterCommit(fn () => $this->notifier->registrationConfirmed($runner, $contest)); + + return $runner; + }); + } +} diff --git a/app/Actions/Fortify/CreateNewUser.php b/app/Application/Actions/Fortify/CreateNewUser.php similarity index 79% rename from app/Actions/Fortify/CreateNewUser.php rename to app/Application/Actions/Fortify/CreateNewUser.php index 3c7c00c..4e37877 100644 --- a/app/Actions/Fortify/CreateNewUser.php +++ b/app/Application/Actions/Fortify/CreateNewUser.php @@ -1,10 +1,10 @@ fix($validated['first_name']), + lastName: $nameFixer->fix($validated['last_name']), + birthDate: CarbonImmutable::parse($validated['birth_date'])->startOfDay(), + email: EmailFixer::locale(self::LOCALE)->fix($validated['email']), + ); + } + + /** + * The name stored on the user account. + */ + public function fullName(): string + { + return "{$this->firstName} {$this->lastName}"; + } +} diff --git a/app/Application/Exceptions/InvalidContestsCsvException.php b/app/Application/Exceptions/InvalidContestsCsvException.php new file mode 100644 index 0000000..d4c355b --- /dev/null +++ b/app/Application/Exceptions/InvalidContestsCsvException.php @@ -0,0 +1,26 @@ + $expected + */ + public static function missingHeader(array $expected): self + { + return new self('The first line must be the header with the columns: '.implode(', ', $expected).'.'); + } + + public static function invalidRow(int $line, string $reason): self + { + return new self("Line {$line} is not valid: {$reason}"); + } +} diff --git a/app/Domain/Contests/Enums/RegistrationRejection.php b/app/Domain/Contests/Enums/RegistrationRejection.php new file mode 100644 index 0000000..7175c5d --- /dev/null +++ b/app/Domain/Contests/Enums/RegistrationRejection.php @@ -0,0 +1,13 @@ +value}."); + } +} diff --git a/app/Domain/Contests/Exceptions/RunnerAlreadyCheckedInException.php b/app/Domain/Contests/Exceptions/RunnerAlreadyCheckedInException.php new file mode 100644 index 0000000..b3d5458 --- /dev/null +++ b/app/Domain/Contests/Exceptions/RunnerAlreadyCheckedInException.php @@ -0,0 +1,13 @@ + */ + use HasFactory; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'date' => 'date', + 'available_places' => 'integer', + 'registrations_open' => 'boolean', + ]; + } + + /** + * The runners registered to the contest. + * + * @return BelongsToMany + */ + public function runners(): BelongsToMany + { + return $this->belongsToMany(Runner::class) + ->withPivot(['registered_at', 'checked_in_at']); + } + + /** + * Limit the query to the contests not held yet, the ones of the given day included. + * + * @param Builder<$this> $query + */ + public function scopeUpcoming(Builder $query, CarbonImmutable $today): void + { + $query->whereDate('date', '>=', $today->toDateString()); + } + + /** + * Tell whether the contest took place before the given day. On the day of the race it has not. + */ + public function hasBeenHeld(CarbonImmutable $today): bool + { + return $this->date->startOfDay()->lessThan($today->startOfDay()); + } + + /** + * Places still free, given the number of runners already registered. + */ + public function placesLeft(int $registeredRunners): int + { + return max(0, $this->available_places - $registeredRunners); + } + + /** + * Tell whether a runner born on the given day is of age (18) by the day of the contest, that day included. + */ + public function admitsRunnerBornOn(CarbonImmutable $birthDate): bool + { + return $birthDate->startOfDay()->addYears(18)->lessThanOrEqualTo($this->date->startOfDay()); + } + + /** + * Create a new factory instance for the model. + */ + protected static function newFactory(): ContestFactory + { + return ContestFactory::new(); + } +} diff --git a/app/Domain/Contests/Policies/ContestPolicy.php b/app/Domain/Contests/Policies/ContestPolicy.php new file mode 100644 index 0000000..690cb50 --- /dev/null +++ b/app/Domain/Contests/Policies/ContestPolicy.php @@ -0,0 +1,17 @@ +is_admin; + } +} diff --git a/app/Domain/Runners/Models/Runner.php b/app/Domain/Runners/Models/Runner.php new file mode 100644 index 0000000..ab3ec4a --- /dev/null +++ b/app/Domain/Runners/Models/Runner.php @@ -0,0 +1,78 @@ + */ + use HasFactory; + + use SoftDeletes; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'birth_date' => 'date', + ]; + } + + /** + * The account that owns the runner profile and holds its email address. + * + * @return BelongsTo + */ + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } + + /** + * The contests the runner is registered to. + * + * @return BelongsToMany + */ + public function contests(): BelongsToMany + { + return $this->belongsToMany(Contest::class) + ->withPivot(['registered_at', 'checked_in_at']); + } + + /** + * Create a new factory instance for the model. + */ + protected static function newFactory(): RunnerFactory + { + return RunnerFactory::new(); + } +} diff --git a/app/Domain/Shared/BaseModel.php b/app/Domain/Shared/BaseModel.php new file mode 100644 index 0000000..e89c0fc --- /dev/null +++ b/app/Domain/Shared/BaseModel.php @@ -0,0 +1,53 @@ +> */ + use HasFactory; + + use SoftDeletes; + + /** + * Indicates if the model should be timestamped. + */ + public $timestamps = true; + + /** + * The attributes that should be cast. + */ + protected $casts = [ + 'created_at' => 'datetime', + 'updated_at' => 'datetime', + 'deleted_at' => 'datetime', + ]; + + /** + * The attributes that aren't mass assignable. + */ + protected $guarded = ['id']; + + /** + * Get the route key for the model. + */ + public function getRouteKeyName(): string + { + return 'id'; + } + + /** + * Boot the model. + */ + protected static function boot(): void + { + parent::boot(); + + // Add global scopes or model events here + } +} diff --git a/app/Models/User.php b/app/Domain/Users/Models/User.php similarity index 56% rename from app/Models/User.php rename to app/Domain/Users/Models/User.php index 2ac592b..ed1471a 100644 --- a/app/Models/User.php +++ b/app/Domain/Users/Models/User.php @@ -1,15 +1,20 @@ */ - use HasFactory, Notifiable; + use HasApiTokens, HasFactory, Notifiable; /** * Get the attributes that should be cast. @@ -41,6 +47,33 @@ protected function casts(): array return [ 'email_verified_at' => 'datetime', 'password' => 'hashed', + 'is_admin' => 'boolean', ]; } + + /** + * Only administrators enter the Filament panels. + */ + public function canAccessPanel(Panel $panel): bool + { + return $this->is_admin; + } + + /** + * The runner profile of the user, when there is one. + * + * @return HasOne + */ + public function runner(): HasOne + { + return $this->hasOne(Runner::class); + } + + /** + * Create a new factory instance for the model. + */ + protected static function newFactory(): UserFactory + { + return UserFactory::new(); + } } diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php deleted file mode 100644 index 8677cd5..0000000 --- a/app/Http/Controllers/Controller.php +++ /dev/null @@ -1,8 +0,0 @@ -argument('path') ?? database_path('data/contests.csv'); + + try { + $imported = $importContests->execute($path); + } catch (InvalidContestsCsvException $exception) { + $this->components->error($exception->getMessage()); + + return self::FAILURE; + } + + $this->components->info("Contests imported: {$imported}."); + + return self::SUCCESS; + } +} diff --git a/app/Infrastructure/Filament/Resources/Contests/ContestResource.php b/app/Infrastructure/Filament/Resources/Contests/ContestResource.php new file mode 100644 index 0000000..a948790 --- /dev/null +++ b/app/Infrastructure/Filament/Resources/Contests/ContestResource.php @@ -0,0 +1,47 @@ + ListContests::route('/'), + 'create' => CreateContest::route('/create'), + 'edit' => EditContest::route('/{record}/edit'), + ]; + } +} diff --git a/app/Infrastructure/Filament/Resources/Contests/Pages/CreateContest.php b/app/Infrastructure/Filament/Resources/Contests/Pages/CreateContest.php new file mode 100644 index 0000000..f5ccb8e --- /dev/null +++ b/app/Infrastructure/Filament/Resources/Contests/Pages/CreateContest.php @@ -0,0 +1,11 @@ +components([ + TextInput::make('name') + ->label('Nome') + ->required() + ->maxLength(255) + ->unique( + ignoreRecord: true, + modifyRuleUsing: fn (Unique $rule, Get $get): Unique => $rule->where('date', $get('date')), + ) + ->validationMessages([ + 'unique' => 'Esiste già una gara con questo nome in questa data.', + ]), + DatePicker::make('date') + ->label('Data') + ->required(), + TextInput::make('available_places') + ->label('Posti totali') + ->required() + ->integer() + ->minValue(0), + Toggle::make('registrations_open') + ->label('Iscrizioni aperte') + ->default(true), + ]); + } +} diff --git a/app/Infrastructure/Filament/Resources/Contests/Tables/ContestsTable.php b/app/Infrastructure/Filament/Resources/Contests/Tables/ContestsTable.php new file mode 100644 index 0000000..d1629d6 --- /dev/null +++ b/app/Infrastructure/Filament/Resources/Contests/Tables/ContestsTable.php @@ -0,0 +1,42 @@ +columns([ + TextColumn::make('name') + ->label('Nome') + ->searchable() + ->sortable(), + TextColumn::make('date') + ->label('Data') + ->date('d/m/Y') + ->sortable(), + TextColumn::make('available_places') + ->label('Posti totali') + ->numeric() + ->sortable(), + TextColumn::make('runners_count') + ->label('Iscritti') + ->counts('runners') + ->numeric() + ->sortable(), + IconColumn::make('registrations_open') + ->label('Iscrizioni aperte') + ->boolean(), + ]) + ->defaultSort('date') + ->recordActions([ + EditAction::make(), + ]); + } +} diff --git a/app/Infrastructure/Filament/Resources/Runners/Pages/EditRunner.php b/app/Infrastructure/Filament/Resources/Runners/Pages/EditRunner.php new file mode 100644 index 0000000..11d1cae --- /dev/null +++ b/app/Infrastructure/Filament/Resources/Runners/Pages/EditRunner.php @@ -0,0 +1,76 @@ + $data + * @return array + */ + protected function mutateFormDataBeforeFill(array $data): array + { + $runner = $this->getRecord(); + assert($runner instanceof Runner); + + $data[RunnerForm::CUSTOM_FIELDS] = $runner->getCustomFields(); + + return $data; + } + + /** + * Save the runner and its custom fields. The page transaction rolls the runner back + * when the custom fields cannot be written. + * + * @param array $data + */ + protected function handleRecordUpdate(Model $record, array $data): Model + { + assert($record instanceof Runner); + + /** @var array $customFields */ + $customFields = Arr::pull($data, RunnerForm::CUSTOM_FIELDS, []); + + $record->update($data); + + try { + $record->setCustomFields($customFields, complete: true); + } catch (ValidationException $exception) { + throw ValidationException::withMessages( + Arr::mapWithKeys( + $exception->errors(), + fn (array $messages, string $slug): array => ['data.'.RunnerForm::CUSTOM_FIELDS.'.'.$slug => $messages], + ), + ); + } + + return $record; + } +} diff --git a/app/Infrastructure/Filament/Resources/Runners/Pages/ListRunners.php b/app/Infrastructure/Filament/Resources/Runners/Pages/ListRunners.php new file mode 100644 index 0000000..cf07c5a --- /dev/null +++ b/app/Infrastructure/Filament/Resources/Runners/Pages/ListRunners.php @@ -0,0 +1,11 @@ + ListRunners::route('/'), + 'edit' => EditRunner::route('/{record}/edit'), + ]; + } + + /** + * @return Builder + */ + public static function getRecordRouteBindingEloquentQuery(): Builder + { + return parent::getRecordRouteBindingEloquentQuery() + ->withoutGlobalScopes([ + SoftDeletingScope::class, + ]); + } +} diff --git a/app/Infrastructure/Filament/Resources/Runners/Schemas/RunnerForm.php b/app/Infrastructure/Filament/Resources/Runners/Schemas/RunnerForm.php new file mode 100644 index 0000000..8307e2e --- /dev/null +++ b/app/Infrastructure/Filament/Resources/Runners/Schemas/RunnerForm.php @@ -0,0 +1,109 @@ +components([ + Section::make('Anagrafica') + ->columns(2) + ->columnSpanFull() + ->schema([ + TextInput::make('first_name') + ->label('Nome') + ->required() + ->maxLength(100), + TextInput::make('last_name') + ->label('Cognome') + ->required() + ->maxLength(100), + DatePicker::make('birth_date') + ->label('Data di nascita') + ->required() + ->maxDate(now()), + TextInput::make('email') + ->label('Email') + ->helperText("L'email appartiene all'utente e non si modifica da qui.") + ->formatStateUsing(fn (?Runner $record): ?string => $record?->user->email) + ->disabled() + ->dehydrated(false), + ]), + Section::make('Preferenze') + ->columns(2) + ->columnSpanFull() + ->statePath(self::CUSTOM_FIELDS) + ->schema(fn (): array => self::customFieldComponents()), + ]); + } + + /** + * One component for each active custom field of the runner, named after its slug. + * + * @return list + */ + private static function customFieldComponents(): array + { + $fieldModel = CustomFields::fieldModel(); + + return array_values($fieldModel::query() + ->where('entity_type', CustomFields::entityKey(Runner::class)) + ->where('is_active', true) + ->orderBy('sort_order') + ->orderBy('id') + ->get() + ->map(fn (CustomField $field): Field => self::componentFor( + slug: $field->getAttribute('slug'), + type: $field->getAttribute('type'), + options: collect($field->optionsForInput())->pluck('label', 'key')->all(), + ) + ->label(Str::ucfirst($field->getAttribute('name'))) + ->required($field->getAttribute('is_required') && $field->getAttribute('type') !== 'boolean')) + ->all()); + } + + /** + * The component that fits a custom field type. A boolean is a toggle, which always + * holds an answer, so it is never marked as required. + * + * @param array $options + */ + private static function componentFor(string $slug, string $type, array $options): Field + { + return match ($type) { + 'textarea' => Textarea::make($slug)->columnSpanFull(), + 'number' => TextInput::make($slug)->integer(), + 'decimal' => TextInput::make($slug)->numeric(), + 'boolean' => Toggle::make($slug), + 'date' => DatePicker::make($slug), + 'datetime' => DateTimePicker::make($slug), + 'select' => Select::make($slug)->options($options), + 'multiselect' => Select::make($slug)->options($options)->multiple(), + 'email' => TextInput::make($slug)->email()->maxLength(255), + 'url' => TextInput::make($slug)->url()->maxLength(255), + 'phone' => TextInput::make($slug)->tel()->maxLength(255), + default => TextInput::make($slug)->maxLength(255), + }; + } +} diff --git a/app/Infrastructure/Filament/Resources/Runners/Tables/RunnersTable.php b/app/Infrastructure/Filament/Resources/Runners/Tables/RunnersTable.php new file mode 100644 index 0000000..a0aac90 --- /dev/null +++ b/app/Infrastructure/Filament/Resources/Runners/Tables/RunnersTable.php @@ -0,0 +1,46 @@ +columns([ + TextColumn::make('full_name') + ->label('Nome e cognome') + ->state(fn (Runner $record): string => "{$record->first_name} {$record->last_name}") + ->searchable(query: fn (Builder $query, string $search): Builder => $query->searchFullName($search)) + ->sortable(query: fn (Builder $query, string $direction): Builder => $query->orderByFullName($direction)), + TextColumn::make('user.email') + ->label('Email') + ->searchable(), + TextColumn::make('birth_date') + ->label('Data di nascita') + ->date('d/m/Y') + ->sortable(), + TextColumn::make('contests_count') + ->label('Gare') + ->counts('contests') + ->numeric(), + TextColumn::make('deleted_at') + ->label('Cancellato il') + ->dateTime('d/m/Y H:i') + ->toggleable(isToggledHiddenByDefault: true), + ]) + ->filters([ + TrashedFilter::make(), + ]) + ->recordActions([ + EditAction::make(), + ]); + } +} diff --git a/app/Infrastructure/Http/Controllers/Api/CheckInController.php b/app/Infrastructure/Http/Controllers/Api/CheckInController.php new file mode 100644 index 0000000..c5a0137 --- /dev/null +++ b/app/Infrastructure/Http/Controllers/Api/CheckInController.php @@ -0,0 +1,34 @@ +execute($contest, $runner); + } catch (RunnerNotRegisteredException) { + return $this->errorResponse('The runner is not registered to this contest.', 404); + } catch (RunnerAlreadyCheckedInException) { + return $this->errorResponse('The runner has already checked in.', 409); + } + + return $this->successResponse([ + 'contest_id' => $contest->id, + 'runner_id' => $runner->id, + 'checked_in_at' => $checkedInAt->toIso8601String(), + ], 'Check-in recorded.'); + } +} diff --git a/app/Infrastructure/Http/Controllers/Controller.php b/app/Infrastructure/Http/Controllers/Controller.php new file mode 100644 index 0000000..79a7bef --- /dev/null +++ b/app/Infrastructure/Http/Controllers/Controller.php @@ -0,0 +1,60 @@ +json([ + 'success' => true, + 'data' => $data, + 'message' => $message, + ], $status); + } + + /** + * Return an error JSON response. + */ + protected function errorResponse(string $message = 'Error', int $status = 400, mixed $errors = null): JsonResponse + { + return response()->json([ + 'success' => false, + 'message' => $message, + 'errors' => $errors, + ], $status); + } + + /** + * Return a paginated JSON response. + * + * @param LengthAwarePaginator $data + */ + protected function paginatedResponse(LengthAwarePaginator $data, string $message = 'Success'): JsonResponse + { + return response()->json([ + 'success' => true, + 'data' => $data->items(), + 'pagination' => [ + 'current_page' => $data->currentPage(), + 'last_page' => $data->lastPage(), + 'per_page' => $data->perPage(), + 'total' => $data->total(), + 'from' => $data->firstItem(), + 'to' => $data->lastItem(), + ], + 'message' => $message, + ]); + } +} diff --git a/app/Http/Controllers/Settings/ProfileController.php b/app/Infrastructure/Http/Controllers/Settings/ProfileController.php similarity index 85% rename from app/Http/Controllers/Settings/ProfileController.php rename to app/Infrastructure/Http/Controllers/Settings/ProfileController.php index d19f963..e68790c 100644 --- a/app/Http/Controllers/Settings/ProfileController.php +++ b/app/Infrastructure/Http/Controllers/Settings/ProfileController.php @@ -1,10 +1,10 @@ [ + 'id' => $contest->id, + 'name' => $contest->name, + 'date' => $contest->date->toDateString(), + ], + ]); + } + + /** + * Register the person to the contest. + */ + public function store( + StoreRegistrationRequest $request, + Contest $contest, + RegisterToContestAction $registerToContest, + ): RedirectResponse { + /** @var array{first_name: string, last_name: string, birth_date: string, email: string} $validated */ + $validated = $request->validated(); + + try { + $registerToContest->execute($contest, RegistrationData::fromValidated($validated)); + } catch (RegistrationRejectedException $exception) { + throw ValidationException::withMessages($this->rejectionMessage($exception->reason)); + } + + Inertia::flash('toast', [ + 'type' => 'success', + 'message' => "Iscrizione a {$contest->name} registrata. Riceverai una mail di conferma.", + ]); + + return to_route('home'); + } + + /** + * Map a rejection of the domain to the form key that shows it and its message. + * + * @return array + */ + private function rejectionMessage(RegistrationRejection $reason): array + { + return match ($reason) { + RegistrationRejection::ContestAlreadyHeld => ['contest' => 'Questa gara si è già svolta.'], + RegistrationRejection::RegistrationsClosed => ['contest' => 'Le iscrizioni a questa gara sono chiuse.'], + RegistrationRejection::NoPlacesLeft => ['contest' => 'I posti per questa gara sono esauriti.'], + RegistrationRejection::RunnerDeleted => ['email' => 'Il profilo associato a questa email è stato disattivato. Contatta gli organizzatori.'], + RegistrationRejection::Underage => ['birth_date' => 'Devi avere compiuto 18 anni entro il giorno della gara.'], + RegistrationRejection::AlreadyRegistered => ['email' => 'Questa email è già iscritta alla gara.'], + }; + } +} diff --git a/app/Infrastructure/Http/Controllers/Web/HomeController.php b/app/Infrastructure/Http/Controllers/Web/HomeController.php new file mode 100644 index 0000000..0cb27dd --- /dev/null +++ b/app/Infrastructure/Http/Controllers/Web/HomeController.php @@ -0,0 +1,38 @@ + $listUpcomingContests->execute() + ->map(function (Contest $contest): array { + $placesLeft = $contest->placesLeft((int) $contest->runners_count); + + return [ + 'id' => $contest->id, + 'name' => $contest->name, + 'date' => $contest->date->toDateString(), + 'places_left' => $placesLeft, + 'status' => match (true) { + ! $contest->registrations_open => 'closed', + $placesLeft === 0 => 'sold_out', + default => 'open', + }, + ]; + }) + ->all(), + ]); + } +} diff --git a/app/Http/Middleware/HandleAppearance.php b/app/Infrastructure/Http/Middleware/HandleAppearance.php similarity index 90% rename from app/Http/Middleware/HandleAppearance.php rename to app/Infrastructure/Http/Middleware/HandleAppearance.php index 1a01684..fd616bd 100644 --- a/app/Http/Middleware/HandleAppearance.php +++ b/app/Infrastructure/Http/Middleware/HandleAppearance.php @@ -1,6 +1,6 @@ > + */ + public function rules(): array + { + return [ + 'first_name' => ['required', 'string', 'max:100', 'regex:'.self::NAME_PATTERN], + 'last_name' => ['required', 'string', 'max:100', 'regex:'.self::NAME_PATTERN], + 'birth_date' => ['required', 'date_format:Y-m-d', 'before:today'], + 'email' => ['bail', 'required', 'string', 'max:255', new SanitizedEmail(locale: 'it')], + ]; + } + + /** + * Get the custom messages for validator errors. + * + * @return array + */ + public function messages(): array + { + return [ + 'required' => 'Il campo :attribute è obbligatorio.', + 'string' => 'Il campo :attribute non è valido.', + 'max' => 'Il campo :attribute non può superare :max caratteri.', + 'regex' => 'Il campo :attribute può contenere solo lettere, spazi, apostrofi e trattini.', + 'birth_date.date_format' => 'La data di nascita non è valida.', + 'birth_date.before' => 'La data di nascita deve essere nel passato.', + ]; + } + + /** + * Get custom attributes for validator errors. + * + * @return array + */ + public function attributes(): array + { + return [ + 'first_name' => 'nome', + 'last_name' => 'cognome', + 'birth_date' => 'data di nascita', + 'email' => 'email', + ]; + } +} diff --git a/app/Http/Requests/Settings/PasswordUpdateRequest.php b/app/Infrastructure/Http/Requests/Settings/PasswordUpdateRequest.php similarity index 83% rename from app/Http/Requests/Settings/PasswordUpdateRequest.php rename to app/Infrastructure/Http/Requests/Settings/PasswordUpdateRequest.php index 0e5ff2f..6198398 100644 --- a/app/Http/Requests/Settings/PasswordUpdateRequest.php +++ b/app/Infrastructure/Http/Requests/Settings/PasswordUpdateRequest.php @@ -1,8 +1,8 @@ user->email)->send(new RegistrationConfirmedMail($runner, $contest)); + } +} diff --git a/app/Infrastructure/Mail/RegistrationConfirmedMail.php b/app/Infrastructure/Mail/RegistrationConfirmedMail.php new file mode 100644 index 0000000..97a6242 --- /dev/null +++ b/app/Infrastructure/Mail/RegistrationConfirmedMail.php @@ -0,0 +1,42 @@ +contest->name}", + ); + } + + /** + * Get the message content definition. + */ + public function content(): Content + { + return new Content( + markdown: 'mail.registration-confirmed', + ); + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index f1525e9..aec663d 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,11 +2,17 @@ namespace App\Providers; +use App\Application\Contracts\RegistrationNotifier; +use App\Domain\Runners\Models\Runner; +use App\Domain\Users\Models\User; +use App\Infrastructure\Mail\MailRegistrationNotifier; use Carbon\CarbonImmutable; +use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; use Illuminate\Support\ServiceProvider; use Illuminate\Validation\Rules\Password; +use PlinCode\CustomFields\Facades\CustomFields; class AppServiceProvider extends ServiceProvider { @@ -15,7 +21,7 @@ class AppServiceProvider extends ServiceProvider */ public function register(): void { - // + $this->app->bind(RegistrationNotifier::class, MailRegistrationNotifier::class); } /** @@ -23,6 +29,12 @@ public function register(): void */ public function boot(): void { + Relation::morphMap([ + 'user' => User::class, + ]); + + CustomFields::registerEntity(Runner::class, 'runner', 'Runner'); + $this->configureDefaults(); } diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php new file mode 100644 index 0000000..72946c3 --- /dev/null +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -0,0 +1,59 @@ +default() + ->id('admin') + ->path('admin') + ->login() + ->colors([ + 'primary' => Color::Amber, + ]) + ->discoverResources(in: app_path('Infrastructure/Filament/Resources'), for: 'App\Infrastructure\Filament\Resources') + ->discoverPages(in: app_path('Infrastructure/Filament/Pages'), for: 'App\Infrastructure\Filament\Pages') + ->pages([ + Dashboard::class, + ]) + ->discoverWidgets(in: app_path('Infrastructure/Filament/Widgets'), for: 'App\Infrastructure\Filament\Widgets') + ->widgets([ + AccountWidget::class, + FilamentInfoWidget::class, + ]) + ->middleware([ + EncryptCookies::class, + AddQueuedCookiesToResponse::class, + StartSession::class, + AuthenticateSession::class, + ShareErrorsFromSession::class, + PreventRequestForgery::class, + SubstituteBindings::class, + DisableBladeIconComponents::class, + DispatchServingFilamentEvent::class, + ]) + ->authMiddleware([ + Authenticate::class, + ]); + } +} diff --git a/app/Providers/FortifyServiceProvider.php b/app/Providers/FortifyServiceProvider.php index 873a58b..6eb2e42 100644 --- a/app/Providers/FortifyServiceProvider.php +++ b/app/Providers/FortifyServiceProvider.php @@ -2,8 +2,8 @@ namespace App\Providers; -use App\Actions\Fortify\CreateNewUser; -use App\Actions\Fortify\ResetUserPassword; +use App\Application\Actions\Fortify\CreateNewUser; +use App\Application\Actions\Fortify\ResetUserPassword; use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; diff --git a/boost.json b/boost.json index 779377a..3b402ac 100644 --- a/boost.json +++ b/boost.json @@ -19,7 +19,8 @@ "spatie/laravel-medialibrary", "filament/filament", "spatie/laravel-backup", - "spatie/laravel-query-builder" + "spatie/laravel-query-builder", + "plin-code/laravel-clean-architecture" ], "sail": true, "skills": [ @@ -32,6 +33,7 @@ "inertia-react-development", "tailwindcss-development", "filament-development", + "clean-architecture-development", "custom-fields-development", "activitylog-development", "laravel-backup", diff --git a/bootstrap/app.php b/bootstrap/app.php index ba5cf4c..a7ef1a4 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,7 +1,8 @@ withRouting( web: __DIR__.'/../routes/web.php', + api: __DIR__.'/../routes/api.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) + ->withCommands([ + ImportContestsCommand::class, + ]) ->withMiddleware(function (Middleware $middleware): void { $middleware->encryptCookies(except: ['appearance', 'sidebar_state']); diff --git a/bootstrap/providers.php b/bootstrap/providers.php index 5ffd769..d23c829 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -1,9 +1,11 @@ 'App', + + /* + | Paths of the three layers, relative to the base path. clean-arch:install + | and the make-* commands write the generated classes there, with + | namespaces derived from these paths, and clean-arch:make-arch-rules + | decides what to scan from them. + */ + 'directories' => [ + 'domain' => 'app/Domain', + 'application' => 'app/Application', + 'infrastructure' => 'app/Infrastructure', + ], + + 'validation' => [ + 'custom_messages' => true, + + /* + | Rules written by clean-arch:make-arch-rules into phparkitect.php. Set + | one to false to leave it out of the generated file, then regenerate it + | with --force. 'no_commands_in_infrastructure' is off by default: a + | console command is an input adapter, like an HTTP controller, so it + | lives in Infrastructure and calls an action for the business logic. + | 'no_classes_outside_layers' is off by default too: it reports every + | class of the directory the layers share (app/ with the defaults) + | that is not in a layer, such as the app/Http and app/Models Laravel + | ships with, so turn it on once the app has been moved into the + | layers. + */ + 'rules' => [ + 'domain_no_application_imports' => true, + 'domain_no_infrastructure_imports' => true, + 'application_no_infrastructure_imports' => true, + 'no_observers_in_domain' => true, + 'no_jobs_in_infrastructure' => true, + 'no_commands_in_infrastructure' => false, + 'no_classes_outside_layers' => true, + ], + + /* + | Infrastructure namespaces the application layer may import without + | breaking 'application_no_infrastructure_imports', for side effects + | such as mail and notifications sent straight from an action. Values + | are relative to the infrastructure layer, so ['Mail', 'Notifications'] + | allows App\Infrastructure\Mail and App\Infrastructure\Notifications + | while every other infrastructure import is still reported. Empty by + | default. Regenerate phparkitect.php with --force after changing it. + */ + 'application_infrastructure_allowed' => [], + + /* + | Namespaces that may stay outside the layers without breaking + | 'no_classes_outside_layers', relative to the root namespace, so + | ['Providers'] allows App\Providers. Providers is listed by default + | because bootstrap/providers.php registers the service providers + | there and Laravel's generators write them there. Regenerate + | phparkitect.php with --force after changing it. + */ + 'outside_layers_allowed' => ['Providers'], + ], + + /* + | Options read by clean-arch:make-domain and the individual make-* commands + | when they generate code. + */ + 'generation' => [ + /* + | When true (the default) generated services and actions extend the + | BaseService and BaseAction classes created by clean-arch:install. + | Pass --no-base to the command, or set this to false, to generate + | standalone classes without a base class. + */ + 'extend_base_classes' => true, + + /* + | Subfolder the domain model is generated under, inside each domain's + | directory. Defaults to 'Models', so clean-arch:make-domain writes + | app/Domain/Articles/Models/Article.php declaring + | App\Domain\Articles\Models\Article. Set it to null or an empty + | string to generate the model directly inside the domain directory + | instead, app/Domain/Articles/Article.php declaring + | App\Domain\Articles\Article. Any other single segment, for example + | 'Entities', replaces 'Models'. + */ + 'model_directory' => 'Models', + + /* + | Prefix clean-arch:make-job puts in front of the generated job, both + | in the class name and in the file name. Defaults to 'Process', so + | make-job Article writes ProcessArticleJob.php. Set it to null or an + | empty string to generate ArticleJob.php instead, or to any other + | studly segment, for example 'Handle'. + */ + 'job_prefix' => 'Process', + + /* + | Path clean-arch:make-controller --web writes to, relative to the + | infrastructure layer directory. The generated namespace follows it. + | Defaults to 'Http/Controllers/Web', next to the API controllers, + | which are always generated under Http/Controllers/Api. + */ + 'web_controller_path' => 'Http/Controllers/Web', + ], +]; diff --git a/config/sanctum.php b/config/sanctum.php new file mode 100644 index 0000000..2b5f44e --- /dev/null +++ b/config/sanctum.php @@ -0,0 +1,87 @@ + explode(',', (string) env('SANCTUM_STATEFUL_DOMAINS', sprintf( + '%s%s', + 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1', + Sanctum::currentApplicationUrlWithPort(), + // Sanctum::currentRequestHost(), + ))), + + /* + |-------------------------------------------------------------------------- + | Sanctum Guards + |-------------------------------------------------------------------------- + | + | This array contains the authentication guards that will be checked when + | Sanctum is trying to authenticate a request. If none of these guards + | are able to authenticate the request, Sanctum will use the bearer + | token that's present on an incoming request for authentication. + | + */ + + 'guard' => ['web'], + + /* + |-------------------------------------------------------------------------- + | Expiration Minutes + |-------------------------------------------------------------------------- + | + | This value controls the number of minutes until an issued token will be + | considered expired. This will override any values set in the token's + | "expires_at" attribute, but first-party sessions are not affected. + | + */ + + 'expiration' => null, + + /* + |-------------------------------------------------------------------------- + | Token Prefix + |-------------------------------------------------------------------------- + | + | Sanctum can prefix new tokens in order to take advantage of numerous + | security scanning initiatives maintained by open source platforms + | that notify developers if they commit tokens into repositories. + | + | See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning + | + */ + + 'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''), + + /* + |-------------------------------------------------------------------------- + | Sanctum Middleware + |-------------------------------------------------------------------------- + | + | When authenticating your first-party SPA with Sanctum you may need to + | customize some of the middleware Sanctum uses while processing the + | request. You may change the middleware listed below as required. + | + */ + + 'middleware' => [ + 'authenticate_session' => AuthenticateSession::class, + 'encrypt_cookies' => EncryptCookies::class, + 'validate_csrf_token' => ValidateCsrfToken::class, + ], + +]; diff --git a/database/data/contests.csv b/database/data/contests.csv new file mode 100644 index 0000000..59d79df --- /dev/null +++ b/database/data/contests.csv @@ -0,0 +1,11 @@ +name,date,available_places,registrations_open +Maratona di Primavera,2027-03-21,500,1 +Mezza del Lago,2027-04-11,300,1 +Corsa dei Colli,2027-05-02,150,1 +Dieci Chilometri del Centro,2027-05-23,400,1 +Trail delle Abbazie,2027-06-13,120,0 +Notturna di San Giovanni,2027-06-24,250,1 +Giro delle Mura,2027-09-12,200,1 +Vertical dei Tre Rifugi,2027-07-18,5,1 +Corsa della Vendemmia,2027-10-03,180,1 +Maratonina d'Autunno,2027-11-07,350,0 diff --git a/database/factories/ContestFactory.php b/database/factories/ContestFactory.php new file mode 100644 index 0000000..a88633e --- /dev/null +++ b/database/factories/ContestFactory.php @@ -0,0 +1,44 @@ + + */ +class ContestFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var class-string + */ + protected $model = Contest::class; + + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'name' => fake()->unique()->city().' Run', + 'date' => fake()->dateTimeBetween('+1 month', '+1 year')->format('Y-m-d'), + 'available_places' => fake()->numberBetween(50, 500), + 'registrations_open' => true, + ]; + } + + /** + * Indicate that the contest does not accept registrations. + */ + public function closed(): static + { + return $this->state(fn (array $attributes) => [ + 'registrations_open' => false, + ]); + } +} diff --git a/database/factories/RunnerFactory.php b/database/factories/RunnerFactory.php new file mode 100644 index 0000000..9b6083f --- /dev/null +++ b/database/factories/RunnerFactory.php @@ -0,0 +1,37 @@ + + */ +class RunnerFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var class-string + */ + protected $model = Runner::class; + + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'first_name' => fake()->firstName(), + 'last_name' => fake()->lastName(), + 'birth_date' => fake()->dateTimeBetween('-70 years', '-20 years')->format('Y-m-d'), + 'user_id' => fn (array $attributes) => User::factory()->state([ + 'name' => $attributes['first_name'].' '.$attributes['last_name'], + ]), + ]; + } +} diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index c4ceb07..2ebae8a 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -2,7 +2,7 @@ namespace Database\Factories; -use App\Models\User; +use App\Domain\Users\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; @@ -12,6 +12,13 @@ */ class UserFactory extends Factory { + /** + * The name of the factory's corresponding model. + * + * @var class-string + */ + protected $model = User::class; + /** * The current password being used by the factory. */ @@ -30,9 +37,20 @@ public function definition(): array 'email_verified_at' => now(), 'password' => static::$password ??= Hash::make('password'), 'remember_token' => Str::random(10), + 'is_admin' => false, ]; } + /** + * Indicate that the user is an administrator. + */ + public function admin(): static + { + return $this->state(fn (array $attributes) => [ + 'is_admin' => true, + ]); + } + /** * Indicate that the model's email address should be unverified. */ diff --git a/database/migrations/2026_11_16_141905_add_is_admin_to_users_table.php b/database/migrations/2026_11_16_141905_add_is_admin_to_users_table.php new file mode 100644 index 0000000..519e738 --- /dev/null +++ b/database/migrations/2026_11_16_141905_add_is_admin_to_users_table.php @@ -0,0 +1,28 @@ +boolean('is_admin')->default(false)->after('password'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('users', function (Blueprint $table) { + $table->dropColumn('is_admin'); + }); + } +}; diff --git a/database/migrations/2026_11_16_141906_create_runners_table.php b/database/migrations/2026_11_16_141906_create_runners_table.php new file mode 100644 index 0000000..19f7177 --- /dev/null +++ b/database/migrations/2026_11_16_141906_create_runners_table.php @@ -0,0 +1,32 @@ +id(); + $table->foreignId('user_id')->unique()->constrained()->cascadeOnDelete(); + $table->string('first_name'); + $table->string('last_name'); + $table->date('birth_date'); + $table->timestamps(); + $table->softDeletes(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('runners'); + } +}; diff --git a/database/migrations/2026_11_16_141908_create_contests_table.php b/database/migrations/2026_11_16_141908_create_contests_table.php new file mode 100644 index 0000000..6da5cdb --- /dev/null +++ b/database/migrations/2026_11_16_141908_create_contests_table.php @@ -0,0 +1,33 @@ +id(); + $table->string('name'); + $table->date('date')->index(); + $table->unsignedInteger('available_places'); + $table->boolean('registrations_open')->default(true); + $table->timestamps(); + + $table->unique(['name', 'date']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('contests'); + } +}; diff --git a/database/migrations/2026_11_16_141910_create_contest_runner_table.php b/database/migrations/2026_11_16_141910_create_contest_runner_table.php new file mode 100644 index 0000000..ad78b0b --- /dev/null +++ b/database/migrations/2026_11_16_141910_create_contest_runner_table.php @@ -0,0 +1,32 @@ +id(); + $table->foreignId('contest_id')->constrained()->cascadeOnDelete(); + $table->foreignId('runner_id')->constrained()->cascadeOnDelete(); + $table->timestamp('registered_at'); + $table->timestamp('checked_in_at')->nullable(); + + $table->unique(['contest_id', 'runner_id']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('contest_runner'); + } +}; diff --git a/database/migrations/2026_11_16_142147_create_personal_access_tokens_table.php b/database/migrations/2026_11_16_142147_create_personal_access_tokens_table.php new file mode 100644 index 0000000..40ff706 --- /dev/null +++ b/database/migrations/2026_11_16_142147_create_personal_access_tokens_table.php @@ -0,0 +1,33 @@ +id(); + $table->morphs('tokenable'); + $table->text('name'); + $table->string('token', 64)->unique(); + $table->text('abilities')->nullable(); + $table->timestamp('last_used_at')->nullable(); + $table->timestamp('expires_at')->nullable()->index(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('personal_access_tokens'); + } +}; diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 6b901f8..d280d81 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -2,24 +2,43 @@ namespace Database\Seeders; -use App\Models\User; -use Illuminate\Database\Console\Seeds\WithoutModelEvents; +use App\Application\Actions\Contests\ImportContestsFromCsvAction; +use App\Domain\Contests\Models\Contest; +use App\Domain\Runners\Models\Runner; +use App\Domain\Users\Models\User; +use Carbon\CarbonImmutable; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { - use WithoutModelEvents; - /** * Seed the application's database. + * + * Model events stay on: the slug of a custom field is generated by an observer. */ - public function run(): void + public function run(ImportContestsFromCsvAction $importContests): void { - // User::factory(10)->create(); - - User::factory()->create([ - 'name' => 'Test User', - 'email' => 'test@example.com', + User::factory()->admin()->create([ + 'name' => 'Admin', + 'email' => 'admin@example.com', + 'password' => 'password', ]); + + $this->call(RunnerPreferenceSeeder::class); + + $importContests->execute(database_path('data/contests.csv')); + + $contest = Contest::query() + ->where('registrations_open', true) + ->orderBy('available_places') + ->firstOrFail(); + + Runner::factory(5) + ->create() + ->each(function (Runner $runner) use ($contest): void { + $runner->setCustomFields(['taglia-maglietta' => 'm', 'newsletter' => true]); + + $contest->runners()->attach($runner->id, ['registered_at' => CarbonImmutable::now()]); + }); } } diff --git a/database/seeders/RunnerPreferenceSeeder.php b/database/seeders/RunnerPreferenceSeeder.php new file mode 100644 index 0000000..1133a2a --- /dev/null +++ b/database/seeders/RunnerPreferenceSeeder.php @@ -0,0 +1,46 @@ + 'Taglia maglietta', + 'type' => 'select', + 'options' => [ + ['key' => 's', 'label' => 'S', 'is_active' => true], + ['key' => 'm', 'label' => 'M', 'is_active' => true], + ['key' => 'l', 'label' => 'L', 'is_active' => true], + ['key' => 'xl', 'label' => 'XL', 'is_active' => true], + ], + ], + ['name' => 'Newsletter', 'type' => 'boolean'], + ['name' => 'Contatto di emergenza', 'type' => 'phone'], + ['name' => 'Note per gli organizzatori', 'type' => 'textarea'], + ]; + + foreach ($preferences as $index => $preference) { + $fieldModel::query()->firstOrCreate( + ['entity_type' => $entity, 'name' => mb_strtolower($preference['name'])], + [ + 'type' => $preference['type'], + 'options' => $preference['options'] ?? null, + 'sort_order' => ($index + 1) * 10, + ], + ); + } + } +} diff --git a/docs/flow.md b/docs/flow.md new file mode 100644 index 0000000..c0a35ac --- /dev/null +++ b/docs/flow.md @@ -0,0 +1,118 @@ +# Flussi dell'applicazione + +Il codice vive in tre layer (`app/Domain`, `app/Application`, `app/Infrastructure`). Fuori dai layer resta solo `app/Providers`. Ogni flusso qui sotto è elencato file per file, nell'ordine in cui la richiesta li attraversa. + +## Home pubblica + +`GET /` + +1. `routes/web.php`: la rotta `home` punta a `HomeController`. +2. `app/Infrastructure/Http/Controllers/Web/HomeController.php`: chiama l'action e trasforma ogni contest in un array (`id`, `name`, `date`, `places_left`, `status`). Lo stato vale `open`, `closed` oppure `sold_out`. +3. `app/Application/Actions/Contests/ListUpcomingContestsAction.php`: legge i contest con data da oggi in poi, ordinati per data, con il conteggio dei runner iscritti (`withCount('runners')`, una sola query). +4. `app/Domain/Contests/Models/Contest.php`: lo scope `upcoming()` e il metodo `placesLeft()`. +5. `resources/js/pages/home.tsx`: elenco con i componenti dello starter kit (`Card`, `Badge`, `Button`). Un contest `open` mostra il link al form, gli altri l'etichetta "Iscrizioni chiuse" o "Posti esauriti". +6. `resources/js/lib/dates.ts`: formatta la data in italiano senza spostarla di fuso. + +## Iscrizione a un contest + +`GET /contests/{contest}/iscrizione` e `POST /contests/{contest}/iscrizione` (con `throttle:10,1`) + +1. `routes/web.php`: rotte `contests.registration.create` e `contests.registration.store`. +2. `app/Infrastructure/Http/Controllers/Web/ContestRegistrationController.php`, metodo `create()`: rende `resources/js/pages/contests/registration.tsx` dentro il layout di autenticazione dello starter kit (`resources/js/app.tsx` lo assegna alle pagine `contests/`). +3. `app/Infrastructure/Http/Requests/Contests/StoreRegistrationRequest.php`: valida nome, cognome, data di nascita ed email. I messaggi sono in italiano. +4. `ContestRegistrationController::store()`: passa `$request->validated()` al DTO e il DTO all'action. +5. `app/Application/DTOs/RegistrationData.php`: applica `NameFixer` ed `EmailFixer` con locale `it` e compone il nome per `users.name`. +6. `app/Application/Actions/Contests/RegisterToContestAction.php`: apre una transazione, blocca la riga del contest con `lockForUpdate()`, esegue le guardie nell'ordine richiesto, crea `User` e `Runner` se servono, inserisce la riga in `contest_runner` e programma la notifica con `DB::afterCommit()`. +7. `app/Domain/Contests/Models/Contest.php`: le regole `hasBeenHeld()`, `placesLeft()` e `admitsRunnerBornOn()`. +8. `app/Domain/Contests/Exceptions/RegistrationRejectedException.php` con `app/Domain/Contests/Enums/RegistrationRejection.php`: una guardia fallita lancia l'eccezione con il motivo. +9. `ContestRegistrationController::rejectionMessage()`: traduce il motivo in un errore di validazione in italiano sulla chiave giusta (`contest`, `email` oppure `birth_date`). La pagina mostra la chiave `contest` come avviso sopra il form. +10. `app/Application/Contracts/RegistrationNotifier.php`: l'interfaccia da cui dipende l'action. +11. `app/Infrastructure/Mail/MailRegistrationNotifier.php`: l'implementazione, legata all'interfaccia in `app/Providers/AppServiceProvider.php`. +12. `app/Infrastructure/Mail/RegistrationConfirmedMail.php` e `resources/views/mail/registration-confirmed.blade.php`: la mail Markdown di conferma, messa in coda. + +## API check-in + +`POST /api/contests/{contest}/runners/{runner}/check-in` + +1. `routes/api.php`: middleware `auth:sanctum`, poi `can('checkIn', 'contest')`. +2. `app/Domain/Contests/Policies/ContestPolicy.php`: `checkIn()` passa solo per gli admin. Laravel trova la policy da sola perché sta accanto al modello. +3. `app/Infrastructure/Http/Controllers/Api/CheckInController.php`: chiama l'action e traduce le eccezioni di dominio in risposte JSON. +4. `app/Application/Actions/Contests/CheckInRunnerAction.php`: un solo `UPDATE` condizionato su `checked_in_at IS NULL`. Se non aggiorna nessuna riga, distingue tra runner non iscritto e check-in già fatto. +5. `app/Domain/Contests/Exceptions/RunnerNotRegisteredException.php` e `RunnerAlreadyCheckedInException.php`. + +| Risposta | Quando | +| -------- | ------------------------------------------------------------------- | +| 200 | check-in registrato | +| 401 | token assente o non valido | +| 403 | utente autenticato ma non admin | +| 404 | contest o runner inesistente, oppure runner non iscritto al contest | +| 409 | check-in già fatto | + +## Import CSV + +`php artisan contests:import {path?}` + +1. `bootstrap/app.php`: registra il comando con `withCommands()`, perché Laravel scopre da solo soltanto `app/Console/Commands`. +2. `app/Infrastructure/Console/Commands/ImportContestsCommand.php`: risolve il percorso (default `database/data/contests.csv`), chiama l'action e stampa l'esito. +3. `app/Application/Actions/Contests/ImportContestsFromCsvAction.php`: pretende l'intestazione `name,date,available_places,registrations_open`, valida ogni riga e scrive tutto in una transazione con `updateOrCreate()` su nome e data. +4. `app/Application/Exceptions/InvalidContestsCsvException.php`: file illeggibile, intestazione mancante o riga non valida (con il numero di riga). +5. `database/data/contests.csv`: dieci contest di esempio. +6. `database/seeders/DatabaseSeeder.php`: riusa la stessa action per il seed. + +## Pannello Filament + +1. `app/Providers/Filament/AdminPanelProvider.php`: pannello `admin` su `/admin`, con le risorse scoperte in `app/Infrastructure/Filament/Resources`. +2. `app/Domain/Users/Models/User.php`: `canAccessPanel()` lascia entrare solo chi ha `is_admin`. +3. `app/Infrastructure/Filament/Resources/Contests`: lista, creazione e modifica dei contest. +4. `app/Infrastructure/Filament/Resources/Runners`: lista e modifica dei runner. La tabella cerca e ordina con le macro `searchFullName()` e `orderByFullName()`. La pagina di modifica legge i custom fields con `getCustomFields()` e li salva con `setCustomFields()`. + +## Decisioni + +Scelte fatte davanti a un'ambiguità della specifica. + +**Struttura** + +- `app/Domain/Shared/BaseModel.php` resta anche se nessun modello lo estende. Il file `phparkitect.php` generato da `clean-arch:make-arch-rules` lo importa come controllo che l'autoload funzioni, quindi cancellarlo rompe `phparkitect check` a ogni rigenerazione con `--force`. Le altre classi generate e inutilizzate (`BaseService`, `BaseRequest`, le tre eccezioni in `Infrastructure/Exceptions`) sono state cancellate. +- Le action estendono `BaseAction` e usano il suo `log()` per registrare iscrizioni, check-in e import. +- Un'action esiste dove c'è una regola da proteggere (guardie, transazione, lock, notifica). Il CRUD senza regole scrive con Eloquent dal layer di infrastruttura, cosa che le regole dei layer permettono: i controller `Settings` dello starter kit, la risorsa Filament dei contest e la pagina di modifica del runner. +- La pagina di modifica del runner fa due scritture (il runner e i suoi custom fields) e attiva la transazione di Filament con `$hasDatabaseTransactions`, che di default è spenta. Se la seconda scrittura fallisce, anche la prima viene annullata. +- L'iscrizione non ha un modello proprio. È la pivot `contest_runner` della relazione `belongsToMany` tra `Contest` e `Runner`. +- Le eccezioni delle guardie sono una sola classe (`RegistrationRejectedException`) con un enum per il motivo. La traduzione in messaggio italiano sta nel controller, perché è un dettaglio di presentazione. +- `User` implementa `FilamentUser` nel layer di dominio. È un'interfaccia del vendor, non dell'infrastruttura dell'app, e le regole dei layer restano verdi. +- `InvalidContestsCsvException` sta in `app/Application/Exceptions` perché riguarda il formato del file, non una regola di dominio. +- `config/sanctum.php` ha un cast a stringa su `env('SANCTUM_STATEFUL_DOMAINS')`, necessario per passare PHPStan senza ignore né baseline. + +**Iscrizione** + +- I posti rimasti sono `available_places` meno i runner iscritti non cancellati. Un runner con soft delete libera il posto ma la sua riga in `contest_runner` resta. +- La riga del contest è bloccata per tutta la transazione, così due iscrizioni concorrenti non superano la capienza. Due iscrizioni concorrenti con la stessa email nuova su due contest diversi possono invece scontrarsi sull'indice unico di `users.email`: la seconda fallisce con un errore e va ripetuta. +- La maggiore età si calcola con `birth_date + 18 anni <= data del contest`. Chi è nato il 29 febbraio compie gli anni il primo marzo negli anni non bisestili. +- Un utente nuovo viene creato senza email verificata e non riceve la mail di verifica di Fortify. Per accedere deve usare il recupero password. +- Il campo email del form è `type="text"` con `inputMode="email"`. Con `type="email"` il browser bloccherebbe proprio gli indirizzi malformati che `SanitizedEmail` sa riparare. +- Senza `rejectGarbage` il pacchetto ripara anche input improbabili (per esempio `not an email` diventa `notan@email.it`). È la conseguenza della scelta richiesta. +- Il messaggio di errore di `SanitizedEmail` è in inglese perché è scritto nel pacchetto. Gli altri messaggi del form sono in italiano. +- Il controllo sui nomi usa una regex nel FormRequest invece di `ValidName` del pacchetto, perché deve accettare anche l'apostrofo tipografico e il punto o la virgola finali, che poi `NameFixer` toglie. +- La mail di conferma è in coda (`ShouldQueue`). Con `QUEUE_CONNECTION=database` serve un worker attivo per vederla nel log. +- Dopo l'iscrizione l'utente torna alla home con un toast di conferma. +- Il form pubblico non verifica che chi scrive sia il proprietario dell'email. È il comportamento richiesto dalla specifica ed è accettato per la demo, ma non va in produzione così. Chi conosce l'email di un runner può iscriverlo a un contest al posto suo. Chi usa l'email di un utente senza Runner (per esempio l'admin) crea il profilo Runner con nome e data di nascita a sua scelta. I messaggi "già iscritta" e "profilo disattivato" rivelano quali email esistono, e il `throttle:10,1` rallenta soltanto. Nessun dato esistente viene sovrascritto e nessun account diventa accessibile. Per la produzione servono un'iscrizione in attesa fino al clic su un link firmato inviato per mail e una risposta unica che non riveli se l'email esiste. + +**Check-in** + +- La policy viene applicata dopo il binding dei modelli. Un utente non admin che chiede un contest inesistente riceve 404 e non 403. +- Un runner con soft delete non è risolto dal binding, quindi il check-in risponde 404. +- Le risposte usano gli helper `successResponse()` ed `errorResponse()` del controller base generato dal pacchetto. + +**Pannello** + +- Il Runner ha le azioni di cancellazione (soft delete) e ripristino nella pagina di modifica, più il filtro sui cancellati in lista. Senza di esse la guardia "runner non cancellato" non sarebbe raggiungibile dall'interfaccia. Non c'è cancellazione definitiva. +- Il Contest non ha azioni di cancellazione: la specifica chiede lista, creazione e modifica, e cancellare un contest eliminerebbe a cascata le iscrizioni. +- L'email del runner è mostrata in sola lettura, perché vive su `users`. +- Modificare nome o cognome di un runner dal pannello non aggiorna `users.name`. +- Un custom field booleano è un toggle, che ha sempre un valore: al salvataggio viene scritto `false` anche se prima non c'era risposta. +- I testi propri di Filament (pulsanti, paginazione) restano in inglese perché `APP_LOCALE` resta `en`. Sono in italiano le etichette di risorse, campi e colonne. + +**Dati di esempio** + +- Le preferenze dei runner sono quattro custom fields: taglia maglietta (select), newsletter (boolean), contatto di emergenza (phone), note per gli organizzatori (textarea). +- I cinque runner del seed sono iscritti al contest aperto con meno posti (cinque), così la home mostra subito un caso "Posti esauriti". +- Le date del CSV sono fisse nel 2027. Quando saranno passate il file andrà aggiornato. diff --git a/docs/prompt-runner-app-sample.md b/docs/prompt-runner-app-sample.md new file mode 100644 index 0000000..faf4c93 --- /dev/null +++ b/docs/prompt-runner-app-sample.md @@ -0,0 +1,100 @@ +Lavora in questo progetto Laravel (frontend React + Inertia, Fortify già presenti). + +## Branch + +Crea il branch `runner-app-sample` partendo da `main` e lavora lì. Sei autorizzato a farlo. + +## Ambiente + +- Se il progetto usa Sail, tutti i comandi PHP, Composer, Node e DB girano dentro Sail (`./vendor/bin/sail ...`) e solo `git` gira sull'host. Se i container sono fermi avviali con `sail up -d`. Senza Sail usa i comandi normali (`php artisan`, `composer`, `npm`). +- Prima della build lancia `npm install` nello stesso ambiente. Se `package-lock.json` cambia solo nel campo `name`, ripristinalo. +- Non modificare `DB_*`, `REDIS_*`, `APP_URL` nel `.env`, né `compose.yaml`. Imposta `MAIL_MAILER=log` in `.env` e `.env.example`. +- Se un comando fallisce per un problema di container, fermati e segnalalo. + +## Setup + +1. Installa il pacchetto e phparkitect: + + ```bash + composer require "plin-code/laravel-clean-architecture:^3.8.1" + composer require --dev phparkitect/phparkitect + ``` + +2. Attiva la skill Boost del pacchetto, `clean-architecture-development`. Boost non la aggiunge da solo senza interazione: aggiungi `plin-code/laravel-clean-architecture` a `packages` in `boost.json`, poi lancia `boost:update`. **Segui quella skill per tutto ciò che qui non è scritto: dove va ogni classe, transazioni, comandi, regole phparkitect.** +3. Lancia `php artisan clean-arch:install --migrate-app` e `composer dump-autoload`, poi attiva `validation.rules.no_classes_outside_layers` in `config/clean-architecture.php`. +4. La suite esistente deve essere verde prima di aggiungere funzionalità. Fai un commit qui. + +## Struttura + +Tutto il codice dell'applicazione vive in `app/Domain`, `app/Application`, `app/Infrastructure`. Fuori dai layer resta solo `app/Providers`. + +- Sei autorizzato a spostare e cancellare codice esistente: le regole "non toccare codice non correlato" e "chiedi prima di cancellare" qui non valgono. +- Un modello creato con `make:class` dichiara `newFactory()` (come fa `User` dopo la migrazione), perché Laravel non indovina la factory da un modello dentro `App\Domain`. +- I modelli estendono `Model` di Eloquent, non `BaseModel` (che impone soft delete e `$guarded` a tutti). A fine lavoro cancella le classi generate che nessuno usa e le cartelle vuote. + +## Dominio + +- `User` con `is_admin` boolean (non mass assignable, `false` di default nella factory). +- `Runner`: nome, cognome, data di nascita, soft delete, 1:1 con `User` tramite `user_id` unico. L'email vive solo su `users`. Preferenze con `plin-code/laravel-custom-fields`. +- `Contest`: nome, data, `available_places` (capienza totale), `registrations_open`. +- Iscrizione: pivot `contest_runner` con `registered_at` e `checked_in_at` nullable, unica per contest e runner. + +## Dati di esempio + +- Factory per User, Runner, Contest. +- `database/data/contests.csv`: dieci contest finti, date future, almeno uno chiuso. +- Comando `contests:import {path?}` → `ImportContestsFromCsvAction`. Ripetibile (chiave nome e data), intestazione obbligatoria. +- `DatabaseSeeder`: admin `admin@example.com` / `password`, preferenze dei runner, contest dal CSV, cinque runner già iscritti. Senza `WithoutModelEvents` (lo slug dei custom fields nasce da un observer). + +## Home pubblica + +`/` sostituisce la `welcome`: elenco dei contest futuri per data (nome, data, posti rimasti). Quelli aperti e con posti hanno il link al form di iscrizione, gli altri l'etichetta del motivo. Controller → `ListUpcomingContestsAction`. Componenti dello starter kit. + +## Iscrizione a un contest + +- Pagina pubblica `/contests/{contest}/iscrizione`: nome, cognome, data di nascita, email, link alla home. POST con `throttle:10,1`. +- FormRequest → Controller → DTO `RegistrationData` → `RegisterToContestAction`. +- Pacchetti `plin-code` già installati (leggi i README in `vendor/` e usa le API reali): + - `laravel-name-fixer` e `laravel-email-fixer` con locale `it`, applicati nel DTO, che compone anche il nome per `users.name` + - `laravel-full-name` serve solo a cercare e ordinare: nella tabella Filament dei runner usa le macro di `Builder` `searchFullName()` e `orderByFullName()` +- FormRequest: + - nome e cognome: solo lettere, spazi, apostrofi (anche `’`), trattini, più un punto o una virgola finale (finiscono in una mail Markdown) + - email: `SanitizedEmail(locale: 'it')`, senza `rejectGarbage` +- Guardie, in ordine: contest non ancora svolto (il giorno della gara vale ancora), iscrizioni aperte, posti disponibili, runner non cancellato, maggiorenne (18 anni compiuti entro la data del contest, compresa), non già iscritto. +- Email già nota: riusa User e Runner senza sovrascriverli e valuta l'età sulla data di nascita salvata. Un runner con soft delete non viene ripristinato. Email nota senza Runner (per esempio l'admin): crea solo il Runner. +- User nuovo: password `Str::password(32)`. +- Mail di conferma dopo il commit: l'action dipende da un'interfaccia `RegistrationNotifier` in `app/Application/Contracts`, implementata in `app/Infrastructure/Mail` e legata in un service provider. `validation.application_infrastructure_allowed` resta vuota. +- Le guardie diventano errori di validazione in italiano: minorenne su `birth_date`, già iscritto e runner cancellato su `email`, contest già svolto, iscrizioni chiuse e posti esauriti sulla chiave `contest`, mostrata come avviso sopra il form. + +## Pannello Filament + +- La dipendenza Filament è già installata, non cambiare versione. Il pannello non esiste ancora: crealo con `make:filament-panel admin`, su `/admin`, accesso solo con `is_admin`. +- Etichette di risorse, campi e colonne in italiano; `APP_LOCALE` resta `en`. +- Resource Contest (lista, crea, modifica) e Runner (lista, modifica). +- Edit del Runner: un campo per ogni custom field attivo, con `getCustomFields()` e `setCustomFields()`. Il pacchetto salva i nomi in minuscolo: `Str::ucfirst` sulle etichette. + +## API check-in + +- Sanctum con `php artisan install:api`. Il comando lancia le migration: se fallisce perché le tabelle esistono già, fai prima `migrate:fresh`. +- `POST /api/contests/{contest}/runners/{runner}/check-in`, `auth:sanctum`, solo admin (Policy). +- `CheckInRunnerAction` con update atomico. Risposte: 200, 401, 403, 404 se il runner non è iscritto, 409 se il check-in è già stato fatto. + +## Documentazione + +- `docs/flow.md`: percorso file per file di home, iscrizione, check-in, import CSV, più la sezione "Decisioni". +- `README.md`: requisiti, installazione, seed, import, credenziali admin, URL, `curl` del check-in con token, comandi di test e phparkitect. + +## Chiusura (tutto verde) + +1. `clean-arch:make-arch-rules --force` e `phparkitect check`; `ls app` mostra solo i tre layer e `Providers` +2. `pint`, `phpstan analyse` (niente ignore né baseline) +3. Test Pest: home, iscrizione riuscita, un test per ogni guardia e per ogni caso di email già nota, nomi con Markdown o link, normalizzazione, import CSV, ogni risposta del check-in, accesso al pannello +4. `npm run build`, `npm run types:check`, `npm run check` +5. `migrate:fresh --seed` +6. Commit piccoli su `runner-app-sample`. Niente push. + +## Regole di esecuzione + +- Non fare domande e non chiudere con offerte. Davanti a un'ambiguità scegli l'opzione più coerente con la struttura, non la più semplice, e annotala in "Decisioni". +- Se un vincolo non è realizzabile, fermati e spiega perché invece di aggirarlo. +- Il riepilogo finale riporta l'output dei controlli e ciò che NON è stato fatto. diff --git a/phparkitect.php b/phparkitect.php new file mode 100644 index 0000000..5cd37e1 --- /dev/null +++ b/phparkitect.php @@ -0,0 +1,70 @@ +that(new ResideInOneOfTheseNamespaces('App\\Domain')) + ->should(new NotDependsOnTheseNamespaces(['App\\Application'])) + ->because('the domain layer must not depend on the application layer'); + + $rules[] = Rule::allClasses() + ->that(new ResideInOneOfTheseNamespaces('App\\Domain')) + ->should(new NotDependsOnTheseNamespaces(['App\\Infrastructure'])) + ->because('the domain layer must not depend on the infrastructure layer'); + + $rules[] = Rule::allClasses() + ->that(new ResideInOneOfTheseNamespaces('App\\Application')) + ->should(new NotDependsOnTheseNamespaces(['App\\Infrastructure'])) + ->because('the application layer must not depend on the infrastructure layer'); + + $rules[] = Rule::allClasses() + ->that(new ResideInOneOfTheseNamespaces('App\\Domain')) + ->should(new NotHaveNameMatching('*Observer')) + ->because('observers react to framework events and belong to the infrastructure layer'); + + $rules[] = Rule::allClasses() + ->that(new ResideInOneOfTheseNamespaces('App\\Infrastructure')) + ->andThat(new IsNotA('Illuminate\\Mail\\Mailable')) + ->andThat(new IsNotA('Illuminate\\Notifications\\Notification')) + ->should(new IsNotA('Illuminate\\Contracts\\Queue\\ShouldQueue')) + ->because('queued jobs orchestrate use cases and belong to the application layer'); + + $rules[] = Rule::allClasses() + ->that(new ResideInOneOfTheseNamespaces('App')) + ->should(new ResideInOneOfTheseNamespaces('App\\Domain', 'App\\Application', 'App\\Infrastructure', 'App\\Providers')) + ->because('every class of the application belongs to one of the three layers'); + + $config->add(ClassSet::fromDir(__DIR__.'/app'), ...$rules); +}; diff --git a/resources/js/app.tsx b/resources/js/app.tsx index 5fb8ca2..a6ae086 100644 --- a/resources/js/app.tsx +++ b/resources/js/app.tsx @@ -12,9 +12,10 @@ void createInertiaApp({ title: (title) => (title ? `${title} - ${appName}` : appName), layout: (name) => { switch (true) { - case name === 'welcome': + case name === 'home': return null; case name.startsWith('auth/'): + case name.startsWith('contests/'): return AuthLayout; case name.startsWith('settings/'): return [AppLayout, SettingsLayout]; diff --git a/resources/js/components/delete-user.tsx b/resources/js/components/delete-user.tsx index 213e76f..3ca3137 100644 --- a/resources/js/components/delete-user.tsx +++ b/resources/js/components/delete-user.tsx @@ -1,6 +1,6 @@ import { Form } from '@inertiajs/react'; import { useRef } from 'react'; -import ProfileController from '@/actions/App/Http/Controllers/Settings/ProfileController'; +import ProfileController from '@/actions/App/Infrastructure/Http/Controllers/Settings/ProfileController'; import Heading from '@/components/heading'; import InputError from '@/components/input-error'; import PasswordInput from '@/components/password-input'; diff --git a/resources/js/lib/dates.ts b/resources/js/lib/dates.ts new file mode 100644 index 0000000..befcb24 --- /dev/null +++ b/resources/js/lib/dates.ts @@ -0,0 +1,12 @@ +const italianDate = new Intl.DateTimeFormat('it-IT', { + day: 'numeric', + month: 'long', + year: 'numeric', +}); + +/** Format a `YYYY-MM-DD` date for Italian readers without shifting it across time zones. */ +export function formatDate(date: string): string { + const [year, month, day] = date.split('-').map(Number); + + return italianDate.format(new Date(year, month - 1, day)); +} diff --git a/resources/js/pages/contests/registration.tsx b/resources/js/pages/contests/registration.tsx new file mode 100644 index 0000000..85cc04a --- /dev/null +++ b/resources/js/pages/contests/registration.tsx @@ -0,0 +1,117 @@ +import { Form, Head } from '@inertiajs/react'; +import AlertError from '@/components/alert-error'; +import InputError from '@/components/input-error'; +import TextLink from '@/components/text-link'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Spinner } from '@/components/ui/spinner'; +import { formatDate } from '@/lib/dates'; +import { home } from '@/routes'; +import { store } from '@/routes/contests/registration'; +import type { ContestHeading } from '@/types'; + +type Props = { + contest: ContestHeading; +}; + +export default function Registration({ contest }: Props) { + return ( + <> + + +
+ {({ processing, errors }) => ( + <> +
+

{contest.name}

+

+ {formatDate(contest.date)} +

+
+ + {errors.contest && ( + + )} + +
+
+ + + +
+ +
+ + + +
+ +
+ + + +
+ +
+ + + +
+ + +
+ +
+ + Torna all'elenco delle gare + +
+ + )} + + + ); +} + +Registration.layout = { + title: 'Iscrizione alla gara', + description: 'Inserisci i tuoi dati per iscriverti', +}; diff --git a/resources/js/pages/home.tsx b/resources/js/pages/home.tsx new file mode 100644 index 0000000..dc5d105 --- /dev/null +++ b/resources/js/pages/home.tsx @@ -0,0 +1,94 @@ +import { Head, Link } from '@inertiajs/react'; +import { Badge } from '@/components/ui/badge'; +import { Button } from '@/components/ui/button'; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from '@/components/ui/card'; +import { formatDate } from '@/lib/dates'; +import { create } from '@/routes/contests/registration'; +import type { ContestStatus, ContestSummary } from '@/types'; + +type Props = { + contests: ContestSummary[]; +}; + +const unavailableLabels: Record, string> = { + closed: 'Iscrizioni chiuse', + sold_out: 'Posti esauriti', +}; + +export default function Home({ contests }: Props) { + return ( + <> + + +
+
+
+

+ Prossime gare +

+

+ Scegli una gara e iscriviti. +

+
+ + {contests.length === 0 ? ( +

+ Nessuna gara in programma. +

+ ) : ( +
    + {contests.map((contest) => ( +
  • + + + + {contest.name} + + + {formatDate(contest.date)} + + + + + Posti rimasti:{' '} + + {contest.places_left} + + + + {contest.status === 'open' ? ( + + ) : ( + + { + unavailableLabels[ + contest.status + ] + } + + )} + + +
  • + ))} +
+ )} +
+
+ + ); +} diff --git a/resources/js/pages/settings/profile.tsx b/resources/js/pages/settings/profile.tsx index 031fe32..6f55c91 100644 --- a/resources/js/pages/settings/profile.tsx +++ b/resources/js/pages/settings/profile.tsx @@ -1,6 +1,6 @@ import { Form, Head, usePage } from '@inertiajs/react'; import { Link } from '@inertiajs/react'; -import ProfileController from '@/actions/App/Http/Controllers/Settings/ProfileController'; +import ProfileController from '@/actions/App/Infrastructure/Http/Controllers/Settings/ProfileController'; import DeleteUser from '@/components/delete-user'; import Heading from '@/components/heading'; import InputError from '@/components/input-error'; diff --git a/resources/js/pages/settings/security.tsx b/resources/js/pages/settings/security.tsx index c1e8ae0..8a9a198 100644 --- a/resources/js/pages/settings/security.tsx +++ b/resources/js/pages/settings/security.tsx @@ -1,6 +1,6 @@ import { Form, Head } from '@inertiajs/react'; import { useRef } from 'react'; -import SecurityController from '@/actions/App/Http/Controllers/Settings/SecurityController'; +import SecurityController from '@/actions/App/Infrastructure/Http/Controllers/Settings/SecurityController'; import Heading from '@/components/heading'; import InputError from '@/components/input-error'; import PasswordInput from '@/components/password-input'; diff --git a/resources/js/pages/welcome.tsx b/resources/js/pages/welcome.tsx deleted file mode 100644 index fd91ee3..0000000 --- a/resources/js/pages/welcome.tsx +++ /dev/null @@ -1,389 +0,0 @@ -import { Head, Link, usePage } from '@inertiajs/react'; -import { dashboard, login } from '@/routes'; -import { register } from '@/routes'; - -export default function Welcome() { - const { auth } = usePage().props; - - return ( - <> - -
-
- -
-
-
-
-

- Let's get started -

-

- Laravel has an incredibly rich ecosystem. -
- We suggest starting with the following. -

- - -
-
- {/* Laravel Logo */} - - - - - - - - - - - {/* 13 */} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
-
-
-
- - ); -} diff --git a/resources/js/types/contests.ts b/resources/js/types/contests.ts new file mode 100644 index 0000000..7d3d0b7 --- /dev/null +++ b/resources/js/types/contests.ts @@ -0,0 +1,11 @@ +export type ContestStatus = 'open' | 'closed' | 'sold_out'; + +export type ContestSummary = { + id: number; + name: string; + date: string; + places_left: number; + status: ContestStatus; +}; + +export type ContestHeading = Pick; diff --git a/resources/js/types/index.ts b/resources/js/types/index.ts index b1f0ee6..5926b68 100644 --- a/resources/js/types/index.ts +++ b/resources/js/types/index.ts @@ -1,3 +1,4 @@ export type * from './auth'; export type * from './navigation'; export type * from './ui'; +export type * from './contests'; diff --git a/resources/views/mail/registration-confirmed.blade.php b/resources/views/mail/registration-confirmed.blade.php new file mode 100644 index 0000000..c2b760d --- /dev/null +++ b/resources/views/mail/registration-confirmed.blade.php @@ -0,0 +1,12 @@ + +# Iscrizione confermata + +Ciao {{ $runner->first_name }} {{ $runner->last_name }}, + +la tua iscrizione a **{{ $contest->name }}** del {{ $contest->date->format('d/m/Y') }} è confermata. + +Presentati al check-in il giorno della gara con un documento di identità. + +A presto,
+{{ config('app.name') }} +
diff --git a/routes/api.php b/routes/api.php new file mode 100644 index 0000000..a8ae24d --- /dev/null +++ b/routes/api.php @@ -0,0 +1,9 @@ +middleware('auth:sanctum') + ->can('checkIn', 'contest') + ->name('api.contests.runners.check-in'); diff --git a/routes/settings.php b/routes/settings.php index 2cbf7ba..edef7fe 100644 --- a/routes/settings.php +++ b/routes/settings.php @@ -1,7 +1,7 @@ name('home'); +Route::get('/', HomeController::class)->name('home'); + +Route::get('contests/{contest}/iscrizione', [ContestRegistrationController::class, 'create']) + ->name('contests.registration.create'); +Route::post('contests/{contest}/iscrizione', [ContestRegistrationController::class, 'store']) + ->middleware('throttle:10,1') + ->name('contests.registration.store'); Route::middleware(['auth', 'verified'])->group(function () { Route::inertia('dashboard', 'dashboard')->name('dashboard'); diff --git a/tests/Feature/Admin/PanelTest.php b/tests/Feature/Admin/PanelTest.php new file mode 100644 index 0000000..003ddc2 --- /dev/null +++ b/tests/Feature/Admin/PanelTest.php @@ -0,0 +1,92 @@ +get('/admin')->assertRedirect('/admin/login'); +}); + +test('users who are not administrators are forbidden from the panel', function () { + $this->actingAs(User::factory()->create()) + ->get('/admin') + ->assertForbidden(); +}); + +test('administrators can open the panel and its resources', function (string $path) { + $this->actingAs(User::factory()->admin()->create()) + ->get($path) + ->assertOk(); +})->with(['/admin', '/admin/contests', '/admin/contests/create', '/admin/runners']); + +test('runners table is searched by full name in either order', function () { + $this->actingAs(User::factory()->admin()->create()); + $mario = Runner::factory()->create(['first_name' => 'Mario', 'last_name' => 'Rossi']); + $anna = Runner::factory()->create(['first_name' => 'Anna', 'last_name' => 'Bianchi']); + + Livewire::test(ListRunners::class) + ->searchTable('rossi mario') + ->assertCanSeeTableRecords([$mario]) + ->assertCanNotSeeTableRecords([$anna]); +}); + +test('runners table is sorted by full name', function () { + $this->actingAs(User::factory()->admin()->create()); + $mario = Runner::factory()->create(['first_name' => 'Mario', 'last_name' => 'Rossi']); + $anna = Runner::factory()->create(['first_name' => 'Anna', 'last_name' => 'Bianchi']); + + Livewire::test(ListRunners::class) + ->sortTable('full_name') + ->assertCanSeeTableRecords([$anna, $mario], inOrder: true) + ->sortTable('full_name', 'desc') + ->assertCanSeeTableRecords([$mario, $anna], inOrder: true); +}); + +test('editing a runner shows and saves its custom fields', function () { + $this->seed(RunnerPreferenceSeeder::class); + $this->actingAs(User::factory()->admin()->create()); + $runner = Runner::factory()->create(['first_name' => 'Mario']); + $runner->setCustomFields(['taglia-maglietta' => 'm']); + + Livewire::test(EditRunner::class, ['record' => $runner->id]) + ->assertSchemaStateSet([ + 'first_name' => 'Mario', + 'custom_fields.taglia-maglietta' => 'm', + ]) + ->fillForm([ + 'first_name' => 'Marco', + 'custom_fields.taglia-maglietta' => 'xl', + 'custom_fields.newsletter' => true, + 'custom_fields.contatto-di-emergenza' => '+39 333 1234567', + ]) + ->call('save') + ->assertHasNoFormErrors(); + + $runner->refresh(); + + expect($runner->first_name)->toBe('Marco') + ->and($runner->getCustomField('taglia-maglietta'))->toBe('xl') + ->and($runner->getCustomField('newsletter'))->toBeTrue() + ->and($runner->getCustomField('contatto-di-emergenza'))->toBe('+39 333 1234567'); +}); + +test('a failed custom field write rolls the runner back', function () { + $this->seed(RunnerPreferenceSeeder::class); + $this->actingAs(User::factory()->admin()->create()); + $runner = Runner::factory()->create(['first_name' => 'Mario']); + CustomFields::valueModel()::saving(fn () => throw new RuntimeException('write failed')); + + expect(fn () => Livewire::test(EditRunner::class, ['record' => $runner->id]) + ->fillForm([ + 'first_name' => 'Marco', + 'custom_fields.contatto-di-emergenza' => '+39 333 1234567', + ]) + ->call('save'))->toThrow(RuntimeException::class, 'write failed'); + + expect($runner->refresh()->first_name)->toBe('Mario'); +}); diff --git a/tests/Feature/Api/CheckInTest.php b/tests/Feature/Api/CheckInTest.php new file mode 100644 index 0000000..f670ca7 --- /dev/null +++ b/tests/Feature/Api/CheckInTest.php @@ -0,0 +1,75 @@ +travelTo('2027-05-02 08:30:00'); + + $this->contest = Contest::factory()->create(['date' => '2027-05-02']); + $this->runner = Runner::factory()->create(); +}); + +test('check-in returns 200 and stores the time for a registered runner', function () { + $this->contest->runners()->attach($this->runner, ['registered_at' => now()->subMonth()]); + Sanctum::actingAs(User::factory()->admin()->create()); + + $this->postJson(route('api.contests.runners.check-in', [$this->contest, $this->runner])) + ->assertOk() + ->assertJsonPath('data.contest_id', $this->contest->id) + ->assertJsonPath('data.runner_id', $this->runner->id) + ->assertJsonPath('data.checked_in_at', now()->toIso8601String()); + + $this->assertDatabaseHas('contest_runner', [ + 'contest_id' => $this->contest->id, + 'runner_id' => $this->runner->id, + 'checked_in_at' => '2027-05-02 08:30:00', + ]); +}); + +test('check-in returns 401 without a token', function () { + $this->contest->runners()->attach($this->runner, ['registered_at' => now()]); + + $this->postJson(route('api.contests.runners.check-in', [$this->contest, $this->runner])) + ->assertUnauthorized(); + + $this->assertDatabaseHas('contest_runner', ['runner_id' => $this->runner->id, 'checked_in_at' => null]); +}); + +test('check-in returns 403 for a user who is not an administrator', function () { + $this->contest->runners()->attach($this->runner, ['registered_at' => now()]); + Sanctum::actingAs(User::factory()->create()); + + $this->postJson(route('api.contests.runners.check-in', [$this->contest, $this->runner])) + ->assertForbidden(); + + $this->assertDatabaseHas('contest_runner', ['runner_id' => $this->runner->id, 'checked_in_at' => null]); +}); + +test('check-in returns 404 when the runner is not registered to the contest', function () { + Contest::factory()->create()->runners()->attach($this->runner, ['registered_at' => now()]); + Sanctum::actingAs(User::factory()->admin()->create()); + + $this->postJson(route('api.contests.runners.check-in', [$this->contest, $this->runner])) + ->assertNotFound(); + + $this->assertDatabaseHas('contest_runner', ['runner_id' => $this->runner->id, 'checked_in_at' => null]); +}); + +test('check-in returns 409 when it was already done and keeps the first time', function () { + $this->contest->runners()->attach($this->runner, [ + 'registered_at' => now()->subMonth(), + 'checked_in_at' => '2027-05-02 07:00:00', + ]); + Sanctum::actingAs(User::factory()->admin()->create()); + + $this->postJson(route('api.contests.runners.check-in', [$this->contest, $this->runner])) + ->assertConflict(); + + $this->assertDatabaseHas('contest_runner', [ + 'runner_id' => $this->runner->id, + 'checked_in_at' => '2027-05-02 07:00:00', + ]); +}); diff --git a/tests/Feature/Auth/AuthenticationTest.php b/tests/Feature/Auth/AuthenticationTest.php index 24874b9..08fd66a 100644 --- a/tests/Feature/Auth/AuthenticationTest.php +++ b/tests/Feature/Auth/AuthenticationTest.php @@ -1,6 +1,6 @@ artisan('contests:import', ['path' => $path])->assertSuccessful(); + + $this->assertDatabaseCount('contests', 2); + $this->assertDatabaseHas('contests', [ + 'name' => 'Corsa dei Colli', + 'date' => '2027-05-02', + 'available_places' => 150, + 'registrations_open' => true, + ]); + $this->assertDatabaseHas('contests', [ + 'name' => 'Trail, delle Abbazie', + 'available_places' => 120, + 'registrations_open' => false, + ]); +}); + +test('importing again updates the contests by name and date instead of duplicating them', function () { + $this->artisan('contests:import', ['path' => contestsCsv(<<<'CSV' + name,date,available_places,registrations_open + Corsa dei Colli,2027-05-02,150,1 + CSV)])->assertSuccessful(); + + $this->artisan('contests:import', ['path' => contestsCsv(<<<'CSV' + name,date,available_places,registrations_open + Corsa dei Colli,2027-05-02,200,0 + Corsa dei Colli,2028-05-07,150,1 + CSV)])->assertSuccessful(); + + $this->assertDatabaseCount('contests', 2); + $this->assertDatabaseHas('contests', [ + 'name' => 'Corsa dei Colli', + 'date' => '2027-05-02', + 'available_places' => 200, + 'registrations_open' => false, + ]); +}); + +test('import fails without the header line', function () { + $path = contestsCsv(<<<'CSV' + Corsa dei Colli,2027-05-02,150,1 + CSV); + + $this->artisan('contests:import', ['path' => $path])->assertFailed(); + + $this->assertDatabaseCount('contests', 0); +}); + +test('one invalid row makes the import fail and write nothing', function () { + $path = contestsCsv(<<<'CSV' + name,date,available_places,registrations_open + Corsa dei Colli,2027-05-02,150,1 + Trail delle Abbazie,13/06/2027,120,0 + CSV); + + $this->artisan('contests:import', ['path' => $path]) + ->expectsOutputToContain('Line 3') + ->assertFailed(); + + $this->assertDatabaseCount('contests', 0); +}); + +test('import fails when the file does not exist', function () { + $this->artisan('contests:import', ['path' => '/nowhere/contests.csv'])->assertFailed(); +}); + +test('sample file holds ten future contests, at least one of them closed', function () { + $this->artisan('contests:import')->assertSuccessful(); + + expect(Contest::query()->count())->toBe(10) + ->and(Contest::query()->whereDate('date', '<=', now())->count())->toBe(0) + ->and(Contest::query()->where('registrations_open', false)->count())->toBeGreaterThanOrEqual(1); +}); diff --git a/tests/Feature/Contests/RegistrationTest.php b/tests/Feature/Contests/RegistrationTest.php new file mode 100644 index 0000000..51e5b14 --- /dev/null +++ b/tests/Feature/Contests/RegistrationTest.php @@ -0,0 +1,293 @@ + $overrides + * @return array + */ +function registrationInput(array $overrides = []): array +{ + return [ + 'first_name' => 'Mario', + 'last_name' => 'Rossi', + 'birth_date' => '1990-05-20', + 'email' => 'mario.rossi@example.com', + ...$overrides, + ]; +} + +beforeEach(function () { + $this->travelTo('2026-11-16 10:00:00'); +}); + +test('registration form of a contest is displayed', function () { + $contest = Contest::factory()->create(['name' => 'Corsa dei Colli', 'date' => '2027-05-02']); + + $this->get(route('contests.registration.create', $contest)) + ->assertOk() + ->assertInertia(fn (AssertableInertia $page) => $page + ->component('contests/registration') + ->where('contest.id', $contest->id) + ->where('contest.name', 'Corsa dei Colli') + ->where('contest.date', '2027-05-02')); +}); + +test('a new person is registered with a user, a runner and a queued confirmation mail', function () { + Mail::fake(); + $contest = Contest::factory()->create(['date' => '2027-05-02']); + + $this->post(route('contests.registration.store', $contest), registrationInput()) + ->assertSessionHasNoErrors() + ->assertRedirect(route('home')); + + $user = User::query()->where('email', 'mario.rossi@example.com')->sole(); + $runner = $user->runner; + + expect($user->name)->toBe('Mario Rossi') + ->and($user->is_admin)->toBeFalse() + ->and($runner->first_name)->toBe('Mario') + ->and($runner->last_name)->toBe('Rossi') + ->and($runner->birth_date->toDateString())->toBe('1990-05-20'); + + $this->assertDatabaseHas('contest_runner', [ + 'contest_id' => $contest->id, + 'runner_id' => $runner->id, + 'registered_at' => '2026-11-16 10:00:00', + 'checked_in_at' => null, + ]); + + Mail::assertQueued( + RegistrationConfirmedMail::class, + fn (RegistrationConfirmedMail $mail): bool => $mail->hasTo('mario.rossi@example.com') + && $mail->runner->is($runner) + && $mail->contest->is($contest), + ); +}); + +test('confirmation mail greets the runner and names the contest', function () { + $contest = Contest::factory()->create(['name' => 'Corsa dei Colli', 'date' => '2027-05-02']); + $runner = Runner::factory()->create(['first_name' => 'Mario', 'last_name' => 'Rossi']); + + (new RegistrationConfirmedMail($runner, $contest)) + ->assertHasSubject('Iscrizione confermata: Corsa dei Colli') + ->assertSeeInText('Ciao Mario Rossi') + ->assertSeeInText('02/05/2027'); +}); + +test('names and email are repaired before they are stored', function () { + Mail::fake(); + $contest = Contest::factory()->create(['date' => '2027-05-02']); + + $this->post(route('contests.registration.store', $contest), registrationInput([ + 'first_name' => "NICOLO'", + 'last_name' => 'D’ANGELO,', + 'email' => 'Nicolo.DAngeloòGmail.COM', + ]))->assertSessionHasNoErrors(); + + $user = User::query()->where('email', 'nicolo.dangelo@gmail.com')->sole(); + + expect($user->name)->toBe("Nicolò D'Angelo") + ->and($user->runner->first_name)->toBe('Nicolò') + ->and($user->runner->last_name)->toBe("D'Angelo"); +}); + +test('names holding markdown or a link are rejected', function (string $field, string $value) { + Mail::fake(); + $contest = Contest::factory()->create(['date' => '2027-05-02']); + + $this->post(route('contests.registration.store', $contest), registrationInput([$field => $value])) + ->assertSessionHasErrors($field); + + expect(User::query()->count())->toBe(0); + Mail::assertNothingQueued(); +})->with([ + 'markdown link in first name' => ['first_name', '[Mario](https://evil.example)'], + 'bold in first name' => ['first_name', '**Mario**'], + 'url in last name' => ['last_name', 'https://evil.example'], + 'image in last name' => ['last_name', '![x](https://evil.example/x.png)'], + 'heading in last name' => ['last_name', '# Rossi'], + 'digits in last name' => ['last_name', 'Rossi2'], + 'dot in the middle of last name' => ['last_name', 'evil.example'], +]); + +test('an email that cannot be repaired is rejected', function () { + $contest = Contest::factory()->create(['date' => '2027-05-02']); + + $this->post(route('contests.registration.store', $contest), registrationInput(['email' => 'mario'])) + ->assertSessionHasErrors('email'); + + expect(User::query()->count())->toBe(0); +}); + +test('registration to a contest already held is rejected', function () { + Mail::fake(); + $contest = Contest::factory()->create(['date' => '2026-11-15']); + + $this->post(route('contests.registration.store', $contest), registrationInput()) + ->assertSessionHasErrors(['contest' => 'Questa gara si è già svolta.']); + + $this->assertDatabaseCount('contest_runner', 0); + Mail::assertNothingQueued(); +}); + +test('registration is still accepted on the day of the contest', function () { + Mail::fake(); + $contest = Contest::factory()->create(['date' => '2026-11-16']); + + $this->post(route('contests.registration.store', $contest), registrationInput()) + ->assertSessionHasNoErrors(); + + $this->assertDatabaseCount('contest_runner', 1); +}); + +test('registration is rejected when registrations are closed', function () { + $contest = Contest::factory()->closed()->create(['date' => '2027-05-02']); + + $this->post(route('contests.registration.store', $contest), registrationInput()) + ->assertSessionHasErrors(['contest' => 'Le iscrizioni a questa gara sono chiuse.']); + + $this->assertDatabaseCount('contest_runner', 0); +}); + +test('registration is rejected when no places are left', function () { + $contest = Contest::factory()->create(['date' => '2027-05-02', 'available_places' => 1]); + $contest->runners()->attach(Runner::factory()->create(), ['registered_at' => now()]); + + $this->post(route('contests.registration.store', $contest), registrationInput()) + ->assertSessionHasErrors(['contest' => 'I posti per questa gara sono esauriti.']); + + $this->assertDatabaseCount('contest_runner', 1); +}); + +test('a deleted runner is rejected and is not restored', function () { + $contest = Contest::factory()->create(['date' => '2027-05-02']); + $runner = Runner::factory() + ->for(User::factory()->state(['email' => 'mario.rossi@example.com'])) + ->create(); + $runner->delete(); + + $this->post(route('contests.registration.store', $contest), registrationInput()) + ->assertSessionHasErrors('email'); + + expect($runner->fresh()->trashed())->toBeTrue(); + $this->assertDatabaseCount('contest_runner', 0); +}); + +test('a person not yet 18 on the day of the contest is rejected', function () { + $contest = Contest::factory()->create(['date' => '2027-05-02']); + + $this->post(route('contests.registration.store', $contest), registrationInput(['birth_date' => '2009-05-03'])) + ->assertSessionHasErrors(['birth_date' => 'Devi avere compiuto 18 anni entro il giorno della gara.']); + + expect(User::query()->count())->toBe(0); +}); + +test('a person turning 18 on the day of the contest is accepted', function () { + Mail::fake(); + $contest = Contest::factory()->create(['date' => '2027-05-02']); + + $this->post(route('contests.registration.store', $contest), registrationInput(['birth_date' => '2009-05-02'])) + ->assertSessionHasNoErrors(); + + $this->assertDatabaseCount('contest_runner', 1); +}); + +test('a runner already registered to the contest is rejected', function () { + Mail::fake(); + $contest = Contest::factory()->create(['date' => '2027-05-02']); + $runner = Runner::factory() + ->for(User::factory()->state(['email' => 'mario.rossi@example.com'])) + ->create(); + $contest->runners()->attach($runner, ['registered_at' => now()]); + + $this->post(route('contests.registration.store', $contest), registrationInput()) + ->assertSessionHasErrors(['email' => 'Questa email è già iscritta alla gara.']); + + $this->assertDatabaseCount('contest_runner', 1); + Mail::assertNothingQueued(); +}); + +test('a known email reuses its user and runner without overwriting them', function () { + Mail::fake(); + $contest = Contest::factory()->create(['date' => '2027-05-02']); + $user = User::factory()->create(['name' => 'Maria Bianchi', 'email' => 'mario.rossi@example.com']); + $runner = Runner::factory()->for($user)->create([ + 'first_name' => 'Maria', + 'last_name' => 'Bianchi', + 'birth_date' => '1985-01-10', + ]); + $password = $user->password; + + $this->post(route('contests.registration.store', $contest), registrationInput()) + ->assertSessionHasNoErrors(); + + expect(User::query()->count())->toBe(1) + ->and(Runner::query()->count())->toBe(1) + ->and($user->fresh()->name)->toBe('Maria Bianchi') + ->and($user->fresh()->password)->toBe($password) + ->and($runner->fresh()->first_name)->toBe('Maria') + ->and($runner->fresh()->birth_date->toDateString())->toBe('1985-01-10'); + + $this->assertDatabaseHas('contest_runner', ['contest_id' => $contest->id, 'runner_id' => $runner->id]); +}); + +test('age of a known runner is judged on the stored birth date, not on the submitted one', function () { + Mail::fake(); + $contest = Contest::factory()->create(['date' => '2027-05-02']); + Runner::factory() + ->for(User::factory()->state(['email' => 'minor@example.com'])) + ->create(['birth_date' => '2012-01-01']); + Runner::factory() + ->for(User::factory()->state(['email' => 'adult@example.com'])) + ->create(['birth_date' => '1980-01-01']); + + $this->post(route('contests.registration.store', $contest), registrationInput([ + 'email' => 'minor@example.com', + 'birth_date' => '1980-01-01', + ]))->assertSessionHasErrors('birth_date'); + + $this->post(route('contests.registration.store', $contest), registrationInput([ + 'email' => 'adult@example.com', + 'birth_date' => '2012-01-01', + ]))->assertSessionHasNoErrors(); + + $this->assertDatabaseCount('contest_runner', 1); +}); + +test('a known email without a runner gets only the runner', function () { + Mail::fake(); + $contest = Contest::factory()->create(['date' => '2027-05-02']); + $admin = User::factory()->admin()->create(['name' => 'Admin', 'email' => 'mario.rossi@example.com']); + + $this->post(route('contests.registration.store', $contest), registrationInput()) + ->assertSessionHasNoErrors(); + + $admin->refresh(); + + expect(User::query()->count())->toBe(1) + ->and($admin->name)->toBe('Admin') + ->and($admin->is_admin)->toBeTrue() + ->and($admin->runner->first_name)->toBe('Mario') + ->and($admin->runner->birth_date->toDateString())->toBe('1990-05-20'); + + $this->assertDatabaseHas('contest_runner', ['contest_id' => $contest->id, 'runner_id' => $admin->runner->id]); +}); + +test('registration returns 429 after ten attempts in a minute', function () { + $contest = Contest::factory()->closed()->create(['date' => '2027-05-02']); + + foreach (range(1, 10) as $attempt) { + $this->post(route('contests.registration.store', $contest), registrationInput())->assertRedirect(); + } + + $this->post(route('contests.registration.store', $contest), registrationInput()) + ->assertTooManyRequests(); +}); diff --git a/tests/Feature/DashboardTest.php b/tests/Feature/DashboardTest.php index 95c6a8b..d3a3e10 100644 --- a/tests/Feature/DashboardTest.php +++ b/tests/Feature/DashboardTest.php @@ -1,6 +1,6 @@ get(route('dashboard')); diff --git a/tests/Feature/HomeTest.php b/tests/Feature/HomeTest.php new file mode 100644 index 0000000..db1e906 --- /dev/null +++ b/tests/Feature/HomeTest.php @@ -0,0 +1,43 @@ +travelTo('2026-11-16 10:00:00'); + + Contest::factory()->create(['name' => 'Later', 'date' => '2027-03-01']); + Contest::factory()->create(['name' => 'Today', 'date' => '2026-11-16']); + Contest::factory()->create(['name' => 'Yesterday', 'date' => '2026-11-15']); + Contest::factory()->create(['name' => 'Sooner', 'date' => '2026-12-01']); + + $this->get(route('home')) + ->assertOk() + ->assertInertia(fn (AssertableInertia $page) => $page + ->component('home') + ->has('contests', 3) + ->where('contests.0.name', 'Today') + ->where('contests.0.date', '2026-11-16') + ->where('contests.1.name', 'Sooner') + ->where('contests.2.name', 'Later')); +}); + +test('home shows the places left and why a contest cannot be joined', function () { + $open = Contest::factory()->create(['date' => now()->addDays(10), 'available_places' => 10]); + $open->runners()->attach(Runner::factory(3)->create(), ['registered_at' => now()]); + + Contest::factory()->closed()->create(['date' => now()->addDays(20), 'available_places' => 10]); + + $soldOut = Contest::factory()->create(['date' => now()->addDays(30), 'available_places' => 1]); + $soldOut->runners()->attach(Runner::factory()->create(), ['registered_at' => now()]); + + $this->get(route('home')) + ->assertInertia(fn (AssertableInertia $page) => $page + ->where('contests.0.places_left', 7) + ->where('contests.0.status', 'open') + ->where('contests.1.places_left', 10) + ->where('contests.1.status', 'closed') + ->where('contests.2.places_left', 0) + ->where('contests.2.status', 'sold_out')); +}); diff --git a/tests/Feature/Settings/ProfileUpdateTest.php b/tests/Feature/Settings/ProfileUpdateTest.php index 8245c65..3a151ae 100644 --- a/tests/Feature/Settings/ProfileUpdateTest.php +++ b/tests/Feature/Settings/ProfileUpdateTest.php @@ -1,6 +1,6 @@ create(); diff --git a/tests/Feature/Settings/SecurityTest.php b/tests/Feature/Settings/SecurityTest.php index ec74400..06fa359 100644 --- a/tests/Feature/Settings/SecurityTest.php +++ b/tests/Feature/Settings/SecurityTest.php @@ -1,6 +1,6 @@